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
3038364585
import pandas as pd mushrooms = pd.read_csv('mushrooms.csv') # convert letters to numbers for n in range(0,mushrooms.shape[1]): mushrooms.iloc[:,n] = [ord(x) - 97 \ for x in mushrooms[mushrooms.columns[n]]] mushrooms.to_csv('mushrooms_clean.csv',index=False)
estimatrixPipiatrix/decision-scientist
pythonCode/support_vector/clean_data.py
clean_data.py
py
276
python
en
code
0
github-code
6
19528118390
__author__ = 'zhaicao' import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QInputDialog, QApplication, QColorDialog, QFrame, QVBoxLayout, QSizePolicy, QLabel, QFontDialog, QTextEdit, QAction, QFileDialog ,QMainWindow) from PyQt5.QtGui import QColor, QIcon #通过输入框改变文字 class simple_1(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): col = QColor() self.btn = QPushButton('Dialog', self) self.btn.move(20, 20) #绑定按钮点击信号和槽函数 self.btn.clicked.connect(self.showDialog) self.el = QLineEdit(self) self.el.move(130, 22) self.setGeometry(300, 300, 290, 150) self.setWindowTitle('Dialog') self.show() def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: self.el.setText(str(text)) #通过对话框改变颜色 class simple_2(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): col = QColor(0, 0, 0) self.btn = QPushButton('Dialog', self) self.btn.move(20, 20) #绑定按钮点击信号和槽函数 self.btn.clicked.connect(self.showDialog) self.frm = QFrame(self) self.frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.frm.setGeometry(130, 22, 100, 100) self.setGeometry(300, 300, 250, 180) self.setWindowTitle('Color Dialog') self.show() def showDialog(self): col = QColorDialog.getColor() if col.isValid(): self.frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) #通过对话框改变字体 class simple_3(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QVBoxLayout() btn = QPushButton('Dialog', self) btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btn.move(20, 20) vbox.addWidget(btn) btn.clicked.connect(self.showDialog) self.lbl = QLabel('Knowledge only matters', self) self.lbl.move(130, 20) vbox.addWidget(self.lbl) self.setLayout(vbox) self.setGeometry(300, 300, 250, 180) self.setWindowTitle('Color Dialog') self.show() def showDialog(self): font, ok = QFontDialog.getFont() if ok: self.lbl.setFont(font) #通过对话框选择文件或目录 class simple_4(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.statusBar() openFile = QAction(QIcon('web.png'), 'OPen', self) openFile.setShortcut('Ctrl+o') openFile.setStatusTip('Open new file') openFile.triggered.connect(self.showDialog) menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(openFile) self.setGeometry(300, 300, 250, 180) self.setWindowTitle('Color Dialog') self.show() def showDialog(self): fname = QFileDialog.getOpenFileName(self, 'Open File', 'C:/Users/slave/Desktop', 'Xml Files(*.xml);;Excel Files(*.xls *.xlsx);;Word Files(*.doc)') print(fname) if fname[0]: f = open(fname[0], 'r') with f: data = f.read() self.textEdit.setText(str(data)) if __name__=='__main__': app = QApplication(sys.argv) s = simple_4() sys.exit(app.exec_())
zhaicao/pythonWorkspace
Pyqt5Practice/demo_8.py
demo_8.py
py
3,852
python
en
code
0
github-code
6
27278546383
from cProfile import label from genericpath import exists from math import ceil import os import random import numpy as np import argparse import time import torch import torch.nn as nn import torch.nn.functional as F from torch import optim, autograd from matplotlib import pyplot as plt import seaborn as sns from mpl_toolkits.axes_grid1 import make_axes_locatable from tqdm import tqdm from utils import * from model import * parser = argparse.ArgumentParser() parser.add_argument("-e", "--epochs", type=int, default=30000) parser.add_argument("-lr", "--learningrate", type=float, default=3e-3) parser.add_argument("-i", "--indim", type=int, default=2) parser.add_argument("-o", "--outdim", type=int, default=1) parser.add_argument("-hd", "--hiddim", type=int, default=10) parser.add_argument("-hn", "--hidnum", type=int, default=5) parser.add_argument("-p", "--pretrained", type=bool, default=False) parser.add_argument("-s", "--seed", type=int, default=2022) parser.add_argument("-sp", "--sample", type=int, default=100) parser.add_argument("-skip", "--skip", type=bool, default=True) args = parser.parse_args() EPOCHS = args.epochs LR = args.learningrate IN_DIM = args.indim OUT_DIM = args.outdim HIDDEN_DIM = args.hiddim NUM_HIDDENS = args.hidnum PRETRAINED = args.pretrained SEED = args.seed SAMPLE = args.sample SKIP = args.skip sns.set_style("white") exp_name = "actSiLU" path = os.path.join("./results/", exp_name) os.makedirs(path, exist_ok=True) def u_real(x): return (1 - x[:, 0]**2) * (1 - x[:, 1]**2) def fetch_interior_points(N=128, d=2): return torch.rand(N, d) * 2 - 1 def fetch_boundary_points(N=33): index = torch.rand(N, 1) index1 = torch.rand(N, 1) * 2 - 1 xb1 = torch.cat((index1, torch.ones_like(index1)), dim=1) xb2 = torch.cat((index1, torch.full_like(index1, -1)), dim=1) xb3 = torch.cat((torch.ones_like(index1), index1), dim=1) xb4 = torch.cat((torch.full_like(index1, -1), index1), dim=1) xb = torch.cat((xb1, xb2, xb3, xb4), dim=0) return xb if __name__ == "__main__": device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Training Device: {device}") seed_everything(SEED) print(f"Random Seed: {SEED}") model = FullConnected_DNN( in_dim=IN_DIM, out_dim=OUT_DIM, hidden_dim=HIDDEN_DIM, num_blks=NUM_HIDDENS, skip=SKIP, act=nn.SiLU(), ).to(device) losses = [] losses_r = [] losses_b = [] model.apply(initialize_weights) optimizer = optim.Adam(model.parameters(), lr=LR) scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=500, T_mult=2, last_epoch=-1) best_loss, best_b, best_r, best_epoch = 0x3F3F3F, 0x3F3F3F, 0x3F3F3F, 0 bar = tqdm(range(EPOCHS)) model.train() t0 = time.time() for epoch in bar: bar.set_description("Training Epoch " + str(epoch)) # generate the data set xr = fetch_interior_points() xb = fetch_boundary_points() xr = xr.to(device) xb = xb.to(device) xr.requires_grad_() output_r = model(xr) output_b = model(xb) # print(output_r.shape, output_b.shape) grads = autograd.grad( outputs=output_r, inputs=xr, grad_outputs=torch.ones_like(output_r), create_graph=True, retain_graph=True, only_inputs=True, )[0] # print(torch.sum(torch.pow(grads, 2), dim=1).shape, output_r.shape) # loss_r = 0.5 * torch.sum(torch.pow(grads, 2), dim=1) - output_r # loss_r = 0.5 * torch.sum(torch.pow(grads, 2), dim=1) loss_r = (0.5 * torch.sum(torch.pow(grads, 2), dim=1) - (4 - 2 * torch.sum(torch.pow(xr, 2), dim=1)) * output_r) loss_r = torch.mean(loss_r) loss_b = torch.mean(torch.pow(output_b, 2)) # loss = 4 * loss_r + 9 * 500 * loss_b loss = loss_r + 100 * loss_b # loss = loss_r + 500 * loss_b bar.set_postfix({ "Tol Loss": "{:.4f}".format(abs(loss)), "Var Loss": "{:.4f}".format(abs(loss_r)), "Bnd Loss": "{:.4f}".format(abs(loss_b)), }) optimizer.zero_grad() loss.backward() optimizer.step() scheduler.step() loss_t = loss.detach().numpy() losses.append(abs(loss_t)) loss_r = loss_r.detach().numpy() losses_r.append(abs(loss_r)) loss_b = loss_b.detach().numpy() losses_b.append(abs(loss_b)) saved = False if epoch > int(4 * EPOCHS / 5): if torch.abs(loss) < best_loss: best_loss = torch.abs(loss).item() best_b = loss_b best_r = loss_r best_epoch = epoch torch.save(model.state_dict(), os.path.join(path, "ckpt.bin")) if not saved: torch.save(model.state_dict(), os.path.join(path, "ckpt.bin")) print( "Best epoch:", best_epoch, "Best loss:", best_loss, "Best Var loss:", best_r, "Best Boundary loss", best_b, ) elapse = time.time() - t0 print(f"Training time: {elapse}") print(f"# of parameters: {get_param_num(model)}") # plot figure model.eval() model.load_state_dict(torch.load(os.path.join(path, "ckpt.bin"))) print("Load weights from checkpoint!") with torch.no_grad(): x1 = torch.linspace(-1, 1, 1001) x2 = torch.linspace(-1, 1, 1001) X, Y = torch.meshgrid(x1, x2) Z = torch.cat((Y.flatten()[:, None], Y.T.flatten()[:, None]), dim=1) Z = Z.to(device) pred = model(Z) plot_loss_and_save( EPOCHS=EPOCHS, losses=losses, losses_r=losses_r, losses_b=losses_b, SAMPLE=SAMPLE, path=path, ) pred = pred.cpu().numpy() pred = pred.reshape(1001, 1001) plot_result_and_save(pred, path) # print(type(pred), type(u_real(Z))) l2_loss = (np.sqrt( np.sum(np.square(pred - u_real(Z).cpu().numpy().reshape(1001, 1001)))) * (2 / 1000)**2) print(f"l2 Loss: {l2_loss}") print("Output figure saved!")
JiantingFeng/Deep-Ritz-PDE-Solver
new_train.py
new_train.py
py
6,408
python
en
code
3
github-code
6
39480165735
import numpy as np import scipy.sparse as sp agg1_index = np.load("../trace/agg1_index.npy") agg1_adj = np.load("../trace/agg1_adj.npy") input_feature = np.load("../trace/feat1.npy") coo_row = agg1_index[0] coo_col = agg1_index[1] num_nodes = input_feature.shape[0] """ # Use adjacency matrix to generate norm num_nodes = input_feature.shape[0] agg1_coo_ones = sp.coo_matrix((np.ones(agg1_adj.shape), (coo_row, coo_col)), shape=(num_nodes, num_nodes)) agg1_coo_ones_T = sp.coo_matrix((np.ones(agg1_adj.shape), (coo_col, coo_row)), shape=(num_nodes, num_nodes)) temp_ones = np.ones((num_nodes, num_nodes)) right = agg1_coo_ones.multiply(agg1_coo_ones.dot(temp_ones)) right.data = 1 / right.data left = (agg1_coo_ones_T.multiply(agg1_coo_ones_T.dot(temp_ones))).transpose() left.data = 1 / left.data both = left.multiply(right) both.data = np.sqrt(both.data) """ agg1_coo = sp.coo_matrix((agg1_adj, (coo_row, coo_col)), shape=(num_nodes, num_nodes)) fc1_weight = np.load("../trace/fc1_weight.npy") feat1 = agg1_coo.dot(input_feature.dot(fc1_weight)) feat1 = feat1 * (feat1 > 0) agg2_index = np.load("../trace/agg2_index.npy") agg2_adj = np.load("../trace/agg2_adj.npy") coo_row = agg2_index[0] coo_col = agg2_index[1] num_nodes = feat1.shape[0] agg2_coo = sp.coo_matrix((agg2_adj, (coo_row, coo_col)), shape=(num_nodes, num_nodes)) fc2_weight = np.load("../trace/fc2_weight.npy") feat2 = agg2_coo.dot(feat1.dot(fc2_weight)) from dgl.data import PubmedGraphDataset from dgl import AddSelfLoop from inference import dgl_GraphConv import torch.nn.functional as F import torch raw_dir = "../data/dgl" transform = AddSelfLoop() data = PubmedGraphDataset(raw_dir=raw_dir, transform=transform) g = data[0].int() input_feature_t = torch.from_numpy(input_feature) fc1_weight_t = torch.from_numpy(fc1_weight) feat1_dgl = dgl_GraphConv(fc1_weight.shape[0], fc1_weight.shape[1], g, input_feature_t, fc1_weight_t, norm='both') feat1_dgl = F.relu(feat1_dgl) fc2_weight_t = torch.from_numpy(fc2_weight) feat2_dgl = dgl_GraphConv(fc2_weight.shape[0], fc2_weight.shape[1], g, feat1_dgl, fc2_weight_t, norm='both') feat2_dgl_np = np.array(feat2_dgl) print(f"GraphConv vs. MM-AGG: {np.all(np.isclose(feat2_dgl_np, feat2, rtol=1e-5, atol=1e-6), axis=0)}") print((feat2_dgl_np-feat2)[np.nonzero(np.isclose(feat2_dgl_np, feat2, rtol=1e-5, atol=1e-7) == False)]) import yaml from os import path root = "../trace/" f = open(path.join(root,"ir_generated.yaml"), "r") totinfo = yaml.safe_load(f) bias = None feat = 0 for info in totinfo: if info['op_type'] == 'mm': input_feat = np.load(path.join(root,info['op_input_data']['read_data_path'])) weight = np.load(path.join(root,info['op_weight']['read_data_path'])) feat_shape = info['op_weight']['data_shape'] feat = input_feat.dot(weight) elif info['op_type'] == 'agg': if info['reduce_type'] == 'sum': index = np.load(path.join(root,info['op_adj']['read_index_path'])) adj = np.load(path.join(root,info['op_adj']['read_data_path'])) num_nodes = info['op_adj']['data_shape'][0] agg_coo = sp.coo_matrix((adj, (index[0], index[1])), shape=(num_nodes, num_nodes)) input_feat = np.load(path.join(root,info['op_input_data']['read_data_path'])) feat = agg_coo.dot(input_feat) if info['bias'] == True: bias = np.load(path.join(root,info['op_bias']['read_data_path'])) feat = feat + bias if info['relu'] == True: feat = feat * (feat > 0) np.save(path.join(root,info['op_output_data']['write_data_path']), feat) ir_feat = np.load(path.join(root,"feat5.npy")) print(f"MM-AGG vs. IR: {np.all(np.isclose(ir_feat, feat2, rtol=1e-5, atol=1e-6), axis=0)}") print((ir_feat-feat2)[np.nonzero(np.isclose(ir_feat, feat2, rtol=1e-5, atol=1e-7) == False)]) from utils import enlarge_and_save enlarge_and_save(torch.from_numpy(np.load(path.join(root,"true_output.npy"))), 1, "enlarge_true_output") true_output = np.load(path.join(root,"enlarge_true_output.npy")) print(f"DGL vs. IR: {np.all(np.isclose(ir_feat, true_output, rtol=1e-2, atol=0), axis=0)}") print((np.abs(ir_feat-true_output) / true_output)[np.nonzero(np.isclose(ir_feat, true_output, rtol=1e-2, atol=0) == False)])
zhang677/SparseAcc
train/dgl/check.py
check.py
py
4,271
python
en
code
0
github-code
6
17459989896
from flask import current_app, render_template, make_response, session from ecom.datastore import db,redis_store from ecom.exceptions import ServiceUnavailableException from ecom.models import Item, Cart, Account import json import razorpay from ecom.utils import general_util class PaymentManager(): @staticmethod def pay(): category_map = general_util.get_category_map() print ("payment manager pay") if 'email' in session: query = Account.query.filter(Account.email == session['email']) account = query.first() query = Cart.query.filter_by(account_id=account.id, active=True) cart = query.first() print (cart.items) value = 0 for item in cart.items: value += item.price amount = int(value*100) print ("checcccc") print (amount) resp = make_response(render_template('payment.html',name=account.name,email=account.email,contact=account.mobile,amount=amount, category_map=category_map)) resp.headers['Content-type'] = 'text/html; charset=utf-8' return resp else: status_message = "SignUp or Login to continue shopping" resp = make_response(render_template('signup.html',category_map=category_map, status_message=status_message)) resp.headers['Content-type'] = 'text/html; charset=utf-8' return resp @staticmethod def charge(data): category_map = general_util.get_category_map() print ("payment manager charge") print (data) client = razorpay.Client(auth=(current_app.config.get('RAZORPAY_KEY'), current_app.config.get('RAZORPAY_SECRET'))) client.set_app_details({"title" : "mmmkart", "version" : "1.0"}) #data = {"amount": 1000, "currency": "INR", "receipt": "654", "payment_capture": 1} #client.order.create(data=data) query = Account.query.filter(Account.email == session['email']) account = query.first() query = Cart.query.filter_by(account_id=account.id, active=True) cart = query.first() print (cart.items) value = 0 for item in cart.items: value += item.price amount = int(value*100) payment_id = data['razorpay_payment_id'] resp = client.payment.capture(payment_id, amount) print (resp) print (resp['status']) if resp["status"] == "captured": print ("sycccecece") cart.active = False try: print ("inserrr") db.session.add(cart) db.session.commit() except Exception as e: print (e) db.session.rollback() message = "Congratulations !!! Your payment is successful" resp = make_response(render_template('paymentresponse.html',message=message,success=1,category_map=category_map,name=session.get('name'))) resp.headers['Content-type'] = 'text/html; charset=utf-8' return resp else: print ("fsasasas") message = "Oops !!! Your payment got declined. Please retry payment" resp = make_response(render_template('paymentresponse.html',message=message,category_map=category_map,name=session.get('name'))) resp.headers['Content-type'] = 'text/html; charset=utf-8' return resp
ubamax/esocial-app
ecom/managers/payment_manager.py
payment_manager.py
py
3,473
python
en
code
0
github-code
6
23722748410
from django.urls import path from gisapp.views import HomeView, county_datasets, point_datasets from gisapp.api.views import ProvincesListAPIView,ProvincesDetailAPIView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('county_data/', county_datasets, name = 'county'), path('incidence_data/', point_datasets, name = 'incidences'), path("provinces/", ProvincesListAPIView.as_view(), name="pr"), path("provinces/<int:pk>/", ProvincesDetailAPIView.as_view(), name=""), ]
shwky56/geo-django
gisapp/urls.py
urls.py
py
506
python
en
code
0
github-code
6
42543026750
"""Utility related functions. """ import sys import os import ctypes import pygame from .window import * def quit(): """Shuts down ag_py the correct way.""" destroy_window() pygame.quit() sys.exit() def is_admin() -> bool: """Determines if the user is running your game as admin.""" try: return os.getuid() == 0 except AttributeError: return ctypes.windll.shell32.IsUserAnAdmin() != 0 def percent(n1: int, n2: int) -> int: """Finds the percentage of n1 out of n2. For example, if n1 was 5, and n2 was 10, it would return 50. """ return (n1 / n2) * 100 def generate_string(length: int) -> str: """Generates a random string of a given lentgh.""" symbols: str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" final_string: str = "" for i in range(length): final_string += symbols[random.randint(0, len(symbols) - 1)] return final_string
trypolis464/ag_py
agpy/utils.py
utils.py
py
951
python
en
code
0
github-code
6
41234449235
# create by andy at 2022/4/21 # reference: import torchvision from torch.utils.tensorboard import SummaryWriter from torchvision import transforms from torch.utils.data import DataLoader dataset_transform = transforms.Compose([ transforms.ToTensor(), ]) train_set = torchvision.datasets.CIFAR10(root="./dataset", train=True, download=True, transform=dataset_transform) test_set = torchvision.datasets.CIFAR10(root="./dataset", train=True, download=False, transform=dataset_transform) test_loader = DataLoader(dataset=test_set, batch_size=64, shuffle=True, num_workers=0, drop_last=False) writer = SummaryWriter("logs") step = 0 for data in test_loader: imgs, targets = data print(imgs.shape) print(targets) writer.add_images("test_batch", imgs, step) step += 1 # writer = SummaryWriter("logs") # for i in range(10): # img, target = test_set[i] # writer.add_image("test_set", img, i) # # writer.close() if __name__ == '__main__': pass
beishangongzi/study_torch
p10_dataset/dataset_download.py
dataset_download.py
py
1,327
python
en
code
0
github-code
6
11038610201
# -*- coding: utf-8 -*- """ Created on Wed Sep 19 14:24:54 2018 @author: henyd """ from sklearn import tree from sklearn import svm import numpy as np from chatterbot import ChatBot from chatterbot.trainers import ListTrainer def get_response(usrText): bot = ChatBot('Couns', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ 'chatterbot.logic.BestMatch', 'chatterbot.logic.MathematicalEvaluation', { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.70, 'default_response': "Sorry, I didn't understand." } ], trainer='chatterbot.trainers.ListTrainer') bot.set_trainer(ListTrainer) while True: if usrText.strip()!= 'start': result = bot.get_response(usrText) reply = str(result) return(reply) if usrText.strip()== 'start': z = [] with open('features1.txt', 'r') as xf: for xline in xf: x = xline.split(',') for i in range(0,len(x)): x[i] = int(x[i]) z.append(x) w = [] with open('labels1.txt', 'r') as yf: for yline in yf: y = yline w.append(y) clf = tree.DecisionTreeClassifier() clf = clf.fit(z, w) abroad = input("Do you see yourself in some foreign country like USA, Canada, UK, Australia, Russia in about 5 years? [1/0]: ") job = input("Are you satisfied with your bachelor's degree and want to do no more furthur studies ? [1/0]: ") interest = input("Do you love doing coding and are you confident that you can solve the hardest problem if you are given plentiful of time ? [1/0]: ") mba = input("Do you feel so as if you can't perform well in IT and you think that you can't compete well with others from our branch ?: [1/0]: ") prediction = clf.predict([[abroad, job, interest, mba]]) print("You should think of doing: ",prediction) return("Thats all")
henydave/career-counselling-chatbot
chatbot_final2.py
chatbot_final2.py
py
2,211
python
en
code
1
github-code
6
9518060798
from ast import Lambda from functools import reduce l2=[1,2,3,4,5,6,7,8,9] l=[1,2,3,4,5,6,7,8,9,10] a=list(filter(lambda x : x>5,l)) print (a) b=list(map(pow,a,l2)) print(b) sum=(reduce(lambda x, y: x + y,b)) print(sum)
SouvikPaul2000/Souvik-paul-2
Basic code/MapFilterLamdaReduce.py
MapFilterLamdaReduce.py
py
222
python
en
code
0
github-code
6
3916832510
T = int(input()) for _ in range(T): num = int(input()) dp = [0] * (num + 1) dp[1] = 1 dp[2] = 2 dp[3] = 4 for i in range(4,num+1): dp[i] = dp[i-1] + dp[i-2] + dp[i-3] print(dp[num])
jun2mun/code_study
코딩테스트/소프트웨어마에스트로/9095.py
9095.py
py
228
python
en
code
2
github-code
6
26465205985
#aks for your to enter a nummber from 1-10 and if it's the coorect answer it'll say you're correct NUM = 4 keep_asking = True while keep_asking == True: number = int(input("Guess a number between 1 and 10 ")) if number == NUM: keep_asking = False print("Good job you guessed the number") if number > NUM and number <=10: print("Go lower") if number < NUM and number >0: print("Go higher") if number > 10 or number <=0: print("Invalid Number")
standrewscollege2018/2021-year-11-classwork-NekoBrewer
Guess the Number.py
Guess the Number.py
py
504
python
en
code
0
github-code
6
71700390588
from django.shortcuts import render from django.shortcuts import render, redirect from .forms import NewUserForm from django.contrib.auth import login, authenticate from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth import get_user_model User = get_user_model() from datetime import datetime import re from gardenGame.models import buildingOfTheDay from pathlib import Path import os from datetime import date from django.http import HttpResponse DIR = Path(__file__).resolve().parent.parent directory = "static/Users/" BASE_DIR = os.path.join(DIR, directory) building_list = ["Harrison Building","Amory Building","The Forum", "Business School Building One","Cornwall House", "Northcott Theatre","Geoffrey Pope","Great Hall","Hatherly", "Henry Wellcome | Biocatalysis", "Innovation One SWIoT", "Institute of AIS","INTO Study Centre", "Laver","Living Systems","Mary Harris","Old Library", "Peter Chalk Centre","Physics","Queens","Reed Hall","Reed Mews Wellbeing Centre", "Sir Henry Wellcome Building","Sports Park", "Streatham Court","Student Health Centre","Washington Singer","Xfi"] # Create your views here. def homepage(request): return render(request, 'homepage.html') def login_error(request): return render(request, 'loginError.html') def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") today = date.today() d1 = today.strftime("%d/%m/%Y") current_date = d1.split("/") #read in that users file and store it as array #increment the login one, update the date #then write the whole file back file_contents_array = [] with open(os.path.join(BASE_DIR, username + ".txt")) as my_file: for line in my_file: file_contents_array.append(line) my_file.close() login_holder = file_contents_array[0] login_data = login_holder.split(",") last_logged_date = login_data[2] last_logged_date = last_logged_date.split("/") if (last_logged_date[0] < current_date[0]): login_data[1] = str(int(login_data[1]) + 1) login_data[2] = d1 elif (last_logged_date[1] < current_date[1]): login_data[1] = str(int(login_data[1]) + 1) login_data[2] = d1 elif (last_logged_date[2] < current_date[2]): login_data[1] = str(int(login_data[1]) + 1) login_data[2] = d1 login_holder = ','.join(login_data) file_contents_array[0] = login_holder+"\n" fileOverwrite = open(os.path.join(BASE_DIR, form.cleaned_data['username'] + ".txt"), "w") for line in file_contents_array: fileOverwrite.write(line) fileOverwrite.close() return redirect('/main/') else: messages.error(request, "Invalid username or password.") return redirect('/loginError') else: messages.error(request, "Invalid username or password.") return redirect('/loginError') form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): code = form.cleaned_data.get('staffVerification') user = User(username=form.cleaned_data.get('username'), email =form.cleaned_data.get('email') ) user.set_password(form.cleaned_data.get('password1')) if code != "": if code == "54321": user.is_superuser=True user.is_staff=True else: messages.error(request, "Unsuccessful registration, Invalid Staff Code") return redirect('/loginError') user.save() login(request, user) messages.success(request, "Registration successful." ) today = date.today() d1 = today.strftime("%d/%m/%Y") current_date = d1.split("/") current_date[0] = str(int(current_date[0])-1) fileCreate = open(os.path.join(BASE_DIR, form.cleaned_data['username']+".txt"), "x") fileCreate.write("login_streak,0,"+current_date[0]+"/"+current_date[1]+"/"+current_date[2]) fileCreate.close() fileAppend = open(os.path.join(BASE_DIR, form.cleaned_data['username']+".txt"), "a") for build in building_list: fileAppend.write(build + ",0,00/00/0000\n") fileCreate.close() return redirect('/main') messages.error(request, "Unsuccessful registration. Invalid information.") return redirect('/loginError') form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def loginStreak(request, user_id): user = User.objects.get(id=user_id) if(user.LastLogin != datatime.today()): user.LoginStreak = user.LoginStreak+1 user.LastLogin = datetime.now().date() user.save() redirect("/main") def simple_function(request): listTemp = str(request).split("?") TempUsername = request.user.username Temp = listTemp[1] Temp = Temp.split("%20&%20")[0] building = re.sub(r'%20', ' ', Temp) building = re.sub(r"'>", '', building) building = re.sub(r'You%20have%20checked%20in%20at%20:%20','',building) ##May need to correct string to be int and then put in error handing userList = User.objects.get(username = TempUsername) user = userList if(building == "Harrison Building"): if(str(user.Harrison_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Harrison_Streak = user.Harrison_Streak + 1 user.Harrison_lastLogin = datetime.now().date() elif(building == "Amory Building"): if(str(user.Amory_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Amory_Streak = user.Amory_Streak + 1 user.Amory_lastLogin = datetime.now().date() elif(building == "The Forum"): if(str(user.Forum_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Forum_Streak = user.Forum_Streak + 1 user.Forum_lastLogin = datetime.now().date() elif(building == "Business School Building One"): if(str(user.Business_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Business_Streak = user.Business_Streak + 1 user.Business_lastLogin = datetime.now().date() elif(building == "Cornwall House Swimming Pool"): if(str(user.Cornwall_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Cornwall_Streak = user.Cornwall_Streak + 1 user.Cornwall_lastLogin = datetime.now().date() elif(building == "Northcott Theatre"): if(str(user.Northcott_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Northcott_Streak = user.Northcott_Streak + 1 user.Northcott_lastLogin = datetime.now().date() elif(building == "Geoffrey Pope"): if(str(user.Geoffrey_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Geoffrey_Streak = user.Geoffrey_Streak + 1 user.Geoffrey_lastLogin = datetime.now().date() elif(building == "Great Hall"): if(str(user.GreatHall_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.GreatHall_Streak = user.GreatHall_Streak + 1 user.GreatHall_lastLogin = datetime.now().date() elif(building == "Hatherly"): if(str(user.Hatherly_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Hatherly_Streak = user.Hatherly_Streak + 1 user.Hatherly_lastLogin = datetime.now().date() elif(building == "Henry Welcome Building for Biocatalysis"): if(str(user.Henry_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Henry_Streak = user.Henry_Streak + 1 user.Henry_lastLogin = datetime.now().date() elif(building == "Innovation One | South West Institute of Technology"): if(str(user.Innovation_One_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Innovation_One_Streak = user.Innovation_One_Streak + 1 user.Innovation_One_lastLogin = datetime.now().date() elif(building == "Institute of Arab and Islamic Studies"): if(str(user.Iais_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Iais_Streak = user.Iais_Streak + 1 user.Iais_lastLogin = datetime.now().date() elif(building == "INTO International Study Centre"): if(str(user.into_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Into_Streak = user.Into_Streak + 1 user.into_lastLogin = datetime.now().date() elif(building == "Laver"): if(str(user.Laver_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Laver_Streak = user.Laver_Streak + 1 user.Laver_lastLogin = datetime.now().date() elif(building == "Library"): if(str(user.Library_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Library_Streak = user.Library_Streak + 1 user.Library_lastLogin = datetime.now().date() elif(building == "Living Systems"): if(str(user.Living_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Living_Streak = user.Living_Streak + 1 user.Living_lastLogin = datetime.now().date() elif(building == "Mary Harris Memorial Chapel"): if(str(user.Mary_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Mary_Streak = user.Mary_Streak + 1 user.Mary_lastLogin = datetime.now().date() elif(building == "Old Library"): if(str(user.Old_Library_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Old_Library_Streak = user.Old_Library_Streak + 1 user.Old_Library_lastLogin = datetime.now().date() elif(building == "Peter Chalk Centre"): if(str(user.Peter_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Peter_Streak = user.Peter_Streak + 1 user.Peter_lastLogin = datetime.now().date() elif(building == "Physics"): if(str(user.Physics_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Physics_Streak = user.Physics_Streak + 1 user.Physics_lastLogin = datetime.now().date() elif(building == "Queens"): if(str(user.Queen_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Queens_Streak = user.Queens_Streak + 1 user.Queen_lastLogin = datetime.now().date() elif(building == "Reed Hall"): if(str(user.Reed_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Reed_Streak = user.Reed_Streak + 1 user.Reed_lastLogin = datetime.now().date() elif(building == "Reed Mews Wellbeing Centre"): if(str(user.Wellbeing_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Wellbeing_Streak = user.Wellbeing_Streak + 1 user.Wellbeing_lastLogin = datetime.now().date() elif(building == "Sir Henry Welcome Building for Mood Disorders Research"): if(str(user.Mood_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Mood_Streak = user.Mood_Streak + 1 user.Mood_lastLogin = datetime.now().date() elif(building == "Sports Park"): if(str(user.Sports_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Sports_Streak = user.Sports_Streak + 1 user.Sports_lastLogin = datetime.now().date() elif(building == "Streatham Court"): if(str(user.Streatham_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Streatham_Streak = user.Streatham_Streak + 1 user.Streatham_lastLogin = datetime.now().date() elif(building == "Student Health Centre"): if(str(user.Health_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Health_Streak = user.Health_Streak + 1 user.Health_lastLogin = datetime.now().date() elif(building == "Washington Singer"): if(str(user.Washington_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Washington_Streak = user.Washington_Streak + 1 user.Washington_lastLogin = datetime.now().date() elif(building == "Xfi"): if(str(user.Xfi_lastLogin) != str(datetime.today().strftime('%Y-%m-%d'))): user.Xfi_Streak = user.Xfi_Streak + 1 user.Xfi_lastLogin = datetime.now().date() buildingsOTDList = buildingOfTheDay.objects.all() buildingOTD = None for i in buildingsOTDList: if(str(i.date) == datetime.today().strftime('%Y-%m-%d')): buildingOTD = i if(buildingOTD.name == building): reward = buildingOTD.reward if(user.UserRewards != ""): user.UserRewards = user.UserRewards + "*" + reward else: user.UserRewards = reward user.save() return redirect("/main") def test(request): if request.GET.get('NameOfYourButton') == 'YourValue': print('\nuser') print('\nuser clicked button') return HttpResponse("""<html><script>window.location.replace('/')</script></html>""")
KeanDelly/GrowExplore
worldBuilder/Login/views.py
views.py
py
13,994
python
en
code
6
github-code
6
23589518050
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import mne fname ="oddball_example_small-fif.gz" raw = mne.io.read_raw_fif(fname) raw = mne.io.read_raw_fif(fname,preload=True) raw.plot_psd(); raw.plot(); #%%data in 20 different ica components ica = mne.preprocessing.ICA(n_components=20, random_state=0) #%% ica.fit(raw.copy().filter(12,35)) #%% ica.plot_components(outlines="skirt"); #%%we store bad components in ica object ica.exclude=[10,13,15,16,17,18] #%%we could also use one of the automatic algorithms bad_idx,scores = ica.find_bads_eog(raw,"SO2",threshold=1.5) print(bad_idx) #%% ica.exclude=bad_idx #%% raw.plot(); #%% raw=ica.apply(raw.copy(),exclude=ica.exclude) ica.apply(raw.copy(),exclude=ica.exclude).plot(); #%%for epoching the data we need event markers events= mne.find_events(raw) #%% events #%% mne.viz.plot_events(events[:100]); #%%create event ids event_ids= {"standard/stimulus":200, "target/stimulus":100} #%%epochs epochs=mne.Epochs(raw,events,event_id=event_ids) #%% epochs.plot(); #%% #%% epochs=mne.Epochs(raw,events,event_id=event_ids,preload=True) epochs= ica.apply(epochs, exclude=ica.exclude) #%%baseline epochs.apply_baseline((None,0)) #%% epochs["target"]
Sarah436/EEG_Control_Drone
EEG_Drone.py
EEG_Drone.py
py
1,304
python
en
code
0
github-code
6
22989091213
#!/usr/bin/python # -*- coding: utf-8 -*- # utf-8 中文编码 u""" >>> m=encrypt('123456789','1'*16) >>> m '34430c0e47da2207d0028e778c186d55ba4c1fb1528ee06b09a6856ddf8a9ced' >>> decrypt('123456789',m) '1111111111111111' m = encrypt_verify('123','0123456789') print m print decrypt_verify('123',m) """ from Crypto.Cipher import AES import hashlib from binascii import b2a_hex, a2b_hex import json IV = b'dsfgh478fdshg4gf' def encrypt(key,text): # 密钥key 长度必须为16(AES-128), 24(AES-192),或者32 (AES-256)Bytes 长度 # 所以直接将用户提供的 key md5 一下变成32位的。 key_md5 = hashlib.md5(key).hexdigest() # AES.MODE_CFB 是加密分组模式,详见 http://blog.csdn.net/aaaaatiger/article/details/2525561 # b'0000000000000000' 是初始化向量IV ,16位要求,可以看做另一个密钥。在部分分组模式需要。 # 那个 b 别漏下,否则出错。 cipher = AES.new(key_md5,AES.MODE_CFB,IV) # AES 要求需要加密的内容长度为16的倍数,当密文长度不够的时候用 '\0' 不足。 ntext = text + ('\0' * (16-(len(text)%16))) # b2a_hex 转换一下,默认加密后的字符串有很多特殊字符。 return b2a_hex(cipher.encrypt(ntext)) def decrypt(key,text): key_md5 = hashlib.md5(key).hexdigest() cipher = AES.new(key_md5,AES.MODE_CFB,IV) t=cipher.decrypt(a2b_hex(text)) return t.rstrip('\0') def encrypt_verify(key,text): """加密数据,并附带验证信息 key 加密 key text 需要加密字符串 返回data """ data_dict = {'value':text,'security':hashlib.md5(hashlib.md5(key + IV).hexdigest()).hexdigest()} data_json = json.dumps(data_dict,encoding='utf8') return encrypt(key,data_json) def decrypt_verify(key,aes_data): """解密数据,并验证 key 解密 key text 需要解密字符串 解密正常返回数据,否则返回 None """ data = None try: data_json = decrypt(key,aes_data) data = json.loads(data_json,encoding='utf8') except : return None if data['security'] == hashlib.md5(hashlib.md5(key + IV).hexdigest()).hexdigest(): return data['value'] return None
GameXG/shadowsocks_admin
mycrypto.py
mycrypto.py
py
2,044
python
zh
code
175
github-code
6
27591581690
import logging from pymongo import MongoClient from src.utils import Singleton logger = logging.getLogger(__name__) class DBConnection(metaclass=Singleton): def __init__(self, db_settings): self.db_settings = db_settings self.client = MongoClient( host=db_settings['host'], port=int(db_settings['port']), username=db_settings['username'], password=db_settings['password'], authSource='admin' ) def _get_database(self): """ get database :return: database client object """ return self.client['fashion-mnist'] def save_request_info(self, request_id, raw, processed, predictions): """ Save request_id, raw, processed and predictions on mongoDB :param request_id: request id :param raw: raw data (input) :param processed: processed data :param predictions: predictions :return: None """ db = self._get_database() logger.info(f'saving raw_data, processed_data and predictions for {len(raw)} predictions') db['predictions'].insert_many([ { 'request_id': request_id, 'raw_data': raw[i], 'processed_data': processed[i], 'predictions': predictions[i] } for i in range(len(raw))] )
andre1393/fashion-mnist
src/database/mongo_connection.py
mongo_connection.py
py
1,388
python
en
code
0
github-code
6
74849030268
""" @author: Tobias Carryer """ import numpy as np import pandas as pd from pyts.image import GASF, GADF, MTF from splitting_data import get_subject_data from matplotlib import pyplot as plt def create_gasf_gadf_mtf_compound_images(observations, image_size=128): """ Designed to take observations of time series data and create compound images from it to analyze with a CNN. The research paper that came up with GASF-GADF-MTF images can be read here: https://arxiv.org/pdf/1506.00327.pdf :param observations: A 2D array. Shape: [n_observations, observation_window_length] :param image_size: Size of the images to create. Must be equal to or smaller than the length of the time series data in each observation. :raises ValueError: If observations is empty. :return: An array of images ready to be used in a CNN. Shape: [n_observations, image_size, image_size, 3] The origin of each image is the top-left corner. When plotted, it would be the point (0,0). """ if len(observations) == 0: raise ValueError("Observations cannot be empty.") gasf_transformer = GASF(image_size) gadf_transformer = GADF(image_size) mtf_transformer = MTF(image_size) gasf = gasf_transformer.fit_transform(observations) gadf = gadf_transformer.fit_transform(observations) mtf = mtf_transformer.fit_transform(observations) return np.stack((gasf, gadf, mtf), axis=3) if __name__ == "__main__": subject_num_to_study = 4 feature_to_study = "HR" # Generate a compound image and display it to the user all_subject_data = pd.read_csv("confocal_all_patient_phys_data.txt", sep="\t") subject_data = get_subject_data(all_subject_data, subject_num_to_study) i = 0 observation = subject_data[feature_to_study].iloc[i:i+128] while observation.isnull().values.any(): observation = subject_data[feature_to_study].iloc[i:i+128] i += 1 observation = observation.values observations = [observation] images = create_gasf_gadf_mtf_compound_images(observations, image_size=128) gasf = images[:,:,:,0] gadf = images[:,:,:,1] mtf = images[:,:,:,2] plt.figure(figsize=(8, 8)) plt.subplot(221) plt.imshow(gasf[0], cmap='rainbow') plt.title("Gramian Angular Summation Field", fontsize=8) plt.tick_params(axis='x', colors=(0, 0, 0, 0)) plt.tick_params(axis='y', colors=(0, 0, 0, 0)) plt.subplot(222) plt.imshow(gadf[0], cmap='rainbow') plt.title("Gramian Angular Difference Field", fontsize=8) plt.tick_params(axis='x', colors=(0, 0, 0, 0)) plt.tick_params(axis='y', colors=(0, 0, 0, 0)) plt.subplot(223) plt.imshow(mtf[0], cmap='rainbow') plt.title("Markov Transition Field", fontsize=8) plt.tick_params(axis='x', colors=(0, 0, 0, 0)) plt.tick_params(axis='y', colors=(0, 0, 0, 0)) plt.subplot(224) plt.plot(observation) plt.title("Heart Rate", fontsize=8) plt.suptitle("Fields generated for a window of heart rate data") plt.show()
TobCar/delirium
demo_compound_images.py
demo_compound_images.py
py
3,064
python
en
code
0
github-code
6
15169928273
from fastapi import Depends, Request from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from admins.models import TemplateField, Template from permissions import manage_helpdesk from admins.schemas import TemplateFieldSchemaCreate, TemplateFieldSchemaReturn from crud_handler import BaseHandler from database import get_async_session template_fields_router = InferringRouter(tags=["TemplateFields"]) ROUTE = "/api/template_fields" @cbv(template_fields_router) class TemplateFieldView(BaseHandler): session: AsyncSession = Depends(get_async_session) def __init__(self): super().__init__(TemplateField) @template_fields_router.post(f"{ROUTE}/", response_model=TemplateFieldSchemaReturn, status_code=201) async def create_item(self, template_field_object: TemplateFieldSchemaCreate, request: Request): template_field_dict = template_field_object.dict() obj = await self.get_obj(select(Template), self.session, {"id": template_field_dict.get("template").get("id")}) template_field_dict["template"] = obj return await self.create(self.session, template_field_dict) @template_fields_router.delete(f"{ROUTE}/" + "{template_field_id}", status_code=204) async def delete_template_field(self, template_field_id: int, request: Request): return await self.delete(self.session, template_field_id) @template_fields_router.put(f"{ROUTE}/" + "{template_field_id}", response_model=TemplateFieldSchemaReturn, status_code=200) async def update_template_field(self, request: Request, template_field_id: int, template_field: TemplateFieldSchemaReturn): template_field_dict = template_field.dict() template_data = template_field_dict.pop("template") fk_obj = {"template_id": template_data["id"]} template_field_obj = await self.update( session=self.session, id=template_field_id, data=template_field_dict, fk_obj=fk_obj, update_fk=True ) await self.session.commit() return template_field_obj
AlexeyShakov/helpdesk_fast_api
src/admins/endpoints/template_fields.py
template_fields.py
py
2,294
python
en
code
0
github-code
6
353792942
import socket ADDRESS = ("127.0.0.1", 9000) if __name__ == '__main__': while True: client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = input("input: ") client.sendto(data.encode(encoding="utf-8"), ADDRESS) recv, addr = client.recvfrom(1024) print(recv.decode(encoding="UTF-8"), "from", addr)
Masterlovsky/NMRVS
tools/client_udp.py
client_udp.py
py
351
python
en
code
0
github-code
6
5897393360
from fastapi import FastAPI, HTTPException from model import Todo from fastapi.middleware.cors import CORSMiddleware from database import( fetch_all_todos, fetch_one_todo, create_todo, remove_todo, patch_todo ) app = FastAPI() origins = [ "https://localhost:3000", "http://localhost:3000", ] app.add_middleware( CORSMiddleware, allow_origins= origins, allow_credentials= True, allow_methods= ["*"], allow_headers= ["*"] ) @app.get("/") async def read_root(): return {"Hello": "Ahosan"} @app.get("/api/todo") async def get_todo(): response = await fetch_all_todos() return response @app.get("/api/todo/{id}", response_model=Todo) async def get_todo_by_id(id): response = await fetch_one_todo(id) if response: return response raise HTTPException(404, f"There is no todo with {id}") @app.post("/api/todo/", response_model=Todo) async def post_todo(todo: Todo): response = await create_todo(todo.dict()) if response: return response raise HTTPException(400, "Something went wrong") @app.patch("/api/todo/update/{id}/", response_model=Todo) async def update_todo(id: int, todo: Todo): response = await patch_todo(id, todo) return response @app.delete("/api/todo/{id}") async def delete_todo(id): response = await remove_todo(id) if response: return "Successfully deleted Todo" raise HTTPException(404, f"There is no todo with the id {id}")
MdAhosanHabib/Redis-Kafka-FastAPI-React
main.py
main.py
py
1,538
python
en
code
0
github-code
6
74130707068
import datetime def get_next_friday(some_date: datetime.datetime, if_friday_same=True): if if_friday_same: # if a Friday, then same day return some_date + datetime.timedelta((4 - some_date.weekday()) % 7) else: # if a Friday, then next one return some_date + datetime.timedelta((3 - some_date.weekday()) % 7 + 1) if __name__ == "__main__": today = datetime.date.today() print(get_next_friday(today)) another_day = datetime.datetime(2022, 7, 28) # Thursday print(get_next_friday(another_day)) a_friday = datetime.datetime(2022, 7, 29) # Friday print(get_next_friday(a_friday)) a_friday = datetime.datetime(2022, 7, 29) # Friday print(get_next_friday(a_friday, False))
alex-muci/small-projects
snippets/five_min_test.py
five_min_test.py
py
748
python
en
code
0
github-code
6
26824633032
import matplotlib.pyplot as plt import scipy import scipy.interpolate import sys sys.path.append('/home/faustian/python/adas/xxdata_13/') from matplotlib import rc import adasread rc('text', usetex=True) rc('font',**{'family':'serif','serif':['Computer Modern Roman']}) #rc('font',**{'family':'sans-serif','sans-serif':['Computer Modern Sans serif']}) rc('font',size=18) # GRAB Lyalpha ONLY def plot(filein,Telim,Nelim): plt.figure() out = adasread.xxdata_13(filein,1,Telim,Nelim) print(out[13]) print(out[12]) print(out[14]) ne = scipy.array(out[13]).ravel() Te = scipy.array(out[12]).ravel() SXB = scipy.array(out[14][:,:,0]) temp = ne != 0 temp2 = Te != 0 xout,yout = scipy.meshgrid(ne[temp]*1e6,Te[temp2]) zout = SXB[temp2,:] zout = zout[:,temp] plt.pcolor(xout,yout,zout) plt.clim([.3,1.6]) plt.colorbar() plt.xlabel(r'electron density [$10^{20} $m$^{-3}$]') plt.ylabel(r'electron temperature [eV]') #plt.title(filein+' colorbar is ionizations per photon') def plot2(filein,Telim,Nelim,pts=101): plt.figure() out = adasread.xxdata_13(filein,1,Telim,Nelim) print(out[13].shape) print(out[12].shape) print(out[14].shape) ne = scipy.array(out[13]).ravel() Te = scipy.array(out[12]).ravel() SXB = scipy.array(out[14][:,:,0]) temp = ne != 0 temp2 = Te != 0 xout2,yout2 = scipy.meshgrid(ne[temp],Te[temp2]) SXB = SXB[temp2,:] SXB = SXB[:,temp] ne1 = scipy.linspace(ne[temp].min(),ne[temp].max(),pts) Te1 = scipy.linspace(Te[temp2].min(),Te[temp2].max(),pts) xout,yout = scipy.meshgrid(ne1,Te1) interp = scipy.interpolate.RectBivariateSpline(scipy.log(ne[temp]), Te[temp2], SXB) zout = interp.ev(scipy.log(xout),yout) #xout,yout = scipy.meshgrid(ne[temp]*1e6,Te[temp2]) #zout = SXB[temp2,:] #zout = zout[:,temp] plt.pcolor(xout*1e6,yout,zout.T) plt.colorbar() plt.xlabel(r'electron density [$10^{20}$ m$^{-3}$]') plt.ylabel(r'electron temperature [eV]') #plt.title(filein+' colorbar is ionizations per photon') def plot3(filein,Telim,Nelim,pts=11): plt.figure() out = adasread.xxdata_13(filein,1,Telim,Nelim) print(out[13].shape) print(out[12].shape) print(out[14].shape) ne = scipy.array(out[13]).ravel() Te = scipy.array(out[12]).ravel() SXB = scipy.array(out[14][:,:,0]) temp = ne != 0 temp2 = Te != 0 SXB = SXB[temp2,:] SXB = SXB[:,temp] xout2,yout2 = scipy.meshgrid(ne[temp],Te[temp2]) print(Te[temp2]) ne1 = scipy.linspace(ne[temp].min(),ne[temp].max(),pts) Te1 = scipy.linspace(Te[temp2].min(),Te[temp2].max(),pts) xout,yout = scipy.meshgrid(ne1,Te1) zout = scipy.interpolate.griddata((scipy.log(xout2.flatten()),yout2.flatten()),SXB.flatten(),(scipy.log(xout),yout),'cubic') #xout,yout = scipy.meshgrid(ne[temp]*1e6,Te[temp2]) #zout = SXB[temp2,:] #zout = zout[:,temp] plt.imshow(zout,cmap='viridis',extent=[ne1[0]*1e6,ne1[-1]*1e6,Te1[0],Te1[-1]],aspect='auto',origin='lower') #plt.clim([.3,1.8]) colorz = plt.colorbar() colorz.set_label(r'S/XB [ionizations per Ly$_\alpha$ photon]') plt.xlabel(r'electron density [m$^{-3}$]') plt.ylabel(r'electron temperature [eV]') #plt.title(filein+' colorbar is ionizations per photon')
icfaust/Misc
analyzeSXB.py
analyzeSXB.py
py
3,468
python
en
code
0
github-code
6
24354887610
import csv import requests import xml.etree.ElementTree as ET def parseXML(xmlfile): tree = ET.parse(xmlfile) root = tree.getroot() orderitems = [] for item in root.findall('./AddOrder'): orders = {} for child in item: orders[child.tag] = child.text.encode('utf8') orderitems.append(orders) for item in root.findall('./AddOrder'): orders = {} for child in item: orders[child.tag] = child.text.encode('utf8') orderitems.append(orders) return orderitems def savetoCSV(newsitems, filename): fields = ['book', 'operation', 'price', 'volume', 'orderId'] with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = fields) writer.writeheader() writer.writerows(newsitems) def main(): orderitems = parseXML('orders.xml') savetoCSV(orderitems, 'orders.csv') if __name__ == "__main__": # calling main function main()
actioncamen13/Orderbook-submission
csv_convert.py
csv_convert.py
py
1,032
python
en
code
0
github-code
6
26624814566
# # SERMEPA / ServiRed payments module for Satchmo # # Author: Michal Salaban <michal (at) salaban.info> # with a great help of Fluendo S.A., Barcelona # # Based on "Guia de comercios TPV Virtual SIS" ver. 5.18, 15/11/2008, SERMEPA # For more information about integration look at http://www.sermepa.es/ # # TODO: SERMEPA interface provides possibility of recurring payments, which # could be probably used for SubscriptionProducts. This module doesn't support it. # from datetime import datetime from decimal import Decimal from django.core import urlresolvers from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, HttpResponseBadRequest from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import never_cache from livesettings import config_get_group, config_value from payment.utils import get_processor_by_key from payment.views import payship from satchmo_store.shop.models import Order, Cart from satchmo_store.shop.satchmo_settings import get_satchmo_setting from satchmo_utils.dynamic import lookup_url, lookup_template import logging try: from hashlib import sha1 except ImportError: # python < 2.5 from sha import sha as sha1 log = logging.getLogger() def pay_ship_info(request): return payship.base_pay_ship_info( request, config_get_group('PAYMENT_SERMEPA'), payship.simple_pay_ship_process_form, 'shop/checkout/sermepa/pay_ship.html' ) pay_ship_info = never_cache(pay_ship_info) def _resolve_local_url(payment_module, cfgval, ssl=False): try: return lookup_url(payment_module, cfgval.value, include_server=True, ssl=ssl) except urlresolvers.NoReverseMatch: return cfgval.value def confirm_info(request): payment_module = config_get_group('PAYMENT_SERMEPA') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop/404.html', context_instance=context) # Check if we are in test or real mode live = payment_module.LIVE.value if live: post_url = payment_module.POST_URL.value signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: post_url = payment_module.POST_TEST_URL.value signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value # SERMEPA system does not accept multiple payment attempts with the same ID, even # if the previous one has never been finished. The worse is that it does not display # any message which could be understood by an end user. # # If user goes to SERMEPA page and clicks 'back' button (e.g. to correct contact data), # the next payment attempt will be rejected. # # To provide higher probability of ID uniqueness, we add mm:ss timestamp part # to the order id, separated by 'T' character in the following way: # # ID: oooooooTmmss # c: 123456789012 # # The Satchmo's Order number is therefore limited to 10 million - 1. now = datetime.now() xchg_order_id = "%07dT%02d%02d" % (order.id, now.minute, now.second) amount = "%d" % (order.balance * 100,) # in cents signature_data = ''.join( map(str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, signature_code, ) ) ) signature = sha1(signature_data).hexdigest() template = lookup_template(payment_module, 'shop/checkout/sermepa/confirm.html') url_callback = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_CALLBACK, ssl=get_satchmo_setting('SSL')) url_ok = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_OK) url_ko = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_KO) ctx = { 'live': live, 'post_url': post_url, 'MERCHANT_CURRENCY': payment_module.MERCHANT_CURRENCY.value, 'MERCHANT_FUC': payment_module.MERCHANT_FUC.value, 'terminal': terminal, 'MERCHANT_TITULAR': payment_module.MERCHANT_TITULAR.value, 'url_callback': url_callback, 'url_ok': url_ok, 'url_ko': url_ko, 'order': order, 'xchg_order_id' : xchg_order_id, 'amount': amount, 'signature': signature, 'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX'), } return render_to_response(template, ctx, context_instance=RequestContext(request)) confirm_info = never_cache(confirm_info) def notify_callback(request): payment_module = config_get_group('PAYMENT_SERMEPA') if payment_module.LIVE.value: log.debug("Live IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: log.debug("Test IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value data = request.POST log.debug("Transaction data: " + repr(data)) try: sig_data = "%s%s%s%s%s%s" % ( data['Ds_Amount'], data['Ds_Order'], data['Ds_MerchantCode'], data['Ds_Currency'], data['Ds_Response'], signature_code ) sig_calc = sha1(sig_data).hexdigest() if sig_calc != data['Ds_Signature'].lower(): log.error("Invalid signature. Received '%s', calculated '%s'." % (data['Ds_Signature'], sig_calc)) return HttpResponseBadRequest("Checksum error") if data['Ds_MerchantCode'] != payment_module.MERCHANT_FUC.value: log.error("Invalid FUC code: %s" % data['Ds_MerchantCode']) return HttpResponseNotFound("Unknown FUC code") if int(data['Ds_Terminal']) != int(terminal): log.error("Invalid terminal number: %s" % data['Ds_Terminal']) return HttpResponseNotFound("Unknown terminal number") # TODO: fields Ds_Currency, Ds_SecurePayment may be worth checking xchg_order_id = data['Ds_Order'] try: order_id = xchg_order_id[:xchg_order_id.index('T')] except ValueError: log.error("Incompatible order ID: '%s'" % xchg_order_id) return HttpResponseNotFound("Order not found") try: order = Order.objects.get(id=order_id) except Order.DoesNotExist: log.error("Received data for nonexistent Order #%s" % order_id) return HttpResponseNotFound("Order not found") amount = Decimal(data['Ds_Amount']) / Decimal('100') # is in cents, divide it if int(data['Ds_Response']) > 100: log.info("Response code is %s. Payment not accepted." % data['Ds_Response']) return HttpResponse() except KeyError: log.error("Received incomplete SERMEPA transaction data") return HttpResponseBadRequest("Incomplete data") # success order.add_status(status='New', notes=u"Paid through SERMEPA.") processor = get_processor_by_key('PAYMENT_SERMEPA') payment = processor.record_payment( order=order, amount=amount, transaction_id=data['Ds_AuthorisationCode']) # empty customer's carts for cart in Cart.objects.filter(customer=order.contact): cart.empty() return HttpResponse()
dokterbob/satchmo
satchmo/apps/payment/modules/sermepa/views.py
views.py
py
8,365
python
en
code
30
github-code
6
39122527665
import yaml, tempfile, os, libUi import PinshCmd, ConfigField from bombardier_core.static_data import OK, FAIL from SystemStateSingleton import SystemState system_state = SystemState() class CreateType(PinshCmd.PinshCmd): '''A thing that can be created.''' def __init__(self, name, help_text): PinshCmd.PinshCmd.__init__(self, name, help_text) self.config_field = None self.cmd_owner = 1 def cmd(self, command_line): '''Create a thing that the user is interested in''' if command_line.no_flag: return FAIL, [] if len(command_line) < 3: return FAIL, ["Incomplete command."] conf_str = self.config_field.get_default_data() #conf_str = yaml.dump(current_dict, default_flow_style=False) file_descriptor, file_name = tempfile.mkstemp(suffix=".yml", text=True) file_handle = os.fdopen(file_descriptor, 'w+b') file_handle.write(conf_str) file_handle.close() os.system("vim %s" % file_name) post_data = yaml.load(open(file_name).read()) submit = libUi.ask_yes_no("Commit changes to server", libUi.YES) if submit: _status, output = self.config_field.post_specific_data(command_line, 2, post_data) os.unlink(file_name) return OK, [output] else: msg = "Discarded changes. Edits can be found here: %s" % file_name return OK, [msg] class Machine(CreateType): 'Create a default machine configuration data from the server' def __init__(self): CreateType.__init__(self, "machine", "machine\tcreate a new machine configuration") self.config_field = ConfigField.ConfigField(data_type=ConfigField.MACHINE, new=True) self.children = [self.config_field] class Include(CreateType): 'Create an include file on the server' def __init__(self): CreateType.__init__(self, "include", "include\tcreate a shared include file") self.config_field = ConfigField.ConfigField(data_type=ConfigField.INCLUDE, new=True) self.children = [self.config_field] class User(CreateType): 'Create a package file' def __init__(self): CreateType.__init__(self, "user", "user\tcreate a new user to log in to Bombardier") self.config_field = ConfigField.ConfigField(data_type=ConfigField.USER, new=True) self.children = [self.config_field] class Package(CreateType): 'Create a package file' def __init__(self): CreateType.__init__(self, "package", "package\tcreate new package metadata") self.config_field = ConfigField.ConfigField(data_type=ConfigField.PACKAGE, new=True) self.children = [self.config_field] class Bom(CreateType): 'create new bill-of-materials ("bom") file from the server' def __init__(self): CreateType.__init__(self, "bom", "bom\tcreate a bill of materials") self.config_field = ConfigField.ConfigField(data_type=ConfigField.BOM, new=True) self.children = [self.config_field] class Create(PinshCmd.PinshCmd): '''Create a file''' def __init__(self): PinshCmd.PinshCmd.__init__(self, "create") self.help_text = "create\tcreate a new system component" machine = Machine() include = Include() package = Package() user = User() bom = Bom() self.children = [machine, include, bom, package, user] self.cmd_owner = 1
psbanka/bombardier
cli/lib/Create.py
Create.py
py
3,460
python
en
code
1
github-code
6
13922774332
import requests from authid_agent_client.listeners.request_listener import RequestListener DEFAULT_HOST = "localhost" DEFAULT_PORT = 8080 API_PATH = "/api/v0.0.1/" IDS_PATH = API_PATH + "ids/" PROCESSOR_KEYS_PATH = API_PATH + "processorKeys/" REQUESTS_PATH = API_PATH + "requests/" ADDRESSES_PATH = API_PATH + "addresses/" TRANSFER_PATH = API_PATH + "ids:transfer/" CHALLENGES_PATH = API_PATH + "challenges/" SIGN_CHALLENGE_PATH = API_PATH + "challenges:sign" VERIFY_CHALLENGE_PATH = API_PATH + "challenges:verify" VERIFY_CERTS_PATH = API_PATH + "certs:verify" SIGN_CERT_PATH = API_PATH + "certs:sign" class AuthIDAgentClient: def __init__(self, host: str = DEFAULT_HOST, port: str = DEFAULT_PORT, request_callback=None): self.__host = host self.__port = port self.__base_url = "http://" + host + ":" + str(port) self.__ids_url = self.__base_url + IDS_PATH self.__requests_url = self.__base_url + REQUESTS_PATH self.__addresses_url = self.__base_url + ADDRESSES_PATH self.__transfer_url = self.__base_url + TRANSFER_PATH self.__processor_keys_path = self.__base_url + PROCESSOR_KEYS_PATH self.__challenges_path = self.__base_url + CHALLENGES_PATH self.__sign_challenge_path = self.__base_url + SIGN_CHALLENGE_PATH self.__verify_challenge_path = self.__base_url + VERIFY_CHALLENGE_PATH self.__verify_certs_path = self.__base_url + VERIFY_CERTS_PATH self.__sign_cert_path = self.__base_url + SIGN_CERT_PATH self.__request_callback = request_callback def get_authid(self, authid: str): request_url = self.__ids_url + authid request = requests.get(request_url) return request.status_code, request.json() def register_authid(self, id: str, protocol: str, address: str, fee: str): request_url = self.__ids_url + id request = requests.post(request_url, {"protocol": protocol, "address": address, "fee": fee}) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() def transfer_authid(self, id: str, protocol: str, address: str): request = requests.post(self.__transfer_url, {"id": id, "protocol": protocol, "address": address}) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() def generate_processor_keys(self, id: str): request_url = self.__processor_keys_path + id request = requests.post(request_url) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() def new_address(self, protocol: str): request_url = self.__addresses_url + "/" + protocol request = requests.post(request_url) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() """ The authentication functions """ def create_challenge(self, challenger_id: str, receiver_id: str): request = requests.post(self.__challenges_path, params={"challengerID": challenger_id, "receiverID": receiver_id}, headers={"Content-Type": "application/json"}) return request.status_code, request.json() def sign_challenge(self, challenge: dict): request = requests.post(self.__sign_challenge_path, json=challenge) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() def verify_challenge(self, signed_challenge: dict): request = requests.post(self.__verify_challenge_path, json=signed_challenge) return request.status_code, request.json() def verify_cert(self, cert: dict): request = requests.post(self.__verify_certs_path, json=cert) return request.status_code, request.json() def sign_cert(self, authid: str, cert: dict): request = requests.post(self.__sign_cert_path, params={"id": authid}, json=cert) if request.status_code == 200: self.add_request_listener(request.json()["requestID"]) return request.status_code, request.json() def add_request_listener(self, request_id: str): listener = RequestListener(request_id, self.__requests_url, self.__request_callback) listener.start()
OnePair/authid-agent-client-py
authid_agent_client/authid_agent_client.py
authid_agent_client.py
py
4,618
python
en
code
0
github-code
6
24416682335
import tests.links.cloudify_nagios_snmp_trap_handler as snmp_trap_handler from tests.fakes import FakeLogger def test_check_name(): logger = FakeLogger() target_type = 'target' trap_value = 'trap' expected = '{target_type}_instances:SNMPTRAP {trap}'.format( target_type=target_type, trap=trap_value, ) result = snmp_trap_handler.get_check_name(target_type, trap_value, logger) assert result == expected assert logger.string_appears_in('debug', ('check name', 'is', expected.lower()))
cloudify-cosmo/cloudify-managed-nagios-plugin
tests/snmp_trap_handler/test_get_check_name.py
test_get_check_name.py
py
574
python
en
code
0
github-code
6
20040254087
string = 'I am not sure this will even work' def rep_chars(string): rstr = [] lower = string.lower() for char in lower: if char.isspace(): continue elif rstr.count(char * lower.count(char)): continue elif lower.count(char) > 1: count = lower.count(char) rstr.append(char * count) return rstr print(rep_chars(string)) # given option def rep_chars(string): lower_str = string.lower() letters_seen = [] result = [] for char in lower_str: char_count = lower_str.count(char) if char_count > 1 and not char.isspace() and char not in letters_seen: result.append(char*char_count) letters_seen.append(char) return result
mwboiss/DSI-Prep
intro_py/string_count.py
string_count.py
py
746
python
en
code
0
github-code
6
23121624875
from flask import render_template, flash from app.giturl_class.url_form import UrlForm from app.giturl_class import bp import json @bp.route('/index', methods = ['GET', 'POST']) def urlPage(): form = UrlForm() citation = None installation = None invocation = None description = None if form.validate_on_submit(): flash("Classifying data") with open('data/output.json') as json_file: data = json.load(json_file) citation = data['citation.sk'] installation = data['installation.sk'] invocation = data['invocation.sk'] description = data['description.sk'] return render_template('giturl_class/giturl.html', form = form, citation = citation, installation = installation, invocation = invocation, description = description) @bp.route('/about', methods = ['GET']) def aboutPage(): return render_template('aboutpage/aboutpage.html') @bp.route('/help', methods = ['GET']) def helpPage(): return render_template('helppage/helppage.html')
quiteaniceguy/SM2KG-WebApp
app/giturl_class/routes.py
routes.py
py
1,182
python
en
code
0
github-code
6
34553013793
# coding:utf8 from numpy import * from loadnews import * ''' Description:分析新闻数据主成分特征 Author:伏草惟存 Prompt: code in Python3 env ''' '''分析数据''' def analyse_data(dataMat,topNfeat = 20): # 去除平均值 meanVals = mean(dataMat, axis=0) meanRemoved = dataMat-meanVals # 计算协方差矩阵 covMat = cov(meanRemoved, rowvar=0) # 特征值和特征向量 eigvals, eigVects = linalg.eig(mat(covMat)) eigValInd = argsort(eigvals) # 保留前N个特征 eigValInd = eigValInd[:-(topNfeat+1):-1] # 对特征主成分分析 cov_all_score = float(sum(eigvals)) sum_cov_score = 0 for i in range(0, len(eigValInd)): line_cov_score = float(eigvals[eigValInd[i]]) sum_cov_score += line_cov_score ''' 我们发现其中有超过20%的特征值都是0。 这就意味着这些特征都是其他特征的副本,也就是说,它们可以通过其他特征来表示,而本身并没有提供额外的信息。 最前面15个值的数量级大于10^5,实际上那以后的值都变得非常小。 这就相当于告诉我们只有部分重要特征,重要特征的数目也很快就会下降。 最后,我们可能会注意到有一些小的负值,他们主要源自数值误差应该四舍五入成0. ''' print('主成分:%s, 方差占比:%s%%, 累积方差占比:%s%%' % (format(i+1, '2.0f'), format(line_cov_score/cov_all_score*100, '4.2f'), format(sum_cov_score/cov_all_score*100, '4.1f'))) if __name__ == "__main__": # 加载新闻数据 dataMat = replaceNanWithMean() # print(shape(dataMat)) # 分析数据:要求满足99%即可 line_cov_score=analyse_data(dataMat,20)
bainingchao/PyDataPreprocessing
Chapter9/analyse.py
analyse.py
py
1,828
python
zh
code
157
github-code
6
30763963293
# Permanently saving data import pickle class Person(): def __init__(self, name, gender, age): self.name = name self.gender = gender self.age = age print('You have crated a new person named: ', self.name) def __str__(self): # Formating the message return '{} {} {}'.format(self.name, self.gender, self.age) class PeopleList(): people = [] def __init__(self): peopleListF = open('PeopleList', 'ab+') # ab+ adding binary inf peopleListF.seek(0) try: self.people = pickle.load(peopleListF) print('{} people loaded from the external file'.format(len(self.people))) except: print('Empty file') finally: peopleListF.close() del(peopleListF) def addPers(self, p): self.people.append(p) self.saveData() def showList(self): for p in self.people: print(p) def saveData(self): peopleListF = open('PeopleList', 'wb') pickle.dump(self.people, peopleListF) peopleListF.close() del(peopleListF) def retrData(self): print('Data on file: ') for p in self.people: print(p) peopleList = PeopleList() person1 = Person('Gio', 'Male', '26') peopleList.addPers(person1) person2 = Person('Andres', 'Male', '26') peopleList.addPers(person2) peopleList.retrData()
Giorc93/PythonCourse
ExternalFiles/TextFiles/SavingData/savingData.py
savingData.py
py
1,432
python
en
code
1
github-code
6
19065408732
from confluent_kafka import Consumer import redis import time from datetime import datetime ################ r = redis.Redis(host='localhost', port=6379) c=Consumer({'bootstrap.servers':'localhost:9092','group.id':'python-consumer','auto.offset.reset':'earliest'}) print('Available topics to consume: ', c.list_topics().topics) c.subscribe(['Tragos']) ################ def main(): i = 0 while True: msg=c.poll(1.0) #timeout dt = datetime.now() time_p = datetime.timestamp(dt) if msg is None: continue if msg.error(): print('Error: {}'.format(msg.error())) continue data=msg.value().decode('utf-8') print(data) r.set(i,data) i+=1 print("tiempo mensaje: ",time_p); c.close() if __name__ == '__main__': main()
Failedvixo/SD-Tarea2
kafka_consumer.py
kafka_consumer.py
py
857
python
en
code
0
github-code
6
21416490365
# #!/usr/bin/env python # #coding:utf-8 from random import randint from BaseAI import BaseAI from Common import * #from ComputerAI import ComputerAI class PlayerAI(BaseAI): def getMove(self, grid, weight): # I'm too naive, please change me! depth = 0 cells = grid.getAvailableCells() limit = 3 bestmove = (None, 0) while depth < limit: #print "depth is "+str(depth) alpha = self.maxmove(depth,(None, -1), (None, sys.maxint), grid, weight) if alpha[0] == None: break; if bestmove[1] < alpha[1]: bestmove = alpha # if depth == 1 and grid.getMaxTile() < 128: # break; depth = depth + 1 return bestmove[0] # moves = grid.getAvailableMoves() # return moves[randint(0, len(moves) - 1)] if moves else None def maxmove(self, depth, alpha, beta, grid, weight): #print "max move with alpha "+str(alpha)+" beta "+str(beta) +" depth "+str(depth) moves = grid.getAvailableMoves() bestmove = None for move in moves: if move!= None and grid.canMove([move]): grid_clone = grid.clone() grid_clone.move(move) if depth == 0: return (move,score(grid_clone)) next = self.minmove(depth-1, alpha, beta, grid_clone, weight) if next[1] > alpha[1]: bestmove = move alpha = (bestmove, next[1]) if alpha[1] >= beta[1]: return beta return (bestmove, alpha[1]) def minmove(self, depth, alpha, beta, grid, weight): cells = grid.getAvailableCells() minimum = sys.maxint scores = [] finalcells = [] for cell in cells: grid.setCellValue(cell, 2) temp1 = score(grid) grid.setCellValue(cell, 0) scores.append((2, temp1, cell)) #print "the branching factor in minmove is " + str(len(finalcells)) for move in scores: grid_clone = grid.clone() grid_clone.setCellValue(move[2], move[0]) next = self.maxmove(depth, alpha, beta, grid_clone, weight) if next[1] < beta[1]: beta = (alpha[0], next[1]) if beta[1]<=alpha[1]: return alpha return beta
Staniel/AI2048
PlayerAI.py
PlayerAI.py
py
1,971
python
en
code
1
github-code
6
2115336751
# Affine Cipher # With ASCII Table # suhaarslan import sys keys = (15,21) def encrypt(chr): global keys formula = lambda a,b,c,m:(a*(c-m)+b)%26+m if chr < 97: return formula(keys[0],keys[1],chr,65) elif chr > 90: return formula(keys[0],keys[1],chr,97) def decrypt(chr): global keys z = 0 formula = lambda z,y,b,m: z*((y-m)-b)%26+m # a^-1 while (keys[0]*z)%26 != 1: z=z+1 if chr < 97: return formula(z, chr, keys[1], 65) elif chr > 90: return formula(z, chr, keys[1], 97) x = 2 while x < len(sys.argv): if sys.argv[1] == 'e': for i in sys.argv[x]: if ord(i) in [i for i in range(97, 123)] or ord(i) in [i for i in range(65, 91)]: print(chr(encrypt(ord(i))), end='') elif sys.argv[1] == 'd': for i in sys.argv[x]: if ord(i) in [i for i in range(97, 123)] or ord(i) in [i for i in range(65, 91)]: print(chr(decrypt(ord(i))), end='') x=x+1
programmer-666/Cryptography
Symetric/Affine.py
Affine.py
py
1,006
python
en
code
0
github-code
6
19990844115
from django.conf.urls import url from . import views, verifycode urlpatterns = [ url(r'^$', views.index), # 生成验证码 url(r'^verifycode/$', verifycode.Verifycode), # 输入验证码试验 url(r'^verifycodeinput/$', views.verifycodeinput), url(r'^verifycodecheck/$', views.checkcode), # 反向解析(针对的是超链接,千万别弄错) # 成功的 # url(r'^$', views.student), # url(r'^return/(\d+)/$', views.retu, name='return'), # 一开始不成功,上面成功后就成功 url(r'^student/$', views.student), url(r'^student/return/(\d+)/$', views.retu, name='return'), # 模板继承 url(r"^main/$", views.main), ]
Evanavevan/Django_Project
Project3/myApp/urls.py
urls.py
py
700
python
en
code
0
github-code
6
14242354466
#基类,将原生的方法都封装一遍,让继承的类去调用 import csv import logging import os from time import sleep, strftime from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from baseView.desired_caps import appium_desired class BaseView(object): def __init__(self,driver): #初始化方法 self.driver = driver def find_element(self,*loc): #传入可变参数,元素定位的方法 return self.driver.find_element(*loc) def find_elements(self,*loc): #传入可变参数,元素定位的方法 return self.driver.find_element(*loc) def get_window_size(self): #获取屏幕大小的方法 return self.driver.get_window_size() def swipe(self,start_x, start_y, end_x, end_y, duration=None): #滑动屏幕的方法 return self.driver.swipe(start_x, start_y, end_x, end_y, duration=None) # 获取屏幕大小方法 def get_size(self): x = self.get_window_size()['width'] y = self.get_window_size()['height'] return x, y loginBtn = (By.ID, 'com.chan.iamabuyer:id/btn_login') # 登录按钮元素 jurBtn = (By.ID, 'com.android.packageinstaller:id/permission_allow_button') # 获取权限按钮元素 #定义一个根据坐标相对定位点击相册照片的方法 def photoSalbum(self): logging.info('调用photosalbum,进行屏幕相对定位点击') l = self.get_size() self.driver.tap([((l[0] * 0.5), (l[1] * 0.14))], 500) sleep(2) self.driver.tap([((l[0] * 0.1), (l[1] * 0.14))], 500) # 从引导页右往左滑动方法 # @classmethod def swipeLeft(self): logging.info('调用swipeLeft滑动引导页') l = self.get_size() # 调用方法获取屏幕大小 x1 = int(l[0] * 0.9) # x1点在最右边 x2 = int(l[0] * 0.1) # x2点在最左边 y1 = int(l[1] * 0.5) # Y1点 self.swipe(x1, y1, x2, y1, 1000) # 从右边划向最左边,y轴不变,持续1秒(1000毫秒) #删除滑动 def addressLeft(self): logging.info('调用addressLeft滑动地址管理') l = self.get_size() # 调用方法获取屏幕大小 x1 = l[0] * 0.7 # x1点在最右边 x2 = l[0] * 0.4 # x2点在最左边 y1 = l[1] * 0.12 # Y1点 self.swipe(x1, y1, x2, y1, 1000) # 从右边划向最左边,y轴不变,持续1秒(1000毫秒) # 定义一个接受当前时间的方法,用来做命名 def getTime(self): # 接收以时间元组,并返回以可读字符串表示的当地时间 self.now = strftime("%Y-%m-%d %H_%M_%S") return self.now # 定义截屏的方法,已传过来的module参数加上日期命名 def getScreenShot(self, module): time = self.getTime() image_file = os.path.dirname(os.path.dirname(__file__)) + '/screenshots/%s_%s.png' % (module, time) logging.info('获取 %s 截图' % module) # get_screenshot_as_file(image_file)是webdriver中的截图方法 self.driver.get_screenshot_as_file(image_file) # 拿account.csv的账户密码 def get_csv_data(self, csv_file, line): # 传过来的是文件地址和账户位置 #logging.info('调用csv文件') with open(csv_file, 'r', encoding='utf-8-sig') as file: reader = csv.reader(file) # 前面的reader是自定义变量,后面的是方法,读取问文件 for i, row in enumerate(reader, 1): # 1为设置初始下标为1 if i == line: return row # 返回找到的位置的账号密码内容 # 定义一个方法,启动页面获取权限,如果没有找到元素就报异常打印没有获取到元素,否则进行点击上 def check_jurisdiction(self): # 因为有写手机打开会有3秒的广告停留,有些手机时间长一点没有写手机时间短一点,所以设置一个隐式等待,在5秒时间内不断扫描元素,全局。 self.driver.implicitly_wait(5) try: # self.driver.implicitly_wait(5) self.driver.find_element(*self.loginBtn) # 登录按钮元素 except NoSuchElementException: try: logging.info("第一次启动app") # 获取权限按钮元素 ok = self.driver.find_element(*self.jurBtn) except NoSuchElementException: # sleep(3) 3秒广告 logging.info("无需手动获取权限,直接滑动引导页") for i in range(0, 3): self.swipeLeft() logging.info('第%d次调用向左滑动', i) # sleep(0.5) else: for i in range(0, 2): ok.click() sleep(0.5) # 第一次启动引导页 # sleep(3) # 3秒广告 for i in range(0, 3): self.swipeLeft() logging.info('第%d次调用向左滑动', i) sleep(0.5) else: logging.info("获取到登录按钮元素,不是第一次启动") # 浏览器前进操作 if __name__=='__main__': driver=appium_desired() ba = BaseView(driver) ba.check_jurisdiction() #然后调用Commom类中的方法 #file = '../data/account.csv' #ba.get_csv_data(file,1)
XiaoChang97/maishou_testProject
baseView/baseView.py
baseView.py
py
5,558
python
zh
code
0
github-code
6
19492440920
# -*- coding: utf-8 -*- from flask import Flask,request,abort # 引用flask库 import os import time import sys, getopt from dd.mylog import TNLog import dd logger = TNLog() print(__name__) app= Flask(__name__) app.config.update(DEBUG=True) # 定义路由 @app.route('/') def hello_world(): out = os.popen('docker info').read() return out @app.route('/docker/Info') def getDockerInfo(): out = os.popen('docker info').read() return out @app.route('/docker/deploy',methods=['POST']) def deploy(): if request.method == 'POST': image_name = request.form['image_name'] run_name = request.form['run_name'] port = request.form['port'] other = request.form['other'] loginfo = '' cmd = 'docker pull %s'%(image_name) os.popen(cmd) loginfo+=cmd+'\n' cmd = 'docker stop %s'%(run_name) loginfo+=cmd+'\n' print(os.popen(cmd).read()) cmd = 'docker rm %s'%(run_name) loginfo+=cmd+'\n' print(os.popen(cmd).read()) cmd = 'docker run -d --restart=always --name=%s -p %s %s %s'%(run_name,port,other,image_name) print(os.popen(cmd).read()) loginfo+=cmd+'\n' logger.info(loginfo) cmd = "docker ps |grep '%s'"%(run_name) ret = os.popen(cmd).read() print(ret) if ret == '': return '0' else: return '1' @app.route('/docker/login',methods=['POST']) def dockerLogin(): if request.method == 'POST': user = request.form['u'] pwd = request.form['p'] host = request.form['host'] outs = os.popen('docker login -u %s -p %s %s' %(user,pwd,host)).readlines() is_successful = False for l in outs: print(l) if l.startswith('Login Succeeded'): is_successful=True return '1' if not is_successful: return '0' def getPort(): usage = ''' usage: python3 -m dd [-v | -h | -p <port>] ddService [-v | -h | -p <port>] ''' port = 8866 argv = sys.argv[1:] try: opts, argvs = getopt.getopt(argv,"p:hv",["port=","help","version"]) except getopt.GetoptError: print("parameter format error") print(usage) sys.exit(2) for opt, arg in opts: if opt == '-h': print(usage) sys.exit() elif opt in ("-p", "--port"): port = arg elif opt == '-v': print(dd.__version__) sys.exit() return port def main(): app.run(host='0.0.0.0',port=getPort(),threaded=True,debug=False) # 开启调试模式,程序访问端口为8080 if __name__=="__main__": #main() if(not os.path.exists('log')): os.mkdir('log') #logger.info("info") app.run(host='0.0.0.0',debug=True,port=getPort(),threaded=True) # 开启调试模式,程序访问端口为8080 #http_server = WSGIServer(('', 5001), app) #http_server.serve_forever()
stosc/dockerDeployer
dd/run.py
run.py
py
3,114
python
en
code
0
github-code
6
24998585781
import wizard import pooler import datetime import time from copy import deepcopy import netsvc from tools.translate import _ _schedule_form = '''<?xml version="1.0"?> <form string="Interview Scheduling Of Candidate"> <field name="start_interview"/> <field name="end_interview"/> <field name="interval_time"/> </form>''' _schedule_fields = { 'start_interview' : {'string' : 'Start Interview Time', 'type' : 'datetime','required':True }, 'end_interview' : {'string' : 'End Interview Time', 'type' : 'datetime','required':True }, 'interval_time' : {'string' : 'Interval(Approximate Evaluation Time) ', 'type' : 'integer','required':True }, } form = """<?xml version="1.0"?> <form string="Use Model"> <separator string="Scheduled Candidate List " colspan="4"/> <field name="list_all" nolabel="1"/> <separator string="Some Candidate Still Remaining " colspan="4"/> <field name="list" nolabel="1"/> </form> """ fields = { 'list' : {'string': "",'type':'text','readonly':True}, 'list_all' : {'string': "",'type':'text','readonly':True} } class wiz_schedule(wizard.interface): def _scheduling(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) hr_int_obj = pool.get("hr.interview") if time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S") < time.strptime(data['form']['end_interview'],"%Y-%m-%d %H:%M:%S") and time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S")[:3] ==time.strptime(str(data['form']['end_interview']),"%Y-%m-%d %H:%M:%S")[:3] : if datetime.datetime(*time.strptime(str(data['form']['end_interview']),"%Y-%m-%d %H:%M:%S")[:6]) >= datetime.datetime(*time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time'])): cur_time = data['form']['start_interview'] re_id = deepcopy(data['ids']) list_all="Interview ID \t Name " for rec in data['ids']: wf_service = netsvc.LocalService('workflow') wf_service.trg_validate(uid, 'hr.interview', rec, 'state_scheduled', cr) record = hr_int_obj.read(cr,uid,rec,['hr_id','name']) list_all +="\n" + record['hr_id']+"\t\t" + record['name'] id = hr_int_obj.write(cr,uid,rec,{'date':cur_time,'state':'scheduled'}) cur_time = datetime.datetime(*time.strptime(str(cur_time),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time'])) re_id.remove(rec) end_time = datetime.datetime(*time.strptime(str(cur_time),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time'])) if len(re_id) > 0 and time.strptime(str(end_time),"%Y-%m-%d %H:%M:%S") > time.strptime(data['form']['end_interview'],"%Y-%m-%d %H:%M:%S") : remain="Interview ID \t Name " for record in hr_int_obj.read(cr,uid,re_id,['hr_id','name']): remain +="\n" + record['hr_id']+"\t\t" + record['name'] data['form']['list']=remain data['form']['list_all']=list_all return data['form'] else : raise wizard.except_wizard(_('UserError'),_('Insert appropriate interval time!!!')) return {} else : raise wizard.except_wizard(_('UserError'),_('The Scheduling is not Appropriate. Enter appropriate date and time ')) return {} data['form']['list_all']= list_all data['form']['list']= "None" return data['form'] states = { 'init': { 'actions': [], 'result': {'type': 'form', 'arch':_schedule_form, 'fields':_schedule_fields, 'state':[('schedule','Schedule','gtk-ok'),('end','Cancel','gtk-cancel')]} }, 'schedule': { 'actions': [_scheduling], 'result': {'type': 'form','arch':form, 'fields':fields, 'state':[('end','Ok')]} }, } wiz_schedule('wiz_interview_scheduling') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
factorlibre/openerp-extra-6.1
hr_interview/wizard/wiz_schedule.py
wiz_schedule.py
py
4,374
python
en
code
9
github-code
6
30133946462
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' game_images = [rock, paper, scissors] user = int(input("what do you choose? type 0 for rock, 1 for paper or 2 for scissors. \n")) if user >=3 or user < 0: print("you have enter a invalid choice!! You lose") else: print(game_images[user]) computer = random.randint(0,2) print("Computer choice: ") print(game_images[computer]) if (user == 0 and computer == 2) or (user == 2 and computer == 1) or (user == 1 and computer == 0): print("You won!!") elif (computer == 0 and user == 2) or (computer == 2 and user == 1) or (computer == 1 and user == 0): print("You lose") else: print("It's a draw")
Divjot-kaur/python
rock_paper_scissors.py
rock_paper_scissors.py
py
969
python
en
code
0
github-code
6
42649131070
""" some tools """ import logging import re import sys from rancon import settings tag_matcher = re.compile("%([A-Z0-9]+)%") def fail(message): """ logs message before calling sys.exit XXX: why is this using print not log? """ if isinstance(message, list) or isinstance(message, tuple): if len(message) > 1: message = "\n - " + "\n - ".join(message) else: message = " " + message[0] else: message = " " + message print("FATAL:%s" % message) sys.exit(-1) def is_true(something): """ checks if something is truthy. for strings this is supposed to be one (lowercased) of "true", "1", "yes", "on" """ if isinstance(something, str): return something.lower() in ("true", "1", "yes", "on") else: return bool(something) def tag_replace(line, replacement_dict, default="UNDEFINED"): """ Replaces a tag content with replacement information from the given replacement hash. The replacement must exist. :param line: The tag value :param replacement_dict: The hash to use for the replacements :return: The processed string """ tags = tag_matcher.findall(line) for tag in tags: replacement = str(replacement_dict.get(tag.lower(), default)) line = line.replace("%{}%".format(tag), replacement) return line def getLogger(*args, **kwargs): """ returns a logger XXX: why not define this in settings? """ logger = logging.getLogger(*args, **kwargs) logger.setLevel(settings.loglevel) return logger
flypenguin/python-rancon
rancon/tools.py
tools.py
py
1,596
python
en
code
0
github-code
6
37108029587
"""2 question 6 sprint""" import json import logging logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') def parse_user(output_file, *input_files): def get_name(dct): if "name" in dct and dct["name"] not in list(map(lambda x: x["name"], users_list)): users_list.append(dct) with open(output_file, "w") as res_file: users_list = [] for file in input_files: try: with open(file, 'r') as f: json.load(f, object_hook=get_name) except FileNotFoundError: logging.error(f"File {file} doesn't exist") json.dump(users_list, res_file, indent=4) if __name__ == '__main__': parse_user("user3.json", "user1.json", "user2.json")
Misha86/python-online-marathon
6_sprint/6_2question.py
6_2question.py
py
803
python
en
code
0
github-code
6
10696495998
# -*- coding: utf-8 -*- import os import uuid import json import requests import re from datetime import datetime import urllib import hmac import base64 from threading import Timer REQUEST_URL = 'https://alidns.aliyuncs.com/' LOCAL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ip.txt') ALIYUN_SETTINGS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'settings.json') def get_common_params(settings): """ 获取公共参数 参考文档:https://help.aliyun.com/document_detail/29745.html?spm=5176.doc29776.6.588.sYhLJ0 """ return { 'Format': 'json', 'Version': '2015-01-09', 'AccessKeyId': settings['access_key'], 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'SignatureVersion': '1.0', 'SignatureNonce': uuid.uuid4() } def get_signed_params(http_method, params, settings): """ 参考文档:https://help.aliyun.com/document_detail/29747.html?spm=5176.doc29745.2.1.V2tmbU """ # 1、合并参数,不包括Signature params.update(get_common_params(settings)) # 2、按照参数的字典顺序排序 sorted_params = sorted(params.items()) # 3、encode 参数 query_params = urllib.parse.urlencode(sorted_params) # 4、构造需要签名的字符串 str_to_sign = http_method + "&" + urllib.parse.quote_plus("/") + "&" + urllib.parse.quote_plus(query_params) # 5、计算签名 signature = base64.b64encode(hmac.new((settings['access_secret']+'&').encode('utf-8'), str_to_sign.encode('utf-8'), digestmod='sha1').digest()) # 6、将签名加入参数中 params['Signature'] = signature return params def update_yun(ip): """ 修改云解析 参考文档: 获取解析记录:https://help.aliyun.com/document_detail/29776.html?spm=5176.doc29774.6.618.fkB0qE 修改解析记录:https://help.aliyun.com/document_detail/29774.html?spm=5176.doc29774.6.616.qFehCg """ with open(ALIYUN_SETTINGS, 'r') as f: settings = json.loads(f.read()) # 首先获取解析列表 get_params = get_signed_params('GET', { 'Action': 'DescribeDomainRecords', 'DomainName': settings['domain'], 'TypeKeyWord': 'A' }, settings) get_resp = requests.get(REQUEST_URL, get_params) records = get_resp.json() print('get_records============') print(records) for record in records['DomainRecords']['Record']: post_params = get_signed_params('POST', { 'Action': 'UpdateDomainRecord', 'RecordId': record['RecordId'], 'RR': record['RR'], 'Type': record['Type'], 'Value': ip }, settings) post_resp = requests.post(REQUEST_URL, post_params) result = post_resp.json() print('update_record============') print(result) def get_curr_ip(): headers = { 'content-type': 'text/html', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0' } resp = requests.get('http://2018.ip138.com/ic.asp', headers=headers) ip = re.split(r"[\[\]]", resp.text)[1] return ip def get_lastest_local_ip(): """ 获取最近一次保存在本地的ip """ print('ip local path', LOCAL_FILE) with open(LOCAL_FILE, 'r') as f: last_ip = f.readline() return last_ip def task_update(): ip = get_curr_ip() if not ip: print('get ip failed') else: last_ip = get_lastest_local_ip() print('curr_ip:', ip, ' last_ip:', last_ip) if ip != last_ip: print('save ip to {}...'.format(LOCAL_FILE)) with open(LOCAL_FILE, 'w') as f: f.write(ip) print('update remote record...') update_yun(ip) Timer(300, task_update).start() if __name__ == '__main__': print('启动ddns服务,每5分钟执行一次...') Timer(0, task_update).start()
mikuh/aliyun_ddns
ddns.py
ddns.py
py
4,069
python
en
code
0
github-code
6
910975330
import sys, argparse, os, numpy as np from horton import __version__, IOData # All, except underflows, is *not* fine. np.seterr(divide='raise', over='raise', invalid='raise') def parse_args(): parser = argparse.ArgumentParser(prog='horton-convert.py', description='Convert between file formats supported in HORTON. This ' 'only works of the input contains sufficient data for the ' 'output') parser.add_argument('-V', '--version', action='version', version="%%(prog)s (HORTON version %s)" % __version__) parser.add_argument('input', help='The input file. Supported file types are: ' '*.h5 (HORTON\'s native format), ' '*.cif (Crystallographic Information File), ' '*.cp2k.out (Output from a CP2K atom computation), ' '*.cube (Gaussian cube file), ' '*.log (Gaussian log file), ' '*.fchk (Gaussian formatted checkpoint file), ' '*.molden.input (Molden wavefunction file), ' '*.mkl (Molekel wavefunction file), ' '*.wfn (Gaussian/GAMESS wavefunction file), ' 'CHGCAR, LOCPOT or POSCAR (VASP files), ' '*.xyz (The XYZ format).') parser.add_argument('output', help='The output file. Supported file types are: ' '*.h5 (HORTON\'s native format), ' '*.cif (Crystallographic Information File), ' '*.cube (Gaussian cube file), ' '*.molden.input (Molden wavefunction file), ' 'POSCAR (VASP files), ' '*.xyz (The XYZ format).') return parser.parse_args() def main(): args = parse_args() mol = IOData.from_file(args.input) mol.to_file(args.output) if __name__ == '__main__': main()
theochem/horton
scripts/horton-convert.py
horton-convert.py
py
1,810
python
en
code
83
github-code
6
36411448777
#import logging; logging.basicConfig(level=logging.INFO) import asyncio, os, json, time, base64 from datetime import datetime from aiohttp import web from jinja2 import Environment, FileSystemLoader from log import Log,create_logger import config as conf import common.orm as orm from common.webmiddlewares import logger_factory, data_factory,response_factory,auth_factory from common.coroweb import add_routes, add_static from cryptography import fernet def init_jinja2(app, **kw): Log.info('init jinja2...') options = dict( autoescape = kw.get('autoescape', True), block_start_string = kw.get('block_start_string', '{%'), block_end_string = kw.get('block_end_string', '%}'), variable_start_string = kw.get('variable_start_string', '{{'), variable_end_string = kw.get('variable_end_string', '}}'), auto_reload = kw.get('auto_reload', True) ) path = kw.get('path', None) if path is None: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') Log.info('set jinja2 template path: %s' % path) env = Environment(loader=FileSystemLoader(path), **options) filters = kw.get('filters', None) if filters is not None: for name, f in filters.items(): env.filters[name] = f app['__templating__'] = env def datetime_filter(t): delta = int(time.time() - t) if delta < 60: return u'1分钟前' if delta < 3600: return u'%s分钟前' % (delta // 60) if delta < 86400: return u'%s小时前' % (delta // 3600) if delta < 604800: return u'%s天前' % (delta // 86400) dt = datetime.fromtimestamp(t) return u'%s年%s月%s日' % (dt.year, dt.month, dt.day) def index(request): return web.Response(body=b'<h1>Hello</h1>',headers={'content-type':'text/html'}) @asyncio.coroutine async def init(loop): try: create_logger() Log.info("server init...") db = conf.configs['db']; Log.info("init configs...") fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) await orm.create_pool(loop=loop, host=db['host'], port=db['port'], user=db['user'], password=db['password'], db= db['database']) app = web.Application(loop=loop, middlewares=[ logger_factory, data_factory, auth_factory, response_factory, ]) init_jinja2(app, filters=dict(datetime=datetime_filter)) add_routes(app, 'routers') add_static(app) url = 'localhost' port = 8050 srv = await loop.create_server(app.make_handler(),url, port) Log.info("server started at http://"+url+":"+ str(port)) return srv except Exception as ex: print('服务启动失败') print(ex) #app = web.Application(loop=loop) #app.router.add_route('GET', '/', index) #srv = yield from loop.create_server(app.make_handler(), url, port) #logging.info("server started at http://"+url+":"+ str(port)) #return srv loop = asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()
jkilili/python_web
www/app.py
app.py
py
3,208
python
en
code
0
github-code
6
20572139596
from ._base import _rule from .field import Field from .operators.operator import Operator class Expr(Field, Operator): reserved = {**Field.reserved, **Operator.reserved} tokens = Field.tokens + Operator.tokens precedence = Field.precedence + Operator.precedence # rules _start = 'expr' @_rule('''expr : expr EQ expr | expr NE expr | expr NN expr | expr LE expr | expr LS expr | expr GE expr | expr GT expr | expr IS expr | expr LIKE expr | expr ILIKE expr | expr DPIPE expr | expr MINUS expr | expr PLUS expr | expr MULTI expr | expr DIVIDE expr | expr MODULAR expr''') def p_expr(self, p): p[0] = self.provider.new_biop(p[2].upper(), p[1], p[3]) @_rule('expr : expr IS NOT expr') def p_expr2(self, p): p[0] = self.provider.new_biop('IS NOT', p[1], p[4]) @_rule('expr : expr IS DISTINCT FROM expr') def p_expr3(self, p): p[0] = self.provider.new_biop('IS DISTINCT FROM', p[1], p[5]) @_rule('expr : expr IS NOT DISTINCT FROM expr') def p_expr4(self, p): p[0] = self.provider.new_biop('IS NOT DISTINCT FROM', p[1], p[6]) @_rule('expr : expr IN LPAREN exprs RPAREN') def p_expr5(self, p): p[0] = self.provider.new_biop('IN', p[1], p[4]) @_rule('expr : expr NOT IN LPAREN exprs RPAREN') def p_expr6(self, p): p[0] = self.provider.new_biop('NOT IN', p[1], p[5]) @_rule('exprs : expr') def p_exprs_expr(self, p): p[0] = self.provider.new_fieldlist(p[1]) @_rule('exprs : exprs COMMA expr') def p_exprs_comma_expr(self, p): p[0] = p[1].append(p[3]) @_rule('expr : field') def p_expr_field(self, p): p[0] = p[1]
bluerelay/windyquery
windyquery/validator/expr.py
expr.py
py
1,965
python
en
code
68
github-code
6
23307657200
from __future__ import print_function try: # For Python 3.0 and later from urllib.request import urlopen from urllib.request import urlretrieve from urllib import request except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen from urllib import urlretrieve import sys import numpy as np import matplotlib.pyplot as plt import pylab from matplotlib.ticker import MaxNLocator import argparse import os import astropy.wcs from astropy.io import fits from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astroquery.gaia import Gaia from astropy.wcs import WCS from astropy.visualization.wcsaxes import SphericalCircle from scipy.ndimage.filters import gaussian_filter import warnings warnings.filterwarnings("ignore") def deg2hour(ra, dec, sep=":"): ''' Transforms the coordinates in degrees into HH:MM:SS DD:MM:SS with the requested separator. ''' if ( type(ra) is str and type(dec) is str ): return ra, dec c = SkyCoord(ra, dec, frame='icrs', unit='deg') ra = c.ra.to_string(unit=u.hourangle, sep=sep, precision=2, pad=True) dec = c.dec.to_string(sep=sep, precision=2, alwayssign=True, pad=True) return str(ra), str(dec) def hour2deg(ra, dec): ''' Transforms string HH:MM:SS DD:MM:SS coordinates into degrees (floats). ''' try: ra = float(ra) dec = float(dec) except: c = SkyCoord(ra, dec, frame='icrs', unit=(u.hourangle, u.deg)) ra = c.ra.deg dec = c.dec.deg return ra, dec def get_offset(ra1, dec1, ra2, dec2): ''' Computes the offset in arcsec between two coordinates. The offset is from (ra1, dec1) - generally an offset star to (ra2, dec2) - the fainter target. ''' from astropy.coordinates import SkyCoord bright_star = SkyCoord(ra1, dec1, frame='icrs', unit=(u.deg, u.deg)) target = SkyCoord(ra2, dec2, frame='icrs', unit=(u.deg, u.deg)) dra, ddec = bright_star.spherical_offsets_to(target) return dra.to(u.arcsec).value, ddec.to(u.arcsec).value def query_sky_mapper_catalogue(ra, dec, radius_deg, minmag=15, maxmag=18.5): ''' Sends a VO query to the SkyMapper catalogue. ''' url = "http://skymapper.anu.edu.au/sm-cone/query?RA=%.6f&DEC=%.6f&SR=%.4f&RESPONSEFORMAT=CSV"%(ra, dec, radius_deg) f = open("/tmp/skymapper_cat.csv", "wb") page = urlopen(url) content = page.read() f.write(content) f.close() # Read RA, Dec and magnitude from CSV catalog = Table.read("/tmp/skymapper_cat.csv", format="ascii.csv") mask = (catalog["class_star"]>0.7) * (catalog["ngood"] >5) * (catalog['r_psf']>minmag) * (catalog['r_psf']<maxmag) catalog = catalog[mask] newcat = np.zeros(len(catalog), dtype=[("ra", np.double), ("dec", np.double), ("mag", np.float)]) newcat["ra"] = catalog["raj2000"] newcat["dec"] = catalog["dej2000"] newcat["mag"] = catalog["r_psf"] return newcat def query_ps1_catalogue(ra, dec, radius_deg, minmag=15, maxmag=18.5): ''' Sends a VO query to the PS1 catalogue. Filters the result by mangitude (between 15 and 18.5) and by the PSF-like shape of the sources. ''' url = "http://gsss.stsci.edu/webservices/vo/CatalogSearch.aspx?CAT=PS1V3OBJECTS&RA=%.5f&DEC=%.5f&SR=%.5f&FORMAT=csv"%(ra, dec, radius_deg) #urllib.urlretrieve(url, "/tmp/ps1_cat.xml") f = open("/tmp/ps1_cat.csv", "wb") try: page = request.urlopen(url) except: page = urlopen(url) content = page.read() f.write(content) f.close() # Read RA, Dec and magnitude from CSV catalog = Table.read("/tmp/ps1_cat.csv", format="ascii.csv", header_start=1) mask = (catalog["nDetections"]>3) * (catalog["rMeanPSFMag"] > minmag) * (catalog["rMeanPSFMag"] < maxmag) *\ (catalog["iMeanPSFMag"] - catalog["iMeanKronMag"] < 0.1) #This last one to select stars. #*(catalog["rMeanPSFMag"] > minmag) * (catalog["rMeanPSFMag"] < maxmag) catalog = catalog[mask] newcat = np.zeros(len(catalog), dtype=[("ra", np.double), ("dec", np.double), ("mag", np.float)]) newcat["ra"] = catalog["RaMean"] newcat["dec"] = catalog["DecMean"] newcat["mag"] = catalog["rMeanPSFMag"] return newcat def query_gaia_catalogue(ra, dec, radius_deg, minmag=15, maxmag=18.5): ''' Sends a VO query to the Gaia catalogue. Filters the result by G mangitude (between minmag and maxmag). ''' query = '''SELECT ra, dec, phot_g_mean_mag FROM gaiaedr3.gaia_source WHERE 1=CONTAINS( POINT('ICRS', %.6f, %.6f), CIRCLE('ICRS',ra, dec, %.6f)) AND phot_g_mean_mag>=%.2d AND phot_g_mean_mag<%.2f'''%(ra, dec, radius_deg, minmag, maxmag) print (query) job = Gaia.launch_job_async(query) #, dump_to_file=True, output_format='votable') catalog = job.get_results() newcat = np.zeros(len(catalog), dtype=[("ra", np.double), ("dec", np.double), ("mag", np.float)]) newcat["ra"] = catalog["ra"] newcat["dec"] = catalog["dec"] newcat["mag"] = catalog["phot_g_mean_mag"] return newcat def get_fits_image(ra, dec, rad, debug=True): ''' Connects to the PS1 or SkyMapper image service to retrieve the fits file to be used as a bse for the finder chart. ''' #If dec> -30, we have Pan-STARRS if dec > -30: # Construct URL to download Pan-STARRS image cutout, and save to tmp.fits # First find the index of images and retrieve the file of the image that we want to use. image_index_url = 'http://ps1images.stsci.edu/cgi-bin/ps1filenames.py?ra={0}&dec={1}&filters=r'.format(ra, dec) urlretrieve(image_index_url, '/tmp/ps1_image_index.txt') ix = Table.read('/tmp/ps1_image_index.txt', format="ascii") f = ix['filename'].data[0] image_url = "http://ps1images.stsci.edu/cgi-bin/fitscut.cgi?red={0}&format=fits&size={1}&ra={2}&dec={3}".format(f, int(np.round(rad*3600*8, 0)), ra, dec) if (debug): print ("URL:", image_url) print ("Downloading PS1 r-band image...") #Store the object to a fits file. urlretrieve(image_url, '/tmp/tmp.fits') #Otherwise, we have SkyMapper else: url="http://skymappersiap.asvo.nci.org.au/dr1_cutout/query?POS=%.6f,%.6f&SIZE=%.3f&FORMAT=image/fits&INTERSECT=center&RESPONSEFORMAT=CSV"%(ra, dec, rad*2) page = urlopen(url) content = page.read() f = open("/tmp/skymapper_image_index.csv", "wb") f.write(content) f.close() ix = Table.read('/tmp/skymapper_image_index.csv', format="ascii.csv") mask = ((ix['band']=='r')|(ix['band']=='g')) ix = ix[mask] ix.sort(keys='exptime') image_url = ix['get_image'][-1] urlretrieve(image_url, '/tmp/tmp.fits') #Finally, once we have Pan-STARRS or SkyMapper images, we try to open them. #If there has been any problem with that, we will just go to the DSS image service. try: image = fits.open("/tmp/tmp.fits") #If everything went well, it shall be a fits image and opening it shall cause no issue. return '/tmp/tmp.fits' #If there was an error with the fits, we shall go for the DSS image except IOError: #One of the services may fail, so we need to account for that and provide a backup DSS image service. try: image_url = 'http://archive.eso.org/dss/dss/image?ra=%.5f&dec=%.5f&x=%.2f&y=%.2f&Sky-Survey=DSS1&mime-type=download-fits' % \ ((ra), (dec), (rad*60), (rad*60)) if debug: print ("Downloading DSS image...") urlretrieve(image_url, '/tmp/tmp.fits') except: image_url = 'http://archive.stsci.edu/cgi-bin/dss_search?ra=%.6f&dec=%.6f&generation=DSS2r&equinox=J2000&height=%.4f&width=%.4f&format=FITS' % \ (ra, dec, rad*60, rad*60) urlretrieve(image_url, '/tmp/tmp.fits') #We try one more time to open it. If not successful, we return None as the image filename. try: fits.open("/tmp/tmp.fits") except IOError: print ("Your fits image could not be retrieved.") return None def get_cutout(ra, dec, name, rad, debug=True): ''' Obtains the color composite cutout from the PS1 images. ''' try: ra=float(ra) dec=float(dec) except: ra, dec = hour2deg(ra, dec) catalog = query_ps1_catalogue(ra, dec, rad) if (debug): print (catalog) # Construct URL to download DSS image cutout, and save to tmp.fits image_index_url_red = 'http://ps1images.stsci.edu/cgi-bin/ps1filenames.py?ra={0}&dec={1}&filters=y'.format(ra, dec) image_index_url_green = 'http://ps1images.stsci.edu/cgi-bin/ps1filenames.py?ra={0}&dec={1}&filters=i'.format(ra, dec) image_index_url_blue = 'http://ps1images.stsci.edu/cgi-bin/ps1filenames.py?ra={0}&dec={1}&filters=g'.format(ra, dec) urlretrieve(image_index_url_red, '/tmp/image_index_red.txt') urlretrieve(image_index_url_green, '/tmp/image_index_green.txt') urlretrieve(image_index_url_blue, '/tmp/image_index_blue.txt') ix_red = np.genfromtxt('/tmp/image_index_red.txt', names=True, dtype=None) ix_green = np.genfromtxt('/tmp/image_index_green.txt', names=True, dtype=None) ix_blue = np.genfromtxt('/tmp/image_index_blue.txt', names=True, dtype=None) image_url = "http://ps1images.stsci.edu/cgi-bin/fitscut.cgi?red=%s&green=%s&blue=%s&filetypes=stack&auxiliary=data&size=%d&ra=%.6f&dec=%.6f&output_size=256"%\ (ix_red["filename"], ix_green["filename"], ix_blue["filename"], rad*3600*4, ra, dec) if (debug): print (image_url) print ("Downloading PS1 r-band image...") urlretrieve(image_url, '/tmp/tmp_%s.jpg'%name) def get_finder(ra, dec, name, rad, debug=False, starlist=None, print_starlist=True, \ telescope="P200", directory=".", minmag=15, maxmag=18.5, mag=np.nan, image_file=None): ''' Creates a PDF with the finder chart for the object with the specified name and coordinates. It queries the PS1 catalogue to obtain nearby offset stars and get an R-band image as background. Parameters ---------- ra : float RA of our target in degrees. dec : float DEC of our target in degrees. name : str The name of your target rad : float Search radius for the finder in degrees. debug : bool (optional) Option to activate/ deactivate additional output. starlist : str (optional) Path/name of the file where the coordinates for the object are going to be saved. If the file exists, the content will be appended at the end. If no value is provided, the output just writes to the standard output (in case print_starlist is True). print_starlist : boolean (optional) Indicates if the starlist shall be printed in the standard output. telescope : str (optional) The current accepted values are "Keck", "P200", "Calar". directory : str (optional) The directory where the PDF with the finder chart shall be stored. If no value given, the file will be store in the current directory where the script is run. minmag : float (optional) The minimum magnitud (brightest in this case) star that we would like to use as an offset star. maxmag : float (optional) The maximum magnitude (faintest) star that we would like to use as an offset star. mag : float or `None` (optional) The magnitude of our target. image_file : str (optional) The name of the fits file that you want to use as a background to your finder chart. If none, provided, the script will automatically look for imaging catalogues: PS1 (North), SkyMapper (South), or DSS ''' print ("Got it") try: ra=float(ra) dec=float(dec) except: ra, dec = hour2deg(ra, dec) print ('Image file:', image_file) #If no custom fits image is provided, we query for one from PS1/DSS/SkyMapper if image_file is None: image_file = get_fits_image(ra, dec, rad, debug=debug) image = fits.open(image_file) wcs = astropy.wcs.WCS(image[0].header) else: print ('Reading custom fits') image = fits.open(image_file) # Get pixel coordinates of SN, reference stars in DSS image wcs = astropy.wcs.WCS(fits.open(image_file)[0].header) try: image[0].data = np.rot90(np.rot90(image[0].data)) except ValueError: print ('Rotation failed') if image_file is None or image is None: print ("FATAL ERROR! Your FITS image could not be retrieved.") return # Plot finder chart #Adjust some of the counts to make easier the plotting. image[0].data[image[0].data>20000] = 20000 image[0].data[np.isnan(image[0].data)] = 0 plt.figure(figsize=(8, 6)) plt.set_cmap('gray_r') smoothedimage = gaussian_filter(image[0].data, 1.1) hdu = fits.open(image_file)[0] wcs = WCS(hdu.header) plt.subplot(projection=wcs) #plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower') plt.grid(color='white', ls='solid') plt.imshow(smoothedimage, origin='lower',vmin=np.percentile(smoothedimage.flatten(), 1), \ vmax=np.percentile(smoothedimage.flatten(), 99)) #Mark target in green ax = plt.gca() r = SphericalCircle((ra * u.deg, dec * u.deg), 2 * u.arcsec, edgecolor='green', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(r) #Write the name of the target plt.annotate(name, xy=(ra, dec), xycoords='data', xytext=(0.55, 0.5), textcoords='axes fraction', color="g") # Plot compass plt.plot([(image[0].data.shape[0])-10,(image[0].data.shape[0]-40)],[10,10], 'k-', lw=2) plt.plot([(image[0].data.shape[0])-10,(image[0].data.shape[0])-10],[10,40], 'k-', lw=2) plt.annotate("N", xy=((image[0].data.shape[0])-20, 40), xycoords='data', xytext=(-4,5), textcoords='offset points') plt.annotate("E", xy=((image[0].data.shape[0])-40, 20), xycoords='data', xytext=(-12,-5), textcoords='offset points') ax.set_xlabel('%.1f\''%(rad*60*2)) ax.set_ylabel('%.1f\''%(rad*60*2)) #Queries a catalogue to get the offset stars try: catalog = query_gaia_catalogue(ra, dec, rad, minmag=minmag, maxmag=maxmag) except Exception as e: print(e) catalog = [] if len(catalog)==0: try: if dec < -30: catalog = query_sky_mapper_catalogue(ra, dec, (rad)*0.95, minmag=minmag, maxmag=maxmag) else: catalog = query_ps1_catalogue(ra, dec, (rad)*0.95, minmag=minmag, maxmag=maxmag) except Exception as e: print(e) catalog = [] if (debug): print ("Catalog of %d stars retrieved"%len(catalog), catalog) #Possible ways to get more stars if we find nothing in the specified range. '''if (len(catalog)<3): if debug: print ("Looking for a bit fainter stars up to mag: %.2f"%(maxmag+0.25)) catalog = query_ps1_catalogue(ra, dec, (rad/2.)*0.95, minmag=minmag, maxmag=maxmag+0.5) if (len(catalog)<3): print ("Restarting with larger radius %.2f arcmin"%(rad*60+0.5)) get_finder(ra, dec, name, rad+0.5/60, directory=directory, minmag=minmag, \ maxmag=maxmag+0.5, mag=mag, starlist=starlist, telescope=telescope, image_file=image_file) return''' if (not catalog is None and len(catalog)>0): np.random.shuffle(catalog) no_self_object = (np.abs(catalog["ra"]-ra)*np.cos(np.deg2rad(dec))>2./3600)*(np.abs(catalog["dec"]-dec)>2./3600) catalog = catalog[no_self_object] #catalog.sort(order='mag') if (debug): print ("Once removed the object", catalog) if (len(catalog)>0): ref1_pix = wcs.wcs_world2pix(np.array([[catalog["ra"][0], catalog["dec"][0]]], np.float_), 1) if (len(catalog)>1): ref2_pix = wcs.wcs_world2pix(np.array([[catalog["ra"][1], catalog["dec"][1]]], np.float_), 1) # Mark and label reference stars #If we have 1, we mark it if (len(catalog)>0): s1ra = catalog[0]["ra"] s1dec = catalog[0]["dec"] s1= SphericalCircle(( s1ra* u.deg, s1dec* u.deg), 2 * u.arcsec, edgecolor='b', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(s1) plt.annotate("S1", xy=(ref1_pix[0][0]+3, ref1_pix[0][1]+3), xycoords='data', color="b") #IFfwe have 2, we mark them as well if (len(catalog)>1): s2ra = catalog[1]["ra"] s2dec = catalog[1]["dec"] s2= SphericalCircle(( s2ra* u.deg, s2dec* u.deg), 2 * u.arcsec, edgecolor='r', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(s2) plt.annotate("S2", xy=(ref2_pix[0][0]+3, ref2_pix[0][1]+3), xycoords='data', color="r") # Set size of window (leaving space to right for ref star coords) plt.subplots_adjust(right=0.65,left=0.1, top=0.99, bottom=0.01) #Write the starlist #If no magnitude was supplied, just do not put it on the chart. if not np.isnan(mag): target_mag = "mag=%.2f"%mag else: target_mag = "" # List name, coords, mag of references etc plt.text(1.02, 0.85, name, fontweight='bold', transform=ax.transAxes) plt.text(1.02, 0.85, name, transform=ax.transAxes, fontweight='bold') plt.text(1.02, 0.80, "%s"%target_mag, transform=ax.transAxes, fontweight='bold') plt.text(1.02, 0.75, "%.5f %.5f"%(ra, dec),transform=ax.transAxes) rah, dech = deg2hour(ra, dec) plt.text(1.02, 0.7,rah+" "+dech, transform=ax.transAxes) #Put the text for the offset stars. if (len(catalog)>0): ofR1 = get_offset(catalog["ra"][0], catalog["dec"][0], ra, dec) S1 = deg2hour(catalog["ra"][0], catalog["dec"][0], sep=":") plt.text(1.02, 0.60,'S1, mag=%.2f'%catalog["mag"][0], transform=ax.transAxes, color="b") plt.text(1.02, 0.55,'%s %s'%(S1[0], S1[1]), transform=ax.transAxes, color="b") plt.text(1.02, 0.5,"E: %.2f N: %.2f"%(ofR1[0], ofR1[1]),transform=ax.transAxes, color="b") if (len(catalog)>1): ofR2 = get_offset(catalog["ra"][1], catalog["dec"][1], ra, dec) S2 = deg2hour(catalog["ra"][1], catalog["dec"][1], sep=":") plt.text(1.02, 0.4,'RS, mag=%.2f'%catalog["mag"][1], transform=ax.transAxes, color="r") plt.text(1.02, 0.35,'%s %s'%(S2[0], S2[1]), transform=ax.transAxes, color="r") plt.text(1.02, 0.3,"E: %.2f N: %.2f"%(ofR2[0], ofR2[1]),transform=ax.transAxes, color="r") #Print starlist in the right format for each telescope if telescope == "Keck": commentchar = "#" separator = "" if telescope == "P200": commentchar = "!" separator = "!" if telescope == "Calar": commentchar = "|" separator = "|" if (len(catalog)>0 and (print_starlist or not starlist is None)): ra_h, dec_h = deg2hour(ra, dec, sep=":") print ( "%s %s %s %s %s %s %s %s %s"%("# Object".ljust(20), separator, "alpha".ljust(11), separator, "delta".ljust(12), separator, "eq".ljust(6), separator, "camp de format lliure") ) print ( "%s %s %s %s %s %s 2000.0 %s"%(name.ljust(20), separator, ra_h, separator, dec_h, separator, commentchar) ) S1 = deg2hour(catalog["ra"][0], catalog["dec"][0], sep=":") print ( "{:s} {:s} {:s} {:s} {:s} {:s} 2000.0 {:s} raoffset={:.2f} decoffset={:.2f} r={:.1f} ".format((name+"_S1").ljust(20), separator, S1[0], separator, S1[1], separator, commentchar, ofR1[0], ofR1[1], catalog["mag"][0]) ) if (len(catalog)>1 and (print_starlist or not starlist is None)): S2 = deg2hour(catalog["ra"][1], catalog["dec"][1], sep=":") print ( "{:s} {:s} {:s} {:s} {:s} {:s} 2000.0 {:s} raoffset={:.2f} decoffset={:.2f} r={:.1f} ".format((name+"_S2").ljust(20), separator, S2[0], separator, S2[1], separator, commentchar, ofR2[0], ofR2[1], catalog["mag"][1]) ) r, d = deg2hour(ra, dec, sep=" ") #Write to the starlist if the name of the starlist was provided. if (not starlist is None) and (telescope =="Keck"): with open(starlist, "a") as f: f.write( "{0} {1} {2} 2000.0 # {3} \n".format(name.ljust(17), r, d, target_mag) ) if (len(catalog)>0): f.write ( "{:s} {:s} {:s} 2000.0 raoffset={:.2f} decoffset={:.2f} r={:.1f} # \n".format( (name+"_S1").ljust(17), S1[0], S1[1], ofR1[0], ofR1[1], catalog["mag"][0])) if (len(catalog)>1): f.write ( "{:s} {:s} {:s} 2000.0 raoffset={:.2f} decoffset={:.2f} r={:.1f} # \n".format( (name+"_S2").ljust(17), S2[0], S2[1], ofR2[0], ofR2[1], catalog["mag"][1])) f.write('\n') if (not starlist is None) and (telescope =="P200"): with open(starlist, "a") as f: f.write( "{0} {1} {2} 2000.0 ! {3}\n".format(name.ljust(19), r, d, target_mag) ) if (len(catalog)>0): f.write ( "{:s} {:s} {:s} 2000.0 ! raoffset={:.2f} decoffset={:.2f} r={:.1f} \n".format( (name+"_S1").ljust(19), S1[0], S1[1], ofR1[0], ofR1[1], catalog["mag"][0])) if (len(catalog)>1): f.write ( "{:s} {:s} {:s} 2000.0 ! raoffset={:.2f} decoffset={:.2f} r={:.1f} \n".format( (name+"_S2").ljust(19), S2[0], S2[1], ofR2[0], ofR2[1], catalog["mag"][1])) f.write('\n') if (not starlist is None) and (telescope =="Calar"): with open(starlist, "a") as f: f.write( "{0} {1} {2} %s 2000.0 %s {3}\n".format(separator, separator, name.ljust(19), r, d, target_mag) ) if (len(catalog)>0): f.write ( "{:s} {:s} {:s} %s 2000.0 %s raoffset={:.2f} decoffset={:.2f} r={:.1f} \n".format( (name+"_S1").ljust(19), separator, S1[0], separator, S1[1], ofR1[0], ofR1[1], catalog["mag"][0])) if (len(catalog)>1): f.write ( "{:s} {:s} {:s} %s 2000.0 %s raoffset={:.2f} decoffset={:.2f} r={:.1f} \n".format( (name+"_S2").ljust(19), separator, S2[0], separator, S2[1], ofR2[0], ofR2[1], catalog["mag"][1])) f.write('\n') # Save to pdf pylab.savefig(os.path.join(directory, str(name+'_finder.pdf'))) if debug: print ("Saved to %s"%os.path.join(directory, str(name+'_finder.pdf'))) pylab.close("all") if __name__ == '__main__': parser = argparse.ArgumentParser(description=\ ''' Creates the finder chart for the given RA, DEC and NAME. Usage: finder.py <RA> <Dec> <Name> <rad [deg]> <telescope [P200|Keck]> ''', formatter_class=argparse.RawTextHelpFormatter) print ("Usage: finder_chart.py <RA> <Dec> <Name> <rad [deg]> <telescope [P200|Keck]>") #Check if correct number of arguments are given if len(sys.argv) < 4: print ("Not enough parameters given. Please, provide at least: finder_chart.py <RA> <Dec> <Name>") sys.exit() ra = float(sys.argv[1]) dec = float(sys.argv[2]) name = str(sys.argv[3]) if (len(sys.argv)>=5): rad = float(sys.argv[4]) if (rad > 15./60): print ('Requested search radius of %.2f arcmin is larger than 15 arcmin. Not sure why you need such a large finder chart... reducing to 10 armin for smoother operations...'%(rad * 60)) rad = 10./60 else: rad = 2./60 print ('Using search radius of %.1f arcsec.'%(rad*3600)) if (len(sys.argv)>5): telescope = sys.argv[5] else: telescope = "P200" print ('Assuming that the telescope you observe will be P200. If it is "Keck", please specify otherwise.') get_finder(ra, dec, name, rad, telescope=telescope, debug=False, minmag=7, maxmag=15)
nblago/utils
src/utils/finder_chart.py
finder_chart.py
py
24,759
python
en
code
2
github-code
6
72683668667
import sys from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QPushButton, QLabel, QHBoxLayout, QLineEdit button_y_position = 0.1 # Initial Y position for the buttons class Addsubject(QDialog): def __init__(self): super().__init__() self.setWindowTitle('Custom Pop-up Block') self.setGeometry(300, 200, 400, 200) # Create layouts for the dialog main_layout = QVBoxLayout() button_layout = QHBoxLayout() # Create labels and line edits for subject name, teacher name, and number of students subject_label = QLabel("Subject Name:") self.subject_edit = QLineEdit(self) teacher_label = QLabel("Teacher Name:") self.teacher_edit = QLineEdit(self) students_label = QLabel("Number of Students:") self.students_edit = QLineEdit(self) # Create and add a button to the button layout button1 = QPushButton("Create") button1.clicked.connect(self.on_button1_click) # Add labels, line edits, and the button to the layouts main_layout.addWidget(subject_label) main_layout.addWidget(self.subject_edit) main_layout.addWidget(teacher_label) main_layout.addWidget(self.teacher_edit) main_layout.addWidget(students_label) main_layout.addWidget(self.students_edit) button_layout.addWidget(button1) # Set the layouts for the dialog main_layout.addLayout(button_layout) self.setLayout(main_layout) def on_button1_click(self): subject_name = self.subject_edit.text() teacher_name = self.teacher_edit.text() num_students = self.students_edit.text() print(f"Subject Name: {subject_name}, Teacher Name: {teacher_name}, Students: {num_students}") self.accept() def create_class_data(self): subject_name = self.subject_edit.text() teacher_name = self.teacher_edit.text() num_students = self.students_edit.text() return subject_name , teacher_name , num_students
Rush-154/DBMS
Login/flexcards.py
flexcards.py
py
2,119
python
en
code
0
github-code
6
15191243945
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: prefix = [] prod = 1 for i in nums: prod *= i prefix.append(prod) sufix = [] prod = 1 for i in range(len(nums)-1,-1,-1): prod *= nums[i] sufix.append(prod) sufix.reverse() res = [] for i in range(len(nums)): if i == 0: res.append(sufix[i+1]) elif i == len(nums) - 1: res.append(prefix[i-1]) else: res.append(sufix[i+1]*prefix[i-1]) return res
Dumbris/leetcode
medium/238.product-of-array-except-self.py
238.product-of-array-except-self.py
py
644
python
en
code
0
github-code
6
22941445874
import re log_lines=None with open(r"C:\Users\remote_pc\Desktop\python_log2.txt",'r',encoding='utf-8') as log_txt: log_lines=log_txt.readlines() machine_policty_logs={} for line in log_lines: if 'Machine policy' in line: re_result_time=re.findall(r'\[\d+:\d+:\d+:\d+\]',line)[0].replace('[','').replace(']','') machine_policty_logs[re_result_time]=line for item in machine_policty_logs.items(): print(item) # --------------------------------------------------------------------------------------------------------- r_cbs=[] package=[] with open(r"C:\Users\remote_pc\Desktop\CBS.log",'r',encoding='utf8') as file: r_cbs.extend(file.readlines()) print(r_cbs) for line in r_cbs: if ', Package: ' in line: sp_split=line.split(', Package: ')[1].split(', ')[0] package.append(sp_split) [print(pkg) for pkg in set(package)]
sam4u3/Ignicia_Python
file_io.py
file_io.py
py
901
python
en
code
0
github-code
6
16062801257
import pygame import init from gui_config import Config from widget import Widget class Label(Widget): def __init__(self, text, x,y,width,height, config=Config.default_drawing_conf): Widget.__init__(self,x,y,width,height,config) self.__set_text(text) def init(self): Widget.init(self) self.__set_text(self.__text) def __set_text(self,text): self.__text=text config=self._config font=self.fonts.get_font(config.font_name,config.font_size) (w,h)=font.size(text) inner=self.inner_rect if w > inner.width or h > inner.height: raise Exception(u'Box too small for label "'+text+'"'+\ u'required: '+str((w,h))+u' available: '+\ str((inner.width,inner.height))) if config.label_align=='left': left=inner.x elif config.label_align=='center': left=inner.x+(inner.width-w)/2.0 else: left=inner.right-w self.pos=(left,inner.y+(inner.height-h)/2.0) self.img=font.render(text,config.font_color,config.bckg_color) self.needs_update=True @property def text(self): return self.__text @text.setter def text(self,t): if t==self.__text: return else: self.__set_text(t) # Draw thyself # Return updated rectangle if there was an update, None otherwise def update(self,surface): surface.blit(self.img,self.pos) self.needs_update=False return self.rect # Label doesn't receive input. def focus_queue(self): return [] # Label doesn't receive input. def focus(self): return def unfocus(self): return # Handle event, return True if handled # If some other widget handled it already 'handled' is True def handle(self, event, handled=False): return False if __name__ == "__main__": l1=Label(u'Label One',10,10,150,42) l1.configuration.label_align='right' l1.init() l2=Label(u'label two',10,70,150,40) l3=Label(u'label Three',10,130,150,45) l3.configuration.label_align='center' l3.init() l4=Label(u'label Four',10,190,150,50) from widgets import Widgets scr = pygame.display.set_mode((300,600)) scr.fill(Config.default_drawing_conf.bckg_color) widgets=Widgets(); widgets.add((l1,l2,l3,l4)) l4.text='LABEL FOUR' widgets.run(scr)
unusualcomputers/unusualgui
code/label.py
label.py
py
2,516
python
en
code
0
github-code
6
73822719228
import math def findMag(vector): return math.sqrt(vector[0]**2 + vector[1]**2 + vector[2]**2) def findUnit(vector): unit = [] mag = findMag(vector) if mag == 0: return [0,0,0] for a,b in enumerate(vector): unit.append(b/mag) return unit def dotProduct(vector1,vector2): dot = 0 for a,b in zip(vector1,vector2): dot += a*b return dot # Project vector1 onto vector2 def vectorDotProduct(vector1, vector2): unit = findUnit(vector2) dp = dotProduct(vector1,unit) vectordp = [] for x in unit: vectordp.append(dp*x) return vectordp def angleBetween(vector1, vector2): mag1 = findMag(vector1) mag2 = findMag(vector2) if mag1 == 0 or mag2 == 0: return 0 return math.degrees(math.acos(dotProduct(vector1,vector2)/(mag1*mag2))) def crossProduct(a,b): i = (a[1]*b[2]-a[2]*b[1]) j = -(a[0]*b[2]-a[2]*b[0]) k = (a[0]*b[1]-a[1]*b[0]) return [i,j,k] def pV(vector): direction = ["i + ","j + ","k "] s = [] for x,b in zip(vector,direction): x = format(x, '.4f') s.append(x+b) return "".join(s)
CaelumD25/Statics-Equations
ENGR141 Equations/mymath.py
mymath.py
py
1,084
python
en
code
0
github-code
6
6922603466
import os # python -m pip install --upgrade pip # python -m pip install --upgrade Pillow from PIL import Image # pip install numpy import numpy as np ####################################################################### black=[25,25,25] blue=[50,75,175] brown=[100,75,50] cyan=[75,125,151] gray=[75,75,75] green=[100,125,50] light_blue=[100,151,213] light_gray=[151,151,151] lime=[125,201,25] magenta=[175,75,213] orange=[213,125,50] pink=[238,125,162] purple=[125,62,175] red=[151,50,50] white=[251,251,251] yellow=[225,225,50] basic_colors = [black, blue, brown, cyan, gray, green, light_blue, light_gray, lime, magenta, orange, pink, purple, red, white, yellow] ####################################################################### def closest(color): """ https://stackoverflow.com/a/54244301/1106708 """ colors = np.array(basic_colors) color = np.array(color) distances = np.sqrt(np.sum((colors-color)**2,axis=1)) index_of_smallest = np.where(distances==np.amin(distances)) smallest_distance = colors[index_of_smallest] return smallest_distance[0] def concrete_art(closest_color): if (closest_color == black).all(): return "black_concrete" elif (closest_color == blue).all(): return "blue_concrete" elif (closest_color == brown).all(): return "brown_concrete" elif (closest_color == cyan).all(): return "cyan_concrete" elif (closest_color == gray).all(): return "gray_concrete" elif (closest_color == green).all(): return "green_concrete" elif (closest_color == light_blue).all(): return "light_blue_concrete" elif (closest_color == light_gray).all(): return "light_gray_concrete" elif (closest_color == lime).all(): return "lime_concrete" elif (closest_color == magenta).all(): return "magenta_concrete" elif (closest_color == orange).all(): return "orange_concrete" elif (closest_color == pink).all(): return "pink_concrete" elif (closest_color == purple).all(): return "purple_concrete" elif (closest_color == red).all(): return "red_concrete" elif (closest_color == white).all(): return "white_concrete" elif (closest_color == yellow).all(): return "yellow_concrete" def glass_art(closest_color): if (closest_color == black).all(): return "black_stained_glass" elif (closest_color == blue).all(): return "blue_stained_glass" elif (closest_color == brown).all(): return "brown_stained_glass" elif (closest_color == cyan).all(): return "cyan_stained_glass " elif (closest_color == gray).all(): return "gray_stained_glass" elif (closest_color == green).all(): return "green_stained_glass" elif (closest_color == light_blue).all(): return "light_blue_stained_glass" elif (closest_color == light_gray).all(): return "light_gray_stained_glass" elif (closest_color == lime).all(): return "lime_stained_glass" elif (closest_color == magenta).all(): return "magenta_stained_glass" elif (closest_color == orange).all(): return "orange_stained_glass" elif (closest_color == pink).all(): return "pink_stained_glass" elif (closest_color == purple).all(): return "purple_stained_glass" elif (closest_color == red).all(): return "red_stained_glass" elif (closest_color == white).all(): return "white_stained_glass" elif (closest_color == yellow).all(): return "yellow_stained_glass" def create_mcfunction(image_file_name, img_type): im = Image.open(image_file_name) pix = im.load() h = im.size[0] w = im.size[1] offset = (h+w)//4 fileName = f"datapacks/img/data/img/functions/items/{img_type}/{image_file_name.split('.')[0]}.mcfunction" os.remove(fileName) with open(fileName, 'a') as mcfunction: for x in range(h): for y in range(w): rgb = pix[x, y] color = [rgb[0], rgb[1], rgb[2]] closest_color = closest(color) if img_type == "player": func = f"setblock ~{x-offset} ~ ~{y-offset} " elif img_type == "sky": func = f"setblock ~{x-offset} 319 ~{y-offset} " if str(rgb) == "(0, 0, 0, 0)": func+="air" else: if img_type == "player": func+=concrete_art(closest_color) elif img_type == "sky": func+=glass_art(closest_color) mcfunction.write(func+'\n') create_mcfunction("apple.png", "player") create_mcfunction("apple.png", "sky")
kirbycope/map-markers-java
img.py
img.py
py
4,689
python
en
code
0
github-code
6
42483141861
import os import json import requests from flask import Flask, jsonify, request, Response from faker import Factory from twilio.access_token import AccessToken, IpMessagingGrant app = Flask(__name__) fake = Factory.create() @app.route('/') def index(): return app.send_static_file('index.html') @app.route('/tone', methods=['POST']) def tone(): try: response = requests.post( url="https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone", params={ "version": "2016-05-19", }, headers={ "Authorization": "Basic MDQ1MjE5ZDUtYzVjNC00ZTE0LTk0MDItMWY1OWJmOTY5OWE3Olk3S1h1bTBNMWY2bw==", "Content-Type": "application/json", }, data=json.dumps({ "text": json.loads(request.data)['text'] }) ) print('Response HTTP Status Code: {status_code}'.format( status_code=response.status_code)) print('Response HTTP Response Body: {content}'.format( content=response.content)) return Response(response.content, mimetype='application/json') except requests.exceptions.RequestException: print('HTTP Request failed') # json_data = json.loads(request.data) @app.route('/token') def token(): # get credentials for environment variables account_sid = "ACcdbab0f13e08eb8b19b6d3025a9ad6f7" api_key = "SK2f52e17a9ca74d4714d28a7c575e1e21" api_secret = "6XYHaD6O5zPKDpM4wU34NknCQj7L1d6C" service_sid = "IS27b6d9077d6c48838881fc41b4748bb2" # create a randomly generated username for the client identity = request.args.get('identity') # Create a unique endpoint ID for the device_id = request.args.get('device') endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id) # Create access token with credentials token = AccessToken(account_sid, api_key, api_secret, identity) # Create an IP Messaging grant and add to token ipm_grant = IpMessagingGrant(endpoint_id=endpoint, service_sid=service_sid) token.add_grant(ipm_grant) # Return token info as JSON return jsonify(identity=identity, token=token.to_jwt()) if __name__ == '__main__': #app.run(debug=True) port = os.getenv('PORT', '5000') app.run(host="0.0.0.0", port=int(port))
AvonGenesis/jwms
app.py
app.py
py
2,338
python
en
code
0
github-code
6
18527949488
import pytest from selene.support.shared import browser from selene import be, have @pytest.fixture(scope='session', autouse=True) def browser_size(): browser.config.window_width = 1280 browser.config.window_height = 720 def test_search(browser_size): browser.open('https://google.com') browser.element('[name="q"]').should(be.blank).type('yashaka/selene').press_enter() browser.element('[id="search"]').should(have.text('yashaka/selene: User-oriented Web UI browser tests in')) def test_search_no_result(browser_size): browser.open('https://google.com') browser.element('[name="q"]').should(be.blank).type('fdfdfdfdfdh141cnjmmmmmm').press_enter() browser.element('[id="result-stats"]').should(have.text('Результатов: примерно 0'))
ekat-barkova/qa_guru_python_6_2_homework
tests/test_google_should_find_selene.py
test_google_should_find_selene.py
py
788
python
en
code
0
github-code
6
72761928188
import nussl import torch from torch import nn from torch.nn.utils import weight_norm from nussl.ml.networks.modules import ( Embedding, DualPath, DualPathBlock, STFT, LearnedFilterBank, AmplitudeToDB, RecurrentStack, MelProjection, BatchNorm, InstanceNorm, ShiftAndScale ) import numpy as np from . import utils, argbind from typing import Dict, List # ---------------------------------------------------- # --------------------- SEPARATORS ------------------- # ---------------------------------------------------- def dummy_signal(): return nussl.AudioSignal( audio_data_array=np.random.rand(1, 100), sample_rate=100 ) @argbind.bind_to_parser() def deep_mask_estimation( device : torch.device, model_path : str = 'checkpoints/best.model.pth', mask_type : str = 'soft', ): """ Creates a DeepMaskEstimation Separation object. Parameters ---------- device : str Either 'cuda' (needs GPU) or 'cpu'. model_path : str, optional Path to the model, by default 'checkpoints/best.model.pth' mask_type : str, optional Type of mask to use, either 'soft' or 'binary', by default 'soft'. """ separator = nussl.separation.deep.DeepMaskEstimation( dummy_signal(), model_path=model_path, device=device, mask_type=mask_type ) return separator @argbind.bind_to_parser() def deep_audio_estimation( device : torch.device, model_path : str = 'checkpoints/best.model.pth', ): """ Creates a DeepMaskEstimation Separation object. Parameters ---------- device : str Either 'cuda' (needs GPU) or 'cpu'. model_path : str, optional Path to the model, by default 'checkpoints/best.model.pth' mask_type : str, optional Type of mask to use, either 'soft' or 'binary', by default 'soft'. """ separator = nussl.separation.deep.DeepAudioEstimation( dummy_signal(), model_path=model_path, device=device, ) return separator # ---------------------------------------------------- # --------------- MASK ESTIMATION MODELS ------------- # ---------------------------------------------------- class MaskInference(nn.Module): def __init__(self, num_features, num_audio_channels, hidden_size, num_layers, bidirectional, dropout, num_sources, activation='sigmoid'): super().__init__() self.amplitude_to_db = AmplitudeToDB() self.input_normalization = BatchNorm(num_features) self.recurrent_stack = RecurrentStack( num_features * num_audio_channels, hidden_size, num_layers, bool(bidirectional), dropout ) hidden_size = hidden_size * (int(bidirectional) + 1) self.embedding = Embedding(num_features, hidden_size, num_sources, activation, num_audio_channels) def forward(self, data): mix_magnitude = data # save for masking data = self.amplitude_to_db(mix_magnitude) data = self.input_normalization(data) data = self.recurrent_stack(data) mask = self.embedding(data) estimates = mix_magnitude.unsqueeze(-1) * mask output = { 'mask': mask, 'estimates': estimates } return output # Added function @staticmethod @argbind.bind_to_parser() def build(num_features, num_audio_channels, hidden_size, num_layers, bidirectional, dropout, num_sources, activation='sigmoid'): # Step 1. Register our model with nussl nussl.ml.register_module(MaskInference) # Step 2a: Define the building blocks. modules = { 'model': { 'class': 'MaskInference', 'args': { 'num_features': num_features, 'num_audio_channels': num_audio_channels, 'hidden_size': hidden_size, 'num_layers': num_layers, 'bidirectional': bidirectional, 'dropout': dropout, 'num_sources': num_sources, 'activation': activation } } } # Step 2b: Define the connections between input and output. # Here, the mix_magnitude key is the only input to the model. connections = [ ['model', ['mix_magnitude']] ] # Step 2c. The model outputs a dictionary, which SeparationModel will # change the keys to model:mask, model:estimates. The lines below # alias model:mask to just mask, and model:estimates to estimates. # This will be important later when we actually deploy our model. for key in ['mask', 'estimates']: modules[key] = {'class': 'Alias'} connections.append([key, [f'model:{key}']]) # Step 2d. There are two outputs from our SeparationModel: estimates and mask. # Then put it all together. output = ['estimates', 'mask',] config = { 'name': 'MaskInference', 'modules': modules, 'connections': connections, 'output': output } # Step 3. Instantiate the model as a SeparationModel. return nussl.ml.SeparationModel(config) # ---------------------------------------------------- # --------------- AUDIO ESTIMATION MODELS ------------ # ---------------------------------------------------- class BaseAudioModel(nn.Module): def __init__(self, *args, **kwargs): super().__init__() @classmethod def config(cls, **kwargs): nussl.ml.register_module(cls) _config = { 'modules': { 'audio': { 'class': cls.__name__, 'args': kwargs } }, 'connections': [ ['audio', ['mix_audio']] ], 'output': ['audio'] } return _config # ---------------------------------------------------- # ------------- REGISTER MODELS WITH NUSSL ----------- # ---------------------------------------------------- nussl.ml.register_module(MaskInference)
bfredl/tutorial
common/models.py
models.py
py
6,359
python
en
code
1
github-code
6
43008598388
# coding:utf-8 import operator import re import math import numpy as np file_path = "./GameOfThrones.txt" def num_dict(str): alist = [] letter_list = [chr(i) for i in range(ord("A"), ord("Z") + 1)] + ["space"] for i in range(26): # 初始化一个长度为26的列表 alist.append(0) str = str.lower() for i in str: if i.isalpha(): # 利用桶的思想 alist[ord(i) - 97] += 1 _, space_num = count_num(file_path) alist = alist + [space_num] letter_dict = dict(zip(letter_list, alist)) # letter_list.insert(0, "space") return letter_list, letter_dict def count_num(path): letter_num = 0 space_num = 0 with open(path, "r") as f: file = f.read() for i in file: if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 65 and ord(i) <= 90): letter_num = letter_num + 1 elif ord(i) == 32: space_num = space_num + 1 return letter_num, space_num def get_txt(file_path): fp = open(file_path, 'r') file_text = fp.read() letter_str = re.findall(r'([a-zA-Z]+)', file_text, re.MULTILINE) fp.close() return ''.join(letter_str) def get_sort_prob_k_list_dict(num_dict): letter_num, space_num = count_num(file_path) sum_num = letter_num + space_num list = [chr(i) for i in range(ord("A"), ord("Z") + 1)] + ["space"] prob_list = [] k_list = [] sorted_letter_list = [] sorted_prob_dict = {} sorted_k_dict = {} for letter in list: probability = num_dict[letter] / sum_num k = math.floor(1 - math.log(probability, 2)) prob_list = prob_list + [probability] k_list = k_list + [k] sorted_prob_list = sorted(prob_list, reverse=True) sorted_k_list = sorted(k_list, reverse=False) prob_dict = dict(zip(list, prob_list)) k_dict = dict(zip(list, k_list)) # *******sorted之后还不是真正的字典********** prob_dict = sorted(prob_dict.items(), key=operator.itemgetter(1), reverse=True) k_dict = sorted(k_dict.items(), key=operator.itemgetter(1), reverse=True) sorted_prob_dict.update(prob_dict) sorted_k_dict.update(k_dict) for key in sorted_prob_dict: sorted_letter_list.append(key) return prob_list, sorted_letter_list, sorted_prob_list, sorted_k_list, sorted_prob_dict, sorted_k_dict def get_append_sorted_prob_list_dict(sorted_prob_dict): append_sorted_prob_list = [] append_sorted_prob_dict = {} first_dict = {"zero": 0} append_sorted_prob_dict.update(first_dict) append_sorted_prob_dict.update(sorted_prob_dict) for key in append_sorted_prob_dict: append_sorted_prob_list.append(append_sorted_prob_dict[key]) return append_sorted_prob_list, append_sorted_prob_dict def get_sumProb_list(append_sorted_prob_list): sum_first = 0 sumProb_list = [] for i in range(0, 27): sum_first = sum_first + append_sorted_prob_list[i] sumProb_list.append(sum_first) return sumProb_list def get_entropy(sorted_prob_list): entropy = 0 for prob in sorted_prob_list: single_entropy = -prob * math.log(prob, 2) entropy = single_entropy + entropy return entropy def get_mean_K(sorted_prob_list, sorted_k_list): list_p_k = np.multiply(np.array(sorted_prob_list), np.array(sorted_k_list)) return sum(list_p_k) def get_var(sorted_prob_list, sorted_k_list, mean_k): sorted_kk_list = sorted_k_list - mean_k sorted_k2_list = sorted_kk_list*sorted_kk_list list_p_k = np.multiply(np.array(sorted_prob_list), np.array(sorted_k2_list)) # sqrt_list = [] # for val in list_p_k: # sqrt_list.append(val*val) return sorted_kk_list, sum(list_p_k) def get_code_efficiency(entropy, mean_k): effficiency = entropy / mean_k return effficiency def dec2bin_list_dict(letter_list, sumProb_list, sorted_k_list): sorted_bin_list = [] sorted_bin_dict = {} global value i = 0 for value in sumProb_list: s = "" for k in range(sorted_k_list[i]): value = value * 2 if value >= 1: value = value - 1 s = s + str(1) else: s = s + str(0) i = i + 1 sorted_bin_list.append(s) sorted_bin_dict = dict(zip(letter_list, sorted_bin_list)) return sorted_bin_list, sorted_bin_dict def main_shannon(): file_path = "./GameOfThrones.txt" letter_num, space_num = count_num(file_path) file_txt = get_txt(file_path) letter_list, letter_dict = num_dict(file_txt) prob_list, sorted_letter_list, sorted_prob_list, sorted_k_list, sorted_prob_dict, sorted_k_dict = get_sort_prob_k_list_dict( letter_dict) append_sorted_prob_list, append_sorted_prob_dict = get_append_sorted_prob_list_dict(sorted_prob_dict) sumProb_list = get_sumProb_list(append_sorted_prob_list) sorted_bin_list, sorted_bin_dict = dec2bin_list_dict(sorted_letter_list, sumProb_list, sorted_k_list) entropy = get_entropy(sorted_prob_list) mean_k = get_mean_K(sorted_prob_list, sorted_k_list) effficiency = get_code_efficiency(entropy, mean_k) sorted_kk_list, var = get_var(sorted_prob_list, sorted_k_list, mean_k) print("******Shannon encoding******") for key, values in sorted_bin_dict.items(): print('%-10s%-20s' % (key, values)) print('%-10s%-20s' % ("信源熵 : ", entropy)) print('%-10s%-20s' % ("平均码字长度 : ", mean_k)) print('%-10s%-20s' % ("码字长度的方差 : ", var)) print('%-10s%-20s' % ("编码效率 : ", effficiency)) if __name__ == '__main__': main_shannon()
weixinxu666/encoders
shannon.py
shannon.py
py
5,662
python
en
code
3
github-code
6
11300309585
from django.contrib import admin from django.urls import path from firstapp import views as v1 urlpatterns = [ path('admin/', admin.site.urls), path('home/',v1.home), path('gm/',v1.gm_), path('ga/',v1.ga_), path('gn/',v1.gn_), ]
Ranjith8796/Demo
firstapp/urls.py
urls.py
py
262
python
en
code
0
github-code
6
5898520470
import os from datetime import datetime, timezone import tweepy def scrape_user_tweets(username: str, num_tweets: int = 10) -> list: """ Scrapes Twitter user's original tweets (i.e., no retweets or replies) and returns them as a list of dictionaries. Each dictionary has three fields: "time_posted" (relative or now), "text", and "url". :param username: Twitter account username :param num_tweets: number of tweets to scrape :return: list """ auth = tweepy.OAuthHandler( os.environ["TWITTER_API_KEY"], os.environ["TWITTER_API_SECRET"] ) auth.set_access_token( os.environ["TWITTER_ACCESS_TOKEN"], os.environ["TWITTER_ACCESS_SECRET"] ) twitter_api = tweepy.API(auth) tweets = twitter_api.user_timeline(screen_name=username, count=num_tweets) tweet_list = [] for tweet in tweets: if "RT @" not in tweet.text and not tweet.text.startswith("@"): tweet_dict = dict() tweet_dict["time_posted"] = str( datetime.now(timezone.utc) - tweet.created_at ) tweet_dict["text"] = tweet.text tweet_dict[ "url" ] = f"https://twitter.com/{tweet.user.screen_name}/status/{tweet.id}" tweet_list.append(tweet_dict) return tweet_list
mdalvi/langchain-with-milind
third_parties/twitter.py
twitter.py
py
1,318
python
en
code
2
github-code
6
28108895632
import mat73 import matplotlib.pyplot as plt FORMAT = 'pdf' plt.rcParams.update({'font.size': 22}) datasets = ["Brain", "MAG-10", "Cooking", "DAWN", "Walmart-Trips", "Trivago"] budgets = [0, .01, .05, .1, .15, .2, .25] budget_strings = ['0.0', '0.01', '0.05', '0.1', '0.15', '0.2', '0.25'] n = [638, 80198, 6714, 2109, 88837, 207974] bicrit_apx = [] bicrit_beta = [] greedy_satisfaction = [] for i in range(len(datasets)): print(i) dataset = datasets[i] bicrit_apx.append([]) bicrit_beta.append([]) greedy_satisfaction.append([]) for j in range(len(budgets)): data = mat73.loadmat("Output/RECC/"+dataset+"_b"+budget_strings[j]+"_results.mat") bicrit_apx[i].append(data["ratio"]) bicrit_beta[i].append(data["budget_ratio"]) greedy_satisfaction[i].append(100*data["greedy_satisfaction"]) orange = [x/255.0 for x in [230, 159, 0]] skyblue = [x/255.0 for x in [86, 180, 233]] bluegreen = [x/255.0 for x in [0, 158, 115]] blue = [x/255.0 for x in [0, 114, 178]] vermillion = [x/255.0 for x in [213, 94, 0]] redpurple = [x/255.0 for x in [204, 121, 167]] colors = [orange, skyblue, bluegreen, redpurple, vermillion, blue] legend_text = ["Brain", "MAG-10", "Cooking", "DAWN", "Walmart", "Trivago"] markers = ['^', 'v', 'o', 's', '<', '>'] fig, ax = plt.subplots() x = [budg*100 for budg in budgets] for i in range(len(datasets)): ax.plot(x, bicrit_apx[i], label=legend_text[i], color=colors[i], marker=markers[i]) ax.set_xlabel(r"$b$ = Deletion Budget (% of $V$)") ax.set_ylabel(r"Observed $\alpha$") ax.legend(fontsize=16) fig.savefig(f'Plots/r_alphas.{FORMAT}', format=FORMAT, bbox_inches='tight') fig2, ax2 = plt.subplots() for i in range(len(datasets)): ax2.plot(x, bicrit_beta[i], label=legend_text[i], color=colors[i],marker=markers[i]) ax2.set_xlabel(r"$b$ = Deletion Budget (% of $V$)") ax2.set_ylabel(r"Observed $\beta$") ax2.legend(fontsize=16) fig2.savefig(f'Plots/r_betas.{FORMAT}', format=FORMAT, bbox_inches='tight') fig3, ax3 = plt.subplots() for i in range(len(datasets)): ax3.plot(x, greedy_satisfaction[i], label=legend_text[i], color=colors[i],marker=markers[i]) ax3.set_xlabel(r"$b$ = Deletion Budget (% of $V$)") ax3.set_ylabel(r"Edge Satisfaction (% of $E$)") ax3.legend(fontsize=16) fig3.savefig(f'Plots/r_greedy_satisfactions.{FORMAT}', format=FORMAT, bbox_inches='tight')
TheoryInPractice/overlapping-ecc
Exp1-Algorithm-Evaluation/R_Plots.py
R_Plots.py
py
2,373
python
en
code
null
github-code
6
71483943548
# SPDX-License-Identifier: MIT # (c) 2023 knuxify and Ear Tag contributors from gi.repository import GObject, GLib import threading import time class EartagBackgroundTask(GObject.Object): """ Convenience class for creating tasks that run in the background without freezing the UI. Provides a "progress" property that can be used by target functions to signify a progress change. This is a float from 0 to 1 and is passed directly to GtkProgressBar. Also provides an optional "halt" property; target functions can check for this property to stop an operation early. Remember to pass all code that interacts with GTK through GLib.idle_add(). """ def __init__(self, target, *args, **kwargs): super().__init__() self._progress = 0 self.target = target self.reset(args, kwargs) def wait_for_completion(self): while self.thread.is_alive(): time.sleep(0.25) def stop(self): self.halt = True self.wait_for_completion() self.halt = False def run(self): self.thread.start() def reset(self, args=[], kwargs=[]): """Re-creates the inner thread with new args and kwargs.""" self._is_done = False self.thread = None self.halt = False self.failed = False if args and kwargs: self.thread = threading.Thread( target=self.target, daemon=True, args=args, kwargs=kwargs ) elif args: self.thread = threading.Thread( target=self.target, daemon=True, args=args ) elif kwargs: self.thread = threading.Thread( target=self.target, daemon=True, kwargs=kwargs ) else: self.thread = threading.Thread( target=self.target, daemon=True ) @GObject.Property(type=float, minimum=0, maximum=1) def progress(self): """ Float from 0 to 1 signifying the current progress of the operation. When the task is done, this automatically resets to 0. This value is set by the target function. """ return self._progress @progress.setter def progress(self, value): self._progress = value @GObject.Signal def task_done(self): self.reset_progress() self._is_done = True @GObject.Property(type=bool, default=False) def is_running(self): if not self.thread: return False return self.thread.is_alive() def reset_progress(self): self.props.progress = 0 def set_progress_threadsafe(self, value): """ Wrapper around self.props.progress that updates the progress, wrapped around GLib.idle_add. This is the preferred way for users to set the progress variable. """ GLib.idle_add(self.set_property, 'progress', value) def increment_progress(self, value): """ Wrapper around self.props.progress that increments the progress, wrapped around GLib.idle_add. This is the preferred way for users to increment the progress variable. """ self.set_progress_threadsafe(self.props.progress + value) def emit_task_done(self): """ Wrapper around self.emit('task-done') that is wrapped around GLib.idle_add. This is the preferred way for users to emit the task-done signal. """ GLib.idle_add(self.emit, 'task-done')
knuxify/eartag
src/utils/bgtask.py
bgtask.py
py
3,589
python
en
code
67
github-code
6
31261537971
from collections import namedtuple from itertools import izip from operator import attrgetter from tilequeue.log import LogCategory from tilequeue.log import LogLevel from tilequeue.log import MsgType from tilequeue.metatile import common_parent from tilequeue.metatile import make_metatiles from tilequeue.process import convert_source_data_to_feature_layers from tilequeue.process import process_coord from tilequeue.queue import JobProgressException from tilequeue.queue.message import QueueHandle from tilequeue.store import write_tile_if_changed from tilequeue.tile import coord_children_subrange from tilequeue.tile import coord_to_mercator_bounds from tilequeue.tile import serialize_coord from tilequeue.utils import convert_seconds_to_millis from tilequeue.utils import format_stacktrace_one_line import Queue import signal import sys import time # long enough to not fight with other threads, but not long enough # that it prevents a timely stop timeout_seconds = 5 def _non_blocking_put(q, data): # don't block indefinitely when trying to put to a queue # this helps prevent deadlocks if the destination queue is full # and stops try: q.put(data, timeout=timeout_seconds) except Queue.Full: return False else: return True def _force_empty_queue(q): # expects a sentinel None value to get enqueued # throws out all messages until we receive the sentinel # with no sentinel this will block indefinitely while q.get() is not None: continue # OutputQueue wraps the process of sending data to a multiprocessing queue # so that we can simultaneously check for the "stop" signal when it's time # to shut down. class OutputQueue(object): def __init__(self, output_queue, tile_proc_logger, stop): self.output_queue = output_queue self.tile_proc_logger = tile_proc_logger self.stop = stop def __call__(self, coord, data): """ Send data, associated with coordinate coord, to the queue. While also watching for a signal to stop. If the data is too large to send, then trap the MemoryError and exit the program. Note that `coord` may be a Coordinate instance or a string. It is only used for printing out a message if there's a MemoryError, so for requests which have no meaningful single coordinate, something else can be used. Returns True if the "stop signal" has been set and the thread should shut down. False if normal operations should continue. """ try: while not _non_blocking_put(self.output_queue, data): if self.stop.is_set(): return True except MemoryError as e: stacktrace = format_stacktrace_one_line() self.tile_proc_logger.error( 'MemoryError sending to queue', e, stacktrace, coord) # memory error might not leave the malloc subsystem in a usable # state, so better to exit the whole worker here than crash this # thread, which would lock up the whole worker. sys.exit(1) return False def _ack_coord_handle( coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler): """share code for acknowledging a coordinate""" # returns tuple of (handle, error), either of which can be None track_result = msg_tracker.done(coord_handle) queue_handle = track_result.queue_handle if not queue_handle: return None, None tile_queue = queue_mapper.get_queue(queue_handle.queue_id) assert tile_queue, \ 'Missing tile_queue: %s' % queue_handle.queue_id parent_tile = None if track_result.all_done: parent_tile = track_result.parent_tile try: tile_queue.job_done(queue_handle.handle) except Exception as e: stacktrace = format_stacktrace_one_line() tile_proc_logger.error_job_done( 'tile_queue.job_done', e, stacktrace, coord, parent_tile, ) return queue_handle, e if parent_tile is not None: # we completed a tile pyramid and should log appropriately start_time = timing_state['start'] stop_time = convert_seconds_to_millis(time.time()) tile_proc_logger.log_processed_pyramid( parent_tile, start_time, stop_time) stats_handler.processed_pyramid( parent_tile, start_time, stop_time) else: try: tile_queue.job_progress(queue_handle.handle) except Exception as e: stacktrace = format_stacktrace_one_line() err_details = {"queue_handle": queue_handle.handle} if isinstance(e, JobProgressException): err_details = e.err_details tile_proc_logger.error_job_progress( 'tile_queue.job_progress', e, stacktrace, coord, parent_tile, err_details, ) return queue_handle, e return queue_handle, None # The strategy with each worker is to loop on a thread event. When the # main thread/process receives a kill signal, it will issue stops to # each worker to signal that work should end. # Additionally, all workers that receive work from a python queue will # also wait for a sentinel value, None, before terminating. They will # discard all messages until receiving this sentinel value. Special # care is also given to the scenario where a None value is received # before the stop event is checked. The sentinel value here counts as # a hard stop as well. # Furthermore, all queue gets and puts are done with timeouts. This is # to prevent race conditions where a worker is blocked waiting to read # from a queue that upstream will no longer write to, or try to put to # a queue that downstream will no longer read from. After any timeout, # the stop event is checked before any processing to see whether a # stop event has been received in the interim. class TileQueueReader(object): def __init__( self, queue_mapper, msg_marshaller, msg_tracker, output_queue, tile_proc_logger, stats_handler, stop, max_zoom, group_by_zoom): self.queue_mapper = queue_mapper self.msg_marshaller = msg_marshaller self.msg_tracker = msg_tracker self.output = OutputQueue(output_queue, tile_proc_logger, stop) self.tile_proc_logger = tile_proc_logger self.stats_handler = stats_handler self.stop = stop self.max_zoom = max_zoom self.group_by_zoom = group_by_zoom def __call__(self): while not self.stop.is_set(): msg_handles = () for queue_id, tile_queue in ( self.queue_mapper.queues_in_priority_order()): try: msg_handles = tile_queue.read() except Exception as e: stacktrace = format_stacktrace_one_line() self.tile_proc_logger.error( 'Queue read error', e, stacktrace) continue if msg_handles: break if not msg_handles: continue for msg_handle in msg_handles: # if asked to stop, break as soon as possible if self.stop.is_set(): break now = convert_seconds_to_millis(time.time()) msg_timestamp = None if msg_handle.metadata: msg_timestamp = msg_handle.metadata.get('timestamp') timing_state = dict( msg_timestamp=msg_timestamp, start=now, ) coords = self.msg_marshaller.unmarshall(msg_handle.payload) # it seems unlikely, but just in case there are no coordinates # in the payload, there's nothing to do, so skip to the next # payload. if not coords: continue # check for duplicate coordinates - for the message tracking to # work, we assume that coordinates are unique, as we use them # as keys in a dict. (plus, it doesn't make a lot of sense to # render the coordinate twice in the same job anyway). coords = list(set(coords)) parent_tile = self._parent(coords) queue_handle = QueueHandle(queue_id, msg_handle.handle) coord_handles = self.msg_tracker.track( queue_handle, coords, parent_tile) all_coords_data = [] for coord, coord_handle in izip(coords, coord_handles): if coord.zoom > self.max_zoom: self._reject_coord(coord, coord_handle, timing_state) continue metadata = dict( # the timing is just what will be filled out later timing=dict( fetch=None, process=None, s3=None, ack=None, ), # this is temporary state that is used later on to # determine timing information timing_state=timing_state, coord_handle=coord_handle, ) data = dict( metadata=metadata, coord=coord, ) all_coords_data.append(data) # we might have no coordinates if we rejected all the # coordinates. in which case, there's nothing to do anyway, as # the _reject_coord method will have marked the job as done. if all_coords_data: coord_input_spec = all_coords_data, parent_tile msg = "group of %d tiles below %s" \ % (len(all_coords_data), serialize_coord(parent_tile)) if self.output(msg, coord_input_spec): break for _, tile_queue in self.queue_mapper.queues_in_priority_order(): tile_queue.close() self.tile_proc_logger.lifecycle('tile queue reader stopped') def _reject_coord(self, coord, coord_handle, timing_state): self.tile_proc_logger.log( LogLevel.WARNING, LogCategory.PROCESS, MsgType.INDIVIDUAL, 'Job coordinates above max zoom are not ' 'supported, skipping %d > %d' % ( coord.zoom, self.max_zoom), None, # exception None, # stacktrace coord, ) # delete jobs that we can't handle from the # queue, otherwise we'll get stuck in a cycle # of timed-out jobs being re-added to the # queue until they overflow max-retries. _ack_coord_handle( coord, coord_handle, self.queue_mapper, self.msg_tracker, timing_state, self.tile_proc_logger, self.stats_handler) def _parent(self, coords): if len(coords) == 0: return None parent = reduce(common_parent, coords) if self.group_by_zoom is not None: if parent.zoom < self.group_by_zoom: assert len(coords) == 1, "Expect either a single tile or a " \ "pyramid at or below group zoom." else: parent = parent.zoomTo(self.group_by_zoom).container() return parent class DataFetch(object): def __init__( self, fetcher, input_queue, output_queue, io_pool, tile_proc_logger, stats_handler, metatile_zoom, max_zoom, metatile_start_zoom=0): self.fetcher = fetcher self.input_queue = input_queue self.output_queue = output_queue self.io_pool = io_pool self.tile_proc_logger = tile_proc_logger self.stats_handler = stats_handler self.metatile_zoom = metatile_zoom self.max_zoom = max_zoom self.metatile_start_zoom = metatile_start_zoom def __call__(self, stop): saw_sentinel = False output = OutputQueue(self.output_queue, self.tile_proc_logger, stop) while not stop.is_set(): try: coord_input_spec = self.input_queue.get( timeout=timeout_seconds) except Queue.Empty: continue if coord_input_spec is None: saw_sentinel = True break coord = None parent = None try: all_data, parent = coord_input_spec for fetch, data in self.fetcher.fetch_tiles(all_data): metadata = data['metadata'] coord = data['coord'] if self._fetch_and_output(fetch, coord, metadata, output): break except Exception as e: stacktrace = format_stacktrace_one_line() self.tile_proc_logger.fetch_error(e, stacktrace, coord, parent) self.stats_handler.fetch_error() if not saw_sentinel: _force_empty_queue(self.input_queue) self.tile_proc_logger.lifecycle('data fetch stopped') def _fetch_and_output(self, fetch, coord, metadata, output): data = self._fetch(fetch, coord, metadata) return output(coord, data) def _fetch(self, fetch, coord, metadata): nominal_zoom = coord.zoom + self.metatile_zoom start_zoom = coord.zoom + self.metatile_start_zoom unpadded_bounds = coord_to_mercator_bounds(coord) start = time.time() source_rows = fetch(nominal_zoom, unpadded_bounds) metadata['timing']['fetch'] = convert_seconds_to_millis( time.time() - start) # every tile job that we get from the queue is a "parent" tile # and its four children to cut from it. at zoom 15, this may # also include a whole bunch of other children below the max # zoom. cut_coords = list( coord_children_subrange(coord, start_zoom, nominal_zoom)) return dict( metadata=metadata, coord=coord, source_rows=source_rows, unpadded_bounds=unpadded_bounds, cut_coords=cut_coords, nominal_zoom=nominal_zoom, ) class ProcessAndFormatData(object): scale = 4096 def __init__(self, post_process_data, formats, input_queue, output_queue, buffer_cfg, output_calc_mapping, layer_data, tile_proc_logger, stats_handler): formats.sort(key=attrgetter('sort_key')) self.post_process_data = post_process_data self.formats = formats self.input_queue = input_queue self.output_queue = output_queue self.buffer_cfg = buffer_cfg self.output_calc_mapping = output_calc_mapping self.layer_data = layer_data self.tile_proc_logger = tile_proc_logger self.stats_handler = stats_handler def __call__(self, stop): # ignore ctrl-c interrupts when run from terminal signal.signal(signal.SIGINT, signal.SIG_IGN) output = OutputQueue(self.output_queue, self.tile_proc_logger, stop) saw_sentinel = False while not stop.is_set(): try: data = self.input_queue.get(timeout=timeout_seconds) except Queue.Empty: continue if data is None: saw_sentinel = True break coord = data['coord'] unpadded_bounds = data['unpadded_bounds'] cut_coords = data['cut_coords'] nominal_zoom = data['nominal_zoom'] source_rows = data['source_rows'] start = time.time() try: feature_layers = convert_source_data_to_feature_layers( source_rows, self.layer_data, unpadded_bounds, nominal_zoom) formatted_tiles, extra_data = process_coord( coord, nominal_zoom, feature_layers, self.post_process_data, self.formats, unpadded_bounds, cut_coords, self.buffer_cfg, self.output_calc_mapping) except Exception as e: stacktrace = format_stacktrace_one_line() self.tile_proc_logger.error( 'Processing error', e, stacktrace, coord) self.stats_handler.proc_error() continue metadata = data['metadata'] metadata['timing']['process'] = convert_seconds_to_millis( time.time() - start) metadata['layers'] = extra_data data = dict( metadata=metadata, coord=coord, formatted_tiles=formatted_tiles, ) if output(coord, data): break if not saw_sentinel: _force_empty_queue(self.input_queue) self.tile_proc_logger.lifecycle('processor stopped') class S3Storage(object): def __init__(self, input_queue, output_queue, io_pool, store, tile_proc_logger, metatile_size): self.input_queue = input_queue self.output_queue = output_queue self.io_pool = io_pool self.store = store self.tile_proc_logger = tile_proc_logger self.metatile_size = metatile_size def __call__(self, stop): saw_sentinel = False queue_output = OutputQueue( self.output_queue, self.tile_proc_logger, stop) while not stop.is_set(): try: data = self.input_queue.get(timeout=timeout_seconds) except Queue.Empty: continue if data is None: saw_sentinel = True break coord = data['coord'] start = time.time() try: async_jobs = self.save_tiles(data['formatted_tiles']) except Exception as e: # cannot propagate this error - it crashes the thread and # blocks up the whole queue! stacktrace = format_stacktrace_one_line() self.tile_proc_logger.error('Save error', e, stacktrace, coord) continue async_exc_info = None e = None n_stored = 0 n_not_stored = 0 for async_job in async_jobs: try: did_store = async_job.get() if did_store: n_stored += 1 else: n_not_stored += 1 except Exception as e: # it's important to wait for all async jobs to # complete but we just keep a reference to the last # exception it's unlikely that we would receive multiple # different exceptions when uploading to s3 async_exc_info = sys.exc_info() if async_exc_info: stacktrace = format_stacktrace_one_line(async_exc_info) self.tile_proc_logger.error( 'Store error', e, stacktrace, coord) continue metadata = data['metadata'] metadata['timing']['s3'] = convert_seconds_to_millis( time.time() - start) metadata['store'] = dict( stored=n_stored, not_stored=n_not_stored, ) data = dict( coord=coord, metadata=metadata, ) if queue_output(coord, data): break if not saw_sentinel: _force_empty_queue(self.input_queue) self.tile_proc_logger.lifecycle('s3 storage stopped') def save_tiles(self, tiles): async_jobs = [] if self.metatile_size: tiles = make_metatiles(self.metatile_size, tiles) for tile in tiles: async_result = self.io_pool.apply_async( write_tile_if_changed, ( self.store, tile['tile'], # important to use the coord from the # formatted tile here, because we could have # cut children tiles that have separate zooms # too tile['coord'], tile['format'])) async_jobs.append(async_result) return async_jobs CoordProcessData = namedtuple( 'CoordProcessData', ('coord', 'timing', 'size', 'store_info',), ) class TileQueueWriter(object): def __init__( self, queue_mapper, input_queue, inflight_mgr, msg_tracker, tile_proc_logger, stats_handler, stop): self.queue_mapper = queue_mapper self.input_queue = input_queue self.inflight_mgr = inflight_mgr self.msg_tracker = msg_tracker self.tile_proc_logger = tile_proc_logger self.stats_handler = stats_handler self.stop = stop def __call__(self): saw_sentinel = False while not self.stop.is_set(): try: data = self.input_queue.get(timeout=timeout_seconds) except Queue.Empty: continue if data is None: saw_sentinel = True break metadata = data['metadata'] coord_handle = metadata['coord_handle'] coord = data['coord'] timing_state = metadata['timing_state'] start = time.time() try: self.inflight_mgr.unmark_inflight(coord) except Exception as e: stacktrace = format_stacktrace_one_line() self.tile_proc_logger.error( 'Unmarking in-flight error', e, stacktrace, coord) continue queue_handle, err = _ack_coord_handle( coord, coord_handle, self.queue_mapper, self.msg_tracker, timing_state, self.tile_proc_logger, self.stats_handler) if err is not None: continue timing = metadata['timing'] now = time.time() timing['ack'] = convert_seconds_to_millis(now - start) time_in_queue = 0 msg_timestamp = timing_state['msg_timestamp'] if msg_timestamp: time_in_queue = convert_seconds_to_millis(now) - msg_timestamp timing['queue'] = time_in_queue layers = metadata['layers'] size = layers['size'] store_info = metadata['store'] coord_proc_data = CoordProcessData( coord, timing, size, store_info, ) self.tile_proc_logger.log_processed_coord(coord_proc_data) self.stats_handler.processed_coord(coord_proc_data) if not saw_sentinel: _force_empty_queue(self.input_queue) self.tile_proc_logger.lifecycle('tile queue writer stopped') class QueuePrint(object): def __init__(self, interval_seconds, queue_info, tile_proc_logger, stop): self.interval_seconds = interval_seconds self.queue_info = queue_info self.tile_proc_logger = tile_proc_logger self.stop = stop def __call__(self): # sleep in smaller increments, so that when we're asked to # stop we aren't caught sleeping on the job sleep_interval_seconds = min(timeout_seconds, self.interval_seconds) while not self.stop.is_set(): i = float(0) while i < self.interval_seconds: if self.stop.is_set(): break time.sleep(sleep_interval_seconds) i += sleep_interval_seconds # to prevent the final empty queue log message if self.stop.is_set(): break self.tile_proc_logger.log_queue_sizes(self.queue_info) self.tile_proc_logger.lifecycle('queue printer stopped')
thanhnghiacntt/tilequeue
tilequeue/worker.py
worker.py
py
24,574
python
en
code
0
github-code
6
73832973307
import numpy as np from .anim_utils.animation_data.joint_constraints import JointConstraint def normalize(v): return v/np.linalg.norm(v) def array_from_mosim_t(_t): t = np.zeros(3) t[0] = -_t.X t[1] = _t.Y t[2] = _t.Z return t def array_from_mosim_q(_q): q = np.zeros(4) q[0] = -_q.W q[1] = -_q.X q[2] = _q.Y q[3] = _q.Z q = normalize(q) return q def array_from_mosim_r(r): q = quaternion_from_euler(-np.radians(r.X), np.radians(r.Y), np.radians(r.Z)) return q def set_static_joints(skeleton, default_joint_names=["left_clavicle", "right_clavicle"]): for j in default_joint_names: joint_name = None if j in skeleton.skeleton_model["joints"]: joint_name = skeleton.skeleton_model["joints"][j] c = JointConstraint() c.is_static = True skeleton.nodes[joint_name].joint_constraint = c def get_inverted_joint_map(joint_map): inverted_map = dict() for name in joint_map: key = joint_map[name] inverted_map[key] = name return inverted_map def map_joint_to_skeleton(skeleton, side): if side == "Left": default_joint_name = "left_wrist" else: default_joint_name = "right_wrist" joint_name = None if default_joint_name in skeleton.skeleton_model["joints"]: joint_name = skeleton.skeleton_model["joints"][default_joint_name] return joint_name def get_chain_end_joint(skeleton, side): if side == "Left": default_joint_name = "left_clavicle" else: default_joint_name = "right_clavicle" joint_name = None if default_joint_name in skeleton.skeleton_model["joints"]: joint_name = skeleton.skeleton_model["joints"][default_joint_name] return joint_name def get_long_chain_end_joint(skeleton): default_joint_name = "spine_1" joint_name = None if default_joint_name in skeleton.skeleton_model["joints"]: joint_name = skeleton.skeleton_model["joints"][default_joint_name] return joint_name def generate_constraint_desc(joint, keyframe_label, target_transform, set_orientation, hold_frame, look_at, scale): c_desc = dict() c_desc["keyframe"] = keyframe_label c_desc["position"] = array_from_mosim_t(target_transform.Position)*scale if set_orientation: c_desc["orientation"] = array_from_mosim_q(target_transform.Rotation) else: c_desc["orientation"] = None c_desc["constrainOrientation"] = set_orientation c_desc["joint"] = joint print("set hand target", c_desc["position"], c_desc["orientation"], target_transform.Rotation) c_desc["hold"] = hold_frame return c_desc def generate_action_desc(action_name, constraints, look_at): action_desc = dict() action_desc["name"] = action_name action_desc["frameConstraints"] = constraints action_desc["lookAtConstraints"] = look_at return action_desc
mercedes-benz/MOSIM_Core
BasicMMus/Python-MMUs/MGReach/utils.py
utils.py
py
2,927
python
en
code
16
github-code
6
43193627416
#!/usr/bin/env python import rospy import smach from PrintColours import * from std_msgs.msg import String class Idle(smach.State): def __init__(self,pub,autopilot,uav_id):#modify, common_data smach.State.__init__( self, outcomes=['gcs_connection', 'shutdown']) self.pub = pub self.autopilot = autopilot self.uav_id = uav_id def execute(self, ud): rospy.loginfo('[Idle] - Idle state') airframe_pub = rospy.Publisher("/uav_{}_sm/com/airframe_type".format(self.uav_id), String, queue_size=10) mission_state_pub = rospy.Publisher("/uav_{}_sm/com/mission_state".format(self.uav_id), String, queue_size=10) if self.autopilot == "px4": airframe = self.autopilot + "/vtol" if self.autopilot == "dji": airframe = self.autopilot + "/M210" # transition to gcs_connection state while not rospy.is_shutdown(): airframe_pub.publish(airframe) mission_state_pub.publish("idle") if self.autopilot == "px4": rospy.loginfo(CBLUE2 +'There are %d connections to the topic of PX4'+CEND, self.pub.get_num_connections())# Modify if self.autopilot == "dji": rospy.loginfo(CBLUE2 +'There are %d connections to the topic of DJI'+CEND, self.pub.get_num_connections()) if self.pub.get_num_connections() > 1: return 'gcs_connection' rospy.sleep(0.2) return 'shutdown'
miggilcas/muav_state_machine
scripts/AgentStates/idle.py
idle.py
py
1,523
python
en
code
0
github-code
6
22963907434
import urllib3 # 忽略警告:InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. urllib3.disable_warnings() import json import os # http://www.meituan.com/meishi/api/poi/getMerchantComment?id=42913246&offset=0&pageSize=50&sortType=1 COMMENT_URL = 'http://www.meituan.com/meishi/api/poi/getMerchantComment?id={}&offset={}&pageSize=50&sortType=1' # DIVIDER = '\n' + '=' * 200 + '\n' DIVIDER = '\n\n\n' def repeat(func, retry=10): success = False response = None try: response = func() success = response.code == 200 except: pass if not success and retry > 0: repeat(func, retry - 1) return response def get_comment(id, offset=0, result=None, save_dir=None, sub_dir=False): # result = [] if result is None else result url = COMMENT_URL.format(id, offset) response = urllib3.PoolManager().request('GET', url, headers={ 'Host': 'www.meituan.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', # 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Cookie': 'uuid=d9f34299c1aa4700b57b.1533529950.1.0.0; _lx_utm=utm_source%3Dgoogle%26utm_medium%3Dorganic; _lxsdk_cuid=1650d8210c2c8-01cc48fa57f124-336b7b05-13c680-1650d8210c3c8; __mta=147110536.1533529952707.1533529952707.1533529952707.1; ci=50; client-id=4fb967a2-deb0-4c90-8408-2def9dc61c9a; oc=-3SKHsosP2d57O95hCYTmTexMhVqo4FIr5jQcztD5J5u_GXn3LjVWWou3uvfqHm4cPOGIMmgH3hNpYXXqbtqA66xGDYgxq8SWnCYIRpidQP13Wxum7XxTcrTNbJC_8r_5xlRsKULCrAWTz-CPQfr6HgZM1gLCuOpCxBnDwi_9JQ; lat=30.207471; lng=120.208933', }) # response = urllib2.urlopen(request) # response = repeat(lambda: urllib.urlopen(request)) if not response: return result comments = None try: text = response.data.decode() json_data = json.loads(text, encoding='utf-8') data = json_data['data'] comments = data['comments'] except: return if comments and result: result.extend(comments) n_comments = len(comments) if comments else 0 if sub_dir and save_dir: filename = 'data.txt' final_save_dir = os.path.join(save_dir, str(id), '%05d_%02d' % (offset // 50, n_comments)) else: final_save_dir = './' filename = 'comment_%d.txt' % id filepath = os.path.join(final_save_dir, filename) save_2_json(comments, filepath) total = data['total'] offset += n_comments if offset < total - 1: get_comment(id, offset, result, save_dir, sub_dir) return result def save_2_json(comments, save_dir): if not comments: return dirname = os.path.abspath(os.path.dirname(save_dir)) if not os.path.isdir(dirname): os.makedirs(dirname) with open(save_dir, 'a', encoding='utf-8') as f: for c in comments: # get = lambda name: (c[name].encode('utf-8')) if c[name] else '' get = lambda name: c[name] if c[name] else '' menu = get('menu') text = get('comment') if not text: continue star = c['star'] item = 'menu = %s\nstar = %s\ntext = %s' % (menu, star / 5, text) f.write(item + DIVIDER) print(text) def dump_comment_data(id, save_dir=None, sub_dir=False): save_dir = save_dir or get_root_path('data/comment') get_comment(id, save_dir=save_dir, sub_dir=sub_dir) def get_root_path(relative=None): relative = relative or '' root_dir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(root_dir, relative) if __name__ == '__main__': # dump_comment_data(42913246, save_dir='data/comment') dump_comment_data(42913246) # print(get_root_path()) # print(get_root_path('data'))
puke3615/comment_spider
comment_spider/util.py
util.py
py
4,172
python
en
code
5
github-code
6
5139284225
def getobjectgroups(DATA) -> list: result = list() ogroup = dict() ogroup['items'] = list() ogroup_detected = False for _ in DATA: data = _.strip().split() if len(data) == 0: continue if data[0] == "object-group": ogroup_detected = True ogroup["name"] = data[2] ogroup["type"] = data[1] if ogroup_detected: if data[0] == "!": result.append(ogroup) ogroup = dict() ogroup['items'] = list() ogroup_detected = False else: if data[0] == "description": ogroup["description"] = ' '.join(map(str, data[1:])) if data[0] == "host": ogroup['items'].append(("host", data[1])) if data[0] == "group-object": ogroup['items'].append(("group-object", data[1])) if data[0][0].isdigit(): ogroup['items'].append(("network", data[0], data[1])) return result
Rel1ct0/Convert2FortiGate
Scripts/IOS/getobjectgroups.py
getobjectgroups.py
py
1,074
python
en
code
0
github-code
6
33645109204
from __future__ import print_function import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from datetime import datetime, timedelta calendar_id = os.environ.get('calendar_id') SCOPES = ['https://www.googleapis.com/auth/calendar'] def connect(): creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=8080) # Save the credentials for the next run with open("token.json", 'w') as token: token.write(creds.to_json()) return build('calendar', 'v3', credentials=creds) def create_event(service, event): try: eventAdded = service.events().insert(calendarId=calendar_id, body=generate_json(event)).execute() print(f'added {event.name} {event.date} {event.eventId}') except Exception as e: save_error("creating", event.name, e) def delete_event(service, event): if event.eventId is not None: try: service.events().delete(calendarId=calendar_id, eventId=event.eventId).execute() except Exception as e: save_error("deleting", event.name, e) def update_event(service, event): try: service.events().update(calendarId=calendar_id, eventId=event.eventId, body=generate_json(event)).execute() except Exception as e: save_error("updating", event.name, e) def generate_json(event): if event.status == 'Urgente': event.icon = "⭐" elif event.progress == 100 or event.status == 'Completado': event.icon = "✔️" if event.type=="Exam": color = 11 elif event.type == "Assignment": color = 4 else: color = 6 #We have to differentiate between the yyy-mm-dd format and the RFC3339 format. #In the case of all day events, for Notion, the start day and the end day is the same, for G. Calendar the end day is the next one. if len(event.date)>11:date = datetype = "dateTime" else: datetype = "date"; event.endDate = datetime.strftime(datetime.strptime(event.endDate, '%Y-%m-%d') + timedelta(1),'%Y-%m-%d') event_to_add = { 'id': event.eventId, 'colorId':color, 'summary': f'{event.icon} {event.type[:1]}. {event.subject} {event.name} ', 'description': f'{event.type}. of {event.subject}: {event.name} \n{event.comments} \n {f"Progreso: {str(event.progress)}" if event.progress >=0 else ""} Status: {event.status}', 'start': { datetype : event.date, }, 'end': { datetype : event.endDate, }, 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'popup', 'minutes': 10080}, #1 week ], }, } return event_to_add def save_error(type, name, msg = ""): text = f"{datetime.now()} --> Error while {type} the following event: {name} \n" file_object = open('errors.log', 'a') file_object.write(text) print (f"{text} \n {msg}") file_object.close()
Santixs/NotionGSync
gcalendarsync.py
gcalendarsync.py
py
3,727
python
en
code
1
github-code
6
8774738477
import gym import numpy as np from cartpole_deep_net import CartpoleDeepNet class CartPole: def __init__(self, render_mode='None'): self.env_title = 'CartPole-v1' self.env=gym.make(self.env_title, render_mode=render_mode) self.single_state_shape_len = 1 self.desired_mean_score = 130 self.observation_space_shape = self.env.observation_space.shape self.no_of_actions = self.env.action_space.n self.hidden_layers = [128] self.model = CartpoleDeepNet(self.observation_space_shape[0], self.hidden_layers, self.no_of_actions) self.model_file_name = 'cartpole_model.pth' self.reset() def reset(self): self.score = 0 self.state = self.env.reset() def get_state(self): if len(self.state) != self.observation_space_shape[0]: return self.state[0] return self.state def play_step(self, action): move = action.index(1) (state, reward, terminated, truncated , _) = self.env.step(move) done = truncated or terminated self.state = state if not done: self.score += 1 return reward, done, self.score
asharali001/Deep-Q-Learning
cartpole.py
cartpole.py
py
1,231
python
en
code
0
github-code
6
39293592719
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while True: city =input('\n choose city to filter by?chicago, new york city, washington?\n') city=city.lower() if city not in ('chicago', 'new york city', 'washington'): print("Sorry, Try again") continue else: break # TO DO: get user input for month (all, january, february, ... , june) while True: month=input("\n choose month that you want filter by? january, february, ... , june or all\n ") month=month.lower() if month not in ('january','february','march','april','may','june','all'): print("Sorry, Try again") continue else: break # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) while True: day=input("\n choose day that you want filter by? satuerday,sunday, monday,tuesday,wednesday,thursday,friday or all \n ") day=day.lower() if day not in ('sunday','monday','tuesday','wednesday','thursday','friday','saturday','all'): print("Sorry, Try again") continue else: break print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df =pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name if month != 'all': months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 df = df[df['month'] == month] if day != 'all': df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month popular_month=df['month'].mode()[0] print ("Most common month:",popular_month) # TO DO: display the most common day of week popular_day=df['day_of_week'].mode()[0] print ("Most common day:",popular_day) # TO DO: display the most common start hour df['hour'] = df['Start Time'].dt.hour popular_hour = df['hour'].mode()[0] print ("Most common hour:",popular_hour) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station Start_Station=df['Start Station'].mode()[0] print("most commonly used start station:",Start_Station) # TO DO: display most commonly used end station End_Station=df['End Station'].mode()[0] print("most commonly used End station:",End_Station) # TO DO: display most frequent combination of start station and end station trip df['combination']=df['Start Station'].map(str)+'&'+df['End Station'] combination=df['combination'].value_counts().idxmax() print("most commonly used Combination of start and end station trip:",combination) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time try: df['Time Delta']=df['End Time']-df['Start Time'] total_time=df['Time Delta'].sum() print("total travel time :",total_time) except Exception as e: print("couldn't calculate total travel time") # TO DO: display mean travel time try: total_mean=df['Time Delta'].mean() print("the mean travel time :",total_mean) except Exception as e: print("couldn't calculate the mean travel time") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types user_types=df['User Type'].value_counts() print('user types:\n',user_types) # TO DO: Display counts of gender if 'Gender' in df: gender = df['Gender'].value_counts() print("Gender:\n",gender) else: print("There is no gender information in this city.") # TO DO: Display earliest, most recent, and most common year of birth if 'Birth_Year' in df: earliest = df['Birth_Year'].min() print("earliest :\n",earliest) recent = df['Birth_Year'].max() print("recent :\n",recent) common_birth = df['Birth Year'].mode()[0] print("common_birth :\n",common_birth) else: print("There is no birth year information in this city.") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
WaadShehab/Explore_US_Bikeshare_Data
bikeshare.py
bikeshare.py
py
6,672
python
en
code
0
github-code
6
33725319623
import qiskit_toqm.native as toqm class ToqmHeuristicStrategy: def __init__(self, latency_descriptions, top_k, queue_target, queue_max, retain_popped=1): """ Constructs a TOQM strategy that aims to minimize overall circuit duration. The priority queue used in the A* is configured to drop the worst nodes whenever it reaches the queue size limit. Node expansion is also limited to exploring the best ``K`` children. Args: latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions for all gates that will appear in the circuit, including swaps. top_k (int): The maximum number of best child nodes that can be pushed to the queue during expansion of any given node. queue_target (int): When the priority queue reaches capacity, nodes are dropped until the size reaches this value. queue_max (int): The priority queue capacity. retain_popped (int): Final nodes to retain. Raises: RuntimeError: No routing was found. """ # The following defaults are based on: # https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt self.mapper = toqm.ToqmMapper( toqm.TrimSlowNodes(queue_max, queue_target), toqm.GreedyTopK(top_k), toqm.CXFrontier(), toqm.Table(list(latency_descriptions)), [toqm.GreedyMapper()], [], 0 ) self.mapper.setRetainPopped(retain_popped) def __call__(self, gates, num_qubits, coupling_map): """ Run native ToqmMapper and return the native result. Args: gates (List[toqm.GateOp]): The topologically ordered list of gate operations. num_qubits (int): The number of virtual qubits used in the circuit. coupling_map (toqm.CouplingMap): The coupling map of the target. Returns: toqm.ToqmResult: The native result. """ return self.mapper.run(gates, num_qubits, coupling_map) class ToqmOptimalStrategy: def __init__(self, latency_descriptions, perform_layout=True, no_swaps=False): """ Constructs a TOQM strategy that finds an optimal (minimal) routing in terms of overall circuit duration. Args: latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions for all gates that will appear in the circuit, including swaps. perform_layout (Boolean): If true, permutes the initial layout rather than inserting swap gates at the start of the circuit. no_swaps (Boolean): If true, attempts to find a routing without inserting swaps. Raises: RuntimeError: No routing was found. """ # The following defaults are based on: # https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt self.mapper = toqm.ToqmMapper( toqm.DefaultQueue(), toqm.NoSwaps() if no_swaps else toqm.DefaultExpander(), toqm.CXFrontier(), toqm.Table(latency_descriptions), [], [toqm.HashFilter(), toqm.HashFilter2()], -1 if perform_layout else 0 ) def __call__(self, gates, num_qubits, coupling_map): """ Run native ToqmMapper and return the native result. Args: gates (List[toqm.GateOp]): The topologically ordered list of gate operations. num_qubits (int): The number of virtual qubits used in the circuit. coupling_map (toqm.CouplingMap): The coupling map of the target. Returns: toqm.ToqmResult: The native result. """ return self.mapper.run(gates, num_qubits, coupling_map)
qiskit-toqm/qiskit-toqm
src/qiskit_toqm/toqm_strategy.py
toqm_strategy.py
py
3,866
python
en
code
6
github-code
6
23060222816
import math import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches compdata=np.loadtxt('compdata.txt') agelabel=compdata[:,0] compdata=compdata[:,1] obsdata=np.loadtxt('obsdata.txt') error=obsdata[:,3] obsdata=obsdata[:,1] #plt.plot(agelabel, compdata, 'r',label='Computed data') plt.errorbar(agelabel, obsdata, yerr=error,fmt='',label='Observational data') #legend = plt.legend(loc='upper left', shadow=True) plt.ylim(ymin=0.1) plt.xlabel('$\mathrm{t}/\mathrm{t}_{ms}$') plt.ylabel('Probability Density') plt.show()
AndreasMu/Bachelor
Graphs and Tex/obsdataplot.py
obsdataplot.py
py
554
python
en
code
0
github-code
6
44665541614
import random l = ["O", "P"] k = [] count = 0 s = 10 while s: x = random.randint(0, 1) k.append(x) for i in range(len(k)-2): if k[i] + k[i+2] == 0: print("O") print(k) elif k[i] + k[i+2] == 2: print("P") print(k) s-=1 # n = int(input('Введите число:')) # while n: # x = random.randint(1, 2) # if x == 1: # print ('Орел') # else: # print ('Решка') # n -= 1
AkulaBiznesu/training
_Coin x3.py
_Coin x3.py
py
499
python
en
code
0
github-code
6
31534048424
import telebot; import os import subprocess import re #получение токена при запуске и возможно его сохранение file = open("Token", "r") token = file.read() file.close() bot = telebot.TeleBot(token) os.system("echo запущено") @bot.message_handler(content_types=['text']) def get_text_messages(message): if message.text == "/start": bot.send_message(message.from_user.id, "bashbot для Телеграмм список основных команд /help") elif message.text == "/help": bot.send_message(message.from_user.id, "здесь пока что пусто") ## else: comm_out=(b'',) lst = message.text.split(' ') print(lst[0]) if (lst[0] == 'cd'): del lst[0] if not lst: lst = ['/root'] path="".join(lst) try: os.chdir(path) except FileNotFoundError: bot.send_message(message.from_user.id, "No such file or directory") else: comm = subprocess.Popen('pwd', stdout=subprocess.PIPE) comm_out = comm.communicate() elif(lst[0] == 'echo'): comm = subprocess.Popen(lst, stdout=subprocess.PIPE) comm_out = comm.communicate() print(comm_out)## elif(lst[0] == 'export'): c = "".join(lst) print(message.text) os.system(message.text) bot.send_message(message.from_user.id, "не готово")## else: try: comm = subprocess.Popen(message.text.split(' '), stdout=subprocess.PIPE) comm_out = comm.communicate() print(comm_out) except FileNotFoundError: bot.send_message(message.from_user.id, "No such file or directory") if (comm_out[0] != b''): bot.send_message(message.from_user.id, comm_out) bot.polling(none_stop=True, interval=0) #сделать логи по ID #добавить clear
romazanovma/probable-octo-potato-telegram-bot
bot.py
bot.py
py
1,759
python
ru
code
0
github-code
6
74197622589
from rest_framework import serializers from des.models import Exposure, SkybotJob, SkybotJobResult class SkybotJobResultSerializer(serializers.ModelSerializer): # job = serializers.PrimaryKeyRelatedField( # queryset=SkybotJob.objects.all(), many=False # ) # exposure = serializers.PrimaryKeyRelatedField( # queryset=Exposure.objects.all(), many=False # ) job = serializers.PrimaryKeyRelatedField( read_only=True ) exposure = serializers.PrimaryKeyRelatedField( read_only=True ) ticket = serializers.SerializerMethodField() band = serializers.SerializerMethodField() date_obs = serializers.SerializerMethodField() ccds = serializers.SerializerMethodField() class Meta: model = SkybotJobResult fields = ( "id", "job", "exposure", "ticket", "success", "error", "execution_time", "ccds", "ccds_with_asteroids", "positions", "inside_ccd", "outside_ccd", "filename", "band", "date_obs", ) def get_ticket(self, obj): try: return str(obj.ticket) except: return None def get_band(self, obj): try: return obj.exposure.band except: return None def get_date_obs(self, obj): try: return obj.exposure.date_obs except: return None def get_ccds(self, obj): try: return obj.exposure.ccd_set.count() except: return 0
linea-it/tno
backend/des/serializers/skybot_job_result.py
skybot_job_result.py
py
1,678
python
en
code
1
github-code
6
22134160802
from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'home'), path('about', views.about, name = 'about'), path('create', views.create, name = 'create'), path('review', views.review, name = 'review'), path('test1', views.test1, name = 'test1'), path('<int:pk>', views.TaskDetailView.as_view(), name='detail_task'), path('<int:pk>/update_task', views.TaskUpdateView.as_view(), name='update_task'), path('<int:pk>/delete_task', views.TaskDeleteView.as_view(), name='delete_task'), ]
Voron4ikhin/Web_lab
taskmanager/main/urls.py
urls.py
py
553
python
en
code
0
github-code
6
11975286960
from socket import * from ssl import * from _ssl import PROTOCOL_TLSv1 finished = False client_socket = socket(AF_INET, SOCK_STREAM) tls_client = wrap_socket(client_socket, ssl_version=PROTOCOL_TLSv1, cert_reqs=CERT_NONE) address = 'localhost' port = 6668 bufsize = 1024 tls_client.connect((address, port)) while not finished: message = 'Hello World!' data_out = message.encode(encoding='utf_8', errors='strict') tls_client.send(data_out) repeat = input('yes or no?') if repeat == 'n': finished = True client_socket.send(b'quit') client_socket.shutdown(SHUT_RDWR) client_socket.close()
SamXSu/458Project
client/client.py
client.py
py
697
python
en
code
0
github-code
6
25791786011
import sys class Shift: def encrypt(self, plain, a): cipher = '' for ch in plain: i = char_to_int(ch) i = (i + a) % 26 ch = int_to_char(i) cipher += ch return cipher def decrypt(self, cipher, a): plain = '' for ch in cipher: i = char_to_int(ch) i = (i - a + 26) % 26 ch = int_to_char(i) plain += ch return plain class Affine: def encrypt(self, plain, a, b): cipher = '' for ch in plain: i = char_to_int(ch) i = (a * i + b) % 26 ch = int_to_char(i) cipher += ch return cipher def decrypt(self, cipher, a, b): plain = '' for ch in cipher: i = char_to_int(ch) if mul_inverse(a, 26) == -1: return 'Can\'t decrypt the message, {} and 26 are coprimes'.format(a) i = ((i - b + 26) * mul_inverse(a, 26)) % 26 ch = int_to_char(i) plain += ch return plain class Vigenere: def generate_full_key(self, text, key): full_key = '' idx = 0 while len(full_key) < len(text): full_key += key[idx] idx = (idx + 1) % len(key) return full_key def encrypt(self, plain, key): key = self.generate_full_key(plain, key) cipher = '' for idx in range(len(key)): i = (char_to_int(plain[idx]) + char_to_int(key[idx])) % 26 ch = int_to_char(i) cipher += ch return cipher def decrypt(self, cipher, key): key = self.generate_full_key(cipher, key) plain = '' for idx in range(len(key)): i = (char_to_int(cipher[idx]) - char_to_int(key[idx]) + 26) % 26 ch = int_to_char(i) plain += ch return plain def char_to_int(ch): return ord(ch) - ord('A') def int_to_char(i): return chr(i + ord('A')) def mul_inverse(x, mod): for i in range(mod): if (x * i) % mod == 1: return i return -1 if __name__ == '__main__': args = sys.argv algorithm, operation, in_file, out_file = args[1:5] in_file = open(in_file, 'r') text = in_file.read() in_file.close() ans = None if algorithm == 'shift': shift = Shift() a = int(args[-1]) if operation[0] == 'e': ans = shift.encrypt(text, a) else: ans = shift.decrypt(text, a) elif algorithm == 'affine': affine = Affine() a, b = int(args[-2]), int(args[-1]) if(operation[0] == 'e'): ans = affine.encrypt(text, a, b) else: ans = affine.decrypt(text, a, b) elif algorithm == 'vigenere': vigenere = Vigenere() key = args[-1] if(operation[0] == 'e'): ans = vigenere.encrypt(text, key) else: ans = vigenere.decrypt(text, key) out_file = open(out_file, 'w') out_file.write(str(ans)) out_file.close()
Ismail-Mahmoud/Cryptography-Assignments
Assignment1/ciphers.py
ciphers.py
py
3,088
python
en
code
0
github-code
6
71200356027
from moviepy.editor import * from moviepy.video.tools.subtitles import SubtitlesClip import moviepy.video.fx as vfx def create_srt(line): subs_obj = open(r"D:\Final Renders\your next line.srt", "r") orig_subs = subs_obj.read().split("\n") print(orig_subs) orig_subs[6] = f"\"{line}\"" orig_subs[10] = line new_srt = open(r"D:\Final Renders\result.srt", "w") for x in orig_subs: new_srt.write(x + "\n") new_srt.close() subs_obj.close() def composite_gif(line): video = VideoFileClip(r"D:\Final Renders\tsuginiomaewa.mp4") video = vfx.resize.resize(video,0.5) generator = lambda txt: TextClip(txt, font='Arial',fontsize=16, color='white') create_srt(line) sub = SubtitlesClip(r"D:\Final Renders\result.srt", generator) result = CompositeVideoClip([video, sub.set_position(('center','bottom'))]) result.write_gif(r"D:\Final Renders\result.gif",fps=10,program="ffmpeg", fuzz=100,colors=2) result.close() video.close()
alwynwan/Messenger-Bot
srtgen.py
srtgen.py
py
1,002
python
en
code
0
github-code
6
17335047402
import sesame import numpy as np ###################################################### ## define the system ###################################################### # dimensions of the system Lx = 3e-4 #[cm] Ly = 3e-4 #[cm] # extent of the junction from the left contact [cm] junction = .1e-4 # [cm] # Mesh x = np.concatenate((np.linspace(0,.2e-4, 30, endpoint=False), np.linspace(0.2e-4, 1.4e-4, 60, endpoint=False), np.linspace(1.4e-4, 2.9e-4, 70, endpoint=False), np.linspace(2.9e-4, 3e-4, 10))) y = np.concatenate((np.linspace(0, 1.75e-4, 50, endpoint=False), np.linspace(1.75e-4, 2.75e-4, 50, endpoint=False), np.linspace(2.75e-4, Ly, 50))) # Create a system sys = sesame.Builder(x, y, periodic=False) # Dictionary with the material parameters mat = {'Nc':8e17, 'Nv':1.8e19, 'Eg':1.5, 'epsilon':9.4, 'Et': 0, 'mu_e':320, 'mu_h':40, 'tau_e':10*1e-9, 'tau_h':10*1e-9, 'B': 1e-10} # Add the material to the system sys.add_material(mat) # define a function specifiying the n-type region def region(pos): x, y = pos return x < junction # define a function specifiying the p-type region region2 = lambda pos: 1 - region(pos) # Add the donors nD = 1e17 # [cm^-3] sys.add_donor(nD, region) # Add the acceptors nA = 1e15 # [cm^-3] sys.add_acceptor(nA, region2) # Use Ohmic contacts Sn_left, Sp_left, Sn_right, Sp_right = 1e7, 1e7, 1e7, 1e7 sys.contact_S(Sn_left, Sp_left, Sn_right, Sp_right) sys.contact_type('Ohmic','Ohmic') # gap state characteristics E = 0 # energy of gap state (eV) from midgap rhoGB = 1e14 # density of defect states s = 1e-14 # defect capture cross section # this implies a surface recombination velocity S = rhoGB*s*vthermal = 1e5 [cm/s] # Specify the two points that make the line containing additional recombination centers p1 = (0, Ly) p2 = (Lx, Ly) # add neutral defect along surface (surface recombination boundary condition) sys.add_defects([p1, p2], rhoGB, s, E=E, transition=(0,0)) # find equilibrium solution with GB. Note we provide the GB-free equilibrium solution as a starting guess solution = sesame.solve(sys, compute='Poisson', periodic_bcs=False) ###################################################### ## EBIC generation profile parameters ###################################################### q = 1.6e-19 # C ibeam = 10e-12 # A Ebeam = 15e3 # eV eg = 1.5 # eV density = 5.85 # g/cm^3 kev = 1e3 # eV # rough approximation for total carrier generation rate from electron beam Gtot = ibeam/q * Ebeam / (3*eg) # length scale of generation volume Rbulb = 0.043 / density * (Ebeam/kev)**1.75 # given in micron Rbulb = Rbulb * 1e-4 # converting to cm # Gaussian spread sigma = Rbulb / np.sqrt(15) # penetration depth y0 = 0.3 * Rbulb # get diffusion length to scale generation density vt = .0258 Ld = np.sqrt(sys.mu_e[0] * sys.tau_e[0]) * sys.scaling.length ###################################################### ## vary position of the electron beam ###################################################### x0list = np.linspace(.1e-4, 2.5e-4, 11) # Array in which to store results jset = np.zeros(len(x0list)) jratio = np.zeros(len(x0list)) rset = np.zeros(len(x0list)) rad_ratio = np.zeros(len(x0list)) # Cycle over beam positions for idx, x0 in enumerate(x0list): # define a function for generation profile def excitation(x,y): return Gtot/(2*np.pi*sigma**2*Ld) * np.exp(-(x-x0)**2/(2*sigma**2)) * np.exp(-(y-Ly+y0)**2/(2*sigma**2)) # add generation to the system at new beam position sys.generation(excitation) # solve the system solution = sesame.solve(sys, periodic_bcs=False, tol=1e-8) # get analyzer object to evaluate current and radiative recombination az = sesame.Analyzer(sys, solution) # compute (dimensionless) current and convert to to dimension-ful form tj = az.full_current() * sys.scaling.current * sys.scaling.length # save the current jset[idx] = tj # obtain total generation from sys object gtot = sys.gtot * sys.scaling.generation * sys.scaling.length**2 jratio[idx] = tj/(q * gtot) # compute (dimensionless) total radiative recombination and convert to to dimension-ful form cl = az.integrated_radiative_recombination() * sys.scaling.generation * sys.scaling.length**2 # save the CL rset[idx] = cl rad_ratio[idx] = cl/gtot # display result for counter in range(len(jset)): print('x = {0:2.1e} [cm], J = {1:5.3e} [mA/cm], CL = {2:5.3e}'.format(x0list[counter],jset[counter]*1e3,rset[counter])) for counter in range(len(jset)): print('x = {0:2.1e} {1:5.3e} {2:5.3e}'.format(x0list[counter],jratio[counter],rad_ratio[counter])) import matplotlib.pyplot as plt plt.plot(x0list,jset) plt.show()
usnistgov/sesame
examples/tutorial5/2d_EBIC.py
2d_EBIC.py
py
4,876
python
en
code
16
github-code
6
3643899773
import random import time isim = input("Merhaba! İsminiz nedir ?") print("Sayı tahmin oyununa hoşgeldin") print("Şimdi 1-50 arası sayı tahmin et",isim) secilen = random.randint(1,50) #1-50 arası random sayı üretir can = 6 while True: deger = int(input("Tahmin ettiğin sayı: ")) if(deger < secilen): print("Bakalım bilebilecek misin, sorgulanıyor..") time.sleep(1) print("Bilemedin! Daha büyük bir sayı söyle!!") can -= 1 elif(deger > secilen): print("Acaba? sorgulanıyor..") time.sleep(1) print("Bilemedin! Daha küçük bir sayı söyle!!") can -= 1 else: time.sleep(1) print("Tebriklerr!!!! Kazandın ",isim) break if(can == 0): print("Kazanamadın...") print("Doğru tahmin: ",secilen) break
brcmst/python-tutorials
GuessingGame.py
GuessingGame.py
py
958
python
tr
code
0
github-code
6
71913849148
import requests API_ENDPOINT = 'https://api.openai.com/v1/chat/completions' API_KEY = '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' MODEL_ID = 'gpt-3.5-turbo' def test_chatgpt_api(): headers = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' } data = { 'model': MODEL_ID, 'messages': [{'role': 'system', 'content': 'Test message'}] } response = requests.post(API_ENDPOINT, headers=headers, json=data) if response.status_code == 200: print("API is working normally.") else: print("API request failed. Status code:", response.status_code) print("Response:", response.json()) # Call the function to test the API test_chatgpt_api()
Ali-Jabowr/TelegramWordBot
commands/chatgpt_testing.py
chatgpt_testing.py
py
777
python
en
code
0
github-code
6
7650485189
# Author hugo # Time 2023/8/11 13:02 ''' 学生信息管理系统 ''' import os.path ''' 需求分析 系统设计 系统开发必备 主函数设计 学生信息维护模块设计 查询/统计模块设计 排序模块设计 项目打包 ''' # 需求分析 ''' 学生管理系统应具备的功能 添加学生及成绩信息 将学生信息保存到文件中 修改和删除学生信息 查询学生信息 根据学生成绩进行排序 统计学生的总分 ''' # 系统设计 ''' 系统功能结构 学生信息管理系统的7大模块 录入学生信息模块 查找学生信息模块 删除学生信息模块 修改学生信息模块 学生成绩排名模块 统计学生总人数模块 显示全部学生信息模块 系统业务流程 用户->主界面->功能菜单->y or n ''' # 系统开发必备 ''' 系统开发环境 操作系统 Python解释器版本 开发工具 Python内置模块 项目目录结构 ''' # 主函数设计 ''' 主函数的业务流程 开始 -> while True -> 显示主菜单 -> 选择菜单项 0 --- 退出系统 1 --- 录入学生信息,调用insert()函数 2 --- 查找学生信息,调用search()函数 3 --- 删除学生信息,调用delete()函数 4 --- 修改学生信息,调用modify()函数 5 --- 对学生成绩进行排序,调用sort()函数 6 --- 统计学生总人数,调用total()函数 7 --- 显示所有学生的信息,调用show()函数 ''' filename = 'student.txt' def main(): while True: menm() choice = int(input('请选择')) if choice in range(0, 8): if choice == 0: answer = input('您确定要退出系统吗?y/n') if answer == 'y' or answer == 'Y': print('谢谢您的使用!!!') break # 退出系统 else: continue elif choice == 1: insert() elif choice == 2: search() elif choice == 3: delete() elif choice == 4: modify() elif choice == 5: sort() elif choice == 6: total() elif choice == 7: show() def menm(): print('==================学生信息管理系统==================') print('---------------------功能菜单---------------------') print('\t\t\t\t 1.录入学生信息') print('\t\t\t\t 2.查找学生信息') print('\t\t\t\t 3.删除学生信息') print('\t\t\t\t 4.修改学生信息') print('\t\t\t\t 5.排序') print('\t\t\t\t 6.统计学生总人数') print('\t\t\t\t 7.显示所有学生信息') print('\t\t\t\t 0.退出') print('-------------------------------------------------') ''' 业务流程 开始 -> while True -> 输入学生姓名或者ID -> 判断是否有输入 -> 输入成绩 -> 保存到列表中 -> 判断是否继续 -> 结束后保存到文件中 具体实现 save(student) 函数,用于将学生信息保存到文件 insert()函数,用于录入学生信息 ''' def insert(): student_list = [] while True: id = input('请输入ID(如1001)') if not id: break name = input('请输入姓名') if not name: break try: english = int(input('请输入英语成绩')) python = int(input('请输入Python成绩')) java = int(input('请输入Java成绩')) except: print('输入无效,不是整数类型,请重新输入') continue # 将录入的学生信息保存到字典中 student = {'id': id, 'name': name, 'english': english, 'python': python, 'java': java} # 将学生信息添加到列表中 student_list.append(student) answer = input('是否继续添加学生信息?y/n\n') if answer == 'y' or answer == 'Y': continue else: break # 调用save()函数 save(student_list) print('学生信息录入完毕!!!') def save(lst): try: stu_txt = open(filename, 'a', encoding='utf-8') except: stu_txt = open(filename, 'w', encoding='utf-8') for item in lst: stu_txt.write(str(item) + '\n') stu_txt.close() ''' while True -> 判断输入是否为1或2 -> 输入学生ID或姓名 -> 读取学生信息列表 -> 遍历列表并将符合条件的信息保存到新列表 ->显示新列表的内容并显示是否继续 ''' def search(): student_query = [] while True: id = '' name = '' if os.path.exists(filename): mode = input('按ID查找请输入1,按姓名输入查找请输入2') if mode == '1': id = input('请输入学生ID') elif mode == '2': name = input('请输入学生姓名') else: print('您的输入有误,请重新输入') search() with open(filename, 'r', encoding='utf-8') as rfile: student = rfile.readlines() for item in student: d = dict(eval(item)) if id != '': if d['id'] == id: student_query.append(d) elif name != '': if d['name'] == name: student_query.append(d) # 显示查询结果 show_student(student_query) # 清空列表 student_query.clear() answer = input('是否要继续查询?y/n') if answer == 'y': continue else: break else: print('暂未保存该学员信息') return def show_student(lst): if len(lst) == 0: print('没有查询到学生信息,无数据显示') return # 定义标题的显示格式 format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}' print(format_title.format('ID', '姓名', '英语成绩', 'Python成绩', 'java成绩', '总成绩')) # 定义内容的显示格式 format_data = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}\t{:^8}' for item in lst: print(format_data.format((item.get('id')), item.get('name'), item.get('english'), item.get('python'), item.get('java'), int(item.get('english')) + int(item.get('python')) + int(item.get('java')))) ''' 实现删除学生信息功能 从控制台录入学生ID,到磁盘文件中找到对应的学生信息,并将其删除 业务流程 开始 -> while True -> 输入学生ID -> 判断是否有输入 -> 读取全部学生信息到列表 遍历列表并将不删除的信息重新写入文件 -> 希纳是全部学生信息,并选择是否继续 -> over 具体实现 编写主函数中调用的删除学生信息的函数delete() 调用了show()函数显示学生信息,该函数的功能将在后面完成 ''' def delete(): while True: student_id = input('请输入要删除的学生的ID') if student_id != '': if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as file: student_old = file.readlines() else: student_old = [] flag = False # 标记是否删除 if student_old: with open(filename, 'w', encoding='utf-8') as wfile: d = {} for item in student_old: d = dict(eval(item)) # 将字符串转成字典 if d['id'] != student_id: wfile.write(str(d) + '\n') else: flag = True if flag: print(f'id为{student_id}的学生信息已被删除') else: print(f'没有找到ID为{student_id}的学生信息') else: print('无学生信息') break show() answer = input('是否继续删除?y/n\n') if answer == 'y': continue else: break ''' 判断学生文件是否存在->读取全部学生列表->以写的模式打开文件 ->输入学生ID->输入新的学生信息->写入信息到文件->是否继续-> ''' def modify(): show() if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as rfile: student_old = rfile.readlines() else: return student_id = input('请输入要修改的学员ID:\n') with open(filename, 'w', encoding='utf-8') as wfile: for item in student_old: d = dict(eval(item)) if d['id'] == student_id: print('找到学生信息,可以修改他的相关信息了') while True: try: d['name'] = input('请输入姓名:') d['english'] = input('请输入英语成绩:') d['python'] = input('请输入python成绩') d['java'] = input('请输入java成绩') except: print('您的输入有误,请重新输入!!!') else: break wfile.write(str(d) + '\n') print('修改成功') else: wfile.write(str(d) + '\n') answer = input('是否继续修改其他学生信息?y/n') if answer == 'y': modify() def sort(): show() if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as rfile: student_list = rfile.readlines() student_new = [] for item in student_list: d = dict(eval(item)) student_new.append(d) else: return asc_or_desc = input('请选择(0.升序,1.降序)') if asc_or_desc == '0': asc_or_desc_bool = False elif asc_or_desc == '1': asc_or_desc_bool = True else: print('您的输入有误,请重新输入') sort() mode = input('请选择排序方式(0.按总成绩排序,1.按英语成绩排序,2.按python成绩排序,3.按java排序成绩排序') if mode == '0': student_new.sort(key=lambda x: int(x['english']) + int(x['python']) + int(x['java']), reverse=asc_or_desc_bool) elif mode == '1': student_new.sort(key=lambda x: int(x['english']), reverse=asc_or_desc_bool) elif mode == '2': student_new.sort(key=lambda x: int(x['python']), reverse=asc_or_desc_bool) elif mode == '3': student_new.sort(key=lambda x: int(x['java']), reverse=asc_or_desc_bool) else: print('您的输入有误,请重新输入') sort() show_student(student_new) ''' 统计学生总人数 判断学生文件在学生信息文件是否存在->读取全部信息到列表-> 判断列表是否不为空-> 统计学生人数并输出 ''' def total(): if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as rfile: students = rfile.readlines() if students: print(f'一共有{len(students)}名学生') else: print('还没有录入学生信息') else: print('暂未保存数据信息') ''' 判断学生信息文件是否存在->打开文件->读取全部信息到列表->将学生信息转换为字典并添加到列表中 ''' def show(): student_lst = [] if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as rfile: students = rfile.readlines() for item in students: student_lst.append(eval(item)) if student_lst: show_student(student_lst) else: print('暂未保存数据信息!!!') if __name__ == '__main__': main()
hjzts/python_code
python_study/exercise/学生信息管理系统.py
学生信息管理系统.py
py
12,248
python
zh
code
1
github-code
6
28639960700
#!/usr/bin/env python # -*- coding: utf-8 -*- import lldb import re import optparse import ds import shlex class GlobalOptions(object): symbols = {} @staticmethod def addSymbols(symbols, options, breakpoint): key = str(breakpoint.GetID()) GlobalOptions.symbols[key] = (symbols, options) def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( 'command script add -f breakifonfunc.breakifonfunc biof') def breakifonfunc(debugger, command, exe_ctx, result, internal_dict): ''' usage: biof regex1 [Optional_ModuleName] ||| regex2 ModuleName1 Regex breakpoint that stops only if the second regex breakpoint is in the stack trace For example, to only stop if code in the "Test" module resulted the setTintColor: being called biof setTintColor: ||| . Test ''' command_args = shlex.split(command, posix=False) parser = generateOptionParser() try: (options, args) = parser.parse_args(command_args) except: result.SetError("Error parsing") return # if len(args) >= 2: # result.SetError(parser.usage) # return target = exe_ctx.target # if len(command.split('|||')) != 2: # result.SetError(parser.usage) t = " ".join(args).split('|||') clean_command = t[0].strip().split() if len(clean_command) == 2: breakpoint = target.BreakpointCreateByRegex(clean_command[0], clean_command[1]) else: breakpoint = target.BreakpointCreateByRegex(clean_command[0], None) moduleName = t[1].strip().split()[1] module = target.module[moduleName] if not module: result.SetError('Invalid module {}'.format(moduleName)) return searchQuery = t[1].strip().split()[0] s = [i for i in module.symbols if re.search(searchQuery, i.name)] GlobalOptions.addSymbols(s, options, breakpoint) breakpoint.SetScriptCallbackFunction("breakifonfunc.breakpointHandler") if not breakpoint.IsValid() or breakpoint.num_locations == 0: result.AppendWarning("Breakpoint isn't valid or hasn't found any hits: " + clean_command[0]) else: result.AppendMessage("\"{}\" produced {} hits\nOnly will stop if the following stack frame symbols contain:\n{}` \"{}\" produced {} hits".format( clean_command[0], breakpoint.num_locations, module.file.basename, searchQuery, len(s)) ) def breakpointHandler(frame, bp_loc, dict): if len(GlobalOptions.symbols) == 0: print("womp something internal called reload LLDB init which removed the global symbols") return True key = str(bp_loc.GetBreakpoint().GetID()) searchSymbols = GlobalOptions.symbols[key][0] options = GlobalOptions.symbols[key][1] function_name = frame.GetFunctionName() thread = frame.thread if options.direct_call: frame = thread.frame[1] print(frame) symbol = frame.symbol return any([symbol in searchSymbols]) s = [i.symbol for i in thread.frames] return any(x in s for x in searchSymbols) def generateOptionParser(): usage = breakifonfunc.__doc__ parser = optparse.OptionParser(usage=usage, prog="biof") parser.add_option("-d", "--direct", action="store_true", default=False, dest="direct_call", help="Only stop if the second regex directly calls the breakpoint") return parser
DerekSelander/LLDB
lldb_commands/breakifonfunc.py
breakifonfunc.py
py
3,454
python
en
code
1,689
github-code
6
24362182930
from datetime import date, timedelta from .downloaders import Downloader from .parsers import Parser class RequiredValue(): def __init__(self, child_of=None): self.child_of = child_of def __call__(self, value): return self.child_of is None or isinstance(value, self.child_of) class DefaultValue(): def __init__(self, default): self.default = default class Supplier(): files = [] categories = () def __init__(self, partner=None): self.partner = partner def retrieve(self, files): data = [] parameters = { 'today': date.today().strftime('%Y%m%d'), 'yesterday': (date.today() - timedelta(days=1)).strftime('%Y%m%d'), } join = files.get('join', None) for location, mapping in files['mapping']: source = self.downloader.download(location % parameters) parsed = self.parser.parse(source, mapping, join) for k, v in parsed.items(): parsed[k]['_file'] = files['name'] data.append(parsed) return data def merge(self, files): merged = {} value_keys = set([]) for f in files: if len(f): value_keys.update(f[list(f.keys())[0]].keys()) for i, f in enumerate(files): for key, value in f.items(): for value_key in value_keys: if value_key not in value: value[value_key] = None if key not in merged: if i > 0: continue merged[key] = {} for k, v in value.items(): if merged[key].get(k) is None: merged[key][k] = v return merged.values() def pull(self): data = [] for files in self.files: file_data = self.retrieve(files) file_data = self.merge(file_data) data += file_data return data def validate(self, item): assert True def group(self, item): return None
suningwz/netaddiction_addons
netaddiction_octopus/base/supplier.py
supplier.py
py
2,132
python
en
code
0
github-code
6
31957664132
# https://www.hackerrank.com/challenges/candies/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming def candies(arr): candies = [1 for i in range(len(arr))] for i in range(0, len(arr) - 1): if(arr[i] < arr[i+1]): candies[i+1] = candies[i] + 1 for j in range(len(arr) - 1, 0, -1): if(arr[j] < arr[j - 1]): candies[j - 1] = max(candies[j - 1], candies[j] + 1) return sum(candies) print(candies([1, 2, 2])) # Should return 4 print(candies([2, 4, 2, 6, 1, 7, 8, 9, 2, 1])) # Should return 19 print(candies([2, 4, 3, 5, 2, 6, 4, 5])) # Should return 12
JacobLayton/code-problems
hackerrank/Python/candies.py
candies.py
py
672
python
en
code
0
github-code
6
72784214587
# https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2 from itertools import starmap def solve(arr): def conv(t1,t2): t1 = tuple(map(int,t1.split(":"))) t2 = tuple(map(int,t2.split(":"))) hd1, md = divmod((t2[1] - t1[1] - 1), 60) hd2 = (t2[0] - t1[0] + hd1) % 24 mm = (hd2 % 24) * 60 + md return mm, ':'.join(str(c).zfill(2) for c in divmod(mm, 60)) arr = sorted(set(arr)) return max(starmap(conv,zip(arr,arr[1:]+arr)))[1]
blzzua/codewars
6-kyu/simple_time_difference.py
simple_time_difference.py
py
487
python
en
code
0
github-code
6
23768567133
#!/usr/bin/env python3 """Main.""" import sys from cpu import * cpu = CPU() program = "default" if len(sys.argv) == 2: program = sys.argv[1] elif len(sys.argv) > 2: print("Only one program can be ran at a time. First argument will be used.") program = sys.argv[1] elif len(sys.argv) < 2: print("No program provided. Default program will be ran.") cpu.load(program) cpu.run()
VictorGoic0/Computer-Architecture
ls8/ls8.py
ls8.py
py
393
python
en
code
0
github-code
6
12746838211
from tkinter import * grid = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] root = Tk() root.title("Sudoku Solver with Backtracking") def print_board(bo): for i in range(len(bo)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - ") for j in range(len(bo[0])): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print(bo[i][j]) else: print(str(bo[i][j]) + " ", end="") def possible(y, x, n): global grid for i in range(0, 9): if grid[y][i] == n: return False for i in range(0, 9): if grid[i][x] == n: return False x0 = (x // 3) * 3 y0 = (y // 3) * 3 for i in range(0, 3): for j in range(0, 3): if grid[y0 + i][x0 + j] == n: return False return True def solve(): global grid for row in range(9): for column in range(9): if grid[row][column] == 0: for n in range(1, 10): if possible(row, column, n) == True: grid[row][column] = n solve() grid[row][column] = 0 return print_board(grid) for row in range(len(grid)): for cell in range(len(grid[row])): Label(text=str(grid[row][cell]), borderwidth=1, relief="solid", font="comicsans 10").grid(row=row, column=cell, ipadx=10, ipady=5) root.mainloop() solve()
Programmer-X31/PythonProjects
Project Sudoku Solver/efficient_main.py
efficient_main.py
py
1,862
python
en
code
0
github-code
6
33135136420
str1 = 'AABBCCDDEEFFGFZZZZZZ' lst1 = [word for word in str1] i = 0 while (i<len(lst1)-1): if lst1[i] != lst1[i+1]: (x,y) = (lst1[i],lst1[i+1]) print (x,y) lst1.remove(lst1[i]) lst1.remove(lst1[i]) i = 0 else: i = i + 1 #Result: ('A', 'B') ('A', 'B') ('C', 'D') ('C', 'D') ('E', 'F') ('E', 'F') ('G', 'F')
Unmindful/Classic-Short-Problems-in-Python
Array Pair Creation.py
Array Pair Creation.py
py
382
python
en
code
0
github-code
6
71718724348
#GUI-less stuff here... from . import FileOps import numpy as np import math from . import MTLsetup def MTLPlotData(fname): data=GetTransferSetupData(fname) dists=[] temps=[] r_errs=[] ind1=[] ind2=[] for setup in data: for sats in setup: #slow... n_opst,d,i1,i2,r_err=sats[0:5] t=sats[10] dists.append((n_opst,d)) temps.append((n_opst,t)) r_errs.append((n_opst,r_err)) ind1.append((n_opst,i1)) ind2.append((n_opst,i2)) return dists,temps,r_errs,ind1,ind2 def rad_to_sec(val): return math.degrees(val)*3600 def GetTransferSetupData(fname): #extract all relevant data from 'transfer setup' - similar to above #extract each setup and return data... f=open(fname) #start by extracting position data and temp. current_temp=None current_date=None current_time=None is_transfer_setup=False nopst=0 for line in f: sline=line.split() if len(sline)>3 and sline[0]=="#": current_temp=float(sline[-2]) current_date=sline[3] current_time=sline[4] break f.close() f=open(fname) line="X" all_data=[] while len(line)>0: #loeb igennem filen nu line=f.readline() sline=line.split() if len(sline)==0: continue if "Satser" in sline and "Afstand" in sline and line.strip()[0]!=";": setup_data=[] #data for this setup nopst+=1 is_transfer_setup=True #we have a setup - now read 'satser' line=f.readline().split() N=int(line[2]) d=float(line[3].replace("m","")) for i in range(N): line1=f.readline().split() line2=f.readline().split() r_err_term=line2[-2] #from the r_error term we can (also) read what unit is used... try: translator,unit,fconv=MTLsetup.Unit2Translator(r_err_term) r_err=float(r_err_term.replace(unit,""))*fconv*180/math.pi*3600 #in seconds ok,z11=translator(line1[-3]) assert(ok) ok,z12=translator(line1[-2]) assert(ok) ok,z21=translator(line2[-4]) assert(ok) ok,z22=translator(line2[-3]) assert(ok) is_buggy=abs(z11+z12-2*math.pi)>math.pi*0.5#stupid bug if is_buggy: zz=z12 z12=z21 z21=zz h1=float(line1[-1].replace("m","")) h2=float(line2[-1].replace("m","")) except Exception as e: print(("Exception: %s\nSpringer denne sats over.."%str(e))) continue ind1=((z11+z12)-2*math.pi)*0.5 ind2=((z21+z22)-2*math.pi)*0.5 #calculate adjusted angles z1c=z11-ind1 z2c=z21-ind2 #print z1c+z2c r_err_raw=(z1c+z2c)-math.pi setup_data.append([nopst,d,rad_to_sec(ind1),rad_to_sec(ind2),r_err,rad_to_sec(r_err_raw),h1,h2,current_date,current_time,current_temp,-9999,-9999]) if len(setup_data)>0: #read until the sats has endend - and dont read too far! n_read=0 while len(sline)>0: line=f.readline() sline=line.split() if len(sline)>2 and sline[0]=="*" and sline[1]=="II": break n_read+=1 #sats endend line=f.readline() sline=line.split() if len(sline)>0 and sline[0]=="GPS:": #may go wrong for basis setup current_x=float(sline[2]) current_y=float(sline[1]) for sats in setup_data: sats[-1]=current_y sats[-2]=current_x all_data.append(setup_data) if len(sline)==0: continue if sline[0]=="#": current_temp=float(sline[-2]) current_date=sline[3] current_time=sline[4] f.close() return all_data def GetSummaRho(fil,include=None,exclude=None,f_out=None): nerrors=0 msg="" heads=FileOps.Hoveder(fil) jsides={} if len(heads)==0: return False,"Ingen hoveder fundet i filen." for head in heads: jside=head[6] fra=head[0] til=head[1] skipthis=False if include is not None: if not (til in include or fra in include): #if til or fra in include continue skipthis=True if (not skipthis) and exclude is not None: if til in exclude or fra in exclude: skipthis=True if skipthis: continue dist=float(head[4]) hdiff=float(head[5]) err=False spl=jside.split(".") if len(spl)!=2: err=True else: try: jside=int(spl[0]) ext=int(spl[1]) except: err=True if err: nerrors+=1 msg+="Ukurankt journalside: %s, str\u00E6kning: %s til %s, fil: %s\n" %(jside,fra,til,os.path.basename(file)) else: if jside in jsides: jsides[jside].append((fra,til,ext,dist,hdiff)) else: jsides[jside]=[(fra,til,ext,dist,hdiff)] summa_rho=0.0 total_dist=0 n_used=0 max_used=0 for jside in jsides: items=jsides[jside] if len(items)>1: item=items[0] h_forward=item[-1] dists=[item[-2]] h_back=0.0 fra=item[0] til=item[1] org_ext=item[2] n_forward=1 n_back=0 ok=True for item in items[1:]: if item[0]==fra and item[1]==til: n_forward+=1 h_forward+=item[-1] elif item[1]==fra and item[0]==til: n_back+=1 h_back+=item[-1] else: msg+="Fejl i journalside %d.%d, punkter stemmer ikke med journalside nummer %d.%d:\n" %(jside,item[2],jside,org_ext) msg+="Fra: %s, til: %s, for denne jside: %s, %s\n" %(fra,til,item[0],item[1]) ok=False break dists.append(item[-2]) if ok: n_used+=1 d1=min(dists) d2=max(dists) if (d2-d1)>50: msg+="Journalside: %d, stor forskel i afstande: %.2f m, max %.2f m, min: %.2f m\n" %(jside,d2-d1,d2,d1) max_used=max((max_used,n_forward,n_back)) h_forward=h_forward/n_forward h_back=h_back/n_back h_all=h_forward+h_back d=np.mean(dists) summa_rho+=h_all total_dist+=d if f_out is not None: f_out.write("'%d';'%s';'%s';%d;%d;%s;%s\n" %(jside,fra,til,n_forward,n_back,("%.2f"%d).replace(".",","),("%.6f"%h_all).replace(".",","))) if n_used>0: summa_rho_norm=abs(summa_rho)/np.sqrt(total_dist/1e3) msg+="Summa rho: %.3f cm\n" %(summa_rho*100.0) msg+="Normaliseret summa rho (mm/sqrt(d_km)): %.2f ne\n" %(summa_rho_norm*1e3) msg+="Samlet afstand: %.2f m\n" %(total_dist) msg+="Brugte journalsidenumre: %d\n" %n_used msg+="Max. antal maalinger af samme straek i samme retning: %d\n" %max_used else: return True,"Fandt ingen relevante/korrekte data..." return True,msg
SDFIdk/nivprogs
MyModules/Analysis.py
Analysis.py
py
6,438
python
en
code
0
github-code
6
24756305475
import os import sys def execute_pipleline(n_prototipes, window_size, step, max_level, standardization, weight): call1 = 'python 1.sample.py lightcurves.R.txt {0} {1} {2} {3}'.format(n_prototipes, standardization, window_size, step) call2 = 'python 2.twed.py lightcurves.R.txt {0} {1} {2} {3}'.format(n_prototipes, standardization, window_size, step) call3 = 'python 3.tree_building.py lightcurves.R.txt {0} {1} {2} {3} {4} {5}'.format(n_prototipes, standardization, weight, window_size, step, max_level) standardization_dict = {'std':'semistdFalse_stdTrue', 'semi': 'semistdTrue_stdFalse', 'not': 'semistdFalse_stdFalse'} standardization_str = standardization_dict[standardization] model_name = 'sequence_tree_lightcurves.R.txt_{0}samples_{1}_20levels_{2}_{3}'.format(n_prototipes, standardization_str, window_size, step) call4 = 'python 4.ndcg_test.py {0} 100 20'.format(model_name) print('RUNNING 1.SAMPLE') os.system(call1) print('RUNNING 2.TWED') os.system(call2) print('RUNNING 3.TREE_BUILDING') os.system(call3) print('RUNNING 4.NDCG_TEST') os.system(call4) print('DONE') if __name__ == '__main__': n = int(sys.argv[1]) window = int(sys.argv[2]) step = int(sys.argv[3]) max_level = sys.argv[4] standardization = sys.argv[5] weight = sys.argv[6] execute_pipleline(n, window, step, max_level, standardization, weight)
luvalenz/time-series-variability-tree
pipeline.py
pipeline.py
py
1,598
python
en
code
2
github-code
6
4473417766
import datetime import logging import re from estropadakparser.parsers.parser import Parser from estropadakparser.estropada.estropada import Estropada, TaldeEmaitza class ArcParserLegacy(Parser): '''Base class to parse an ARC legacy(2006-2008) race result''' def __init__(self, **kwargs): pass def parse(self, *args): '''Parse a result and return an estropada object''' document = self.get_content(*args) urla = args[0] estropadaDate = args[2] liga = args[3] d = datetime.datetime.strptime(estropadaDate, '%Y-%m-%d') (estropadaName) = self.parse_headings(document) opts = {'urla': urla, 'data': estropadaDate, 'liga': liga} self.estropada = Estropada(estropadaName, **opts) self.parse_tandas(document, d.year) if d.year <= 2008: self.calculate_tanda_posizioa() else: self.parse_resume(document) return self.estropada def parse_headings(self, document): '''Parse headings table''' heading_one = document.cssselect('#contenido h1') estropada = heading_one[0].text.strip() estropada = estropada.replace("Resultados de: ", "") return (estropada) def parse_date(self, date): new_date = date.replace('Jun', '06') new_date = new_date.replace('Jul', '07') new_date = new_date.replace('Ago', '08') new_date = new_date.replace('Sept', '09') date_list = re.split('-', new_date) if len(date_list) == 3: new_date = date_list[2] + "-" + date_list[1] + "-" + date_list[0] return new_date def parse_tandas(self, document, urtea): tandas = document.cssselect('table.resultados') for num, text in enumerate(tandas): rows = text.findall('.//tr') for kalea, row in enumerate(rows): if kalea == 0: continue data = [x.text for x in row.findall('.//td')] try: if not data[1] is None: if urtea < 2008: pos = 12 aux = re.sub('[^0-9]', '', data[6]) try: pos = int(aux) except ValueError: pos = 12 else: pos = 0 emaitza = TaldeEmaitza(talde_izena=data[1], kalea=kalea, ziabogak=data[2:5], denbora=data[5], tanda=num + 1, posizioa=pos, tanda_postua=4) self.estropada.taldeak_add(emaitza) except TypeError as e: print(e) def calculate_tanda_posizioa(self): tanda_posizioak = [0] + [1] * 7 for pos, taldea in enumerate(sorted(self.estropada.sailkapena)): taldea.posizioa = pos + 1 taldea.tanda_postua = tanda_posizioak[taldea.tanda] tanda_posizioak[taldea.tanda] = tanda_posizioak[taldea.tanda] + 1 def parse_resume(self, document): sailkapenak = document.cssselect('#resultado table') tandaKopurua = len(sailkapenak) rows = sailkapenak[tandaKopurua-1].findall('.//tr') tanda_posizioak = [0] + [1] * 7 for pos, row in enumerate(rows): if pos == 0: continue try: taldea = row.find('.//td[2]').text.strip() posizioa = pos print(posizioa) puntuak = row.find('.//td[4]').text.strip() for t in self.estropada.sailkapena: if re.match(t.talde_izena, taldea, re.I): try: t.posizioa = posizioa t.tanda_postua = tanda_posizioak[t.tanda] t.puntuazioa = int(puntuak) except Exception as e: print(e) t.posizioa = 1 t.tanda_postua = tanda_posizioak[t.tanda] t.puntuazioa = 0 tanda_posizioak[t.tanda] = tanda_posizioak[t.tanda] + 1 except Exception as e: logging.warn(self.estropada.izena) logging.info("Error parsing results", exec_info=True)
ander2/estropadak-lxml
estropadakparser/parsers/arc_legacy_parser.py
arc_legacy_parser.py
py
4,486
python
eu
code
2
github-code
6
14927451670
import tkinter as tk from tkinter import filedialog, simpledialog, messagebox, Scale, HORIZONTAL from tkinter.ttk import Notebook from PIL import Image, ImageTk import random import os import shutil import zipfile import json class TraitBubble: def __init__(self, canvas, trait_name, x, y, prob_scale): self.canvas = canvas self.trait_name = trait_name self.x = x self.y = y self.prob_scale = prob_scale self.radius = 25 self.bubble_id = self.canvas.create_oval( self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius, fill="white", outline="black" ) self.text_id = self.canvas.create_text( self.x, self.y - self.radius - 15, text=self.trait_name, fill="black", font=("Arial", 10, "bold") ) self.canvas.tag_bind(self.bubble_id, "<Button-1>", self.start_drag) self.canvas.tag_bind(self.bubble_id, "<B1-Motion>", self.move_drag) self.canvas.tag_bind(self.bubble_id, "<ButtonRelease-1>", self.stop_drag) self.canvas.tag_bind(self.bubble_id, "<Double-Button-1>", self.delete_bubble) def start_drag(self, event): self.drag_data = {"x": event.x, "y": event.y} def move_drag(self, event): dx = event.x - self.drag_data["x"] dy = event.y - self.drag_data["y"] self.canvas.move(self.bubble_id, dx, dy) self.canvas.move(self.text_id, dx, dy) self.x += dx self.y += dy self.drag_data["x"] = event.x self.drag_data["y"] = event.y def stop_drag(self, event): self.drag_data = None def delete_bubble(self, event): self.canvas.delete(self.bubble_id) self.canvas.delete(self.text_id) self.prob_scale.destroy() class NFTGeneratorApp: def __init__(self, root): self.root = root self.root.title("NFT Generator") self.trait_categories = {} self.trait_bubbles = [] self.generated_images = [] self.num_nfts = 1 self.unique_combinations = set() # Create and configure the UI elements self.trait_label = tk.Label(self.root, text="Trait Categories:") self.trait_label.pack() self.trait_buttons_frame = tk.Frame(self.root) self.trait_buttons_frame.pack() self.add_trait_button = tk.Button(self.root, text="Add Trait Category", command=self.add_trait_category) self.add_trait_button.pack() self.generate_label = tk.Label(self.root, text="Number of NFTs to Generate:") self.generate_label.pack() self.generate_entry = tk.Entry(self.root) self.generate_entry.insert(tk.END, "1") self.generate_entry.pack() self.generate_button = tk.Button(self.root, text="Generate NFT", command=self.generate_nft) self.generate_button.pack() self.download_button = tk.Button(self.root, text="Download All NFTs", command=self.download_nfts) self.download_button.pack() self.notebook = Notebook(self.root) self.notebook.pack() self.canvas = tk.Canvas(self.root, width=500, height=500) self.canvas.pack() def add_trait_category(self): trait_category = simpledialog.askstring("Add Trait Category", "Enter the name of the trait category:") if trait_category: folder_path = filedialog.askdirectory(title="Select Folder for {}".format(trait_category)) if folder_path: self.trait_categories[trait_category] = self.get_valid_image_files(folder_path) self.create_trait_bubbles(trait_category) def create_trait_bubbles(self, trait_category): x = 60 y = len(self.trait_bubbles) * 60 + 60 prob_scale = Scale(self.root, from_=0, to=100, orient=HORIZONTAL, length=100) prob_scale.set(50) prob_scale.pack() bubble = TraitBubble(self.canvas, trait_category, x, y, prob_scale) self.trait_bubbles.append(bubble) def generate_nft(self): self.num_nfts = int(self.generate_entry.get()) if self.trait_bubbles and self.num_nfts > 0: self.generated_images = [] for _ in range(self.num_nfts): traits_used = [] layers = sorted(self.trait_bubbles, key=lambda bubble: bubble.y) base_image = Image.new("RGBA", (400, 400)) for bubble in layers: trait_category = bubble.trait_name if random.randint(1, 100) <= bubble.prob_scale.get(): trait_image = self.get_random_image(self.trait_categories[trait_category]) traits_used.append((trait_category, trait_image)) trait_image = trait_image.resize((400, 400)) base_image = Image.alpha_composite(base_image, trait_image) trait_combination = frozenset(traits_used) if trait_combination not in self.unique_combinations: self.generated_images.append((base_image, traits_used)) self.unique_combinations.add(trait_combination) self.add_preview(base_image, traits_used) def get_valid_image_files(self, folder_path): valid_extensions = [".png", ".jpg", ".jpeg", ".gif"] image_files = [] for root, dirs, files in os.walk(folder_path): for file in files: _, ext = os.path.splitext(file) if ext.lower() in valid_extensions: image_files.append(os.path.join(root, file)) return image_files def get_random_image(self, image_list): return Image.open(random.choice(image_list)).convert("RGBA") def add_preview(self, image, traits_used): image = image.resize((200, 200)) photo = ImageTk.PhotoImage(image) frame = tk.Frame(self.notebook) label = tk.Label(frame, image=photo) label.image = photo label.pack() text = tk.Text(frame, height=5, width=30) text.pack() text.insert(tk.END, json.dumps({trait: str(image) for trait, image in traits_used}, indent=4)) self.notebook.add(frame, text=f"NFT #{len(self.generated_images)}") def download_nfts(self): if self.generated_images: folder_path = filedialog.askdirectory(title="Select Folder to Save NFTs") if folder_path: zip_path = os.path.join(folder_path, "nfts.zip") with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zip_file: for index, (image, traits) in enumerate(self.generated_images): image_path = os.path.join(folder_path, f"nft_{index + 1}.png") image.save(image_path, "PNG", compress_level=9) zip_file.write(image_path, f"nft_{index + 1}.png") os.remove(image_path) metadata = {trait: str(img) for trait, img in traits} metadata_path = os.path.join(folder_path, f"metadata_{index + 1}.json") with open(metadata_path, "w") as f: json.dump(metadata, f, indent=4) zip_file.write(metadata_path, f"metadata_{index + 1}.json") os.remove(metadata_path) messagebox.showinfo("Download Complete", "All NFTs and metadata have been downloaded as a zip file.") if __name__ == "__main__": root = tk.Tk() app = NFTGeneratorApp(root) root.mainloop()
net1ife/NFT-generation
v0.py
v0.py
py
7,914
python
en
code
0
github-code
6
1008006432
'''Solving today's Yohaku Puzzle posted on Twitter https://twitter.com/1to9puzzle/status/1123345947755311105 May 1, 2019''' import random import time start = time.time() NUMS = [1,2,3,4,5,6,7,8,9] products = [90,90,72,24] attempts = 0 #infinite loop while True: #increment attempts attempts += 1 if attempts % 100000 == 0: print(attempts,'attempts so far.') #assign values to the 9 variables a,b,c,d,f,g,h,i = random.sample(NUMS,8) #check if their sums satisfy the conditions: if a*b*c != products[0]: continue #go back to beginning of loop and start over if c*f*i != products[1]: continue if g*h*i != products[2]: continue if a*d*g != products[3]: continue #if the program has reached this point, #it must be the solution. Print it out: print() print(a,b,c) print(d," ",f) print(g,h,i) print() print(attempts,"attempts.") print("Time:", round(time.time() - start,2),"seconds.") break
hackingmath/puzzles
yohakuPuzzle050119Products.py
yohakuPuzzle050119Products.py
py
1,003
python
en
code
7
github-code
6
40369189284
from multiprocessing.spawn import old_main_modules from os import listdir from os.path import isfile, join from wordcloud import WordCloud import codecs import jieba import matplotlib.pyplot as plt # read data mypath = 'lab/contexts/' font_filename = 'fonts/STFangSong.ttf' files = [f for f in listdir(mypath) if isfile(join(mypath, f))] text_list=[] text='' for file in files: with open(mypath+file) as f: lines = f.readlines() text = text + ' '.join(lines) text = ' '.join(jieba.cut(text.replace(" ", ""))) stopwords_filename = 'lab/stopwords.txt' stopwords = set([line.strip() for line in codecs.open(stopwords_filename, 'r', 'utf-8')]) # build wordcloud wordcloud = WordCloud(font_path=font_filename, prefer_horizontal=1,stopwords=stopwords, max_font_size=260, width=1000, height=860, max_words=200).generate(text) plt.figure() plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show()
NATaaLiAAK/PPE1
cloud_build.py
cloud_build.py
py
1,000
python
en
code
0
github-code
6
8420322841
# Program to show classes and objects in Python class Person: def __init__(self,name, age): self.name = name # instance attribute self.age = age person1 = Person("David", 31) print("person 1 name = ", person1.name) print("person 1 age = ", person1.age) person2 = Person("Paul",32) print("person 2 name = ", person2.name) print("person 2 age = ", person2.age)
davidjava1991/Python3CompleteCourse
Section6/lecture61/Program1.py
Program1.py
py
384
python
en
code
1
github-code
6
35743736914
import sys import os import numpy as np import scipy.sparse from scipy.sparse import csr_matrix, find import read_write as rw import matlab.engine ''' finput_iu_rating_matrix_train = "Data/iu_sparse_matrix_train.npz" finput_title_sim_matrix = "Data/title_similarity_matrix" finput_description_sim_matrix = "Data/description_similarity_matrix" finput_user_cluster_set = "Data/user_cluster_set" finput_train_item_id = "Data/train_item_id" finput_test_item_id = "Data/test_item_id" finput_nonlinreg = "Data/nonlinreg" finput_init_tp = 1.0 finput_init_dp = 1.0 foutput_iuclst_rating_matrix = "Data/iuclst_rating_matrix" foutput_item_sim_matrix = "Data/item_sim_matrix" ''' if (__name__ == '__main__'): #### data path finput_iu_rating_matrix_train = sys.argv[1] finput_iu_rating_matrix_test = sys.argv[2] finput_title_sim_matrix = sys.argv[3] finput_description_sim_matrix = sys.argv[4] finput_user_cluster_set = sys.argv[5] finput_train_item_id = sys.argv[6] finput_test_item_id = sys.argv[7] finput_nonlinreg = sys.argv[8] finput_init_tp = float(sys.argv[9]) finput_init_dp = float(sys.argv[10]) foutput_iuclst_rating_matrix_train = sys.argv[11] foutput_iuclst_rating_matrix_test = sys.argv[12] foutput_item_sim_matrix = sys.argv[13] # load data iu_rating_matrix_train = scipy.sparse.load_npz(finput_iu_rating_matrix_train) iu_rating_matrix_test = scipy.sparse.load_npz(finput_iu_rating_matrix_test) title_sim_matrix = rw.readffile(finput_title_sim_matrix) description_sim_matrix = rw.readffile(finput_description_sim_matrix) user_cluster_set = rw.readffile(finput_user_cluster_set) train_item_id = rw.readffile(finput_train_item_id) test_item_id = rw.readffile(finput_test_item_id) # run matlab script and get parameters for title and description print("call matlab script....") cur_path = os.getcwd() os.chdir("D:\GitCode\Dissertation\Step1-Preprocessing") eng = matlab.engine.start_matlab() x = eng.my_fitnlm(finput_nonlinreg, finput_init_tp, finput_init_dp, nargout=3) theta1, theta2, RMSE = x[0], x[1], x[2] eng.quit() sim_matrix = theta1*title_sim_matrix + theta2*description_sim_matrix os.chdir(cur_path) rw.write2file(sim_matrix, foutput_item_sim_matrix) print("theta1 = ", theta1) print("theta2 = ", theta2) print("RMSE = ", RMSE) print("matlab finished") # extract similarity matrix for training and test item # resort_id = list(train_item_id.keys()) + list(test_item_id.keys()) sim_matrix_train = sim_matrix.loc[list(train_item_id.keys()), list(train_item_id.keys())].values sim_matrix_test = sim_matrix.loc[list(test_item_id.keys()), list(test_item_id.keys())].values # user cluster - item rating matrix iuclst_rating_matrix_train = np.zeros((len(train_item_id), len(user_cluster_set))) iuclst_rating_matrix_test = np.zeros((len(test_item_id), len(user_cluster_set))) item_in_node_train = list(range(iu_rating_matrix_train.shape[0])) item_in_node_test = list(range(iu_rating_matrix_test.shape[0])) for ind, user_cluster in zip(range(len(user_cluster_set)), user_cluster_set): print("user cluster: %d / %d"%(ind+1, len(user_cluster_set)), end="\r") user_cluster_size = len(user_cluster) sub_rating_matrix = iu_rating_matrix_train[np.ix_(item_in_node_train, user_cluster)].T.toarray() # user number * training item number sub_rating_matrix_pred = (np.dot(sub_rating_matrix, sim_matrix_train) / (1e-9+np.dot(sub_rating_matrix != 0, sim_matrix_train))) iuclst_rating_matrix_train[:, ind] = np.sum(sub_rating_matrix + 0.01*(sub_rating_matrix == 0) * sub_rating_matrix_pred, axis=0) / np.sum((sub_rating_matrix == 0)*0.01 + (sub_rating_matrix != 0)*1, axis=0) sub_rating_matrix = iu_rating_matrix_test[np.ix_(item_in_node_test, user_cluster)].T.toarray() # user number * test item number sub_rating_matrix_pred = (np.dot(sub_rating_matrix, sim_matrix_test) / (1e-9+np.dot(sub_rating_matrix != 0, sim_matrix_test))) iuclst_rating_matrix_test[:, ind] = np.sum(sub_rating_matrix + 0.01*(sub_rating_matrix == 0) * sub_rating_matrix_pred, axis=0) / np.sum((sub_rating_matrix == 0)*0.01 + (sub_rating_matrix != 0)*1, axis=0) print("\nuser cluster/item rating matrix generated done!") rw.write2file(iuclst_rating_matrix_train, foutput_iuclst_rating_matrix_train) rw.write2file(iuclst_rating_matrix_test, foutput_iuclst_rating_matrix_test) print("file saved done!")
clamli/Dissertation
Step1-Preprocessing/buildtree_preparation.py
buildtree_preparation.py
py
4,436
python
en
code
28
github-code
6
17615533766
import web import os urls = ('/upload', 'Upload') class Upload: def GET(self): web.header("Content-Type","text/html; charset=utf-8") return open(r'upload.html', 'r').read() def POST(self): try: x = web.input(myfile={}) filedir = 'submit' # change this to the directory you want to store the file in. if 'myfile' in x: # to check if the file-object is created filepath = x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones. filename = filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension) fout = open(filedir +'/'+ filename,'w+') # creates the file where the uploaded file should be stored fout.write(x.myfile.file.read().decode('utf-8')) # writes the uploaded file to the newly created file. fout.close() # closes the file, upload complete. if filename[-2:] == '.c': # start analyze os.system('echo check') os.system('python3 grade.py > result.txt') os.system('rm ' + filedir + '/' + filename) print('[file deleted]') resultWeb = open(r'result.html', 'r').read() result = open('result.txt', 'r').read() if(result.find('Failed.') != -1): resultWeb = resultWeb[: resultWeb.find('<!--result-->')] + '\n<h3><strong style="color: red"> Test Failed</strong></h3><br>\n' + result + '\n' + resultWeb[resultWeb.find('<!--result-->') + len('<!--result-->'):] else: # add result to website resultWeb = resultWeb[: resultWeb.find('<!--result-->')] + '\n<h3><strong style="color: green"> Test Passed</strong></h3><br>\n' + result + '\n' + resultWeb[resultWeb.find('<!--result-->') + len('<!--result-->'):] else: resultWeb = open(r'error.html', 'r').read() resultWeb = resultWeb[:resultWeb.find('<!--file-->')] + filename +resultWeb[resultWeb.find('<!--file-->'):] os.system('rm ' + filedir + '/' + filename) print('[file deleted]') return resultWeb except: resultWeb = open(r'error.html', 'r').read() resultWeb = resultWeb[:resultWeb.find('<!--file-->')] + 'ERROR:\n No file uploaded or internal error occured while uploading the file.' + resultWeb[resultWeb.find('<!--file-->'):] return resultWeb raise web.seeother('/upload') if __name__ == "__main__": app = web.application(urls, globals()) app.run()
Louis-He/simpleOj
webmain.py
webmain.py
py
2,766
python
en
code
0
github-code
6
71226678909
from hzf.file import base_file import os # ------------------------------ base_file ----- bfile = base_file.BaseFile() # ===== folder testfolder = os.getcwd() + r"\temp\testfolder" bfile.create_folder(testfolder) bfile.remove_folder(testfolder) # ===== path print(bfile.split_path_drive(testfolder)) print(bfile.split_path_last(testfolder)) # ===== file file_list = [os.getcwd() + r"\temp\a.txt"] bfile.copy_files_to_folder(file_list, os.getcwd() + r"\temp\output") remove_file_list = [os.getcwd() + r"\temp\output\a.txt"] # bfile.remove_file(remove_file_list) for line, lineno, new_file in bfile.inplace(file_list[0]): new_file.write(line.replace("d", 'e')) print("end")
huangzf128/something
code/python/hzf-unittest/file.py
file.py
py
685
python
en
code
0
github-code
6
12639157505
"""Escribe un programa que calcule el promedio general de una clase.""" quant = int(input(f"Ingrese la cantidad de alumnos que tiene la clase: ")) count = 0 acc = 0 while count < quant: acc += int(input(f"Ingrese la nota del alumno Nº {count + 1}: ")) count += 1 print(f"El promedio final de la clase es {acc / quant}")
sbelbey/pp-python
Ejercicios_21_al_30/ejercicio24.py
ejercicio24.py
py
327
python
es
code
0
github-code
6
7125623220
###################################################### ### SQL Database Script for PokeDex and TrainerDex ### ###################################################### import numpy as np import pandas as pd from sqlalchemy import create_engine from config import password import pprint as pp # Set locations for CSV Files and create dataframes csv_file1 = "pokedex_clean.csv" pokedex_df = pd.read_csv(csv_file1) csv_file2 = "trainer_clean.csv" trainer_df = pd.read_csv(csv_file2) csv_file3 = "trainer_junction_clean.csv" trainer_junction_df = pd.read_csv(csv_file3) # Connect to PostgreSQL rds_connection_string = "postgres:"+password+"@localhost:5432/pokemon_db" engine = create_engine(f'postgresql://{rds_connection_string}') # Read Dataframes into SQL and replace table if exists pokedex_df.to_sql(name='pokedex', con=engine, if_exists='replace', index=False) trainer_df.to_sql(name='trainer', con=engine, if_exists='replace', index=False) trainer_junction_df.to_sql(name='trainer_junction', con=engine, if_exists='replace', index=False) ################################################# ############ Search Function Script ############ ################################################# # Resume_Search is a nested inner function that allows the user to choose whether or not they want to search again. def search(): def resume_search(): resume = input ("Would you like to search again? (Yes or No) ") if resume.lower() in ["yes", "y"]: search() else: print ('Search Canceled. Closing Script.') request = 0 request = input ("What would you like to search for? (Select the number of the menu option)\ \n1: Trainer Name Containing:\ \n2: Trainers that own (name of pokemon):\ \n3: Pokedex Entry for (pokemon name):\ \n4: Pokedex Entry for (dex number):\ \n0: Cancel search and end program.:\ \nMenu Number: ") if request == 1 or request == str(1): trainer_search = input('Search for a trainer using their name:\nTrainer Name: ') search_return1 = pd.read_sql_query(\ "SELECT tr.trainer_id, tr.trainername, t_j.pokelevel, pk.pokemon_name\ FROM trainer_junction as t_j \ LEFT JOIN trainer AS tr ON tr.trainer_id = t_j.trainer_id \ LEFT JOIN pokedex as pk ON t_j.pokedex_number = pk.pokedex_number \ WHERE tr.trainername LIKE " "'%%" + str((trainer_search).title()) + "%%'", con=engine) print(search_return1) resume_search() elif request == 2 or request == str(2): poke_search = input('For a list of all trainers owning this pokemon: \nPokemon Name: ') search_return2 = pd.read_sql_query(\ "SELECT tr.trainername\ FROM trainer_junction as t_j \ LEFT JOIN trainer AS tr ON tr.trainer_id = t_j.trainer_id \ LEFT JOIN pokedex as pk ON t_j.pokedex_number = pk.pokedex_number \ WHERE pk.pokemon_name = " "'" + str((poke_search).title()) + "'", con=engine) search_result2 = [val[0] for val in search_return2.values] pp.pprint(search_result2) resume_search() elif request == 3 or request == str(3): poke_name = input('What is the name of the pokemon whose pokedex entry you wish to search for? \nPokemon Name: ') search_return3 = pd.read_sql_query("SELECT * FROM pokedex WHERE pokemon_name = " + "'" + str((poke_name).title()) + "'", con=engine) search_result3 = search_return3.transpose() print(search_result3) resume_search() elif request == 4 or request == str(4): poke_num = input('What is the pokedex number of the pokemon whose pokedex entry you wish to search for? \ \nPlease note that we have our own pokedex numbering system. \ \nPokedex Number: ') search_return4 = pd.read_sql_query("SELECT * FROM pokedex WHERE pokedex_number = " + "'" + str(poke_num) + "'", con=engine) search_result4 = search_return4.transpose() print(search_result4) resume_search() elif request == 0 or request == str(0): print ('Search Canceled. Ending Prompt.') else: request = 0 print ("That isn't a menu option number. Please try again.") search() ########################################## ######## Call The Search Function ######## ########################################## if __name__ == '__main__': search() ########################################## ############### END SCRIPT ############### ##########################################
ASooklall/ETL_Project
pokemon_db/pokemon_db.py
pokemon_db.py
py
4,633
python
en
code
0
github-code
6