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
63614571
import torch import torch.nn.functional as F import matplotlib.pyplot as plt # for making figures import os # read in all the words current_dir = os.getcwd() words = open(current_dir+'/makemore/names.txt', 'r').read().splitlines() # print(f"{words[:8]}") # build the vocabulary of characters and mappings to/from integers chars = sorted(list(set(''.join(words)))) stoi = {s:i+1 for i,s in enumerate(chars)} stoi['.'] = 0 itos = {i:s for s,i in stoi.items()} # print(itos) # build the dataset block_size = 3 # context length: how many characters do we take to predict the next one? def build_dataset(words): X, Y = [], [] for w in words: #print(w) context = [0] * block_size for ch in w + '.': ix = stoi[ch] X.append(context) Y.append(ix) #print(''.join(itos[i] for i in context), '--->', itos[ix]) context = context[1:] + [ix] # crop and append X = torch.tensor(X) Y = torch.tensor(Y) # print(X.shape, Y.shape) return X, Y import random random.seed(42) random.shuffle(words) n1 = int(0.8*len(words)) n2 = int(0.9*len(words)) Xtr, Ytr = build_dataset(words[:n1]) Xdev, Ydev = build_dataset(words[n1:n2]) Xte, Yte = build_dataset(words[n2:]) g = torch.Generator().manual_seed(42) # for reproducibility C = torch.randn((27, 10), generator=g) W1 = torch.randn((30, 200), generator=g) W2 = torch.randn((200, 27), generator=g) parameters = [C, W1, W2] for p in parameters: p.requires_grad = True lri = [] lossi = [] stepi = [] batch = 32 for i in range(100): # minibatch construct ix = torch.randint(0, Xtr.shape[0], (batch,)) # forward pass emb = C[Xtr[ix]] # (32, 3, 10) h = torch.tanh(emb.view(-1, 30) @ W1) # (32, 200) logits = h @ W2 # (32, 27) loss = F.cross_entropy(logits, Ytr[ix]) #print(loss.item()) # backward pass for p in parameters: p.grad = None loss.backward() # update lr = 0.1 for p in parameters: p.data += -lr * p.grad # track stats #lri.append(lre[i]) stepi.append(i) lossi.append(loss.item()) #print(loss.item()) plt.plot(stepi, lossi) plt.show() # sample from the model g = torch.Generator().manual_seed(2147483647 + 10) for _ in range(5): out = [] context = [0] * block_size # initialize with all ... while True: emb = C[torch.tensor([context])] # (1,block_size,d) h = torch.tanh(emb.view(1, -1) @ W1) logits = h @ W2 probs = F.softmax(logits, dim=1) ix = torch.multinomial(probs, num_samples=1, generator=g).item() context = context[1:] + [ix] out.append(ix) if ix == 0: break print(''.join(itos[i] for i in out))
code-cp/bitesize_ai_rs
makemore/scripts/mlp.py
mlp.py
py
2,642
python
en
code
2
github-code
6
22795567170
import urllib2 import sys user=sys.argv[1] url='http://noaddress.x10.mx/chat/' url+= user url+=".txt" response = urllib2.urlopen(url).read() response=response[4:] #RSA def split(txt, seps): default_sep = seps[0] for sep in seps[1:]: # we skip seps[0] because that's the default seperator txt = txt.replace(sep, default_sep) return [i.strip() for i in txt.split(default_sep)] response=split(response, ['&', '%26']) for i in range(0,len(response)): print(response[i])
noaddress/securemessenger
client/0.0-TheBeginnings/read.py
read.py
py
491
python
en
code
0
github-code
6
4034606024
import argparse import glob import multiprocessing as mp import os import shutil import time import cv2 import tqdm import numpy as np from detectron2.config import get_cfg from partseg import add_partseg_config from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.engine.defaults import DefaultPredictor from detectron2.utils.visualizer import ColorMode, Visualizer # constants WINDOW_NAME = "COCO detections" def setup_cfg(args): # load config from file and command-line arguments cfg = get_cfg() add_partseg_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) # Set score_threshold for builtin models cfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_threshold cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_threshold cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = ( args.confidence_threshold ) # load weights from the default path if not args.custom_weights: default_weights = os.path.join(cfg.OUTPUT_DIR, "model_final.pth") if os.path.exists(default_weights): print("Use the default weights.") cfg.MODEL.WEIGHTS = default_weights cfg.freeze() return cfg def get_parser(): parser = argparse.ArgumentParser(description="Detectron2 demo for builtin models") parser.add_argument( "--config-file", default="configs/mask_rcnn_R_50_FPN_chair.yaml", metavar="FILE", help="path to config file", ) parser.add_argument( "--root-dir", type=str, help="root directory", default="datasets/images/test/chair", ) parser.add_argument( "--output-dir", type=str, help="path to output", default="datasets/predictions/test/chair", ) parser.add_argument("--shape-list-fn", type=str, help="path to shape list") parser.add_argument("--start", type=int, default=0) parser.add_argument("--end", type=int, default=None) parser.add_argument( "--confidence-threshold", type=float, default=0.5, help="Minimum score for instance predictions to be shown", ) parser.add_argument( "--custom-weights", action="store_true", help="whether to use custom weights" ) parser.add_argument( "--include-image", action="store_true", help="whether to include input images" ) parser.add_argument("--vis", action="store_true") parser.add_argument("--with-score", action="store_true") parser.add_argument( "--opts", help="Modify config options using the command-line 'KEY VALUE' pairs", default=[], nargs=argparse.REMAINDER, ) return parser if __name__ == "__main__": mp.set_start_method("spawn", force=True) args = get_parser().parse_args() setup_logger(name="fvcore") logger = setup_logger() logger.info("Arguments: " + str(args)) cfg = setup_cfg(args) predictor = DefaultPredictor(cfg) root_dir = args.root_dir if args.shape_list_fn: with open(args.shape_list_fn, "r") as f: image_ids = f.readlines() image_ids = [x.strip() for x in image_ids] else: image_ids = os.listdir(root_dir) image_ids = [x for x in image_ids if os.path.isdir(os.path.join(root_dir, x))] image_ids = sorted(image_ids) image_ids = image_ids[args.start : args.end] for image_id in tqdm.tqdm(image_ids[:]): file_name = os.path.join(root_dir, image_id, "img.png") image = read_image(file_name, format="BGR") predictions = predictor(image) instances = predictions["instances"].to("cpu") pred_masks = instances.pred_masks.numpy() # [N, H, W] pred_masks = (pred_masks * 255).astype(np.uint8) # for pred_mask in pred_masks: # cv2.imshow('mask', pred_mask) # if cv2.waitKey(0) == 27: # break # esc to quit output_dir = os.path.join(args.output_dir, image_id) if not os.path.isdir(output_dir): os.makedirs(output_dir) # save for idx, pred_mask in enumerate(pred_masks): output_file_name = os.path.join(output_dir, f"partmask_{idx}.png") cv2.imwrite(output_file_name, pred_mask) # Convert image from OpenCV BGR format to Matplotlib RGB format. image_rgb = image[:, :, ::-1] visualizer = Visualizer(image_rgb, None, instance_mode=ColorMode.IMAGE) if not args.with_score: # workaround to suppress visualizing scores instances.remove("scores") vis_output = visualizer.draw_instance_predictions(predictions=instances) if args.vis: cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL) cv2.imshow(WINDOW_NAME, vis_output.get_image()[:, :, ::-1]) if cv2.waitKey(0) == 27: break # esc to quit else: output_file_name = os.path.join(output_dir, f"partmask_all.png") vis_output.save(output_file_name) if args.include_image: shutil.copy(file_name, os.path.join(output_dir, "img.png"))
hansongfang/CompNet
PartSeg/predict_net.py
predict_net.py
py
5,233
python
en
code
33
github-code
6
38453799002
T = int(input()) for i in range(1,T+1): L = list(map(int,input().split())) L.sort() a,b,c = L type = "" if a+b <= c: type = "invalid!" elif a == b and b == c: type = "equilateral" elif a == b or b == c: type = "isosceles" else: type = "scalene" print(f"Case #{i}: {type}")
LightPotato99/baekjoon
math/geometry/triangle/triClassify.py
triClassify.py
py
345
python
en
code
0
github-code
6
72602309309
import sys n1 = sys.stdin.readline() n, m = n1.split(" ") n = int(n) m = int(m) matrix=[] for i in range(n): n1 = sys.stdin.readline() row =[] for j in n1.strip(): row.append(int(j)) matrix.append(row) def DFS(x,y,k,maze): row = len(maze) col = len(maze[0]) if k==0: res.append((x,y)) return else: f =False for x1,y1 in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: if maze[x1,y1] !=maze[x,y] and x<row and x>=0 and y<col and y>=0: f = True maze[x1,y1] = 1 if maze[x1,y1]==0 else 0 DFS(x1,y1,k-1,maze) maze[x1,y1] = 1 if maze[x1,y1]==0 else 0 if f==False: res.append((x,y)) n = input() n = int(n) for i in range(n): n1 = sys.stdin.readline() x , y ,k=n1.split(" ") x = int(x) y = int(y) k = int(k) res=[] maze= matrix.copy() r = DFS(x,y,k,maze) print(r[0])
CountyRipper/offer_py
mt2.py
mt2.py
py
974
python
en
code
0
github-code
6
23013301215
''' The purpose of this python script is to produce a program, that when run, will provide two input options: 1. File path 2. Type of directory One inputted, the program will create a directory with sub folders for data requests. The best package to use may be Tkinter. ''' from tkinter import * from tkinter.ttk import * import tkinter import os window = Tk() window.title("Batch File") window.geometry('450x200') #window.configure(background = 'Gray64') directory_base_check = '' style = Style() #style.layout() lbl_description = Label(window, text='Enter the Directory and type of Data Request to create standard folders') lbl_description.grid(column=0,row=0, columnspan = 2, pady = 5, sticky=W+E+N+S) lbl_path = Label(window, text='Directory:').grid(row=2, sticky = E, pady = 20) #lbl_path.grid(column=0,row=2, pady = 20) directory_input = Entry(window,width=50) directory_input.grid(column=1, row=2, sticky = W, padx = 5) lbl_combo = Label(window, text='Data Request Type:').grid(row=4, sticky = W) #lbl_combo.grid(column=0,row=4) #Types of Data Requests dr_type = Combobox(window) dr_type['values']= ('External with DA','External without DA','Internal','Recurring Reporting') dr_type.current(0) #set the selected item dr_type.grid(column=1, row=4, sticky =W, padx = 5) def print_text(input_text): lbl_display['text'] = input_text def directory_create(): dr_type_ans = dr_type.get() dir_ans = directory_input.get() #Create Error if Folder path does not match preferred if directory_base_check in dir_ans: pass else: print('Recheck Directory: Incorrect Directory') print_text('Recheck Directory: Incorrect Directory') btn = Button(window, text="Create Folders",command=directory_create) btn.grid(column=0, row=5, pady = 20) lbl_display = Label(window, text = '') lbl_display.grid(column = 1, row = 5, sticky=W+E+N+S, pady = 20, padx = 5) lbl_display.configure(background = 'gray64') #combo.get() window.mainloop()
jfkocher/Python_Code
Data Request/Batch_v3/main.py
main.py
py
1,989
python
en
code
0
github-code
6
31153800734
import pygame import random import numpy as np class Explosion(pygame.sprite.Sprite): def __init__(self, frames, xcoord, ycoord, scale=1.5, update_n=1): pygame.sprite.Sprite.__init__(self) # call Sprite initializer self.frame = 0 self.frames = frames self.image = self.frames[self.frame] self.rect = self.image.get_rect() self.x = xcoord self.y = ycoord self.scale = scale self.update_n = update_n self.update_counter = self.update_n def update(self): self.update_counter -= 1 if self.frame >= len(self.frames) - 1: self.kill() self.image = self.frames[self.frame] self.rect = self.image.get_rect() self.image = pygame.transform.scale(self.image, (int(self.rect.size[0] * self.scale), int(self.rect.size[1] * self.scale))) self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y if self.update_counter == 0: self.frame += 1 self.update_counter = self.update_n gameDisplay.blit(self.image, self.rect) def update_moving(self, xspeedboss, yspeedboss): if self.frame >= len(self.frames) - 1: self.kill() self.image = self.frames[self.frame] self.rect = self.image.get_rect() self.image = pygame.transform.scale(self.image, (int(self.rect.size[0] * 1.5), int(self.rect.size[1] * 1.5))) self.rect = self.image.get_rect() self.x += xspeedboss self.y += yspeedboss self.rect.x = self.x self.rect.y = self.y self.frame += 1 gameDisplay.blit(self.image, self.rect) class Explosion2(pygame.sprite.Sprite): def __init__(self, frames, xcoord, ycoord): pygame.sprite.Sprite.__init__(self) # call Sprite initializer self.frame = 0 self.frames = frames self.image = self.frames[self.frame] self.rect = self.image.get_rect() self.x = xcoord self.y = ycoord self.expansion = 0.8 self.update_counter = 3 def update(self): self.update_counter -= 1 if self.frame >= len(self.frames) - 1: self.kill() self.image = self.frames[self.frame] self.rect = self.image.get_rect() self.image = pygame.transform.scale(self.image, (int(self.rect.size[0] * self.expansion), int(self.rect.size[1] * self.expansion))) self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) self.rect.centerx = self.x self.rect.centery = self.y if self.update_counter == 0: self.expansion += 0.045 self.frame += 1 self.update_counter = 4 gameDisplay.blit(self.image, self.rect) class Ship(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # call Sprite initializer self.image = player_ship self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = (display_width - self.width) * 0.5 self.y = display_height - self.height * 1.2 self.speed = 0 # This variable changes with key presses self.endspeed = 1 self.mask = pygame.mask.from_surface(self.image) def update(self): # Update variables of the game for next update self.x += self.speed if self.x > display_width - self.width: self.x = display_width - self.width # boundaries for ship elif self.x < 0: self.x = 0 # boundaries for ship self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) def to_end_position(self, xcoord): statement = False self.speed = 0 if self.x < xcoord - 1: self.x += self.endspeed elif self.x > xcoord + 1: self.x -= self.endspeed else: statement = True self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) return statement class Meteor(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # call Sprite initializer meteor_choices = [meteor1, meteor2, meteor3, meteor4] self.image = meteor_choices[random.randrange(0, 3)] self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = random.randrange(0, display_width - self.width) self.y = -200 self.mask = pygame.mask.from_surface(self.image) self.speed = 7 def update(self): self.y += self.speed self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) class Laser(pygame.sprite.Sprite): def __init__(self, xcoord, ycoord): pygame.sprite.Sprite.__init__(self) self.image = laser_blue self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = xcoord - 0.5 * self.width # depends on ship location self.y = ycoord # These will be set at spawn because it depends on ship location self.speed = -20 self.mask = pygame.mask.from_surface(self.image) def update(self): self.y += self.speed if self.y < 0 - self.height: self.kill() else: self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) class EnemyGoon(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # call Sprite initializer enemy_choices = [enemy1, enemy2, enemy3] self.image = enemy_choices[random.randrange(0, 2)] self.rect = self.image.get_rect() self.image = pygame.transform.scale(self.image, (int(self.rect.size[0] / 1.5), int(self.rect.size[1] / 1.5))) self.rect = self.image.get_rect() # after transforming need to acquire new rect self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = random.choice(np.linspace(0, display_width - self.width, 10)) self.y = 100 + self.height self.mask = pygame.mask.from_surface(self.image) self.update_timer = fps * 2 # update every 60 frames self.x_speed = random.choice([-3, 3]) def update(self): self.update_timer -= 1 if self.update_timer == 0: self.fire() self.update_timer = fps * 2 self.y = 100 * np.sin(timer / 500) + 100 self.x += self.x_speed if self.x > display_width - self.width: self.x = display_width - self.width # boundaries for enemy self.x_speed = -self.x_speed # flip speed so that enemy moves into opposite direction elif self.x < 0: self.x = 0 # boundaries for ship self.x_speed = -self.x_speed # flip speed so that enemy moves into opposite direction self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) def fire(self): enemy_lasers.add(EnemyLaser(self.x + 0.5 * self.width, self.y)) pygame.mixer.Channel(2).play(enemy_laser_sound) class EnemyLaser(pygame.sprite.Sprite): def __init__(self, xcoord, ycoord): pygame.sprite.Sprite.__init__(self) self.image = laser_red self.image = pygame.transform.flip(self.image, 0, 1) self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = xcoord - 0.5 * self.width # depends on ship location self.y = ycoord # These will be set at spawn because it depends on ship location self.speed = 7 self.mask = pygame.mask.from_surface(self.image) def update(self): self.y += self.speed if self.y > display_height: self.kill() else: self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) class ChooseFont(object): def __init__(self, fonttype, fontsize, color): self.font = pygame.font.Font(fonttype, fontsize) self.color = color def message(self, text, xcoord, ycoord, centered=False): text_surface = self.font.render(text, True, self.color) text_rect = text_surface.get_rect() if centered is True: text_rect.center = (xcoord, ycoord) elif centered is False: text_rect.x = xcoord text_rect.y = ycoord gameDisplay.blit(text_surface, text_rect) class Boss(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # call Sprite initializer self.image = boss_image self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = display_width * 0.5 - self.width * 0.5 self.y = 50 self.y_speed = 0 self.mask = pygame.mask.from_surface(self.image) self.laser_timer_max = fps * 2 # update every 120 frames self.laser_timer = fps * 2 # update every 120 frames self.laser_list = [5, 10, 15, 20, 25] self.bomb_timer_max = fps * 4 self.bomb_timer = self.bomb_timer_max self.x_speed = 3 self.hp = 100 self.maxhp = self.hp self.dead_timer = 170 self.add_explosion_timer = 10 self.randx = None self.randy = None self.hp_50 = False self.hp_25 = False def update(self): if self.hp > 0: self.laser_timer -= 1 self.bomb_timer -= 1 if self.laser_timer in self.laser_list: # frames at which ship fires self.fire_laser() if self.laser_timer == 0: self.laser_timer = self.laser_timer_max if self.bomb_timer == 0: self.bomb_timer = self.bomb_timer_max self.fire_bomb() if self.hp < self.maxhp * 0.5 and self.hp_50 is False: if self.x_speed > 0: self.x_speed = 5 elif self.x_speed < 0: self.x_speed = -5 self.laser_timer_max = fps * 1.7 self.bomb_timer_max = fps * 3.5 self.hp_50 = True if self.hp < self.maxhp * 0.25 and self.hp_25 is False: if self.x_speed > 0: self.x_speed = 7 elif self.x_speed < 0: self.x_speed = -7 self.laser_timer_max = fps * 1.5 self.bomb_timer_max = fps * 3 self.hp_25 = True elif self.dead_timer > 0: self.x_speed = 1 self.add_explosion_timer -= 1 self.dead_timer -= 1 if self.add_explosion_timer == 0: self.add_explosions() self.add_explosion_timer = 10 for explosion in explosions_boss: explosion.update_moving(self.x_speed, self.y_speed) self.x += self.x_speed if self.x > display_width - self.width: self.x = display_width - self.width # boundaries for enemy self.x_speed = -self.x_speed # flip speed so that enemy moves into opposite direction elif self.x < 0: self.x = 0 # boundaries for ship self.x_speed = -self.x_speed # flip speed so that enemy moves into opposite direction self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) self.draw_health() def fire_laser(self): enemy_lasers.add(EnemyLaser(self.x + 0.35 * self.width, self.y + 0.8 * self.height)) enemy_lasers.add(EnemyLaser(self.x + 0.65 * self.width, self.y + 0.8 * self.height)) pygame.mixer.Channel(2).play(enemy_laser_sound) def fire_bomb(self): boss_bomb.add(BossBomb(self.x, self.y)) pygame.mixer.Channel(4).play(bomb_release_sound) def draw_health(self): color = red width_hp = self.width * (self.hp / self.maxhp) healthbar = pygame.Rect((self.x, self.y - 10, width_hp, 10)) pygame.draw.rect(gameDisplay, color, healthbar) def add_explosions(self): for i in range(2): self.randx = random.randint(np.round(self.x) + 10 - 32, np.round(self.x) + self.width - 10 - 32) self.randy = random.randint(np.round(self.y) + 10 - 64, np.round(self.y) + self.height - 10 - 64) explosions_boss.add(Explosion(explosion1, self.randx, self.randy)) pygame.mixer.Channel(3).play(explosion_sound) class BossBomb(pygame.sprite.Sprite): def __init__(self, xcoord, ycoord): pygame.sprite.Sprite.__init__(self) self.image = missile self.image = pygame.transform.flip(self.image, 0, 1) self.rect = self.image.get_rect() self.width = self.rect.size[0] self.height = self.rect.size[1] self.x = xcoord - 0.5 * self.width # depends on ship location self.y = ycoord # These will be set at spawn because it depends on ship location self.xspeed = 0 self.xspeedincr = 0.3 self.xspeedmax = 5 self.yspeed = 3 self.mask = pygame.mask.from_surface(self.image) def update(self, xship, yship): if xship > self.x: if self.xspeed < self.xspeedmax: self.xspeed += self.xspeedincr elif xship < self.x: if self.xspeed > -self.xspeedmax: self.xspeed -= self.xspeedincr self.x += self.xspeed self.y += self.yspeed if self.y >= display_height - 200: self.kill() explosions.add(Explosion2(explosion2, self.x, self.y)) pygame.mixer.Channel(5).play(bomb_explosion_sound) else: self.rect.x = self.x self.rect.y = self.y # set the rect (not just blit) or collision won't work! gameDisplay.blit(self.image, self.rect) def main_menu(): button_width = start_button.get_rect().size[0] scheme_width = controlscheme.get_rect().size[0] button_x_center = (display_width - button_width) * 0.5 scheme_x_center = (display_width - scheme_width) * 0.5 # End game when this becomes true in_main_menu = True # Play the soundtrack pygame.mixer.Channel(0).play(game_music, loops=-1) # This is the game loop where all game logic happens while in_main_menu: # This checks all events that happen (which are located in pygame.event.get() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = pygame.mouse.get_pos() if startbutton.collidepoint(pos): pygame.mixer.Channel(1).play(button_sound) global time_since_startbutton time_since_startbutton = pygame.time.get_ticks() game_loop() elif creditbutton.collidepoint(pos): credit_loop() elif quitbutton.collidepoint(pos): pygame.mixer.Channel(1).play(button_sound) pygame.quit() quit() # Update main menu gameDisplay.blit(background, (0, 0)) startbutton = gameDisplay.blit(start_button, (button_x_center, display_height * 0.4)) creditbutton = gameDisplay.blit(credit_button, (button_x_center, display_height * 0.5)) quitbutton = gameDisplay.blit(quit_button, (button_x_center, display_height * 0.6)) gameDisplay.blit(controlscheme, (scheme_x_center, display_height * 0.7)) pygame.display.update() def credit_loop(): credits = True while credits: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: credits = False # Update gameDisplay.blit(credit_background, (0, 0)) pygame.display.update() def game_loop(): # Instantiate Ship & Meteor and create a group for lasersprites global ship, ship_group, meteors, lasers, score_count, enemies, fps, timer, enemy_lasers, score_count global boss_bomb, explosions, explosions_boss ship_group = pygame.sprite.GroupSingle() boss_group = pygame.sprite.GroupSingle() boss_bomb = pygame.sprite.Group() enemies = pygame.sprite.Group() meteors = pygame.sprite.Group() lasers = pygame.sprite.Group() enemy_lasers = pygame.sprite.Group() explosions = pygame.sprite.Group() explosions_boss = pygame.sprite.Group() # Set variables and events needed for meteor shower add_meteor_event = pygame.USEREVENT + 1 add_meteor_timer = 300 # add new meteor evert 300 ms ms_event = pygame.USEREVENT + 2 ms_start = 60000 # ms after which meteor shower arrives ms_duration = 20000 pygame.time.set_timer(add_meteor_event, add_meteor_timer) pygame.time.set_timer(ms_event, ms_start) ms_passed = False ms_announcement = False # Set variables needed to spawn enemies add_enemies_event = pygame.USEREVENT + 3 add_enemies_timer = 5000 # add new enemies every 5000 ms pygame.time.set_timer(add_enemies_event, add_enemies_timer) num_enemies = 3 enemies_meteors_spawning = True # Set variables for boss battle boss_battle = False won = False ship_centered = False boss_announcement = False # Instatiate other variables score_count = 0 # score meteors_dodged = 0 enemies_killed = 0 bosses_killed = 0 fps = 60 ship = Ship() ship_group.add(ship) # Add ship once before playing loop starts # This is the game loop where all game logic happens playing = True while playing: timer = pygame.time.get_ticks() - time_since_startbutton # ms that have passed since start if 30000 < timer <= 40000: num_enemies = 4 elif 40000 < timer <= 50000: num_enemies = 5 elif 50000 < timer <= 60000: num_enemies = 6 # Check for global events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if not won: # Check for user-inputted event if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: ship.speed = -10 elif event.key == pygame.K_RIGHT: ship.speed = 10 elif event.key == pygame.K_SPACE: lasers.add(Laser(ship.x + 0.5*ship.width, ship.y)) pygame.mixer.Channel(1).play(laser_sound) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: ship.speed = 0 if ship_centered is True: # Button to return to main menu after defeating boss if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: playing = False # Check for events that only happen within certain time range if event.type == ms_event and ms_passed is False: # This only occurs once ms_announcement_timer = timer ms_announcement = True enemies_meteors_spawning = False if event.type == add_enemies_event and enemies_meteors_spawning: for i in range(num_enemies): enemies.add(EnemyGoon()) try: if timer - ms_announcement_timer < 2000 and ms_announcement is True: # display message 2000 ms continue elif ms_announcement is True: ms_announcement = False # This makes sure announcement doesn't return anymore ms_start_timer = timer # Timestamp start of meteor shower except UnboundLocalError: continue try: if timer - ms_start_timer < ms_duration and ms_passed is False: if event.type == add_meteor_event: # add a meteor every time event is in event queue meteors.add(Meteor()) elif ms_passed is False: ms_passed = True # This makes sure ms doesn't return after it passed event is queued again boss_announcement_timer = timer boss_announcement = True except UnboundLocalError: continue try: if timer - boss_announcement_timer < 2000 and boss_announcement is True: continue elif boss_announcement is True: boss_announcement = False boss_battle = True boss = Boss() boss_group.add(boss) except UnboundLocalError: continue # Update display and sprites gameDisplay.blit(background, (0, 0)) ship.update() if len(meteors) < 1 and enemies_meteors_spawning: meteors.add(Meteor()) for meteor in meteors: meteor.update() if meteor.y > display_height: meteor.kill() meteors_dodged += 1 score_count += 10 for laser in lasers: laser.update() for enemy in enemies: enemy.update() for laser in enemy_lasers: laser.update() if boss_battle is True: boss.update() for bomb in boss_bomb: bomb.update(ship.x + 0.5 * ship.width, ship.y + 0.5 * ship.height) boss_hit = pygame.sprite.groupcollide(lasers, boss_group, 1, 0, pygame.sprite.collide_mask) for sprite in boss_hit: if boss_hit[sprite]: explosions_boss.add(Explosion(explosion1, sprite.x - 32, sprite.y - 64)) # 64 is w/l of explosion pygame.mixer.Channel(3).play(explosion_sound) boss.hp -= 1 for explosion in explosions_boss: explosion.update_moving(boss.x_speed, boss.y_speed) if boss.dead_timer <= 0: explosions.add(Explosion(explosion3, boss.x - boss.width*0.5, boss.y - boss.height*0.5, 3, 5)) del boss boss_battle = False won = True score_count += 1000 bosses_killed += 1 for explosion in explosions: explosion.update() if boss_battle is True: burned = pygame.sprite.groupcollide(ship_group, explosions, 0, 0, pygame.sprite.collide_mask) if burned: explosions.add(Explosion(explosion3, ship.x - ship.width * 0.5, ship.y - ship.height * 0.5, 2, 5)) crashed_text.message('you died. BUT DO NOT PANIC!', display_width * 0.5, display_height * 0.5, centered=True) pygame.display.update() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: waiting = False playing = False for explosion in explosions: explosion.update() performance_text.message('Return to main menu by pressing Enter and try again.', display_width * 0.5, 500, centered=True) pygame.display.update() if boss_battle is False and won is True: if ship_centered is False: ship_centered = ship.to_end_position(display_width*0.5 - ship.width * 0.5) # Check for collisions after new display if updated crashed = pygame.sprite.groupcollide(ship_group, meteors, 0, 0, pygame.sprite.collide_mask) hit = pygame.sprite.groupcollide(enemy_lasers, ship_group, 1, 0, pygame.sprite.collide_mask) if crashed or hit: explosions.add(Explosion(explosion3, ship.x - ship.width * 0.5, ship.y - ship.height * 0.5, 2, 5)) crashed_text.message('you died. BUT DO NOT PANIC!', display_width * 0.5, display_height * 0.5, centered=True) pygame.display.update() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: waiting = False playing = False for explosion in explosions: explosion.update() performance_text.message('Return to main menu by pressing Enter and try again.', display_width * 0.5, 500, centered=True) pygame.display.update() # Kill sprites after collision pygame.sprite.groupcollide(lasers, meteors, 1, 0, pygame.sprite.collide_mask) pygame.sprite.groupcollide(enemy_lasers, meteors, 1, 0, pygame.sprite.collide_mask) enemy_hit = pygame.sprite.groupcollide(enemies, lasers, 1, 1, pygame.sprite.collide_mask) for sprite in enemy_hit: if enemy_hit[sprite]: explosions.add(Explosion(explosion1, sprite.x, sprite.y)) pygame.mixer.Channel(3).play(explosion_sound) score_count += 100 enemies_killed += 1 # Lastly, show text performance_text.message('score: ' + str(score_count), 5, 0) performance_text.message('%i' % (timer/1000), display_width - 45, 0) if ms_announcement: shower_text.message('METEOR SHOWER INCOMING', display_width * 0.5, display_height * 0.5, centered=True) if boss_announcement: shower_text.message('FINAL BOSS INCOMING', display_width * 0.5, display_height * 0.5, centered=True) if ship_centered is True: performance_text.message('meteors dodged: %i' % meteors_dodged, display_width * 0.5, 360, centered=True) performance_text.message('enemies destroyed: %i:' % enemies_killed, display_width * 0.5, 380, centered=True) performance_text.message('bosses destroyed: %i' % bosses_killed, display_width * 0.5, 400, centered=True) endgame_score_text.message('Final score: %i' % score_count, display_width * 0.5, 430, centered=True) performance_text.message('press enter to return to main menu', display_width * 0.5, 500, centered=True) pygame.display.update() # Set FPS clock.tick(fps) # Here we initialize pygame, set variables and start the actual game pygame.init() # pygame.mouse.set_cursor(*pygame.cursors.diamond) pygame.mouse.set_cursor(*pygame.cursors.broken_x) # Define some colors black = (0, 0, 0) # (R,G,B) red = (255, 0, 0) green = (0, 255, 0) # Setup a window for the game display_width = 800 display_height = 800 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('MyFirstGame') # Window Title # -- Load sprites from spritesheets spritesheet_explosion1 = pygame.image.load('Textures/explosions.png') explosion1 = [] x_all = [628, 628, 628, 628, 576, 566, 562, 562, 562, 562, 924, 858, 792, 726, 660, 594, 924, 858, 792, 726, 660, 594, 924, 764] y_all = [772, 706, 640, 574, 938, 872, 772, 706, 640, 574, 502, 496, 496, 496, 496, 496, 436, 430, 430, 430, 430, 430, 370, 826] height = 64 width = 64 for i in range(24): frame = str(i) if len(frame) is 1: frame = '0' + frame x = x_all[i] y = y_all[i] explosion1.append(spritesheet_explosion1.subsurface(pygame.Rect(x, y, width, height))) explosion3 = [] x_all = [100, 100, 100, 100, 888, 790, 692, 594, 496, 398, 300, 202, 104, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 100] y_all = [398, 300, 202, 104, 2, 2, 2, 2, 2, 2, 2, 2, 2, 884, 786, 688, 590, 492, 394, 296, 198, 100, 2, 496] h = 96 w = 96 for i in range(24): frame = str(i) if len(frame) is 1: frame = '0' + frame x = x_all[i] y = y_all[i] explosion3.append(spritesheet_explosion1.subsurface(pygame.Rect(x, y, h, w))) spritesheet_explosion2 = pygame.image.load('Textures/particlefx_06.png') height_exp = 128 width_exp = 128 explosion2 = [] for i in range(8): for j in range(8): explosion2.append(spritesheet_explosion2.subsurface(pygame.Rect( i*height_exp, j*width_exp, height_exp, width_exp))) spritesheetspace = pygame.image.load('Textures/spritesheet_space.png') start_button = spritesheetspace.subsurface(pygame.Rect(0, 117, 222, 39)) credit_button = spritesheetspace.subsurface(pygame.Rect(0, 78, 222, 39)) quit_button = spritesheetspace.subsurface(pygame.Rect(0, 0, 222, 39)) enemy1 = spritesheetspace.subsurface(pygame.Rect(423, 728, 93, 84)) enemy2 = spritesheetspace.subsurface(pygame.Rect(120, 604, 104, 84)) enemy3 = spritesheetspace.subsurface(pygame.Rect(144, 156, 103, 84)) laser_blue = spritesheetspace.subsurface(pygame.Rect(856, 421, 9, 54)) laser_red = spritesheetspace.subsurface(pygame.Rect(858, 230, 9, 54)) meteor1 = spritesheetspace.subsurface(pygame.Rect(224, 664, 101, 84)) meteor2 = spritesheetspace.subsurface(pygame.Rect(0, 520, 120, 98)) meteor3 = spritesheetspace.subsurface(pygame.Rect(518, 810, 89, 82)) meteor4 = spritesheetspace.subsurface(pygame.Rect(327, 452, 98, 96)) player_ship = spritesheetspace.subsurface(pygame.Rect(224, 832, 99, 75)) spritesheetspace2 = pygame.image.load('Textures/spritesheet_space2.png') missile = spritesheetspace2.subsurface(pygame.Rect(1093, 711, 19, 40)) boss_image = spritesheetspace2.subsurface(pygame.Rect(276, 0, 172, 151)) controlscheme = pygame.image.load('Textures/controlscheme.png') background = pygame.image.load('Textures/space_background.png').convert() credit_background = pygame.image.load('Textures/credits.png').convert() # Load files used in the game game_music = pygame.mixer.Sound('Sounds/desert-travel.ogg') # Channel 0 game_music.set_volume(0.5) button_sound = pygame.mixer.Sound('Sounds/click_menu_sound.wav') # Channel 1 laser_sound = pygame.mixer.Sound('Sounds/laser5.wav') # Channel 1 enemy_laser_sound = pygame.mixer.Sound('Sounds/laser8.wav') # Channel 2 enemy_laser_sound.set_volume(0.5) explosion_sound = pygame.mixer.Sound('Sounds/explodemini.wav') # Channel 3 bomb_release_sound = pygame.mixer.Sound('Sounds/weaponfire4.wav') # Channel 4 bomb_explosion_sound = pygame.mixer.Sound('Sounds/explosion2.wav') # Channel 5 # Load fonts to use in the game performance_text = ChooseFont('Fonts/xirod.ttf', 15, green) endgame_score_text = ChooseFont('Fonts/xirod.ttf', 30, green) crashed_text = ChooseFont('Fonts/xirod.ttf', 30, red) shower_text = ChooseFont('Fonts/xirod.ttf', 30, red) # Define game clock to time things clock = pygame.time.Clock() main_menu()
Hiimbawb/Spacey
Spacey.py
Spacey.py
py
32,449
python
en
code
0
github-code
6
22284911130
# --------------------------------------------------- # # 필수 import 파일임: # scripts 폴더의 스크립트들이 서로 import하기 위해서는 # scripts 폴더를 pythonpath에 등록해야한다. # # --------------------------------------------------- import os dirpath = os.path.dirname(os.path.realpath(__file__)) dirpath = dirpath + "\\scripts" print('Using modified Pythonpath from PYTHONPATH.py') os.sys.path.append(dirpath)
crack-love/KSL
Project_DNN/PYTHONPATH.py
PYTHONPATH.py
py
447
python
ko
code
0
github-code
6
24013809061
from QLearning import Game from collections import Counter import pandas as pd import matplotlib.pyplot as plt gamma = 0.1 def Menu(): usr_op = None while usr_op != 0: print('//-//-//-// Card-Jitsu Menu //-//-//-//') print('\nSelect an option to continue: ') print('1. Play game vs AI.') print('2. Get Strategy Metrics.') print('3. Get Random Metrics.') print('4. Train Ai Manual.') print('5. Train Ai Random.') print('0. Exit.') usr_op = int(input('\n Option selected: ')) if usr_op == 1: Game(gamma) elif usr_op == 2: get_metrics(is_random = False, train = False, show_game = True) elif usr_op == 3: get_metrics(is_random = True, train = False, show_game = False) elif usr_op == 4: get_metrics(is_random = False, train = True, show_game = True) elif usr_op == 5: get_metrics(is_random = True, train = True, show_game = False, show_metrics = False) print('\n\n') def get_metrics(is_random, train, show_game, show_metrics = True): history = { 'Game': [], 'Round': [], 'AI': [], 'Player': [], 'Winner': [], 'Game Winner': [] } game = 0 g = int(input('Numero de juegos a realizar: ')) while game < g: winrecord , winner = Game(gamma, is_random, train, show_game) for round in range(len(winrecord)): history['Game'].append(game) history['Game Winner'].append(winner) history['Round'].append(round) history['AI'].append(winrecord[round]['AI']) history['Player'].append(winrecord[round]['Player']) history['Winner'].append(winrecord[round]['Winner']) game += 1 if not show_metrics: return 0 history = pd.DataFrame.from_dict(history) # Histograma de Rondas y juegos game_winrate = Counter(list(history['Game Winner'])) game_winrate = pd.DataFrame.from_dict(game_winrate, orient='index', columns=['Games Won']) game_winrate.plot(kind='pie', y='Games Won', autopct='%1.0f%%', explode=(0.01, 0.01), startangle=20) plt.title('Frecuency of Games Won') plt.ylabel('') plt.show() # Diagrama de Pie de rondas ganadas round_winrate = Counter(list(history['Winner'])) round_winrate = pd.DataFrame.from_dict(round_winrate, orient='index', columns=['Rounds Won']) round_winrate.plot(kind='pie', y='Rounds Won', autopct='%1.0f%%', explode=(0.01, 0.01, 0.01), startangle=60) plt.title('Frecuency of Rounds Won and Tied') plt.ylabel('') plt.show() # Histograma de cartas ai_cardrate = Counter(list(history['AI'])) ai_cardrate = pd.DataFrame.from_dict(ai_cardrate, orient='index', columns=['AI Cards']) player_cardrate = Counter(list(history['Player'])) player_cardrate = pd.DataFrame.from_dict(player_cardrate, orient='index', columns=['Player Cards']) hist_cardrate = ai_cardrate.merge(player_cardrate, how='outer', left_index=True, right_index=True).fillna(0) hist_cardrate.plot(kind = 'bar') plt.title('Frecuency of Cards Used') plt.show() Menu()
Marinovsky/Card-Jitsu
metrics_modifications/game.py
game.py
py
3,225
python
en
code
0
github-code
6
73817284346
"""Basic status commands to check the health of the bot.""" import datetime import discord from discord.ext import commands from metricity.config import BotConfig DESCRIPTIONS = ( "Command processing time", "Last event received", "Discord API latency", ) ROUND_LATENCY = 3 INTRO_MESSAGE = "Hello, I'm {name}. I insert all your data into a GDPR-compliant database." class Status(commands.Cog): """Get the latency between the bot and Discord.""" def __init__(self, bot: commands.Bot) -> None: self.bot = bot @commands.Cog.listener() async def on_socket_event_type(self, _: str) -> None: """Store the last event received as an int.""" self.last_event_received = int(datetime.datetime.now(datetime.UTC).timestamp()) @commands.command() @commands.has_any_role(BotConfig.staff_role_id) @commands.guild_only() async def status(self, ctx: commands.Context) -> None: """Respond with an embed with useful status info for debugging.""" if ctx.guild.id != BotConfig.guild_id: return bot_ping = (datetime.datetime.now(datetime.UTC) - ctx.message.created_at).total_seconds() * 1000 if bot_ping <= 0: bot_ping = "Your clock is out of sync, could not calculate ping." else: bot_ping = f"{bot_ping:.{ROUND_LATENCY}f} ms" discord_ping = f"{self.bot.latency * 1000:.{ROUND_LATENCY}f} ms" last_event = f"<t:{self.last_event_received}>" embed = discord.Embed( title="Status", description=INTRO_MESSAGE.format(name=ctx.guild.me.display_name), ) for desc, latency in zip(DESCRIPTIONS, (bot_ping, last_event, discord_ping), strict=True): embed.add_field(name=desc, value=latency, inline=False) await ctx.send(embed=embed) async def setup(bot: commands.Bot) -> None: """Load the status extension.""" await bot.add_cog(Status(bot))
python-discord/metricity
metricity/exts/status.py
status.py
py
1,958
python
en
code
39
github-code
6
36347921741
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_pyredatam Tests for `pyredatam` module. """ from __future__ import unicode_literals import unittest import nose import pyredatam import queries class RedatamTestCase(unittest.TestCase): def test_arealist_query(self): # Test case AREALIST1 area_level = "FRAC" variables = "PERSONA.CONDACT" area_filter = {"PROV": ["02", "03"]} universe_filter = "1 = 1" title = "El titulo" query = pyredatam.arealist_query(area_level, variables, area_filter, universe_filter, title) self.assertEqual(query, queries.AREALIST1.strip()) # Test case AREALIST2 variables = ["PERSONA.CONDACT"] query = pyredatam.arealist_query(area_level, variables) self.assertEqual(query, queries.AREALIST2.strip()) # Test case AREALIST3 area_filter = {"PROV": "02"} query = pyredatam.arealist_query(area_level, variables, area_filter) self.assertEqual(query, queries.AREALIST3.strip()) def test_counter_query(self): # Test case COUNTER1 area_level = "RADIO" entity_count = "PERSONA" area_filter = {"PROV": "02"} universe_filter = "1 = 1" title = "El titulo" query = pyredatam.counter_query(area_level, entity_count, area_filter, universe_filter, title) self.assertEqual(query, queries.COUNTER1.strip()) # Test case COUNTER2 area_level = "DPTO" entity_count = "FRAC" incl_area_name = True incl_total = True query = pyredatam.counter_query(area_level, entity_count, area_filter, universe_filter, title, incl_area_name, incl_total) self.assertEqual(query, queries.COUNTER2.strip()) def test_median_query(self): # Test case MEDIAN1 variable = "PERSONA.P03" by_var1 = "PERSONA.CONDACT" by_var2 = "PERSONA.P02" incl_name = True area_break = "PROV" area_filter = None universe_filter = "1 = 1" title = "El titulo" query = pyredatam.median_query(variable, by_var1, by_var2, incl_name, area_break, area_filter, universe_filter, title) self.assertEqual(query, queries.MEDIAN1.strip()) # Test case MEDIAN2 variable = "PERSONA.P03" incl_name = None area_break = None universe_filter = None title = None query = pyredatam.median_query(variable, by_var1, by_var2, incl_name, area_break, area_filter, universe_filter, title) self.assertEqual(query, queries.MEDIAN2.strip()) # Test case MEDIAN3 variable = "PERSONA.P03" by_var1 = None by_var2 = None query = pyredatam.median_query(variable, by_var1, by_var2, incl_name, area_break, area_filter, universe_filter, title) self.assertEqual(query, queries.MEDIAN3.strip()) if __name__ == '__main__': nose.run(defaultTest=__name__)
abenassi/pyredatam
tests/test_pyredatam.py
test_pyredatam.py
py
3,362
python
en
code
4
github-code
6
11579227616
import cv2 import numpy as np from imageclassifier import ImageClassifier n_clusters = [3, 4, 5, 6, 7, 8] kmeans_keys = [ [0], [1], [2], [0, 1], [0, 2], [1, 2], [0, 1, 2] ] sorting_lambdas = [ lambda pixel: pixel[0], lambda pixel: pixel[1], lambda pixel: pixel[2], lambda pixel: sum(pixel), lambda pixel: max(pixel) ] cl_sorting_lambdas = [ lambda cluster: cluster[0][0][0], lambda cluster: cluster[0][0][1], lambda cluster: cluster[0][0][2], lambda cluster: sum(cluster[0][0]), lambda cluster: max(cluster[0][0]) ] coeffs = [] for i in range(5): for j in range(5): for k in range(5): coeffs.append([i, j, k]) sorting_keys = [i for i in range(len(sorting_lambdas))] colorspaces = [None, cv2.COLOR_BGR2HSV, cv2.COLOR_BGR2LAB, cv2.COLOR_BGR2HLS] def str_colorspace(colorspace): if colorspace == None: return "BGR" if colorspace == cv2.COLOR_BGR2HSV: return "HSV" if colorspace == cv2.COLOR_BGR2LAB: return "LAB" if colorspace == cv2.COLOR_BGR2HLS: return "HLS" def save(folder, img, n_cluster, key, color_in, sorting_key, color_sort): filename = folder + "/c{0}_k".format(n_cluster) filename = filename + '-'.join([str(s) for s in key]) filename = filename + '_' + str_colorspace(color_in) + "_" filename = filename + 's{0}_'.format(sorting_key) filename = filename + str_colorspace(color_sort) + ".png" cv2.imwrite(filename, img) print("saved: " + filename) def bruteforce(target, folder): for n_cluster in n_clusters: classifier = ImageClassifier(n_cluster, target) for color_in in colorspaces: df = classifier.get_dataframe(colorspace=color_in) for key in kmeans_keys: cluster_map = classifier.run_kmeans(df, key) clusters = classifier.get_clusters(cluster_map) clusters_bak = clusters.copy() for color_sort in colorspaces: for sorting_key in sorting_keys: cmp1 = sorting_lambdas[sorting_key] cmp2 = cl_sorting_lambdas[sorting_key] clusters = classifier.sort_clusters(clusters, cmp1, color_sort=color_sort) res = classifier.merge_clusters(clusters, cmp2) save(folder, res, n_cluster, key, color_in, sorting_key, color_sort) clusters = clusters_bak.copy() def process(): n_cluster = 4 classifier = ImageClassifier(n_cluster, 'src.jpg') df = classifier.get_dataframe(colorspace=cv2.COLOR_BGR2HSV) cluster_map = classifier.run_kmeans(df, [0]) clusters = classifier.get_clusters(cluster_map) clusters_bak = clusters.copy() #cmp = lambda pixel: (255 - int(pixel[1])) * 2 - (200 if pixel[1] < pixel[2] else 0) cmp = lambda pixel: int(pixel[0]) #cmp = lambda pixel: pixel[1] clusters = classifier.sort_clusters(clusters, cmp, color_sort=cv2.COLOR_BGR2LAB) res = classifier.merge_clusters(clusters, lambda cluster: sum(cluster[0][0])) #filename = 'res_sort/res_{0}_{1}_{2}.png'.format(coeff[0], coeff[1], coeff[2]) filename="res.png" cv2.imwrite(filename, res) print('saved {0}'.format(filename)) clusters = clusters_bak.copy() def compare(target1, target2): cl1 = ImageClassifier(4, target1) cl2 = ImageClassifier(4, target2) df1 = cl1.get_dataframe() df2 = cl2.get_dataframe() print(df1.describe()) print(df2.describe()) exit() img1 = cv2.imread(target1) img2 = cv2.imread(target2) shape1 = img1.shape shape2 = img2.shape img1 = np.reshape(img1, (shape1[0] * shape1[1], 3)) img2 = np.reshape(img2, (shape2[0] * shape2[1], 3)) img1 = sorted(img1, key = lambda pixel: sum(pixel)) img2 = sorted(img2, key = lambda pixel: sum(pixel)) img1 = np.reshape(img1, (shape1)) img2 = np.reshape(img2, (shape2)) cv2.imwrite('img1.png', img1) cv2.imwrite('img2.png', img2) # bruteforce("town.jpg", "result/town") # compare("res.png", "town.jpg") process()
elraffray/pyImage
classifier.py
classifier.py
py
4,167
python
en
code
0
github-code
6
10527381076
''' 7. Reverse Integer https://leetcode.com/problems/reverse-integer/description/ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1 ''' class Solution: def reverse(self, x: int) -> int: s = str(x) if x >= 0 : return int(s[::-1]) if int(s[::-1]) <= (2**31 - 1) else 0 else: s = str(abs(x)) return int('-'+s[::-1]) if int(s[::-1]) <= (2**31) else 0
bhaveshratan/LeetCode-Programming-Solutions-in-Python
Reverse Integer.py
Reverse Integer.py
py
799
python
en
code
0
github-code
6
75316082746
import os import wx from wx.lib.colourchooser.canvas import Canvas class ImageCanvas(wx.Panel): """ Image Panel """ def __init__(self, parent, image_path=None, *args, **kwargs): """ Constructor :param parent: """ wx.Panel.__init__(self, parent=parent, *args, **kwargs) self.image_path = image_path if self.image_path: bmp = wx.Bitmap(self.image_path) padding = 10 self.SetMinClientSize((bmp.GetWidth() + padding, bmp.GetHeight() + padding)) self.glyphs = [] # self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.frame = parent # img = wx.EmptyImage(240, 240) self.main_sizer = wx.BoxSizer(wx.HORIZONTAL) self.main_sizer.Add((1, 1), 0, wx.EXPAND, 75) # self.main_sizer.Add(img, 0, wx.EXPAND) self.main_sizer.Add((1,1), 0, wx.ALL, 75) self.SetSizer(self.main_sizer) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background) self.Bind(wx.EVT_SIZE, self.on_size) def set_sizer(self): """ :param sizer: :return: """ sizer = wx.BoxSizer(wx.VERTICAL) hSizer = wx.BoxSizer(wx.HORIZONTAL) for num in range(4): label = "Button %s" % num btn = wx.Button(self, label=label) sizer.Add(btn, 0, wx.ALL, 5) hSizer.Add((1,1), 1, wx.EXPAND) hSizer.Add(sizer, 0, wx.TOP, 100) hSizer.Add((1,1), 0, wx.ALL, 75) self.SetSizer(hSizer) def on_size(self, event): """ :param event: """ event.Skip() self.Refresh() def scale_image(self, image, max_width=None, max_height=None): """ :param image: :param max_width: :param max_height: :return: """ width = image.GetWidth() height = image.GetHeight() ratio = min(max_width / width, max_height / height) image = image.Scale(ratio * width, ratio * height, wx.IMAGE_QUALITY_HIGH) result = wx.BitmapFromImage(image) return result def on_erase_background(self, event): """ Add a picture to the background :param event: """ # self.Freeze() dc = event.GetDC() w, h = self.GetClientSize() if not dc: dc = wx.ClientDC(self) rect = self.GetUpdateRegion().GetBox() dc.SetClippingRect(rect) dc.Clear() if self.image_path: bmp = wx.Bitmap(self.image_path) # bmp = self.scale_image(bmp, 100, 200) size = bmp.GetSize() x = int(w/2.0 - size.x/2.0) y = int(h/2.0 - size.y/2.0) dc.DrawBitmap(bmp, x, y) self.draw_model(dc) # self.Thaw() def draw_model(self, dc): """ Draw glyps :param dc: :return: """ for glyph in self.glyphs: glyph.draw(dc) class Glyph(object): def __init__(self, *args, **kwargs): self.pen_color = kwargs.get('pen_color', wx.BLACK) self.pen_width = kwargs.get('pen_width', 5) self.coordinates = kwargs.get('coordinates', []) def set_pen(self, dc): dc.SetPen(self.pen_color, self.pen_width) def pre_draw(self, dc): self.set_pen() def post_draw(self, dc): pass def _draw_(self, dc): pass def draw(self, dc): self.pre_draw(dc) self._draw_(dc) self.post_draw(dc) class Arc(Glyph): """ """ def _draw_(self, dc): pass class Line(Glyph): """ """ def _draw_(self, dc): xy1 = self.coordinates[0] xy2 = self.coordinates[1] dc.DrawLine(xy1[0], xy1[1], xy2[0], xy2[1]) class Circle(Glyph): """ """ def _draw_(self, dc): xy = self.coordinates[0] dc.DrawCircle(xy[0], xy[1], 100) class Rectangle(Glyph): """ """ def _draw_(self, dc): pass
JoenyBui/boa-gui
boaui/panel/image.py
image.py
py
4,085
python
en
code
0
github-code
6
1002491820
import unittest from zag import * from zag.configable import ConfigException class ConfigTest(unittest.TestCase): def test_stage(self): foo = PyTask("zag.foo") workflow = Sequence("foo-flow", stages=[ Stage("run-foo", foo, args=[ ("--foo-type", "$type") ]) ]) self.assertEqual(workflow.get_config(), {}) my_config = {"type": "ponies"} nw = workflow.apply_config(my_config) self.assertEqual(nw.stages[0].args, [("--foo-type", "ponies")]) def test_missing_value(self): foo = PyTask("zag.foo") workflow = Sequence("foo-flow", stages=[ Stage("run-foo", foo, args=[ ("--foo-type", "$type"), ("--missing-val", "$mv") ]) ]) self.assertEqual(workflow.get_config(), {}) my_config = {"type": "ponies"} with self.assertRaises(ConfigException): nw = workflow.apply_config(my_config) def test_nested_workflows(self): foo = PyTask("zag.foo") simple_stage = Stage("run-foo", foo, args=[ ("--foo-type", "$type") ]) bar = Sequence('bar-flow', config={ "type": "bar" }, stages=[simple_stage]) baz = Sequence('baz-flow', config={ "type": "baz" }, stages=[simple_stage]) qux = Sequence('qux-flow', config={ "type": "qux" }, stages=[baz]) workflow = Sequence("all-workflows", stages=[ bar, qux, baz ]) config = {} nw = workflow.apply_config(config) self.assertEqual(nw.stages[0].stages[0].args, [("--foo-type", "bar")]) self.assertEqual(nw.stages[1].stages[0].stages[0].args, [("--foo-type", "qux")]) self.assertEqual(nw.stages[2].stages[0].args, [("--foo-type", "baz")]) def test_tags(self): simple_stage = Stage("run-foo", PyTask("zag.foo"), args=[ ("--foo-type", "$type") ], tags=['$tag']) baz = Sequence('baz-flow', config={ "type": "baz" }, stages=[simple_stage], tags=["fomo"]) with self.assertRaises(ConfigException): baz.apply_config({}) nw = baz.apply_config({"tag": "TAG"}) self.assertEqual(nw.stages[0].tags, {"TAG"}) def test_inherit_tags(self): simple_stage = Stage("run-foo", PyTask("zag.foo"), args=[ ("--foo-type", "$type") ], tags=['foo']) baz = Sequence('baz-flow', config={ "type": "baz" }, stages=[simple_stage], tags=['all-baz']) stages = baz.apply_config({"tag": "TAG"}).resolve_stages() stages = list(stages) self.assertEqual(stages[0].tags, {"foo", "baz-flow", "all-baz"}) class ZagTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_identity(self): pass if __name__ == '__main__': unittest.main()
Refefer/zag
tests/test_zag.py
test_zag.py
py
3,411
python
en
code
1
github-code
6
9357540363
#!/usr/bin/env python __author__ = '[email protected]' import commands from d3r.celppade.custom_protein_prep import ProteinPrep class chimera_dockprep(ProteinPrep): """Abstract class defining methods for a custom docking solution for CELPP """ ProteinPrep.OUTPUT_PROTEIN_SUFFIX = '.mol2' def receptor_scientific_prep(self, protein_file, prepared_protein_file, targ_info_dict={}): """ Protein 'scientific preparation' is the process of generating a dockable representation of the candidate protein from a single-chain PDB file. :param protein_file: PDB file containing candidate protein. :param prepared_protein_file: The result of preparation should have this file name. :param targ_info_dict: A dictionary of information about this target and the candidates chosen for docking. :returns: True if preparation was successful. False otherwise. """ ##################################################################### ### $ python clean_receptor.py receptor.pdb clean_receptor.pdb ### ##################################################################### # Implements the logic that was formerly in clean_receptor.py orig_pdb = open(protein_file).readlines() with open('clean_receptor.pdb','wb') as of: for line in orig_pdb: if len(line) > 4: if line[:4] == 'ATOM': of.write(line) ##################################################################### ### $ chimera --nogui --script "chimeraPrep.py clean_receptor.pdb prepared_receptor.mol2" ##################################################################### # Write the chimera-interpreted code to a script file chimera_prep_text = '''import chimera import sys opened = chimera.openModels.open(sys.argv[1]) mol = opened[0] import DockPrep DockPrep.prep([mol]) from WriteMol2 import writeMol2 with open(sys.argv[2],'wb') as of: writeMol2([mol], of) ''' with open('chimera_prep.py','wb') as of: of.write(chimera_prep_text) # Run chimera with the script as an input prep_cmd = 'chimera --nogui --script "chimera_prep.py clean_receptor.pdb ' + prepared_protein_file + ' " 1> prep.stdout 2> prep.stderr' commands.getoutput(prep_cmd) return True if ("__main__") == (__name__): import logging import os import shutil from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-p", "--pdbdb", metavar = "PATH", help = "PDB DATABANK which we will dock into") parser.add_argument("-c", "--challengedata", metavar="PATH", help = "PATH to the unpacked challenge data package") parser.add_argument("-o", "--prepdir", metavar = "PATH", help = "PATH to the output directory") logger = logging.getLogger() logging.basicConfig( format = '%(asctime)s: %(message)s', datefmt = '%m/%d/%y %I:%M:%S', filename = 'final.log', filemode = 'w', level = logging.INFO ) opt = parser.parse_args() pdb_location = opt.pdbdb challenge_data_path = opt.challengedata prep_result_path = opt.prepdir #running under this dir abs_running_dir = os.getcwd() log_file_path = os.path.join(abs_running_dir, 'final.log') log_file_dest = os.path.join(os.path.abspath(prep_result_path), 'final.log') prot_prepper = chimera_dockprep() prot_prepper.run_scientific_protein_prep(challenge_data_path, pdb_location, prep_result_path) #move the final log file to the result dir shutil.move(log_file_path, log_file_dest)
drugdata/tutorial_rdock_implementation
tutorial_rdock_implementation/tutorial_rdock_implementation_protein_prep.py
tutorial_rdock_implementation_protein_prep.py
py
3,827
python
en
code
0
github-code
6
29191289762
import datetime import json import os import re import shutil class Fileop(): def isDirectory(self, fDir): return os.path.isdir(fDir) def countDir(self, dPath): dirListing = next(os.walk(dPath))[2] return len(dirListing) def CjsonLoad(self, jfile): fdir = os.path.join(Fileop.dwnDir(''), "conf") condir = Fileop.isDirectory('', fdir) if condir: confile = os.path.join(fdir, jfile) with open(confile, "r") as j: return json.load(j) def SjsonLoad(self, jfile): fdir = Fileop.dwnDir('') condir = Fileop.isDirectory('', fdir) if condir: confile = os.path.join(fdir, jfile) with open(confile, "r") as j: return json.load(j) def curWorkDir(self): return os.path.dirname(os.path.realpath(__file__)) def makDir(self, Folder): try: os.makedirs(Folder) except OSError as e: print("Warning making {0} : MSG - {1}".format(Folder, e)) def dwnDir(self): return os.path.normpath(os.getcwd() + os.sep + os.pardir) def newDirec(self, nDirName): return os.mkdir(nDirName) def RecFileDir(self, dirName): new_Folder = os.path.join(Fileop.dwnDir(''), dirName) dFlag = Fileop.isDirectory('', new_Folder) if not dFlag: # make directory try: Fileop.newDirec('', new_Folder) except OSError: print("Creation of the directory %s failed. \n" % new_Folder) else: print("Successfully created the directory %s.\n " % new_Folder) else: print("Directory ( %s ) already exists.\n" % new_Folder) return new_Folder def newest(self, path): files = os.listdir(path) lenfile = len(files) if lenfile != 0: paths = [os.path.join(path, basename) for basename in files] return max(paths, key=os.path.getctime) else: print("Directory ( %s ) is empty\n", path) def removefiles(self, folder): files_in_directory = os.listdir(folder) filtered_files = [file for file in files_in_directory if file.endswith(".wav")] dircount = Fileop.countDir('', folder) if dircount > 1: for file in filtered_files: path_to_file = os.path.join(folder, file) os.remove(path_to_file) else: print('Failed to delete files, {0} is empty: \n'.format(folder)) def moveFiles(self, froDir, toDir, froFile, toFile): try: shutil.move(os.path.join(froDir, froFile), os.path.join(toDir, toFile)) print("Successfully moved {0}.\n".format(os.path.join(froDir, froFile))) except OSError: print("Could not move file ({0}) operation.\n".format(os.path.join(froDir, froFile))) def main(self): # Check if directories have been created source_param = Fileop.CjsonLoad('', "conf.json") source_rep = os.path.join(Fileop.dwnDir(''), "reports") Fileop.RecFileDir('', source_rep) dwn_dir = source_param['download_dir'] # Recordings directory based on current date recFolder = "Recordings" + datetime.datetime.now().strftime("%Y%m%d") dirRecs = Fileop.RecFileDir('', recFolder) # print(dirRecs) # get latest data report file newFile = Fileop.newest('', source_rep) # print (newFile) count = 0 if Fileop.countDir('', dwn_dir) != 0: with open(newFile, "r") as nf: lines = nf.readlines() for line in lines: count += 1 line_id = ' '.join(re.findall(r'\b\w+\b', line)[:+1]) line_data = ' '.join(re.findall(r'\b\w+\b', line)[:]).replace(line_id, "") line_data = "_".join(line_data.split()) print("line {0} - file ID : {1} file metadata :- {2} \n".format(count, line_id, line_data)) # move and rename files Fileop.moveFiles("", dwn_dir, dirRecs, line_id + ".wav", line_data + ".wav") else: print("Warning: Call recordings download did not run!\n") # if __name__ == "__main__": # main()
kkweli/Avaya
Avy/avayaFile.py
avayaFile.py
py
4,353
python
en
code
0
github-code
6
72143866108
from typing import Any, Dict def play_game() -> None: print('playing game') def update_state(current_state: Dict) -> Dict: print('here we change things') possible_actions = { 'mod status': lambda : print('modifting status'), 'remove status': lambda : print('removing status'), 'go back': lambda : print('saving updates') } show_commands('update status menu', possible_actions) return current_state def quit(): print('good bye m8') def show_commands(title: str, commands: Dict) -> Any: print(title.upper()) idxs = {} for idx, op in enumerate(commands): print(f'{op} -> press [{idx}]') idxs[str(idx)] = commands[op] while True: user_op = input('select an option > ') if user_op in idxs: return idxs[user_op]() def main(): state = { 'user_name': 'santi' } commands = { 'play': play_game, 'quit': quit, 'update_satus': lambda : update_state(state) } show_commands('main menu', commands=commands) main()
levensworth/udesa-pc-tutorial
2022-a/4-testing_and_train/solutions/example_command.py
example_command.py
py
1,096
python
en
code
2
github-code
6
11353167972
# Licensed under a 3-clause BSD style license - see LICENSE from __future__ import print_function, division from astropy.table import Table, Column from .import_modules import * ##----- ----- ----- ----- ----- ----- ----- ----- ----- -----## ## Miscellaneous utilities ## Contain functions that do not pertain to a particular class. ##----- ----- ----- ----- ----- ----- ----- ----- ----- -----## def Fit_linear(y, x=None, err=1.0, m=None, b=None, output=None, inline=False): """ Fit_linear(y, x=None, err=1.0, m=None, b=None, output=None, inline=False): return (sol, res, rank, s) Uses the scipy.linalg.lstsq function to solve the equation y = mx + b sol -> [b, m] N.B. Uses the scipy.linalg.lstsq algorithm. If inline = True, flattens the results. """ #x = array([52997., 53210., 53310., 53380.]) #y = array([1.66, 1.54, 1.4, 1.4]) # standard error of the y-variable: #sy = array([0.05, 0.05, 0.05, 0.05]) if x is None: x = np.arange(y.shape[0], dtype=float) if (b is not None) and (m is not None): sol = [b, m] res = (((b + m*x - y)/err)**2).sum() rank = 0. s = 0. else: if b is not None: A = np.reshape(x/err,(x.shape[0],1)) y1 = y-b y1 /= err sol, res, rank, s = scipy.linalg.lstsq(A, y1) sol = [b,sol[0]] elif m is not None: A = np.resize(1/err,(x.shape[0],1)) y1 = y-m*x y1 /= err sol, res, rank, s = scipy.linalg.lstsq(A, y1) sol = [sol[0],m] else: A = (np.vstack([np.ones(x.shape[0], dtype=float),x])/err).T y1 = y/err sol, res, rank, s = scipy.linalg.lstsq(A, y1) if output: b, m = sol fit_y = b + m*x print('b -> ' + str(b)) print('m -> ' + str(m)) print('Reduced chi-square: ' + str(res/(len(y)-rank))) plotxy(y, x, line=None, symbol=2, color=2) plotxy(fit_y, x) if res.shape == (0,): res = np.r_[0.] if inline: return np.hstack((sol, res, rank, s)) else: return (sol, res, rank, s) def Pprint(arr, show_index=False, max_lines=None): arr = np.atleast_2d(arr) if show_index: cols = np.arange(arr.shape[1]).astype(str) #rows = np.arange(arr.shape[0]).astype(str) rows = np.array([r+' |' for r in np.arange(arr.shape[0]).astype(str)]) t = Table(data=arr, names=cols, copy=True) t.add_column(Column(data=rows, name=' '), index=0) else: t = Table(data=arr, copy=True) t.pprint(show_name=show_index, max_lines=max_lines) def Sort_list(lst, cols): """Sort_list(lst, cols) Sorts inplace a list by multiple columns. lst: List to be sorted. cols: Columns to be sorted, cols[0] first, cols[1] second, etc. >>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)] >>> Sort_list(lst, [2,1]) """ from operator import itemgetter for keycolumn in reversed(cols): lst.sort(key=itemgetter(keycolumn)) return
bretonr/Icarus
Icarus/Utils/Misc.py
Misc.py
py
3,104
python
en
code
11
github-code
6
3508041211
#!/usr/bin/env python3 import numpy as np import re position_re = re.compile('(\d+),(\d+).*?(\d+),(\d+)') def execute(cmd: str, a: np.array, a2: np.array): items = position_re.search(cmd) pos1 = (int(items.group(1)), int(items.group(2))) pos2 = (int(items.group(3)) + 1, int(items.group(4)) + 1) if cmd.startswith('toggle'): a[pos1[0]:pos2[0], pos1[1]:pos2[1]] = np.invert(a[pos1[0]:pos2[0], pos1[1]:pos2[1]]) a2[pos1[0]:pos2[0], pos1[1]:pos2[1]] += 2 elif cmd.startswith('turn on'): a[pos1[0]:pos2[0], pos1[1]:pos2[1]] = True a2[pos1[0]:pos2[0], pos1[1]:pos2[1]] += 1 elif cmd.startswith('turn off'): a[pos1[0]:pos2[0], pos1[1]:pos2[1]] = False a2[pos1[0]:pos2[0], pos1[1]:pos2[1]] -= 1 a2[a2 < 0] = 0 a = np.zeros((1000, 1000), bool) a2 = np.zeros((1000, 1000), int) for cmd in open('6.input').readlines(): execute(cmd, a, a2) print('part 1', np.sum(a == True)) print('part 2', np.sum(a2))
pboettch/advent-of-code
2015/6.py
6.py
py
987
python
en
code
1
github-code
6
16325116494
from functools import wraps from typing import Callable from util.threading import Thread, TimeoutException from util.typing import P from .AbstractHandler import PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE, AbstractHandler class AbstractTimeoutHandler(AbstractHandler[PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE]): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.handle_request = cls._wrap_timeout(cls.handle_request) def __init__(self, timeout: float = None, default: PAYLOAD_TYPE = None, **kwargs): super().__init__(**kwargs) self.timeout = timeout self.default = default @staticmethod def _wrap_timeout( handle_request: Callable[P, RESPONSE_TYPE] ) -> Callable[P, RESPONSE_TYPE]: if ( hasattr(handle_request, "_AbstractTimeoutHandler_wrapped") and handle_request._AbstractTimeoutHandler_wrapped == True ): return handle_request @wraps(handle_request) def execute_with_timeout(self: "AbstractTimeoutHandler") -> RESPONSE_TYPE: result = None completed = False def run_execute_and_store_result(): nonlocal result nonlocal completed try: result = handle_request() completed = True except TimeoutException: pass thread = Thread(target=run_execute_and_store_result, daemon=True) thread.start() thread.join(self.timeout) if not completed: result = self.default return result # type: ignore execute_with_timeout._AbstractTimeoutHandler_wrapped = True return execute_with_timeout
MysteriousChallenger/nat-holepunch
protocol/interface/request_handler/AbstractTimeoutHandler.py
AbstractTimeoutHandler.py
py
1,804
python
en
code
0
github-code
6
37502345925
import numpy as np from typing import Callable, Dict, List, Optional, Tuple, Union import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_ from torch.cuda.amp import autocast from detectron2.config import configurable from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling import SEM_SEG_HEADS_REGISTRY from mask2former.modeling.pixel_decoder.msdeformattn import MSDeformAttnTransformerEncoderOnly from mask2former.modeling.transformer_decoder.position_encoding import PositionEmbeddingSine @SEM_SEG_HEADS_REGISTRY.register() class MSSharePixelDecoder(nn.Module): @configurable def __init__( self, input_shape: Dict[str, ShapeSpec], *, transformer_dropout: float, transformer_nheads: int, transformer_dim_feedforward: int, transformer_enc_layers: int, conv_dim: int, mask_dim: int, norm: Optional[Union[str, Callable]] = None, # deformable transformer encoder args transformer_in_features: List[str], common_stride: int, ): """ NOTE: this interface is experimental. Args: input_shape: shapes (channels and stride) of the input features transformer_dropout: dropout probability in transformer transformer_nheads: number of heads in transformer transformer_dim_feedforward: dimension of feedforward network transformer_enc_layers: number of transformer encoder layers conv_dims: number of output channels for the intermediate conv layers. mask_dim: number of output channels for the final conv layer. norm (str or callable): normalization for all conv layers """ super().__init__() transformer_input_shape = { k: v for k, v in input_shape.items() if k in transformer_in_features } # this is the input shape of pixel decoder input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride) self.in_features = [k for k, v in input_shape] # starting from "res2" to "res5" self.feature_strides = [v.stride for k, v in input_shape] self.feature_channels = [v.channels for k, v in input_shape] # this is the input shape of transformer encoder (could use less features than pixel decoder transformer_input_shape = sorted(transformer_input_shape.items(), key=lambda x: x[1].stride) self.transformer_in_features = [k for k, v in transformer_input_shape] # starting from "res2" to "res5" transformer_in_channels = [v.channels for k, v in transformer_input_shape] self.transformer_feature_strides = [v.stride for k, v in transformer_input_shape] # to decide extra FPN layers self.transformer_num_feature_levels = len(self.transformer_in_features) if self.transformer_num_feature_levels > 1: input_proj_list = [] # from low resolution to high resolution (res5 -> res2) for in_channels in transformer_in_channels[::-1]: input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, conv_dim, kernel_size=1), nn.GroupNorm(32, conv_dim), )) self.input_proj = nn.ModuleList(input_proj_list) else: self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(transformer_in_channels[-1], conv_dim, kernel_size=1), nn.GroupNorm(32, conv_dim), )]) for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) self.transformer = MSDeformAttnTransformerEncoderOnly( d_model=conv_dim, dropout=transformer_dropout, nhead=transformer_nheads, dim_feedforward=transformer_dim_feedforward, num_encoder_layers=transformer_enc_layers, num_feature_levels=self.transformer_num_feature_levels, ) N_steps = conv_dim // 2 self.pe_layer = PositionEmbeddingSine(N_steps, normalize=True) ''' self.mask_dim = mask_dim # use 1x1 conv instead self.mask_features = Conv2d( conv_dim, mask_dim, kernel_size=1, stride=1, padding=0, ) weight_init.c2_xavier_fill(self.mask_features) ''' self.maskformer_num_feature_levels = 3 # always use 3 scales self.common_stride = common_stride # extra fpn levels stride = min(self.transformer_feature_strides) self.num_fpn_levels = int(np.log2(stride) - np.log2(self.common_stride)) lateral_convs = [] output_convs = [] use_bias = norm == "" for idx, in_channels in enumerate(self.feature_channels[:self.num_fpn_levels]): lateral_norm = get_norm(norm, conv_dim) output_norm = get_norm(norm, conv_dim) lateral_conv = Conv2d( in_channels, conv_dim, kernel_size=1, bias=use_bias, norm=lateral_norm ) output_conv = Conv2d( conv_dim, conv_dim, kernel_size=3, stride=1, padding=1, bias=use_bias, norm=output_norm, activation=F.relu, ) weight_init.c2_xavier_fill(lateral_conv) weight_init.c2_xavier_fill(output_conv) self.add_module("adapter_{}".format(idx + 1), lateral_conv) self.add_module("layer_{}".format(idx + 1), output_conv) lateral_convs.append(lateral_conv) output_convs.append(output_conv) # Place convs into top-down order (from low to high resolution) # to make the top-down computation in forward clearer. self.lateral_convs = lateral_convs[::-1] self.output_convs = output_convs[::-1] ''' share_mask_branch = [] for idx in range(self.maskformer_num_feature_levels): share_norm = get_norm(norm, mask_dim) share_mask_conv = Conv2d( conv_dim, mask_dim, kernel_size=3, stride=2, padding=1, norm=share_norm, activation=F.relu, ) weight_init.c2_xavier_fill(share_mask_conv) self.add_module("share_{}".format(idx + 1), share_mask_conv) share_mask_branch.append(share_mask_conv) self.share_mask_branch = share_mask_branch ''' @classmethod def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]): ret = {} ret["input_shape"] = { k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES } ret["conv_dim"] = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM ret["mask_dim"] = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM ret["norm"] = cfg.MODEL.SEM_SEG_HEAD.NORM ret["transformer_dropout"] = cfg.MODEL.MASK_FORMER.DROPOUT ret["transformer_nheads"] = cfg.MODEL.MASK_FORMER.NHEADS # ret["transformer_dim_feedforward"] = cfg.MODEL.MASK_FORMER.DIM_FEEDFORWARD ret["transformer_dim_feedforward"] = 1024 # use 1024 for deformable transformer encoder ret[ "transformer_enc_layers" ] = cfg.MODEL.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS # a separate config ret["transformer_in_features"] = cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_IN_FEATURES ret["common_stride"] = cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE return ret @autocast(enabled=False) def forward_features(self, features): srcs = [] pos = [] # Reverse feature maps into top-down order (from low to high resolution) for idx, f in enumerate(self.transformer_in_features[::-1]): x = features[f].float() # deformable detr does not support half precision srcs.append(self.input_proj[idx](x)) pos.append(self.pe_layer(x)) y, spatial_shapes, level_start_index = self.transformer(srcs, pos) bs = y.shape[0] split_size_or_sections = [None] * self.transformer_num_feature_levels for i in range(self.transformer_num_feature_levels): if i < self.transformer_num_feature_levels - 1: split_size_or_sections[i] = level_start_index[i + 1] - level_start_index[i] else: split_size_or_sections[i] = y.shape[1] - level_start_index[i] y = torch.split(y, split_size_or_sections, dim=1) out = [] multi_scale_features = [] num_cur_levels = 0 for i, z in enumerate(y): out.append(z.transpose(1, 2).view(bs, -1, spatial_shapes[i][0], spatial_shapes[i][1])) # append `out` with extra FPN levels # Reverse feature maps into top-down order (from low to high resolution) for idx, f in enumerate(self.in_features[:self.num_fpn_levels][::-1]): x = features[f].float() lateral_conv = self.lateral_convs[idx] output_conv = self.output_convs[idx] cur_fpn = lateral_conv(x) # Following FPN implementation, we use nearest upsampling here y = cur_fpn + F.interpolate(out[-1], size=cur_fpn.shape[-2:], mode="bilinear", align_corners=False) y = output_conv(y) out.append(y) for o in out: if num_cur_levels < self.maskformer_num_feature_levels: multi_scale_features.append(o) num_cur_levels += 1 ''' mask_feats = [] feat = features['res2'].float() for idx in range(self.maskformer_num_feature_levels): feat = self.share_mask_branch[idx](feat) mask_feats.append(feat) feat = features['res2'] mask_feat = mask_feats[0] for idx in range(self.maskformer_num_feature_levels-1, 0, -1): mask_feat = mask_feats[idx] + F.interpolate(mask_feat, size=mask_feats[idx].shape[-2:], mode="bilinear", align_corners=False) mask_feat = feat + F.interpolate(mask_feat, size=feat.shape[-2:], mode="bilinear", align_corners=False) ''' return out[-1], out[0], multi_scale_features #return self.mask_features(mask_feat), out[0], multi_scale_features
zfonemore/NewVIS
minvis/share_mask_fpn.py
share_mask_fpn.py
py
10,597
python
en
code
0
github-code
6
21228252116
from django.urls import path from widgets.views import HomePageView, UserProfilePageView, SharedWidgetsPageView, \ PrivateWidgetsPageView, MemoryWidgetsView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('home/shared-widgets/', SharedWidgetsPageView.as_view(), name='shared-widgets'), path('user-profile/<slug:slug>/', UserProfilePageView.as_view(), name='user-profile'), path('user-profile/<slug:slug>/widgets/', PrivateWidgetsPageView.as_view(), name='private-widgets'), path('memory-widgets/<int:pk>', MemoryWidgetsView.as_view(), name='memory-widgets'), ]
alex-polo/homepage
widgets/urls.py
urls.py
py
607
python
en
code
0
github-code
6
856153134
from setuptools import setup import sys VERSION = '1.2.1263' plist = dict( CFBundleName='VisTrails', CFBundleShortVersionString=VERSION, CFBundleGetInfoString=' '.join(['VisTrails', VERSION]), CFBundleExecutable='vistrails', CFBundleIdentifier='edu.utah.sci.vistrails', ) sys.path.append('../..') APP = ['../../vistrails/run.py'] #comma-separated list of additional data files and #folders to include (not for code!) #DATA_FILES = ['/usr/local/graphviz-2.12/bin/dot',] OPTIONS = {'argv_emulation': True, 'iconfile': 'vistrails/resources/vistrails_icon.icns', 'includes': 'sip,pylab,xml,netCDF3,netCDF4_utils,netcdftime,\ libxml2,libxslt, Cookie, BaseHTTPServer, multifile, shelve,itk, itkBase, itkConfig, itkLazy, itkTypes, itkExtras', 'packages': 'PyQt4,vtk,MySQLdb,matplotlib,vistrails,numpy,ZSI,api', 'plist': plist, } setup( app=APP, # data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
VisTrails/VisTrails
scripts/dist/mac/setup_itk.py
setup_itk.py
py
1,027
python
en
code
100
github-code
6
32612633515
# Реализовать базовый класс Worker (работник), в котором определить атрибуты: # name, surname, position (должность), income (доход). Последний атрибут должен быть защищенным и # ссылаться на словарь, содержащий элементы: оклад и премия, например, {"wage": wage, "bonus": bonus}. # Создать класс Position (должность) на базе класса Worker. В классе Position реализовать методы # получения полного имени сотрудника (get_full_name) и дохода с учетом премии (get_total_income). # Проверить работу примера на реальных данных (создать экземпляры класса Position, передать данные, # проверить значения атрибутов, вызвать методы экземпляров). salary_dict = {'Сергей Петров': {'wage': 30000, 'bonus': 7000}, 'Михаил Смирнов': {'wage': 10000, 'bonus': 5000} } class Worker: name: str surname: str position: str _income = salary_dict def __init__(self, name, surname, position): self.name = name self.surname = surname self.position = position class Position(Worker): def __init__(self, name, surname, position): super().__init__(name, surname, position) def get_full_name(self): print(f'\nСотрудник: {self.name} {self.surname}\nДолжность: {self.position}') def get_total_income(self): if f"{self.name} {self.surname}" in self._income.keys(): print(f'Доход с учетом премии: {sum(self._income[f"{self.name} {self.surname}"].values())} рублей.') else: print('Такого сотрудника нет!') petrov = Position('Сергей', 'Петров', 'Менеджер') petrov.get_full_name() petrov.get_total_income() smirnov = Position('Михаил', 'Смирнов', 'Грузчик') smirnov.get_full_name() smirnov.get_total_income() tenev = Position('Михаил', 'Тенев', 'Иллюминат') tenev.get_full_name() tenev.get_total_income()
Unst1k/GeekBrains-PythonCourse
DZ6/DZ6-3.py
DZ6-3.py
py
2,365
python
ru
code
1
github-code
6
43242415991
from os.path import abspath, dirname, join from preggy import expect from tornado.testing import gen_test from tests.base import TestCase from thumbor.compatibility.storage import Storage from thumbor.config import Config from thumbor.context import Context, ServerParameters from thumbor.importer import Importer STORAGE_PATH = abspath(join(dirname(__file__), "../fixtures/images/")) class CompatibilityStorageTestCase(TestCase): def get_image_path(self, name): return f"./tests/fixtures/images/{name}" def get_image_bytes(self, name): with open(self.get_image_path(name), "rb") as img: return img.read() def get_image_url(self, name): return f"s.glbimg.com/some/{name}" def get_context(self): config = Config( FILE_LOADER_ROOT_PATH=STORAGE_PATH, COMPATIBILITY_LEGACY_STORAGE="tests.compatibility.legacy_file_storage", STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True, ) importer = Importer(config) importer.import_modules() server = ServerParameters( 8889, "localhost", "thumbor.conf", None, "info", None ) server.security_key = "ACME-SEC" return Context(server, config=config, importer=importer) @gen_test async def test_should_raise_for_invalid_compatibility_storage(self): config = Config( FILE_LOADER_ROOT_PATH=STORAGE_PATH, STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True, ) importer = Importer(config) importer.import_modules() server = ServerParameters( 8889, "localhost", "thumbor.conf", None, "info", None ) server.security_key = "ACME-SEC" ctx = Context(server, config=config, importer=importer) storage = Storage(ctx) with expect.error_to_happen( RuntimeError, message=( "The 'COMPATIBILITY_LEGACY_STORAGE' configuration should " "point to a valid storage when using compatibility storage." ), ): await storage.get("invalid-path") @gen_test async def test_should_return_none_for_invalid_image(self): storage = Storage(self.context) result = await storage.get("invalid-path") expect(result).to_be_null() @gen_test async def test_should_get(self): url = self.get_image_url("image.jpg") image_bytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(url, image_bytes) result = await storage.get(url) expect(result).not_to_be_null() expect(result).not_to_be_an_error() expect(result).to_equal(image_bytes) @gen_test async def test_should_put(self): url = self.get_image_url("image.jpg") image_bytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(url, image_bytes) result = await storage.get(url) expect(result).not_to_be_null() expect(result).not_to_be_an_error() expect(result).to_equal(image_bytes) @gen_test async def test_should_put_detector_data(self): iurl = self.get_image_url("image_7.jpg") ibytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(iurl, ibytes) await storage.put_detector_data(iurl, "some-data") got = await storage.get_detector_data(iurl) expect(got).not_to_be_null() expect(got).not_to_be_an_error() expect(got).to_equal("some-data") @gen_test async def test_should_put_crypto(self): iurl = self.get_image_url("image_7.jpg") ibytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(iurl, ibytes) await storage.put_crypto(iurl) got = await storage.get_crypto(iurl) expect(got).not_to_be_null() expect(got).not_to_be_an_error() expect(got).to_equal("ACME-SEC") @gen_test async def test_exists(self): iurl = self.get_image_url("image_7.jpg") ibytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(iurl, ibytes) exists = await storage.exists(iurl) not_exists = await storage.exists("some-invalid-random-file.jpg") expect(exists).to_be_true() expect(not_exists).to_be_false() @gen_test async def test_remove(self): iurl = self.get_image_url("image_7.jpg") ibytes = self.get_image_bytes("image.jpg") storage = Storage(self.context) await storage.put(iurl, ibytes) exists = await storage.exists(iurl) expect(exists).to_be_true() await storage.remove(iurl) not_exists = await storage.exists(iurl) expect(not_exists).to_be_false()
thumbor/thumbor
tests/compatibility/test_compatibility_storage.py
test_compatibility_storage.py
py
4,916
python
en
code
9,707
github-code
6
72784516667
# https://www.codewars.com/kata/58fd9f6213b00172ce0000c9 def split_exp(n): lenn = len(n) res = [] pnt = n.find('.') if pnt < 0: res = [c + '0'*(lenn-i-1) for i, c in enumerate(n) if c != '0'] else: for i,j in zip(range(0, pnt), range(pnt-1,-1,-1)): if n[i]!= '0': res.append(n[i] + '0'*j) for i, j in zip(range(pnt+1, lenn), range(lenn)): if n[i]!= '0': res.append('.' + '0'*j + n[i]) return res
blzzua/codewars
7-kyu/simple_fun_205_split_exp.py
simple_fun_205_split_exp.py
py
470
python
en
code
0
github-code
6
24615537845
# Layers are stacked in order of drawing level_0 = { 'tiles_sheet_path': '../imgs/terrain/mario_terrain.png', 'layers': { 'terrain': { 'path': '../levels/level_data/0/level0_Level.csv', 'type': 'static', }, 'ghost_passage': { 'path': '../levels/level_data/0/level0_GhostPassage.csv', 'type': 'passage', }, 'scenery': { 'path': '../levels/level_data/0/level0_Scenery.csv', 'type': 'static', }, 'scenery2': { 'path': '../levels/level_data/0/level0_Additional Scenery.csv', 'type': 'static', }, 'player': { 'path': '../levels/level_data/0/level0_Mario.csv', 'type': 'player', }, 'ghosts': { 'path': '../levels/level_data/0/level0_Pacman.csv', 'type': 'ghosts', }, 'coins': { 'path': '../levels/level_data/0/level0_Coins.csv', 'type': 'coin', }, 'question_blocks': { 'path': '../levels/level_data/0/level0_Question_blocks.csv', 'type': 'question_block', }, 'pipe_head_pair_0': { 'path': '../levels/level_data/0/level0_Pipe_head_pair_0.csv', 'type': 'pipe_head', }, 'pipe_head_pair_1': { 'path': '../levels/level_data/0/level0_Pipe_head_pair_1.csv', 'type': 'pipe_head', }, 'pipe_head_pair_2': { 'path': '../levels/level_data/0/level0_Pipe_head_pair_2.csv', 'type': 'pipe_head', }, } } player = { 'sprite_sheet_path': '../imgs/player/shroomaddict.png', 'animation_idle': { 'frames': [0], 'fps': 1, }, 'animation_walking': { 'frames': [1, 2, 3], 'fps': 10 }, 'animation_running': { 'frames': [1, 2, 3], 'fps': 16 }, 'animation_jumping': { 'frames': [5], 'fps': 1 }, 'animation_dede': { 'frames': [6], 'fps': 1 } } ghosts = { 'sprite_sheet_path': '../imgs/ghosts/ghost_sprites.png', 'seconds_following': 12, 'seconds_spreading': 8, 'animation_idle': { 'frames': [0], 'fps': 1 }, 'animation_right': { 'frames': [0, 1], 'fps': 7, }, 'animation_left': { 'frames': [2, 3], 'fps': 7 }, 'animation_up': { 'frames': [4, 5], 'fps': 7 }, 'animation_down': { 'frames': [6, 7], 'fps': 7 }, 'animation_scared': { 'frames': [8, 9], 'fps': 7 }, 'animation_scared_white': { 'frames': [10, 11], 'fps': 7 }, 'animation_dead_right': { 'frames': [12], 'fps': 1 }, 'animation_dead_left': { 'frames': [13], 'fps': 1 }, 'animation_dead_up': { 'frames': [14], 'fps': 1 }, 'animation_dead_down': { 'frames': [15], 'fps': 1 } } coins = { 'sprite_sheet_path': '../imgs/coin/coin.png', 'animation_idle': { 'frames': [0, 1, 2, 3, 4, 5, 6, 7], 'fps': 10 } } question_block = { 'sprite_sheet_path': '../imgs/question_block/question_block.png', 'animation_idle': { 'frames': [0, 0, 0, 1, 2], 'fps': 4 }, 'animation_hit': { 'frames': [3, 3], 'fps': 1 } } pipe_head = { 'sprite_sheet_path': '../imgs/terrain/mario_terrain.png', 'animation_idle': { 'frames': [0], 'fps': 1 }, } ui = { 'sprite_sheet_path': '../imgs/ui/ui.png' }
ysbrandB/M6FinalProject
code/game_data.py
game_data.py
py
3,637
python
en
code
0
github-code
6
71066866429
from ....utils.onlinetex import tex_to_svg_file_online from ....utils.jupyter import video from ..scene import SceneGL from ..config import Size from .plot import Plot from .scatter import Scatter from pathlib import Path import re import time import shutil from manimlib import ( BLUE, GREEN, ShowCreation, Write, VGroup, Transform, ReplacementTransform, FadeIn, FadeOut, ) from manimlib.utils.rate_functions import linear, smooth from manimlib.extract_scene import get_scene_config import manimlib.config from manimlib.camera.camera import Camera from sparrow.path import rel_to_abs __all__ = ["EagerModeScene", "JupyterModeScene", "CONFIG"] class CONFIG: # skip_animations = False # "Save the last frame" color = None # Background color" full_screen = False gif = False resolution = '1920x1080' preview = False # Render to a movie file with an alpha channel, # if transparent is True, .mov file will be generated. transparent = False save_pngs = False # Save each frame as a png hd = False uhd = False quiet = True open = False # Automatically open the saved file once its done finder = False # Show the output file in finder frame_rate = 30 file_name = None video_dir = None # directory to write video start_at_animation_number = None use_online_tex = False class EagerModeScene(SceneGL): def __init__( self, screen_size=Size.big, scene_name='EagerModeScene', ): # self.CONFIG = CONFIG args = manimlib.config.parse_cli() args_dict = vars(args) args_dict['file'] = None args_dict['scene_names'] = scene_name args_dict['screen_size'] = screen_size if CONFIG.preview: from pyglet.window import key self.key = key else: args_dict['write_file'] = True for key, value in CONFIG.__dict__.items(): args_dict[key] = value if CONFIG.gif is True: args_dict['write_file'] = True # if CONFIG.gif is True: # args_dict["transparent"] = False if CONFIG.use_online_tex: print("Use online latex compiler") manimlib.mobject.svg.tex_mobject.tex_to_svg_file = tex_to_svg_file_online self.config = manimlib.config.get_configuration(args) self.scene_config = get_scene_config(self.config) super().__init__(**self.scene_config) self.virtual_animation_start_time = 0 self.real_animation_start_time = time.time() self.file_writer.begin() self.setup() self.plt = Plot() self.is_axes_line_gen_ed = False self._scatter_ax = None self.clips = [] self.current_clip = 0 self.saved_states = [] self.animation_list = [] self.animation_func_dict = {} self.loop_start_animation = None self.pause_start_animation = 0 def play(self, *args, run_time=1, rate_func=linear, **kwargs): """TODO:""" super().play(*args, run_time=run_time, rate_func=rate_func, **kwargs) def _play_method(self, mobj, Method, loc): loc.pop('self') args = loc.pop('args') kwargs = loc.pop('kwargs') self.play(Method(mobj), *args, **loc, **kwargs) def write(self, mobject, *args, run_time=1., rate_func=linear, **kwargs): self._play_method(mobject, Write, locals()) def show_creation(self, mobject, *args, run_time=1, rate_func=linear, **kwargs): self._play_method(mobject, ShowCreation, locals()) def fade_in(self, mobject, *args, run_time=1, rate_func=linear, **kwargs): self._play_method(mobject, FadeIn, locals()) def fade_out(self, mobject, *args, run_time=1, rate_func=linear, **kwargs): self._play_method(mobject, FadeOut, locals()) def get_animate_name_func(self): def get_clip_names(): names = [] # Fixme: use other method to replace `dir()` for name in dir(self): if re.search(r'clip_*[0-9]+', name): names.append(name) # sort if names: names = sorted(names, key=lambda x: int(re.search(r"[0-9]+", x).group())) return names clip_names = get_clip_names() animation_func_dict = {} if clip_names: for func_name in clip_names: animation_func_dict.setdefault(func_name, getattr(self, func_name)) self.animation_func_dict = animation_func_dict def save_image(self, filename): """This method works only when CONFIG.preview=False. """ assert (CONFIG.preview == False, "`self.save_image` works only when CONFIG.preview=False.") self.camera: Camera self.camera.get_image().save(filename) def render(self): self.get_animate_name_func() for name, func in self.animation_func_dict.items(): self.save_state() self.saved_states.append(self.saved_state) self.current_clip += 1 func() self.animation_list.append(func) self.hold_on() def replay(self, animation_index=None): if animation_index is None: animation_index = self.current_clip self.saved_state = self.saved_states[animation_index - 1] self.restore() self.animation_list[animation_index - 1]() def loop_animate(self, animation_index=None, num=10): while num: num -= 1 self.replay(animation_index) def next_animate(self): self.current_clip += 1 def _clip_control(self, symbol): # play preview clip if symbol in (self.key.LEFT, self.key.COMMA, self.key.NUM_1, self.key._1): self.current_clip -= 1 try: self.replay(self.current_clip) except IndexError: self.current_clip += 1 # play next clip elif symbol in (self.key.RIGHT, self.key.PERIOD, self.key._3, self.key.NUM_3): self.current_clip += 1 try: self.replay(self.current_clip) except IndexError: self.current_clip -= 1 # play current clip elif symbol in (self.key.NUM_DIVIDE, self.key.DOWN, self.key._2, self.key.NUM_2): self.replay(self.current_clip) def hold_on(self): self.tear_down() def tear_down(self): super().tear_down() def get_config(self): return self.config def save_default_config(self): """Save the default config file to current directory.""" shutil.copy(rel_to_abs("custom_config.yml"), rel_to_abs('custom_config.yml')) def get_scene_config(self): return self.scene_config def save_start(self, file_name): """TODO""" def save_end(self): """TODO""" # self.file_writer.finish() def embed(self): super().embed() # FIXME: Remove method `plot` from EagerModeScene. def plot(self, x, y, color=None, width=2, axes_ratio=0.62, scale_ratio=None, num_decimal_places=None, show_axes=True, include_tip=True, x_label='x', y_label='y'): """ params ------ scale_ratio: Scale ratio of coordinate axis. i.e. y / x . num_decimal_places: Number of significant digits of coordinate_labels. """ self.plt.plot(x, y, color, width, axes_ratio, scale_ratio, show_axes, include_tip, num_decimal_places, x_label, y_label) def scatter2d(self, x, y, color=BLUE, size=0.05, ax=None): self._scatter_nd(x, y, color=color, size=size, ax=ax) def scatter3d(self, x, y, z, color=BLUE, size=0.05, ax=None): self._scatter_nd(x, y, z, color=color, size=size, ax=ax) def _scatter_nd(self, x, y, z=None, color=BLUE, size=0.05, ax=None): scatter_obj = Scatter() if ax is not None: self._scatter_ax = ax if z is not None: self._scatter_ax, mobj = scatter_obj.from_dot_cloud_3d( x, y, z, size=size, color=color, ax=self._scatter_ax) else: self._scatter_ax, mobj = scatter_obj.from_dotcloud(x, y, size=size, color=color, ax=self._scatter_ax) if self._scatter_ax not in self.mobjects: self.write(self._scatter_ax) self.add(mobj) return self._scatter_ax, mobj def plot3d(self, x, y, z, width=2, axes_ratio=0.62, show_axes=True): """TODO""" def get_plot_mobj(self): if self.is_axes_line_gen_ed is False: self.plt.gen_axes_lines() self.is_axes_line_gen_ed = True axes_lines_dict = self.plt.get_axes_lines() axes_mobj = VGroup(*axes_lines_dict["axes"]) lines_mobj = VGroup(*axes_lines_dict["line"]) return axes_mobj, lines_mobj def get_plot_axes(self): return self.plt.get_axes() def reset_plot(self): self.plt = Plot() self.is_axes_line_gen_ed = False def show_plot(self, play=True, reset=True): axes_mobj, lines_mobj = self.get_plot_mobj() pltvgroup = VGroup(axes_mobj, lines_mobj) if play: self.write(axes_mobj, run_time=1.5, rate_func=smooth) self.show_creation(lines_mobj, run_time=1.5, rate_func=smooth) else: self.add(pltvgroup) if reset: self.plt = Plot() return pltvgroup class JupyterModeScene(EagerModeScene): def __init__(self, write_file=True, **kwargs): CONFIG.write_file = write_file super().__init__(**kwargs) def finish(self): self.file_writer.finish() def embed(self): """We don't need it in jupyter lab/notebook.""" @property def video_path(self): path = Path(self.file_writer.get_movie_file_path()) self.file_writer.finish() relative_path = path.relative_to(Path.cwd()) return str(relative_path) def display(self, width=854, height=480, controls=True, autoplay=True, loop=True): return video(self.video_path, width, height, controls, autoplay, loop) def quit(self): """Please use exit() or quit() in jupyter cell.""" pass
beidongjiedeguang/manim-express
manim_express/backend/manimgl/express/eager.py
eager.py
py
10,559
python
en
code
13
github-code
6
6969799516
import re import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from collections import OrderedDict from torch import Tensor from torch.jit.annotations import List #added import torchvision.transforms as transforms from torch.utils.data import DataLoader from load_utils import load_state_dict_from_url from cub_voc import CUB_VOC import os from tqdm import tqdm import shutil import numpy as np from newPad2d import newPad2d #from torch.autograd import Variable MEMORY_EFFICIENT = True IS_TRAIN = 0 # 0/1 IS_MULTI = 0 # 0/1 LAYERS = '121' DATANAME = 'bird' # bird/cat/.../cub/helen/voc_multi NUM_CLASSES =6 if IS_MULTI else 2 cub_file = '/data/sw/dataset/frac_dataset' voc_file = '/data/sw/dataset/VOCdevkit/VOC2010/voc2010_crop' log_path = '/data/fjq/iccnn/densenet/' # for model save_path = '/data/fjq/iccnn/basic_fmap/densenet/' # for get_feature acc_path = '/data/fjq/iccnn/basic_fmap/densenet/acc/' dataset = '%s_densenet_%s_ori' % (LAYERS, DATANAME) log_path = log_path + dataset + '/' pretrain_model = log_path + 'model_2000.pth' BATCHSIZE = 1 LR = 0.00001 EPOCH = 1000 __all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161'] model_urls = { 'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth', 'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth', 'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth', 'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth', } class _DenseLayer(nn.Module): def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient=MEMORY_EFFICIENT): super(_DenseLayer, self).__init__() self.add_module('norm1', nn.BatchNorm2d(num_input_features)), self.add_module('relu1', nn.ReLU(inplace=True)), self.add_module('conv1', nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)), self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)), self.add_module('relu2', nn.ReLU(inplace=True)), self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=0, #new padding bias=False)), self.drop_rate = float(drop_rate) self.memory_efficient = memory_efficient self.pad2d_1 = newPad2d(1) #nn.ReplicationPad2d(1)#new padding def bn_function(self, inputs): # type: (List[Tensor]) -> Tensor concated_features = torch.cat(inputs, 1) bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484 return bottleneck_output # todo: rewrite when torchscript supports any def any_requires_grad(self, input): # type: (List[Tensor]) -> bool for tensor in input: if tensor.requires_grad: return True return False @torch.jit.unused # noqa: T484 def call_checkpoint_bottleneck(self, input): # type: (List[Tensor]) -> Tensor def closure(*inputs): return self.bn_function(inputs) return cp.checkpoint(closure, *input) @torch.jit._overload_method # noqa: F811 def forward(self, input): # type: (List[Tensor]) -> (Tensor) pass @torch.jit._overload_method # noqa: F811 def forward(self, input): # type: (Tensor) -> (Tensor) pass # torchscript does not yet support *args, so we overload method # allowing it to take either a List[Tensor] or single Tensor def forward(self, input): # noqa: F811 if isinstance(input, Tensor): prev_features = [input] else: prev_features = input if self.memory_efficient and self.any_requires_grad(prev_features): if torch.jit.is_scripting(): raise Exception("Memory Efficient not supported in JIT") bottleneck_output = self.call_checkpoint_bottleneck(prev_features) else: bottleneck_output = self.bn_function(prev_features) new_features = self.conv2(self.pad2d_1(self.relu2(self.norm2(bottleneck_output))))#new padding if self.drop_rate > 0: new_features = F.dropout(new_features, p=self.drop_rate, training=self.training) return new_features class _DenseBlock(nn.ModuleDict): _version = 2 def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=MEMORY_EFFICIENT): super(_DenseBlock, self).__init__() for i in range(num_layers): layer = _DenseLayer( num_input_features + i * growth_rate, growth_rate=growth_rate, bn_size=bn_size, drop_rate=drop_rate, memory_efficient=memory_efficient, ) self.add_module('denselayer%d' % (i + 1), layer) def forward(self, init_features): features = [init_features] for name, layer in self.items(): new_features = layer(features) features.append(new_features) return torch.cat(features, 1) class _Transition(nn.Sequential): def __init__(self, num_input_features, num_output_features): super(_Transition, self).__init__() self.add_module('norm', nn.BatchNorm2d(num_input_features)) self.add_module('relu', nn.ReLU(inplace=True)) self.add_module('conv', nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)) self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2)) class DenseNet(nn.Module): r"""Densenet-BC model class, based on `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: growth_rate (int) - how many filters to add each layer (`k` in paper) block_config (list of 4 ints) - how many layers in each pooling block num_init_features (int) - the number of filters to learn in the first convolution layer bn_size (int) - multiplicative factor for number of bottle neck layers (i.e. bn_size * k features in the bottleneck layer) drop_rate (float) - dropout rate after each dense layer num_classes (int) - number of classification classes memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ """ def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, drop_rate=0, num_classes=2, memory_efficient=MEMORY_EFFICIENT): super(DenseNet, self).__init__() # First convolution self.features = nn.Sequential(OrderedDict([ ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=0, bias=False)), # new padding ('norm0', nn.BatchNorm2d(num_init_features)), ('relu0', nn.ReLU(inplace=True)), ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=0)), # new padding ])) self.pad2d_1 = newPad2d(1)#nn.ZeroPad2d(1) #new padding self.pad2d_3 = newPad2d(3)#nn.ZeroPad2d(3) #new padding # Each denseblock num_features = num_init_features for i, num_layers in enumerate(block_config): block = _DenseBlock( num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate, memory_efficient=memory_efficient ) self.features.add_module('denseblock%d' % (i + 1), block) num_features = num_features + num_layers * growth_rate if i != len(block_config) - 1: trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2) self.features.add_module('transition%d' % (i + 1), trans) num_features = num_features // 2 # Final batch norm self.features.add_module('norm5', nn.BatchNorm2d(num_features)) # Linear layer self.classifier = nn.Linear(num_features, num_classes) # Official init from torch repo. for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0) def forward(self, x): for i, layer in enumerate(self.features): if i == 0: x = self.pad2d_3(x) # new padding if i == 3: x = self.pad2d_1(x) # new padding x = layer(x) out = F.relu(x, inplace=True) f_map = out.detach() # get_feature out = F.adaptive_avg_pool2d(out, (1, 1)) out = torch.flatten(out, 1) out = self.classifier(out) return out, f_map #out def _load_state_dict(model, model_url, progress): # '.'s are no longer allowed in module names, but previous _DenseLayer # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'. # They are also in the checkpoints in model_urls. This pattern is used # to find such keys. pattern = re.compile( r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$') state_dict = load_state_dict_from_url(model_url, progress=progress) for key in list(state_dict.keys()): # print(key) res = pattern.match(key) if res: new_key = res.group(1) + res.group(2) state_dict[new_key] = state_dict[key] del state_dict[key] pretrained_dict = {k: v for k, v in state_dict.items() if 'classifier' not in k} model_dict = model.state_dict() model_dict.update(pretrained_dict) model.load_state_dict(model_dict, strict=False) def _densenet(arch, growth_rate, block_config, num_init_features, num_class, pretrained, progress, **kwargs): model = DenseNet(growth_rate, block_config, num_init_features, num_classes=num_class, **kwargs) if pretrained: _load_state_dict(model, model_urls[arch], progress) else: if pretrain_model is not None: device = torch.device("cuda") model = nn.DataParallel(model).to(device) model.load_state_dict(torch.load(pretrain_model)) else: print('Error: pretrain_model == None') return model def densenet121(num_class, pretrained=False, progress=True, **kwargs): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ """ return _densenet('densenet121', 32, (6, 12, 24, 16), 64, num_class, pretrained, progress, **kwargs) def densenet161(num_class, pretrained=False, progress=True, **kwargs): r"""Densenet-161 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ """ return _densenet('densenet161', 48, (6, 12, 36, 24), 96, num_class, pretrained, progress, **kwargs) def densenet169(num_class, pretrained=False, progress=True, **kwargs): r"""Densenet-169 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ """ return _densenet('densenet169', 32, (6, 12, 32, 32), 64, num_class, pretrained, progress, **kwargs) def densenet201(num_class, pretrained=False, progress=True, **kwargs): r"""Densenet-201 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ """ return _densenet('densenet201', 32, (6, 12, 48, 32), 64, num_class, pretrained, progress, **kwargs) def get_Data(is_train, dataset_name, batch_size): transform = transforms.Compose([ transforms.RandomResizedCrop((224, 224), scale=(0.5, 1.0)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) val_transform = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) voc_helen = ['bird', 'cat', 'cow', 'dog', 'horse', 'sheep', 'helen', 'voc_multi'] ##cub dataset### label = None if is_train else 0 if not is_train: batch_size = 1 if dataset_name == 'cub': trainset = CUB_VOC(cub_file, dataset_name, 'ori', train=True, transform=transform, is_frac=label) testset = CUB_VOC(cub_file, dataset_name, 'ori', train=False, transform=val_transform, is_frac=label) ###cropped voc dataset### elif dataset_name in voc_helen: trainset = CUB_VOC(voc_file, dataset_name, 'ori', train=True, transform=transform, is_frac=label) testset = CUB_VOC(voc_file, dataset_name, 'ori', train=False, transform=val_transform, is_frac=label) ###celeb dataset### #elif dataset_name == 'celeb': # trainset = Celeb(training = True, transform=None) # testset = Celeb(training = False, transform=None) train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True) test_loader = DataLoader(testset, batch_size=batch_size, shuffle=False) return train_loader, test_loader def net_train(): trainset_loader, testset_loader = get_Data(IS_TRAIN, DATANAME, BATCHSIZE) if os.path.exists(log_path): shutil.rmtree(log_path);os.makedirs(log_path) else: os.makedirs(log_path) device = torch.device("cuda") net = None if LAYERS == '121': net = densenet121(num_class=NUM_CLASSES, pretrained=True) if LAYERS == '161': net = densenet161(num_class=NUM_CLASSES, pretrained=True) net = nn.DataParallel(net).to(device) # Loss and Optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(net.module.parameters(), lr=LR) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=200, gamma=0.6) # Train the model best_acc = 0.0; save_loss = []; test_loss = []; train_acc = []; test_acc = []; for epoch in range(EPOCH+1): scheduler.step() net.train() total_loss = 0.0; correct = .0; total = .0; for batch_step, input_data in tqdm(enumerate(trainset_loader,0),total=len(trainset_loader),smoothing=0.9): inputs, labels = input_data inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() output, _ = net(inputs) #print(output) _, predicted = torch.max(output.data, 1) correct += (predicted == labels).sum() total += labels.size(0) loss = criterion(output, labels) #print(module.features.conv0.weight) loss.backward() #if batch_step>0: # return #for name, parms in net.named_parameters(): # print('after* name:', name, 'grad_value:',parms.grad) optimizer.step() total_loss += loss.item() total_loss = float(total_loss) / (batch_step+1) correct = float(correct) / total testacc, testloss = test(net, testset_loader) save_loss.append(total_loss); train_acc.append(correct); test_loss.append(testloss); test_acc.append(testacc); np.savez(log_path+'loss.npz', train_loss=np.array(save_loss), test_loss=np.array(test_loss),\ train_acc=np.array(train_acc), test_acc=np.array(test_acc)) print('Epoch', epoch, 'train loss: %.4f' % total_loss, 'train accuracy:%.4f' % correct, \ 'test loss: %.4f' % testloss, 'test accuracy:%.4f' % testacc) if epoch % 50 == 0: torch.save(net.state_dict(), log_path+'model_%.3d.pth' % epoch) if epoch % 1 == 0: if testacc > best_acc: best_acc = testacc torch.save(net.state_dict(), log_path+'model_%.3d_%.4f.pth' % (epoch, best_acc)) print('Finished Training') return net def get_feature(): print('pretrain_model:', pretrain_model) _, testset_test = get_Data(True, DATANAME, BATCHSIZE) _, testset_feature = get_Data(False, DATANAME, BATCHSIZE) device = torch.device("cuda") net = None if LAYERS == '121': net = densenet121(num_class=NUM_CLASSES, pretrained=False) if LAYERS == '161': net = densenet161(num_class=NUM_CLASSES, pretrained=False) net = nn.DataParallel(net).to(device) # Test the model acc, _ = test(net, testset_test) f = open(acc_path+dataset+'_test.txt', 'w+') f.write('%s\n' % dataset) f.write('acc:%f\n' % acc) print('test acc:', acc) all_feature = [] testset = testset_test if DATANAME == 'voc_multi' else testset_feature for batch_step, input_data in tqdm(enumerate(testset,0),total=len(testset),smoothing=0.9): inputs, labels = input_data inputs, labels = inputs.to(device), labels.to(device) net.eval() output, f_map = net(inputs) all_feature.append(f_map.cpu().numpy()) all_feature = np.concatenate(all_feature,axis=0) f.write('sample num:%d' % (all_feature.shape[0])) f.close() print(all_feature.shape) np.savez_compressed(save_path+LAYERS+'_densenet_'+DATANAME+'_ori.npz', f_map=all_feature[...]) print('Finished Operation!') return net def test(net, testdata): criterion = nn.CrossEntropyLoss() correct, total = .0, .0 total_loss = .0 for batch_step, input_data in tqdm(enumerate(testdata,0),total=len(testdata),smoothing=0.9): inputs, labels = input_data inputs, labels = inputs.cuda(), labels.cuda() net.eval() outputs, _ = net(inputs) loss = criterion(outputs, labels) total_loss += loss.item() _, predicted = torch.max(outputs, 1) total += labels.size(0) correct += (predicted == labels).sum() total_loss = float(total_loss)/(batch_step+1) return float(correct)/total, total_loss def densenet_ori_train(): if IS_TRAIN == 1: net = net_train() elif IS_TRAIN == 0: net = get_feature()
ada-shen/icCNN
densenet_ori_train.py
densenet_ori_train.py
py
20,335
python
en
code
18
github-code
6
73789760509
def leiaint(msg): while True: try: i = int(input(msg)) except KeyboardInterrupt: print('entrada de dados interrompida pelo usuario.') break except (ValueError, TypeError): print(f'\033[0;31m ERRO! digite um numero valido \033[m') continue else: return i def leiafloat(msg): while True: try: f = float(input(msg)) except: print(f'\033[0;31m ERRO! digite um numero valido \033[m') else: return f i = leiaint('digite um numero inteiro: ') f = leiafloat('digite um numero real: ') print(f'os valores digitados foram {i} e {f}')
Kaue-Marin/Curso-Python
pacote dowlond/curso python/exercicio113.py
exercicio113.py
py
697
python
pt
code
0
github-code
6
10422172533
from __future__ import annotations from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt from PySide6.QtWidgets import QLayout, QSizePolicy, QWidgetItem class FlowLayout(QLayout): def __init__(self, parent=None, center=False): super().__init__(parent) if parent is not None: self.setContentsMargins(QMargins(0, 0, 0, 0)) self._item_list: list[QWidgetItem] = [] self.center = center def __del__(self): item = self.takeAt(0) while item: item = self.takeAt(0) def addItem(self, item): self._item_list.append(item) def count(self): return len(self._item_list) def itemAt(self, index): if 0 <= index < len(self._item_list): return self._item_list[index] return None def takeAt(self, index): if 0 <= index < len(self._item_list): return self._item_list.pop(index) return None def expandingDirections(self): return Qt.Orientation(0) def hasHeightForWidth(self): return True def heightForWidth(self, width): height = self._do_layout(QRect(0, 0, width, 0), True) return height def setGeometry(self, rect): super().setGeometry(rect) self._do_layout(rect, False) def sizeHint(self): return self.minimumSize() def minimumSize(self): size = QSize() for item in self._item_list: size = size.expandedTo(item.minimumSize()) size += QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top()) return size def _do_layout(self, rect, test_only): x = rect.x() y = rect.y() line_height = 0 spacing = self.spacing() rows: list[tuple[list[QWidgetItem], int, int]] = [] row = [] for item in self._item_list: style = item.widget().style() layout_spacing_x = style.layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) layout_spacing_y = style.layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) space_x = ( spacing + layout_spacing_x ) * item.widget().isVisible() # If an item isn't visible, it does not have any influence on the next space_y = spacing + layout_spacing_y next_x = x + item.sizeHint().width() + space_x if next_x - space_x > rect.right() and line_height > 0: rows.append( (row, rect.right() - x - space_x, line_height) ) # We need to remove the unnecessary extra padding from all rows, not just the last row = [] x = rect.x() y = y + line_height + space_y next_x = x + item.sizeHint().width() + space_x line_height = 0 if not test_only: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = next_x line_height = max(line_height, item.sizeHint().height()) row.append(item) rows.append((row, rect.right() - x - space_x, line_height)) if not test_only and self.center: for items, x_margin, y_size in rows: x_margin /= 2 for item in items: r = item.geometry() new_y = r.y() if r.height() < y_size: new_y += (y_size - r.height()) / 2 item.setGeometry(QRect(QPoint(r.x() + x_margin, new_y), item.sizeHint())) return y + line_height - rect.y()
randovania/randovania
randovania/gui/lib/flow_layout.py
flow_layout.py
py
3,663
python
en
code
165
github-code
6
73008021309
#Lesson / Exercise 23 my code, sort the customer total amount from pyspark import SparkConf, SparkContext #boilerplate conf = SparkConf().setMaster("local").setAppName("TotalAmountOrdered") sc = SparkContext(conf = conf) def parseLine(line): fields = line.split(',') return (int(fields[0]), float(fields[2])) #return (float(fields[2]), int(fields[1])) # ALTERNATE OPTION I think lines = sc.textFile("file:///C:/Users/cenzo/SparkCourse/CSV/customer-orders.csv") #read from correct file rdd = lines.map(parseLine) totalAmount = rdd.reduceByKey(lambda x, y: x+y) totalSortedAmount = totalAmount.map(lambda x: (x[1], x[0])).sortByKey() #to sort this, we want to sort it by total spent so we can see who is biggest spender. TO do this we need to swap the key and values so the amount spent becomes the key results = totalSortedAmount.collect() for result in results: print(str(result[1]) + "\t\t" + str(result[0])) #need to change how output is printed, we do not want the total amount to be pritned first. We also have to cast the result to a string
CenzOh/Python_Spark
MyCode/customerTotalAmountSorted.py
customerTotalAmountSorted.py
py
1,078
python
en
code
0
github-code
6
29954994164
from __future__ import print_function import re import bitarray def filterFeatures(sr_obj, feature_types=None, qualifier_regexs=None): """Filter a `SeqRecord` object's `SeqFeature` list by type and qualifiers. Args: sr_obj (``SeqRecord``) : instantiated Biopython ``SeqRecord`` object feature_types (list, optional) : list of feature types (e.g., ['gene', 'CDS']) qualifier_regexs (dict, optional) : dict of <field name>: <value regex> entries Returns: Filtered list of `SeqRecord` objects Raises: None Examples: Return a list of all ``SeqFeature`` objects from ``gb_rec`` that are of type 'mRNA' or 'CDS':: >>>filterFeatures(gb_rec, ['mRNA', 'CDS']) Return a list of all ``SeqFeature`` objects from ``gb_rec`` that are of type 'mRNA' or 'CDS' and that additionally have the qualifier field 'gene' with a value that matches the regular expression 'ubc.*':: >>>filterFeatures(gb_rec, ['gene', 'CDS'], {'gene': 'ubc.*'}) The latter example would match the following genbank records:: CDS join(54..567,789..1254) /gene="ubc42" /product="ubiquitin conjugating enzyme" /function="cell division control" CDS join(54..567,789..1254) /gene="ubc51" /product="ubiquitin conjugating enzyme" /function="cell division control" """ qualifier_regexs = qualifier_regexs or {} features = sr_obj.features def _featureFilter(feature): if feature_types is not None and feature.type not in feature_types: return False for feat_key, feat_value_re in qualifier_regexs.items(): q_values = feature.qualifiers.get(feat_key, None) if q_values is None: return False for v in q_values: if re.search(feat_value_re, v) is None: return False return True return filter(_featureFilter, features) def findBorders(sr_obj, feature_types=None, qualifier_regexs=None, strand_specific=False): """Filter a ``SeqFeature`` list and find the border indices of its members. See :func:`filterFeatures` for explanation of filtering functionality. Args: sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object feature_types (list, optional) : list of feature types (e.g., ['gene', 'CDS']) qualifier_regexs (list, optional) : dict of <field name>: <value regex> entries strand_specific (list, optional) : boolean determining whether separate lists should be returned for each strand (fwd / rev) Returns: List(s) of (<idx>, <1 if rising edge, 0 if falling edge>) tuples. Raises: None """ filtered_features = filterFeatures(sr_obj, feature_types, qualifier_regexs) if strand_specific: fwd_feat_list = [] rev_feat_list = [] else: feat_list = [] for feat in filtered_features: if strand_specific: if feat.location.strand == -1: feat_list = rev_feat_list else: feat_list = fwd_feat_list feat_list.append((feat.location.start, 1)) feat_list.append((feat.location.end, 0)) if strand_specific: return fwd_feat_list, rev_feat_list else: return feat_list def buildBorderLUT(sr_obj, feature_types=None, qualifier_regexs=None, strand_specific=False): """Filter a ``SeqRecord``'s features and build a binary LUT of border edges. See :func:`filterFeatures` for explanation of filtering functionality. Args: sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object feature_types (list, optional) : list of feature types (e.g., ['gene', 'CDS']) qualifier_regexs (list, optional) : dict of <field name>: <value regex> entries strand_specific (list, optional) : boolean determining whether separate lists should be returned for each strand (fwd / rev) Returns: Binary bitarray(s) (``bitarray.bitarray``) indicating the indices of feature borders (border indices have a value of 1). Strand-specific bitarrays are returned if ``strand_specific`` is ``True``. Raises: None """ if strand_specific: fwd_feat_list, rev_feat_list = findBorders(sr_obj, feature_types, qualifier_regexs, strand_specific) fwd_lut = bitarray.bitarray(len(sr_obj.seq)) fwd_lut.setall(0) rev_lut = bitarray.bitarray(len(sr_obj.seq)) rev_lut.setall(0) for rec in fwd_feat_list: fwd_lut[rec[0]] = 1 for rec in rev_feat_list: rev_lut[rec[0]] = 1 return fwd_lut, rev_lut else: feat_list = findBorders(sr_obj, feature_types, qualifier_regexs, strand_specific) feat_lut = bitarray.bitarray(len(sr_obj.seq)) feat_lut.setall(0) for rec in feat_list: try: feat_lut[rec[0]] = 1 except IndexError: print('IndexError while generating border array {}'.format( rec[0])) return feat_lut def findAggregateBoundaries(sr_obj, feature_types=None, qualifier_regexs=None): """Determine the outermost border indices of a group of filtered features. See :func:`filterFeatures` for explanation of filtering functionality. Args: sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object feature_types (list, optional) : list of feature types (e.g., ['gene', 'CDS']) qualifier_regexs (list, optional) : dict of <field name>: <value regex> entries Returns: Tuple of (<min index>, <max index>) of the filtered features Raises: None For example, let's say your genbank file has the following features: synth_seg 1001..2000 /label="seg17_000" synth_seg 2001..3000 /label="seg17_001" synth_seg 3001..4000 /label="seg17_002" synth_seg 4001..5000 /label="seg18_000" Then the following call will produce this output:: >>>findAggregateBoundaries(sr, ['synth_seg'], {'label': r'seg17.*'}) (1001, 4000) """ filtered_features = list(filterFeatures(sr_obj, feature_types, qualifier_regexs)) if len(filtered_features) == 0: return None, None min_idx = len(sr_obj.seq) + 1 max_idx = -1 for ff in filtered_features: min_idx = min(int(ff.location.start), min_idx) max_idx = max(int(ff.location.end), max_idx) return min_idx, max_idx
Wyss/mascpcr
mascpcr/genbankfeatures.py
genbankfeatures.py
py
7,725
python
en
code
2
github-code
6
41439897989
from django.test import TestCase from django.urls.base import reverse from .models import Provinces # Create your tests here. class ProvincesModelTests(TestCase): def test_get_one_province(self): """if not province exist with passed id, return appropiate message""" province = Provinces.objects.create(id=1, name='Santa Fe', population=23142323, density=5.8, surface=3252352) response = self.client.get(reverse('provinciasCrud:get_one_province', args=[province.id])) print(response) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Santa Fe') # self.assertQuerysetEqual(response.context['province'], {}) def test_get_all_provinces(self): """if provinces array is empty, return appropiate message""" province = Provinces.objects.create(id=1, name='Santa Fe', population=23142323, density=5.8, surface=3252352) response = self.client.get(reverse('provinciasCrud:get_provinces')) print(response) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Santa Fe')
matiasfeliu92/crud_provincias
server/provinciasCrud/tests.py
tests.py
py
1,119
python
en
code
1
github-code
6
24199771377
# -*- coding: utf-8 -*- """ Created on Thu May 30 16:32:39 2019 @author: Administrator """ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = {} for i in strs: key = tuple(sorted(i)) if key not in d.keys(): d[key] = [i] else: d[key].append(i) return list(d.values())
AiZhanghan/Leetcode
code/49. Group Anagrams.py
49. Group Anagrams.py
py
403
python
en
code
0
github-code
6
42126550080
class Student: def __init__(self, name, age): self.name = name self.age = age def display(self): print("Name:", self.name, " and age:", self.age) class laptop: def __init__(self, brand, ram): self.brand = brand self.ram = ram def display(self): print("Laptop brand:", self.brand, " and Ram:", self.ram) s1 = Student('arun', 26) s2 = Student('navin', 21) s1.display() s2.display() lap1 = s1.laptop("Sony", 8) lap2 = s2.laptop("Mac", 16) lap1.display() lap2.display()
Robinrrr10/python
src/innerClass.py
innerClass.py
py
597
python
en
code
0
github-code
6
34221019372
""" UP42 authentication mechanism and base requests functionality """ import json from pathlib import Path from typing import Dict, List, Optional, Union import requests import requests.exceptions from tenacity import ( Retrying, wait_fixed, wait_random_exponential, stop_after_attempt, retry_if_exception, retry_if_exception_type, retry, ) from up42.utils import get_logger logger = get_logger(__name__) class retry_if_429_error(retry_if_exception): """ Adapted from https://github.com/alexwlchan/handling-http-429-with-tenacity Retry strategy that retries if the exception is an ``HTTPError`` with a 429 status code. """ def __init__(self): def is_http_429_error(exception): return ( isinstance(exception, requests.exceptions.HTTPError) and exception.response.status_code == 429 ) super().__init__(predicate=is_http_429_error) class Auth: def __init__( self, cfg_file: Union[str, Path] = None, project_id: str = None, project_api_key: str = None, **kwargs, ): """ The Auth class handles the authentication with UP42. Info: Authentication is possible via the credentials of a specific project (project_id & project_api_key). To get your **project id** and **project api key**, follow the instructions in the docs authentication chapter. Args: cfg_file: File path to the cfg.json with {project_id: "...", project_api_key: "..."}. project_id: The unique identifier of the project. project_api_key: The project-specific API key. """ self.cfg_file = cfg_file self.project_id = project_id self.project_api_key = project_api_key self.workspace_id: Optional[str] = None try: self.env: str = kwargs["env"] except KeyError: self.env = "com" try: self.authenticate: bool = kwargs["authenticate"] except KeyError: self.authenticate = True try: self.retry: bool = kwargs["retry"] except KeyError: self.retry = True try: self.get_info: bool = kwargs["get_info"] except KeyError: self.get_info = True if self.authenticate: self._find_credentials() self._get_token() self._get_workspace() logger.info("Authentication with UP42 successful!") def __repr__(self): return f"UP42ProjectAuth(project_id={self.project_id}, env={self.env})" def _find_credentials(self) -> None: """ Sources the project credentials from a provided config file, error handling if no credentials are provided in arguments or config file. """ if self.project_id is None or self.project_api_key is None: if self.cfg_file is None: raise ValueError( "Provide project_id and project_api_key via arguments or config file!" ) # Source credentials from config file. try: with open(self.cfg_file) as src: config = json.load(src) try: self.project_id = config["project_id"] self.project_api_key = config["project_api_key"] except KeyError as e: raise ValueError( "Provided config file does not contain project_id and " "project_api_key!" ) from e logger.info("Got credentials from config file.") except FileNotFoundError as e: raise ValueError("Selected config file does not exist!") from e elif all( v is not None for v in [self.cfg_file, self.project_id, self.project_api_key] ): logger.info( "Credentials are provided via arguments and config file, " "now using the argument credentials." ) def _endpoint(self) -> str: """Gets the endpoint.""" return f"https://api.up42.{self.env}" # pylint: disable=assignment-from-no-return def _get_token(self): try: self._get_token_project() except requests.exceptions.HTTPError as err: raise ValueError( "Authentication was not successful, check the provided project credentials." ) from err def _get_token_project(self) -> None: """Project specific authentication via project id and project api key.""" url = ( f"https://{self.project_id}:{self.project_api_key}@api.up42.{self.env}" f"/oauth/token" ) payload = "grant_type=client_credentials" headers = { "Content-Type": "application/x-www-form-urlencoded", "cache-control": "no-cache", } token_response = requests.request("POST", url, data=payload, headers=headers) token_response.raise_for_status() token = json.loads(token_response.text) # pylint: disable=attribute-defined-outside-init self.token = token["data"]["accessToken"] def _get_workspace(self) -> None: """Get workspace id belonging to authenticated project.""" url = f"https://api.up42.{self.env}/projects/{self.project_id}" resp = self._request("GET", url) self.workspace_id = resp["data"]["workspaceId"] # type: ignore @staticmethod def _generate_headers(token: str) -> Dict[str, str]: version = ( Path(__file__) .resolve() .parent.joinpath("_version.txt") .read_text(encoding="utf-8") ) headers = { "Content-Type": "application/json", "Authorization": f"Bearer {token}", "cache-control": "no-cache", "X-UP42-info": f"python/{version}", } return headers # pylint: disable=dangerous-default-value @retry( retry=retry_if_429_error(), wait=wait_random_exponential(multiplier=0.5, max=180), reraise=True, ) def _request_helper( self, request_type: str, url: str, data: Dict = {}, querystring: Dict = {} ) -> requests.Response: """ Helper function for the request, running the actual request with the correct headers. Args: request_type: 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' url: The requests url. data: The payload, e.g. dictionary with job parameters etc. querystring: The querystring. Returns: The request response. """ headers = self._generate_headers(self.token) if querystring == {}: response = requests.request( method=request_type, url=url, data=json.dumps(data), headers=headers ) else: response = requests.request( method=request_type, url=url, data=json.dumps(data), headers=headers, params=querystring, ) logger.debug(response) logger.debug(data) response.raise_for_status() return response def _request( self, request_type: str, url: str, data: Union[Dict, List] = {}, querystring: Dict = {}, return_text: bool = True, ) -> Union[str, Dict, requests.Response]: """ Handles retrying the request and automatically gets a new token if the old is invalid. Retry is enabled by default, can be set to False as kwargs in Api(). Args: request_type: 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' url: The url to request. data: The payload, e.g. dictionary with job parameters etc. querystring: The querystring. return_text: If true returns response text/json, false returns response. retry: If False, after 5 minutes and invalid token will return 401 errors. Returns: The API response. """ try: if self.retry: retryer = Retrying( stop=stop_after_attempt(1), # TODO: Find optimal retry solution wait=wait_fixed(0), retry=( retry_if_exception_type(requests.exceptions.HTTPError) | retry_if_exception_type(requests.exceptions.ConnectionError) ), after=self._get_token(), reraise=True, ) response = retryer( self._request_helper, request_type, url, data, querystring ) else: response = self._request_helper(request_type, url, data, querystring) # type: ignore except requests.exceptions.RequestException as err: # Base error class err_message = json.loads(err.response.text)["error"] if "code" in err_message: err_message = f"{err_message['code']} Error - {err_message['message']}!" logger.error(err_message) raise requests.exceptions.RequestException(err_message) from err # Handle response text. if return_text: try: response_text = json.loads(response.text) except json.JSONDecodeError: # e.g. JobTask logs are str format. response_text = response.text # Handle api error messages here before handling it in every single function. # pylint: disable=no-else-raise try: if response_text["error"] is not None and response_text["data"] is None: raise ValueError(response_text["error"]) else: return response_text except ( KeyError, TypeError, ): # Catalog search, JobTask logs etc. does not have the usual {"data":"", # "error":""} format. return response_text else: # E.g. for DELETE return response
stasSajinDD/up42-py
up42/auth.py
auth.py
py
10,421
python
en
code
null
github-code
6
5243707290
#!/usr/bin/env python3 import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA NUMBER_OF_WORDS = 50 file_path = sys.argv[1] lines = pd.read_table(file_path, header=None, delim_whitespace=True) lines = lines.sample(NUMBER_OF_WORDS).reset_index(drop=True) words = lines.iloc[:, 0] vectors = lines.iloc[:, 1:] pca = PCA(n_components=2) vecs_transformed = pca.fit_transform(vectors) plt.figure(figsize=(16, 16)) for i in range(len(words)): (x, y) = [float(val) for val in vecs_transformed[i]] plt.scatter(x, y) plt.annotate(words[i], xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.show() plt.savefig('evaluation.png')
data-science-and-big-data-analytics/data-science-frameworks
FastText/evaluation.py
evaluation.py
py
819
python
en
code
2
github-code
6
32169695426
import requests from .models import Item import datetime from django.utils.timezone import make_aware def fetch_items(): conn = requests.get('https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty') res = sorted(conn.json()) return list(reversed(res))[:5] # top 5 stories def fetch_item_by_id(item): int_item = int(item) conn = requests.get(f'https://hacker-news.firebaseio.com/v0/item/{int_item}.json?print=pretty') res = conn.json() if res['type'] == 'job': print(res) return res def add_kid(kid): comment = fetch_item_by_id(kid) parent = Item.objects.get(id=comment['parent']) if 'deleted'in comment or 'dead' in comment: return obj = get_obj(comment) Item.objects.create(**obj, parent=parent) return obj def get_obj(detail): type = detail.get("type") id = str(detail.get("id")) by = detail.get("by") timestamp = datetime.datetime.fromtimestamp(detail.get("time")) time = make_aware(timestamp) url = detail.get("url") title = detail.get("title") text = detail.get("text") descendants = detail.get("descendants", 0) score = detail.get("score", 0) obj = { "type": type, "id": id, "by": by, "time": time, "url": url, "title": title, "text": text, "score": score, "fetched": True, "descendants": descendants } return obj def add_to_db(): items = fetch_items() for single in items: details = fetch_item_by_id(single) if details['type'] == 'comment' or 'deleted' in details or 'dead' in details: return if details['type'] == 'job': print(details) if not Item.objects.filter(id=details['id']).exists(): item_obj = get_obj(details) Item.objects.create(**item_obj) if 'kids' in details: kids = details['kids'] for kid in kids: add_kid(kid)
Alisjj/HackerNews
newsList/fetcher.py
fetcher.py
py
2,008
python
en
code
0
github-code
6
35241998177
from flask import Flask #from flask_cors import CORS, cross_origin from pymongo import MongoClient connection = MongoClient("mongodb://localhost:27017/") def create_mongodatabase(): try: dbnames = connection.database_names() if 'cloud_native' not in dbnames: db = connection.cloud_native.users db_tweets = connection.cloud_native.tweets db_api = connection.cloud_native.apirelease db.insert({ "email": "[email protected]", "id": 33, "name": "Eric stromberg", "password": "eric@123", "username": "eric.strom" }) db_tweets.insert({ "body": "New blog post, Launch your app with the AWS StartupKit! # AWS", "id": 18, "timestamp": "2017-03-11T06:39:40Z", "tweetedby": "eric.strom" }) db_api.insert({ "buildtime": "2017-01-01 10:00:00", "links": "/api/v1/users", "methods": "get, post, put, delete", "version": "v1" }) db_api.insert({ "buildtime": "2017-02-11 10:00:00", "links": "api/v2/tweets", "methods": "get, post", "version": "2017-01-10 10:00:00" }) print("Database Initialize completed!") else: print("Database already Initialized!") except: print(" Database creation failed!!") app = Flask(__name__) #app.config['SERVER_NAME'] = 'enrg_sy:5000' #app.secret_key = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KTq' #CORS(app) from flask import jsonify import json import sqlite3 from flask import make_response @app.errorhandler(404) def resource_not_found(error): return make_response(jsonify({'error': 'Resource not found1!'}), 404) @app.route("/performance") def get_perf_counter(): strCount1 = "<div style=""position:relative;width:100%;height:60%"">" \ "<iframe width=""384"" height=""216""" \ " src=""https://insights-embed.newrelic.com/embedded_widget/y8OoxNBFXRR6yDOsQCIDGPlTkEA6LnJi"" frameborder=""0""" \ " style=""position:absolute;width:100%;height:100%""></iframe></div>" \ "<div id = ""we"" style=""position:relative;width:100%;height:60%"">" \ " <iframe width=""384"" height=""216"" " \ " src=""https://insights-embed.newrelic.com/embedded_widget/35HhAcTJ1y3KgDpbnSDmcI8y_5R01b1n"" frameborder=""0""" \ " style=""position:absolute;width:100%;height:100%""></iframe></div>" return strCount1 @app.route("/api/v1/info") def home_index(): api_list = [] db = connection.cloud_native.apirelease for row in db.find(): api_list.append(str(row)) return jsonify({'api_version': api_list}), 200 @app.route('/api/v1/users', methods=['GET']) def get_users(): return list_users() def list_users(): api_list=[] db = connection.cloud_native.users for row in db.find(): api_list.append(str(row)) return jsonify({'user_list': api_list}) @app.route('/api/v1/users/<int:user_id>', methods=['GET']) def get_user(user_id): return list_user(user_id) def list_user(user_id): api_list=[] db = connection.cloud_native.users for i in db.find({'id':user_id}): api_list.append(str(i)) if api_list == []: abort(404) return jsonify({'user_details':api_list}) @app.errorhandler(400) def invalid_request(error): return make_response(jsonify({'error': 'Bad Request1'}), 400) @app.errorhandler(401) def invalid_request1(error): return make_response(jsonify({'error': 'Bad Request2'}), 400) @app.errorhandler(405) def invalid_request2(error): return make_response(jsonify({'error': 'Bad Request5'}), 400) @app.errorhandler(403) def invalid_request3(error): return make_response(jsonify({'error': 'Bad Request4'}), 400) from flask import request, abort import random @app.route('/api/v1/users', methods=['POST']) def create_user(): if not request.json or not 'username' in request.json or not \ 'email' in request.json or not 'password' in request.json: abort(400) user = { 'username': request.json['username'], 'email': request.json['email'], 'name': request.json['name'], 'password': request.json['password'], 'id': random.randint(1, 1000) } return jsonify({'status': add_user(user)}), 201 def add_user(new_user): api_list=[] print(new_user) db = connection.cloud_native.users user = db.find({'$or':[{"username":new_user['username']}, {"email":new_user['email']}]}) for i in user: print(str(i)) api_list.append(str(i)) if api_list == []: db.insert(new_user) return "Succes" else: abort(409) @app.route('/api/v1/users', methods=['DELETE']) def delete_user(): if not request.json or not 'username' in request.json: abort(400) user = request.json['username'] return jsonify({'status': del_user(user)}), 200 def del_user(del_user): db = connection.cloud_native.users api_list = [] for i in db.find({'username':del_user}): api_list.append(str(i)) if api_list == []: abort(404) else: db.remove({'username':del_user}) return "Succes" @app.route('/api/v1/users/<int:user_id>', methods=['PUT']) def update_user(user_id): print(user_id) user = {} user['id'] = user_id key_list = request.json.keys() for i in key_list: user[i] = request.json[i] return jsonify({'status': upd_user(user)}), 200 def upd_user(user): api_list=[] print(user) db_user = connection.cloud_native.users users = db_user.find_one({"id":user['id']}) for i in users: api_list.append(str(i)) if api_list == []: abort(409) else: db_user.update({'id':user['id']},{'$set': user},upsert=False) return "Succes" @app.route('/api/v2/tweets', methods=['GET']) def get_tweets(): return list_tweets() def list_tweets(): api_list = [] db = connection.cloud_native.tweets for row in db.find(): api_list.append(str(row)) return jsonify({'tweets_list': api_list}) import time @app.route('/api/v2/tweets', methods=['POST']) def add_tweets(): user_tweet = {} if not request.json or not 'username' in request.json or not 'Body' in request.json: abort(400) user_tweet['id'] = request.json['id'] user_tweet['tweetedby'] = request.json['username'] user_tweet['body'] = request.json['Body'] user_tweet['created_at'] = time.strftime( "%Y-%m-%dT%H:%M:%SZ", time.gmtime()) print(user_tweet) return add_tweet(user_tweet) def add_tweet(new_tweets): api_list = [] db_users = connection.cloud_native.users db_tweets = connection.cloud_native.tweets print(new_tweets) users = db_users.find({"username":new_tweets['tweetedby']}) for user in users: api_list.append(str(user)) if api_list == []: abort(400) else: db_tweets.insert(new_tweets) return "Succes" #sdfsd @app.route('/api/v2/tweets/<int:id>', methods=['GET']) def get_tweet(id): return list_tweet(id) def list_tweet(user_id): db = connection.cloud_native.tweets api_list = [] tweets = db.find({'id':user_id}) for tweet in tweets: api_list.append(str(tweet)) if api_list == []: abort(404) else: return jsonify({"tweet":api_list}) from flask import render_template, make_response, url_for, request, redirect, session def sumSessionCounter(): try: session['counter'] += 1 except KeyError: session['counter'] = 1 @app.route('/') def main(): sumSessionCounter() return render_template('main.html') @app.route('/addname') def addname(): if request.args.get('yourname'): session['name'] = request.args.get('yourname') # And then redirect the user to the main page return redirect(url_for('main')) else: return render_template('addname.html', session=session) @app.route('/adduser') def adduser(): return render_template('adduser.htm') @app.route('/addtweets') def addtweets(): return render_template('addtweets.htm') @app.route('/clear') def clearsession(): # Clear the session session.clear() # Redirect the user to the main page return redirect(url_for('main')) @app.route('/set_cookie') def cookie_insertion(): redirect_to_main = redirect('/') response = app.make_response(redirect_to_main) response.set_cookie('cookie_name2', value='qwqwqw') return response @app.route('/index') def index(): return render_template('index.html') if __name__ == "__main__": create_mongodatabase() app.run(host='0.0.0.0', port=5000, debug=True)
AnatolyS1/Cloud-Native-Python
app.py
app.py
py
8,921
python
en
code
0
github-code
6
21365592875
from __future__ import print_function import sys import os from os.path import exists, dirname import numpy as np import pickle import json import time import six if six.PY3: import _thread as thread from queue import Queue else: import thread from Queue import Queue from collections import OrderedDict from datetime import datetime from sklearn.metrics import roc_auc_score import multiprocessing import paddle.distributed as dist from glob import glob from paddle import fluid from pahelix.utils.splitters import \ RandomSplitter, IndexSplitter, ScaffoldSplitter, RandomScaffoldSplitter from pahelix.datasets import * def get_downstream_task_names(dataset_name, data_path): """ Get task names of downstream dataset """ if dataset_name == 'bace': task_name = get_default_bace_task_names() elif dataset_name == 'bbbp': task_name = get_default_bbbp_task_names() elif dataset_name == 'clintox': task_name = get_default_clintox_task_names() elif dataset_name == 'hiv': task_name = get_default_hiv_task_names() elif dataset_name == 'muv': task_name = get_default_muv_task_names() elif dataset_name == 'sider': task_name = get_default_sider_task_names() elif dataset_name == 'tox21': task_name = get_default_tox21_task_names() elif dataset_name == 'toxcast': task_name = get_default_toxcast_task_names(data_path) elif dataset_name == 'esol': return get_default_esol_task_names() elif dataset_name == 'freesolv': return get_default_freesolv_task_names() elif dataset_name == 'lipophilicity': return get_default_lipophilicity_task_names() else: raise ValueError('%s not supported' % dataset_name) return task_name def get_dataset(dataset_name, data_path, task_names): """Return dataset according to the ``dataset_name``""" if dataset_name == 'bace': dataset = load_bace_dataset(data_path, task_names) elif dataset_name == 'bbbp': dataset = load_bbbp_dataset(data_path, task_names) elif dataset_name == 'clintox': dataset = load_clintox_dataset(data_path, task_names) elif dataset_name == 'hiv': dataset = load_hiv_dataset(data_path, task_names) elif dataset_name == 'muv': dataset = load_muv_dataset(data_path, task_names) elif dataset_name == 'sider': dataset = load_sider_dataset(data_path, task_names) elif dataset_name == 'tox21': dataset = load_tox21_dataset(data_path, task_names) elif dataset_name == 'toxcast': dataset = load_toxcast_dataset(data_path, task_names) elif dataset_name == 'pcba': dataset = load_pcba_dataset(data_path, task_names) elif dataset_name == 'esol': dataset = load_esol_dataset(data_path, task_names) elif dataset_name == 'freesolv': dataset = load_freesolv_dataset(data_path, task_names) elif dataset_name == 'lipophilicity': dataset = load_lipophilicity_dataset(data_path, task_names) elif dataset_name == 'qm7': dataset = load_qm7_dataset(data_path, task_names) elif dataset_name == 'qm8': dataset = load_qm8_dataset(data_path, task_names) elif dataset_name == 'qm9': dataset = load_qm9_dataset(data_path, task_names) elif dataset_name == 'qm9_gdb': dataset = load_qm9_gdb_dataset(data_path, task_names) else: raise ValueError('%s not supported' % dataset_name) return dataset def get_dataset_stat(dataset_name, data_path, task_names): """tbd""" if dataset_name == 'esol': return get_esol_stat(data_path, task_names) elif dataset_name == 'freesolv': return get_freesolv_stat(data_path, task_names) elif dataset_name == 'lipophilicity': return get_lipophilicity_stat(data_path, task_names) elif dataset_name == 'qm7': return get_qm7_stat(data_path, task_names) elif dataset_name == 'qm8': return get_qm8_stat(data_path, task_names) elif dataset_name == 'qm9': return get_qm9_stat(data_path, task_names) elif dataset_name == 'qm9_gdb': return get_qm9_gdb_stat(data_path, task_names) else: raise ValueError(dataset_name) def create_splitter(split_type): """Return a splitter according to the ``split_type``""" if split_type == 'random': splitter = RandomSplitter() elif split_type == 'index': splitter = IndexSplitter() elif split_type == 'scaffold': splitter = ScaffoldSplitter() elif split_type == 'random_scaffold': splitter = RandomScaffoldSplitter() else: raise ValueError('%s not supported' % split_type) return splitter def calc_rocauc_score(labels, preds, valid): """compute ROC-AUC and averaged across tasks""" if labels.ndim == 1: labels = labels.reshape(-1, 1) preds = preds.reshape(-1, 1) rocauc_list = [] for i in range(labels.shape[1]): c_valid = valid[:, i].astype("bool") c_label, c_pred = labels[c_valid, i], preds[c_valid, i] #AUC is only defined when there is at least one positive data. if len(np.unique(c_label)) == 2: rocauc_list.append(roc_auc_score(c_label, c_pred)) print('Valid ratio: %s' % (np.mean(valid))) print('Task evaluated: %s/%s' % (len(rocauc_list), labels.shape[1])) if len(rocauc_list) == 0: raise RuntimeError("No positively labeled data available. Cannot compute ROC-AUC.") return sum(rocauc_list)/len(rocauc_list) def calc_rmse(labels, preds): """tbd""" return np.sqrt(np.mean((preds - labels) ** 2)) def calc_mae(labels, preds): """tbd""" return np.mean(np.abs(preds - labels)) def exempt_parameters(src_list, ref_list): """Remove element from src_list that is in ref_list""" res = [] for x in src_list: flag = True for y in ref_list: if x is y: flag = False break if flag: res.append(x) return res def mkdir(path): path = path.strip() path = path.rstrip("\\") isExists = os.path.exists(path) if not isExists: os.makedirs(path) return True else: return False def avg_split_list(listTemp, n): twoList = [[] for i in range(n)] for i, e in enumerate(listTemp): twoList[i % n].append(e) return twoList def load_pkls_to_list(args): fid, pkl_path = args if (pkl_path.endswith(".pkl")): pkl = open(pkl_path, "rb") data = pickle.load(pkl) if fid % 10 == 0: print(" ", fid, end=", ") return data def get_pickle_files_list(path): # traversal directory files_list = [] for root, dirs, files in os.walk(path): for name in files: if name.endswith(".pkl"): files_list.append(os.path.join(root, name)) files_list.sort() return files_list """ Load data, build dataset list with InMemoryDataset, each line is the smile of a molecular """ def load_smiles_to_dataset(data_path): """tbd""" files = sorted(glob('%s/*' % data_path)) print("files:", files) data_list = [] for file in files: with open(file, 'r') as f: tmp_data_list = [line.strip() for line in f.readlines()] data_list.extend(tmp_data_list) dataset = InMemoryDataset(data_list=data_list) return dataset def get_steps_per_epoch(args): """tbd""" # add as argument if args.dataset == 'zinc': train_num = int(20000000 * (1 - args.test_ratio)) else: raise ValueError(args.dataset) # if args.DEBUG: # train_num = 100 steps_per_epoch = int(train_num / args.batch_size) if args.distributed: steps_per_epoch = int(steps_per_epoch / dist.get_world_size()) return steps_per_epoch
liyishuilys/SMPT
src/utils.py
utils.py
py
7,884
python
en
code
0
github-code
6
31344968208
from tkinter import * import tkinter, threading from tkinter import messagebox as tmsg from tkinter import ttk import random import datetime import imageio import time from PIL import Image, ImageTk import smtplib as s import config root1 = Tk() root1.geometry("1208x830") root1.wm_iconbitmap("Artboard 1.ico") root1.minsize(1208, 830) root1.maxsize(1208, 830) root1.title("RYOCO TOURS© 2021") video_name = "video1.mp4" #This is your video file path video = imageio.get_reader(video_name) def dr1(): time.sleep(2) root1.destroy() def login_window(): root2 =Toplevel() # global dr1, root3 root2.geometry("1202x802") root2.minsize(1202, 802) root2.maxsize(1202, 802) root2.wm_iconbitmap("Artboard 1.ico") root2.title("RYOCO SIGNIN") load = Image.open("LOGIN1.png") render = ImageTk.PhotoImage(load) jpg = Label(root2, image=render) jpg.place(x=0, y=0) #def statusr1(): # for i in range(2): # statusvar.set("Busy.") # statusbar.update() # # time.sleep(0.2) # statusvar.set("Busy..") # statusbar.update() # # time.sleep(0.2) # statusvar.set("Busy...") # statusbar.update() # # time.sleep(0.2) # statusvar.set("Busy....") # statusbar.update() # # time.sleep(0.2) # x = 0 # for i in range(101): # statusvar.set(f"LOADING {x}%") # statusbar.update() # time.sleep(0.0000001) # x += 1 # # statusvar.set("READY TO USE") # statusbar.update() # time.sleep(0.5) # statusvar.set("PROCEED ENTERING YOUR DATA\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRYOCO TOURS© 2021") def register(): with open("ryoco_credentials.txt", 'r') as l: m = l.read() l.close() if reg_name_entry.get() == "" or reg_cnic_entry.get() == '' or reg_contact_entry == "" or reg_email_entry == "" or reg_password_entry == '' or reg_username_entry == '': tmsg.showerror('ENTRY INVALID', 'PLEASE ENTER COMPLETE DETAILS!', parent=root2) elif len(reg_cnic_entry.get()) != 13: tmsg.showerror('ENTRY INVALID', 'CNIC NOT VALID!', parent=root2) elif len(reg_contact_entry.get()) != 11: tmsg.showerror('ENTRY INVALID', 'CONTACT NOT VALID!', parent=root2) # elif reg_username_entry in m: # tmsg.showerror('ENTRY INVALID', 'USERNAME ALREADY REGISTERED!', parent=root2) else: a = tmsg.showinfo("Registeration Successful", "Your information has been registered!", parent=root2) print(f''' ====================================================================================== First Name: {reg_name_entry.get()} CNIC No : \t {reg_cnic_entry.get()} Contact: \t {reg_contact_entry.get()} E-mail: \t {reg_email_entry.get()} \nCONFIDENTIAL DETAILS username:\t {reg_username_entry.get()}' Password: {reg_password_entry.get()} ''') with open(f"{reg_username_entry.get()}_Record.txt", "a") as f: try: f.write(f''' ========================================================================= First Name: {reg_name_entry.get()} CNIC No : \t {reg_cnic_entry.get()} Contact: \t {reg_contact_entry.get()} E-mail: \t {reg_email_entry.get()} \nCONFIDENTIAL DETAILS username:\t {reg_username_entry.get()} Password: {reg_password_entry.get()} ''') f.close() except: pass with open("ryoco_credentials.txt", 'a') as j: j.write(f"{reg_username_entry.get()}:{reg_password_entry.get()}\n") j.close() def login(): with open("ryoco_credentials.txt", 'r') as f: e = f.read().splitlines() f.close() usernames = [] passwords = [] for items in e: e1 = items.split(":")[0] e2 = items.split(":")[1] usernames.insert(1, e1) passwords.insert(1, e2) if username_entry.get() not in usernames: tmsg.showerror("ERROR", "INVALID USERNAME", parent=root2) elif password_entry.get() not in passwords: tmsg.showerror("ERROR", "INVALID PASSWORD", parent=root2) else: global render1 c = tmsg.showinfo("LOGIN SUCCESSFUL", "LOGIN SUCCESSFUL",parent=root2) root3 = Toplevel() # root3.wm_iconbitmap("Artboard 1.ico") root3.geometry("1202x802") root3.minsize(1202, 802) root3.maxsize(1202, 802) root3.title("RYOCO BOOKING") def logout(): root3.destroy() login_window() def LOCAL(): tmsg.showinfo('DETAILS', ''' \nTOUR-I:\tKumrat Valley (3-Days) \t\t\tvia-Jahaz Band, Katora Lake \nTOUR-II:\tFairy Meadows (4-Days) \t\t\tvia-Naran, Hunza \nTOUR-III:\tHunza (5-Days) \t\t\tvia-Swat, Khunjerab''', parent=root3) def INTERNATIONAL(): tmsg.showinfo('DETAILS', ''' TOUR-I: (14-DAYS) Russia, Turkey, Dubai (290,000 PKR Per Person) TOUR-II: (5-DAYS) Mauritius Tour Package (225,000 PKR Per Person) TOUR-III: (05-Days) TURKEY (45,000 PKR Per Person)''', parent=root3) def dr3(): root3.destroy() root2.destroy() load1 = Image.open("booking1.png") render1 = ImageTk.PhotoImage(load1) jpg1 = Label(root3, image=render1) jpg1.place(x=0, y=0) # def statusr2(): # x = 0 # for i in range(101): # statusvar.set(f"LOADING {x}%") # statusbar.update() # time.sleep(0.000001) # x += 1 # statusvar.set("READY TO USE") # statusbar.update() # time.sleep(0.5) # statusvar.set(f"\t\t{date_of_booking}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRYOCO TOURS© 2021") def BOOK(): global listbox, login_window # ============================================ MAILING =========================================================== with open(f'{reg_username_entry}_trip.txt', "a") as b: try: b.write(f''' CLIENT: {reg_name_entry.get()} CNIC: {reg_cnic_entry.get()} USERNAME: {reg_username_entry.get()} PASSWORD: {reg_password_entry.get()} TOUR: {tour.get()} TYPE: {type.get()} DEPARTURE: {departure.get()} Time: {time_of_booking}, {date_of_booking}''') except: b.write(f''' TOUR: {tour.get()} TYPE: {type.get()} DEPARTURE: {departure.get()} Time: {time_of_booking}, {date_of_booking}''') b.close() with open(f'Ryoco_records.txt', "w") as e: try: e.write(f''' Dear MR/MRS.{reg_name_entry.get()}, CNIC NO. {reg_cnic_entry.get()} Your username is "{reg_username_entry.get()}" and password is "{reg_password_entry.get()}" Contact: {reg_contact_entry.get()} ---- Trip Details: TOUR: {tour.get()} TYPE: {type.get()} DEPARTURE: {departure.get()} Time: {time_of_booking}, {date_of_booking} YOUR TOUR HAS BEEN BOOKED, OUR ADMINISTRATION WILL CONTACT YOU SHORTLY. THANK YOU FOR TRUSTING US! :) Regards, RYOCO Tours(PVT), Limited. ''') except: print(username_entry.get()) e.write(f''' Dear MR/MRS.{username_entry.get()} Your username is "{username_entry.get()}" and password is "{password_entry.get()}" ---- Trip Details: TOUR: {tour.get()} TYPE: {type.get()} DEPARTURE: {departure.get()} Time: {time_of_booking}, {date_of_booking} YOUR TOUR HAS BEEN BOOKED, OUR ADMINISTRATION WILL CONTACT YOU SHORTLY. THANK YOU FOR TRUSTING US! :) Regards, RYOCO Tours(PVT), Limited. ''') e.close() if mail.get() == True: print('EMAIL SELECTED') with open('mailingaddress.txt', 'w') as t: t.write(f'{reg_email_entry.get()}') t.close() x = open('mailingaddress.txt', 'r') mailing = x.read() x.close() p = open('Ryoco_records.txt', 'r') contents = p.read() p.close() try: mailfrom = '[email protected]' mailto = mailing subject = 'RYOCO: BOOKING DETIALS' message = contents msg = 'Subject: {}\n\n{}'.format(subject, message) username = config.EMAIL_ADDRESS password = config.PASSWORD server = s.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(username, password) server.sendmail(mailfrom, mailto, msg) server.quit() print("Successfully mailed") except: print('Failed to mail details') else: print('EMAIL NOT SELECTED') listbox = Text(root3, height=2, width=15, bg='#6F4624', fg="white", font=("Montserrat", 18)) listbox.place(x=700, y=600) listbox.delete("1.0", END) if departure.get() == 'ISLAMABAD' and tour.get() == 'TOUR-I' and type.get() == 'local': TotalCost1 = int('11499') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-I' and type.get() == 'local': TotalCost1 = int('14999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-I' and type.get() == 'local': TotalCost1 = int('19999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') # =======================================TOUR-II============================================================= elif departure.get() == 'ISLAMABAD' and tour.get() == 'TOUR-II' and type.get() == 'local': TotalCost1 = int('14999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-II' and type.get() == 'local': TotalCost1 = int('15499') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-II' and type.get() == 'local': TotalCost1 = int('21999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') # ========================================= TOUR-III ======================================================= elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-III' and type.get() == 'local': TotalCost1 = int('19499') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-III' and type.get() == 'local': TotalCost1 = int('19999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-III' and type.get() == 'local': TotalCost1 = int('24999') if class1.get() == 'business': TotalCost1 += 5000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') # =========================================== INTERNATIONAL ============================================== # ==========================================TOUR-I======================================================== elif departure.get() == 'ISLAMABAD' and tour.get() == 'TOUR-I' and type.get() == 'international': TotalCost1 = int('299999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-I' and type.get() == 'international': TotalCost1 = int('294999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-I' and type.get() == 'international': TotalCost1 = int('289999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') # ==========================================TOUR-II======================================================== elif departure.get() == 'ISLAMABAD' and tour.get() == 'TOUR-II' and type.get() == 'international': TotalCost1 = int('234999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-II' and type.get() == 'international': TotalCost1 = int('229999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-II' and type.get() == 'international': TotalCost1 = int('224999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') # ==========================================TOUR-III======================================================== elif departure.get() == 'ISLAMABAD' and tour.get() == 'TOUR-III' and type.get() == 'international': TotalCost1 = int('54999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'LAHORE' and tour.get() == 'TOUR-III' and type.get() == 'international': TotalCost1 = int('49999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') elif departure.get() == 'KARACHI' and tour.get() == 'TOUR-III' and type.get() == 'international': TotalCost1 = int('44999') if class1.get() == 'business': TotalCost1 += 50000 Tax = int((TotalCost1 / 100) * 5) SubTotal1 = int(Tax + TotalCost1) print(f"Cost for trip: Rs{TotalCost1}(tax exclusive)") print(f'Total Cost: Rs{SubTotal1}') listbox.insert(END, f'Rs.{TotalCost1}/-\n+{Tax}/-(tax)') local_button = Radiobutton(root3, text="LOCAL", font=("Montserrat Black", 18, "italic"), variable=type, value="local", bg="#FFAA00", fg="#623D28") local_button.place(x=30, y=580) international_button = Radiobutton(root3, text="INTERNATIONAL", font=("Montserrat Black", 18, "italic"), variable=type, value="international", bg="#FFAA00", fg="#623D28") international_button.place(x=165, y=580) type_entry = ttk.Combobox(root3, width=50, textvariable=tour) type_entry['value'] = ('TOUR-I', 'TOUR-II', 'TOUR-III') type_entry.place(x=65, y=630) departure_entry = ttk.Combobox(root3, width=30, textvariable=departure) departure_entry['value'] = ('ISLAMABAD', 'LAHORE', 'KARACHI') departure_entry.place(x=186, y=665) economy_button = Radiobutton(root3, text="ECONOMY", font=("Montserrat Black", 18, "italic"), variable=class1, value="economy", bg="#FFAA00", fg="#623D28") economy_button.place(x=435, y=602) business_button = Radiobutton(root3, text="BUSINESS", font=("Montserrat Black", 18, "italic"), variable=class1, value="business", bg="#FFAA00", fg="#623D28") business_button.place(x=435, y=650) book_button = Button(root3, text="BOOK RIDE", relief=FLAT, bg="#FCD34B", fg="#7F7F7F", font=("TrashHand", 40), command=BOOK) book_button.place(x=985, y=490) listbox = Text(root3, height=2, width=15, bg='#6F4624', fg="white", font=("Montserrat", 18)) listbox.place(x=700, y=600) # listbox8.insert(END, time_of_booking) local_button = Button(root3, text="LOCAL ", width=35, relief=FLAT, bg="#EA7415", fg="#6F4624", font=("Bahnschrift Light", 25), command=LOCAL) local_button.place(x=15, y=724) international_button = Button(root3, text="INTERNATIONAL", width=33, relief=FLAT, bg="#EA7415", fg="#6F4624", font=("Bahnschrift Light", 25), command=INTERNATIONAL) international_button.place(x=585, y=724) mailcheck = Checkbutton(root3, text="EMAIL BOOKING INFO", variable=mail, bg="#FFAA00", font=("Consolas", 13)) mailcheck.place(x=980, y=665) logout_button = Button(root3, width=15, text="🔙 LOGOUT ", bg="#EA7415", font=("Montserrat SemiBold", 14),relief=FLAT,command=logout) logout_button.place(x=950, y=36) # statusvar = StringVar() # statusvar.set("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRYOCO TOURS© 2021") # statusbar = Label(root3, textvariable=statusvar, bg="#FEEEC6", relief=GROOVE, anchor=W) # statusbar.pack(side=BOTTOM, fill=X) # statusr2() def admin(): root4 = Toplevel() root4.geometry("1202x802") root4.minsize(1202, 802) root4.maxsize(1202, 802) root4.title("ADMIN CONSOLE") root2.destroy() root4.mainloop() # statusvar = StringVar() # statusvar.set("READY") # statusbar = Label(root2, textvariable=statusvar, bg="#FEEEC6", relief=GROOVE, anchor=W) # statusbar.pack(side=BOTTOM, fill=X) # ==========================================REGISTERIES======================================== reg_name_entry = StringVar() reg_cnic_entry = StringVar() reg_contact_entry = StringVar() reg_email_entry = StringVar() reg_username_entry = StringVar() reg_password_entry = StringVar() username_entry = StringVar() password_entry = StringVar() CNIC = StringVar() CNIC.set("0") # ================================================LOGIN================================================================= username_entryx = Entry(root2, width=23, bg="#F8C43A", textvariable=username_entry, font=("Gill Sans MT", 12)) username_entryx.place(x=985, y=667) password_entryx = Entry(root2, width=23, bg="#F8C43A", textvariable=password_entry, font=("Gill Sans MT", 12), show="*") password_entryx.place(x=985, y=720) # =============================================REGISERATION============================================================= reg_username_entryx = Entry(root2, width=25, bg="#F8C43A", textvariable=reg_username_entry, font=("Gill Sans MT", 12)) reg_username_entryx.place(x=275, y=669) reg_password_entryx = Entry(root2, width=25, bg="#F8C43A", textvariable=reg_password_entry, font=("Gill Sans MT", 12)) reg_password_entryx.place(x=275, y=723) reg_name_entryx = Entry(root2, width=25, bg="#F8C43A", textvariable=reg_name_entry, font=("Gill Sans MT", 12)) reg_name_entryx.place(x=275, y=408) reg_cnic_entryx = Entry(root2, width=36, bg="#F8C43A", textvariable=reg_cnic_entry, font=("Montserrat SemiBold", 12)) reg_cnic_entryx.place(x=80, y=500) reg_contact_entryx = Entry(root2, width=18, bg="#F8C43A", textvariable=reg_contact_entry, font=("Montserrat SemiBold", 12)) reg_contact_entryx.place(x=275, y=560) reg_email_entryx = Entry(root2, width=22, bg="#F8C43A", textvariable = reg_email_entry, font=("Consolas", 12)) reg_email_entryx.place(x=275, y=615) check = Radiobutton(root2, variable=CNIC, bg="#F7BA11", value="cnic") check.place(x=75, y=452) check1 = Radiobutton(root2, variable=CNIC, bg="#F7C235", value="passport") check1.place(x=235, y=452) login_button = Button(root2, width=16, text="LOGIN ", bg="#C6633C", font=("Montserrat SemiBold", 12), relief=FLAT, command=login) login_button.place(x=880, y=756) reg_button = Button(root2, width=16, text="REGISTER ", bg="#C6633C", font=("Montserrat SemiBold", 12), relief=FLAT, command=register) reg_button.place(x=164, y=756) # admin_button = Button(root2, width=16, text="ADMIN ", bg="#C6633C", font=("Montserrat SemiBold", 12), relief=FLAT, # command=admin) # admin_button.place(x=980, y=40) # statusr1() # ================================================ BOOKING TAB ========================================================= mail = IntVar() local = StringVar() international = StringVar() class1 = StringVar() type = StringVar() tour = StringVar() departure = StringVar() type.set('0') class1.set('0') root2.mainloop() try: dr1() except: pass def stream(label): for image in video.iter_data(): frame_image = ImageTk.PhotoImage(Image.fromarray(image)) label.config(image=frame_image) label.image = frame_image #====================================== win-0 ===================================== time_of_booking = (time.strftime("%I:%M:%S %p")) date_of_booking = (time.strftime("%d/%m/%Y")) def begin(): Button(text="BEGIN EXPLORING!", font=("TrashHand 29"), height=2, width=20, bg="#FFBB56", command=login_window, relief=FLAT).place(x=45, y=680) my_label = Label(root1) my_label.pack() thread = threading.Thread(target=stream, args=(my_label,)) thread.daemon = 1 thread.start() begin() root1.mainloop()
zuwanish/Tour-Management-System
MAIN PROJECT GUI BASED.py
MAIN PROJECT GUI BASED.py
py
30,680
python
en
code
0
github-code
6
71344208509
import turtle as turtle # Set up game screen turtle.title("Pong game") turtle.setup(400, 300) turtle.bgcolor("lightblue") welcome = turtle.Turtle() welcome.color("black") welcome.write("Welcome", align='center', font=("Arial", 40, "bold")) p1 = input("Enter player1 name: ") p2 = input("Enter player2 name: ") welcome.clear() welcome.hideturtle() border = turtle.Turtle() border.width(8) def draw_rec(linecolor, length1=800, length2=600): border.penup() border.goto(-400, -300) border.color(linecolor, "black") border.pendown() for i in range(2): border.forward(length1) border.left(90) border.forward(length2) border.left(90) border.begin_fill() draw_rec("orange") border.end_fill() border.hideturtle() # Left Paddle or Paddle 1 paddle1 = turtle.Turtle() paddle1.shape("square") paddle1.color("red") paddle1.shapesize(stretch_wid=5, stretch_len=1) paddle1.penup() paddle1.goto(-350, 0) paddle1.dy = 0 # Right paddle or paddle2 paddle2 = turtle.Turtle() paddle2.shape("square") paddle2.color("blue") paddle2.shapesize(stretch_len=1, stretch_wid=5) paddle2.penup() paddle2.goto(350, 0) paddle2.dy = 0 # Game Rules game_over = False winner = None points = { "player1": 0, "player2": 0 } game_rules = { "max_points": 3, "ball_speed": 3 } # Creating the Ball ball = turtle.Turtle() ball.shape("circle") ball.color("white") ball.penup() ball.goto(0, 0) ball.dx = 0.75 ball.dy = 0.75 ballspeed = 10 # Score display score_display = turtle.Turtle() score_display.color("white") score_display.penup() score_display.hideturtle() score_display.goto(0, 260) score_display.write(f"{p1}: 0 {p2}: 0", align="center", font=("Arial", 24, "bold")) # Function to move paddle1 up def paddle1_up(): paddle1.dy = 10 # Function to move paddle1 down def paddle1_down(): paddle1.dy = -10 # Function to move paddle2 up def paddle2_up(): paddle2.dy = 10 # Function to move paddle2 down def paddle2_down(): paddle2.dy = -10 def paddle1_stop(): paddle1.dy = 0 def paddle2_stop(): paddle2.dy = 0 # Logic for moving the paddles # Set up keyboard bindings turtle.listen() turtle.onkeypress(paddle1_up, "w") turtle.onkeypress(paddle1_down, "s") turtle.onkeypress(paddle2_up, "Up") turtle.onkeypress(paddle2_down, "Down") turtle.onkeyrelease(paddle1_stop, "w") turtle.onkeyrelease(paddle1_stop, "s") turtle.onkeyrelease(paddle2_stop, "Up") turtle.onkeyrelease(paddle2_stop, "Down") # Game mathematical logic # Game loop while not game_over: # Move paddles and ball paddle1.sety(paddle1.ycor() + paddle1.dy) paddle2.sety(paddle2.ycor() + paddle2.dy) ball.setx(ball.xcor() + ball.dx * ballspeed) ball.sety(ball.ycor() + ball.dy * ballspeed) # Check for game over conditions if points["player1"] == game_rules["max_points"]: game_over = True winner = p1 elif points["player2"] == game_rules["max_points"]: game_over = True winner = p2 # Check for ball collision with paddles if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle2.ycor() + 50 and ball.ycor() > paddle2.ycor() - 50): ball.setx(340) ball.dx *= -1 elif (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle1.ycor() + 50 and ball.ycor() > paddle1.ycor() - 50): ball.setx(-340) ball.dx *= -1 # Check for ball going off screen if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -1 points["player1"] += 1 elif ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 points["player2"] += 1 # Check for ball colliding with top or bottom of screen if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 elif ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 print(ball.dy) # Update score display score_display.clear() score_display.write( f"{p1}: {points['player1']} {p2}: {points['player2']}", align="center", font=("Arial", 24, "bold")) # Game over screen game_over_display = turtle.Turtle() game_over_display.color("white") game_over_display.penup() game_over_display.hideturtle() game_over_display.goto(0, 0) game_over_display.write("Game Over! {} wins!".format( winner), align="center", font=("Arial", 36, "normal")) turtle.done() # input("Press any key to exit")
SoumyadeepBera0230b/Pong_Game.github.io
pong.py
pong.py
py
4,418
python
en
code
0
github-code
6
26425792111
import pandas as pd import optuna import numpy as np from pathlib import Path import datetime import lightgbm import pickle from functools import partial import logging import argparse from clearml import Task WORK_DIR = Path(".") STUDY_PATH = WORK_DIR.joinpath( f'total_dataset_study_{datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")}' ) kvant = {7105: 10, 7103: 10, 7115: 5, 7101: 3, 7175: 3, 517: 10} price_df = pd.DataFrame({'game_code': [7105, 7103, 7115, 7101, 7175], 'price': [100, 100, 75, 50, 75]}) price_df = price_df.set_index('game_code') utilization_coefficients = {7105: 30, 7103: 35, 7115: 50, 7101: 50, 7175: 50, 517: 30} utilization_coefficients = {int(game): 100 / (100 - int(utilization_coefficients[game])) for game in list(utilization_coefficients.keys())} def mse(real, forecast): real_array = np.array(real) forecast_array = np.array(forecast) return np.mean(np.power((real_array - forecast_array), 2)) def smape(A, F): return 100 / len(A) * np.sum(2 * np.abs(F - A) / (np.abs(A) + np.abs(F))) def score(test, predict, active_ops=False, compare_with_real_sales=True): # return pandas df df = test.copy() df['predict'] = predict df.predict = df.predict.astype(int) if compare_with_real_sales: s = sales[sales.game_code.isin(list(test.game_code.unique()))] s = s[s.ds.isin(list(test.ds.unique()))] if 'value' in df.columns: df = df.drop(['value'], 1) df = df.merge(s[['game_code', 'ds', 'value', 'ops_id']], on=['game_code', 'ds', 'ops_id'], how='left') # outer df.value = df.value.fillna(0) df.predict = df.predict.fillna(0) # df = df.merge(sales) if active_ops: f = prod[prod.ds.isin(list(test.ds.values))] f = f[f.game_code.isin(list(test.game_code.values))] df = df.merge(f[['ops_id', 'ds', 'base_forecast', 'game_code']], on=['ops_id', 'ds', 'game_code'], how='outer') df['value'] = df.value.fillna(0) # business processing (add utilization and round to kvant) df['distributing'] = df.apply( lambda x: max(np.ceil( x.predict * utilization_coefficients[x.game_code] / kvant[x.game_code] ), 1) * kvant[x.game_code] , 1) df['plan_transfer'] = df.apply( lambda x: max(np.ceil( x.value * utilization_coefficients[x.game_code] / kvant[x.game_code] ), 1) * kvant[x.game_code] , 1) if active_ops: df['distributing'].loc[df.base_forecast.isna()] = 0 df['distributing'].loc[df.predict.isna()] = df.loc[df.predict.isna()].game_code.map(kvant) df['predict'].loc[df.base_forecast.isna()] = 0 df['predict'].loc[df.predict.isna()] = df.loc[df.predict.isna()].game_code.map(kvant) score_result = pd.concat( [ df.groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.value)], columns=['sales']) ), df.groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.predict)], columns=['origin_predict']) ), df.groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.distributing)], columns=['predict']) ), df.groupby(['game_code']).apply( lambda x: pd.DataFrame([len(x.predict)], columns=['ops_count']) ), df[df.value < df.predict].groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.predict - x.value)], columns=['origin_over_sales']) ), df[df.value > df.predict].groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.value - x.predict)], columns=['origin_lost_sales']) ), df.groupby(['game_code']).apply( lambda x: pd.DataFrame( [ sum( x[x.value > x.distributing].value - x[x.value > x.distributing].distributing ) / sum(x.value) * 100 ], columns=['lost_percent']) ), df.groupby(['game_code']).apply( lambda x: pd.DataFrame([100 - sum(x.value) / sum(x.distributing) * 100], columns=['util_coef']) ), df[df.value < df.distributing].groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.distributing - x.value)], columns=['over_sales']) ), df[df.plan_transfer < df.distributing].groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.distributing - x.plan_transfer)], columns=['over_plan_sales']) ), df[df.value > df.distributing].groupby(['game_code']).apply( lambda x: pd.DataFrame([sum(x.value - x.distributing)], columns=['lost_sales']) ) ], 1 ) # score_result = score_result.set_index('game_code') score_result = score_result.join(price_df, on='game_code', how='left') score_result['over_plan_losses'] = score_result['lost_sales'] * score_result['price'] + score_result[ 'over_plan_sales'] * 5 score_result['lost_sales_losses'] = score_result['lost_sales'] * score_result['price'] score_result['losses'] = score_result['lost_sales'] * score_result['price'] + score_result['over_sales'] * 5 return score_result def train_model(args, X, Y, params): """Train LightGBM model""" train_params = {key: value for key, value in params.items() if key != "max_bin"} if args and args.use_gpu: train_params["device"] = "gpu" train_params["gpu_device_id"] = 2 train_params["gpu_platform_id"] = 1 train_params["num_threads"] = 10 dataset = lightgbm.Dataset(X, Y, params={"max_bin": params["max_bin"]}) model = lightgbm.train(train_params, dataset) return model def scoring( trial: object, dss, args ) -> float: # Objective function for binary classification. # Calculates the average precision in holdout # for the model with picked parameters. # Args: # trial (object): a process of evaluating an objective funtion # x_train (pd.DataFrame, optional): features for training. Defaults to None. # y_train (pd.DataFrame, optional): labels for training. Defaults to None. # x_val (pd.DataFrame, optional): features for validation. Defaults to None. # y_val (pd.DataFrame, optional): labels for validation. Defaults to None. # Returns: # float: average precision on test data. trial_params = { "seed": 424242, "verbosity": -1, "num_gpu": 2, "n_estimators": trial.suggest_int("n_estimators", 100, 3500, step=100), # "max_depth": trial.suggest_int("max_depth", -1, 12), "max_bin": trial.suggest_int("max_bin", 63, 255, step=10), "learning_rate": trial.suggest_loguniform("learning_rate", 1e-3, 1e-1), "num_leaves": trial.suggest_int("num_leaves", 7, 100, step=10), "colsample_bytree": trial.suggest_float("colsample_bytree", 0.2, 1.0, step=0.1), "colsample_bynode": trial.suggest_float("colsample_bynode", 0.2, 1.0, step=0.1), "lambda_l1": trial.suggest_float("lambda_l1", 0, 10, step=0.1), # "max_delta_step": trial.suggest_float("max_delta_step", 0, 10, step=0.1), # "subsample_freq": trial.suggest_int("subsample_freq", 0, 50, step=1), "min_child_samples": trial.suggest_int("min_child_samples", 1, 1000, step=10), "subsample": trial.suggest_float("subsample", 0.5, 1.0, step=0.05), "cegb_penalty_split": trial.suggest_float("cegb_penalty_split", 0.0, 3.0, step=0.1), # 'extra_trees': trial.suggest_categorical('extra_trees', [False, True]), } dates = ["2020-01-12", '2020-01-26', '2020-03-01', '2020-03-08', '2020-04-05'] drop_columns = ['ds', 'game_code', 'ops_id', 'value'] scores = [] lossses_list = [] for j, ds in enumerate(dss): X_train = ds[0].drop(drop_columns, 1) Y_train = ds[0]['value'] drop_test = ds[1][drop_columns].copy() X_valid = ds[1].drop(drop_columns, 1) y_valid = ds[1]['value'] # rgr.fit(X_train, Y_train) model = train_model(args, X_train, Y_train, trial_params) y_predict = model.predict(X_valid) X_valid['base_forecast'] = y_predict.astype('int') X_valid['base_forecast'] = X_valid['base_forecast'].fillna(0) X_valid[['ds', 'game_code', 'ops_id', 'value']] = drop_test[['ds', 'game_code', 'ops_id', 'value']] score_table = score(X_valid.drop(['base_forecast'], 1), X_valid['base_forecast'], active_ops=False, compare_with_real_sales=True) lossses = score_table["losses"].sum() lossses_list.append(lossses) scores.append(score_table.assign(test_date=dates[j])) # lossses_sum = np.sum(lossses_list) all_scores = pd.concat(scores) i = trial.number all_scores.to_csv(f"./scores_optuna_2/optuna_scores_{i}.csv") lossses_sum = all_scores['losses'].sum() lost_sales = all_scores['lost_sales'].sum() over_sales = all_scores['over_sales'].sum() * 5 lost_sales_losses = all_scores['lost_sales_losses'].sum() logger.report_text(f"itaration: {i}", iteration=i) logger.report_text(f"params: {trial_params}", iteration=i) logger.report_scalar("losses", "base", value=lossses_sum, iteration=i) logger.report_scalar("lost_sales_losses", "base", value=lost_sales_losses, iteration=i) logger.report_scalar("over_sales", "base", value=over_sales, iteration=i) logger.report_table("scores", f"scores_{i}", table_plot=all_scores, iteration=i) return lossses_sum if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--study-name", type=str, dest="study_name") parser.add_argument("--use-gpu", dest="use_gpu", action="store_true") parser.add_argument("--ntrials", type=int, dest="n_trials") args = parser.parse_args() LOG_PATH = Path(WORK_DIR / "tuneparams.log") logging.basicConfig( filename=LOG_PATH, filemode="a", level=logging.INFO, ) log = logging.getLogger() log.addHandler(logging.StreamHandler()) log.info("Loading data") train0 = pd.read_parquet('./optuna_splits/train_14features_0.parquet') test0 = pd.read_parquet('./optuna_splits/test_14features_0.parquet') train1 = pd.read_parquet('./optuna_splits/train_14features_1.parquet') test1 = pd.read_parquet('./optuna_splits/test_14features_1.parquet') train2 = pd.read_parquet('./optuna_splits/train_14features_2.parquet') test2 = pd.read_parquet('./optuna_splits/test_14features_2.parquet') train3 = pd.read_parquet('./optuna_splits/train_14features_3.parquet') test3 = pd.read_parquet('./optuna_splits/test_14features_3.parquet') train4 = pd.read_parquet('./optuna_splits/train_14features_4.parquet') test4 = pd.read_parquet('./optuna_splits/test_14features_4.parquet') dss = [(train0, test0), (train1, test1), (train2, test2), (train3, test3), (train4, test4)] read_data = [] for i, p in enumerate( Path("./sales.parquet").iterdir() ): if "parquet" in p.name: df = pd.read_parquet(p) read_data.append(df) sales = pd.concat(read_data) sales.ds = pd.to_datetime(sales.ds) sales.game_code = sales.game_code.astype(int) sales.value = sales.value.astype(int) sales.shape # Run optuna study log.info("Starting optuna study") log.info( f'Starting optuna study_{datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")}' ) # init ClearML model_name = 'lightgbm' target = 'stoloto' task = Task.init( project_name="stoloto", task_name="optuna_14f", tags=['opt_params'] ) logger = task.get_logger() study_name = ( args.study_name if args.study_name else "stoloto-optuna-study" ) # Unique identifier of the study. storage_name = "sqlite:///{}.db".format(study_name) total_study = optuna.create_study( direction="minimize", study_name=study_name, storage=storage_name, load_if_exists=True, ) first_trial_params = {'colsample_bynode': 0.6, 'colsample_bytree': 0.5, 'lambda_l1': 6.4, 'learning_rate': 0.06878228501024089, 'max_bin': 163, 'max_depth': 7, 'min_child_samples': 13, 'n_estimators': 1400, 'num_leaves': 87, 'subsample': 0.8, 'subsample_freq': 14, 'max_delta_step': 0.0, 'cegb_penalty_split': 0.0 } total_study.enqueue_trial(params=first_trial_params) scoring = partial( scoring, dss=dss, args=args, ) try: total_study.optimize(scoring, n_trials=args.n_trials, show_progress_bar=True) except KeyboardInterrupt: pass with open(STUDY_PATH, "wb") as f: pickle.dump(total_study, f) log.info("Save study at studypath") log.info("Best LightGBM parameters") log.info(total_study.best_params) log.info( f'Save study results_{datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")}' ) with open(STUDY_PATH, "wb") as fs: pickle.dump(total_study, fs) task.mark_completed()
Anaksibia/Ticket_distribution_system
scripts/run_optuna_5_dates.py
run_optuna_5_dates.py
py
13,803
python
en
code
0
github-code
6
10719490049
import sys import pathlib import generator_func import generator_logging from datetime import datetime from PyQt6.QtCore import QRunnable, QThreadPool, QDateTime, QSettings from PyQt6.QtWidgets import (QApplication, QDateTimeEdit, QLabel, QMainWindow, QPushButton, QWidget, QFileDialog, QGridLayout, QLineEdit, QComboBox, QProgressBar, QStatusBar, QSpinBox, QTableWidget, QTableWidgetItem, QMessageBox) from PyQt6.QtGui import QIcon MAXIMUM_IK_QUANTITY = 9999 class Worker(QRunnable): # класс для мультипоточности??? def run(self): # мой код date_1 = win.date_1 ed_date = date_1.toString('yyyy-MM-dd') req_date_time = date_1.toString('yyyy-MM-ddThh:mm:ssZ') path_for_ik = win.directory_path.currentText() # в качестве пути для ИК берётся значение, указанное в ComboBox win.progressbar.setMaximum(win.ik_quantity.value()) win.btn_create_IK.setEnabled(False) start = datetime.now() # aaa = generator_func.check_dir_emptiness(path_for_ik) # проверка каталога сохранения ИК на наличие файлов for i in range(win.ik_quantity.value()): generator_func.create_ik(path_for_ik, ed_date, req_date_time) win.progressbar.setValue(i + 1) win.status_bar.showMessage(f'Создано конвертов: {i + 1}') end = datetime.now() win.status_bar.showMessage(f'Создано конвертов: {win.ik_quantity.value()}. Затраченное время: {end - start}') generator_logging.log_event(f'Создано конвертов: {win.ik_quantity.value()}. Каталог: {path_for_ik}. ' f'Затраченное время: {end - start}') win.btn_create_IK.setEnabled(True) class Window(QMainWindow): def __init__(self): super(Window, self).__init__() # Добавляем файл с настройками self.settings = QSettings('settings.ini', QSettings.Format.IniFormat) self.path_history = set() self.date_1 = '' self.setWindowTitle("Генератор ИК") # заголовок главного окна self.setMinimumSize(500, 150) # минимальные размеры главного окна self.get_directory_path = QPushButton('Выбрать каталог', self) self.get_directory_path.setFixedWidth(150) # установка ширины кнопки # Определяем элементы интерфейса self.btn_create_IK = QPushButton('Создать конверты', self) self.ik_quantity_label = QLabel() self.calendar_label = QLabel() self.line_edit_for_combo = QLineEdit() self.directory_path = QComboBox() self.directory_path.setLineEdit(self.line_edit_for_combo) self.ik_quantity = QSpinBox() self.calendar = QDateTimeEdit() self.progressbar = QProgressBar() self.status_bar = QStatusBar() self.start_date = QDateTime.currentDateTime() self.calendar.setDisplayFormat('dd.MM.yyyy') self.ik_quantity.setMaximum(MAXIMUM_IK_QUANTITY) self.setMaximumWidth(1800) self.get_directory_path.clicked.connect(self.get_directory) self.btn_create_IK.clicked.connect(self.create_ik_func) self.ik_quantity.textChanged.connect(self.ik_quantity_signal) self.calendar.dateTimeChanged.connect(self.calendar_changed) self.calendar.setCalendarPopup(True) self.calendar.setDateTime(self.start_date) self.date_1 = self.calendar.dateTime() self.table = QTableWidget() self.table_widget_item = QTableWidgetItem() # размещение элементов grid_layout = QGridLayout() grid_layout.addWidget(self.get_directory_path, 0, 0) grid_layout.addWidget(self.directory_path, 0, 1) grid_layout.addWidget(self.ik_quantity_label, 1, 0) grid_layout.addWidget(self.ik_quantity, 1, 1) grid_layout.addWidget(self.calendar_label, 2, 0) grid_layout.addWidget(self.calendar, 2, 1) grid_layout.addWidget(self.btn_create_IK, 3, 0, 1, 2) # grid_layout.addWidget(self.progressbar, 5, 0, 1, 2) grid_layout.addWidget(self.status_bar, 4, 0, 1, 2) widget = QWidget() widget.setLayout(grid_layout) self.setCentralWidget(widget) self.ik_quantity_label.setText('Количество конвертов') self.calendar_label.setText('Дата ИК') self.btn_create_IK.setEnabled(False) # создание всплывающих подсказок для элементов интерфейса self.get_directory_path.setToolTip('Выберите каталог для сохранения ИК') self.directory_path.setToolTip('Можно вставить путь или выбрать с помощью кнопки') self.ik_quantity.setToolTip('Количество создаваемых конвертов') self.btn_create_IK.setToolTip('Введите количество создаваемых конвертов') self.calendar.setToolTip('Дата интеграционного конверта, дата заявки, дата выдачи кредита') self.status_bar.showMessage('') # self.table.cellClicked(0,0) # Что-то про многопоточность self.threadpool = QThreadPool() self.ik_quantity_label = '' self.iteration_count = '' # определение переменных для пути к каталогам и файлам self.start_path = pathlib.Path.cwd() self.envelope_path = self.start_path.joinpath('sample/envelope.xml') self.routeinfo_path = self.start_path.joinpath('sample/RouteInfo.xml') self.ed421_path = self.start_path.joinpath('sample/ED421.xml') self.line_edit_for_combo.setText(str(self.start_path)) self.path_for_ik = self.start_path self.path_for_ik_str = str(self.path_for_ik) # подгонка ширины под длину пути к каталогу self.setMinimumWidth(int(len(str(self.start_path)) * 8.5)) # импорт сохраненных настроек if self.settings.value('OD'): self.calendar.setDateTime(self.settings.value('OD')) else: self.date_1 = self.calendar.date() if self.settings.value('Path'): self.directory_path.addItems(self.settings.value('Path')) self.path_history = self.settings.value('Path') else: self.path_history = set() def get_directory(self): """ Вызов диалогового окна для выбора каталога сохранения создаваемых конвертов :return: """ self.path_for_ik = QFileDialog.getExistingDirectory(self, caption='Выбрать каталог сохранения', directory=str(pathlib.Path.cwd())) self.path_for_ik_str = str(self.path_for_ik) self.line_edit_for_combo.setText(self.path_for_ik_str) self.setMinimumWidth(len(self.path_for_ik_str * 10)) def create_ik_func(self): """ Создание конвертов :return: """ worker = Worker() # делаем переменную на созданный класс FirstThread self.threadpool.start(worker) # обращаемся к созданному классу FirstThread # добавление пути для ИК в выпадающий список if self.path_for_ik_str in self.path_history: pass elif self.path_for_ik_str not in self.path_history: self.path_history.add(self.path_for_ik_str) self.directory_path.addItem(self.path_for_ik_str) def ik_quantity_signal(self, value): """ Определяет заполнено поле с количеством конвертов или нет и блокирует кнопку создания ИК :param value: :return: """ if self.ik_quantity.value() == 0: self.btn_create_IK.setEnabled(False) self.btn_create_IK.setToolTip('Введите количество создаваемых конвертов') else: self.btn_create_IK.setEnabled(True) self.btn_create_IK.setToolTip('Создать конверты') def calendar_changed(self): self.date_1 = self.calendar.dateTime() def closeEvent(self, event): # переопределение события закрытия окна self.settings.setValue('Path', self.path_history) # Сохранить переменную с историей в файле с настройками self.settings.setValue('OD', self.date_1) # Сохранить переменную с датой в файле с настройками if __name__ == '__main__': app = QApplication(sys.argv) style = """ QMainWindow { /*background-color: #fff;*/ } QProgressBar { border: 1px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: #05B8CC; width: 10px; /*margin: 0.5px;*/ } """ app.setStyleSheet(style) win = Window() app.setWindowIcon(QIcon(str(win.start_path.joinpath('other/hedgehog_deep_red.png')))) win.show() sys.exit(app.exec())
Steelglowhawk/updateTool
generator_gui.py
generator_gui.py
py
10,348
python
ru
code
1
github-code
6
2621863867
''' The elif clause executes if age < 12 is True and name == 'Alice' is False. However, if both of the conditions are False, then both of the clauses are skipped. It is not guaranteed that at least one of the clauses will be executed. When there is a chain of elif statements, only one or none of the clauses will be executed. Once one of the statements’ conditions is found to be True, the rest of the elif clauses are automatically skipped.''' name = 'Carol' age = 3000 if name == 'Alice': print('Hi, Alice.') elif age <12: print("You are not Alice, Kiddo.") elif age > 2000: print("Unlike you, Alice is not an undead, immortal vampire.") elif age > 100: print('You are not Alice, grannie.')
ladamsperez/python_excercises
automatetheboringstuff/vampire.py
vampire.py
py
718
python
en
code
0
github-code
6
24531644863
import os import json import random as rd from copy import deepcopy from matplotlib.pylab import * import math import torch import torchvision.datasets as dsets import torch.nn as nn import torch.nn.functional as F # import torch_xla # import torch_xla.core.xla_model as xm device = torch.device("cuda") def encode(lstm, wemb_l, l, return_hidden=False, hc0=None, last_only=False): """ [batch_size, max token length, dim_emb] """ bS, mL, eS = wemb_l.shape # sort before packking l = array(l) perm_idx = argsort(-l) perm_idx_inv = generate_perm_inv(perm_idx) # pack sequence packed_wemb_l = nn.utils.rnn.pack_padded_sequence(wemb_l[perm_idx, :, :], l[perm_idx], batch_first=True) # Time to encode if hc0 is not None: hc0 = (hc0[0][:, perm_idx], hc0[1][:, perm_idx]) # ipdb.set_trace() packed_wemb_l = packed_wemb_l.float() # I don't know why.. packed_wenc, hc_out = lstm(packed_wemb_l, hc0) hout, cout = hc_out # unpack wenc, _l = nn.utils.rnn.pad_packed_sequence(packed_wenc, batch_first=True) if last_only: # Take only final outputs for each columns. wenc = wenc[tuple(range(bS)), l[perm_idx] - 1] # [batch_size, dim_emb] wenc.unsqueeze_(1) # [batch_size, 1, dim_emb] wenc = wenc[perm_idx_inv] if return_hidden: # hout.shape = [number_of_directoin * num_of_layer, seq_len(=batch size), dim * number_of_direction ] w/ batch_first.. w/o batch_first? I need to see. hout = hout[:, perm_idx_inv].to(device) cout = cout[:, perm_idx_inv].to(device) # Is this correct operation? return wenc, hout, cout else: return wenc def encode_hpu(lstm, wemb_hpu, l_hpu, l_hs): wenc_hpu, hout, cout = encode(lstm, wemb_hpu, l_hpu, return_hidden=True, hc0=None, last_only=True) wenc_hpu = wenc_hpu.squeeze(1) bS_hpu, mL_hpu, eS = wemb_hpu.shape hS = wenc_hpu.size(-1) wenc_hs = wenc_hpu.new_zeros(len(l_hs), max(l_hs), hS) wenc_hs = wenc_hs.to(device) # Re-pack according to batch. # ret = [B_NLq, max_len_headers_all, dim_lstm] st = 0 for i, l_hs1 in enumerate(l_hs): wenc_hs[i, :l_hs1] = wenc_hpu[st:(st + l_hs1)] st += l_hs1 return wenc_hs def generate_perm_inv(perm): # Definitly correct. perm_inv = zeros(len(perm), dtype=int) # Was an undefine int32 variable for i, p in enumerate(perm): perm_inv[int(p)] = i return perm_inv def pred_sc(s_sc): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sc = [] for s_sc1 in s_sc: pr_sc.append(s_sc1.argmax().item()) return pr_sc def pred_sc_beam(s_sc, beam_size): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sc_beam = [] for s_sc1 in s_sc: val, idxes = s_sc1.topk(k=beam_size) pr_sc_beam.append(idxes.tolist()) return pr_sc_beam def pred_sa(s_sa): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sa = [] for s_sa1 in s_sa: pr_sa.append(s_sa1.argmax().item()) return pr_sa def pred_wn(s_wn): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_wn = [] for s_wn1 in s_wn: pr_wn.append(s_wn1.argmax().item()) # print(pr_wn, s_wn1) # if s_wn1.argmax().item() == 3: # input('') return pr_wn def pred_wc(wn, s_wc): """ return: [ pr_wc1_i, pr_wc2_i, ...] ! Returned index is sorted! """ # get g_num pr_wc = [] for b, wn1 in enumerate(wn): s_wc1 = s_wc[b] pr_wc1 = argsort(-s_wc1.data.cpu().numpy())[:wn1] pr_wc1.sort() pr_wc.append(list(pr_wc1)) return pr_wc def pred_wo(wn, s_wo): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # s_wo = [B, 4, n_op] pr_wo_a = s_wo.argmax(dim=2) # [B, 4] # get g_num pr_wo = [] for b, pr_wo_a1 in enumerate(pr_wo_a): wn1 = wn[b] pr_wo.append(list(pr_wo_a1.data.cpu().numpy()[:wn1])) return pr_wo def topk_multi_dim(tensor, n_topk=1, batch_exist=True): if batch_exist: idxs = [] for b, tensor1 in enumerate(tensor): idxs1 = [] tensor1_1d = tensor1.reshape(-1) values_1d, idxs_1d = tensor1_1d.topk(k=n_topk) idxs_list = unravel_index(idxs_1d.cpu().numpy(), tensor1.shape) # (dim0, dim1, dim2, ...) # reconstruct for i_beam in range(n_topk): idxs11 = [] for idxs_list1 in idxs_list: idxs11.append(idxs_list1[i_beam]) idxs1.append(idxs11) idxs.append(idxs1) else: tensor1 = tensor idxs1 = [] tensor1_1d = tensor1.reshape(-1) values_1d, idxs_1d = tensor1_1d.topk(k=n_topk) idxs_list = unravel_index(idxs_1d.numpy(), tensor1.shape) # (dim0, dim1, dim2, ...) # reconstruct for i_beam in range(n_topk): idxs11 = [] for idxs_list1 in idxs_list: idxs11.append(idxs_list1[i_beam]) idxs1.append(idxs11) idxs = idxs1 return idxs def remap_sc_idx(idxs, pr_sc_beam): for b, idxs1 in enumerate(idxs): for i_beam, idxs11 in enumerate(idxs1): sc_beam_idx = idxs[b][i_beam][0] sc_idx = pr_sc_beam[b][sc_beam_idx] idxs[b][i_beam][0] = sc_idx return idxs def check_sc_sa_pairs(tb, pr_sc, pr_sa, ): """ Check whether pr_sc, pr_sa are allowed pairs or not. agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] """ bS = len(pr_sc) check = [False] * bS for b, pr_sc1 in enumerate(pr_sc): pr_sa1 = pr_sa[b] hd_types1 = tb[b]['types'] hd_types11 = hd_types1[pr_sc1] if hd_types11 == 'text': if pr_sa1 == 0 or pr_sa1 == 3: # '' check[b] = True else: check[b] = False elif hd_types11 == 'real': check[b] = True else: raise Exception("New TYPE!!") return check def pred_wvi_se_beam(max_wn, s_wv, beam_size): """ s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx output: pr_wvi_beam = [B, max_wn, n_pairs, 2]. 2 means [st, ed]. prob_wvi_beam = [B, max_wn, n_pairs] """ bS = s_wv.shape[0] # [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1] s_wv_st, s_wv_ed = s_wv.split(1, dim=3) s_wv_st = s_wv_st.squeeze(3) # [B, 4, mL, 1] -> [B, 4, mL] s_wv_ed = s_wv_ed.squeeze(3) prob_wv_st = F.softmax(s_wv_st, dim=-1).detach().to('cpu').numpy() prob_wv_ed = F.softmax(s_wv_ed, dim=-1).detach().to('cpu').numpy() k_logit = int(ceil(sqrt(beam_size))) n_pairs = k_logit**2 assert n_pairs >= beam_size values_st, idxs_st = s_wv_st.topk(k_logit) # [B, 4, mL] -> [B, 4, k_logit] values_ed, idxs_ed = s_wv_ed.topk(k_logit) # [B, 4, mL] -> [B, 4, k_logit] # idxs = [B, k_logit, 2] # Generate all possible combination of st, ed indices & prob pr_wvi_beam = [] # [B, max_wn, k_logit**2 [st, ed] paris] prob_wvi_beam = zeros([bS, max_wn, n_pairs]) for b in range(bS): pr_wvi_beam1 = [] idxs_st1 = idxs_st[b] idxs_ed1 = idxs_ed[b] for i_wn in range(max_wn): idxs_st11 = idxs_st1[i_wn] idxs_ed11 = idxs_ed1[i_wn] pr_wvi_beam11 = [] pair_idx = -1 for i_k in range(k_logit): for j_k in range(k_logit): pair_idx += 1 st = idxs_st11[i_k].item() ed = idxs_ed11[j_k].item() pr_wvi_beam11.append([st, ed]) p1 = prob_wv_st[b, i_wn, st] p2 = prob_wv_ed[b, i_wn, ed] prob_wvi_beam[b, i_wn, pair_idx] = p1*p2 pr_wvi_beam1.append(pr_wvi_beam11) pr_wvi_beam.append(pr_wvi_beam1) # prob return pr_wvi_beam, prob_wvi_beam def convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_wp_t, wp_to_wh_index, nlu): """ - Convert to the string in whilte-space-separated tokens - Add-hoc addition. """ pr_wv_str_wp = [] # word-piece version pr_wv_str = [] for b, pr_wvi1 in enumerate(pr_wvi): pr_wv_str_wp1 = [] pr_wv_str1 = [] wp_to_wh_index1 = wp_to_wh_index[b] nlu_wp_t1 = nlu_wp_t[b] nlu_t1 = nlu_t[b] for i_wn, pr_wvi11 in enumerate(pr_wvi1): st_idx, ed_idx = pr_wvi11 # Ad-hoc modification of ed_idx to deal with wp-tokenization effect. # e.g.) to convert "butler cc (" ->"butler cc (ks)" (dev set 1st question). pr_wv_str_wp11 = nlu_wp_t1[st_idx:ed_idx+1] pr_wv_str_wp1.append(pr_wv_str_wp11) st_wh_idx = wp_to_wh_index1[st_idx] ed_wh_idx = wp_to_wh_index1[ed_idx] pr_wv_str11 = nlu_t1[st_wh_idx:ed_wh_idx+1] pr_wv_str1.append(pr_wv_str11) pr_wv_str_wp.append(pr_wv_str_wp1) pr_wv_str.append(pr_wv_str1) return pr_wv_str, pr_wv_str_wp def merge_wv_t1_eng(where_str_tokens, NLq): """ Almost copied of SQLNet. The main purpose is pad blank line while combining tokens. """ nlq = NLq.lower() where_str_tokens = [tok.lower() for tok in where_str_tokens] alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$' special = {'-LRB-': '(', '-RRB-': ')', '-LSB-': '[', '-RSB-': ']', '``': '"', '\'\'': '"', } # '--': '\u2013'} # this generate error for test 5661 case. ret = '' double_quote_appear = 0 for raw_w_token in where_str_tokens: # if '' (empty string) of None, continue if not raw_w_token: continue # Change the special characters # maybe necessary for some case? w_token = special.get(raw_w_token, raw_w_token) # check the double quote if w_token == '"': double_quote_appear = 1 - double_quote_appear # Check whether ret is empty. ret is selected where condition. if len(ret) == 0: pass # Check blank character. elif len(ret) > 0 and ret + ' ' + w_token in nlq: # Pad ' ' if ret + ' ' is part of nlq. ret = ret + ' ' elif len(ret) > 0 and ret + w_token in nlq: pass # already in good form. Later, ret + w_token will performed. # Below for unnatural question I guess. Is it likely to appear? elif w_token == '"': if double_quote_appear: ret = ret + ' ' # pad blank line between next token when " because in this case, it is of closing apperas # for the case of opening, no blank line. elif w_token[0] not in alphabet: pass # non alphabet one does not pad blank line. # when previous character is the special case. elif (ret[-1] not in ['(', '/', '\u2013', '#', '$', '&']) and (ret[-1] != '"' or not double_quote_appear): ret = ret + ' ' ret = ret + w_token return ret.strip()
DebadityaPal/RoBERTa-NL2SQL
seq2sql_model_internal_functions.py
seq2sql_model_internal_functions.py
py
11,929
python
en
code
17
github-code
6
42929566304
class Solution: def decodeString(self, str): num, stack, i = 0, [""], 0 while i < len(str): if str[i].isdigit(): num = num*10 + int(str[i]) elif str[i] == "[": stack.append(num) num = 0 stack.append("") elif str[i] == "]": str1 = stack.pop() cnt = stack.pop() str2 = stack.pop() stack.append(str2 + str1*cnt) else: stack[-1] += str[i] i += 1 return "".join(stack) obj = Solution() str = "3[a2[c]]" ans = obj.decodeString(str) print(ans)
shwetakumari14/Leetcode-Solutions
Miscellaneous/Python/394. Decode String.py
394. Decode String.py
py
702
python
en
code
0
github-code
6
75316085946
import wx import os from .smart import SmartCheckBox, SmartInputLayout __author__ = 'Joeny' class CheckboxInputLayout(SmartInputLayout): """ Checkbox Input Layout """ def __init__(self, parent, checkbox=None, layout=None, *args, **kwargs): label = None if checkbox: label = checkbox else: label = SmartCheckBox(parent) SmartInputLayout.__init__(self, parent, layout=layout, label=label, *args, **kwargs) self.do_layout() def set_value(self, value): # type: (object) -> object self.label.SetValue(bool(value)) def get_value(self): return self.label.Value
JoenyBui/boa-gui
boaui/textbox/checkbox.py
checkbox.py
py
675
python
en
code
0
github-code
6
33559300888
#Declarar Varibles contador = int () suma = int () #Limpiar/Inicializar Variables contador = 0 suma = 0 #Asignar Valores a las variables contador = 1 while (contador <= 10): suma = suma + contador contador = contador + 1 print("El resultado de la suma de estos numeros es: ", suma)
renzovarela9/Proyectos-Propios
PYTHON/PROBANDO UNA SUMA CON WHILE.py
PROBANDO UNA SUMA CON WHILE.py
py
302
python
es
code
0
github-code
6
29942141352
import functools import typing as tp import shapely.geometry import torch import torchmetrics from torch.nn.utils.rnn import PackedSequence def _multiarange(counts: torch.Tensor) -> torch.Tensor: """Returns a sequence of aranges concatenated along the first dimension. >>> counts = torch.tensor([1, 3, 2]) >>> _multiarange(counts) torch.tensor([0, 0, 1, 2, 0, 1]) """ counts1 = counts[:-1] reset_index = counts1.cumsum(0) incr = torch.ones(int(counts.sum()), dtype=torch.int64) incr[0] = 0 incr[reset_index] = 1 - counts1 out: torch.Tensor = incr.cumsum(0) return out class TokenAccuracy(torchmetrics.Metric): higher_is_better = True def __init__(self) -> None: super().__init__() self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum") self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") def update(self, prediction: PackedSequence, target: PackedSequence) -> None: if prediction.data.ndim == 2: prediction = prediction._replace(data=prediction.data.argmax(1)) # prediction and target should be padded to the same length so the shapes match pad_length = max(len(prediction.batch_sizes), len(target.batch_sizes)) prediction_padded, prediction_lens = torch.nn.utils.rnn.pad_packed_sequence( prediction, batch_first=True, total_length=pad_length ) target_padded, target_lens = torch.nn.utils.rnn.pad_packed_sequence( target, batch_first=True, total_length=pad_length ) # correct only among target tokens, if prediction is longer extra tokens are # ignored selection = (torch.repeat_interleave(target_lens), _multiarange(target_lens)) self.correct += torch.sum( prediction_padded[selection] == target_padded[selection] ) self.total += torch.sum(target_lens) def compute(self) -> torch.Tensor: if self.correct == 0: return torch.tensor(0.0) return self.correct / self.total # type:ignore[operator] class SequenceAccuracy(torchmetrics.Metric): higher_is_better = True def __init__(self) -> None: super().__init__() self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum") self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") def update(self, prediction: PackedSequence, target: PackedSequence) -> None: if prediction.data.ndim == 2: prediction = prediction._replace(data=prediction.data.argmax(1)) # prediction and target should be padded to the same length so the shapes match pad_length = max(len(prediction.batch_sizes), len(target.batch_sizes)) prediction_padded, prediction_lens = torch.nn.utils.rnn.pad_packed_sequence( prediction, batch_first=True, total_length=pad_length ) target_padded, target_lens = torch.nn.utils.rnn.pad_packed_sequence( target, batch_first=True, total_length=pad_length ) batch_size = target_padded.shape[0] self.correct += torch.sum(torch.all(prediction_padded == target_padded, dim=1)) self.total += batch_size # type:ignore[operator] def compute(self) -> torch.Tensor: if self.correct == 0: return torch.tensor(0.0) return self.correct / self.total # type:ignore[operator] class PolygonAccuracy(torchmetrics.Metric): correct: torch.Tensor total: torch.Tensor def __init__(self) -> None: super().__init__() self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum") self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") pass def update( self, point_sets: PackedSequence, predictions: PackedSequence, targets: PackedSequence, ) -> None: pad = functools.partial( torch.nn.utils.rnn.pad_packed_sequence, batch_first=True ) if predictions.data.ndim == 2: predictions = predictions._replace(data=predictions.data.argmax(1)) correct, total = 0, 0 for i, ( point_set, point_set_len, prediction, prediction_len, target, target_len, ) in enumerate(zip(*pad(point_sets), *pad(predictions), *pad(targets))): target_polygon = shapely.geometry.Polygon( point_set[target[: target_len - 1] - 1].tolist() ) predicted_polygon = shapely.geometry.Polygon( point_set[prediction[: prediction_len - 1] - 1].tolist() ) correct += target_polygon.equals(predicted_polygon) total += 1 self.correct += correct self.total += total def compute(self) -> torch.Tensor: if self.correct == 0: return torch.tensor(0.0) return self.correct / self.total class AverageAreaCoverage(torchmetrics.Metric): coverages: tp.List[torch.Tensor] is_valid: tp.List[torch.Tensor] def __init__(self, is_valid_threshold: float = 0.1) -> None: super().__init__() self.is_valid_threshold = is_valid_threshold self.add_state("coverages", default=[], dist_reduce_fx="cat") self.add_state("is_valid", default=[], dist_reduce_fx="cat") def update( self, point_sets: PackedSequence, predictions: PackedSequence, targets: PackedSequence, ) -> None: pad = functools.partial( torch.nn.utils.rnn.pad_packed_sequence, batch_first=True ) coverages: tp.List[float] = [] is_valid: tp.List[bool] = [] for ( point_set, point_set_len, prediction, prediction_len, target, target_len, ) in zip(*pad(point_sets), *pad(predictions), *pad(targets)): target_polygon = shapely.geometry.Polygon( point_set[target[: target_len - 1] - 1].tolist() ) predicted_polygon = shapely.geometry.Polygon( point_set[prediction[: prediction_len - 1] - 1].tolist() ) coverages.append(predicted_polygon.area / target_polygon.area) is_valid.append(predicted_polygon.is_simple) self.coverages.append(torch.tensor(coverages)) self.is_valid.append(torch.tensor(is_valid)) def compute(self) -> torch.Tensor: is_valid = torch.cat(self.is_valid, dim=0) coverages = torch.cat(self.coverages, dim=0) if torch.sum(~is_valid) > self.is_valid_threshold * len(is_valid): return torch.tensor(-1.0) return torch.mean(coverages[is_valid]) class TourDistance(torchmetrics.Metric): tour_distances: tp.List[torch.Tensor] def __init__(self) -> None: super().__init__() self.add_state("tour_distances", default=[], dist_reduce_fx="cat") def update(self, point_sets: PackedSequence, prediction: PackedSequence) -> None: batch_size = point_sets.batch_sizes[0] device = point_sets.data.device point_sets_padded, npoints = torch.nn.utils.rnn.pad_packed_sequence( point_sets, batch_first=True ) prediction_padded, prediction_lens = torch.nn.utils.rnn.pad_packed_sequence( prediction, batch_first=True ) max_pred_len = prediction_padded.shape[1] batch_arange = torch.arange(batch_size, device=device) assert torch.all( prediction_padded[batch_arange, prediction_lens - 1] == 0 ), "all prediction should finish with a 0" assert torch.all( prediction_padded[batch_arange, prediction_lens - 2] == prediction_padded[:, 0] ), "all tours should end where they start" # pad with the first value, so that summing distances after closing # tour doesn't increase the tour distance prediction_padded += ( torch.arange(max_pred_len, device=device).expand_as(prediction_padded) >= (prediction_lens.to(device) - 1)[:, None] ) * prediction_padded[:, 0:1] # NOTE: i just trust from decoding that there are no repeated points # and all points are visited curr = point_sets_padded[batch_arange[:, None], prediction_padded[:, :-1] - 1] next_ = point_sets_padded[batch_arange[:, None], prediction_padded[:, 1:] - 1] tour_distances = torch.sum( torch.sqrt(torch.sum((next_ - curr) ** 2, dim=2)), dim=1 ) self.tour_distances.append(tour_distances) def compute(self) -> torch.Tensor: all_tour_distances = torch.cat(self.tour_distances) return all_tour_distances.mean()
gchaperon/pointer-networks
ptrnets/metrics.py
metrics.py
py
8,846
python
en
code
20
github-code
6
18187145317
# ----------------------------- # pluieOS source code # made with heart by dadoum # ----------------------------- # Partly based on rainbox # ----------------------------- import subprocess import sys import time import signal import os import traceback import matplotlib as matplotlib import numpy import sh import distutils.core import urllib.request from pprint import pprint from PIL import Image, ImageDraw, ImageFont from pluieAPI import Application, View, width, height import platform # import bakebit_128_64_oled as display app_path = os.path.join(os.getenv("HOME"), "Pluvieuses applications") # POA format is a compressed format that means pluieOS Application, but it corresponds to a Pluvieuses application (or correctly application pluvieuse, but we will stay simple) # Launcher Application is an application like any application, # Except it will never be killed until shutdown, and that it is not in the standard folder class LauncherApp(Application): name = "Launcher" def __init__(self): super().__init__() def run(self): sub = os.listdir(app_path) import json # For each app applications = [] jsons = [] dirs = [] for di in sub: d = os.path.join(app_path, di) if os.path.isdir(d): # We take its app.json, app_json = os.path.join(d, "app.json") with open(app_json) as f: content = f.read() # Retrieve some important values parsed_json = json.loads(content) script = os.path.join(d, parsed_json["script"]) name = parsed_json["name"] entry_point = parsed_json["entry_point"] # And import the entry point import importlib.util spec = importlib.util.spec_from_file_location(os.path.splitext(parsed_json["script"])[0], script) app = importlib.util.module_from_spec(spec) spec.loader.exec_module(app) # This is the application class app_class = getattr(app, entry_point) applications.append(app_class) jsons.append(parsed_json) dirs.append(d) collectionView = AppCollectionView(applications, jsons) while True: btn = collectionView.run() if not collectionView.app_avail: print("Cannot go further, shutdown.") btn = 3 if btn == 1: collectionView.app_number += 1 collectionView.reset() elif btn == 2: selected_app = applications[collectionView.app_number] appli = selected_app() appli.run(dirs[collectionView.app_number]) elif btn == 3: print("Shutdown...") if not os.uname().machine == "x86_64": os.system('systemctl poweroff') break return 0 class AppCollectionView(View): app_number = 0 app_avail = True app_list = [] app_jsons = [] def __init__(self, app_list, app_jsons): super().__init__("Applications", "Next", "Select", "Shutdown") self.app_list = app_list self.app_jsons = app_jsons return def draw(self, draw): if len(self.app_list) == 0: w, h = draw.textsize("No any app installed\nConnect on your computer\nand install apps !") draw.text(((width - w) / 2, (height - h) / 2), "No any app installed\nConnect on your computer\nand install apps !", 255) self.app_avail = False return self.app_number %= len(self.app_list) app_name = str(self.app_jsons[self.app_number]["name"]) w, h = draw.textsize(app_name) app_icon = os.path.join(app_path, self.app_jsons[self.app_number]["name"], "icon.png") img = Image.open(app_icon) img_w, img_h = img.size from pluieAPI import image # Bad practice, do that when it is not possible to do in another way image.paste(img, (5, int((height - (img_h + (h / 2))) / 2))) draw.text(((width - w - 5), (height - h) / 2), app_name, 255) return def launch(): trace = "" try: launcher = LauncherApp() exitCode = launcher.run() except: trace = "" try: trace = traceback.format_exc(-1) exitCode = 2 except: exitCode = 1 if exitCode != 0: print("Launcher crashed !") from pluieAPI import draw, image draw.rectangle((0, 0, width, height), 0) draw.text((0, 0), "Launcher crashed :(", 255) if exitCode == 2: w, h = draw.textsize("Launcher crashed!") print(trace) draw.text((0, h + 1), trace, 255, font=ImageFont.truetype('DejaVuSansMono.ttf', 8)) if os.uname().machine == "x86_64": image.save("./debug.png") launch()
Dadoum/pluieOS
pluieLauncher.py
pluieLauncher.py
py
4,248
python
en
code
0
github-code
6
22879333885
# import socket # import json # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # # host = socket.gethostname() # port = 9999 # s.connect(("127.0.0.1", port)) # msg = s.recv(1024) # msg = msg.decode('utf-8') # print(msg) # s.close() import socket import json s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # host = socket.gethostname() port = 8888 s.connect(("127.0.0.1", port)) # msg = "hi" msg = {"a":0.01} msg = json.dumps(msg) s.sendall(msg.encode('utf-8')) s.close()
HugoXK/ECE-445-Senior-Design
client.py
client.py
py
491
python
en
code
0
github-code
6
72740356347
import subprocess from dataclasses import dataclass from typing import Dict import json from src.config import LOGGER @dataclass class Server: server_name: str server_id: int class SpeedTestGateway: @classmethod def get_speed_test_result(cls, server_id: int) -> Dict: command = [ "speedtest", "--format=json-pretty", "--progress=no", "--accept-license", "--accept-gdpr", f"--server-id={server_id}", ] try: console_output = subprocess.check_output(command, timeout=180) return cls.parse_json(console_output=console_output) except subprocess.CalledProcessError as exc: LOGGER.error("Process error", extra={"server_id": server_id, "exc": str(exc)}) except subprocess.TimeoutExpired: LOGGER.error("Time out error", extra={"server_id": server_id}) @staticmethod def parse_json(console_output: bytes) -> Dict: try: return json.loads(console_output) except ValueError: raise subprocess.CalledProcessError
galloramiro/internet-connection-log
src/speed_test_gateway.py
speed_test_gateway.py
py
1,128
python
en
code
0
github-code
6
9989418734
import socket # Crear un socket TCP/IP sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Vincular el socket a un puerto conocido server_address = ('', 12345) sock.bind(server_address) # Escuchar conexiones entrantes sock.listen(1) while True: connection, client_address = sock.accept() # Recibir el mensaje del contenedor1 data = connection.recv(1024) # Responder al contenedor1 response = "Su solicitud de visculación ha sido ingresada con exito" connection.sendall(response.encode()) # Cerrar la conexión connection.close()
JoseMiranda21/poli
poli2/app2.py
app2.py
py
604
python
es
code
0
github-code
6
26171304664
import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.nn import CrossEntropyLoss from torch.optim import Adam from datetime import datetime class MLPClassifier(nn.Module): def __init__(self): super().__init__() self.MLP = nn.Sequential( nn.Linear(10000, 2000), nn.ReLU(), nn.Linear(2000, 500), nn.ReLU(), nn.Linear(500, 500), nn.ReLU(), nn.Linear(500, 500), nn.ReLU(), nn.Linear(500, 5) ) def forward(self, x): x = self.MLP(x) return x def predict(self, X): self.to('cpu') samples = torch.from_numpy(X).float() with torch.no_grad(): outputs = self(samples) predicted = torch.argmax(outputs.data, axis=1) return predicted def fit(self, train_dataset, batch_size=128, num_epochs=5, PATH=None, device='cpu'): # Multi-layer Perceptron classifier criterion = CrossEntropyLoss() optimizer = Adam(self.parameters(), lr=0.001) trainloader = DataLoader(train_dataset, batch_size=batch_size) losses = [] running_loss = 0.0 for epoch in range(num_epochs): for i, (inputs, labels) in enumerate(trainloader, start=0): # get the inputs; data is a list of [inputs, labels] inputs, labels = inputs.to(device), labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = self(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if epoch % 1 == 0 and i==0: # print every epoch print(f'[{epoch+1}] loss: {running_loss:.6f}') losses.append((epoch, running_loss)) running_loss = 0.0 if not PATH: t = datetime.now().strftime('%d-%m-%Y_%H-%M-%S') PATH = f'models/MLP_{t}.pth' torch.save(self.state_dict(), PATH) return self
Charlie-Bell/stack-overflow-classifier
src/MLP.py
MLP.py
py
2,284
python
en
code
0
github-code
6
19703597779
# check the costs after every time consuming all examples # usage: python check_costs.py import mnist_loader training_data, validation_data, test_data = mnist_loader.load_data_wrapper() import network import numpy as np import matplotlib.pyplot as plt net = network.Network([784, 30, 10]) net.set_check_cost_inside_SGD() net.SGD(training_data, 5, 10, 3.0, test_data=test_data) # draw a picture xpoints = [] ypoints = [] for x, y in net.costs: xpoints.append(x) ypoints.append(y) plt.plot(xpoints, ypoints, marker = 'o', mec = 'r', mfc = 'r') plt.xlabel('# of input') plt.ylabel('average cost') plt.show()
hzget/machine-learning
dl_tutorial/check_costs.py
check_costs.py
py
617
python
en
code
0
github-code
6
6400878080
##4. Write a program that takes a line as input and converts all lower-case letters to upper case and all upper-case letters to lower-case and spaces to $. ##Input Example: ##My NaMe is KhaN. ##Output: ##mY$nAmE$ISkHAn. res=input() rstr='' for i in res: if(i.isupper())==True: rstr=rstr+(i.lower()) elif(i.islower())==True: rstr=rstr+(i.upper()) elif(i.isspace())==True: rstr=rstr+'$' print(rstr)
bhumijaapandey248/Python-Programs-Assignments
assignment16.4.py
assignment16.4.py
py
464
python
en
code
0
github-code
6
71484036668
import sys if sys.version[0] == '2': range, input = xrange, raw_input sys.setrecursionlimit(10 ** 6) MAX_COINS = 500 * 100 INF = 10 ** 9 def dfs(idx, coins): if idx == N: return 0, 0 elif dp[idx][coins] != -1: return dp[idx][coins] ret = (0, -INF) # not buy ret = max(ret, dfs(idx + 1, coins)) # buy using only bills change = (1000 - P[idx] % 1000) % 1000 cand, money = dfs(idx + 1, coins + change % 500) ret = max(ret, (cand + (change >= 500), money - P[idx])) # buy using both and get 500 if (P[idx] + 500) % 1000 <= coins: cand, money = dfs(idx + 1, coins - (P[idx] + 500) % 1000) ret = max(ret, (cand + 1, money - P[idx])) dp[idx][coins] = ret # print(idx, coins, ret) return ret while True: N = int(input()) if not N: break P = [int(input()) for _ in range(N)] dp = [[-1] * (MAX_COINS + 1) for _ in range(N + 1)] ans, money = dfs(0, 0) print(ans, -money)
knuu/competitive-programming
aoj/16/aoj1603.py
aoj1603.py
py
993
python
en
code
1
github-code
6
30665509176
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('cows/', views.cows_index, name='index'), path('cows/<int:cow_id>/', views.cows_detail, name='detail'), path('cows/create/', views.CowCreate.as_view(), name='cows_create'), path('cows/<int:pk>/update/', views.CowUpdate.as_view(), name='cows_update'), path('cows/<int:pk>/delete/', views.CowDelete.as_view(), name='cows_delete'), path('cows/<int:cow_id>/add_feeding/', views.add_feeding, name='add_feeding'), path('cows/<int:cow_id>/assoc_toy/<int:toy_id>/', views.assoc_toy, name='assoc_toy'), path('cows/<int:cow_id>/unassoc_toy/<int:toy_id>/', views.unassoc_toy, name='unassoc_toy'), path('toys/', views.ToyList.as_view(), name='toys_index'), path('toys/<int:pk>/', views.ToyDetail.as_view(), name='toys_detail'), path('toys/create/', views.ToyCreate.as_view(), name='toys_create'), path('toys/<int:pk>/update/', views.ToyUpdate.as_view(), name='toys_update'), path('toys/<int:pk>/delete/', views.ToyDelete.as_view(), name='toys_delete'), ]
jessmucklow/cowcollector
main_app/urls.py
urls.py
py
1,122
python
en
code
1
github-code
6
4343926541
# make all the vowels become "g" def translate(phrase): translation = "" for letter in phrase: if letter.lower() in "aeiou": if letter.isupper(): translation = translation + "G" else: translation = translation + "g " else: translation = translation + letter return translation print(translate(input("Enter a phrase: "))) # if letter.lower in "aeiou" # only have to type out the lower case letters
silviawin/Giraffe_python_exercises
pyTranslator.py
pyTranslator.py
py
516
python
en
code
0
github-code
6
31126701613
from SensorGroup import SensorGroup from DistanceSensor import DistanceSensor import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) r1 = DistanceSensor(21,20,'r1') r2 = DistanceSensor(26,19,'r2') sensorGroup = SensorGroup(sensors=[r1,r2],delay_between_pings_ms =1*1000) try: while True: reading = sensorGroup.measure() print(reading) except KeyboardInterrupt: GPIO.cleanup() except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging # so only use it once your code is working print("Other error or exception occurred!") finally: GPIO.cleanup() # this ensures a clean exit
gregorianrants/technic-bot
technic/distance_sensors/SensorGroup.test.py
SensorGroup.test.py
py
674
python
en
code
0
github-code
6
25168389335
if __name__ == "__main__": list_ = [4, -1, 10, -1, 3, -3, -6, 8, 6, 9] list_n = [i for i in list_ if i % 2 == 1] list_ch = [i for i in list_ if i % 2 == 0] print(list_ch) print(list_n) z_n = len(list_n) z_ch = len(list_ch) if z_n > z_ch: print("Нечетных больше") elif z_n < z_ch: print("Четных больше") elif z_n == z_ch: print("Числа равны")
mur78/PythonPY100
Занятие4/Лабораторные_задания/task1_5/main.py
main.py
py
445
python
ru
code
0
github-code
6
24213867050
from django.contrib import admin from django.urls import path, include from . import views #应用的名称 app_name = 'userprofile' urlpatterns = [ path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('register/', views.user_register, name='register'), #用户信息 path('edit/<int:id>/', views.user_edit, name='edit'), ]
blackjibert/Blog
myblog/userprofile/urls.py
urls.py
py
392
python
en
code
0
github-code
6
6159880936
import sys def sum_int(): filename = sys.argv[1] result = 0 numbers = [] file = open(filename, "r") numbers = file.read() numbers = numbers.split(' ') for i in range(len(numbers)-1): result = result + int(numbers[i]) return result if __name__ == '__main__': print (sum_int())
Vencislav-Dzhukelov/101-3
week2/2-File-System-Problems/sum_numbers.py
sum_numbers.py
py
324
python
en
code
0
github-code
6
35616526877
# https://adventofcode.com/2022/day/15 from dataclasses import dataclass from aoctk.data import Range, weighted_union_size from aoctk.input import get_lines from aoctk.metric import manhattan2d as md @dataclass class Sensor: pos: complex beacon: complex distance: int def __init__(self, desc): self.pos, self.beacon = eval( desc.replace("Sensor at x=", "complex(") .replace("y=", "") .replace(": closest beacon is at x=", "), complex(") + ")" ) self.distance = md(self.beacon, self.pos) def get_intervals(y, sensors): beacons = tuple({int(_.beacon.real) for _ in sensors if _.beacon.imag == y}) intervals = [] for s in sensors: left = s.distance - int(abs(s.pos.imag - y)) if left >= 0: intervals.extend( Range(int(s.pos.real - left), int(s.pos.real + left)).split(*beacons) ) return Range.weighted_union(intervals) def part_one(data="input.txt", y=2000000): return weighted_union_size(get_intervals(y, [Sensor(_) for _ in get_lines(data)])) def part_two(data="input.txt", y=2000000, lo=0, hi=4000000): sensors = [Sensor(_) for _ in get_lines(data)] beacons = {_.beacon for _ in sensors} v_max = hi - lo + 1 for cy in ( _ for p in zip(range(y - 1, lo - 1, -1), range(y + 1, hi + 1)) for _ in p ): intervals = get_intervals(cy, sensors) for i, _ in intervals: i.clip(lo, hi) if weighted_union_size(intervals) < v_max: (x,) = set(range(lo, hi + 1)) - set.union( *(set(i) for i, w in intervals if w > 0) ) if complex(x, cy) not in beacons: return x * 4000000 + cy def test(): assert part_one("test.txt", 10) == 26 assert part_two("test.txt", 10, 0, 20) == 56000011
P403n1x87/aoc
2022/15/code.py
code.py
py
1,883
python
en
code
2
github-code
6
25091116397
# -*- coding: utf-8 -*- """ Created on Thu Aug 8 13:14:13 2019 @author: jordan loll Creating a cards library / deck """ import random from PIL import Image, ImageDraw #Local Path local_path =r"C:\Users\jorda\Documents\PythonPrograms\Questar\Git_Stuff\Quest-Game" #local_path = r"C:\Users\xTheC\Desktop\Quest\Quest-Game" image_path = local_path+"\Images" # Create the deck # class for format of each card # weapons/armor need a 'slot' on each character class card: def __init__(self, n = "none", i = 'none', t = "none", st = "0", d = "none"): self.title = n self.image = i self.type = t self.stats = st self.desc = d # Weapons, Armor, and any other cards types we need # Perhaps make a class for each type of card instead of one generic form #images im_sw = Image.open(image_path+"\sword.png") # Weapons sword = card("Sword", im_sw, "1-Handed Weapon", 10, "Sharp Steel") spear = card("Spear", "image", "2-Handed Weapon", 30, "Deadly at a Distance") # Armor shield = card("Kite Shield", "shield image", "1-Handed", 20, "Impenetrable") #print(sword.title, sword.type) #print(sword.stats, shield.desc, spear.image) sword.image.show() # Jordan is the best
scottwedge/Quest-Game
Old Files/cards.py
cards.py
py
1,214
python
en
code
0
github-code
6
11296078217
import requests import json data = { "a": "GetBidYiDong", "Token": "29db4b581d67ec1c46a231e09e919671", "c": "StockBidYiDong", "UserID": 19, "day": "20171026" } url = "https://hq.kaipanla.com/w1/api/index.php" respone = requests.post(url, data) respone.encoding = "unicode_escape" result = respone.text print(result) result = result.replace("zhangfu", "涨幅").replace("BidAmount", "成交").replace("sjltp", "市值")\ .replace("BidAmount", "净额").replace("BuyP", "大单占比").replace("Buy100", "买入")\ .replace("Sell100", "卖出").replace("BidAmount", "净额").replace("Plate", "概念") for p in json.loads(result)["List"]: print("--------------------------------------------------------------------------------") print(p)
mykright/auto_stock_search
竞价.py
竞价.py
py
778
python
en
code
3
github-code
6
38722538066
import pandas as pd import numpy as np import tensorflow as tf import sklearn.model_selection as sk import helper as hp import preprocessing as pre import machine_learning as ml import json import os from flask import Flask, redirect, url_for, request, jsonify from tensorflow.keras import layers from tensorflow.keras.models import load_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' ML_model = None ML_history = None graph = None titles = None classes = None targets = None categories = None training_type = 0 app = Flask(__name__) @app.route('/') def initialize(): return 'Use /Train or /Predict' @app.route('/Train', methods = ['POST']) def Train(): global ML_model global ML_history global classes global titles global targets global categories global graph # Getting the POST Request Body Data Data = request.data # Converting Text/Plain to JSON Structure JsonData = json.loads(Data) # Extracting product titles and product classes titles = JsonData["products"] targets = JsonData["classes"] training_type = JsonData["training_type"] # 1 is Very Small (80 vec size, Hidden Layers (1024,512)) # 2 is Small (200 vec size, Hidden Layers (2048,1024)) # 3 is Large (200 vec size, Hidden Layers (2048,1024,1024)) if(len(titles) == len(targets)): # Preprocessing of data # Converts target to multi classes array where [1,0,0,0,0,0,....] corresponds to class 1 and [0,1,0,0,0,0,....] corresponds to class 2 labels, classes, categories = hp.Get_Targets_Arrays(targets) print(categories) # Converts products titles to vectors pre.Doc2Vectors(titles, training_type) # Creating Vectors List for all products -> Dataset Vectors_List = hp.Get_Product_Vectors(len(titles),training_type) # Splitting Data to Train, Validate and Test sets train_data, train_labels, val_data, val_labels, test_data, test_labels = pre.Data_Split(Vectors_List,labels) # Training if(training_type == 1): ML_model, ML_history = ml.Train_1(train_data, train_labels, val_data, val_labels, len(labels[0])) else: if(training_type ==2): ML_model, ML_history = ml.Train_2(train_data, train_labels, val_data, val_labels, len(labels[0])) else: ML_model, ML_history = ml.Train_3(train_data, train_labels, val_data, val_labels, len(labels[0])) graph = tf.get_default_graph() # Evaluating the trained model results = ML_model.evaluate(test_data, test_labels) response = "Training Completed with testing scores of " + str(results[1]) + " accuracy and " + str(results[0]) + " Loss" return response else: return "Products and Classes don't have the same length" @app.route('/Predict',methods = ['POST']) def Predict(): global ML_model global classes global categories global training_type # Getting the POST Request Body Data Data = request.data # Converting Text/Plain to JSON Structure JsonData = json.loads(Data) # Extracting product titles and product classes titles = JsonData["products"] # Get the product title for prediction from the GET Request #title = request.args.get('product') # Convert the title to vector based on the titles vector model done in the training process #v = hp.Get_Products_Title_Vector(titles) # Load model weights for predictins ML_model = load_model("weights") ML_model._make_predict_function() predicted_classes = [] for title in titles: v = hp.Get_Product_Title_Vector(title) # Predictions pred = ML_model.predict(v) max_index = np.argmax(pred) predicted_class = categories[max_index] predicted_classes.append(predicted_class) response = { "predictions":predicted_classes, } return jsonify(response) if __name__ == '__main__': app.run(host='0.0.0.0', port=5010)
ahmedhazemfekry/Neural-Network-Flask-Server
server.py
server.py
py
4,067
python
en
code
0
github-code
6
36724497528
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Count from django.http import Http404 from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse_lazy, reverse from django.utils import timezone from django.views.generic import UpdateView, ListView, DeleteView from .forms import NewTopicForm, NewPostForm from .models import ( Board, Topic, Post ) class BoardListView(ListView): model = Board context_object_name = 'boards' template_name = 'home.html' class TopicListView(ListView): model = Topic context_object_name = 'topics' paginate_by = 20 def get_context_data(self, **kwargs): kwargs['board'] = self.board return super().get_context_data(**kwargs) def get_queryset(self): self.board = get_object_or_404(Board, pk=self.kwargs.get('pk')) queryset = self.board.topics.order_by('-last_update').annotate( replies=Count('posts') - 1) return queryset @login_required def topic_new(request, pk): board = get_object_or_404(Board, pk=pk) if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): user = request.user topic = form.save(commit=False) topic.board = board topic.starter = user topic.save() message = form.cleaned_data.get('message') Post.objects.create( message=message, topic=topic, created_by=user, ) return redirect('boards:topic-posts', pk=pk, topic_pk=topic.pk) else: form = NewTopicForm() context = { 'board': board, 'form': form } return render(request, 'boards/topic_new.html', context) class PostListView(ListView): model = Post context_object_name = 'posts' paginate_by = 20 def get_context_data(self, **kwargs): session_key = f'viewed_topic_{self.topic.id}' if not self.request.session.get(session_key, False): self.topic.views += 1 self.topic.save() self.request.session[session_key] = True kwargs['topic'] = self.topic return super().get_context_data(**kwargs) def get_queryset(self): self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk')) queryset = self.topic.posts.order_by('created_at') return queryset @login_required def topic_reply(request, pk, topic_pk): topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk) if request.method == "POST": form = NewPostForm(request.POST) if form.is_valid(): user = request.user post = form.save(commit=False) post.topic = topic post.created_by = user post.save() topic.last_update = timezone.now() topic.save() topic_url = reverse('boards:topic-posts', kwargs={ 'pk': topic.board.pk, 'topic_pk': topic.pk }) topic_post_url = f'{topic_url}?page={topic.get_page_count()}#{post.pk}' return redirect(topic_post_url) else: form = NewPostForm() context = { 'form': form, 'topic': topic } return render(request, 'boards/topic_reply.html', context) class PostEditView(LoginRequiredMixin, UpdateView): model = Post fields = ('message',) template_name = 'boards/post_edit.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): queryset = super().get_queryset() if not self.request.user.is_staff: queryset = queryset.filter(created_by=self.request.user) return queryset def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.save() return redirect('boards:topic-posts', pk=post.topic.board.pk, topic_pk=post.topic.pk) class TopicDeleteView(DeleteView): def get_object(self, queryset=None): user = self.request.user board_pk = self.kwargs.get('pk') topic_pk = self.kwargs.get('topic_pk') topic = get_object_or_404(Topic, board__pk=board_pk, pk=topic_pk) if not topic.starter == user and not user.is_staff: raise Http404 return topic def get_success_url(self): board_pk = self.kwargs.get('pk') return reverse_lazy('boards:topic-list', kwargs={'pk': board_pk})
zawi99/web-boards
boards/views.py
views.py
py
4,855
python
en
code
0
github-code
6
23936105649
import numpy as np from scipy.io import loadmat from variables import* def load_mat_file(mat_file): mat_data = loadmat(mat_file) x, y = mat_data['X'], mat_data['y'] x = x.reshape( -1, input_shape[0], input_shape[1], input_shape[2] ) y = y.reshape(-1,) return x, y def load_data(): X, Y = load_mat_file(train_dir) Xtest, Ytest = load_mat_file(test_dir) X = X/rescale Xtest = Xtest/rescale return X, Y, Xtest, Ytest
1zuu/SVHN-Image-Classification
util.py
util.py
py
543
python
en
code
0
github-code
6
22458997174
import flask from flask import Flask,request,jsonify import json from sqlib import cek_data_user, input_data,input_dataa, show_data, node1_suhu, node1_kelembapanudara, node1_kelembapantanah, node1_keltanah_konversi, node1_intensitascahaya, node1_curahhujan, node1_curahhujan_konversi, node2_suhu, node2_kelembapanudara, node2_kelembapantanah, node2_keltanah_konversi, node2_curahhujan, node2_curahhujan_konversi ,node2_intensitascahaya, show_dataa,input_user,cek_username,update_ip app = Flask(__name__) @app.route('/monitor/node1', methods=['POST']) def node1(): json_data = flask.request.json if json_data ==None: result = {"pesan":"data not found"} resp = jsonify(result) return resp,404 else : if 'Suhu' not in json_data or 'Kelembapan_udara' not in json_data or 'Intensitas_cahaya' not in json_data or 'Curah_hujan' not in json_data or 'Kelembapan_tanah' not in json_data : result = {"pesan": "bad request"} resp = jsonify(result) return resp,403 else : Suhu = json_data ['Suhu'] Kelembapan_udara = json_data ['Kelembapan_udara'] Intensitas_cahaya = json_data ['Intensitas_cahaya'] Curah_hujan = json_data ['Curah_hujan'] Kelembapan_tanah = json_data ['Kelembapan_tanah'] input_data(Suhu,Kelembapan_udara,Intensitas_cahaya,Curah_hujan,Kelembapan_tanah) result = {"pesan" : " input berhasil"} resp= jsonify(result) return resp, 200 @app.route('/monitor/node2', methods=['POST']) def node2(): json_data = flask.request.json if json_data ==None: result = {"pesan":"data not found"} resp = jsonify(result) return resp,404 else : if 'Suhu' not in json_data or 'Kelembapan_udara' not in json_data or 'Intensitas_cahaya' not in json_data or 'Curah_hujan' not in json_data or 'Kelembapan_tanah' not in json_data : result = {"pesan": "bad request"} resp = jsonify(result) return resp,403 else : Suhu = json_data ['Suhu'] Kelembapan_udara = json_data ['Kelembapan_udara'] Intensitas_cahaya = json_data ['Intensitas_cahaya'] Curah_hujan = json_data ['Curah_hujan'] Kelembapan_tanah = json_data ['Kelembapan_tanah'] input_dataa (Suhu,Kelembapan_udara,Intensitas_cahaya,Curah_hujan,Kelembapan_tanah) result = {"pesan" : " input berhasil"} resp= jsonify(result) return resp, 200 @app.route('/monitor/node1', methods=['GET']) def monitor_node1() : resp = show_data() return resp,200 @app.route('/monitor/suhu', methods=['GET']) def monitor_suhu() : resp = node1_suhu() return resp,200 @app.route('/monitor/udara', methods=['GET']) def monitor_udara() : resp = node1_kelembapanudara() return resp,200 @app.route('/monitor/tanah', methods=['GET']) def monitor_tanah() : resp = node1_kelembapantanah() return resp,200 @app.route('/monitor/tanahkonversi', methods=['GET']) def monitor_tanahkonversi() : resp = node1_keltanah_konversi() return resp,200 @app.route('/monitor/cahaya', methods=['GET']) def monitor_cahaya() : resp = node1_intensitascahaya() return resp,200 @app.route('/monitor/hujan', methods=['GET']) def monitor_hujan() : resp = node1_curahhujan() return resp,200 @app.route('/monitor/hujankonversi', methods=['GET']) def monitor_hujankonversi() : resp = node1_curahhujan_konversi() return resp,200 @app.route('/monitor/node2', methods=['GET']) def monitor_node2() : resp = show_dataa() return resp,200 @app.route('/monitor/suhu2', methods=['GET']) def monitor_suhu2() : resp = node2_suhu() return resp,200 @app.route('/monitor/udara2', methods=['GET']) def monitor_udara2() : resp = node2_kelembapanudara() return resp,200 @app.route('/monitor/tanah2', methods=['GET']) def monitor_tanah2() : resp = node2_kelembapantanah() return resp,200 @app.route('/monitor/tanahkonversi2', methods=['GET']) def monitor_tanahkonversi2() : resp = node2_keltanah_konversi() return resp,200 @app.route('/monitor/cahaya2', methods=['GET']) def monitor_cahaya2() : resp = node2_intensitascahaya() return resp,200 @app.route('/monitor/hujan2', methods=['GET']) def monitor_hujan2() : resp = node2_curahhujan() return resp,200 @app.route('/monitor/hujankonversi2', methods=['GET']) def monitor_hujankonversi2() : resp = node2_curahhujan_konversi() return resp,200 @app.route('/monitor/register/user',methods=['POST']) def user_register(): json_data = request.json if json_data==None: result = {"pesan":"data not found"} resp = jsonify(result) return resp,404 else: if 'Username' not in json_data or 'Password' not in json_data or 'IP_Address' not in json_data: result = {"pesan": "bad request"} resp = jsonify(result) return resp,403 else: Username = json_data['Username'] Password = json_data['Password'] IP_Address = json_data['IP_Address'] cek = cek_username(Username) if cek == False: result = {"pesan" : " User Already Existed"} resp= jsonify(result) return resp, 208 else: input_user(Username,Password,IP_Address) result = {"pesan" : " input berhasil"} resp= jsonify(result) return resp, 200 @app.route('/monitor/login/user',methods=['POST']) def user_login(): json_data = request.json if json_data==None: result = {"pesan":"data not found"} resp = jsonify(result) return resp,404 else: if 'Username' not in json_data or 'Password' not in json_data or 'IP_Address' not in json_data: result = {"pesan": "bad request"} resp = jsonify(result) return resp,403 else: Username = json_data['Username'] Password = json_data['Password'] IP_Address = json_data['IP_Address'] cek = cek_data_user(Username,Password) if cek==False: result = {"pesan": "Forbidden"} resp = jsonify(result) return resp,203 else: update_ip(IP_Address,Username,Password) result = {"pesan" : " Selamat Datang "+Username} resp= jsonify(result) return resp, 200 if __name__ == "__main__" : #serve(app, host="0.0.0.0", port=4001) app.run(port=4001, debug=True)
triani16/Aplikasi-Monitoring-Tanaman
penerima.py
penerima.py
py
6,735
python
en
code
0
github-code
6
71969681149
"""This module is useful for generating yaml files for the withParams tests and for running unformal compiler tests during development.""" import time from kfp.compiler import compiler from kfp import dsl from kfp.dsl import _for_loop class Coder: def __init__(self, ): self._code_id = 0 def get_code(self, ): self._code_id += 1 return '{code:0{num_chars:}d}'.format(code=self._code_id, num_chars=_for_loop.LoopArguments.NUM_CODE_CHARS) dsl.ParallelFor._get_unique_id_code = Coder().get_code if __name__ == '__main__': do_output = True params = {} if do_output: @dsl.pipeline(name='my-pipeline') def pipeline(): op0 = dsl.ContainerOp( name="my-out-cop0", image='python:alpine3.6', command=["sh", "-c"], arguments=['python -c "import json; import sys; json.dump([{\'a\': 1, \'b\': 2}, {\'a\': 10, \'b\': 20}], open(\'/tmp/out.json\', \'w\'))"'], file_outputs={'out': '/tmp/out.json'}, ) with dsl.ParallelFor(op0.output) as item: op1 = dsl.ContainerOp( name="my-in-cop1", image="library/bash:4.4.23", command=["sh", "-c"], arguments=["echo do output op1 item.a: %s" % item.a], ) op_out = dsl.ContainerOp( name="my-out-cop2", image="library/bash:4.4.23", command=["sh", "-c"], arguments=["echo do output op2, outp: %s" % op0.output], ) job_name = f'do-output=TRUE-passed-{time.time()}' else: @dsl.pipeline(name='my-pipeline') def pipeline(loopidy_doop=[{'a': 1, 'b': 2}, {'a': 10, 'b': 20}]): op0 = dsl.ContainerOp( name="my-out-cop0", image='python:alpine3.6', command=["sh", "-c"], arguments=['python -c "import json; import sys; json.dump([i for i in range(20, 31)], open(\'/tmp/out.json\', \'w\'))"'], file_outputs={'out': '/tmp/out.json'}, ) with dsl.ParallelFor(loopidy_doop) as item: op1 = dsl.ContainerOp( name="my-in-cop1", image="library/bash:4.4.23", command=["sh", "-c"], arguments=["echo no output global op1, item: %s" % item.a], ).after(op0) op_out = dsl.ContainerOp( name="my-out-cop2", image="library/bash:4.4.23", command=["sh", "-c"], arguments=["echo no output global op2, outp: %s" % op0.output], ) job_name = f'do-output=FALSE-global-{time.time()}' yaml_text = compiler.Compiler().compile(pipeline, None) print(yaml_text) import kfp import time client = kfp.Client(host='127.0.0.1:8080/pipeline') print(client.list_experiments()) pkg_path = '/tmp/witest_pkg.tar.gz' compiler.Compiler().compile(pipeline, package_path=pkg_path) exp = client.create_experiment('withparams_exp') client.run_pipeline( experiment_id=exp.id, job_name=job_name, pipeline_package_path=pkg_path, params=params, )
kubeflow/kfp-tekton-backend
sdk/python/tests/compiler/compiler_withparams_test_helper.py
compiler_withparams_test_helper.py
py
3,332
python
en
code
8
github-code
6
71997536508
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import * from .models import * # from my side... @login_required(login_url='/useraccount/common_login') def business_location_list(request): if request.method == 'POST': form = BusinessLocationForm(request.POST) if form.is_valid(): form_save = form.save(commit=False) form_save.save() if form_save.location_id == '' or form_save.location_id == None: form_save.location_id = 'LOC-1000' + str(form_save.id) form_save.save() messages.success(request, 'added a business location ' + str(form_save.name)) return redirect('business-location') else: form = BusinessLocationForm() list_locations = BusinessLocation.objects.filter(status=True).order_by('-id') return render(request, 'divmart_dashboard/business_location_list.html', {'lists':list_locations,'form':form}) @login_required(login_url='/useraccount/common_login') def business_location_update(request, id): loc_obj = BusinessLocation.objects.get(id=id) if request.method == 'POST': form = BusinessLocationForm(request.POST, instance=loc_obj) if form.is_valid(): form.save() messages.success(request, str(loc_obj.name) +' update success...') return redirect('business-location') else: form = BusinessLocationForm(instance=loc_obj) return render(request, 'divmart_dashboard/business_location_edit.html', {'form':form, 'loc_obj':loc_obj}) @login_required(login_url='/useraccount/common_login') def business_location_delete(request, id): loc_obj = BusinessLocation.objects.get(id=id) if loc_obj: loc_obj.status = False loc_obj.save() messages.info(request, str(loc_obj.name) + ' remove success..') return redirect('business-location') @login_required(login_url='/useraccount/common_login') def add_tax_rate(request): if request.method == 'POST': form = TaxRateForm(request.POST) if form.is_valid(): form_save = form.save(commit=False) form_save.status = True form_save.save() return redirect('tax-rate') else: form = TaxRateForm() tax_rates = TaxRate.objects.filter(status=True) return render(request, 'divmart_dashboard/tax_rate.html', {'rates':tax_rates}) @login_required(login_url='/useraccount/common_login') def edit_tax_rate(request, id): tax_rate_obj = TaxRate.objects.get(id=id, status=True) if request.method == 'POST': form = TaxRateForm(request.POST, instance = tax_rate_obj) if form.is_valid(): form.save() return redirect('tax-rate') else: form = TaxRateForm(instance=tax_rate_obj) return render(request, 'divmart_dashboard/tax_rate_edit.html', {'obj':tax_rate_obj}) @login_required(login_url='/useraccount/common_login') def delete_tax_rate(request, id): tax_rate_obj = TaxRate.objects.get(id=id, status=True) tax_rate_obj.status = False tax_rate_obj.save() return redirect('tax-rate')
chaitphani/New-DivMart
div_settings/views.py
views.py
py
3,238
python
en
code
0
github-code
6
70720136829
import re from zipfile import ZipFile nothing = 90052 nothings = [] with ZipFile('channel.zip', 'r') as myzip: def get_path(nothing): return '{0}.txt'.format(nothing) def get_next_nothing(nothing): data = myzip.read(get_path(nothing)).decode('utf-8') m = re.search('(\d*)$', data) next_nothing = m.group(1) return next_nothing def get_comment(nothing): return myzip.getinfo(get_path(nothing)).comment.decode('utf-8') while(1): try: if nothing: nothings.append(nothing) nothing = get_next_nothing(nothing) except: break print("".join([get_comment(n) for n in nothings])) #http://www.pythonchallenge.com/pc/def/oxygen.html
akiran/pythonchallenge
challenge7.py
challenge7.py
py
758
python
en
code
0
github-code
6
17652959673
saver = tf.train.Saver() session=tf.InteractiveSession() # Initializing the variables session.run(tf.global_variables_initializer()) for itr in range(training_iters): offset = (itr * batch_size) % (labels.shape[0] - batch_size) batch_x = X_train[offset:(offset + batch_size), :, :] batch_y = y_train[offset:(offset + batch_size), :] _, c = session.run([optimizer, loss_f],feed_dict={x: batch_x, y : batch_y, keep_prob: 0.95}) if itr % display_step == 0: # Calculate batch accuracy acc = session.run(accuracy, feed_dict={x: batch_x, y: batch_y, keep_prob: 1}) # Calculate batch loss loss = session.run(loss_f, feed_dict={x: batch_x, y: batch_y, keep_prob: 1}) print("Iter " + str(itr) + ", Minibatch Loss= " + \ "{:.6f}".format(loss) + ", Training Accuracy= " + \ "{:.5f}".format(acc)) print('Test accuracy: ',round(session.run(accuracy, feed_dict={x: X_test, y: y_test, keep_prob: 1}) , 3)) saver.save(session, save_path = "./model/mfcc_audio.ckpt")
AntoniaLovjer/audio_adversarial_training
train.py
train.py
py
1,065
python
en
code
1
github-code
6
30424017235
import numpy as np import re import operator from Indice_Invertido import Indice_Invertido class Consulta: def formataString(self, s): s = s.lower() s = re.sub("[:,'|.@()?!#$&]"," ", s) s = s.replace("\n", " ") s = re.sub('[^A-Za-z0-9 ]+', '', s) strings = s.split() return strings def __init__(self, queryOriginal, indInv): self.queryOriginal = queryOriginal self.numPalavras = 0 self.indiceDaConsulta = {} self.vetorDaConsulta = np.zeros((indInv.numPalavras,1)) self.resultado = {} self.documentos = {} self.formataQuery() self.constroiIndiceConsulta(indInv) def formataQuery (self): palavrasNaConsulta = self.formataString(self.queryOriginal) for palavra in palavrasNaConsulta: if palavra in self.indiceDaConsulta: self.indiceDaConsulta[palavra] += 1 else: self.indiceDaConsulta[palavra] = 1 self.numPalavras += 1 def constroiIndiceConsulta(self, indInv): palavrasCoincidentes = 0 indicePalavra = 0; for palavra, docs in indInv.indice.items(): if palavra in self.indiceDaConsulta.keys(): nx = len(docs) idf = np.log(indInv.numDocs/nx) w = self.indiceDaConsulta[palavra] * idf self.vetorDaConsulta[indicePalavra,0] = w palavrasCoincidentes+=1 indicePalavra+=1 if palavrasCoincidentes != 0: self.verificaConsulta(indInv) else: print("Nada a fazer") def verificaConsulta(self, indInv): Q = self.vetorDaConsulta for i in range(np.shape(indInv.coordenadas)[1]): vec = indInv.coordenadas[:, i] vec = vec.reshape((len(vec),1)) similaridade = (vec.T @ Q)/(np.linalg.norm(vec) * np.linalg.norm(Q)) self.resultado[i] = similaridade[0][0] self.organizaResultado(indInv) def organizaResultado(self, indInv): for idDoc, similaridade in self.resultado.items(): if similaridade != 0: for nomeDoc, idDocIndInv in indInv.arquivos.items(): if idDoc == idDocIndInv: self.documentos[nomeDoc] = similaridade self.documentos = sorted(self.documentos.items(), key=operator.itemgetter(1))
pdrsa/PSE
code/Consulta.py
Consulta.py
py
2,563
python
pt
code
0
github-code
6
13453404410
import sqlite3 from flask import Flask import json app = Flask(__name__) @app.route('/animals/<idx>') def animals(idx): with sqlite3.connect("animal.db") as connection: cursor = connection.cursor() query = f""" select * from animals_final left join outcomes on outcomes.animal_id = animals_final.animal_id where animals_final.id = {idx} """ cursor.execute(query) result = cursor.fetchall() if len(result) == 1: line = result[0] result_dict = {} number = 1 for i in line: result_dict[f"{number}"] = i number += 1 else: result_dict = "Nothing found" return json.dumps(result_dict) app.run(debug=True, port=5001)
aquwue/lesson_15
main_program.py
main_program.py
py
812
python
en
code
0
github-code
6
18805686608
# 3 - Imprima os 10 primeiros números naturais após um número inserido no console usando um loop while: num = int(input('Informe um número: ')) contador = 0 while (contador < 10): if num > 0: num += 1 contador += 1 print(num) else: print('erro!, não existem números naturais negativos') break
chrystian-souza/exercicios_em_python
exerciciosAula4/exercicio03.py
exercicio03.py
py
352
python
pt
code
0
github-code
6
17996198287
# -*- coding:utf-8 -*- # 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 # 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return nums[0] g = l = -10000000 for n in nums: l = max(n, n + l) g = max(l, g) return g if __name__ == '__main__': print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
shirleychangyuanyuan/LeetcodeByPython
53-最大子序和.py
53-最大子序和.py
py
672
python
zh
code
0
github-code
6
13680558659
""" Production Settings """ import os import dj_database_url from .dev import * ############ # SECURITY # ############ DEBUG = bool(os.getenv('DJANGO_DEBUG', '')) SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', SECRET_KEY) ALLOWED_HOSTS = ['*'] ########### # LOGGING # ########### LOGGING = { 'version': 1, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers':['console'], 'propagate': True, 'level':'DEBUG', } }, }
team-terminus17/dublin_bus
backend/settings/prod.py
prod.py
py
604
python
en
code
1
github-code
6
28749398084
import urllib2 import json import mraa import threading import sys import time moveSensor = mraa.Gpio(20) moveSensor.dir(mraa.DIR_IN) soundSensor = mraa.Gpio(21) soundSensor.dir(mraa.DIR_IN) fotoSensor = mraa.Gpio(43) fotoSensor.dir(mraa.DIR_IN) gasSensor = mraa.Gpio(17) gasSensor.dir(mraa.DIR_IN) def update(): threading.Timer(3.0, update).start() moveVal = moveSensor.read() if (moveVal == 1): moveValue = True else: moveValue = False gasVal = gasSensor.read() if (gasVal == 0): gasValue = True else: gasValue = False fotoVal = fotoSensor.read() if (fotoVal == 1): fotoValue = True else: fotoValue = False soundVal = soundSensor.read() if (soundVal == 1): soundValue = True else: soundValue = False url = 'http://%s:5000/api/rooms/0' % host data = json.dumps({'movement': moveValue, 'gas': gasValue, 'light': fotoValue, 'noise': soundValue, 'timestamp': time.time()}) req = urllib2.Request(url, data, {'Content-Type': 'application/json'}) f = urllib2.urlopen(req) response = f.read() f.close() host = sys.argv[1] update();
Jasiu0/SmartGlassIoT
client-linkit/rest_client.py
rest_client.py
py
1,172
python
en
code
0
github-code
6
18028682844
from pyfiglet import Figlet import os from shutil import copyfile import shutil import sqlite3 import subprocess import winreg import base64 import subprocess import datetime import socket import ctypes def init(): f = Figlet(font='slant') print(f.renderText('Reboot')) print("This program is Artifact collecter\n") def showOptions(): print("\n==========Options==========") print("1) Memory Dump") print("2) Registry Hive") print("3) System Info") print("4) System Audit Policy") print("5) Group Policy") print("6) Event Viewer Log") print("7) Services Log") print("8) Hosts Data") print("9) SRUM (System Resource Utilization Monitor)") print("10) Environment Variables") print("11) Patch List") print("12) Process List") print("13) Opened Port") print("14) IP Config Info") print("15) ARP Info") print("16) Net BIOS") print("17) Opened Handle") print("18) Task Schedule Info") print("19) System Logon Info") print("20) UserAssist") print("21) AutoRun") print("22) Registry User") print("23) Internet Browser History") print("24) Recycle Bin") print("25) LNK File") print("26) PowerShell Log File") print("27) Registerd Service Info") print("28) Recent Activity Info") print("29) Prefetch") print("30) NTFS Artifact") print("777) ALL") print("0) exit program") def registryHive(): print("\n==========Registry Hive File==========") current_directory = os.getcwd() export_registry_hive(current_directory, winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE") export_registry_hive(current_directory, winreg.HKEY_CURRENT_USER, r"Software") def export_registry_hive(output_directory, hive_name, hive_path): registry_folder = os.path.join(output_directory, "RegistryHive") if not os.path.exists(registry_folder): os.makedirs(registry_folder) try: with winreg.ConnectRegistry(None, hive_name) as hive: hive_output_file = os.path.join(registry_folder, f"{hive_name}_hive.txt") with open(hive_output_file, 'w', encoding='utf-16') as file: def export_subkeys(key, indent=""): for i in range(winreg.QueryInfoKey(key)[0]): subkey_name = winreg.EnumKey(key, i) subkey_path = os.path.join(hive_path, subkey_name) file.write(f"{indent}[{subkey_path}]\n") with winreg.OpenKey(key, subkey_name) as subkey: export_subkeys(subkey, indent + " ") export_subkeys(hive) print(f"{hive_name} hive exported to {hive_output_file}") except Exception as e: print(f"Error: {e}") def systemInfo(): print("\n==========System Info File==========") subprocess.run(['systeminfo'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') output_directory = os.getcwd() system_info_folder = os.path.join(output_directory, "SystemInfo") if not os.path.exists(system_info_folder): os.makedirs(system_info_folder) try: system_info_output_file = os.path.join(system_info_folder, "system_info.txt") with open(system_info_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput('systeminfo')) print(f"System info exported to {system_info_output_file}") except Exception as e: print(f"Error: {e}") def systemAudit(): print("\n==========System Audit Policy File==========") subprocess.run(['auditpol', '/get', '/category:*'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') output_directory = os.getcwd() audit_policy_folder = os.path.join(output_directory, "AuditPolicy") if not os.path.exists(audit_policy_folder): os.makedirs(audit_policy_folder) try: audit_policy_output_file = os.path.join(audit_policy_folder, "audit_policy_info.txt") with open(audit_policy_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput('auditpol /get /category:*')) print(f"Audit policy info exported to {audit_policy_output_file}") except Exception as e: print(f"Error: {e}") def groupPolicy(): print("\n==========Group Policy File==========") subprocess.run(['gpresult', '/R'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') output_directory = os.getcwd() group_policy_folder = os.path.join(output_directory, "GroupPolicy") if not os.path.exists(group_policy_folder): os.makedirs(group_policy_folder) try: group_policy_output_file = os.path.join(group_policy_folder, "group_policy_info.txt") with open(group_policy_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput('gpresult /R')) print(f"Group policy info exported to {group_policy_output_file}") except Exception as e: print(f"Error: {e}") def eventLog(): print("\n==========Event Viewer Log File==========") output_directory = os.getcwd() event_logs_folder = os.path.join(output_directory, "EventLogs") if not os.path.exists(event_logs_folder): os.makedirs(event_logs_folder) try: # 시스템 이벤트 로그 내용 가져오기 system_log_output_file = os.path.join(event_logs_folder, "system_event_log.txt") subprocess.run(['wevtutil', 'qe', 'System', '/f:text', '/c:1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') with open(system_log_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput(f'wevtutil qe System /f:text /c:1')) print(f"System event log exported to {system_log_output_file}") # 응용 프로그램 이벤트 로그 내용 가져오기 application_log_output_file = os.path.join(event_logs_folder, "application_event_log.txt") subprocess.run(['wevtutil', 'qe', 'Application', '/f:text', '/c:1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') with open(application_log_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput(f'wevtutil qe Application /f:text /c:1')) print(f"Application event log exported to {application_log_output_file}") except Exception as e: print(f"Error: {e}") def serviceLog(): print("\n==========Service Log File==========") output_directory = os.getcwd() service_log_folder = os.path.join(output_directory, "ServiceLog") if not os.path.exists(service_log_folder): os.makedirs(service_log_folder) try: # 서비스 로그를 가져와서 파일로 저장 service_log_output_file = os.path.join(service_log_folder, "service_log.txt") subprocess.run(['net', 'start'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True, encoding='utf-8') with open(service_log_output_file, 'w', encoding='utf-8') as file: file.write(subprocess.getoutput('net start')) print(f"Service log exported to {service_log_output_file}") except Exception as e: print(f"Error: {e}") def hostsData(): print("\n==========Hosts Data File==========") output_directory = os.getcwd() hosts_folder = os.path.join(output_directory, "Hosts") if not os.path.exists(hosts_folder): os.makedirs(hosts_folder) try: hosts_file_path = r"C:\Windows\System32\drivers\etc\hosts" # Hosts 파일 경로 hosts_output_file = os.path.join(hosts_folder, "hosts.txt") with open(hosts_file_path, 'r', encoding='utf-8') as input_file, open(hosts_output_file, 'w', encoding='utf-8') as output_file: hosts_content = input_file.read() output_file.write(hosts_content) print(f"Hosts file exported to {hosts_output_file}") except Exception as e: print(f"Error: {e}") def srum(): print("\n==========SRUM File==========") output_directory = os.getcwd() srum_folder = os.path.join(output_directory, "SRUM") if not os.path.exists(srum_folder): os.makedirs(srum_folder) try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SRUM\Extensions", 0, winreg.KEY_READ) as key: i = 0 while True: try: subkey_name = winreg.EnumKey(key, i) subkey_path = os.path.join(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SRUM\Extensions", subkey_name) with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey_path, 0, winreg.KEY_READ) as subkey: j = 0 while True: try: value_name, srum_data, _ = winreg.EnumValue(subkey, j) # 각 데이터를 파일로 저장 (바이너리 모드 또는 문자열 모드로 열기) srum_output_file = os.path.join(srum_folder, f"{subkey_name}_{value_name}.txt") with open(srum_output_file, 'wb' if isinstance(srum_data, bytes) else 'w') as file: if isinstance(srum_data, bytes): file.write(srum_data) else: file.write(str(srum_data)) print(f"SRUM data from {subkey_name}/{value_name} exported to {srum_output_file}") j += 1 except OSError as e: break i += 1 except OSError as e: break if i == 0: print("No SRUM data found.") except Exception as e: print(f"Error: {e}") def environmentVar(): print("\n==========Envionment Variable File==========") output_directory = os.getcwd() environ_var_folder = os.path.join(output_directory, "EnvironmentVar") if not os.path.exists(environ_var_folder): os.makedirs(environ_var_folder) output_file = os.path.join(environ_var_folder, "environment_variables.txt") try: with open(output_file, 'w') as file: for key, value in os.environ.items(): file.write(f"{key} = {value}\n") print(f"Environment variables exported to {output_file}") except Exception as e: print(f"Error: {e}") def patchList(): print("\n==========Patch List File==========") output_directory = os.getcwd() patch_list_folder = os.path.join(output_directory, "PatchList") if not os.path.exists(patch_list_folder): os.makedirs(patch_list_folder) try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key: i = 0 while True: try: package_name = winreg.EnumKey(key, i) patch_list_file = os.path.join(patch_list_folder, f"{package_name}.txt") with open(patch_list_file, 'w') as file: file.write(package_name) i += 1 except OSError as e: break if i > 0: print(f"Patch list exported to {patch_list_folder}") else: print("No patch list information found.") except Exception as e: print(f"Error: {e}") def processList(): print("\n==========Process List File==========") file_path = os.getcwd() file_path = os.path.join(file_path, "ProcessList") if not os.path.exists(file_path): os.makedirs(file_path) file_path = os.path.join(file_path, "process_list.txt") process_info_list = [] for process in psutil.process_iter(attrs=['pid', 'name', 'username', 'memory_info']): info = process.info pid = info['pid'] name = info['name'] username = info['username'] memory = info['memory_info'].rss # Resident Set Size: 메모리 사용량 process_info = f"PID: {pid}, Process Name: {name}, User: {username}, Memory: {memory} bytes" process_info_list.append(process_info) with open(file_path, 'w') as f: for process in process_info_list: f.write(process + '\n') print(f"실행 중인 프로세스 정보가 {file_path} 에 저장되었습니다.") def openPort(): print("\n==========Open Port File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "OpenPort") if not os.path.exists(destination_folder): os.makedirs(destination_folder) file_path = os.path.join(destination_folder, "open_ports.txt") open_ports = [] for conn in psutil.net_connections(kind='inet'): laddr, raddr, status, pid = conn.laddr, conn.raddr, conn.status, conn.pid if raddr: open_ports.append(f"{laddr} <--> {raddr} {status} {pid}") else: open_ports.append(f"{laddr} {status} {pid}") with open(file_path, 'w') as f: for port in open_ports: f.write(f"{port}\n") print(f"Open port information has been saved to {file_path}") def IPConfigInfo(): print("\n==========IP Config File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "IPConfig") if not os.path.exists(destination_folder): os.makedirs(destination_folder) ip_info = {} hostname = socket.gethostname() local_ip = socket.gethostbyname(hostname) ip_info["Hostname"] = hostname ip_info["Local IP"] = local_ip interfaces = psutil.net_if_addrs() for interface, addrs in interfaces.items(): ip_info[interface] = [] for addr in addrs: ip_info[interface].append(str(addr)) filename = os.path.join(destination_folder, f"ip_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") with open(filename, 'w') as f: for key, value in ip_info.items(): f.write(f"{key}: {value}\n") print(f"IP 설정 정보가 {filename} 에 저장되었습니다.") def arpInfo(): print("\n==========ARP Info File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "ARPInfo") if not os.path.exists(destination_folder): os.makedirs(destination_folder) try: # 'arp -a' 명령을 실행하고 결과를 반환받습니다. arp_output = subprocess.check_output("arp -a", shell=True, stderr=subprocess.STDOUT, text=True) except subprocess.CalledProcessError as e: arp_output = f"An error occurred while trying to fetch ARP info: {str(e)}" # 파일 이름에 현재 시간을 추가하여 고유하게 만듭니다. filename = os.path.join(destination_folder, f"arp_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") # ARP 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: f.write(arp_output) print(f"ARP 정보가 {filename} 에 저장되었습니다.") def netBIOS(): print("\n==========Net BIOS File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "NetBIOS") if not os.path.exists(destination_folder): os.makedirs(destination_folder) try: # 'nbtstat -n' 명령을 실행하고 그 결과를 반환합니다. netbios_output = subprocess.check_output("nbtstat -n", shell=True, stderr=subprocess.STDOUT, text=True) except subprocess.CalledProcessError as e: netbios_output = f"An error occurred while trying to fetch NetBIOS info: {str(e)}" # 파일 이름에 현재 시간을 추가해 고유한 파일을 생성합니다. filename = os.path.join(destination_folder, f"netbios_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") # NetBIOS 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: f.write(netbios_output) print(f"NetBIOS 정보가 {filename} 에 저장되었습니다.") def openedHandle(): print("\n==========Opened Handle File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "OpenHandle") if not os.path.exists(destination_folder): os.makedirs(destination_folder) processes = [] for proc in psutil.process_iter(['pid', 'name', 'open_files']): processes.append(proc.info) # 파일 이름에 현재 시간을 추가해 고유한 파일을 생성합니다. filename = os.path.join(destination_folder, f"handle_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") # 핸들 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: for proc in processes: f.write(f"PID: {proc['pid']}, Name: {proc['name']}\n") if proc['open_files']: for open_file in proc['open_files']: f.write(f"\t{open_file}\n") print(f"열려있는 핸들 정보가 {filename} 에 저장되었습니다.") def taskSchedule(): print("\n==========Task Schedule File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "JobSchedule") if not os.path.exists(destination_folder): os.makedirs(destination_folder) try: # 'schtasks' 명령을 실행하고 그 결과를 반환합니다. output = subprocess.check_output("schtasks /query /fo LIST", shell=True, stderr=subprocess.STDOUT, text=True) except subprocess.CalledProcessError as e: output = f"An error occurred while trying to fetch task scheduler info: {str(e)}" # 파일 이름에 현재 시간을 추가해 고유한 파일을 생성합니다. filename = os.path.join(destination_folder, f"task_scheduler_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") # 작업 스케줄러 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: f.write(output) print(f"작업 스케줄 정보가 {filename} 에 저장되었습니다.") def systemLogon(): print("\n==========System Logon File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "SystemLogon") if not os.path.exists(destination_folder): os.makedirs(destination_folder) file_path = os.path.join(destination_folder, "logon_history.txt") query = "wevtutil qe Security /q:\"*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and (EventID=4624)]]\" /c:1 /rd:true /f:text" result = subprocess.run(query, capture_output=True, text=True, shell=True) with open(file_path, 'w') as f: f.write(result.stdout) print(f"시스템 로그온 정보가 {file_path} 에 저장되었습니다.") def memoryDump(): print("\n==========MemoryDump File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "MemoryDump") # "MemoryDump" 폴더 생성 후 저장 if not os.path.exists(destination_folder): os.makedirs(destination_folder) # 메모리 덤프 파일을 저장할 디렉토리 경로 지정 dump_directory = destination_folder # psexec.exe 경로 (psexec을 다운로드한 경로로 설정) psexec_path = os.getcwd() psexec_path = os.path.join(psexec_path, "PSTools") psexec_path = os.path.join(psexec_path, "PsExec.exe") # procdump.exe 경로 (procdump를 설치한 경로로 설정) procdump_path = os.getcwd() procdump_path = os.path.join(procdump_path, "Procdump") procdump_path = os.path.join(procdump_path, "procdump.exe") # 현재 실행 중인 모든 프로세스 가져오기 running_processes = list(psutil.process_iter(attrs=['pid', 'name'])) # 실행 중인 모든 프로세스에 대해 메모리 덤프 생성 for process in running_processes: process_name = process.info['name'] process_pid = process.info['pid'] dump_file_path = os.path.join(dump_directory, f"{process_name}_{process_pid}_dump.dmp") # procdump을 사용하여 메모리 덤프 실행 cmd = [procdump_path, f"-ma", process_name, dump_file_path] try: subprocess.run(cmd, check=True) print(f"{process_name} 프로세스의 메모리 덤프 생성 완료:", dump_file_path) except subprocess.CalledProcessError as e: print(f"{process_name} 프로세스의 메모리 덤프 생성 중 오류 발생:", e) print("모든 프로세스의 메모리 덤프 생성 완료") def userAssist(): print("\n==========UserAssist File==========") keys_to_copy = [ # 실행파일 기록 subkey r"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{CEBFF5CD-ACE2-4F4F-9178-9926F41749EA}\Count", # 바로가기 실행 기록 subkey r"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{F4E57C4B-2036-45F0-A9AB-443BCFE33D9F}\Count" ] current_directory = os.getcwd() destination_folder = os.path.join(current_directory, "UserAssist") if not os.path.exists(destination_folder): os.makedirs(destination_folder) try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, keys_to_copy[0], 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key: userAssistRegistry(key, destination_folder, 1) with winreg.OpenKey(winreg.HKEY_CURRENT_USER, keys_to_copy[1], 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key: userAssistRegistry(key, destination_folder, 2) except Exception as e: print(f"Error: {e}") def sanitize_filename(filename): # 파일 이름에 유효하지 않은 문자를 대체 invalid_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '.', '&', '!', '@', '#', '$', '%', '^', '(', ')', '[', ']', '{', '}', '+', '=', ',', ';', '`', "'", '~', ' '] for char in invalid_chars: filename = filename.replace(char, '_') # 파일 이름을 최대 100자로 제한 return filename[:100] def userAssistRegistry(subkey, output_directory, num): try: if not os.path.exists(output_directory): os.makedirs(output_directory) if num == 1: subkey_name = str(winreg.QueryInfoKey(subkey)[0]) subkey_path = os.path.join(output_directory, "CEBFF5CD-ACE2-4F4F-9178-9926F41749EA") else: subkey_name = str(winreg.QueryInfoKey(subkey)[0]) subkey_path = os.path.join(output_directory, "F4E57C4B-2036-45F0-A9AB-443BCFE33D9F") if not os.path.exists(subkey_path): os.makedirs(subkey_path) i = 0 while True: try: value_name, value_data, _ = winreg.EnumValue(subkey, i) value_output_file = os.path.join(subkey_path, f"{sanitize_filename(value_name)}.txt") # 중간 디렉터리가 없는 경우 생성 value_output_dir = os.path.dirname(value_output_file) if not os.path.exists(value_output_dir): os.makedirs(value_output_dir) with open(value_output_file, 'w') as file: file.write(str(value_data)) # value_data를 문자열로 변환하여 쓰기 i += 1 except OSError as e: print(f"Error while processing subkey {subkey_name}: {e}") break print(f"Data from subkey {subkey_name} has been saved to {subkey_path}") except Exception as e: print(f"Error: {e}") def autoRun(): print("\n==========AutoRun File==========") output_directory = os.getcwd() autorun_folder = os.path.join(output_directory, "AutoRun") if not os.path.exists(autorun_folder): os.makedirs(autorun_folder) try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key: values = {} i = 0 while True: try: value_name, value_data, _ = winreg.EnumValue(key, i) values[value_name] = value_data i += 1 except OSError as e: break if values: output_file = os.path.join(autorun_folder, "autorun_values.txt") with open(output_file, 'w') as file: for name, data in values.items(): file.write(f"{name} = {data}\n") print(f"AutoRun values exported to {output_file}") else: print("No AutoRun values found.") except Exception as e: print(f"Error: {e}") def registryUser(): print("\n==========Registry User File==========") output_directory = os.getcwd() registry_folder = os.path.join(output_directory, "AllUserRegistry") if not os.path.exists(registry_folder): os.makedirs(registry_folder) try: with winreg.ConnectRegistry(None, winreg.HKEY_USERS) as users_hive: with winreg.OpenKey(users_hive, None) as users_key: num_subkeys = winreg.QueryInfoKey(users_key)[0] for i in range(num_subkeys): user_sid = winreg.EnumKey(users_key, i) user_hive_path = f"{user_sid}\\Software" # 사용자 하이브 경로 with winreg.ConnectRegistry(None, winreg.HKEY_USERS) as user_hive: with winreg.CreateKey(user_hive, user_hive_path) as user_key: # 사용자 레지스트리 정보를 파일로 저장 user_output_file = os.path.join(registry_folder, f"{user_sid}_registry.txt") with open(user_output_file, 'w', encoding='utf-16') as file: def export_subkeys(key, indent=""): for j in range(winreg.QueryInfoKey(key)[0]): subkey_name = winreg.EnumKey(key, j) subkey_path = os.path.join(user_hive_path, subkey_name) file.write(f"{indent}[{subkey_path}]\n") with winreg.OpenKey(key, subkey_name) as subkey: export_subkeys(subkey, indent + " ") export_subkeys(user_key) print(f"{user_sid} registry exported to {user_output_file}") except Exception as e: print(f"Error: {e}") def export_registry_key(reg_file, hkey, key_path): try: key = winreg.OpenKey(hkey, key_path) for i in range(winreg.QueryInfoKey(key)[0]): sub_key_name = winreg.EnumKey(key, i) sub_key_path = os.path.join(key_path, sub_key_name) reg_file.write(f'\n[{sub_key_path}]\n') export_registry_key(reg_file, hkey, sub_key_path) for i in range(winreg.QueryInfoKey(key)[1]): value_name, value_data, value_type = winreg.EnumValue(key, i) if value_type == winreg.REG_SZ: reg_file.write(f'"{value_name}"="{value_data}"\n') elif value_type == winreg.REG_DWORD: reg_file.write(f'"{value_name}"=dword:{value_data:08X}\n') # 여러 다른 레지스트리 값 유형에 대한 처리 추가 가능 except Exception as e: pass def save_browser_history(): print("\n==========Browser History File==========") current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "BrowserHistory") # "MemoryDump" 폴더 생성 후 저장 if not os.path.exists(destination_folder): os.makedirs(destination_folder) # 크롬 브라우저의 기록 데이터베이스 경로 chrome_history_path = os.path.expanduser('~') + '\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History' # 복사할 임시 파일 경로 temp_db_path = os.path.join(destination_folder, 'temp_history') # 기록 데이터베이스 파일 복사 copyfile(chrome_history_path, temp_db_path) # 데이터베이스 연결 connection = sqlite3.connect(temp_db_path) cursor = connection.cursor() # 방문 기록 가져오기 cursor.execute("SELECT title, url, last_visit_time FROM urls") history = cursor.fetchall() # 파일로 저장 history_file_path = os.path.join(destination_folder, 'browser_history.txt') with open(history_file_path, 'w', encoding='utf-8') as file: for item in history: title, url, timestamp = item time_formatted = str(timestamp) file.write(f"Title: {title}\nURL: {url}\nTimestamp: {time_formatted}\n\n") # 연결 종료 및 임시 데이터베이스 파일 삭제 cursor.close() connection.close() os.remove(temp_db_path) print("브라우저 기록이 'Browser' 폴더에 저장되었습니다.") def recycleBin(): print("\n==========Recycle Bin File==========") # 'RecycleBin' 폴더 생성 destination_folder = os.path.join(os.getcwd(), 'RecycleBin') if not os.path.exists(destination_folder): os.makedirs(destination_folder) try: # Powershell 스크립트 실행 script_path = os.path.join(os.path.dirname(__file__), 'copy_recycle.ps1') command = ["powershell", "-ExecutionPolicy", "Bypass", "-File", script_path] subprocess.run(command, shell=True, check=True) print("휴지통 내용이 'RecycleBin' 폴더에 복사되었습니다.") except Exception as e: print(f"오류가 발생했습니다: {e}") def lnkFile(): print("\n==========LNK File==========") # LNK 폴더 생성 후 저장 current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "LNK") if not os.path.exists(destination_folder): os.makedirs(destination_folder) # .lnk파일 위치 source_folder = os.path.expanduser("~") + "\\AppData\\Roaming\\Microsoft\\Windows\\Recent" # file copy for root, dirs, files in os.walk(source_folder): for file in files: source_file_path = os.path.join(root, file) destination_file_path = os.path.join(destination_folder, file) try: shutil.copy2(source_file_path, destination_file_path) print(f"복사 완료: {file}") except Exception as e: print(f"복사 실패: {file}, 오류: {e}") def PowerShellLogFile(): print("\n==========PowerShell Log File==========") # PowerShellLog 폴더 생성 후 저장 current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "PowerShellLog") if not os.path.exists(destination_folder): os.makedirs(destination_folder) # .lnk파일 위치 source_folder = os.path.expanduser("~") + "\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine" # file copy for root, dirs, files in os.walk(source_folder): for file in files: source_file_path = os.path.join(root, file) destination_file_path = os.path.join(destination_folder, file) try: shutil.copy2(source_file_path, destination_file_path) print(f"복사 완료: {file}") except Exception as e: print(f"복사 실패: {file}, 오류: {e}") def registeredService(): print("\n==========Registered Service File==========") # PowerShellLog 폴더 생성 후 저장 current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "RegisteredService") if not os.path.exists(destination_folder): os.makedirs(destination_folder) filename = os.path.join(destination_folder, f"service_info_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") try: # 'sc query' 명령을 실행하여 서비스 정보를 가져옵니다. output = subprocess.check_output("sc query", shell=True, text=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: output = f"An error occurred while trying to fetch service info: {str(e)}" # 서비스 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: f.write(output) print(f"등록된 서비스 정보가 {filename} 에 저장되었습니다.") def recentActivity(): print("\n==========Recent Activity File==========") # PowerShellLog 폴더 생성 후 저장 current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "RecentActivity") if not os.path.exists(destination_folder): os.makedirs(destination_folder) # Recent Items 폴더의 경로를 가져옵니다. recent_folder = os.path.join(os.environ['USERPROFILE'], r'AppData\Roaming\Microsoft\Windows\Recent') recent_items = [] # 폴더 내의 모든 파일과 폴더를 나열합니다. for item in os.listdir(recent_folder): item_path = os.path.join(recent_folder, item) item_stat = os.stat(item_path) # 파일의 마지막 액세스 시간을 가져옵니다. last_access_time = datetime.datetime.fromtimestamp(item_stat.st_atime).strftime('%Y-%m-%d %H:%M:%S') recent_items.append(f"{item}: Last accessed at {last_access_time}") # 파일 이름에 현재 시간을 추가해 고유한 파일을 생성합니다. filename = os.path.join(destination_folder, f"recent_activity_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") # 최근 활동 정보를 .txt 파일에 저장합니다. with open(filename, 'w') as f: for info in recent_items: f.write(f"{info}\n") print(f"최근 활동 정보가 {filename} 에 저장되었습니다.") def prefetch(): print("\n==========Prefetch File==========") # PowerShellLog 폴더 생성 후 저장 current_directory = os.path.dirname(os.path.abspath(__file__)) destination_folder = os.path.join(current_directory, "Prefetch") if not os.path.exists(destination_folder): os.makedirs(destination_folder) # Prefetch 폴더 경로 prefetch_path = r"C:\Windows\Prefetch" # Prefetch 폴더에서 .pf 파일 목록 수집 try: prefetch_files = [f for f in os.listdir(prefetch_path) if f.endswith('.pf')] except PermissionError: print("관리자 권한이 필요합니다.") exit() for prefetch_file in prefetch_files: source_file = os.path.join(prefetch_path, prefetch_file) destination_file = os.path.join(destination_folder, prefetch_file) shutil.copy(source_file, destination_file) print(f"prefetch 파일이 {destination_file} 에 저장되었습니다.") def NTFS(): print("\n==========NTFS Artifact File==========") script_dir = os.path.dirname(os.path.abspath(__file__)) ntfs_folder = os.path.join(script_dir, 'NTFS') os.makedirs(ntfs_folder, exist_ok=True) # 'NTFS' 폴더 생성 (이미 존재하면 무시) # 복사할 NTFS 시스템 파일 ntfs_files = ["$MFT", "$LogFile", "$Extend\\$UsnJrnl:$J"] for ntfs_file in ntfs_files: source_file = "C:\\" + ntfs_file destination_file_name = ntfs_file.replace('$', '').replace(':', '').replace('\\', '_') + ".txt" destination_file = os.path.join(ntfs_folder, destination_file_name) command = "fsutil file queryextents {} > {}".format(source_file, destination_file) try: subprocess.run(command, shell=True, check=True, stderr=subprocess.PIPE) print("{}를 성공적으로 복사했습니다.".format(source_file)) except subprocess.CalledProcessError as e: print("{}를 복사하는 데 실패했습니다: {}".format(source_file, e.stderr.decode('utf-8'))) print(f"NTFS 파일이 {destination_file} 에 저장되었습니다.") def main(): init() while(True): showOptions() options = input("[Select Option] : ") if options == "0": print("Good Bye!") exit() elif options == "1": memoryDump() elif options == "2": registryHive() elif options == "3": systemInfo() elif options == "4": systemAudit() elif options == "5": groupPolicy() elif options == "6": eventLog() elif options == "7": serviceLog() elif options == "8": hostsData() elif options == "9": srum() elif options == "10": environmentVar() elif options == "11": patchList() elif options == "12": processList() elif options == "13": openPort() elif options == "14": IPConfigInfo() elif options == "15": arpInfo() elif options == "16": netBIOS() elif options == "17": openedHandle() elif options == "18": taskSchedule() elif options == "19": systemLogon() elif options == "20": userAssist() elif options == "21": autoRun() elif options == "22": registryUser() elif options == "23": save_browser_history() elif options == "24": recycleBin() elif options == "25": lnkFile() elif options == "26": PowerShellLogFile() elif options == "27": registeredService() elif options == "28": recentActivity() elif options == "29": prefetch() elif options == "30": NTFS() elif options == "777": memoryDump() registryHive() systemInfo() systemAudit() groupPolicy() eventLog() serviceLog() hostsData() srum() environmentVar() patchList() processList() openPort() IPConfigInfo() arpInfo() netBIOS() openedHandle() taskSchedule() systemLogon() userAssist() autoRun() registryUser() save_browser_history() recycleBin() lnkFile() PowerShellLogFile() registeredService() recentActivity() prefetch() NTFS() else : print("\nPlease input correct options!") pass if __name__ == "__main__": main()
KIMJOONSIG/Reboot3
Windows/reboot3.py
reboot3.py
py
36,418
python
en
code
0
github-code
6
10356870047
import time import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ExponentialLR import argparse import os # pylint: disable=E1101, W0612 """ # GPU CLUSTER source = '/vol/gpudata/rar2417/src/model1' #path to code location data_path = '/vol/gpudata/rar2417/Data' #path to the parent directory of 'audio' output_path = '/vol/gpudata/rar2417/results/model1' #path to output the results model_path = output_path + '/models/resnet_bgru_1.ckpt' #path to find pre-trained model """ # HOME SETUP source = '/home/r2d9/Desktop/SpeechRecognitionProject' #path to code location data_path = '/home/r2d9/Desktop/Data/train' #path to the parent directory of 'audio' output_path = '/home/r2d9/Desktop/results' #path to output the results model_path = output_path + '/models/resnet_bgru_1.ckpt' #path to find pre-trained model parser = argparse.ArgumentParser() parser.add_argument('-key', '--filekey', type = str, help='key for multiple trainings') parser.add_argument('-lr', '--learning_rate', type = float, help='LEARNING_RATE') parser.add_argument('-md', '--mode', type = int, help='1, 2 or 3') args = parser.parse_args() KEY = '' #provided for convenience, easy way to differenciate experiments if args.filekey is not None: KEY = args.filekey MODE = 4 #3-step training procedure if args.mode is not None: MODE = args.mode os.chdir(source) from dataset import dataset from model_resnet_bgru import Network, accuracy # Configuration start = time.time() torch.set_default_tensor_type('torch.FloatTensor') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Hyperparams NUM_EPOCHS = 50 BATCH_SIZE = 20 LAMBDA = 0.87 LEARNING_RATE = 0.0003 if args.learning_rate is not None: LEARNING_RATE = args.learning_rate # Model & Dataset data = dataset(data_path + '/training_list.txt', data_path + '/audio') valset = dataset(data_path + '/validation_list.txt', data_path + '/audio') testset = dataset(data_path + '/testing_list.txt', data_path + '/audio') if MODE == 1: #training only the resnet model = Network(mode=1).to(device) if MODE == 2: #training only the bgru model = Network().to(device) model.load_state_dict(torch.load(model_path)) for name, param in model.named_parameters(): if 'gru' in name: param.requires_grad = True if 'resnet' in name: param.requires_grad = False if MODE == 3: #training resnet and bgru from pre-trained model model = Network().to(device) model.load_state_dict(torch.load(model_path)) for params in model.parameters(): params.requires_grad = True if MODE == 4: #training everything in one go from scratch model = Network().to(device) for params in model.parameters(): params.requires_grad = True # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=LEARNING_RATE) scheduler = ExponentialLR(optimizer, LAMBDA) #learning rate decay, halved every 5 epochs epoch, estop, maxval, maxind = 0, False, 0, 0 while epoch < NUM_EPOCHS and not estop: #early stopping dataloader = DataLoader(data, batch_size=BATCH_SIZE, shuffle=True, drop_last=False) if epoch > 4: #fixed learning rate for first 5 epochs scheduler.step() for i_batch, batch in enumerate(dataloader): # Forward optimizer.zero_grad() outputs = model(batch['audio']) loss = criterion(outputs, batch['label'].to(device)) # Backward and optimize loss.backward() optimizer.step() # Save loss with open(output_path +'/loss_'+KEY+'.txt', 'a') as myfile: myfile.write(str(loss.item())+'\n') # Save model, accuracy at each epoch newval = accuracy(model, valset, output_path + '/val_'+KEY+'.txt', 4) #accuracy on validation set for early-stopping accuracy(model, dataset, output_path + '/train_'+KEY+'.txt', 4) #accuracy on training set to monitor overfitting accuracy(model, testset, output_path + '/test_'+KEY+'.txt', 4) #accuracy on testing set # Early stopping if newval > maxval: maxval = newval maxind = epoch if MODE == 1: torch.save(model.state_dict(), output_path + '/models/resnet_'+KEY+'.ckpt') if MODE == 2: torch.save(model.state_dict(), output_path +'/models/bgru_'+KEY+'.ckpt') if MODE == 3: torch.save(model.state_dict(), output_path +'/models/resnet_bgru_3_'+KEY+'.ckpt') if MODE == 4: torch.save(model.state_dict(), output_path +'/models/resnet_bgru_'+KEY+'.ckpt') if epoch > maxind + 4: estop = True epoch += 1 data.resample_unknown_class() print('key ', KEY) print('time ', time.time()-start) print('epochs ', epoch)
remit0/SpeechRecognitionProject
legacy/training3.py
training3.py
py
4,844
python
en
code
0
github-code
6
18454402127
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import import sys import argparse import logging.config from pathlib import Path sys.path.append(str(Path().absolute())) from mx_crm.main import run_completing from mx_crm.settings import LOGGING logging.config.dictConfig(LOGGING) logger = logging.getLogger(__name__) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Complete/Update data') parser.add_argument('--all', action='store_true', help='Run all completers') parser.add_argument('--websites', action='store_true', help='Complite missing websites') parser.add_argument('--update-wiki', action='store_true', help='Update already parsed wiki data by existing url') parser.add_argument('--update-xing', action='store_true', help='Update already parsed xing data by existing url') parser.add_argument('--parse-wiki', action='store_true', help='Parse not parsed/found data for wiki') parser.add_argument('--parse-xing', action='store_true', help='Parse not parsed/found data for xing') parser.add_argument('--force-update', action='store_true', help='Force update') parser.add_argument('--google-evaluation', action='store_true', help='Parse not parsed google evaluation') args = parser.parse_args() logger.info(""" Arguments: --all={all} --websites={websites} --update-wiki={update_wiki} --update-xing={update_xing} --parse-wiki={parse_wiki} --parse-xing={parse_xing} --force-update={force_update} """.format( all=args.all, websites=args.websites, update_wiki=args.update_wiki, update_xing=args.update_xing, parse_wiki=args.parse_wiki, parse_xing=args.parse_xing, force_update=args.force_update, google_evaluation=args.google_evaluation, )) try: run_completing( force_update=args.force_update, c_all=args.all, c_websites=args.websites, c_update_wiki=args.update_wiki, c_update_xing=args.update_xing, c_parse_wiki=args.parse_wiki, c_parse_xing=args.parse_xing, c_google_evaluation=args.google_evaluation ) except IOError as e: logger.error(e)
alexpinkevichwork/squirrel
complete_data.py
complete_data.py
py
2,311
python
en
code
0
github-code
6
17510483933
''' start: 1:42? end: left and right pointers come from both ends until sum of left and right equals target if the sum isn't target. then if it is more than target decrement right. otherwise increment left T: O(n) S: O(1) ''' class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left, right = 0, len(numbers) - 1 while left < right: twosum = numbers[left] + numbers[right] #17 if twosum == target: return [1 + left, 1 + right] elif twosum < target: left += 1 else: right -= 1 raise ValueError("numbers has no two sum")
soji-omiwade/cs
dsa/before_rubrik/twosum_ordered_input.py
twosum_ordered_input.py
py
675
python
en
code
0
github-code
6
30903913191
import pdb from models.gamedetail import Gamedetail from models.game import Game from models.team import Team from repositories import gamedetail_repository, game_repository, team_repository gamedetail_repository.delete_all() game_repository.delete_all() team_repository.delete_all() team_1 = Team("Glasgow Clan", "Breahead Arena", "Glasgow", "http://www.clanihc.com", "gla_logo.png") team_repository.save(team_1) team_2 = Team("Fife Flyers", "Fife Ice Arena", "Kirkcaldy", "http://www.fifeflyers.co.uk", "fif_logo.png") team_repository.save(team_2) team_3 = Team("Dundee Stars", "Dundee Ice Arena", "Dundee", "http://www.dundeestars.com", "dun_logo.png") team_repository.save(team_3) team_4 = Team("Sheffield Steelers", "Sheffield Arena", "Sheffield", "http://www.sheffieldsteelers.co.uk", "she_logo.png") team_repository.save(team_4) team_5 = Team("Coventry Blaze", "Skydome Arena", "Coventry", "http://www.coventryblaze.co.uk", "cov_logo.png") team_repository.save(team_5) team_6 = Team("Nottingham Panthers", "Motorpoint Arena", "Nottingham", "http://www.panthers.co.uk", "not_logo.png") team_repository.save(team_6) team_7 = Team("Cardiff Devils", "Ice Arena Wales", "Cardiff", "http://www.cardiffdevils.com", "car_logo.png") team_repository.save(team_7) team_8 = Team("Manchester Storm", "Planet Ice Altrincham", "Manchester", "http://www.manchesterstorm.com", "mcr_logo.png") team_repository.save(team_8) team_9 = Team("Belfast Giants", "The SSE Arena", "Belfast", "http://www.belfastgiants.com", "bel_logo.png") team_repository.save(team_9) team_10 = Team("Guildford Flames", "Spectrum Leisure Complex", "Guildford", "http://www.guildfordflames.co.uk", "gui_logo.png") team_repository.save(team_10) game_1 = Game("20220918","1800", "Guildford", "2022") game_repository.save(game_1) game_2 = Game("20220922","1930", "Glasgow", "2022") game_repository.save(game_2) game_3 = Game("20220924","1900", "Cardiff", "2022") game_repository.save(game_3) game_4 = Game("20221008","1900", "Glasgow", "2022") game_repository.save(game_4) game_5 = Game("20220924","1915", "Kirkcaldy", "2022") game_repository.save(game_5) game_6 = Game("20220625","1730", "coventry", "2022") game_repository.save(game_6) game_7 = Game("20221010","1915", "Guildford", "2022") game_repository.save(game_7) game_8 = Game("20221002","1900", "Kirkcaldy", "2022") game_repository.save(game_8) game_9 = Game("20220918","1700", "Dundee", "2022") game_repository.save(game_9) game_10 = Game("20223009","1930", "Nottingham", "2022") game_repository.save(game_10) game_11 = Game("20221001","1900", "Manchester", "2022") game_repository.save(game_11) game_12 = Game("20221009","1700", "Dundee", "2022") game_repository.save(game_12) game_13 = Game("20220910","1900", "Sheffield", "2022") game_repository.save(game_13) game_14 = Game("20220911","1800", "Guildford", "2022") game_repository.save(game_14) game_15 = Game("20220210","1730", "Coventry", "2022") game_repository.save(game_15) game_16 = Game("20221006","1930", "Sheffield", "2022") game_repository.save(game_16) game_17 = Game("20220910","1900", "Manchester", "2022") game_repository.save(game_17) game_18 = Game("20220911","1730", "Coventry", "2022") game_repository.save(game_18) game_19 = Game("20220917","1930", "Nottingham", "2022") game_repository.save(game_19) game_20 = Game("20220925","1730", "Coventry", "2022") game_repository.save(game_20) gamedetail_1 = Gamedetail(game_1,team_1,"Home","Win",7,2,"") gamedetail_repository.save(gamedetail_1) gamedetail_2 = Gamedetail(game_1,team_2,"Away","loss",3,8,"") gamedetail_repository.save(gamedetail_2) gamedetail_3 = Gamedetail(game_2,team_3,"Home","Win",5,2,"") gamedetail_repository.save(gamedetail_3) gamedetail_4 = Gamedetail(game_2,team_4,"Away","loss",0,10,"") gamedetail_repository.save(gamedetail_4) gamedetail_5 = Gamedetail(game_3,team_5,"Home","Win",7,2,"") gamedetail_repository.save(gamedetail_5) gamedetail_6 = Gamedetail(game_3,team_6,"Away","loss",3,8,"") gamedetail_repository.save(gamedetail_6) gamedetail_7 = Gamedetail(game_4,team_7,"Home","Win",5,2,"") gamedetail_repository.save(gamedetail_7) gamedetail_8 = Gamedetail(game_4,team_8,"Away","loss",0,10,"") gamedetail_repository.save(gamedetail_8) gamedetail_9 = Gamedetail(game_5,team_9,"Home","Win",7,2,"") gamedetail_repository.save(gamedetail_9) gamedetail_10 = Gamedetail(game_5,team_10,"Away","loss",3,8,"") gamedetail_repository.save(gamedetail_10) gamedetail_11 = Gamedetail(game_6,team_10,"Home","Win",5,2,"") gamedetail_repository.save(gamedetail_11) gamedetail_12 = Gamedetail(game_6,team_1,"Away","loss",0,10,"") gamedetail_repository.save(gamedetail_12) gamedetail_13 = Gamedetail(game_7,team_2,"Home","Win",7,2,"") gamedetail_repository.save(gamedetail_13) gamedetail_14 = Gamedetail(game_7,team_9,"Away","loss",3,8,"") gamedetail_repository.save(gamedetail_14) gamedetail_15 = Gamedetail(game_8,team_4,"Home","Win",5,2,"") gamedetail_repository.save(gamedetail_15) gamedetail_16 = Gamedetail(game_8,team_3,"Away","loss",0,10,"") gamedetail_repository.save(gamedetail_16) gamedetail_17 = Gamedetail(game_9,team_8,"Home","Win",7,2,"") gamedetail_repository.save(gamedetail_17) gamedetail_18 = Gamedetail(game_9,team_7,"Away","loss",3,8,"") gamedetail_repository.save(gamedetail_18) gamedetail_19 = Gamedetail(game_10,team_6,"Home","Win",5,2,"") gamedetail_repository.save(gamedetail_19) gamedetail_20 = Gamedetail(game_10,team_5,"Away","loss",0,10,"") gamedetail_repository.save(gamedetail_20)
GregorRoss/Ice_Hockey_Tracker
console.py
console.py
py
5,470
python
en
code
1
github-code
6
811063416
# Network Delay Time - https://leetcode.com/problems/network-delay-time/ '''There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target. Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1. Example 1: Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2 Output: 2''' # Dijkstra's Algorithm - 0(n2) from collections import defaultdict class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: def getMinDistance(distance, seen): minNode = float('inf') minIndex = -1 for i in range(1, N+1): if distance[i] < minNode and not seen[i]: minNode = distance[i] minIndex = i return minIndex graph = defaultdict(list) for u, v, w in times: graph[u].append((v,w)) seen = [False] * (N+1) distance = {node: float('inf') for node in range(1, N+1)} distance[K] = 0 while True: u = getMinDistance(distance, seen) if u < 0: break seen[u] = True for neighbour, time in graph[u]: if distance[neighbour] > distance[u] + time: distance[neighbour] = distance[u] + time output = max(distance.values()) return output if output != float('inf') else -1 # Dijkstra's Algorithm - 0(nlogn) from collections import defaultdict import heapq class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: graph = defaultdict(list) for u, v, w in times: graph[u].append((v,w)) distance = {} q = [(0, K)] while q: time, node = heapq.heappop(q) if node in distance: continue distance[node] = time for neighbour, timeTravelled in graph[node]: if neighbour not in distance: heapq.heappush(q, (time+timeTravelled, neighbour)) return max(distance.values()) if len(distance) == N else -1
Saima-Chaity/Leetcode
Graph/networkDelayTime.py
networkDelayTime.py
py
2,428
python
en
code
0
github-code
6
27284711802
import numpy as np import pandas as pd import matplotlib.pyplot as plt import pandas_datareader as data from sklearn.preprocessing import MinMaxScaler # noinspection PyUnresolvedReferences import silence_tensorflow.auto # for ignoring tensorflow info and warnings from keras.layers import Dense, Dropout, LSTM from keras.models import Sequential from datetime import date # starting and ending of data frame start = '2010-01-01' end = date.today().strftime('%Y-%m-%d') # data frame df = data.DataReader('SBI', 'yahoo', start, end) df = df.reset_index() df = df.drop(['Date', 'Adj Close'], axis=1) # splitting data into Training and Testing data_training = pd.DataFrame(df['Close'][0:int(len(df) * 0.70)]) data_testing = pd.DataFrame(df['Close'][int(len(df) * 0.70): int(len(df))]) # scaling down the training data and converting it into an array scale = MinMaxScaler(feature_range=(0, 1)) data_training_array = scale.fit_transform(data_training) # splitting data into x_train and y_train # x_train is taken as fist 100 values and y_train as 101 value # then first value of x_train is dropped and y_train is inserted into x_train # next y_train is taken as 102 value and same continues till last value x_train = [] y_train = [] for i in range(100, data_training_array.shape[0]): x_train.append(data_training_array[i - 100: i]) y_train.append(data_training_array[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train) # Simple LSTM Model model = Sequential() # layer 1 model.add(LSTM(units=50, activation='relu', return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(Dropout(0.2)) # layer 2 model.add(LSTM(units=60, activation='relu', return_sequences=True)) model.add(Dropout(0.3)) # layer 3 model.add(LSTM(units=80, activation='relu', return_sequences=True)) model.add(Dropout(0.4)) # layer 4 model.add(LSTM(units=120, activation='relu')) model.add(Dropout(0.5)) # dense layer model.add(Dense(units=1)) # compile model with adam optimizer model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=50) # saving model model.save('keras_model.h5') # predicting values for testing data past_100_days = data_training.tail(100) final_df = past_100_days.append(data_testing, ignore_index=True) # scaling down the testing data and converting it into an array input_data = scale.fit_transform(final_df) # splitting data into x_test and y_test x_test = [] y_test = [] for i in range(100, input_data.shape[0]): x_test.append(input_data[i - 100: i]) y_test.append(input_data[i, 0]) x_test, y_test = np.array(x_test), np.array(y_test) # Making Prediction y_predicted = model.predict(x_test) # scaling up the predicted data scale_factor = 1/scale.scale_[0] y_predicted = y_predicted * scale_factor y_test = y_test * scale_factor # plotting original vs predicted data plt.figure(figsize=(12, 6)) plt.plot(y_test, 'b', label='Original Price') plt.plot(y_predicted, 'r', label='Predicted Price') plt.xlabel('Time') plt.ylabel('Price') plt.legend() plt.show()
aashima1433/StockProject
LSTM_model.py
LSTM_model.py
py
3,046
python
en
code
0
github-code
6
73401806589
from torch import nn class Mojmyr(nn.Module): def __init__(self, input_shape, hidden_units, output_shape): super().__init__() # Copy TinyVGG structure, modify it slightly for this specific case self.conv_block_1 = nn.Sequential( nn.Conv2d(input_shape, hidden_units, 3, 1, 1), nn.ReLU(), nn.Conv2d(hidden_units, hidden_units, 3, 1, 1), nn.ReLU(), nn.MaxPool2d(2, 2) ) self.conv_block_2 = nn.Sequential( nn.Conv2d(hidden_units, hidden_units, 3, 1), nn.ReLU(), nn.Conv2d(hidden_units, hidden_units, 3, 1), nn.ReLU(), nn.MaxPool2d(2) ) self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(in_features=hidden_units*14*14, out_features=output_shape) ) # Required forward method that takes the input 'x' through all the conv_blocks and the classifier, returning logits because of the last Linear layer def forward(self, x): x = self.conv_block_1(x) x = self.conv_block_2(x) x = self.classifier(x) return x
PopeCorn/myr
code/model.py
model.py
py
1,162
python
en
code
0
github-code
6
74589712187
import cv2 smilecascade=cv2.CascadeClassifier('haarcascade\\haarcascade_smile.xml') cap = cv2.VideoCapture(0) while 1: ret, img=cap.read() #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) smiles = smilecascade.detectMultiScale(img, 1.3,50 ) for (x,y,w,h) in smiles: cv2.rectangle(img, (x,y), (x+w, y+h), (255,255,255), 2) cv2.imshow('img', img) if cv2.waitKey(1) & 0xFF==ord('q'): break cap.release() cv2.destroyAllWindows()
harshikesh-kumar/Projects
Project Smile Detect.py
Project Smile Detect.py
py
488
python
en
code
0
github-code
6
44530888336
import cv2 import numpy as np from dlclive import DLCLive, Processor from skimage.transform import (hough_line, hough_line_peaks) folder = 'model/' dlc_proc = Processor() dlc_live = DLCLive(folder, processor=dlc_proc) dlc_live.init_inference() i = 0 while True: # Load frame i += 1 frame = cv2.imread('frames/ (' + str(i) + ').jpg') frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) # Get poses pose = dlc_live.get_pose(frame) nose = (int(pose[0, 0]), int(pose[0, 1])) head = (int(pose[1, 0]), int(pose[1, 1])) body = (int(pose[2, 0]), int(pose[2, 1])) # Draw lines on Stage for angle measurement stage = np.zeros((frame.shape[0], frame.shape[1]), np.uint8) # Clear frame stage = cv2.line(stage, nose, head, 255, 1) # Perform Hough Transformation to detect lines hspace, angles, distances = hough_line(stage) # Find angle angle = [] for _, a, distances in zip(*hough_line_peaks(hspace, angles, distances)): angle.append(a) # Obtain angle for each line angles = [a * 180 / np.pi for a in angle] # Get length of radius for angle visualization radius = cv2.norm(head, nose) axes = (int(radius), int(radius)) # Get 360 degree readout degree = int(angles[0]) if nose[0] > head[0] and degree < 0: degree = 180 + degree elif nose[0] < head[0] and degree < 0: degree = 360 + degree elif nose[0] < head[0] and degree > 0: degree = 180 + degree # Draw lines frame = cv2.line(frame, nose, head, (255, 255, 0), 1, lineType=cv2.LINE_AA) frame = cv2.line(frame, (head[0], int(head[1] - radius)), head, (255, 255, 0), 1, lineType=cv2.LINE_AA) frame = cv2.putText(frame, str(degree), (head[0] - 50, head[1] - 50), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), lineType=cv2.LINE_AA) # Draw arc of angle if nose[0] >= head[0]: frame = cv2.ellipse(frame, head, axes, -90, degree, 0, (255, 255, 0), lineType=cv2.LINE_AA) else: frame = cv2.ellipse(frame, head, axes, -90, 0, degree, (255, 255, 0), lineType=cv2.LINE_AA) # Show video cv2.imshow('Pose', frame) cv2.imwrite("output/head_angle/" + str(i) + ".png", frame) cv2.waitKey(1) # Reset loop if i == 969: i = 0
nghess/dlc-live-test
head-angle-vf.py
head-angle-vf.py
py
2,324
python
en
code
0
github-code
6
26683394696
#!/usr/bin/python3 '''This module adds all arguments to a Python list and saves them to a file ''' import sys save_to_json_file = __import__('5-save_to_json_file').save_to_json_file load_from_json_file = __import__('6-load_from_json_file').load_from_json_file filename = 'add_item.json' try: arguments = load_from_json_file(filename) except FileNotFoundError: arguments = [] # for each time this module is run with command line arguments, # append the arguments to the existing arguments list. # Then create new JSON representation of the updated arguments list # and save it in filename for arg in sys.argv[1:]: arguments.append(arg) save_to_json_file(arguments, filename)
nzubeifechukwu/alx-higher_level_programming
0x0B-python-input_output/7-add_item.py
7-add_item.py
py
692
python
en
code
0
github-code
6
25881543237
#!/usr/bin/python f = open("in.txt", "r") kalorije = 0 sumkalorij = [] for vrstica in f: if len(vrstica) <= 1: sumkalorij.append(kalorije) kalorije = 0 else: kalorije += int(vrstica) sumkalorij.sort(reverse=True) print(sumkalorij[0] + sumkalorij[1] + sumkalorij[2])
Anja159/Advent_of_code_2022
Day1/part2.py
part2.py
py
314
python
hr
code
1
github-code
6
24201915314
from lnd_client import LND_CLIENT from utilities import * class Invoice: def __init__(self, r_hash_hex, payment_request, add_index, is_paid=False): self.r_hash_hex = r_hash_hex self.payment_request = payment_request self.add_index = add_index self.decoded_pay_req = LND_CLIENT.rpc.decode_pay_req(pay_req=self.payment_request) self.is_paid = is_paid def __str__(self): return f"{self.decoded_pay_req}Is paid: {self.is_paid}" def __repr__(self): return f"Invoice({self.r_hash_hex}, {self.payment_request}," \ f"{self.add_index}, {self.is_paid})" def pay(self, preimage_base64): preimage_bytes = base64_to_bytes(preimage_base64) preimage_hash_hex = sha256_of_bytes_to_hex(preimage_bytes) # hash_hex = bytes_to_hex(hash_bytes) if preimage_hash_hex == self.decoded_pay_req.payment_hash: self.is_paid = True print('\nInvoice paid successfully, releasing item.\n\n') else: print("Preimage not valid. Check encoding is base64")
willcl-ark/boltstore
invoices.py
invoices.py
py
1,088
python
en
code
1
github-code
6
38036093112
import logging from collections import defaultdict from typing import Dict, Optional, Tuple, Union import numpy as np from matplotlib import rcParams from matplotlib.axes import SubplotBase from matplotlib.axis import Axis from matplotlib.colors import LogNorm from matplotlib.ticker import AutoMinorLocator, MaxNLocator from pymatgen.electronic_structure.bandstructure import ( BandStructure, BandStructureSymmLine, ) from pymatgen.electronic_structure.core import Spin from pymatgen.electronic_structure.plotter import BSPlotter from sumo.plotting import pretty_plot from sumo.symmetry import Kpath, PymatgenKpath from amset.constants import defaults, hbar from amset.interpolation.bandstructure import Interpolator from amset.interpolation.periodic import PeriodicLinearInterpolator from amset.log import initialize_amset_logger from amset.plot import BaseMeshPlotter, amset_base_style, styled_plot __author__ = "Alex Ganose" __maintainer__ = "Alex Ganose" __email__ = "[email protected]" logger = logging.getLogger(__name__) class LineshapePlotter(BaseMeshPlotter): def __init__( self, data, interpolation_factor=5, print_log=defaults["print_log"], symprec=defaults["symprec"], ): super().__init__(data) self.interpolation_factor = interpolation_factor if print_log: initialize_amset_logger(filename="lineshape.log") self.symprec = symprec def _get_interpolater(self, n_idx, t_idx, mode="linear"): props = defaultdict(dict) for spin in self.spins: # calculate total rate spin_rates = np.sum(self.scattering_rates[spin][:, n_idx, t_idx], axis=0) # easier to interpolate the log log_rates = np.log10(spin_rates) # # handle rates that close to numerical noise log_rates[log_rates > 18] = 15 log_rates[np.isnan(log_rates)] = 15 # map to full k-point mesh props[spin]["rates"] = log_rates if mode == "linear": return _LinearBandStructureInterpolator( self.kpoints, self.ir_to_full_kpoint_mapping, self.energies, self.structure, self.efermi, props, ) elif mode == "fourier": bs = BandStructure( self.ir_kpoints, self.energies, self.structure.lattice, self.efermi, structure=self.structure, ) return Interpolator( bs, self.num_electrons, interpolation_factor=self.interpolation_factor, soc=self.soc, other_properties=props, ) raise ValueError("Unknown interpolation mode; should be 'linear' or 'fourier'.") @styled_plot(amset_base_style) def get_plot( self, n_idx, t_idx, zero_to_efermi=True, estep=0.01, line_density=100, height=3.2, width=3.2, emin=None, emax=None, amin=5e-5, amax=1e-1, ylabel="Energy (eV)", plt=None, aspect=None, kpath=None, cmap="viridis", colorbar=True, style=None, no_base_style=False, fonts=None, ): interpolater = self._get_interpolater(n_idx, t_idx) bs, prop = interpolater.get_line_mode_band_structure( line_density=line_density, return_other_properties=True, kpath=kpath, symprec=self.symprec, ) bs, rates = force_branches(bs, {s: p["rates"] for s, p in prop.items()}) fd_emin, fd_emax = self.fd_cutoffs if not emin: emin = fd_emin if zero_to_efermi: emin -= bs.efermi if not emax: emax = fd_emax if zero_to_efermi: emax -= bs.efermi logger.info("Plotting band structure") if isinstance(plt, (Axis, SubplotBase)): ax = plt else: plt = pretty_plot(width=width, height=height, plt=plt) ax = plt.gca() if zero_to_efermi: bs.bands = {s: b - bs.efermi for s, b in bs.bands.items()} bs.efermi = 0 bs_plotter = BSPlotter(bs) plot_data = bs_plotter.bs_plot_data(zero_to_efermi=zero_to_efermi) energies = np.linspace(emin, emax, int((emax - emin) / estep)) distances = np.array([d for x in plot_data["distances"] for d in x]) # rates are currently log(rate) mesh_data = np.full((len(distances), len(energies)), 0.0) for spin in self.spins: for spin_energies, spin_rates in zip(bs.bands[spin], rates[spin]): for d_idx in range(len(distances)): energy = spin_energies[d_idx] linewidth = 10 ** spin_rates[d_idx] * hbar / 2 broadening = lorentzian(energies, energy, linewidth) broadening /= 1000 # convert 1/eV to 1/meV mesh_data[d_idx] += broadening im = ax.pcolormesh( distances, energies, mesh_data.T, rasterized=True, cmap=cmap, norm=LogNorm(vmin=amin, vmax=amax), shading="auto", ) if colorbar: pos = ax.get_position() cax = plt.gcf().add_axes([pos.x1 + 0.035, pos.y0, 0.035, pos.height]) cbar = plt.colorbar(im, cax=cax) cbar.ax.tick_params(axis="y", length=rcParams["ytick.major.size"] * 0.5) cbar.ax.set_ylabel( r"$A_\mathbf{k}$ (meV$^{-1}$)", rotation=270, va="bottom" ) _maketicks(ax, bs_plotter, ylabel=ylabel) _makeplot( ax, plot_data, bs, zero_to_efermi=zero_to_efermi, width=width, height=height, ymin=emin, ymax=emax, aspect=aspect, ) return plt def _makeplot( ax, data, bs, zero_to_efermi=True, ymin=-3.0, ymax=3.0, height=None, width=None, aspect=None, ): """Tidy the band structure & add the density of states if required.""" # draw line at Fermi level if not zeroing to e-Fermi if not zero_to_efermi: ytick_color = rcParams["ytick.color"] ef = bs.efermi ax.axhline(ef, color=ytick_color) # set x and y limits ax.set_xlim(0, data["distances"][-1][-1]) if bs.is_metal() and not zero_to_efermi: ax.set_ylim(bs.efermi + ymin, bs.efermi + ymax) else: ax.set_ylim(ymin, ymax) # keep correct aspect ratio for axes based on canvas size if aspect is not False: x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() if width is None: width = rcParams["figure.figsize"][0] if height is None: height = rcParams["figure.figsize"][1] if not aspect: aspect = height / width ax.set_aspect(aspect * ((x1 - x0) / (y1 - y0))) def _maketicks(ax, bs_plotter, ylabel="Energy (eV)"): """Utility method to add tick marks to a band structure.""" # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(6)) ax.yaxis.set_minor_locator(AutoMinorLocator(2)) # set x-ticks; only plot the unique tick labels ticks = bs_plotter.get_ticks() unique_d = [] unique_l = [] if ticks["distance"]: temp_ticks = list(zip(ticks["distance"], ticks["label"])) unique_d.append(temp_ticks[0][0]) unique_l.append(temp_ticks[0][1]) for i in range(1, len(temp_ticks)): # Append label to sequence if it is not same as predecessor if unique_l[-1] != temp_ticks[i][1]: unique_d.append(temp_ticks[i][0]) unique_l.append(temp_ticks[i][1]) logging.info("Label positions:") for dist, label in list(zip(unique_d, unique_l)): logging.info(f"\t{dist:.4f}: {label}") ax.set_xticks(unique_d) ax.set_xticklabels(unique_l) ax.xaxis.grid(True) ax.set_ylabel(ylabel) def lorentzian(x, x0, gamma): return 1 / np.pi * gamma / ((x - x0) ** 2 + gamma**2) class _LinearBandStructureInterpolator: def __init__( self, full_kpoints, ir_to_full_idx, energies, structure, efermi, other_properties, ): self.structure = structure self.efermi = efermi self.spins = list(energies.keys()) self.nbands = {s: len(e) for s, e in energies.items()} full_energies = {s: e[:, ir_to_full_idx] for s, e in energies.items()} self.bs_interpolator = PeriodicLinearInterpolator.from_data( full_kpoints, full_energies ) self.property_interpolators = {} other_properties = _transpose_dict(other_properties) for prop, prop_data in other_properties.items(): full_prop_data = {s: p[:, ir_to_full_idx] for s, p in prop_data.items()} self.property_interpolators[prop] = PeriodicLinearInterpolator.from_data( full_kpoints, full_prop_data, gaussian=0.75 ) def get_line_mode_band_structure( self, line_density: int = 50, kpath: Optional[Kpath] = None, symprec: Optional[float] = defaults["symprec"], return_other_properties: bool = False, ) -> Union[ BandStructureSymmLine, Tuple[BandStructureSymmLine, Dict[Spin, Dict[str, np.ndarray]]], ]: """Gets the interpolated band structure along high symmetry directions. Args: line_density: The maximum number of k-points between each two consecutive high-symmetry k-points symprec: The symmetry tolerance used to determine the space group and high-symmetry path. return_other_properties: Whether to include the interpolated other_properties data for each k-point along the band structure path. Returns: The line mode band structure. """ if not kpath: kpath = PymatgenKpath(self.structure, symprec=symprec) kpoints, labels = kpath.get_kpoints(line_density=line_density, cart_coords=True) labels_dict = { label: kpoint for kpoint, label in zip(kpoints, labels) if label != "" } rlat = self.structure.lattice.reciprocal_lattice frac_kpoints = rlat.get_fractional_coords(kpoints) energies = {} other_properties = defaultdict(dict) for spin in self.spins: energies[spin] = self._interpolate_spin( spin, frac_kpoints, self.bs_interpolator ) if return_other_properties: for prop, property_interpolator in self.property_interpolators.items(): other_properties[spin][prop] = self._interpolate_spin( spin, frac_kpoints, property_interpolator ) bs = BandStructureSymmLine( kpoints, energies, rlat, self.efermi, labels_dict, coords_are_cartesian=True, structure=self.structure, ) if return_other_properties: return bs, other_properties else: return bs def _interpolate_spin(self, spin, kpoints, interpolator): nkpoints = len(kpoints) spin_nbands = self.nbands[spin] ibands = np.repeat(np.arange(spin_nbands), nkpoints) all_kpoints = np.tile(kpoints, (spin_nbands, 1)) data = interpolator.interpolate(spin, ibands, all_kpoints) return data.reshape(spin_nbands, nkpoints) def _transpose_dict(d): td = defaultdict(dict) for k1, v1 in d.items(): for k2, v2 in v1.items(): td[k2][k1] = v2 return td def force_branches(bandstructure, other_property=None): """Force a linemode band structure to contain branches. Branches give a specific portion of the path from one high-symmetry point to another. Branches are required for the plotting methods to function correctly. Unfortunately, due to the pymatgen BandStructure implementation they require duplicate k-points in the band structure path. To avoid this unnecessary computational expense, this function can reconstruct branches in band structures without the duplicate k-points. Args: bandstructure: A band structure object. other_property: Another property with the format {spin: (nbands, nkpts, ...) to split into branches. Returns: A band structure with brnaches. """ kpoints = np.array([k.frac_coords for k in bandstructure.kpoints]) labels_dict = {k: v.frac_coords for k, v in bandstructure.labels_dict.items()} # pymatgen band structure objects support branches. These are formed when # two kpoints with the same label are next to each other. This bit of code # will ensure that the band structure will contain branches, if it doesn't # already. dup_ids = [] high_sym_kpoints = tuple(map(tuple, labels_dict.values())) for i, k in enumerate(kpoints): dup_ids.append(i) if ( tuple(k) in high_sym_kpoints and i != 0 and i != len(kpoints) - 1 and ( not np.array_equal(kpoints[i + 1], k) or not np.array_equal(kpoints[i - 1], k) ) ): dup_ids.append(i) kpoints = kpoints[dup_ids] eigenvals = {} projections = {} for spin, spin_energies in bandstructure.bands.items(): eigenvals[spin] = spin_energies[:, dup_ids] if len(bandstructure.projections) != 0: projections[spin] = bandstructure.projections[spin][:, dup_ids] new_property = {} if other_property is not None: for spin, spin_prop in other_property.items(): new_property[spin] = spin_prop[:, dup_ids] new_bandstructure = type(bandstructure)( kpoints, eigenvals, bandstructure.lattice_rec, bandstructure.efermi, labels_dict, structure=bandstructure.structure, projections=projections, ) return new_bandstructure, new_property
hackingmaterials/amset
amset/plot/lineshape.py
lineshape.py
py
14,486
python
en
code
110
github-code
6
11708352884
BOARD_SIZE = 9 # it's a square def strip_zero_unique(list): strip_zero = [i for i in list if i != 0] return len(strip_zero) == len(set(strip_zero)) class Board: def __init__(self): self.cells = [ [ 0 for _ in range(1 + BOARD_SIZE) ] for _ in range(1 + BOARD_SIZE) ] self.known_points = [] self.black_dot_constraints = [] self.white_dot_constraints = [] self.arrow_constraints = [] self.thermo_constraints = [] self.palindrome_constraints = [] self.box_constraints = [] def get_cells(self): return [ line[1:] for line in self.cells[1:] ] def set_cell(self, line, col, value): self.cells[line][col] = value def add_known_point(self, line, col, value): self.known_points.append((line, col, value)) # black dot connects two adjacent cells, which must have a ratio of 2:1 def add_black_dot_constraint(self, c1, c2): self.black_dot_constraints.append((c1, c2)) # white dot connects two adjacent cells, which must contain consecutive numbers def add_white_dot_constraint(self, c1, c2): self.white_dot_constraints.append((c1, c2)) # the arrow connects multiple cells, and the numbers must sum up to the start of the arrow # arrow will be passed as a list of cells, from start to end def add_arrow_constraint(self, cell_list): self.arrow_constraints.append(cell_list) # thermo connects multiple cells, and the numbers must be increasing from the bottom up # thermo will be passed as a list of cells, from bottom to top def add_thermo_constraint(self, cell_list): self.thermo_constraints.append(cell_list) # palindrome is self-explanatory # also passed as a list of cells, in the specific order def add_palindrome_constraint(self, cell_list): self.palindrome_constraints.append(cell_list) # box constains multiple cells, and the numbers must be unique and sum to a specific number # box will be passed as a tuple containing the sum and the list of cells, in any order def add_box_constraint(self, sum, cell_list): self.box_constraints.append((sum, cell_list)) def check_known_points(self, line, col): for constraint in self.known_points: if constraint[0] == line and constraint[1] == col: return constraint[2] == self.cells[line][col] return True def check_line(self, line, col): # print(f'For line {line}, col {col}, checking {self.cells[line][col]} vs {self.cells[line][1:col]}') return self.cells[line][col] not in self.cells[line][1:col] def check_col(self, line, col): # print(f'For line {line}, col {col}, checking {self.cells[line][col]} vs {[ self.cells[i][col] for i in range(1, col) ]}') return self.cells[line][col] not in [ cell_line[col] for cell_line in self.cells[1:line] ] def check_3x3(self, line, col): line3 = ((line - 1) // 3) col3 = ((col - 1) // 3) # print(f'For line {line}, col {col}, checking {self.cells[line][col]} vs {[ self.cells[line3 * 3 + i][col3 * 3 + j] for i in range(1, 4) for j in range(1, 4) if (line3 * 3 + i != line or col3 * 3 + j != col) ]}') for i in range(1, 4): for j in range(1, 4): if (line3 * 3 + i != line or col3 * 3 + j != col) and self.cells[line3 * 3 + i][col3 * 3 + j] == self.cells[line][col]: return False return True def check_black_dot(self, line, col): for constraint in self.black_dot_constraints: if constraint[0] == (line, col): other_line = constraint[1][0] other_col = constraint[1][1] return self.cells[other_line][other_col] == 0 or self.cells[line][col] * 2 == self.cells[other_line][other_col] or self.cells[line][col] == self.cells[other_line][other_col] * 2 if constraint[1] == (line, col): other_line = constraint[0][0] other_col = constraint[0][1] return self.cells[other_line][other_col] == 0 or self.cells[line][col] * 2 == self.cells[other_line][other_col] or self.cells[line][col] == self.cells[other_line][other_col] * 2 return True def check_white_dot(self, line, col): for constraint in self.white_dot_constraints: if constraint[0] == (line, col): other_line = constraint[1][0] other_col = constraint[1][1] return self.cells[other_line][other_col] == 0 or abs(self.cells[line][col] - self.cells[other_line][other_col]) == 1 if constraint[1] == (line, col): other_line = constraint[0][0] other_col = constraint[0][1] return self.cells[other_line][other_col] == 0 or abs(self.cells[line][col] - self.cells[other_line][other_col]) == 1 return True def check_arrow(self, line, col): for constraint in self.arrow_constraints: if (line, col) not in constraint: continue if not strip_zero_unique([ self.cells[cell[0]][cell[1]] for cell in constraint ]): return False target_sum_point = constraint[0] target_sum = self.cells[target_sum_point[0]][target_sum_point[1]] found_zero = False for cell in constraint[1:]: if self.cells[cell[0]][cell[1]] == 0: found_zero = True break target_sum -= self.cells[cell[0]][cell[1]] return found_zero or target_sum == 0 return True def check_thermo(self, line, col): for constraint in self.thermo_constraints: if (line, col) not in constraint: continue if not strip_zero_unique([ self.cells[cell[0]][cell[1]] for cell in constraint ]): return False found_zero = False for cell in constraint: if self.cells[cell[0]][cell[1]] == 0: found_zero = True break thermo_values = [ self.cells[cell[0]][cell[1]] for cell in constraint ] return found_zero or all([ thermo_values[i] < thermo_values[i + 1] for i in range(len(thermo_values) - 1) ]) return True def check_palindrome(self, line, col): for constraint in self.palindrome_constraints: if (line, col) not in constraint: continue palindrome_values = [ self.cells[cell[0]][cell[1]] for cell in constraint ] return all([ palindrome_values[i] == 0 or palindrome_values[i] == palindrome_values[len(palindrome_values) - i - 1] or palindrome_values[len(palindrome_values) - i - 1 == 0] for i in range(len(palindrome_values) // 2) ]) return True def check_box(self, line, col): for constraint in self.box_constraints: box_sum = constraint[0] if (line, col) not in constraint[1]: continue if not strip_zero_unique([ self.cells[cell[0]][cell[1]] for cell in constraint[1] ]): return False found_zero = False for cell in constraint[1]: if self.cells[cell[0]][cell[1]] == 0: found_zero = True break box_values = [ self.cells[cell[0]][cell[1]] for cell in constraint[1] ] return found_zero or sum(box_values) == box_sum return True # check all constraints + sudoku default ones def check_at(self, line, col): if not self.check_known_points(line, col): return False if not self.check_line(line, col): return False if not self.check_col(line, col): return False if not self.check_3x3(line, col): return False if not self.check_black_dot(line, col): return False if not self.check_white_dot(line, col): return False if not self.check_arrow(line, col): return False if not self.check_thermo(line, col): return False if not self.check_box(line, col): return False if not self.check_palindrome(line, col): return False return True def save_solution(self): with open('solution.txt', 'w') as savefile: for line in self.cells[1:]: savefile.write(' '.join([ str(cell) for cell in line[1:] ])) savefile.write('\n')
CristiMacovei/F-Puzzles-Sudoku
board.py
board.py
py
7,944
python
en
code
0
github-code
6
3026162796
#encoding: utf-8 'Support subclassing c++ objects in python, with some limitations. Useful primarily for pure-python preprocessors.' from woo.core import * from minieigen import * class PyAttrTrait(object): ''' Class mimicking the `AttrTrait` template in c++, to be used when deriving from :obj:`PyWooObject`, like in this example (can be found in `woo.pyderived` module's source):: class _SamplePyDerivedPreprocessor(woo.core.Preprocessor,PyWooObject): 'Sample preprocessor written in pure python' _attrTraits=[ PyAttrTrait(bool,'switch',True,"Some bool switch, starting group",startGroup='General'), PyAttrTrait(int,'a',2,"Integer argument in python"), PyAttrTrait(str,'b','whatever',"String argument in python"), PyAttrTrait([Node,],'c',[],"List of nodes in python"), PyAttrTrait(float,'d',.5,"Parameter with range",range=Vector2(0,.7),startGroup='Advanced'), PyAttrTrait(int,'choice',2,"Param with choice",choice=[(0,'choice0'),(1,'choice1'),(2,'choice2')]), PyAttrTrait(int,'flags',1,"Param with bits",bits=['bit0','bit1','bit2','bit3','bit4'],buttons=(['Clear flags','self.flags=0','Set flags to zero'],True)), PyAttrTrait(int,'choice2',2,'Param with unnamed choice',choice=[0,1,2,3,4,5,6,-1]), PyAttrTrait(Vector3,'color',Vector3(.2,.2,.2),"Color parameter",rgbColor=True), PyAttrTrait(float,'length',1.5e-3,"Length",unit='mm'), ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(self): pass # ... This class will be represented like this in the GUI: .. image:: fig/pyderived-gui.png :param pyType: python type object; can be * primitive type (like `bool`, `float`, `Vector3`, `str`, …) * sequence of primitive types, written as 1-list: `[bool,]`, `[float,]`, … * :obj:`woo Object <woo.core.Object>` or any derived type (:obj:`woo.core.Node`, :obj:`woo.dem.Sphere`, …) * sequence of woo objects, e.g. `[woo.core.Node,]` When a value is assigned to the attribute, provided type must be convertible to *pyType*, otherwise `TypeError` is raised. There are some additional restrictions: * `str` and `unicode` values will *not* be converted to `floats` and such − although python will accept `float('1.23')` :param name: name of the attribute, given as `str` :param ini: initial (default) value of the attribute :param str doc: documentation for this attribute, as it appears in generated docs and tooltips in the UI :param str unit: unit given as string, which is looked up in :obj:`woo.unit`; the multiplier is the ratio between *unit* and associated basic unit, which is found automatically. .. warning:: `unit` only determines multiplier for the GUI representation; it has no impact on the internal value used; in particular, the *ini* value is *unit-less*. If you want to give units to the initial value, say something like ``PyAttrTrait(float,'angle',60*woo.unit['deg'],units='deg','This is some angle')``. :param bool noGui: do not show this attribute in the GUI; use this for attributes which the GUI does not know how to represent (such as python objects, numpy arrays and such), to avoid warnings. :param bool noDump: skip this attribute when dumping/loading this object; that means that after loading (or after a :obj:`PyWooObjects.deepcopy`), the attribute will be default-initialized. :param bool rgbColor: this attribute is color in the RGB space (its type must be `Vector3`); the GUI will show color picker. :param str startGroup: start new attribute group, which is represented as collapsible blocks in the GUI. :param str hideIf: python expression which determines whether the GUI hide/show this attribute entry dynamically; use `self` to refer to the instance, as usual. :param range: give range (`Vector2` or `Vector2i`) to this numerical (`float` or `int`) attribute − a slider will be shown in the GUI. :param choice: this attribute chooses from predefined set of integer values; `choice` itself can be * list of unnamed values, e.g. `[0,1,2,3,4]` to choose from; * list of named values, e.g. `[(0,'choice0'),(1,'choice1'),(2,'choice2')]`, where the name will be displayed in the GUI, and the number will be assigned when the choice is made. :param bits: give names for bit values which this (integer) attribute which represents; they will be shown as array of checkboxes in the GUI. :param buttons: Tuple of *list* and *bool*; in the flat list of strings, where each consecutive triplet contains 1. button label 2. python expression to evaluate when the button is clicked 3. label to be shown as button description in the GUI The bool at the end determined whether the button is created above (*True*) or below (*False*) the current attribute. :param filename: `str` attribute representing filename with file picker in the GUI; the file is possibly non-existent. :param existingFilename: `str` attribute for existing filename, with file picker in the GUI. :param dirname: `str` attribute for existing directory name, with directory picker in the GUI. :param triggerPostLoad: when this attribute is being assigned to, `postLoad(id(self.attr))` will be called. ''' # # fake cxxType # primitiveTypes={int:'int',str:'string',float:'Real',bool:'bool', Vector2:'Vector2r',Vector3:'Vector3r',Vector6:'Vector6r',Matrix3:'Matrix3r',Matrix6:'Matrix6r', Quaternion:'Quaternionr',Vector2i:'Vector2i',Vector3i:'Vector3i',Vector6i:'Vector6i', MatrixX:'MatrixXr',VectorX:'VectorXr' } def __init__(self,pyType,name,ini,doc,# *, unit=None, noGui=False, noDump=False, #multiUnit=False, rgbColor=False, #prefUnit=None, #altUnit=None, startGroup=None, hideIf=None, range=None, choice=None, bits=None, buttons=None, altUnits=None, filename=False, existingFilename=False, dirname=False, psd=False, triggerPostLoad=False, guiReadonly=False, noGuiResize=False, ): # validity checks if range: if (pyType,type(range)) not in [(int,Vector2i),(float,Vector2)]: raise TypeError("Range must be Vector2 for floats and Vector2i for ints") if isinstance(pyType,list): if len(pyType)!=1: raise TypeError('Type must be a list of length exactly one, or a plain type') if pyType[0] in self.primitiveTypes: self.cxxType='vector<%s>'%self.primitiveTypes[pyType[0]] elif isinstance(pyType[0],type): self.cxxType='vector<shared_ptr<%s>>'%(pyType[0].__name__) else: raise TypeError('List element must be a type, not a %s'%(str(pyType[0]))) # force correct types in the sequence if pyType[0] in self.primitiveTypes: ini=[pyType[0](i) for i in ini] else: for i,v in enumerate(ini): if v==None: continue # this is OK if not isinstance(v,pyType[0]): raise TypeError("%d-th initial value item must be a %s, not a %s"%(i,pyType[0],type(v))) elif pyType in self.primitiveTypes: self.cxxType=self.primitiveTypes[pyType] ini=pyType(ini) elif isinstance(pyType,type): self.cxxType='shared_ptr<%s>'%pyType.__name__ else: raise ValueError('Type must be a list of length one, or a primitive type; not a %s'%str(pyType)) # # # mandatory args self.pyType=pyType self.name=name self.ini=ini self.doc=doc # optional args self.noGui=noGui self.noDump=noDump self.rgbColor=rgbColor self.startGroup=startGroup self.hideIf=hideIf self.range=range self.choice=choice self.bits=bits self.buttons=buttons self.filename=filename self.existingFilename=existingFilename self.dirname=dirname self.triggerPostLoad=triggerPostLoad self.noGuiResize=noGuiResize self.readonly=guiReadonly # this has different meaning in c++ and python, so call it differently # those are unsupported in python self.noSave=self.hidden=self.pyByRef=self.static=self.activeLabel=self.namedEnum=False # self.validator=None if self.choice and type(self.choice[0])==str: #print '%s: Choice of strings (%s)!!!!'%(self.name,str(self.choice)) # choice from strings def validateStrChoice(self,val): if val not in self.choice: raise ValueError("%s: '%s' is not an admissible value (must be one of: %s)"%(self.name,str(val),', '.join(["'%s'"%str(c) for c in self.choice]))) self.validator=validateStrChoice # PSD buttons if psd: if self.buttons: raise ValueError("%s: psd and buttons are mutually exclusive (psd created a button for displaying the PSD)"%self.name) self.buttons=(['Plot the PSD','import pylab; pylab.plot(*zip(*self.%s)); pylab.grid(True); pylab.show();'%(self.name),''],0) # # units # import woo._units baseUnit=woo._units.baseUnit def _unicodeUnit(u): if isinstance(u,unicode): return u elif isinstance(u,str): return unicode(u,'utf-8') elif isinstance(u,tuple): return (_unicodeUnit(u[0]),u[1]) raise ValueError(u"Unknown unit type %sfor %s"%(str(type(u)),u)) if isinstance(unit,str) or isinstance(unit,unicode): unit=[_unicodeUnit(unit)] if altUnits: altUnits=[[_unicodeUnit(a) for a in altUnits]] if not unit: self.unit=None self.multiUnit=False self.prefUnit=None self.altUnits=None elif isinstance(unit,list) or isinstance(unit,tuple): self.multiUnit=(len(unit)>1) self.unit=[] self.altUnits=[] self.prefUnit=[] for u in unit: # print self.name,u if u not in baseUnit: raise ValueError(u'Unknown unit %s; admissible values are: '%u+', '.join(baseUnit.keys())) base=baseUnit[u] self.unit.append(base) self.prefUnit.append((u,1./woo.unit[u])) alts=[] for alt in baseUnit: if baseUnit[alt]==base and alt!=base: alts.append((alt,1./woo.unit[alt])) self.altUnits.append(alts) # user-specified alternative units if altUnits: if len(altUnits)!=len(self.unit): raise ValueError("altUnits must be of the same length as unit") for i,au in enumerate(altUnits): self.altUnits[i]+=au else: raise ValueError('Unknown unit type %s (must be list, tuple, str, unicode): %s'%(type(unit).__name__,str(unit))) def validate(self,val): 'Called when the attribute is set' if self.validator: self.validator(self,val) def coerceValue(self,val): 'Check whether *val* has type compatible with declared type (pyType). Raise exception if not. Values converted to required types are returned (it is safe to ignore the return value). In addition, validate the (converted) value, if a validator is defined' def tName(T): return (T.__module__+'.' if T.__module__!='__builtin__' else '')+T.__name__ # sequences if isinstance(self.pyType,list): assert len(self.pyType)==1 ret=[] if not hasattr(val,'__len__'): raise TypeError("Attribute {self.name} declared as sequence of {T}{cxxType}, but its value {val!s} of type {valType} is not a sequence (__len__ not defined).".format(self=self,T=tName(self.pyType[0]),val=val,valType=tName(type(val)),cxxType=((' ('+self.cxxT+' in c++') if hasattr(self,'cxxT') else ''))) T=self.pyType[0] if T in self.primitiveTypes: # check convertibility for i,v in enumerate(val): try: if type(v) in (str,unicode) and T in (float,int): raise TypeError("Don't allow conversions from strings to numbers, since that will fail if used without conversion") ret.append(T(v)) except: raise TypeError("Attribute {self.name} declared as sequence of {T}, but {i}'th item {v!s} of type {itemType} is not convertible to {T}.".format(self=self,i=i,v=v,itemType=tName(type(v)),T=tName(T))) else: for i,v in enumerate(val): ret.append(v) if v==None: continue # python representation for NULL shared_ptr if not isinstance(v,T): raise TypeError("Attribute {self.name} declared as a sequence of {T}, but {i}'th item {v!s} of type {itemType} is not a {T}.".format(self=self,i=i,v=v,itemType=tName(type(v)),T=tName(T))) else: # do the same as for sequence items; ugly code duplication T=self.pyType if T in self.primitiveTypes: try: if type(val) in (str,unicode) and T in (float,int): raise TypeError("Don't allow conversions from strings to numbers, since that will fail if used without conversion") ret=T(val) except: raise TypeError("Attribute {self.name} declared as {T}, but value {val!s} of type {valType} is not convertible to {T}".format(self=self,val=val,valType=tName(type(val)),T=tName(T))) else: # objects ret=val if val!=None and not isinstance(val,T): raise TypeError("Attribute {self.name} declared as {T}, but value {val!s} of type {valType} is not a {T}".format(self=self,val=val,valType=tName(type(val)),T=tName(T))) self.validate(ret) return ret def __str__(self): return '<PyAttrTrait '+self.name+' @ '+str(id(self))+'>' def __repr__(self): return self.__str__() class PyWooObject: ''' Define some c++-compatibility functions for python classes. Derived class is created as:: class SomeClass(woo.core.Object,woo.pyderived.PyWooObject): # order of base classes important! _attrTraits=[ # see below ] def __init__(self,**kw): woo.core.Object.__init__(self) self.wooPyInit(self.__class__,woo.core.Object,**kw) This new class automatically obtains several features: * dumping/loading via :obj:`woo.core.Object.dump` etc works. * the GUI (:obj:`woo.qt.ObjectEditor`) will know how to present this class. * documentation for this class will be generated * all attributes are type-checked when assigned * support for postLoad hooks (see below) The `_attrTraits` ist a list of :obj:`PyAttrTrait`; each attribute is defined via its traits, which declare its type, default value, documentation and so on -- this is documented with :obj:`PyAttrTrait`. This example shows trait definitions, and also the `triggerPostLoad` flag:: class SomeClass(woo.core.Object,woo.pyderived.PyWooObject): _PAT=woo.pyderived.PyAttrTrait # alias for class name, to save typing _attrTraits=[ _PAT(float,'aF',1.,'float attr'), _PAT([float,],'aFF',[0.,1.,2.],'list of floats attr'), _PAT(Vector2,'aV2',(0.,1.),'vector2 attr'), _PAT([Vector2,],'aVV2',[(0.,0.),(1.,1.)],'list of vector2 attr'), _PAT(woo.core.Node,'aNode',woo.core.Node(pos=(1,1,1)),'node attr'), _PAT([woo.core.Node,],'aNNode',[woo.core.Node(pos=(1,1,1)),woo.core.Node(pos=(2,2,2))],'List of nodes'), _PAT(float,'aF_trigger',1.,triggerPostLoad=True,doc='Float triggering postLoad'), ] def postLoad(self,I): if I==None: pass # called when constructed/loaded elif I==id(self.aF_trigger): pass # called when aF_trigger is modified def __init__(self,**kw): pass # ... The `postLoad` function is called with * `None` when the instance has just been created (or loaded); it *shoud* be idempotent, i.e. calling `postLoad(None)` the second time should have no effect:: SomeClass() # default-constructed; will call postLoad(None) SomeClass(aF=3.) # default-construct, assign, call postLoad(None) * `id(self.attr)` when `self.attr` is modified; this can be used to check for some particular conditions or modify other variables:: instance=SomeClass() # calls instance.postLoad(None) instance.aF_trigger=3 # calls instance.postLoad(id(instance.aF_trigger)) .. note:: Pay attention to not call `postLoad` in infinite regression. ''' def wooPyInit(self,derivedClass,cxxBaseClass,**kw): '''Inject methods into derivedClass, so that it behaves like woo.core.Object, for the purposes of the GUI and expression dumps''' cxxBaseClass.__init__(self) # repeat, just to make sure self.cxxBaseClass=cxxBaseClass self.derivedClass=derivedClass self._instanceTraits={} self._attrValues={} self._attrTraitsDict=dict([(trait.name,trait) for trait in derivedClass._attrTraits]) for trait in derivedClass._attrTraits: # basic getter/setter getter=(lambda self,trait=trait: self._attrValues[trait.name]) setter=(lambda self,val,trait=trait: self._attrValues.__setitem__(trait.name,trait.coerceValue(val))) if trait.triggerPostLoad: if not hasattr(derivedClass,'postLoad'): raise RuntimeError('%s.%s declared with triggerPostLoad, but %s.postLoad is not defined.'%(derivedClass.__name__,trait.name,derivedClass.__name__)) def triggerSetter(self,val,trait=trait): self._attrValues[trait.name]=trait.coerceValue(val) self.postLoad(id(self._attrValues[trait.name])) setter=triggerSetter # chain validation and actual setting def validatingSetter(self,val,trait=trait,setter=setter): trait.validate(val) setter(self,val) setattr(derivedClass,trait.name,property(getter,validatingSetter,None,trait.doc)) self._attrValues[trait.name]=trait.ini #print derivedClass,self._attrValues if kw: for k in kw: if not hasattr(self,k): raise AttributeError('No such attribute: %s'%k) if k in self._attrValues: self._attrValues[k]=self._attrTraitsDict[k].coerceValue(kw[k]) else: setattr(self,k,kw[k]) derivedClass.__str__=lambda o:'<%s @ %d (py)>'%(derivedClass.__name__,id(o)) derivedClass.__repr__=derivedClass.__str__ derivedClass._cxxAddr=property(lambda sefl: id(self)) # pickle support def __getstate__(self): #print '__getstate__ in python' ret=self._attrValues.copy() ret.update(cxxBaseClass.__getstate__(self)) # get boost::python stuff as well return ret def __setstate__(self,st): #print '__setstate__ in python' # set managed attributes indirectly, to avoid side-effects for k in st.keys(): if k in self._attrValues: self._attrValues[k]=self._attrTraitsDict[k].coerceValue(st.pop(k)) # set remaining attributes using setattr for k,v in st.items(): setattr(self,k,v) # call postLoad as if after loading if hasattr(derivedClass,'postLoad'): self.postLoad(None) def deepcopy(self): '''The c++ dedepcopy uses boost::serialization, we need to use pickle. As long as deepcopy is called from python, this function gets precende over the c++ one.''' import pickle return pickle.loads(pickle.dumps(self)) derivedClass.__getstate__=__getstate__ derivedClass.__setstate__=__setstate__ derivedClass.deepcopy=deepcopy if hasattr(derivedClass,'postLoad'): self.postLoad(None) if __name__=='wooMain': # do not define this class when running woo normally, # so that it does not show up in the preprocessor dialogue # inheritance order must not change, due to us using __bases__[0] frequently # when traversing the class hierarchy class SamplePyDerivedPreprocessor(Preprocessor,PyWooObject): 'Sample preprocessor written in pure python' _classTraits=None _attrTraits=[ PyAttrTrait(bool,'switch',True,"Some bool switch, starting group",startGroup='General'), PyAttrTrait(int,'a',2,"Integer argument in python"), PyAttrTrait(str,'b','whatever',"String argument in python"), PyAttrTrait([Node,],'c',[],"List of nodes in python"), PyAttrTrait(float,'d',.5,"Parameter with range",range=Vector2(0,.7),startGroup='Advanced'), PyAttrTrait(int,'choice',2,"Param with choice",choice=[(0,'choice0'),(1,'choice1'),(2,'choice2')]), PyAttrTrait(int,'flags',1,"Param with bits",bits=['bit0','bit1','bit2','bit3','bit4'],buttons=(['Clear flags','self.flags=0','Set flags to zero'],True)), PyAttrTrait(int,'choice2',2,'Param with unnamed choice',choice=[0,1,2,3,4,5,6,-1]), PyAttrTrait(Vector3,'color',Vector3(.2,.2,.2),"Color parameter",rgbColor=True), PyAttrTrait(float,'length',1.5e-3,"Length",unit='mm'), PyAttrTrait(str,'outDir','/tmp',dirname=True,doc='output directory'), ] def __init__(self,**kw): # construct all instance attributes Preprocessor.__init__(self) self.wooPyInit(SamplePyDerivedPreprocessor,Preprocessor,**kw) def __call__(self): import woo.core, woo.dem, woo.utils S=woo.core.Scene(fields=[woo.dem.DemField()]) S.dem.par.append([ woo.utils.wall(0,axis=2,sense=1), woo.utils.sphere((0,0,1),radius=.2) ]) S.dem.gravity=(0,0,-10) S.dt=1e-4*woo.utils.pWaveDt(S) S.engines=woo.utils.defaultEngines(damping=.01) S.dem.collectNodes() return S import woo.pre woo.pre.SamplePyDerivedPreprocessor=SamplePyDerivedPreprocessor t=PyAttrTrait(str,'sChoice','aa',choice=['aa','bb','cc'],doc='string choice with validation') t.validate('abc')
Azeko2xo/woodem
py/pyderived.py
pyderived.py
py
20,207
python
en
code
2
github-code
6
28969795163
""" Artifact module. """ from __future__ import annotations import typing from typing import Self from sdk.entities.artifact.metadata import build_metadata from sdk.entities.artifact.spec import build_spec from sdk.entities.base.entity import Entity from sdk.entities.utils.utils import get_uiid from sdk.utils.api import DTO_ARTF, api_ctx_create, api_ctx_update from sdk.utils.exceptions import EntityError from sdk.utils.factories import get_context, get_default_store from sdk.utils.file_utils import check_file, get_dir from sdk.utils.uri_utils import get_name_from_uri, get_uri_scheme, rebuild_uri if typing.TYPE_CHECKING: from sdk.entities.artifact.metadata import ArtifactMetadata from sdk.entities.artifact.spec import ArtifactSpec class Artifact(Entity): """ A class representing a artifact. """ def __init__( self, project: str, name: str, kind: str = None, metadata: ArtifactMetadata = None, spec: ArtifactSpec = None, local: bool = False, embedded: bool = False, uuid: str = None, **kwargs, ) -> None: """ Initialize the Artifact instance. Parameters ---------- project : str Name of the project. name : str Name of the artifact. kind : str Kind of the artifact metadata : ArtifactMetadata Metadata of the object. spec : ArtifactSpec Specification of the object. local: bool If True, run locally. embedded: bool If True embed object in backend. **kwargs Keyword arguments. """ super().__init__() self.project = project self.name = name self.kind = kind if kind is not None else "artifact" self.metadata = metadata if metadata is not None else build_metadata(name=name) self.spec = spec if spec is not None else build_spec(self.kind, **{}) self.embedded = embedded self.id = uuid if uuid is not None else get_uiid() self._local = local # Temporary local artifact path (see as_file()) self._temp_path = None # Set new attributes self._any_setter(**kwargs) # Set context self._context = get_context(self.project) # Set key in spec store://<project>/artifacts/<kind>/<name>:<uuid> self.spec.key = ( f"store://{self.project}/artifacts/{self.kind}/{self.name}:{self.id}" ) ############################# # Save / Export ############################# def save(self, uuid: str = None) -> dict: """ Save artifact into backend. Parameters ---------- uuid : str UUID. Returns ------- dict Mapping representation of Artifact from backend. """ if self._local: raise EntityError("Use .export() for local execution.") obj = self.to_dict() if uuid is None: api = api_ctx_create(self.project, DTO_ARTF) return self._context.create_object(obj, api) self.id = uuid api = api_ctx_update(self.project, DTO_ARTF, self.name, uuid) return self._context.update_object(obj, api) def export(self, filename: str = None) -> None: """ Export object as a YAML file. Parameters ---------- filename : str Name of the export YAML file. If not specified, the default value is used. Returns ------- None """ obj = self.to_dict() filename = ( filename if filename is not None else f"artifact_{self.project}_{self.name}.yaml" ) self._export_object(filename, obj) ############################# # Artifacts Methods ############################# def as_file(self, target: str = None) -> str: """ Get artifact as file. In the case of a local store, the store returns the current path of the artifact. In the case of a remote store, the artifact is downloaded in a temporary directory. Parameters ---------- target : str Target path is the remote path of the artifact where it is stored Returns ------- str Temporary path of the artifact. """ # Get store store = get_default_store() # If local store, return local artifact path if store.is_local(): self._check_src() return self.spec.src_path # Check if target path is specified self._check_target(target) # Check if target path is remote self._check_remote() # Download artifact and return path self._temp_path = store.download(self.spec.target_path) return self._temp_path def download( self, target: str = None, dst: str = None, overwrite: bool = False ) -> str: """ Download artifact from backend. Parameters ---------- target : str Target path is the remote path of the artifact dst : str Destination path as filename overwrite : bool Specify if overwrite an existing file Returns ------- str Path of the downloaded artifact. """ # Check if target path is specified self._check_target(target) # Check if target path is remote self._check_remote() # Check if download destination path is specified and rebuild it if necessary dst = self._rebuild_dst(dst) # Check if destination path exists for overwrite self._check_overwrite(dst, overwrite) # Get store store = get_default_store() # Download artifact and return path return store.download(self.spec.target_path, dst) def upload(self, source: str = None, target: str = None) -> str: """ Upload artifact to backend. Parameters ---------- source : str Source path is the local path of the artifact target : str Target path is the remote path of the artifact Returns ------- str Path of the uploaded artifact. """ # Check if source path is provided. self._check_src(source) # Check if source path is local self._check_local() # Check if target path is provided. self._check_target(target, upload=True) # Check if target path is remote self._check_remote() # Get store store = get_default_store() # Upload artifact and return remote path return store.upload(self.spec.src_path, self.spec.target_path) ############################# # Private Helpers ############################# def _check_target(self, target: str = None, upload: bool = False) -> None: """ Check if target path is specified. Parameters ---------- target : str Target path is the remote path of the artifact upload : bool Specify if target path is for upload Returns ------- None """ if self.spec.target_path is None: if target is None: if not upload: raise EntityError("Target path is not specified.") path = get_dir(self.spec.src_path) filename = get_name_from_uri(self.spec.src_path) target_path = rebuild_uri(f"{path}/{filename}") self.spec.target_path = target_path return self.spec.target_path = target return def _check_src(self, src: str = None) -> None: """ Check if source path is specified. Parameters ---------- src : str Source path is the local path of the artifact Returns ------- None Raises ------ Exception If source path is not specified. """ if self.spec.src_path is None: if src is None: raise EntityError("Source path is not specified.") self.spec.src_path = src def _check_remote(self) -> None: """ Check if target path is remote. Parameters ---------- ignore_raise : bool Specify if raise an exception if target path is not remote Returns ------- None Raises ------ Exception If target path is not remote. """ if self.spec.target_path is None: return if get_uri_scheme(self.spec.target_path) in ["", "file"]: raise EntityError("Only remote source URIs are supported for target paths") def _check_local(self) -> None: """ Check if source path is local. Returns ------- None Raises ------ Exception If source path is not local. """ if get_uri_scheme(self.spec.src_path) not in ["", "file"]: raise EntityError("Only local paths are supported for source paths.") def _rebuild_dst(self, dst: str = None) -> None: """ Check if destination path is specified. Parameters ---------- dst : str Destination path as filename Returns ------- str Destination path as filename. """ if dst is None: dst = f"./{get_name_from_uri(self.spec.target_path)}" return dst @staticmethod def _check_overwrite(dst: str, overwrite: bool) -> None: """ Check if destination path exists for overwrite. Parameters ---------- dst : str Destination path as filename. overwrite : bool Specify if overwrite an existing file. Raises ------ Exception If destination path exists and overwrite is False. """ if check_file(dst) and not overwrite: raise EntityError(f"File {dst} already exists.") ############################# # Getters and Setters ############################# @property def local(self) -> bool: """ Get local flag. """ return self._local @property def temp_path(self) -> str: """ Get temporary path. """ return self._temp_path ############################# # Generic Methods ############################# @classmethod def from_dict(cls, obj: dict) -> Self: """ Create object instance from a dictionary. Parameters ---------- obj : dict Dictionary to create object from. Returns ------- Self Self instance. """ parsed_dict = cls._parse_dict(obj) obj_ = cls(**parsed_dict) obj_._local = obj_._context.local return obj_ @staticmethod def _parse_dict(obj: dict) -> dict: """ Parse dictionary. Parameters ---------- obj : dict Dictionary to parse. Returns ------- dict Parsed dictionary. """ # Mandatory fields project = obj.get("project") name = obj.get("name") if project is None or name is None: raise EntityError("Project or name are not specified.") # Optional fields uuid = obj.get("id") kind = obj.get("kind") embedded = obj.get("embedded") # Build metadata and spec spec = obj.get("spec") spec = spec if spec is not None else {} spec = build_spec(kind=kind, **spec) metadata = obj.get("metadata", {"name": name}) metadata = build_metadata(**metadata) return { "project": project, "name": name, "kind": kind, "uuid": uuid, "metadata": metadata, "spec": spec, "embedded": embedded, } def artifact_from_parameters( project: str, name: str, description: str = "", kind: str = "artifact", key: str = None, src_path: str = None, target_path: str = None, local: bool = False, embedded: bool = False, uuid: str = None, ) -> Artifact: """ Create artifact. Parameters ---------- project : str Name of the project. name : str Identifier of the artifact. description : str Description of the artifact. kind : str The type of the artifact. key : str Representation of artfact like store://etc.. src_path : str Path to the artifact on local file system or remote storage. targeth_path : str Destination path of the artifact. local : bool Flag to determine if object has local execution. embedded : bool Flag to determine if object must be embedded in project. uuid : str UUID. Returns ------- Artifact Artifact object. """ meta = build_metadata(name=name, description=description) spec = build_spec(kind, key=key, src_path=src_path, target_path=target_path) return Artifact( project=project, name=name, kind=kind, metadata=meta, spec=spec, local=local, embedded=embedded, uuid=uuid, ) def artifact_from_dict(obj: dict) -> Artifact: """ Create artifact from dictionary. Parameters ---------- obj : dict Dictionary to create artifact from. Returns ------- Artifact Artifact object. """ return Artifact.from_dict(obj)
trubbio83/core
sdk/sdk/entities/artifact/entity.py
entity.py
py
14,056
python
en
code
0
github-code
6