seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
32043962015
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 02:46:22 2019 @author: Michael """ #importing the necessary libraries import os import shutil from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from keras.optimizers import SGD from keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt import numpy as np from imutils import paths from utilities.preprocessing import AspectAwarePreprocessor from utilities.datasets import SimpleDatasetLoader from utilities.nn.cnn import MiniVGGNet #importing the dataset segment = 80 path = r'C:\Users\Michael\Desktop\Data Science\My directory set-up for Computer-Vision\Deep learning for computer vision - Practitioneers bundle\datasets\Flowers17' pl = os.listdir(path) flower_className = ['Daffodil', 'Snowdrop', 'Lily_Valley', 'Bluebell', 'Crocus', 'Iris', 'Tigerlily', 'Tulip', 'Fritillary', 'Sunflower', 'Daisy', 'Colts\'s_Foot', 'Dandelion', 'Cowslip', 'Buttercup', 'Windflower', 'Pansy'] for p in pl: if '.jpg' in p: index = int(p.split("_")[-1].strip(".jpg")) - 1 classname = index // 80 classname = flower_className[classname] os.makedirs(path + '/' + classname, exist_ok=True) shutil.move(path + '/' + p, path + '/' + classname + '/' + p) print("[INFO]") imagePaths = list(paths.list_images(r'C:\Users\Michael\Desktop\Data Science\My directory set-up for Computer-Vision\Deep learning for computer vision - Practitioneers bundle\datasets\Flowers17')) aap = AspectAwarePreprocessor(64,64) sdl = SimpleDatasetLoader(preprocessors=[aap]) (data, labels) = sdl.load(imagePaths, verbose=500) #preprocessing the data data = data.astype("float")/255.0 lb = LabelBinarizer() labels = lb.fit_transform(labels) trainX, testX, trainY, testY = train_test_split(data, labels, random_state=42, test_size=0.25) #building the netwok and applying data augmentaion opt = SGD(lr = 0.05, nesterov=True, momentum = 0.9) aug = ImageDataGenerator(rotation_range = 30, width_shift_range = 0.1, zoom_range = 0.2, height_shift_range = 0.1, shear_range = 0.2, horizontal_flip = True, fill_mode = "nearest") model = MiniVGGNet.build(width = 64, height = 64, depth = 3, classes = len(flower_className)) model.compile(optimizer = opt, loss = "categorical_crossentropy", metrics = ["accuracy"]) H = model.fit_generator(aug.flow(trainX, trainY, batch_size = 32), steps_per_epoch = len(trainX)//32, validation_data = (testX, testY), epochs = 100, verbose = 1) #saving the model model.save("MiniVGGNet on flowers 17 dataset with data augmentation.hdf5") #plotting and evaluating the dataset progress reports plt.style.use("ggplot") plt.figure("MiniVGGNet on flowers 17 with data aumentation") plt.plot(np.arange(0, 100), H.history["acc"], label = "Training accuracy") plt.plot(np.arange(0, 100), H.history["val_acc"], label = "Validation accuracy") plt.title("Training loss and accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.savefig("MiniVGGNet on flowers 17 with data aumentation")
Monarene/CV-Deep-learning-Pracittioner
minivggnet_flower17_data_aug.py
minivggnet_flower17_data_aug.py
py
3,346
python
en
code
0
github-code
6
35525386991
""" Module containing ports and adapters for forward curve suppliers. Contains both the abstract interface and concrete implementation. """ import abc import datetime as dt from typing import Collection from volfitter.adapters.option_metrics_helpers import create_expiry from volfitter.adapters.sample_data_loader import AbstractDataFrameSupplier from volfitter.domain.datamodel import ForwardCurve class AbstractForwardCurveSupplier(abc.ABC): """ Abstract base class for forward curve suppliers. """ @abc.abstractmethod def get_forward_curve( self, datetime: dt.datetime, expiries: Collection[dt.datetime] ) -> ForwardCurve: """ Returns a forward curve. :param datetime: The datetime for which to return a forward curve. :param expiries: The expiries for which to return forward prices. :return: ForwardCurve. """ raise NotImplementedError class OptionMetricsForwardCurveSupplier(AbstractForwardCurveSupplier): """ Constructs a ForwardCurve from a DataFrame containing OptionMetrics data. OptionMetrics is a vendor supplying historical options data. The DataFrame is expected to be in their format. See papers/option_metrics_reference_manual.pdf. """ def __init__(self, dataframe_supplier: AbstractDataFrameSupplier): self.dataframe_supplier = dataframe_supplier def get_forward_curve( self, datetime: dt.datetime, expiries: Collection[dt.datetime] ) -> ForwardCurve: """ Constructs a ForwardCurve from a DataFrame containing OptionMetrics data. :param datetime: The datetime for which to return a forward curve. :param expiries: The expiries for which to return forward prices. :return: ForwardCurve. """ df = self.dataframe_supplier.get_dataframe(datetime) rows = zip( df["expiration"].values, df["AMSettlement"].values, df["ForwardPrice"].values, ) all_forward_prices = { create_expiry(date, am_settlement): forward for (date, am_settlement, forward) in rows } requested_forward_prices = {} for expiry in expiries: if expiry not in all_forward_prices: raise ValueError(f"Missing forward price for {expiry}!") requested_forward_prices[expiry] = all_forward_prices[expiry] return ForwardCurve(datetime, requested_forward_prices)
docadam78/vf_project
src/volfitter/adapters/forward_curve_supplier.py
forward_curve_supplier.py
py
2,503
python
en
code
2
github-code
6
71643512507
import pygame from pygame.sprite import Sprite class Button(Sprite): def __init__(self, ai_settings, screen, msg, position, function_num): super(Button, self).__init__() self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.function_num = function_num # 设置按钮的尺寸和其他属性 self.width, self.height = 160, 50 self.button_color = (230, 230, 230) self.text_color = self.ai_settings.BLACK self.font = pygame.font.SysFont(None, 48) self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.topleft = position # 按钮的标签只需创建一次 self.prep_msg(msg) def prep_msg(self, msg): """ 将msg渲染成图像,并使其在按钮上居中 :param msg: :return: """ self.msg_image = self.font.render(msg, True, self.text_color, self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = self.rect.center def is_over(self): """判断鼠标是否在按钮上""" point_x, point_y = pygame.mouse.get_pos() x, y = self.rect.x, self.rect.y in_x = x < point_x < x + self.width in_y = y < point_y < y + self.height return in_x and in_y def update(self): button_color = self.button_color if self.is_over(): if self.ai_settings.pressed[0] and self.ai_settings.is_upped: button_color = (190, 190, 190) self.ai_settings.mouse_state = self.function_num self.ai_settings.is_upped = False else: button_color = (220, 220, 220) self.screen.fill(button_color, self.rect) self.screen.blit(self.msg_image, self.msg_image_rect) # r1rect = pygame.draw.rect(screen, BLACK, (20, 52.25, 160, 50), 1) # r2rect = pygame.draw.rect(screen, BLACK, (20, 206.75, 160, 50), 1) # r3rect = pygame.draw.rect(screen, BLACK, (20, 361.25, 160, 50), 1) # r4rect = pygame.draw.rect(screen, BLACK, (20, 515.75, 160, 50), 1) # r5rect = pygame.draw.rect(screen, BLACK, (205, 52.25, 160, 50), 1) # r6rect = pygame.draw.rect(screen, BLACK, (205, 206.75, 160, 50), 1) # r7rect = pygame.draw.rect(screen, BLACK, (205, 361.25, 160, 50), 1) # r8rect = pygame.draw.rect(screen, BLACK, (205, 515.75, 160, 50), 1) # # f1 = pygame.freetype.Font('德彪钢笔行书字库.TTF', 36) # f1rect = f1.render_to(screen, (40, 58), "上一层", fgcolor=BLACK, size=40) # f2rect = f1.render_to(screen, (40, 212.5), "下一层", fgcolor=BLACK, size=40) # f3rect = f1.render_to(screen, (57, 367), "删除", fgcolor=BLACK, size=40) # f4rect = f1.render_to(screen, (57, 521.5), "完成", fgcolor=BLACK, size=40) # f5rect = f1.render_to(screen, (225, 58), "长砖块", fgcolor=BLACK, size=40) # f6rect = f1.render_to(screen, (225, 212.5), "短砖块", fgcolor=BLACK, size=40) # f7rect = f1.render_to(screen, (225, 367), "厚砖块", fgcolor=BLACK, size=40) # f8rect = f1.render_to(screen, (225, 521.5), "其他块", fgcolor=BLACK, size=40)
Karllzy/Architect
button.py
button.py
py
3,292
python
en
code
2
github-code
6
25814086176
from selenium.webdriver import Firefox from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException import pytest import time @pytest.mark.needs_server class TestMaxlifeFeature: """ Checks if the maxlife feature is working """ def setup_class(self): """ Setup: Open a mozilla browser, login """ self.browser = Firefox() self.browser.get('http://localhost:5000/') token = self.browser.find_element_by_name("token") password = "foo" # login token.send_keys(password) token.send_keys(Keys.ENTER) time.sleep(.1) try: self.browser.find_element_by_xpath("//input[@value='Logout']") except NoSuchElementException: raise ValueError("Can't login!!! Create a user 'foo' with the permissions" "'read' and 'create' in your PERMISSIONS in the config") def teardown_class(self): """ Tear down: Close the browser """ self.browser.quit() @property def page_body_lowercase(self): return self.browser.find_element_by_tag_name("body").text.lower() def test_unit_input_exists(self): unit_input = self.browser.find_element_by_name("maxlife-unit") assert unit_input is not None value_input = self.browser.find_element_by_name("maxlife-value") assert value_input is not None def fill_form(self): """ Fills test values to the form and submits it :return: tuple(filename, pasted_text) """ filename = "test.txt" text_to_paste = "This is test" paste_input = self.browser.find_element_by_id("formupload") paste_input.send_keys(text_to_paste) filename_input = self.browser.find_element_by_id("filename") filename_input.send_keys(filename) contenttype_input = self.browser.find_element_by_id("contenttype") contenttype_input.send_keys("text/plain") contenttype_input.send_keys(Keys.ENTER) time.sleep(.2) # give some time to render next view return filename, text_to_paste def delete_current_file(self): self.browser.find_element_by_id("del-btn").click() time.sleep(.2) self.browser.find_element_by_class_name("bootbox-accept").click() def test_paste_keep_forever(self): self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='forever']").click() value_input = self.browser.find_element_by_name("maxlife-value") value_input.clear() value_input.send_keys(1) self.fill_form() assert "max lifetime: forever" in self.page_body_lowercase self.delete_current_file() def test_paste_keep_minutes(self): self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='minutes']").click() value_input = self.browser.find_element_by_name("maxlife-value") value_input.clear() value_input.send_keys(1) self.fill_form() assert "max lifetime: forever" not in self.page_body_lowercase self.delete_current_file() def test_filename_gets_displayed(self): filename, _ = self.fill_form() assert filename.lower() in self.page_body_lowercase self.delete_current_file() def test_pasted_text_gets_displayed(self): _, pasted_text = self.fill_form() self.browser.find_element_by_id("inline-btn").click() assert pasted_text.lower() in self.page_body_lowercase self.browser.back() self.delete_current_file() @pytest.mark.slow def test_file_gets_deleted_after_expiry_time(self): self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='minutes']").click() value_input = self.browser.find_element_by_name("maxlife-value") value_input.clear() value_input.send_keys(1) self.fill_form() time.sleep(61) self.browser.find_element_by_id("inline-btn").click() assert "not found" in self.page_body_lowercase
bepasty/bepasty-server
src/bepasty/tests/test_website.py
test_website.py
py
4,149
python
en
code
162
github-code
6
25399032626
import re from csv import reader from colorama import init, Fore # Insert the actual exploits in searchsploit in the database def update_database(exploit_database, mycursor): print(Fore.BLUE + "Updating database...") # Read the CSV to get the basic information with open('/usr/share/exploitdb/files_exploits.csv','r') as read_obj: # Read the CSV and skip the first row (headers) csv_reader = reader(read_obj) next(csv_reader) # Insert each row in the table for row in csv_reader: query = """INSERT IGNORE INTO Exploits (ID, File, Description, Date, Author, Type, Platform, Port, SellerLink, SoftwareLink, Version, Tested, CVE) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ values = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7]) # To get more information about the exploit values = search_content(row[1], values) mycursor.execute(query, values) exploit_database.commit() print(Fore.GREEN + "Database update") # Search the exploit content to find more information about it. def search_content(exploit_path, values): # Add the root path to the exploit path exploit_path = "/usr/share/exploitdb/" + exploit_path # Specific variables to look for within each exploit seller_link = "" software_link = "" version = "" tested = "" CVE = "" # Booleans to control the search isEmptyVendor = True isEmptySoftware = True isEmptyVersion = True isEmptyTested = True isEmptyCVE = True # Open the file to read its content with open(exploit_path, 'r') as exploit: # Get all the lines of the file data = exploit.read().splitlines() # Iterate through them to find the key words and, after cleaning it, store them for line in data: # Search and check the vendor link if isEmptyVendor: if re.search('[Vv]endor [Hh]omepage', line): if (re.split('[Vv]endor [Hh]omepage', line)[1].strip().startswith(':')): seller_link = clean_characters(line,'[Vv]endor [Hh]omepage',':') elif (re.split('[Vv]endor [Hh]omepage', line)[1].strip().startswith('-')): seller_link = clean_characters(line,'[Vv]endor [Hh]omepage','-') elif (re.split('[Vv]endor [Hh]omepage', line)[1].startswith(' ')): seller_link = clean_white(line,'[Vv]endor [Hh]omepage') isEmptyVendor = False elif re.search('[Vv]endor', line): if (re.split('[Vv]endor', line)[1].strip().startswith(':')): seller_link = clean_characters(line,'[Vv]endor',':') elif (re.split('[Vv]endor', line)[1].strip().startswith('-')): seller_link = clean_characters(line,'[Vv]endor','-') elif (re.split('[Vv]endor', line)[1].startswith(' ')): seller_link = clean_white(line,'[Vv]endor') isEmptyVendor = False # Search and check the software link if isEmptySoftware: if re.search('[Ss]oftware [Ll]ink', line): if (re.split('[Ss]oftware [Ll]ink', line)[1].strip().startswith(':')): software_link = clean_characters(line,'[Ss]oftware [Ll]ink',':') elif (re.split('[Ss]oftware [Ll]ink', line)[1].strip().startswith('-')): software_link = clean_characters(line,'[Ss]oftware [Ll]ink','-') elif (re.split('[Ss]oftware [Ll]ink', line)[1].startswith(' ')): software_link = clean_white(line,'[Ss]oftware [Ll]ink') isEmptySoftware = False elif re.search('[Pp]roduct [Ww]eb [Pp]age', line): if (re.split('[Pp]roduct [Ww]eb [Pp]age', line)[1].strip().startswith(':')): software_link = clean_characters(line,'[Pp]roduct [Ww]eb [Pp]age',':') elif (re.split('[Pp]roduct [Ww]eb [Pp]age', line)[1].strip().startswith('-')): software_link = clean_characters(line,'[Pp]roduct [Ww]eb [Pp]age','-') elif (re.split('[Pp]roduct [Ww]eb [Pp]age', line)[1].startswith(' ')): software_link = clean_white(line,'[Pp]roduct [Ww]eb [Pp]age') isEmptySoftware = False # Search and check the affected version if isEmptyVersion: if re.search('[Vv]ersion', line): if (re.split('[Vv]ersion', line)[1].strip().startswith(':')): version = clean_characters(line,'[Vv]ersion',':') elif (re.split('[Vv]ersion', line)[1].strip().startswith('-')): version = clean_characters(line,'[Vv]ersion','-') elif (re.split('[Vv]ersion', line)[1].startswith(' ')): version = clean_white(line,'[Vv]ersion') isEmptyVersion = False # Search and check where it has been tested if isEmptyTested: if re.search('[Tt]ested [Oo]n', line): if (re.split('[Tt]ested [Oo]n', line)[1].strip().startswith(':')): tested = clean_characters(line,'[Tt]ested [Oo]n',':') elif (re.split('[Tt]ested [Oo]n', line)[1].strip().startswith('-')): tested = clean_characters(line,'[Tt]ested [Oo]n','-') elif (re.split('[Tt]ested [Oo]n', line)[1].startswith(' ')): tested = clean_white(line,'[Tt]ested [Oo]n') isEmptyTested = False # Search and check the CVE if isEmptyCVE: if line.__contains__('CVE ID'): if (line.partition('CVE ID')[2].strip().startswith(':')): CVE = clean_characters(line,'CVE ID',':') elif (line.partition('CVE ID')[2].strip().startswith('-')): CVE = clean_characters(line,'CVE ID','-') elif (line.partition('CVE ID')[2].startswith(' ')): CVE = clean_white(line,'CVE ID') isEmptyCVE = False elif line.__contains__('CVE'): if (line.partition('CVE')[2].strip().startswith(':')): CVE = clean_characters(line,'CVE',':') elif (line.partition('CVE')[2].strip().startswith('-')): CVE = clean_characters(line,'CVE','-') elif (line.partition('CVE')[2].startswith(' ')): CVE = clean_white(line,'CVE') isEmptyCVE = False # Add the new values to the values tuple values = values + (seller_link,) values = values + (software_link,) values = values + (version,) values = values + (tested,) values = values + (CVE,) return values # Clean with characters def clean_characters(line, word, character): if (word == 'CVE' or word == 'CVE ID'): return line.partition(word)[2].split(character,1)[1].translate({ord(i): None for i in '[]'}).strip() else: return re.split(word, line)[1].split(character,1)[1].translate({ord(i): None for i in '[]'}).strip() # Clean with white space def clean_white(line, word): if (word == 'CVE' or word == 'CVE ID'): return line.partition(word)[2].translate({ord(i): None for i in '[]'}).strip() else: return re.split(word, line)[1].translate({ord(i): None for i in '[]'}).strip()
alvaroreinaa/Can-You-EXPLOIT-It
update_database.py
update_database.py
py
7,870
python
en
code
1
github-code
6
27127443756
""" 基于Memoization的递归可以大大提升性能,此时可以自定义一个memorize修饰器 author:Andy """ import functools def memorize(fn): # 缓存字典 know = dict() # 为创建修饰器提供便利,保留被修饰函数的__name__和__doc__属性 @functools.wraps(fn) def memoizer(*args): # 如果缓存字典中已经存在 if args in know: return know[args] # 如果缓存字典中不存在 else: know[args] = fn(*args) return know[args] return memoizer @memorize # 返回前n个数的和 def nsum(n): assert (n >= 0), "n must be >=0" return n if n == 0 else n + nsum(n - 1) @memorize # 返回斐波那契数列的第n个数 def fib(n): assert (n >= 0), "n must be >=0" return n if n in (0, 1) else fib(n - 1) + fib(n - 2) if __name__ == '__main__': from timeit import Timer measures = [ {"exec": "fib(100)", "import": "fib", "func": fib}, {"exec": "nsum(100)", "import": "nsum", "func": nsum}, ] for item in measures: t = Timer( item["exec"], "from __main__ import {}".format(item["import"]) ) print("name: {}, doc: {}, executing: {}, time:{}". \ format(item["func"].__name__, item["func"].__doc__, item["exec"], t.timeit()))
LiUzHiAn/pythonDesignPatterns
decorate_pattern/my_math.py
my_math.py
py
1,213
python
en
code
0
github-code
6
24993603901
from osv import fields from osv import osv class dm_matchcode(osv.osv): _name = 'dm.matchcode' _description = 'Matchcodes for DM' _columns = { 'name': fields.char('Name', size=64, required=True), 'matchexp': fields.char('Match Expression', size=128, help="""This string defines \ the matchcode expression used to compute the matchcode of a \ customer (partner address). The expression must be a pair of \ key:value separated by a coma. Example : firstname:7, lastname:1, \ street1:-3, city:4, zip:3. A minus sign means that x last characters of the string"""), 'country_id': fields.many2one('res.country', 'Country') } dm_matchcode() class res_partner_address(osv.osv): _inherit = 'res.partner.address' _columns = { 'id': fields.integer('ID', readonly=True), 'firstname': fields.char('First Name', size=64), 'name_complement': fields.char('Name Complement', size=64), 'street3': fields.char('Street3', size=128), 'street4': fields.char('Street4', size=128), 'moved': fields.boolean('Moved'), 'quotation': fields.float('Quotation', digits=(16,2)), 'origin_partner': fields.char('Origin Partner', size=64), 'origin_support': fields.char('Origin Support', size=64), 'origin_keyword': fields.char('Origin Keyword', size=64), 'origin_campaign_id': fields.many2one('dm.campaign', 'Origin Campaign'), 'origin_country_id': fields.many2one('res.country', 'Origin Country'), 'date_birth': fields.datetime('Date of Birth'), 'matchcode_id': fields.many2one('dm.matchcode', 'Matchcode') } res_partner_address() #vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
factorlibre/openerp-extra-6.1
dm_partner_address/dm_partner_address.py
dm_partner_address.py
py
1,845
python
en
code
9
github-code
6
2615744068
# topics = ["Таѕ"] from typing import List class Solution: def simplifyPath(self, path: str) -> str: st: List[str] = [] for s in path.split('/'): if not s or s == '.': continue if s == '..': if st: st.pop() else: st.append(s) return f'/{"/".join(st)}'
show-me-code/signInHelper-using-face-
algorithms/[71]简化路径/solution.py
solution.py
py
389
python
en
code
0
github-code
6
20299042800
"""crud URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from .views import create_view,list_view,create_view_curso,delete_view_estudiante,delete_view_curso,update_view_estudiante,update_view_curso urlpatterns = [ path('admin/', admin.site.urls), path('estudiante/', create_view,name = 'estudiante'), path('curso/', create_view_curso,name = 'curso'), path('lista/', list_view,name = 'lista'), path('delete_estudiante/<int:int>', delete_view_estudiante,name = 'delete_view_estudiante' ), path('delete_curso/<int:int>', delete_view_curso,name = 'delete_view_curso' ), path('update_estudiante/<int:int>', update_view_estudiante,name = 'update_view_estudiante' ), path('update_curso/<int:int>', update_view_curso,name = 'update_view_curso' ) ]
JairoObregon/django
crud/urls.py
urls.py
py
1,405
python
en
code
0
github-code
6
19167047686
""" A part is a component of the overall derp system that communicates with other parts """ from derp.util import TOPICS, MSG_STEM, init_logger, subscriber, publisher, get_timestamp class Part: """ The root class for every part, includes a bunch of useful functions and cleanup """ def __init__(self, config, name, sub_names, init_pubsub=True): """ By default every part is its own publisher and subscribes to one/many messages """ self._name = name self._sub_names = sub_names self._config = config[name] self._global_config = config self._logger = init_logger(name, config['recording_path']) self._logger.info("__init__") self._messages = {topic: TOPICS[topic].new_message() for topic in TOPICS} self._sub_context, self._subscriber = None, None self._pub_context, self._publisher = None, None self._is_pubsub_initialized = False self._timestamp = 0 if init_pubsub: self.init_pubsub() def __del__(self): """ Clean up the pub/sub system """ self._logger.info("__del__") if self._subscriber: self._subscriber.close() if self._sub_context: self._sub_context.term() if self._publisher: self._publisher.close() if self._pub_context: self._pub_context.term() def init_pubsub(self): sub_paths = [MSG_STEM + name for name in self._sub_names] self._sub_context, self._subscriber = subscriber(sub_paths) self._pub_context, self._publisher = publisher(MSG_STEM + self._name) self._is_pubsub_initialized = True def __repr__(self): return self.__class__.__name__.lower() def __str__(self): return repr(self) def run(self): assert True def subscribe(self): if not self._is_pubsub_initialized: return None topic_bytes, message_bytes = self._subscriber.recv_multipart() self._timestamp = get_timestamp() topic = topic_bytes.decode() self._messages[topic] = TOPICS[topic].from_bytes(message_bytes).as_builder() return topic def publish(self, topic, **kwargs): if not self._is_pubsub_initialized: return None message = TOPICS[topic].new_message( createNS=self._timestamp, publishNS=get_timestamp(), **kwargs ) self._publisher.send_multipart([str.encode(topic), message.to_bytes()]) return message
notkarol/derplearning
derp/part.py
part.py
py
2,517
python
en
code
40
github-code
6
26632895276
import pygame from setting import * from bullet import Bullet class Player(pygame.sprite.Sprite): #初期化(元グループ、初期位置x、初期位置y) def __init__(self, groups, x, y, enemy_group): super().__init__(groups) #敵グループ self.enemy_group = enemy_group #画面取得 self.screen = pygame.display.get_surface() #画像取得 self.image_list = [] for i in range(3): #tmp_image = pygame.image.load(f'assets/img/player/{i}.png') tmp_image = pygame.image.load(player_image_path + str(i) + image_extension) self.image_list.append(tmp_image) #画像設定 #self.image = pygame.Surface((50,50)) #self.image.fill(COLOR_RED) self.image_index = player_image_index_straight self.update_image() #自機を載せる台車 self.rect = self.image.get_rect(center = (x,y)) #移動方向初期化 self.direction = pygame.math.Vector2() #移動速度取得 self.speed = player_speed #体力 self.health = player_health self.alive = True #効果音 self.shot_sound = pygame.mixer.Sound(shot_se_path) self.shot_sound.set_volume(se_volume) #弾グループ設定 self.bullet_group = pygame.sprite.Group() #弾発射中 self.fire = False self.cooldown_timer = 0 ##表示の更新 def update(self): self.input() self.move() self.update_image() #print(str(self.direction) + "-" + str(self.rect)) #弾描画 self.bullet_cooldown() self.bullet_group.draw(self.screen) self.bullet_group.update() #体力 self.collision_enemy() self.check_alive() #デバッグ用 #print('b:' + str(self.bullet_group)) #入力キー取得 def input(self): key = pygame.key.get_pressed() #上下キー if key[pygame.K_UP]: self.direction.y = -1 elif key[pygame.K_DOWN]: self.direction.y = 1 else: self.direction.y = 0 #左右キー if key[pygame.K_LEFT]: self.direction.x = -1 self.image_index = player_image_index_left elif key[pygame.K_RIGHT]: self.direction.x = 1 self.image_index = player_image_index_right else: self.direction.x = 0 self.image_index = player_image_index_straight #zキー(弾発射) if key[pygame.K_z] and not self.fire: bullet = Bullet(self.bullet_group, self.rect.centerx, self.rect.top) self.fire = True self.shot_sound.play() #移動処理 def move(self): #画面端チェック(画面端での移動速度修正) self.check_edge_screen() #移動速度の平準化 if self.direction.magnitude() != 0: self.direction = self.direction.normalize() #X座標移動 self.rect.x += self.direction.x * self.speed self.check_off_screen("x") #y座標移動 self.rect.y += self.direction.y * self.speed self.check_off_screen("y") #画面端チェック #画面端でキーが押されたらそちらの方向への移動を0に def check_edge_screen(self): if self.rect.left <= 0 and self.direction.x < 0: self.direction.x = 0 if self.rect.right >= screen_width and self.direction.x > 0: self.direction.x = 0 if self.rect.top <= 0 and self.direction.y < 0: self.direction.y = 0 if self.rect.bottom >= screen_height and self.direction.y > 0: self.direction.y = 0 #画面外チェック #画面外に出そうな場合は座標を修正(画面端チェックだけでは微妙にはみ出すため残す) def check_off_screen(self, vector): if vector == "x": if self.rect.left < 0: self.rect.left = 0 if self.rect.right > screen_width: self.rect.right = screen_width if vector == "y": if self.rect.top < 0: self.rect.top = 0 if self.rect.bottom > screen_height: self.rect.bottom = screen_height #TODO:画面端で斜め移動しようとしたとき、x成分y成分の移動速度は斜め移動の値のままのため、遅くなっている。 #画像の更新 def update_image(self): self.pre_image = self.image_list[int(self.image_index)] self.image = pygame.transform.scale(self.pre_image, player_image_size) #弾クールダウン処理 def bullet_cooldown(self): if self.fire: self.cooldown_timer += 1 if self.cooldown_timer > bullet_cooldown_time: self.fire = False self.cooldown_timer = 0 #敵との当たり判定 def collision_enemy(self): for enemy in self.enemy_group: if self.rect.colliderect(enemy.rect) and enemy.alive: self.health -= enemy_power self.check_health() def check_health(self): if self.health <= 0: self.alive = False #生存確認 def check_alive(self): if not self.alive: self.kill()
shu0411/training
python/trainingEnv/shooting/player.py
player.py
py
5,639
python
ja
code
0
github-code
6
29579733720
# -*- coding: utf-8 -*- """ Created on Fri Dec 7 15:39:51 2018 @author: Akitaka """ import numpy as np from sklearn.model_selection import cross_val_score from lwpls import LWPLS def psi(xlist,M): """ make a design matrix """ ret = [] for x in xlist: ret.append([x**i for i in range(0,M+1)]) return np.array(ret) np.random.seed(1) """ Data """ N = 10 M = 15 xlist = np.linspace(0, 1, N) ylist = np.sin(2 * np.pi * xlist) + np.random.normal(0, 0.2, xlist.size) X = psi(xlist,M) y = ylist """ Cross validation""" reg = LWPLS(n_components=2) reg.fit(X,y) y_pred = reg.predict(X) scores = cross_val_score(reg, X, y, cv=5, scoring='neg_mean_squared_error') print(scores.mean())
nakanishi-akitaka/python2018_backup
1207/cross_validation_lwpls.py
cross_validation_lwpls.py
py
740
python
en
code
5
github-code
6
8829027988
######################################################## # Rodrigo Leite - drigols # # Last update: 21/09/2021 # ######################################################## def OLS(dic): from matplotlib import pyplot as plt import pandas as pd df = pd.DataFrame(dic) df['(x_i - x_mean)'] = df['Grade'] - df['Grade'].mean() df['(y_i - y_mean)'] = df['Salary'] - df['Salary'].mean() df['(x_i - x_mean)(y_i - y_mean)'] = df['(x_i - x_mean)'] * df['(y_i - y_mean)'] df['(x_i - x_mean)^2'] = (df['Grade'] - df['Grade'].mean())**2 m = (sum(df['(x_i - x_mean)'] * df['(y_i - y_mean)'])) / sum(df['(x_i - x_mean)^2']) b = df['Salary'].mean() - (m * df['Grade'].mean()) print("Angular Coefficient (m): {0}\nLinear Coefficient (b): {1}".format(round(m), round(b))) regression_line = [(m*x) + b for x in df['Grade']] plt.figure(figsize=(10, 7)) plt.scatter(df.Grade, df.Salary, color='g') plt.plot(df.Grade, regression_line, color='b') plt.title('Grades vs Salaries | Ordinary Least Squares: OLS') plt.xlabel('Grade') plt.ylabel('Salary') plt.grid() plt.savefig('../images/plot-02.png', format='png') plt.show() if __name__ =="__main__": students_dic = { 'Grade':[50, 50, 46, 95, 50, 5, 57, 42, 26, 72, 78, 60, 40, 17, 85], 'Salary':[50000, 54000, 50000, 189000, 55000, 40000, 59000, 42000, 47000, 78000, 119000, 95000, 49000, 29000, 130000] } OLS(students_dic)
drigols/studies
modules/ai-codes/modules/linear-regression/src/students_ols_bestLineFit.py
students_ols_bestLineFit.py
py
1,511
python
en
code
0
github-code
6
70633246909
#c1 dung for print("cach 1 dung for") try: a,b=map(int, input().split()) except: print("dau vao ko hop le") tong=0 for i in range(a,b+1): tong+=i print("tong:{}".format(tong)) #c2 dung while print("cach 2 dung while") try: a,b=map(int, input().split()) except: print("dau vao ko hop le") tong=0 i=a while(i<=b): tong+=i i+=1 print("tong:{}".format(tong))
Clapboiz/Python-basics
tongcacsotrongdoanab.py
tongcacsotrongdoanab.py
py
383
python
en
code
0
github-code
6
25844066272
"""Test Role""" import unittest import json from flask import url_for from app.test import BaseTest class RolePermissionTests(BaseTest): """ Role Permission Test api class """ def test_insert_update_delete(self): """ insert, update, delete roles permission""" role_url = url_for('auth.role_role_list') prm = { 'name': 'role_test', 'active': True, } role_data = json.dumps(prm) response = self.client.post( role_url, data=role_data, content_type='application/json' ) role_id = response.json['data']['id'] permission_url = url_for('auth.permission_permission_list') prm = { 'code': 'permission_test', 'name': 'permission_test', 'active': True } permission_data = json.dumps(prm) response = self.client.post( permission_url, data=permission_data, content_type='application/json' ) permission_id = response.json['data']['id'] # insert role permission params = {"role_id": role_id, "permission_id": permission_id, "status": "false", } role_permission = json.dumps(params) url = url_for('auth.role-permission_role_permission_list') response = self.client.post( url, data=role_permission, content_type='application/json' ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json['data']['permission_id'], permission_id) # update role permission params = { "status": "true", } role_permission = json.dumps(params) url = url_for('auth.role-permission_role_permission_detail', uuid=response.json['data']['id']) response = self.client.put( url, data=role_permission, content_type='application/json' ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json['data']['status'], True) # check readonly fields value changing created_at = response.json['data']['created_at'] updated_at = response.json['data']['updated_at'] self.assertIsNotNone(updated_at) self.assertNotEqual(created_at, updated_at) url = url_for('auth.role-permission_role_permission_list') response = self.client.get(url, content_type='application/json' ) self.assertEqual(response.status_code, 200) self.assertGreaterEqual(len(response.json['data']), 1) if __name__ == "__main__": unittest.main()
ekramulmostafa/ms-auth
app/test/test_role_permission.py
test_role_permission.py
py
2,795
python
en
code
0
github-code
6
40341366552
import os import re import selenium from selenium import webdriver from time import sleep from openpyxl import load_workbook from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait # Required for explicit wait from selenium.webdriver.support import expected_conditions as ec # Required for explicit wait from selenium.webdriver.common.by import By # Required for explicit wait from selenium.webdriver.common.desired_capabilities import DesiredCapabilities excel_file = 'token_generation_automation.xlsx' driver_exe = 'chromedriver.exe' wb = load_workbook(filename = os.path.join(os.getcwd(),excel_file), read_only = False) sheet = wb.sheetnames ws1 = wb[sheet[2]] max_consumers = ws1.max_row ######################################################## ######################################################## indent = 0 #Last valid iteration; Must check before each run ######################################################## ######################################################## print(max_consumers-indent) browser = webdriver.Chrome(executable_path = os.path.join(os.getcwd(), driver_exe)) browser.get("http://172.16.15.18/prepay/login!init.do") browser.implicitly_wait(100) #implicit wait browser.maximize_window() x1 = browser.find_element_by_id("czyId") x1.send_keys("ChandpurAE1") x2 = browser.find_element_by_id("pwd") x2.send_keys("C6_029_Prepaid") x3 = browser.find_element_by_xpath("//input[@type='button']") x3.click() print('Hello') sleep(5) for x in range(max_consumers-indent): browser.implicitly_wait(100) browser.get('http://172.16.15.18/prepay/prepay/mgtCode/codeMgt!ctc.do?timestamp=NaN&menuid=63100&menupath=Clear%20Tamper%20Status&curTabId=63100') browser.implicitly_wait(100) generateBtn = browser.find_elements_by_class_name('ext_btn')[0] selectBtn = browser.find_element_by_xpath('/html/body/table/tbody/tr/td[2]/form/table/tbody/tr[2]/td[2]/select') selectOptn = browser.find_element_by_xpath('/html/body/table/tbody/tr/td[2]/form/table/tbody/tr[2]/td[2]/select/option[2]') browser.switch_to.frame(browser.find_element_by_id('accountQueryIframe')) browser.implicitly_wait(100) meterNo = ws1.cell(row = indent+1+x, column = 1).value print("Meter No: ", meterNo) browser.find_element(By.ID, "metNo").send_keys(meterNo) # print('1') browser.find_elements_by_class_name('ext_btn')[0].click() browser.implicitly_wait(100) # print('2') browser.switch_to_default_content() sleep(2) selectOptn.click() browser.implicitly_wait(100) selectBtn.click() browser.implicitly_wait(100) generateBtn.click() browser.implicitly_wait(100) browser.find_element_by_xpath('/html/body/div[7]/div[2]/div[2]/div/div/div/div[1]/table/tbody/tr/td[1]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]/em/button').click() sleep(2) browser.switch_to.frame(browser.find_element_by_id('openwin')) serial = browser.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/table/tbody/tr[14]').text print("Token: ", serial) sequence = browser.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/table/tbody/tr[11]').text print("Sequence: ", sequence[10:len(sequence)]) ws1.cell(row = indent+1+x, column = 3).value = sequence[10:len(sequence)] ws1.cell(row = indent+1+x, column = 4).value = serial ws1.cell(row = indent+1+x, column = 5).value = 'Done' wb.save(os.path.join(os.getcwd(),excel_file)) print('Ends : ', x+1) browser.close()
Himu1234/web-automation-chandpur
prepaid_token_generation_xlsx.py
prepaid_token_generation_xlsx.py
py
3,524
python
en
code
0
github-code
6
130536507
import numpy as np import matplotlib.pyplot as plt import pyRaven as rav import emcee import corner from scipy.stats import norm import scipy from statistics import mode def fitdata(param,DataPacket,guess): ''' This function fits a set of LSD profiles using scipy's curve fit function. Inputs: param - input parameter dictionary DataPacket - input DataPacket with real data guess - array of guess values for kappa, vsini, and vmac. Ex: np.array([1.3,250,30]) Outputs: parameters - array of fit parameters covariance - covariance matrix of the fit modelout - the best fit model ''' def model(v,kappa,vsini,vmac): ''' This function creates the line profile model that will be fit to the observed profile Inputs: kappa - value of kappa that the walker is on in parameter space vsini - value of vsini that the walker is on in parameter space v - velocity array of the actual data Outputs: f - line profile model using the weak field method at the walker's position in parameter space ''' param['general']['vsini']=vsini param['general']['vmac']=vmac param['general']['logkappa']=np.log(kappa) #pyRaven's weakfield disk integration function model=rav.diskint2.analytical(param,False) #interpolating the model to be size MCMC wants f=np.interp(v,model['vel'],model['flux']) return(f) x=DataPacket.scaled.lsds[0].vel#+DataPacket.vrad[0] y=DataPacket.scaled.lsds[0].specI if DataPacket.nobs!=1: for i in range(1,DataPacket.nobs): x=np.append(x,DataPacket.scaled.lsds[i].vel)#+DataPacket.vrad[i]) y=np.append(y,DataPacket.scaled.lsds[i].specI) parameters,covariance = scipy.optimize.curve_fit(model,x,y,guess) modelout=model(x,parameters[0],parameters[1],parameters[2]) modelout=modelout[:DataPacket.scaled.lsds[0].vel.size] return parameters,covariance,modelout def fitdataMCMC(param,DataPacket,nsteps,guess): ''' This function fits the LSD profile using MCMC Inputs: param - input parameter dictionary DataPacket - input DataPacket with real data nsteps - number of steps to run MCMC guess - array of guess values for kappa, vsini, and vmac. Ex: np.array([1.3,250,30]) Outputs: kappa - The average fitted value of kappa vsini - The average fitted value of vsini vmac - The average fitted value of vmac ''' #def model(v,c,a,b,Ic): # return(-c*np.exp(-0.5*np.power(v-a,2)/b**2)+Ic) def model(v,kappa,vsini,vmac): ''' This function creates the line profile model that will be fit to the observed profile Inputs: kappa - value of kappa that the walker is on in parameter space vsini - value of vsini that the walker is on in parameter space vmac - value of the vmac that the walker is on in parameter space v - velocity array of the actual data Outputs: f - line profile model using the weak field method at the walker's position in parameter space ''' param['general']['vsini']=vsini param['general']['vmac']=vmac param['general']['logkappa']=np.log(kappa) #pyRaven's weakfield disk integration function model=rav.diskint2.analytical(param,False) #interpolating the model to be size MCMC wants f=np.interp(v,model['vel'],model['flux']) return(f) def lnprior(params): ''' This function is used to set constraints on the parameter space the walkers are allowed in. I did this to try and save time, could probably use some tweaking. Inputs: params - list of walker parameters, in this code that is [kappa, vsini] Outputs: -infinity - if kappa and/or vsini are out of the specified ranges 0 - otherwise ''' kappa,vsini,vmac=params if kappa<=0.0 or kappa>=10.0 or vsini >= 500.0 or vsini<=0.0 or vmac<=0.0 or vmac>=100.0: return(-np.inf) else: return(0.0) def lnlike(params,v,I,Ierr): ''' Inputs: params -list of walker parameters, in this code that is [kappa, vsini] v - velocity array of the data I - stokes I of the actual data Ierr - uncertainty in the stokes I of the actual data Outputs: The log likelihood using a gaussian function ''' kappa,vsini,vmac= params m = model(v,kappa,vsini,vmac) sigma2 = Ierr**2 #+m**2*np.exp(2*log_f) return(-0.5 * np.sum((I - m) ** 2 / sigma2 + np.log(sigma2))) def lnprob(params,v,I,Ierr): ''' Inputs: params - list of walker parameters, in this code that is [kappa, vsini] v - velocity array of the data I - stokes I of the actual data Ierr - uncertainty in the stokes I of the actual data Outputs: log probability. Used to determine how good a fit the model is ''' prior=lnprior(params) if not np.isfinite(prior): return(-np.inf) else: return(prior+lnlike(params,v,I,Ierr)) # Set up the convergence diagonstic plots. At the final step we want all the walkers to be very close together, i.e a straight line at the end. fig, ax = plt.subplots(3,1,figsize=(15,5)) ax[0].set_title('Convergence Diagnostic Plots') fig1, ax1 = plt.subplots(1,1,figsize=(5,5)) #sets up the send set of plots #for i in range(1): kappa=np.array([]) #log_f=np.array([]) vsini=np.array([]) vmac=np.array([]) Ic=1.0 #defining the continuum value of the real data vsiniin=DataPacket.vsini #defining the vsini listed in the data packet v=DataPacket.scaled.lsds[0].vel#+DataPacket.vrad[0] #defining the velocity array of the data I=DataPacket.scaled.lsds[0].specI #defining the stokes I array of the data Ierr=DataPacket.scaled.lsds[0].specSigI #defining the stokes I error of the data for i in range(1,DataPacket.nobs): v=np.append(v,DataPacket.scaled.lsds[i].vel)#+DataPacket.vrad[i] #defining the velocity array of the data I=np.append(I,DataPacket.scaled.lsds[i].specI) #defining the stokes I array of the data Ierr=np.append(Ierr,DataPacket.scaled.lsds[i].specSigI) #defining the stokes I error of the data ndim = 3 #number of parameters to fit nwalkers= 10 * ndim #number of walkers (10/parameter) pguess = guess #initial guess for kappa and vsini positions = np.zeros((nwalkers,ndim)) #set up walker position array positions[:,0] = np.abs(np.random.randn(nwalkers)*pguess[0]*0.1+pguess[0]) #set the inital positions of the kappa walkers to be a random distribution around the guess positions[:,1] = np.random.randn(nwalkers)*pguess[1]*0.1+pguess[1] #set the initial positions of the vsini walkers positions[:,2] = np.random.randn(nwalkers)*pguess[2]*2 sampler = emcee.EnsembleSampler(nwalkers,ndim,lnprob,args=(v,I,Ierr)) #set up MCMC. Note that the args keyword contains the real data arrays pos,prob,state = sampler.run_mcmc(positions, nsteps,progress=True) #runs MCMC for the specified number of steps #make the first set of plots res = [ax[j].plot(sampler.chain[:,:,j].T, '-', color='k', alpha=0.3) for j in range(3)] res = [ax[j].axhline(pguess[j]) for j in range(3)] #save the walker positions at each step (for diagnostics) #kappa=np.append(kappa,np.mean(sampler.flatchain[int(2*nsteps/3):], axis=0)[0]) #vsini=np.append(vsini,np.mean(sampler.flatchain[int(2*nsteps/3):], axis=0)[1]) #vmac=np.append(vmac,np.mean(sampler.flatchain[int(2*nsteps/3):], axis=0)[2]) kappa=sampler.flatchain[int(2*100/3):][:,0] vsini=sampler.flatchain[int(2*100/3):][:,1] vmac=sampler.flatchain[int(2*100/3):][:,2] bins=20 bin_means = (np.histogram(kappa, bins, weights=kappa)[0]/np.histogram(kappa, bins)[0]) kappa=bin_means[np.histogram(kappa, bins)[0]==np.histogram(kappa, bins)[0].max()][0] bin_means = (np.histogram(vsini, bins, weights=vsini)[0]/np.histogram(vsini, bins)[0]) vsini=bin_means[np.histogram(vsini, bins)[0]==np.histogram(vsini, bins)[0].max()][0] bin_means = (np.histogram(vmac, bins, weights=vmac)[0]/np.histogram(vmac, bins)[0]) vmac=bin_means[np.histogram(vmac, bins)[0]==np.histogram(vmac, bins)[0].max()][0] #log_f=np.append(log_f,np.mean(sampler.flatchain, axis=0)[1]) #make the second set of plots ax1.plot(DataPacket.scaled.lsds[0].vel,model(DataPacket.scaled.lsds[0].vel, kappa,vsini,vmac)) ax1.plot(v,I) print('kappa: {} | vsini: {} | vmac: {}'.format(kappa,vsini,vmac)) #make the corner plots flat_samples = sampler.get_chain(discard=0, thin=5, flat=True) labels = ["kappa","vsini",'vmac'] corner.corner( flat_samples, labels=labels) return(kappa,vsini,vmac,sampler.flatchain) def fitdata_novsini(param,DataPacket,guess): ''' This function fits a set of LSD profiles using scipy's curve fit function. Inputs: param - input parameter dictionary DataPacket - input DataPacket with real data guess - array of guess values for kappa and vmac. Ex: np.array([1.3,30]) Outputs: parameters - array of fit parameters covariance - covariance matrix of the fit modelout - the best fit model ''' def model(v,kappa,vmac): ''' This function creates the line profile model that will be fit to the observed profile Inputs: kappa - value of kappa that the walker is on in parameter space vmac - value of vmac that the walker is on in parameter space v - velocity array of the actual data Outputs: f - line profile model using the weak field method at the walker's position in parameter space ''' param['general']['vmac']=vmac param['general']['logkappa']=np.log(kappa) #pyRaven's weakfield disk integration function model=rav.diskint2.analytical(param,False) #interpolating the model to be size MCMC wants f=np.interp(v,model['vel'],model['flux']) return(f) param['general']['vsini']=DataPacket.vsini x=DataPacket.scaled.lsds[0].vel#+DataPacket.vrad[0] y=DataPacket.scaled.lsds[0].specI if DataPacket.nobs!=1: for i in range(1,DataPacket.nobs): x=np.append(x,DataPacket.scaled.lsds[i].vel)#+DataPacket.vrad[i]) y=np.append(y,DataPacket.scaled.lsds[i].specI) parameters,covariance = scipy.optimize.curve_fit(model,x,y,guess) modelout=model(x,parameters[0],parameters[1]) modelout=modelout[:DataPacket.scaled.lsds[0].vel.size] return parameters,covariance,modelout
veropetit/pyRaven
fitparams.py
fitparams.py
py
10,372
python
en
code
0
github-code
6
23947460253
from game_object.base_object import BaseObject, Wall, Life import random class FactoryMethod: def __init__(self, health=1000, position=None, velocity=None, acceleration=None, size=None, control=None) -> None: self.health = health self.position = position or [0, 0] self.velocity = velocity or [0, 0] self.acceleration = acceleration or [0, 0] self.size = size or 100 self.control = control super().__init__() def create_object(self): return BaseObject() class WallFactory(FactoryMethod): def __init__(self, health=1000, position=[0, 0], velocity=[0, 0], acceleration=[0, 0], size=[100, 100], control=None) -> None: super().__init__(health, position, velocity, acceleration, size, control) self.counter = 0 def create_object(self): position = self.position.copy() max_val = 9 if self.counter < max_val: position = [self.position[0], self.position[1] + self.size * self.counter] elif self.counter < max_val * 2: position = [self.position[0] + self.size * (self.counter - max_val), self.position[1] + self.size * max_val] elif self.counter < max_val * 3: position = [self.position[0] + self.size * max_val, self.position[1] + self.size * (max_val - (self.counter - 2 * max_val))] size = self.size # if self.counter % 4 != 0 else self.size / 1.5 velocity = self.velocity # if self.counter % 4 != 0 else [0, -0.1] wall = Wall(health=self.health, position=position, velocity=velocity, acceleration=self.acceleration, size=size, control=self.control) self.counter += 1 return wall class LifeFactory(FactoryMethod): def create_object(self): position = [random.randint(0, 1600), random.randint(0, 1000)] if self.position == [0, 0] else self.position return Life(health=self.health, position=position, velocity=self.velocity, acceleration=self.acceleration, size=self.size, control=self.control)
NoOneZero/wall_game
game_object/factory.py
factory.py
py
2,244
python
en
code
1
github-code
6
41957074771
import json import os j = None searchables = {} path = os.path.dirname(os.path.abspath(__file__)) with open (os.path.join(path, 'fhir_parser/downloads/search-parameters.json'), 'r') as f: j = json.loads(f.read()) for entry in j['entry']: resource = entry['resource'] for base in resource['base']: searchables[base] = searchables.get(base, []) + [resource['name']] import pprint pprint.pprint(searchables)
zensoup/fhirbug
tools/get_searchables.py
get_searchables.py
py
420
python
en
code
14
github-code
6
42060446091
import pygame as pg from settings import * class Bullet(pg.sprite.Sprite): def __init__(self, groups): self.groups = groups pg.sprite.Sprite.__init__(self, self.groups) class PlayerBullet(Bullet): def __init__(self, game, x, y): self.game = game self.groups = self.game.sprites, self.game.bullets, self.game.player_bullets Bullet.__init__(self, self.groups) self.image = self.game.spritesheet.get_image(60, 0, 4, 16, GREEN) self.rect = self.image.get_rect(center=(x, y + PLAYER_BULLET_HEIGHT)) self.mask = pg.mask.from_surface(self.image) def update(self): if self.rect.top - 4 < TOP_SPACING: self.kill() self.rect.y -= PLAYER_BULLET_SPEED class MobBullet(Bullet): def __init__(self, game, x, y): self.game = game self.groups = self.game.sprites, self.game.bullets, self.game.mob_bullets Bullet.__init__(self, self.groups) self.load_images() self.last_updated = pg.time.get_ticks() self.frame = 0 self.image = self.frames[0] self.rect = self.image.get_rect(midbottom=(x, y + MOB_BULLET_HEIGHT)) def load_images(self): self.frames = [ self.game.spritesheet.get_image(64, 224, 12, 28, WHITE), self.game.spritesheet.get_image(76, 224, 12, 28, WHITE), pg.transform.flip(self.game.spritesheet.get_image(64, 224, 12, 28, WHITE), True, False), pg.transform.flip(self.game.spritesheet.get_image(76, 224, 12, 28, WHITE), True, False) ] def animate(self): now = pg.time.get_ticks() if now - self.last_updated > MOB_BULLET_FRAME_RATE: self.frame += 1 if self.frame == len(self.frames): self.frame = 0 self.image = self.frames[self.frame] self.last_updated = now self.mask = pg.mask.from_surface(self.image) def update(self): if self.rect.bottom > HEIGHT - BOT_SPACING: self.kill() self.rect.y += MOB_BULLET_SPEED self.animate()
soupss/space-invaders
sprites/bullet.py
bullet.py
py
2,099
python
en
code
0
github-code
6
27125372338
import logging from datetime import datetime import smtplib from notifications import * from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from db.client import db_create_close, r logging.config.fileConfig('/opt/TopPatch/conf/logging.config') logger = logging.getLogger('rvapi') @db_create_close def email_config_exists(customer_name=None, conn=None): mail_exists = False try: mail_config = list( r .table(NotificationCollections.NotificationPlugins) .get_all(customer_name, index=NotificationPluginIndexes.CustomerName) .filter( { NotificationPluginKeys.PluginName: 'email' } ) .run(conn) ) if mail_config: mail_exists = (True, mail_config[0][NotificationPluginKeys.Id]) except Exception as e: msg = 'Failed to get mail config: %s' % (e) logger.error(msg) return(mail_exists) @db_create_close def get_email_config(customer_name=None, conn=None): mail_config = None config_exists = False msg = '' try: mail_config = list( r .table(NotificationCollections.NotificationPlugins) .get_all(customer_name, index=NotificationPluginIndexes.CustomerName) .filter( { NotificationPluginKeys.PluginName: 'email' } ) .run(conn) ) if not mail_config: mail_config = { 'modified_time': '', 'username': '', 'password': '', 'server': '', 'port': '', 'is_tls': '', 'is_ssl': '', 'from_email': '', 'to_email': '', 'last_modify_user': '', } msg = 'mail_config does not exist' else: config_exists = True except Exception as e: msg = 'Failed to get mail config: %s' % (str(e)) logger.exception(e) return( { 'pass': config_exists, 'message': msg, 'data': mail_config } ) @db_create_close def delete_email_config(customer_name=None, conn=None): deleted = False try: mail_deleted = ( r .table(NotificationCollections.NotificationPlugins) .get_all(customer_name, index=NotificationPluginIndexes.CustomerName) .filter( { NotificationPluginKeys.PluginName: 'email' } ) .delete() .run(conn) ) if 'deleted' in mail_deleted: if mail_deleted['deleted'] > 0: deleted = True except Exception as e: msg = ( 'Failed to delete mail config for customer %s: %s' % (customer_name, e) ) logger.error(msg) return(deleted) @db_create_close def create_or_modify_mail_config(modifying_username=None, customer_name=None, server=None, username=None, password=None, port=25, is_tls=False, is_ssl=False, from_email=None, to_email=None, conn=None): created = False msg = '' base_config = [] email_uuid = None if (server and username and password and port and customer_name and modifying_username and from_email and len(to_email) > 0): modified_time = str(datetime.now()) to_email = ','.join(to_email) base_config = { NotificationPluginKeys.ModifiedTime: modified_time, NotificationPluginKeys.UserName: username, NotificationPluginKeys.Password: password, NotificationPluginKeys.Server: server, NotificationPluginKeys.Port: port, NotificationPluginKeys.IsTls: is_tls, NotificationPluginKeys.IsSsl: is_ssl, NotificationPluginKeys.FromEmail: from_email, NotificationPluginKeys.ToEmail: to_email, NotificationPluginKeys.PluginName: 'email', NotificationPluginKeys.CustomerName: customer_name, NotificationPluginKeys.ModifiedBy: modifying_username, } config_exists = email_config_exists(customer_name=customer_name) if config_exists: email_uuid = config_exists[1] try: ( r .table(NotificationCollections.NotificationPlugins) .get(config_exists[1]) .update(base_config) .run(conn) ) created = True msg = ( 'Email config for customer %s has been updated' % (customer_name) ) except Exception as e: msg = 'Failed to update mail config: %s' (e) logger.error(msg) else: try: is_created = ( r .table(NotificationCollections.NotificationPlugins) .insert(base_config, upsert=True) .run(conn) ) if 'inserted' in is_created: if 'generated_keys' in is_created: if len(is_created['generated_keys']) > 0: email_uuid = is_created['generated_keys'[0]] created = True msg = ( 'Email config for customer %s has been created' % (customer_name) ) except Exception as e: msg = 'Failed to update mail config: %s' % (e) logger.exception(e) return( { 'pass': created, 'message': msg, 'data': [base_config] } ) class MailClient(): def __init__(self, customer_name): self.CONFIG = None self.validated = False self.connected = False self.error = None data = get_email_config(customer_name=customer_name) self.config_exists = False if data['pass']: config = data['data'][0] self.config_exists = data['pass'] if self.config_exists: self.server = config['server'] self.username = config['username'] self.password = config['password'] self.port = config['port'] self.from_email = config['from_email'] self.to_email = config['to_email'].split(",") self.is_tls = config['is_tls'] self.is_ssl = config['is_ssl'] else: self.server = None self.username = None self.password = None self.port = None self.from_email = None self.to_email = None self.is_tls = None self.is_ssl = None def server_status(self): msg = '' try: ehlo = self.mail.ehlo() if ehlo[0] == 250: self.connected = True self.server_reply_code = ehlo[0] self.server_reply_message = ehlo[1] msg = self.server_reply_message logger.info(msg) except Exception as e: msg = ( 'Connection to mail server %s has not been initialized: %s' % (self.server, e) ) logger.exception(msg) return(msg) def connect(self): connected = False logged_in = False msg = None mail = None try: if self.is_ssl: mail = smtplib.SMTP_SSL(self.server, int(self.port), timeout=10) else: mail = smtplib.SMTP(self.server, int(self.port), timeout=10) connected = True except Exception as e: logger.exception(e) msg = e if connected: try: if self.is_tls: mail.starttls() mail.login(self.username, self.password) logged_in = True except Exception as e: logger.exception(e) msg = e self.connected = connected self.error = msg self.logged_in = logged_in self.mail = mail return(connected, msg, logged_in, mail) def disconnect(self): msg = '' self.disconnected = False try: loggedout = self.mail.quit() msg = ( 'Logged out of Email Server %s: %s' % (self.server, loggedout) ) self.disconnected = True logger.info(msg) except Exception as e: msg = ( 'Failed to log out of %s: %s' % (self.server, e) ) self.disconnected = True logger.exception(e) return(self.disconnected, msg) def send(self, subject, msg_body, to_addresses=None, body_type='html'): completed = True from_address = None try: from_address = self.from_email except Exception as e: msg = 'From_address has not been set' logger.exception(msg) if not to_addresses: try: to_addresses = self.to_email except Exception as e: msg = 'Pass a valid email address:%s' % (e) logger.exception(msg) completed = False if isinstance(to_addresses, list): msg = MIMEMultipart('alternative') msg['From'] = from_address msg['To'] = ','.join(list(to_addresses)) msg['Subject'] = subject formatted_body = MIMEText(msg_body, body_type) msg.attach(formatted_body) try: self.mail.sendmail( from_address, to_addresses, msg.as_string() ) except Exception as e: completed = False msg = ( 'Could not send mail to %s: %s' % (','.join(to_addresses), e) ) logger.exception(msg) return(completed)
SteelHouseLabs/vFense
tp/src/emailer/mailer.py
mailer.py
py
10,469
python
en
code
5
github-code
6
23229945677
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings admin.site.site_header = "Адмнистрирование TBO Dashboard" admin.site.site_title = "Адмнистрирование TBO Dashboard" admin.site.index_title = "TBO Dashboard" urlpatterns = [ path('admin/', admin.site.urls), path('api/docs/', include('tbo_dash.docs.urls')), path('api/', include('djoser.urls')), path('api/', include('djoser.urls.authtoken')), path('api/', include('tbo_dash.dashboards.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # Silk profiler urlpatterns = [ path('silk/', include('silk.urls', namespace='silk')), ] + urlpatterns
alldevic/tbo_dash_old
tbo_dash/urls.py
urls.py
py
875
python
en
code
0
github-code
6
30162237145
from tkinter import * import plateau as plateau import gestionnaire_evenements as g_evenements import pions as pions import debug as de import gestionnaire_images as g_images def recommencer_jeu(fenetre,can,*debug): """ Relance le jeu avec certains paramètres :param can: Canva Tkinter :type can: Objet Tkinter :param continuer: Si la condition continuer est vraie le jeu charge une partie existante (default false) (facultatif) :type continuer: Booléen """ deb = de.afficher_temps_execution_debut() #Fonctions plateau.generer_plateaux(can,g_images.case_noire_iso,g_images.case_blanche_iso,g_images.case_noire_plat,g_images.case_blanche_plat) grille = pions.ajouter_pions_grille(8) pions.afficher_pions_plateau_iso(grille,can) pions.afficher_pions_plateau_plat(grille,can) pions.tour = 0 g_evenements.afficher_tour(can,pions.tour,g_images.tourn,g_images.tourb) pions.afficher_pions_captures(can,grille,"C","c",g_images.cavalier_blanc_plat,g_images.cavalier_noir_plat) de.afficher_temps_execution_fin(deb, "Lancement en") #Evenements can.bind("<Button-1>",lambda event: pions.selectionner_pion(event,grille,can)) can.bind("<Button-3>",lambda event: pions.deplacer_pion(event,fenetre,grille,can)) fenetre.protocol("WM_DELETE_WINDOW",lambda: g_evenements.confirmer_quitter(fenetre,grille,pions.tour)) if True in debug: print(grille)
PierreMonrocq/L1-Latroncules-game
relance.py
relance.py
py
1,433
python
fr
code
0
github-code
6
10423383033
from __future__ import annotations import copy import dataclasses import json from typing import TYPE_CHECKING import pytest from randovania.game_description.db.node_identifier import NodeIdentifier from randovania.games.prime2.layout.echoes_configuration import EchoesConfiguration from randovania.games.prime2.layout.translator_configuration import LayoutTranslatorRequirement from randovania.gui import tracker_window from randovania.layout.lib.teleporters import TeleporterShuffleMode from randovania.layout.versioned_preset import VersionedPreset if TYPE_CHECKING: from pathlib import Path from unittest.mock import MagicMock @pytest.fixture(params=[{}, {"teleporters": TeleporterShuffleMode.ONE_WAY_ANYTHING, "translator_configuration": True}]) def layout_config(request, default_echoes_configuration): if "translator_configuration" in request.param: translator_requirement = copy.copy(default_echoes_configuration.translator_configuration.translator_requirement) for gate in translator_requirement.keys(): translator_requirement[gate] = LayoutTranslatorRequirement.RANDOM break new_gate = dataclasses.replace( default_echoes_configuration.translator_configuration, translator_requirement=translator_requirement ) request.param["translator_configuration"] = new_gate return dataclasses.replace(default_echoes_configuration, **request.param) def test_load_previous_state_no_previous_layout(tmp_path: Path, default_echoes_configuration): # Run result = tracker_window._load_previous_state(tmp_path, default_echoes_configuration) # Assert assert result is None def test_load_previous_state_previous_layout_not_json(tmp_path: Path, default_echoes_configuration): # Setup tmp_path.joinpath("preset.rdvpreset").write_text("this is not a json") # Run result = tracker_window._load_previous_state(tmp_path, default_echoes_configuration) # Assert assert result is None def test_load_previous_state_previous_layout_not_layout(tmp_path: Path, default_echoes_configuration): # Setup tmp_path.joinpath("preset.rdvpreset").write_text(json.dumps({"trick_level": "foo"})) tmp_path.joinpath("state.json").write_text("[]") # Run result = tracker_window._load_previous_state(tmp_path, default_echoes_configuration) # Assert assert result is None def test_load_previous_state_missing_state(tmp_path: Path, default_preset): # Setup VersionedPreset.with_preset(default_preset).save_to_file(tmp_path.joinpath("preset.rdvpreset")) # Run result = tracker_window._load_previous_state(tmp_path, default_preset.configuration) # Assert assert result is None def test_load_previous_state_invalid_state(tmp_path: Path, default_preset): # Setup VersionedPreset.with_preset(default_preset).save_to_file(tmp_path.joinpath("preset.rdvpreset")) tmp_path.joinpath("state.json").write_text("") # Run result = tracker_window._load_previous_state(tmp_path, default_preset.configuration) # Assert assert result is None def test_load_previous_state_success(tmp_path: Path, default_preset): # Setup data = {"asdf": 5, "zxcv": 123} VersionedPreset.with_preset(default_preset).save_to_file(tmp_path.joinpath("preset.rdvpreset")) tmp_path.joinpath("state.json").write_text(json.dumps(data)) # Run result = tracker_window._load_previous_state(tmp_path, default_preset.configuration) # Assert assert result == data @pytest.mark.parametrize("shuffle_advanced", [False, True]) async def test_apply_previous_state( skip_qtbot, tmp_path: Path, default_echoes_preset, shuffle_advanced, echoes_game_description ): configuration = default_echoes_preset.configuration assert isinstance(configuration, EchoesConfiguration) if shuffle_advanced: translator_requirement = copy.copy(configuration.translator_configuration.translator_requirement) for gate in translator_requirement.keys(): translator_requirement[gate] = LayoutTranslatorRequirement.RANDOM break new_gate = dataclasses.replace( configuration.translator_configuration, translator_requirement=translator_requirement ) layout_config = dataclasses.replace( configuration, teleporters=dataclasses.replace( configuration.teleporters, mode=TeleporterShuffleMode.ONE_WAY_ANYTHING, ), translator_configuration=new_gate, ) preset = dataclasses.replace(default_echoes_preset.fork(), configuration=layout_config) else: preset = default_echoes_preset state: dict = { "actions": ["Temple Grounds/Landing Site/Save Station"], "collected_pickups": { "Amber Translator": 0, "Annihilator Beam": 0, "Boost Ball": 0, "Cobalt Translator": 0, "Dark Agon Key 1": 0, "Dark Agon Key 2": 0, "Dark Agon Key 3": 0, "Dark Ammo Expansion": 0, "Dark Beam": 0, "Dark Torvus Key 1": 0, "Dark Torvus Key 2": 0, "Dark Torvus Key 3": 0, "Dark Visor": 0, "Darkburst": 0, "Echo Visor": 0, "Emerald Translator": 0, "Energy Tank": 0, "Grapple Beam": 0, "Gravity Boost": 0, "Ing Hive Key 1": 0, "Ing Hive Key 2": 0, "Ing Hive Key 3": 0, "Light Ammo Expansion": 0, "Light Beam": 0, "Missile Expansion": 0, "Missile Launcher": 0, "Morph Ball Bomb": 0, "Power Bomb": 0, "Power Bomb Expansion": 0, "Progressive Suit": 0, "Screw Attack": 0, "Seeker Launcher": 0, "Sky Temple Key 1": 0, "Sky Temple Key 2": 0, "Sky Temple Key 3": 0, "Sky Temple Key 4": 0, "Sky Temple Key 5": 0, "Sky Temple Key 6": 0, "Sky Temple Key 7": 0, "Sky Temple Key 8": 0, "Sky Temple Key 9": 0, "Sonic Boom": 0, "Space Jump Boots": 1, "Spider Ball": 0, "Sunburst": 0, "Super Missile": 0, "Violet Translator": 0, }, "teleporters": [ { "data": None, "teleporter": { "area": "Transport to Temple Grounds", "node": "Elevator to Temple Grounds", "region": "Agon Wastes", }, }, { "data": None, "teleporter": { "area": "Transport to Torvus Bog", "node": "Elevator to Torvus Bog", "region": "Agon Wastes", }, }, { "data": None, "teleporter": { "area": "Transport to Sanctuary Fortress", "node": "Elevator to Sanctuary Fortress", "region": "Agon Wastes", }, }, { "data": None, "teleporter": { "area": "Temple Transport C", "node": "Elevator to Temple Grounds", "region": "Great Temple", }, }, { "data": None, "teleporter": { "area": "Temple Transport A", "node": "Elevator to Temple Grounds", "region": "Great Temple", }, }, { "data": None, "teleporter": { "area": "Temple Transport B", "node": "Elevator to Temple Grounds", "region": "Great Temple", }, }, { "data": None, "teleporter": { "area": "Aerie", "node": "Elevator to Aerie Transport Station", "region": "Sanctuary Fortress", }, }, { "data": None, "teleporter": { "area": "Aerie Transport Station", "node": "Elevator to Aerie", "region": "Sanctuary Fortress", }, }, { "data": None, "teleporter": { "area": "Transport to Temple Grounds", "node": "Elevator to Temple Grounds", "region": "Sanctuary Fortress", }, }, { "data": None, "teleporter": { "area": "Transport to Agon Wastes", "node": "Elevator to Agon Wastes", "region": "Sanctuary Fortress", }, }, { "data": None, "teleporter": { "area": "Transport to Torvus Bog", "node": "Elevator to Torvus Bog", "region": "Sanctuary Fortress", }, }, { "data": None, "teleporter": { "area": "Sky Temple Energy Controller", "node": "Elevator to Temple Grounds", "region": "Great Temple", }, }, { "data": None, "teleporter": { "area": "Sky Temple Gateway", "node": "Elevator to Great Temple", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Transport to Agon Wastes", "node": "Elevator to Agon Wastes", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Temple Transport B", "node": "Elevator to Great Temple", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Transport to Sanctuary Fortress", "node": "Elevator to Sanctuary Fortress", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Temple Transport A", "node": "Elevator to Great Temple", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Transport to Torvus Bog", "node": "Elevator to Torvus Bog", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Temple Transport C", "node": "Elevator to Great Temple", "region": "Temple Grounds", }, }, { "data": None, "teleporter": { "area": "Transport to Sanctuary Fortress", "node": "Elevator to Sanctuary Fortress", "region": "Torvus Bog", }, }, { "data": None, "teleporter": { "area": "Transport to Temple Grounds", "node": "Elevator to Temple Grounds", "region": "Torvus Bog", }, }, { "data": None, "teleporter": { "area": "Transport to Agon Wastes", "node": "Elevator to Agon Wastes", "region": "Torvus Bog", }, }, ], "configurable_nodes": { "Agon Wastes/Mining Plaza/Translator Gate": None, "Agon Wastes/Mining Station A/Translator Gate": None, "Great Temple/Temple Sanctuary/Transport A Translator Gate": None, "Great Temple/Temple Sanctuary/Transport B Translator Gate": None, "Great Temple/Temple Sanctuary/Transport C Translator Gate": None, "Sanctuary Fortress/Reactor Core/Translator Gate": None, "Sanctuary Fortress/Sanctuary Temple/Translator Gate": None, "Temple Grounds/GFMC Compound/Translator Gate": None, "Temple Grounds/Hive Access Tunnel/Translator Gate": None, "Temple Grounds/Hive Transport Area/Translator Gate": None, "Temple Grounds/Industrial Site/Translator Gate": None, "Temple Grounds/Meeting Grounds/Translator Gate": None, "Temple Grounds/Path of Eyes/Translator Gate": None, "Temple Grounds/Temple Assembly Site/Translator Gate": None, "Torvus Bog/Great Bridge/Translator Gate": None, "Torvus Bog/Torvus Temple/Elevator Translator Scan": None, "Torvus Bog/Torvus Temple/Translator Gate": None, }, "starting_location": {"region": "Temple Grounds", "area": "Landing Site", "node": "Save Station"}, } if shuffle_advanced: for teleporter in state["teleporters"]: if ( teleporter["teleporter"]["region"] == "Agon Wastes" and teleporter["teleporter"]["node"] == "Elevator to Sanctuary Fortress" and teleporter["teleporter"]["area"] == "Transport to Sanctuary Fortress" ): teleporter["data"] = { "area": "Agon Energy Controller", "region": "Agon Wastes", "node": "Door to Controller Access", } state["configurable_nodes"]["Temple Grounds/Hive Access Tunnel/Translator Gate"] = "violet" VersionedPreset.with_preset(preset).save_to_file(tmp_path.joinpath("preset.rdvpreset")) tmp_path.joinpath("state.json").write_text(json.dumps(state), "utf-8") # Run window = await tracker_window.TrackerWindow.create_new(tmp_path, preset) skip_qtbot.add_widget(window) # Assert assert window.state_for_current_configuration() is not None persisted_data = json.loads(tmp_path.joinpath("state.json").read_text("utf-8")) assert persisted_data == state window.reset() window.persist_current_state() persisted_data = json.loads(tmp_path.joinpath("state.json").read_text("utf-8")) assert persisted_data != state async def test_load_multi_starting_location( skip_qtbot, tmp_path: Path, default_echoes_configuration, default_echoes_preset, mocker ): preset = default_echoes_preset new_start_loc = ( NodeIdentifier.create("Temple Grounds", "Landing Site", "Save Station"), NodeIdentifier.create("Temple Grounds", "Temple Transport C", "Elevator to Great Temple"), ) layout_config = dataclasses.replace( default_echoes_configuration, starting_location=dataclasses.replace(default_echoes_configuration.starting_location, locations=new_start_loc), ) preset = dataclasses.replace(default_echoes_preset.fork(), configuration=layout_config) mock_return = ("Temple Grounds/Temple Transport C/Elevator to Great Temple", True) # Run mock_get_item: MagicMock = mocker.patch("PySide6.QtWidgets.QInputDialog.getItem", return_value=mock_return) window = await tracker_window.TrackerWindow.create_new(tmp_path, preset) skip_qtbot.add_widget(window) # Assert mock_get_item.assert_called_once() state = window.state_for_current_configuration() assert state is not None assert state.node.identifier == new_start_loc[1] async def test_load_single_starting_location( skip_qtbot, tmp_path: Path, default_echoes_configuration, default_echoes_preset ): preset = default_echoes_preset new_start_loc = (NodeIdentifier.create("Temple Grounds", "Temple Transport C", "Elevator to Great Temple"),) layout_config = dataclasses.replace( default_echoes_configuration, starting_location=dataclasses.replace(default_echoes_configuration.starting_location, locations=new_start_loc), ) preset = dataclasses.replace(default_echoes_preset.fork(), configuration=layout_config) # Run window = await tracker_window.TrackerWindow.create_new(tmp_path, preset) skip_qtbot.add_widget(window) # Assert state = window.state_for_current_configuration() assert state is not None assert state.node.identifier == new_start_loc[0] async def test_preset_without_starting_location( skip_qtbot, tmp_path: Path, default_echoes_configuration, default_echoes_preset ): preset = default_echoes_preset new_start_loc = () layout_config = dataclasses.replace( default_echoes_configuration, starting_location=dataclasses.replace(default_echoes_configuration.starting_location, locations=new_start_loc), ) preset = dataclasses.replace(default_echoes_preset.fork(), configuration=layout_config) # Run with pytest.raises(ValueError, match="Preset without a starting location"): await tracker_window.TrackerWindow.create_new(tmp_path, preset)
randovania/randovania
test/gui/test_tracker_window.py
test_tracker_window.py
py
17,755
python
en
code
165
github-code
6
21077625640
import json import os import requests from get_token import GetToken from log_setup import Logging from program_data import PDApi """ NetApp / SolidFire CPE mnode support utility """ """ Package service api calls https://[mnodeip]/package-repository/1 """ # set up logging logmsg = Logging.logmsg() # disable ssl warnings so the log doesn't fill up requests.packages.urllib3.disable_warnings() class Package: def list_packages(repo): """ List available packages """ url = f'{repo.base_url}/package-repository/1/packages/' json_return = PDApi.send_get_return_json(repo, url, debug=repo.debug) if json_return: return json_return def delete_package(repo, package_id): """ Delete a package """ url = f'{repo.base_url}/package-repository/1/packages/{package_id}' logmsg.debug(f'Sending DELETE {url}') json_return = PDApi.send_delete_return_status(repo, url) if json_return: logmsg.info(f'{json_return["version"]}: {json_return["message"]}') def upload_element_image(repo, updatefile): """ upload a package requires some special treatment with the api call. So it does not use PDApi.send_put """ token = GetToken(repo, True) logmsg.info('Add upgrade image to package repository') if os.path.exists(updatefile) != True: logmsg.info(f'{updatefile} not found') exit(1) header = {"Accept": "application/json", "Prefer": "respond-async", "Content-Type": "application/octet-stream", "Authorization":f'Bearer {token.token}'} url = f'{repo.base_url}/package-repository/1/packages' session = requests.Session() with open(updatefile, 'rb') as f: try: logmsg.debug(f'Sending PUT {url} {updatefile}') logmsg.info(f'Loading {updatefile} into the package repository. This will take a few minutes') response = session.post(url, headers=header, data=f, verify=False) if response.status_code == 200 or response.status_code == 202: logmsg.info('Upload successful') logmsg.info(response.text) response_json = json.loads(response.text) else: logmsg.info(f'Package upload fail with status {response.status_code}\n\t{response.text}') except requests.exceptions.RequestException as exception: logmsg.info("An exception occured. See /var/log/mnode-support-util.log for details") logmsg.debug(exception) logmsg.debug(f'{response}') session.close() return response_json
solidfire/mnode-support-util
api_package_service.py
api_package_service.py
py
2,719
python
en
code
0
github-code
6
39434540766
# from sklearn.naive_bayes import MultinomialNB # from sklearn.naive_bayes import GaussianNB # from sklearn.cluster import KMeans import pandas as pd # from random import shuffle import numpy as np import os # from sklearn.feature_extraction.text import CountVectorizer # from sklearn.feature_extraction.text import TfidfTransformer from nltk.corpus import stopwords # from nltk.corpus import stopwords # from nltk.tokenize import word_tokenize # import nltk import re import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser from lxml import etree def obtener_text(path = str(), file = str()): """ Función que regresa el texto del archivo que se le pasa, preferentemente pasar la ruta relativa de donde se encuentra el archivo. Funciona con los archivos #.review.post del corpus del mismo directorio. Retorna el texto unicamente. path = ruta relativa o completa del archivo seleccionado. """ with open(path + file, encoding='latin1', mode = 'r') as f: text = f.read() listas = text.split('\n') test = [] for linea in listas: aux = linea.split(' ') try: test.append(aux[1]) except: pass cad = ' '.join(test) return cad def normalizar(text = str()): # nltk.download('stopwords') ''' Funcion para normalizar el texto y eliminar stopwords, así como signos de puntuación, guiones bajos y demás caracteres que no sean texto, retorna la cadena limpia. text : texto para normalizar ''' stop_words = set(stopwords.words('spanish')) lower_string = text.lower() no_number_string = re.sub(r'\d+','',lower_string) no_sub_ = re.sub('[\_]',' ', no_number_string) no_punc_string = re.sub(r'[^\w\s]','', no_sub_) no_wspace_string = no_punc_string.strip() # no_wspace_string lst_string = [no_wspace_string][0].split() # print(lst_string) no_stpwords_string="" for i in lst_string: if not i in stop_words: no_stpwords_string += i+' ' no_stpwords_string = no_stpwords_string[:-1] return no_stpwords_string def get_rank (path = str(), file = str(), llave = 'rank'): """ En la función solo se tiene que pasar el path, más el archivo del cual se quiera obtener el rank, o mejor dicho la valoración que se obtuvo en la pelicula, el archivo a pasar tiene que ser en formato .xml para que la función funcione de forma correcta, retorna el valor entero que se puso en la pelicula. path : ruta donde se encuentran los archivos xml file : nombre del archivo el cual se va a obtener el valor llave : atributo que se quiere, valor por defecto rank """ with open(path + file, mode = 'r', encoding= 'latin1') as f: parser = etree.XMLParser(recover=True) tree = ET.parse(f, parser=parser) root = tree.getroot() att = root.attrib return int(att[llave]) def obtener_y (path = str(), file_pos = list(), file_xml = list()): """ Funcion hecha para obtener el mismo número de archivos xml y de review.pos, regresa el valor del archivo xml. Retorna una lista. path : Dirección donde se encuentra el corpus file_pos : lista con los nombres del archivo review.pos xml_file : lista con los nombres del archivo xml contenidas en el corpus """ file_of_x = list() value_of_y = list() for file in file_pos: aux = file.split('.') num = aux[0] comp = str(num) + '.xml' if comp in file_xml: file_of_x.append(obtener_text(path,file)) value_of_y.append(get_rank(path, comp)) return file_of_x, value_of_y
svroo/PNL-Escom
Joder es cine/Modulo/text_proc.py
text_proc.py
py
3,744
python
es
code
0
github-code
6
72283436667
import requests import json match = { "Date": "21-01-2023", "Form": "decent", "Opposition": "tough", "season": "middle", "venue": "home", "Previous match": "0", "uEFa": "active" } #url = 'http://localhost:9696/predict' url = 'https://klopp-s-liverp-prod-klopp-s-liverpool-hql7qt.mo4.mogenius.io/predict' response = requests.post(url, json=match) result = response.json() print(result)
Blaqadonis/klopps_liverpool
predict_test.py
predict_test.py
py
416
python
en
code
0
github-code
6
44354332755
from datetime import datetime ## Method to remove empty values from a dictionary def remove_empty_values_from_dict(dictionary): return {k: v for k, v in dictionary.items() if v is not None and v != '' and v != [] and v != {} } def pretty_time(seconds): seconds = abs(int(seconds)) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if days > 0: return '%dd %dh %dm %ds' % (days, hours, minutes, seconds) elif hours > 0: return '%dh %dm %ds' % (hours, minutes, seconds) elif minutes > 0: return '%dm %ds' % (minutes, seconds) else: return '%ds' % (seconds) ## Coverts a datetime to a specified string format. def convert_datetime(dt, fmt): return dt.strftime(fmt) ## Formats RingCentral Call Metadata into a formatted note for a Close call def format_ringcentral_call_note(note_data): keys = ["RC ID", "From", "To", "Duration", "Direction", "Result", "Reason", "Reason Description", "RC Users"] note = [] note_key_data = { "RC ID": note_data.get('id'), "From": note_data['from']['phoneNumber'], "To": note_data['to']['phoneNumber'], "Duration": pretty_time(note_data['duration']), "Direction": note_data['direction'], 'Result': note_data.get('result'), 'Reason': note_data.get('reason'), 'Reason Description': note_data.get('reasonDescription'), 'RC Users': note_data.get('users') } note_key_data = remove_empty_values_from_dict(note_key_data) for key in keys: if key in note_key_data: note.append(f"{key}: {note_key_data[key]}" ) if note: note = ['RingCentral Call:'] + note return '\n'.join(note) return None ## Formats RingCentral Call Data into a dictionary that can be POSTed to ## the Close API def format_ringcentral_call_data(call_data): if call_data.get('duration') and call_data.get('result') == 'Missed': call_data['duration'] = 0 close_call_data = { 'lead_id': call_data['lead_id'], 'duration': call_data.get('duration', 0), 'direction': call_data.get('direction', 'outbound').lower(), 'remote_phone': call_data.get('remote_phone'), 'date_created': call_data.get('startTime', '').replace('Z', '+00:00'), 'note': format_ringcentral_call_note(call_data) } return remove_empty_values_from_dict(close_call_data)
eengoron/close-crm-ringcentral-connector
app/format_rc_to_close.py
format_rc_to_close.py
py
2,444
python
en
code
1
github-code
6
15370026614
import random numbers=[1,2,3,4,5,6,7,8,9] guess=input("your guess : ") randomNumber=random.choice(numbers) if randomNumber==guess: print("you win") else: print("you lose") print("the number is : ") print(randomNumber)
pavanajmadhu/guessing-python
guessing.py
guessing.py
py
235
python
en
code
0
github-code
6
4737933535
#Defines what a 'student' is (Something in your program that has 'name, major, gpa, and is_on_probation' parameters) class student: def __init__(self, name, major, gpa, is_on_probation): #Constructor: when creating a new student object, this function is called and uses the given parameters self.name = name self.major = major #self.major = attribute assigned from the parameter of provided student class. self.gpa = gpa self.is_on_probation = is_on_probation def on_honor_roll(self): if self.gpa >= 3.5: #Refers to gpa from provided student class return True else: return False #Creating a 'student' object from the 'student' class student1 = student("Dan", "Azure", 3.1, False) student2 = student("Pam", "Art", 3.7, True) print(student1.name) print(student2.gpa) print(student2.on_honor_roll()) class dog: def __init__(self, breed, age, name): self.breed = breed self.age = age self.name = name dog1 = dog("German Shepherd", 12, "Joe") print(dog1.name)
danlhennessy/Learn
Python/fundamentals/OOP/class.py
class.py
py
1,097
python
en
code
0
github-code
6
24347584300
# # Categorize all issues # # To use: open with jupyter notebook/lab using jupytext and run all cells # + from getpass import getpass from textwrap import dedent from ipywidgets import Button, ToggleButtons, Output, VBox from IPython.display import display, Markdown import gitlab # - gl = gitlab.Gitlab(url="https://gitlab.kwant-project.org", private_token=getpass("Gitlab API token: ")) repo = gl.projects.get("zesje/zesje") labels = repo.labels.list() # + label_dict = {tuple(label.name.split(": ")): label for label in labels if ": " in label.name} categories = ["impact", "effort", "maintainability"] degrees = ["low", "medium", "high"] # + description = Output() selector = { category: ToggleButtons( options=[(degree, label_dict[category, degree]) for degree in degrees], description=category, label="medium", style={"button_color": label_dict}, ) for category in categories } submit = Button(description="submit & next", icon="check") current_issue = None def submit_labels(issue): other_labels = [i for i in issue.labels if ": " not in i] issue.labels = [i.value.name for i in selector.values()] + other_labels issue.save() def render_issue(issue): return Markdown( dedent( f"""### [{issue.title}]({issue.web_url}) {issue.description} """ ) ) def next_issue(): issues = repo.issues.list(all=True, state="opened") for issue in issues: issue_categories = {label.split(": ")[0]: label.split(": ")[1] for label in issue.labels if ": " in label} already_labeled = len(issue_categories) == 3 and len(set(issue_categories)) == 3 if not already_labeled: break else: submit.disabled = True submit.text = "Done!" for button in selector.values(): button.disabled = True return None description.clear_output(wait=True) with description: display(render_issue(issue)) for category, degree in issue_categories.items(): selector[category].label = degree return issue def submit_and_next(event): global current_issue if current_issue is not None: submit_labels(current_issue) current_issue = next_issue() submit.on_click(submit_and_next) VBox(children=[description] + list(selector.values()) + [submit])
zesje/zesje
label_issues.py
label_issues.py
py
2,370
python
en
code
9
github-code
6
72787079228
import time import psutil import scapy.interfaces from scapy.all import * from PyQt6.QtCore import QObject, pyqtSignal class GetInterfaceServer(QObject): """捕获网卡信息""" isActive = True bytes_flow = pyqtSignal(dict) interfaces_scapy = scapy.interfaces.get_working_ifaces() interfaces_psutil = psutil.net_io_counters(pernic=True) def run(self): while True: if not self.isActive: break res = {} for interface in self.interfaces_scapy: if interface.name in self.interfaces_psutil: bytes_sent = psutil.net_io_counters(pernic=True)[interface.name].bytes_sent bytes_recv = psutil.net_io_counters(pernic=True)[interface.name].bytes_recv else: bytes_sent = 0 bytes_recv = 0 res[interface.name] = (bytes_sent, bytes_recv) time.sleep(1) self.bytes_flow.emit(res)
VanCoghChan/CCSniffer
models/GetInterfaceModel.py
GetInterfaceModel.py
py
1,002
python
en
code
0
github-code
6
26401762339
# %% import plotly.express as px import plotly.graph_objects as go import os import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import pandas as pd import pdb def visualize_map(): # %% map_prefix = "50_10_5_10_5_2" ndf = pd.read_csv("" + map_prefix + "_Nodes.csv") edf = pd.read_csv("" + map_prefix + "_Edges.csv") # %% ### Plotly newDf = [] traces = [] xLines, yLines, zLines = [], [], [] for index, row in edf.iterrows(): bidir = row['bidirectional'] node1 = ndf.loc[ndf['NodeId'] == row['nodeFrom']] node2 = ndf.loc[ndf['NodeId'] == row['nodeTo']] xline = [node1['X'].iloc[0], node2['X'].iloc[0]] yline = [node1['Y'].iloc[0], node2['Y'].iloc[0]] zline = [node1['Z'].iloc[0], node2['Z'].iloc[0]] # aTrace = go.Scatter3d(x=xline, y=yline, z=zline, mode='lines', line=dict(color="blue"), hoverinfo='skip', showlegend=False) # traces.append(aTrace) vals = [xline[0], yline[0], zline[0], xline[1], yline[1], zline[1]] newDf.append([row["nodeFrom"], row["nodeFrom"], bidir, *vals]) xLines.extend([*xline, None]) yLines.extend([*yline, None]) zLines.extend([*zline, None]) aTrace = go.Scatter3d(x=xLines, y=yLines, z=zLines, mode='lines', line=dict(color="blue"), hoverinfo='skip', showlegend=False) traces.append(aTrace) # fig = go.Figure(data=traces) # fig.write_image("testPlotly.png") # plt.show() # %% fig = go.Figure(data=traces) # fig.write_image("../figs/maps/" + map_prefix + ".png") fig.write_html("hello_world/templates/" + map_prefix + ".html") def animate_paths(): map_prefix = "50_10_5_10_5_2" ndf = pd.read_csv("" + map_prefix + "_Nodes.csv") pdf = pd.read_csv("paths.csv") pdf = pdf.iloc[:, :-1] # Drop last empty column # %% ### Creating traces of pathTraces = [] for index, row in pdf.iterrows(): tmpdf = ndf.iloc[row[1:]] aTrace = go.Scatter3d(x=tmpdf["X"], y=tmpdf["Y"], z=tmpdf["Z"], mode='lines', hoverinfo="skip", showlegend=False) pathTraces.append(aTrace) # %% # fig = go.Figure(data=pathTraces) # fig.write_image("testPlotly.png") # %% ### Create animations numFrames = len(pdf.columns) - 1 # First columns is the string "Timesteps" numAgents = pdf.shape[0] agentColors = list(range(numAgents)) def getSingleFrame(curT): curLocs = ndf.iloc[pdf[str(curT)]] return go.Frame(name=str(curT), data = go.Scatter3d(x=curLocs["X"], y=curLocs["Y"], z=curLocs["Z"], mode="markers", marker=dict(size=6, color=agentColors), showlegend=False, hoverinfo="skip")) allFrames = [getSingleFrame(t) for t in range(numFrames)] # %% ### https://plotly.com/python/visualizing-mri-volume-slices/?_ga=2.213007632.583970308.1664493502-1988171524.1656003349 def sliderFrameArgs(duration): return { "frame": {"duration": duration}, "mode": "immediate", "fromcurrent": True, "transition": {"duration": duration, "easing": "linear"}, } sliders = [{ "pad": {"b": 10, "t": 60}, "len": 0.6, "x": 0.22, "y": 0, "steps": [ { "args": [[f.name], sliderFrameArgs(300)], "label": str(k), "method": "animate", } for k, f in enumerate(allFrames)] }] fig = go.Figure(frames=allFrames, # data=traces, ## Show entire grid, significantly slows down animation # data=allFrames[0].data, ## First frame, no grid lines data=pathTraces, ## Show path traces, animation works fine layout=go.Layout( title="3D MAPF Animation", updatemenus=[dict( type="buttons", buttons=[dict(label="&#9654;", # play symbol method="animate", args=[None, sliderFrameArgs(300)]), dict(label="&#9724;", # pause symbol method="animate", args=[[None], sliderFrameArgs(0)]) ], direction="left", pad={"r": 10, "t": 70}, x=0.22, y=0)], sliders=sliders) ) # fig.update_layout(sliders=sliders) # %% fig.write_html("hello_world/templates/backAndForth.html") # %%
pwang649/3D_MAPF
hello_world/core/visualization.py
visualization.py
py
4,687
python
en
code
0
github-code
6
43392192504
import cv2 import numpy as np from matplotlib import pyplot as plt # 模版匹配 img = cv2.imread("fb.png", 0) img2 = img.copy() template = cv2.imread("zdbz.png", 0) w,h = template.shape[::-1] method = eval("cv2.TM_CCOEFF") res = cv2.matchTemplate(img2, template ,method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) print(min_val,max_val,min_loc,max_loc) topLeft = max_loc bottomRight = (topLeft[0]+w,topLeft[1]+h) print(bottomRight)
frebudd/python
阴阳师副本自动化/副本自动化2.py
副本自动化2.py
py
450
python
en
code
2
github-code
6
35426911515
#!/usr/bin/python3 import numpy as np import scipy.integrate import matplotlib.pyplot as plt def vdp(t,y): """calculate Van Der Pol Derivatives""" # y is a tuple (y0,y1) y0dot = y[1] y1dot = (1-y[0]**2)*y[1]-y[0] dydt = ( y0dot, y1dot ) return dydt solution = scipy.integrate.solve_ivp(vdp, t_span=(0,20), y0=(0,2), method='RK45', rtol=1e-6) t = solution.t y0 = solution.y[0] y1 = solution.y[1] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(t, y0, color='tab:blue', label='y1') ax.plot(t, y1, color='tab:orange', label='y2') ax.set_title('Solution of the van der Pol equation, mu=1') ax.set_xlabel('time') ax.set_ylabel('solution') ax.legend() plt.show()
martinaoliver/GTA
ssb/m1a/numeric/Practical_full_solutions_jupyter/python_script_solutions/vanderpol_20191001.py
vanderpol_20191001.py
py
695
python
en
code
0
github-code
6
28493662472
###### Librerias ###### import tkinter as tk import Widgets as Wd import Ecuaciones as Ec import time as tm import threading as hilos import numpy as np ###### Modulos De Librerias ###### import tkinter.ttk as ttk import tkinter.messagebox as MsB import serial import serial.tools.list_ports import matplotlib.pyplot as plt ###### SubModulos De Librerias ###### from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) board =serial.Serial(port='COM1', baudrate=9600) tm.sleep(1) board2 =serial.Serial(port='COM4', baudrate=9600) tm.sleep(1) def Show_Sliders(event): #Función Para Mostrar Sliders Alter_Sliders('T', Pl_x.get()) Datos_Temp(0,0,0,1) Wd.Aparecer([Pl_x, Pl_y, Pl_z, P_xi, P_yi, P_zi, P_x, P_y, P_z, P_inicial, P_final], [1/16+0.025, 1/16+0.025, 1/16+0.025, 0, 0, 0, 1/16+0.01, 1/16+0.01, 1/16+0.01, 0, 2/16], [1/6, 3/6-0.07, 0.693, 2/6-0.02, 3/6+0.075, 0.836, 2/6-0.02, 3/6+0.075, 0.836, 1/6-0.02, 0]) def Show_Codo(Iden, Valor): #Función Para Mostrar Codos Wd.Aparecer([T_Codo, Despl_Codo], [4/16+0.02, 4/16+0.01], [3/7+0.02, 4/6]) def Show_Perfiles(event): #Función Para Mostrar Perfiles Wd.Aparecer([Cuadratico, TrapezoidalI, TrapezoidalII], [6/16+0.04, 9/16+0.04, 12/16+0.04], [0, 0, 0]) def Show_Datos(): #Función Para Mostrar Los Sliders De Datos De Entrada if Tipo.get()==1: Wd.Ocultar([Vj_1, Vj_2, Vj_3, Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3, TVc_1, TVc_2, TVc_3]) if Tipo.get()==2: Wd.Aparecer([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3], [9/16+0.04, 9/16+0.04, 9/16+0.04, 9/16+0.02, 9/16+0.02, 9/16+0.02], [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12]) Wd.Ocultar([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3]) #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,1) if Tipo.get()==3: Wd.Aparecer([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3], [12/16+0.04, 12/16+0.04, 12/16+0.04, 12/16+0.02, 12/16+0.02, 12/16+0.02], [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12]) Wd.Ocultar([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3]) #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,2) Wd.Aparecer([T_f, N_p, TT_f, TN_p, Calcular_PT], [6/16+0.04, 6/16+0.04, 6/16+0.02, 6/16+0.02, 6/16+0.04], [1/8+0.01, 3/8+0.04, 1/7+0.012, 3/7+0.012, 6/8]) def Show_Graficas(Iden, Valor): print(Valor) bands=0 bandr=0 def Datos_Temp(xtemp, ytemp, ztemp, RW): #Función Para Guardar Los Valores Para Nuevo Punto Inicial global bands global bandr if RW==0: selection = Despl_Mani.get() if selection == "Scara (PRR)": temp_xs=xtemp temp_ys=ytemp temp_zs=ztemp bands=1 else: temp_xr=xtemp temp_yr=ytemp temp_zr=ztemp bandr=1 else: selection = Despl_Mani.get() if selection == "Scara (PRR)": if bands==1: P_xi.config(text=temp_xs) P_yi.config(text=temp_ys) P_zi.config(text=temp_zs) else: P_xi.config(text=345.2) P_yi.config(text=0) P_zi.config(text=0) else: if bandr==1: P_xi.config(text=temp_xr) P_yi.config(text=temp_yr) P_zi.config(text=temp_zr) else: P_xi.config(text=197) P_yi.config(text=0) P_zi.config(text=95.5) def Alter_Sliders(Ident, Valor): #Función Para Alternos Los Sliders (Scara-Antropomórfico) if Despl_Mani.get() == "Scara (PRR)": Pl_x['from_']=-131.5 Pl_x['to']=375.5 Pl_z['from_']=0 Pl_z['to']=19 if Ident == 'A1': Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Valor) else: Pl_x['from_']=-197 Pl_x['to']=197 if Ident == 'A1': Red_Slider(['A1', 'T', Pl_y, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor) elif Ident == 'A2': Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor) def Mensajes(Cual): #Función Para Seleccionar Mensaje Emergente A Mostrar if Cual=="DK": MsB.showinfo( "Instrucciones Cinemática Directa", """ Sliders: Desplazar los slider para mover las articulaciones del brazo robótico en tiempo real para obtener las matrices individuales y total de la cinemática directa. \n Cuadro de Texto: Digitar el valor que se encuentre en el rango de funcionamiento del robot para mover las articulaciones del brazo robótico. Luego presionar el botón de envió y obtener las matrices individuales y total de la cinemática directa en tiempo real. """) elif Cual=="IK": MsB.showinfo( "Instrucciones Cinemática Inversa", """ Deslizar cada slider para establecer la posición del efector final, dar click en el botón "Calcular" y finalizar seleccionando la configuración del codo a utilizar para mover el manipulador. \n Se debe tener en cuenta que las opciones de los codos únicamente están disponibles sí los valores calculados de las articulaciones no superan los límites mecánicos """) def Color(Bandera, Boton, Identi): #Función Para Alternan Color De Boton #print-->board.write if Bandera: Boton["bg"]="red4" board.write(Identi.encode() +b',1\n') else: Boton["bg"]="lime green" board.write(Identi.encode() +b',0\n') def Gripper(Identi): #Función Para Abrir o Cerrar Grippers global Estado_S global Estado_A global Estado_R if Identi=='E': Estado_S=not Estado_S Color(Estado_S,Gp_S,'E') elif Identi=='A': Estado_A=not Estado_A Color(Estado_A,Gp_A,'A') else: Estado_R=not Estado_R Color(Estado_R,Gp_R,'R') def Red_Slider(Vec, Valor): #Función Para Redefinir Los Limites de Los Sliders De Cinematica Inversa Ident=Vec[0] if (Ident == 'S') or (Ident == 'A2') or (Ident =='A1'): Pes=Vec[1] Slider=Vec[2] Check=Vec[3] PosX=Vec[4] PosY=Vec[5] if Ident =='S': #Redefinir Slider "Py_S" De Scara if Pes == 'I': Variable=Check_S_Valor elif Pes == 'T': Variable=Check_ST_Valor Check_A_PL.place_forget() LimitY_S=Ec.Limites_Y_S(Valor) Slider['from_']=str(LimitY_S[0]) Slider['to']=str(LimitY_S[1]) if LimitY_S[2] == 1 : Check.place(relx=PosX, rely=PosY) else: Check.place_forget() if Variable.get(): #Evalua El Checkbox "-", Para Valores Negativos Slider['from_']=str(float(-1)*LimitY_S[1]) Slider['to']=str(float(-1)*LimitY_S[0]) if Ident =='A1': #Redefinir Slider "Py_A" De Antropomórfico LimitY_A=Ec.Limites_Y_A(Valor) Slider['from_']=str(LimitY_A[1]) Slider['to']=str(LimitY_A[0]) if Ident =='A2': #Redefinir Slider "Pz_A" De Antropomórfico if Pes == 'I': LimitZ=Ec.Limites_Z_A(Px_A.get(), Py_A.get()) Variable=Check_A_Valor elif Pes == 'T': LimitZ=Ec.Limites_Z_A(Pl_x.get(), Pl_y.get()) Variable=Check_AT_Valor Check_S_PL.place_forget() if LimitZ[2] == 1 : Check.place(relx=PosX, rely=PosY) if Variable.get(): #Evalua El Checkbox "inf", Para Valores Del Limite Inferior Slider['from_']=str(LimitZ[1][1]) Slider['to']=str(LimitZ[1][0]) else: Slider['from_']=str(LimitZ[0][1]) Slider['to']=str(LimitZ[0][0]) else: Check.place_forget() Slider['from_']=str(LimitZ[1]) Slider['to']=str(LimitZ[0]) def Cambio(Ident): #Función Para Detectar El Cambio De Los CheckBox if Ident == 'S': Red_Slider(['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01], Px_S.get()) elif Ident == 'A2': Red_Slider(['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18], None) elif Ident == 'ST': Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Pl_x.get()) elif Ident == 'AT': Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], None) def Cine_Directa(Vector, Valor): #Función Para Enviar y Calcular Cinemática Directa Con Los Sliders Identi=Vector[0] if (bool(Identi.find('E')))==False: Matriz=Ec.Parametros(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get(), None, None, None) Wd.Llenado(Matriz, 1, 4) elif (bool(Identi.find('A')))==False: Matriz=Ec.Parametros(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get(), None, None, None) Wd.Llenado(Matriz, 5, 8) else: Matriz=Ec.Parametros(3, Qs1_R.get(), Qs2_R.get(), Qs3_R.get(), Qs4_R.get(), Qs5_R.get(), Qs6_R.get()) Wd.Llenado(Matriz, 9, 15) hilos.Thread(target=Wd.Barra.Carga, args=(Vector[1],)).start() board.write(Identi.encode()+b','+ Valor.encode()+b'\n') print(Identi.encode()+b','+ Valor.encode()+b'\n') board2.write(Identi.encode()+b','+ Valor.encode()+b'\r\n') def Cajas_DK(Vector): #Función Para Boton "Enviar". Se Calcula y Envia La Cinemática Directa Con Los Cuadros de Texto Identi=Vector[0] Valor=Vector[1] Enviar(Vector) if (bool(Identi[0].find('E')))==False: Matriz=Ec.Parametros(1, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None) Wd.Llenado(Matriz, 1, 4) elif (bool(Identi[0].find('A')))==False: Matriz=Ec.Parametros(2, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None) Wd.Llenado(Matriz, 5, 8) else: Matriz=Ec.Parametros(3, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), float(Valor[3].get()), float(Valor[4].get()), float(Valor[5].get())) Wd.Llenado(Matriz, 9, 15) def Cine_Inversa(Vector): #Función Para Calcular Cinematica Inversa Del Scara Identi=Vector[0] Codos=Vector[1] if Identi=='S': Vec_IK=Ec.Calculo_Inversa(1, float(Px_S.get()), float(Py_S.get()), float(Pz_S.get())) Codos[0].Ubicacion(1/2,1/2,tk.N) Codos[1].Ubicacion(2/3, 1/2, tk.N) #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba) q1_S.set(str(int(Vec_IK[0]/10))) q2_S_D.set(str(int(Vec_IK[1]))) q3_S_D.set(str(int(Vec_IK[2]))) q2_S_U.set(str(int(Vec_IK[3]))) q3_S_U.set(str(int(Vec_IK[4]))) elif Identi=='A': Vec_IK=Ec.Calculo_Inversa(2, float(Px_A.get()), float(Py_A.get()), float(Pz_A.get())) Codos[0].Ubicacion(1/2, 1/2, tk.N) Codos[1].Ubicacion(2/3, 1/2, tk.N) if Vec_IK[0]<(-1): Vec_IK[0]=360+Vec_IK[0] #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba) q1_A.set(str(int(Vec_IK[0]))) q2_A_D.set(str(int(Vec_IK[1]))) q3_A_D.set(str(int(Vec_IK[2]))) q2_A_U.set(str(int(Vec_IK[3]))) q3_A_U.set(str(int(Vec_IK[4]))) #Desabilitación de Botones de Envio Cinematica Inversa if Vec_IK[5] or Vec_IK[6]: #indar indab if Vec_IK[6] == 1:#indab Codos[0].place_forget() if Vec_IK[5] == 1:#indar Codos[1].place_forget() MsB.showwarning("Advertencia Selección Codo",""" Una o ambas soluciones supera los limites mecanicos. Varie el valor del punto """) def Enviar(Vector): #Función Donde Se Envia Los Datos Identi=Vector[0] Valor=Vector[1] for i in range (0,len(Identi)): hilos.Thread(target=Wd.Barra.Carga, args=(Vector[2],)).start() board.write(Identi[i].encode()+Valor[i].get().encode()+b'\n') board2.write(Identi[i].encode()+Valor[i].get().encode()+b'\r\n') tm.sleep(3) def Jacobians(Barra): #Función Para Mostrar Los Jacobianos j_S=Ec.Jacobianos(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get()) j_A=Ec.Jacobianos(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get()) Matriz=[j_S[0], j_S[1], j_A[0], j_A[1]] hilos.Thread(target=Wd.Barra.Carga, args=(Barra,)).start() Wd.Llenado_Jaco(Matriz, 1, 4) def elec_manipulador():#Funcion Para Elección de Manipulador selection=Despl_Mani.get() if selection == "Scara (PRR)": return 1 else: return 2 def elec_codo():#Funcion Para Elección de codo selection=Despl_Codo.get() if selection == "Codo Abajo": return 1 else: return 2 def plot_3d(pos_final_x, pos_final_y, pos_final_z): root_3d = tk.Tk() root_3d.wm_title("Plot 3D Efector Final") fig = Figure(figsize=(5, 5), dpi=100) canvas = FigureCanvasTkAgg(fig, master=root_3d) canvas.draw() ax = fig.add_subplot(111, projection="3d") ax.plot(pos_final_x, pos_final_y, pos_final_z) toolbar = NavigationToolbar2Tk(canvas, root_3d) toolbar.update() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) tk.mainloop() def Envio_Pl(Vectores_1, Vectores_2, Vectores_3): paso=(T_f.get()/(N_p.get())) if Despl_Mani.get() == "Scara (PRR)": board.write(b'Eb,'+"{:.4f}".format(int(Vectores_1[-1])).encode()+b'\n') board2.write(b'Eb,'+str(int(Vectores_1[-1])).encode()+b'\r\n') Time_Prisma=int(Vectores_1[-1])*(1.8) tm.sleep (Time_Prisma) Restante=T_f.get()-Time_Prisma paso=(Restante/N_p.get()) for i in range(0,int(N_p.get())): board.write(b'Ebr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n') board2.write(b'Ebr,'+str(int(Vectores_2[i])).encode()+b'\r\n') tm.sleep(paso/2) board.write(b'Eab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n') board2.write(b'Eab,'+str(int(Vectores_3[i])).encode()+b'\r\n') tm.sleep(paso/2) else: for i in range(0,int(N_p.get())): board.write(b'Ab,'+"{:.4f}".format(int(Vectores_1[i])).encode()+b'\n') board2.write(b'Ab,'+str(int(Vectores_1[i])).encode()+b'\r\n') tm.sleep(paso/3) board.write(b'Abr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n') board2.write(b'Abr,'+str(int(Vectores_2[i])).encode()+b'\r\n') tm.sleep(paso/3) board.write(b'Aab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n') board2.write(b'Aab,'+str(int(Vectores_3[i])).encode()+b'\r\n') tm.sleep(paso/3) def But_Perfiles(Ident):#Funcion Para Calcular La Generación de Trayectorias mani=elec_manipulador() codo=elec_codo() xini=float(P_xi.cget("text")) yini=float(P_yi.cget("text")) zini=float(P_zi.cget("text")) xfin=float(Pl_x.get()) yfin=float(Pl_y.get()) zfin=float(Pl_z.get()) tip=Tipo.get() tfin=T_f.get() resolucion=N_p.get() if tip == 2: variable=[Vj_1.get(), Vj_2.get(), Vj_3.get()] elif tip == 3: variable=[Aj_1.get(), Aj_2.get(), Aj_3.get()] else: variable=[0, 0, 0] Vectores=Wd.Perfil(tip, mani, codo, tfin, xini, yini, zini, xfin, yfin, zfin, resolucion, variable) if Vectores[0] == 1: # vel MsB.showwarning(title="error", message="La magnitud de la velocidad supera la condición. \n Varie el los valores de la velocidad crucero ") for i in range (0, 3): if Vectores[2]==0: Vj_1["from_"]=(Vectores[1])+0.1 Vj_1["to"]=(Vectores[1]*2)-0.1 if Vectores[2]==1: Vj_2["from_"]=(Vectores[1])+0.1 Vj_2["to"]=(Vectores[1]*2)-0.1 if Vectores[2]==2: Vj_3["from_"]=(Vectores[1])+0.1 Vj_3["to"]=(Vectores[1]*2)-0.1 Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Vj_1.get(), Vj_2.get(), Vj_3.get()]) elif Vectores[0] == 2: #acel MsB.showwarning(title="error", message="La magnitud de la aceleración supera la condición. \n Varie el los valores de la aceleración crucero") for i in range (0, 3): if Vectores[2]==0: Aj_1["from_"]=(Vectores[1])+0.1 Aj_1["to"]=(Vectores[1]*4)-0.1 if Vectores[2]==1: Aj_2["from_"]=(Vectores[1])+0.1 Aj_2["to"]=(Vectores[1]*4)-0.1 if Vectores[2]==2: Aj_3["from_"]=(Vectores[1])+0.1 Aj_3["to"]=(Vectores[1]*4)-0.1 Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Aj_1.get(), Aj_2.get(), Aj_3.get()]) else: posx=np.empty(resolucion) posy=np.empty(resolucion) posz=np.empty(resolucion) for n in range(0, resolucion): if mani == 1: mat=Ec.Parametros(1, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None) vect_pos=Ec.Vec('C', 3, None, mat[0]) posx[n]=vect_pos[0] posy[n]=vect_pos[1] posz[n]=vect_pos[2] else: mat=Ec.Parametros(2, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None) vect_pos=Ec.Vec('C', 3, None, mat[0]) posx[n]=vect_pos[0] posy[n]=vect_pos[1] posz[n]=vect_pos[2] #Thread(target=envio_graf1(Vectores[1],Vectores[2],Vectores[3])).start() Gr1=Wd.Grafica(Fr_Graf, r'Posición $q_1$', "q[°]", 0, 0) Gr2=Wd.Grafica(Fr_Graf, r'Posición $q_2$', "q[°]", 1/3, 0) Gr3=Wd.Grafica(Fr_Graf, r'Posición $q_3$', "q[°]", 2/3, 0) Gr4=Wd.Grafica(Fr_Graf, r'Velocidad $w_1$', r'w$[rad/s]$', 0, 1/2) Gr5=Wd.Grafica(Fr_Graf, r'Velocidad $w_2$', r'w$[rad/s]$', 1/3, 1/2) Gr6=Wd.Grafica(Fr_Graf, r'Velocidad $w_3$', r'w$[rad/s]$', 2/3, 1/2) Gr1.Linea(resolucion, int(Vectores[1][0]), int(Vectores[1][-1]), int(T_f.get()), Vectores[1]) Gr2.Linea(resolucion, int(Vectores[2][0]), int(Vectores[2][-1]), int(T_f.get()), Vectores[2]) Gr3.Linea(resolucion, int(Vectores[3][0]), int(Vectores[3][-1]), int(T_f.get()), Vectores[3]) Gr4.Linea(resolucion, 0, Vectores[4][int(resolucion/2)], int(T_f.get()), Vectores[4]) Gr5.Linea(resolucion, 0, Vectores[5][int(resolucion/2)], int(T_f.get()), Vectores[5]) Gr6.Linea(resolucion, 0, Vectores[6][int(resolucion/2)], int(T_f.get()), Vectores[6]) P_xi.config(text=Pl_x.get()) P_yi.config(text=Pl_y.get()) P_zi.config(text=Pl_z.get()) Datos_Temp(P_xi.cget("text"), P_yi.cget("text"), P_zi.cget("text"), 0) Envio_Pl(Vectores[1], Vectores[2], Vectores[3]) plot_3d(posx, posy, posz) #Objetos Principales Ventana = tk.Tk() Ventana.title('Controles de Manipuladores Roboticos') width=Ventana.winfo_screenwidth() height= Ventana.winfo_screenheight() Ventana.geometry("%dx%d" % (width, height)) Panel_Pestañas = ttk.Notebook(Ventana) Panel_Pestañas.pack(fill='both',expand='yes') #Variables Nombres= tk.StringVar() #Variable String Para Nombres Nombres.set(""" Dario Delgado - 1802992 \n Brayan Ulloa - 1802861 \n Fernando Llanes - 1802878 \n Karla Baron - 1803648 \n Sebastian Niño - 1803558 """) Reposo= tk.StringVar() #Variable String Para Mensaje Reposo Reposo.set("Parte de reposo \r termina en reposo: \r Ti=0; Vi=0; Vf=0") Wd.Variables_Matrices(15, 4, 4, "DK") #Variables Matrices DK Wd.Variables_Matrices(4, 6, 3, "Jaco") #Variables Matrices Jacobianos Scara-Antropomórfico Wd.Variables_Matrices(2, 6, 6, "JacoR") #Variables Matrices Jacobianos R Estado_S=False Estado_A=False Estado_R=False Check_S_Valor=tk.BooleanVar() Check_A_Valor=tk.BooleanVar() Check_ST_Valor=tk.BooleanVar() Check_AT_Valor=tk.BooleanVar() #Pestañas Pestaña_Info=Wd.Pestañas(Panel_Pestañas, 'Portada') Pestaña_Scara=Wd.Pestañas(Panel_Pestañas, 'Robot Scara (P2R)') Pestaña_Antro3R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (3R)') Pestaña_Antro6R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (6R)') Pestaña_Trayectorias_Jacobiano=Wd.Pestañas(Panel_Pestañas, 'Trayectorias Por Jacobiano Inverso') Pestaña_Jacobianos=Wd.Pestañas(Panel_Pestañas, 'Jacobiano') Pestaña_Trayectorias=Wd.Pestañas(Panel_Pestañas, 'Planeación De Trayectorias') #Fuentes Fuente_12 = Wd.Fuentes("Lucida Grande", 12) Fuente_15 = Wd.Fuentes("Lucida Grande", 15) Fuente_25 = Wd.Fuentes("Lucida Grande", 25) Fuente_Num = Wd.Fuentes("Palatino Linotype", 18) Fuente_Num2 = Wd.Fuentes("Palatino Linotype", 12) Fuente_Slider= Wd.Fuentes("Bookman Old Style", 12) ##################################Pestaña 1######################################## Fi=Wd.Frame(Pestaña_Info, 'GUI Para Controlar Manipuladores Robóticos', Fuente_12, 1, 1, 0, 0, None) #Frame Wd.Labels(Fi, Nombres, None, None, None, None, Fuente_25, None).Ubicacion(1/2, 1/2, tk.CENTER)#Label-Nombres #Com=Wd.Boton(Fi, 20, 5, 'COM Close', None).Ubicacion(1/2, 7/8, tk.CENTER) #Imagenes Logo= Wd.Imagenes('./Imagenes/LOGOUMNG.png').zoom(2) #Logo UMNG tk.Label(Fi, image=Logo).place(relx=1/4, rely=1/2, anchor=tk.CENTER) Icono= Wd.Imagenes('./Imagenes/icon.png').zoom(2) #Icono Robot tk.Label(Fi, image=Icono).place(relx=3/4, rely=1/2, anchor=tk.CENTER) ##################################Pestaña 2######################################## Fr_DK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None) #Frame Cinematica Directa Fr_IK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa ######Cinematica Directa###### #Barra De Progreso Ba_S=Wd.Barra(Fr_IK_S, 300, 1/6, 0.98, 0.25, tk.E) #Sliders Qs1_S=Wd.Slider(Fr_DK_S, 1, 19, 1, 250, 34, 'Desplazamiento Base', Fuente_Slider, Cine_Directa, ['Eb',Ba_S]) Qs1_S.Ubicacion(0,0) Qs2_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Ebr',Ba_S]) Qs2_S.Ubicacion(0, 1/3) Qs3_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Eab',Ba_S]) Qs3_S.Ubicacion(0, 2/3) Qt1_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 0.11) Qt2_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 1/3+0.11) Qt3_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 2/3+0.11) Qt_S=[Qt1_S, Qt2_S, Qt3_S] #Matrices Wd.Matrices(Fr_DK_S, "DK", 1, 4, 4, "Link 1", 1/2, 0, Fuente_12) Wd.Matrices(Fr_DK_S, "DK", 2, 4, 4, "Link 2", 5/6, 0, Fuente_12) Wd.Matrices(Fr_DK_S, "DK", 3, 4, 4, "Link 3", 1/2, 1/2, Fuente_12) Wd.Matrices(Fr_DK_S, "DK", 4, 4, 4, "Total", 5/6, 1/2, Fuente_12) #Botones Wd.Boton(Fr_DK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE) Gp_S=Wd.Boton(Fr_DK_S, 15, 3, "Griper", "lime green", Gripper, 'E') Gp_S.Ubicacion(4/6, 0.9, tk.CENTER) Wd.Boton(Fr_DK_S, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Eb,','Ebr,','Eab,'], Qt_S, Ba_S]).Ubicacion(1/4+0.02, 0.9, tk.W) ######Cinematica Inversa###### #Sliders Py_S=Wd.Slider(Fr_IK_S, -90, 90, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['N','N']) Py_S.Ubicacion(0, 1/3) Pz_S=Wd.Slider(Fr_IK_S, 0, 190, 10, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N']) Pz_S.Ubicacion(0, 2/3) Check_S=Wd.Check(Fr_IK_S, '-', 3/16, 1/3+0.18, Cambio, 'S', Check_S_Valor) Px_S=Wd.Slider(Fr_IK_S, -101.5, 345, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01]) Px_S.Ubicacion(0, 0) #Codo Abajo Co_D_S=Wd.Frame(Fr_IK_S, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N) q1_S=tk.StringVar() q2_S_D=tk.StringVar() q3_S_D=tk.StringVar() qs_S_D=[q1_S, q2_S_D, q3_S_D] Wd.Labels(Co_D_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW) Wd.Labels(Co_D_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE) Wd.Labels(Co_D_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW) Wd.Labels(Co_D_S, q2_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE) Wd.Labels(Co_D_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW) Wd.Labels(Co_D_S, q3_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE) #Codo Arriba Co_U_S=Wd.Frame(Fr_IK_S, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N) q2_S_U=tk.StringVar() q3_S_U=tk.StringVar() qs_S_U=[q1_S, q2_S_U, q3_S_U] Wd.Labels(Co_U_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW) Wd.Labels(Co_U_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE) Wd.Labels(Co_U_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW) Wd.Labels(Co_U_S, q2_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE) Wd.Labels(Co_U_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW) Wd.Labels(Co_U_S, q3_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE) #Botones Wd.Boton(Fr_IK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE) CodoD_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_D, Ba_S]) CodoU_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_U, Ba_S]) Wd.Boton(Fr_IK_S, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['S', [CodoD_S, CodoU_S]]).Ubicacion(1/4+0.02, 1/2, tk.W) ##################################Pestaña 3######################################## Fr_DK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None) #Frame Cinematica Directa Fr_IK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa ######Cinematica Directa###### #Barra De Progreso Ba_A=Wd.Barra(Fr_IK_A, 300, 1/6, 0.98, 0.25, tk.E) #Sliders Qs1_A=Wd.Slider(Fr_DK_A, 0, 360, 10, 250, 34, 'Rotación Base', Fuente_Slider, Cine_Directa, ['Ab',Ba_A]) Qs1_A.Ubicacion(0, 0) Qs2_A=Wd.Slider(Fr_DK_A, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Aab',Ba_A]) Qs2_A.Ubicacion(0, 2/3) Qs3_A=Wd.Slider(Fr_DK_A, 0, 180, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Abr',Ba_A]) Qs3_A.Ubicacion(0, 1/3) Qt1_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 0.11) Qt2_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 1/3+0.11) Qt3_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 2/3+0.11) Qt_A=[Qt1_A, Qt2_A, Qt3_A] #Matrices Wd.Matrices(Fr_DK_A, "DK", 5, 4, 4, "Link 1", 1/2, 0, Fuente_12) Wd.Matrices(Fr_DK_A, "DK", 6, 4, 4, "Link 2", 5/6, 0, Fuente_12) Wd.Matrices(Fr_DK_A, "DK", 7, 4, 4, "Link 3", 1/2, 1/2, Fuente_12) Wd.Matrices(Fr_DK_A, "DK", 8, 4, 4, "Total", 5/6, 1/2, Fuente_12) #Botones Wd.Boton(Fr_DK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE) Gp_A=Wd.Boton(Fr_DK_A, 15, 3, "Griper", "lime green", Gripper, 'A') Gp_A.Ubicacion(4/6, 0.9, tk.CENTER) Wd.Boton(Fr_DK_A, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Ab,','Abr,','Aab,'], Qt_A, Ba_A]).Ubicacion(1/4+0.02, 0.9, tk.W) ######Cinematica Inversa###### #Sliders Pz_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N']) Pz_A.Ubicacion(0, 2/3) Check_A=Wd.Check(Fr_IK_A, 'Inf', 3/16, 2/3+0.18, Cambio, 'A2', Check_A_Valor) Py_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18]) Py_A.Ubicacion(0, 1/3) Px_A=Wd.Slider(Fr_IK_A, -197, 197, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['A1', 'I', Py_A, None, None, None]) Px_A.Ubicacion(0, 0) #Codo Abajo Co_D_A=Wd.Frame(Fr_IK_A, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N) q1_A=tk.StringVar() q2_A_D=tk.StringVar() q3_A_D=tk.StringVar() qs_A_D=[q1_A, q2_A_D, q3_A_D] Wd.Labels(Co_D_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW) Wd.Labels(Co_D_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE) Wd.Labels(Co_D_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW) Wd.Labels(Co_D_A, q2_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE) Wd.Labels(Co_D_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW) Wd.Labels(Co_D_A, q3_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE) #Codo Arriba Co_U_A=Wd.Frame(Fr_IK_A, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N) q2_A_U=tk.StringVar() q3_A_U=tk.StringVar() qs_A_U=[q1_A, q2_A_U, q3_A_U] Wd.Labels(Co_U_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW) Wd.Labels(Co_U_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE) Wd.Labels(Co_U_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW) Wd.Labels(Co_U_A, q2_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE) Wd.Labels(Co_U_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW) Wd.Labels(Co_U_A, q3_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE) #Botones Wd.Boton(Fr_IK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE) CodoD_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_D, Ba_A]) CodoU_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_U, Ba_A]) Wd.Boton(Fr_IK_A, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['A', [CodoD_A, CodoU_A]]).Ubicacion(1/4+0.02, 1/2, tk.W) ##################################Pestaña 4######################################## #Desplegable Despl_R=Wd.Desplegable(Pestaña_Antro6R, ["Cinemática Directa", "Cinemática Inversa"]) Despl_R.Ubicacion(0, 0) Despl_R.bind("<<ComboboxSelected>>",Despl_R.Cambio) Fr_DK_R=Despl_R.Frame_DK Fr_IK_R=Despl_R.Frame_IK #####Cinematica Directa###### #Barra De Progreso Ba_R=Wd.Barra(Fr_DK_R, 200, 1/15, 0.98, 3/4, tk.NE) #Sliders Qs1_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primera Base', Fuente_Slider, Cine_Directa, ['Rb1',Ba_R]) Qs1_R.Ubicacion(0, 0) Qs2_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primer Brazo', Fuente_Slider, Cine_Directa, ['Rbr1',Ba_R]) Qs2_R.Ubicacion(0, 1/6) Qs3_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segundo Brazo', Fuente_Slider, Cine_Directa, ['Rbr2',Ba_R]) Qs3_R.Ubicacion(0, 2/6) Qs4_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segunda Base', Fuente_Slider, Cine_Directa, ['Rb2',Ba_R]) Qs4_R.Ubicacion(0, 3/6) Qs5_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Rab',Ba_R]) Qs5_R.Ubicacion(0, 4/6) Qs6_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Muñeca', Fuente_Slider, Cine_Directa, ['Rm',Ba_R]) Qs6_R.Ubicacion(0, 5/6) Qt1_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 1/18+0.014) Qt2_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 4/18+0.014) Qt3_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 7/18+0.014) Qt4_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 10/18+0.014) Qt5_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 13/18+0.014) Qt6_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 16/18+0.014) Qt_R=[Qt1_R, Qt2_R, Qt3_R, Qt4_R, Qt5_R, Qt6_R] #Matrices Wd.Matrices(Fr_DK_R, "DK", 9, 4, 4, "Link 1", 1/2, 0, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 10, 4, 4, "Link 2", 5/6, 0, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 11, 4, 4, "Link 3", 1/2, 1/4, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 12, 4, 4, "Link 4", 5/6, 1/4, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 13, 4, 4, "Link 5", 1/2, 2/4, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 14, 4, 4, "Link 6", 5/6, 2/4, Fuente_12) Wd.Matrices(Fr_DK_R, "DK", 15, 4, 4, "Total", 2/3, 3/4, Fuente_12) #Botones Wd.Boton(Fr_DK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE) Gp_R=Wd.Boton(Fr_DK_R, 15, 3, "Griper", "lime green", Gripper, 'R') Gp_R.Ubicacion(7/16, 3/4+0.1, tk.N) Wd.Boton(Fr_DK_R, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Rb1,','Rbr1,','Rbr2,','Rb2,','Rab,','Rm,'], Qt_R, Ba_R]).Ubicacion(7/16, 3/4, tk.N) ######Cinematica Inversa###### #Sliders # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Px', Fuente_Slider, None, None).Ubicacion(0, 0) # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Py', Fuente_Slider, None, None).Ubicacion(0, 1/6) # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Pz', Fuente_Slider, None, None).Ubicacion(0, 2/6) # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Alfa', Fuente_Slider, None, None).Ubicacion(0, 3/6) # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Beta', Fuente_Slider, None, None).Ubicacion(0, 4/6) # Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Gamma', Fuente_Slider, None, None).Ubicacion(0, 5/6) #Botones Wd.Boton(Fr_IK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE) ##################################Pestaña 5######################################## Fr_T_J=Wd.Frame(Pestaña_Trayectorias_Jacobiano, 'Planificación de Trayectorias Por Jacobiano Inverso', Fuente_12, 1, 1, 0, 0, None) #Frame Jacobiano ##################################Pestaña 6######################################## Fr_J=Wd.Frame(Pestaña_Jacobianos, 'Jacobianos', Fuente_12, 1, 1, 0, 0, None) #Frame Jacobiano #Barra De Progreso Ba_J=Wd.Barra(Fr_J, 300, 1/15, 1/2, 1/3, tk.N) #Matrices Wd.Matrices(Fr_J, "Jaco", 1, 6, 3, "Jacobiano Scara Geométrico", 1/4, 0, Fuente_12) Wd.Matrices(Fr_J, "Jaco", 2, 6, 3, "Jacobiano Scara Analítico", 3/4, 0, Fuente_12) Wd.Matrices(Fr_J, "Jaco", 3, 6, 3, "Jacobiano Antropomórfico Geométrico", 1/4, 1/3, Fuente_12) Wd.Matrices(Fr_J, "Jaco", 4, 6, 3, "Jacobiano Antropomórfico Analítico", 3/4, 1/3, Fuente_12) Wd.Matrices(Fr_J, "JacoR", 1, 6, 6, "Jacobiano Antropomórfico 6R Geométrico", 1/4, 2/3, Fuente_12) Wd.Matrices(Fr_J, "JacoR", 2, 6, 6, "Jacobiano Antropomórfico 6R Analítico", 3/4, 2/3, Fuente_12) #Botones #Wd.Boton(Fr_J, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE) Wd.Boton(Fr_J, 15, 3, "Mostrar", "dim gray", Jacobians, Ba_J).Ubicacion(1/2, 1/2, tk.N) ##################################Pestaña 7######################################## Fr_T=Wd.Frame(Pestaña_Trayectorias, 'Datos de Entrada', Fuente_12, 1, 1/4, 0, 0, None) #Frame Datos Trayectorias #Desplegables Despl_Mani=Wd.Desplegable(Fr_T, ["Scara (PRR)", "Antropomórfico (RRR)"]) Despl_Mani.Ubicacion(0, 0) Despl_Mani.bind("<<ComboboxSelected>>",Show_Sliders) Despl_Codo=Wd.Desplegable(Fr_T, ["Codo Arriba", "Codo Abajo"]) Despl_Codo.bind("<<ComboboxSelected>>",Show_Perfiles) #Label Información Importante (Parte de Reposo) Wd.Labels(Fr_T, Reposo, None, 1, "solid", None, Fuente_15, None).Ubicacion(4/16, 0, None) #Puntos Iniciales-Finales #Labels P_xi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None) P_yi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None) P_zi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None) P_x= Wd.Labels(Fr_T, None, "Px", None, None, None, None, None) P_y= Wd.Labels(Fr_T, None, "Py", None, None, None, None, None) P_z= Wd.Labels(Fr_T, None, "Pz", None, None, None, None, None) #Buttons Tipo=tk.IntVar() Cuadratico=Wd.Radio(Fr_T, "Perfil Cuadrático", Fuente_12, 1, Tipo, 15, Show_Datos) TrapezoidalI=Wd.Radio(Fr_T, "Perfil Trapezoidal I", Fuente_12, 2, Tipo, 15, Show_Datos) TrapezoidalII=Wd.Radio(Fr_T, "Perfil Trapezoidal II", Fuente_12, 3, Tipo, 15, Show_Datos) Calcular_PT=Wd.Boton(Fr_T, 12, None, "Calcular", "dim gray", But_Perfiles, None) #Wd.Boton(Fr_T, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE) #Barra De Progreso Br_Pl=Wd.Barra(Fr_T, 150, 1/8, 5/16, 1, tk.S) #Sliders Check_S_PL=Wd.Check(Fr_T, '-', 1/4-0.025, 1/3+0.22, Cambio, 'ST', Check_ST_Valor) Check_A_PL=Wd.Check(Fr_T, 'Inf', 1/4-0.025, 2/3+0.15, Cambio, 'AT', Check_AT_Valor) Pl_x=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A1') Pl_y=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A2') Pl_z=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Show_Codo, None) T_f=Wd.Slider(Fr_T, 15, 40, 1, 180, 20, None, None, Show_Graficas, None) N_p=Wd.Slider(Fr_T, 10, 100, 10, 180, 20, None, None, Show_Graficas, None) Vj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) Vj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) Vj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) Aj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) Aj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) Aj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None) # #Titulos P_inicial=Wd.Labels(Fr_T, None, "Puntos Iniciales", None, None, 12, Fuente_Num2, None) P_final=Wd.Labels(Fr_T, None, "Puntos Finales", None, None, 12, Fuente_Num2, None) T_Codo=Wd.Labels(Fr_T, None, "Elección Codo", None, None, 12, Fuente_Num2, None) TT_f=Wd.Labels(Fr_T, None, "Tf", None, None, None, Fuente_Num2, None) TN_p=Wd.Labels(Fr_T, None, "Np", None, None, None, Fuente_Num2, None) TVc_1=Wd.Labels(Fr_T, None, "Vc1", None, None, None, Fuente_Num2, None) TVc_2=Wd.Labels(Fr_T, None, "Vc2", None, None, None, Fuente_Num2, None) TVc_3=Wd.Labels(Fr_T, None, "Vc3", None, None, None, Fuente_Num2, None) TAc_1=Wd.Labels(Fr_T, None, "Ac1", None, None, None, Fuente_Num2, None) TAc_2=Wd.Labels(Fr_T, None, "Ac2", None, None, None, Fuente_Num2, None) TAc_3=Wd.Labels(Fr_T, None, "Ac3", None, None, None, Fuente_Num2, None) Fr_Graf=Wd.Frame(Pestaña_Trayectorias, 'Gráficas', Fuente_12, 1, 3/4, 0, 1/4, None) #Frame Graficas #Ventana.attributes('-fullscreen',True) Ventana.mainloop()
daridel99/UMNG-robotica
Interfaz.py
Interfaz.py
py
39,199
python
es
code
0
github-code
6
2418871084
import torch import numpy as np from copy import deepcopy from typing import List, Optional, Tuple from torch.utils.data import DataLoader from supervised.utils import ids, keys, typeddicts from supervised import saving, data, networks VERBOSE = False # Default: whether the code output should be verbose NR_EPOCHS = 50 # Default max number of epochs for training in case of no early stopping EARLY_STOPPING_PATIENCE = 5 # Number of epochs to be patient before early stopping the training def train_epoch_multi_readout(model: networks.classes.MultitaskLearner, data_loader: DataLoader, optimizer: torch.optim.Optimizer, track_pmdd: Optional[bool] = False, training_tracker: Optional[typeddicts.TrackingOutcome] = None, train_params: Optional[typeddicts.TrainParameters] = None, pmdd_dataset: Optional[data.load.DatasetType] = None, validation_dl: Optional[typeddicts.DL] = None ) -> Tuple[List[float], typeddicts.TrackingOutcome]: # List to store the train loss for each batch loss_list = [] for batch_idx, ((data_batch, _), (task, targets)) in enumerate(data_loader): optimizer.zero_grad() out = model.forward(data_batch) if len(model.rbs) != 1: out = torch.gather(out, 0, torch.add(task.view(1, -1), train_params[keys.K_FIRST_TASK_ID])).reshape(-1) loss = networks.evaluate.mse_loss(out, targets) loss.backward() optimizer.step() loss_list += [float(loss.detach())] if track_pmdd: if (batch_idx + 1) in networks.evaluate.PMDD_TRACK_BATCHES: training_tracker = networks.evaluate.track_network(model=model, pmdd_dataset=pmdd_dataset, training_tracker=training_tracker, train_loss=loss_list[-1], validation_dl=validation_dl, train_params=train_params) return loss_list, training_tracker def train_epoch_context_learner(model: networks.classes.MultitaskLearner, data_loader: DataLoader, optimizer: torch.optim.Optimizer, track_pmdd: Optional[bool] = False, training_tracker: Optional[typeddicts.TrackingOutcome] = None, train_params: Optional[typeddicts.TrainParameters] = None, pmdd_dataset: Optional[data.load.DatasetType] = None, validation_dl: Optional[typeddicts.DL] = None ) -> Tuple[List[float], typeddicts.TrackingOutcome]: # List to store the train loss for each batch loss_list = [] # Train one batch at a time for batch_idx, ((data_batch, _), (tasks, targets)) in enumerate(data_loader): optimizer.zero_grad() out = model.forward(data_batch, tasks + train_params[keys.K_FIRST_TASK_ID]).reshape(-1) loss = networks.evaluate.mse_loss(out, targets) loss_list += [float(loss.detach())] loss.backward() optimizer.step() # Track pmdd loss, validation performance & train loss if track_pmdd: if (batch_idx + 1) in networks.evaluate.PMDD_TRACK_BATCHES: training_tracker = networks.evaluate.track_network(model=model, pmdd_dataset=pmdd_dataset, training_tracker=training_tracker, train_loss=loss_list[-1], validation_dl=validation_dl, train_params=train_params) return loss_list, training_tracker def train_epoch(model: networks.classes.MultitaskLearner, data_loader: DataLoader, optimizer: torch.optim.Optimizer, prog_params: typeddicts.ProgramParameters, train_params: typeddicts.TrainParameters, save_params: typeddicts.SavingParameters, pmdd_dataset: data.load.DatasetType, validation_dl: Optional[typeddicts.DL] = None, track_pmdd: Optional[bool] = False) -> List[float]: # Initialize the tracker for pmdd loss, validation performance & train loss to a database if track_pmdd: assert validation_dl is not None training_tracker = networks.evaluate.init_track_network(model=model, train_params=train_params, pmdd_dataset=pmdd_dataset, validation_dl=validation_dl) else: training_tracker = None # Train for one epoch if prog_params[keys.K_MODEL_ID] == ids.ID_MULTI_READOUT: loss_list, training_tracker = train_epoch_multi_readout( model=model, data_loader=data_loader, optimizer=optimizer, track_pmdd=track_pmdd, train_params=train_params, training_tracker=training_tracker, pmdd_dataset=pmdd_dataset, validation_dl=validation_dl) else: loss_list, training_tracker = train_epoch_context_learner( model=model, data_loader=data_loader, optimizer=optimizer, track_pmdd=track_pmdd, train_params=train_params, pmdd_dataset=pmdd_dataset, validation_dl=validation_dl) # Save the tracked pmdd loss, validation performance & train loss to a database if track_pmdd: saving.save.save_first_epoch_batches_pmdd(prog_params=prog_params, train_params=train_params, save_params=save_params, tracked_pmdd_batches=training_tracker) return loss_list def train_model(model: networks.classes.MultitaskLearner, train_data: data.datasets.KTaskNClassMDatasetData, validation_data: data.datasets.KTaskNClassMDatasetData, optimizer: torch.optim.Optimizer, prog_params: typeddicts.ProgramParameters, train_params: typeddicts.TrainParameters, save_params: typeddicts.SavingParameters, verbose: Optional[bool] = VERBOSE ) -> Tuple[networks.classes.MultitaskLearner, typeddicts.PerformanceOutcome]: # Prepare to evaluate best time to stop training validation_data_loader, nr_samples = data.load.get_dataloader(validation_data) validation_dl: typeddicts.DL = {keys.K_NUMBER_SAMPLES: nr_samples, keys.K_VALIDATION_DATALOADER: validation_data_loader} best_model = deepcopy(model) best_validation_performance = -1. best_validation_loss = -1. stagnation_counter = 0 training_tracker = None if save_params[keys.K_SAVE_PMDD_LOSS]: if save_params[keys.K_PMDD_LOSS_TRACK_DATASET] in [ids.ID_EMNIST, ids.ID_K49, ids.ID_CIFAR100]: track_dataset = data.load.get_dataset(save_params[keys.K_PMDD_LOSS_TRACK_DATASET], False).data.reshape( [-1, data.datasets.n_input_dimension(save_params[keys.K_PMDD_LOSS_TRACK_DATASET])]) else: raise NotImplementedError(f"{save_params[keys.K_PMDD_LOSS_TRACK_DATASET]} track pmdd loss") if save_params[keys.K_SAVE_PMDD_LOSS] is not None: training_tracker = {keys.K_TRACKED_TRAIN_LOSS: [], keys.K_TRACKED_VALIDATION_PERFORMANCE: [], keys.K_TRACKED_PMDD_LOSS: []} pmdd_loss = networks.evaluate.get_pmdd_loss(dataset=track_dataset, weights=np.transpose(model.ws[0].detach().numpy())) training_tracker[keys.K_TRACKED_PMDD_LOSS] += [pmdd_loss] print(f"Epoch 0 had pmdd L2 {pmdd_loss}") else: track_dataset = None # Train epochs until performance stops to improve for epoch in range(1, NR_EPOCHS + 1): data_loader = DataLoader(train_data, batch_size=train_params[keys.K_BATCH_SIZE], shuffle=True) # Train for one epoch if epoch == 1: train_loss = train_epoch(model=model, data_loader=data_loader, optimizer=optimizer, prog_params=prog_params, train_params=train_params, save_params=save_params, pmdd_dataset=track_dataset, validation_dl=validation_dl, track_pmdd=save_params[keys.K_SAVE_PMDD_LOSS]) else: train_loss = train_epoch(model=model, data_loader=data_loader, optimizer=optimizer, prog_params=prog_params, train_params=train_params, save_params=save_params, pmdd_dataset=track_dataset) # Evaluate model performance on validation dataset validation_performance, validation_loss = networks.evaluate.evaluate_performance( model_id=prog_params[keys.K_MODEL_ID], model=model, dataset=validation_data_loader, nr_samples=nr_samples, task_id0=train_params[keys.K_FIRST_TASK_ID]) if verbose: print(f"Epoch {epoch} had training loss {train_loss} and validation performance {validation_performance}%") if save_params[keys.K_SAVE_PMDD_LOSS]: training_tracker[keys.K_TRACKED_TRAIN_LOSS] += [train_loss] training_tracker[keys.K_TRACKED_VALIDATION_PERFORMANCE] += [validation_performance] pmdd_loss = networks.evaluate.get_pmdd_loss(dataset=track_dataset, weights=np.transpose(model.ws[0].detach().numpy())) training_tracker[keys.K_TRACKED_PMDD_LOSS] += [pmdd_loss] print(f"Epoch {epoch} had " f"training loss {sum(train_loss)}, " f"validation performance {validation_performance}% and " f"pmdd L2 {pmdd_loss}") # Check whether performance is still improving and stop training otherwise if validation_performance > best_validation_performance: stagnation_counter = 0 best_validation_performance = validation_performance best_validation_loss = validation_loss best_model = deepcopy(model) else: stagnation_counter += 1 if stagnation_counter >= EARLY_STOPPING_PATIENCE: if verbose: print(f"Early stopping training at epoch {epoch} " f"with validation performance of {best_validation_performance}%") break # Save the pmdd, train and validation losses during training epochs (if the saving parameters require it) saving.save.save_train_epochs_pmdd(prog_params=prog_params, train_params=train_params, save_params=save_params, tracked_pmdd_epochs=training_tracker) # Evaluate training performance train_performance, train_loss = networks.evaluate.evaluate_performance(model_id=prog_params[keys.K_MODEL_ID], model=best_model, dataset=train_data, task_id0=train_params[keys.K_FIRST_TASK_ID]) outcome: typeddicts.PerformanceOutcome = {keys.K_TRAIN_PERFORMANCE: train_performance, keys.K_TRAIN_LOSS: train_loss, keys.K_VALIDATION_PERFORMANCE: best_validation_performance, keys.K_VALIDATION_LOSS: best_validation_loss} return best_model, outcome def get_optimizer(training_type: str, model: networks.classes.MultitaskLearner, train_params: typeddicts.TrainParameters ) -> torch.optim.Optimizer: parameters = None optimizer = None # Train both shared and contextual parameters if ids.ID_TRAIN in training_type: lr = train_params[keys.K_SHARED_PARAM_LEARNING_RATE] if ids.ID_SINGLE_TASK in training_type: optimizer = torch.optim.Adam(model.parameters(), lr) elif ids.ID_CONTEXT_B_SHARED_W in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_G_SHARED_BW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs}, {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_G_SHARED_XW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_G_SHARED_BXW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.bs}, {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_BG_SHARED_W in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}, {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_M_SHARED_BW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs}, {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_M_SHARED_XW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_M_SHARED_BXW in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.bs}, {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) elif ids.ID_CONTEXT_BM_SHARED_W in training_type: optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}, {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) # Train multiple labels with individual readout neurons each all at the same time elif ids.ID_MULTI_READOUT in training_type: optimizer = torch.optim.Adam([{"params": [w for w in model.ws] + [b for b in model.bs]}, {"params": [r for r in model.rs] + [rb for rb in model.rbs], "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr) # Train only contextual parameters elif ids.ID_TRANSFER in training_type: lr = train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE] if "deepen" in training_type: if ids.ID_CONTEXT_B_SHARED_W in training_type: optimizer = torch.optim.Adam([{"params": model.ws[1:]}, {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], train_params[keys.K_SHARED_PARAM_LEARNING_RATE]) else: raise NotImplementedError elif ids.ID_CONTEXT_B_SHARED_W in training_type: parameters = model.bs elif ids.ID_CONTEXT_BG_SHARED_W in training_type: optimizer = torch.optim.Adam([{"params": model.bs, "lr": lr}, {"params": model.gs, "lr": lr}], lr) elif ids.ID_CONTEXT_G_SHARED_BW in training_type or ids.ID_CONTEXT_G_SHARED_XW in training_type \ or ids.ID_CONTEXT_G_SHARED_BXW in training_type: parameters = model.gs # Train only readout neurons on top of a fixed trunk elif ids.ID_MULTI_READOUT in training_type: parameters = [r for r in model.rs] + [rb for rb in model.rbs] else: raise ValueError(training_type) if optimizer is None: optimizer = torch.optim.Adam(parameters, lr) return optimizer
doggydigit/Biasadaptation-jureca
supervised/simulate/train.py
train.py
py
17,379
python
en
code
0
github-code
6
43623562044
#Micah lee 03/12/18 media_type = input("what is the media type? ") title = input("what is the title ") des = input("give me a brief description ") yr = str(input("what year was it created ")) rating = float(input(" what rating would you give this media type (1/10) " )) new_list = [ title, des, yr, rating ] if media_type == "Book": print (new_list) elif media_type == "movies": print (new_list)
MicLee52/Micah-Lee
micah_lee-assign01.py
micah_lee-assign01.py
py
414
python
en
code
1
github-code
6
73549603388
''' Slakeys Surf Alert Add Users with the argument "add" "user name * email * surf spot name * surf spot url" Run with the argument "run" ''' import sys from SurfAlertUtils import * if __name__ == "__main__": args = sys.argv args.pop(0) if len(args) == 0: print("Welcome to Slakey\'s Surf Alert. If you have not added a user, please input \"add\" \"user\" \"email\" \"surfspot\" \"url\". If you want to run just input \"run\"") elif args[0] == "run": run() elif args[0] == "add": adduser(args[1:])
aslakey/SlakeysSurfAlert
surfalert.py
surfalert.py
py
514
python
en
code
0
github-code
6
508734253
from itertools import permutations import cProfile # #make permutation of array # list = [1,2,3,4] listPermutations = permutations(list) for permutation in listPermutations: print(permutation) # #count number of permutations # listPermutations = permutations(list) count = 0 for permutation in listPermutations: count += 1 print(len(list), count) # #check the performance and undestand # how fast the space of permutations grows # def faculty(n): if n <= 1: return n else: return faculty(n-1)+n def counter(n): count = 0 for i in range(n): count += 1 return count cProfile.run("counter(faculty(10))")
sleevs/JSNSecurity
Permutations.py
Permutations.py
py
695
python
en
code
0
github-code
6
71811420988
#!/usr/bin/env python # -*- coding:utf-8 -*- """code_info @Time : 2020 2020/7/9 13:15 @Author : Blanc @File : double_color_ball.py """ # 程序运行之后,从1‐64中挑选5个数作为彩票的抽奖结果 import random a = list() for i in range(0, 5): b = random.randint(1, 64) a.append(b) print('双色球号开奖:', a)
Flynn-Lu/PythonCode
2020python实训/Day7/double_color_ball.py
double_color_ball.py
py
361
python
en
code
0
github-code
6
24794059633
#!/usr/bin/env python3 # import sys, argparse import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True def h2pgf(h): """ Convert TH1 into pgfplot data with error bars input: xmin xmax y ey output: x ex y ey ex = (xmax+xmin)/2 """ nbins = h.GetNbinsX() # print("# \\begin{axis}") # print("# \\addplot[const plot mark mid, black, solid, no markers, error bars/.cd, y dir=both, y explicit, error mark=none]") # print(" coordinates {") print("x ex y ey") for b in range(1, nbins+1): x = h.GetBinCenter(b) ex = h.GetBinWidth(b)/2.0 y = h.GetBinContent(b) ey = h.GetBinError(b) # print(x,ex,y,ey) if y>0.0: print(x, ex, y, ey) def g2pgf(h): """ Convert TGraph into pgfplot data """ N = h.GetN() print("\\begin{axis}") print("\\addplot[ultra thick]") print(" coordinates {") print("x ex y ey") for b in range(N): x = h.GetX()[b] y = h.GetY()[b] print(x, y) print("};") print("\\addlegendentry{TGraph};") def main(): """ A script to convert TH1 and TGraph into a pgfplot format """ parser = argparse.ArgumentParser(description=main.__doc__, epilog='Homepage: https://github.com/kbat/mc-tools') parser.add_argument('root', type=str, help='ROOT file') parser.add_argument('hist', type=str, help='histogram name') args = parser.parse_args() f = ROOT.TFile(args.root) f.ls() h = f.Get(args.hist) if h.InheritsFrom("TH1"): h2pgf(h) elif h.InheritsFrom("TGraph"): g2pgf(h) if __name__ == "__main__": sys.exit(main())
kbat/mc-tools
mctools/common/root2pgf.py
root2pgf.py
py
1,629
python
en
code
38
github-code
6
22117461324
import rospy from MyStatics.RealTimePlotter import RealTimePlotter from MyStatics.GaussianPlotter import GaussPlot from FaultDetection import ChangeDetection from geometry_msgs.msg import AccelStamped from dynamic_reconfigure.server import Server from accelerometer_ros.cfg import accelerometerGaussConfig import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt class AccGaussCUSUM(RealTimePlotter,ChangeDetection,GaussPlot): def __init__(self, max_samples = 500, pace = 2, cusum_window_size = 10 ): self.data_ = [] self.data_.append([0,0,0]) self.i = 0 self.msg = 0 self.window_size = cusum_window_size RealTimePlotter.__init__(self,max_samples,pace) ChangeDetection.__init__(self,3) GaussPlot.__init__(self ) rospy.init_node("accelerometer_gauss_cusum", anonymous=True) rospy.Subscriber("accel", AccelStamped, self.accCB) self.dyn_reconfigure_srv = Server(accelerometerGaussConfig, self.dynamic_reconfigureCB) plt.legend() plt.show() rospy.spin() plt.close("all") def dynamic_reconfigureCB(self,config, level): self.window_size = config["window_size"] return config def accCB(self, msg): while (self.i< self.window_size): self.addData([msg.accel.linear.x,msg.accel.linear.y, msg.accel.angular.z]) self.i = self.i+1 if len(self.samples) is self.max_samples: self.samples.pop(0) return self.i=0 self.changeDetection(len(self.samples)) cur = np.array(self.cum_sum, dtype = object) self.call(np.mean(self.samples, axis=0),np.var(self.samples, axis=0)) """ THIS IS NOT REALLY WORKING x1 = np.linspace(-140, 140, len(self.s_z)) print(len(x1), len(np.sort(self.s_z))) plt.scatter([x1,x1,x1],np.sort(self.s_z)) """ x = np.linspace(-140, 140, 200) y = np.array([i.pdf(x) for i in self.rv]) self.update(msg.header.seq,x.tolist(),y.T.tolist())
jcmayoral/collision_detector_observers
collision_observers/accelerometer/accelerometer_ros/src/fault_detection/AccGaussCUSUM.py
AccGaussCUSUM.py
py
2,101
python
en
code
0
github-code
6
70879484348
import collections import functools from operator import mul def tokenize(s: str): tokens = [] words = s.strip().split() for word in words: if word.startswith("("): tokens.append(word[0]) tokens.extend(tokenize(word[1:])) elif word.endswith(")"): tokens.extend(tokenize(word[:-1])) tokens.append(word[-1]) elif word in "+*": tokens.append(word) else: tokens.append(int(word)) return tokens def weird_math_a_helper(tokens): ans = None op = None while len(tokens) > 0: token = tokens.popleft() if token == ")": break elif token in ("*", "+"): op = token else: n = weird_math_a_helper(tokens) if token == "(" else token if ans is None: ans = n elif op == "+": ans += n elif op == "*": ans *= n return ans def weird_math_a(problem): return weird_math_a_helper(collections.deque(tokenize(problem))) def weird_math_b_helper(tokens): sums = [] ans = None op = None while len(tokens) > 0: token = tokens.popleft() if token == ")": break elif token == "*": sums.append(ans) ans = None op = None elif token == "+": op = token else: n = weird_math_b_helper(tokens) if token == "(" else token if ans is None: ans = n elif op == "+": ans += n sums.append(ans) return functools.reduce(mul, sums, 1) def weird_math_b(problem): return weird_math_b_helper(collections.deque(tokenize(problem))) def parta(txt): return sum(weird_math_a(line) for line in txt.splitlines()) def partb(txt): return sum(weird_math_b(line) for line in txt.splitlines()) if __name__ == "__main__": from aocd import data print(f"parta: {parta(data)}") print(f"partb: {partb(data)}")
cj81499/advent-of-code
src/aoc_cj/aoc2020/day18.py
day18.py
py
2,065
python
en
code
2
github-code
6
74472010426
import unittest from car_simulation import Car, Field, main from unittest.mock import patch from io import StringIO class TestCar(unittest.TestCase): def test_change_direction(self): car = Car("TestCar", 0, 0, "N", "F") car.change_direction("R") self.assertEqual(car.direction, "E") def test_move_within_field(self): field = Field(5, 5) car = Car("TestCar", 2, 2, "N", "F") car.move(field) self.assertEqual((car.x, car.y), (2, 3)) def test_move_out_of_bounds(self): field = Field(5, 5) car = Car("TestCar", 4, 4, "E", "F") car.move(field) self.assertEqual((car.x, car.y), (4, 4)) # Should not move out of bounds def test_execute_commands(self): field = Field(5, 5) car = Car("TestCar", 0, 0, "N", "F") car.execute_commands(field) self.assertEqual(car.direction, "N") self.assertEqual((car.x, car.y), (0, 1)) def test_execute_empty_commands(self): field = Field(5, 5) car = Car("TestCar", 0, 0, "N", "") car.execute_commands(field) self.assertEqual((car.x, car.y), (0, 0)) # Should not move with empty commands def test_get_status(self): car = Car("TestCar", 3, 3, "W", "FFL") status = car.get_status() self.assertEqual(status, "TestCar, (3, 3) W, FFL") def test_collide(self): car = Car("TestCar", 2, 2, "S", "F") car.collid(1, "AnotherCar") self.assertTrue(car.collided) self.assertEqual(car.step, 1) self.assertEqual(car.collided_with, "AnotherCar") class TestField(unittest.TestCase): def test_add_car_within_field(self): field = Field(5, 5) car = Car("TestCar", 1, 1, "N", "F") field.add_car(car) self.assertIn(car, field.cars) def test_add_car_out_of_bounds(self): field = Field(5, 5) car = Car("TestCar", 6, 6, "N", "F") field.add_car(car) self.assertNotIn(car, field.cars) def test_add_car_collision(self): field = Field(5, 5) car1 = Car("Car1", 2, 2, "N", "F") car2 = Car("Car2", 2, 2, "S", "F") field.add_car(car1) field.add_car(car2) self.assertNotIn(car2, field.cars) # Car2 should not be added due to collision def test_is_within_field(self): field = Field(5, 5) self.assertTrue(field.is_within_field(2, 3)) self.assertFalse(field.is_within_field(6, 6)) class TestCarSimulation(unittest.TestCase): @patch("builtins.input", side_effect=["10 10", "1", "A", "1 2 N", "FFRFFFFRRL", "2", "2"]) def test_simulation_with_single_car(self, mock_input): with patch("sys.stdout", new_callable=StringIO) as mock_stdout: main() output = mock_stdout.getvalue().strip() self.assertIn("Your current list of cars are:", output) self.assertIn("- A, (1, 2) N, FFRFFFFRRL", output) self.assertIn("After simulation, the result is:", output) self.assertIn("- A, (5, 4) S", output) @patch("builtins.input", side_effect=["10 10", "1", "A", "1 2 N", "FFRFFFFRRL", "1", "B", "7 8 W", "FFLFFFFFFF", "2", "2"]) def test_simulation_with_multiple_car(self, mock_input): with patch("sys.stdout", new_callable=StringIO) as mock_stdout: main() output = mock_stdout.getvalue().strip() self.assertIn("Your current list of cars are:", output) self.assertIn("- A, (1, 2) N, FFRFFFFRRL", output) self.assertIn("- B, (7, 8) W, FFLFFFFFFF", output) self.assertIn("After simulation, the result is:", output) self.assertIn("- A, collides with B at (5, 4) at step 7", output) self.assertIn("- B, collides with A at (5, 4) at step 7", output) if __name__ == "__main__": unittest.main()
LiSheng-Chris/car-simulation
car_simulation_test.py
car_simulation_test.py
py
3,835
python
en
code
0
github-code
6
12258821097
import math import random import time import carla import cv2 import numpy as np actor_list = [] def pure_pursuit(tar_location, v_transform): L = 2.875 yaw = v_transform.rotation.yaw * (math.pi / 180) x = v_transform.location.x - L / 2 * math.cos(yaw) y = v_transform.location.y - L / 2 * math.sin(yaw) dx = tar_location.x - x dy = tar_location.y - y ld = math.sqrt(dx ** 2 + dy ** 2) alpha = math.atan2(dy, dx) - yaw delta = math.atan(2 * math.sin(alpha) * L / ld) * 180 / math.pi steer = delta/90 if steer > 1: steer = 1 elif steer < -1: steer = -1 return steer def img_process(data): img = np.array(data.raw_data) img = img.reshape((1080, 1920, 4)) img = img[:, :, :3] cv2.imwrite('car.png', img) # cv2.imshow('', img) # cv2.waitKey(1) pass def callback(event): print("碰撞") def callback2(event): print("穿越车道") try: client = carla.Client('localhost', 2000) client.set_timeout(5.0) world = client.get_world() map = world.get_map() blueprint_library = world.get_blueprint_library() v_bp = blueprint_library.filter("model3")[0] spawn_point = random.choice(world.get_map().get_spawn_points()) vehicle = world.spawn_actor(v_bp, spawn_point) actor_list.append(vehicle) # Find the blueprint of the sensor. blueprint = blueprint_library.find('sensor.camera.rgb') # Modify the attributes of the blueprint to set image resolution and field of view. blueprint.set_attribute('image_size_x', '1920') blueprint.set_attribute('image_size_y', '1080') blueprint.set_attribute('fov', '110') # Set the time in seconds between sensor captures blueprint.set_attribute('sensor_tick', '1.0') transform = carla.Transform(carla.Location(x=0.8, z=1.7)) sensor = world.spawn_actor(blueprint, transform, attach_to=vehicle) actor_list.append(sensor) sensor.listen(lambda data: img_process(data)) blueprint_collision = blueprint_library.find('sensor.other.collision') transform = carla.Transform(carla.Location(x=0.8, z=1.7)) sensor_collision = world.spawn_actor(blueprint_collision, transform, attach_to=vehicle) actor_list.append(sensor_collision) sensor_collision.listen(callback) blueprint_lane_invasion = blueprint_library.find('sensor.other.lane_invasion') transform = carla.Transform(carla.Location(x=0.8, z=1.7)) sensor_lane_invasion = world.spawn_actor(blueprint_lane_invasion, transform, attach_to=vehicle) actor_list.append(sensor_lane_invasion) sensor_lane_invasion.listen(callback2) vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0)) while True: waypoint01 = map.get_waypoint(vehicle.get_location(), project_to_road=True, lane_type=(carla.LaneType.Driving | carla.LaneType.Sidewalk)) v_trans = vehicle.get_transform() waypoints = waypoint01.next(8.0) waypoint02 = waypoints[0] tar_loc = waypoint02.transform.location steer = pure_pursuit(tar_loc, v_trans) vehicle.apply_control(carla.VehicleControl(throttle=0.6, steer=steer)) time.sleep(0.02) finally: for actor in actor_list: actor.destroy() print("结束")
DYSfu/Carla_demo
demo3.py
demo3.py
py
3,290
python
en
code
4
github-code
6
75235905147
from v_model import * aho=visual.box() par=visual.box() par.color=visual.color.red baka=V_PartsObject(FRAME()) baka.set_shape(aho) pa=FRAME(xyzabc=[0,0,0,pi/4,0,0]) pb=FRAME(xyzabc=[0,0,0,0,pi/4,0]) pc=FRAME(xyzabc=[0,0,0,0,0,pi/4]) pe=FRAME(xyzabc=[1,0,0,0,pi/4,0,0]) pf=FRAME(xyzabc=[0,1,0,0,0,0])
hsnuhayato/iv-plan-hironx
rmrc_geo_model/src/model/test.py
test.py
py
300
python
en
code
0
github-code
6
19399824149
from typing import List # 438. 找到字符串中所有字母异位词 # https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/ class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: p_vec = self.to_vector(p) s_vec = self.to_vector(s[0: len(p) - 1]) # print(s_vec, p_vec) i = 0 ans = [] for j in range(len(p) - 1, len(s)): s_vec[ord(s[j]) - ord('a')] += 1 if p_vec == s_vec: # print(i) ans.append(i) s_vec[ord(s[i]) - ord('a')] -= 1 i += 1 return ans # 用不到 def compare(self, p_vec, word): d = dict() for i, c in enumerate(word): if c in d: d[c] += 1 else: d[c] = 1 if c not in p_vec: return False, i + 1 elif d[c] > p_vec[c]: return False, 1 return p_vec == d, 1 def to_vector(self, word): # d = dict() # for each in word: # if each in d: # d[each] += 1 # else: # d[each] = 1 # return d vec = [0] * 26 for each in word: vec[ord(each) - ord('a')] += 1 return vec s = "abab" p = "ab" print(s) r = Solution().findAnagrams(s, p) print(r)
Yigang0622/LeetCode
findAnagrams.py
findAnagrams.py
py
1,375
python
en
code
1
github-code
6
4552159327
import random import sys sys.path.insert(1, '../') from utils import read_instance, objetive_function, corrent_solution_size import config # Heurística Construtiva 02 # Constructive Heuristic 02 # Random para selecionar o teste e calculado a melhor mesa para aplicá-lo def constructive_heuristic_02(corrent_size): def validade_best_desk(solution, idx): # idx = test number / index iteration_value = 100000 iteration_solution = solution.copy() for i in range(0, desk_count): current_solution = solution.copy() if solution[i] == 0: # Não sobrescrever casos já alocados current_solution[i] = idx current_value = objetive_function(current_solution) if current_value < iteration_value: iteration_value = current_value iteration_solution = current_solution.copy() return iteration_solution, iteration_value desks, tests, empty = config.desks, config.tests, config.empty desk_count = len(desks) test_count = len(tests) s = [0 for _ in range(desk_count)] best_value = 0 desk_with_test = 0 while desk_with_test < (desk_count): sort_list = [i for i in range(1, test_count)] idx = random.choice(sort_list) s, best_value = validade_best_desk(s, idx) desk_with_test += 1 if corrent_size: s, best_value = corrent_solution_size(s, empty) return s, best_value if __name__ == '__main__': file_name = sys.argv[1] read_instance(file_name) response_solution, objetive = constructive_heuristic_02(True) print() print(response_solution) print(objetive)
guilhermelange/Test-Assignment-Problem
stage_01/constructive_heuristic_02.py
constructive_heuristic_02.py
py
1,701
python
en
code
0
github-code
6
9401341695
# coding: utf-8 import re import requests response = requests.get('http://ads.fraiburgo.ifc.edu.br') if response.status_code == 200: texto = response.content.decode('utf-8') links = re.findall(r'<a href="(.*?)".*>(.*)</a>', texto) for url in links: print(url)
fabricioifc/python_regex_tarefa
exemplos_professor/regex_02.py
regex_02.py
py
266
python
en
code
1
github-code
6
74548599546
import boto3 from botocore.exceptions import NoCredentialsError def upload_to_aws(local_file, bucket, s3_file): s3 = boto3.client('s3') try: s3.upload_file(local_file, bucket, s3_file) print("Upload Successful") return True except FileNotFoundError: print("The file was not found") return False except NoCredentialsError: print("Credentials not available") return False if __name__ == "__main__": uploaded = upload_to_aws('Screenshot (288).png', 'group-6-marxel-pictures', 'test.png')
HULKMARXEL/Group_6_AWS_project
localhost/S3.py
S3.py
py
562
python
en
code
0
github-code
6
32693295741
class man(object): # name of the man name = "" def __init__(self, P_name): """ Class constructor """ self.name = P_name print("Here comes " + self.name) def talk(self, P_message): print(self.name + " says: '" + P_message + "'") def walk(self): """ This let an instance of a man to walk """ print(self.name + " walks") # This class inherits from Man class # A superman has all the powers of a man (A.K.A. Methods and Properties in our case ;-) class superman(man): # Name of his secret identity secret_identity = "" def __init__(self, P_name, P_secret_identity): """ Class constructor that overrides its parent class constructor""" # Invokes the class constructor of the parent class # super(superman, self).__init__(P_name) # Now let's add a secret identity self.secret_identity = P_secret_identity print("...but his secret identity is '" + self.secret_identity + "' and he's a super-hero!") def walk(self, P_super_speed = False): # Overrides the normal walk, because a superman can walk at a normal # pace or run at the speed of light! if (not P_super_speed): super(superman, self).walk() else: print(self.secret_identity + " run at the speed of light") def fly(self): """ This let an instance of a superman to fly """ # No man can do this! print(self.secret_identity + " fly up in the sky") def x_ray(self): """ This let an instance of a superman to use his x-ray vision """ # No man can do this! print(self.secret_identity + " uses his x-ray vision") # Declare some instances of man and superman lois = man("Lois Lane") jimmy = man("Jimmy Olsen") clark = superman("Clark Kent", "Superman") # Let's puth them into action! print("\n--> Let's see what a man can do:\n") jimmy.walk() lois.talk("Oh no, we're in danger!") print("\n--> Let's see what a superman can do:\n") clark.walk() clark.talk("This is a job for SUPERMAN!") clark.walk(True) clark.fly() clark.x_ray()
code4ghana/randomPrograms
PythonPrograms/testme.py
testme.py
py
2,360
python
en
code
1
github-code
6
7649624460
# convolution 계산 함수 import numpy as np import pycuda.autoinit from pycuda.compiler import SourceModule from pycuda import gpuarray, tools import pycuda.driver as cuda class padding(): # CUDA Limit size cu_lim = 32 def __init__(self,D,K,mode='vaild'): # D : Data, K = kernel, kw = int(K.shape[0]) # kernel width kh = int(K.shape[1]) # kernel height # size setting (padding) if mode == 'vaild': aw = D.shape[0]-kw+1 ah = D.shape[1]-kh+1 P = D elif mode == 'same': D = D.astype(np.float32) aw = int(D.shape[0]) ah = int(D.shape[1]) if (aw % self.cu_lim == 0): aw_n = int(aw/self.cu_lim) else : aw_n = int(aw/self.cu_lim +1) if (ah % self.cu_lim == 0): ah_n = int(ah/self.cu_lim) else : ah_n = int(ah/self.cu_lim +1) # result size P = np.zeros([aw+kw-1,ah+kh-1]).astype(np.float32) # Module mod = SourceModule(open("CUDAKernelStudy\\padding.cu", "r", encoding="utf-8").read()) cu_pad = mod.get_function("padding") # allocate memory on device d_gpu = cuda.mem_alloc(D.nbytes) p_gpu = cuda.mem_alloc(P.nbytes) # memory copy (host to device) cuda.memcpy_htod(d_gpu, D) cuda.memcpy_htod(p_gpu, P) kw32 = np.int32(kw) kh32 = np.int32(kh) cusiz = np.int32(self.cu_lim) # padding by CUDA cu_pad(d_gpu,kw32,kh32,cusiz,p_gpu,block=(self.cu_lim,self.cu_lim,1),grid=(aw_n,ah_n,1)) # memory copy (device to host) cuda.memcpy_dtoh(P, p_gpu) d_gpu.free() p_gpu.free() self.D = D self.P = P self.C = np.zeros([aw,ah])
JUHYUKo3o/CUDAKernelStudy
padding.py
padding.py
py
1,964
python
en
code
1
github-code
6
18385134746
class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__( *args, **kwargs ) return cls._instances[cls] class Logger(metaclass=MetaSingleton): def __init__(self, x): self.x = x class Singleton1: __instance = None def __new__(cls, nome): if Singleton1.__instance is None: Singleton1.__instance = object.__new__(cls) Singleton1.__instance.__nome = nome return Singleton1.__instance @property def nome(self): return self.__nome class Singleton2: def __new__(cls, nome): if not hasattr(cls, 'instance'): cls.instance = super(Singleton2, cls).__new__(cls) cls.instance.__nome = nome return cls.instance @property def nome(self): return self.__nome if __name__ == '__main__': foo = Singleton1('Maria') print(foo.nome) print(foo) bar = Singleton1('Joao') print(bar.nome) print(bar) print(foo is bar) foo = Singleton2('Maria') print(foo.nome) print(foo) bar = Singleton2('Joao') print(bar.nome) print(bar) print(foo is bar) # Example using metaclass logger1 = Logger(1) logger2 = Logger(2) print(logger1) print(logger1.x) print(logger2) print(logger2.x)
kelvins/design-patterns-python
criacao/singleton/main.py
main.py
py
1,460
python
en
code
468
github-code
6
18028370803
import json from logging import info import boto3 from botocore.exceptions import ClientError from lgw.lambda_util import get_lambda_info, grant_permission_to_api_resource def create_rest_api( api_name, api_description, binary_types, lambda_name, resource_path, deploy_stage, integration_role, method_response_models, ): ''' Creates & deploys a REST API that proxies to a Lambda function, returning the URL pointing to this API. :param api_name: Name of the REST API :param api_description: Textual description of the API :param binary_types: A list of binary types that this API may serve up :param lambda_name: Name of an existing Lambda function :param resource_path: The resource path that points to the lambda. :param deploy_stage: The name of the deployment stage. :param integration_role :param method_response_models: Dictionary of content-type => response-model mappings to be applied to child method :return: URL of API. If error, returns None. ''' api_client = boto3.client('apigateway') api_id = create_api_gateway(api_client, api_name, api_description, binary_types) (lambda_arn, lambda_uri, region, account_id) = get_lambda_info(lambda_name) root_resource_id = get_root_resource_id(api_client, api_id) create_method(api_client, api_id, root_resource_id, 'ANY') create_lambda_integration(api_client, api_id, root_resource_id, lambda_uri, integration_role) child_resource_id = create_resource(api_client, api_id, root_resource_id, resource_path) create_method(api_client, api_id, child_resource_id, 'ANY', method_response_models) create_lambda_integration(api_client, api_id, child_resource_id, lambda_uri, integration_role) deploy_to_stage(api_client, api_id, deploy_stage) # grant_permission_to_api_resource(api_id, region, account_id, lambda_arn, resource_path) return f'https://{api_id}.execute-api.{region}.amazonaws.com/{deploy_stage}' def delete_rest_api(api_name): api_client = boto3.client('apigateway') delete_api_gateway(api_client, api_name) def deploy_to_stage(api_client, api_id, deploy_stage): return api_client.create_deployment(restApiId=api_id, stageName=deploy_stage) def create_lambda_integration(api_client, api_id, root_resource_id, lambda_uri, role_arn=None): ''' Set the Lambda function as the destination for the ANY method Extract the Lambda region and AWS account ID from the Lambda ARN ARN format="arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME" ''' api_client.put_integration( restApiId=api_id, resourceId=root_resource_id, httpMethod='ANY', type='AWS_PROXY', integrationHttpMethod='POST', uri=lambda_uri, credentials=role_arn, ) def create_method(api_client, api_id, resource_id, http_method, method_response_models={}): try: response = api_client.get_method( restApiId=api_id, resourceId=resource_id, httpMethod=http_method ) if response and response.get('httpMethod'): info(f'{http_method} method already exists for resource {resource_id}') return except api_client.exceptions.NotFoundException: info(f'{http_method} method does not exist for resource {resource_id}, adding it.') api_client.put_method( resourceId=resource_id, restApiId=api_id, httpMethod=http_method, authorizationType='NONE' ) # Set the content-type of the method response to JSON api_client.put_method_response( restApiId=api_id, resourceId=resource_id, httpMethod=http_method, statusCode='200', responseModels=method_response_models, ) def create_resource(api_client, api_id, parent_id, resource_path): resources = api_client.get_resources(restApiId=api_id) if 'items' in resources: for resource in resources['items']: if resource.get('parentId') == parent_id and resource.get('pathPart') == resource_path: info('Found existing resource for %s' % resource['parentId']) return resource['id'] info(f'No existing resource found for {parent_id}/{resource_path}, creating a new one') result = api_client.create_resource( restApiId=api_id, parentId=parent_id, pathPart=resource_path ) return result['id'] def get_root_resource_id(api_client, api_id): result = api_client.get_resources(restApiId=api_id) root_id = None for item in result['items']: if item['path'] == '/': root_id = item['id'] if root_id is None: raise ClientError( 'Could not retrieve the ID of the API root resource using api_id [%s]' % api_id ) return root_id def delete_api_gateway(api_client, api_name): api_id = lookup_api_gateway(api_client, api_name) if api_id: info(f'Deleting API with ID: {api_id}') api_client.delete_rest_api(restApiId=api_id) def create_api_gateway(api_client, api_name, api_description, binary_types): api_id = lookup_api_gateway(api_client, api_name) if api_id: return api_id info(f'No existing API account found for {api_name}, creating it.') result = api_client.create_rest_api( name=api_name, description=api_description, binaryMediaTypes=binary_types ) return result['id'] def lookup_api_gateway(api_client, api_name): apis = api_client.get_rest_apis() if 'items' in apis: for api in apis['items']: if api['name'] == api_name: info('Found existing API account for %s' % api['name']) return api['id'] info(f'No API gateway found with name {api_name}') return None
ebridges/lgw
lgw/api_gateway.py
api_gateway.py
py
5,773
python
en
code
0
github-code
6
29778083632
import stagger import os import sys from stagger.id3 import * def metaHound(argvPath): #ef það er sendur parametri inní fallið þá er það slóðin a möppuna #sem á að fara i gegnum. #ef ekki er sendur parameter er reiknað með að mappan sem á að fara #í gegnum sé í cwd. if argvPath != '': os.chdir(argvPath) os.chdir('..') ipodFolder = argvPath else: ipodFolder = os.path.join(os.getcwd(), 'ipod') if not os.path.exists(os.path.join(os.getcwd(), 'Music')): os.mkdir('Music') root = os.path.join(os.getcwd(), 'Music') #Búið að búa til Music möppu ef hún er ekki til og stilla current working directory á hana for data in os.walk(ipodFolder): for file in data[2]: #data[2] því við viljum bara skoða fæla, ekki folera os.chdir(root) #passa að í byrjun hvers hrings sé cwd alltaf Music mappan currPath = os.path.join(data[0], file) filename, extension = os.path.splitext(file) try: tag = stagger.read_tag(currPath) #ná í meta-data album = tag.album artist = tag.artist title = tag.title if artist == '': artist = 'unknown artists' if album == '': album = 'unknown albums' artist = fixName(artist) album = fixName(album) title = fixName(title) #taka burtu óleyfileg tákn artistPath = os.path.join(root, artist) if not os.path.exists(artistPath): os.mkdir(artist) os.chdir(artistPath) #búa til möppu ef þarf fyrir þennan artista #stilla current working directory á þá möppu albumPath = os.path.join(artistPath, album) if not os.path.exists(albumPath): os.mkdir(album) os.chdir(albumPath) #búa til möppu inní artistanum fyrir plötuna #stilla current working directory á þá möppu newPath = os.path.join(albumPath, title + extension) if not os.path.exists(newPath): os.rename(currPath, newPath) else: os.remove(currPath) #færa lagið í album möppuna ef það er ekki þar nú þegar, annars er því eytt except: #hingað ef tekst ekki að ná i meta-data path = os.path.join(root, 'unknown files') os.chdir(root) if not os.path.exists(path): os.mkdir('unknown files') newPath = os.path.join(path, file) #Búa til unknown files möppu ef hún er ekki til if not os.path.exists(newPath): os.rename(currPath, newPath) else: os.remove(currPath) #færa lagið í unknown files möppuna ef það er ekki þar nú þegar, annars er því eytt #henda ipod möppunni ef allt er tómt for folder in os.listdir(ipodFolder): os.removedirs(os.path.join(ipodFolder, folder)) def fixName(name): #ef nafnið inniheldur ólöglega caractera er þeim skipt út fyrir kommu return name.replace('\\', ',').replace('/', ',').replace(':', ',').replace('*', ',').replace('?', ',').replace('"', ',').replace('<', ',').replace('>', ',').replace('|', ',') try: metaHound(sys.argv[1]) except: metaHound('')
asav13/PRLA-Verk5
part1/metaDataReader.py
metaDataReader.py
py
3,804
python
is
code
0
github-code
6
24362863500
from odoo import models, fields, api from ..tools.nawh_error import NAWHError class NetaddictionWhLocationsLine(models.Model): _name = 'netaddiction.wh.locations.line' _description = "Netaddiction WH Locations Line" _order = 'qty' product_id = fields.Many2one( 'product.product', required=True, string="Prodotto", ) qty = fields.Integer( default=1, required=True, string="Quantità", ) wh_location_id = fields.Many2one( 'netaddiction.wh.locations', required=True, string="Ripiano", ) @api.model def get_products(self, barcode): """ dato il barcode di un ripiano ritorna i prodotti allocati """ result = self.search([('wh_location_id.barcode', '=', barcode)]) if not result: return NAWHError( "Non sono stati trovati prodotti per il barcode" ) return result ########################## # INVENTORY APP FUNCTION # # ritorna un dict simile # # ad un json per il web # ########################## @api.model def get_json_products(self, barcode): """ ritorna un json con i dati per la ricerca per ripiano """ is_shelf = self.env['netaddiction.wh.locations'].check_barcode(barcode) if isinstance(is_shelf, NAWHError): return {'result': 0, 'error': is_shelf.msg} results = self.get_products(barcode) if isinstance(results, NAWHError): return {'result': 0, 'error': results.msg} return { 'result': 1, 'shelf': is_shelf.name, 'barcode': barcode, 'products': [ {'product_name': res.product_id.display_name, 'qty': res.qty, 'barcode': res.product_id.barcode} for res in results ] } @api.model def put_json_new_allocation(self, barcode, qty, product_id, now_wh_line): """ sposta la quantità qty dal ripiano barcode al new_shelf """ is_shelf = self.env['netaddiction.wh.locations'].check_barcode(barcode) if isinstance(is_shelf, NAWHError): return {'result': 0, 'error': is_shelf.msg} new_shelf = is_shelf.id line = self.search( [('id', '=', int(now_wh_line)), ('product_id', '=', int(product_id))] ) if not line: return { 'result': 0, 'error': 'Prodotto non più presente in questa locazione' } if line.wh_location_id.id == new_shelf: return { 'result': 0, 'error': 'Non puoi spostare un prodotto nella' ' stessa locazione di partenza' } dec = line.decrease(qty) if isinstance(dec, NAWHError): return {'result': 0, 'error': dec.msg} self.allocate(product_id, qty, new_shelf) product = self.env['product.product'].browse(int(product_id)) return {'result': 1, 'product_barcode': product.barcode} ############################## # END INVENTORY APP FUNCTION # ############################## ################## # FUNZIONI VARIE # ################## def decrease(self, qta): """ decrementa la quantità allocata di qta """ self.ensure_one() end_qty = self.qty - int(qta) if end_qty < 0: return NAWHError( "Non puoi scaricare una quantità maggiore di quella allocata" ) elif end_qty > 0: self.write({'qty': end_qty}) else: self.unlink() def increase(self, qta): """ incrementa la quantità allocata di qta """ self.ensure_one() self.qty += int(qta) @api.model def allocate(self, product_id, qta, new_location_id): """ alloca in new_location_id la qta di product_id """ result = self.search( [('product_id', '=', int(product_id)), ('wh_location_id', '=', int(new_location_id))] ) if result: # è già presente una locazione con questo prodotto # incremento for res in result: res.increase(qta) else: self.create([{ 'product_id': product_id, 'qty': qta, 'wh_location_id': new_location_id }])
suningwz/netaddiction_addons
netaddiction_warehouse/models/netaddiction_wh_locations_line.py
netaddiction_wh_locations_line.py
py
4,531
python
it
code
0
github-code
6
73675812026
import django from django.conf import settings import pandas as pd import os, sys proj_path = "/home/webuser/webapps/tigaserver/" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tigaserver_project.settings") sys.path.append(proj_path) django.setup() from tigaserver_app.models import Fix FILE = os.path.join(settings.STATIC_ROOT, "geo_user_fixes.csv") # Getting all fixes and create a new DataFrame. # Selecting only the desired fields for speed reasons. df = pd.DataFrame.from_records( Fix.objects.all().values('server_upload_time', 'masked_lon', 'masked_lat') ) # Remove any NaN value df.dropna(inplace=True) # Rename the datetime colume to a more readable name df.rename( columns={"server_upload_time": "datetime"}, inplace=True ) # Convert datetime column to just date df['datetime'] = pd.to_datetime(df['datetime']).dt.normalize() # Round float to 2 decimals (lat and lon) df = df.round(decimals=2) ########## # Group by date, lat, lon and count the number of elements # to make the resulting file smaller. ########## # If the dataviz is slow, create bins for the latitude and longitue. # Example: https://stackoverflow.com/questions/39254704/pandas-group-bins-of-data-per-longitude-latitude # import numpy as np # degres_step = 0.1 # to_bin = lambda x: np.floor(x / step) * step # df["latBin"] = to_bin(df.masked_lat) # df["lonBin"] = to_bin(df.masked_lon) # See: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html df.groupby( [ pd.Grouper(key='datetime', freq='3W-MON'), # Every 3 weeks. df['masked_lon'], df['masked_lat'] ]).size()\ .reset_index(name='count')\ .to_csv(FILE, index=False)
Mosquito-Alert/mosquito_alert
util_scripts/update_geo_userfixes_static.py
update_geo_userfixes_static.py
py
1,682
python
en
code
6
github-code
6
12704422220
#!/usr/bin/env python3 import asyncio import discord import os client= discord.Client() TOKEN = os.getenv('USER_TOKEN') CHANNEL_ID = int(os.getenv('CHANNEL_ID')) MESSAGE = os.getenv('MESSAGE') def lambda_handler(event, context): print("lambda start") client.run(TOKEN, bot=False) @client.event async def on_ready(): print('%s has connected to Discord!' % client.user) channel = client.get_channel(CHANNEL_ID) if channel: await channel.send(MESSAGE) print("message sent") else: print("channel not found") await client.close()
mgla/lambda-discord-messager
lambda_function.py
lambda_function.py
py
580
python
en
code
0
github-code
6
38905374725
from torch import Tensor, LongTensor, max from typing import Dict from sklearn.metrics import accuracy_score def compute_metrics( outputs: Tensor, labels: LongTensor, ) -> Dict[str, float]:\ metrics = {} outputs = outputs.cpu() labels = labels.cpu() _, pred = max(outputs.data, 1) y_true = labels y_pred = pred # accuracy accuracy = accuracy_score( y_true=y_true, y_pred=y_pred, ) # Optional add metrics metrics["accuracy"] = accuracy return metrics if __name__ == '__main__': pass
Agiratex/histological-image-classification
utils/compute_metrics.py
compute_metrics.py
py
570
python
en
code
0
github-code
6
12228572050
import pygame import socket import numpy as np import math import random import time import sys class launch_missiles: def __init__(self, screen, pygame, socket, board, is_client, is_server): self.screen = screen self.pygame = pygame self.socket = socket self.board = board self.missile_board = np.zeros(shape=(10, 10), dtype=int) self.is_client = is_client self.is_server = is_server self.our_turn = is_client self.cell_offset = 0 self.first = True self.very_first = True self.server = None self.client = None def generate_rand_board(self): for i_idx, i in enumerate(self.board): for j_idx, j in enumerate(i): self.board[i_idx][j_idx] = random.randint(0, 1) def title(self): font = self.pygame.font.Font("coolvetica rg.ttf", 48) self.screen.fill((13, 17, 31)) your_board = font.render("Your Board", True, (255, 255, 255)) self.screen.blit(your_board, (200, 10)) missile_board = font.render("Missile Board", True, (255, 255, 255)) self.screen.blit(missile_board, (820, 10)) def createSocket(self, IP): if self.is_server: self.server = self.socket.socket(self.socket.AF_INET, self.socket.SOCK_STREAM) self.server.bind(('', 8088)) self.server.listen() self.conn, self.addr = self.server.accept() else: self.client = self.socket.socket(self.socket.AF_INET, self.socket.SOCK_STREAM) time.sleep(3) self.client.connect((IP, 8088)) def draw_your_board(self): x_loc = 20 for idx, i in enumerate(self.board): for jdx, j in enumerate(i): if j == 0: self.pygame.draw.rect(self.screen, (214, 229, 255), (x_loc + 60 * jdx, 90 + self.cell_offset, 58, 58), 1) self.pygame.draw.circle(self.screen, (163, 163, 162), ((x_loc + (60 * jdx)) + 30, (88 + self.cell_offset) + 30), 6) elif j == 1: self.pygame.draw.rect(self.screen, (25, 209, 83), (x_loc + 60 * jdx, 90 + self.cell_offset, 58, 58), 1) self.pygame.draw.circle(self.screen, (25, 209, 83), ((x_loc + (60 * jdx)) + 30, (88 + self.cell_offset) + 30), 6) elif j == 2: self.pygame.draw.rect(self.screen, (242, 19, 19), (x_loc + 60 * jdx, 90 + self.cell_offset, 58, 58), 1) self.pygame.draw.circle(self.screen, (242, 19, 19), ((x_loc + (60 * jdx)) + 30, (88 + self.cell_offset) + 30), 6) self.cell_offset = self.cell_offset + 60 self.cell_offset = 0 def draw_missile_board(self): x_loc = 650 for idx, i in enumerate(self.missile_board): for jdx, j in enumerate(i): if j == 0: self.pygame.draw.rect(self.screen, (214, 229, 255), (x_loc + 60 * jdx, 90 + self.cell_offset, 58, 58), 1) self.pygame.draw.circle(self.screen, (163, 163, 162), ((x_loc + (60 * jdx)) + 30, (88 + self.cell_offset) + 30), 6) elif j == 2: self.pygame.draw.rect(self.screen, (242, 19, 19), (x_loc + 60 * jdx, 90 + self.cell_offset, 58, 58), 1) self.pygame.draw.circle(self.screen, (242, 19, 19), ((x_loc + (60 * jdx)) + 30, (88 + self.cell_offset) + 30), 6) self.cell_offset = self.cell_offset + 60 self.cell_offset = 0 def turn(self): font = self.pygame.font.Font("coolvetica rg.ttf", 36) if self.our_turn: myTurn = font.render("Your Turn!", True, (255, 255, 255)) self.screen.blit(myTurn, (560, 20)) else: myTurn = font.render("Oppenent's Turn!", True, (255, 255, 255)) self.screen.blit(myTurn, (510, 20)) def change_board(self, x, y): self.missile_board[y][x] = 2 self.first = True self.our_turn = False if self.client: self.client.send(bytes(str(x) + "_" + str(y), 'utf-8')) else: print("sent server") self.conn.send(bytes(str(x) + "_" + str(y), 'utf-8')) print("overall sent") def missed_hit(self, description): font = self.pygame.font.Font("coolvetica rg.ttf", 32) description = font.render(str(description) + "!", True, (255, 255, 255)) self.screen.blit(description, (30, 20)) self.pygame.display.update() def drawui(self, IP): if self.very_first: self.createSocket(IP=IP) self.very_first = False if self.first: self.title() self.draw_your_board() self.draw_missile_board() self.turn() self.pygame.display.update() self.first = not self.first if not self.our_turn: if self.server: array_x_y = self.conn.recv(1024).decode().split("_") if array_x_y[0] == "Target Hit" or array_x_y[0] == "Missed": self.missed_hit(array_x_y[0]) self.first = True pass else: print(array_x_y) x = int(array_x_y[0]) y = int(array_x_y[1]) print(x, y) if x < 0 and y < 0: pass else: if self.board[y][x] == 1: self.conn.send(bytes("Target Hit", 'utf-8')) else: self.conn.send(bytes("Missed", 'utf-8')) self.board[y][x] = 2 self.our_turn = True self.first = True else: array_x_y = self.client.recv(1024).decode().split("_") print("received " + str(array_x_y[0])) if array_x_y[0] == "Target Hit" or array_x_y[0] == "Missed": self.missed_hit(array_x_y[0]) self.first = True pass else: print(array_x_y[0] + "yo") x = int(array_x_y[0]) y = int(array_x_y[1]) print(x, y) if x < 0 and y < 0: pass else: if self.board[y][x] == 1: self.client.send(bytes("Target Hit", 'utf-8')) else: self.client.send(bytes("Missed", 'utf-8')) self.board[y][x] = 2 self.our_turn = True self.first = True def run(self, IP): self.drawui(IP=IP) ''' pygame.init() pygame.mixer.quit() screen = pygame.display.set_mode([1280, 720]) CELLS = 10 #SERVER_BOARD = np.zeros(shape=(CELLS, CELLS), dtype=int) #server_player = launch_missiles(screen=screen, pygame=pygame, socket=socket) #SERVER_BOARD = server_player.generate_rand_board() CLIENT_BOARD = np.zeros(shape=(CELLS, CELLS), dtype=int) client_server = sys.argv[1] if client_server == "server": is_server = True is_client = False else: is_server = False is_client = True client_player = launch_missiles(screen=screen, pygame=pygame, socket=socket, board=CLIENT_BOARD, is_client=is_client, is_server=is_server) client_player.generate_rand_board() clock = pygame.time.Clock() while True: clock.tick(60) events = pygame.event.get() for event in events: if event.type == pygame.QUIT: break if event.type == pygame.MOUSEBUTTONDOWN and client_player.our_turn: x, y = pygame.mouse.get_pos() print("debug") x = math.floor((x - 650) / 60) y = math.floor((y - 90) / 60) client_player.change_board(x, y) client_player.run() '''
AtulPhadke/Battleship
missile.py
missile.py
py
8,591
python
en
code
0
github-code
6
32150136387
from collections import deque def solution(queue1, queue2): answer = -1 queue1Sum = sum(queue1) queue2Sum = sum(queue2) sameSum = (queue1Sum + queue2Sum) // 2 queue1Copy = deque(queue1) queue2Copy = deque(queue2) cnt = 0 while cnt < len(queue1) * 3: if sameSum < queue1Sum: value = queue1Copy.popleft() queue2Copy.append(value) queue1Sum -= value queue2Sum += value elif sameSum > queue1Sum: value = queue2Copy.popleft() queue1Copy.append(value) queue1Sum += value queue2Sum -= value else: answer = cnt break cnt += 1 return answer queue1 = [3, 2, 7, 2] queue2 = [4, 6, 5, 1] print(solution(queue1,queue2))
HS980924/Algorithm
src/8.Queue,Deque/두큐합.py
두큐합.py
py
810
python
en
code
2
github-code
6
32731940278
from collections import deque n, m = map(int, input().split()) number = list(map(int, input().split())) deq = deque(i for i in range(1, n+1)) count = 0 for i in range(m): while True: if (deq[0] == number[i]): deq.popleft() break else: if(len(deq) / 2 > deq.index(number[i])): deq.append(deq.popleft()) count += 1 else: deq.appendleft(deq.pop()) count += 1 print(count)
woo222/baekjoon
python/큐,스택/s3_1021_회전하는큐.py
s3_1021_회전하는큐.py
py
505
python
en
code
0
github-code
6
34390260723
from pathlib import Path from datetime import timedelta import environ import os import pymysql pymysql.install_as_MySQLdb() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent REST_AUTH = { 'SESSION_LOGIN': False } ###### 환경변수 쪽 설정 ################## env = environ.Env(DEBUG=(bool, True)) environ.Env.read_env( env_file=os.path.join(BASE_DIR, '.env') ) SECRET_KEY=env('SECRET_KEY') DEBUG=env('DEBUG') DATABASES = { 'default': { 'ENGINE': env('DATABASES_ENGINE'), 'NAME': BASE_DIR / 'db.sqlite3', } } ####################################### INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'rest_framework', "corsheaders", 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', # In Folder Installed App 'ycwg', 'party_list', 'account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] ROOT_URLCONF = 'ycwg.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ycwg.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases # Password validation # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/dev/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # CORS_ALLOWED_ORIGINS = [ # "http://localhost:5173", # "http://localhost:8000", # "https://port-0-ycwg-backend-1maxx2klgvs8aq4.sel3.cloudtype.app" # ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTP_ONLY = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:8000", "http://localhost:5173", "https://port-0-ycwg-backend-1maxx2klgvs8aq4.sel3.cloudtype.app" ] CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" SESSION_COOKIE_SAMESITE = "None" MEDIA_URL = '/media/' # ex) /media/photo1.png MEDIA_ROOT = os.path.join(BASE_DIR, 'media') SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=30), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=30), # custom 'AUTH_COOKIE': 'access', # Cookie name. Enables cookies if value is set. 'AUTH_COOKIE_REFRESH': 'refresh', # A string like "example.com", or None for standard domain cookie. 'AUTH_COOKIE_DOMAIN': 'port-0-ycwg-backend-1maxx2klgvs8aq4.sel3.cloudtype.app', # Whether the auth cookies should be secure (https:// only). 'AUTH_COOKIE_SECURE': False, # Http only cookie flag.It's not fetch by javascript. 'AUTH_COOKIE_HTTP_ONLY': True, 'AUTH_COOKIE_PATH': '/', # The path of the auth cookie. # Whether to set the flag restricting cookie leaks on cross-site requests. This can be 'Lax', 'Strict', or None to disable the flag. 'AUTH_COOKIE_SAMESITE': "Lax", # TODO: Modify to Lax } REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'account.authenticate.CustomAuthentication', ], "DEFAULT_PERMISSION_CLASSES": [ 'rest_framework.permissions.AllowAny', 'rest_framework.permissions.IsAuthenticated', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } AUTH_USER_MODEL = "account.Account" ALLOWED_HOSTS = [ '*' ]
YCWG/YCWG-BackEnd
ycwg/settings.py
settings.py
py
6,231
python
en
code
0
github-code
6
30003290472
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Description: # @File: test.py # @Project: ip_nlp # @Author: Yiheng # @Email: [email protected] # @Time: 7/15/2019 10:30 import time from pymongo import ASCENDING from common import logger_factory from mongo.connect import get_collection from mongo.utils.query_filter_utils import get_clf_query_filter logger = logger_factory.get_logger('doc_service') def create_index(db_name, clc_name, field_name, sort=ASCENDING): """ create index of doc field to specified db's collection :param db_name: :param clc_name: :param field_name: :param sort: default direction is asc :return: """ clc = get_collection(db_name, clc_name) clc.create_index([(field_name, sort)], background=True) def remove_redundant(db_name, clc_name): """ remove redundant docs :param db_name: :param clc_name: :return: """ clc = get_collection(db_name, clc_name) redundant_docs = clc.aggregate([ {'$group': { '_id': {'pubId': '$pubId'}, 'uniqueIds': {'$addToSet': '$_id'}, 'count': {'$sum': 1} }}, {'$match': { 'count': {'$gt': 1} }}], allowDiskUse=True) print('redundant_docs {}'.format(type(redundant_docs))) for doc in redundant_docs: logger.info(f'{doc}') obj_ids = doc['uniqueIds'] logger.info(f'obj ids is {obj_ids}') for i in range(len(obj_ids)): if i == len(obj_ids) - 1: break clc.remove(obj_ids[i]) def find_some(db_name: str, clc_name: str, limit: int): """ find specified count of docs return a generator, whose item is a Bson obj :param db_name: :param clc_name: :param limit: :return: """ logger.info(f'start find_some with limit {limit}') clc = get_collection(db_name, clc_name) limit = 0 if limit < 0 else limit cursor = clc.find({}).limit(limit) for doc in cursor: yield doc def find_all(db_name: str, clc_name: str): """ find all docs and return a generator, whose item is a Bson obj :param db_name: :param clc_name: :return: """ logger.info('start find_all') return find_some(db_name, clc_name, 0) def find_by_clf(db_name, clc_name, limit=300, **kwargs): """ find docs by classification infos and return a generator, whose item is a Bson obj :param db_name: :param clc_name: :param limit: :param kwargs: :return: """ cursor = find_cursor_by_clf(db_name, clc_name, limit, **kwargs) for doc in cursor: yield doc def find_cursor_by_clf(db_name, clc_name, limit, **kwargs): """ get docs obj by classification params :param db_name: :param clc_name: :param limit: :param kwargs: section required mainClass subClass :return: """ logger.info(f'start search tasks with {kwargs}') clc = get_collection(db_name, clc_name) query_filter = get_clf_query_filter(kwargs) cursor = clc.find(query_filter).limit(limit) logger.info(f'search tasks {kwargs} complete') return cursor if __name__ == '__main__': db_ip_doc = 'ip_doc' clc_raw = 'raw' # remove_redundant('ip_doc', 'raw') start_time = time.time() docs = find_by_clf(db_ip_doc, clc_raw, section='B', mainClass='29', subClass='K') # count = len(list(docs)) # print('count is {}'.format(count)) for doc in docs: logger.info(f'find doc pubId {doc["pubId"]}') end_time = time.time() logger.info(f'complete...,take time {end_time - start_time}s')
zhenxun815/ip_nlp
src/mongo/doc_service.py
doc_service.py
py
3,720
python
en
code
0
github-code
6
29098845226
#!/bin/env python # This script undoes the "WellFolders.py" script, aka it empties all of the well folders out into the parent folder. import os import re import argparse parser = argparse.ArgumentParser(description='Takes a folder formatted by WellFolders and undoes it ', usage='%(prog)s FOLDERPATH') parser.add_argument('folderlocation', type=str, help='Absolute path of the folder to modify') args = parser.parse_args() regex = re.compile(r'\w{1}\d{2}_Day\d{1}') allfolders = [file for file in os.scandir(args.folderlocation) if file.is_dir() and regex.match(file.name)] for folder in allfolders: redfolder = folder.path + '/Red/' greenfolder = folder.path + '/Green/' brightfield = folder.path + '/Brightfield/' for foldpath in [redfolder, greenfolder, brightfield]: for file in os.scandir(foldpath): if file.name.endswith('.txt'): os.remove(file.path) elif file.name.endswith('.tif'): os.rename(file.path, f'{args.folderlocation}/{file.name}') os.rmdir(foldpath) os.rmdir(folder.path)
jc6213/CRANIUM
UndoWellFolders.py
UndoWellFolders.py
py
1,123
python
en
code
0
github-code
6
40546898692
import json from django.http import JsonResponse from django.shortcuts import render from admin_manage.models import Company from admin_manage.views import method_verify, verify_token from face_machine_client.models import ClientInfo from asgiref.sync import async_to_sync from channels.layers import get_channel_layer @verify_token @method_verify() def client_register(request): """ 设备注册接口 请求实例 { 'type':'register', 'username':'', 'password':'', 'company_id':'', } :param request: :return: {'msg':'ok'} """ req_data = request.POST # 检测消息类型 if req_data.get('type') == 'register': client_user = req_data.get('client_user') client_key = req_data.get('client_key') client_company_id = req_data.get('client_company_id') # 检测必填项 if client_user and client_key and client_company_id: client_check = ClientInfo.objects.filter(client_user=client_user).count() if client_check == 0: try: # 进行设备注册 company_id = Company.objects.filter(company_id=client_company_id).get() ClientInfo.objects.create(client_user=client_user, client_key=client_key, client_info=company_id) except Exception as e: print(e) return JsonResponse({'msg': str(e)}) return JsonResponse({'msg': '设备注册成功,请记录设备号与密码', 'username': client_user, 'password': client_key, 'code': "200", 'error_code': "0" }) else: return JsonResponse({'msg': '设备已经被注册', 'code': "200", 'error_code': "601" }) else: return JsonResponse({'msg': '有必填项未填', 'code': "200", 'error_code': "884" }) elif req_data.get('type') == 'delete': # 删除设备 client_user = req_data.get('client_user') client_company_id = req_data.get('client_company_id') company_id = Company.objects.filter(company_id=client_company_id).get() # 检测必填项 if client_user and client_company_id: client_object = ClientInfo.objects.filter(client_user=client_user, client_info=company_id) if client_object.count() == 1: try: client_object.delete() except Exception as e: print(e) return JsonResponse({'msg': '删除失败', 'error': str(e), 'code': "200", 'error_code': "884" }) else: return JsonResponse({'msg': '删除成功', 'code': "200", 'error_code': "0"}) elif client_object.count() == 0: return JsonResponse({'msg': '设备不存在', 'code': "200", 'error_code': "606" }) else: return JsonResponse({'msg': '参数出错', 'code': "200", 'error_code': "607" }) else: return JsonResponse({'msg': '有必填项未填', 'code': "200", 'error_code': "884" }) else: return JsonResponse({'msg': '注册参数出错', 'code': "200", 'error_code': "886" }) @method_verify() def push_to_client(request): """ 主动推送数据至客户端 """ req_data = request.POST # 推送类型 push_type = req_data.get('push_type') push_message = request.POST.get('push_message') # 按照企业id进行设备全推送 if push_type == "company": company_id = request.POST.get('company_id') try: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( # ASGI是异步的,这里转为同步操作;通过通信层向组群发送消息 str(company_id), # 设备的企业id { 'type': 'get_notification', # 标记发送事件的type 'message': push_message, # 提示信息 } ) except Exception as e: print(e) return JsonResponse({'msg': '推送出错', 'code': "200", 'error_code': "701" }) else: return JsonResponse({'msg': '推送成功', 'code': "200", 'error_code': "0" }) # 单个设备推送 elif push_type == "single_client": client_user = request.POST.get('client_user') try: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( # ASGI是异步的,这里转为同步操作;通过通信层向组群发送消息 str(client_user), # 设备的设备号 { 'type': 'get_notification', # 标记发送事件的type 'message': push_message, # 提示信息 } ) except Exception as e: print(e) return JsonResponse({'msg': '推送出错', 'code': "200", 'error_code': "701" }) else: return JsonResponse({'msg': '推送成功', 'code': "200", 'error_code': "0" })
hamster1963/face-all-in-one-machine-backend
face_machine_client/views.py
views.py
py
6,512
python
en
code
0
github-code
6
19400727989
class Car: def __init__(self, id, brand, model, product_year, convertible): self.id = id self.brand = brand self.model = model self.production_year = product_year self.convertible = convertible def jsonEncoder(car): if isinstance(car, Car): return car.__dict__ else: raise TypeError(car.__class__.__name__ + "is not JSON seriazable")
Yifei-G/vintage-car-database
car.py
car.py
py
426
python
en
code
0
github-code
6
3477127800
import logging from dvc.cli.command import CmdBase logger = logging.getLogger(__name__) class CmdQueueWorker(CmdBase): """Run the exp queue worker.""" def run(self): self.repo.experiments.celery_queue.worker.start(self.args.name) return 0 def add_parser(experiments_subparsers, parent_parser): QUEUE_WORKER_HELP = "Run the exp queue worker." parser = experiments_subparsers.add_parser( "queue-worker", parents=[parent_parser], description=QUEUE_WORKER_HELP, add_help=False, ) parser.add_argument("name", help="Celery worker name.") parser.set_defaults(func=CmdQueueWorker)
gshanko125298/Prompt-Engineering-In-context-learning-with-GPT-3-and-LLMs
myenve/Lib/site-packages/dvc/commands/experiments/queue_worker.py
queue_worker.py
py
656
python
en
code
3
github-code
6
8105081811
# coding=utf-8 import os import re import glob import MeCab import torch from torch import nn import pickle import linecache import pandas as pd from sklearn.model_selection import train_test_split import torch.optim as optim import sys sys.path.append(os.path.join('./', '..', '..')) from classification.script.models import LSTMClassifier def make_dataset(data_dir): categories = [dir_name for dir_name in os.listdir(data_dir) if os.path.isdir(data_dir + dir_name)] datasets = pd.DataFrame(columns=['title', 'category']) for category in categories: text_files = glob.glob(os.path.join(data_dir, category, '*.txt')) for text_file in text_files: title = linecache.getline(text_file, 3) data = pd.Series([title, category], index=datasets.columns) datasets = datasets.append(data, ignore_index=True) # データをシャッフル datasets = datasets.sample(frac=1).reset_index(drop=True) return datasets def make_wakati(sentence): """ 文章を分かち書きしたリストにする。 Args: sentence (string): Returns: list: 記号や英語が削除された、日本語の単語の分かち書きされたリスト """ tagger = MeCab.Tagger('-Owakati') sentence = tagger.parse(sentence) sentence = re.sub(r'[0-90-9a-zA-Za-zA-Z]+', " ", sentence) # 半角全角英数字除去 sentence = re.sub(r'[\._-―─!@#$%^&\-‐|\\*\“()_■×+α※÷⇒—●★☆〇◎◆▼◇△□(:〜~+=)/*&^%$#@!~`){}[]…\[\]\"\'\”\’' r':;<>?<>〔〕〈〉?、。・,\./『』【】「」→←○《》≪≫\n\u3000]+', "", sentence) # 記号を削除 wakati = sentence.split(' ') wakati = [word for word in wakati if word != ""] # 空を削除 return wakati def sentence2index(sentence, word2index): """文章を単語に分割し、単語ごとのindex numを持つ配列にする""" wakati = make_wakati(sentence) return torch.tensor([word2index[word] for word in wakati], dtype=torch.long) def main(): data_dir = '../data/text/' dataset_pickle_file = os.path.join('../', 'data', 'text', 'title_category_dataset.pickle') category2index = { 'movie-enter': 0, 'it-life-hack': 1, 'kaden-channel': 2, 'topic-news': 3, 'livedoor-homme': 4, 'peachy': 5, 'sports-watch': 6, 'dokujo-tsushin': 7, 'smax': 8 } device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") if not os.path.exists(dataset_pickle_file): datasets = make_dataset(data_dir) with open(dataset_pickle_file, 'wb') as pickle_write_file: pickle.dump(datasets, pickle_write_file) else: with open(dataset_pickle_file, 'rb') as pickle_read_file: datasets = pickle.load(pickle_read_file) word2index = {} for title in datasets['title']: wakati_title = make_wakati(title) for word in wakati_title: if word in word2index: continue word2index[word] = len(word2index) print('vocab size:{}'.format(len(word2index))) vocab_size = len(word2index) embedding_dim = 10 hidden_dim = 128 output_size = len(category2index) train_data, test_data = train_test_split(datasets, train_size=0.7) model = LSTMClassifier(embedding_dim, hidden_dim, vocab_size, output_size).to(device) criterion = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.01) train_num, test_num = len(train_data), len(test_data) train_losses, eval_losses = [], [] accuracies = [] # [TODO] 比較して精度計算する for epoch in range(5): train_loss = 0 train_correct_num = 0 for title, cat in zip(train_data['title'], train_data['category']): model.zero_grad() inputs = sentence2index(title, word2index).to(device) outputs = model(inputs).to(device) gt = torch.tensor([category2index[cat]], dtype=torch.long).to(device) _, predict = torch.max(outputs, 1) if gt == predict: train_correct_num += 1 loss = criterion(outputs, gt) loss.backward() optimizer.step() train_loss += loss.item() train_losses.append(train_loss) print('epoch:{}\t train loss:{}\t accuracy:{}'.format( epoch, train_loss, round(train_correct_num / train_num, 3))) # テストデータを確認 test_loss = 0 test_correct_num = 0 with torch.no_grad(): for title, cat in zip(test_data['title'], test_data['category']): inputs = sentence2index(title, word2index).to(device) outputs = model(inputs).to(device) gt = torch.tensor([category2index[cat]], dtype=torch.long).to(device) _, predict = torch.max(outputs, 1) if gt == predict: test_correct_num += 1 loss = criterion(outputs, gt) test_loss += loss.item() eval_losses.append(test_loss) print('epoch:{}\t eval loss:{}\t accuracy:{}'.format( epoch, test_loss, round(test_correct_num / test_num, 3))) if __name__ == '__main__': main()
ys201810/lstm_pytorch
classification/script/train.py
train.py
py
5,357
python
en
code
0
github-code
6
41255517387
while True: try: a = int(input("Enter a: ")) b = int(input("Enter b: ")) op = input("Operation: ") break except: print('Ви повинні використовувати числа!') if __name__ == '__main__': print('Ви запустили цей файл, як головний!\n') elif __name__ == 'operations': print('Дякуємо за використання модуля отримання даних!\n')
timkaaa23/TP-KB-221-Tymofii-Savosta
topic_6/operations.py
operations.py
py
434
python
uk
code
0
github-code
6
40688712803
import logging from feg.protos import s6a_proxy_pb2, s6a_proxy_pb2_grpc from google.protobuf.json_format import MessageToJson from magma.common.rpc_utils import print_grpc from magma.subscriberdb import metrics from magma.subscriberdb.crypto.utils import CryptoError from magma.subscriberdb.store.base import SubscriberNotFoundError from magma.subscriberdb.subscription.utils import ServiceNotActive class S6aProxyRpcServicer(s6a_proxy_pb2_grpc.S6aProxyServicer): """ gRPC based server for the S6aProxy. """ def __init__(self, lte_processor, print_grpc_payload: bool = False): self.lte_processor = lte_processor logging.info("starting s6a_proxy servicer") self._print_grpc_payload = print_grpc_payload def add_to_server(self, server): """ Add the servicer to a gRPC server """ s6a_proxy_pb2_grpc.add_S6aProxyServicer_to_server(self, server) def AuthenticationInformation(self, request, context): print_grpc(request, self._print_grpc_payload, "AIR:") imsi = request.user_name aia = s6a_proxy_pb2.AuthenticationInformationAnswer() try: plmn = request.visited_plmn re_sync_info = request.resync_info # resync_info = # rand + auts, rand is of 16 bytes + auts is of 14 bytes sizeof_resync_info = 30 if re_sync_info and (re_sync_info != b'\x00' * sizeof_resync_info): rand = re_sync_info[:16] auts = re_sync_info[16:] self.lte_processor.resync_lte_auth_seq(imsi, rand, auts) rand, xres, autn, kasme = \ self.lte_processor.generate_lte_auth_vector(imsi, plmn) metrics.S6A_AUTH_SUCCESS_TOTAL.inc() # Generate and return response message aia.error_code = s6a_proxy_pb2.SUCCESS eutran_vector = aia.eutran_vectors.add() eutran_vector.rand = bytes(rand) eutran_vector.xres = xres eutran_vector.autn = autn eutran_vector.kasme = kasme logging.info("Auth success: %s", imsi) return aia except CryptoError as e: logging.error("Auth error for %s: %s", imsi, e) metrics.S6A_AUTH_FAILURE_TOTAL.labels( code=metrics.DIAMETER_AUTHENTICATION_REJECTED, ).inc() aia.error_code = metrics.DIAMETER_AUTHENTICATION_REJECTED return aia except SubscriberNotFoundError as e: logging.warning("Subscriber not found: %s", e) metrics.S6A_AUTH_FAILURE_TOTAL.labels( code=metrics.DIAMETER_ERROR_USER_UNKNOWN, ).inc() aia.error_code = metrics.DIAMETER_ERROR_USER_UNKNOWN return aia except ServiceNotActive as e: logging.error("Service not active for %s: %s", imsi, e) metrics.M5G_AUTH_FAILURE_TOTAL.labels( code=metrics.DIAMETER_ERROR_UNAUTHORIZED_SERVICE, ).inc() aia.error_code = metrics.DIAMETER_ERROR_UNAUTHORIZED_SERVICE return aia finally: print_grpc(aia, self._print_grpc_payload, "AIA:") def UpdateLocation(self, request, context): print_grpc(request, self._print_grpc_payload, "ULR:") imsi = request.user_name ula = s6a_proxy_pb2.UpdateLocationAnswer() try: profile = self.lte_processor.get_sub_profile(imsi) except SubscriberNotFoundError as e: ula.error_code = s6a_proxy_pb2.USER_UNKNOWN logging.warning('Subscriber not found for ULR: %s', e) print_grpc(ula, self._print_grpc_payload, "ULA:") return ula try: sub_data = self.lte_processor.get_sub_data(imsi) except SubscriberNotFoundError as e: ula.error_code = s6a_proxy_pb2.USER_UNKNOWN logging.warning("Subscriber not found for ULR: %s", e) print_grpc(ula, self._print_grpc_payload, "ULA:") return ula ula.error_code = s6a_proxy_pb2.SUCCESS ula.default_context_id = 0 ula.total_ambr.max_bandwidth_ul = profile.max_ul_bit_rate ula.total_ambr.max_bandwidth_dl = profile.max_dl_bit_rate ula.all_apns_included = 0 ula.msisdn = self.encode_msisdn(sub_data.non_3gpp.msisdn) context_id = 0 for apn in sub_data.non_3gpp.apn_config: sec_apn = ula.apn.add() sec_apn.context_id = context_id context_id += 1 sec_apn.service_selection = apn.service_selection sec_apn.qos_profile.class_id = apn.qos_profile.class_id sec_apn.qos_profile.priority_level = apn.qos_profile.priority_level sec_apn.qos_profile.preemption_capability = ( apn.qos_profile.preemption_capability ) sec_apn.qos_profile.preemption_vulnerability = ( apn.qos_profile.preemption_vulnerability ) sec_apn.ambr.max_bandwidth_ul = apn.ambr.max_bandwidth_ul sec_apn.ambr.max_bandwidth_dl = apn.ambr.max_bandwidth_dl sec_apn.ambr.unit = ( s6a_proxy_pb2.UpdateLocationAnswer .AggregatedMaximumBitrate.BitrateUnitsAMBR.BPS ) sec_apn.pdn = ( apn.pdn if apn.pdn else s6a_proxy_pb2.UpdateLocationAnswer.APNConfiguration.IPV4 ) print_grpc(ula, self._print_grpc_payload, "ULA:") return ula def PurgeUE(self, request, context): logging.warning( "Purge request not implemented: %s %s", request.DESCRIPTOR.full_name, MessageToJson(request), ) pur = s6a_proxy_pb2.PurgeUEAnswer() print_grpc(pur, self._print_grpc_payload, "PUR:") return pur @staticmethod def encode_msisdn(msisdn: str) -> bytes: # Mimic how the MSISDN is encoded in ULA : 3GPP TS 29.329-f10 # For odd length MSISDN pad it with an extra 'F'/'1111' if len(msisdn) % 2 != 0: msisdn = msisdn + "F" result = [] # Treat each 2 characters as a byte and flip the order for i in range(len(msisdn) // 2): first = int(msisdn[2 * i]) second = int(msisdn[2 * i + 1], 16) flipped = first + (second << 4) result.append(flipped) return bytes(result)
magma/magma
lte/gateway/python/magma/subscriberdb/protocols/s6a_proxy_servicer.py
s6a_proxy_servicer.py
py
6,492
python
en
code
1,605
github-code
6
39275803820
## For random paymentid import re import secrets import sha3 import sys from binascii import hexlify, unhexlify import pyed25519 # byte-oriented StringIO was moved to io.BytesIO in py3k try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO b = pyed25519.b q = pyed25519.q l = pyed25519.l # CN: def cn_fast_hash(s): return keccak_256(unhexlify(s)) def keccak_256(s): # return Keccak().Keccak((len(s)*4, s), 1088, 512, 0x01, 32*8, False).lower() k = sha3.keccak_256() k.update(s) return k.hexdigest() def sc_reduce(key): return intToHexStr(hexStrToInt(key) % l) def sc_reduce32(key): return intToHexStr(hexStrToInt(key) % q) def public_from_int(i): pubkey = ed25519.encodepoint(ed25519.scalarmultbase(i)) return hexlify(pubkey) def public_from_secret(sk): return public_from_int(hexStrToInt(sk)).decode('utf-8') ### base58 # MoneroPy - A python toolbox for Monero # Copyright (C) 2016 The MoneroPy Developers. # # MoneroPy is released under the BSD 3-Clause license. Use and redistribution of # this software is subject to the license terms in the LICENSE file found in the # top-level directory of this distribution. __alphabet = [ord(s) for s in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'] __b58base = 58 __UINT64MAX = 2 ** 64 __encodedBlockSizes = [0, 2, 3, 5, 6, 7, 9, 10, 11] __fullBlockSize = 8 __fullEncodedBlockSize = 11 def _hexToBin(hex): if len(hex) % 2 != 0: return "Hex string has invalid length!" return [int(hex[i * 2:i * 2 + 2], 16) for i in range(len(hex) // 2)] def _binToHex(bin): return "".join([("0" + hex(int(bin[i])).split('x')[1])[-2:] for i in range(len(bin))]) def _strToBin(a): return [ord(s) for s in a] def _binToStr(bin): return ''.join([chr(bin[i]) for i in range(len(bin))]) def _uint8be_to_64(data): l_data = len(data) if l_data < 1 or l_data > 8: return "Invalid input length" res = 0 switch = 9 - l_data for i in range(l_data): if switch == 1: res = res << 8 | data[i] elif switch == 2: res = res << 8 | data[i] elif switch == 3: res = res << 8 | data[i] elif switch == 4: res = res << 8 | data[i] elif switch == 5: res = res << 8 | data[i] elif switch == 6: res = res << 8 | data[i] elif switch == 7: res = res << 8 | data[i] elif switch == 8: res = res << 8 | data[i] else: return "Impossible condition" return res def _uint64_to_8be(num, size): res = [0] * size; if size < 1 or size > 8: return "Invalid input length" twopow8 = 2 ** 8 for i in range(size - 1, -1, -1): res[i] = num % twopow8 num = num // twopow8 return res def encode_block(data, buf, index): l_data = len(data) if l_data < 1 or l_data > __fullEncodedBlockSize: return "Invalid block length: " + str(l_data) num = _uint8be_to_64(data) i = __encodedBlockSizes[l_data] - 1 while num > 0: remainder = num % __b58base num = num // __b58base buf[index + i] = __alphabet[remainder]; i -= 1 return buf def encode(hex): '''Encode hexadecimal string as base58 (ex: encoding a Monero address).''' data = _hexToBin(hex) l_data = len(data) if l_data == 0: return "" full_block_count = l_data // __fullBlockSize last_block_size = l_data % __fullBlockSize res_size = full_block_count * __fullEncodedBlockSize + __encodedBlockSizes[last_block_size] res = [0] * res_size for i in range(res_size): res[i] = __alphabet[0] for i in range(full_block_count): res = encode_block(data[(i * __fullBlockSize):(i * __fullBlockSize + __fullBlockSize)], res, i * __fullEncodedBlockSize) if last_block_size > 0: res = encode_block( data[(full_block_count * __fullBlockSize):(full_block_count * __fullBlockSize + last_block_size)], res, full_block_count * __fullEncodedBlockSize) return _binToStr(res) def decode_block(data, buf, index): l_data = len(data) if l_data < 1 or l_data > __fullEncodedBlockSize: return "Invalid block length: " + l_data res_size = __encodedBlockSizes.index(l_data) if res_size <= 0: return "Invalid block size" res_num = 0 order = 1 for i in range(l_data - 1, -1, -1): digit = __alphabet.index(data[i]) if digit < 0: return "Invalid symbol" product = order * digit + res_num if product > __UINT64MAX: return "Overflow" res_num = product order = order * __b58base if res_size < __fullBlockSize and 2 ** (8 * res_size) <= res_num: return "Overflow 2" tmp_buf = _uint64_to_8be(res_num, res_size) for i in range(len(tmp_buf)): buf[i + index] = tmp_buf[i] return buf def decode(enc): '''Decode a base58 string (ex: a Monero address) into hexidecimal form.''' enc = _strToBin(enc) l_enc = len(enc) if l_enc == 0: return "" full_block_count = l_enc // __fullEncodedBlockSize last_block_size = l_enc % __fullEncodedBlockSize last_block_decoded_size = __encodedBlockSizes.index(last_block_size) if last_block_decoded_size < 0: return "Invalid encoded length" data_size = full_block_count * __fullBlockSize + last_block_decoded_size data = [0] * data_size for i in range(full_block_count): data = decode_block(enc[(i * __fullEncodedBlockSize):(i * __fullEncodedBlockSize + __fullEncodedBlockSize)], data, i * __fullBlockSize) if last_block_size > 0: data = decode_block(enc[(full_block_count * __fullEncodedBlockSize):( full_block_count * __fullEncodedBlockSize + last_block_size)], data, full_block_count * __fullBlockSize) return _binToHex(data) """Varint encoder/decoder varints are a common encoding for variable length integer data, used in libraries such as sqlite, protobuf, v8, and more. Here's a quick and dirty module to help avoid reimplementing the same thing over and over again. """ if sys.version > '3': def _byte(b): return bytes((b,)) else: def _byte(b): return chr(b) def varint_encode(number): """Pack `number` into varint bytes""" buf = b'' while True: towrite = number & 0x7f number >>= 7 if number: buf += _byte(towrite | 0x80) else: buf += _byte(towrite) break return buf def hexStrToInt(h): '''Converts a hexidecimal string to an integer.''' return int.from_bytes(unhexlify(h), "little") def intToHexStr(i): '''Converts an integer to a hexidecimal string.''' return hexlify(i.to_bytes(32, "little")).decode("latin-1") # Validate CN address: def cn_validate_address(wallet_address: str, get_prefix: int, get_addrlen: int, get_prefix_char: str): prefix_hex = varint_encode(get_prefix).hex() remain_length = get_addrlen - len(get_prefix_char) my_regex = r"" + get_prefix_char + r"[a-zA-Z0-9]" + r"{" + str(remain_length) + ",}" if len(wallet_address) != int(get_addrlen): return None if not re.match(my_regex, wallet_address.strip()): return None try: address_hex = decode(wallet_address) if address_hex.startswith(prefix_hex): i = len(prefix_hex) - 1 address_no_prefix = address_hex[i:] spend = address_no_prefix[1:65] view = address_no_prefix[65:129] checksum = address_no_prefix[129:137] expectedChecksum = cn_fast_hash(prefix_hex + spend + view)[0:8] if checksum == expectedChecksum: return wallet_address except Exception as e: pass return None # Validate address: def cn_validate_integrated(wallet_address: str, get_prefix_char: str, get_prefix: int, get_intaddrlen: int): prefix_hex = varint_encode(get_prefix).hex() remain_length = get_intaddrlen - len(get_prefix_char) my_regex = r"" + get_prefix_char + r"[a-zA-Z0-9]" + r"{" + str(remain_length) + ",}" if len(wallet_address) != int(get_intaddrlen): return None if not re.match(my_regex, wallet_address.strip()): return None try: address_hex = decode(wallet_address) if address_hex.startswith(prefix_hex): i = len(prefix_hex) - 1 address_no_prefix = address_hex[i:] integrated_id = address_no_prefix[1:129] spend = address_no_prefix[(128 + 1):(128 + 65)] view = address_no_prefix[(128 + 65):(128 + 129)] checksum = address_no_prefix[(128 + 129):(128 + 137)] expectedChecksum = cn_fast_hash(prefix_hex + integrated_id + spend + view)[0:8] if checksum == expectedChecksum: checksum = cn_fast_hash(prefix_hex + spend + view); address_b58 = encode(prefix_hex + spend + view + checksum[0:8]) result = {} result['address'] = str(address_b58) result['integrated_id'] = str(hextostr(integrated_id)) else: return 'invalid' except Exception as e: return None return result # make_integrated address: def cn_make_integrated(wallet_address, get_prefix_char: str, get_prefix: int, get_addrlen: int, integrated_id=None): prefix_hex = varint_encode(get_prefix).hex() remain_length = get_addrlen - len(get_prefix_char) my_regex = r"" + get_prefix_char + r"[a-zA-Z0-9]" + r"{" + str(remain_length) + ",}" if integrated_id is None: integrated_id = paymentid() if len(wallet_address) != get_addrlen: return None if not re.match(my_regex, wallet_address.strip()): return None if not re.match(r'[a-zA-Z0-9]{64,}', integrated_id.strip()): return None try: address_hex = decode(wallet_address) checkPaymentID = integrated_id integrated_id = integrated_id.encode('latin-1').hex() if (address_hex.startswith(prefix_hex)): i = len(prefix_hex) - 1 address_no_prefix = address_hex[i:] spend = address_no_prefix[1:65] view = address_no_prefix[65:129] expectedChecksum = cn_fast_hash(prefix_hex + integrated_id + spend + view)[0:8] address = (prefix_hex + integrated_id + spend + view + expectedChecksum) address = str(encode(address)) result = {} result['address'] = wallet_address result['paymentid'] = checkPaymentID result['integrated_address'] = address return result except Exception as e: pass return None ## make random paymentid: def paymentid(length=None): if length is None: length = 32 return secrets.token_hex(length) def hextostr(hex): h2b = _hexToBin(hex) # print(h2b) res = '' for i in h2b: res = res + chr(i) return res ##########
wrkzcoin/TipBot
wrkzcoin_tipbot/cn_addressvalidation.py
cn_addressvalidation.py
py
11,230
python
en
code
137
github-code
6
72960119867
"""def is_triangle(a, b, c): if a > (b + c) or b > (a + c) or c > (a + b): print("You cannot form a triangle with these numbers") else: print("You can form a triangle with these numbers") is_triangle(4, 8, 12)""" """def compare(a, b): if a > b: #print(1) return 1 elif a == b: #print(0) return 0 else: return -1 def collection(): return int(input()) print(compare(collection(), collection()), end="")""" def is_between(x, y, z): if x <= y and y <= z: return True else: return False print(is_between(1, 2, 3), end="")
derinsola01/Projects
sticks.py
sticks.py
py
578
python
en
code
0
github-code
6
3897488762
from pointcloud import PointCloud from evaluation import Evaluation_3d pc = PointCloud(channel_num=4, filename='../data/TCC12.pcd') pc.create_vis() pred_boxes = pc.draw_3dboxes_from_txt('../data/PC_0729_3_pred.txt') gt_boxes = pc.draw_3dboxes_from_txt('../data/PC_0729_3.txt', color=[1, 0, 1]) eval = Evaluation_3d(pred_boxes, gt_boxes, 0.5) recall = eval.compute_recall() pc.display_pc()
zhangtingyu11/pointcloud_utils
pointcloud_utils/demo.py
demo.py
py
390
python
en
code
0
github-code
6
24519510155
from __future__ import print_function import sys import re import argparse import json from constants import * class Graph(object): """ contains all data and information about a single graph inside a :py:class:diagram.Diagram. """ def __init__(self,name, signal_accumulators, ylabel, formatting): """ :param name: how the graph will be called in the diagram :param signal_accumulators: an iterator for signal_accumulators :param ylabel: naming of the corresponding y-axis in the diagram :param formatting: Matlab style formatting for this graph """ self.name = name self.__signal_accumulators = signal_accumulators self.ylabel = ylabel self.formatting = formatting self.__xdata = np.array([]) self.__ydata = np.array([]) self.__applied = False def __apply_accumulators(): """ generate pylab parsable data from accumulators """ self.__xdata = np.array([]) self.__ydata = np.array([]) for acc in self.signal_accumulators: self.__xdata = __array_append(self.__xdata,acc.attempt) self.__ydata = __array_append(self.__ydata,acc.count) self.__applied = True @property def signal_accumulators(self): return self.__signal_accumulators @signal_accumulators.setter def signal_accumulators(self,value): self.__signal_accumulators = value self.__applied = False @signal_accumulators.deleter def signal_accumulators(self): self.__signal_accumulators = None self.__applied = False @property def x_data(self): """ generates data for the x values of a pylab graph plot """ if not self.__applied: self.__apply_accumulators() return self.__xdata @property def y_data(self): """ generates data for the y values of a pylab graph plot """ if not self.__applied: self.__apply_accumulators() return self.__ydata def __array_append(self, in_a,in_b): """ append a numpy array to another :param in_a: a numpy array :param in_b: a numpy array or a number """ in_b = np.array([in_b]) if isinstance(in_b,(int,float,long,complex)) else in_b return np.concatenate((in_a,in_b))
DFE/night-owl
graph.py
graph.py
py
2,380
python
en
code
3
github-code
6
30299002056
import datetime from elasticsearch import Elasticsearch def insertData(): es = Elasticsearch('[localhost]:9200') # index : product_list, type : _doc index = "product_list" doc = { "category": "t-shirt", "price": 16700, "@timestamp": datetime.datetime.now() } es.index(index="product_list", doc_type="_doc", body=doc) def searchAPI(): es = Elasticsearch('[localhost]:9200') index = "product_list" body = { "query": { "match_all": {} } } res = es.search(index=index, body=body) print(type(res)) print(len(res['hits']['hits'])) for item in res['hits']['hits']: print(item['_source']) #insertData() searchAPI()
yeahyung/python-flask
study/elastic.py
elastic.py
py
730
python
en
code
0
github-code
6
15963688161
# Profundizando tipo float a = 3.0 # Constructor float puede recibir int y str a = float(10) a = float('10') # print(f'a: {a:.2f}') # Notación exponencial (valores positivos o negativos) a = 3e5 a = 3e-5 # print(f'a: {a:.5f}') # Cualquier cálculo que involucre un float, se promueve a float a = 4 + 5.0 print(a) print(type(a))
Drako01/Python-Curso
0029/01-03-00-ProfundizandoTipoFlotante-UP.py
01-03-00-ProfundizandoTipoFlotante-UP.py
py
329
python
es
code
2
github-code
6
34862439177
import datetime import decimal import urllib.parse from typing import Dict, Any from django import template from django.conf import settings from django.template.defaultfilters import date from django.urls import NoReverseMatch, reverse from django.utils import timezone from django.utils.safestring import mark_safe from django.utils.timezone import make_aware from pysvg.structure import Svg from components.models import Component from incidents.choices import IncidentImpactChoices from utilities.forms import get_selected_values from utilities.forms.forms import TableConfigForm from utilities.pysvg_helpers import create_rect from utilities.utils import get_viewname register = template.Library() # # Filters # @register.filter() def viewname(model, action): """ Return the view name for the given model and action. Does not perform any validation. """ return get_viewname(model, action) @register.filter() def validated_viewname(model, action): """ Return the view name for the given model and action if valid, or None if invalid. """ viewname = get_viewname(model, action) # Validate the view name try: reverse(viewname) return viewname except NoReverseMatch: return None @register.filter() def humanize_speed(speed): """ Humanize speeds given in Kbps. Examples: 1544 => "1.544 Mbps" 100000 => "100 Mbps" 10000000 => "10 Gbps" """ if not speed: return '' if speed >= 1000000000 and speed % 1000000000 == 0: return '{} Tbps'.format(int(speed / 1000000000)) elif speed >= 1000000 and speed % 1000000 == 0: return '{} Gbps'.format(int(speed / 1000000)) elif speed >= 1000 and speed % 1000 == 0: return '{} Mbps'.format(int(speed / 1000)) elif speed >= 1000: return '{} Mbps'.format(float(speed) / 1000) else: return '{} Kbps'.format(speed) @register.filter() def humanize_megabytes(mb): """ Express a number of megabytes in the most suitable unit (e.g. gigabytes or terabytes). """ if not mb: return '' if not mb % 1048576: # 1024^2 return f'{int(mb / 1048576)} TB' if not mb % 1024: return f'{int(mb / 1024)} GB' return f'{mb} MB' @register.filter() def simplify_decimal(value): """ Return the simplest expression of a decimal value. Examples: 1.00 => '1' 1.20 => '1.2' 1.23 => '1.23' """ if type(value) is not decimal.Decimal: return value return str(value).rstrip('0').rstrip('.') @register.filter(expects_localtime=True) def annotated_date(date_value): """ Returns date as HTML span with short date format as the content and the (long) date format as the title. """ if not date_value: return '' if type(date_value) == datetime.date: long_ts = date(date_value, 'DATE_FORMAT') short_ts = date(date_value, 'SHORT_DATE_FORMAT') else: long_ts = date(date_value, 'DATETIME_FORMAT') short_ts = date(date_value, 'SHORT_DATETIME_FORMAT') return mark_safe(f'<span title="{long_ts}">{short_ts}</span>') @register.simple_tag def annotated_now(): """ Returns the current date piped through the annotated_date filter. """ tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None return annotated_date(datetime.datetime.now(tz=tzinfo)) @register.filter() def divide(x, y): """ Return x/y (rounded). """ if x is None or y is None: return None return round(x / y) @register.filter() def percentage(x, y): """ Return x/y as a percentage. """ if x is None or y is None: return None return round(x / y * 100) @register.filter() def has_perms(user, permissions_list): """ Return True if the user has *all* permissions in the list. """ return user.has_perms(permissions_list) @register.filter() def as_range(n): """ Return a range of n items. """ try: int(n) except TypeError: return list() return range(n) @register.filter() def meters_to_feet(n): """ Convert a length from meters to feet. """ return float(n) * 3.28084 @register.filter("startswith") def startswith(text: str, starts: str) -> bool: """ Template implementation of `str.startswith()`. """ if isinstance(text, str): return text.startswith(starts) return False @register.filter def get_key(value: Dict, arg: str) -> Any: """ Template implementation of `dict.get()`, for accessing dict values by key when the key is not able to be used in a template. For example, `{"ui.colormode": "dark"}`. """ return value.get(arg, None) @register.filter def get_item(value: object, attr: str) -> Any: """ Template implementation of `__getitem__`, for accessing the `__getitem__` method of a class from a template. """ return value[attr] @register.filter def status_from_tag(tag: str = "info") -> str: """ Determine Bootstrap theme status/level from Django's Message.level_tag. """ status_map = { 'warning': 'bg-yellow-400', 'success': 'bg-green-400', 'error': 'bg-red-400', 'debug': 'bg-blue-400', 'info': 'bg-blue-400', } return status_map.get(tag.lower(), 'info') @register.filter def icon_from_status(status: str = "info") -> str: """ Determine icon class name from Bootstrap theme status/level. """ icon_map = { 'warning': 'alert', 'success': 'check-circle', 'danger': 'alert', 'info': 'information', } return icon_map.get(status.lower(), 'information') @register.filter def get_visible_components(value: any) -> Any: """ Template to return only visibly components """ return value.filter(visibility=True) @register.filter def get_historic_status(value: Component) -> Any: """ Template to return historic status """ num_days = 90 start_date = make_aware(datetime.datetime.today()) + datetime.timedelta(days=1) end_date = (start_date - datetime.timedelta(days=num_days)).replace(microsecond=0, second=0, minute=0, hour=0) date_list = [end_date + datetime.timedelta(days=x) for x in range(num_days)] component_incidents = value.incidents.all() status_svg = Svg(width=816, height=34) for index, date in enumerate(date_list): end = date + datetime.timedelta(days=1) incidents = list(filter(lambda i: date <= i.created <= end, component_incidents)) if len(list(filter(lambda i: i.impact == IncidentImpactChoices.CRITICAL, incidents))) > 0: status_svg.addElement(create_rect(index=index, date=date, incidents=len(incidents), fill="rgb(239, 68, 68)")) elif len(list(filter(lambda i: i.impact == IncidentImpactChoices.MAJOR, incidents))) > 0: status_svg.addElement(create_rect(index=index, date=date, incidents=len(incidents), fill="rgb(249, 115, 22)")) elif len(list(filter(lambda i: i.impact == IncidentImpactChoices.MINOR, incidents))) > 0: status_svg.addElement(create_rect(index=index, date=date, incidents=len(incidents), fill="rgb(234, 179, 8)")) else: status_svg.addElement(create_rect(index=index, date=date, incidents=len(incidents), fill="rgb(34, 197, 94)")) return mark_safe(status_svg.getXML()) @register.filter def join_components_with_groups(value: any) -> Any: """ Template to return only visibly components """ return mark_safe(", ".join(list(map(lambda c: f'{c.component_group.name} &mdash; {c.name}' if c.component_group else c.name, value)))) @register.filter def urlencode(value: str) -> Any: return urllib.parse.quote(value) # # Tags # @register.simple_tag() def querystring(request, **kwargs): """ Append or update the page number in a querystring. """ querydict = request.GET.copy() for k, v in kwargs.items(): if v is not None: querydict[k] = str(v) elif k in querydict: querydict.pop(k) querystring = querydict.urlencode(safe='/') if querystring: return '?' + querystring else: return '' @register.inclusion_tag('helpers/utilization_graph.html') def utilization_graph(utilization, warning_threshold=75, danger_threshold=90): """ Display a horizontal bar graph indicating a percentage of utilization. """ if utilization == 100: bar_class = 'bg-secondary' elif danger_threshold and utilization >= danger_threshold: bar_class = 'bg-danger' elif warning_threshold and utilization >= warning_threshold: bar_class = 'bg-warning' elif warning_threshold or danger_threshold: bar_class = 'bg-success' else: bar_class = 'bg-gray' return { 'utilization': utilization, 'bar_class': bar_class, } @register.inclusion_tag('helpers/table_config_form.html') def table_config_form(table, table_name=None): return { 'table_name': table_name or table.__class__.__name__, 'form': TableConfigForm(table=table), } @register.inclusion_tag('helpers/applied_filters.html') def applied_filters(form, query_params): """ Display the active filters for a given filter form. """ form.is_valid() applied_filters = [] for filter_name in form.changed_data: if filter_name not in form.cleaned_data: continue querydict = query_params.copy() if filter_name not in querydict: continue bound_field = form.fields[filter_name].get_bound_field(form, filter_name) querydict.pop(filter_name) display_value = ', '.join([str(v) for v in get_selected_values(form, filter_name)]) applied_filters.append({ 'name': filter_name, 'value': form.cleaned_data[filter_name], 'link_url': f'?{querydict.urlencode()}', 'link_text': f'{bound_field.label}: {display_value}', }) return { 'applied_filters': applied_filters, }
Status-Page/Status-Page
statuspage/utilities/templatetags/helpers.py
helpers.py
py
10,704
python
en
code
45
github-code
6
12950748282
#!/usr/bin/env python # coding: utf-8 # ## 3. Sphere of influence # In[1]: import matplotlib.pyplot as plt import numpy as np import scipy.integrate as spy G = 6.674e-11 #N*m^2/kg^2 # In[2]: class Body: def __init__(self, mass, radius,r0,v0): self.m = mass self.R = radius self.r0 = r0 self.v0 = v0 # In[3]: Earth = Body(5.972e24, 6371.0e3,np.array([152.10e9,0,0]),np.array([0,29.78e3,0])) #m, m/s Sun = Body(1.989e30, 695508e3, np.array([0,0,0]),np.array([0,0,0])) #m, m/s Mars = Body(0.64171e24, 3389.5e3, np.array([0,228.0e9,0]), np.array([24.07e3,0,0])) #m, m/s # #### Comet 67P/C-G: Churyumov–Gerasimenko # In[11]: Rosetta = Body(9.982e12, 0, np.array([0,0,0]), np.array([0,0,0])) #m, m/s r_a = 850150.0e6 #m r_p = 185980.0e6 #m # In[5]: # At perihelium rho = r_p #m R_i_p = rho*(Rosetta.m/Sun.m)**(2/5) print('Sphere of influence. R_i (perihelium) =',R_i_p/1e3,'km') # In[7]: # At apohelium rho = r_a #m R_i_a = rho*(Rosetta.m/Sun.m)**(2/5) print('Sphere of influence. R_i (apohelium) =',R_i_a/1e3,'km')
veronicasaz/AstrodynamicsScripts
SimpleExercises/SphereOfInfluence.py
SphereOfInfluence.py
py
1,078
python
en
code
1
github-code
6
25569721131
import numpy as np batch_size_dis = 64 # batch size for discriminator batch_size_gen = 63 # batch size for generator lambda_dis = 1e-5 # l2 loss regulation factor for discriminator lambda_gen = 1e-5 # l2 loss regulation factor for generator n_sample_dis = 20 # sample num for generator n_sample_gen = 20 # sample num for discriminator update_ratio = 1 # updating ratio when choose the trees save_steps = 10 lr_dis = 1e-4 # learning rate for discriminator lr_gen = 1e-3 # learning rate for discriminator max_epochs = 50 # outer loop number max_epochs_gen = 5 # loop number for generator max_epochs_dis = 5 # loop number for discriminator gen_for_d_iters = 10 # iteration numbers for generate new data for discriminator max_degree = 0 # the max node degree of the network model_log = "../log/iteration1/" use_mul = False # control if use the multiprocessing when constructing trees load_model = False # if load the model for continual training gen_update_iter = 200 window_size = 3 random_state = np.random.randint(0, 100000) app = "link_prediction" import_tree = False tree_path = "../../data/input/trees" train_filename = "../../data/input/toy-edges.txt" test_filename = "" test_neg_filename = "" n_embed = 300 n_node = 9890 pretrain_emd_filename_d = "../../data/input/embed.txt" pretrain_emd_filename_g = "../../data/input/embed.txt" modes = ["dis", "gen"] emb_filenames = ["../../data/output/toy_" + modes[0] + "_" + str(random_state) + ".emb", "../../data/output/toy_" + modes[1] + "_" + str(random_state) + ".emb"] result_filename = "../../data/output/toy_" + str(random_state) + ".txt" # for mr_predict test_data = "../../data/input/test.data" crossmap = "../../data/input/pickled.model" predict_type = ['w', 'l', 't'] node_dict = "../../data/input/node_dict111.txt"
PonderLY/NetworkEmbedding
GraphGAN/config.py
config.py
py
1,814
python
en
code
4
github-code
6
6829602172
# ==================================================== # Quantum Information and Computing exam project # # UNIPD Project | AY 2022/23 | QIC # group : Barone, Coppi, Zinesi # ---------------------------------------------------- # > description | # # dQA utilities: perceptron hamiltonian tools # ---------------------------------------------------- # coder : Barone Francesco, Zinesi Paolo # : github.com/baronefr/perceptron-dqa/ # dated : 17 March 2023 # ver : 1.0.0 # ==================================================== import numpy as np import matplotlib.pyplot as plt class PerceptronHamiltonian: def make_Ux(N, beta_p, dtype = np.complex128): """Return as MPO the U_x evolution operator at time-parameter beta_p.""" tb = np.array( [[np.cos(beta_p), 1j*np.sin(beta_p)],[1j*np.sin(beta_p), np.cos(beta_p)]], dtype=dtype) return [ np.expand_dims(tb, axis=(0,1)) for _ in range(N) ] def Wz(N, Uk : np.array, xi : int, marginal = None, dtype = np.complex128): """The tensors of Eq. 17 of reference paper.""" bond_dim = len(Uk) if marginal == 'l': shape = (1,bond_dim,2,2) elif marginal == 'r': shape = (bond_dim,1,2,2) else: shape = (bond_dim,bond_dim,2,2) tensor = np.zeros( shape, dtype = dtype ) coeff = np.power( Uk/np.sqrt(N+1), 1/N) exx = 1j * np.arange(bond_dim) * np.pi / (N + 1) # check: N+1 for kk in range(bond_dim): spin_matrix = np.diag( [ coeff[kk]*np.exp(exx[kk]*(1-xi)), coeff[kk]*np.exp(exx[kk]*(1+xi)) ] ) if marginal == 'l': tensor[0,kk,:,:] = spin_matrix elif marginal == 'r': tensor[kk,0,:,:] = spin_matrix else: tensor[kk,kk,:,:] = spin_matrix return tensor def make_Uz(N : int, Uk : np.array, xi : np.array, dtype = np.complex128): """Return as MPO the U_z evolution operator at time s_p (defined indirectly by Uk).""" # Uk must be a vector for all k values, while p is fixed # xi must be a single sample from dataset assert len(xi) == N, 'not matching dims' arrays = [ PerceptronHamiltonian.Wz(N, Uk, xi[0], marginal = 'l', dtype = dtype) ] + \ [ PerceptronHamiltonian.Wz(N, Uk, xi[i+1], dtype = dtype) for i in range(N-2) ] + \ [ PerceptronHamiltonian.Wz(N, Uk, xi[N-1], marginal = 'r', dtype = dtype) ] return arrays def h_perceptron(m, N): """ Cost function to be minimized in the perceptron model, depending on the overlap m. The total H_z Hamiltonian is obtained as a sum of these cost functions evaluated at each pattern csi_mu. h(m) = 0 if m>=0 else -m/sqrt(N) """ m = np.array(m) return np.where(m>=0, 0, -m/np.sqrt(N)).squeeze() def f_perceptron(x, N): """ Cost function to be minimized in the perceptron model, depending on the Hamming distance x. The total H_z Hamiltonian is obtained as a sum of these cost functions evaluated at each pattern csi_mu. f(x) = h(N - 2x) = h(m(x)) with m(x) = N - 2x """ m = N - 2*np.asarray(x) return PerceptronHamiltonian.h_perceptron(m, N) def Hz_mu_singleK(N, mu, K, f_FT_, patterns): """ Build factorized Hz^{mu,k} (bond dimension = 1) on N sites""" d = 2 Hz_i = [] for i in range(1,N+1): tens = np.zeros((1,1,d,d), dtype=np.complex128) for s_i in range(d): tens[0,0,s_i,s_i] = np.power(f_FT_[K]/np.sqrt(N+1), 1/N) * np.exp(1.0j * (np.pi/(N+1)) * K * (1-patterns[mu,i-1]*(-1)**s_i)) Hz_i.append(tens) return Hz_i def create_dataset(N : int, features : int): """Create dataset as described by ref. paper, i.e. random +-1 values.""" x = np.random.randint(2, size=(N, features)) x[ x == 0 ] = -1 # data is encoded as +- 1 return x
baronefr/perceptron-dqa
lib/dQA_utils.py
dQA_utils.py
py
4,128
python
en
code
2
github-code
6
37018522643
import numpy as np import statsmodels.api as sm np.random.seed(2021) mu = 0 sigma = 1 # number of observations n = 100 alpha = np.repeat(0.5, n) beta = 1.5 def MC_estimation_slope(M): MC_betas = [] MC_samples = {} for i in range(M): # to make sure the variance in X is bigger than the variance in the error term X = 9 * np.random.normal(mu, sigma, n) # random error term e = np.random.normal(mu, sigma, n) # determining Y Y = (alpha + beta * X + e) MC_samples[i] = Y # running regression model = sm.OLS(Y.reshape((-1, 1)), X.reshape((-1, 1))) ols_result = model.fit() # getting model slope coeff = ols_result.params MC_betas.append(coeff) MC_beta_hats = np.array(MC_betas).flatten() return (MC_samples, MC_beta_hats) MS_samples, MC_beta_hats = MC_estimation_slope(M = 10000) beta_hat_MC = np.mean(MC_beta_hats) print(MC_beta_hats) print(beta_hat_MC)
TatevKaren/mathematics-statistics-for-data-science
Statistical Sampling/Monte Carlo Simulation OLS estimate.py
Monte Carlo Simulation OLS estimate.py
py
985
python
en
code
88
github-code
6
45484267256
from setuptools import setup, find_packages __version__ = '0.8.6' with open('README.rst', 'r', encoding='utf-8') as fh: long_description = fh.read() setup( name='LMRt', # required version=__version__, description='LMR turbo', long_description=long_description, long_description_content_type='text/x-rst', author='Feng Zhu', author_email='[email protected]', url='https://github.com/fzhu2e/LMRt', packages=find_packages(), include_package_data=True, license='GPL-3.0 license', zip_safe=False, scripts=['bin/LMRt'], keywords='LMRt', classifiers=[ 'Natural Language :: English', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], install_requires=[ 'termcolor', 'pyyaml', 'pandas', 'cftime', 'tqdm', 'xarray', 'netCDF4', 'statsmodels', 'seaborn', 'pyleoclim', 'pyvsl', 'pyresample', 'fbm', ], )
fzhu2e/LMRt
setup.py
setup.py
py
1,031
python
en
code
9
github-code
6
17371125676
from django.contrib import admin from django.contrib.auth import get_user_model User = get_user_model() class UserAdmin(admin.ModelAdmin): list_display = ( 'id', 'first_name', 'last_name', 'username', 'email', 'balance', 'freeze_balance', 'role', ) admin.site.register(User, UserAdmin)
vavsar/freelance_t
users/admin.py
admin.py
py
363
python
en
code
1
github-code
6
7938194140
import pytesseract from PIL import Image import cv2 # Path to the Tesseract executable (you might not need this on Ubuntu) # pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract' # You may need to set the correct path to Tesseract on your system # Open an image file image_path = 'image.jpeg' img = Image.open(image_path) # Use pytesseract to do OCR on the image text = pytesseract.image_to_string(img) # Print the extracted text print(text) image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) cv2.imshow("", image) cv2.waitKey(0) cv2.destroyAllWindows()
KolKemboi/AiMazing
OCR.py
OCR.py
py
572
python
en
code
0
github-code
6
4728965077
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 11 10:19:22 2018 @author: psanch """ import tensorflow as tf from sklearn.manifold import TSNE import matplotlib.pyplot as plt import numpy as np import utils.utils as utils class BaseVisualize: def __init__(self, model_name, result_dir, fig_fize): self.model_name = model_name self.result_dir = result_dir self.fig_size = fig_fize self.colors = {0:'black', 1:'grey', 2:'blue', 3:'cyan', 4:'lime', 5:'green', 6:'yellow', 7:'gold', 8:'red', 9:'maroon'} def save_img(self, fig, name): utils.save_img(fig, self.model_name, name, self.result_dir) return def reduce_dimensionality(self, var, perplexity=10): dim = var.shape[-1] if(dim>2): tsne = TSNE(perplexity=perplexity, n_components=2, init='pca', n_iter=1000) var_2d = tsne.fit_transform(var) else: var_2d = np.asarray(var) return var def scatter_variable(self, var, labels, title, perplexity=10): f, axarr = plt.subplots(1, 1, figsize=self.fig_size) var_2d = self.reduce_dimensionality(var) if(labels is not None): for number, color in self.colors.items(): axarr.scatter(x=var_2d[labels==number, 0], y=var_2d[labels==number, 1], color=color, label=str(number)) axarr.legend() else: axarr.scatter(x=var_2d[:, 0], y=var_2d[:, 1], color=self.colors[2]) axarr.grid() f.suptitle(title, fontsize=20) return f
psanch21/VAE-GMVAE
base/base_visualize.py
base_visualize.py
py
1,607
python
en
code
197
github-code
6
8564353511
import tkinter as tk import random from sql import SqlInject LARGE_FONT = ("Verdana", 12) data = SqlInject() class GuiFood(tk.Tk): def __init__(self, data=data, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.database = data self.value1 = tk.StringVar() self.user_choice = "purée" self.user_product_name = "Purée de Pois Cassés " self.user_product_data = [] self.subs_product_data = [] self.frames = {} self.all_frames = (StartPage, ChooseCate, ChooseFood, FoodInfo, SubsFood, SaveSearch) for F in self.all_frames: frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Start Page", font=LARGE_FONT) label.pack(pady=10, padx=10) button = tk.Button(self, text="Substituer un aliment", command=lambda: controller.show_frame(ChooseCate)) button.pack() button2 = tk.Button(self, text="Retrouver mes aliments substitués.", command=lambda: controller.show_frame(SaveSearch)) button2.pack() class ChooseCate(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Choix de l'aliment a substituer", font=LARGE_FONT) label.pack(pady=10, padx=10) vals = controller.database.get_category() etiqs = controller.database.get_category() self.varCatch = tk.StringVar() # define type of variable catching self.choice = None def get_value(): controller.user_choice = self.varCatch.get() frame = ChooseFood(parent, controller) controller.frames[ChooseFood] = frame frame.grid(row=0, column=0, sticky="nsew") for i in range(len(vals)): b = tk.Radiobutton(self, variable=self.varCatch, text=etiqs[i], value=vals[i], command=lambda: [get_value(), controller.show_frame(ChooseFood)]) b.pack(side="top", expand=1) button1 = tk.Button(self, text="Retour au menu", command=lambda: controller.show_frame(StartPage)) button1.pack() class ChooseFood(tk.Frame): def __init__(self, parent, controller): self.controller = controller self.choice_cate = self.controller.user_choice tk.Frame.__init__(self, parent) label = tk.Label(self, text=str(self.choice_cate), font=LARGE_FONT) label.pack(side="top") food_data = controller.database.get_categorized_food(self.choice_cate) list = tk.Listbox(self) for i in food_data: list.insert(i[0], i[2]) list.pack() button2 = tk.Button(self, text="Afficher les infos", command=lambda:[info_food(), controller.show_frame(FoodInfo)]) button2.pack() button1 = tk.Button(self, text="Retour au Menu", command=lambda: controller.show_frame(StartPage)) button1.pack() def info_food(): controller.user_product_name = list.get(list.curselection()) frame = FoodInfo(parent, controller) controller.frames[FoodInfo] = frame frame.grid(row=0, column=0, sticky="nsew") class FoodInfo(tk.Frame): def __init__(self, parent, controller): self.controller = controller self.choice_info = self.controller.user_product_name tk.Frame.__init__(self, parent) food_data = controller.database.get_data_product(column="product_name", search=self.choice_info) column_name = ["nutriscore","nom du produit","Nom générique","Magasin","Marques","url"] for col, data in zip(column_name, food_data[0][1:-1]): label = tk.Label(self, text=str(col)+" : "+str(data)+"\n", font=LARGE_FONT) label.pack(side="top") button1 = tk.Button(self, text="Retour au Menu", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = tk.Button(self, text="Substituer cet aliment", command=lambda:[substitute_food(), controller.show_frame(SubsFood)]) button2.pack() def substitute_food(): controller.user_product_data = food_data frame = SubsFood(parent, controller) controller.frames[SubsFood] = frame frame.grid(row=0, column=0, sticky="nsew") class SubsFood(tk.Frame): def __init__(self, parent, controller): self.controller = controller self.cate = self.controller.user_choice tk.Frame.__init__(self, parent) food_data = controller.database.get_substitute(self.cate)[random.randrange(0,2)] column_name = ["nutriscore", "nom du produit", "Nom générique", "Magasin", "Marques", "url"] for col, data in zip(column_name, food_data[1:-1]): label = tk.Label(self, text=str(col)+" : "+str(data)+"\n", font=LARGE_FONT) label.pack(side="top") button1 = tk.Button(self, text="Retour au Menu", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = tk.Button(self, text="Sauvegarder?", command= lambda: save_search()) button2.pack() def save_search(): prod_id = controller.user_product_data[0][0] controller.database.save_substitute(product_id=int(prod_id), substitute_id=int(food_data[0])) frame = StartPage(parent, controller) controller.frames[StartPage] = frame frame.grid(row=0, column=0, sticky="nsew") class SaveSearch(tk.Frame): def __init__(self, parent, controller): self.controller = controller self.save = controller.database.get_save_substitute() print(str(self.save)) tk.Frame.__init__(self, parent) for i in self.save: product_name = controller.database.get_data_product(search=i[1])[0][2] substitute_name = controller.database.get_data_product(search=i[2])[0][2] label = tk.Label(self, text=str(product_name)+" ==> "+str(substitute_name)+"\n", font=LARGE_FONT) label.pack(side="top") if __name__ == '__main__': app = GuiFood() app.mainloop()
Bainard/activite5
newgui.py
newgui.py
py
6,917
python
en
code
0
github-code
6
12580230297
from django.shortcuts import render from django.http import JsonResponse import openai # Create your views here. openai_api_key='MI-API-KEY' openai.api_key=openai_api_key def ask_openai(message): response = openai.Completion.create( model = "text-davinci-003", prompt= message, max_tokens=150, n=1, stop= None, temperature=0.7, ) answer = response.choices[0].text.strip() answer = "Miau... " + answer + " ...Miau" return answer def chatbot(request): if request.method=='POST': message = request.POST.get('message') sarcastic_order = "Quiero que actúes como una persona sarcástica. " message = sarcastic_order + message response = ask_openai(message) return JsonResponse({'message':message, 'response':response}) return render(request, 'chatbot.html')
elgualas/MichiAI
chatbot/views.py
views.py
py
880
python
en
code
0
github-code
6
2734136284
# -*- coding: utf-8 -*- """ @project ensepro @since 25/02/2018 @author Alencar Rodrigo Hentges <[email protected]> """ import json import logging from ensepro.constantes import ConfiguracoesConstantes, StringConstantes, LoggerConstantes def __init_logger(): global logger logging.basicConfig( filename=ConfiguracoesConstantes.ENSEPRO_PATH + __get_config(LoggerConstantes.NOME_DO_ARQUIVO), level=logging.INFO, format=__get_config(LoggerConstantes.FORMATO), filemode=__get_config(LoggerConstantes.MODO_DO_ARQUIVO), ) logger = logging.getLogger(LoggerConstantes.GET_LOGGER_MODULO.format(modulo=LoggerConstantes.MODULO_CONFIGURACOES)) logger.setLevel(logging.getLevelName(__get_config(LoggerConstantes.NIVEL_LOG_MODULO.format(modulo=LoggerConstantes.MODULO_CONFIGURACOES)))) def __carregar_configuracoes(): global __configs __configs = json.loads(open( file=ConfiguracoesConstantes.ARQUIVO_CONFIGURACOES, mode=StringConstantes.FILE_READ_ONLY, encoding=StringConstantes.UTF_8 ).read()) def __get_config(path): value = __configs _path = path.split(".") for key in _path: value = value[key] return value def get_config(path: str, path_params=None, config_params=None): """ Obtém a configuração (<i>path</i>) do arquivo de configuração. :param path: caminho da configuração no arquivo json, separada por ponto('.'). :param path_params: mapa com os parametros necessários para preencher o caminho da configuração. :param config_params: mapa com os parametros necessários para completar a configuração obtida :return: """ logger.debug("Obtendo configuração: [path=%s, path_params=%s, config_params=%s]", path, path_params, config_params) if path_params: path = path.format_map(path_params) config = __get_config(path) if config_params: return config.format_map(config_params) logger.info("Configuração obtida: [path=%s] = %s", path, config) return config __carregar_configuracoes() __init_logger()
Ensepro/ensepro-core
ensepro/configuracoes/configuracoes.py
configuracoes.py
py
2,135
python
pt
code
1
github-code
6
40176969885
from setuptools import setup, find_packages VERSION = "0.0.6" DESCRIPTION = "Investopedia simulator trading API" LONG_DESCRIPTION = ( "An API that allows trading with stock simulator for from Investopedia" ) install_requires = ["selenium", "schedule"] setup( name="simulatorTradingApi", version=VERSION, author="Michael Chi", author_email="[email protected]", description=DESCRIPTION, long_description=LONG_DESCRIPTION, packages=find_packages(), install_requires=install_requires, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires=">=3.7", include_package_data=True, )
mchigit/investopedia-simulator-api
setup.py
setup.py
py
752
python
en
code
0
github-code
6
5892500320
import tkinter import requests import ujson import datetime from PIL import ImageTk,Image from tkinter import ttk from concurrent import futures # pip install: requests, pillow, ujson #region Static Requests key = 0000000000 #<-- Riot developer key needed. # ----------- Request Session ----------- sessionSummoner = requests.Session() sessionRank = requests.Session() sessionMatch = requests.Session() sessionMatchList = requests.Session() # ----------- Current Patch ----------- patchesJson = requests.get("https://ddragon.leagueoflegends.com/api/versions.json") patches = ujson.loads(patchesJson.text) currentPatch = patches[0] # ----------- Static League Data ----------- summonerSpellJsonData = requests.get(f"http://ddragon.leagueoflegends.com/cdn/{currentPatch}/data/en_US/summoner.json") summonerSpellRawData = ujson.loads(summonerSpellJsonData.text)["data"] mapListJsonData = requests.get("https://static.developer.riotgames.com/docs/lol/maps.json") mapListRawData = ujson.loads(mapListJsonData.text) #endregion root = tkinter.Tk() root.title("League Quick Data") root.iconbitmap("LQ.ico") root.configure(background = "black") root.resizable(False, False) #region Languages class ChangeRegion: def __init__(self, languageDict = None, buttonSearchLang = None, sessionRegionLang = None, matchResultLang = None): self.languageDict = languageDict self.buttonSearchLang = buttonSearchLang self.sessionRegionLang = sessionRegionLang self.matchResultLang = matchResultLang def CreateDict(self): self.languageDict = {"searchButton":["BUSCAR", "SEARCH"], "sessionRegion":["BR", "NA"], "gameResult":[["VITORIA", "DERROTA"], ["VICTORY", "DEFEAT"]]} self.buttonSearchLang = self.languageDict["searchButton"][0] self.sessionRegionLang = self.languageDict["sessionRegion"][0] self.matchResultLang = self.languageDict["gameResult"][0] def RegionNA(self, buttonSearch, buttonBR, buttonNA): self.buttonSearchLang = self.languageDict["searchButton"][1] self.sessionRegionLang = self.languageDict["sessionRegion"][1] self.matchResultLang = self.languageDict["gameResult"][1] buttonSearch.configure(text = self.buttonSearchLang) buttonBR.configure(background = "black") buttonNA.configure(background = "#10293f") def RegionBR(self, buttonSearch, buttonBR, buttonNA): self.buttonSearchLang = self.languageDict["searchButton"][0] self.sessionRegionLang = self.languageDict["sessionRegion"][0] self.matchResultLang = self.languageDict["gameResult"][0] buttonSearch.configure(text = self.buttonSearchLang) buttonBR.configure(background = "#10293f") buttonNA.configure(background = "black") regionMethods = ChangeRegion() regionMethods.CreateDict() #endregion # ----------- Search Button ----------- searchButtonBorder = tkinter.Frame(root, background = "#048195") searchButtonBorder.grid(row = 0, column = 2, sticky = "nswe") searchButtonBorder.grid_columnconfigure(0, weight = 1) searchButton = tkinter.Label(searchButtonBorder, text = "BUSCAR", font = ("", 8, "bold"), background = "black", foreground = "white", borderwidth = 3) searchButton.grid(row = 0, column = 0, sticky = "nswe", padx = 2, pady = 2) # ----------- Region Buttons ----------- languageFrame = tkinter.Frame(root, width = 10, background = "#024e64") languageFrame.grid(row = 0, column = 4, sticky = "e") brButton = tkinter.Button(languageFrame, width = 3, text = "BR", font = ("Arial", 9, "bold"), activebackground = "#07141f", activeforeground = "white", foreground = "white", background = "black", relief = "ridge", borderwidth = 0, command = lambda: regionMethods.RegionBR(searchButton, brButton, naButton)) brButton.grid(row = 0, column = 0, padx = 1, pady = 1) naButton = tkinter.Button(languageFrame, width = 3, text = "NA", font = ("Arial", 9, "bold"), activebackground = "#07141f", activeforeground = "white", foreground = "white", background = "black", relief = "ridge", borderwidth = 0, command = lambda: regionMethods.RegionNA(searchButton, brButton, naButton)) naButton.grid(row = 0, column = 1, padx = 1, pady = 1) regionMethods.RegionBR(searchButton, brButton, naButton) # ----------- Scrollbar Style ----------- style = ttk.Style() style.theme_use("classic") style.map("TScrollbar", background=[('pressed', '!focus', '#ae914b')], relief=[('pressed', 'flat')]) style.configure("TScrollbar", troughcolor = "black", relief = "flat", background = "#775829", arrowsize = 0, width = 5, borderwidth = 0) #region Entries player1 = tkinter.Entry(root, width = 22, background = "black", foreground = "white", borderwidth = 0, highlightthickness = 2, highlightcolor = "#775829", highlightbackground = "#775829", insertbackground = "light grey", insertborderwidth = 1, relief= "ridge") player1.grid(row = 1, column = 0, sticky = "we") player2 = tkinter.Entry(root, width = 22, background = "black", foreground = "white", borderwidth = 0, highlightthickness = 2, highlightcolor = "#775829", highlightbackground = "#775829", insertbackground = "light grey", insertborderwidth = 1, relief= "ridge") player2.grid(row = 1, column = 1, sticky = "we") player3 = tkinter.Entry(root, width = 22, background = "black", foreground = "white", borderwidth = 0, highlightthickness = 2, highlightcolor = "#775829", highlightbackground = "#775829", insertbackground = "light grey", insertborderwidth = 1, relief= "ridge") player3.grid(row = 1, column = 2, sticky = "we") player4 = tkinter.Entry(root, width = 22, background = "black", foreground = "white", borderwidth = 0, highlightthickness = 2, highlightcolor = "#775829", highlightbackground = "#775829", insertbackground = "light grey", insertborderwidth = 1, relief= "ridge") player4.grid(row = 1, column = 3, sticky = "we") player5 = tkinter.Entry(root, width = 22, background = "black", foreground = "white", borderwidth = 0, highlightthickness = 2, highlightcolor = "#775829", highlightbackground = "#775829", insertbackground = "light grey", insertborderwidth = 1, relief= "ridge") player5.grid(row = 1, column = 4, sticky = "we") playerArray = [player1, player2, player3, player4, player5] #endregion #region Gui creation methods scrollBarArray = [0, 0, 0, 0, 0] # ----------- Frame Buttons ----------- playerHistoryButtonArray = [0, 0, 0, 0, 0] def CreateButtonBG(): for i in range(5): if playerArray[i].get(): buttonBackground = tkinter.Label(root, background = "black", foreground = "white") buttonBackground.grid(row = 2, columnspan = 5, sticky = "nswe") break if i == 4: buttonBackground = tkinter.Label(root, background = "black", foreground = "white", text = "Null") buttonBackground.grid(row = 2, columnspan = 5, sticky = "nswe") def CreateHistoryButton(playerNumber): historyButtonBorder = tkinter.Frame(root, background = "#ae914b") historyButtonBorder.grid(row = 2, column = playerNumber, sticky = "we") historyButtonBorder.grid_columnconfigure(0, weight = 1) playerHistoryButton = tkinter.Label(historyButtonBorder, text = playerArray[playerNumber].get(), font = ("", 9, "bold"), background = "#0e191d", foreground = "#fff6d6", borderwidth = 2) playerHistoryButton.grid(row = 0, column = 0, sticky = "we", padx = 1, pady = 1) playerHistoryButtonArray[playerNumber] = playerHistoryButton # ----------- Frames ----------- scrollableMainFrameArray = [0, 0, 0, 0, 0] historyFrameArray = [0, 0, 0, 0, 0] def CreateHistoryFrame(playerNumber): scrollableFrame = tkinter.Frame(root, height = 450, width = 680, background = "black") scrollableFrame.grid(row = 4, columnspan = 5, sticky = "nsew") scrollableFrame.grid_columnconfigure((0, 1), weight = 1) canvasLayout = tkinter.Canvas(scrollableFrame, height = 450, width = 680, background = "black", highlightthickness = 0, scrollregion = (0, 0, 0, 980)) canvasLayout.grid(row=0, column = 0, sticky = "nsew") historyFrame = tkinter.Frame(canvasLayout, height = 450, width = 680, background = "black") canvasLayout.create_window((0, 0), window = historyFrame, anchor = "nw") scrollbar = ttk.Scrollbar(scrollableFrame, orient = "vertical", command = canvasLayout.yview) scrollbar.grid(row = 0, column = 1, sticky = "nse", padx = (4, 3), pady = (0, 3)) canvasLayout.configure(yscrollcommand = scrollbar.set) # ----------- Scroll Function ----------- def MouseWheelMove(event): canvasLayout.yview_scroll(-1 * (event.delta // 120), "units") scrollbar.bind_all("<MouseWheel>", MouseWheelMove) scrollableMainFrameArray[playerNumber] = scrollableFrame historyFrameArray[playerNumber] = historyFrame # ----------- Match Previews ----------- playerMatchArray = [0, 0, 0, 0, 0] def CreateMatchPreview(playerNumber): matchArray = [] for i in range(11): if i == 0: ProfileSummary.CreateProfileFrame(playerNumber) else: match = tkinter.Frame(historyFrameArray[playerNumber], height = 85, width = 680, background = "black") match.grid(pady = (6, 0), columnspan = 5) match.grid_rowconfigure((0,1) , weight = 1) match.grid_columnconfigure((0,1,2,3) , weight = 1) match.grid_propagate(False) matchArray.append(match) playerMatchArray[playerNumber] = matchArray #endregion #region Classes championCircleFrame = ImageTk.PhotoImage(Image.open("circlebig.png").resize((75, 75))) levelCircleFrame = ImageTk.PhotoImage(Image.open("circlesma.png").resize((23, 23))) minionIcon = ImageTk.PhotoImage(Image.open("minion.png").resize((11, 13))) goldIcon = ImageTk.PhotoImage(Image.open("gold.png").resize((15, 12))) itemList1 = [[],[],[],[],[],[],[],[],[],[]] itemList2 = [[],[],[],[],[],[],[],[],[],[]] itemList3 = [[],[],[],[],[],[],[],[],[],[]] itemList4 = [[],[],[],[],[],[],[],[],[],[]] itemList5 = [[],[],[],[],[],[],[],[],[],[]] spellList1 = [[],[],[],[],[],[],[],[],[],[]] spellList2 = [[],[],[],[],[],[],[],[],[],[]] spellList3 = [[],[],[],[],[],[],[],[],[],[]] spellList4 = [[],[],[],[],[],[],[],[],[],[]] spellList5 = [[],[],[],[],[],[],[],[],[],[]] championList = [[],[],[],[],[],[],[],[],[],[]] summaryChampionIconArray = [[],[],[],[],[]] profileSummaryArray = [0, 0, 0, 0, 0] # ----------- Get Data ----------- class SummaryStats: def __init__(self, matchesWon = None, matchesLost = None, averageKill = None, averageDeath = None, averageAssist = None, championDictOrder = None): self.matchesWon = matchesWon self.matchesLost = matchesLost self.averageKill = averageKill self.averageDeath = averageDeath self.averageAssist = averageAssist self.championDictOrder = championDictOrder def GetSummaryWins(self, matchRawDataArray, playerPuuid): #Recent win/lose/winrate self.matchesWon = 0 self.matchesLost = 0 for i in range(10): if len(matchRawDataArray) >= i + 1: participants = matchRawDataArray[i]["metadata"]["participants"] if matchRawDataArray[i]["info"]["participants"][participants.index(playerPuuid)]["win"]: self.matchesWon += 1 else: self.matchesLost += 1 def GetSummaryKda(self, matchRawDataArray, playerPuuid): #Player kda self.averageKill = 0 self.averageDeath = 0 self.averageAssist = 0 for i in range(10): if len(matchRawDataArray) >= i + 1: participants = matchRawDataArray[i]["metadata"]["participants"] self.averageKill += matchRawDataArray[i]["info"]["participants"][participants.index(playerPuuid)]["kills"] self.averageDeath += matchRawDataArray[i]["info"]["participants"][participants.index(playerPuuid)]["deaths"] self.averageAssist += matchRawDataArray[i]["info"]["participants"][participants.index(playerPuuid)]["assists"] def GetSummaryChampions(self, matchRawDataArray, playerPuuid, player): championDict = {} participantsArray = [] championPlayedArray = [] # ----------- Recent Champion Names ----------- for i in range(10): if len(matchRawDataArray) >= i + 1: participants = matchRawDataArray[i]["metadata"]["participants"] participantsArray.append(participants) championPlayedArray.append(matchRawDataArray[i]["info"]["participants"][participants.index(playerPuuid)]["championName"]) # ----------- Match Result ----------- championIndex = 0 for i in championPlayedArray: if i in championDict: if matchRawDataArray[championIndex]["info"]["participants"][participantsArray[championIndex].index(playerPuuid)]["win"]: championDict[i][1] += 1 else: championDict[i][2] += 1 else: if matchRawDataArray[championIndex]["info"]["participants"][participantsArray[championIndex].index(playerPuuid)]["win"]: championDict[i] = [[0, 0, 0], 1, 0] else: championDict[i] = [[0, 0, 0], 0, 1] championIndex += 1 # ----------- Recent Champion Names ----------- for i in range(10): if len(matchRawDataArray) >= i + 1: championName = matchRawDataArray[i]["info"]["participants"][participantsArray[i].index(playerPuuid)]["championName"] championDict[championName][0][0] += matchRawDataArray[i]["info"]["participants"][participantsArray[i].index(playerPuuid)]["kills"] championDict[championName][0][1] += matchRawDataArray[i]["info"]["participants"][participantsArray[i].index(playerPuuid)]["deaths"] championDict[championName][0][2] += matchRawDataArray[i]["info"]["participants"][participantsArray[i].index(playerPuuid)]["assists"] # ----------- Sort Dictionary ----------- self.championDictOrder = [[key, value] for (key, value) in championDict.items()] for i in range(len(championDict)): aux = 0 for j in range(len(championDict) - 1): if (self.championDictOrder[j][1][1] + self.championDictOrder[j][1][2]) < (self.championDictOrder[j + 1][1][1] + self.championDictOrder[j + 1][1][2]): aux = self.championDictOrder[j + 1] self.championDictOrder[j + 1] = self.championDictOrder[j] self.championDictOrder[j] = aux # ----------- Champion Icon ----------- for i in range(3): if len(self.championDictOrder) >= i + 1: try: image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.championDictOrder[i][0]}.png").resize((32,32))) except: response = requests.get(f"http://ddragon.leagueoflegends.com/cdn/{currentPatch}/img/champion/{self.championDictOrder[i][0]}.png") if response.status_code == 200: open(f"datadragon/{self.championDictOrder[i][0]}.png", 'wb').write(response.content) image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.championDictOrder[i][0]}.png").resize((32, 32))) summaryChampionIconArray[player].append(image) class PlayerStats: def __init__(self, playerPuuid = None, encryptedSummonerId = None, playerRank = None): self.playerPuuid = playerPuuid #"puuid" - summoner api self.encryptedSummonerId = encryptedSummonerId #"id" - summoner api self.playerRank = playerRank #"tier + rank" - leagueV4 api def PlayerDataRequest(self, name): if regionMethods.sessionRegionLang == "BR": playerJsonData = sessionSummoner.get(f"https://br1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{name}?api_key={key}") playerRawData = ujson.loads(playerJsonData.text) else: playerJsonData = sessionSummoner.get(f"https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{name}?api_key={key}") playerRawData = ujson.loads(playerJsonData.text) try: self.playerPuuid = playerRawData["puuid"] self.encryptedSummonerId = playerRawData["id"] print(self.playerPuuid) except: return 0 else: return 1 def PlayerRankRequest(self): if regionMethods.sessionRegionLang == "BR": playerRankJsonData = sessionRank.get(f"https://br1.api.riotgames.com/lol/league/v4/entries/by-summoner/{self.encryptedSummonerId}?api_key={key}") playerRankRawData = ujson.loads(playerRankJsonData.text) else: playerRankJsonData = sessionRank.get(f"https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/{self.encryptedSummonerId}?api_key={key}") playerRankRawData = ujson.loads(playerRankJsonData.text) try: self.playerRank = playerRankRawData[0]["tier"] + " " + playerRankRawData[0]["rank"] if playerRankRawData[0]["tier"] == "MASTER" or "GRANDMASTER" or "CHALLANGER": self.playerRank = playerRankRawData[0]["tier"] except: self.playerRank = "Unranked" class MatchStatsChampion: def __init__(self, championId = None, championLevel = None): self.championId = championId #"championId" - match api self.championLevel = championLevel #"champLevel" - #match api def MatchStatsChampionRequest(self, matchRawData, playerKey, player): participants = matchRawData["metadata"]["participants"] self.championId = matchRawData["info"]["participants"][participants.index(playerKey)]["championName"] self.championLevel = matchRawData["info"]["participants"][participants.index(playerKey)]["champLevel"] try: image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.championId}.png").resize((60,60))) except: response = requests.get(f"http://ddragon.leagueoflegends.com/cdn/{currentPatch}/img/champion/{self.championId}.png") if response.status_code == 200: open(f"datadragon/{self.championId}.png", 'wb').write(response.content) image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.championId}.png").resize((60,60))) championList[player].append(image) class MatchStatsSpells: def __init__(self, spellArrayIds = None, spellSpriteName = None): self.spellArrayIds = spellArrayIds #["Summoner1Id", "Summoner2Id"] - #match api self.spellSpriteName = spellSpriteName #[spells[0], spells[1]] - #key in http://ddragon.leagueoflegends.com/cdn/11.19.1/data/en_US/summoner.json def MatchStatsSpellsRequest(self, matchRawData, playerKey): participants = matchRawData["metadata"]["participants"] self.spellArrayIds = [0, 0] self.spellSpriteName = [0, 0] self.spellArrayIds[0] = matchRawData["info"]["participants"][participants.index(playerKey)]["summoner1Id"] self.spellArrayIds[1] = matchRawData["info"]["participants"][participants.index(playerKey)]["summoner2Id"] for spellDict in summonerSpellRawData.values(): if spellDict["key"] == f"{self.spellArrayIds[0]}": self.spellSpriteName[0] = (spellDict["id"]) elif spellDict["key"] == f"{self.spellArrayIds[1]}": self.spellSpriteName[1] = (spellDict["id"]) def GetSpellSprites(self, player, preview): for i in range(2): if self.spellSpriteName[i] != 0: try: image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.spellSpriteName[i]}.png").resize((18, 18))) except: response = requests.get(f"http://ddragon.leagueoflegends.com/cdn/{currentPatch}/img/spell/{self.spellSpriteName[i]}.png") if response.status_code == 200: open(f"datadragon/{self.spellSpriteName[i]}.png", 'wb').write(response.content) image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.spellSpriteName[i]}.png").resize((18, 18))) if player == 0: spellList1[preview].append(image) elif player == 1: spellList2[preview].append(image) elif player == 2: spellList3[preview].append(image) elif player == 3: spellList4[preview].append(image) elif player == 4: spellList5[preview].append(image) if player == 0: return spellList1 elif player == 1: return spellList2 elif player == 2: return spellList3 elif player == 3: return spellList4 elif player == 4: return spellList5 class MatchStatsItems: def __init__(self, itemArray = None): self.itemArray = itemArray #["num", "num", "num", "num", "num", "num", "num"] - #match api def MatchStatsItemsRequests(self, matchRawData, playerKey): participants = matchRawData["metadata"]["participants"] self.itemArray = [] for i in range(7): self.itemArray.append(matchRawData["info"]["participants"][participants.index(playerKey)][f"item{i}"]) def GetItemSprites(self, player, preview): for i in range(7): if self.itemArray[i] != 0: try: image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.itemArray[i]}.png").resize((32, 32))) except: response = requests.get(f"http://ddragon.leagueoflegends.com/cdn/{currentPatch}/img/item/{self.itemArray[i]}.png") if response.status_code == 200: open(f"datadragon/{self.itemArray[i]}.png", 'wb').write(response.content) image = ImageTk.PhotoImage(Image.open(f"datadragon/{self.itemArray[i]}.png").resize((32, 32))) if player == 0: itemList1[preview].append(image) elif player == 1: itemList2[preview].append(image) elif player == 2: itemList3[preview].append(image) elif player == 3: itemList4[preview].append(image) elif player == 4: itemList5[preview].append(image) if player == 0: return itemList1 elif player == 1: return itemList2 elif player == 2: return itemList3 elif player == 3: return itemList4 elif player == 4: return itemList5 class MatchStatsPlayer: def __init__(self, playerKills = None, playerDeaths = None, playerAssists = None, playerMinions = None, playerGold = None): self.playerKills = playerKills #"kill" - match api self.playerDeaths = playerDeaths #"death" - match api self.playerAssists = playerAssists #"assist" - match api self.playerMinions = playerMinions #"totalMinionsKilled" - match api self.playerGold = playerGold #"goldEarned" - match api def MatchStatsPlayerRequest(self, matchRawData, playerKey): participants = matchRawData["metadata"]["participants"] self.playerKills = matchRawData["info"]["participants"][participants.index(playerKey)]["kills"] self.playerDeaths = matchRawData["info"]["participants"][participants.index(playerKey)]["deaths"] self.playerAssists = matchRawData["info"]["participants"][participants.index(playerKey)]["assists"] self.playerMinions = matchRawData["info"]["participants"][participants.index(playerKey)]["totalMinionsKilled"] self.playerGold = matchRawData["info"]["participants"][participants.index(playerKey)]["goldEarned"] self.playerGold = '{:,}'.format(self.playerGold).replace(",", ".") def ScoreConstructor(self): return f"{self.playerKills} / {self.playerDeaths} / {self.playerAssists}" class MatchStatsGame: def __init__(self, mapId = None, mapName = None, gameMode = None, gameCreation = None, gameDuration = None, matchResult = None): self.mapId = mapId #"mapId" - match api self.mapName = mapName #mapId > mapName https://static.developer.riotgames.com/docs/lol/maps.json self.gameMode = gameMode #"gameMode" - match api self.gameCreation = gameCreation #"gameCreation" - match api - unix to date self.gameDuration = gameDuration #"gameDuration" - match api - milisegundos self.matchResult = matchResult #"win" - match api def MatchModeRequest(self, matchRawData): self.mapId = matchRawData["info"]["mapId"] self.mapName = [mapValues["mapName"] for mapValues in mapListRawData if mapValues["mapId"] == self.mapId] self.mapName = self.mapName[0] self.gameMode = matchRawData["info"]["gameMode"] def MatchTimeRequest(self, matchRawData): gameCreationTimestamp = matchRawData["info"]["gameCreation"] gameCreationDatetime = datetime.datetime.fromtimestamp(gameCreationTimestamp/1000) if regionMethods.sessionRegionLang == "BR": self.gameCreation = gameCreationDatetime.strftime('%d / %m / %Y') else: self.gameCreation = gameCreationDatetime.strftime('%m / %d / %Y') if "gameEndTimestamp" in matchRawData["info"]: datatimeRaw = str(datetime.timedelta(seconds = matchRawData["info"]["gameDuration"])) if datatimeRaw[0] == "0": self.gameDuration = datatimeRaw[2:] else: self.gameDuration = datatimeRaw else: datatimeRaw = str(datetime.timedelta(seconds = (matchRawData["info"]["gameDuration"] // 1000))) if datatimeRaw[0] == "0": self.gameDuration = datatimeRaw[2:] else: self.gameDuration = datatimeRaw def GetMatchResult(self, matchRawData, playerKey): participants = matchRawData["metadata"]["participants"] self.matchResult = regionMethods.matchResultLang[0] if matchRawData["info"]["participants"][participants.index(playerKey)]["win"] else regionMethods.matchResultLang[1] # ----------- Create Assets ----------- class ProfileSummary: def CreateProfileFrame(playerNumber): profileSummaryFrame = tkinter.Frame(historyFrameArray[playerNumber], height = 60, width = 680, background = "black") profileSummaryFrame.grid(columnspan = 5) profileSummaryFrame.grid_propagate(False) profileSummaryFrame.grid_rowconfigure(0, weight = 1) profileSummaryFrame.grid_columnconfigure((0, 1), weight = 1) profileSummaryArray[playerNumber] = profileSummaryFrame def CreateNameRank(profileSummaryArray, name, rank): nameRankFrame = tkinter.Frame(profileSummaryArray, height = 38, width = 135, background = "black") nameRankFrame.grid(row = 0, column = 0, sticky = "w") nameRankFrame.grid_propagate(False) nameRankFrame.grid_rowconfigure((0, 1), weight = 1) nameRankFrame.grid_columnconfigure(0, weight = 1) nameLabel = tkinter.Label(nameRankFrame, text = name, font = ("", 10, "bold"), background = "black", foreground = "white", borderwidth = 0, highlightthickness = 0) nameLabel.grid(row = 0, column = 0, sticky = "swe", pady = (0, 0)) rankLabel = tkinter.Label(nameRankFrame, text = rank, font = ("", 10, "bold"), background = "black", foreground = "white", borderwidth = 0, highlightthickness = 0) rankLabel.grid(row = 1, column = 0, sticky = "nwe", pady = (0, 0)) frameLine = tkinter.Frame(nameRankFrame, height = 1, width = 120, background = "#775829") frameLine.grid(row = 2, column = 0, pady = (5, 0)) def CreateRecentMatches(profileSummaryArray, recentWinValue, recentLossValue, averageKill, averageDeath, averageAssist): # ----------- Recent Matches Stats ----------- recentMatchesStats = tkinter.Frame(profileSummaryArray, height = 110, width = 152, background = "black") recentMatchesStats.grid(row = 0, column = 1, sticky = "w", pady = (7, 0)) recentMatchesStats.grid_propagate(False) recentMatchesStats.grid_rowconfigure((0, 1), weight = 1) recentMatchesStats.grid_columnconfigure((0, 1), weight = 1) # ----------- Player Performance (Recent Matches Stats) ----------- recentPerformance = tkinter.Frame(recentMatchesStats, height = 30, width = 150) recentPerformance.grid(row = 0, column = 0) recentPerformance.grid_propagate(False) recentPerformance.grid_rowconfigure((0, 1), weight = 1) recentPerformance.grid_columnconfigure((0), weight = 1) winrate = f"{recentWinValue} / {recentLossValue}" kda = f"{averageKill / 10} / {averageDeath / 10} / {averageAssist / 10}" recentWinrateLabel = tkinter.Label(recentPerformance, text = winrate, font = ("", 11, "bold"), background = "black", foreground = "white") recentWinrateLabel.grid(row = 0, column = 0, sticky = "we") averageKdaLabel = tkinter.Label(recentPerformance, text = kda, font = ("", 8, "bold"), background = "black", foreground = "white") averageKdaLabel.grid(row = 1, column = 0, sticky = "we") # ----------- Winrate Stats (Recent Matches Stats) ----------- winrateGraph = tkinter.Frame(recentMatchesStats, height = 22, width = 150, background = "black", highlightthickness = 0, borderwidth = 0) winrateGraph.grid(row = 1, column = 0, pady = (0, 4)) winrateGraph.grid_propagate(False) winrateGraph.grid_columnconfigure((0, 1, 2), weight = 1) winrateGraph.grid_rowconfigure(0, weight = 1) recentWinsLabel = tkinter.Label(winrateGraph, text = f"{recentWinValue} V", font = ("", 10, "bold"), background = "black", foreground = "deep sky blue", borderwidth = 0, highlightthickness = 0) recentWinsLabel.grid(row = 0, column = 0, sticky = "e") kdaBar = tkinter.Frame(winrateGraph, height = 15, width = 80, highlightthickness = 0, borderwidth = 0) kdaBar.grid(row = 0, column = 1) recentLossesLabel = tkinter.Label(winrateGraph, text = f"{recentLossValue} D", font = ("", 10, "bold"), background = "black", foreground = "red", borderwidth = 0, highlightthickness = 0) recentLossesLabel.grid(row = 0, column = 2, sticky = "w") for i in range(recentWinValue): filledColor = tkinter.Canvas(kdaBar, height = 15, width = 8, background = "deep sky blue", highlightthickness = 0, borderwidth = 0) filledColor.grid(row = 0, column = i) for i in range(recentLossValue): filledColor = tkinter.Canvas(kdaBar, height = 15, width = 8, background = "red", highlightthickness = 0, borderwidth = 0) filledColor.grid(row = 0, column = recentWinValue + i) # ----------- Vertical Line (Recent Matches Stats) ----------- frameLine = tkinter.Frame(recentMatchesStats, height = 110, width = 1, background = "#775829") frameLine.grid(row = 0,rowspan = 2, column = 1,sticky = "ns") def CreateRecentChampion(profileSummaryArray, championDict, championIconArray): recentChampionsFrame = tkinter.Frame(profileSummaryArray, height = 34, width = 381, background = "black") recentChampionsFrame.grid(row = 0, column = 2) recentChampionsFrame.grid_propagate(False) recentChampionsFrame.grid_columnconfigure((0, 1, 2), weight = 1) recentChampionsFrame.grid_rowconfigure(0, weight = 1) for i in range(3): if len(championDict) >= i + 1: # ----------- Champion Data ----------- championWinrate = f"{championDict[i][1][1]} / {championDict[i][1][2]}" championWinrate = championWinrate + " (" + str("{:.0f}".format((championDict[i][1][1] / (championDict[i][1][1] + championDict[i][1][2])) * 100)) + "%)" championAverageKill = "{:.1f}".format(championDict[i][1][0][0] / (championDict[i][1][1] + championDict[i][1][2])) championAverageDeath = "{:.1f}".format(championDict[i][1][0][1] / (championDict[i][1][1] + championDict[i][1][2])) championAverageAssist = "{:.1f}".format(championDict[i][1][0][2] / (championDict[i][1][1] + championDict[i][1][2])) championKda = f"{championAverageKill} / {championAverageDeath} / {championAverageAssist}" # ----------- Recent Played Champion ----------- mostPlayedChampion = tkinter.Frame(recentChampionsFrame, height = 34, width = 127, background = "black") mostPlayedChampion.grid(row = 0, column = i) mostPlayedChampion.grid_propagate(False) mostPlayedChampion.grid_columnconfigure((0, 1), weight = 1) mostPlayedChampion.grid_rowconfigure(0, weight = 1) # ----------- Champion Icon (Recent Played Champion) ----------- championBorder = tkinter.Frame(mostPlayedChampion, height = 34, width = 34, background = "#775829", borderwidth = 0, highlightthickness = 0) championBorder.grid(row = 0, column = 0, sticky = "w") championIcon = tkinter.Canvas(championBorder, height = 32, width = 32, background = "black", borderwidth = 0, highlightthickness = 0) championIcon.grid(row = 0, column = 0, padx = 1, pady = 1) championIcon.create_image((16, 16), image = championIconArray[i]) # ----------- Champion Stats Label (Recent Played Champion) ----------- championStats = tkinter.Frame(mostPlayedChampion, height = 34, width = 84, background = "black", borderwidth = 0) championStats.grid(row = 0, column = 1, padx = (0, 6), sticky = "w") championStats.grid_propagate(False) championStats.grid_columnconfigure(0, weight = 1) championStats.grid_rowconfigure((0, 1), weight = 1) championWinrateLabel = tkinter.Label(championStats, text = championWinrate, font = ("Arial Narrow", 10, "bold"), background = "black", foreground = "white") championWinrateLabel.grid(row = 0, column = 0, sticky = "w" ) championKdaLabel = tkinter.Label(championStats, text = championKda, font = ("Arial Narrow", 10, "bold"), background = "black", foreground = "white") championKdaLabel.grid(row = 1, column = 0, sticky = "w") class MatchPreview: def ChampionCircle(frameNumber, championImage, playerLevel): circle = tkinter.Canvas(frameNumber, height = 85, width = 85, background = "black", highlightthickness = 0) circle.grid(row = 0, column = 0) circle.create_image((42, 42), image = championImage) circle.create_image((42, 42), image = championCircleFrame) circle.create_image((65, 62), image = levelCircleFrame) circle.create_text((65, 63), text = playerLevel, fill = "#918c83", font = ("", 8, "bold")) def GamemodeResult(frameNumber, matchResult, gameMode, spellArray, preview): gamemodeResultFrame = tkinter.Frame(frameNumber, height = 63, width = 110, background = "black") gamemodeResultFrame.grid(row = 0, column = 1, pady = (14, 0), sticky= "nwe") gamemodeResultFrame.grid_rowconfigure((0 , 1, 2), weight = 1) gamemodeResultFrame.grid_propagate(False) # ----------- Match Result ----------- matchResultLabel = tkinter.Label(gamemodeResultFrame, text = matchResult, background = "black", foreground = "red" if matchResult == regionMethods.matchResultLang[1] else "deep sky blue", borderwidth = 0, font = ("", 10, "bold")) #text = matchResult/gameMode matchResultLabel.grid(row = 0, column = 0, sticky = "nw") # ----------- Gamemode ----------- matchGamemodeLabel = tkinter.Label(gamemodeResultFrame, text = gameMode, background = "black", foreground = "#918c83", borderwidth = 0, font = ("", 9, "bold")) #text = matchResult/gameMode matchGamemodeLabel.grid(row = 1, column = 0, sticky= "nw", pady = (0,3)) # ----------- Spell Sprites ----------- spellFrame = tkinter.Frame(gamemodeResultFrame, height = 18, width = 36, background = "#775829", borderwidth = 0) spellFrame.grid(row = 2, column = 0, sticky = "nw", pady = (0, 3)) for i in range(2): if len(spellArray[preview]) >= i + 1: if i == 1: spellSprite = tkinter.Canvas(spellFrame, height = 18, width = 18 , highlightthickness = 0, borderwidth = 0) spellSprite.grid(row = 0, column = i, padx = 1, pady = 1) else: spellSprite = tkinter.Canvas(spellFrame, height = 18, width = 18 , highlightthickness = 0, borderwidth = 0) spellSprite.grid(row = 0, column = i, padx = (1,0), pady = 1) spellSprite.create_image((9, 9), image = spellArray[preview][i]) def PlayerResult(frameNumber, gold, totalMinion, score, itemArray, preview): playerResultFrame = tkinter.Frame(frameNumber, height = 64, width = 192, background = "black", borderwidth = 0) playerResultFrame.grid(row = 0, column = 2, pady = (16, 0), padx = (20, 20), sticky = "n") # ----------- Items ----------- itemFrame = tkinter.Frame(playerResultFrame, height = 32, width = 192, background = "#775829", borderwidth = 0) itemFrame.grid(row = 0, column = 0) for i in range(7): if i == 6: itemSprite = tkinter.Canvas(itemFrame, height = 32, width = 32 , background = "black", highlightthickness = 0, borderwidth = 0) itemSprite.grid(row = 0, column = i, padx = 1, pady = 1) else: itemSprite = tkinter.Canvas(itemFrame, height = 32, width = 32 , background = "black", highlightthickness = 0, borderwidth = 0) itemSprite.grid(row = 0, column = i, padx = (1,0), pady = 1) if i < len(itemArray[preview]): itemSprite.create_image((16,16), image = itemArray[preview][i]) # ----------- Score ----------- scoreFrame = tkinter.Frame(playerResultFrame, height = 11, width = 192, background = "black", borderwidth = 0) scoreFrame.grid(row = 1, column = 0, pady = (9, 0), sticky = "swe") scoreFrame.grid_columnconfigure((0, 1, 2), weight = 1) kdaLabel = tkinter.Label(scoreFrame, text = score, background = "black", foreground = "#918c83", font = ("Heuristica", 11,"bold"), borderwidth = 0) kdaLabel.grid(row = 0, column = 0, sticky = "w") # ----------- Minions ----------- minionFrame = tkinter.Frame(scoreFrame, background = "black") minionFrame.grid(row = 0, column = 1) minionLabel = tkinter.Label(minionFrame, text = totalMinion, background = "black", foreground = "#918c83", font = ("", 11,"bold"), borderwidth = 0) minionLabel.grid(row = 0, column = 0, padx = (0, 2)) minionCanvas = tkinter.Canvas(minionFrame, background = "black", highlightthickness = 0, height = 16, width = 16) minionCanvas.grid(row = 0, column = 1) minionCanvas.create_image((8, 7), image = minionIcon) # ----------- Gold ----------- goldFrame = tkinter.Frame(scoreFrame, background = "black") goldFrame.grid(row = 0, column = 2, sticky = "e") goldLabel = tkinter.Label(goldFrame, text = gold, background = "black", foreground = "#918c83",font = ("", 11,"bold"), borderwidth = 0) goldLabel.grid(row = 0, column = 0, padx = (0, 4)) goldCanvas = tkinter.Canvas(goldFrame, background = "black", highlightthickness = 0, height = 17, width = 17) goldCanvas.grid(row = 0, column = 1) goldCanvas.create_image((8, 8), image = goldIcon) def TimeData(frameNumber, mapName, gameDuration, gameCreation): dataFrame = tkinter.Frame(frameNumber, height = 85, width = 100, background = "black", borderwidth = 0) dataFrame.grid(row = 0, column = 3, pady = 5, sticky = "nswe") dataFrame.grid_rowconfigure((0, 1), weight=1) dataFrame.grid_columnconfigure((0), weight=1) dataFrame.grid_propagate(False) mapLabel = tkinter.Label(dataFrame, text = mapName, background = "black", font = ("", 9, "bold"), foreground = "#918c83") mapLabel.grid(row = 0, column = 0, sticky = "w") dateTimeLabel = tkinter.Label(dataFrame, text = f"{gameDuration} · {gameCreation}", font = ("", 9, "bold"), background = "black", foreground = "#918c83") dateTimeLabel.grid(row = 1, column = 0, pady = (0, 20), sticky = "w") def PreviewLine(frameNumber): line = tkinter.Frame(frameNumber, height = 1, width = 800, background = "#7d6f4b", borderwidth = 0) line.grid(row = 0, columnspan = 6, sticky = "swe") #endregion #region Match Data matchDataArray = [[], [], [], [], []] def MatchDataRequest(match): matchJsonData = sessionMatch.get(match) matchRawData = ujson.loads(matchJsonData.text) return matchRawData def MatchListDataRequest(playerPuuid, player): matchListJsonData = sessionMatchList.get(f"https://americas.api.riotgames.com/lol/match/v5/matches/by-puuid/{playerPuuid}/ids?start=0&count=10&api_key={key}") matchListRawData = ujson.loads(matchListJsonData.text) multithreadMatchList = [] for i in range(10): if len(matchListRawData) >= i + 1: multithreadMatchList.append(f"https://americas.api.riotgames.com/lol/match/v5/matches/{matchListRawData[i]}?api_key={key}") if len(matchListRawData) == 0: return 0 with futures.ThreadPoolExecutor(max_workers = 10) as executor: for request in executor.map(MatchDataRequest, multithreadMatchList): matchDataArray[player].append(request) def ChangeFrame(player): if player == "player1": scrollableMainFrameArray[0].tkraise() elif player == "player2": scrollableMainFrameArray[1].tkraise() elif player == "player3": scrollableMainFrameArray[2].tkraise() elif player == "player4": scrollableMainFrameArray[3].tkraise() elif player == "player5": scrollableMainFrameArray[4].tkraise() #endregion #region Instantiation playerSummaryStats1 = SummaryStats() playerStats1 = PlayerStats() matchStatsChampion1 = MatchStatsChampion() matchStatsSpells1 = MatchStatsSpells() matchStatsItems1 = MatchStatsItems() matchStatsPlayer1 = MatchStatsPlayer() matchStatsGame1 = MatchStatsGame() playerSummaryStats2 = SummaryStats() playerStats2 = PlayerStats() matchStatsChampion2 = MatchStatsChampion() matchStatsSpells2 = MatchStatsSpells() matchStatsItems2 = MatchStatsItems() matchStatsPlayer2 = MatchStatsPlayer() matchStatsGame2 = MatchStatsGame() playerSummaryStats3 = SummaryStats() playerStats3 = PlayerStats() matchStatsChampion3 = MatchStatsChampion() matchStatsSpells3 = MatchStatsSpells() matchStatsItems3 = MatchStatsItems() matchStatsPlayer3 = MatchStatsPlayer() matchStatsGame3 = MatchStatsGame() playerSummaryStats4 = SummaryStats() playerStats4 = PlayerStats() matchStatsChampion4 = MatchStatsChampion() matchStatsSpells4 = MatchStatsSpells() matchStatsItems4 = MatchStatsItems() matchStatsPlayer4 = MatchStatsPlayer() matchStatsGame4 = MatchStatsGame() playerSummaryStats5 = SummaryStats() playerStats5 = PlayerStats() matchStatsChampion5 = MatchStatsChampion() matchStatsSpells5 = MatchStatsSpells() matchStatsItems5 = MatchStatsItems() matchStatsPlayer5 = MatchStatsPlayer() matchStatsGame5 = MatchStatsGame() #endregion playerSummaryStatsArray = [playerSummaryStats1, playerSummaryStats2, playerSummaryStats3, playerSummaryStats4, playerSummaryStats5] playerStatsArray = [playerStats1, playerStats2, playerStats3, playerStats4, playerStats5] statsChampionArray = [matchStatsChampion1, matchStatsChampion2, matchStatsChampion3, matchStatsChampion4, matchStatsChampion5] statsSpellsArray = [matchStatsSpells1, matchStatsSpells2, matchStatsSpells3, matchStatsSpells4, matchStatsSpells5] statsItemsArray = [matchStatsItems1, matchStatsItems2, matchStatsItems3, matchStatsItems4, matchStatsItems5] matchStatsPlayerArray = [matchStatsPlayer1, matchStatsPlayer2, matchStatsPlayer3, matchStatsPlayer4, matchStatsPlayer5] statsGameArray = [matchStatsGame1, matchStatsGame2, matchStatsGame3, matchStatsGame4, matchStatsGame5] def AssignHistoryButton(player): if player == 0: playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeFrame("player1")) playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeEntry(event, 0), add = "+") if player == 1: playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeFrame("player2")) playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeEntry(event, 1), add = "+") if player == 2: playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeFrame("player3")) playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeEntry(event, 2), add = "+") if player == 3: playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeFrame("player4")) playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeEntry(event, 3), add = "+") if player == 4: playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeFrame("player5")) playerHistoryButtonArray[player].bind("<Button-1>", lambda event: ChangeEntry(event, 4), add = "+") def DestroyOldApp(): for i in range(5): summaryChampionIconArray[i].clear() if playerHistoryButtonArray[i] != 0: scrollableMainFrameArray[i].destroy() matchDataArray[i].clear() profileSummaryArray[i].destroy() for i in range(10): itemList1[i].clear() itemList2[i].clear() itemList3[i].clear() itemList4[i].clear() itemList5[i].clear() spellList1[i].clear() spellList2[i].clear() spellList3[i].clear() spellList4[i].clear() spellList5[i].clear() championList[i].clear() def AppBuilder(event): lastColor = [] DestroyOldApp() # ----------- UI Creation ----------- CreateButtonBG() for i in range(5): if playerArray[i].get() != "" and " ": if playerStatsArray[i].PlayerDataRequest(playerArray[i].get()) == 0: pass elif MatchListDataRequest(playerStatsArray[i].playerPuuid, i) == 0: pass else: CreateHistoryButton(i) CreateHistoryFrame(i) CreateMatchPreview(i) AssignHistoryButton(i) playerStatsArray[i].PlayerRankRequest() playerSummaryStatsArray[i].GetSummaryWins(matchDataArray[i], playerStatsArray[i].playerPuuid) playerSummaryStatsArray[i].GetSummaryKda(matchDataArray[i], playerStatsArray[i].playerPuuid) playerSummaryStatsArray[i].GetSummaryChampions(matchDataArray[i], playerStatsArray[i].playerPuuid, i) ProfileSummary.CreateNameRank(profileSummaryArray[i], playerArray[i].get(), playerStatsArray[i].playerRank) ProfileSummary.CreateRecentMatches(profileSummaryArray[i], playerSummaryStatsArray[i].matchesWon, playerSummaryStatsArray[i].matchesLost, playerSummaryStatsArray[i].averageKill, playerSummaryStatsArray[i].averageDeath, playerSummaryStatsArray[i].averageAssist) ProfileSummary.CreateRecentChampion(profileSummaryArray[i], playerSummaryStatsArray[i].championDictOrder, summaryChampionIconArray[i]) lastColor.append(playerHistoryButtonArray[i]) elif i == 4: lastColor[len(lastColor) - 1].configure(background = "#042937") for player in range(5): if playerHistoryButtonArray[player] != 0: for preview in range(10): # ----------- Data Requests ----------- statsChampionArray[player].MatchStatsChampionRequest(matchDataArray[player][preview], playerStatsArray[player].playerPuuid, player) statsSpellsArray[player].MatchStatsSpellsRequest(matchDataArray[player][preview], playerStatsArray[player].playerPuuid) statsItemsArray[player].MatchStatsItemsRequests(matchDataArray[player][preview], playerStatsArray[player].playerPuuid) matchStatsPlayerArray[player].MatchStatsPlayerRequest(matchDataArray[player][preview], playerStatsArray[player].playerPuuid) statsGameArray[player].GetMatchResult(matchDataArray[player][preview], playerStatsArray[player].playerPuuid) statsGameArray[player].MatchModeRequest(matchDataArray[player][preview]) statsGameArray[player].MatchTimeRequest(matchDataArray[player][preview]) # ----------- UI Elements ----------- MatchPreview.ChampionCircle(playerMatchArray[player][preview], championList[player][preview], statsChampionArray[player].championLevel) MatchPreview.GamemodeResult(playerMatchArray[player][preview], statsGameArray[player].matchResult, statsGameArray[player].gameMode, statsSpellsArray[player].GetSpellSprites(player, preview), preview) MatchPreview.PlayerResult(playerMatchArray[player][preview], matchStatsPlayerArray[player].playerGold, matchStatsPlayerArray[player].playerMinions, matchStatsPlayerArray[player].ScoreConstructor(), statsItemsArray[player].GetItemSprites(player, preview), preview) MatchPreview.TimeData(playerMatchArray[player][preview], statsGameArray[player].mapName, statsGameArray[player].gameDuration, statsGameArray[player].gameCreation) MatchPreview.PreviewLine(playerMatchArray[player][preview]) def ChangeSearch(event): if str(event.type) == "ButtonPress": searchButton.config(background = "#07141f") elif str(event.type) == "ButtonRelease": searchButton.config(background = "black") def ChangeEntry(event, player): for i in range(5): if i == player: playerHistoryButtonArray[i].configure(background = "#042937") elif playerHistoryButtonArray[i] != 0: playerHistoryButtonArray[i].configure(background = "black") searchButton.bind("<Button-1>", ChangeSearch) searchButton.bind("<Button-1>", AppBuilder, add = "+") searchButton.bind("<ButtonRelease>", ChangeSearch) player1.bind("<Return>", AppBuilder) player2.bind("<Return>", AppBuilder) player3.bind("<Return>", AppBuilder) player4.bind("<Return>", AppBuilder) player5.bind("<Return>", AppBuilder) root.mainloop() #pyinstaller --onefile --noconsole MainFile.py
WandersonKnight/League-Quick-Data
MainFile.py
MainFile.py
py
54,615
python
en
code
0
github-code
6
21816512190
from flask import Flask, request import json app = Flask(__name__) @app.route("/") def api(): x = request.headers.get("Xxx") if x == None: return "missing header" headers = [header for header in request.headers] return json.dumps(headers) if __name__ == "__main__": app.run(host="0.0.0.0", port=3000, debug=True)
mrtc0/abusing-hop-by-hop-header
app/app.py
app.py
py
344
python
en
code
1
github-code
6
1175959273
#!/usr/bin/env python3 """ Watersheds problem for Google Code Jam 2009 Qualification Round Link to problem description: http://code.google.com/codejam/contest/dashboard?c=90101#s=p1 author: Chris Nitsas (nitsas) language: Python 3.2.1 date: April, 2012 usage: $ python3 runme.py sample.in or $ runme.py sample.in (where sample.in is the input file and $ the prompt) """ import sys # non-standard modules: from helpful import read_int, read_list_of_int def get_altitudes_map(file, height): altitudes = [] for i in range(height): altitudes.append(read_list_of_int(file)) return altitudes def label_cells(altitudes): height, width = len(altitudes), len(altitudes[0]) label_of_cell = [['' for i in line] for line in altitudes] unused_labels = label_generator() for i in range(height): for j in range(width): if not label_of_cell[i][j]: travel_to_sink_and_label_backwards((i, j), altitudes, label_of_cell, unused_labels) return label_of_cell def travel_to_sink_and_label_backwards(cell, altitudes, label_of_cell, unused_labels): path = [cell] neighbor = get_lowest_neighbor(altitudes, cell) while neighbor: # we aren't at the sink yet if not label_of_cell[neighbor[0]][neighbor[1]]: path.append(neighbor) neighbor = get_lowest_neighbor(altitudes, neighbor) else: label_path(path, label_of_cell, label_of_cell[neighbor[0]][neighbor[1]]) break else: # we got to a sink; label the path with a new, unused label label_path(path, label_of_cell, next(unused_labels)) def label_generator(): labels = "abcdefghijklmnopqrstuvwxyz" for label in labels: yield label def label_path(path, label_of_cell, label): for (i, j) in path: label_of_cell[i][j] = label def get_lowest_neighbor(altitudes, cell): row, col = cell height, width = len(altitudes), len(altitudes[0]) lowest_altitude = altitudes[row][col] neighbor = () # check North neighbor (if it exists) if row > 0 and altitudes[row - 1][col] < lowest_altitude: lowest_altitude = altitudes[row - 1][col] neighbor = (row - 1, col) # now check West neighbor (if it exists) if col > 0 and altitudes[row][col - 1] < lowest_altitude: lowest_altitude = altitudes[row][col - 1] neighbor = (row, col - 1) # now check East neighbor (if it exists) if col < width - 1 and altitudes[row][col + 1] < lowest_altitude: lowest_altitude = altitudes[row][col + 1] neighbor = (row, col + 1) # finally, check South neighbor (if it exists) if row < height - 1 and altitudes[row + 1][col] < lowest_altitude: lowest_altitude = altitudes[row + 1][col] neighbor = (row + 1, col) return neighbor def print_cell_labels(cell_labels): for line in cell_labels: print(" ".join(line)) def main(filename=None): if filename is None: if len(sys.argv) == 2: filename = sys.argv[1] else: print("Usage: runme.py input_file") return 1 with open(filename, "r") as f: num_maps = read_int(f) for i in range(num_maps): print("Case #" + str(i+1) + ":") (height, width) = read_list_of_int(f) altitudes = get_altitudes_map(f, height) cell_labels = label_cells(altitudes) print_cell_labels(cell_labels) return 0 if __name__ == "__main__": status = main() sys.exit(status)
nitsas/codejamsolutions
Watersheds/runme.py
runme.py
py
3,572
python
en
code
1
github-code
6
70078444988
import logging import math import threading import time import torch #import support.kernels as kernel_factory from ...support.kernels import factory from ...core import default from ...core.model_tools.deformations.exponential import Exponential from ...core.models.abstract_statistical_model import AbstractStatisticalModel from ...core.models.model_functions import initialize_control_points, initialize_momenta from ...core.observations.deformable_objects.deformable_multi_object import DeformableMultiObject from ...in_out.array_readers_and_writers import * from ...in_out.dataset_functions import create_template_metadata #import support.utilities as utilities from ...support.utilities import move_data, get_best_device from .abstract_statistical_model import process_initial_data import torch.nn.functional as F logger = logging.getLogger(__name__) # def _subject_attachment_and_regularity(arg): # """ # Auxiliary function for multithreading (cannot be a class method). # """ # from .abstract_statistical_model import process_initial_data # if process_initial_data is None: # raise RuntimeError('process_initial_data is not set !') # # # Read arguments. # freeze_sparse_matrix = False # (deformable_objects, multi_object_attachment, objects_noise_variance, # freeze_template, freeze_control_points, freeze_momenta, # exponential, sobolev_kernel, use_sobolev_gradient, tensor_scalar_type, gpu_mode) = process_initial_data # (i, template, template_data, control_points, momenta, with_grad, momenta_t, sparse_matrix, alpha) = arg # # # start = time.perf_counter() # device, device_id = get_best_device(gpu_mode=gpu_mode) # # device, device_id = ('cpu', -1) # if device_id >= 0: # torch.cuda.set_device(device_id) # # # convert np.ndarrays to torch tensors. This is faster than transferring torch tensors to process. # template_data = {key: move_data(value, device=device, dtype=tensor_scalar_type, # requires_grad=with_grad and not freeze_template) # for key, value in template_data.items()} # template_points = {key: move_data(value, device=device, dtype=tensor_scalar_type, # requires_grad=with_grad and not freeze_template) # for key, value in template.get_points().items()} # control_points = move_data(control_points, device=device, dtype=tensor_scalar_type, # requires_grad=with_grad and not freeze_control_points) # momenta = move_data(momenta, device=device, dtype=tensor_scalar_type, # requires_grad=with_grad and not freeze_momenta) # # assert torch.device( # device) == control_points.device == momenta.device, 'control_points and momenta tensors must be on the same device. ' \ # 'device=' + device + \ # ', control_points.device=' + str(control_points.device) + \ # ', momenta.device=' + str(momenta.device) # # attachment, regularity = DeterministicAtlasHypertemplate._deform_and_compute_attachment_and_regularity( # exponential, template_points, control_points, momenta, # template, template_data, multi_object_attachment, # deformable_objects[i], objects_noise_variance, alpha, # device) # # res = DeterministicAtlasHypertemplate._compute_gradients( # attachment, regularity, # freeze_template, momenta_t, # freeze_control_points, control_points, # freeze_momenta, momenta, freeze_sparse_matrix, sparse_matrix, # with_grad) # # elapsed = time.perf_counter() - start # # logger.info('pid=' + str(os.getpid()) + ', ' + torch.multiprocessing.current_process().name + # # ', device=' + device + ', elapsed=' + str(elapsed)) # return i, res class DeterministicAtlasWithModule(AbstractStatisticalModel): """ Deterministic atlas object class. """ #################################################################################################################### ### Constructor: #################################################################################################################### def __init__(self, template_specifications, number_of_subjects, dimension=default.dimension, tensor_scalar_type=default.tensor_scalar_type, tensor_integer_type=default.tensor_integer_type, dense_mode=default.dense_mode, number_of_processes=default.number_of_processes, deformation_kernel_type=default.deformation_kernel_type, deformation_kernel_width=default.deformation_kernel_width, deformation_kernel_device=default.deformation_kernel_device, shoot_kernel_type=default.shoot_kernel_type, number_of_time_points=default.number_of_time_points, use_rk2_for_shoot=default.use_rk2_for_shoot, use_rk2_for_flow=default.use_rk2_for_flow, freeze_template=default.freeze_template, use_sobolev_gradient=default.use_sobolev_gradient, smoothing_kernel_width=default.smoothing_kernel_width, initial_control_points=default.initial_control_points, freeze_control_points=default.freeze_control_points, initial_cp_spacing=default.initial_cp_spacing, initial_momenta=default.initial_momenta, freeze_momenta=default.freeze_momenta, gpu_mode=default.gpu_mode, process_per_gpu=default.process_per_gpu, **kwargs): AbstractStatisticalModel.__init__(self, name='DeterministicAtlas', number_of_processes=number_of_processes, gpu_mode=gpu_mode) # Global-like attributes. self.dimension = dimension self.tensor_scalar_type = tensor_scalar_type self.tensor_integer_type = tensor_integer_type self.dense_mode = dense_mode # Declare model structure. self.fixed_effects['template_data'] = None self.fixed_effects['hypertemplate_data'] = None self.fixed_effects['control_points'] = None self.fixed_effects['momenta'] = None self.fixed_effects['momenta_t'] = None self.fixed_effects['module_intensities'] = None self.fixed_effects['module_positions'] = None self.fixed_effects['module_variances'] = None self.freeze_template = freeze_template self.freeze_control_points = freeze_control_points self.freeze_momenta = freeze_momenta self.freeze_sparse_matrix = False self.alpha = 1 # Deformation. self.exponential = Exponential( dense_mode=dense_mode, kernel=factory(deformation_kernel_type, gpu_mode=gpu_mode, kernel_width=deformation_kernel_width), shoot_kernel_type=shoot_kernel_type, number_of_time_points=number_of_time_points, use_rk2_for_shoot=use_rk2_for_shoot, use_rk2_for_flow=use_rk2_for_flow) self.exponential_t = Exponential( dense_mode=dense_mode, kernel=factory(deformation_kernel_type, gpu_mode=gpu_mode, kernel_width=deformation_kernel_width), shoot_kernel_type=shoot_kernel_type, number_of_time_points=number_of_time_points, use_rk2_for_shoot=use_rk2_for_shoot, use_rk2_for_flow=use_rk2_for_flow) # Template. (object_list, self.objects_name, self.objects_name_extension, self.objects_noise_variance, self.multi_object_attachment) = create_template_metadata(template_specifications, self.dimension) self.template = DeformableMultiObject(object_list) self.hypertemplate = DeformableMultiObject(object_list) # self.template.update() self.number_of_objects = len(self.template.object_list) self.use_sobolev_gradient = use_sobolev_gradient self.smoothing_kernel_width = smoothing_kernel_width if self.use_sobolev_gradient: self.sobolev_kernel = factory(deformation_kernel_type, gpu_mode=gpu_mode, kernel_width=smoothing_kernel_width) # Template data. self.fixed_effects['template_data'] = self.template.get_data() self.fixed_effects['hypertemplate_data'] = self.hypertemplate.get_data() # Control points. self.fixed_effects['control_points'] = initialize_control_points( initial_control_points, self.template, initial_cp_spacing, deformation_kernel_width, self.dimension, self.dense_mode) self.number_of_control_points = len(self.fixed_effects['control_points']) # Momenta. self.fixed_effects['momenta'] = initialize_momenta( initial_momenta, self.number_of_control_points, self.dimension, number_of_subjects) self.fixed_effects['momenta'] = 0.0001*np.ones(self.fixed_effects['momenta'].shape) self.number_of_subjects = number_of_subjects self.fixed_effects['momenta_t'] = initialize_momenta( None, self.number_of_control_points, self.dimension, 1) # initial_cp = initialize_control_points(None, self.template, 40, None, self.dimension, False) # self.nb_modules = initial_cp.shape[0] # self.fixed_effects['module_positions'] = np.array([initial_cp,]*self.number_of_subjects) #self.fixed_effects['module_positions'] = np.array([[np.array(self.template.get_points()['image_points'].shape[:-1])/2]*initial_cp.shape[0]]*self.number_of_subjects) for i in range(object_list[0].bounding_box.shape[0]): object_list[0].bounding_box[i,0] = object_list[0].bounding_box[i,1]/2 - 10/2 object_list[0].bounding_box[i, 1] = object_list[0].bounding_box[i, 1] / 2 + 10 / 2 t = DeformableMultiObject(object_list) initial_cp = initialize_control_points(None, t, 3, None, self.dimension, False) self.nb_modules = initial_cp.shape[0] self.fixed_effects['module_positions'] = np.array([initial_cp, ] * self.number_of_subjects) # k = 0 # j = 0 # add = 1 # while k < self.nb_modules - 1: # self.fixed_effects['module_positions'][:,k,j] += add # self.fixed_effects['module_positions'][:, k+1, j] -= add # k += 2 # if j == self.fixed_effects['module_positions'].shape[2] - 1: # j = 0 # add += 1 # else: # j+=1 self.fixed_effects['module_intensities'] = 0*np.ones([self.number_of_subjects, self.nb_modules]) self.fixed_effects['module_variances'] = 5*np.ones([self.number_of_subjects, self.nb_modules, self.dimension]) self.process_per_gpu = process_per_gpu self.regu_var_m = 5 self.regu_var_m_ortho = 10 def initialize_noise_variance(self, dataset, device='cpu'): if np.min(self.objects_noise_variance) < 0: hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, momenta_t \ = self._fixed_effects_to_torch_tensors(False, device=device) targets = dataset.deformable_objects targets = [target[0] for target in targets] residuals_torch = [] self.exponential.set_initial_template_points(template_points) self.exponential.set_initial_control_points(control_points) for i, target in enumerate(targets): self.exponential.set_initial_momenta(momenta[i]) self.exponential.update() deformed_points = self.exponential.get_template_points() deformed_data = self.template.get_deformed_data(deformed_points, template_data) residuals_torch.append(self.multi_object_attachment.compute_distances( deformed_data, self.template, target)) residuals = np.zeros((self.number_of_objects,)) for i in range(len(residuals_torch)): residuals += residuals_torch[i].detach().cpu().numpy() # Initialize the noise variance hyper-parameter as a 1/100th of the initial residual. for k, obj in enumerate(self.objects_name): if self.objects_noise_variance[k] < 0: nv = 0.01 * residuals[k] / float(self.number_of_subjects) self.objects_noise_variance[k] = nv logger.info('>> Automatically chosen noise std: %.4f [ %s ]' % (math.sqrt(nv), obj)) #################################################################################################################### ### Encapsulation methods: #################################################################################################################### # Template data ---------------------------------------------------------------------------------------------------- def get_template_data(self): return self.fixed_effects['template_data'] def set_template_data(self, td): self.fixed_effects['template_data'] = td self.template.set_data(td) def get_hypertemplate_data(self): return self.fixed_effects['hypertemplate_data'] # Control points --------------------------------------------------------------------------------------------------- def get_control_points(self): return self.fixed_effects['control_points'] def set_control_points(self, cp): self.fixed_effects['control_points'] = cp # self.number_of_control_points = len(cp) # Momenta ---------------------------------------------------------------------------------------------------------- def get_momenta(self): return self.fixed_effects['momenta'] def set_momenta(self, mom): self.fixed_effects['momenta'] = mom def get_momenta_t(self): return self.fixed_effects['momenta_t'] def set_momenta_t(self, mom): self.fixed_effects['momenta_t'] = mom def set_module_intensities(self, w): self.fixed_effects['module_intensities'] = w def get_module_intensities(self): return self.fixed_effects['module_intensities'] def set_module_positions(self, c): self.fixed_effects['module_positions'] = c def get_module_positions(self): return self.fixed_effects['module_positions'] def set_module_variances(self, sigma): self.fixed_effects['module_variances'] = sigma def get_module_variances(self): return self.fixed_effects['module_variances'] # Full fixed effects ----------------------------------------------------------------------------------------------- def get_fixed_effects(self): out = {} if not self.freeze_template: out['momenta_t'] = self.fixed_effects['momenta_t'] if not self.freeze_control_points: out['control_points'] = self.fixed_effects['control_points'] if not self.freeze_momenta: out['momenta'] = self.fixed_effects['momenta'] if not self.freeze_sparse_matrix: out['module_positions'] = self.fixed_effects['module_positions'] out['module_intensities'] = self.fixed_effects['module_intensities'] out['module_variances'] = self.fixed_effects['module_variances'] return out def set_fixed_effects(self, fixed_effects): if not self.freeze_template: device, _ = get_best_device(self.gpu_mode) hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, momenta_t, module_intensities, module_positions, module_variances \ = self._fixed_effects_to_torch_tensors(False, device=device) self.exponential_t.set_initial_template_points(hypertemplate_points) self.exponential_t.set_initial_control_points(control_points) self.exponential_t.set_initial_momenta(momenta_t[0]) self.exponential_t.move_data_to_(device=device) self.exponential_t.update() template_points = self.exponential_t.get_template_points() template_data = self.hypertemplate.get_deformed_data(template_points, hypertemplate_data) template_data = {key: value.detach().cpu().numpy() for key, value in template_data.items()} self.set_momenta_t(fixed_effects['momenta_t']) self.set_template_data(template_data) if not self.freeze_control_points: self.set_control_points(fixed_effects['control_points']) if not self.freeze_momenta: self.set_momenta(fixed_effects['momenta']) if not self.freeze_sparse_matrix: self.set_module_positions(fixed_effects['module_positions']) self.set_module_variances((fixed_effects['module_variances'])) self.set_module_intensities(fixed_effects['module_intensities']) #################################################################################################################### ### Public methods: #################################################################################################################### def setup_multiprocess_pool(self, dataset): self._setup_multiprocess_pool(initargs=([target[0] for target in dataset.deformable_objects], self.multi_object_attachment, self.objects_noise_variance, self.freeze_template, self.freeze_control_points, self.freeze_momenta, self.exponential, self.sobolev_kernel, self.use_sobolev_gradient, self.tensor_scalar_type, self.gpu_mode)) # Compute the functional. Numpy input/outputs. def compute_log_likelihood(self, dataset, population_RER, individual_RER, mode='complete', with_grad=False): """ Compute the log-likelihood of the dataset, given parameters fixed_effects and random effects realizations population_RER and indRER. :param fixed_effects: Dictionary of fixed effects. :param population_RER: Dictionary of population random effects realizations. :param individual_RER: Dictionary of individual random effects realizations. :param mode: Indicates which log_likelihood should be computed, between 'complete', 'model', and 'class2'. :param with_grad: Flag that indicates wether the gradient should be returned as well. :return: """ if self.number_of_processes > 1: targets = [target[0] for target in dataset.deformable_objects] (deformable_objects, multi_object_attachment, objects_noise_variance, freeze_template, freeze_control_points, freeze_momenta, exponential, sobolev_kernel, use_sobolev_gradient, tensor_scalar_type, gpu_mode) = process_initial_data device, device_id = get_best_device(gpu_mode=gpu_mode) self.exponential_t.set_initial_template_points(self.hypertemplate.get_points()) self.exponential_t.set_initial_control_points(self.fixed_effects['control_points']) self.exponential_t.set_initial_momenta(self.fixed_effects['momenta_t']) self.exponential_t.move_data_to_(device=device) self.exponential_t.update() template_points = self.exponential_t.get_template_points() template_data = self.hypertemplate.get_deformed_data(template_points, self.fixed_effects['hypertemplate_data']) args = [(i, self.template, template_data, self.fixed_effects['control_points'], self.fixed_effects['momenta'][i], with_grad) for i in range(len(targets))] start = time.perf_counter() results = self.pool.map(_subject_attachment_and_regularity, args, chunksize=1) # TODO: optimized chunk size # results = self.pool.imap_unordered(_subject_attachment_and_regularity, args, chunksize=1) # results = self.pool.imap(_subject_attachment_and_regularity, args, chunksize=int(len(args)/self.number_of_processes)) logger.debug('time taken for deformations : ' + str(time.perf_counter() - start)) # Sum and return. if with_grad: attachment = 0.0 regularity = 0.0 gradient = {} if not self.freeze_template: gradient['momenta_t'] = np.zeros(self.fixed_effects['momenta_t'].shape) if not self.freeze_control_points: gradient['control_points'] = np.zeros(self.fixed_effects['control_points'].shape) if not self.freeze_momenta: gradient['momenta'] = np.zeros(self.fixed_effects['momenta'].shape) for result in results: i, (attachment_i, regularity_i, gradient_i) = result attachment += attachment_i regularity += regularity_i for key, value in gradient_i.items(): if key == 'momenta': gradient[key][i] = value else: gradient[key] += value return attachment, regularity, gradient else: attachment = 0.0 regularity = 0.0 for result in results: i, (attachment_i, regularity_i) = result attachment += attachment_i regularity += regularity_i return attachment, regularity else: device, device_id = get_best_device(gpu_mode=self.gpu_mode) hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, \ momenta_t, module_intensities, module_positions, module_variances = self._fixed_effects_to_torch_tensors(with_grad,device=device) sparse_matrix = self.construct_sparse_matrix(template_points['image_points'], module_positions, module_variances, module_intensities) return self._compute_attachment_and_regularity(dataset, hypertemplate_data, hypertemplate_points, control_points, momenta, momenta_t, sparse_matrix, module_intensities, module_positions, module_variances, with_grad, device=device) #################################################################################################################### ### Private methods: #################################################################################################################### @staticmethod def _deform_and_compute_attachment_and_regularity(exponential, template_points, control_points, momenta, module_positions, module_variances, module_intensities, sparse_matrix, template, template_data, multi_object_attachment, deformable_objects, objects_noise_variance, regu_var_m, regu_var_m_ortho, device='cpu'): # Deform. exponential.set_initial_template_points(template_points) exponential.set_initial_control_points(control_points) exponential.set_initial_momenta(momenta) exponential.move_data_to_(device=device) exponential.update() # Compute attachment and regularity. deformed_points = exponential.get_template_points() deformed_data = template.get_deformed_data(deformed_points, template_data) deformed_data['image_intensities'] += sparse_matrix attachment = -multi_object_attachment.compute_weighted_distance(deformed_data, template, deformable_objects, objects_noise_variance) regularity = - exponential.get_norm_squared() # x = template_points['image_points'].cpu().detach() # final_cp = exponential.control_points_t[-1].cpu().detach() # regu = torch.zeros(x.shape[:-1], dtype=torch.float64) # for k in range(final_cp.shape[0]): # m = momenta[k].clone().cpu().detach() # if m.numpy().any(): # m /= torch.norm(m) # e = torch.randn(m.size(), dtype=torch.float64) # e -= e.dot(m) * m # e /= torch.norm(e) # if m.size()[0] == 2: # y = x - final_cp[k] # regu += torch.exp(-torch.mm(y.view(-1,2), m.view(2,1)) ** 2 / (2 * 1) - torch.mm(y.view(-1,2), e.view(2,1)) ** 2 / (2 * 10)).view(y.shape[:-1]) # else: # e2 = torch.cross(m, e) # y = x - final_cp[k] # regu += torch.exp( # -torch.dot(y, m) ** 2 / (2 * 1) - torch.dot(y, e) ** 2 / (2 * 10) - torch.dot(y, e2) ** 2 / (2 * 10)) # # dim = template_data['image_intensities'].shape # regu2 = torch.zeros(dim).double() # for k in range(module_positions.shape[0]): # x_norm = torch.mul(x ** 2, 1 / module_variances[k] ** 2).sum(-1).view(-1, 1) # y_norm = torch.mul(module_positions[k] ** 2, 1 / module_variances[k] ** 2).sum().view(-1, 1) # points_divided = torch.mul(x, 1 / module_variances[k] ** 2) # dist = (x_norm + y_norm - 2.0 * torch.mul(points_divided, module_positions[k]).sum(-1).view(-1, # 1)).reshape( # dim) # regu2 += torch.exp(-dist)*torch.abs(module_intensities[k].detach()) # # regularity -= 200.*torch.sum(torch.mul(torch.tensor(regu, dtype=torch.float64),regu2)) final_cp = exponential.control_points_t[-1] final_momenta = exponential.momenta_t[-1] for k in range(final_cp.shape[0]): if momenta[k].detach().numpy().any(): m = final_momenta[k] / torch.norm(momenta[k]) e = torch.randn(m.shape[0], dtype=torch.float64) e = e - torch.dot(e, m) * m e = e / torch.norm(e) for l in range(module_positions.shape[0]): if m.size()[0] == 2: y = module_positions[l] - final_cp[k] regularity += - 10000*torch.sum(torch.exp(- torch.mm(y.view(-1,2), m.view(2,1)) ** 2 / (2 * regu_var_m) - torch.mm(y.view(-1,2), e.view(2,1)) ** 2 / (2 * regu_var_m_ortho)).view(y.shape[:-1])) else: e2 = torch.cross(m, e) y = module_positions[l] - final_cp[k] regularity += - torch.sum(torch.exp( -torch.dot(y, m) ** 2 / (2 * regu_var_m) - torch.dot(y, e) ** 2 / (2 * regu_var_m_ortho) - torch.dot(y, e2) ** 2 / (2 * regu_var_m_ortho)).view(y.shape[:-1])) x_norm = (module_positions ** 2).sum(1).view(-1, 1) dist = x_norm + x_norm.view(1, -1) - 2.0 * torch.mm(module_positions, torch.transpose(module_positions, 0, 1)) # dist = torch.zeros([16,16], dtype=torch.float64) # for k in range(16): # dist[k,:] = torch.norm(module_positions - module_positions[k], dim=1)**2/400 regularity -= -torch.sum(torch.exp(-dist)) assert torch.device( device) == attachment.device == regularity.device, 'attachment and regularity tensors must be on the same device. ' \ 'device=' + device + \ ', attachment.device=' + str(attachment.device) + \ ', regularity.device=' + str(regularity.device) return attachment, regularity @staticmethod def _compute_gradients(attachment, regularity, freeze_template, momenta_t, freeze_control_points, control_points, freeze_momenta, momenta, freeze_sparse_matrix, module_intensities, module_positions, module_variances, with_grad=False): if with_grad: total_for_subject = attachment + regularity total_for_subject.backward() gradient = {} if not freeze_template: assert momenta_t.grad is not None, 'Gradients have not been computed' gradient['momenta_t'] = momenta_t.grad.detach().cpu().numpy() if not freeze_control_points: assert control_points.grad is not None, 'Gradients have not been computed' gradient['control_points'] = control_points.grad.detach().cpu().numpy() if not freeze_momenta: assert momenta.grad is not None, 'Gradients have not been computed' gradient['momenta'] = momenta.grad.detach().cpu().numpy() if not freeze_sparse_matrix: gradient['module_intensities'] = module_intensities.grad.detach().cpu().numpy() gradient['module_positions'] = module_positions.grad.detach().cpu().numpy() gradient['module_variances'] = module_variances.grad.detach().cpu().numpy() res = attachment.detach().cpu().numpy(), regularity.detach().cpu().numpy(), gradient else: res = attachment.detach().cpu().numpy(), regularity.detach().cpu().numpy() return res def _compute_attachment_and_regularity(self, dataset, hypertemplate_data, hypertemplate_points, control_points, momenta, momenta_t, sparse_matrix, module_intensities, module_positions, module_variances, with_grad=False, device='cpu'): """ Core part of the ComputeLogLikelihood methods. Torch input, numpy output. Single-thread version. """ # Initialize. targets = [target[0] for target in dataset.deformable_objects] attachment = 0. regularity = 0. self.exponential_t.set_initial_template_points(hypertemplate_points) self.exponential_t.set_initial_control_points(control_points) self.exponential_t.set_initial_momenta(momenta_t[0]) self.exponential_t.move_data_to_(device=device) self.exponential_t.update() template_points = self.exponential_t.get_template_points() template_data = self.hypertemplate.get_deformed_data(template_points, hypertemplate_data) self.set_template_data({key: value.detach().cpu().numpy() for key, value in template_data.items()}) regularity -= self.exponential_t.get_norm_squared() # loop for every deformable object # deform and update attachment and regularity for i, target in enumerate(targets): new_attachment, new_regularity = DeterministicAtlasWithModule._deform_and_compute_attachment_and_regularity( self.exponential, template_points, control_points, momenta[i], module_positions[i], module_variances[i], module_intensities[i], sparse_matrix[i], self.template, template_data, self.multi_object_attachment, target, self.objects_noise_variance, self.regu_var_m, self.regu_var_m_ortho, device=device) attachment += new_attachment regularity += new_regularity # Compute gradient. return self._compute_gradients(attachment, regularity, self.freeze_template, momenta_t, self.freeze_control_points, control_points, self.freeze_momenta, momenta, self.freeze_sparse_matrix, module_intensities, module_positions, module_variances, with_grad) #################################################################################################################### ### Private utility methods: #################################################################################################################### def construct_sparse_matrix(self, points, module_centers, module_variances, module_intensities): dim = (self.number_of_subjects,) + self.fixed_effects['template_data']['image_intensities'].shape sparse_matrix = torch.zeros(dim).double() for i in range(dim[0]): for k in range(self.nb_modules): x_norm = torch.mul(points ** 2, 1/module_variances[i,k]**2).sum(-1).view(-1, 1) y_norm = torch.mul(module_centers[i,k] ** 2, 1/module_variances[i,k]**2).sum().view(-1, 1) points_divided = torch.mul(points, 1/module_variances[i,k]**2) dist = (x_norm + y_norm - 2.0 * torch.mul(points_divided, module_centers[i,k]).sum(-1).view(-1,1)).reshape(dim[1:]) sparse_matrix[i] += torch.exp(-dist)*module_intensities[i,k] # sparse_matrix[i] += 70/81*(1-dist)**2*(dist<1).double()*module_intensities[i,k] # x_norm = (points ** 2) # y_norm = (module_centers[i,k] ** 2) # dist = (x_norm + y_norm - 2.0 * torch.mul(points, module_centers[i, k])).view(-1, 2) # rect = ((dist[:,0] < module_variances[i,k,0]) * (dist[:,1] < module_variances[i,k,1])).double() # f = torch.exp(-dist.sum(1)/10) # conv2 = torch.nn.Conv2d(1, 1, kernel_size=1, stride=1, padding=1, bias=False) # conv2.weights = rect.reshape([1, 1, 100, 100]) # sparse_matrix[i] += conv2(f.float().reshape([1,1,100,100]))[0,0,1:-1,1:-1].double()*module_intensities[i,k] #sparse_matrix[i] += module_intensities[i,k] * (1/(1+torch.exp(-2*2*(points[:,:,0] - module_centers[i,k,0] + module_variances[i,k,0]/2))) - 1/(1+torch.exp(-2*2*(points[:,:,0] - module_centers[i,k,0] - module_variances[i,k,0]/2)))) * (1/(1+ torch.exp(-2*2*(points[:,:,1] - module_centers[i,k,1] + module_variances[i,k,1]/2))) - 1/(1+torch.exp(-2*2*(points[:,:,1] - module_centers[i,k,1] - module_variances[i,k,1]/2)))) # x_norm = torch.mul(points ** 2, 1/module_variances[i,k]**2).sum(2).view(-1, 1) # y_norm = torch.mul(module_centers[i,k] ** 2, 1/module_variances[i,k]**2).sum().view(-1, 1) # points_divided = torch.mul(points, 1/module_variances[i,k]**2) # dist = (x_norm + y_norm - 2.0 * torch.mul(points_divided, module_centers[i,k]).sum(2).view(-1,1)).reshape(dim[1:]) # sparse_matrix[i] += module_intensities[i,k] * (1/(1+torch.exp(-2*100*(dist+0.1))) - 1/(1+torch.exp(-2*100*(dist - 1)))) return sparse_matrix def _fixed_effects_to_torch_tensors(self, with_grad, device='cpu'): """ Convert the fixed_effects into torch tensors. """ # Template data. template_data = self.fixed_effects['template_data'] template_data = {key: move_data(value, device=device, dtype=self.tensor_scalar_type, requires_grad=False) for key, value in template_data.items()} # Template points. template_points = self.template.get_points() template_points = {key: move_data(value, device=device, dtype=self.tensor_scalar_type, requires_grad=False) for key, value in template_points.items()} hypertemplate_data = self.fixed_effects['hypertemplate_data'] hypertemplate_data = {key: move_data(value, device=device, dtype=self.tensor_scalar_type, requires_grad=False) for key, value in hypertemplate_data.items()} # Template points. hypertemplate_points = self.hypertemplate.get_points() hypertemplate_points = {key: move_data(value, device=device, dtype=self.tensor_scalar_type, requires_grad=False) for key, value in hypertemplate_points.items()} momenta_t = self.fixed_effects['momenta_t'] momenta_t = move_data(momenta_t, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_template and with_grad)) # Control points. if self.dense_mode: assert (('landmark_points' in self.template.get_points().keys()) and ('image_points' not in self.template.get_points().keys())), \ 'In dense mode, only landmark objects are allowed. One at least is needed.' control_points = template_points['landmark_points'] else: control_points = self.fixed_effects['control_points'] control_points = move_data(control_points, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_control_points and with_grad)) # control_points = Variable(torch.from_numpy(control_points).type(self.tensor_scalar_type), # requires_grad=(not self.freeze_control_points and with_grad)) # Momenta. momenta = self.fixed_effects['momenta'] momenta = move_data(momenta, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_momenta and with_grad)) module_intensities = self.fixed_effects['module_intensities'] module_intensities = move_data(module_intensities, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_sparse_matrix and with_grad)) module_positions = self.fixed_effects['module_positions'] module_positions = move_data(module_positions, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_sparse_matrix and with_grad)) module_variances = self.fixed_effects['module_variances'] module_variances = move_data(module_variances, device=device, dtype=self.tensor_scalar_type, requires_grad=(not self.freeze_sparse_matrix and with_grad)) return hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, momenta_t, module_intensities, module_positions, module_variances #################################################################################################################### ### Writing methods: #################################################################################################################### def write(self, dataset, population_RER, individual_RER, output_dir, write_residuals=True): # Write the model predictions, and compute the residuals at the same time. residuals = self._write_model_predictions(dataset, individual_RER, output_dir, compute_residuals=write_residuals) # Write residuals. if write_residuals: residuals_list = [[residuals_i_k.data.cpu().numpy() for residuals_i_k in residuals_i] for residuals_i in residuals] write_2D_list(residuals_list, output_dir, self.name + "__EstimatedParameters__Residuals.txt") # Write the model parameters. self._write_model_parameters(output_dir) def _write_model_predictions(self, dataset, individual_RER, output_dir, compute_residuals=True): device, _ = get_best_device(self.gpu_mode) # Initialize. hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, momenta_t, \ module_intensities, module_positions, module_variances = self._fixed_effects_to_torch_tensors(False, device=device) sparse_matrix = self.construct_sparse_matrix(template_points['image_points'], module_positions, module_variances, module_intensities) # Deform, write reconstructions and compute residuals. self.exponential.set_initial_template_points(template_points) self.exponential.set_initial_control_points(control_points) residuals = [] # List of torch 1D tensors. Individuals, objects. for i, subject_id in enumerate(dataset.subject_ids): self.exponential.set_initial_momenta(momenta[i]) self.exponential.update() # Writing the whole flow. names = [] for k, object_name in enumerate(self.objects_name): name = self.name + '__flow__' + object_name + '__subject_' + subject_id names.append(name) #self.exponential.write_flow(names, self.objects_name_extension, self.template, template_data, output_dir) deformed_points = self.exponential.get_template_points() deformed_data = self.template.get_deformed_data(deformed_points, template_data) deformed_data['image_intensities'] += sparse_matrix[i] m = torch.max(deformed_data['image_intensities']) for k in range(module_positions.shape[1]): for j in range(module_positions[i,k].shape[0]): module_positions[i,k,j] = min(99, module_positions[i,k,j]) module_positions[i, k, j] = max(0, module_positions[i, k, j]) deformed_data['image_intensities'][tuple(module_positions[i,k].int())] = 2* m if compute_residuals: residuals.append(self.multi_object_attachment.compute_distances( deformed_data, self.template, dataset.deformable_objects[i][0])) names = [] for k, (object_name, object_extension) \ in enumerate(zip(self.objects_name, self.objects_name_extension)): name = self.name + '__Reconstruction__' + object_name + '__subject_' + subject_id + object_extension names.append(name) self.template.write(output_dir, names, {key: value.detach().cpu().numpy() for key, value in deformed_data.items()}) deformed_data['image_intensities'] = sparse_matrix[i] names = [] for k, (object_name, object_extension) \ in enumerate(zip(self.objects_name, self.objects_name_extension)): name = self.name + '__Reconstruction__' + object_name + '__subject_' + subject_id + '_sparsematrix' + object_extension names.append(name) self.template.write(output_dir, names, {key: value.detach().cpu().numpy() for key, value in deformed_data.items()}) return residuals def _write_model_parameters(self, output_dir): # Template. device, _ = get_best_device(self.gpu_mode) template_names = [] hypertemplate_data, hypertemplate_points, template_data, template_points, control_points, momenta, momenta_t, module_intensities, module_positions, module_variances \ = self._fixed_effects_to_torch_tensors(False, device=device) self.exponential_t.set_initial_template_points(hypertemplate_points) self.exponential_t.set_initial_control_points(control_points) self.exponential_t.set_initial_momenta(momenta_t[0]) self.exponential_t.move_data_to_(device=device) self.exponential_t.update() template_points = self.exponential_t.get_template_points() template_data = self.hypertemplate.get_deformed_data(template_points, hypertemplate_data) self.set_template_data({key: value.detach().cpu().numpy() for key, value in template_data.items()}) for i in range(len(self.objects_name)): aux = self.name + "__EstimatedParameters__Template_" + self.objects_name[i] + self.objects_name_extension[i] template_names.append(aux) self.template.write(output_dir, template_names) # Control points. write_2D_array(self.get_control_points(), output_dir, self.name + "__EstimatedParameters__ControlPoints.txt") # Momenta. write_3D_array(self.get_momenta(), output_dir, self.name + "__EstimatedParameters__Momenta.txt") write_2D_array(self.get_momenta_t()[0], output_dir, self.name + "__EstimatedParameters__Momenta_t.txt") write_3D_array(self.get_module_positions(), output_dir, self.name + "__EstimatedParameters__ModulePositions.txt") write_3D_array(self.get_module_intensities(), output_dir, self.name + "__EstimatedParameters__ModuleIntensities.txt") write_3D_array(self.get_module_variances(), output_dir, self.name + "__EstimatedParameters__ModuleVariances.txt")
lepennec/Deformetrica_coarse_to_fine
core/models/deterministic_atlas_withmodule.py
deterministic_atlas_withmodule.py
py
45,901
python
en
code
0
github-code
6
35754362412
import pandas as pandas import matplotlib.pyplot as pyplot import numpy as numpy import streamlit as st import geopandas as gpd import pydeck as pdk from helpers.data import load_data, data_preprocessing, load_geo_data, geo_data_preprocessing from helpers.viz import yearly_pollution, monthly_pollution, ranking_pollution, pollution_map from helpers.model import pollution_prediction DATA_PATH = 'pollution_us_2000_2016.csv' st.title("Analysis of US Pollution between 2000 and 2016, focusing on California") # Read Data df = load_data(DATA_PATH,145000) st.header('Raw data') st.dataframe(df) # Clean Data st.header('Data Preprocessing') df_cleaned = data_preprocessing(df.copy()) st.subheader('Cleaned data') st.dataframe(df_cleaned) # Data Visualization st.header('Data Visualization') st.sidebar.title('Filters') pollutant = st.sidebar.selectbox('Pollutant', ["NO2Mean", "SO2Mean", "O3Mean", "COMean"]) cali = st.sidebar.checkbox('Cali Data Only') values = st.sidebar.checkbox('Show Data Values') # Yearly plot st.subheader('Yearly pollution change') st.markdown(f"__{pollutant} in {'California' if cali else 'the US'} by year between 2000 and 2016__") yearly_pollution_chart = yearly_pollution(df_cleaned, pollutant, cali, values) st.pyplot(yearly_pollution_chart) # Monthly plot st.subheader('Monthly pollution change') st.markdown(f"__{pollutant} in {'California' if cali else 'the US'} by month between 2000 and 2016__") monthly_pollution_chart = monthly_pollution(df_cleaned, pollutant, cali, values) st.pyplot(monthly_pollution_chart) # Ranking plot st.subheader('State rankings') st.markdown(f"__Top 30 {pollutant} rankings in the US__") ranking_pollution_chart = ranking_pollution(df_cleaned, pollutant, values) st.pyplot(ranking_pollution_chart) # Modeling st.subheader('Prediction Model') st.markdown(f"__{pollutant} predictions until 2026 in {'California' if cali else 'the US'}__") prediction_model = pollution_prediction(df_cleaned, pollutant, cali, values) st.pyplot(prediction_model) # Data Mapping st.header('Data Mapping') GEO_DATA_PATH = 'geo_data.json' # Read Data geo_data = load_geo_data(GEO_DATA_PATH) st.subheader('Raw Geo Data (sample of 3)') st.write(geo_data.sample(3)) # Clean and merge data st.subheader('Geo data Preprocessing: Cleaned and Merged Geo data (sample of 3)') merged = geo_data_preprocessing(geo_data.copy(), df_cleaned.copy()) st.write(merged) # Map data st.subheader('Mapped data') st.markdown(f"__US {pollutant} Averages from 2000 to 2016__") COLOR_BREWER_BLUE_SCALE = [ [240, 249, 232], [204, 235, 197], [168, 221, 181], [123, 204, 196], [67, 162, 202], [8, 104, 172], ] NO2Mean = pdk.Layer( "HeatmapLayer", data=merged, opacity=0.9, get_position=["long", "lat"], aggregation=pdk.types.String("MEAN"), color_range=COLOR_BREWER_BLUE_SCALE, threshold=1, get_weight="NO2Mean", pickable=True, ) SO2Mean = pdk.Layer( "ColumnLayer", data=merged, get_position=["long", "lat"], get_elevation="SO2Mean", elevation_scale=100, radius=50, get_fill_color=[180, 0, 200, 140], pickable=True, auto_highlight=True, ) st.pydeck_chart(pdk.Deck( map_style='mapbox://styles/mapbox/light-v9', initial_view_state=pdk.ViewState( latitude=37.6000, longitude=-95.6650, zoom=5, pitch=50, ), layers=[NO2Mean] ))
natalie-cheng/pollution-project
main.py
main.py
py
3,405
python
en
code
0
github-code
6
26609155963
import pyautogui import time def click_on_bluestacks(x, y): # Attendez 5 secondes pour vous donner le temps de changer de fenêtre time.sleep(5) # Trouvez la fenêtre Bluestacks bluestacks_windows = pyautogui.getWindowsWithTitle('Bluestacks') # Vérifiez si la fenêtre Bluestacks a été trouvée if len(bluestacks_windows) == 0: print("La fenêtre Bluestacks n'a pas été trouvée.") return # Si la fenêtre Bluestacks a été trouvée, effectuez un clic à des coordonnées spécifiques bluestacks_window = bluestacks_windows[0] # Déplacez le curseur de souris à ces coordonnées dans la fenêtre Bluestacks pyautogui.moveTo(bluestacks_window.left + x, bluestacks_window.top + y) # Cliquez à ces coordonnées pyautogui.click() # Appelez la fonction click_on_bluestacks avec les coordonnées (100, 100) if __name__ == "__main__": click_on_bluestacks(100, 100)
Edgarflc/Summoners-War-Bot
test.py
test.py
py
941
python
fr
code
0
github-code
6
42123413608
import datetime from collections import namedtuple import isodate from .. import build_data_path as build_data_path_global from ..input_definitions.examples import LAGTRAJ_EXAMPLES_PATH_PREFIX TrajectoryOrigin = namedtuple("TrajectoryOrigin", ["lat", "lon", "datetime"]) TrajectoryDuration = namedtuple("TrajectoryDuration", ["forward", "backward"]) TrajectoryDefinition = namedtuple( "TrajectoryDefinition", [ "domain", "duration", "origin", "name", "type", "timestep", "extra_kwargs", "version", ], ) def duration_or_none(s): if s is None: return datetime.timedelta() return isodate.parse_duration(s) INPUT_REQUIRED_FIELDS = { "trajectory_type": ["linear", "eulerian", "lagrangian"], # domain should only be given when creating a lagrangian trajectory or if # we're trying to get the timestep from the domain data. In both cases the # domain should be a string "domain": [ dict(requires=dict(trajectory_type="lagrangian"), choices=str), dict(requires=dict(timestep="domain_data"), choices=str), None, ], "lat_origin": float, "lon_origin": float, "datetime_origin": isodate.parse_datetime, "forward_duration|backward_duration": duration_or_none, # if the domain is given we can use domain data for the timestep, otherwise # the timestep should be a parsable duration string "timestep": ( dict( requires=dict(domain="__is_set__"), choices=["domain_data"], ), isodate.parse_duration, ), # only linear trajectories need to have their velocity prescribed "u_vel": dict(requires=dict(trajectory_type="linear"), choices=float), "v_vel": dict(requires=dict(trajectory_type="linear"), choices=float), # velocity method is only relevant when making lagrangian trajectories "velocity_method": dict( requires=dict(trajectory_type="lagrangian"), choices=[ "single_height_level", "single_pressure_level", "lower_troposphere_humidity_weighted", ], ), "velocity_method_height": dict( requires=dict(velocity_method="single_height_level"), choices=float, ), "velocity_method_pressure": dict( requires=dict(velocity_method="single_pressure_level"), choices=float, ), } def build_data_path(root_data_path, trajectory_name): # we need to strip the `lagtraj://` prefix before we construct the path # since the data is stored locally if trajectory_name.startswith(LAGTRAJ_EXAMPLES_PATH_PREFIX): trajectory_name = trajectory_name[len(LAGTRAJ_EXAMPLES_PATH_PREFIX) :] data_path = build_data_path_global( root_data_path=root_data_path, data_type="trajectory" ) return data_path / "{}.nc".format(trajectory_name)
EUREC4A-UK/lagtraj
lagtraj/trajectory/__init__.py
__init__.py
py
2,892
python
en
code
8
github-code
6
27532635720
# Question 19 class Py: def get_String(self, str): self.str = str def print_String(self): print(self.str.upper()) str = input("Enter a String: ") p1 = Py() p1.get_String(str) print("String in uppercase: ", end="") p1.print_String()
rudravashishtha/Python_ETE_Solution
19ques.py
19ques.py
py
261
python
en
code
0
github-code
6
32636741250
import six from c7n_azure.actions.tagging import Tag, AutoTagUser, RemoveTag, TagTrim, TagDelayedAction from c7n_azure.actions.delete import DeleteAction from c7n_azure.filters import (MetricFilter, TagActionFilter, DiagnosticSettingsFilter, PolicyCompliantFilter) from c7n_azure.provider import resources from c7n_azure.query import QueryResourceManager, QueryMeta, ChildResourceManager, TypeInfo, \ ChildTypeInfo, TypeMeta from c7n_azure.utils import ResourceIdParser from c7n.utils import local_session @six.add_metaclass(TypeMeta) class ArmTypeInfo(TypeInfo): # api client construction information for ARM resources id = 'id' name = 'name' diagnostic_settings_enabled = True default_report_fields = ( 'name', 'location', 'resourceGroup' ) @resources.register('armresource') @six.add_metaclass(QueryMeta) class ArmResourceManager(QueryResourceManager): class resource_type(ArmTypeInfo): service = 'azure.mgmt.resource' client = 'ResourceManagementClient' enum_spec = ('resources', 'list', None) def augment(self, resources): for resource in resources: if 'id' in resource: resource['resourceGroup'] = ResourceIdParser.get_resource_group(resource['id']) return resources def get_resources(self, resource_ids): resource_client = self.get_client('azure.mgmt.resource.ResourceManagementClient') session = local_session(self.session_factory) data = [ resource_client.resources.get_by_id(rid, session.resource_api_version(rid)) for rid in resource_ids ] return [r.serialize(True) for r in data] @staticmethod def register_arm_specific(registry, _): for resource in registry.keys(): klass = registry.get(resource) if issubclass(klass, ArmResourceManager): klass.action_registry.register('tag', Tag) klass.action_registry.register('untag', RemoveTag) klass.action_registry.register('auto-tag-user', AutoTagUser) klass.action_registry.register('tag-trim', TagTrim) klass.filter_registry.register('metric', MetricFilter) klass.filter_registry.register('marked-for-op', TagActionFilter) klass.action_registry.register('mark-for-op', TagDelayedAction) klass.filter_registry.register('policy-compliant', PolicyCompliantFilter) if resource != 'resourcegroup': klass.action_registry.register('delete', DeleteAction) if hasattr(klass.resource_type, 'diagnostic_settings_enabled') \ and klass.resource_type.diagnostic_settings_enabled: klass.filter_registry.register('diagnostic-settings', DiagnosticSettingsFilter) @six.add_metaclass(QueryMeta) class ChildArmResourceManager(ChildResourceManager, ArmResourceManager): class resource_type(ChildTypeInfo, ArmTypeInfo): pass resources.subscribe(resources.EVENT_FINAL, ArmResourceManager.register_arm_specific)
LRuttenCN/cloud-custodian
tools/c7n_azure/c7n_azure/resources/arm.py
arm.py
py
3,163
python
en
code
1
github-code
6