blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
c06b62f0d63e1d04242598918306df367ec92d5a
77f00f129308b82138c517e928380fc65e547bcb
/2018/06/part_2.py
7af107221e7e71cd2a7cac8f9c73655723cf47ef
[]
no_license
Hall-Erik/AdventOfCode
99075a9d46dedb244bf6ac2c026a3f9e3d0e1fba
0629cf336dd06bea1ce11802d873abe1f299873c
refs/heads/master
2023-03-10T17:13:31.027794
2022-12-26T18:38:15
2022-12-26T18:38:15
161,951,303
0
0
null
2023-03-05T16:42:49
2018-12-15T23:15:31
Python
UTF-8
Python
false
false
1,827
py
from typing import List points = [] with open('input.txt', 'r') as f: for line in f: l = line.strip() x, y = l.split(', ') p = [int(x), int(y)] points.append(p) def get_distance(a: List[int], b: List[int]) -> int: ''' Returns Manhattan distance of two points ''' return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_distances(a: List[int], points: List[list]) -> int: ''' Returns Sum of Manhattan distances between point a and all points in the list points ''' total = 0 for point in points: total += get_distance(a, point) return total def get_area(points: List[list], limit: int=10000) -> int: ''' Returns the number of points that have a total distance from all input points less than 10000. ''' total = 0 # find the edges min_x = min(points, key=lambda x: x[0])[0] max_x = max(points, key=lambda x: x[0])[0] min_y = min(points, key=lambda x: x[1])[1] max_y = max(points, key=lambda x: x[1])[1] all_points = [ [x, y] for y in range(min_y, max_y+1) for x in range(min_x, max_x+1) ] for p in all_points: if get_distances(p, points) < limit: total += 1 return total test_points = [ [1, 1], [1, 6], [8, 3], [3, 4], [5, 5], [8, 9]] assert get_distance([4, 3], test_points[0]) == 5 assert get_distance([4, 3], test_points[1]) == 6 assert get_distance([4, 3], test_points[2]) == 4 assert get_distance([4, 3], test_points[3]) == 2 assert get_distance([4, 3], test_points[4]) == 3 assert get_distance([4, 3], test_points[5]) == 10 assert get_distances([4, 3], test_points) == 30 assert get_area(test_points, 32) == 16 print(get_area(points, 10000))
[ "hall.erik@gmail.com" ]
hall.erik@gmail.com
388481b96e51f53bceedf30b12831cfa1f6d8933
901944f407f4a06a4c4027d6139ce21165976857
/Protein_Structure_Prediction/protein_model_code4/parallel_main_experts.py
92c9d5584bf76b139b96c7dfdc12e964b701b4d1
[]
no_license
chriscremer/Other_Code
a406da1d567d63bf6ef9fd5fbf0a8f177bc60b05
7b394fa87523803b3f4536b316df76cc44f8846e
refs/heads/master
2021-01-17T02:34:56.215047
2020-05-26T13:59:05
2020-05-26T13:59:05
34,680,279
7
4
null
null
null
null
UTF-8
Python
false
false
2,317
py
import numpy as np import os import numpy as np import tensorflow as tf import math import random import pickle import json import phase_1_model import protein_model_tools from multiprocessing import Pool import sys from os.path import expanduser home = expanduser("~") #RASH L = 166 msa_file = home + '/Documents/Protein_data/RASH/RASH_HUMAN2_833a6535-26d0-4c47-8463-7970dae27a32_evfold_result/alignment/RASH_HUMAN2_RASH_HUMAN2_jackhmmer_e-10_m30_complete_run.fa' msa, n_aa = protein_model_tools.convert_msa(L, msa_file) # print len(msa), len(msa[0]) def learn_expert(ij): expert_weights = np.zeros((n_aa,n_aa)) #ij2 = ij[0] i = ij[0] # print i # print i # fasfasf j = ij[1] print j if i == j: # print 'start ' + str(i) + ' ' + str(j) # print 'done ' + str(i) + ' ' + str(j) return expert_weights else: # print 'start ' + str(i) + ' ' + str(j) #print str((i*L)+j) + '/' + str(total) + ' '+ str(i) + ' ' + str(j) #Make datasets X_train = [] y_train = [] X_valid = [] y_valid = [] for samp in range(len(msa)): if samp < 500: vec = np.zeros((n_aa)) vec[msa[samp][i]] = 1 X_valid.append(vec) vec = np.zeros((n_aa)) vec[msa[samp][j]] = 1 y_valid.append(vec) else: vec = np.zeros((n_aa)) vec[msa[samp][i]] = 1 X_train.append(vec) vec = np.zeros((n_aa)) vec[msa[samp][j]] = 1 y_train.append(vec) X_train = np.array(X_train) y_train = np.array(y_train) X_valid = np.array(X_valid) y_valid = np.array(y_valid) #Train model model1 = phase_1_model.Expert_Learner(n_aa=22, tol=.01, batch_size=5, lr=.0001, mom=.9, lmbd=.0001) model1.fit([X_train,y_train], [X_valid,y_valid]) experts_weights = model1.w # experts_biases[i,j] = model1.b # print 'done ' + str(i) + ' ' + str(j) return expert_weights #for each position, use pool to learn the L experts, save it to experts folder # todo_list = range(30,158) # todo_list = todo_list[::-1] # for i in todo_list: # print i i = int(sys.argv[1]) work = [[i,j] for j in range(L)] experts = [learn_expert(work[k]) for k in range(len(work))] #print work # p = Pool(8) # experts = p.map(learn_expert, work) #save experts with open('expert_' + str(i) + '.pkl', "wb" ) as f: pickle.dump(experts, f) print 'saved expert ' + str(i) #close and run
[ "chris@Chriss-MacBook-Pro.local" ]
chris@Chriss-MacBook-Pro.local
b1750df738bd79655826274525af9f0cbd580b45
5d5f6ba3bdcb52b4750a5f28afa8a1a1019bfc9e
/django/django_fundamentals/ninjaGoldProject/ninjaGoldProject/asgi.py
29329a1fddfdd54f07df4fe1c89e6ab2052e0ee5
[]
no_license
eDiazGtz/pythonLearning
06e96f2f5a6e48ac314cb815cf9fbf65d0b7c2c8
57d7b2292cf5d9769cce9adf765962c3c0930d6c
refs/heads/master
2023-06-18T02:16:09.293375
2021-05-03T18:09:52
2021-05-03T18:09:52
335,090,531
0
0
null
2021-05-03T18:09:53
2021-02-01T21:35:24
Python
UTF-8
Python
false
false
409
py
""" ASGI config for ninjaGoldProject project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ninjaGoldProject.settings') application = get_asgi_application()
[ "ediaz-gutierrez@hotmail.com" ]
ediaz-gutierrez@hotmail.com
1626409a1035bc63d593bd9f20bc111b2d957b18
0e51d1be69b26a4bc2020db597b187b8b4784614
/03. Inheritance/03. project/knight.py
9793052c11a77fb1b7bfe8461711866ab89706ee
[]
no_license
dplamen/04_Python_OOP
81dbc21095ca776d9ce034dbe9959ca4903c8d82
cb0880a70c903e252958587d7051527527f57af4
refs/heads/main
2023-09-03T03:15:28.313039
2021-11-13T16:51:27
2021-11-13T16:51:27
427,719,779
0
0
null
null
null
null
UTF-8
Python
false
false
122
py
from project import Hero class Knight(Hero): def __init__(self, name, level): super().__init__(name, level)
[ "plamenkostov@gmail.com" ]
plamenkostov@gmail.com
814d38ad04c862e9ade6a62c9e8d11c619b2b54d
294bb6e4a439bceb3937ea1abd781389a4d7ae00
/clock_sync_ds/code/bloom_clock_4.py
143da17400ff6119486ac7813de44f819d162aaa
[]
no_license
rupeshkmr/Bloom-Clock
b282d966bcb62f8e839dbb97ae8fa3ec06f7f0a8
0928ed1d53000f68b7e54ec58144936aa51eef23
refs/heads/master
2022-12-02T20:27:51.297471
2020-08-16T09:31:32
2020-08-16T09:31:32
272,669,651
0
0
null
null
null
null
UTF-8
Python
false
false
5,456
py
# referenced from https://towardsdatascience.com/understanding-lamport-timestamps-with-pythons-multiprocessing-library-12a6427881c6 from multiprocessing import Process,Pipe,Manager from os import getpid from datetime import datetime from bloom_filter import BloomFilter from hasse import Hasse import json import csv n = 8#number of items_count p = 0.29 # False positive probability t = [0,0,0]# to store the global timestamp for each process #Helper Functions #Print Local timestamp and actual time on machine executing the processes def local_time(counter): return counter #Calculate new timestamp when a process receives a msg def calc_recv_timestamp(eid,recv_time_stamp, counter): counter.update_filter(eid,recv_time_stamp) return counter #prints all the previous timestamps for a particular process def print_history(counter,pid): print("Displaying histories of process pid = ",pid) for i in counter.history.keys(): print(i,":\t",counter.history[i]) #Function for every event that ma occur 1: Local event 2: Message send 3: Message Received #The event function will return updated timestamp #1 Local event #Input is local counter and process id #return local_timestamp +1 #eid is the event id string name def event(pid,counter,eid): global t,poset1 t[pid] += 1 #print('{} Event happened in {} !'.format(eid,pid)) #print("Ip filter\t:",counter.bit_array) counter.add(eid) #print("Op filter\t:",counter.bit_array) poset1[eid] = counter.bit_array data = {eid:counter.bit_array} with open('bloom_poset_4.txt', 'a') as outfile: json.dump(data, outfile) outfile.write("\n") return counter #2 Message send #Requires pid ,counter and a pipe for two way communication #pipe creates two objects one for send and one for receive #it sends down it's updated counter alongwith the message in the pipe def send_message(pipe,pid,counter,eid): global t,poset1 t[pid]+=1 #print('Message sent from ' +str(pid)+" event id "+eid) #print("Ip filter\t:",counter.bit_array) counter.add(eid) #print("Op filter\t:",counter.bit_array) poset1[eid] = counter.bit_array data = {eid:counter.bit_array} with open('bloom_poset_4.txt', 'a') as outfile: json.dump(data, outfile) outfile.write("\n") pipe.send((eid,counter)) # #print(counter.bit_array) return counter #3 Message Receive #receives message, timestamp by invoking recv function on pipe #Then it further calculates it's new timestamp depending upon the received timestamp and current timestamp def recv_message(pipe,pid,counter,eid): global t,poset1 t[pid]+=1 #print('Message received at '+ str(pid)+"event id "+eid) #print("Ip filter\t:",counter.bit_array) #counter.add(eid) message,timestamp = pipe.recv(); #print("\tfrom: "+message+" timestamp\t:",end="") #print(timestamp.bit_array) counter = calc_recv_timestamp(eid,timestamp,counter) #print("Op filter\t:",counter.bit_array) poset1[eid] = counter.bit_array data = {eid:counter.bit_array} with open('bloom_poset_4.txt', 'a') as outfile: json.dump(data, outfile) outfile.write("\n") # #print(counter.bit_array) return counter #Defenitions for three processes #Each process starts with getting it's process id and sets it's counter to 0 def process_one(pipe12,pipe13): pid = 0 counter = BloomFilter(n,p,0) counter = send_message(pipe13,pid,counter,'a') counter = recv_message(pipe12,pid,counter,'b') counter = recv_message(pipe12,pid,counter,'c') def process_two(pipe21,pipe23): pid = 1 counter = BloomFilter(n,p,0) counter = event(pid,counter,'d') counter = send_message(pipe21,pid,counter,'e') counter = send_message(pipe21,pid,counter,'f') def process_three(pipe31,pipe32): pid = 2 counter = BloomFilter(n,p,0) counter = recv_message(pipe31,pid,counter,'g') counter = event(pid,counter,'h') #counter = send_message(pipe31,pid,counter,'j') #counter = recv_message(pipe31,pid,counter,'k') #counter = recv_message(pipe32,pid,counter,'l') #counter = event(pid,counter,'m') #to draw a hasse representing casual ordering of the events def get_ordering(poset): ##print(poset) # poset = list(return_dict.values()) hasse = Hasse(poset) #hasse.print_table() print(hasse.hasse) with open('bloom_poset.csv','a') as openfile: csvwriter = csv.writer(openfile,delimiter=',') for i in hasse.table: csvwriter.writerow(i) if __name__ == '__main__': poset1 = {} poset= []#to store the bloomfilter values at each event oneandtwo, twoandone = Pipe() twoandthree, threeandtwo = Pipe() oneandthree, threeandone = Pipe() process1 = Process(target=process_one,args=(oneandtwo,oneandthree)) process2 = Process(target=process_two,args=(twoandone,twoandthree)) process3 = Process(target=process_three,args=(threeandone,threeandtwo)) process1.start() process2.start() process3.start() process1.join() process2.join() process3.join() poset = {} with open('bloom_poset_4.txt') as json_file: for jsonobj in json_file: data = json.loads(jsonobj)#[json.load(line) for line in json_file] poset[list(data.keys())[0]] = data[list(data.keys())[0]] get_ordering(poset) ##print(poset)
[ "rupeshkmr955@gmail.com" ]
rupeshkmr955@gmail.com
8d3073bcfd4fbf7022fdc56c8e182030feed1fb7
de674c103f1dd184d97f56493c62ef50973c655e
/Exercise4_Phasit_P.py
1de7ed289c50fe0d10b69861f80640bcb2cf8da3
[]
no_license
FlorkforGithub/CP3-Phasit-Supharojdilok
64f2e0c37ffa2e7dcd453861d94777180c43792d
ab61702501009d0dc24276fac906de0438734065
refs/heads/main
2023-02-08T02:08:46.788335
2021-01-01T16:23:29
2021-01-01T16:23:29
325,516,442
0
0
null
null
null
null
UTF-8
Python
false
false
588
py
''' เก็บข้อมูลคะแนนสอน 4 วิชา ของนักศึกษา ''' ''' รายวิชาทั้ง4 ''' Fe = " Subject : Foundation English" Gb = " Subject : General Bussiness" Cs = " Subject : Introduction to Computer System" Cp = " Subject : Computer Programming" '''s = student''' s_Fe= Fe+':'+ " 10 point = A Grade" s_Gb= Gb+':'+ " 5 point = B Grade" s_Cs= Cs+':'+ " 2.5 point = C Grade" s_Cp= Cp+':'+ " 9 point = A Grade" print("------------Student Score------------") print(s_Fe) print(s_Gb) print(s_Cs) print(s_Cp)
[ "Florkphasit@hotmail.com" ]
Florkphasit@hotmail.com
8d220ca7329f6275ed998c629538a17f89c22dff
94c9ce58200f255920e4006deda65cc6ddb24575
/RESUMEWEBSITE/settings.py
0332874cf16048f75a9810deaa1b55b7f577bf9a
[]
no_license
puja81198/ResumeWebsite
3e5ff1cfb3d4b328a0f12125879d8d883db753ef
9a31c323a34144dcfbebff52550448ba36584082
refs/heads/master
2023-06-03T23:31:36.010731
2021-06-20T09:00:49
2021-06-20T09:00:49
378,599,977
0
0
null
null
null
null
UTF-8
Python
false
false
3,264
py
""" Django settings for RESUMEWEBSITE project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+i-46b5w^zo9i^no^x!q=c-i6&l-mftat$5_91@6i!ugwjv@u(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'resumeapp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'RESUMEWEBSITE.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'RESUMEWEBSITE.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=[ STATIC_DIR ]
[ "p81198@gmail.com" ]
p81198@gmail.com
cc20e260af9a3ff85b8c39ca5df665f100fa4eff
beeee5695deeb3b21eefcf44b31558746e9bc575
/build/segmentation/catkin_generated/pkg.develspace.context.pc.py
627464c637c630f50e4462711b39aa275d67e041
[]
no_license
mannylazalde/EECS106A
47db0728a02db498e77184010f1b59983c5a98a2
0ac0de951bdba56eb8634711448677b7c8a73114
refs/heads/master
2020-09-13T11:48:36.878212
2019-12-21T07:03:57
2019-12-21T07:03:57
222,768,305
0
0
null
null
null
null
UTF-8
Python
false
false
412
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "segmentation" PROJECT_SPACE_DIR = "/home/cc/ee106a/fa19/class/ee106a-abe/ros_workspaces/project/devel" PROJECT_VERSION = "0.0.0"
[ "mannylazalde@berkeley.edu" ]
mannylazalde@berkeley.edu
f098e7c71f2213558005887d417d8f3e749e4ed3
2238d81eb5a8f1b6d8a0364319533b0b58f5b019
/youtube/views.py
2c5ec119f11e6f20dd6885f656e2ac57b1e4d895
[]
no_license
gar-den/py_web_ver1
9e14aefbf3362ec3c0b1f36de1ebd605b0325442
7408180ccbdf22b689cb5325a87b5e13e799964a
refs/heads/master
2022-12-30T14:51:26.137041
2020-10-24T01:42:09
2020-10-24T01:42:09
287,203,270
0
0
null
2020-08-14T08:37:19
2020-08-13T06:48:53
Python
UTF-8
Python
false
false
185
py
from django.shortcuts import render from django.views.generic import ListView from youtube.models import Youtube # Create your views here. class YoutubeLV(ListView): model = Youtube
[ "prepella3@gmail.com" ]
prepella3@gmail.com
299305ee4aee9caf43fa57f664f00935d1ae6ae7
5f23bfaac3a29bec0e1fc84d2041e56fb08d6122
/Hearts/Hearts/Team.py
7c63bf01ab597c521a170eb909a0c6fa80203384
[]
no_license
dscott-kamen/Hearts
27a217c90a4ce91c4948b21b4b5a5e18fba699d0
d27c96d01e9de6b8bdda3f04c724ad2599f5dba4
refs/heads/master
2020-06-01T02:29:48.970934
2019-06-18T15:54:47
2019-06-18T15:54:47
190,597,300
0
0
null
null
null
null
UTF-8
Python
false
false
855
py
''' Created on Apr 23, 2019 @author: Doug Kamen ''' class Team(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.roundScore = 0 self.totalScore = 0 self.bags = 0 self.hands = [] def setBags(self, bags): self.bags = bags def getBags(self): return self.bags def setTotalScore(self, totalScore): self.totalScore = totalScore def getTotalScore(self): return self.totalScore def setRoundScore(self, roundScore): self.__roundScore = roundScore def getRoundScore(self): return self.roundScore def addHand(self, hand): self.hands.append(hand) def getHands(self): return self.hands
[ "Doug Kamen@LAPTOP-N8E98DTQ.attlocal.net" ]
Doug Kamen@LAPTOP-N8E98DTQ.attlocal.net
b93d484729f23cb51cfb7cf363ab0cd5e3f534f6
2dd3f59b229bebd3486bbc9dfa6d661419e28cd9
/fibonacci_last_digit_fd.py
21135cc6f45dce0fcb54fc4ea7c42a8bbe07a637
[]
no_license
rajfal/algos
7e73e17dccc60ff28bc19bc1c7786c9f5e797efa
cc2cd8a4947a893822f682f31fe89e81cb52373c
refs/heads/master
2021-01-22T20:50:15.718882
2017-06-06T01:59:40
2017-06-06T01:59:40
85,369,076
0
0
null
null
null
null
UTF-8
Python
false
false
906
py
# # Fast doubling Fibonacci algorithm (Python) # # Copyright (c) 2015 Project Nayuki # All rights reserved. Contact Nayuki for licensing. # https://www.nayuki.io/page/fast-fibonacci-algorithms # import sys # (Public) Returns F(n). def fibonacci(n): if n < 0: raise ValueError("Negative arguments not implemented") return _fib(n)[0] # (Private) Returns the tuple (F(n), F(n+1)). def _fib(n, count=0): if n == 0: print(count) return (0, 1) else: a, b = _fib(n // 2, count=count+1) c = a * (b * 2 - a) d = a * a + b * b if n % 2 == 0: return (c, d) else: return (d, c + d) # Recursive def rec(a, b): if (b > a): return a else: return rec(a - 1, b+ 1) # Iterative def rec2(a, b): while b <= a: a = a - 1 b = b + 1 return a print(rec2(30, 20))
[ "noreply@github.com" ]
rajfal.noreply@github.com
4449e49661a93160ebe5eee3a2b91f66910ff3fe
c5042a26594b2b8758128b6e0a623393acdb0464
/Assignments/Week 7/Lab7-1.py
e615842c95a9e31a9c36f1c8cf758bddcc549efd
[]
no_license
ian-garrett/CIS_122
892e72c167f5bbdefb3a2ce7f5c744d5e3f58c8f
a0ba7982357887a0758ca099189c2777ac3d3960
refs/heads/master
2021-01-23T18:50:03.047509
2015-05-16T00:45:43
2015-05-16T00:45:43
35,703,569
0
0
null
null
null
null
UTF-8
Python
false
false
1,171
py
# by Ian Garrett' # Lab 7-1 print ("Welcome to my turtle program\n") import turtle turtle.speed(0) def get_ok(): ok = input("Do again? Press y or n") ok = ok.lower() + "x" ok = ok[0] return ok def ask_y_or_n(question): answer = ' ' while answer != 'y' and answer != 'n': answer = input (question + "'Press y or n ") answer = answer .lower() + "x" answer = answer[0] return answer def get_float(prompt): temp = input(prompt + ' ') return float(temp) def get_int(prompt): temp = input(prompt + ' ') return int(temp) def get_str(prompt): temp = input(prompt + ' ') return str(temp) rerun = 'y' while rerun == 'y': turtle.reset() color = get_str("Enter line color ") bg_color = get_str("Enter background color ") angle = get_float("Enter angle to turn ") number_of_lines = get_int("Enter number of lines ") for i in range (number_of_lines): turtle.color(color) turtle.bgcolor(bg_color) turtle.forward(100) turtle.right(angle) rerun = "n" print ("Exiting program...")
[ "igarrett@uoregon.edu" ]
igarrett@uoregon.edu
3e4b24a783839a4c708bc72c6f8d4fdcd529d307
261af4075ccb5e838af1a5274507691bd41ab707
/control-flow/range.py
ff848426b0c4ef091f48b7bf2fc6a44ad1cd12c6
[]
no_license
md-rabiul-hasan/Python
977cf8c8348a48abe27a885bc0185afb52458a34
45219762bb57be1be6d5b4ff9def85b2bb64a013
refs/heads/main
2023-03-06T23:50:18.406482
2021-02-14T03:01:06
2021-02-14T03:01:06
338,703,623
0
0
null
null
null
null
UTF-8
Python
false
false
193
py
for i in range(5) : print(i) for i in range(5,10, 2) : # value , end, stepping print(i) print(range(10)) ssum = sum(range(4)) print(ssum) print(list(range(0,10,2))) # [0, 2, 4, 6, 8]
[ "rabiul.fci@gmail.com" ]
rabiul.fci@gmail.com
77e2650141b3df3dd0db9e967a404402301ac1c6
17984a295f87b9f7f9c7f71caef7342117c3997e
/todo/migrations/0001_initial.py
b88665dfc5184431cc701a373f3e9792925ef58c
[]
no_license
rsalazarhanson/todolist
06058ecf15fc45fab333ab45e2c485819dd87323
4cf0f3b869a0681395b921c00d6999af7d9b2928
refs/heads/master
2022-04-25T15:45:42.432929
2020-04-25T19:00:53
2020-04-25T19:00:53
258,686,529
0
0
null
null
null
null
UTF-8
Python
false
false
998
py
# Generated by Django 3.0.5 on 2020-04-19 23:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Todo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('memo', models.TextField(blank=True)), ('created', models.DateTimeField(auto_now_add=True)), ('datecompleted', models.DateTimeField(null=True)), ('important', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "rsalazarhanson@gmail.com" ]
rsalazarhanson@gmail.com
d08f60a954f8103cf36b659ef841607c9ed7362f
1f49933377063f75262c50f978d316b1a7bdd483
/createDatabase.py
170b85002e04a58cdc21b3b317b372f1734a22c8
[]
no_license
hasadi/CognitiveHF-uhd
65c1793c2f76640b26a3f2aeea454094ab52e9e7
bfafdd046a5b3ffc25a71525bac4f62cf3b50295
refs/heads/master
2020-02-26T13:25:03.480647
2016-09-16T22:35:15
2016-09-16T22:35:15
68,416,908
0
0
null
null
null
null
UTF-8
Python
false
false
1,954
py
import time import numpy as np import random import math import sqlite3 from CE import * ###################################################################### conn=sqlite3.connect('config.db') print "Opened database successfully"; conn.execute('''CREATE TABLE CONFIG (ID INT PRIMARY KEY NOT NULL, MODULATION INT NOT NULL, Innercode INT NOT NULL, Outercode INT NOT NULL, TrialN INT NOT NULL, Total INT NOT NULL, Success INT NOT NULL, Throughput REAL NOT NULL, SQTh REAL NOT NULL);''') print "Table created successfully"; conn=sqlite3.connect('config.db') j=1 for m in xrange(0,11): ## for i in xrange(0,7): for o in xrange(0,8): conn.execute('INSERT INTO CONFIG (ID,MODULATION,Innercode,Outercode,TrialN,Total,Success,Throughput,SQTh) \ VALUES (?, ?, 0, ?, 0, 0, 0, 0.0, 0.0)',(j, m, o)); j=j+1 conn.commit() conn.close() print "Config Records created successfully"; ################################################################################################################################# conn=sqlite3.connect('rules.db') print "Opened rules database successfully"; conn.execute('''CREATE TABLE rules1 (idd INT PRIMARY KEY NOT NULL, ID INT NOT NULL, MODULATION INT NOT NULL, Innercode INT NOT NULL, Outercode INT NOT NULL);''') print "rules Table created successfully"; conn=sqlite3.connect('rules.db') conn.execute('INSERT INTO rules1 (idd,ID,MODULATION,Innercode,Outercode) \ VALUES (1,1, 0, 0, 0)'); conn.execute('INSERT INTO rules1 (idd,ID,MODULATION,Innercode,Outercode) \ VALUES (2,2, 0, 0, 0)'); conn.commit() conn.close() print "rules1 Records created successfully";
[ "asady.hamed@gmail.com" ]
asady.hamed@gmail.com
61b41d699962a32345f95dfdce17ff9e173bc03d
da1d3a5c7d6fa4c7d71d585272895ec53cf4b844
/feature_extractor.py
f3a7419ed4fd27fabf6edf3c0de87ead48bf737e
[]
no_license
teaf1001/DataChallenge
fdbd7af43fd0b757b5229f4a0c697c75bb8b9824
ae78844bae8e4c169406cb6cd5574568e9ce6fb8
refs/heads/master
2023-02-14T02:22:17.823989
2021-01-03T09:27:38
2021-01-03T09:27:38
326,348,973
1
0
null
null
null
null
UTF-8
Python
false
false
2,287
py
import features_reboot as features import init import numpy as np import json import jsonpickle import sys import datetime from glob import glob import csv import sys import os #folders = [r"E:\KISA-CISC2017-Malware-1st"] #csv_path = r"E:\label\2017_malware_1st_answer.csv" folders = sys.argv[1] # 추출 대상 파일 경로 csv_path = sys.argv[2] # 정답지 경로 savename = csv_path.split('/')[2].split('_')[0] # 피쳐 저장 이름 # 라벨 매핑 def label_check(hash): with open(csv_path, 'r') as reader: for line in reader: fields = line.strip().split(',') if fields[0].startswith(hash): return fields[1] # 피쳐 추출 def extract(filename): mal_data = open(filename, 'rb').read() # 실행 파일 열기 extractor = init.features.PEFeatureExtractor(2) #인자 2 고정 filehash=filename.split("/")[-1].split('.vir')[0] try: features = extractor.raw_features(mal_data, filename) # 피쳐 추출 features['label'] = label_check(filehash) # 라벨 매핑 features = jsonpickle.encode(features) # 피쳐 업데이트(라벨) except Exception as e: print(filename + " error: " + str(e)) return False return features if __name__ == '__main__': files = glob(folders + '/*.vir') num = -1 time = str(datetime.datetime.now()) path=time.split()[0].replace('-','_')+'_'+time.split()[1].replace(':','')[:6] savepath = os.makedirs(r'./features/'+path) for i in range(len(files)): if i % 100 == 0: num += 1 print(datetime.datetime.now(), savename +'_train_features_' + str(num) + '.jsonl') f = open('./features/'+ path+'/' + savename + '_train_features_'+str(num)+'.jsonl', 'a+', encoding='utf8') data = extract(files[i]) if data==False: print(files[i],': False',) continue else: data = data+'\n' f.write(data) f.close() #dddd ''' # 파일 하나만 뽑기 f = open("test_new", 'a+', encoding='utf8') data=extract(r"5b712f3ced695dd1510320494ecac67b277c0b386ee465303504c89431f87c78.vir") f.write(data) f.close() print(data) '''
[ "sin-yeongjae@sin-yeongjaeui-Mac-mini.local" ]
sin-yeongjae@sin-yeongjaeui-Mac-mini.local
49b7400ff1fb27da159f80419327e64298ec00db
9a4c569548c6aa96f9e137da1e4dba9a8dd0ec13
/catkin_ws/build/ur5_moveit_config/catkin_generated/pkg.develspace.context.pc.py
903c7800f8d6143865f2fe142b89bd26f6c954a4
[]
no_license
capf-2011/Vargi-Bots-eYRC
081014358a1b2f9cf55064d58ff2e5bdee554445
89b0bd0d5de1215e2338379931e31aea2e946ed3
refs/heads/master
2023-03-23T07:50:43.159560
2021-03-07T10:19:50
2021-03-07T10:19:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
406
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "ur5_moveit_config" PROJECT_SPACE_DIR = "/home/satyam/catkin_ws/devel/.private/ur5_moveit_config" PROJECT_VERSION = "1.2.5"
[ "satyamozar@gmail.com" ]
satyamozar@gmail.com
708a5fb086d03666cca8733239d0066138462d8f
599e320b8d66e86a77db268f8c26cf36e1ee4ec5
/DP/barn/barn_len.py
755e650842843682aa800a5a333b40c70b7149cb
[]
no_license
DariaMikhailovna/Algorithms
7f28b1582a5e451f20b9afe2d7773b3b57f39da7
13be99696ab9f6a22cc3cfa8efa292e9ae9f433e
refs/heads/master
2022-12-10T16:11:18.616755
2020-05-07T19:13:49
2020-05-07T19:13:49
221,887,652
0
0
null
2022-12-08T09:32:06
2019-11-15T09:15:00
Python
UTF-8
Python
false
false
456
py
def get_len(): n, m = map(int, input().split()) t = int(input()) matrix = [[1] * n for _ in range(m)] for i in range(t): c, r = list(map(int, input().strip().split())) matrix[r][c] = 0 for m_ in range(1, m): for n_ in range(n): if matrix[m_][n_] != 0: matrix[m_][n_] = matrix[m_ - 1][n_] + 1 for i in range(m): print(*matrix[i]) if __name__ == '__main__': get_len()
[ "0610-1994@mail.ru" ]
0610-1994@mail.ru
346d47583613b27aac0f54c6122283312a8ceb10
1299f84b3c8fc3c32395aaed716c7838f5612363
/flask_blog/main/routes.py
7baa571210f11f4c93b413c865a7bd0075af5a8e
[]
no_license
Mahdi-py/FlaskBlog
3086352e03f4c80aee8605b29497c513fcd9a03b
fc06d23256e9fe69355385fcca6f66d5e1727fca
refs/heads/master
2022-07-01T01:02:45.143600
2020-05-14T02:33:00
2020-05-14T02:33:00
261,048,728
0
0
null
null
null
null
UTF-8
Python
false
false
635
py
from flask import Blueprint from flask import render_template, request, Blueprint from flask_blog.models import Post main = Blueprint('main', __name__) @main.route('/') @main.route('/home') def home(): page = request.args.get('page', 1, type=int) # to identify the page number we want posts = Post.query.order_by(Post.date_posted.desc()).paginate(per_page=5, page=page) # to identify how many posts per page return render_template('home.html', posts=posts) @main.route('/about') def about(): return render_template('about.html', title='About')
[ "61730840+Mahdi-py@users.noreply.github.com" ]
61730840+Mahdi-py@users.noreply.github.com
1b4f8dc92b5359ccad11d45ce4e14519b47c409d
00c71b014f328ed841057754b77c350f4d7ff5f7
/customers/migrations/0007_auto_20190312_1358.py
c1e5f5ba6a9f3c1560e5cd5899eccfa372c4438c
[]
no_license
vlehra/djangoproject
c91aca392167316167acf87b8d09ff117ce80685
968c22a18f05fc338c79044388196f0960bffb5b
refs/heads/master
2020-04-29T09:15:22.170780
2019-04-18T07:54:15
2019-04-18T07:54:15
176,017,430
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
# Generated by Django 2.1.5 on 2019-03-12 08:28 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('customers', '0006_auto_20190311_1435'), ] operations = [ migrations.AlterField( model_name='customer', name='date_cust', field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 3, 12, 13, 58, 41, 799456)), ), migrations.AlterField( model_name='customer_detail', name='date_cust', field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 3, 12, 13, 58, 41, 799456)), ), ]
[ "vaibhavlehra@gmail.com" ]
vaibhavlehra@gmail.com
b96a098719f93c3d4ef9c9aff636a205cd38883c
fda9a6eabdeb6e41ea9023e112b7809b93936d86
/viewer/scenes.py
cf0e13d0c279a8e5f952fcd7132e05640210280b
[]
no_license
snsinfu/3dview
3c6f9b14192de0208ab0fc0605cc3be871b18b90
c80fd5c16bef6aec793204bcf37ce0b95617c3f0
refs/heads/master
2020-03-21T17:39:00.074821
2018-06-27T07:15:49
2018-06-27T07:21:05
138,844,796
1
0
null
null
null
null
UTF-8
Python
false
false
636
py
from vispy import gloo from shaders import CompositeShader class TranslucentScene(object): def __init__(self, shaders, background='black'): self._shader = CompositeShader(shaders) self._background = background def set_view_matrix(self, view): self._shader.set_view_matrix(view) def set_projection_matrix(self, proj): self._shader.set_projection_matrix(proj) def draw(self): gloo.set_state('translucent') gloo.clear(self._background, depth=True) gloo.gl.glClear(gloo.gl.GL_DEPTH_BUFFER_BIT) # XXX vispy does not clear depth buffer self._shader.draw()
[ "snsinfu@gmail.com" ]
snsinfu@gmail.com
3f251aa3b4a8d8a424bbb3c5ee2fbe0956835183
95e1a08dc19813180ce7e1668320160bd59122be
/src/examples/Client/generated_gui_client.py
ed071d380c8b859c39f3ad829ba6d5c896e1d14c
[]
no_license
SuperKuooo/ZYNC
8a1ee02aa37892716beae4eb439ac56375078478
3083828403135799de448967293462e01791bb6f
refs/heads/master
2020-06-13T23:10:34.315310
2019-07-26T09:26:55
2019-07-26T09:26:55
194,817,765
1
0
null
2019-07-24T10:27:13
2019-07-02T08:05:29
Python
UTF-8
Python
false
false
12,344
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ZYNC_Client.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_frmClientTerminal(object): def setupUi(self, frmClientTerminal): frmClientTerminal.setObjectName("frmClientTerminal") frmClientTerminal.resize(823, 464) self.centralwidget = QtWidgets.QWidget(frmClientTerminal) self.centralwidget.setObjectName("centralwidget") self.layoutWidget = QtWidgets.QWidget(self.centralwidget) self.layoutWidget.setGeometry(QtCore.QRect(10, 0, 641, 22)) self.layoutWidget.setObjectName("layoutWidget") self.horizontalLayout_11 = QtWidgets.QHBoxLayout(self.layoutWidget) self.horizontalLayout_11.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_11.setObjectName("horizontalLayout_11") self.lblListOfConnection = QtWidgets.QLabel(self.layoutWidget) font = QtGui.QFont() font.setFamily("Myriad Pro") font.setPointSize(12) self.lblListOfConnection.setFont(font) self.lblListOfConnection.setObjectName("lblListOfConnection") self.horizontalLayout_11.addWidget(self.lblListOfConnection) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setGeometry(QtCore.QRect(90, 265, 721, 31)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.layoutWidget_2 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_2.setGeometry(QtCore.QRect(570, 290, 241, 131)) self.layoutWidget_2.setObjectName("layoutWidget_2") self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.layoutWidget_2) self.verticalLayout_9.setContentsMargins(0, 0, 0, 0) self.verticalLayout_9.setObjectName("verticalLayout_9") self.btnStartClient = QtWidgets.QPushButton(self.layoutWidget_2) font = QtGui.QFont() font.setFamily("Myriad Pro") font.setPointSize(22) self.btnStartClient.setFont(font) self.btnStartClient.setAutoFillBackground(False) self.btnStartClient.setObjectName("btnStartClient") self.verticalLayout_9.addWidget(self.btnStartClient) self.verticalLayout_10 = QtWidgets.QVBoxLayout() self.verticalLayout_10.setObjectName("verticalLayout_10") self.horizontalLayout_12 = QtWidgets.QHBoxLayout() self.horizontalLayout_12.setObjectName("horizontalLayout_12") self.lblInputIP = QtWidgets.QLabel(self.layoutWidget_2) self.lblInputIP.setObjectName("lblInputIP") self.horizontalLayout_12.addWidget(self.lblInputIP) spacerItem = QtWidgets.QSpacerItem(38, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_12.addItem(spacerItem) self.linInputIP = QtWidgets.QLineEdit(self.layoutWidget_2) self.linInputIP.setObjectName("linInputIP") self.horizontalLayout_12.addWidget(self.linInputIP) self.verticalLayout_10.addLayout(self.horizontalLayout_12) self.horizontalLayout_13 = QtWidgets.QHBoxLayout() self.horizontalLayout_13.setObjectName("horizontalLayout_13") self.lblPort = QtWidgets.QLabel(self.layoutWidget_2) self.lblPort.setObjectName("lblPort") self.horizontalLayout_13.addWidget(self.lblPort) spacerItem1 = QtWidgets.QSpacerItem(28, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_13.addItem(spacerItem1) self.linPort = QtWidgets.QLineEdit(self.layoutWidget_2) self.linPort.setObjectName("linPort") self.horizontalLayout_13.addWidget(self.linPort) self.verticalLayout_10.addLayout(self.horizontalLayout_13) self.verticalLayout_9.addLayout(self.verticalLayout_10) self.lblStatusLog = QtWidgets.QLabel(self.centralwidget) self.lblStatusLog.setGeometry(QtCore.QRect(10, 265, 101, 21)) font = QtGui.QFont() font.setFamily("Myriad Pro") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lblStatusLog.setFont(font) self.lblStatusLog.setObjectName("lblStatusLog") self.txtStatusUpdate = QtWidgets.QTextEdit(self.centralwidget) self.txtStatusUpdate.setGeometry(QtCore.QRect(10, 290, 541, 131)) font = QtGui.QFont() font.setFamily("Myriad Pro") font.setPointSize(10) self.txtStatusUpdate.setFont(font) self.txtStatusUpdate.setReadOnly(True) self.txtStatusUpdate.setObjectName("txtStatusUpdate") self.lstTransferredFiles = QtWidgets.QListWidget(self.centralwidget) self.lstTransferredFiles.setGeometry(QtCore.QRect(12, 32, 541, 231)) self.lstTransferredFiles.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.lstTransferredFiles.setObjectName("lstTransferredFiles") self.btnUnzip = QtWidgets.QPushButton(self.centralwidget) self.btnUnzip.setGeometry(QtCore.QRect(568, 32, 241, 121)) font = QtGui.QFont() font.setFamily("Myriad Pro") font.setPointSize(22) self.btnUnzip.setFont(font) self.btnUnzip.setAutoFillBackground(False) self.btnUnzip.setObjectName("btnUnzip") self.linOutput = QtWidgets.QLineEdit(self.centralwidget) self.linOutput.setGeometry(QtCore.QRect(630, 160, 181, 20)) self.linOutput.setObjectName("linOutput") self.lblOuput = QtWidgets.QLabel(self.centralwidget) self.lblOuput.setGeometry(QtCore.QRect(570, 160, 51, 16)) self.lblOuput.setObjectName("lblOuput") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(640, 200, 171, 51)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.lblLocationResults = QtWidgets.QLabel(self.widget) self.lblLocationResults.setObjectName("lblLocationResults") self.verticalLayout.addWidget(self.lblLocationResults) self.lblTimeResults = QtWidgets.QLabel(self.widget) self.lblTimeResults.setObjectName("lblTimeResults") self.verticalLayout.addWidget(self.lblTimeResults) self.widget1 = QtWidgets.QWidget(self.centralwidget) self.widget1.setGeometry(QtCore.QRect(570, 200, 58, 51)) self.widget1.setObjectName("widget1") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget1) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.lblLocation = QtWidgets.QLabel(self.widget1) font = QtGui.QFont() font.setPointSize(10) self.lblLocation.setFont(font) self.lblLocation.setObjectName("lblLocation") self.verticalLayout_2.addWidget(self.lblLocation) self.lblTime = QtWidgets.QLabel(self.widget1) font = QtGui.QFont() font.setPointSize(10) self.lblTime.setFont(font) self.lblTime.setObjectName("lblTime") self.verticalLayout_2.addWidget(self.lblTime) frmClientTerminal.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(frmClientTerminal) self.menubar.setGeometry(QtCore.QRect(0, 0, 823, 21)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuSettings = QtWidgets.QMenu(self.menubar) self.menuSettings.setObjectName("menuSettings") frmClientTerminal.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(frmClientTerminal) self.statusbar.setObjectName("statusbar") frmClientTerminal.setStatusBar(self.statusbar) self.actionAuto_Reconnect = QtWidgets.QAction(frmClientTerminal) self.actionAuto_Reconnect.setObjectName("actionAuto_Reconnect") self.actionTimeout = QtWidgets.QAction(frmClientTerminal) self.actionTimeout.setObjectName("actionTimeout") self.actionReconnect_Time = QtWidgets.QAction(frmClientTerminal) self.actionReconnect_Time.setObjectName("actionReconnect_Time") self.actionHelp = QtWidgets.QAction(frmClientTerminal) self.actionHelp.setObjectName("actionHelp") self.actionClose = QtWidgets.QAction(frmClientTerminal) self.actionClose.setObjectName("actionClose") self.actionReset = QtWidgets.QAction(frmClientTerminal) self.actionReset.setObjectName("actionReset") self.actionSave_Directory = QtWidgets.QAction(frmClientTerminal) self.actionSave_Directory.setObjectName("actionSave_Directory") self.actionSave_Log = QtWidgets.QAction(frmClientTerminal) self.actionSave_Log.setObjectName("actionSave_Log") self.actionAuto_Unzip = QtWidgets.QAction(frmClientTerminal) self.actionAuto_Unzip.setObjectName("actionAuto_Unzip") self.menuFile.addAction(self.actionSave_Log) self.menuFile.addAction(self.actionClose) self.menuFile.addAction(self.actionReset) self.menuFile.addAction(self.actionHelp) self.menuSettings.addAction(self.actionAuto_Reconnect) self.menuSettings.addAction(self.actionAuto_Unzip) self.menuSettings.addAction(self.actionReconnect_Time) self.menuSettings.addAction(self.actionTimeout) self.menuSettings.addAction(self.actionSave_Directory) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuSettings.menuAction()) self.retranslateUi(frmClientTerminal) QtCore.QMetaObject.connectSlotsByName(frmClientTerminal) def retranslateUi(self, frmClientTerminal): _translate = QtCore.QCoreApplication.translate frmClientTerminal.setWindowTitle(_translate("frmClientTerminal", "Client Terminal")) self.lblListOfConnection.setText(_translate("frmClientTerminal", "Transferred Files")) self.btnStartClient.setText(_translate("frmClientTerminal", "START")) self.lblInputIP.setText(_translate("frmClientTerminal", "IP Address")) self.linInputIP.setText(_translate("frmClientTerminal", "192.168.1.118")) self.lblPort.setText(_translate("frmClientTerminal", "Port Number")) self.linPort.setText(_translate("frmClientTerminal", "8000")) self.lblStatusLog.setText(_translate("frmClientTerminal", "Status Log:")) self.btnUnzip.setText(_translate("frmClientTerminal", "UNPACT")) self.lblOuput.setText(_translate("frmClientTerminal", "Output:")) self.lblLocationResults.setText(_translate("frmClientTerminal", "None")) self.lblTimeResults.setText(_translate("frmClientTerminal", "None")) self.lblLocation.setText(_translate("frmClientTerminal", "Location: ")) self.lblTime.setText(_translate("frmClientTerminal", "Time: ")) self.menuFile.setTitle(_translate("frmClientTerminal", "File")) self.menuSettings.setTitle(_translate("frmClientTerminal", "Settings")) self.actionAuto_Reconnect.setText(_translate("frmClientTerminal", "Auto Reconnect")) self.actionTimeout.setText(_translate("frmClientTerminal", "Timeout")) self.actionReconnect_Time.setText(_translate("frmClientTerminal", "Reconnect Time")) self.actionHelp.setText(_translate("frmClientTerminal", "Help")) self.actionClose.setText(_translate("frmClientTerminal", "Close")) self.actionReset.setText(_translate("frmClientTerminal", "Reset")) self.actionSave_Directory.setText(_translate("frmClientTerminal", "Save Location")) self.actionSave_Log.setText(_translate("frmClientTerminal", "Save Log")) self.actionAuto_Unzip.setText(_translate("frmClientTerminal", "Auto Unzip")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) frmClientTerminal = QtWidgets.QMainWindow() ui = Ui_frmClientTerminal() ui.setupUi(frmClientTerminal) frmClientTerminal.show() sys.exit(app.exec_())
[ "jerrykuo820@gmail.com" ]
jerrykuo820@gmail.com
18503f562a8631a5dd079fd0e2bd0c2cd019d0e7
7bb27e5b89ff67b19fc3a2b28b42be42e737b3ec
/rest_tutorial/s4/code/security.py
6ff46d619544d1459c340fdf5c717dbaa0cb47b2
[]
no_license
obitech/tutorials
c87fe1c9820d67f9870426fff52746d560a1669f
a4b86a70bbeb76de2e1b4bae4d614d2ae0bb9c7b
refs/heads/master
2020-05-23T02:11:07.197006
2017-11-02T20:27:14
2017-11-02T20:27:14
84,741,493
0
0
null
null
null
null
UTF-8
Python
false
false
426
py
from user import User users = [ User(1, 'bob', 'abc') ] username_mapping = { u.username: u for u in users} userid_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) if user and user.password == password: return user # payload = content of JWT token def identity(payload): user_id = payload['identity'] return userid_mapping.get(user_id, None)
[ "the.am0k@gmx.de" ]
the.am0k@gmx.de
35a755dc8baf89055c4eb85e7e9f6bf0f24b42b1
e9d64b02a01214b1c6f083fe09c5126bf53ef515
/docs/conf.py
91205c0c3f33deb6bc1f7de9b3345097c6e1add0
[ "BSD-3-Clause" ]
permissive
lihang00/scikit-neuralnetwork
feababbb3a5db39f4dc865911fa3c78b9e217d5c
e16f591df5026807589d7564bb2f94ff0809e69e
refs/heads/master
2021-01-13T05:21:38.083474
2015-06-12T22:33:52
2015-06-12T22:33:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,830
py
# -*- coding: utf-8 -*- # # scikit-neuralnetwork documentation build configuration file, created by # sphinx-quickstart on Tue Mar 31 20:28:10 2015. import sys import os project = u'scikit-neuralnetwork' copyright = u'2015, scikit-neuralnetwork developers (BSD License)' # -- Configuration of documentation ------------------------------------------- # sys.path.append(os.path.dirname(os.path.dirname(__file__)).encode('utf-8')) import sknn version = sknn.__version__ release = sknn.__version__ extensions = ['sphinx.ext.autosummary', 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'numpydoc'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' exclude_patterns = ['_build'] pygments_style = 'sphinx' todo_include_todos = False # -- Overrides for modules ---------------------------------------------------- from mock import Mock as MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): if name in ('BaseEstimator', 'TransformerMixin', 'RegressorMixin', 'ClassifierMixin'): return object return Mock() MOCK_MODULES = ['numpy', 'theano', 'sknn.backend', 'sklearn', 'sklearn.base', 'sklearn.pipeline', 'sklearn.cross_validation', 'sklearn.preprocessing'] for fullname in MOCK_MODULES: segments = [] for s in fullname.split('.'): segments.append(s) mod_name = ".".join(segments) if mod_name not in sys.modules: sys.modules[mod_name] = Mock() # -- Options for HTML output -------------------------------------------------- html_title = 'scikit-neuralnetwork documentation' # html_logo = 'img/logo.png' # html_favicon = 'img/favicon.ico' html_static_path = ['_static'] htmlhelp_basename = 'sknndoc'
[ "alexjc@aigamedev.com" ]
alexjc@aigamedev.com
fab3f271f5738e8faba34e026e918b5949d34853
156554b4c94718af0b20bb4ae27bbc15f50ec059
/GDPRconsent/__init__.py
b74d9370ccb90820b6badc5f2059ec097f4c41ed
[ "MIT" ]
permissive
brassic-lint/gdpr-consent-string
1d3ca5a4830aa1df8e9283848f6f9a7cff80e19c
69add3b14745c7c1b573b66fa5dc30793aaa3039
refs/heads/master
2020-04-25T05:41:04.207610
2018-07-16T11:51:26
2018-07-16T11:51:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
123
py
from GDPRconsent.consent import Consent from GDPRconsent.consent_decoder import StringConsentDecoder name = "GDPRconsent"
[ "etrapero@acceso.com" ]
etrapero@acceso.com
4064d294f4238a13f7c3f3cdb692b5d489635da2
79e1b483198b64d44431ca821fda8318549b8c6c
/zlfs.py
3a791d2189030a0638b4739d41d62f30c0a63660
[]
no_license
xufucun/zhzl
b8ec473118880752eab0008ed71a5b9e209054ef
dd3ca88ea1f904cc23488df07620934457f660e2
refs/heads/master
2021-05-10T08:24:03.694146
2018-01-25T08:59:30
2018-01-25T08:59:30
118,888,389
0
0
null
null
null
null
UTF-8
Python
false
false
609
py
""" 获取知乎专栏粉丝 DATE:20180125 """ import requests # 请求链接 url = 'https://zhuanlan.zhihu.com/api/columns/alenxwn/followers' # 模拟浏览器 header = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/63.0.3239.132 Mobile Safari/537.36'} # 参数 data = {'limit': 20, 'offset': 40} # 获得数据 def get_data(): html = requests.get(url, params=data, headers=header) for n in range(len(html.json())): print(html.json()[n]['hash']) if __name__ == '__main__': get_data()
[ "xufucun@gmail.com" ]
xufucun@gmail.com
2f8755e473548b558b553e9baf43fcd11723fb3f
c845e02456ed0a4987de684a6d032b2dcaa23ba5
/blog/admin.py
7ee50b36e4fd2db90a174d0eae66a19829eb4359
[]
no_license
inkvizitor1991/Optimizing-the-Site
023203fd1a718a9178e019653fb34f4d4b2e15c5
761d108930b9663ef86e26ae815fc8403d09d302
refs/heads/main
2023-09-03T18:15:56.285005
2021-11-10T16:01:44
2021-11-10T16:01:44
420,957,982
0
0
null
null
null
null
UTF-8
Python
false
false
344
py
from django.contrib import admin from blog.models import Post, Tag, Comment class PostAdmin(admin.ModelAdmin): raw_id_fields = ('author', 'likes', 'tags') class CommentAdmin(admin.ModelAdmin): raw_id_fields = ('post', 'author') admin.site.register(Post,PostAdmin) admin.site.register(Tag) admin.site.register(Comment,CommentAdmin)
[ "85788805+inkvizitor1991@users.noreply.github.com" ]
85788805+inkvizitor1991@users.noreply.github.com
fc3270bfe0be25cc014d30c7e3917835e547f841
b8554b90dedaa2b4b6311dc9817160f3aeba1919
/l10n_ar_debit_credit_note/wizards/__init__.py
7ecdc05a8eeef12a68f36c9567553c34ffa5485e
[]
no_license
armandorg81/aitic-argentina-odoo
836c7f39c5084cc6a09499c65292030d8634ec1d
df0a40e7537d6ef6ecb6a21c33dcf3903704778e
refs/heads/master
2022-04-21T12:13:24.955080
2020-01-28T20:18:49
2020-01-28T20:18:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
97
py
# -*- coding: utf-8 -*- from . import account_invoice_debit from . import account_invoice_refund
[ "aparra@aitic.com.ar" ]
aparra@aitic.com.ar
c82cf537500229dbea0c0563f4ed084782152caa
1aecfba7cd453709f4676bdc39c6262225902732
/venv/bin/gunicorn_paster
d4f24805edf8344a31e97de8dbd503494113e64c
[]
no_license
JoaquinRoca/heroku_python
8e5f764e73124cbf1a3a5009c24a5f0aba61a0e2
1b5b35b1c162d8e2a0c4036fcbcd100461d12b79
refs/heads/master
2020-12-24T15:05:12.177433
2015-06-17T02:50:56
2015-06-17T02:50:56
37,420,580
0
0
null
null
null
null
UTF-8
Python
false
false
273
#!/Users/joaquinroca/python_projects/heroku_python/venv/bin/python2.7 # -*- coding: utf-8 -*- import re import sys from gunicorn.app.pasterapp import run if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(run())
[ "me@joaquinroca.com" ]
me@joaquinroca.com
5859658c2b11c214e2e9c2fe644c988070b1fb54
ade1a0b38e4128753d8b2a28bb1f8ef224ae4f56
/manage.py
9e3c71d991889aa428cb704de9d1cb5737044a77
[]
no_license
james-allen/astromapper
efdbb3db6507b29bacb7323dded4feeabf3277c5
6174f9bdacb0f63e745e0aac7137c567b7a5dc91
refs/heads/master
2020-05-22T13:19:38.939608
2015-09-19T00:33:36
2015-09-19T00:33:36
42,753,315
0
0
null
null
null
null
UTF-8
Python
false
false
254
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "astromapper.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "j.allen@physics.usyd.edu.au" ]
j.allen@physics.usyd.edu.au
96eb4824c3f7bdc697a50705e230d558c819654b
933b22e4168665f8737cedf2e05dbaec87219fb8
/application/posts/models.py
4558c3b38bfb06b34ccc749c7501c6ca0c26eb0d
[]
no_license
shtakai/flask_brueprint_socializer
7114116723aa5119f7dd3223357962c30ee0ab04
a0f07d614127dcbd740a80b09946d30cb709ad93
refs/heads/master
2021-04-15T03:44:27.465597
2016-08-14T06:25:29
2016-08-14T06:25:29
65,615,191
0
0
null
null
null
null
UTF-8
Python
false
false
748
py
__all__ = ['Post'] from application import db import datetime class Post(db.Model): # The unique primary key for each post created. id = db.Column(db.Integer, primary_key=True) # The free-form text-based content of each post. content = db.Column(db.Text()) # The date/time that the post was created on. created_on = db.Column(db.DateTime(), default=datetime.datetime.utcnow, index=True) # The user ID that created this post. user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % self.body def __init__(self, user_id, content): """Initialize a new Post object.""" self.user_id = user_id self.content = content
[ "shtakai@gmail.com" ]
shtakai@gmail.com
c360f9a9ce63394f5931d074266031400e036f84
6aa4d173e6f89fb3ca1952b42a51ea3f99b26782
/Server/game/html2text.py
90d5f0efe5b23a4e6bf29bfa0653ecd2a209c6c5
[]
no_license
RhostMUSH/trunk
3c2e849e57e405eff0f6882d197151284d8bd5b3
05fdec0d11ee8b015ab3f416e6bad839e3c318a2
refs/heads/master
2023-08-17T03:18:55.226735
2023-08-07T19:16:02
2023-08-07T19:16:02
23,922,823
30
26
null
2023-08-31T16:35:25
2014-09-11T14:57:33
C
UTF-8
Python
false
false
32,122
py
#!/usr/bin/env python """html2text: Turn HTML into equivalent Markdown-structured text.""" __version__ = "3.200.3" __author__ = "Aaron Swartz (me@aaronsw.com)" __copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3." __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"] # TODO: # Support decoded entities with unifiable. try: True except NameError: setattr(__builtins__, 'True', 1) setattr(__builtins__, 'False', 0) def has_key(x, y): if hasattr(x, 'has_key'): return x.has_key(y) else: return y in x try: import htmlentitydefs import urlparse import HTMLParser except ImportError: #Python3 import html.entities as htmlentitydefs import urllib.parse as urlparse import html.parser as HTMLParser try: #Python3 import urllib.request as urllib except: import urllib import optparse, re, sys, codecs, types try: from textwrap import wrap except: pass # Use Unicode characters instead of their ascii psuedo-replacements UNICODE_SNOB = 0 # Escape all special characters. Output is less readable, but avoids corner case formatting issues. ESCAPE_SNOB = 0 # Put the links after each paragraph instead of at the end. LINKS_EACH_PARAGRAPH = 0 # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.) BODY_WIDTH = 78 # Don't show internal links (href="#local-anchor") -- corresponding link targets # won't be visible in the plain text file anyway. SKIP_INTERNAL_LINKS = True # Use inline, rather than reference, formatting for images and links INLINE_LINKS = True # Number of pixels Google indents nested lists GOOGLE_LIST_INDENT = 36 IGNORE_ANCHORS = False IGNORE_IMAGES = False IGNORE_EMPHASIS = False ### Entity Nonsense ### def name2cp(k): if k == 'apos': return ord("'") if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3 return htmlentitydefs.name2codepoint[k] else: k = htmlentitydefs.entitydefs[k] if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1 return ord(codecs.latin_1_decode(k)[0]) unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"', 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*', 'ndash':'-', 'oelig':'oe', 'aelig':'ae', 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a', 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e', 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i', 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o', 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u', 'lrm':'', 'rlm':''} unifiable_n = {} for k in unifiable.keys(): unifiable_n[name2cp(k)] = unifiable[k] ### End Entity Nonsense ### def onlywhite(line): """Return true if the line does only consist of whitespace characters.""" for c in line: if c is not ' ' and c is not ' ': return c is ' ' return line def hn(tag): if tag[0] == 'h' and len(tag) == 2: try: n = int(tag[1]) if n in range(1, 10): return n except ValueError: return 0 def dumb_property_dict(style): """returns a hash of css attributes""" return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]); def dumb_css_parser(data): """returns a hash of css selectors, each of which contains a hash of css attributes""" # remove @import sentences data += ';' importIndex = data.find('@import') while importIndex != -1: data = data[0:importIndex] + data[data.find(';', importIndex) + 1:] importIndex = data.find('@import') # parse the css. reverted from dictionary compehension in order to support older pythons elements = [x.split('{') for x in data.split('}') if '{' in x.strip()] try: elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements]) except ValueError: elements = {} # not that important return elements def element_style(attrs, style_def, parent_style): """returns a hash of the 'final' style attributes of the element""" style = parent_style.copy() if 'class' in attrs: for css_class in attrs['class'].split(): css_style = style_def['.' + css_class] style.update(css_style) if 'style' in attrs: immediate_style = dumb_property_dict(attrs['style']) style.update(immediate_style) return style def google_list_style(style): """finds out whether this is an ordered or unordered list""" if 'list-style-type' in style: list_style = style['list-style-type'] if list_style in ['disc', 'circle', 'square', 'none']: return 'ul' return 'ol' def google_has_height(style): """check if the style of the element has the 'height' attribute explicitly defined""" if 'height' in style: return True return False def google_text_emphasis(style): """return a list of all emphasis modifiers of the element""" emphasis = [] if 'text-decoration' in style: emphasis.append(style['text-decoration']) if 'font-style' in style: emphasis.append(style['font-style']) if 'font-weight' in style: emphasis.append(style['font-weight']) return emphasis def google_fixed_width_font(style): """check if the css of the current element defines a fixed width font""" font_family = '' if 'font-family' in style: font_family = style['font-family'] if 'Courier New' == font_family or 'Consolas' == font_family: return True return False def list_numbering_start(attrs): """extract numbering from list element attributes""" if 'start' in attrs: return int(attrs['start']) - 1 else: return 0 class HTML2Text(HTMLParser.HTMLParser): def __init__(self, out=None, baseurl=''): HTMLParser.HTMLParser.__init__(self) # Config options self.unicode_snob = UNICODE_SNOB self.escape_snob = ESCAPE_SNOB self.links_each_paragraph = LINKS_EACH_PARAGRAPH self.body_width = BODY_WIDTH self.skip_internal_links = SKIP_INTERNAL_LINKS self.inline_links = INLINE_LINKS self.google_list_indent = GOOGLE_LIST_INDENT self.ignore_links = IGNORE_ANCHORS self.ignore_images = IGNORE_IMAGES self.ignore_emphasis = IGNORE_EMPHASIS self.google_doc = False self.ul_item_mark = '*' self.emphasis_mark = '_' self.strong_mark = '**' if out is None: self.out = self.outtextf else: self.out = out self.outtextlist = [] # empty list to store output characters before they are "joined" try: self.outtext = unicode() except NameError: # Python3 self.outtext = str() self.quiet = 0 self.p_p = 0 # number of newline character to print before next output self.outcount = 0 self.start = 1 self.space = 0 self.a = [] self.astack = [] self.maybe_automatic_link = None self.absolute_url_matcher = re.compile(r'^[a-zA-Z+]+://') self.acount = 0 self.list = [] self.blockquote = 0 self.pre = 0 self.startpre = 0 self.code = False self.br_toggle = '' self.lastWasNL = 0 self.lastWasList = False self.style = 0 self.style_def = {} self.tag_stack = [] self.emphasis = 0 self.drop_white_space = 0 self.inheader = False self.abbr_title = None # current abbreviation definition self.abbr_data = None # last inner HTML (for abbr being defined) self.abbr_list = {} # stack of abbreviations to write later self.baseurl = baseurl try: del unifiable_n[name2cp('nbsp')] except KeyError: pass unifiable['nbsp'] = '&nbsp_place_holder;' def feed(self, data): data = data.replace("</' + 'script>", "</ignore>") HTMLParser.HTMLParser.feed(self, data) def handle(self, data): self.feed(data) self.feed("") return self.optwrap(self.close()) def outtextf(self, s): self.outtextlist.append(s) if s: self.lastWasNL = s[-1] == '\n' def close(self): HTMLParser.HTMLParser.close(self) self.pbr() self.o('', 0, 'end') self.outtext = self.outtext.join(self.outtextlist) if self.unicode_snob: nbsp = unichr(name2cp('nbsp')) else: nbsp = u' ' self.outtext = self.outtext.replace(u'&nbsp_place_holder;', nbsp) return self.outtext def handle_charref(self, c): self.o(self.charref(c), 1) def handle_entityref(self, c): self.o(self.entityref(c), 1) def handle_starttag(self, tag, attrs): self.handle_tag(tag, attrs, 1) def handle_endtag(self, tag): self.handle_tag(tag, None, 0) def previousIndex(self, attrs): """ returns the index of certain set of attributes (of a link) in the self.a list If the set of attributes is not found, returns None """ if not has_key(attrs, 'href'): return None i = -1 for a in self.a: i += 1 match = 0 if has_key(a, 'href') and a['href'] == attrs['href']: if has_key(a, 'title') or has_key(attrs, 'title'): if (has_key(a, 'title') and has_key(attrs, 'title') and a['title'] == attrs['title']): match = True else: match = True if match: return i def drop_last(self, nLetters): if not self.quiet: self.outtext = self.outtext[:-nLetters] def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis fixed = google_fixed_width_font(tag_style) and not \ google_fixed_width_font(parent_style) and not self.pre if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o('`') self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = 0 self.outtext = self.outtext.rstrip() if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o('`') self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_last(2) self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1 def handle_tag(self, tag, attrs, start): #attrs = fixattrs(attrs) if attrs is None: attrs = {} else: attrs = dict(attrs) if self.google_doc: # the attrs parameter is empty for a closing tag. in addition, we # need the attributes of the parent nodes in order to get a # complete style description for the current element. we assume # that google docs export well formed html. parent_style = {} if start: if self.tag_stack: parent_style = self.tag_stack[-1][2] tag_style = element_style(attrs, self.style_def, parent_style) self.tag_stack.append((tag, attrs, tag_style)) else: dummy, attrs, tag_style = self.tag_stack.pop() if self.tag_stack: parent_style = self.tag_stack[-1][2] if hn(tag): self.p() if start: self.inheader = True self.o(hn(tag)*"#" + ' ') else: self.inheader = False return # prevent redundant emphasis marks on headers if tag in ['p', 'div']: if self.google_doc: if start and google_has_height(tag_style): self.p() else: self.soft_br() else: self.p() if tag == "br" and start: self.o(" \n") if tag == "hr" and start: self.p() self.o("* * *") self.p() if tag in ["head", "style", 'script']: if start: self.quiet += 1 else: self.quiet -= 1 if tag == "style": if start: self.style += 1 else: self.style -= 1 if tag in ["body"]: self.quiet = 0 # sites like 9rules.com never close <head> if tag == "blockquote": if start: self.p(); self.o('> ', 0, 1); self.start = 1 self.blockquote += 1 else: self.blockquote -= 1 self.p() if tag in ['em', 'i', 'u'] and not self.ignore_emphasis: self.o(self.emphasis_mark) if tag in ['strong', 'b'] and not self.ignore_emphasis: self.o(self.strong_mark) if tag in ['del', 'strike', 's']: if start: self.o("<"+tag+">") else: self.o("</"+tag+">") if self.google_doc: if not self.inheader: # handle some font attributes, but leave headers clean self.handle_emphasis(start, tag_style, parent_style) if tag in ["code", "tt"] and not self.pre: self.o('`') #TODO: `` `this` `` if tag == "abbr": if start: self.abbr_title = None self.abbr_data = '' if has_key(attrs, 'title'): self.abbr_title = attrs['title'] else: if self.abbr_title != None: self.abbr_list[self.abbr_data] = self.abbr_title self.abbr_title = None self.abbr_data = '' if tag == "a" and not self.ignore_links: if start: if has_key(attrs, 'href') and not (self.skip_internal_links and attrs['href'].startswith('#')): self.astack.append(attrs) self.maybe_automatic_link = attrs['href'] else: self.astack.append(None) else: if self.astack: a = self.astack.pop() if self.maybe_automatic_link: self.maybe_automatic_link = None elif a: if self.inline_links: self.o("](" + escape_md(a['href']) + ")") else: i = self.previousIndex(a) if i is not None: a = self.a[i] else: self.acount += 1 a['count'] = self.acount a['outcount'] = self.outcount self.a.append(a) self.o("][" + str(a['count']) + "]") if tag == "img" and start and not self.ignore_images: if has_key(attrs, 'src'): attrs['href'] = attrs['src'] alt = attrs.get('alt', '') self.o("![" + escape_md(alt) + "]") if self.inline_links: self.o("(" + escape_md(attrs['href']) + ")") else: i = self.previousIndex(attrs) if i is not None: attrs = self.a[i] else: self.acount += 1 attrs['count'] = self.acount attrs['outcount'] = self.outcount self.a.append(attrs) self.o("[" + str(attrs['count']) + "]") if tag == 'dl' and start: self.p() if tag == 'dt' and not start: self.pbr() if tag == 'dd' and start: self.o(' ') if tag == 'dd' and not start: self.pbr() if tag in ["ol", "ul"]: # Google Docs create sub lists as top level lists if (not self.list) and (not self.lastWasList): self.p() if start: if self.google_doc: list_style = google_list_style(tag_style) else: list_style = tag numbering_start = list_numbering_start(attrs) self.list.append({'name':list_style, 'num':numbering_start}) else: if self.list: self.list.pop() self.lastWasList = True else: self.lastWasList = False if tag == 'li': self.pbr() if start: if self.list: li = self.list[-1] else: li = {'name':'ul', 'num':0} if self.google_doc: nest_count = self.google_nest_count(tag_style) else: nest_count = len(self.list) self.o(" " * nest_count) #TODO: line up <ol><li>s > 9 correctly. if li['name'] == "ul": self.o(self.ul_item_mark + " ") elif li['name'] == "ol": li['num'] += 1 self.o(str(li['num'])+". ") self.start = 1 if tag in ["table", "tr"] and start: self.p() if tag == 'td': self.pbr() if tag == "pre": if start: self.startpre = 1 self.pre = 1 else: self.pre = 0 self.p() def pbr(self): if self.p_p == 0: self.p_p = 1 def p(self): self.p_p = 2 def soft_br(self): self.pbr() self.br_toggle = ' ' def o(self, data, puredata=0, force=0): if self.abbr_data is not None: self.abbr_data += data if not self.quiet: if self.google_doc: # prevent white space immediately after 'begin emphasis' marks ('**' and '_') lstripped_data = data.lstrip() if self.drop_white_space and not (self.pre or self.code): data = lstripped_data if lstripped_data != '': self.drop_white_space = 0 if puredata and not self.pre: data = re.sub('\s+', ' ', data) if data and data[0] == ' ': self.space = 1 data = data[1:] if not data and not force: return if self.startpre: #self.out(" :") #TODO: not output when already one there if not data.startswith("\n"): # <pre>stuff... data = "\n" + data bq = (">" * self.blockquote) if not (force and data and data[0] == ">") and self.blockquote: bq += " " if self.pre: if not self.list: bq += " " #else: list content is already partially indented for i in xrange(len(self.list)): bq += " " data = data.replace("\n", "\n"+bq) if self.startpre: self.startpre = 0 if self.list: data = data.lstrip("\n") # use existing initial indentation if self.start: self.space = 0 self.p_p = 0 self.start = 0 if force == 'end': # It's the end. self.p_p = 0 self.out("\n") self.space = 0 if self.p_p: self.out((self.br_toggle+'\n'+bq)*self.p_p) self.space = 0 self.br_toggle = '' if self.space: if not self.lastWasNL: self.out(' ') self.space = 0 if self.a and ((self.p_p == 2 and self.links_each_paragraph) or force == "end"): if force == "end": self.out("\n") newa = [] for link in self.a: if self.outcount > link['outcount']: self.out(" ["+ str(link['count']) +"]: " + urlparse.urljoin(self.baseurl, link['href'])) if has_key(link, 'title'): self.out(" ("+link['title']+")") self.out("\n") else: newa.append(link) if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done. self.a = newa if self.abbr_list and force == "end": for abbr, definition in self.abbr_list.items(): self.out(" *[" + abbr + "]: " + definition + "\n") self.p_p = 0 self.out(data) self.outcount += 1 def handle_data(self, data): if r'\/script>' in data: self.quiet -= 1 if self.style: self.style_def.update(dumb_css_parser(data)) if not self.maybe_automatic_link is None: href = self.maybe_automatic_link if href == data and self.absolute_url_matcher.match(href): self.o("<" + data + ">") return else: self.o("[") self.maybe_automatic_link = None if not self.code and not self.pre: data = escape_md_section(data, snob=self.escape_snob) self.o(data, 1) def unknown_decl(self, data): pass def charref(self, name): if name[0] in ['x','X']: c = int(name[1:], 16) else: c = int(name) if not self.unicode_snob and c in unifiable_n.keys(): return unifiable_n[c] else: try: return unichr(c) except NameError: #Python3 return chr(c) def entityref(self, c): if not self.unicode_snob and c in unifiable.keys(): return unifiable[c] else: try: name2cp(c) except KeyError: return "&" + c + ';' else: try: return unichr(name2cp(c)) except NameError: #Python3 return chr(name2cp(c)) def replaceEntities(self, s): s = s.group(1) if s[0] == "#": return self.charref(s[1:]) else: return self.entityref(s) r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") def unescape(self, s): return self.r_unescape.sub(self.replaceEntities, s) def google_nest_count(self, style): """calculate the nesting count of google doc lists""" nest_count = 0 if 'margin-left' in style: nest_count = int(style['margin-left'][:-2]) / self.google_list_indent return nest_count def optwrap(self, text): """Wrap all paragraphs in the provided text.""" if not self.body_width: return text assert wrap, "Requires Python 2.3." result = '' newlines = 0 for para in text.split("\n"): if len(para) > 0: if not skipwrap(para): result += "\n".join(wrap(para, self.body_width)) if para.endswith(' '): result += " \n" newlines = 1 else: result += "\n\n" newlines = 2 else: if not onlywhite(para): result += para + "\n" newlines = 1 else: if newlines < 2: result += "\n" newlines += 1 return result ordered_list_matcher = re.compile(r'\d+\.\s') unordered_list_matcher = re.compile(r'[-\*\+]\s') md_chars_matcher = re.compile(r"([\\\[\]\(\)])") md_chars_matcher_all = re.compile(r"([`\*_{}\[\]\(\)#!])") md_dot_matcher = re.compile(r""" ^ # start of line (\s*\d+) # optional whitespace and a number (\.) # dot (?=\s) # lookahead assert whitespace """, re.MULTILINE | re.VERBOSE) md_plus_matcher = re.compile(r""" ^ (\s*) (\+) (?=\s) """, flags=re.MULTILINE | re.VERBOSE) md_dash_matcher = re.compile(r""" ^ (\s*) (-) (?=\s|\-) # followed by whitespace (bullet list, or spaced out hr) # or another dash (header or hr) """, flags=re.MULTILINE | re.VERBOSE) slash_chars = r'\`*_{}[]()#+-.!' md_backslash_matcher = re.compile(r''' (\\) # match one slash (?=[%s]) # followed by a char that requires escaping ''' % re.escape(slash_chars), flags=re.VERBOSE) def skipwrap(para): # If the text begins with four spaces or one tab, it's a code block; don't wrap if para[0:4] == ' ' or para[0] == '\t': return True # If the text begins with only two "--", possibly preceded by whitespace, that's # an emdash; so wrap. stripped = para.lstrip() if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-": return False # I'm not sure what this is for; I thought it was to detect lists, but there's # a <br>-inside-<span> case in one of the tests that also depends upon it. if stripped[0:1] == '-' or stripped[0:1] == '*': return True # If the text begins with a single -, *, or +, followed by a space, or an integer, # followed by a ., followed by a space (in either case optionally preceeded by # whitespace), it's a list; don't wrap. if ordered_list_matcher.match(stripped) or unordered_list_matcher.match(stripped): return True return False def wrapwrite(text): text = text.encode('utf-8') try: #Python3 sys.stdout.buffer.write(text) except AttributeError: sys.stdout.write(text) def html2text(html, baseurl=''): h = HTML2Text(baseurl=baseurl) return h.handle(html) def unescape(s, unicode_snob=False): h = HTML2Text() h.unicode_snob = unicode_snob return h.unescape(s) def escape_md(text): """Escapes markdown-sensitive characters within other markdown constructs.""" return md_chars_matcher.sub(r"\\\1", text) def escape_md_section(text, snob=False): """Escapes markdown-sensitive characters across whole document sections.""" text = md_backslash_matcher.sub(r"\\\1", text) if snob: text = md_chars_matcher_all.sub(r"\\\1", text) text = md_dot_matcher.sub(r"\1\\\2", text) text = md_plus_matcher.sub(r"\1\\\2", text) text = md_dash_matcher.sub(r"\1\\\2", text) return text def main(): baseurl = '' p = optparse.OptionParser('%prog [(filename|url) [encoding]]', version='%prog ' + __version__) p.add_option("--ignore-emphasis", dest="ignore_emphasis", action="store_true", default=IGNORE_EMPHASIS, help="don't include any formatting for emphasis") p.add_option("--ignore-links", dest="ignore_links", action="store_true", default=IGNORE_ANCHORS, help="don't include any formatting for links") p.add_option("--ignore-images", dest="ignore_images", action="store_true", default=IGNORE_IMAGES, help="don't include any formatting for images") p.add_option("-g", "--google-doc", action="store_true", dest="google_doc", default=False, help="convert an html-exported Google Document") p.add_option("-d", "--dash-unordered-list", action="store_true", dest="ul_style_dash", default=False, help="use a dash rather than a star for unordered list items") p.add_option("-e", "--asterisk-emphasis", action="store_true", dest="em_style_asterisk", default=False, help="use an asterisk rather than an underscore for emphasized text") p.add_option("-b", "--body-width", dest="body_width", action="store", type="int", default=BODY_WIDTH, help="number of characters per output line, 0 for no wrap") p.add_option("-i", "--google-list-indent", dest="list_indent", action="store", type="int", default=GOOGLE_LIST_INDENT, help="number of pixels Google indents nested lists") p.add_option("-s", "--hide-strikethrough", action="store_true", dest="hide_strikethrough", default=False, help="hide strike-through text. only relevant when -g is specified as well") p.add_option("--escape-all", action="store_true", dest="escape_snob", default=False, help="Escape all special characters. Output is less readable, but avoids corner case formatting issues.") (options, args) = p.parse_args() # process input encoding = "utf-8" if len(args) > 0: file_ = args[0] if len(args) == 2: encoding = args[1] if len(args) > 2: p.error('Too many arguments') if file_.startswith('http://') or file_.startswith('https://'): baseurl = file_ j = urllib.urlopen(baseurl) data = j.read() if encoding is None: try: from feedparser import _getCharacterEncoding as enc except ImportError: enc = lambda x, y: ('utf-8', 1) encoding = enc(j.headers, data)[0] if encoding == 'us-ascii': encoding = 'utf-8' else: data = open(file_, 'rb').read() if encoding is None: try: from chardet import detect except ImportError: detect = lambda x: {'encoding': 'utf-8'} encoding = detect(data)['encoding'] else: data = sys.stdin.read() data = data.decode(encoding) h = HTML2Text(baseurl=baseurl) # handle options if options.ul_style_dash: h.ul_item_mark = '-' if options.em_style_asterisk: h.emphasis_mark = '*' h.strong_mark = '__' h.body_width = options.body_width h.list_indent = options.list_indent h.ignore_emphasis = options.ignore_emphasis h.ignore_links = options.ignore_links h.ignore_images = options.ignore_images h.google_doc = options.google_doc h.hide_strikethrough = options.hide_strikethrough h.escape_snob = options.escape_snob wrapwrite(h.handle(data)) if __name__ == "__main__": main()
[ "mrsenile@gmail.com" ]
mrsenile@gmail.com
82cf840ba3e0aef7cd5e83f5b1345dff0248f2bc
84115aea93154878ac65599ed9cb4988fce76e8c
/2nd_phase_code/exploratory/tracts_kmeans.py
c067c4b562acbbcc27a3fba4b6a6aa19f44a40c6
[]
no_license
BradyEngelke/msba_elp
b03939f6df3d79e98c1b55c06103de102a9216b3
29f527043dbde335b869b3f748f436f97735fb55
refs/heads/master
2022-07-15T05:17:57.961579
2020-05-15T15:39:40
2020-05-15T15:39:40
263,989,391
0
3
null
null
null
null
UTF-8
Python
false
false
1,954
py
from py2neo import Graph import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style="darkgrid") from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans graph = Graph('http://localhost:7474', password='cypha2') tracts = pd.DataFrame(graph.run(""" MATCH (t:Tract) WHERE t.date = 2019 RETURN t.name, t.total_pop, t.median_age, t.white_perc, t.black_perc, t.asian_perc, t.hdi_index, t.emp_unemployed_perc, t.edu_k_12_enrolled_perc, t.edu_college_undergrad_perc, t.edu_stem_degree_perc, t.edu_no_HS_diploma_households, t.edu_limited_english_households, t.hl_health_insured_perc, t.hl_life_expectancy, t.hs_eviction_rate_perc, t.inc_income_median, t.inc_total_enrolled_SNAP """).data()) cluster_df = tracts[['t.total_pop', 't.median_age', 't.emp_unemployed_perc', 't.edu_k_12_enrolled_perc', 't.edu_college_undergrad_perc', 't.hl_life_expectancy', 't.inc_income_median', 't.inc_total_enrolled_SNAP']] cluster_df = cluster_df.rename(columns={ 't.total_pop': 'pop', 't.median_age': 'age', 't.emp_unemployed_perc': 'unemployed_perc', 't.edu_k_12_enrolled_perc': 'k_12_perc', 't.edu_college_undergrad_perc': 'undergrad_perc', 't.hl_life_expectancy': 'life_exp', 't.inc_income_median': 'income', 't.inc_total_enrolled_SNAP': 'SNAP_enrollment' }) cluster_df = cluster_df.dropna() tracts_scaled = StandardScaler().fit_transform(cluster_df) x = list(range(1, 9)) y = [] for i in list(range(1, 9)): km = KMeans(n_clusters=i).fit(tracts_scaled) y.append(km.inertia_) sns.lineplot(x=x, y=y) plt.show(block=True) plt.interactive(False) km_final = KMeans(n_clusters=5).fit(tracts_scaled) cluster_df['cluster'] = km_final.labels_ clustered_tract_avgs = cluster_df.groupby('cluster').mean() clustered_tract_avgs = clustered_tract_avgs.round(2)
[ "noreply@github.com" ]
BradyEngelke.noreply@github.com
ffef9189714bac90c1249eed5cc90b4205c99cec
3e2c69c403ffaad7c5e69836c870075e96ce9572
/2252.py
fe3b1b4eaa21ad4dd2c2c58650b913addff5a843
[]
no_license
Hongyiel/algorithm_study
88252607117779fa9489a4087c21b215e75c87b5
18477da8085db56f7ee08cfa883a9444a2ff265c
refs/heads/main
2023-04-16T17:44:41.196908
2021-05-03T03:35:12
2021-05-03T03:35:12
328,557,597
0
0
null
null
null
null
UTF-8
Python
false
false
705
py
from collections import deque n, m = map(int, input().split()) in_degree = [0 for _ in range(n+1)] graph = [[] for _ in range(n+1)] q = deque() result = [] def sortRange(): for _ in range(n): print(q) print(graph) if not q: return target = q.popleft() result.append(target) for j in graph[target]: in_degree[j] -= 1 if not in_degree[j]: q.append(j) for _ in range(m): a, b = map(int, input().split()) graph[a].append(b) in_degree[b] += 1 for i in range(1, n+1): if in_degree[i] == 0: q.append(i) sortRange() print(*result) # 3 2 # 1 3 # 2 3
[ "suhho@oregonstate.edu" ]
suhho@oregonstate.edu
005705b8027973cdde1035fa4f275b774574a615
5588539c3733f3c212a0815bf9b692476e775e95
/mspray/apps/reveal/views.py
b1edfe2a521c855a77b69854b0102add27afe4dd
[ "Apache-2.0" ]
permissive
Frazerbesa/mspray
87605937b95a97a23333495de8b6353c3bf59889
b3e0f4b5855abbf0298de6b66f2e9f472f2bf838
refs/heads/master
2022-01-20T17:18:40.428046
2019-02-06T08:41:27
2019-02-06T08:41:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
713
py
"""views module for reveal""" from django.core.exceptions import ValidationError from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from mspray.apps.reveal.utils import add_spray_data @api_view(["GET", "POST"]) def add_spray_data_view(request): """Accepts data and passes it to the add_spray_data function""" if request.method == "POST": data = request.data try: add_spray_data(data) except ValidationError: pass else: return Response({"success": True}, status=status.HTTP_200_OK) return Response({"success": False}, status=status.HTTP_400_BAD_REQUEST)
[ "kjayanoris@gmail.com" ]
kjayanoris@gmail.com
7f322781490d01de8281072c57fe57c46ec6e724
b0958e674b9d562b9b983d26eca99747acc00365
/backend/apps/user/migrations/0009_auto_20200309_1428.py
ffe58a5080a239f08f6e34643da31971af4d68f6
[ "MIT" ]
permissive
IT-xiaoge/Journey
d55bae3d6a4e8ac6fddc39c492f9a6a4699341a1
43f241e25e6030ddae39cc06a74b3da70c48da34
refs/heads/master
2021-05-23T10:51:33.424181
2020-03-23T03:15:10
2020-03-23T03:15:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,144
py
# Generated by Django 2.0.4 on 2020-03-09 14:28 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('user', '0008_auto_20200303_1721'), ] operations = [ migrations.AddField( model_name='menu', name='api', field=models.CharField(blank=True, max_length=255, verbose_name='后端api接口地址'), ), migrations.AlterField( model_name='menu', name='mtype', field=models.IntegerField(blank=True, verbose_name='菜单类型 0:目录 1:菜单 2:权限 3:内部跳转url'), ), migrations.AlterField( model_name='menu', name='perms', field=models.CharField(blank=True, max_length=255, verbose_name='授权(多个用逗号分隔,如sys:user:post,sys:user:patch)'), ), migrations.AlterField( model_name='users', name='jwt_secret', field=models.UUIDField(default=uuid.UUID('70490f1b-e537-48b5-a85d-338ed0556221'), verbose_name='用户jwt加密秘钥'), ), ]
[ "977983452@qq.com" ]
977983452@qq.com
b78d22c718e0eac68bbac1d7ec6c144290552cbe
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/CropsPlantingInfo.py
2ed0cdb31c9a7141470a9bdac5c6225ccf088307
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
2,478
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class CropsPlantingInfo(object): def __init__(self): self._actual_date = None self._addition_info = None self._crop_code = None self._planting_area = None @property def actual_date(self): return self._actual_date @actual_date.setter def actual_date(self, value): self._actual_date = value @property def addition_info(self): return self._addition_info @addition_info.setter def addition_info(self, value): self._addition_info = value @property def crop_code(self): return self._crop_code @crop_code.setter def crop_code(self, value): self._crop_code = value @property def planting_area(self): return self._planting_area @planting_area.setter def planting_area(self, value): self._planting_area = value def to_alipay_dict(self): params = dict() if self.actual_date: if hasattr(self.actual_date, 'to_alipay_dict'): params['actual_date'] = self.actual_date.to_alipay_dict() else: params['actual_date'] = self.actual_date if self.addition_info: if hasattr(self.addition_info, 'to_alipay_dict'): params['addition_info'] = self.addition_info.to_alipay_dict() else: params['addition_info'] = self.addition_info if self.crop_code: if hasattr(self.crop_code, 'to_alipay_dict'): params['crop_code'] = self.crop_code.to_alipay_dict() else: params['crop_code'] = self.crop_code if self.planting_area: if hasattr(self.planting_area, 'to_alipay_dict'): params['planting_area'] = self.planting_area.to_alipay_dict() else: params['planting_area'] = self.planting_area return params @staticmethod def from_alipay_dict(d): if not d: return None o = CropsPlantingInfo() if 'actual_date' in d: o.actual_date = d['actual_date'] if 'addition_info' in d: o.addition_info = d['addition_info'] if 'crop_code' in d: o.crop_code = d['crop_code'] if 'planting_area' in d: o.planting_area = d['planting_area'] return o
[ "jishupei.jsp@alibaba-inc.com" ]
jishupei.jsp@alibaba-inc.com
89002b7ba7e2a0837b46746488412e38d8378680
d9c0cd08c22334e2e1f2a3de80d95a250436990f
/build/goal_set/catkin_generated/pkg.installspace.context.pc.py
9b5fe7787d2e4fa497bb4704848dee0cc3e84608
[]
no_license
temburuyk/rise_ws
88b96e027a65cedc49376171b66d69b6382a3c25
34567040945842784f438bc702d9ae3eb14f0f9f
refs/heads/master
2021-07-18T16:39:45.485621
2017-10-27T18:54:16
2017-10-27T18:54:16
108,579,035
1
0
null
null
null
null
UTF-8
Python
false
false
372
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "goal_set" PROJECT_SPACE_DIR = "/home/yashwant/rise_ws/install" PROJECT_VERSION = "0.0.0"
[ "temburuyk@gmail.com" ]
temburuyk@gmail.com
727198d4d30fcba99d7f86924fe4c259ac22f877
674f5dde693f1a60e4480e5b66fba8f24a9cb95d
/armulator/armv6/opcodes/concrete/ssub16_a1.py
97e11338e7793896109aef02af803c4965a9c1f9
[ "MIT" ]
permissive
matan1008/armulator
75211c18ebc9cd9d33a02890e76fc649483c3aad
44f4275ab1cafff3cf7a1b760bff7f139dfffb07
refs/heads/master
2023-08-17T14:40:52.793120
2023-08-08T04:57:02
2023-08-08T04:57:02
91,716,042
29
7
MIT
2023-08-08T04:55:59
2017-05-18T16:37:55
Python
UTF-8
Python
false
false
458
py
from armulator.armv6.bits_ops import substring from armulator.armv6.opcodes.abstract_opcodes.ssub16 import Ssub16 class Ssub16A1(Ssub16): @staticmethod def from_bitarray(instr, processor): rm = substring(instr, 3, 0) rd = substring(instr, 15, 12) rn = substring(instr, 19, 16) if rd == 15 or rn == 15 or rm == 15: print('unpredictable') else: return Ssub16A1(instr, m=rm, d=rd, n=rn)
[ "matan1008@gmail.com" ]
matan1008@gmail.com
c20c712ae52e9c55489f99d31bbcc3ddc0311148
c711b870b3c4f420e055e41190babbfee2c15c99
/mainProcessUI.py
09e153c98b092a988abac47cef3603a9d33008c6
[]
no_license
usino/Self-checkout
c5bcc349052cf7bb949b131500bdc1b676883066
148b198cc244881f84738aa32b63bb2fa5a413c8
refs/heads/master
2020-09-26T08:59:22.865137
2019-12-06T01:59:50
2019-12-06T01:59:50
226,222,298
0
0
null
null
null
null
UTF-8
Python
false
false
3,511
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainProcessUI.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.frameMenu = QtWidgets.QFrame(self.centralwidget) self.frameMenu.setMaximumSize(QtCore.QSize(50, 16777215)) self.frameMenu.setSizeIncrement(QtCore.QSize(0, 0)) self.frameMenu.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frameMenu.setFrameShadow(QtWidgets.QFrame.Raised) self.frameMenu.setObjectName("frameMenu") self.gridLayout_3 = QtWidgets.QGridLayout(self.frameMenu) self.gridLayout_3.setObjectName("gridLayout_3") self.pushButton_3 = QtWidgets.QPushButton(self.frameMenu) self.pushButton_3.setObjectName("pushButton_3") self.gridLayout_3.addWidget(self.pushButton_3, 3, 0, 1, 1) self.pushButton_4 = QtWidgets.QPushButton(self.frameMenu) self.pushButton_4.setObjectName("pushButton_4") self.gridLayout_3.addWidget(self.pushButton_4, 4, 0, 1, 1) self.pushButton_5 = QtWidgets.QPushButton(self.frameMenu) self.pushButton_5.setObjectName("pushButton_5") self.gridLayout_3.addWidget(self.pushButton_5, 5, 0, 1, 1) self.pushButton_2 = QtWidgets.QPushButton(self.frameMenu) self.pushButton_2.setObjectName("pushButton_2") self.gridLayout_3.addWidget(self.pushButton_2, 1, 0, 1, 1) self.pushButton_1 = QtWidgets.QPushButton(self.frameMenu) self.pushButton_1.setObjectName("pushButton_1") self.gridLayout_3.addWidget(self.pushButton_1, 0, 0, 1, 1) self.horizontalLayout.addWidget(self.frameMenu) self.gridLayout_4 = QtWidgets.QGridLayout() self.gridLayout_4.setObjectName("gridLayout_4") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setText("") self.label.setObjectName("label") self.gridLayout_4.addWidget(self.label, 0, 0, 1, 1) self.horizontalLayout.addLayout(self.gridLayout_4) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton_3.setText(_translate("MainWindow", "3")) self.pushButton_4.setText(_translate("MainWindow", "4")) self.pushButton_5.setText(_translate("MainWindow", "5")) self.pushButton_2.setText(_translate("MainWindow", "2")) self.pushButton_1.setText(_translate("MainWindow", "1"))
[ "noreply@github.com" ]
usino.noreply@github.com
02ae5de0ecdaedea5b8a3dc63be2667ba76018c7
a2733474a25d504903be46ad0602817708055374
/lambda/alertNotify/alert_notification_config.py
5c37e62374bf81eb633d57a3853f03821537041a
[]
no_license
XrizA/big_data_backend
c2470cb132e9134014feac36c63147eb2bba9ef0
ff64c58bb9b118209f60b9ecb7e2a56956f78670
refs/heads/main
2023-05-31T01:14:24.324195
2021-06-20T17:29:40
2021-06-20T17:29:40
378,690,059
0
0
null
null
null
null
UTF-8
Python
false
false
124
py
aws_access_key_id = 'your aws key ' aws_secret_access_key = 'your aws secret key' region_name = 'your aws region' ARN = ''
[ "suzngod1062474@gmail.com" ]
suzngod1062474@gmail.com
c0263a27dc0d5f52ae3207227f08690e9f1a2545
de01a51dcd29b05c1d90b87d1e57592e3fcb1a0d
/Euler/part1/p4.py
d0e2d61bd8339bc68267d1e695736d0556332aba
[]
no_license
qs8607a/Algorithm-39
9f9dea54f3098929c54fd669948c165cafb343b0
e1a106e98ba5002672acb7914dd827e4bd5f760c
refs/heads/master
2021-01-10T20:30:20.178902
2013-01-29T10:20:38
2013-01-29T10:20:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,729
py
##A palindromic number reads the same both ways. The largest palindrome made from ##the product of two 2-digit numbers is 9009 = 91 99. ##Find the largest palindrome made from the product of two 3-digit numbers. def isPalindromic(n): return str(n)==''.join(reversed(str(n))) def f1(): result=0 for i in range(999,99,-1): if i*999<=result: break for j in range(999,i-1,-1): if i*j<=result: break if isPalindromic(i*j) and i*j>result: result=i*j; return result def f2(): result=0 for i in range(999,99,-1): if i*999<=result: break for j in range(999 if i%11==0 else 990,i-1,-1 if i%11==0 else -11): if i*j<=result: break if isPalindromic(i*j) and i*j>result: result=i*j; return result def f3(): i=(999,999) result=0 while (sum(i)/2)**2>result: while i[1]<=i[0]: if isPalindromic(i[0]*i[1]) and i[0]*i[1]>result: result=i[0]*i[1] i=(i[0]-1,i[1]+1) i=(999,sum(i)-1000) return result from math import ceil def f4(): def makePalindromic(x): return int(str(x)+''.join(reversed(str(x)))) def isProductOfTwo(x): for i in range(ceil(x**0.5),1000): if x%i==0: return True return False return next(filter(isProductOfTwo,map(makePalindromic,range(999,99,-1)))) ##print(f1()) ##print(f2()) ##print(f3()) ##print(f4()) from timeit import Timer def test(): f4() t=Timer("test()","from __main__ import test") print(t.timeit(100)) ##print(f1())
[ "llq@gmail.com" ]
llq@gmail.com
98fcb55342df28798e6509142a57153fd0b115ec
b168ae36f71f5877553324ee21a00cd8ccb61269
/ios/manage.py
c00f88c1c7b16e6ac08214388d3e6e2da2989a9b
[]
no_license
davidamin/IOSBackend
e9b9595ccd1fb105eeb657c1f1e689d52748a09d
30b8344604596c90f8d3ad80daea0681cff66cd4
refs/heads/master
2016-08-11T13:01:44.346991
2015-12-04T05:05:27
2015-12-04T05:05:27
46,690,646
0
0
null
null
null
null
UTF-8
Python
false
false
246
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ios.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "ubuntu@ip-172-31-62-154.ec2.internal" ]
ubuntu@ip-172-31-62-154.ec2.internal
05833df3f8579a3eb93e90a581a2d832eaa99e02
621d94eddc55ed3ea4f5788ecdf9237bf9d9270f
/nicefolder/make3d_cost_graph.py
c32b3408514572ee9361062297c4fea1631cecc2
[]
no_license
epicarts/tensorflow
0b571892fd0f3158b2b36e4577a43c5ddf402ca2
4a12f5dbc86edd1ecc7d6bc54264b0f5223cd2f1
refs/heads/master
2020-03-27T11:11:44.294673
2019-02-25T11:57:15
2019-02-25T11:57:15
146,471,328
0
0
null
null
null
null
UTF-8
Python
false
false
9,019
py
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D import tensorflow as tf import pandas as pd from pandas import DataFrame, Series ''' 3d 그래프를 텐서플로우를 사용하여 그려보쟈!! 1. 3d 그래프에 대한 설정을 한다.(x좌표: Weight, y좌표: Bais, z좌표: cost) 2. x좌표와 y좌표를 전부 이용한다. cost 함수는 모든 x, y좌표값을 사용함 3. 모든 weight 와 bais를 cost 함수에 대입한 모든 값을 구해야한다. 4. weight값이 고정되어있을때, 혹은 bais 값이 고정되어있을때 cost를 생각해보라. 5. 위 식을 토대로 텐서플로우를 활용해서 그려보자. ''' #17*x^2-16*abs(x)*y+17*y^2=225 #z = func_z(x, y)#z = x**2/5. + x*y/50. + y**2/5. w_range = np.arange(-4.0, 4.0, 0.05) b_range = np.arange(-4.0, 4.0, 0.05) w, b = np.meshgrid(w_range, b_range) x = [1., 2., 3., 4., 5.] y = [2.1, 3.1, 4.1, 5.1, 6.1] w.shape b.shape cost_graph_3d(w, b, x, y) z = cost_graph(w, b, x) epoch = 10 w = 3 b = 3 learning_rate=0.05 figsize=(8, 5) def cost_graph_3d_gradient(w, b, x, y, epoch = 5, learning_rate=0.05, figsize=(8, 5)): ''' 3차원 공간에서 gradients를 사용하여 최저점을 찾아간다. w: 랜덤으로 주어진 weight 시작 값 b: 랜덤으로 주어진 bais 시작 값 x: input data [1., 2., 3., 4., 5.] y: label data [1., 2., 3., 4., 5.] ''' #초기 weight 값 설정하기. weight_init = tf.constant([w], tf.float32) #초기 bais값 설정하기. bais_init = tf.constant([b], tf.float32) #Variable()생성자로 tensor를 전달 받음. constant or random weight = tf.Variable(weight_init, name="weights") bais = tf.Variable(bais_init, name='bais') x_data = tf.constant(x, tf.float32) y_data = tf.constant(y, tf.float32) x_data #가설 설정 hypothesis = weight * x_data + bais hypothesis #cost 설정 / 최소 제곱 오차법 cost = tf.reduce_mean((tf.square(hypothesis - y_data))) #GradientDescentOptimizer를 사용하지 않고 tf.gradients 를 사용할 것이다. d_bais, d_weight = tf.gradients(cost, [bais, weight]) #기존값 - 미분값*learning_rate #assign 값을 바꿈. 기존 값 ==> 계산한 식으로 변경 update_w = tf.assign(weight, weight - (learning_rate * d_weight)) update_b = tf.assign(bais, bais - (learning_rate * d_bais)) #모델 파라미터를 업데이트 하는 텐서를 실행 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #시작 위치 저장 b_result = np.array([b], np.float32) w_result = np.array([w], np.float32) c_result = np.array([sess.run(cost)]) #모든 데이터를 돌리는 횟수(epoch) for step in range(epoch): #update를 하여 기존 assign을 변경 시킨다. sess.run([update_b, update_w]) #값이 바뀔때 마다 배열에 저장 b_val, w_val, c_val = sess.run([bais, weight, cost]) b_result = np.append(b_result, b_val) w_result = np.append(w_result, w_val) c_result = np.append(c_result, c_val) x fig, ax = plt.subplots(figsize=(10, 6)) ax.contour(w_result, b_result, c_result, levels=np.logspace(0, 5, 35), cmap=plt.cm.jet) ''' fig, ax = plt.subplots(figsize=figsize, subplot_kw={'projection': '3d'}) #그래프의 범위는 -|최대값| ~ |최대값| #x축 설정 w_abs = abs(w_result.max()) ax.set_xlabel('Weight') ax.set_xlim([-w_abs, w_abs]) #y축 설정 b_abs = abs(b_result.max()) ax.set_ylabel('Bais') ax.set_ylim([-b_abs, b_abs]) #cost 범위는 최소 0 ~ |최대값| #z축 설정 c_abs = abs(c_result.max()) ax.set_zlabel('Cost') ax.set_zlim([0, c_abs]) ax.invert_xaxis() ax.plot_surface(w, b, z, cmap='jet',rstride=1, cstride=1, linewidth=0) print("minimum cost:", z.min()) plt.show() ''' w_result.shape b_result.shape c_result.shape #여기서 움직이는 그래프 그리기. #화살표 추가 #3d 범위를 구해야함. #gradients를 사용하여 나온 b의 범위와 w의 범위를 이용하여, w, b값을 대입하쟈 #그래야 그래프 그리기 쉬울 듯. cost_graph_3d(w, b, x, y, figsize=(8, 5)) def two_variable_graph_gradient(): ''' 두 변수를 그린 그래프에서 최저 값을 찾아 내려가는 그래프를 그릴 예정ㄴ ''' x_gd, y_gd, z_gd = gradient_descent(x0, y0, learning_rate, epoch) ax1.plot(x_gd, y_gd, 'bo') for i in range(1, epoch+1): ax1.annotate('', xy=(x_gd[i], y_gd[i]), xytext=(x_gd[i-1], y_gd[i-1]), arrowprops={'arrowstyle': '->', 'color': 'r', 'lw': 1}, va='center', ha='center') def two_variable_graph(): ''' 두 변수의 상관관계를 나타낸 그래프를 그릴예정 여기에선 Weight 값과 bais 값사이를 알수 있겟징.. ''' a = np.arange(-3, 3, 0.05) b = np.arange(-3, 3, 0.05) x, y = np.meshgrid(a, b) z = func_z(x, y) fig1, ax1 = plt.subplots() ax1.contour(x, y, z, levels=np.logspace(-3, 3, 25), cmap='jet') def cost_graph_3d(w, b, x, y, figsize=(8, 5)): ''' w: weight 범위 np.meshgrid() 결과 값. b: bais 범위 np.meshgrid() 결과 값. x: input data [1., 2., 3., 4., 5.] y: label data [1., 2., 3., 4., 5.] 데이터 X, 예측값 Y, cost 함수(tensor type) ''' #Weight와 bais 3차원으로 변환, (x, y, 1) weight = tf.constant(w, shape=(w.shape[0], w.shape[1],1),dtype=tf.float32) weight bais = tf.constant(b, shape=(w.shape[0], w.shape[1],1),dtype=tf.float32) bais #차원 변경 (1, 1, data size) x_data = tf.constant(x,shape=(1, 1, len(x)),dtype=tf.float32) x_data y_data = tf.constant(y,shape=(1, 1, len(y)),dtype=tf.float32) y_data ##z = x**2/5. + x*y/50. + y**2/5. #가설 만들기 y = ax + b hypothesis = weight * x_data + bais hypothesis #cost 함수 3차원 값 합치기((예측값 - 실제값)^2 /5) cost = tf.sqrt(tf.reduce_mean(tf.square(hypothesis - y_data), axis=2)) cost with tf.Session() as sess: z = sess.run(cost) z.shape z #여기서 부터 그래프 그리기 fig, ax = plt.subplots(figsize=figsize, subplot_kw={'projection': '3d'}) #x축 설정 ax.set_xlabel('Weight') ax.set_xlim([w.min(), w.max()]) #y축 설정 ax.set_ylabel('Bais') ax.set_ylim([b.min(), b.max()]) #z축 설정 ax.set_zlabel('Cost') ax.set_zlim([z.min(), z.max()]) ax.invert_xaxis() ax.plot_surface(w, b, z, cmap='jet',rstride=1, cstride=1, linewidth=0) print("minimum cost:", z.min()) plt.show() ''' fig, ax2 = plt.subplots(figsize=(10, 6)) ax2.contour(w, b, z, cmap='jet',norm=LogNorm()) ''' a = LogNorm() a from matplotlib.colors import LogNorm cost_graph_3d(w, b, x, y) import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D import tensorflow as tf import pandas as pd from pandas import DataFrame, Series w_range = np.arange(-4.0, 4.0, 0.05) b_range = np.arange(-4.0, 4.0, 0.05) w, b = np.meshgrid(w_range, b_range) x = [1., 2., 3., 4., 5.] y = [2.1, 3.1, 4.1, 5.1, 6.1] cost_graph_3d(w, b, x, y) def cost_graph_3d(w, b, x, y, figsize=(8, 5)): ''' w: weight 범위 np.meshgrid() 결과 값. b: bais 범위 np.meshgrid() 결과 값. x: input data [1., 2., 3., 4., 5.] y: label data [1., 2., 3., 4., 5.] 데이터 X, 예측값 Y, cost 함수(tensor type) ''' #Weight와 bais 3차원으로 변환, (x, y, 1) weight = tf.constant(w, shape=(w.shape[0], w.shape[1],1),dtype=tf.float32) weight bais = tf.constant(b, shape=(w.shape[0], w.shape[1],1),dtype=tf.float32) bais #차원 변경 (1, 1, data size) x_data = tf.constant(x,shape=(1, 1, len(x)),dtype=tf.float32) x_data y_data = tf.constant(y,shape=(1, 1, len(y)),dtype=tf.float32) y_data ##z = x**2/5. + x*y/50. + y**2/5. #가설 만들기 y = ax + b hypothesis = weight * x_data + bais hypothesis #cost 함수 3차원 값 합치기((예측값 - 실제값)^2 /5) cost = tf.sqrt(tf.reduce_mean(tf.square(hypothesis - y_data), axis=2)) cost with tf.Session() as sess: z = sess.run(cost) z.shape z #여기서 부터 그래프 그리기 fig, ax = plt.subplots(figsize=figsize, subplot_kw={'projection': '3d'}) #x축 설정 ax.set_xlabel('Weight') ax.set_xlim([w.min(), w.max()]) #y축 설정 ax.set_ylabel('Bais') ax.set_ylim([b.min(), b.max()]) #z축 설정 ax.set_zlabel('Cost') ax.set_zlim([z.min(), z.max()]) ax.invert_xaxis() ax.plot_surface(w, b, z, cmap='jet',rstride=1, cstride=1, linewidth=0) print("minimum cost:", z.min()) plt.show() cost_graph_3d(w, b, x, y)
[ "0505zxc@gmail.com" ]
0505zxc@gmail.com
0a68cf069d2cb76e4209408adf21e61e6a70be83
838766d5150e3f1b4869fb06bf9e897f6bd54040
/venv/bin/django-admin
8701dc09babf822384c4dd88cb1c8a96fd0e05ec
[]
no_license
tcelik/DjangoApp
aca0a66916a7b694fa5154a436b265a384d7881d
7f727c599ac899fe7d121ded38f7abce69628b77
refs/heads/master
2020-04-15T19:28:55.824266
2019-01-09T23:25:23
2019-01-09T23:25:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
330
#!/Users/tugberk/Desktop/Kurslar/Python/src/DjangoWithIntellijApp/venv/bin/python # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
[ "mehmettugberkcelik@gmail.com" ]
mehmettugberkcelik@gmail.com
52b57870d45b2e64728eb50e46f8e63372d4ea5b
9ed7f1aca163cdb65ff2b46fdccffb4d0a473c4e
/练习/11_python的垃圾回收机制.py
40c0eaad58143ef4e731d2ecb94aa79b88fcad51
[]
no_license
xmlu2020/python_learn
f3d567e5038ac1f56b9860cd18c4c15a5ac6bde9
bb8ca4077eb987f4e60d5eb58b7df2a5c66026cd
refs/heads/master
2023-01-02T10:14:51.266254
2020-10-19T11:04:48
2020-10-19T11:04:48
277,552,512
0
0
null
null
null
null
UTF-8
Python
false
false
1,065
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/9/16 16:11 # @Author : XiaomeiLu # @FileName: 11_python的垃圾回收机制.py # @Software: PyCharm """ python垃圾回收主要以引用计数为主,标记-清除和分代清除为辅的机制,其中标记-清除 和分代回收主要是为了处理循环引用的难题 引用计数算法 当有1个变量保存了对象的引用时,此对象的引用计数就会加1 当使用del删除变量指向的对象时,如果独享的引用计数不为1,比如3,那么此时只会让这个引用计数 减1,即变为2,当再次调用del时,变为1,如果在调用1次del,此时会真的把对象进行删除 """ def __del__(self): print("__del__方法被调用") print("%s对象马上被干掉了..." % self.__name) cat = "波斯猫" cat2 = cat cat3 = cat print(id(cat), id(cat2), id(cat3)) print("---马上 删除cat对象") del cat print(id(cat2), id(cat3)) print("---马上 删除cat2对象") del cat2 print(id(cat3)) print("---马上 删除cat3对象") del cat3
[ "xmlu@aibee.com" ]
xmlu@aibee.com
3685139b4b8bde3db2388418149e456e5ecfa998
4acd6fcea175d92d8402904f193bb11bb887de22
/servidor/redOperonesJSON.py
afe96260cc2b74b855f9f681654b5e3088c99823
[]
no_license
AgustinPardo/mycoRT
5ab6cc471294357e14fd42ae46cd17221a3b3ccc
2d50e8d528ad3f0a3211982d3f1a1bf5cbe099b4
refs/heads/master
2021-07-01T08:00:50.870312
2019-08-21T20:10:18
2019-08-21T20:10:18
102,166,645
1
0
null
null
null
null
UTF-8
Python
false
false
831
py
from __future__ import print_function import mysql.connector def redRTOperones(): cnx = mysql.connector.connect(user='root', password="agustin", database='mycoDB') cursor = cnx.cursor() # Query query = ( "SELECT o1.operonID, o2.operonID FROM operons o1, operons o2, redRTOperons r WHERE o1.mfinderID = r.A AND o2.mfinderID = r.B;") cursor.execute(query) # Capturo la Query y la pongo en una lista de tuplas. rows = cursor.fetchall() listaAristas=[] listaNodos=[] listaControl=[] for row in rows: listaAristas.append({"op1":row[0],"op2":row[1]}) for elem in row: if elem not in listaControl: listaNodos.append({"rv":elem}) listaControl.append(row) nodosAristas={} nodosAristas["nodos"]=listaNodos nodosAristas["aristas"]=listaAristas cursor.close() cnx.close() print(nodosAristas)
[ "agu_pardo@hotmail.com" ]
agu_pardo@hotmail.com
9fda735e612bcc0a100e0481b836e13b86c40ae5
9db62269224ba5913eb9adfdf2e648dda4ed31c3
/cnocr/consts.py
9147212d3b155af045b771722270a2b79a862217
[ "NCSA", "Zlib", "Intel", "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-2-Clause-Views", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
Jinnrry/cnocr
acb72509a8825c98ba2fc8dfc4d15f847cb50d8a
e685db43622916b127728e0a714fef81036b8caa
refs/heads/master
2020-05-05T04:02:44.694466
2019-04-05T14:18:43
2019-04-05T14:18:43
179,695,433
1
0
null
null
null
null
UTF-8
Python
false
false
107
py
MODEL_BASE_URL = 'https://www.dropbox.com/s/5n09nxf4x95jprk/cnocr-models-v0.1.0.zip?dl=1' MODEL_EPOCE = 20
[ "breezedeus@163.com" ]
breezedeus@163.com
6241a31d4b9a7b6b7322874469928947427a22a6
47b75d1084cc3584a622dc1567ab866b89a0b62b
/luxon/utils/middleware.py
e0f31a5dc3b7dbfffab66787056cdf9440e5a8e3
[ "BSD-3-Clause" ]
permissive
Vuader/old_luxon
956152013aee93bd644c39a743e310bf151dd842
5d2417816ccad7491143bace9158d58c3feba32b
refs/heads/master
2021-09-10T15:19:40.731714
2018-01-14T18:02:47
2018-01-14T18:02:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,093
py
# -*- coding: utf-8 -*- # Copyright (c) 2018 Christiaan Frans Rademan. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. class MiddlewareWrapper(object): __slots__ = ( '_middleware', '_func' ) def __init__(self, middleware, func): self._middleware = middleware self._func = func @property def __doc__(self): return self._func.__doc__ def __call__(self, *args, **kwargs): self._middleware(*args, **kwargs) return self._func(*args, **kwargs) def middleware(middleware): def func_wrapper(func): return MiddlewareWrapper(middleware, func) return func_wrapper
[ "christiaan.rademan@gmail.com" ]
christiaan.rademan@gmail.com
6bbf8605b2a34bf5082402876f6879fe59b06a08
e951ec12086ea36bfb45424d6250dcd41259a134
/swegallery/gallery/migrations/0003_contact.py
791e3d15b4abc3b855550f9f1181afec7e326a88
[]
no_license
Niamulhasan11/SWE_Gallery
f7d274a7a867721674c9adfabd95e19f4b088767
1c0f0a568c5200be5954503d039a3fcb61987390
refs/heads/master
2022-12-02T00:17:26.162915
2020-08-14T08:12:32
2020-08-14T08:12:32
287,479,569
0
0
null
null
null
null
UTF-8
Python
false
false
689
py
# Generated by Django 3.0.8 on 2020-08-08 20:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gallery', '0002_auto_20200729_0139'), ] operations = [ migrations.CreateModel( name='contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=250)), ('email', models.EmailField(max_length=254)), ('subject', models.CharField(max_length=500)), ('message', models.TextField()), ], ), ]
[ "niamulhasan111@gmail.com" ]
niamulhasan111@gmail.com
bac053d577408eea75543b60753d156b6e9bc083
d5280a5dd28a81b9e3a687b7c5312a0a4c36353a
/Transactions/emptyEntryClassCreateAndContinueTestCase.py
a8c25fd2417de7b8ab9ab2a0a6c4b0e2f0162a07
[]
no_license
amritregmi/python_automation
4eb394ecbc09517eeae3edcd7ab6b8d335a58fb0
c514641a69c83dd3691eed973facf6f938dccd06
refs/heads/main
2023-03-07T06:02:36.563055
2021-02-19T21:40:08
2021-02-19T21:40:08
313,269,526
0
0
null
null
null
null
UTF-8
Python
false
false
1,712
py
from selenium.webdriver.support.ui import Select import os, sys sys.path.insert(0, os.path.abspath("..")) from Base import loggedInBaseTestCase class EmptyEntryClassCreateAndContinueTestCase(loggedInBaseTestCase.LoggedInBaseTestCase): def test_EmptyEntryClassCreateAndContinue(self): self._caseId = 138 self._suiteId = 2 self._user = "rumbu" self._password = "Test@123" driver = self.driver self.login() #current Url self.assertEqual(driver.current_url,"http://54.186.24.234/pages/dashboard") #Going To Transaction Menu driver.find_element_by_xpath("/html/body/div[1]/header/div/div[2]/ul[1]/li[2]/a").click() #clicking the create Button driver.find_element_by_xpath("/html/body/div[1]/header/div/div[2]/ul[1]/li[2]/ul/li[2]/a").click() #inserting value in Customer Name driver.find_element_by_id("TransactionCustomerName").send_keys("AmritRegmi") #inserting value in description driver.find_element_by_id("TransactionDescription").send_keys("This is Descriptopn") #inserting value in Routing Number driver.find_element_by_id("TransactionRoutingNumber").send_keys("123456789") #inserting Value In Amount driver.find_element_by_id("TransactionAmount").send_keys("234") #inserting value in Sec Code #transactions_entry_class = Select(driver.find_element_by_id("TransactionEntryClass")) #transactions_entry_class.select_by_visible_text("PPD") #inserting value in Account Number driver.find_element_by_id("TransactionAccountNumber").send_keys("") #CLicking the botton create and continue driver.find_element_by_id("createNext").click() #check if its in same link self.assertEqual(driver.current_url,"http://54.186.24.234/transactions/create")
[ "amrit@amrit.com" ]
amrit@amrit.com
16a89efdd04e4aaa80fcfabc958e5849e510f080
7d68ecca889f7a77932759fe58299e9e2a76001e
/src/video_emotion_color_demo.py
6504c79b257631cb0eab568e43933cc4f876ee7a
[]
no_license
harshfadadu/facial-expression-recognition-real-time
1e4a5125ae98529f39ad6a0a6a29afde097e2966
ecf1460f6e4d75b75e695c3431a4c0a0833cbd8d
refs/heads/master
2023-04-14T16:01:08.818141
2022-02-10T07:22:55
2022-02-10T07:22:55
204,751,501
1
0
null
2023-03-25T01:27:20
2019-08-27T17:09:14
Python
UTF-8
Python
false
false
3,163
py
from statistics import mode import cv2 from keras.models import load_model import numpy as np from utils.datasets import get_labels from utils.inference import detect_faces from utils.inference import draw_text from utils.inference import draw_bounding_box from utils.inference import apply_offsets from utils.inference import load_detection_model from utils.preprocessor import preprocess_input # parameters for loading data and images detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml' emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.29-0.62.hdf5' emotion_labels = get_labels('fer2013') # hyper-parameters for bounding boxes shape frame_window = 10 emotion_offsets = (20, 40) # loading models face_detection = load_detection_model(detection_model_path) emotion_classifier = load_model(emotion_model_path, compile=False) # getting input model shapes for inference emotion_target_size = emotion_classifier.input_shape[1:3] # starting lists for calculating modes emotion_window = [] # starting video streaming cv2.namedWindow('window_frame') video_capture = cv2.VideoCapture(0) while True: bgr_image = video_capture.read()[1] gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY) rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB) faces = detect_faces(face_detection, gray_image) for face_coordinates in faces: x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets) gray_face = gray_image[y1:y2, x1:x2] try: gray_face = cv2.resize(gray_face, (emotion_target_size)) except: continue gray_face = preprocess_input(gray_face, True) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) emotion_prediction = emotion_classifier.predict(gray_face) emotion_probability = np.max(emotion_prediction) emotion_label_arg = np.argmax(emotion_prediction) emotion_text = emotion_labels[emotion_label_arg] emotion_window.append(emotion_text) if len(emotion_window) > frame_window: emotion_window.pop(0) try: emotion_mode = mode(emotion_window) except: continue if emotion_text == 'angry': color = emotion_probability * np.asarray((255, 0, 0)) elif emotion_text == 'sad': color = emotion_probability * np.asarray((0, 0, 255)) elif emotion_text == 'happy': color = emotion_probability * np.asarray((255, 255, 0)) elif emotion_text == 'surprise': color = emotion_probability * np.asarray((0, 255, 255)) else: color = emotion_probability * np.asarray((0, 255, 0)) color = color.astype(int) color = color.tolist() draw_bounding_box(face_coordinates, rgb_image, color) draw_text(face_coordinates, rgb_image, emotion_mode, color, 0, -45, 1, 1) bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR) cv2.imshow('window_frame', bgr_image) if cv2.waitKey(1) & 0xFF == ord('q'): break
[ "noreply@github.com" ]
harshfadadu.noreply@github.com
da9a8fb990e076c40a614cffcc13160625e43c6f
1310b85ae7b3fdbf05745c81231b3c5cd88b6957
/AI/lab1/KNN/my_vs_sklearn.py
b70691462deeadb601d251039571460b9a3d7d9e
[]
no_license
Lester1707/Mywork
25c8085e74b6fd4aee8ee7dd39bec9e53f9b6c0b
d66eb4f1a2a280e1722ab37050260eda595db1ed
refs/heads/master
2021-08-16T16:53:30.700608
2021-06-25T15:14:35
2021-06-25T15:14:35
218,858,727
0
2
null
null
null
null
UTF-8
Python
false
false
1,358
py
from myKNN import KNN import numpy as np import pandas as pd from sklearn.datasets import load_breast_cancer from sklearn.metrics import confusion_matrix from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split breast_cancer = load_breast_cancer() X = pd.DataFrame(breast_cancer.data, columns=breast_cancer.feature_names) X = X[['mean area', 'mean compactness']] y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names) y = pd.get_dummies(y, drop_first=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) knn1 = KNeighborsClassifier(n_neighbors=5, metric='euclidean') knn1.fit(X_train, y_train.values.ravel()) y_pred = knn1.predict(X_test) y_test = y_test.values.ravel() X_tmp = [[x1] for x1 in X_train['mean area']] i = 0 for element in X_train['mean compactness']: X_tmp[i].append(element) i += 1 X_train = X_tmp X_tmp = [[x1] for x1 in X_test['mean area']] i = 0 for element in X_test['mean compactness']: X_tmp[i].append(element) i += 1 X_test = X_tmp count = 0 knn2 = KNN(X_train, y_train.values.ravel()) for j in range(len(X_test)): if y_test[j] == knn2.classification(5, X_test[j]): count += 1 print(float(count)/len(y_pred)) count = 0 for j in range(len(y_pred)): if y_pred[j] == y_test[j]: count += 1 print(float(count)/len(y_pred))
[ "antylol311@gmail.com" ]
antylol311@gmail.com
5bd6343ecea5951ab07e334dc403a8fdbaedd594
ba77287322dfe0ceaa4db6285951252a0dce482f
/accounts/forms.py
34f00add8427efa782bcb6c3a384c188a1c523ea
[]
no_license
dash9231/assignment_3
52245a918b6f1299b213996c2fd3bad2621c3473
9a72887edcfcc83a96da39161bfa6a43ffc2fb90
refs/heads/master
2020-05-16T22:32:19.765827
2015-08-25T12:20:02
2015-08-25T12:20:02
41,361,497
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
from django import forms from accounts.models import UserProfile from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1', 'password2') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture')
[ "dash9231@gmail.com" ]
dash9231@gmail.com
3a00b624fcad6e46c859e40eb09612fac83daad5
6febcc9e34f44bebe36908a443400d8d4f3fdf53
/lib/python/setup.py
d94fd5a83843d42ee246de9a65715d70c9ff77c8
[ "Apache-2.0" ]
permissive
ray-project/photon
517b133d3dd04a0765f400595d13e3a95cd99900
63ec24478487de76a984c525c0303e3a817e885d
refs/heads/master
2023-08-29T08:46:26.468069
2016-10-19T01:27:43
2016-10-19T01:27:43
68,425,226
1
1
null
2016-10-19T01:27:43
2016-09-17T01:26:57
Python
UTF-8
Python
false
false
699
py
from setuptools import setup, find_packages, Extension photon_module = Extension("photon", sources=["photon_extension.c", "../../common/lib/python/common_extension.c"], include_dirs=["../../", "../../common/", "../../common/thirdparty/", "../../common/lib/python"], extra_objects=["../../build/photon_client.a", "../../common/build/libcommon.a"], extra_compile_args=["--std=c99", "-Werror"]) setup(name="Photon", version="0.1", description="Photon library for Ray", ext_modules=[photon_module])
[ "pcmoritz@gmail.com" ]
pcmoritz@gmail.com
053534610b9b61747d4654db2ffff6a143e5e247
710a8800a1155b67c292a19f9a3eb2e9fba61bdd
/keygen_api/urls.py
b7196fb1f17d024d9ffc9ce4ebc8f58770403eb4
[]
no_license
chirazcheikha/key-generator-app
8735188cfae1ac745c62a88c744b0d29f933c2ed
051bb5452e226975016d30e4c38848d81ac703ac
refs/heads/main
2023-07-27T20:25:33.055334
2021-09-10T02:13:18
2021-09-10T02:13:18
404,097,275
0
0
null
null
null
null
UTF-8
Python
false
false
430
py
from django.contrib import admin from django.urls import path,include from crud import views from rest_framework import routers # registering route to serialized data router = routers.DefaultRouter() router.register(r'keys', views.KeyView, 'index') urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name="index"), path('form/',views.form,name="form"), path('api/', include(router.urls)), ]
[ "chirazcheikha@gmail.com" ]
chirazcheikha@gmail.com
36f5188f122b3ee8c1b8fb88b89d38942266287b
dc63bff99ae5e8013c03e1c0650b281ac6d0ba3b
/backend/blog/handler/open/blog.py
4b7a04366b3d0d416a213f0126216aac1ea5616f
[ "MIT" ]
permissive
o8oo8o/blog
f99c6304ea5ef5e706620418f8a3db57624ee19e
2a6f44f86469bfbb472dfd1bec4238587d8402bf
refs/heads/main
2023-04-21T19:41:34.188436
2021-05-09T04:32:34
2021-05-09T04:32:34
200,951,083
0
0
null
null
null
null
UTF-8
Python
false
false
470
py
#!/usr/bin/evn python3 # coding=utf-8 from handler.open.base import WebBaseHandler from service.blog import BlogSrv class BlogHandler(WebBaseHandler): async def get(self, blog_id): """ # 根据博客ID获取一个博客 :param blog_id: 博客ID """ blog = BlogSrv.get_blog(int(blog_id), is_read=True) if blog: self.send_json({"code": 0, **blog}) else: self.send_json({"code": 1})
[ "a@huangrui.vip" ]
a@huangrui.vip
862866fc41f7fa6674620d7c40d57979c7fcff77
9875d011bf7b478421a4a5a57c6b42c24c069903
/examples/07_paraview/SimpleCone/LocalRendering.py
2523ff9be9b5a9565a31f6838b1fba4384c5cdd6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kitware/trame
bc9a0d7d6a845050f4fb386d514bd7e9b7060a21
861b60718798cca2db292e65e6ad39106ba75ccd
refs/heads/master
2023-08-20T22:42:57.129511
2023-08-18T04:25:32
2023-08-18T04:25:32
410,108,340
198
41
NOASSERTION
2023-09-14T15:29:10
2021-09-24T21:38:47
Python
UTF-8
Python
false
false
2,534
py
r""" Version for trame 1.x - https://github.com/Kitware/trame/blob/release-v1/examples/ParaView/SimpleCone/LocalRendering.py Delta v1..v2 - https://github.com/Kitware/trame/commit/37e36bdd0bc55dfa9134e4f8eba9a014dda4f865 Installation requirements: pip install trame trame-vuetify trame-vtk """ import paraview.web.venv # Available in PV 5.10-RC2+ from trame.app import get_server from trame.widgets import vuetify, paraview from trame.ui.vuetify import SinglePageLayout from paraview import simple # ----------------------------------------------------------------------------- # Trame setup # ----------------------------------------------------------------------------- server = get_server() state, ctrl = server.state, server.controller # ----------------------------------------------------------------------------- # ParaView code # ----------------------------------------------------------------------------- DEFAULT_RESOLUTION = 6 cone = simple.Cone() representation = simple.Show(cone) view = simple.Render() @state.change("resolution") def update_cone(resolution, **kwargs): cone.Resolution = resolution ctrl.view_update() def update_reset_resolution(): state.resolution = DEFAULT_RESOLUTION # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- state.trame__title = "ParaView cone" with SinglePageLayout(server) as layout: layout.icon.click = ctrl.view_reset_camera layout.title.set_text("Cone Application") with layout.toolbar: vuetify.VSpacer() vuetify.VSlider( v_model=("resolution", DEFAULT_RESOLUTION), min=3, max=60, step=1, hide_details=True, dense=True, style="max-width: 300px", ) vuetify.VDivider(vertical=True, classes="mx-2") with vuetify.VBtn(icon=True, click=update_reset_resolution): vuetify.VIcon("mdi-undo-variant") with layout.content: with vuetify.VContainer(fluid=True, classes="pa-0 fill-height"): html_view = paraview.VtkLocalView(view, ref="view") ctrl.view_reset_camera = html_view.reset_camera ctrl.view_update = html_view.update # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__ == "__main__": server.start()
[ "sebastien.jourdain@kitware.com" ]
sebastien.jourdain@kitware.com
c9bed746fda7add413531d4186b3ad460e613fdc
d71790dc935189e8008b202d4c43c1f439fb3f82
/mysite/base/variable_for_trans.py
be02e0d6da7c5372764f0747adbe57399efdb9cb
[]
no_license
RockyLiys/erp
2c93846f2f0a169bd420cc3cba125ad54039f96c
f9fb551afbf47aaca7cdeba8b64a32d2fe3e30d6
refs/heads/master
2020-12-30T14:13:25.060004
2017-06-05T14:05:54
2017-06-05T14:05:54
91,294,386
1
0
null
null
null
null
UTF-8
Python
false
false
5,019
py
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ # 变量的翻译放在此数组中好让makemessage_ext能够检测到 list_variable_for_trans = [ _("get_emp_name"), _("name"), _("groups"), _("accfirstopen_set"), _(u"首卡常开"), _("get_name_by_PIN"), _(u"姓名"), _("accmorecardset_set"), _(u"多卡开门"), _("interlock_details"), _(u"互锁设置信息"), _("antiback_details"), _(u"反潜设置信息"), _("emp_group"), _(u"人员"), _("morecard_emp_count"), _(u"人员数"), _("foemp_count"), _(u"可开门人数"), _("emp_count"), _(u"人员数"), _("level_count"), _(u"从属权限组数"), _("show_status"), _(u"状态"), _("show_enabled"), _(u"启用"), _(u"get_template"), _(u"指纹数"), _(u"get_ExceptionID"), _(u"例外情况"), _(u"get_process_status"), _(u"设备执行命令进度"), _(u"get_attarea"), _(u"所属区域"), _(u"deptadmin_set"), _(u"授权部门"), _(u"areaadmin_set"), _(u"授权区域"), _(u"morecardgroup"), _(u"多卡开门组合"), _(u"get_user_template"), _(u"指纹数"), _(u"get_face"), _(u"人脸数"), _(u"personnel"), _(u"人事"), _(u"iclock"), _(u"设备"), _(u"iaccess"), _(u"门禁"), _(u"att"), _(u"考勤"), _(u"base"), _(u"系统设置"), _(u"Can add 角色"), _(u"增加角色"), _(u"Can change 角色"), _(u"修改角色"), _(u"Can add 用户"), _(u"增加用户"), _(u"Can change 用户"), _(u"修改用户"), _(u"Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"), _(u"浏览调休"), _(u"浏览公告类别"), _(u"浏览联动设置"), _(u"浏览临时排班"), _(u"浏览假类"), _(u"浏览员工排班"), _(u"浏览考勤时段"), _(u"浏览班次"), _(u"浏览班次明细"), _(u"浏览统计结果详情"), _(u"浏览统计项目表"), _(u"浏览考勤参数"), _(u"浏览考勤明细表"), _(u"浏览数据库管理"), _(u"浏览通信命令详情"), _(u"浏览考勤计算与报表"), _(u"浏览考勤设备管理"), _(u"浏览数据库管理"), _(u"浏览区域用户管理"), _(u"浏览人员"), _(u"浏览设备监控"), _(u"浏览监控全部"), _(u"浏览报警事件"), _(u"浏览全部门禁事件"), _(u"浏览门禁异常事件"), _(u"浏览人员门禁权限"), _(u"浏览考勤节假日"), _(u"浏览补签卡"), _(u"浏览请假"), _(u"浏览轮班表"), _(u"浏览角色"), _(u"浏览权限"), _(u"浏览用户"), _(u"浏览日志记录"), _(u"浏览个性设置"), _(u"浏览系统参数"), _(u"浏览基础代码表"), _(u"浏览互锁设置"), _(u"浏览反潜设置"), _(u"浏览多卡开门人员组"), _(u"浏览多卡开门组"), _(u"浏览多卡开门设置"), _(u"浏览实时监控记录"), _(u"浏览门禁时间段"), _(u"浏览门禁节假日"), _(u"浏览门"), _(u"浏览门禁权限组"), _(u"浏览门禁设备扩展参数"), _(u"浏览韦根卡格式"), _(u"浏览首卡常开设置"), _(u"浏览人员指纹"), _(u"浏览原始记录表"), _(u"浏览设备"), _(u"浏览服务器下发命令"), _(u"浏览操作设备日志"), _(u"浏览设备通讯日志"), _(u"浏览人事报表"), _(u"浏览人员发卡"), _(u"浏览人员离职"), _(u"浏览人员调动"), _(u"浏览区域设置"), _(u"浏览卡类型"), _(u"浏览卡类型"), _(u"浏览考勤报表"), _(u"浏览部门"), _(u"浏览公告发布"), _(u"浏览系统提醒设置"), _(u"浏览用户消息确认"), _(u"查看设备操作日志"), _(u"清除临时排班记录"), _(u"新增临时排班"), _(u"清除排班记录"), _(u"新增请假"), _(u"员工卡片清单"), _(u"数据初始化"), _(u"批量发卡"), _(u"挂失卡"), _(u"解挂卡"), _(u"关闭门禁"), _(u"关闭考勤"), _(u"离职恢复"), _(u"为区域添加用户"), _(u"编辑多卡开门"), _(u"清除数据"), _(u"重新上传日志"), _(u"设置自动关机"), _(u"重新启动设备"), _(u"更新设备信息"), _(u"清除图片"), _(u"恢复使用"), _(u"病假"), _(u"事假"), _(u"产假"), _(u"探亲假"), _(u"年假"), _(u"应到/实到"), _(u"迟到"), _(u"早退"), _(u"请假"), _(u"旷工"), _(u"加班"), _(u"未签到"), _(u"未签退"), _(u"浏览"), _(u"UserID.DeptID.code"), _(u"UserID.DeptID.name"), _(u"UserID__DeptID__code"), _(u"UserID__DeptID__name"), _(u"pos"), _(u"user__PIN"), _(u"user__EName"), _(u"posdevice"), _(u"pos_dev_status"), _(u"pos_file_count"), _(u"pos_cmd_count"), ]
[ "liyansong@weizoom.com" ]
liyansong@weizoom.com
7ce810fe13ba0bcc23fe6cd00258925650027e53
6661cd69f78744040079af8c99a2a5f9d7473f7a
/exam/Template/nousethread.py
a032b0872430322608344b62ccfb1eba196b9229
[]
no_license
Sushilprajapati/online-examination-web-application
2c36adafbc4d9e82edee8911d1fafec9a431633e
8ab03c162a296c32d754980e1a8cf8c554dc05b1
refs/heads/master
2023-03-15T13:44:00.508344
2021-03-07T17:55:01
2021-03-07T17:55:01
270,981,040
0
0
null
null
null
null
UTF-8
Python
false
false
731
py
from threading import Thread import pyscreenshot as ImageGrab import time # # def sum(): # for i in range(100000): # print("Sushil") # def man(): # for i in range(1000000): # print("Chhaya") # t1 = Thread(target=sum) # t2 = Thread(target=man) # # t1.start() # time.sleep(.1) # t2.start() def Takescreenshort(): k = 0 while True: time.sleep(5) image = ImageGrab.grab() im = ImageGrab.grab(bbox=(200, 10, 1600, 500)) im = im.save(f"/home/sushil/Desktop/{k}.png") print("hold_user") k = k + 1 Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort() Takescreenshort()
[ "susheelprajapati07001@gmail.com" ]
susheelprajapati07001@gmail.com
146583a997648d25f329abd2cc16516579b13fa4
89b2db0af633ae5b5be515a04d87a5db9c9b5778
/07-01.py
6196721a0962d459229b4619a75fca0841d268b7
[]
no_license
slahmar/advent-of-code-2018
d4f6cc33997332c74758bf1a194a2db5001b5544
67348b501b7119558855d6034c9178285da30203
refs/heads/master
2020-04-09T12:40:55.213364
2019-02-09T18:16:46
2019-02-09T18:16:46
160,359,882
0
0
null
null
null
null
UTF-8
Python
false
false
924
py
from collections import deque with open('07.txt', 'r') as file: lines = file.readlines() couples = [(line[line.index('Step')+5],line[line.index('step')+5]) for line in lines] prerequisites = {} order = '' for couple in couples: if couple[0] not in prerequisites: prerequisites[couple[0]] = [] if couple[1] not in prerequisites: prerequisites[couple[1]] = [] prerequisites[couple[1]].append(couple[0]) while prerequisites: leading_step = sorted({key for key in prerequisites if not prerequisites[key]})[0] order += leading_step del prerequisites[leading_step] print(f'Leading step {leading_step}') for step in prerequisites: if leading_step in prerequisites[step]: prerequisites[step].remove(leading_step) print(f'Prereq {prerequisites}') print(f'Final order {order}')
[ "noreply@github.com" ]
slahmar.noreply@github.com
5d870e3b0cd04789ba780a20b773bb5dde6db19b
319c5751d6a05371474e0fe52718ca1c64577455
/subprocess_ls.py
b9db17411e3638cfde1190bb3246b65cc090377e
[]
no_license
abhiroyg/useful-scripts
a691840eea164cbaea11d3bab933f46daca5b903
66ee79347e1a446f49274ee759b7e29da3133270
refs/heads/master
2021-01-20T11:45:14.354531
2018-10-21T19:55:01
2018-10-21T19:55:01
58,490,480
1
2
null
null
null
null
UTF-8
Python
false
false
251
py
import subprocess def b(folder_path): try: a = subprocess.check_output('ls {}'.format(folder_path), shell=True) except: a = '' print filter(None, a.split()) b('/home/nineleaps/') b('/home/nineleaps/Pictures/craigslist/')
[ "abhilashroy.g@gmail.com" ]
abhilashroy.g@gmail.com
81b07a97e7b77e409a6504ba04817caf89baba25
15eea21e7fa3531d45ad0eb8bfab305fcc0fe37a
/程序员代码面试指南-左程云/链表问题/q5.py
845248b69b5fcfea8fefa56cc4609124d4a74bad
[]
no_license
yearing1017/Algorithm_Note
a3fcfd852903536d02f9360d96d31fc1a7aa6f8f
8a3f1bda222cb777ff7786170c6d2071ad951ac0
refs/heads/master
2023-02-20T19:19:32.641519
2023-02-06T15:55:44
2023-02-06T15:55:44
223,118,925
43
9
null
2023-02-06T15:55:45
2019-11-21T07:55:50
Python
UTF-8
Python
false
false
2,930
py
""" 问题描述:给定一个单链表的头结点head,以及两个整数from和to,在单链表上 把第from个节点到第to个节点这一部分进行反转。 例如: 1->2->3->4->5->None, from=2, to=4 调整结果为:1->4->3->2->5->None 再如: 1->2->3->None, from=1, to=3 调整结果为: 3->2->1->None 要求: 1.如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1) 2.如果不满足1<=from<=to<=N,则不用调整 """ # 单链表结构 class Node: def __init__(self, value): self.value = value self.next = None class RevertPart: @classmethod def print_list(cls, head): while head is not None: print(head.value) head = head.next @classmethod def revert_part_of_linked_list(cls, head, list_from, list_to): # 排除特定的已知情况 if list_from >= list_to or list_from < 1 or head is None: return head # 求from的前一点 和 to的后一点 fpre, fnext = None, None length = 0 cur = head while cur: length += 1 if length == list_from - 1: fpre = cur elif length == list_to + 1: fnext = cur cur = cur.next # 求得链表的length后,排除一种情况 if list_to > length: return head # 分析from-to是否在链表中:若fpre空,则说明第一个反转的为头结点;反之,第一个为fpre.next if fpre is None: node1 = head else: node1 = fpre.next # node2为第二个要反转的点,先保存下来 node2 = node1.next # 反转第一个点的next指针 node1.next = fnext # 循环反转 while node2 != fnext: node_next = node2.next node2.next = node1 node1 = node2 node2 = node_next # node1为最后一个反转的点 # 若fpre空,不用调整fpre,说明头结点也在其中,返回新的头结点 if fpre is None: return node1 else: fpre.next = node1 return head if __name__ == '__main__': head = None head = RevertPart.revert_part_of_linked_list(head, 1, 1) RevertPart.print_list(head) head = None head = RevertPart.revert_part_of_linked_list(head, 1, 1) RevertPart.print_list(head) head = Node(1) head.next = Node(2) head = RevertPart.revert_part_of_linked_list(head, 1, 2) RevertPart.print_list(head) head = Node(1) head.next = Node(2) head.next.next = Node(3) head = RevertPart.revert_part_of_linked_list(head, 1, 2) RevertPart.print_list(head) head = Node(1) head.next = Node(2) head.next.next = Node(3) head = RevertPart.revert_part_of_linked_list(head, 2, 3) RevertPart.print_list(head)
[ "yearing1017@126.com" ]
yearing1017@126.com
c5d592b4710455595b596cad3d3570ef844a554b
643523d89250b00b59809dbf1ec1b9a447d79489
/search_sort/min_meeting_rooms.py
f155a9737af680926a520f5b5a3b3187cbe60f14
[]
no_license
adarshmodh/Data-Structures-Algorithms-in-Python
2ef51b596a837c16d9a72a09f173feb4a931dffa
d6219afa4281e95178bfddb69aa5fdb5d0685aeb
refs/heads/master
2022-12-08T20:55:32.994194
2020-08-25T22:14:01
2020-08-25T22:14:01
265,917,651
1
0
null
null
null
null
UTF-8
Python
false
false
2,764
py
""" Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Example 1: Input: [[0, 30],[5, 10],[15, 20]] Output: 2 Example 2: Input: [[7,10],[2,4]] Output: 1 """ import heapq def minMeetingRooms(intervals): ##################### Both approaches have equal runtime and space complexity (nlogn, n) ############################## Using priority queue - min heap # If there is no meeting to schedule then no room needs to be allocated. if not intervals: return 0 # The heap initialization free_rooms = [] # Sort the meetings in increasing order of their start time. intervals.sort(key= lambda x: x[0]) # Add the first meeting. We have to give a new room to the first meeting. heapq.heappush(free_rooms, intervals[0][1]) # For all the remaining meeting rooms for i in intervals[1:]: # If the room due to free up the earliest is free, assign that room to this meeting. if free_rooms[0] <= i[0]: heapq.heappop(free_rooms) # If a new room is to be assigned, then also we add to the heap, # If an old room is allocated, then also we have to add to the heap with updated end time. heapq.heappush(free_rooms, i[1]) # The size of the heap tells us the minimum rooms required for all the meetings. return len(free_rooms) # ############################### Using 2 pointer approach # # If there are no meetings, we don't need any rooms. # if not intervals: # return 0 # used_rooms = 0 # # Separate out the start and the end timings and sort them individually. # start_timings = sorted([i[0] for i in intervals]) # end_timings = sorted(i[1] for i in intervals) # L = len(intervals) # # The two pointers in the algorithm: e_ptr and s_ptr. # end_pointer = 0 # start_pointer = 0 # # Until all the meetings have been processed # while start_pointer < L: # # If there is a meeting that has ended by the time the meeting at `start_pointer` starts # if start_timings[start_pointer] >= end_timings[end_pointer]: # # Free up a room and increment the end_pointer. # used_rooms -= 1 # end_pointer += 1 # # We do this irrespective of whether a room frees up or not. # # If a room got free, then this used_rooms += 1 wouldn't have any effect. used_rooms would # # remain the same in that case. If no room was free, then this would increase used_rooms # used_rooms += 1 # start_pointer += 1 # return used_rooms a = [[0, 30],[5, 10],[15, 20]] b = [[7,10],[2,4]] print(minMeetingRooms(b))
[ "adarsh.modh@gmail.com" ]
adarsh.modh@gmail.com
b5c88421aad051a281faedea524b3c35cc6b0c07
d59282c74143cb09ddf8a67388a8adacc86e05ab
/math/202_Happy_Number.py
f9a74380bdb1b9b00b63c200c79c3e993e77bd8d
[]
no_license
mclearning2/Algorithm_Practice
f8ebe64ad26b244f4e6a9b9485cb10db834a4924
7ed38310078647c3d11ca29a055b697577f3eddb
refs/heads/master
2020-07-04T09:02:59.975373
2019-09-06T12:51:19
2019-09-06T12:51:19
202,233,519
0
0
null
null
null
null
UTF-8
Python
false
false
848
py
''' Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 ''' class Solution: def isHappy(self, n: int) -> bool: c = 0 while True: s = 0 for i in str(n): s += int(i) ** 2 if s == 1: return True n = s c += 1 if c > 1000: return False
[ "mclearning2@gmail.com" ]
mclearning2@gmail.com
e2349b7f298d9a6052fa440b3fc315906f36d9ec
ca429f6ad184f54f8ed431fce5e5d61a87a8d9dc
/05.1.Loops/06.MinNumber.py
0b4eccf690f9fd152b3a05f2b43978e7eab5d315
[]
no_license
EmiliaPavlova/Learning_Python
2ba84d4c7e42870170154df9219b67d758741d16
3a25c64d4a3e54b158e363a77452f1653a9610e1
refs/heads/master
2020-06-07T23:34:55.017197
2019-08-09T15:27:59
2019-08-09T15:27:59
193,115,737
0
0
null
null
null
null
UTF-8
Python
false
false
205
py
from sys import maxsize n = int(input()) smallest_number = maxsize for i in range(0, n): number = int(input()) if smallest_number > number: smallest_number = number print(smallest_number)
[ "epavl@softserveinc.com" ]
epavl@softserveinc.com
7086f1cc76f73edceb39695f6680d0b875781e1a
96331651bbd57dbaa92fb53215909437aca9a5b8
/test.py
75d9b4dc2ff50f11d59d474ae90a965d7f7322ae
[]
no_license
okkevdwal/nmt_sa
94ec98b6415577b90490308db5121cf430d19b15
da60f21735680b79aad01512b18bfa5eee5fcb6d
refs/heads/master
2020-05-06T15:43:59.228955
2019-05-22T12:40:20
2019-05-22T12:40:20
180,205,698
0
0
null
null
null
null
UTF-8
Python
false
false
37
py
def main (x,y): print x*y main()
[ "okkevanderwal@gmail.com" ]
okkevanderwal@gmail.com
929595b1b7243cd4cbd0b161aa2aab5df169153b
65b15e9da9b5b88e9ce248f06bb011663ebdf22b
/post_a_comment.py
1580f329cfe0763756953ac5b11fd67dd4a5369f
[]
no_license
JYOTITHAKUROSEM/instabot
8ad7f82d602edd03efd83204ee50a17947b57651
0043aadc78345183e7d82ca0b4576b29373af9ac
refs/heads/master
2020-12-02T16:14:32.582068
2017-07-11T09:39:12
2017-07-11T09:39:12
96,522,634
0
0
null
null
null
null
UTF-8
Python
false
false
682
py
import requests from constants import APP_ACCESS_TOKEN,BASE_URL from get_post_id import get_post_id def post_a_comment(insta_username): media_id=get_post_id(insta_username) comment_text=raw_input("Your Comment: ") payload={"access_token":APP_ACCESS_TOKEN, "text" : comment_text} request_url=(BASE_URL + 'media/%s/comments') % (media_id) print 'POST request url : %s ' % (request_url) make_comment=requests.post(request_url,payload).json() if make_comment['meta']['code'] ==200: print "sucessfully added a new comment" else: print "Sorry You Are Unable To add Comment. plz.. Try Again!" #post_a_comment(insta_username="sharmatanu9878")
[ "jyotithakur15111@gmail.com" ]
jyotithakur15111@gmail.com
d08c375fec4142731d34d72bd786e25ab5438af3
bdf14b6ff6a52a44e704a191e22467e7378167aa
/image.py
8816e79841bcf261f103e832956850d486350dc7
[]
no_license
OwenFeik/dndmap
f9b98c8d9f6d9c185fbf455296bfeba1c92f7c5f
89cf2c4cd82779fb2b1f3bc0d5bded208ad20a07
refs/heads/master
2023-01-19T21:54:36.712155
2020-11-27T02:25:40
2020-11-27T02:25:40
294,429,277
0
0
null
null
null
null
UTF-8
Python
false
false
6,409
py
import io import numpy as np import PIL.Image, PIL.ImageTk import gui_util # must be either 'pillow' or 'pygame'; currently 'pygame' is somewhat faster # if using pillow, pillow-simd is likely to offer better performance RENDERER = 'pygame' class ImageWrapper(): IMAGE_FORMAT = 'RGBA' BLOB_FORMAT = 'PNG' THUMBNAIL_SIZE = (128, 128) FORMATS = [ 'BMP', 'PNG', 'JPG', 'JPEG' ] def __init__(self, **kwargs): size = kwargs.get('size', (0, 0)) w, h = size self.w = kwargs.get('w', kwargs.get('width', w)) self.h = kwargs.get('h', kwargs.get('height', h)) @property def size(self): return self.w, self.h def __str__(self): return f'<Image {self.size}>' def get_pillow_image(self): """return a PIL.Image with this image's data""" def get_imagetk(self): """return a PIL.ImageTk.PhotoImage for use in the tkinter UI""" return PIL.ImageTk.PhotoImage(self.get_pillow_image()) def blit(self, other, offset): """blit other image onto this one with top left at offset""" def draw_line(self, start, end, colour, width): """draw a line of width on this image from start to end in colour""" def flip(self, flip_x, flip_y): """flip the image in either the x, y, or both directions""" def resize(self, new_size, fast=False): """return a resized version of this image of new_size""" if not (new_size[0] >= 0 and new_size[1] >= 0): raise ValueError('Cannot resize to negative dimensions.') return self._resize(new_size, fast) def _resize(self, new_size, fast=False): """resize implementation, after value verification""" def as_greyscale_array(self): """return a 2d array of this image converted to greyscale""" return np.asarray(self.get_pillow_image().convert('L')) def as_thumbnail(self): """get a thumbnail of this image, to save in db or similar""" return self.resize(Image.THUMBNAIL_SIZE) def as_bytes(self): """convert this image to a byte array""" blob = io.BytesIO() self.get_pillow_image().save(blob, format=Image.BLOB_FORMAT) return blob.getvalue() @staticmethod def load(filelike): """load the given filelike""" @staticmethod def from_file(path): """return an Image with image loaded from path""" return Image.load(open(path, 'rb')) @staticmethod def from_bytes(data): """read provided bytes (data) as an Image""" return Image.load(io.BytesIO(data)) class PygameImage(ImageWrapper): def __init__(self, **kwargs): super().__init__(**kwargs) self.transparency_colour = gui_util.BG_COLOUR image = kwargs.get('image') bg_colour = kwargs.get('bg_colour') if not image: self.image = pygame.Surface(self.size) self.image.set_colorkey(self.transparency_colour) if bg_colour: if not bg_colour[3]: self.image.fill(self.transparency_colour) else: self.image.fill(bg_colour) else: self.image = image self.image.set_colorkey(self.transparency_colour) def get_pillow_image(self): return PIL.Image.frombytes( Image.IMAGE_FORMAT, self.size, pygame.image.tostring(self.image, Image.IMAGE_FORMAT, False) ) def blit(self, other, offset): self.image.blit(other.image, offset) def draw_line(self, start, end, colour, width): pygame.draw.line(self.image, colour, start, end, width) def flip(self, flip_x, flip_y): return PygameImage( size=self.size, image=pygame.transform.flip(self.image, flip_x, flip_y) ) def _resize(self, new_size, fast=False): if fast: new_img = pygame.transform.scale(self.image, new_size) else: new_img = pygame.transform.smoothscale(self.image, new_size) return PygameImage(size=new_size, image=new_img) @staticmethod def load(filelike): image = pygame.image.load(filelike) return PygameImage(size=image.get_size(), image=image) class PillowImage(ImageWrapper): def __init__(self, **kwargs): super().__init__(**kwargs) image = kwargs.get('image') bg_colour = kwargs.get('bg_colour', 0) if not image: self.image = PIL.Image.new( Image.IMAGE_FORMAT, self.size, bg_colour ) else: self.image = image self.draw = None def get_pillow_image(self): return self.image def ensure_draw(self): if self.draw is None: self.draw = PIL.ImageDraw.Draw(self.image) def blit(self, other, offset): self.image.paste(other.image, offset, other.image) def draw_line(self, start, end, colour, width): self.ensure_draw() self.draw.line([start, end], colour, width) def flip(self, flip_x, flip_y): if flip_x and flip_y: new = self.image.transpose(PIL.Image.ROTATE_180) elif flip_x: new = self.image.transpose(PIL.Image.FLIP_LEFT_RIGHT) elif flip_y: new = self.image.transpose(PIL.Image.FLIP_TOP_BOTTOM) return PillowImage(size=self.size, image=new) def _resize(self, new_size, fast=False): if fast: new_img = self.image.resize(new_size, resample=PIL.Image.NEAREST) else: new_img = self.image.resize(new_size) return PillowImage(size=new_size, image=new_img) @staticmethod def load(filelike): image = PIL.Image.open(filelike).convert(Image.IMAGE_FORMAT) return PillowImage(size=image.size, image=image) if RENDERER == 'pygame': import contextlib with contextlib.redirect_stdout(None): import pygame Image = PygameImage elif RENDERER == 'pillow': import PIL.ImageDraw Image = PillowImage else: if RENDERER == '': raise ValueError( 'No renderer set. RENDERER must be either ' + \ '"pygame" or "pillow"' ) else: raise ValueError(f'Renderer "{RENDERER}" not available.')
[ "owenhfeik@gmail.com" ]
owenhfeik@gmail.com
14f25ced3a3f281101ab2d388450248a0529e8eb
a0cc20d183c2cf5817913183fa431218e7c1567a
/randomCards.py
b42880244b5162c12507c87defa63e014f0c20e1
[]
no_license
tab1tha/Beginning
3aa1289931da91d555b29c1b4171727c151c7447
d0c7e0b3553a91fd0925acd979be52e8e9d39b98
refs/heads/master
2022-11-22T07:36:15.926509
2022-11-08T12:10:23
2022-11-08T12:10:23
149,529,940
0
0
null
null
null
null
UTF-8
Python
false
false
599
py
#this program deals a pseudorandom card each time. # real randomness can only be achieved using the urandom() function. values=list(range(1,11)) +'Jack King Queen '.split() suits='Hearts Spades Diamonds Clubs'.split() deck=['{} of {}'.format(v,s) for v in values for s in suits] from random import shuffle shuffle(deck) #randomly rearranges the content of deck such that any possible outcome is equally probable. print(deck) while deck:input(deck.pop) #to get Python to deal you a card each time you press Enter on your keyboard, until there are no #more cards, you simply create a little while loop
[ "tambetachere@gmail.com" ]
tambetachere@gmail.com
4d235725ff0fb5417f1d71d8b9f04900e876d8bd
76a12d5180ebbe2c0ad24471789e1368e14b298f
/memorytools/plugins/ocr/ocr.py
36d1582a9d5347a39b62dffb67a2be4caf5e30a6
[ "MIT" ]
permissive
shanhaiying/MemoryTools
213076a97a412768e5e7621b7377c4e6b0149f32
6a95f44fd824db9a508f0206945db32f5f712a5f
refs/heads/master
2023-02-04T14:11:13.106216
2020-12-24T05:07:17
2020-12-24T05:07:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,067
py
# -*- coding: utf-8 -*- """ @file: ocr @author: Memory @date: 2020/10/11 @description: ocr插件的定义 """ from pathlib import Path from . import BaiduOCR from . import LatexOCR from PIL import Image, ImageGrab, ImageDraw from .ocrbox import OcrBox from tools.logger import logger from globals import BAIDU_ACCOUNTS, XUEERSI_ACCOUNTS, ICON, PATH from tools.utils import is_check, is_pick, get_rect, Color, copy_clip from plugins import BasePlugin, change_config class OCR(BasePlugin): def __init__(self, root): config_path = PATH.config / ("%s.json" % self.__class__.__name__) super(OCR, self).__init__("OCR识别", root, ICON.ocr, config_path) self.config = self.init_config() self.text_ocr = BaiduOCR(BAIDU_ACCOUNTS) self.math_ocr = LatexOCR(XUEERSI_ACCOUNTS) def create_menu(self) -> tuple: menu_options = ( ("开启OCR", is_check(self.is_ocr), self.pause_ocr, True), ('去除换行', is_check(not self.newline), self.turn_newline, True), ('识别文本', is_pick(self.mode == 'text'), self.text_mode, False), ('识别公式', is_pick(self.mode == 'math'), self.math_mode, False), ) return menu_options def create_default_config(self) -> dict: config = { "is_ocr": True, "newline": False, "mode": "text" } return config @change_config def pause_ocr(self, option_text): self.is_ocr = not self.is_ocr if self.is_ocr: logger.info("[OCR识别] 开启OCR识别") else: logger.info("[OCR识别] 关闭OCR识别") @change_config def text_mode(self, option_text): self.mode = 'text' logger.info("[OCR识别] 切换OCR识别模式为: 文本") @change_config def math_mode(self, option_text): self.mode = 'math' logger.info("[OCR识别] 切换OCR识别模式为: 公式") @change_config def turn_newline(self, option_text): self.newline = not self.newline if not self.newline: logger.info("[OCR识别] 开启去除换行") else: logger.info("[OCR识别] 关闭去除换行") def start(self): if not self.is_ocr: return im = ImageGrab.grabclipboard() # 获取剪切板 if isinstance(im, Image.Image): # 判断是否是图片 try: if self.mode == 'text': text = self.text_ocr.ocr(im, self.newline) elif self.mode == 'math': pos, text = self.math_ocr.latex(im) print("位置:", pos) draw = ImageDraw.Draw(im) color = Color() for rect in pos: draw.polygon(get_rect(*rect), outline=color.next()) except Exception as e: text = str(e) copy_clip('') OcrBox('OCR识别结果').show(im, text) if __name__ == '__main__': OCR().start()
[ "732527427@qq.com" ]
732527427@qq.com
b670e6a607d2b3a5ec144863a84871c42fd619f6
5054a97e7805aacdb6fa8ff903f5b6d0797ce422
/scripts/acr_generate_overview_overall.py
bc56329b3164590bd232d0fc53706074261003bb
[ "BSD-3-Clause" ]
permissive
jstorrs/LAB-QA2GO
ec59ee933e16e1474ae596e9e9b5a9011dfa1902
be434da7399d396413309f947f4b634d8fae9a17
refs/heads/master
2022-01-27T04:38:06.466147
2019-07-15T08:20:16
2019-07-15T08:20:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
27,289
py
#script to generate the graphs for the overview page and to create the overview page for the acr #!/usr/bin/python # script to generate the overview graphs and to generate the overview html page for the gel phantoms import os,sys sys.path.append('/home/brain/qa/scripts/') import cgi import cgitb; cgitb.enable() # set HOME environment variable to a directory the httpd server can write to os.environ[ 'HOME' ] = '/tmp/' os.chdir('/home/brain/qa/html/results/acr/') import matplotlib # chose a non-GUI backend matplotlib.use( 'Agg' ) import pylab def generate_graph(overview_logfile,matlab_path,resultpath,number_of_shown_values): rfile = open(overview_logfile,'r') lines = rfile.readlines() #last 10 lines if (len(lines)-1 >= int(number_of_shown_values)): lines = lines[-int(number_of_shown_values):] else: lines = lines[1:] date_list = [] geo_loc = [] geo_T1sl1hor = [] geo_T1sl1ver = [] geo_T1sl5hor = [] geo_T1sl5ver = [] geo_T1sl5_p45 = [] geo_T1sl5_m45 = [] res_maxT1rechts1_1 = [] res_maxT1links1_1 = [] res_maxT1rechts1_0 = [] res_maxT1links1_0 = [] res_maxT1rechts0_9 = [] res_maxT1links0_9 = [] res_maxT2rechts1_1 = [] res_maxT2links1_1 = [] res_maxT2rechts1_0 = [] res_maxT2links1_0 = [] res_maxT2rechts0_9 = [] res_maxT2links0_9 = [] thick_T1 = [] thick_T2 = [] pos_T1sl2 = [] pos_T1sl12 = [] pos_T2sl2 = [] pos_T2sl12 = [] pIU_T1 = [] pIU_T2 = [] pSG_T1 = [] pSG_T2 = [] lCOD_sum_T1 = [] lCOD_sum_T2 = [] for i in lines: entry = i.split(';') try: date_list.append(entry[0]) except: date_list.appent('XXXX-XX-XX') try: geo_loc.append(float(entry[1].replace(',','.'))) except: geo_loc.append(float(0.0)) try: geo_T1sl1hor.append(float(entry[2].replace(',','.'))) except: geo_T1sl1hor.append(float(0.0)) try: geo_T1sl1ver.append(float(entry[3].replace(',','.'))) except: geo_T1sl1ver.append(float(0.0)) try: geo_T1sl5hor.append(float(entry[4].replace(',','.'))) except: geo_T1sl5hor.append(float(0.0)) try: geo_T1sl5ver.append(float(entry[5].replace(',','.'))) except: geo_T1sl5ver.append(float(0.0)) try: geo_T1sl5_p45.append(float(entry[6].replace(',','.'))) except: geo_T1sl5_p45.append(float(0.0)) try: geo_T1sl5_m45.append(float(entry[7].replace(',','.'))) except: gep_T1sl5_m45.append(float(0.0)) try: res_maxT1rechts1_1.append(float(entry[8].replace(',','.'))) except: res_maxT1rechts1_1.append(float(0.0)) try: res_maxT1links1_1.append(float(entry[9].replace(',','.'))) except: res_maxT1links1_1.append(float(0.0)) try: res_maxT1rechts1_0.append(float(entry[10].replace(',','.'))) except: res_maxT1rechts1_0.append(float(0.0)) try: res_maxT1links1_0.append(float(entry[11].replace(',','.'))) except: res_maxT1links1_0.append(float(0.0)) try: res_maxT1rechts0_9.append(float(entry[12].replace(',','.'))) except: res_maxT1rechts0_9.append(float(0.0)) try: res_maxT1links0_9.append(float(entry[13].replace(',','.'))) except: res_maxT1links0_9.append(float(0.0)) try: res_maxT2rechts1_1.append(float(entry[14].replace(',','.'))) except: res_maxT2rechts1_1.append(float(0.0)) try: res_maxT2links1_1.append(float(entry[15].replace(',','.'))) except: res_maxT2links1_1.append(float(0.0)) try: res_maxT2rechts1_0.append(float(entry[16].replace(',','.'))) except: res_maxT2rechts1_0.append(float(0.0)) try: res_maxT2links1_0.append(float(entry[17].replace(',','.'))) except: res_maxT2links1_0.append(float(0.0)) try: res_maxT2rechts0_9.append(float(entry[18].replace(',','.'))) except: res_maxT2rechts0_9.append(float(0.0)) try: res_maxT2links0_9.append(float(entry[19].replace(',','.'))) except: res_maxT2links0_9.append(float(0.0)) try: thick_T1.append(float(entry[20].replace(',','.'))) except: thick_T1.append(float(0.0)) try: thick_T2.append(float(entry[21].replace(',','.'))) except: thick_T2.append(float(0.0)) try: pos_T1sl2.append(float(entry[22].replace(',','.'))) except: pos_T1sl2.append(float(0.0)) try: pos_T1sl12.append(float(entry[23].replace(',','.'))) except: pos_T1sl12.append(float(0.0)) try: pos_T2sl2.append(float(entry[24].replace(',','.'))) except: pos_T2sl2.append(float(0.0)) try: pos_T2sl12.append(float(entry[25].replace(',','.'))) except: pos_T2sl12.append(float(0.0)) try: pIU_T1.append(float(entry[26].replace(',','.'))) except: pIU_T1.append(float(0.0)) try: pIU_T2.append(float(entry[27].replace(',','.'))) except: pIU_T2.append(float(0.0)) try: pSG_T1.append(float(entry[28].replace(',','.'))) except: pSG_T1.append(float(0.0)) try: pSG_T2.append(float(entry[29].replace(',','.'))) except: pSG_T2.append(float(0.0)) try: lCOD_sum_T1.append(float(entry[30].replace(',','.'))) except: lCOD_sum_T1.append(float(0.0)) try: lCOD_sum_T2.append(float(entry[31].strip().replace(',','.'))) except: lCOD_sum_T2.append(float(0.0)) rfile.close() os.chdir(matlab_path) dateliste = '' for i in date_list: dateliste = dateliste+i+',' dateliste = dateliste[:-1] numElements=[i for i in range(len(date_list))] os.chdir('/home/brain/qa/html/results/acr/') if int(number_of_shown_values)==5: normal_overview_width=10 normal_overview_height=6 normal_overview_fontsize=11 normal_overview_tickrota=40 two_subplot_overview_width=10 two_subplot_overview_height=8 two_subplot_overview_fontsize=11 two_subplot_overview_tickrota=40 four_subplot_overview_width=10 four_subplot_overview_height=10 four_subplot_overview_fontsize=11 four_subplot_overview_tickrota=40 six_subplot_overview_width=10 six_subplot_overview_height=12 six_subplot_overview_fontsize=11 six_subplot_overview_tickrota=40 elif int(number_of_shown_values)==10: normal_overview_width=12 normal_overview_height=6 normal_overview_fontsize=11 normal_overview_tickrota=60 two_subplot_overview_width=12 two_subplot_overview_height=8 two_subplot_overview_fontsize=11 two_subplot_overview_tickrota=60 four_subplot_overview_width=12 four_subplot_overview_height=10 four_subplot_overview_fontsize=11 four_subplot_overview_tickrota=60 six_subplot_overview_width=12 six_subplot_overview_height=12 six_subplot_overview_fontsize=11 six_subplot_overview_tickrota=60 elif int(number_of_shown_values)==15: normal_overview_width=14 normal_overview_height=6 normal_overview_fontsize=11 normal_overview_tickrota=70 two_subplot_overview_width=14 two_subplot_overview_height=8 two_subplot_overview_fontsize=11 two_subplot_overview_tickrota=70 four_subplot_overview_width=14 four_subplot_overview_height=10 four_subplot_overview_fontsize=11 four_subplot_overview_tickrota=70 six_subplot_overview_width=14 six_subplot_overview_height=12 six_subplot_overview_fontsize=11 six_subplot_overview_tickrota=70 elif int(number_of_shown_values)==20: normal_overview_width=16 normal_overview_height=6 normal_overview_fontsize=11 normal_overview_tickrota=75 two_subplot_overview_width=16 two_subplot_overview_height=8 two_subplot_overview_fontsize=11 two_subplot_overview_tickrota=75 four_subplot_overview_width=16 four_subplot_overview_height=10 four_subplot_overview_fontsize=11 four_subplot_overview_tickrota=75 six_subplot_overview_width=16 six_subplot_overview_height=12 six_subplot_overview_fontsize=11 six_subplot_overview_tickrota=75 elif int(number_of_shown_values)==50: normal_overview_width=18 normal_overview_height=6 normal_overview_fontsize=11 normal_overview_tickrota=90 two_subplot_overview_width=18 two_subplot_overview_height=8 two_subplot_overview_fontsize=11 two_subplot_overview_tickrota=90 four_subplot_overview_width=18 four_subplot_overview_height=10 four_subplot_overview_fontsize=11 four_subplot_overview_tickrota=90 six_subplot_overview_width=18 six_subplot_overview_height=12 six_subplot_overview_fontsize=11 six_subplot_overview_tickrota=90 #Geometry Localizer matplotlib.pyplot.figure(figsize=(normal_overview_width,normal_overview_height)) matplotlib.pyplot.plot(numElements, geo_loc, 'bo',markersize=4) matplotlib.pyplot.xticks(numElements, date_list,rotation=normal_overview_tickrota) matplotlib.pyplot.title('Geometry Localizer') axes = matplotlib.pyplot.gca() axes.set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes.set_xlabel('Date') axes.set_ylabel('Size in mm') axes.axhspan(146, 150, alpha=0.5, color='green') ymin = min(geo_loc) - 10 ymax = max(geo_loc) + 10 axes.set_ylim([ymin,ymax]) axes.yaxis.grid() matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Geometry_Localizer') #Geometry T1 ymin = 177 ymax = 200 f, axes = matplotlib.pyplot.subplots(3, 2, sharex='col', sharey='row') f.set_figheight(six_subplot_overview_height) f.set_figwidth(six_subplot_overview_width) axes[0, 0].plot(numElements, geo_T1sl1hor, 'bo',markersize=4) axes[0, 0].set_title('slice 1 horizontal') axes[0, 0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[0, 0].set_ylabel('Size in mm') axes[0, 0].axhspan(188, 192, alpha=0.5, color='green') axes[0, 0].set_ylim([ymin,ymax]) axes[0, 1].plot(numElements, geo_T1sl1ver, 'bo',markersize=4) axes[0, 1].set_title('slice 1 vertical') axes[0, 1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[0, 1].axhspan(188, 192, alpha=0.5, color='green') axes[0, 1].set_ylim([ymin,ymax]) axes[1, 0].plot(numElements, geo_T1sl5hor, 'bo',markersize=4) axes[1, 0].set_title('slice 5 horizontal') axes[1, 0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[1, 0].set_ylabel('Size in mm') axes[1, 0].axhspan(188, 192, alpha=0.5, color='green') axes[1, 0].set_ylim([ymin,ymax]) axes[1, 1].plot(numElements, geo_T1sl5ver, 'bo',markersize=4) axes[1, 1].set_title('slice 5 vertical') axes[1, 1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[1, 1].axhspan(188, 192, alpha=0.5, color='green') axes[1, 1].set_ylim([ymin,ymax]) axes[2, 0].plot(numElements, geo_T1sl5_p45, 'bo',markersize=4) axes[2, 0].set_title('slice 5 plus 45 degree') axes[2, 0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[2, 0].set_xlabel('Date') axes[2, 0].set_ylabel('Size in mm') matplotlib.pyplot.sca(axes[2, 0]) matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) axes[2, 0].axhspan(188, 192, alpha=0.5, color='green') axes[2, 0].set_ylim([ymin,ymax]) axes[2, 1].plot(numElements, geo_T1sl5_m45, 'bo',markersize=4) axes[2, 1].set_title('slice 5 minus 45 degree') axes[2, 1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[2, 1].set_xlabel('Date') axes[2, 1].set_ylabel('Size in mm') axes[2, 1].axhspan(188, 192, alpha=0.5, color='green') axes[2, 1].set_ylim([ymin,ymax]) axes[0 ,0].yaxis.grid() axes[0 ,1].yaxis.grid() axes[1 ,0].yaxis.grid() axes[1 ,1].yaxis.grid() axes[2 ,0].yaxis.grid() axes[2 ,1].yaxis.grid() matplotlib.pyplot.sca(axes[2, 1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Geometry_T1') #Resolution T1 ymin = 0 ymax = 7 f, axes = matplotlib.pyplot.subplots(3, 2, sharex='col', sharey='row') f.set_figheight(six_subplot_overview_height) f.set_figwidth(six_subplot_overview_width) axes[0, 0].plot(numElements, res_maxT1rechts1_1, 'bo',markersize=4) axes[0, 0].set_title('1.1 mm right') axes[0, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[0, 0].set_ylabel('Maximum number of holes') axes[0, 0].axhspan(0, 4, alpha=0.5, color='green') axes[0, 0].set_ylim([ymin,ymax]) axes[0, 1].plot(numElements, res_maxT1links1_1, 'bo',markersize=4) axes[0, 1].set_title('1.1 mm left') axes[0, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[0, 1].axhspan(0, 4, alpha=0.5, color='green') axes[0, 1].set_ylim([ymin,ymax]) axes[1, 0].plot(numElements, res_maxT1rechts1_0, 'bo',markersize=4) axes[1, 0].set_title('1.0 mm right') axes[1, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[1, 0].set_ylabel('Maximum number of holes') axes[1, 0].axhspan(0, 4, alpha=0.5, color='green') axes[1, 0].set_ylim([ymin,ymax]) axes[1, 1].plot(numElements, res_maxT1links1_0, 'bo',markersize=4) axes[1, 1].set_title('1.0 mm left') axes[1, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[1, 1].axhspan(0, 4, alpha=0.5, color='green') axes[1, 1].set_ylim([ymin,ymax]) axes[2, 0].plot(numElements, res_maxT1rechts0_9, 'bo',markersize=4) axes[2, 0].set_title('0.9 mm right') axes[2, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[2, 0].set_xlabel('Date') axes[2, 0].set_ylabel('Maximum number of holes') matplotlib.pyplot.sca(axes[2, 0]) matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) axes[2, 0].axhspan(0, 4, alpha=0.5, color='green') axes[2, 0].set_ylim([ymin,ymax]) axes[2, 1].plot(numElements, res_maxT1links0_9, 'bo',markersize=4) axes[2, 1].set_title('0.9 mm left') axes[2, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[2, 1].set_xlabel('Date') axes[2, 1].axhspan(0, 4, alpha=0.5, color='green') axes[2, 1].set_ylim([ymin,ymax]) matplotlib.pyplot.sca(axes[2, 1]) axes[0 ,0].yaxis.grid() axes[0 ,1].yaxis.grid() axes[1 ,0].yaxis.grid() axes[1 ,1].yaxis.grid() axes[2 ,0].yaxis.grid() axes[2 ,1].yaxis.grid() matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Resolution_T1') #Resolution T2 ymin = 0 ymax = 7 f, axes = matplotlib.pyplot.subplots(3, 2, sharex='col', sharey='row') f.set_figheight(six_subplot_overview_height) f.set_figwidth(six_subplot_overview_width) axes[0, 0].plot(numElements, res_maxT2rechts1_1, 'bo',markersize=4) axes[0, 0].set_title('1.1 mm right') axes[0, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[0, 0].set_ylabel('Maximum number of holes') axes[0, 0].axhspan(0, 4, alpha=0.5, color='green') axes[0, 0].set_ylim([ymin,ymax]) axes[0, 1].plot(numElements, res_maxT2links1_1, 'bo',markersize=4) axes[0, 1].set_title('1.1 mm left') axes[0, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[0, 1].axhspan(0, 4, alpha=0.5, color='green') axes[0, 1].set_ylim([ymin,ymax]) axes[1, 0].plot(numElements, res_maxT2rechts1_0, 'bo',markersize=4) axes[1, 0].set_title('1.0 mm right') axes[1, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[1, 0].set_ylabel('Maximum number of holes') axes[1, 0].axhspan(0, 4, alpha=0.5, color='green') axes[1, 0].set_ylim([ymin,ymax]) axes[1, 1].plot(numElements, res_maxT2links1_0, 'bo',markersize=4) axes[1, 1].set_title('1.0 mm left') axes[1, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[1, 1].axhspan(0, 4, alpha=0.5, color='green') axes[1, 1].set_ylim([ymin,ymax]) axes[2, 0].plot(numElements, res_maxT2rechts0_9, 'bo',markersize=4) axes[2, 0].set_title('0.9 mm right') axes[2, 0].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[2, 0].set_xlabel('Date') axes[2, 0].set_ylabel('Maximum number of holes') matplotlib.pyplot.sca(axes[2, 0]) matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) axes[2, 0].axhspan(0, 4, alpha=0.5, color='green') axes[2, 0].set_ylim([ymin,ymax]) axes[2, 1].plot(numElements, res_maxT2links0_9, 'bo',markersize=4) axes[2, 1].set_title('0.9 mm left') axes[2, 1].set_xlim([-0.5,float(number_of_shown_values)+ 0.5]) axes[2, 1].set_xlabel('Date') axes[2, 1].axhspan(0, 4, alpha=0.5, color='green') axes[2, 1].set_ylim([ymin,ymax]) axes[0 ,0].yaxis.grid() axes[0 ,1].yaxis.grid() axes[1 ,0].yaxis.grid() axes[1 ,1].yaxis.grid() axes[2 ,0].yaxis.grid() axes[2 ,1].yaxis.grid() matplotlib.pyplot.sca(axes[2, 1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=six_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Resolution_T2') # Thickness f, axarr = matplotlib.pyplot.subplots(2, sharex=True) f.set_figheight(two_subplot_overview_height) f.set_figwidth(two_subplot_overview_width) ymin = 0 ymax = 10 axarr[0].set_ylim([ymin,ymax]) axarr[0].plot(numElements, thick_T1, 'bo',markersize=4) axarr[0].set_title('Slice thickness T1') axarr[0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[0].set_ylabel('Size in mm') axarr[0].axhspan(4.3, 5.7, alpha=0.5, color='green') axarr[0].set_ylim([ymin,ymax]) axarr[1].axhspan(4.3, 5.7, alpha=0.5, color='green') axarr[1].set_ylim([ymin,ymax]) axarr[1].plot(numElements, thick_T2, 'bo',markersize=4) axarr[1].set_title('Slice thickness T2') axarr[1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[1].set_xlabel('Date') axarr[1].set_ylabel('Size in mm') axarr[1].set_ylim([ymin,ymax]) axarr[0].yaxis.grid() axarr[0].yaxis.grid() matplotlib.pyplot.sca(axarr[1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=two_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Thickness') #Position ymin = 0 ymax = 10 f, axes = matplotlib.pyplot.subplots(2, 2, sharex='col', sharey='row') f.set_figheight(four_subplot_overview_height) f.set_figwidth(four_subplot_overview_width) axes[0, 0].plot(numElements, pos_T1sl2, 'bo',markersize=4) axes[0, 0].set_title('T1 slice 2') axes[0, 0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[0, 0].set_ylabel('Difference in mm') axes[0, 0].axhspan(0, 5, alpha=0.5, color='green') axes[0, 0].set_ylim([ymin,ymax]) axes[0, 1].plot(numElements, pos_T1sl12, 'bo',markersize=4) axes[0, 1].set_title('T1 slice 12') axes[0, 1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[0, 1].axhspan(0, 5, alpha=0.5, color='green') axes[0, 1].set_ylim([ymin,ymax]) axes[1, 0].plot(numElements, pos_T2sl2, 'bo',markersize=4) axes[1, 0].set_title('T2 slice 2') axes[1, 0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[1, 0].set_xlabel('Date') axes[1, 0].set_ylabel('Difference in mm') matplotlib.pyplot.sca(axes[1, 0]) matplotlib.pyplot.xticks(numElements, date_list,rotation=four_subplot_overview_tickrota) axes[1, 0].axhspan(0, 5, alpha=0.5, color='green') axes[1, 0].set_ylim([ymin,ymax]) axes[1, 1].plot(numElements, pos_T2sl12, 'bo',markersize=4) axes[1, 1].set_title('T2 slice 12') axes[1, 1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axes[1, 1].set_xlabel('Date') axes[1, 1].axhspan(0, 5, alpha=0.5, color='green') axes[1, 1].set_ylim([ymin,ymax]) axes[0 ,0].yaxis.grid() axes[0 ,1].yaxis.grid() axes[1 ,0].yaxis.grid() axes[1 ,1].yaxis.grid() matplotlib.pyplot.sca(axes[1, 1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=four_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('Position') # PIU f, axarr = matplotlib.pyplot.subplots(2, sharex=True) f.set_figheight(two_subplot_overview_height) f.set_figwidth(two_subplot_overview_width) ymin = 65 ymax = 100 axarr[0].set_ylim([ymin,ymax]) axarr[0].plot(numElements, pIU_T1, 'bo',markersize=4) axarr[0].set_title('PIU T1') axarr[0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[0].set_ylabel('PIU in percentage') axarr[0].axhspan(82, 100, alpha=0.5, color='green') axarr[0].set_ylim([ymin,ymax]) axarr[1].axhspan(82,100, alpha=0.5, color='green') axarr[1].set_ylim([ymin,ymax]) axarr[1].plot(numElements, pIU_T2, 'bo',markersize=4) axarr[1].set_title('PIU T2') axarr[1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[1].set_xlabel('Date') axarr[1].set_ylabel('PIU in percentage') axarr[1].set_ylim([ymin,ymax]) axarr[0].yaxis.grid() axarr[0].yaxis.grid() matplotlib.pyplot.sca(axarr[1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=two_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('PIU') # PSG f, axarr = matplotlib.pyplot.subplots(2, sharex=True) f.set_figheight(two_subplot_overview_height) f.set_figwidth(two_subplot_overview_width) ymin = 0 ymax = 0.1 axarr[0].set_ylim([ymin,ymax]) axarr[0].plot(numElements, pSG_T1, 'bo',markersize=4) axarr[0].set_title('PSG T1') axarr[0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[0].set_ylabel('PSG in percentage') axarr[0].axhspan(0, 0.025, alpha=0.5, color='green') axarr[0].set_ylim([ymin,ymax]) axarr[1].axhspan(0,0.025, alpha=0.5, color='green') axarr[1].set_ylim([ymin,ymax]) axarr[1].plot(numElements, pSG_T2, 'bo',markersize=4) axarr[1].set_title('PSG T2') axarr[1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[1].set_xlabel('Date') axarr[1].set_ylabel('PSG in percentage') axarr[1].set_ylim([ymin,ymax]) axarr[0].yaxis.grid() axarr[0].yaxis.grid() matplotlib.pyplot.sca(axarr[1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=two_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('PSG') # Low-contrast object f, axarr = matplotlib.pyplot.subplots(2, sharex=True) f.set_figheight(two_subplot_overview_height) f.set_figwidth(two_subplot_overview_width) ymin = 0 ymax = 45 axarr[0].set_ylim([ymin,ymax]) axarr[0].plot(numElements, lCOD_sum_T1, 'bo',markersize=4) axarr[0].set_title('PSG T1') axarr[0].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[0].set_ylabel('Number of objects') axarr[0].axhspan(36, 40, alpha=0.5, color='green') axarr[0].set_ylim([ymin,ymax]) axarr[1].axhspan(36,40, alpha=0.5, color='green') axarr[1].set_ylim([ymin,ymax]) axarr[1].plot(numElements, lCOD_sum_T1, 'bo',markersize=4) axarr[1].set_title('PSG T2') axarr[1].set_xlim([-0.5,float(number_of_shown_values)+0.5]) axarr[1].set_xlabel('Date') axarr[1].set_ylabel('Number of objects') axarr[1].set_ylim([ymin,ymax]) axarr[0].yaxis.grid() axarr[0].yaxis.grid() matplotlib.pyplot.sca(axarr[1]) matplotlib.pyplot.xticks(numElements, date_list,rotation=two_subplot_overview_tickrota) matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig('LCOD') # HTML def generate_html(resultpath): menu_html_file_path = '/home/brain/qa/html/menu_html.html' menu_html_file = open(menu_html_file_path, 'r') menu_html = menu_html_file.readlines() menu_html_file.close() result_file = open(resultpath+'overview.html','w') result_file.writelines(menu_html) result_file.write('\t\t<h1 style="margin-top:80px;">ACR-Overview</h1>\n') result_file.write('\t\t<h2>Geometry Localizer</h2>\n\t\t<p>\n\t\t\t<img src="Geometry_Localizer.png" alt="Geometry Localizer">\n\t\t</p>\n') result_file.write('\t\t<h2>Geometry T1</h2>\n\t\t<p>\n\t\t\t<img src="Geometry_T1.png" alt="Geometry T1">\n\t\t</p>\n') result_file.write('\t\t<h2>Resolution T1</h2>\n\t\t<p>\n\t\t\t<img src="Resolution_T1.png" alt="Resolution T1">\n\t\t</p>\n') result_file.write('\t\t<h2>Resolution T2</h2>\n\t\t<p>\n\t\t\t<img src="Resolution_T2.png" alt="Resolution T2">\n\t\t</p>\n') result_file.write('\t\t<h2>Slice Thickness</h2>\n\t\t<p>\n\t\t\t<img src="Thickness.png" alt="Slice Thickness">\n\t\t</p>\n') result_file.write('\t\t<h2>Slice Position</h2>\n\t\t<p>\n\t\t\t<img src="Position.png" alt="Slice Position">\n\t\t</p>\n') result_file.write('\t\t<h2>PIU</h2>\n\t\t<p>\n\t\t\t<img src="PIU.png" alt="PIU"></p>\n') result_file.write('\t\t<h2>PSG</h2>\n\t\t<p>\n\t\t\t<img src="PSG.png" alt="PSG"></p>\n') result_file.write('\t\t<h2>LCOD</h2>\n\t\t<p>\n\t\t\t<img src="LCOD.png" alt="LCOD">\n\t\t</p>\n') result_file.write('\t\t<h1>Results</h1>\n') result_file.write('\t\t<ul>\n') result_list = os.listdir(resultpath) result_list.sort(reverse=True) for i in result_list: if os.path.isdir(resultpath+i): rfile = open(i+'/overview.txt','r') lines = rfile.readlines() for j in lines: entry = j.split(';') geo_loc = float(entry[1].replace(',','.')) geo_T1sl1hor = float(entry[2].replace(',','.')) geo_T1sl1ver = float(entry[3].replace(',','.')) geo_T1sl5hor = float(entry[4].replace(',','.')) geo_T1sl5ver = float(entry[5].replace(',','.')) geo_T1sl5_p45 = float(entry[6].replace(',','.')) geo_T1sl5_m45 = float(entry[7].replace(',','.')) res_maxT1rechts1_1 = float(entry[8].replace(',','.')) res_maxT1links1_1 = float(entry[9].replace(',','.')) res_maxT1rechts1_0 = float(entry[10].replace(',','.')) res_maxT1links1_0 = float(entry[11].replace(',','.')) res_maxT1rechts0_9 = float(entry[12].replace(',','.')) res_maxT1links0_9 = float(entry[13].replace(',','.')) res_maxT2rechts1_1 = float(entry[14].replace(',','.')) res_maxT2links1_1 = float(entry[15].replace(',','.')) res_maxT2rechts1_0 = float(entry[16].replace(',','.')) res_maxT2links1_0 = float(entry[17].replace(',','.')) res_maxT2rechts0_9 = float(entry[18].replace(',','.')) res_maxT2links0_9 = float(entry[19].replace(',','.')) thick_T1 = float(entry[20].replace(',','.')) thick_T2 = float(entry[21].replace(',','.')) pos_T1sl2 = float(entry[22].replace(',','.')) pos_T1sl12 = float(entry[23].replace(',','.')) pos_T2sl2 = float(entry[24].replace(',','.')) pos_T2sl12 = float(entry[25].replace(',','.')) pIU_T1 = float(entry[26].replace(',','.')) pIU_T2 = float(entry[27].replace(',','.')) pSG_T1 = float(entry[28].replace(',','.')) pSG_T2 = float(entry[29].replace(',','.')) lCOD_sum_T1 = float(entry[30].replace(',','.')) try: lCOD_sum_T2 = float(entry[31].replace(',','.')) except: lCOD_sum_T2 = 0 rfile.close() if (146 <= geo_loc and geo_loc <= 150) and (188 <= geo_T1sl1hor and geo_T1sl1hor <= 192) and (188 <= geo_T1sl1ver and geo_T1sl1ver <= 192) and (188 <= geo_T1sl5hor and geo_T1sl5hor <= 192) and (188 <= geo_T1sl5ver and geo_T1sl5ver <= 192) and (188 <= geo_T1sl5_p45 and geo_T1sl5_p45 <= 192) and (188 <= geo_T1sl5_m45 and geo_T1sl5_m45 <= 192) and (res_maxT1rechts1_1 >= 4) and (res_maxT1links1_1 >= 4) and (res_maxT1rechts1_0 >= 4) and (res_maxT1links1_0 >= 4) and (res_maxT1rechts0_9 >= 4) and (res_maxT1links0_9 >= 4) and (res_maxT2rechts1_1 >= 4) and (res_maxT2links1_1 >= 4) and (res_maxT2rechts1_0 >= 4) and (res_maxT2links1_0 >= 4) and (res_maxT2rechts0_9 >= 4) and (res_maxT2links0_9 >= 4) and (4.3 <= thick_T1 and thick_T1 <= 5.7) and (4.3 <= thick_T1 and thick_T1 <= 5.7) and (0 <= pos_T1sl2 and pos_T1sl2 <= 5) and (0 <= pos_T1sl12 and pos_T1sl12 <= 5) and (0 <= pos_T2sl2 and pos_T2sl2 <= 5) and (0 <= pos_T2sl12 and pos_T2sl12 <= 5) and (82 <= pIU_T1 and pIU_T1 <= 100) and ( 82 <= pIU_T2 and pIU_T2 <= 100) and (0 <= pSG_T1 and pSG_T1 <= 0.025) and (0 <= pSG_T2 and pSG_T2 <= 0.025) and (36 <= lCOD_sum_T1 and lCOD_sum_T1 <= 40) and (36 <= lCOD_sum_T2 and lCOD_sum_T2 <= 40): result_file.write('\t\t\t<li><a href="'+i+'/results.html">'+i+'</a></li>\n') else: result_file.write('\t\t\t<li><img src="/warning.png"><a href="'+i+'/results.html">'+i+'</a></li>\n') result_file.write('\t\t</ul>\n') result_file.write('\t</body>\n</html>') def main(overview_logfile,matlab_path,resultpath,number_of_shown_values): os.chdir('/home/brain/qa/html/results/acr/') generate_graph(overview_logfile,matlab_path,resultpath,number_of_shown_values) generate_html(resultpath)
[ "christophvogelbacher@gmail.com" ]
christophvogelbacher@gmail.com
56fdabbe1587c1823795ba24b870fd98aabe0384
e2f823cf79c6ec89b976e7f53e0035b0eb0831cc
/01.python/ch04/ex02.py
1b1d44dd12dc79593a00a66c1f45098a55231734
[]
no_license
taxioo/study_python
a292ea371d5e75ff97cede040f71838dabcc9d56
28f9436948e806ff559a2778946b5147605f45b9
refs/heads/master
2023-06-13T03:58:46.843182
2021-07-13T08:43:19
2021-07-13T08:43:19
383,677,279
0
0
null
null
null
null
UTF-8
Python
false
false
95
py
print(3**3) print(2**10) print(5/2) print(5//2) print(5%2) print(7%2) print(8%3) print(9%3)
[ "taxioo@naver.com" ]
taxioo@naver.com
dd95876820f404bb83e0407de3cbb5f7f4cb2719
97f74fe460e2622e42dc713abc44de29ec3b8544
/Week7/day5/xp.py
0a1d4f5184d98184a899207816a30f944a4f0621
[]
no_license
amcamhi/Developers-Institute
dd54878955bc6cefdba819b9a543fb0e79b2aab0
255917850a0234c97a80f7de3da8c67ca94967b6
refs/heads/master
2022-11-24T05:53:28.301057
2020-08-04T13:11:49
2020-08-04T13:11:49
272,376,528
0
0
null
2020-06-15T15:43:27
2020-06-15T07:56:51
HTML
UTF-8
Python
false
false
679
py
import json # sampleJson = """{ # "company":{ # "employee":{ # "name":"emma", # "payble":{ # "salary":7000, # "bonus":800 # } # } # } # }""" # data = json.loads(sampleJson) # print(data['company']['employee']['payble']['salary']) sampleJson = {"id": 1, "name": "value2", "age": 29} # Expected Output: # { # "age": 29, # "id": 1, # "name": "value2" # } data = sampleJson json_file = 'my_file.json' with open(json_file, 'w') as file_obj: json.dump(data, file_obj, indent=2, sort_keys=True) with open(json_file, 'r') as file_obj: sampleJson = json.load(file_obj) print(sampleJson)
[ "andrescamhi@gmail.com" ]
andrescamhi@gmail.com
4f7a9fd1c215ece430e21b41ce6af42e090f8715
3291359d8867e7b5ca9e8befb83629810938f903
/timetable_v3/webapp/migrations/0005_auto_20210625_1358.py
120f34ac33c17a1128eccac0690cad55bf008e69
[]
no_license
A-miin/timetable_v3
f9e4610800acb83f3477dcffd2b0ce1c75d2c1d0
1de0885f04beec83657672275deff22b71af2de3
refs/heads/master
2023-06-09T18:51:44.298534
2021-07-02T15:01:54
2021-07-02T15:01:54
341,462,656
0
0
null
null
null
null
UTF-8
Python
false
false
958
py
# Generated by Django 3.1.7 on 2021-06-25 07:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webapp', '0004_auto_20210507_0129'), ] operations = [ migrations.RemoveField( model_name='timetablegenerator', name='course', ), migrations.RemoveField( model_name='timetablegenerator', name='department', ), migrations.RemoveField( model_name='timetablegenerator', name='grade_year', ), migrations.RemoveField( model_name='timetablegenerator', name='room', ), migrations.RemoveField( model_name='timetablegenerator', name='teacher', ), migrations.DeleteModel( name='Editor', ), migrations.DeleteModel( name='TimeTableGenerator', ), ]
[ "zulaykaisaeva@gmail.com" ]
zulaykaisaeva@gmail.com
2d551f252fa3c728349140379132ba33e39183ad
51970fa793ec7f92164e60c1fcbf17f62aa469d5
/ScreamingIce/pages/views.py
261c600db923286480ac868117163b2fcdd5b679
[]
no_license
SixStringsCoder/pdx_coding
6eef25490c74459feafd53a190ab06a0aaf685aa
5853bb74a247187cec6ac0f4bb8b3a54931372e9
refs/heads/master
2021-01-19T20:41:23.268478
2017-08-24T06:37:29
2017-08-24T06:37:29
88,534,471
0
0
null
null
null
null
UTF-8
Python
false
false
169
py
from django.shortcuts import render # Create your views here. def home(request): """ Renders the landing page. """ return render(request, 'home.html')
[ "rshanlon@gmail.com" ]
rshanlon@gmail.com
06630dccbc178eb0cd698a329c16505bf613ac97
ba6601770cad359b3f9b2724ceb7f469081a0c33
/djangoDemo/bin/python-config
0216af85e8e66a6c5553f2043eacd25f86994142
[]
no_license
merryt/djangoDemo
57f848242025049d828320f2dd9ab9e7ffe9787a
7243d64845747f8378c28c74c4bd754849894a27
refs/heads/master
2021-09-02T12:32:50.647043
2018-01-02T16:48:20
2018-01-02T16:48:20
115,240,629
0
0
null
2018-01-02T16:42:35
2017-12-24T04:49:16
null
UTF-8
Python
false
false
2,385
#!/Users/tylermerry/Dropbox/SideProjects/fool-devinterview/djangoDemo/bin/python import sys import getopt import sysconfig valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] if sys.version_info >= (3, 2): valid_opts.insert(-1, 'extension-suffix') valid_opts.append('abiflags') if sys.version_info >= (3, 3): valid_opts.append('configdir') def exit_with_usage(code=1): sys.stderr.write("Usage: {0} [{1}]\n".format( sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) except getopt.error: exit_with_usage() if not opts: exit_with_usage() pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var opt_flags = [flag for (flag, val) in opts] if '--help' in opt_flags: exit_with_usage(code=0) for opt in opt_flags: if opt == '--prefix': print(sysconfig.get_config_var('prefix')) elif opt == '--exec-prefix': print(sysconfig.get_config_var('exec_prefix')) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_path('include'), '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): abiflags = getattr(sys, 'abiflags', '') libs = ['-lpython' + pyver + abiflags] libs += getvar('LIBS').split() libs += getvar('SYSLIBS').split() # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) if not getvar('PYTHONFRAMEWORK'): libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) elif opt == '--extension-suffix': ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix is None: ext_suffix = sysconfig.get_config_var('SO') print(ext_suffix) elif opt == '--abiflags': if not getattr(sys, 'abiflags', None): exit_with_usage() print(sys.abiflags) elif opt == '--configdir': print(sysconfig.get_config_var('LIBPL'))
[ "tymerry@gmail.com" ]
tymerry@gmail.com
443ff8d3ac0f5fd82f895ebe8333083de4acfa43
b4d334e6495f97fa20e4a19d5546cafab49c36c9
/src/Prodavac.py
da010f2ff258bc2a65641d3ab67da5085b904fdc
[]
no_license
OMKE/CinemaApp
892cf35312ca0e23e0fe7a33980bbe496210a2a8
e58d251e0f52f5e60981fdca5f435d3862c6a4d9
refs/heads/master
2020-03-21T14:25:11.507322
2018-10-11T23:16:09
2018-10-11T23:16:09
138,656,235
1
0
null
null
null
null
UTF-8
Python
false
false
3,027
py
import Menadzer import ProdavacPrikaz import Login import datetime import uuid racun = [] ukupnoZaPlatiti = [] def prodajaKarti(): print(28 * "-") print(" Prodaja karata ") print(28 * "-") projekcije = Menadzer.prikazProjekcija() nadjen = False unosId = input("Unesite ID projekcije: ") for i in projekcije: if unosId == i["id"]: nadjen = True print("Izabrali ste projekciju: " + i["film"] + " - Datum: " + i["datum"] + " - Vrijeme pocetka: " + i[ "vrijemePocetka"] + " - Sala: " + i["sala"]) while True: try: unosBroja = int(input("Unesite broj karata koliko zelite prodati: ")) break except ValueError: print("Unos rijeci nije dozvoljen, pokusajte ponovo") if unosBroja > int(i["slobodnoMjesta"]): print("Uneseni broj karata je veci od broja slobodnog mjesta") prodajaKarti() else: ukupno = int(i["cijena"]) * unosBroja slobodnaMjesta = int(i["slobodnoMjesta"]) - unosBroja i["slobodnoMjesta"] = slobodnaMjesta print("Ukupno za platiti: " + str(ukupno) + " RSD") racun.append(i) saveRacun(unosBroja) ukupnoZaPlatiti.append(ukupno) racun.pop(0) if nadjen == False: print("Ne postoji projekcija sa unesenim ID-jem") ProdavacPrikaz.prodavacPrikaz() josProjekcija = input("Ako zelite jos projekcija unesite rijec - da: ") if josProjekcija.lower() == "da": prodajaKarti() else: Menadzer.saveProjekcije(projekcije) zapisiRacun() print("Racun je zapisan u bazu podataka") ProdavacPrikaz.prodavacPrikaz() def sracunajUkupno(): suma = 0 for i in ukupnoZaPlatiti: suma += i return suma def saveRacun(unosBroja): with open("data/racuni.txt", "a") as racuni: racuni.write("\n" + 30 * "-") racuni.write("\n Racun") for i in racun: racuni.write(" \nProjekcija: " + str(i["film"]) + "\n - Datum: " + str( i["datum"]) + "\n - Vrijeme pocetka: " + str(i[ "vrijemePocetka"]) + "\n - Sala: " + str(i["sala"])) racuni.write("\nBroj karata: " + str(unosBroja)) def zapisiRacun(): ukupno = sracunajUkupno() with open("data/racuni.txt", "a") as racuni: racuni.write("\n") for j in Login.ulogovaniKorisnik: racuni.write("\nIznos: " + str(ukupno) + " RSD") racuni.write("\nProdavac: " + str(j["ime"] + " " + str(j["prezime"]))) racuni.write("\nDatum: " + str(datetime.datetime.now())) racuni.write("\nSifra racuna: " + str(uuid.uuid1())[:8]) racuni.write("\n") racuni.write(30 * "-") racuni.write("\n")
[ "noisewavehd@gmail.com" ]
noisewavehd@gmail.com
4ef05b142fdc35985ff11f279c6a5933b45adfb3
346351a2ca85267d68f1a5897ccfb36e52b166fb
/manage.py
b88d5435e0232bd437170d646b418ac49c9131a1
[]
no_license
jeffyromney/VRC
1e00a1369127231eba4e8653f9ff3c5214b763c4
384ba7d4f08962ec8ad47141b79da475acc18142
refs/heads/master
2021-05-23T06:21:36.972639
2021-02-10T18:05:10
2021-02-10T18:05:10
42,422,738
0
0
null
null
null
null
UTF-8
Python
false
false
246
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vrc.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "jeffyromney@gmail.com" ]
jeffyromney@gmail.com
db378aa0c16f3ee5c69c61b89bb58d0e9d9b3077
fd54c0886b81b49a55c31eb8c5254ce83df78785
/Source_Code/madagascar/appussd/ussd/services/prepaid/prepaidServicesServer.py
958a6c3c2997ac0db1b9f53b6f8c10cea1f1ef4c
[]
no_license
santsy03/RADIX
7854896651833b1be6e3279be409db59a71c76e4
da8f2535692697b80a6dc543b9eb270fe3d5e4d3
refs/heads/master
2021-01-12T09:48:32.085432
2016-12-13T06:01:41
2016-12-13T06:01:41
76,260,115
0
0
null
2016-12-13T06:01:41
2016-12-12T13:46:31
null
UTF-8
Python
false
false
2,681
py
#!/usr/bin/env python from twisted.web import http from string import Template from twisted.internet import threads,reactor,defer from config import debug,errorMsg import cx_Oracle from DBUtils.PooledDB import PooledDB def getParams(request): params = {} for k,v in request.args.items(): params[k] = v[0] return params def sendResponse(results,request): if debug: print 'sendResponse: results - '+str(results) request.write(results) request.finish() def processMenu1(request): from core import processRequest params = getParams(request) resources = {} resources['request'] = request params['connections'] = request.getConnections() resources['parameters'] = params try: response = processRequest(resources) success = 'success:%s|%s' %(str(resources['parameters']),str(response),) print success except Exception,e: error = 'failed:%s,error:%s' %(str(resources['parameters']),str(e),) print error response = errorMsg sendResponse(response,request) class requestHandler(http.Request): pages = {'/process':processMenu1} def __init__(self,channel,queued): http.Request.__init__(self,channel,queued) def process(self): if self.pages.has_key(self.path): handler = self.pages[self.path] d = threads.deferToThread(handler,self) d.addErrback(catchError) return d else: self.setResponseCode(http.NOT_FOUND) self.write('page not found') self.finish() def getConnections(self): return self.channel.getDbConnection() class requestProtocol(http.HTTPChannel): requestFactory = requestHandler def getDbConnection(self): connections = self.factory.connectionPools return connections class RequestFactory(http.HTTPFactory): protocol = requestProtocol isLeaf = True def __init__(self): from ussd.configs.core import databases from ussd.services.common.secure.secure import decrypt username = decrypt(databases['core']['username']) password = decrypt(databases['core']['password']) string = databases['core']['string'] http.HTTPFactory.__init__(self) pool = PooledDB(cx_Oracle, maxcached=5, maxconnections=100, user=username, password=password, dsn=string, threaded=True) self.connectionPools = pool def catchError(e=''): resp = {} resp['ussdResponseString'] = 'System Error. Please try again later.' resp['action'] = 'end' print "Error %s"%(str(e)) return resp
[ "root@oc4686551628.ibm.com" ]
root@oc4686551628.ibm.com
e9e2af2ca6bcc6c6f56fc553bfda90c0b95f9869
fefb1e9b0b736da4e49d7754f8d1dbaf37f2fa6a
/.history/test_class_20210217173011.py
bce5fddaade07a680e979ac2cd09b3d00cf65f73
[]
no_license
wh-debug/python
5a78a2227874ebc400d075197de0adab9f55d187
1467eeda670f170e6e2d7c0a0550f713f1ee9d75
refs/heads/master
2023-03-12T22:08:12.608882
2021-02-17T09:49:52
2021-02-17T09:49:52
334,032,494
0
0
null
null
null
null
UTF-8
Python
false
false
599
py
''' Author: 零到正无穷 Date: 2021-02-17 17:13:26 LastEditTime: 2021-02-17 17:21:47 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: \python\test_class.py ''' class AnonymousSurvey: def __init__(self, question): self.question = question self.responses = [] def show_question(self): print(self.question) def store_response(self, new_response): self.responses.append(new_response) def show_results(self): print("Survey results: ") for response in self.responses: print(f"- {response}")
[ "1813763848@qq.com" ]
1813763848@qq.com
fee879aeb0c17bd0494eed14ce79c9daf9a1cad2
c3ef4e33bcdbd8c880f5903bdab1ae1848963ef4
/pomodoro.py
5a24941849eb33e61adb5c51d8a5dd8fc554ad91
[]
no_license
permanentdaylight/pomodoro_tkinter
1380f5a7e05c2b8d55d2adc9294e72c425a12eed
991861ae494bae609efa9543d5ae0544617ecf8f
refs/heads/master
2021-06-02T03:28:23.989775
2016-08-17T22:05:16
2016-08-17T22:05:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,455
py
import tkinter from tkinter import messagebox DEFAULT_GAP = 60 * 25 DEFAULT_GAP = 5 class Pymodoro: def __init__(self, master): self.master = master self.mainframe = tkinter.Frame(self.master, bg='white') self.mainframe.pack(fill=tkinter.BOTH, expand=True) self.timer_text = tkinter.StringVar() self.timer_text.trace('w', self.build_timer) self.time_left = tkinter.IntVar() self.time_left.set(DEFAULT_GAP) self.time_left.trace('w', self.alert) self.running = False self.build_grid() self.build_banner() self.build_buttons() self.build_timer() self.update() def build_grid(self): self.mainframe.columnconfigure(0, weight=1) self.mainframe.rowconfigure(0, weight=0) self.mainframe.rowconfigure(1, weight=1) self.mainframe.rowconfigure(2, weight=0) def build_banner(self): banner = tkinter.Label( self.mainframe, background='red', text='Pymodoro', fg='white', font=('Helvetica', 24) ) banner.grid( row=0, column=0, sticky='ew', padx=10, pady=10 ) def build_buttons(self): buttons_frame = tkinter.Frame(self.mainframe) buttons_frame.grid(row=2, column=0, sticky='nsew', padx=10, pady=10) buttons_frame.columnconfigure(0, weight=1) buttons_frame.columnconfigure(1, weight=1) self.start_button = tkinter.Button( buttons_frame, text='Start', command=self.start_timer ) self.stop_button = tkinter.Button( buttons_frame, text='Stop', command=self.stop_timer ) self.start_button.grid(row=0, column=0, sticky='ew') self.stop_button.grid(row=0, column=1, sticky='ew') self.stop_button.config(state=tkinter.DISABLED) def build_timer(self, *args): timer = tkinter.Label( self.mainframe, text=self.timer_text.get(), font=('Helvetica', 36) ) timer.grid(row=1, column=0, sticky='nsew') def start_timer(self): self.time_left.set(DEFAULT_GAP) self.running = True self.stop_button.config(state=tkinter.NORMAL) self.start_button.config(state=tkinter.DISABLED) def stop_timer(self): self.running = False self.stop_button.config(state=tkinter.DISABLED) self.start_button.config(state=tkinter.NORMAL) def alert(self, *args): if not self.time_left.get(): messagebox.showinfo('Timer done!', 'Your timer is done!') def minutes_seconds(self, seconds): return int(seconds/60), int(seconds%60) def update(self): time_left = self.time_left.get() if self.running and time_left: minutes, seconds = self.minutes_seconds(time_left) self.timer_text.set( '{:0>2}:{:0>2}'.format(minutes, seconds) ) self.time_left.set(time_left-1) else: minutes, seconds = self.minutes_seconds(DEFAULT_GAP) self.timer_text.set( '{:0>2}:{:0>2}'.format(minutes, seconds) ) self.stop_timer() self.master.after(1000, self.update) if __name__ == '__main__': root = tkinter.Tk() Pymodoro(root) root.mainloop()
[ "oakesonline@gmail.com" ]
oakesonline@gmail.com
648cbaab7881874ead2cdc6da70524daa33610e1
c716b5a5d68e2c17dd83d3b051e6d7791ae50e5b
/main.py
566f4881a4e1e647cde880bad52db2633881cb3a
[]
no_license
Akon-111/telegram_bot
8146a24e709bda761406994e0d212df7fddaa7b2
293be9b84846429994a68b52c855bbe29250501a
refs/heads/main
2023-02-10T12:37:03.018008
2021-01-09T10:56:16
2021-01-09T10:56:16
328,089,160
1
0
null
null
null
null
UTF-8
Python
false
false
1,695
py
from telegram import ReplyKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackContext, ConversationHandler, MessageHandler,Filters from covid19 import Covid19 buttons = ReplyKeyboardMarkup([[ 'Statistika'],['Dunyo']], resize_keyboard = True) covid = Covid19() def start(update,context): update.message.reply_html( '<b>Assalomu alaykum, {}</b>\n \nMen Koronavirus statistikasi haqida ma"lumot beruvchi botman'.format(update.message.from_user.first_name), reply_markup = buttons) return 1 def stats (update,context): data = covid.getByCountryCode("UZ") update.message.reply_html( '🇺🇿<b>O"zbekistonda</b>\n \n<b>Yuqtirganlar:</b> {}\n <b>Sog"ayganlar: </b>{}\n<b> Vafot etganlar:</b> {}'. format( data['confirmed'], data['recovered'], data['deaths']), reply_markup = buttons) def world (update,context): data = covid.getLatest() update.message.reply_html( '🌎<b>Dunyoda</b>\n \n<b>Yuqtirganlar:</b>{}\n<b>Sogayganlar:</b>{}\n<b>Vafot etganlar:</b>[}'.format( "{:,}".format(data['confirmed']), "{:,}".format(data['recovered']), "{:,}".format(data['deaths']) ), reply_markup = buttons) updater = Updater('1581441216:AAG-sHW2QLxWFPmAO2dIe5vr8SxS2-yWfjU', use_context=True) conv_handler = ConversationHandler( entry_points = [CommandHandler('start',start)], states={ 1:[ MessageHandler(Filters.regex('^(Statistika)$'),stats), MessageHandler(Filters.regex('^(Dunyo)$'),world), ] }, fallbacks = [MessageHandler(Filters.text,start)] ) updater.dispatcher.add_handler(conv_handler) updater.start_polling() updater.idle()
[ "aromjonadhamov@mail.ru" ]
aromjonadhamov@mail.ru
0ad006c54cbc1cf67afd98386a4474fad49ffcab
8f7b7a910520ba49a2e614da72f7b6297f617409
/Problemset/sqrtx/sqrtx.py
6624e19f4dc011f04130cc73002bce4d6d2ef5c9
[]
no_license
fank-cd/python_leetcode
69c4466e9e202e48502252439b4cc318712043a2
61f07d7c7e76a1eada21eb3e6a1a177af3d56948
refs/heads/master
2021-06-16T23:41:55.591095
2021-03-04T08:31:47
2021-03-04T08:31:47
173,226,640
1
0
null
null
null
null
UTF-8
Python
false
false
481
py
# @Title: x 的平方根 (Sqrt(x)) # @Author: 2464512446@qq.com # @Date: 2020-11-23 17:00:58 # @Runtime: 48 ms # @Memory: 13.5 MB class Solution: def mySqrt(self, x: int) -> int: left, right = 1, x res = 0 while left <= right: mid = left + (right-left)//2 sqrt = mid * mid if sqrt <= x: left = mid + 1 res = mid else: right = mid - 1 return res
[ "2464512446@qq.com" ]
2464512446@qq.com
1f33da6f38fbb1be0b6988122f5be9fc863eb5c5
8f43323e42495b766cae19a76a87d24c2ea2b086
/compiler/tests/11_ms_flop_array_test.py
ce24f49a2230155c4473399da4189fc694c32e97
[ "BSD-3-Clause" ]
permissive
rowhit/OpenRAM
7c78b3998044d8c30effd33c9176dc07491df949
f98155fc0b6019dc61b73b59ca2a9d52245bb41c
refs/heads/master
2021-05-05T22:32:43.177316
2017-12-19T15:39:43
2017-12-19T15:39:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,627
py
#!/usr/bin/env python2.7 """ Run a regresion test on a dff_array. """ import unittest from testutils import header import sys,os sys.path.append(os.path.join(sys.path[0],"..")) import globals from globals import OPTS import debug import verify import importlib #@unittest.skip("SKIPPING 20_sram_test") class dff_array_test(unittest.TestCase): def runTest(self): globals.init_openram("config_20_{0}".format(OPTS.tech_name)) OPTS.check_lvsdrc = False import ms_flop_array debug.info(2, "Testing ms_flop_array for columns=8, word_size=8") a = ms_flop_array.ms_flop_array(columns=8, word_size=8) self.local_check(a) debug.info(2, "Testing ms_flop_array for columns=16, word_size=8") a = ms_flop_array.ms_flop_array(columns=16, word_size=8) self.local_check(a) OPTS.check_lvsdrc = True globals.end_openram() def local_check(self, a): tempspice = OPTS.openram_temp + "temp.sp" tempgds = OPTS.openram_temp + "temp.gds" a.sp_write(tempspice) a.gds_write(tempgds) self.assertFalse(verify.run_drc(a.name, tempgds)) self.assertFalse(verify.run_lvs(a.name, tempgds, tempspice)) os.remove(tempspice) os.remove(tempgds) # reset the static duplicate name checker for unit tests import design design.design.name_map=[] # instantiate a copdsay of the class to actually run the test if __name__ == "__main__": (OPTS, args) = globals.parse_args() del sys.argv[1:] header(__file__, OPTS.tech_name) unittest.main()
[ "mrg@ucsc.edu" ]
mrg@ucsc.edu
de9931a68f802ab5e6176d363006cdef2f69ac7b
104a73fff0fb23e002f1b75167fea12364cf6574
/timeline_logger/migrations/0002_auto_20160624_1045.py
071bfa7be73e29e2967c21c8d04ef98cbf724d75
[ "MIT" ]
permissive
maykinmedia/django-timeline-logger
2ae4c3dd450c4a1674ee258015962e184a5c05fe
63f656699b11f242e7aaad1d07cb80ebc953cd48
refs/heads/master
2023-07-20T13:08:41.703719
2023-07-12T09:29:31
2023-07-12T09:29:31
61,119,762
56
7
MIT
2023-07-12T09:12:37
2016-06-14T12:08:51
Python
UTF-8
Python
false
false
520
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-06-24 10:45 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("timeline_logger", "0001_initial"), ] operations = [ migrations.AlterModelOptions( name="timelinelog", options={ "verbose_name": "timeline log entry", "verbose_name_plural": "timeline log entries", }, ), ]
[ "sergei@maykinmedia.nl" ]
sergei@maykinmedia.nl
b7cc83503174e4285c45f749f026d6c253fbba70
eb07b61f41e6d8e3a9c36e92ac0f41e180a63a87
/excelerador.py
a61ffda3337b70b61b951a3dbbf6fbc0f3864029
[]
no_license
grodriguece/NPO
11b6640d79c38f2a9926a53f60201ef9d5fad099
087774f73b2e4af0236839bbc5c69c8ccfad5257
refs/heads/master
2023-02-14T22:10:25.312262
2021-01-11T19:00:04
2021-01-11T19:00:04
280,881,032
0
0
null
null
null
null
UTF-8
Python
false
false
2,611
py
def pasarchivo(ruta, datb, tablas, tipo): """copy to csv files tables from query results""" import sqlite3 import pandas as pd import timeit from pyexcelerate import Workbook from pathlib import Path from datetime import date dat_dir = Path(ruta) db_path1 = dat_dir / datb start_time = timeit.default_timer() conn = sqlite3.connect(db_path1) # database connection c = conn.cursor() today = date.today() df1 = pd.read_csv(tablas) xls_file = "Param" + today.strftime("%y%m%d") + ".xlsx" xls_path = dat_dir / xls_file # xls file path-name csv_path = dat_dir / "csv" # csv path to store big data wb = Workbook() # excelerator file init i = 0 for index, row in df1.iterrows(): # panda row iteration tablas file by tipo column line = row[tipo] if not pd.isna(row[tipo]): # nan null values validation try: df = pd.read_sql_query("select * from " + line + ";", conn) # pandas dataframe from sqlite if len(df) > 1000000: # excel not supported csv_loc = line + today.strftime("%y%m%d") + '.csv.gz' # compressed csv file name print('Table {} saved in {}'.format(line, csv_loc)) df.to_csv(csv_path / csv_loc, compression='gzip') # pandas dataframe saved to csv else: data = [df.columns.tolist()] + df.values.tolist() data = [[index] + row for index, row in zip(df.index, data)] wb.new_sheet(line, data=data) print('Table {} stored in xlsx sheet'.format(line)) i += 1 except sqlite3.Error as error: # sqlite error handling print('SQLite error: %s' % (' '.join(error.args))) end_time = timeit.default_timer() delta = round(end_time - start_time, 2) print("Data proc took " + str(delta) + " secs") deltas = 0 if i == 0: print('No tables to excel') else: print("Saving tables in {} workbook".format(xls_path)) start_time = timeit.default_timer() wb.save(xls_path) end_time = timeit.default_timer() deltas = round(end_time - start_time, 2) print("xlsx save took " + str(deltas) + " secs") print("Total time " + str(delta+deltas) + " secs") c.close() conn.close() pasarchivo("C:/XML/SQL/missiing", "20200522_sqlite.db", "tablasSQL.csv", "Audit")
[ "grodriguece@gmail.com" ]
grodriguece@gmail.com
8a78e1eeec85f9bc4813694064d41de800fa6166
0559d727fbf03410674daf16f2be7dd335a1159d
/hello.py
4aa3a10a5eb408c937d7ae874e5978f733631054
[ "MIT" ]
permissive
sanjaykim/class
8c89da225477f1069b04423976266f5bd696924c
48a96045476873c56adaaa7ef9ce81db5e785f76
refs/heads/master
2021-01-19T01:05:24.747735
2016-06-16T08:51:40
2016-06-16T08:51:40
61,268,815
0
0
null
null
null
null
UTF-8
Python
false
false
42
py
import pandas as pd print("Hello World")
[ "sanjay@sanjay.gq" ]
sanjay@sanjay.gq
a775d9b0bb304911d934449b4f80e22ed88eba30
9ef923b4f24e1db90cc2904556fe30c4d99abff6
/prime-numbers.py
b24d111f14ba0accca8acf507349931dddeb2489
[]
no_license
magda-zielinska/python-level1
f8ca551fb6b136a8eef51a24a617eea475c34b85
c6a19b6d35a1b68ba6294e82074e3085e8d34c6f
refs/heads/master
2021-10-21T07:43:37.666621
2019-03-03T11:00:21
2019-03-03T11:00:21
173,561,698
0
0
null
null
null
null
UTF-8
Python
false
false
320
py
def IsPrime(num): if num % 2 == 0 and num > 2: return False if num % 3 == 0 and num > 3: return False if num % 4 == 0: return False else: return True # # put your code here # for i in range(1,20): if IsPrime(i + 1): print(i+1,end=" ") print()
[ "zielinska.magdalen@gmail.com" ]
zielinska.magdalen@gmail.com
a56d637b3b5b50849575e94c56f6cfec42b1dc51
eb3ac9092eeb0b9f738cd4317b46be49de7774c5
/test_mg-waypoint-test-2.py
f4e3155e336cc56e9cdd60f23f0f5ee3932848b2
[]
no_license
tiny-dancer/deepracer-fun
e8a32852d62239d819cda018755b8ac2c9b49429
bea81061d964e7120335c44d055559d9eb49dc8e
refs/heads/master
2020-07-16T20:58:36.963787
2020-02-23T21:20:23
2020-02-23T21:20:23
205,867,673
1
0
null
null
null
null
UTF-8
Python
false
false
7,766
py
import pytest import os from mg_waypoint_test_2 import reward_function def test_reward_function(): os.environ['LOCAL_TESTING'] = 'true' params = { 'all_wheels_on_track': 1, 'waypoints': [[6.309836387634277,2.717386484146118],[6.195788621902466,2.7166789770126343],[6.081685543060303,2.715367913246155],[5.967700958251953,2.7118070125579834],[5.85396146774292,2.704580545425415],[5.740401983261108,2.6932029724121094],[5.627721548080444,2.675312042236328],[5.5175135135650635,2.6464585065841675],[5.409301042556763,2.609961986541748],[5.301126956939697,2.574303984642029],[5.1921679973602295,2.541111946105957],[5.0821373462677,2.5100131034851074],[4.970782518386841,2.4851750135421753],[4.8580474853515625,2.4710450172424316],[4.744303464889526,2.4700599908828735],[4.630417108535767,2.481245994567871],[4.5177764892578125,2.499838948249817],[4.407072305679321,2.5253244638442993],[4.298267602920532,2.559592604637146],[4.190068483352661,2.5966734886169434],[4.080982565879822,2.629265546798706],[3.970926523208618,2.6589781045913696],[3.859932541847229,2.686348557472229],[3.7475284337997437,2.7046855688095093],[3.633828043937683,2.7119990587234497],[3.5197654962539673,2.7135950326919556],[3.4057350158691406,2.713532567024231],[3.4057350158691406,2.713532567024231],[3.291683554649353,2.7141895294189453],[3.1491129398345947,2.7152745723724365],[3.0065420866012573,2.71635901927948],[2.863971471786499,2.7174439430236816],[2.7214009761810303,2.7185285091400146],[2.607404947280884,2.7163679599761963],[2.493346095085144,2.7110939025878906],[2.3756535053253174,2.696616053581238],[2.26602041721344,2.6667665243148804],[2.1631579995155334,2.6214065551757812],[2.0682084560394287,2.5637874603271484],[1.9771165251731873,2.4951614141464233],[1.8911914825439453,2.420231580734253],[1.8114585280418396,2.3387160301208496],[1.7394945025444033,2.250212073326111],[1.677141010761261,2.1548174619674683],[1.6248934864997864,2.0534849166870117],[1.5823744535446167,1.9477075338363647],[1.5505254864692688,1.8382489681243896],[1.5311545133590698,1.7257940173149109],[1.5271174907684326,1.6120454668998718],[1.539400041103363,1.4987789988517761],[1.5642725229263303,1.387354493141175],[1.5989729762077332,1.278760015964508],[1.6428920030593872,1.1736074686050415],[1.6964020133018494,1.0729964077472687],[1.7604795098304749,0.9785585701465607],[1.8357470035552979,0.8929627537727356],[1.9221299886703491,0.8187586665153503],[2.0174149870872498,0.7561855316162109],[2.1191929578781132,0.704834684729576],[2.22581148147583,0.6641798615455627],[2.33598256111145,0.635000690817833],[2.448741912841797,0.6194588989019394],[2.562835931777954,0.6146939992904663],[2.676932454109192,0.614323690533638],[2.790879011154175,0.615065410733223],[2.904958486557007,0.6154943406581879],[3.0190669298171997,0.6158859431743622],[3.1330950260162354,0.6165954917669296],[3.247138500213623,0.6172222346067429],[3.3612254858016968,0.6176614463329315],[3.475271463394165,0.6182866990566254],[3.5893020629882812,0.6188997328281403],[3.703405976295471,0.6189960688352585],[3.8174840211868286,0.6192460358142853],[3.9314393997192383,0.6201631426811218],[4.045536994934082,0.6195012480020523],[4.159003019332886,0.6116561591625214],[4.269382476806641,0.5892668068408966],[4.3730175495147705,0.5481619536876678],[4.465728044509888,0.4880164936184883],[4.5481369495391855,0.4090211018919938],[4.621875524520874,0.3185627665370703],[4.6936728954315186,0.22756083868443966],[4.7715795040130615,0.14663729816675186],[4.859802007675172,0.0780811086297031],[4.959166049957275,0.025352105498313904],[5.0663206577301025,-0.015855446457862854],[5.176241874694823,-0.05405664443969701],[5.283515930175781,-0.09862619638442993],[5.383999586105347,-0.15561671182513237],[5.4742419719696045,-0.22708586091175675],[5.549779891967773,-0.31260108947753906],[5.605553150177002,-0.40983645617961884],[5.639118432998657,-0.5152479559183121],[5.650930881500244,-0.6257368326187143],[5.643277406692505,-0.7384651899337769],[5.621659517288208,-0.8504203259944916],[5.592641115188599,-0.9608891308307648],[5.561022996902466,-1.070693016052246],[5.530486106872559,-1.1807215213775635],[5.5035319328308105,-1.2914490103721619],[5.480241298675537,-1.4030935168266296],[5.462010145187378,-1.5157455205917358],[5.45079493522644,-1.6292679905891418],[5.448741912841797,-1.7466390132904053],[5.459894418716431,-1.863289475440979],[5.48825740814209,-1.9755980372428894],[5.5363075733184814,-2.078725516796112],[5.60352635383606,-2.1696360111236572],[5.686964511871338,-2.2464959621429443],[5.7828369140625,-2.307755947113037],[5.88683295249939,-2.3526118993759155],[5.996015548706055,-2.380347967147827],[6.108441114425659,-2.3914250135421753],[6.2222607135772705,-2.388285517692566],[6.335166931152344,-2.371910572052002],[6.445005655288696,-2.3454989194869995],[6.550752639770508,-2.307651996612549],[6.655766487121582,-2.2621095180511475],[6.759855031967163,-2.215474545955658],[6.861518144607542,-2.164350986480714],[6.959713220596313,-2.106059551239014],[7.055949926376343,-2.044655501842499],[7.1512110233306885,-1.9823670387268066],[7.245310068130493,-1.9179010391235352],[7.3375091552734375,-1.8504455089569092],[7.42688202857971,-1.7797914743423473],[7.513786554336548,-1.7061240077018738],[7.5983476638793945,-1.6292839646339417],[7.677422523498535,-1.5470519661903381],[7.750153303146361,-1.457656025886537],[7.814417362213134,-1.3615394830703753],[7.8690268993377686,-1.2585055232048035],[7.910868167877197,-1.1510785222053528],[7.936350584030151,-1.041047990322113],[7.943183898925781,-0.9302619397640228],[7.929688930511475,-0.8188509643077873],[7.898606061935424,-0.7099088430404646],[7.858716964721679,-0.6015907526016219],[7.818351984024048,-0.49343155324459076],[7.785273790359497,-0.38304539024829865],[7.766066551208496,-0.2702548950910568],[7.764912366867065,-0.1569973491132242],[7.782723426818848,-0.04621594771742936],[7.816987752914428,0.06044381856918132],[7.862348318099976,0.1640622103586793],[7.9113850593566895,0.2672598920762539],[7.964816093444824,0.36797454953193665],[8.023759365081787,0.4654194712638855],[8.083719730377197,0.5625471323728577],[8.140750885009766,0.661509245634079],[8.19270658493042,0.7627629637718201],[8.238867044448853,0.8667940497398376],[8.279578924179077,0.9738516509532945],[8.31326961517334,1.0863134860992432],[8.33589792251587,1.2011854648590088],[8.344946384429932,1.3162800073623657],[8.336476802825928,1.4300925135612488],[8.307107925415039,1.5377934575080872],[8.256765365600586,1.6361489892005905],[8.187145233154297,1.7235015034675598],[8.102343559265135,1.7990955710411083],[8.010600328445433,1.8678620457649242],[7.919651508331299,1.9377470016479492],[7.838100910186769,2.0161675214767443],[7.767462730407714,2.1045645475387587],[7.704502820968628,2.199170470237732],[7.6444172859191895,2.2959940433502197],[7.5782294273376465,2.3898375034332275],[7.501000642776489,2.4726409912109375],[7.413156032562256,2.543642044067383],[7.317309379577637,2.601830005645752],[7.213808059692383,2.6475000381469727],[7.105192422866821,2.680868983268738],[6.993459939956665,2.7023710012435913],[6.879996061325073,2.7138789892196655],[6.766035556793213,2.718880534172058],[6.651995420455933,2.720201015472412],[6.537929534912109,2.7195639610290527],[6.423866033554077,2.7183064222335815],[6.309836387634277,2.717386484146118]], 'closest_waypoints': [1, 2], 'heading': -174.2816699776837, 'is_left_of_center': 1, 'is_reversed': 0, 'progress': 5.661323987274458, 'speed': 2.6666666666666665, 'steering_angle': 9.999999999999998, 'steps': 17, 'track_width': 0.660273308091193, 'x': 6.174768391459522, 'y': 2.667314668352434 } assert reward_function(params) > 0
[ "grose.matthewf@gmail.com" ]
grose.matthewf@gmail.com
801d15a87798caa4cf2a52967cbd60c92b086f45
636b31e9bef7c82183f288d441f08d448af49f9c
/parlai/mturk/tasks/light/light_chat_eval/task_config.py
5f9e334abcba8a67746b5518ff0e9e64cf26b9d2
[ "MIT" ]
permissive
ShaojieJiang/tldr
a553051c6b615237212082bbc21b09e9069929af
c878ed10addbae27fa86cc0560f168b14b94cf42
refs/heads/master
2023-08-21T23:36:45.148685
2020-04-08T15:09:35
2020-04-08T15:09:35
247,427,860
12
0
MIT
2023-08-11T19:52:22
2020-03-15T08:25:21
Python
UTF-8
Python
false
false
1,381
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. task_config = {} task_config['frontend_version'] = 1 """A short and descriptive title about the kind of task the HIT contains. On the Amazon Mechanical Turk web site, the HIT title appears in search results, and everywhere the HIT is mentioned. """ task_config['hit_title'] = 'Play a character in a room of a text adventure game' """A description includes detailed information about the kind of task the HIT contains. On the Amazon Mechanical Turk web site, the HIT description appears in the expanded view of search results, and in the HIT and assignment screens. """ task_config['hit_description'] = ( 'Given a character and a personality, as well as a setting, communicate ' 'with your partner and complete game actions.' ) """One or more words or phrases that describe the HIT, separated by commas. On MTurk website, these words are used in searches to find HITs. """ task_config['hit_keywords'] = 'chat,text adventure,role playing,creative writing' """A detailed task description that will be shown on the HIT task preview page and on the left side of the chat page. Supports HTML formatting. """ task_config['task_description'] = '*overridden in custom.jsx*'
[ "s.jiang@uva.nl" ]
s.jiang@uva.nl
6da1ef318047a6a8dabbd5231cdc3bbccdb5658b
30fa4bb7b0cb9b72aab786af3ed7d2462a1e72bf
/v_env/lib/python3.7/enum.py
e275cd25667f3e78f3e1d8a3bba70e3438e155a9
[ "MIT" ]
permissive
buds-lab/psychrometric-chart-makeover
3be2f45455b050a6b0673d232b2e02707e34f28a
e7267f57584d8ba645507189ea4a8e474c67e0de
refs/heads/master
2022-12-11T16:21:08.114952
2019-07-24T14:28:12
2019-07-24T14:28:12
148,023,677
6
1
MIT
2021-06-01T23:47:24
2018-09-09T12:36:05
Python
UTF-8
Python
false
false
93
py
/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/enum.py
[ "p.jayathissa@gmail.com" ]
p.jayathissa@gmail.com
2b06a62180b5b84c2ac1e7b938b0c1fcf65e79a7
feface5c27a81ac1e79f14c890166a58a02caeeb
/flaskr/youtube2.py
ce64db78e0710d230a355e2954f46bf5e7043c1c
[]
no_license
acx2o/boc_music
bd3d39f784b505c362c047de8c051d493b1810da
d1c8818705925417ad720b3550a32255fc2fceee
refs/heads/master
2020-03-19T04:20:27.084298
2018-07-19T05:44:06
2018-07-19T05:44:06
135,817,900
0
0
null
null
null
null
UTF-8
Python
false
false
2,220
py
from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import os # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. DEVELOPER_KEY = os.environ['DEVELOPER_KEY'] # DEVELOPER_KEY = os.environ['DEVELOPER_KEY'] YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" def youtube_search(query): print('------------------') print(query) # print(type(query)) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. print("***********************") # print( youtube.search().list( # q=query,#検索キーワード # part="id,snippet", # maxResults=10 # )) search_response = youtube.search().list( q=query,#検索キーワード part="id,snippet", maxResults=10 ).execute() videos = [] # Add each result to the appropriate list, and then display the lists of # matching videos, channels, and playlists. print(search_response) for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": # videos.append("%s (%s)" % (search_result["snippet"]["title"],search_result["id"]["videoId"])) videos.append([search_result["snippet"]["title"],search_result["id"]["videoId"]]) print("***********************") print(search_result["snippet"]["title"]) # print("***********************") # print() # print("***********************") # print(videos[0][1]) return videos[0][1] # print("Videos:\n", "\n".join(videos), "\n") if __name__ == "__main__": argparser.add_argument("--q", help="Search term", default="Google") argparser.add_argument("--max-results", help="Max results", default=25) args = argparser.parse_args() try: youtube_search(args) except HttpError as e: print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
[ "acx2o.mm@gmail.com" ]
acx2o.mm@gmail.com
57cddf491e2bb50812cbc97ea8ec4dd626164350
32cd1029b15f481c763f597fc824736de4e0b1ac
/setup.py
a37e482f0259ac707687008d6380e83606af3553
[]
no_license
renero/dataset
7805825893247612a7a82f47c61fd27bdf24f325
a7771f10c72c2f1a9db0453d4224592e455c5a2a
refs/heads/master
2023-07-22T08:08:05.669928
2021-07-19T13:50:34
2021-07-19T13:50:34
174,870,468
7
8
null
2023-07-06T21:55:03
2019-03-10T19:26:52
Jupyter Notebook
UTF-8
Python
false
false
1,389
py
# -*- coding: utf-8 -*- # Copyright (C) 2021 Jesus Renero # Licence: MIT import codecs import os.path try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages with open('README.md', encoding="utf-8") as f: long_description = f.read() def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), 'r') as fp: return fp.read() def get_version(): for line in read("dataset/__init__.py").splitlines(): if line.startswith('__version__'): delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable to find version string.") def setup_package(): setup( name='dataset', version=get_version(), description='A library to start managing data in ML projects, \ for educational purposes.', packages=find_packages(), url='https://github.com/renero/dataset', license='MIT', author='J.Renero', install_requires=['matplotlib', 'numpy', 'pandas', 'scikit_learn', 'scipy', 'seaborn', 'sklearn_pandas', 'skrebate', 'statsmodels', 'nbsphinx'], author_email='jrenero@faculty.ie.edu' ) if __name__ == '__main__': setup_package()
[ "jesus.renero@gmail.com" ]
jesus.renero@gmail.com
3420d95ed0d3806058205bc6ef1f5ccf8d2eb0c4
7a5bf238df905ec2e0fdd63edf4132f87ce7421a
/Train/model/__init__.py
e3bb74a5f97580ee5505140fd7be1b65691befaf
[]
no_license
scott-mao/LPNet-PyTorch
f14aaea19f4446e623ecf3401c1612d5313e9f9a
1c38cc7213ea3eb50b62195274f726c4a8da545b
refs/heads/main
2023-03-27T08:54:18.030090
2021-03-31T06:29:40
2021-03-31T06:29:40
356,148,832
5
1
null
2021-04-09T05:37:36
2021-04-09T05:37:36
null
UTF-8
Python
false
false
6,398
py
import os from importlib import import_module import torch import torch.nn as nn from torch.autograd import Variable class Model(nn.Module): def __init__(self, args, ckp): super(Model, self).__init__() print('Making model...') self.scale = args.scale self.idx_scale = 0 self.self_ensemble = args.self_ensemble self.chop = args.chop self.precision = args.precision self.cpu = args.cpu self.device = torch.device('cpu' if args.cpu else 'cuda') self.n_GPUs = args.n_GPUs self.save_models = args.save_models module = import_module('model.' + args.model.lower()) self.model = module.make_model(args).to(self.device) if args.precision == 'half': self.model.half() if not args.cpu and args.n_GPUs > 1: self.model = nn.DataParallel(self.model, range(args.n_GPUs)) self.load( ckp.dir, pre_train=args.pre_train, resume=args.resume, cpu=args.cpu ) print(self.model, file=ckp.log_file) def forward(self, x, idx_scale): self.idx_scale = idx_scale target = self.get_model() if hasattr(target, 'set_scale'): target.set_scale(idx_scale) if self.self_ensemble and not self.training: if self.chop: forward_function = self.forward_chop else: forward_function = self.model.forward return self.forward_x8(x, forward_function) elif self.chop and not self.training: return self.forward_chop(x) else: return self.model(x) def get_model(self): if self.n_GPUs == 1: return self.model else: return self.model.module def state_dict(self, **kwargs): target = self.get_model() return target.state_dict(**kwargs) def save(self, apath, epoch, is_best=False): target = self.get_model() torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_latest.pt') ) if is_best: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_best.pt') ) if self.save_models: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_{}.pt'.format(epoch)) ) def load(self, apath, pre_train='.', resume=-1, cpu=False): if cpu: kwargs = {'map_location': lambda storage, loc: storage} else: kwargs = {} if resume == -1: self.get_model().load_state_dict( torch.load( os.path.join(apath, 'model', 'model_latest.pt'), **kwargs ), strict=False ) elif resume == 0: if pre_train != '.': print('Loading model from {}'.format(pre_train)) self.get_model().load_state_dict( torch.load(pre_train, **kwargs), strict=False ) else: self.get_model().load_state_dict( torch.load( os.path.join(apath, 'model', 'model_{}.pt'.format(resume)), **kwargs ), strict=False ) def forward_chop(self, x, shave=10, min_size=160000): scale = self.scale[self.idx_scale] n_GPUs = min(self.n_GPUs, 4) b, c, h, w = x.size() h_half, w_half = h // 2, w // 2 h_size, w_size = h_half + shave, w_half + shave lr_list = [ x[:, :, 0:h_size, 0:w_size], x[:, :, 0:h_size, (w - w_size):w], x[:, :, (h - h_size):h, 0:w_size], x[:, :, (h - h_size):h, (w - w_size):w]] if w_size * h_size < min_size: sr_list = [] for i in range(0, 4, n_GPUs): lr_batch = torch.cat(lr_list[i:(i + n_GPUs)], dim=0) #dfanet # sr_batch,_ = self.model(lr_batch) #ean #_, sr_batch = self.model(lr_batch) #original sr_batch = self.model(lr_batch) sr_list.extend(sr_batch[0].chunk(n_GPUs, dim=0)) else: sr_list = [ self.forward_chop(patch, shave=shave, min_size=min_size) \ for patch in lr_list ] h, w = scale * h, scale * w h_half, w_half = scale * h_half, scale * w_half h_size, w_size = scale * h_size, scale * w_size shave *= scale output = x.new(b, c, h, w) output[:, :, 0:h_half, 0:w_half] \ = sr_list[0][:, :, 0:h_half, 0:w_half] output[:, :, 0:h_half, w_half:w] \ = sr_list[1][:, :, 0:h_half, (w_size - w + w_half):w_size] output[:, :, h_half:h, 0:w_half] \ = sr_list[2][:, :, (h_size - h + h_half):h_size, 0:w_half] output[:, :, h_half:h, w_half:w] \ = sr_list[3][:, :, (h_size - h + h_half):h_size, (w_size - w + w_half):w_size] return output def forward_x8(self, x, forward_function): def _transform(v, op): if self.precision != 'single': v = v.float() v2np = v.data.cpu().numpy() if op == 'v': tfnp = v2np[:, :, :, ::-1].copy() elif op == 'h': tfnp = v2np[:, :, ::-1, :].copy() elif op == 't': tfnp = v2np.transpose((0, 1, 3, 2)).copy() ret = torch.Tensor(tfnp).to(self.device) if self.precision == 'half': ret = ret.half() return ret lr_list = [x] for tf in 'v', 'h', 't': lr_list.extend([_transform(t, tf) for t in lr_list]) sr_list = [forward_function(aug) for aug in lr_list] for i in range(len(sr_list)): if i > 3: sr_list[i] = _transform(sr_list[i], 't') if i % 4 > 1: sr_list[i] = _transform(sr_list[i], 'h') if (i % 4) % 2 == 1: sr_list[i] = _transform(sr_list[i], 'v') output_cat = torch.cat(sr_list, dim=0) output = output_cat.mean(dim=0, keepdim=True) return output
[ "cvjunchengli@gmail.com" ]
cvjunchengli@gmail.com
2cabb97340331fa3487eb8d75167daf5abeae380
97a818fd366221c92a2ade0445135740cfee4fa8
/app/controllers/system_configuration_controller.py
1a9f00c6423655fb1be39cdeec42055cbe8b448e
[]
no_license
f228476653/parking_server_code_v2
e55cbeeb1f7dd2640b547a27bf0680c1f5bd2b5c
00eb1a81d120bd2978d97a02c77af01148142454
refs/heads/main
2023-02-10T16:19:35.137510
2020-12-31T00:33:15
2020-12-31T00:33:15
325,676,426
0
0
null
null
null
null
UTF-8
Python
false
false
2,229
py
import json from app.controllers.controller import Controller from app.decorators.authorize import authorize from app.controllers.api_response import ApiResponse from app.services.system_configuration import SystemConfigurationService class SystemConfigurationController(Controller): async def create_system_configuration(self, request): system_configuration = SystemConfigurationService(request.app['pmsdb'], request['login']) post_data = await request.json() result = await system_configuration.create_system_configuration(post_data) api_response = ApiResponse(result) return self.json_response(api_response.asdict()) async def get_all_system_configuration(self, request): system_configuration = SystemConfigurationService(request.app['pmsdb'], request['login']) result = await system_configuration.get_all_system_configuration() api_response = ApiResponse(result) return self.json_response(api_response.asdict()) async def get_system_configuration_by_key(self, request): system_configuration = SystemConfigurationService(request.app['pmsdb'], request['login']) key = request.match_info['key'] result = await system_configuration.get_system_configuration_by_key(key) api_response = ApiResponse(result) return self.json_response(api_response.asdict()) async def update_system_configuration_by_key(self, request): system_configuration = SystemConfigurationService(request.app['pmsdb'], request['login']) post_data = await request.json() result = await system_configuration.update_system_configuration_by_key(post_data) api_response = ApiResponse(result) return self.json_response(api_response.asdict()) async def delete_system_configuration_by_key(self, request): system_configuration = SystemConfigurationService(request.app['pmsdb'], request['login']) post_data = await request.json() result = await system_configuration.delete_system_configuration_by_key(post_data['key']) api_response = ApiResponse(result) return self.json_response(api_response.asdict())
[ "huilong@gmail.com" ]
huilong@gmail.com
18506f3fbc27c4b41b2452c10e701ae411a989f3
6cf39b2089734e049e7c8ea5bc676077a10a436b
/countries/migrations/0006_auto_20200816_0022.py
e75f3ffcf31cd537cf921108c0bcc19bb9a3fa8f
[]
no_license
Azmah-Bad/where2go-backend
3869d148f12b2a45265e33c923602f7ca6b9b605
f56e131d934875b2d116088ce928e48d314fa152
refs/heads/master
2022-12-27T15:19:03.135731
2020-10-14T10:56:15
2020-10-14T10:56:15
288,805,248
0
1
null
2020-10-01T12:49:02
2020-08-19T18:19:00
Python
UTF-8
Python
false
false
410
py
# Generated by Django 3.1 on 2020-08-16 00:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('countries', '0005_auto_20200816_0021'), ] operations = [ migrations.AlterField( model_name='country', name='info', field=models.CharField(blank=True, default='', max_length=160), ), ]
[ "56384031+Azmah-Bad@users.noreply.github.com" ]
56384031+Azmah-Bad@users.noreply.github.com
aceca9bba4cb87a2ea51e8dab7fe35a25df64288
c7da4e737a6a8c276581907ef4dd5c926929a01a
/Module6/assignment2.py
d86de7d3b1575d667063a6630c6753dfd3eb61c9
[ "MIT" ]
permissive
galinams/Programming-with-Python-for-Data-Science
e31f7d14d5be4fe5b37e4d643c890aa8d1e66489
9f37a6698b58becbfccc8ef44df73104c3f8e858
refs/heads/master
2021-01-22T06:11:11.330226
2017-11-23T23:06:33
2017-11-23T23:06:33
81,742,084
0
0
null
null
null
null
UTF-8
Python
false
false
6,564
py
import pandas as pd # The Dataset comes from: # https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits # At face value, this looks like an easy lab; # But it has many parts to it, so prepare yourself before starting... def load(path_test, path_train): # Load up the data. # You probably could have written this.. with open(path_test, 'r') as f: testing = pd.read_csv(f) with open(path_train, 'r') as f: training = pd.read_csv(f) # The number of samples between training and testing can vary # But the number of features better remain the same! n_features = testing.shape[1] X_test = testing.ix[:,:n_features-1] X_train = training.ix[:,:n_features-1] y_test = testing.ix[:,n_features-1:].values.ravel() y_train = training.ix[:,n_features-1:].values.ravel() # # Special: X_train = X_train[:int(len(X_train)*0.04)] y_train = y_train[:int(len(y_train)*0.04)] return X_train, X_test, y_train, y_test print X_train.shape print y_train.shape def peekData(X_train): # The 'targets' or labels are stored in y. The 'samples' or data is stored in X print "Peeking your data..." fig = plt.figure() cnt = 0 for col in range(5): for row in range(10): plt.subplot(5, 10, cnt + 1) plt.imshow(X_train.ix[cnt,:].reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest') plt.axis('off') cnt += 1 fig.set_tight_layout(True) plt.show() def drawPredictions(X_train, X_test, y_train, y_test): fig = plt.figure() # Make some guesses y_guess = model.predict(X_test) # # INFO: This is the second lab we're demonstrating how to # do multi-plots using matplot lab. In the next assignment(s), # it'll be your responsibility to use this and assignment #1 # as tutorials to add in the plotting code yourself! num_rows = 10 num_cols = 5 index = 0 for col in range(num_cols): for row in range(num_rows): plt.subplot(num_cols, num_rows, index + 1) # 8x8 is the size of the image, 64 pixels plt.imshow(X_test.ix[index,:].reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest') # Green = Guessed right # Red = Fail! fontcolor = 'g' if y_test[index] == y_guess[index] else 'r' plt.title('Label: %i' % y_guess[index], fontsize=6, color=fontcolor) plt.axis('off') index += 1 fig.set_tight_layout(True) plt.show() # # TODO: Pass in the file paths to the .tes and the .tra files X_train, X_test, y_train, y_test = load('C:\DAT207x\Programming with Python for Data Science\Module6\Datasets\optdigits.tes', 'C:\DAT207x\Programming with Python for Data Science\Module6\Datasets\optdigits.tra') import matplotlib.pyplot as plt from sklearn import svm # # Get to know your data. It seems its already well organized in # [n_samples, n_features] form. Our dataset looks like (4389, 784). # Also your labels are already shaped as [n_samples]. peekData(X_train) # # TODO: Create an SVC classifier. Leave C=1, but set gamma to 0.001 # and set the kernel to linear. Then train the model on the training # data / labels: print "Training SVC Classifier..." # # .. your code here .. from sklearn.svm import SVC model = SVC(C=1.0, kernel='linear',gamma=0.001) model.fit(X_train,y_train) # TODO: Calculate the score of your SVC against the testing data print "Scoring SVC Classifier..." # # .. your code here .. score = model.score(X_test,y_test) print "Score:\n", score # Visual Confirmation of accuracy drawPredictions(X_train, X_test, y_train, y_test) # # TODO: Print out the TRUE value of the 1000th digit in the test set # By TRUE value, we mean, the actual provided label for that sample # # .. your code here .. true_1000th_test_value = y_test[1000] print "1000th test label: ", true_1000th_test_value # # TODO: Predict the value of the 1000th digit in the test set. # Was your model's prediction correct? # INFO: If you get a warning on your predict line, look at the # notes from the previous module's labs. # # .. your code here .. guess_1000th_test_value = model.predict(X_test)[1000] print "1000th test prediction: ", guess_1000th_test_value # # TODO: Use IMSHOW to display the 1000th test image, so you can # visually check if it was a hard image, or an easy image # # .. your code here .. plt.imshow(X_test.ix[1000,:].reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest') # # TODO: Were you able to beat the USPS advertised accuracy score # of 98%? If so, STOP and answer the lab questions. But if you # weren't able to get that high of an accuracy score, go back # and change your SVC's kernel to 'poly' and re-run your lab # again. # # TODO: Were you able to beat the USPS advertised accuracy score # of 98%? If so, STOP and answer the lab questions. But if you # weren't able to get that high of an accuracy score, go back # and change your SVC's kernel to 'rbf' and re-run your lab # again. # # TODO: Were you able to beat the USPS advertised accuracy score # of 98%? If so, STOP and answer the lab questions. But if you # weren't able to get that high of an accuracy score, go back # and tinker with your gamma value and C value until you're able # to beat the USPS. Don't stop tinkering until you do. =). ################################################# # # TODO: Once you're able to beat the +98% accuracy score of the # USPS, go back into the load() method. Look for the line that # reads "# Special:" # # Immediately under that line, alter X_train and y_train ONLY. # Keep just the ___FIRST___ 4% of the samples. In other words, # for every 100 samples found, throw away 96 of them. Make sure # all the samples (and labels) you keep come from the start of # X_train and y_train. # If the first 4% is a decimal number, then use int + ceil to # round up to the nearest whole integer. # That operation might require some Pandas indexing skills, or # perhaps some numpy indexing skills if you'd like to go that # route. Feel free to ask on the class forum if you want; but # try to exercise your own muscles first, for at least 30 # minutes, by reviewing the Pandas documentation and stack # overflow. Through that, in the process, you'll pick up a lot. # Part of being a machine learning practitioner is know what # questions to ask and where to ask them, so this is a great # time to start! # Re-Run your application after throwing away 96% your training # data. What accuracy score do you get now? # # TODO: Lastly, change your kernel back to linear and run your # assignment one last time. What's the accuracy score this time? # Surprised?
[ "korolvlondone@gmail" ]
korolvlondone@gmail
a9eb87d1a7b947e187a134b36a9714680f316838
d3f6083ae5c2d5d3233339f57e53ea0ecaae9e9f
/src/database/exceptions/user_recovery_token_not_found_error.py
9698108a76e020077b8bc222344082bf8c33157a
[]
no_license
crpistillo/taller2-auth-server
c7db4177f22a652a9e696212aac48df8a945e9d1
86cd3b9a753a0da68dc10adbedc1a96860a31fa2
refs/heads/master
2022-11-18T18:29:19.177046
2020-07-25T03:10:29
2020-07-25T03:10:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
56
py
class UserRecoveryTokenNotFoundError(KeyError): pass
[ "cpistillo@fi.uba.ar" ]
cpistillo@fi.uba.ar
b47b24dc2788e39f4046e9ec28ca28fc5c85b985
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/ds_write_1/snapshot_delete.py
339319e6eb10dc8e4205981138e524afa8f8c359
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
1,055
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_one_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/delete-snapshot.html if __name__ == '__main__': """ create-snapshot : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/create-snapshot.html describe-snapshots : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/describe-snapshots.html """ parameter_display_string = """ # snapshot-id : The identifier of the directory snapshot to be deleted. """ add_option_dict = {} ####################################################################### # parameter display string add_option_dict["parameter_display_string"] = parameter_display_string # ex: add_option_dict["no_value_parameter_list"] = "--single-parameter" write_one_parameter("ds", "delete-snapshot", "snapshot-id", add_option_dict)
[ "hcseo77@gmail.com" ]
hcseo77@gmail.com