def addBinary(a, b):
    #print(len(a)," ",len(b))
    if len(a)<len(b):
        while len(a)<len(b):
            a='0'+a
    elif len(b)<len(a):
        while len(b)<len(a):
            b='0'+b
    #print(a," ",b)
    binary=''
    carry=0
    for i in range(len(a)-1,-1,-1):
        #print(a[i]," ",b[i]," ",carry)
        if a[i]=='1' and b[i]=='1' and carry==0:
            binary+='0'
            carry=1
        elif a[i]=='1' and b[i]=='1' and carry==1:
            binary+='1'
            #carry=1
        elif a[i]=='0' and b[i]=='0' and carry==0:
            binary+='0'
        elif a[i]=='0' and b[i]=='0' and carry==1:
            binary+='1'
            carry=0
        elif ((a[i]=='0' and b[i]=='1') or (a[i]=='1' and b[i]=='0')) and carry==1:
            binary+='0'
            #carry=1
        elif ((a[i]=='0' and b[i]=='1') or (a[i]=='1' and b[i]=='0')) and carry==0:
            binary+='1'
    if carry==1:
        binary+='1'
    binary=list(binary)
    for i in range(len(binary)//2):
        temp=binary[i]
        binary[i]=binary[len(binary)-1-i]
        binary[len(binary)-1-i]=temp
    bitstring=''
    for x in binary:
        bitstring+=x
    return bitstring


from discord import Interaction
import bdg
import enum

class FormatStyle(enum.Enum):
	UPPER    = 0
	LOWER    = 1
	REVERSED = 2
	SPACED   = 3
	HACKER   = 4
	IRONIC   = 5

hacker_dict = {
	"a": "4",
	"s": "5",
	"o": "0",
	"e": "3"
}

class FormatCommand(bdg.BdgCommand):

	header = {
		'name': "formatar",
		'description': "Formate um texto de acordo com o estilo selecionado"
	}

	params = {
		'estilo': "O estilo do texto, podendo ser: UPPER, LOWER, REVERSED, SPACED, HACKER, IRONIC",
		'texto': "O texto a ser formatado no estilo indicado"
	}

	async def on_command(self, i: Interaction, estilo: FormatStyle, texto: str):
		text = ""

		if estilo == FormatStyle.UPPER:
			text = texto.upper()

		if estilo == FormatStyle.LOWER:
			text = texto.lower()

		if estilo == FormatStyle.REVERSED:
			# Loop pelo "texto" ao contrário.
			for char in texto[len(texto)-1:-1:-1]:
				text += char

		elif estilo == FormatStyle.SPACED:
			chars = list(texto)
			text = " ".join(chars)

		elif estilo == FormatStyle.HACKER:
			# Para cada caractére, use-o como chave no dicionário "hacker_style_dict",
			# ... se a chave não existe, use o próprio caractére
			text = "".join([hacker_dict.get(char.lower(), char) for char in texto])

		elif estilo == FormatStyle.IRONIC:
			# Se 'c' for par é maiúsculo, senão é minúsculo
			for c in range(len(texto)):
				char = texto[c]
				text += char.upper() if c % 2 else char.lower()

		await i.response.send_message(":speech_balloon: | " + text)


import openai

openai.api_key = "[YOUR_OPENAI_API]"

chat_history = [{"role": "system", "content": "You are a assistant."}]

def bot_message(input):
    chat_history.append({"role": "user", "content": f"{input}"})
    chat = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=chat_history
    )

    return chat

def start_conversation():
    print("Hi, I'm a chatbot. How can I help you today?")
    token_count = 0
    while True:
        user_input = input("> ")
        prompt = f"{user_input}"
        response = bot_message(prompt)
        role = response.choices[0].message.role
        answer = response.choices[0].message.content

        return_message = f"BOT : {answer}"
        history_message = {"role": f'{role}', "content": f"{answer}"}
        chat_history.append(history_message)

        completion_token = response.usage.completion_tokens
        prompt_token = response.usage.prompt_tokens
        used_tokens = completion_token + prompt_token
        token_count = token_count + used_tokens

        token_message = f"In this conversation, you use {used_tokens} tokens. Completion : {completion_token}, Prompt : {prompt_token}"
        total_token_message = f"You used {token_count} Tokens"

        print(return_message)
        print(token_message)
        print(total_token_message)

start_conversation()


from pygame.locals import *
import figures
import pygame
import random
import sys

types = [figures.Square, figures.Line]

class Game:

    def __init__(self, window=(500, 500), speed=5, block=20, fps=20):
        pygame.init()
        pygame.display.set_caption("Tetrissss")

        self.WINDOW_SIZE = window
        self.SPEED = speed
        self.BLOCK = block
        self.FPS = fps

        # Calcul des dimensions de la grille / de l'adresse de chaque case et mise en place
        self.nb_blocks = ((self.WINDOW_SIZE[0] - 1) // (self.BLOCK + 1), (self.WINDOW_SIZE[1] - 1) // (self.BLOCK + 1))
        self.padd = ((self.WINDOW_SIZE[0] - 1) % (self.BLOCK + 1), (self.WINDOW_SIZE[1] - 1) % (self.BLOCK + 1))
        self.grid_x = {i: (self.padd[0] // 2) + 2 + i * (self.BLOCK + 1) for i in range(self.nb_blocks[0])}
        self.grid_y = {i: (self.padd[1] // 2) + 2 + i * (self.BLOCK + 1) for i in range(self.nb_blocks[1])}

        self.clock = pygame.time.Clock()
        self.clock.tick(self.FPS)
        self.surface = pygame.display.set_mode(self.WINDOW_SIZE)

        # Instanciation figure(s) et variables de suivi du mur de blocs
        self.fig = random.choice(types)(self, self.BLOCK, 5, 0)
        self.fig.draw()
        self.limit = {i: self.nb_blocks[1] - 1 for i in range(self.nb_blocks[0])}
        self.wall = {y: {} for y in range(self.nb_blocks[1])}
        self.lines = {i: self.nb_blocks[0] for i in range(self.nb_blocks[1])}

        self.playing = True

    def draw_grid(self):
        """Mise en place de la grille"""
        self.surface.fill((0, 0, 0))
        curs = (self.padd[0] // 2) + 1
        for _ in range(self.nb_blocks[0] + 1):
            pygame.draw.line(self.surface, (20, 20, 20), (curs, self.padd[1] // 2),
                             (curs, self.WINDOW_SIZE[1] - (self.padd[1] // 2 + self.padd[1] % 2)))
            curs += self.BLOCK + 1
        curs = (self.padd[1] // 2) + 1
        for _ in range(self.nb_blocks[1] + 1):
            pygame.draw.line(self.surface, (20, 20, 20), (self.padd[0] // 2, curs),
                             (self.WINDOW_SIZE[0] - (self.padd[0] // 2 + self.padd[0] % 2), curs))
            curs += self.BLOCK + 1

    def block_to_wall(self):
        """Ajout d'un bloc ayant achevé sa chute au mur de blocs"""
        for block in self.fig.get_top():
            self.limit[block[0]] = block[1] - 1
            if block[1] <= 2:
                self.playing = False  # TODO : perdu
        full_lines = []
        for block in self.fig.get_blocks():
            self.wall[block[1]][block[0]] = self.fig.color
            self.lines[block[1]] -= 1
            if self.lines[block[1]] == 0:
                full_lines.append(block[1])
        if len(full_lines) > 0:
            full_lines.sort(reverse=True)
            for i in range(len(full_lines)):
                self.del_line(full_lines[i] + i)
            # TODO : bonus si plusieurs lignes complétées en même temps
        del self.fig

        # Instanciation aléatoire d'une figure
        self.fig = random.choice(types)(self, self.BLOCK, 5, 0)

    def del_line(self, y):
        """Suppression d'une ligne complète"""
        for x, val in self.limit.items():
            self.limit[x] += 1
        toDel = []
        iterate = True
        while iterate:
            self.lines[y] = self.lines[y - 1]
            for bl, col in self.wall[y].items():
                if bl in self.wall[y - 1].keys():
                    self.wall[y][bl] = self.wall[y - 1][bl]
                else:
                    toDel.append((y, bl))
            y -= 1
            if self.lines[y] == self.nb_blocks[0]:
                iterate = False
        for blY, blX in toDel:
            del self.wall[blY][blX]

    def game_loop(self):
        count = 0
        while self.playing:
            pygame.display.update()
            self.draw_grid()

            # Lorsque la figure atteint le sol, ses blocs sont intégrés au mur et la limite recalculée
            if not self.fig.falling:
                self.block_to_wall()

            # Affichage du bloc courant et du mur de blocs
            self.fig.draw()
            for y, bl in self.wall.items():
                for x, col in bl.items():
                    pygame.draw.rect(self.surface, col, (self.grid_x[x], self.grid_y[y], self.BLOCK, self.BLOCK))

            # Commandes utilisateur
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_LEFT:
                        self.fig.move(-1)
                    elif event.key == K_RIGHT:
                        self.fig.move(1)
                    elif event.key == K_DOWN:
                        self.fig.fall()
                    elif event.key == K_UP:
                        while self.fig.falling:
                            self.fig.fall()
                    elif event.key == K_SPACE:
                        self.fig.turn()

            # Chute du bloc courant
            if count < self.SPEED:
                count += 1
            elif count == self.SPEED:
                self.fig.fall()
                count = 0

            self.clock.tick(self.FPS)

if __name__ == "__main__":
    game = Game(window=(230, 300))
    game.game_loop()


import datetime
from airflow import models
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dummy_operator import DummyOperator

default_dag_args = {
    # https://airflow.apache.org/faq.html#what-s-the-deal-with-start-date
    'start_date': datetime.datetime(2020, 4, 27)
}

dataset = 'airflow'
table = 'Country'

query_cmd = 'bq query --use_legacy_sql=false '

table_cmd = 'create or replace table ' + dataset + '.' + table + '(id int64, name string)'

insert_cmd = 'insert into ' + dataset + '.' + table + '(id, name) values(1, "\'"USA"\'")'

with models.DAG(
        'country2',
        schedule_interval=None,
        default_args=default_dag_args) as dag:

    create_dataset = BashOperator(
            task_id='create_dataset',
            bash_command='bq --location=US mk --dataset ' + dataset)

    create_table = BashOperator(
            task_id='create_table',
            bash_command=query_cmd + "'" + table_cmd + "'",
            trigger_rule='all_done')

    insert_row = BashOperator(
            task_id='insert_row',
            bash_command=query_cmd + "'" + insert_cmd + "'",
            trigger_rule='one_success')

    create_dataset >> create_table >> insert_row


# Python code to check if a file exist in a folder
# whose name is equal to the row data of csv file.

# Importing required libraries
import os
import csv

# Opening CSV file in a variable.
with open("Python\\Colors.csv", newline='') as f:

    # Reading CSV file
    ereader = csv.DictReader(f)

    # Initializing loop to get CSV file data in a variable.
    for row in ereader:

        # Getting values in variables
        a = row['name']
        b = row['hex']

        # Initializing loop for the files in the defined folder
        for filename in os.listdir("Python\\Sample_videos"):

            # Applying condition to check if file name is equal to CSV row data or not.
            if ((filename.endswith(".mp4")) & (filename[:-4] == b[1:])): # here "(filename.endswith(".mp4"))" is used for checking for a particular file type.
                print("File named",filename,"found in dir.")
            else:
                continue


from functools import reduce

n = int(input())
data = list(map(int, input().split()))

def mean(data):
    sum = reduce(lambda x, y: x + y, data)
    return sum / len(data)

def stdev(data):
    mu = mean(data)
    sq_sq_dists_mean = list(map(lambda x: (x - mu) ** 2, data))
    sum_sq_dists_mean = reduce(lambda x, y: x + y, sq_sq_dists_mean)
    return round((sum_sq_dists_mean / len(data)) ** 0.5, 1)

print(stdev(data))


import os
import cv2
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from handy_msgs.msg import Float32Stamped
import readchar
import json

class MyNode(Node):
    def __init__(self, name, published_image):
        super().__init__(name)
        self.image_publisher = self.create_publisher(Image, published_image, 10)
        self.dist_publisher = self.create_publisher(Float32Stamped, '/gps/distance', 10)
        self.bridge = CvBridge()
        self.image_paths = []
        self.gps_paths = []

    def load_image_paths(self, folder_path):
        for file_name in os.listdir(folder_path):
            if file_name.endswith('.jpg') or file_name.endswith('.png'):
                self.image_paths.append(os.path.join(folder_path, file_name))
        new_array = sorted(self.image_paths, key=lambda name: name.lower())
        for filename in new_array:
            name, ext = os.path.splitext(filename)
            new_filename = name + '.json'
            self.gps_paths.append(new_filename)
        self.image_paths = new_array

    def publish(self, index, distance):
            file_name = self.image_paths[index]
            image = cv2.imread(file_name)
            ros_image = self.bridge.cv2_to_imgmsg(image, 'bgr8')
            self.image_publisher.publish(ros_image)
            with open(self.gps_paths[index]) as f:
                data = json.load(f)
                json_str = json.dumps(data)
                self.get_logger().info(f"JSON {json_str}")
                if distance:
                    new_msg = Float32Stamped()
                    new_msg.header = ros_image.header
                    new_msg.data = float(data['DIST'])
                    self.dist_publisher.publish(new_msg)
            self.get_logger().info(f"Published image {file_name}")

def main(args=None):
    rclpy.init(args=args)
    folder_path = '/doc/DATA/R4C/data/Cam/20230223143203'
    front_node = MyNode('image_player', '/Pioneer3at/camera_front')
    back_node = MyNode('image_player', '/Pioneer3at/camera_back')
    front_node.load_image_paths(folder_path + '/RGB-18443010C1A2DF0F00')
    back_node.load_image_paths(folder_path + '/RGB-18443010B1F4DE0F00')

    counter = 0
    while rclpy.ok():
        key = readchar.readkey()
        if key == ' ':
            front_node.publish(counter, distance=True)
            back_node.publish(counter, distance=True)
            counter += 1
        if key == 'r':
            counter = 0
        if key == 'b':
            counter -= 2

    front_node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


pkgname = "grilo"
pkgver = "0.3.16"
pkgrel = 0
build_style = "meson"
configure_args = [
    "-Denable-introspection=true",
    "-Denable-vala=true",
    "-Denable-gtk-doc=false",
    "-Dsoup3=true",
]
hostmakedepends = [
    "meson",
    "pkgconf",
    "gobject-introspection",
    "glib-devel",
    "gettext",
    "vala",
]
makedepends = [
    "glib-devel",
    "libxml2-devel",
    "libsoup-devel",
    "gtk+3-devel",
    "liboauth-devel",
    "totem-pl-parser-devel",
]
pkgdesc = "Framework for media discovery"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://wiki.gnome.org/Projects/Grilo"
source = f"$(GNOME_SITE)/{pkgname}/{pkgver[:-3]}/{pkgname}-{pkgver}.tar.xz"
sha256 = "884580e8c5ece280df23aa63ff5234b7d48988a404df7d6bfccd1e77b473bd96"

@subpackage("grilo-devel")
def _devel(self):
    return self.default_devel()


from flask import Flask, render_template, jsonify
from database import engine, text, load_job_from_db

app = Flask(__name__)

def load_jobs_from_db():
  try:
    with engine.connect() as conn:
      result = conn.execute(text("select * from jobs"))
      column_names = result.keys()
      jobs = []
      for row in result.all():
        jobs.append(dict(zip(column_names, row)))
    return jobs
  except Exception as e:
    print(f"An error occurred while loading jobs from database: {e}")
    return []

@app.route("/")
def hello():
  job_list = load_jobs_from_db()
  return render_template('home.html', jobs=job_list)

@app.route("/api/<id>")
def show_job(id):
  job_list = load_job_from_db(id)
  if not job_list:
    return "Not found", 404
  return render_template('jobpage.html', job=job_list)

@app.route("/api/jobs")
def list_jobs():
  job_list = load_jobs_from_db()
  return jsonify(job_list)

if __name__ == "__main__":
  app.run(host='0.0.0.0', debug=True)


'''
Script to export PASCAL VOC 2012 annotation data in VIA format

Author: Abhishek Dutta <adutta@robots.ox.ac.uk>
12 Apr. 2018
'''

import xmltodict
import os
import json

base_dir = '/data/datasets/voc2012/VOCdevkit/VOC2012/'
img_dir = os.path.join(base_dir, 'JPEGImages/')
ann_dir = os.path.join(base_dir, 'Annotations')
set_dir = os.path.join(base_dir, 'ImageSets', 'Main')

def get_via_fileid(filename, filesize):
  return filename + str(filesize);

def get_file_size(filename):
  return os.path.getsize(filename)

def get_region_attributes(d):
  ri = {}
  ri['shape_attributes'] = {}
  if 'bndbox' in d:
    x0 = int( float(d['bndbox']['xmin']) )
    y0 = int( float(d['bndbox']['ymin']) )
    x1 = int( float(d['bndbox']['xmax']) )
    y1 = int( float(d['bndbox']['ymax']) )

    ri['shape_attributes']['name'] = 'rect'
    ri['shape_attributes']['x'] = x0
    ri['shape_attributes']['y'] = y0
    ri['shape_attributes']['width'] = x1 - x0
    ri['shape_attributes']['height'] =  y1 - y0

  ri['region_attributes'] = {}
  if 'name' in d:
    ri['region_attributes']['name'] = d['name']
  if 'pose' in d:
    ri['region_attributes']['pose'] = d['pose']
  if 'truncated' in d:
    ri['region_attributes']['truncated'] = d['truncated']
  if 'difficult' in d:
    ri['region_attributes']['difficult'] = d['difficult']
  return ri

def voc_xml_to_json(fn):
  print(fn)
  with open(fn) as f:
    d = xmltodict.parse(f.read())
    d = d['annotation']

    img_fn   = d['filename']
    img_path = os.path.join(img_dir, img_fn)
    img_size = get_file_size(img_path)
    img_id   = get_via_fileid(img_fn, img_size)

    js = {}
    js[img_id] = {}
    js[img_id]['fileref']  = img_path
    js[img_id]['size']     = img_size
    js[img_id]['filename'] = img_fn
    js[img_id]['base64_img_data'] = ''

    fa = {}
    if 'source' in d:
      if 'database' in d['source']:
        fa['database'] = d['source']['database']
      if 'annotation' in d['source']:
        fa['annotation'] = d['source']['annotation']
      if 'image' in d['source']:
        fa['image'] = d['source']['image']
    if 'size' in d:
      if 'width' in d['size']:
        fa['width'] = d['size']['width']
      if 'height' in d['size']:
        fa['height'] = d['size']['height']
      if 'depth' in d['size']:
        fa['depth'] = d['size']['depth']

    if 'segmented' in d:
      fa['segmented'] = d['segmented']

    js[img_id]['file_attributes'] = fa

    js[img_id]['regions'] = []
    if isinstance(d['object'], list):
      region_count = len(d['object'])
      for i in range(0, region_count):
        ri = get_region_attributes( d['object'][i] )
        js[img_id]['regions'].append(ri)
    else:
      r = get_region_attributes( d['object'] )
      js[img_id]['regions'].append(r)

    return js

outjson_fn = '/data/datasets/via/import/pascal_voc/_via_project_pascal_voc2012_import.js'
outjson_f = open(outjson_fn, 'w')
outjson_f.write('var via_project_pascal_voc2012 = \'{"_via_settings":{}, "_via_attributes":{}, "_via_img_metadata":{')
first = True

for file in os.listdir(ann_dir):
  if file.endswith(".xml"):
    file_path = os.path.join(ann_dir, file)
    js = voc_xml_to_json(file_path)
    js_str = json.dumps(js)
    if not first:
      outjson_f.write( "," ) # remove first and last curley braces
    else:
      first = False

    outjson_f.write( js_str[1:-1] ) # remove first and last curley braces

outjson_f.write("}}\';")
outjson_f.close()
print('\nWritten everything to {}'.format(outjson_fn))


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

from fabric.api import *
import os

#env.hosts = ['catchment.niva.no']
env.hosts=['35.242.200.24']
env.user='jose-luis'
env.key_filename='/home/jose-luis/.ssh/fimexKeys/jose-luis'
env.roledefs={'ncquery':['35.242.200.24'],
                'basin': ['catchment.niva.no'],  #
               }

global path, file

#------------------------------------------------------------------------------------------------------------
#Setting up virtual machine with necessary dependencies to install fimex

def whoAmI():
    run('uname -a')
    run ('whoami')

def updateMachine():
    run('sudo apt-get update')

def installUtilities():
    run('yes | sudo apt-get install gcc g++ gfortran cmake make git libnetcdf-dev libnetcdff-dev netcdf-bin xmlstarlet tmux unzip python3-netcdf4 cdo parallel nco')

def installFimex():
    run('echo | sudo add-apt-repository ppa:met-norway/fimex && sudo apt-get update && yes | sudo apt-get install fimex-0.66-bin libfimex-dev fimex-0.66-dbg && sudo ln -s /usr/bin/fimex-0.66 /usr/bin/fimex')

def installGcsfuse():
    run('''export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s` &&
           echo "deb http://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list &&
           curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - &&
           sudo apt-get update &&
           sudo apt-get install gcsfuse
        ''')
#------------------------------------------------------------------------------------------------------------
#Getting netcdf files from metno openDAP server and processing them
def getFromList(fileList,box,path,outputFile,var):
    run('''rm -rf {}'''.format(path))
    run('''mkdir -p {}'''.format(path))
    put(fileList, path)
    put('getsubset.sh',path)
    run('''cd {} && chmod +x getsubset.sh && ./getsubset.sh '{}' '{}' '{}' '{}' '''.format(path,fileList,box,outputFile,var))

@task
def installDependencies():
    updateMachine.roles=('ncquery',)
    installUtilities.roles=('ncquery',)
    installFimex.roles=('ncquery',)
    installGcsfuse.roles=('ncquery',)
    execute(updateMachine)
    execute(installUtilities)
    execute(installFimex)

@task
def getDataForBasin(fileList,box,path,outputFile,var):
    getFromList.roles=('ncquery',)
    execute(getFromList,fileList,box,path,outputFile,var)


import unittest
import skill_tree

class TestSkillTree(unittest.TestCase):

    def test_skill_tree1(self):
        result = skill_tree.solution('CBD', ['BACDE', 'CBADF', 'AECB', 'BDA'])
        self.assertEqual(result, 2)

if __name__ == '__main__':
    unittest.main()


## This module
from StreamAnimations import utils, sprite
from StreamAnimations.sprite import hitbox
from StreamAnimations.canvases import SinglePageCanvas
from StreamAnimations.engine.renderers.gif import GifRenderer
from StreamAnimations.engine import utils as engineutils
from StreamAnimations.systems import twodimensional

## Builtin
import pathlib
import random

ROOT = pathlib.Path(__file__).resolve().parent
OUTDIR = ( ROOT / "output").resolve()
OUTDIR.mkdir(exist_ok = True)
SAMPLEDIR = (ROOT / "samples").resolve()
SPRITESIZE = 32
CANVASSIZE = 384, 216
BASEHEIGHT = 10

def load_walk():
    up, down, right = utils.import_spritesheet((SAMPLEDIR / "Walk Up.png").resolve()), \
        utils.import_spritesheet((SAMPLEDIR / "Walk Down.png").resolve()), \
            utils.import_spritesheet((SAMPLEDIR / "Walk Right.png"))
    directions = dict(up = utils.split_spritesheet(up, SPRITESIZE, SPRITESIZE),
        down = utils.split_spritesheet(down, SPRITESIZE, SPRITESIZE),
        right = utils.split_spritesheet(right, SPRITESIZE, SPRITESIZE)
        )
    directions["left"] = utils.mirror_sprite(directions['right'])

    return directions

def load_printer():
    frames = []
    for zlevel in range(1,6):
        sheet = utils.import_spritesheet( (SAMPLEDIR / f"Prusa Z{zlevel}.png").resolve())
        frames.extend(utils.split_spritesheet(sheet, SPRITESIZE, SPRITESIZE))
    return {"idle": frames}

def load_desk():
    return {"idle":utils.split_spritesheet(utils.import_spritesheet( (SAMPLEDIR / "Desk-1.png").resolve()), SPRITESIZE, 45)}

def load_desk_text():
    return {"idle": utils.split_spritesheet(utils.import_spritesheet( (SAMPLEDIR / "stream.png").resolve() ), SPRITESIZE, 21)}

walk = load_walk()
me = twodimensional.Sprite2D(directionalsprites= walk, hitboxes = [], animations = {"idle":[walk['down'][0],]})
mehitbox = hitbox.MaskedHitbox(hitbox.create_rect_hitbox_image(me.get_image().width, BASEHEIGHT),anchor="bl")
me.add_hitbox(mehitbox)

printer = sprite.StationarySprite(animations=load_printer())
printerhitbox = hitbox.MaskedHitbox(hitbox.create_rect_hitbox_image(printer.get_image().width, BASEHEIGHT//2), anchor="bl")
printer.add_hitbox(printerhitbox)
desk = sprite.StationarySprite(animations= load_desk())
deskhitbox = hitbox.MaskedHitbox(hitbox.create_rect_hitbox_image(desk.get_image().width, BASEHEIGHT),anchor="bl")
desk.add_hitbox(deskhitbox)
monitortext = sprite.CosmeticSprite(animations= load_desk_text(), offset = (12, 12), parent = desk)

canvas = SinglePageCanvas(CANVASSIZE, SPRITESIZE // 4)
canvas.add_listener("movement", engineutils.collision_stop_rule)

canvas.add_sprite(me, (50, 70))
canvas.add_sprite(printer, (80,80))
canvas.add_sprite(monitortext, (0,0))
canvas.add_sprite(desk, (50, 50))

## ANIMATION
renderer = GifRenderer(canvas, sorter= twodimensional.twod_sprite_sorter)
with renderer.frame(): pass

path = ["right","right","right","right","right", "up", "up", "up", "up","left","left","left","left","left"]

for i in range(100):
    with renderer.frame() as frame:
        #frame.move_sprite(me, random.choice(twodimensional.TwoDimensional_4Way.directions()))
        if path: frame.move_sprite(me, path.pop(0))
        if(printer.animations.is_last_frame()): printer.animations.pause()

renderer.save((OUTDIR / "map2.gif"), 10, scale = 5)


#coding=gbk
#文件备份改进版，以当天日期为目录，默认以时间为zip文件名字，如果用户输入备注则以时间+备注作为文件名字
import os
import time

#需要备份的文件目录列表
source=[r'C:\Users\zk\Pictures', r'"C:\Users\zk\Documents\WeChat Files\zhengknight\Files"']

#目标文件夹
target_dir=r'e:\backup'
#如果目标目录不存在则创建
if not os.path.exists(target_dir):
    os.mkdir(target_dir)

#当日文件夹
today=target_dir + os.sep + time.strftime('%Y%m%d')

#将当前时间作为备份的文件名
now = time.strftime('%H%M%S')
#获取用户输入备注信息
comment = input('请输入备注信息-->')
#检查用户是否输入备注
if len(comment)==0:
   target=today + os.sep + now + '.zip'
else:
    #此处一个物理行换行的时候pycharm自动给加上反斜杠了
    target = today + os.sep + now + '_'\
             +comment.replace(' ','_') + '.zip'
#如果当日文件夹不存在则创建
if not os.path.exists(today):
    os.mkdir(today)
    print('当日文件夹目录创建成功',today)

#构造zip命令行
zip_command = 'zip -r {0} {1}'.format(target,' '.join(source))

print('zip_command')
print(zip_command)
print('Running')
if os.system(zip_command)==0:
    print('已成功备份到',target)
else:
    print('备份失败！！！')


from flair.data import Corpus
from flair.datasets import ColumnCorpus
from flair.embeddings import TokenEmbeddings, WordEmbeddings, StackedEmbeddings
from flair.models import SequenceTagger
from flair.trainers import ModelTrainer
from pathlib import Path

columns={0: 'text', 1: 'label'}
dataPath='../data/'
test_file=input("Test data file name:")
corpus: Corpus = ColumnCorpus(dataPath, columns, train_file='train_data.txt', test_file=test_file, dev_file='test_data.txt')

tag_type='label'
tag_dict=corpus.make_tag_dictionary(tag_type=tag_type)
print(tag_dict)

embedding_types = [WordEmbeddings('glove')]
embeddings: StackedEmbeddings = StackedEmbeddings(embeddings=embedding_types)

tagger: SequenceTagger = SequenceTagger(hidden_size=256, embeddings=embeddings, tag_dictionary=tag_dict,
                                        tag_type=tag_type, use_crf=True)

str_path = input("path to saved model:")
path = Path(str_path)

trainer: ModelTrainer = ModelTrainer(tagger, corpus)
trainer.final_test(path, eval_mini_batch_size=32)


print("Will I be printed in main when called? -Yes!")

# print(__name__)  # 'module' if a file is imported as a module, or __main__ if it's executed directly

"""
 Personal/Private variable.

 Unlike many other programming languages, Python has no means of allowing you to hide such variables
 from the eyes of the module's users.

 You can only inform your users that this is your variable, that they may read it,
 but that they should not modify it under any circumstances.

 This is done by preceding the variable's name with _ (one underscore) or __ (two underscores),
 but remember, it's only a convention. Your module's users may obey it or they may no
"""
__counter = 0

def suml(the_list):
    global __counter
    __counter += 1
    the_sum = 0
    for element in the_list:
        the_sum += element
    return the_sum

def prodl(the_list):
    global __counter
    __counter += 1
    prod = 1
    for element in the_list:
        prod *= element
    return prod

"""
 the functions defined inside the module (suml() and prodl()) are available for import;
 we've used the __name__ variable to detect when the file is run stand-alone, and seized this
 opportunity to perform some simple tests
"""
if __name__ == "__main__":
    print("I prefer to be a module, but I can do some tests for you.")
    my_list = [i+1 for i in range(5)]
    print(suml(my_list) == 15)
    print(prodl(my_list) == 120)

"""
 #! /usr/bin/env python3

 the line starting with { #! }  has many names - it may be called shabang, shebang, hashbang, poundbang or
 even hashpling (don't ask us why). The name itself means nothing here - its role is more important.

 From Python's point of view, it's just a comment as it starts with #. For Unix and Unix-like OSs
 (including MacOS) such a line instructs the OS how to execute the contents of the file (in other
 words, what program needs to be launched to interpret the text).

 In some environments (especially those connected with web servers) the absence of that line will cause trouble;

 a string (maybe a multiline) placed before any module instructions (including imports) is called
 the doc-string, and should briefly explain the purpose and contents of the module;
"""


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 地牢逃脱.py
# @Author: smx
# @Date  : 2020/2/16
# @Desc  :

#
# 最终的题意是：从给定起点（一定为'.'），按照给定的若干跳跃（可以跨过障碍，但不可以落在'x'上），到达任意一个'.'的最小步骤次数集合中，选择一个最大的！
# 如果存在一个点'.'从起点始终无法抵达，则认为起点到该点的最小距离为无穷∞，则返回-1.
# 因此，从起点开始广度优先遍历到所有可达点，记录每个可达点的最小距离，将其存入集合中。
# 然后遍历集合寻找最大的距离。如果存在一个点'.'无法抵达，直接返回-1.
# 所以是假设重点是任意点，找到一点，其达到的最短路径最大
def BFS(m, n, matrix, x, y, arr, k):
    queue = [(x, y)]
    vis = [[1 for _ in range(n)] for _ in range(m)]
    vis[x][y] = 0
    count = 1
    step = 0
    max_count = sum([matrix[i].count('.') for i in range(m)])
    while queue:
        step += 1
        length = len(queue)
        while length:
            top = queue.pop(0)
            for i in range(k):
                new_x = top[0] + arr[i][0]
                new_y = top[1] + arr[i][1]
                if 0 <= new_x < m and 0 <= new_y < n and matrix[new_x][new_y] == '.' and vis[new_x][new_y] == 1:
                    queue.append((new_x, new_y))
                    vis[new_x][new_y] = 0
                    count += 1
                    if count == max_count:
                        return step
            length -= 1
    return -1

if __name__ == '__main__':
    m, n = map(int, input().strip().split(' '))
    matrix = []
    for _ in range(n):
        matrix.append(list(input().strip()))
    x, y = map(int, input().strip().split(' '))
    k = int(input().strip())
    arr = []
    for _ in range(k):
        arr.append(list(map(int, input().strip().split(' '))))
    ans = BFS(m, n, matrix, x, y, arr, k)
    print(ans)


import sys
input = sys.stdin.readline
n = int(input())
L = []
for i in range(n):
    name, a, b, c = input().split()
    L.append([int(a), int(b), int(c), name])
L = sorted(L, key=lambda x: (-x[0], x[1], -x[2], x[3]))
for l in L:
    print(l[3])


def possible_scores(roundNumbers, totalScore, teams, team1, team2, c, d, n, amount, history, history2):
    # roundNumbers = the rounds that are left
    # totalScore = the scores of all four teams
    # team is my favourable team
    # team1 and team2 are the teams that compete, c and d are team1 score and team2 score respectively
    # n = a number; how i keep track of which rounds are played - this is the base case
    # amount is amount of times my team comes on top
    # history is the history of games for team1
    # history2 is the history of games for team2
    # abc is the match that is happening currently

    # this adds the three possible outcomes of the game to each team, and to their history
    totalScore[team1] += c
    totalScore[team2] += d
    history.append([team1, c])
    history2.append([team2, d])

    # this is the base case: if N becomes the amount of rounds left that means all rounds are played
    # then we check to see if my favourable team wins
    if n == len(roundNumbers):
        x = 0
        for abc in range(0, 5):
            if abc == teams:
                pass
            elif totalScore[teams] > totalScore[abc]:
                x += 1
        # x is the counter to see how many of the matches my team won
        # its out of five because i have a score[0] so that
        # when i call the teams i don't need to do score[x - 1]

        if x == 4:
            amount.append(1)

        # because this part of the tree is a dead end, this deletes the history of the dead end
        totalScore[history[-1][0]] -= history[-1][1]
        totalScore[history2[-1][0]] -= history2[-1][1]
        del history[-1]
        del history2[-1]
        return
    else:
        # this finds out what the next match is, assigns the teams to team1 and 2
        # and then there's recursion for the three outcomes
        abc = roundNumbers[n]
        team1 = abc[0]
        team2 = abc[1]
        c = 0
        d = 0
        n += 1
        possible_scores(roundNumbers, totalScore, teams, team1, team2, c + 3, d, n, amount, history, history2)
        possible_scores(roundNumbers, totalScore, teams, team1, team2, c, d + 3, n, amount, history, history2)
        possible_scores(roundNumbers, totalScore, teams, team1, team2, c + 1, d + 1, n, amount, history, history2)

        # we delete the history again after the third recursion
        # because we know all three outcomes of that portion of the tree diagram
        totalScore[history[-1][0]] -= history[-1][1]
        totalScore[history2[-1][0]] -= history2[-1][1]
        del history[-1]
        del history2[-1]

# this is the code
team = int(input())
played = int(input())
rounds = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
score = [-10000, 0, 0, 0, 0]

# based on our input, I see which team won, and add points to the team's score
for i in range(0, played):
    qq = input()
    x_split = qq.split()
    y = [int(x_split[0]), int(x_split[1])]
    z = rounds.index(y)
    del rounds[z]
    if int(x_split[2]) > int(x_split[3]):
        score[y[0]] += 3
    elif int(x_split[3]) > int(x_split[2]):
        score[y[1]] += 3
    else:
        score[y[0]] += 1
        score[y[1]] += 1
team1 = 0
team2 = 0
c = 0
d = 0
n = 0
amount = []
history = []
history2 = []
# calls the function
possible_scores(rounds, score, team, team1, team2, c, d, n, amount, history, history2)
print(len(amount))


h, m, s = map(int, input().split())
input = int(input())

s = s + input
m = m + int(s/60)
h = h + int(m/60)
s = s % 60
m = m % 60
h = h % 24

print(h,m,s)


from flask import Flask,render_template,request
import tweepy
import re
import pandas as pd
from tweepy import OAuthHandler
from nltk.corpus import stopwords
from nltk.tokenize import TweetTokenizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn import naive_bayes
from sklearn.metrics import roc_auc_score

#======================================================= ======================================================
df = pd.read_csv("/home/saurabh/Sentiment_Analysis_Dataset.csv")
t = pd.DataFrame()
t['Sentiment'] = df.Sentiment
t['Text'] = df.SentimentText
#======================================================= ======================================================

stop_words = set(stopwords.words("english"))
vectorizer = TfidfVectorizer(use_idf = True, lowercase = True , strip_accents = 'ascii' , stop_words = stop_words )

X = vectorizer.fit_transform(t.Text)
y = t.Sentiment

X_train,X_test,y_train,y_test = train_test_split(X,y)

clf = naive_bayes.MultinomialNB()
clf.fit(X_train,y_train)

#======================================================= ======================================================

def classifier(queries):

		#===================================================================
		#
		query = queries
		tknzr=TweetTokenizer(strip_handles=True,reduce_len=True)
		consumer_key="YOUR_KEY"
		consumer_secret="YOUR SECRET_TOKEN"
		access_token="YOUR TOKEN"
		access_token_secret="TOKEN_SECRET"
		try:
		    auth = OAuthHandler(consumer_key, consumer_secret)
		    auth.set_access_token(access_token, access_token_secret)

		    api = tweepy.API(auth)
		    tweets_caught = api.search(q=query,count=5)

		except:
		    print("Error")

		#====================================================================

		#===========================cleaning tweet===========================
		count = 0
		text = []
		raw_tweet = []
		for tweet in tweets_caught:

		    clean_text = []

		    words = tknzr.tokenize(tweet.text)

		    for w in words:
		        if w not in stop_words:
		            clean_text.append(w)

		    str = " "
		    for w in clean_text:
		        str = str+w+" "

		    URLless_str = re.sub(r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))', '', str)

		    if tweet.retweet_count > 0:
		        if URLless_str not in text:
		        	text.append(URLless_str)
		        	raw_tweet.append(tweet.text)
		        	count = count+1
		    else:
		    	text.append(URLless_str)
		    	raw_tweet.append(tweet.text)
		    	count = count + 1

		#
		#======================================================================

		text_vec = vectorizer.transform(text)
		Resultant_Sentiment = clf.predict(text_vec)

		answer = pd.DataFrame()
		answer["tweet"] = raw_tweet
		answer["Sentiment"] = Resultant_Sentiment

		return answer

#======================================================= ======================================================

app = Flask(__name__)

@app.route('/')
def dir1():
    return render_template("profile.html")

@app.route('/sentiment' , methods = ['POST'])
def sentiment():
	queries = request.form['query']
	answer = classifier(queries)
	return render_template("sentiment.html",sentiments=answer)

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

#======================================================= ======================================================


import collections
import heapq
from typing import List

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
        adj = collections.defaultdict(list)
        for i in range(len(edges)):
            src, dst = edges[i]
            adj[src].append([dst, succProb[i]])
            adj[dst].append([src, succProb[i]])

        pq = [(-1, start)]
        vis = set()

        while pq:
            prob, curr = heapq.heappop(pq)
            vis.add(curr)

            if curr == end:
                return prob * -1

            for neig, edgeProb in adj[curr]:
                if neig not in vis:
                    heapq.heappush(pq, (prob * edgeProb, neig))

        return 0


from calendar import c
from pyexpat import model
from re import L
import numpy as np
import pandas as pd

compas_scores_raw= pd.read_csv("compas_score_raw.csv",  lineterminator='\n')
compas_scores_two_year= pd.read_csv("compas_scores_two_years.csv",  lineterminator='\n')
print('-----------------Compas Scores Raw-----------------')
print('type',type(compas_scores_raw))
print('-----------------Compas Scores Two Year-----------------')
print('type',type(compas_scores_two_year))

#number of rows and columns
print('-----------------Compas Scores Raw-----------------')
print('shape',compas_scores_raw.shape)
print('-----------------Compas Scores Two Year-----------------')
print('shape',compas_scores_two_year.shape)

# fitlering the data with the following conditions
# 1. if charge data was not within 30 days of arrest
# 2. c_charge_degree is not missing
# 3. score_text is not missing
# 4. is_recid is not missing -1 means missing

print('-----------------Compas Scores two year-----------------')
df= compas_scores_two_year[[ 'age', 'c_charge_degree','race', 'age_cat', 'score_text', 'sex', 'priors_count', 'days_b_screening_arrest', 'decile_score', 'is_recid',  'c_jail_in', 'c_jail_out',  'v_decile_score','two_year_recid\r']]
print(np.shape(df))

df = df.loc[(df['days_b_screening_arrest'] <= 30) & (df['days_b_screening_arrest'] >= -30) & (df['is_recid'] != -1) & (df['c_charge_degree'] != 'O') & (df['score_text'] != 'N/A')]
print('shape of filtered data',df.shape)

#length of stay in jail
df['length_of_stay'] = pd.to_datetime(df['c_jail_out']) - pd.to_datetime(df['c_jail_in'])
df['length_of_stay'] = df['length_of_stay'].astype('timedelta64[D]')
df['length_of_stay'] = df['length_of_stay'].astype(int)
print(df['length_of_stay'])
print('shape of filtered data',df.shape)
print('length of stay',df['length_of_stay'].describe())
#correlation between length of stay and decile score
print('correlation between length of stay and decile score',df['length_of_stay'].corr(df['decile_score']))

print('-----------------describe age-----------------')
print(df['age'].describe())
print('-----------------describe race----------------')
print(df['race'].describe())

print('-----------------race split-----------------')
race  = ['African-American', 'Caucasian', 'Hispanic', 'Asian', 'Native American', 'Other']
for i in race :
    print( i,len(df[df['race']== i])/len(df['race']))

print ('-----------------describe score text----------------')
print('low ', len(df[df['score_text'] == 'Low']))
print('medium ', len(df[df['score_text'] == 'Medium']))
print('high ', len(df[df['score_text'] == 'High']))

#race and sex split
female = []
male = []

for i in race :

    temp  = len(df[(df['race']== i) & (df['sex'] == 'Male')]  )
    print(temp)
    male.append(temp)
    temp  = len(df[(df['race']== i) & (df['sex'] == 'Female')])
    female.append(temp)

print(race)
print ('female', female)
print('male', male)

f = pd.crosstab(df['sex'], df['race'])
print('f',f)

# find decide score for african american
print('-----------------decile score for african american-----------------')
print(df[(df['race']) == 'African-American']['decile_score'].describe())

decile = [1,2,3,4,5,6,7,8,9,10]
# plot decide score for african american
import matplotlib.pyplot as plt

# bar plot for decide score for african american and caucasian

df_race_decile_score = df[['race', 'decile_score']]
df_african = df_race_decile_score[ df_race_decile_score['race'] == 'African-American']
df_caucasian = df_race_decile_score[ df_race_decile_score['race'] == 'Caucasian']
counts_decile_AA = []
counts_decile_C = []
temp = []
for i in decile:
    temp = len(df_african[df_african['decile_score'] == i])
    counts_decile_AA.append(temp)
    temp = len(df_caucasian[df_caucasian['decile_score'] == i])
    counts_decile_C.append(temp)

fig = plt.figure()
ax = fig.subplots(1,2)
ax[0].bar(decile, counts_decile_AA)
ax[0].set_title('African American')
ax[1].bar(decile, counts_decile_C)
ax[1].set_title('Caucasian')

ax[0].set_ylabel('Count')
ax[0].set_xlabel('Decile score')
ax[0].set_ylim(0, 650)
ax[1].set_ylabel('Count')
ax[1].set_xlabel('Decile score')
ax[1].set_ylim(0, 650)

plt.show()

# # plot volinent decide score for african american and caucasian

df_race_V_decile_score = df[['race', 'v_decile_score']]
df_african = df_race_V_decile_score[ df_race_V_decile_score['race'] == 'African-American']
df_caucasian = df_race_V_decile_score[ df_race_V_decile_score['race'] == 'Caucasian']
counts_decile_AA = []
counts_decile_C = []
temp = []
for i in decile:
    temp = len(df_african[df_african['v_decile_score'] == i])
    counts_decile_AA.append(temp)
    temp = len(df_caucasian[df_caucasian['v_decile_score'] == i])
    counts_decile_C.append(temp)

fig = plt.figure()
ax = fig.subplots(1,2)
ax[0].bar(decile, counts_decile_AA)
ax[0].set_title('African American')
ax[1].bar(decile, counts_decile_C)
ax[1].set_title('Caucasian')

ax[0].set_ylabel('Count')
ax[0].set_xlabel('Violent Decile score')
ax[0].set_ylim(0, 850)
ax[1].set_ylabel('Count')
ax[1].set_xlabel('Violent Decile score')
ax[1].set_ylim(0, 850)

plt.show()

# create some factors for logistic regression
df_c_charge_degree = df[['c_charge_degree']]
df_age_cat = df[['age_cat']]
df_race = df[['race']]
df_sex = df[['sex']]
df_age_race = df[['race']]
df_score = df[['score_text']]

# df_c_charge_degree = pd.get_dummies(df_c_charge_degree)

# print('head', df_c_charge_degree.head())
#labels, uniques = pd.factorize(df_c_charge_degree)

#factorize df_c_charge_degree
crime_factor, u_charge_degree = pd.factorize(df_c_charge_degree['c_charge_degree'])
f_age_cat, u_age_cat= pd.factorize(df_age_cat['age_cat'])
#relevel age cat with reference = 1
f_age_cat = f_age_cat - 1
#factorize race
f_race_AA, u_race_AA= pd.factorize(df_age_race['race'] == 'African-American')
f_race_C, u_race = pd.factorize(df_age_race['race'] == 'Caucasian')
#relevel race with reference = 3
print('----------------race----------------')
print("Numeric Representation : \n", f_race_AA)
print("Unique Values : \n", u_race_AA)

#factorize gender with male and female labels
f_gender, uniques_gender  = pd.factorize(df_sex['sex'])
print("Numeric Representation : \n", f_gender)
print("Unique Values : \n", uniques_gender)
#factorise score text
f_score_text, u_score_text = pd.factorize(df_score['score_text'] != 'Low')
print("Numeric Representation : \n", f_score_text)
print("size of f_score_text", len(f_score_text))
print("Unique Values : \n", u_score_text)

# create a new maxtrix with the factors
priors_count  = df[['priors_count']]
two_year_recid = df[['two_year_recid\r']]

X = np.column_stack(( f_age_cat, crime_factor, f_race_AA, f_race_C, f_gender, priors_count, two_year_recid  ))

# build a binmal logistic regression model to explain the score text given the factors
from sklearn.linear_model import LogisticRegression
model  = LogisticRegression(penalty='l2', C=1)
model.fit(X, f_score_text)
ypred = model.predict(X)
#print summary
print('intercept', model.intercept_)
#print coefficients with corresponding factors
print('coefficients', model.coef_)
print('score', model.score(X, f_score_text))
#model accuracy
from sklearn.metrics import accuracy_score
print('accuracy', accuracy_score(f_score_text, ypred))

import statsmodels.api as sm
model = sm.GLM(f_score_text, X,  family=sm.families.Binomial())
results = model.fit()
print(results.summary())


# 2013 GCE A Level P1

"""
Task 1.1
"""

def main():
    # read data from file and store in wordList
    # wordList format:  [(term,occ)]

    wordList = []
    inF = open('WORDS1.TXT', 'r')
    term = inF.readline().rstrip()
    while term != '':
        occ = int(inF.readline().rstrip())
        wordList.append((term, occ))
        term = inF.readline().rstrip()
    inF.close()

    # compute the highest number of occurrrences
    maxTerm, maxOcc = wordList[0]  # initialise maxTerm and maxOcc with
    # the 1st word and its occurrencs
    for term, occ in wordList:
        if occ > maxOcc:
            maxOcc = occ
            maxTerm = term

    # output the term with the highest number of occurrences
    print('Highest occurring term:', maxTerm)

main()


from __future__ import print_function

__revision__ = "src/engine/SCons/Tool/FortranCommon.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"

import re
import os.path

import SCons.Action
import SCons.Defaults
import SCons.Scanner.Fortran
import SCons.Tool
import SCons.Util

def isfortran(env, source):
    """Return 1 if any of code in source has fortran files in it, 0
    otherwise."""
    try:
        fsuffixes = env['FORTRANSUFFIXES']
    except KeyError:
        # If no FORTRANSUFFIXES, no fortran tool, so there is no need to look
        # for fortran sources.
        return 0

    if not source:
        # Source might be None for unusual cases like SConf.
        return 0
    for s in source:
        if s.sources:
            ext = os.path.splitext(str(s.sources[0]))[1]
            if ext in fsuffixes:
                return 1
    return 0

def _fortranEmitter(target, source, env):
    node = source[0].rfile()
    if not node.exists() and not node.is_derived():
       print("Could not locate " + str(node.name))
       return ([], [])
    # This has to match the def_regex in the Fortran scanner
    mod_regex = r"""(?i)^\s*MODULE\s+(?!PROCEDURE|SUBROUTINE|FUNCTION|PURE|ELEMENTAL)(\w+)"""
    cre = re.compile(mod_regex,re.M)
    # Retrieve all USE'd module names
    modules = cre.findall(node.get_text_contents())
    # Remove unique items from the list
    modules = SCons.Util.unique(modules)
    # Convert module name to a .mod filename
    suffix = env.subst('$FORTRANMODSUFFIX', target=target, source=source)
    moddir = env.subst('$FORTRANMODDIR', target=target, source=source)
    modules = [x.lower() + suffix for x in modules]
    for m in modules:
       target.append(env.fs.File(m, moddir))
    return (target, source)

def FortranEmitter(target, source, env):
    target, source = _fortranEmitter(target, source, env)
    return SCons.Defaults.StaticObjectEmitter(target, source, env)

def ShFortranEmitter(target, source, env):
    target, source = _fortranEmitter(target, source, env)
    return SCons.Defaults.SharedObjectEmitter(target, source, env)

def ComputeFortranSuffixes(suffixes, ppsuffixes):
    """suffixes are fortran source files, and ppsuffixes the ones to be
    pre-processed. Both should be sequences, not strings."""
    assert len(suffixes) > 0
    s = suffixes[0]
    sup = s.upper()
    upper_suffixes = [_.upper() for _ in suffixes]
    if SCons.Util.case_sensitive_suffixes(s, sup):
        ppsuffixes.extend(upper_suffixes)
    else:
        suffixes.extend(upper_suffixes)

def CreateDialectActions(dialect):
    """Create dialect specific actions."""
    CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect)
    CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect)
    ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect)
    ShCompPPAction = SCons.Action.Action('$SH%sPPCOM ' % dialect, '$SH%sPPCOMSTR' % dialect)

    return CompAction, CompPPAction, ShCompAction, ShCompPPAction

def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0):
    """Add dialect specific construction variables."""
    ComputeFortranSuffixes(suffixes, ppsuffixes)

    fscan = SCons.Scanner.Fortran.FortranScan("%sPATH" % dialect)

    for suffix in suffixes + ppsuffixes:
        SCons.Tool.SourceFileScanner.add_scanner(suffix, fscan)

    env.AppendUnique(FORTRANSUFFIXES = suffixes + ppsuffixes)

    compaction, compppaction, shcompaction, shcompppaction = \
            CreateDialectActions(dialect)

    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    for suffix in suffixes:
        static_obj.add_action(suffix, compaction)
        shared_obj.add_action(suffix, shcompaction)
        static_obj.add_emitter(suffix, FortranEmitter)
        shared_obj.add_emitter(suffix, ShFortranEmitter)

    for suffix in ppsuffixes:
        static_obj.add_action(suffix, compppaction)
        shared_obj.add_action(suffix, shcompppaction)
        static_obj.add_emitter(suffix, FortranEmitter)
        shared_obj.add_emitter(suffix, ShFortranEmitter)

    if '%sFLAGS' % dialect not in env:
        env['%sFLAGS' % dialect] = SCons.Util.CLVar('')

    if 'SH%sFLAGS' % dialect not in env:
        env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)

    # If a tool does not define fortran prefix/suffix for include path, use C ones
    if 'INC%sPREFIX' % dialect not in env:
        env['INC%sPREFIX' % dialect] = '$INCPREFIX'

    if 'INC%sSUFFIX' % dialect not in env:
        env['INC%sSUFFIX' % dialect] = '$INCSUFFIX'

    env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect)

    if support_module == 1:
        env['%sCOM' % dialect]     = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
        env['%sPPCOM' % dialect]   = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
        env['SH%sCOM' % dialect]    = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
        env['SH%sPPCOM' % dialect]  = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
    else:
        env['%sCOM' % dialect]     = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
        env['%sPPCOM' % dialect]   = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
        env['SH%sCOM' % dialect]    = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
        env['SH%sPPCOM' % dialect]  = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)

def add_fortran_to_env(env):
    """Add Builders and construction variables for Fortran to an Environment."""
    try:
        FortranSuffixes = env['FORTRANFILESUFFIXES']
    except KeyError:
        FortranSuffixes = ['.f', '.for', '.ftn']

    #print("Adding %s to fortran suffixes" % FortranSuffixes)
    try:
        FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
    except KeyError:
        FortranPPSuffixes = ['.fpp', '.FPP']

    DialectAddToEnv(env, "FORTRAN", FortranSuffixes,
                    FortranPPSuffixes, support_module = 1)

    env['FORTRANMODPREFIX'] = ''     # like $LIBPREFIX
    env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX

    env['FORTRANMODDIR'] = ''          # where the compiler should place .mod files
    env['FORTRANMODDIRPREFIX'] = ''    # some prefix to $FORTRANMODDIR - similar to $INCPREFIX
    env['FORTRANMODDIRSUFFIX'] = ''    # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX
    env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'

def add_f77_to_env(env):
    """Add Builders and construction variables for f77 to an Environment."""
    try:
        F77Suffixes = env['F77FILESUFFIXES']
    except KeyError:
        F77Suffixes = ['.f77']

    #print("Adding %s to f77 suffixes" % F77Suffixes)
    try:
        F77PPSuffixes = env['F77PPFILESUFFIXES']
    except KeyError:
        F77PPSuffixes = []

    DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes)

def add_f90_to_env(env):
    """Add Builders and construction variables for f90 to an Environment."""
    try:
        F90Suffixes = env['F90FILESUFFIXES']
    except KeyError:
        F90Suffixes = ['.f90']

    #print("Adding %s to f90 suffixes" % F90Suffixes)
    try:
        F90PPSuffixes = env['F90PPFILESUFFIXES']
    except KeyError:
        F90PPSuffixes = []

    DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes,
                    support_module = 1)

def add_f95_to_env(env):
    """Add Builders and construction variables for f95 to an Environment."""
    try:
        F95Suffixes = env['F95FILESUFFIXES']
    except KeyError:
        F95Suffixes = ['.f95']

    #print("Adding %s to f95 suffixes" % F95Suffixes)
    try:
        F95PPSuffixes = env['F95PPFILESUFFIXES']
    except KeyError:
        F95PPSuffixes = []

    DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
                    support_module = 1)

def add_f03_to_env(env):
    """Add Builders and construction variables for f03 to an Environment."""
    try:
        F03Suffixes = env['F03FILESUFFIXES']
    except KeyError:
        F03Suffixes = ['.f03']

    #print("Adding %s to f95 suffixes" % F95Suffixes)
    try:
        F03PPSuffixes = env['F03PPFILESUFFIXES']
    except KeyError:
        F03PPSuffixes = []

    DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes,
                    support_module = 1)

def add_f08_to_env(env):
    """Add Builders and construction variables for f08 to an Environment."""
    try:
        F08Suffixes = env['F08FILESUFFIXES']
    except KeyError:
        F08Suffixes = ['.f08']

    try:
        F08PPSuffixes = env['F08PPFILESUFFIXES']
    except KeyError:
        F08PPSuffixes = []

    DialectAddToEnv(env, "F08", F08Suffixes, F08PPSuffixes,
                    support_module = 1)

def add_all_to_env(env):
    """Add builders and construction variables for all supported fortran
    dialects."""
    add_fortran_to_env(env)
    add_f77_to_env(env)
    add_f90_to_env(env)
    add_f95_to_env(env)
    add_f03_to_env(env)
    add_f08_to_env(env)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


import sys
import json
import logging
import argparse
import select
import time
import logs.server_log_config
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
from common.variables import ACTION, PRESENCE, TIME, USER, ACCOUNT_NAME, RESPONSE, \
    MESSAGE, MESSAGE_TEXT, ERROR, DEFAULT_PORT, MAX_CONNECTIONS, SENDER
from common.utils import get_message, send_message
from decorators import log

# Инициализация логирования сервера:
SERVER_LOGGER = logging.getLogger('server')

@log
def process_client_message(message, messages_list, client):
    """
    Обработчик сообщений от клиентов.
    Функция принимает словарь-сообщение от клиента, проверяет корректность, возвращает словарь-ответ для клиента.
    :param message:
    :param messages_list:
    :param client:
    :return:
    """
    SERVER_LOGGER.debug(f'Разбор сообщения от клиента: {message}.')
    # Если это сообщение присутствует, принимаем и отвечаем.
    if ACTION in message and message[ACTION] == PRESENCE and TIME in message \
            and USER in message and message[USER][ACCOUNT_NAME] == 'Guest':
        send_message(client, {RESPONSE: 200})
        return
    # Если это сообщение, то добавляем его в очередь сообщений. Ответ не требуется.
    elif ACTION in message and message[ACTION] == MESSAGE and TIME in message \
            and MESSAGE_TEXT in message:
        messages_list.append((message[ACCOUNT_NAME], message[MESSAGE_TEXT]))
        return
    else:
        send_message(client, {
            RESPONSE: 400,
            ERROR: 'Bad request',
        })
        return

@log
def arg_parser():
    """Парсер аргументов командной строки."""
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', default=DEFAULT_PORT, type=int, nargs='?')
    parser.add_argument('-a', default='', nargs='?')
    namespace = parser.parse_args(sys.argv[1:])
    listen_address = namespace.a
    listen_port = namespace.p

    # Проверка получения корректного номера порта для работы сервера.
    if not 1023 < listen_port < 65535:
        SERVER_LOGGER.critical(
            f'Попытка запуска сервера с неподходящим номером порта: {listen_port}.'
            f' Допустимые адреса с 1024 до 65535. Клиент завершается.'
        )
        sys.exit(1)

    return listen_address, listen_port

def main():
    """
    Загрузка параметров командной строки.
    Если нет параметров, то задаем значения по умолчанию.
    :return:
    """
    listen_address, listen_port = arg_parser()

    SERVER_LOGGER.info(f'Запущен сервер. Порт для подключений: {listen_port}, '
                       f'адрес, с которого принимаются подключения: {listen_address}. '
                       f'Если адрес не указан, то принимаются соединения с любых адресов.')

    # Готовим сокет.
    transport = socket(AF_INET, SOCK_STREAM)
    transport.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    transport.bind((listen_address, listen_port))
    transport.settimeout(1)

    # Список клиентов, очередь сообщений.
    clients = []
    messages = []

    # Слушаем порт.
    transport.listen(MAX_CONNECTIONS)

    while True:
        try:
            client, client_address = transport.accept()
        except OSError as err:
            print(err.errno)
            pass
        else:
            SERVER_LOGGER.info(f'Установлено соединение с ПК {client_address}.')
            clients.append(client)

        recv_data_list = []
        send_data_list = []
        err_list = []

        # Проверяем на наличие ждущих клиентов.
        try:
            if clients:
                recv_data_list, send_data_list, err_list = select.select(clients, clients, [], 0)
        except OSError:
            pass

        # Принимаем сообщения и еcли они есть, то кладем в словарь. В случае ошибки исключаем клиента.
        if recv_data_list:
            for client_with_message in recv_data_list:
                try:
                    process_client_message(get_message(client_with_message), messages, client_with_message)
                except:
                    SERVER_LOGGER.info(f'Клиент {client_with_message.getpeername()} отключился от сервера.')
                    clients.remove(client_with_message)
        # Если есть сообщения для отправки и ожидающие клиенты, то отправляем им сообщение.
        if messages and send_data_list:
            message = {
                ACTION: MESSAGE,
                SENDER: messages[0][0],
                TIME: time.time(),
                MESSAGE_TEXT: messages[0][1]
            }
            del messages[0]
            for waiting_client in send_data_list:
                try:
                    send_message(waiting_client, message)
                except:
                    SERVER_LOGGER.info(f'Клиент {waiting_client.getpeername()} отключился от сервера.')
                    waiting_client.close()
                    clients.remove(waiting_client)

if __name__ == '__main__':
    main()


import sys
import ruamel
from ruamel.yaml import YAML
from datetime import datetime, date, time
from common import *
import fileinput

class NonAliasingRTRepresenter(ruamel.yaml.RoundTripRepresenter):
    def ignore_aliases(self, data):
        return True

def main():
    out = {'races': []}

    yaml = YAML(typ='safe')
    with open('data/common.yaml', 'r') as fi:
        ydat = yaml.load(fi)

    d = date.today()
    year = d.year
    month = d.month + 1
    if month == 13:
        # skip Smarch
        year = year + 1
        month = 1
    day = 1

    try:
        while True:
            d = date(year, month, day)
            for w in ydat['weekly']:
                if w['isoweekday'] == d.isoweekday():
                    t = time.fromisoformat(w['time'])
                    dt = datetime.combine(d, t, tzinfo=RACETZ)
                    r = {'datetime': dt.strftime('%Y-%m-%d %H:%M')}
                    for k in w.keys():
                        if k not in ('isoweekday', 'time', 'msg'):
                            r[k] = w[k]
                    kw = dt.isocalendar().week

                    sunday = d.isoweekday() == 7
                    casual = r['skills_preset'] == 'casual'

                    # alternate simple and complex, and do the opposite on Sunday
                    simple = True
                    if (kw % 2 == 0 and casual) or (kw % 2 != 0 and not casual):
                        simple = False
                    if sunday:
                        simple = not simple

                    if simple:
                        r['desc'] += ' - Simple'
                    else:
                        r['desc'] += ' - Complex'
                    out['races'].append(r)

            day = day + 1

    except ValueError:
        pass

    # ugly hack
    replace_last = 'Casual - Complex' if month % 2 == 0 else 'Hard - Complex'
    for i, obj in reversed(list(enumerate(out['races']))):
        if obj['desc'] == replace_last:
            out['races'][i]['desc'] = obj['desc'].replace('Complex', 'Mystery')
            break

    yout = YAML()
    yout.default_flow_style = False
    yout.version = (1, 2)
    yout.indent(mapping=2, sequence=4, offset=2)
    yout.Representer = NonAliasingRTRepresenter
    with open('data/races-new.yaml', 'w') as fout:
        yout.dump(out, fout)

    # add whitespace
    with fileinput.FileInput('data/races-new.yaml', inplace=True) as f:
        for line in f:
            if line.startswith('  -') and f.lineno() > 4:
                print()
            print(line, end='')

if __name__ == '__main__':
    main()


import numpy as np
from scipy.special import expit

def piston_action(alfa, p_linea, p_servicio):
    alfa %= 2 * np.pi
    return (p_servicio - p_linea) * expit((alfa - np.pi) * 20)

def build_indep(
    alfa: np.float32,
    beta: np.float32,
    omega: np.float32,
    mb: np.float32,
    mp: np.float32,
    R: np.float32,
    Ib: np.float32,
    Lg: np.float32,
    L: np.float32,
    D_plunger,
    p_linea,
    p_servicio,
) -> np.ndarray:
    p_alfa = piston_action(alfa, p_linea, p_servicio)

    dbdt = (R / L) * (np.cos(alfa) / np.cos(beta)) * omega
    d2bdt2 = (dbdt**2 - omega**2) * np.tan(beta)

    b0 = mb * Lg * (R / L) * omega**2 * np.sin(alfa)
    b1 = (
        -mb
        * R
        * omega**2
        * (
            np.cos(alfa)
            + (1 - Lg / L)
            * (
                (R / L) * (np.cos(alfa) ** 2 / np.cos(beta) ** 3)
                - np.sin(alfa) * np.tan(beta)
            )
        )
    )
    b2 = Ib * d2bdt2
    b3 = 0
    b4 = mp * R * omega**2 * (
        (np.cos(alfa + beta) / np.cos(beta))
        + (R / L) * (np.cos(alfa) ** 2 / np.cos(beta) ** 3)
    ) - p_alfa * (D_plunger**2 * np.pi / 4)

    return np.array([b0, b1, b2, b3, b4])

def build_matrix(L: np.float32, Lg: np.float32, beta: np.float32) -> np.ndarray:
    m = np.eye(5)
    m[4, 4] = 0
    m[4, 3] = 1

    m[3, 3] = 0
    m[3, 4] = -1
    m[3, 2] = 1

    m[0, 2] = 1
    m[1, 3] = 1

    vec = np.array(
        [
            -(L - Lg) * np.sin(beta),
            (L - Lg) * np.sin(beta),
            Lg * np.cos(beta),
            -Lg * np.sin(beta),
            0,
        ]
    )

    m[2] = vec
    return m

def solve_system(
    alfa,
    beta,
    omega,
    mb: np.float32,
    mp: np.float32,
    R: np.float32,
    Ib: np.float32,
    L,
    Lg,
    D_plunger,
    p_linea,
    p_servicio,
):
    A = build_matrix(L, Lg, beta)
    b = build_indep(
        alfa, beta, omega, mb, mp, R, Ib, Lg, L, D_plunger, p_linea, p_servicio
    )

    sol = np.linalg.solve(A, b) / 1000

    R = np.sqrt((sol[0] + sol[2]) ** 2 + (sol[1] + sol[3]) ** 2)
    theta_R = np.arctan((sol[1] + sol[3]) / (sol[0] + sol[2]))

    ret_dict = {
        "module_A": np.sqrt(sol[0] ** 2 + sol[1] ** 2),
        "phase_A": np.arctan2(sol[1], sol[0]),
        "module_B": np.sqrt(sol[2] ** 2 + sol[3] ** 2),
        "phase_B": np.arctan2(sol[3], sol[2]),
        "Total_mod": R,
        "Total_phase": theta_R,
        "solution": sol,
    }

    return ret_dict

def get_max(res):
    modA = np.array([x["module_A"] for x in res])
    phiA = np.array([x["phase_A"] for x in res])

    modB = np.array([x["module_B"] for x in res])
    phiB = np.array([x["phase_B"] for x in res])

    XA = modA * np.cos(phiA)
    YA = modA * np.sin(phiA)

    XB = modB * np.cos(phiB)
    YB = modB * np.sin(phiB)

    Amax = np.argmax(modA)
    Bmax = np.argmax(modB)

    XAmax = XA[Amax]
    YAmax = YA[Amax]
    XBmax = XB[Bmax]
    YBmax = YB[Bmax]

    print(f"XAmax = {XAmax}, YAmax = {YAmax}")
    print(f"XBmax = {XBmax}, YBmax = {YBmax}")

    return 1, 1


from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.graphics import Color, Line, Rectangle
from image_to_text import get_text, train_model
import cv2
from string import ascii_uppercase as UC

class DrawWidget(RelativeLayout):

    def __init__(self, **kwargs):

        super(DrawWidget, self).__init__(**kwargs)

        with self.canvas:
           Color(*(1,1,1),mode="rgb")

           self.rect = Rectangle(size = self.size, pos = self.pos)
        self.bind(size=self.update_rect)

    def on_touch_down(self, touch):
        color = (0,0,0)
        with self.canvas:
            Color(*color,mode="rgb")
            width = 2.5
            x,y = self.to_local(x=touch.x, y=touch.y)
            touch.ud["line"] = Line(points=(x, y),width=width)
    def on_touch_move(self,touch):
        x,y = self.to_local(x=touch.x, y=touch.y)
        touch.ud['line'].points += [x, y]

    def update_rect(self, instance, value):
        self.rect.size = self.size
        self.rect.pos = self.pos

class DrawApp(App):

    def build(self):
        self.title = 'Convert To Text'

        parent = RelativeLayout()

        self.draw = DrawWidget(size_hint=(0.5,0.8),pos_hint={'x':0,'y':0.2})

        clear_btn = Button(size_hint=(0.5,0.1),text="Clear",pos_hint={'x':0,'y':0.1})
        clear_btn.bind(on_release=self.clear_canvas)

        convert_btn = Button(size_hint=(0.5,0.1),text="Convert to text",pos_hint={'x':0.5,'y':0.1})
        convert_btn.bind(on_release=self.convert)

        self.label = Label(size_hint=(0.5,0.9),pos_hint={'x':0.5,'y':0.2})

        label1 = Label(size_hint=(0.3,0.1),pos_hint={"x":0,"y":0},text="Wrong conversion? Type in correct capital letters comma separated and train")
        label1.bind(width=lambda *x: label1.setter('text_size')(label1, (label1.width, None)), texture_size=lambda *x: label1.setter('height')(label1, label1.texture_size[1]))

        self.inp_txt = TextInput(size_hint=(0.4,0.1),pos_hint={"x":0.3,"y":0})
        self.train_btn = Button(size_hint=(0.3,0.1),pos_hint={"x":0.7,"y":0},text="Train", disabled=True)
        self.train_btn.bind(on_release = self.train)

        parent.add_widget(self.draw)
        parent.add_widget(self.label)
        parent.add_widget(clear_btn)
        parent.add_widget(convert_btn)
        parent.add_widget(label1)
        parent.add_widget(self.inp_txt)
        parent.add_widget(self.train_btn)

        return parent

    def clear_canvas(self, obj):
        self.draw.canvas.clear()
        with self.draw.canvas:
           Color(*(1,1,1),mode="rgb")
           self.draw.rect = Rectangle(size = self.draw.size, pos = (0,0))
        self.draw.bind(size=self.draw.update_rect)
        self.train_btn.disabled = True

    def convert(self, obj):
        self.train_btn.disabled = False
        self.draw.export_to_png("draw.png")
        img = cv2.imread("draw.png")
        self.lets, self.imgs = get_text(img)
        txt = " ".join(self.lets)
        self.label.text = txt

    def train(self, obj):
        let = self.inp_txt.text
        let = let.replace(" ","").split(",")
        lbls = []
        chars = list(UC)
        for l in let:
            lbls.append(chars.index(l))
        if len(lbls) == len(self.imgs):
            train_model(self.imgs, lbls)

if __name__ == "__main__":
    DrawApp().run()


from django.db import models
import re
import statistics

from .direct_indicator import DirectIndicator
from .question_response import QuestionResponse

find_square_bracket_keys = re.compile(r"\[(.*?)\]")

class IndirectIndicator(models.Model):
    topic = models.ForeignKey('Topic', related_name='indirect_indicators', on_delete=models.SET_NULL, null=True)
    method = models.ForeignKey("Method", related_name="indirect_indicators", on_delete=models.CASCADE, null=True)

    key = models.CharField(max_length=255, blank=False)
    formula = models.CharField(max_length=1000, unique=False, blank=False)
    name = models.CharField(max_length=255, unique=False, blank=False)
    description = models.TextField(blank=True, null=True)
    pre_unit = models.CharField(max_length=30, blank=True, default="")      # Examples: $,€
    post_unit = models.CharField(max_length=30, blank=True, default="")     # Examples: %, points, persons
    cut_off_lower_limit = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
    cut_off_upper_limit = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)

    TEXT = "text"
    INTEGER = "integer"
    DOUBLE = "double"
    DATE = "date"
    BOOLEAN = "boolean"
    SINGLECHOICE = "singlechoice"
    MULTIPLECHOICE = "multiplechoice"

    DATA_TYPES = (
        (TEXT, "text"),
        (INTEGER, "integer"),
        (DOUBLE, "double"),
        (DATE, "date"),
        (BOOLEAN, "boolean"),
        (SINGLECHOICE, "singlechoice"),
        (MULTIPLECHOICE, "multiplechoice")
    )

    datatype = models.CharField(max_length=50, blank=False, choices=DATA_TYPES, default="text")

    PERFORMANCE = "performance"
    SCORING = "scoring"
    CERTIFICATION = "certification"

    INDICATOR_TYPES = (
        (PERFORMANCE, "performance"),
        (SCORING, "scoring"),
        (CERTIFICATION, "certification")
    )

    type = models.CharField(max_length=50, blank=False, choices=INDICATOR_TYPES, default="scoring")

    calculation = ''
    absolute_weights = []
    indicator_impact = None
    critical_impact_by = {}
    value = None
    has_conditionals = False
    exception = None
    exception_detail = None
    responses = None

    # used to find absolute weights
    expression = ''

    class Meta:
        unique_together = ['key', 'method']

    def __init__(self, *args, **kwargs):
        super(IndirectIndicator, self).__init__(*args, **kwargs)
        self.calculation = self.formula.replace("\n", "")

        if self.calculation.strip().startswith("IF"):
            self.has_conditionals = True

    def __str__(self):
        return self.key

    # calculation_keys are all indicators that are used within the formula of this indirect indicator
    @property
    def calculation_keys(self):
        calculation_keys =  re.findall(find_square_bracket_keys, self.calculation) #self.formula.replace("\n", ""))
        # print('*****************************', self.formula, self.calculation, calculation_keys)
        calculation_keys_uniques = list(set(calculation_keys))

        if self.key in calculation_keys_uniques:
            calculation_keys_uniques.remove(self.key)
        return calculation_keys_uniques

    # Used for calculation of absolute weights
    @property
    def formula_keys(self):
        formula_keys = re.findall(find_square_bracket_keys, self.formula)
        calculation_keys_uniques = list(set(formula_keys))

        if self.key in calculation_keys_uniques:
            calculation_keys_uniques.remove(self.key)
        return calculation_keys_uniques

    def find_weights(self, weight_dict):
        self.absolute_weights = [weight_dict]
        return self.absolute_weights

    # Replaces indicator keys with corresponding value to be able to calculate the indirect indicator (used in 'utils > calculate_indicators')
    def find_values(self, key_value_list):
        calculation = self.calculation
        if not None in key_value_list.values():
            for calculation_key in self.calculation_keys:
                if calculation_key in key_value_list:
                    value = key_value_list[calculation_key]
                    if isinstance(value, dict):
                        value = max(value, key=value.get)
                    calculation = calculation.replace(f"[{calculation_key}]", f"{value}")
            self.calculation = calculation
        else:
            print('Missing values in key_value_list!')

    # Calculates indicator formula
    def calculate(self):
        if len(self.calculation_keys) and not self.has_conditionals:
            self.exception = Exception("Not all keys are replaced with values")
            return

        self.exception = None
        self.error = None
        functionList = ['sum(', 'avg(', 'min(', 'max(', 'median(', 'mode(']

        # If there are conditionals
        if self.has_conditionals:
            self.value = None
            value = self.calculate_conditionals()
            self.value = value

        # if there's a function
        elif any(func in self.calculation for func in functionList):
            key = re.findall(find_square_bracket_keys, self.formula)
            if len(key):
                question_responses = QuestionResponse.objects.filter(survey_response__esea_account=4, survey_response__finished=True)
                directind = DirectIndicator.objects.filter(method=self.method, key=key[0]).first()
                indirectind = IndirectIndicator.objects.filter(method=self.method, key=key[0]).first()
                if directind is not None:
                    indicator = directind
                    indicator.filter_responses(question_responses)
                    responses = [float(r) for r in indicator.responses]

                    if 'avg(' in self.calculation:
                        self.value = sum(responses)/len(responses) # int(direct_indicator.value)
                    elif 'sum(' in self.calculation:
                            self.value = sum(responses)
                    elif 'min(' in self.calculation:
                        self.value = min(responses)
                    elif 'max(' in self.calculation:
                        self.value = max(responses)
                    elif 'median(' in self.calculation:
                        self.value = statistics.median(responses)
                    elif 'mode(' in self.calculation:
                        self.value = statistics.mode(responses)
                else:
                    self.value = 1
                    print('There are no responses to calculate the sum with.')
                    return

        # If a regular calculation can be performed
        else:
            try:
                self.expression = self.formula
                self.value = eval(self.calculation)
                return self.value
            except Exception as e:
                print('error!', self.calculation, self.has_conditionals)
                self.value = None

    # Calculates conditional formulas (IF..THEN..)
    def calculate_conditionals(self, verbose=False):
        formula = self.calculation.replace('IF', '@@IF').replace('ELSE', '##ELSE').replace('THEN', '%%THEN')
        formula = [x.strip() for x in re.split('@@|##|%%', formula)]
        formula = list(filter(lambda x: x != '', formula))

        if verbose:
            print(f'\n  {self.key}:::::::::: Start Conditional Calculations... \nformula: {formula}')

        full_formula = self.formula.replace('IF', '@@IF').replace('ELSE', '##ELSE').replace('THEN', '%%THEN')
        full_formula = [x.strip() for x in re.split('@@|##|%%', full_formula)]
        full_formula = list(filter(lambda x: x != '', full_formula))

        ifs = 1
        elses = 0
        last_if = False
        search_else = False
        val = None

        for i, cond in enumerate(formula):
            bracket_keys = list(set(re.findall(find_square_bracket_keys, cond)))

            if self.key in bracket_keys:
                bracket_keys.remove(self.key)
            if len(bracket_keys):
                print('Invalid Partial Condition: ', bracket_keys)
                # raise Exception("invalid partial condition")

            # Skips code till it finds the corresponding then/else statements corresponding to the IF statement that fails or succeeds.
            if search_else:
                if 'IF' in cond:
                    ifs += 1
                if 'ELSE' in cond:
                    elses += 1
                if ifs != elses:
                    continue
                else:
                    search_else = False
                    last_if = True
                    ifs = 1
                    elses = 0

            # Checks whether if statement equates to True
            if 'IF' in cond:
                cond = cond.replace('IF', '').replace('(', '').replace(')', '').replace('"', '').strip()
                last_if = False

                if 'AND' in cond:
                    conds = cond.split("AND")
                    conds = self.process_expression(conds)
                    evaluatedconds = [eval(n) for n in conds]

                    if not False in evaluatedconds:
                        last_if = True
                    else:
                        search_else = True
                    continue

                if 'OR' in cond:
                    conds = cond.split("OR")
                    conds = self.process_expression(conds)

                    evaluatedconds = [eval(n) for n in conds]

                    if True in evaluatedconds:
                        last_if = True
                    else:
                        search_else = True
                    continue

                cond = self.process_expression(cond)

                if eval(cond):
                    last_if = True
                else:
                    search_else = True
                continue

            # Serves conditional outcome
            if (last_if and '=' in cond) or (cond == formula[-1]):
                cond = cond.replace('(', '').replace(')', '')
                [var, val] = cond.split('=')
                var = var.replace('THEN', '').replace('ELSE', '')
                var = var.replace('[', '').replace(']', '').strip()
                if var != self.key:
                    raise Exception('Assignment variable does not match the key of this indirect indicator')
                val = val.replace('"', '')

                if verbose:
                    print('====', self.key, val)

                # Used for extracting weights
                self.expression = full_formula[i]
                try:
                    val = eval(val)
                except:
                    pass

                return str(val)

    def process_expression(self, conds):
        allowedOperators = ['<', '<=', '==', '>=', '>', '=']

        if not isinstance(conds, list):
            conds = [conds]

        for index, cond in enumerate(conds):
            # cond = cond.replace('=', '==')
            processed_cond = re.split('(<|<=|==|>=|>|=)', cond)
            for idx, value in enumerate(processed_cond):
                if value not in allowedOperators:
                    # Makes eval() of string equals string possible
                    processed_cond[idx] = f'"{value.strip().lower()}"'
            conds[index] = ''.join(processed_cond)

        if len(conds) == 1:
            conds = conds[0]

        return conds


from lib_das.DAS220_240 import telnet_das220_240
import time
import socket
import numpy

def REMOTE_SAMPLING_EXAMPLE():
    print("-------------------------------------------------------")
    print("  Remote Sammpling example : ")
    print("    - Getting NUMBER_OF_SAMPLE sample of CHANNEL_LIST channel each SAMP_TIME")
    print("    - Save the result into a CSV files")
    launch_time = time.strftime("%d_%b_%Y_%H_%M_%S")
    # Connexion to the DAS220 or DAS240
    mydas = telnet_das220_240(DAS_IP)
    #Setting the channel in the list to thermocouple K +/-30°C range and enable it
    mydas.all_chan_off()
    for chan in CHANNEL_LIST:
        mydas.set_chanmes(chan,'THErmo K,COMP,CEL',60,0,0)

    #Disabling command printing
    mydas.PR_OUT_CMD = 0
    mydas.PR_OUT = 1
    tab_res  = []
    time_res = []
    for chan in CHANNEL_LIST:
        tab_res.append([]) #create one list by channel

    #Make the measure
    for i in range(0,NUMBER_OF_SAMPLE):
        print("sample " + str(i))
        time.sleep(SAMP_TIME)
        time_res.append(time.strftime("%H:%M:%S"))
        for ichan in range(0,len(CHANNEL_LIST)):
            tab_res[ichan].append(mydas.get_chanmes(CHANNEL_LIST[ichan]))

    mydas.close();

    #Create CSV files
    f_name = "Remote_sampling_test_"+ launch_time + ".csv"
    flog = open(f_name,"a")
    #Create the first line
    first_string = "Sample Time" + CSV_SEPARATOR
    for ichan in range(0,len(CHANNEL_LIST)):
        first_string += "CHAN_" + CHANNEL_LIST[ichan] + CSV_SEPARATOR

    flog.write(first_string + "\n")

    #write each result in the csv files
    for ires in range(1, NUMBER_OF_SAMPLE):
        line = time_res[ires] + CSV_SEPARATOR
        for ichan in range(0,len(CHANNEL_LIST)):
            line += str(tab_res[ichan][ires]).replace('.',CSV_DECIMAL_DELIMITER) + CSV_SEPARATOR
        flog.write(line + "\n")
    flog.close()

    print("Test file Name : " + f_name )

'''
   main script
'''
#Update the DAS IP adress here
DAS_IP = "192.168.0.72"
SAMP_TIME = 1   #time in seconds
NUMBER_OF_SAMPLE = 10
CHANNEL_LIST = ["A1","A2"]
CSV_SEPARATOR = ';'
CSV_DECIMAL_DELIMITER  = ',' #update following your country

print("********* Starting DAS220/240 Remote sampling Script **************")
REMOTE_SAMPLING_EXAMPLE()
print("**************** End of DAS220/240 Test Script *******************")


from rally.common import logging
from rally.task import hook

LOG = logging.getLogger(__name__)

class Trigger(hook.HookTrigger):
    """DEPRECATED!!! USE `rally.task.hook.HookTrigger` instead."""

    def __init__(self, *args, **kwargs):
        super(Trigger, self).__init__(*args, **kwargs)
        LOG.warning("Please contact Rally plugin maintainer. The plugin '%s' "
                    "inherits the deprecated base class(Trigger), "
                    "`rally.task.hook.HookTrigger` should be used instead."
                    % self.get_name())

    @property
    def context(self):
        action_name, action_cfg = self.hook_cfg["action"]
        trigger_name, trigger_cfg = self.hook_cfg["trigger"]
        return {"description": self.hook_cfg["description"],
                "name": action_name,
                "args": action_cfg,
                "trigger": {"name": trigger_name,
                            "args": trigger_cfg}}


from os import stat
from flask import Flask, Response

from flask_restx import Resource, Api, reqparse
import random
import json
import os

from werkzeug.exceptions import BadHost, BadRequest

app = Flask(__name__)
api = Api(app)

#Cette route va permettre de retourner la valeur +1
@api.route('/plus_one/<int:number>')
@api.doc(params={"x": "Must be an integer."})
class Add(Resource):
    def get(self, number):
        return {'value': number+1}

#Cette route permet de retourner la valeur au carré et, pour mon cas j'ai testé de transmettre deux paramètres

@api.route('/square')
@api.doc(params={"int": "Must be an integer", "email": "Must be a string"}, location="query")
class Square(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('int', type=int)
        parser.add_argument('email', type=str)
        args = parser.parse_args()
        return {'value': args['int'] ** 2, 'email': args['email']}

#Cette route prend en paramètre le choix de l'utilisateur sous forme de int et renvoie le message final

@api.route('/game/<int:choice>')
@api.doc(params={"choice": "1: Pierre \n 2: Papier \n 3: Ciseaux \n 4: Lézard \n 5: Spock"})
class Game(Resource):
    def get(self, choice):
        liste_choices = ["Pierre", "Papier", "Ciseaux", "Lézard", "Spock"]

        def choice_computer(index):
            possibilities = ["Pierre", "Papier", "Ciseaux", "Lézard", "Spock"]
            possibilities.remove(possibilities[index])
            computer = possibilities[random.randint(0, len(possibilities)-1)]
            return computer

        if choice not in [1,2,3,4,5]:
            return Response(
        "Send a number between 1 and 5 !",
        status=400,
    )
        else:
            user_choice= liste_choices[choice-1]
            computer_choice= choice_computer(choice-1)
            index_computer = liste_choices.index(computer_choice)

            result = {0: {1: True, 2: False, 3: True, 4: False },
            1: {0: True, 2: False, 3: False, 4: True},
            2: {0: False, 1: True, 3: True, 4: False},
            3: {0: False, 1: True, 2: False, 4: True},
            4: {0: True, 1: False, 2: True, 3: False} }

            if result[choice-1][index_computer] == False:
                with open('stats.json') as json_file:
                    data = json.load(json_file)
                    data[user_choice] = int(data[user_choice]) + 1

                    with open('stats.json', 'w') as json_file:
                        json.dump(data, json_file)
                return {"ordinateur" : computer_choice, "user": user_choice, "message": "Vous avez perdu."}
            else:
                with open('stats.json') as json_file:
                    data = json.load(json_file)
                    data[user_choice] = int(data[user_choice]) + 1

                    with open('stats.json', 'w') as json_file:
                        json.dump(data, json_file)

                return {"ordinateur" : computer_choice, "user": user_choice, "message": "Vous avez gagné !"}

@api.route('/stats')
class Stats(Resource):
    def get(self):
        SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
        json_url = os.path.join(SITE_ROOT,"stats.json")
        data = json.load(open(json_url))
        return data

if __name__ == '__main__':
    app.run(debug=True)


import torch
import torch.nn as nn
from torch.utils.cpp_extension import load
import os
import time
import random
import math

cur_path = os.path.dirname(os.path.realpath(__file__))
cpu_unsorted_segsum = load('cpu_unsorted_segsum',
    [f'{cur_path}/cpu_extension.cc'],
    extra_cflags=['-fopenmp', '-O3', '-march=native'],
    extra_ldflags=['-lgomp', '-O3', '-march=native'],
    verbose=False)

import cpu_unsorted_segsum

if torch.cuda.is_available():
    cuda_unsorted_segsum = load('cuda_unsorted_segsum',
        [f'{cur_path}/cuda_extension.cu'],
        extra_cflags=['-fopenmp', '-O3', '-march=native'],
        extra_ldflags=['-lgomp', '-O3', '-march=native'],
        verbose=False)

    import cuda_unsorted_segsum

else:
    cuda_unsorted_segsum = None
    print('CUDA not available, cuda_unsorted_segsum will not be available')

def unsorted_segment_sum_ref(
    data : torch.Tensor,
    indices : torch.Tensor,
    num_segments : int
) -> torch.Tensor:
    return torch.cat([
        data[indices == i].sum(dim=0, keepdim=True)
        for i in range(num_segments)
    ], dim=0)

class UnsortedSegmentSum(torch.autograd.Function):
    @staticmethod
    def forward(ctx, data : torch.Tensor, indices  : torch.Tensor, num_segments : int) -> torch.Tensor:
        ctx.save_for_backward(indices)

        M = cuda_unsorted_segsum if data.device.type == 'cuda' else cpu_unsorted_segsum

        assert M is not None, f'No backend for {data.device}'

        if len(data.shape) == 2:
            return M.unsorted_segment_sum_fwd(data, indices, num_segments)
        else:
            raise NotImplementedError()

    @staticmethod
    def backward(ctx, grad):
        indices, = ctx.saved_tensors

        M = cuda_unsorted_segsum if grad.device.type == 'cuda' else cpu_unsorted_segsum

        assert M is not None, f'No backend for {grad.device}'

        if len(grad.shape) == 2:
            return M.unsorted_segment_sum_bwd(grad.contiguous(), indices), None, None
        else:
            raise NotImplementedError()

def unsorted_segment_sum(
    data : torch.Tensor,
    indices  : torch.Tensor,
    num_segments : int
) -> torch.Tensor:
    return UnsortedSegmentSum.apply(data, indices, num_segments)

def unit_test_cpu():
    print('==== Correctness Test CPU ====')
    data = torch.randn(1000, 3, requires_grad=False)
    indices = torch.randint(0, 100, (1000,), requires_grad=False)
    num_segments = 100

    d1 = data.clone().requires_grad_()
    d2 = data.clone().requires_grad_()

    ref = unsorted_segment_sum_ref(d1, indices, num_segments)
    out = UnsortedSegmentSum.apply(d2, indices, num_segments)

    print('(FWD) L2 = ', (ref - out).pow(2).sum().sqrt())

    ref.pow(2).sum().backward()
    out.pow(2).sum().backward()

    print('(BWD) L2 = ', (d1.grad - d2.grad).pow(2).sum().sqrt())

def unit_test_gpu():
    print('==== Correctness Test GPU ====')
    data = torch.randn(1000, 3, requires_grad=False)
    indices = torch.randint(0, 100, (1000,), requires_grad=False)
    num_segments = 100

    d1 = data.clone().requires_grad_()
    d2 = data.clone().cuda().requires_grad_()

    ref = unsorted_segment_sum_ref(d1, indices, num_segments)
    out = UnsortedSegmentSum.apply(d2, indices.clone().cuda(), num_segments)

    print('(FWD) L2 = ', (ref - out.cpu()).pow(2).sum().sqrt())

    ref.pow(2).sum().backward()
    out.pow(2).sum().backward()

    print('(BWD) L2 = ', (d1.grad - d2.grad.cpu()).pow(2).sum().sqrt())

if __name__ == '__main__':
    unit_test_cpu()
    unit_test_gpu()

    exit(0)

    # Benchmark

    t0 = time.perf_counter()
    for _ in range(1000):
        _ = unsorted_segment_sum_ref(data, indices, num_segments)
    t1 = time.perf_counter()
    print(f'Reference (Fwd): {(t1 - t0) * 1000:.2f} ms')

    t0 = time.perf_counter()
    for _ in range(1000):
        _ = UnsortedSegmentSum.apply(data, indices, num_segments)
    t1 = time.perf_counter()
    print(f'Extension (Fwd): {(t1 - t0) * 1000:.2f} ms')

    t0 = time.perf_counter()
    for _ in range(1000):
        out = unsorted_segment_sum_ref(d1, indices, num_segments)
        out.pow(2).sum().backward()
    t1 = time.perf_counter()
    print(f'Reference (Fwd + Bwd): {(t1 - t0) * 1000:.2f} ms')

    t0 = time.perf_counter()
    for _ in range(1000):
        out = UnsortedSegmentSum.apply(d2, indices, num_segments)
        out.pow(2).sum().backward()
    t1 = time.perf_counter()
    print(f'Extension (Fwd + Bwd): {(t1 - t0) * 1000:.2f} ms')


class numbers(object):
    def set(self):
        self.a=10
        self.b=12
        self.a,self.b=self.b,self.a
        print(self.a,self.b)
        print(self.b,self.a)
class strings(numbers):
    def put(self):
        super().set()
        self.s1="prasad"
        self.s2="naidu"
        self.s1,self.s2=self.s2,self.s1
        print(self.s1,self.s2)
        print(self.s2,self.s1)
s=strings()
s.put()

Adv python practice/method override/KV RAO  OVERRIDE.py


import bpy
import bmesh
import os

#function for changing the topology of the object by triangulating it
def triangulate_object(obj):
    me = obj.data
    # Get a BMesh representation
    bm = bmesh.new()
    bm.from_mesh(me)

    bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)

    # Finish up, write the bmesh back to the mesh
    bm.to_mesh(me)
    bm.free()

#retrieves the radi for the Envelope based elip
def min_max_axis(object):
     Xs = []
     Ys = []
     Zs = []
     boundaries = []

     coords = [(object.matrix_world * v.co) for v in object.data.vertices]

     for vert in coords:
         Xs.append(vert[0])
         Ys.append(vert[1])
         Zs.append(vert[2])

     Xs.sort()
     Ys.sort()
     Zs.sort()

     boundaries.append(Xs[len(Xs) - 1])
     boundaries.append(Xs[0])
     boundaries.append(Ys[len(Ys) - 1])
     boundaries.append(Ys[0])
     boundaries.append(Zs[len(Zs) - 1])
     boundaries.append(Zs[0])

     E_radi.append((abs(boundaries[0] - boundaries[1]))/2)
     E_radi.append((abs(boundaries[2] - boundaries[3]))/2)
     E_radi.append((abs(boundaries[4] - boundaries[5]))/2)

#create folder and move blend file into it
file = bpy.path.basename(bpy.context.blend_data.filepath)

filename = file.strip('.blend')

mom_folder = '/Users/rileysterman/Desktop/blender objects/pre-pre-animation/'

object_folder = mom_folder + filename

os.makedirs(object_folder)

os.rename(bpy.context.blend_data.filepath, object_folder + '/' + file)

#identify object of interest,create lists of elip radi, and reset its location to the origin, and set the center to be based on mass volume
ob = bpy.data.objects[0]
E_radi = []

ob.location = (0,0,0)
#ob.origin_set(type='ORIGIN_CENTER_OF_VOLUME')

#triangulate the object
triangulate_object(ob)

#export stl file of triangulated object into the object folder
stl_path = object_folder + '/' + filename + '.stl'
bpy.ops.export_mesh.stl(filepath=stl_path)

#export fbx file
fbx_path = object_folder + '/' + filename + '.fbx'
bpy.ops.export_scene.fbx(filepath =fbx_path)

# E_radi
min_max_axis(ob)

#noramlize E_radi
radi_sum = E_radi[0] + E_radi[1] + E_radi[2]
E_radi[0] = E_radi[0] /radi_sum
E_radi[1] = E_radi[1] /radi_sum
E_radi[2] = E_radi[2] /radi_sum

E = open(object_folder +'/'+ 'E' + filename, 'w+')
E.write(str(E_radi[0]) + '~' + str(E_radi[1]) + '~' + str(E_radi[2]))
E.close()


# Incomplete
import os
import random

def game():
    with open("./files/data.txt","r",encoding="UTf-8") as data:
            words = [word for word in data]
            print(words)
            word = random.choice(words)
            random_word = word(words)
            print(random_word)

    with open("./files/game.txt","w",encoding="UTF-8") as file:
        print(words)
        letter = input("Put a letter: ")

def main():
    os.system("cls")
    #Print the game
    game()

if __name__ == "__main__":
    main()