blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
0d190ebd0cd022263649c4dc8a283a4e8c923602
Python
SamScott/rootbot
/main/main.py
UTF-8
2,792
2.640625
3
[]
no_license
# ROOT_BOT 1.6.1 # (C) 2014 root_user, Svetlana A. Tkachenko # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Thanks to Svetlana for cleaning up the code. import socket import sys import random import time import re import string server = "irc.esper.net" channel = "#test1234" botnick = "root_bot" irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print "connecting to:"+server # Connect irc.connect((server, 6667)) # Register - send NICK and USER irc.send("NICK "+ botnick +"\n") print('Sent NICK') irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :I am a bot! \n") print('Sent USER') # Loop while 1: time.sleep(1); # Receive text=irc.recv(2040) # Print to console if something is received if(text): print text # Pong if text.find('PING') != -1: irc.send('PONG ' + text.split() [1] + '\r\n') print('Ponged to the server') # Join channels on 001 numeric if text.find('001') != -1: irc.send("JOIN "+ channel +"\n") #join the chan print("Sent JOIN\r\n") ##COMMANDS # Say Something if text.find(':!say') !=-1: t = text.split(':!say') to = t[1].strip() irc.send('PRIVMSG '+channel+' :' + str(to) +'\r\n') # Roll dice if text.find(':!dice') !=-1: rand=random.randrange(1,12) rand=str(rand) #convert to string, python doesn't like it when strings/numbers are mixed. irc.send('PRIVMSG '+channel+' :I rolled a ' + rand + '!\r\n') # Snarky remarks if text.find('asshole') !=-1: irc.send('PRIVMSG '+channel+" :You're an asshole.\r\n") if text.find(':!help') !=-1: irc.send('PRIVMSG '+channel+' :Find my full commandlist at http://github.com/samscott/rootbot/\r\n') #ROT13 if text.find(':!rot13') !=-1: t = text.split(':!rot13') inp = t[1].strip() rot13 = string.maketrans( "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm") out = string.translate(inp, rot13) irc.send('PRIVMSG '+channel+' :' + out +'\r\n')
true
3736ef08b6e27e3b44b3c19a55a75a79d05e36bd
Python
mjpatter88/ProjEuler
/Problem082/test_solver.py
UTF-8
1,110
2.609375
3
[]
no_license
from solver import min_path_sum, min_path_total mat = [ [131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 37, 331] ] mat2 = [ [131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [1, 1, 1, 1, 2] ] mat3 = [ [131, 673, 234, 1, 18], [201, 96, 342, 1, 150], [630, 803, 746, 1, 111], [537, 699, 497, 1, 956], [1, 1, 1, 1, 100] ] def test_min_path_sum__end(): assert min_path_sum(mat, 4, 4, None) == 331 def test_min_path_sum__end_2(): assert min_path_sum(mat, 2, 4, None) == 111 def test_min_path_sum__top(): assert min_path_sum(mat, 0, 3, None) == 103 + 18 def test_min_path_sum__full(): assert min_path_sum(mat, 1, 0, None) == 201 + 96 + 342 + 234 + 103 + 18 def test_min_path_total__full(): assert min_path_total(mat) == 201 + 96 + 342 + 234 + 103 + 18 def test_min_path_total__bottom(): assert min_path_total(mat2) == 6 def test_min_path_total__l(): assert min_path_total(mat3) == 8 + 18
true
89d65df25aab0e418b19da2cae5ae0018481b6c1
Python
ViacheslavP/FS_scattering
/novelfss/atomic_states.py
UTF-8
2,210
2.921875
3
[]
no_license
import numpy as np # methods and procedures for creating various chains class atomic_state(object): def __init__(self, pos, campl): self.noa = pos.shape[1] self._mpos = np.asarray(pos, dtype=np.float64) self.dim = self.noa + 2 * self.noa * (self.noa - 1) #not shuffled; run atomic_state.shuffle() for shuffling self.pos = self._mpos if not np.vdot(campl, campl) == 0: self.campl = campl / np.vdot(campl, campl) else: self.campl = campl if pos.shape[0] != 3: raise TypeError("Something wrong with the atomic state") def __add__(self, other): return self.merge_atomic_states(other, distance=0) def shuffle(self): self.pos = self._mpos from .dyson_solvers import sxy, sz self.pos[0] += np.random.normal(0.0, sxy, self.noa) self.pos[1] += np.random.normal(0.0, sxy, self.noa) self.pos[2] += np.random.normal(0.0, sz, self.noa) def illuminate(self, V): amps = V(*self.pos) dim = self.noa + 2 * self.noa * (self.noa - 1) self.campl = np.zeros(dim, dtype=np.complex) for i in range(self.noa): self.campl[i] = amps[i] def merge_atomic_states(self, bstate: object, distance=0) -> object: n1, n2 = self.noa, bstate.noa add_dist = 0 zpos = np.concatenate((self._mpos, bstate._mpos + distance + add_dist), axis=None) campl = np.concatenate((self.campl, np.exp(2j * (distance + add_dist) * np.pi) * bstate.campl), axis=None) return atomic_state(zpos, campl) # Create an atomic cloud around center def new_cloud(noa:int): xpos = np.zeros(noa) ypos = np.zeros(noa) zpos = np.zeros(noa) poss = np.stack((xpos, ypos, zpos), axis=0) campl = np.ones_like(zpos, dtype=np.complex) return atomic_state(poss, campl) # Create a simple chain of noa atoms with period d def new_chain(noa: int, d, random=False): xpos = np.zeros(noa) ypos = np.zeros(noa) zpos = d * (np.arange(noa) - (noa-1)/2.) poss = np.stack((xpos, ypos, zpos), axis=0) campl = np.ones_like(zpos, dtype=np.complex) return atomic_state(poss, campl)
true
990312554a1eddc06d477d4c58dc9b30dceb838d
Python
erickfmm/ML-experiments
/load_data/loader/basic/_glass.py
UTF-8
1,815
2.546875
3
[ "MIT" ]
permissive
from load_data.ILoadSupervised import ILoadSupervised, SupervisedType import csv from os.path import join __all__ = ["LoadGlass"] class LoadGlass(ILoadSupervised): def __init__(self, folder_path="train_data/Folder_Basic/glass/"): self.TYPE = SupervisedType.Classification self.folder_path = folder_path self.headers = ["RI: refractive index", "Na: Sodium", "Mg: Magnesium", "Al: Aluminum", "Si: Silicon", "K: Potassium", "Ca: Calcium", "Ba: Barium", "Fe: Iron"] self.classes = [None, "building_windows_float_processed", "building_windows_non_float_processed", "vehicle_windows_float_processed", "vehicle_windows_non_float_processed (none in this database)", "containers", "tableware", "headlamps"] def get_default(self): return self.get_all() @staticmethod def get_splited(): return None def get_classes(self): return self.classes def get_headers(self): return self.headers def get_all(self): xs = [] ys = [] for x, y in self.get_all_yielded(): xs.append(x) ys.append(y) return xs, ys def get_all_yielded(self): i = 0 with open(join(self.folder_path, 'glass.data')) as data_glass_file: data_glass_csv = csv.reader(data_glass_file) for el in data_glass_csv: i_field = 0 x = [] for field in el: if 0 < i_field < len(el)-2: x.append(float(field)) elif i_field > len(el) - 2: y = int(field) i_field += 1 yield x, y i += 1
true
9c939af83008e3366669c397a2d00db4d9f55620
Python
subhadarship/textdistance
/tests/compression_based.py
UTF-8
5,267
2.828125
3
[ "Python-2.0", "MIT" ]
permissive
# built-in from fractions import Fraction # project from __main__ import textdistance, unittest class CommonNCDTest(unittest.TestCase): def test_monotonicity(self): algos = ( textdistance.arith_ncd, # textdistance.bwtrle_ncd, textdistance.bz2_ncd, # textdistance.lzma_ncd, # textdistance.rle_ncd, # textdistance.zlib_ncd, textdistance.sqrt_ncd, textdistance.entropy_ncd, ) for alg in algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): same = alg('test', 'test') similar = alg('test', 'text') diffirent = alg('test', 'nani') self.assertLess(same, similar) self.assertLess(similar, diffirent) def test_monotonicity2(self): algos = ( textdistance.arith_ncd, textdistance.bwtrle_ncd, textdistance.bz2_ncd, textdistance.lzma_ncd, textdistance.rle_ncd, textdistance.zlib_ncd, textdistance.sqrt_ncd, textdistance.entropy_ncd, ) for alg in algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): same = alg('test', 'test') similar = alg('test', 'text') diffirent = alg('test', 'nani') self.assertLessEqual(same, similar) self.assertLessEqual(similar, diffirent) def test_symmetry(self): algos = ( # textdistance.arith_ncd, # textdistance.bwtrle_ncd, textdistance.bz2_ncd, textdistance.lzma_ncd, textdistance.rle_ncd, textdistance.zlib_ncd, textdistance.sqrt_ncd, textdistance.entropy_ncd, ) for alg in algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertEqual(alg('aab', 'aab'), alg('abb', 'abb')) self.assertEqual(alg('aab', 'abb'), alg('abb', 'aab')) self.assertEqual(alg('a', 'b'), alg('b', 'a')) self.assertEqual(alg('ab', 'ba'), alg('ba', 'ab')) class ArithNCDTest(unittest.TestCase): alg = textdistance.ArithNCD(terminator='\x00') def test_make_probs(self): probs = self.alg._make_probs('lol', 'lal') self.assertEqual(probs['l'], (Fraction(0, 1), Fraction(4, 7))) self.assertEqual(probs['o'][1], Fraction(1, 7)) self.assertEqual(probs['a'][1], Fraction(1, 7)) def test_arith_output(self): fraction = self.alg._compress('BANANA') self.assertEqual(fraction.numerator, 1525) def test_arith_distance(self): same = self.alg('test', 'test') similar = self.alg('test', 'text') diffirent = self.alg('test', 'nani') self.assertLess(same, similar) self.assertLess(similar, diffirent) class NormalCompressorsNCDTest(unittest.TestCase): algos = ( textdistance.sqrt_ncd, textdistance.entropy_ncd, ) def test_simmetry_compressor(self): for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertEqual(alg._compress('ab'), alg._compress('ba')) def test_idempotency_compressor(self): # I've modified idempotency to some kind of distributivity for constant. # Now it indicates that compressor really compress. for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertLess(alg._get_size('aa'), alg._get_size('a') * 2) def test_monotonicity_compressor(self): for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertLess(alg._get_size('ab'), alg._get_size('abc')) def test_distributivity_compressor(self): for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertLess( alg._get_size('ab') + alg._get_size('c'), alg._get_size('ac') + alg._get_size('bc'), ) def test_distance(self): for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): same = alg('test', 'test') similar = alg('test', 'text') diffirent = alg('test', 'nani') self.assertLess(same, similar) self.assertLess(similar, diffirent) def test_simmetry_distance(self): for alg in self.algos: with self.subTest(algorithm=alg.__class__.__name__, func=alg): self.assertEqual(alg('aab', 'aab'), alg('abb', 'abb')) self.assertEqual(alg('aab', 'abb'), alg('abb', 'aab')) self.assertEqual(alg('a', 'b'), alg('b', 'a')) self.assertEqual(alg('ab', 'ba'), alg('ba', 'ab')) class EntropyNCD(unittest.TestCase): alg = textdistance.entropy_ncd def test_normalization(self): self.assertEqual(self.alg('test', 'test'), 0) self.assertEqual(self.alg('aaa', 'bbb'), 1)
true
9125b86200cfe6d9af0bf1949a12f64fcf29bc59
Python
malingreats/scoringapp-serve-model-service
/scoring_service/app.py
UTF-8
1,292
2.890625
3
[]
no_license
""" This module defines the scoring service in the following steps: - loads the ML model into memory; - defines the ML scoring REST API endpoints; and, - starts the service. """ from typing import Dict import pickle import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder import requests import numpy as np from flask import Flask, jsonify, make_response, request, Response from joblib import load from sklearn.base import BaseEstimator from .application_score import compute_prediction MODEL_PATH = 'XGBoost.sav' app = Flask(__name__) @app.route('/api/v1/app_scoring/score', methods=['POST']) def score() -> Response: """Application scoring API endpoint""" request_data = request.json request_data = request.get_json() value1 = request_data.get('Final branch') value2 = request_data.get('principal_amount') if value1 is not None and value2 is not None: model_output = compute_prediction(request_data) response_data = jsonify({**model_output, 'model_info': str(model)}) return make_response(response_data) # if __name__ == '__main__': # model = pickle.load(open(MODEL_PATH, 'rb')) # print(f'loaded model={model}') # print(f'starting API server') # app.run(host='0.0.0.0')
true
834088d59d32f8712fe303835f9071658e808050
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_206/1190.py
UTF-8
464
3.359375
3
[]
no_license
f = open("A-large.in"); f.readline() # Remove total tc cnt.. tc_cnt = 1; while True: line = f.readline() if not line: break token = line.split(" ") D = int(token[0]) N = int(token[1]) speed_arr = [] for x in range(N): line = f.readline() token = line.split(" ") speed_arr.append((D - int(token[0])) / int(token[1])) print("Case #"+str(tc_cnt)+": " + str(D/max(speed_arr))) tc_cnt+=1 f.close()
true
2ba7b41952c7e4667b958246f678fec9d0132975
Python
HCelante/Minim-Finite-Automata
/teste.py
UTF-8
296
2.65625
3
[]
no_license
import sys def CarregaAFD(): with open((sys.argv[1]), "r") as ponteiro: automato = [line.strip().split(" ") for line in ponteiro] return automato def main(): # automato = [] automato = CarregaAFD() for line in automato: print(line) if __name__ == "__main__": main()
true
782574da88b80acc37d54ee2d1adc22129aa834f
Python
dolobanko/python-scripts
/port_scan.py
UTF-8
789
3.015625
3
[]
no_license
#!/usr/bin/env python import socket import subprocess import sys from datetime import datetime subprocess.call ('clear', shell=True) host = raw_input ("Enter IP of scanning hosts: ") print "-"*60 print "Scanning remote host", host print "-"*60 tl=datetime.now() try: for port in range(1,1025): sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) result=sock.connect_ex((host,port)) if result == 0: print "Port {}:\t Open".format(port) sock.close() except KeyboardInterrupt: print "You pressed Ctrl+C" sys.exit() except socket.error: print "Couldn't connect to server" sys.exit() t2=datatume.now() total=t1-t2 print 'Scanning complited in: ', total
true
8be770d8ebb0ffdfb6cc66b58fb6f10f23e44ea0
Python
Teinaki/dev-practicals
/03-practical/practical-03/q1.py
UTF-8
1,353
4.21875
4
[]
no_license
# Below are three pairs of strings. Before you run the code, try to # predict what will happen in each case. Then run the code. Did the # results match your expectations? Can you explain the results? st1 = 'Spam, spam, spam' st2 = st1 print('st1 == st2: ' , st1 == st2) #Predict True print('st1 is st2: ', st1 is st2) #Predict True ### st3 = 'a' st4 = 'a' print('st3 == st4:', st3 == st4) #Predict True print('st3 is st4: ', st3 is st4) #Predict False ### Triple quotes give us multi-line strings. st5 = """Though yet of Hamlet our dear brother's death The memory be green, and that it us befitted To bear our hearts in grief and our whole kingdom To be contracted in one brow of woe, Yet so far hath discretion fought with nature That we with wisest sorrow think on him, Together with remembrance of ourselves. """ st6 = """Though yet of Hamlet our dear brother's death The memory be green, and that it us befitted To bear our hearts in grief and our whole kingdom To be contracted in one brow of woe, Yet so far hath discretion fought with nature That we with wisest sorrow think on him, Together with remembrance of ourselves. """ print('st5 == st6: ',st5 == st6) #Predict True print('st5 is st6: ',st5 is st6) #Predict False #Strings are immutable therefore true on is, interpreter already created an instance of the string so it's false
true
3b37fe9cab677b09d15d37769c48a780bf14e798
Python
quigsml/PythonTrainingFiles
/Part2_ObjOrienProg/Chapter14_MoreObjectOrientatedProgramming/Chapter14_Challenges.py
UTF-8
390
3.984375
4
[]
no_license
#Chapter 14 Challenges: #1, 2 class Square(): square_list = [] def __init__(self, l): self.len = l self.square_list.append((self.len)) def __repr__(self): return "{} by {} by {} by {}".format(self.len, self.len, self.len, self.len) sq1 = Square(5) sq2 = Square(6) print(Square.square_list) #3 def compare(a, b): return a is b
true
dec4e2ea4112e3dd83d95a8a42db9db64640f03e
Python
jpatsenker/network-routing-learner
/core/user.py
UTF-8
296
2.9375
3
[]
no_license
class User: def __init__(self,uid,comm,pos,friends): self.uid=uid self.comm=comm self.pos=pos self.friends=friends self.deg1=len(friends) self.deg2=None def __repr__(self): return str(self) def __str__(self): return str(self.uid) + ": " + str(self.friends)
true
21a3c0a7867dc0af60c051be66c991717100e0b3
Python
Leehoryeong/proto
/class2/day4/q.py
UTF-8
680
3.671875
4
[]
no_license
data = [10,70,90,50,40] data1 = [(40,50),(70,30),(20,60)] #(๊ตญ์–ด, ์˜์–ด) data2 = [{'kor':40,'eng':50},{'kor':70,'eng':30},{'kor':20,'eng':60}] def vfn(n): return n def tkfn(n): return n[0] def tefn(n): return n[1] def dkfn(n): return n['kor'] def mymax(dt,key): mx = None for n in dt: if mx == None or key(n) > key(mx): #open - closed ํ•จ์ˆ˜ mx = n return mx # open - closed๊ธฐ๋ฒ•์œผ๋กœ ์ž‘์„ฑ๋œ ํ•จ์ˆ˜๋กœ ๋ณ€๋™๋˜๋Š” ๋ถ€๋ถ„์€ ๋ณ„๋„์˜ ํ•จ์ˆ˜๋กœ ์ž‘์„ฑํ•ด์ค€๋‹ค. m = mymax(data2, dkfn) print(m,m['kor']) # m = mymax(data1, tkfn) # print(m,m[1]) # m = mymax(data1, tkfn) # print(m,m[0]) # m = mymax(data, vfn) # print(m)
true
77ceddcb97389d8553cfbd99b174be591abb4852
Python
gunnsa/TgrafProject2
/box.py
UTF-8
769
2.671875
3
[]
no_license
from dataclasses import dataclass import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from data import Vector from data import Point @dataclass class Box: begin_position: Point end_position: Point # motion: Vector # size: Vector color: tuple # scale: Vector def draw(self): glPushMatrix() glBegin(GL_TRIANGLE_FAN) glColor3f(*self.color) glVertex2f(self.begin_position.x, self.begin_position.y) # (x1, y1) glVertex2f(self.end_position.x, self.begin_position.y) # (x2, y1) glVertex2f(self.end_position.x, self.end_position.y) # (x2, y2) glVertex2f(self.begin_position.x, self.end_position.y) # (x1, y2) glEnd() glPopMatrix()
true
7204b9498e8255100b5c8af08a9b745e2f303a83
Python
msjithin/LeetCode_exercises
/LeetCode_exercises/LeetCode_exercises.py
UTF-8
163
2.734375
3
[]
no_license
import ex0123_buyAndSellStocks as ex123 prices = [3,3,5,0,0,3,1,4] #prices = [1,2,3,4,5] #prices = [7,6,4,3,1] print( ex123.Solution().maxProfit(prices) )
true
c69839bb2de039cbb75d72076f753ab44105cefb
Python
shobhit-nigam/qti_panda
/day4/functions/11.py
UTF-8
127
3.203125
3
[]
no_license
import matplotlib.pyplot as plt listx = [1, 2, 3, 4] listy = [11, 13, 17, 14] plt.plot(listx, listy, color='red') plt.show()
true
8b73138985b6623ac704c0c8847797b4d1dac069
Python
JaydeepUniverse/python
/class/40-class.py
UTF-8
442
3.421875
3
[]
no_license
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "Happy birthday dear Jaydeep", "Happy birthday to you"]) aashiqui2 = Song(["Tum hi ho", "Chahu mein ya na", "Milne he mujhse aayi"]) happy_bday.sing_me_a_song() aashiqui2.sing_me_a_song()
true
e629748732a34fb351711ec9e9766c497bc1633d
Python
wsgan001/PyFPattern
/Data Set/bug-fixing-5/f70146e922873ddb4b8c2b70fe6f2ff81a8fb35d-<__init__>-fix.py
UTF-8
319
2.9375
3
[]
no_license
def __init__(self, name='weight', n_power_iterations=1, eps=1e-12): self.name = name if (n_power_iterations <= 0): raise ValueError('Expected n_power_iterations to be positive, but got n_power_iterations={}'.format(n_power_iterations)) self.n_power_iterations = n_power_iterations self.eps = eps
true
292fecec5f3277e322357504a6c8b7e05a6650cc
Python
tash1629/Game-of-Bingo
/gameBingo.py
UTF-8
3,732
3.765625
4
[]
no_license
# File: gameBingo.py # the game of bingo # 4x4 bingo board # by: Rushnan Alam from graphics import * from random import * def main(): row1, row2, row3, row4 = printIntro() windows = drawBoard(row1, row2, row3, row4) count_ = playGame(windows, row1, row2, row3, row4) printSummary(count_) def printIntro(): print("This is a game of Bingo!") print("In this game, a bingo is reached\nonly when all numbers in a horizontal row are crossed off.") print("The game coordinator will call numbers until a bingo is reached.") print("If a number called is on the board, click on it.") r1 = [randrange(1, 144), randrange(1, 144), randrange(1, 144), randrange(1, 144)] r2 = [randrange(1, 144), randrange(1, 144), randrange(1, 144), randrange(1, 144)] r3 = [randrange(1, 144), randrange(1, 144), randrange(1, 144), randrange(1, 144)] r4 = [randrange(1, 144), randrange(1, 144), randrange(1, 144), randrange(1, 144)] return r1, r2, r3, r4 def drawBoard(row1, row2, row3, row4): win = GraphWin("Bingo Board", 325, 325) s1 = Rectangle(Point(20, 90), Point(90, 20)) for i in range(4): x = s1.clone() x.move(70*(i), 0) x.draw(win) for i in range(4): x = s1.clone() x.move(70*(i), 70) x.draw(win) for i in range(4): x = s1.clone() x.move(70*(i), 140) x.draw(win) for i in range(4): x = s1.clone() x.move(70*(i), 210) x.draw(win) x = 55 for i in range(4): x2 = 67*i Text(Point(x + x2, 55), row1[i]).draw(win) for i in range(4): x2 = 67*i Text(Point(x + x2, 122), row2[i]).draw(win) for i in range(4): x2 = 67*i Text(Point(x + x2, 189), row3[i]).draw(win) for i in range(4): x2 = 67*i Text(Point(x + x2, 256), row4[i]).draw(win) return win def playGame(windows, row1, row2, row3, row4): count = 0 number = randrange(1, 144) while row1 and row2 and row3 and row4: number = randrange(1, 144) print("\nnumber called:", number) if number in row1: print("CROSS OFF NUMBER!\n") row1.pop(row1.index(number)) p = windows.getMouse() c = Circle(Point(p.getX(), p.getY()), 5) c.setFill("red") c.draw(windows) elif number in row2: print("CROSS OFF NUMBER!\n") row2.pop(row2.index(number)) p = windows.getMouse() c = Circle(Point(p.getX(), p.getY()), 5) c.setFill("red") c.draw(windows) elif number in row3: print("CROSS OFF NUMBER!\n") row3.pop(row3.index(number)) p = windows.getMouse() c = Circle(Point(p.getX(), p.getY()), 5) c.setFill("red") c.draw(windows) elif number in row4: print("CROSS OFF NUMBER!\n") row4.pop(row4.index(number)) p = windows.getMouse() c = Circle(Point(p.getX(), p.getY()), 5) c.setFill("red") c.draw(windows) else: print("Number not on board.") print() count = count + 1 t = Text(Point(162.5, 162.5), "BINGO! Click to close game board") t.setTextColor("yellow") t.setSize(15) t.setOutline("red") t.draw(windows) windows.getMouse() windows.close() return count def printSummary(count_): print("\n\nBINGO! You have successfully crossed off 1 row of numbers!!") print("It took", count_, "calls to win!") if __name__ == "__main__": main()
true
4ac7f190f2cbfe093f660dd19e88ff6ac8f78a9e
Python
dannywillems/radix-dlt-python
/radixdlt/crypto/utils.py
UTF-8
114
2.59375
3
[]
no_license
import hashlib def double_sha256(bytestr): return hashlib.sha256(hashlib.sha256(bytestr).digest()).digest()
true
e20c08ff810e76ed80d649b5b6245635eb394735
Python
anuar-a/DSA-Algorithmic-toolbox
/gcd.py
UTF-8
183
3.59375
4
[]
no_license
# Uses python3 def gcd(a, b): while b != 0: temp = b b = a % b a = temp return a numbers = input() a, b = numbers.split() print(gcd(int(a), int(b)))
true
d8a4cbbb6d9b66ca2cccb4fa532cb3e23c7f2193
Python
fuyan2/ECE521_Intro_ML
/A2/part_1_2.py
UTF-8
785
2.78125
3
[]
no_license
from common import * # part 1.2 # as batch_size increase to the size of training data, # the training MSE reduces, however, the training time increases _, axis_1 = plt.subplots() batch_sizes = [500, 1500, 3500] for i in range(len(batch_sizes)): W, b, loss, accuracy, lin_op = linear_optimizer(0.005, 0) batch_size = batch_sizes[i] train_W, train_b, train_losses, _, _, _ = \ train(lin_op, W, b, loss, accuracy, batch_size, iterations) # compute validation loss valid_accuracy = get_lin_accuracy(train_W, train_b, validData, validTarget) plot("batch size = " + str(batch_size), axis_1, train_losses) print("batch_size = ", batch_size) print("Training loss = ", train_losses[-1]) print("Validation accuracy = ", valid_accuracy) axis_1.legend(loc='upper right') plt.show()
true
c68974c23af96020636f268403545fdb3b00df08
Python
ravshanyusupov/ravshan
/infi.py
UTF-8
1,669
3.109375
3
[]
no_license
# a = int(input("a soni: ")) # b = int(input("b soni: ")) # c = int(input("c soni: ")) # d = int(input("d soni: ")) # e = int(input("e soni: ")) # s = [a,b,c,d,e,] # o = max(s) # print(o) # a = int(input("son: ")) # if a == 2: # print("28 kun bor bu oyda") # elif a == 4 or a == 6 or a == 9 or a == 11: # print("30 kun bor bu oyda") # else: # print("31 kun bor bun oyda") # a = int(input("son kiriting: ")) # b = int(input("b soni kiriting: ")) # if a < 12 and b < 31: # x = 12 - a # x2 = 31 - b # print("yangi yilga", x, "oyu", x2, "kun qoldi") # elif a == 12 and b == 31: # print("hozir yangi yil") # else: # if a == 12 and b <= 31: # x = 31 - b # print(x,"kun qoldi") # else: # print("xato son") # a = int(input("son kiriting: ")) # if a == 3 or a == 4 or a == 5: # print("bahor") # elif a == 6 or a == 7 or a == 8: # print("yoz") # else: # if a == 9 or a == 10 or a ==11: # print("kuz") # else: # if a == 12 or a == 1 or a ==2: # print("qiw") # else: # print("xato son kiritildi") # a = int(input("son kiriting: ")) # if a > 25 and a < 40: # print("mos keladi") # else: # print("mos kelmaydi") # a = int(input("son kiriting: ")) # if a >= 0 and a <= 5: # print("chaqaloq") # elif a >= 6 and a <= 12: # print("bola") # else: # if a >= 13 and a <= 19: # print("ospirin") # else: # if a >= 20 and a <= 50: # print("yoshroq") # else: # if a >= 50 and a <= 100: # print("qari") # else: # print("xato son")
true
265a5304deab118d0da5441a396ad4964cc3d966
Python
sadqwerch/Bolaris
/user_classfication/my_sql_sentence.py
UTF-8
325
2.90625
3
[]
no_license
def my_sql(mysql_conn, sql): try: with mysql_conn.cursor() as cursor: cursor.execute(sql) mysql_conn.commit() data = cursor.fetchall() if len(data) > 0: return data except Exception as e: print(sql) print("Commit Failed!") return None
true
928666ddb60ab1ed32c5ca0cf5314c2ae2303926
Python
msuriyak/ME-757
/recursive_polynomial.py
UTF-8
3,442
3.421875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from scipy.special import legendre # *********** Evaluation *********** def legendre_value(n, x): value = np.zeros(n + 1) value[0] = 1 value[1] = x for i in range(2, n + 1): value[i] = ((2 * i - 1) * value[i - 1] * x - (i - 1) * value[i - 2]) / i return value[n] # *********** Roots *********** def legendre_roots(n): x = np.zeros(n) for i in range(n): a = ((4. * i + 3) / (4 * n + 2)) * np.pi b = (n - 1) / (8. * (n**3)) x[i] = (1 - b) * np.cos(a) iters = 0 while True: if(iters > 500 or abs(0 - legendre_value(n, x[i])) < 1e-16): break y = legendre_value(n, x[i]) y1 = (n * (legendre_value(n - 1, x[i]) - x[i] * legendre_value(n, x[i]))) / (1 - x[i]**2) y2 = (2 * x[i] * y1 - n * (n + 1) * legendre_value(n, x[i])) / (1 - x[i]**2) num = 2 * y * y1 den = 2 * (y1**2) - y * y2 x[i] = x[i] - (num / den) iters = iters + 1 return np.sort(x) def lobatto_roots(n): x = np.zeros(n) x[0] = 1.0 x[n - 1] = -1.0 for i in range(1, n - 1): a = ((4. * i + 1) / (4 * n - 3)) * np.pi b = 3 * (n - 2) / (8. * ((n - 1)**3)) x[i] = (1 - b) * np.cos(a) iters = 0 while True: y = 1.0 if(iters > 500 or abs(x[i] - y) < 1e-16): break d = (1 - x[i]**2) y = (n - 1) * (legendre_value(n - 2, x[i]) - x[i] * legendre_value(n - 1, x[i])) / d y1 = (2 * x[i] * y - n * (n - 1) * legendre_value(n - 1, x[i])) / d y2 = (2 * x[i] * y1 - (n * (n - 1) - 2) * y) / d num = 2 * y * y1 den = 2 * (y1**2) - y * y2 x[i] = x[i] - (num / den) iters = iters + 1 return np.sort(x) # *********** Weights *********** def legendre_weights(n): x = legendre_roots(n) w = np.zeros(n) for i in range(n): val = legendre_value(n - 1, x[i]) w[i] = 2 * (1 - x[i]**2) / (n * val)**2 return w def lobatto_weights(n): x = lobatto_roots(n) w = np.zeros(n) for i in range(n): val = legendre_value(n - 1, x[i]) w[i] = 2.0 / (n * (n - 1) * (val**2)) return w # *********** Interpolation *********** def lagrange(i, n, x, x_k): v = 1.0 for j in range(n): if i != j: v = v * ((x_k - x[j]) / (x[i] - x[j])) return v def func_interpolation(x, n, x_k, func): f = func(x) vv = [] for j in range(len(x_k)): v = 0.0 for i in range(n): v = v + f[i] * lagrange(i, n, x, x_k[j]) vv.append(v) return np.array(vv) NODES = {'lobatto' : lobatto_roots, 'legendre' : legendre_roots} WEIGHTS = {'lobatto' : lobatto_weights, 'legendre' : legendre_weights} def func_integrate(n, func, type_interpolation='legendre', type_integration='lobatto'): x = NODES[type_interpolation](n) nodes = NODES[type_integration](n) func = func_interpolation(x, n, nodes, func) weights = WEIGHTS[type_integration](n) integral = 0.0 for i in range(n): integral = integral + func[i] * weights[i] return integral if __name__ == '__main__': print('Running main!!')
true
2f57de3c84557899c80126cb9a492665756f0866
Python
fwparkercode/IntroProgrammingNotes
/Notes/Fall2018/ch6A.py
UTF-8
9,347
4.65625
5
[]
no_license
# Chapter 6 Notes, More Loops! # Learn to master the FOR loop # more with printing print("Francis", "Parker") # Python automatically puts a space in between print("Francis" + "Parker") # Concatenation smushes two strings together print("Python" * 10) # printing multiple times # Python automatically adds "\n" to the end of every print() print() print("First", end=" ") print("Second", end=" ") print("Third") print() # THE FOLLOWING PROBLEMS ARE FROM CHAPTER 6 # 1 # Write code that will print ten asterisks (*) like the following: ''' * * * * * * * * * * ''' # Have this code print using a FOR loop. # Can be done in two lines of code, a FOR loop and a print statement. print("#1") for i in range(10): print("*", end=" ") print() # 2 # Write code that will print the following: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' # This is just like the prior problem, but also printing five and twenty stars. # Copy and paste from the prior problem, adjusting the for loop as needed. print("#2") for i in range(10): print("*", end=" ") print() for i in range(5): print("*", end=" ") print() for i in range(20): print("*", end=" ") print() # 3 # Use two for loops, one of them nested inside the other, to print the following # 10x10 rectangle: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' print("#3") for j in range(10): for i in range(10): print("*", end=" ") print() # 4 # Use two for loops, one of them nested, to print the following 5x10 rectangle: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' print("#4") for j in range(10): for i in range(5): print("*", end=" ") print() # 5 # Use two for loops, one of them nested, to print the following 20x5 rectangle: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' print("#5") for j in range(5): for i in range(20): print("*", end=" ") print() # 6 # Write code that will print the following: ''' 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ''' # Use two nested loops. print("#6") for j in range(10): for i in range(10): print(i, end=" ") print() # 7 # Adjust the prior program to print: ''' 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 ''' print("#7") for j in range(10): for i in range(10): print(j, end=" ") print() # 8 # Write code that will print the following: ''' 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 9 ''' # Tip: This is just problem 6, but the inside loop no longer loops a # fixed number of times. Don't use range(10), but adjust that range # amount. print("#8") for row in range(11): for column in range(row): print(column, end=" ") print() for row in range(10): for column in range(row + 1): print(column, end=" ") print() # 9 ''' Write code that will print the following: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0 This one is difficult. Tip: Two loops are needed inside the outer loop that controls each row. First, a loop prints spaces, then a loop prints the numbers. Loop both these for each row. To start with, try writing just one inside loop that prints: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0 Then once that is working, add a loop after the outside loop starts and before the already existing inside loop. Use this new loop to print enough spaces to right justify the other loops. ''' print("#9") for row in range(10): for space in range(row): print(" ", end="") for column in range(10 - row): print(column, end=" ") print() for row in range(10): print(" " * row, end="") for column in range(10 - row): print(column, end=" ") print() for i in range(10, 0, -1): for space in range(10 - i): print(" ", end="") for j in range(i): print(j, end=" ") print() # 10 ''' Write code that will print the following (Getting the alignment is hard, at least get the numbers): 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81 Tip: Start by adjusting the code in problem 1 to print: 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 ''' for i in range(1, 10): for j in range(1, 10): if i * j >= 10: print(i * j, end=" ") else: print(i * j, end=" ") print() ''' Then adjust the code to print: 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81 ''' ''' Finally, use an if to print spaces if the number being printed is less than 10. ''' # 11 ''' Write code that will print the following: 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 ''' ''' Tip: first write code to print: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 ''' for i in range(9): for j in range(1, i + 2): print(j, end=" ") print() ''' Then write code to print: 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 ''' for i in range(9): for j in range(9 - i): print(" ", end=" ") # count up for j in range(1, i + 2): print(j, end=" ") # count down for j in range(i, 0, -1): print(j, end = " ") print() ''' Then finish by adding spaces to print the final answer. ''' # 12 ''' Write code that will print the following: 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 This can be done by combining problems 11 and 9. After working at least ten minutes on the problem, here is the answer: ProgramArcadeGames.com/chapters/06_back_to_looping/three_quarters.php Write code that will print the following: 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1 1 2 3 2 1 1 2 1 1 ''' ''' #ONE POTENTIAL SOLUTION TO THIS PROBLEM for i in range(10): # print spaces for l in range(9 - i): print(" ", end = " ") # print up for j in range(i): print(j + 1, end = " ") # print down for k in range(i - 1 , 0, -1 ): print(k, end = " ") print() for i in range(10, 0, -1): # print spaces for l in range(11 - i): print(" ", end = " ") # print up for j in range(i - 2): print(j + 1, end = " ") print() ''' #2 n = 4 ''' oooooooo o o o o oooooooo ''' #1 x = 10 for row in range(10): for column in range(row): print(x, end=" ") print() #2 # top line for i in range(??): print("oo", end="") print() # middle portion for row in range(??): print("o", end="") for space in range(??): print(" ", end="") print("o") # bottom line for i in range(??): print("oo", end="") print()
true
2f53f19a5c879b266767d040ba7bfbe8582bf695
Python
Kausara-Kpabia/100DaysOfCode-Exercises
/exercise.py
UTF-8
526
4.1875
4
[]
no_license
"""" #Exercise 1-Hello name = input("What is your name") print('hello', name) """ """ #Exercise 2- Area of a room width = float(input('What is the width of your room')) length = float(input('What is its length')) print('The area of your room is :', str(width * length) , 'fts') """ """ #Exercise 3- Area of a field width = float(input('What is the width of your farm in fts')) length = float(input('What is its length in fts')) area = (width * length) / 43560 print('The area of your field is :' , str(area) , 'acres' ) """
true
33cec4e59f5ed288a177bb4a7e36849d608ca01c
Python
HONGWENHT/LeetCode
/264.py
UTF-8
650
3.5625
4
[]
no_license
import collections class Ugly: def __init__(self): self.nums = [1, ] p2 = p3 = p5 = 0 for i in range(1, 1690): ugly = min(self.nums[p2] * 2, self.nums[p3] * 3, self.nums[p5] * 5) self.nums.append(ugly) if ugly == self.nums[p2] * 2: p2 += 1 elif ugly == self.nums[p3] * 3: p3 += 1 elif ugly == self.nums[p5] * 5: p5 += 1 class Solution: def nthUglyNumber(self, n: int) -> int: u = Ugly() return u.nums[n] s = Solution() s.nthUglyNumber(10) s = "ffffannnssh" print(collections.Counter(s))
true
0938f530e011d7b3fe70f3733419d6cb0ea1524a
Python
meutband/DailyAssignments
/Natural_Language_Processing/Exercise1.py
UTF-8
2,367
3.390625
3
[]
no_license
from pymongo import MongoClient from nltk.tokenize import word_tokenize from nltk.stem.snowball import SnowballStemmer from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer import numpy as np from sklearn.metrics.pairwise import linear_kernel import pandas as pd ''' Setup using MongoDB. - Marks-MBP:nlp meutband$ sudo mongod #Without closing, open a new terminal tab - Marks-MacBook-Pro:nlp meutband$ mongoimport --db nyt_dump --collection articles data/articles_mongoimport.json --batchSize 1 Now from python: ''' ''' 1. load all of the article content from the collection into a list of strings where each individual string is a NY Times article. ''' client = MongoClient() db = client.nyt_dump coll = db.articles documents = ['\n'.join(article['content']) for article in coll.find()] ''' 2. Write a function that will tokenize the documents and use SnowballStemmer to stemitize the documents. ''' snowball = SnowballStemmer('english') def tokenize(doc): return [snowball.stem(word) for word in word_tokenize(doc.lower())] ''' 3. Apply CountVectorizer. Print the counts and then print the feature names ''' countvect = CountVectorizer(stop_words='english', tokenizer=tokenize) count_vectorized = countvect.fit_transform(documents) print count_vectorized words = countvect.get_feature_names() print words ''' 4. Apply TfidfVectorizer. Print the vectors and then print the feature names ''' tfidfvect = TfidfVectorizer(stop_words='english', tokenizer=tokenize) tfidf_vectorized = tfidfvect.fit_transform(documents) print tfidf_vectorized words_tfidf = tfidfvect.get_feature_names() print words_tfidf ''' 5. Find the cosine similarity between 2 documents. Find the 5 most alike document pairs ''' # TfidfVectorizer can produce normalized vectors, in which case cosine_similarity # is equivalent to linear_kernel, only slower. cosine_similarities = linear_kernel(tfidf_vectorized, tfidf_vectorized) results = pd.DataFrame() d1 = [] d2 = [] cs = [] for i, doc1 in enumerate(documents): for j, doc2 in enumerate(documents): if i != j: d1.append(i) d2.append(j) cs.append(cosine_similarities[i,j]) results['Document1'] = d1 results['Document2'] = d2 results['Cosine Similarity'] = cs results.sort_values(by='Cosine Similarity', ascending='False') print results.head(5)
true
a580cadcdaeaad9d9921e319a42c599572adfb9c
Python
Incertam7/Infosys-InfyTQ
/Data-Structures-and-Algorithms/Day-2/Linked-List-Operations/Insertion.py
UTF-8
2,621
4.03125
4
[]
no_license
class Node: def __init__(self, data): self.__data = data self.__next = None def get_data(self): return self.__data def set_data(self, data): self.__data = data def get_next(self): return self.__next def set_next(self, next_node): self.__next = next_node class LinkedList: def __init__(self): self.__head = None self.__tail = None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self, data): new_node = Node(data) if(self.__head is None): self.__head = self.__tail = new_node else: self.__tail.set_next(new_node) self.__tail = new_node def display(self): temp = self.__head while temp is not None: print(temp.get_data()) temp = temp.get_next() def find_node(self, data): if self.__head == None: return None else: temp = self.get_head() while temp is not None: if temp.get_data() == data: return temp elif temp.get_next() is None: return None else: temp = temp.get_next() def insert(self, data, data_before): new_node = Node(data) if data_before is None: new_node.set_next(self.get_head()) self.__head = new_node if new_node.get_next() is None: self.__tail = new_node else: prev_node = self.find_node(data_before) if prev_node is None: print("Data not found") return else: new_node.set_next(prev_node.get_next()) prev_node.set_next(new_node) if new_node.get_next() is None: self.__tail = new_node #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): temp = self.__head msg = [] while temp is not None: msg.append(str(temp.get_data())) temp = temp.get_next() msg = " ".join(msg) msg = "Linkedlist data(Head to Tail): " + msg return msg list1 = LinkedList() list1.add("Sugar") list1.add("Teabags") list1.add("Milk") list1.add("Biscuits") #Insert the element in the required position list1.insert("Eggs", "Sugar") list1.display()
true
2e7430c3ecae252d5242826b25f34701f5fd1655
Python
shlomimatichin/codeprocessing
/py/amatureguard/meaninglessidentifier.py
UTF-8
558
2.9375
3
[]
no_license
import string CHARACTERS = string.ascii_lowercase + string.ascii_uppercase + string.digits + '_' OBJECTIVE_C_KEEP_INIT_PREFIX = False def meaninglessIdentifier(spelling, id): assert id < len(CHARACTERS) ** 3 first = (id / (len(CHARACTERS) ** 2)) % len(CHARACTERS) second = (id / len(CHARACTERS)) % len(CHARACTERS) third = id % len(CHARACTERS) result = 'Z' + CHARACTERS[first] + CHARACTERS[second] + CHARACTERS[third] if OBJECTIVE_C_KEEP_INIT_PREFIX and spelling.startswith("init"): return "init" + result return result
true
9323772e4a6bde3455ead1262323f32757962f6a
Python
mnastorg/CR_INTERPOLATION_PROJ_MOD
/CODES/rotation_dim_1.py
UTF-8
2,391
2.734375
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def rotation(G1,G2,t): G1 = G1.reshape(G1.shape[0]*G1.shape[1]) G2 = G2.reshape(G2.shape[0]*G2.shape[1]) theta = np.arccos(np.dot(G1,G2)/(np.linalg.norm(G1)*np.linalg.norm(G2))) w = G2/np.linalg.norm(G2) v = (G1 - (np.dot(G1,w))*w)/np.linalg.norm((G1 - (np.dot(G1,w))*w)) M = np.zeros((2,np.size(v))) M[0,:] = v M[1,:] = w P = np.dot(np.transpose(M),M) O = mat_rotation(theta,t) I = np.eye(np.shape(P)[0]) ROT = (I-P) + np.dot(np.dot(np.transpose(M),O),M) return ROT def mat_rotation(theta,t): MAT = [ [np.cos(theta*t),-np.sin(theta*t)], [np.sin(theta*t),np.cos(theta*t)] ] return MAT def gaussienne(x,y,N,x0,y0,x1,y1,sig1,sig2): x = np.linspace(0,1,N+1) y = np.linspace(0,1,N+1) G1 = np.zeros((N+1,N+1)) G2 = np.zeros((N+1,N+1)) for i in range(N+1): for j in range(N+1): G1[i,j] = np.exp(-(((x[i]-x0)**2)/(2*sig1) + ((y[j]-y0)**2)/(2*sig1))) G2[i,j] = np.exp(-(((x[i]-x1)**2)/(2*sig2) + ((y[j]-y1)**2)/(2*sig2))) return G1,G2 def affichage(FILE): INTERPOL = np.loadtxt(FILE) x = np.linspace(0,1,np.shape(INTERPOL)[0]) y = np.linspace(0,1,np.shape(INTERPOL)[0]) fig = plt.figure(figsize = [10,10]) X,Y = np.meshgrid(x,y) ax = fig.add_subplot(111, projection = '3d') ax.plot_surface(X,Y,INTERPOL, cmap = 'hot') plt.xlabel("x") plt.ylabel("y") plt.title("INTERPOLATION") #fig2 = plt.figure(figsize = [10,10]) #X,Y = np.meshgrid(x,y) #ax2 = fig2.add_subplot(111, projection = '3d') #ax2.plot_surface(X,Y,INTERPOL, cmap = 'hot') #plt.xlabel("x") #plt.ylabel("y") #plt.title("INTERPOLATION") plt.show() def main(N): x = np.linspace(0,1,N+1) y = np.linspace(0,1,N+1) G1, G2 = gaussienne(x,y,N,0.4,0.4,0.6,0.6,0.01,0.01) GR1 = G1.reshape(G1.shape[0]*G1.shape[1],1) GR2 = G2.reshape(G2.shape[0]*G2.shape[1],1) for t in np.arange(0,1.1,0.1): t = round(t,3) ROT = rotation(G1,G2,t) GG1 = np.dot(ROT,GR1) GG1 = GG1.reshape(G1.shape[0],G1.shape[1]) np.savetxt("output1/Interpol_{}.txt".format(t),GG1) for t in np.arange(0,2.1,0.1): t = round(t,3) affichage("output1/Interpol_{}.txt".format(t))
true
848024287c047514457c82559e66ac4e1f17335e
Python
jonathanmendoza-tx/data-structures
/doubly_linked_list/doubly_linked_list.py
UTF-8
4,179
4.4375
4
[]
no_license
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next """ Our doubly-linked list class. It holds references to the list's head and tail nodes. """ class DoublyLinkedList: def __init__(self, node=None): self.head = node self.tail = node self.length = 1 if node is not None else 0 def __len__(self): return self.length """ Wraps the given value in a ListNode and inserts it as the new head of the list. Don't forget to handle the old head node's previous pointer accordingly. """ def add_to_head(self, value): new_node = ListNode(value) if self.length == 0: self.head = new_node self.tail = new_node elif self.length == 1: self.head = new_node self.head.next = self.tail self.tail.prev = self.head elif self.length > 1: old_head = self.head self.head = new_node self.head.next = old_head self.head.next.prev = self.head self.length += 1 """ Removes the List's current head node, making the current head's next node the new head of the List. Returns the value of the removed Node. """ def remove_from_head(self): if self.length == 1: value = self.head.value self.head = None self.tail = None elif self.length > 1: value = self.head.value self.head.next.prev = None self.head = self.head.next self.length -= 1 return value """ Wraps the given value in a ListNode and inserts it as the new tail of the list. Don't forget to handle the old tail node's next pointer accordingly. """ def add_to_tail(self, value): new_node = ListNode(value) if self.length == 0: self.head = new_node self.tail = new_node elif self.length == 1: self.tail = new_node self.tail.prev = self.head self.head.next = self.tail elif self.length > 1: self.tail = new_node cur_node = self.head while cur_node.next is not None: cur_node = cur_node.next cur_node.next = self.tail self.tail.prev = cur_node self.length += 1 """ Removes the List's current tail node, making the current tail's previous node the new tail of the List. Returns the value of the removed Node. """ def remove_from_tail(self): if self.length == 0: return None elif self.length == 1: value = self.tail.value self.tail = None self.head = None elif self.length > 1: value = self.tail.value self.tail.prev.next = None self.tail = self.tail.prev self.length -= 1 return value """ Removes the input node from its current spot in the List and inserts it as the new head node of the List. """ def move_to_front(self, node): # save value, delete(node) # add_to_head(value) value = node.value self.delete(node) self.add_to_head(value) """ Removes the input node from its current spot in the List and inserts it as the new tail node of the List. """ def move_to_end(self, node): if node.next is not None: if node.prev is None: self.head = node.next self.head.prev = None else: node.prev.next = node.next node.next.prev = node.prev old_tail = self.tail self.tail = node self.tail.next = None self.tail.prev = old_tail self.tail.prev.next = self.tail """ Deletes the input node from the List, preserving the order of the other elements of the List. """ def delete(self, node): if node is not None: if node.next is None and node.prev is None: self.head = None self.tail = None elif node.next is None: node.prev.next = None self.tail = node.prev elif node.prev is None: node.next.prev = None self.head = node.next else: node.prev.next = node.next node.next.prev = node.prev self.length -= 1 else: return None """ Finds and returns the maximum value of all the nodes in the List. """ def get_max(self): cur_node = self.head value = self.head.value while cur_node.next is not None: cur_node = cur_node.next if value < cur_node.value: value = cur_node.value return value
true
6dede2177648e310011a9a924edce3a5b0073568
Python
2333paopao/KomiProject
/test_frame/test_perform/test_perform_notepad.py
UTF-8
702
2.90625
3
[]
no_license
#!/usr/bin/env python # -*- coding:utf-8 -*- #====#====#====#==== #Author: #CreatDate: #Version: #====#====#====#==== #ๅฏผๅ…ฅๆต‹่ฏ•็”จไพ‹ from test_case.test_case_notepad import TestCaseNotepad class TestPerformNotepad: #ๅ‚ๆ•ฐไธบ่พ“ๅ…ฅๆ–‡ๆœฌๅ’Œๆ–‡ไปถไฟๅญ˜่ทฏๅพ„ def __init__(self,text,save_path): self.text = text self.save_path = save_path def test_perform_notepad(self): #่ฐƒ็”จๆต‹่ฏ•็”จไพ‹ TestCaseNotepad(self.text,self.save_path).test_case_notepad() if __name__ == '__main__': #ๅฐ†่พ“ๅ…ฅๆ–‡ๆœฌๅ’Œไฟๅญ˜่ทฏๅพ„ไผ ๅ…ฅ TestPerformNotepad('ไธ€ไบŒไธ‰ๅ››ไบ”\nไธŠๅฑฑๆ‰“่€่™Ž\n','C:\\Users\\Komi\\Desktop\\file01.txt').test_perform_notepad()
true
dfd5dd95ee26cca99e4974716b999038e9a8afa9
Python
Manash-git/Python-Programming
/python-programming-basic/none_type_cast.py
UTF-8
782
3.6875
4
[]
no_license
# print('Test') # x= None # print(type(x)) # print(id(x)) # z= 10 # y= print(z) # print(y) # print(str(10.5)) # print(type(str(10.5))) # print(str(0b1011)) # print(type(str(0b1011))) # print(bool("hello")) # print(bool("0")) # print(bool(0)) # print(bool("")) # print(bool(None)) # print(bool(" ")) # print(bool(0j)) # print(complex(2)) # print(complex(2+5j)) # print(complex(5,9)) # print(complex(5,9.5)) # print(complex(5.4,9)) # print(complex(5.4,9)) # print(complex(0b1010,9)) # print(complex(0b1010,0xB)) # print(complex(True)) # print(complex(False)) # # print(complex(None)) # Eval() = Its converts the value with its respective type print(eval('10')) print(type(eval("10"))) print(type(eval("10.5"))) print(type(eval("10.56e7"))) print(type(eval("0b10111")))
true
103db8e8c5eca497360a576b5fa12262e06d63a8
Python
macrdona/UserLogin
/Completed Login App/Hash.py
UTF-8
530
3.296875
3
[]
no_license
import hashlib #creating class hash class Hash: #contructor to initialize password def __init__(self, password): self.password = password #return the hash value of the given password '''After the password has been hashed, it is then converted into hexadecimal form. It returns as a string that can be store into the database''' def hashFunction(self, salt): result = hashlib.pbkdf2_hmac('sha256',self.password.encode('utf-8'), salt, 100000).hex() return result
true
85c1a5ad9e6f089d4147ebe8869f55373139c7c5
Python
akkikiki/katakana_segmentation
/tfissf/test_tfisfViterbiLattice.py
UTF-8
3,089
2.71875
3
[ "Apache-2.0" ]
permissive
# coding: utf-8 import codecs import sys from segment_katakana_tfisf import TfisfViterbiLattice import unittest from unittest import TestCase from sklearn.model_selection import KFold TF_TRIE = "TF_TRIE" ISF_TRIE = "ISF_TRIE" class TestTfisfViterbiLattice(TestCase): def test_segment_hashtags(self): in_file = "TEST_FILE" test_file = codecs.open(in_file, "r", "utf-8") test_file_out = codecs.open(in_file + "_tfisf_result.txt", "w", "utf-8") self.segment_and_output(test_file, test_file_out) print "Finished segmenting hashtags using only tf-isf" # @unittest.skip("testing skipping") def test_segment(self): compound_word_candidates = [u'ใƒžใ‚คใƒŠใƒณใƒใƒผ'] tfisf_viterbi_lattice = TfisfViterbiLattice() tfisf_viterbi_lattice.set_tf_trie(TF_TRIE) tfisf_viterbi_lattice.set_isf_trie(ISF_TRIE) for word in compound_word_candidates: decoded_segments = tfisf_viterbi_lattice.construct_lattice(word) print word + " -> " + " ".join(decoded_segments) # @unittest.skip("testing skipping") def test_segment_bccwj(self): training_filename = "TRAINING_FILENAME" f = codecs.open(training_filename, "r", "utf-8") training_lines = f.readlines() splitted_training = [] splitted_tests = [] data_indice = list(range(len(training_lines))) f.close() kf = KFold(n_splits=3, shuffle=True, random_state=1) for train_index, test_index in kf.split(data_indice): print(len(train_index), len(test_index)) splitted_training.append(train_index) splitted_tests.append(test_index) tfisf_viterbi_lattice = TfisfViterbiLattice() # replace spaces tfisf_viterbi_lattice.set_tf_trie(TF_TRIE) tfisf_viterbi_lattice.set_isf_trie(ISF_TRIE) for i, splitted_test in enumerate(splitted_tests): test_file = [] for test_index in splitted_test: print(test_index) test_file.append(training_lines[test_index]) test_file_out = codecs.open(training_filename + "_tfisf_result_20151226_%i.txt" % i, "w", "utf-8") for katakana in test_file: space_deleted = katakana[:-1].replace(" ", "") decoded_segments = tfisf_viterbi_lattice.construct_lattice(space_deleted) print space_deleted + " -> " + " ".join(decoded_segments) test_file_out.write(" ".join(decoded_segments).rstrip() + "\n") def segment_and_output(self, test_file, test_file_out): tfisf_viterbi_lattice = TfisfViterbiLattice() tfisf_viterbi_lattice.set_tf_trie(TF_TRIE) tfisf_viterbi_lattice.set_isf_trie(ISF_TRIE) for katakana in test_file: print(katakana[:-1]) decoded_segments = tfisf_viterbi_lattice.construct_lattice(katakana[:-1].replace(" ", "")) # print katakana[:-1] + " -> " + " ".join(decoded_segments) test_file_out.write(" ".join(decoded_segments).rstrip() + "\n")
true
3ec375873c07013c9a95364fae74fa0ed767f987
Python
victorpham1997/Automatic-health-declaration-for-SUTD
/automatic_health_declaration_v3.py
UTF-8
11,250
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on 11/03/2021 Last edit on 11/03/2021 version 3 @author: T.Vic note: This version can bypass the captcha by utilising cv2 filters, BFS and pytesseract OCR. The script will attempt to make a number of attempts to inference the captcha and log in with the provided username and password. The number of try depends on your luck, the average number of try I got is usually around 10. Chrome driver will be automatically downloaded For SUTD account username and password, you can either hardcode inside the script or parse it as arguments to the script. Please ensure they are correct! Telegram me @Vhektor if you have any question regards to the script! """ from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import argparse import os import time import datetime import cv2 import sys import os import numpy as np import pytesseract from PIL import Image from matplotlib import cm from webdriver_manager.chrome import ChromeDriverManager class autoHealthDeclaration: def __init__ (self, args): if sys.platform == "win32": pytesseract.pytesseract.tesseract_cmd = args.tesseractpath self.abs_path = os.path.realpath(__file__)[:-len(os.path.basename(__file__))] self.log_path = os.path.abspath(self.abs_path + "auto_health_log.txt") self.sutd_declaration_url = "https://tts.sutd.edu.sg/tt_login.aspx?formmode=expire" self.userID_elem_name = "ctl00$pgContent1$uiLoginid" self.pw_elem_name = "ctl00$pgContent1$uiPassword" self.captcha_field_name = "ctl00$pgContent1$txtVerificationCode" self.login_submit_btn_name = "ctl00$pgContent1$btnLogin" self.captcha_image_id = "pgContent1_Image2" self.login_page_url = "https://tts.sutd.edu.sg/tt_home_user.aspx" self.daily_declaration_url = "https://tts.sutd.edu.sg/tt_daily_dec_user.aspx" self.temperature_taking_url = "https://tts.sutd.edu.sg/tt_temperature_taking_user.aspx" chrome_options = Options() # You comment the next 3 lines to debug if there is any issue chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') chorme_driver_path = ChromeDriverManager().install() # Use the driver on the line below to prevent the script from creating a chrome window whenever the script run if args.sandbox: self.driver = webdriver.Chrome(chorme_driver_path) else: self.driver = webdriver.Chrome(chorme_driver_path, chrome_options=chrome_options) #------------------------------ Hardcode your username and pw here!!------------------------------------------ self.userid = "" self.userpw = "" #--------------------------Else you have to manually pass it as arguement------------------------------------- if args.username != "": self.userid = args.username if args.pw != "": self.userpw = args.pw self.login = False self.captcha = "" self.filter_threshold = 195 def main(self): #if condition returns False, AssertionError is raised: assert self.userid != "" and self.userpw != "", "Username and/or password cannot be empty, either provide it in the arguments or hardcode it in the script!" # This while loop is to keep trying to login, the average number of try is around 10 i = 1 while not self.login: self.driver.get(self.sutd_declaration_url) captcha = self.driver.find_element_by_id(self.captcha_image_id) captcha.screenshot(self.abs_path+"temp.png") img = cv2.imread(self.abs_path+"temp.png") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img[3:,3:] self.captcha = self.bypassCaptcha(img).strip() # self.captcha = input("Enter captcha:") print(f"\ncaptcha is: {self.captcha}") # time.sleep() if self.captcha.isalnum() and (len(self.captcha)==4 or len(self.captcha)==5): current_url = self.Login() print(current_url) if current_url == self.login_page_url: print(f"Login succeeded after {i} tries!\nMoving on to next step!") try: f = open(self.log_path, "a") f.write(f"{datetime.datetime.now()} Succeeded after {i} tries\n") f.close() except: print(f"Cannot write to log file at {self.log_path}, please check if your path is valid") self.login = True else: print(f"Inferenced captcha {self.captcha} is incorrect, retrying for the {i} time...") else: print(f"Inferenced captcha {self.captcha} does not match the required condition, retrying for the {i} time...") i+=1 if i > 100: print("Loop timeout, please check your username and password and make sure it is correct before trying again (or you are just very very very unlucky :(") try: f = open(self.log_path, "a") f.write(f"{datetime.datetime.now()} Failed\n") f.close() except: print(f"Cannot write to log file at {self.log_path}, please check if your path is valid") exit() self.tempTaking() self.alertHandling() self.dailyDeclaration() self.alertHandling() print("All processes is completed! Exiting...") self.driver.quit() def Login(self): userID = self.driver.find_element_by_name(self.userID_elem_name) pw = self.driver.find_element_by_name(self.pw_elem_name) captcha_field = self.driver.find_element_by_name(self.captcha_field_name) submit_btn = self.driver.find_element_by_name(self.login_submit_btn_name) userID.clear() userID.send_keys(self.userid) pw.clear() pw.send_keys(self.userpw) captcha_field.clear() captcha_field.send_keys(self.captcha) # pw.send_keys(Keys.RETURN) submit_btn.click() time.sleep(1) return self.driver.current_url def bypassCaptcha(self, img): c_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) out = cv2.medianBlur(c_gray,3) a = np.where(out>self.filter_threshold, 1, out) out = np.where(a!=1, 0, a) out = self.removeIsland(out, 30) out = cv2.medianBlur(out,3) # plt.imshow(out,cmap='gray') im = Image.fromarray(out*255) out_captcha = pytesseract.image_to_string(im) # print(out_captcha) return out_captcha def bfs(self, visited, queue, array, node): # I make BFS itterative instead of recursive to accomodate my WINDOWS friends >:] def getNeighboor(array, node): neighboors = [] if node[0]+1<array.shape[0]: if array[node[0]+1,node[1]] == 0: neighboors.append((node[0]+1,node[1])) if node[0]-1>0: if array[node[0]-1,node[1]] == 0: neighboors.append((node[0]-1,node[1])) if node[1]+1<array.shape[1]: if array[node[0],node[1]+1] == 0: neighboors.append((node[0],node[1]+1)) if node[0]-1>0: if array[node[0],node[1]-1] == 0: neighboors.append((node[0],node[1]-1)) return neighboors queue.append(node) visited.add(node) while queue: current_node = queue.pop(0) for neighboor in getNeighboor(array, current_node): if neighboor not in visited: # print(neighboor) visited.add(neighboor) queue.append(neighboor) def removeIsland(self, img_arr, threshold): while 0 in img_arr: x,y = np.where(img_arr == 0) point = (x[0],y[0]) visited = set() queue = [] self.bfs(visited, queue, img_arr, point) if len(visited) <= threshold: for i in visited: img_arr[i[0],i[1]] = 1 else: for i in visited: img_arr[i[0],i[1]] = 2 img_arr = np.where(img_arr==2, 0, img_arr) return img_arr def tempTaking(self): self.driver.get(self.temperature_taking_url) self.driver.find_element_by_xpath("//select[@name='ctl00$pgContent1$uiTemperature']/option[text()='Less than or equal to 37.6ยฐC']").click() submit_btn = self.driver.find_element_by_xpath(".//form//input[@type='submit']") submit_btn.click() def dailyDeclaration(self): time.sleep(1) self.driver.get(self.daily_declaration_url) buttons = self.driver.find_elements_by_xpath(".//form//input[@type='radio']") self.box_clicked = 0 def check_box(): self.box_clicked = 0 for i in range(len(buttons)): btn_ls = self.driver.find_elements_by_xpath(".//form//input[@type='radio']") # print(len(btn_ls)) if (btn_ls[i].get_attribute("value").endswith("No")): btn_ls[i].click() self.box_clicked += 1 while(self.box_clicked < 4): try: check_box() except: print("Error occured, trying again.") submit_btn = self.driver.find_element_by_xpath(".//form//input[@type='submit']") submit_btn.click() def alertHandling(self): alert = self.driver.switch_to.alert alert.accept() if __name__ == "__main__": parser = argparse.ArgumentParser(description='This is automatic_health_declaration version 3, it can bypass captcha and help you log your temperature and health check automatically. Username and pw can be hardcoded in the script or passed as arguments!') parser.add_argument('-s', '--sandbox', type=bool, nargs='?', const=True, default=False , help='Will open chrome window if flag is set') parser.add_argument('-u', '--username', type=str, default="" , help='Input your username here or ignore it and hardcode in the script') parser.add_argument('-p', '--pw', type=str, default="" , help='Input your password here or ignore it and hardcode in the script') parser.add_argument('-tp', '--tesseractpath', type=str, default=r'C:\Program Files\Tesseract-OCR\tesseract.exe' , help='Manually set the path to Tesseract on your system. Only for Windows') args = parser.parse_args() ahd = autoHealthDeclaration(args) ahd.main() exit(10) # print(os.path.realpath(__file__)[-len(os.path.basename(__file__)):]) # print(os.path.realpath(__file__)[:-len(os.path.basename(__file__))])
true
f0fb666f60ea01f9025b5641f3ebbe7fc2b675cc
Python
youngBai-c/100-Days-of-Code
/Beginner/1/1.3.py
UTF-8
232
3.703125
4
[]
no_license
# input() will get user input in console # Then print() will print the word "Hello" and the user input #print("Hello "+input("What is your name?")) # Example Input Angela # Example Output 6 print(len(input("What is your name?")))
true
98edac331ebba563871cd02e2bbcf6fa3afe1f06
Python
pmnyc/Data_Engineering_Collections
/trajectory_distance/traj_dist/pydist/erp.py
UTF-8
2,027
3.171875
3
[]
no_license
import numpy as np from basic_euclidean import eucl_dist from basic_geographical import great_circle_distance ############# # euclidean # ############# def e_erp(t0,t1,g): """ Usage ----- The Edit distance with Real Penalty between trajectory t0 and t1. Parameters ---------- param t0 : len(t0)x2 numpy_array param t1 : len(t1)x2 numpy_array Returns ------- dtw : float The Dynamic-Time Warping distance between trajectory t0 and t1 """ n0 = len(t0) n1 = len(t1) C=np.zeros((n0+1,n1+1)) C[1:,0]=sum(map(lambda x : abs(eucl_dist(g,x)),t0)) C[0,1:]=sum(map(lambda y : abs(eucl_dist(g,y)),t1)) for i in np.arange(n0)+1: for j in np.arange(n1)+1: derp0 = C[i-1,j] + eucl_dist(t0[i-1],g) derp1 = C[i,j-1] + eucl_dist(g,t1[j-1]) derp01 = C[i-1,j-1] + eucl_dist(t0[i-1],t1[j-1]) C[i,j] = min(derp0,derp1,derp01) erp = C[n0,n1] return erp ################ # geographical # ################ def g_erp(t0,t1,g): """ Usage ----- The Edit distance with Real Penalty between trajectory t0 and t1. Parameters ---------- param t0 : len(t0)x2 numpy_array param t1 : len(t1)x2 numpy_array Returns ------- dtw : float The Dynamic-Time Warping distance between trajectory t0 and t1 """ n0 = len(t0) n1 = len(t1) C=np.zeros((n0+1,n1+1)) C[1:,0]=sum(map(lambda x : abs(great_circle_distance(g[0],g[1],x[0],x[1])),t0)) C[0,1:]=sum(map(lambda y : abs(great_circle_distance(g[0],g[1],y[0],y[1])),t1)) for i in np.arange(n0)+1: for j in np.arange(n1)+1: derp0 = C[i-1,j] + great_circle_distance(t0[i-1][0],t0[i-1][1],g[0],g[1]) derp1 = C[i,j-1] + great_circle_distance(g[0],g[1],t1[j-1][0],t1[j-1][1]) derp01 = C[i-1,j-1] + great_circle_distance(t0[i-1][0],t0[i-1][1],t1[j-1][0],t1[j-1][1]) C[i,j] = min(derp0,derp1,derp01) erp = C[n0,n1] return erp
true
a691f7fb988158c307f4cc3a10fcc74b8c12dfaf
Python
Iyamoto/stocksadvisor
/collectors/ema.py
UTF-8
6,587
2.734375
3
[]
no_license
"""Collect EMA 200""" import sys import os sys.path.insert(0, os.path.abspath('..')) import datetime import time import logging import fire import requests from influxdb import InfluxDBClient import configs.alphaconf import configs.influx import configs.fxit def get_ema200(symbol, age=5*23*3600): influx_client = InfluxDBClient( configs.influx.HOST, configs.influx.PORT, configs.influx.DBUSER, configs.influx.DBPWD, configs.influx.DBNAME, timeout=5 ) query = 'SELECT last("ema200") FROM "data" WHERE ("symbol"=~ /^' + symbol + '$/)' result = influx_client.query(query) ema200_date = result.raw['series'][0]['values'][0][0] tmp = ema200_date.split('.') ema200_date = tmp[0] ema200_date = datetime.datetime.strptime(ema200_date, '%Y-%m-%dT%H:%M:%S') now = datetime.datetime.utcnow() diff = now - ema200_date if diff.total_seconds() < age: ema200 = result.raw['series'][0]['values'][0][1] else: ema200 = None return ema200 def get_price(symbol, age=23*3600): influx_client = InfluxDBClient( configs.influx.HOST, configs.influx.PORT, configs.influx.DBUSER, configs.influx.DBPWD, configs.influx.DBNAME, timeout=5 ) # influx_client.drop_measurement('data') # exit() query = 'SELECT last("price") FROM "data" WHERE ("symbol"=~ /^' + symbol + '$/)' result = influx_client.query(query) price_date = result.raw['series'][0]['values'][0][0] tmp = price_date.split('.') price_date = tmp[0] price_date = datetime.datetime.strptime(price_date, '%Y-%m-%dT%H:%M:%S') now = datetime.datetime.utcnow() diff = now - price_date if diff.total_seconds() < age: price = result.raw['series'][0]['values'][0][1] else: price = None query = 'SELECT last("change_percent") FROM "data" WHERE ("symbol"=~ /^' + symbol + '$/)' result = influx_client.query(query) change_percent = result.raw['series'][0]['values'][0][1] return price, change_percent def fetch_ema200_alpha(symbol, key=configs.alphaconf.key): url = 'https://www.alphavantage.co/query?function=' + \ 'EMA&symbol={}&interval=daily&time_period=200&series_type=close&apikey={}'.format(symbol, key) retry = 0 # Check cache try: ema200 = get_ema200(symbol) except: ema200 = None if ema200: logging.info(symbol + ' Got EMA200 from InfluxDB: ' + str(ema200)) else: # Try to fetch from the WEB while True: try: r = requests.get(url=url, timeout=5) data = r.json() last = data['Meta Data']['3: Last Refreshed'] ema200 = float(data['Technical Analysis: EMA'][last]['EMA']) if ema200: break except: retry += 1 if retry > 10: logging.error('Can not fetch ' + symbol) logging.error(url) break logging.info(symbol + ' retry ' + str(retry)) time.sleep(retry*5) continue return ema200 def fetch_price_alpha(symbol, key=configs.alphaconf.key): url = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={}&apikey={}'.format(symbol, key) retry = 0 # Check cache try: price, change_percent = get_price(symbol) except: price = None change_percent = None if price: logging.info(symbol + ' Got price from InfluxDB: ' + str(price)) else: # Try to fetch from the WEB while True: try: r = requests.get(url=url, timeout=5) data = r.json() price = float(data['Global Quote']['05. price']) change_percent = data['Global Quote']['10. change percent'] change_percent = float(change_percent.strip('%')) if price: break except: retry += 1 if retry > 10: logging.error('Can not fetch ' + symbol) logging.error(url) break logging.info(symbol + ' retry ' + str(retry)) time.sleep(retry*5) continue return price, change_percent def fetch(write_to_influx=True, datatype='fxit'): if write_to_influx: influx_client = InfluxDBClient( configs.influx.HOST, configs.influx.PORT, configs.influx.DBUSER, configs.influx.DBPWD, configs.influx.DBNAME, timeout=5 ) if datatype == 'fxit': symbols = configs.fxit.holdings if datatype == 'portfolio': symbols = configs.alphaconf.symbols for symbol in symbols: if datatype == 'portfolio': symbol = list(symbol.keys())[0] price, change_percent = fetch_price_alpha(symbol) logging.info(symbol + ' price: ' + str(price)) ema200 = fetch_ema200_alpha(symbol) logging.info(symbol + ' ema200: ' + str(ema200)) if type(ema200) != float: logging.error(symbol + ' ema200 ' + str(ema200) + ' not float') continue if type(price) != float: logging.error(symbol + ' price ' + str(price) + ' not float') continue ema_distance = round(100 * (price - ema200) / ema200, 2) if symbol in configs.fxit.holdings: symbol_type = 'FXIT' else: symbol_type = 'Portfolio' if write_to_influx: json_body = [ { "measurement": "data", "tags": { "symbol": symbol, "symbol_type": symbol_type, }, "fields": { "price": price, "ema200": ema200, "ema_distance": ema_distance, "change_percent": change_percent, } } ] influx_client.write_points(json_body) if __name__ == "__main__": logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s', level='INFO', stream=sys.stderr) if "PYCHARM_HOSTED" in os.environ: # print(fetch_price_alpha('MSFT')) fetch(write_to_influx=False) else: fire.Fire()
true
c6368e95f6e0febfaae2b4544171d5ee5c3d2402
Python
CAU-SE-Project/UC-10-Disease-Management
/alarm3.py
UTF-8
1,619
2.75
3
[]
no_license
# alarm3.py import sys from PyQt5.QtWidgets import * import databaseConnection class Alarm3(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.tableWidget = QTableWidget() query_list = self.load_alarm() rowNum = len(query_list) self.tableWidget.setRowCount(rowNum) self.tableWidget.setColumnCount(2) self.tableWidget.setHorizontalHeaderLabels( ['์•Œ๋žŒ ์‹œ๊ฐ„', '์•Œ๋žŒ ๋‚ด์šฉ'] ) self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # self.tableWidget.setEditTriggers(QAbstractItemView.DoubleClicked) # self.tableWidget.setEditTriggers(QAbstractItemView.AllEditTriggers) self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) for i in range(rowNum): dateTimeVar = query_list[i][0] self.tableWidget.setItem(i, 0, QTableWidgetItem(dateTimeVar)) self.tableWidget.setItem(i, 1, QTableWidgetItem(query_list[i][1])) layout = QVBoxLayout() layout.addWidget(self.tableWidget) self.setLayout(layout) self.setWindowTitle('Alarm ๋ชฉ๋ก') self.setGeometry(300, 100, 600, 400) self.show() def load_alarm(self): dbConnection = databaseConnection.DatabaseConnection() query_list = dbConnection.loadDB(1) # print("load query ์™„๋ฃŒ") return query_list if __name__ == '__main__': app = QApplication(sys.argv) ex = Alarm3() sys.exit(app.exec_())
true
3deb6aea6ad761f41dbc417cb1113a3cb42e2f1c
Python
Elenanikiforov/my_python
/cinema_price.py
UTF-8
7,956
3.5625
4
[]
no_license
print("ะคะธะปัŒะผั‹:\n1.'ะŸัั‚ะฝะธั†ะฐ'\n2.'ะงะตะผะฟะธะพะฝั‹'\n3.'ะŸะตั€ะฝะฐั‚ะฐั ะฑะฐะฝะดะฐ'\n") film = int(input("ะ’ั‹ะฑะตั€ะธั‚ะต ะฝะพะผะตั€ ั„ะธะปัŒะผะฐ: ")) if film == 1: day = int(input("1. Cะตะณะพะดะฝั\n2.ะ—ะฐะฒั‚ั€ะฐ\n")) if day == 1: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n12 ั‡ะฐัะพะฒ,16 ั‡ะฐัะพะฒ, 20 ั‡ะฐัะพะฒ:\n')) if time == 12: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*0.8*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250) elif time == 16: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350) elif time == 20: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450) if day == 2: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n12 ั‡ะฐัะพะฒ,16 ั‡ะฐัะพะฒ, 20 ั‡ะฐัะพะฒ:\n')) if time == 12: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*0.8*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.95) elif time == 16: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.95) elif time == 20: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.95) elif film == 2: day = int(input("1.Cะตะณะพะดะฝั\n2.ะ—ะฐะฒั‚ั€ะฐ\n")) if day == 1: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n10 ั‡ะฐัะพะฒ,13 ั‡ะฐัะพะฒ, 16 ั‡ะฐัะพะฒ:\n')) if time == 10: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*0.8*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250) elif time == 13: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350) elif time == 16: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350) if day == 2: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n10 ั‡ะฐัะพะฒ,13 ั‡ะฐัะพะฒ, 16 ั‡ะฐัะพะฒ:\n')) if time == 10: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*0.8*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',250*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",250*0.95) elif time == 13: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.95) elif time == 16: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.95) elif film == 3: day = int(input("1.Cะตะณะพะดะฝั\n2.ะ—ะฐะฒั‚ั€ะฐ\n")) if day == 1: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n10 ั‡ะฐัะพะฒ,14 ั‡ะฐัะพะฒ, 18 ั‡ะฐัะพะฒ:\n')) if time == 10: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350) elif time == 14: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450) elif time == 18: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450) if day == 2: time = int(input('ะ’ั‹ะฑะตั€ะธั‚ะต ะฒั€ะตะผั:\n10 ั‡ะฐัะพะฒ,14 ั‡ะฐัะพะฒ, 18 ั‡ะฐัะพะฒ:\n')) if time == 10: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*0.8*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',350*n*0.95, "\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",350*0.95) elif time == 14: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.95) elif time == 18: n = int(input("ะกะบะพะปัŒะบะพ ะฑะธะปะตั‚ะพะฒ ะฝะตะพะฑั…ะพะดะธะผะพ?\n")) if n >= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*0.8*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.8*0.95) elif n <= 20: print('ะกั‚ะพะธะผะพัั‚ัŒ ะฑะธะปะตั‚ะพะฒ: ',450*n*0.95,"\nะกั‚ะพะธะผะพัั‚ัŒ ะพะดะฝะพะณะพ: ",450*0.95)
true
68e481f0d057fbd69486c6a2d8cbf5a9767ced5d
Python
psegedy/schemathesis
/test/loaders/test_graphql.py
UTF-8
1,664
2.71875
3
[ "MIT" ]
permissive
"""GraphQL specific loader behavior.""" from io import StringIO import pytest from schemathesis.specs.graphql import loaders RAW_SCHEMA = """ type Book { title: String author: Author } type Author { name: String books: [Book] } type Query { getBooks: [Book] getAuthors: [Author] }""" def test_graphql_asgi_loader(graphql_path, fastapi_graphql_app, run_asgi_test): # When an ASGI app is loaded via `from_asgi` schema = loaders.from_asgi(graphql_path, fastapi_graphql_app) strategy = schema[graphql_path]["POST"].as_strategy() # Then it should successfully make calls via `call_asgi` run_asgi_test(strategy) def test_graphql_wsgi_loader(graphql_path, graphql_app, run_wsgi_test): # When a WSGI app is loaded via `from_wsgi` schema = loaders.from_wsgi(graphql_path, graphql_app) strategy = schema[graphql_path]["POST"].as_strategy() # Then it should successfully make calls via `call_wsgi` run_wsgi_test(strategy) def defines_type(parsed, name): return len([item for item in parsed["__schema"]["types"] if item["name"] == name]) == 1 def assert_schema(schema): assert "__schema" in schema.raw_schema assert defines_type(schema.raw_schema, "Author") assert defines_type(schema.raw_schema, "Book") @pytest.mark.parametrize("transform", (lambda x: x, StringIO)) def test_graphql_file_loader(transform): raw_schema = transform(RAW_SCHEMA) schema = loaders.from_file(raw_schema) assert_schema(schema) def test_graphql_path_loader(tmp_path): path = tmp_path / "schema.graphql" path.write_text(RAW_SCHEMA) schema = loaders.from_path(path) assert_schema(schema)
true
4f46c14a4d71b3aa83305b09f73950ba5c884814
Python
thotte/competitor-price-scraping
/test_hallon.py
UTF-8
984
2.859375
3
[]
no_license
""" hallon.py unit tests (https://www.hallon.se/mobilabonnemang) """ import requests from hallon import Hallon hallon = Hallon("Hallon") df = hallon.get_dataframe() function_returns_list = hallon.process_dataframe(df) def test_site_availability(): """Test site availability""" site = Hallon.website req = requests.head(site) assert req.status_code == 200 def test_getting_dataframe(): """Test that dataframe is returning something""" assert len(df) != 0 def test_processing_dataframe(): """Test that dataframe is correctly processed""" assert len(function_returns_list) != 0 def test_number_of_rows(): """Test that dataframe rows is more than 5""" total_rows = len(function_returns_list) assert total_rows > 3 def test_column_names(): """Test that column names are correct""" assert set(function_returns_list.columns) == {'volume', 'campaign_price', 'full_price', 'campaign_months', 'campaign_data', 'operator', 'date'}
true
9d2239873e2251549e018b4dade871fc023bce60
Python
another1s/Companyfreport
/financial_repot_pdf/code/debug_.py
UTF-8
6,716
2.671875
3
[]
no_license
import pandas as pd import tabula from pandas.api.types import * import numpy as np import csv import pdfplumber import re import warnings warnings.filterwarnings("ignore") TAG = 'PdfPlumber_Demo:' class Util: @staticmethod def get_page_text(text_page): text_str = [] text_list = [] for line in text_page: text_list.append(list(filter(lambda x: len(str(x[0]).strip()) > 0, line))) text_line = '' for ch in line: text_line += (str(ch[0]) + '~[' + str(ch[1]) + '->' + str(ch[2]) + ' | ' + str(ch[3]) + '->' + str(ch[4]) + ']; ') text_str.append(text_line) text_str = "\n".join(text_str) return text_list, text_str __x_thr = 6 col_list = ['2018', '2017', 'ๆฌŠ็›Š็ธฝ้ก'] @staticmethod def get_value(text_list, key_list): col_list = Util.__get_col_loc(text_list) result_list = {} for key in key_list: for i in range(0, text_list.__len__()): cu_line = text_list[i] if list(filter(lambda x: x[0].strip().lower() == key.lower(), cu_line)): result_line = Util.__check_col(cu_line, col_list, Util.__x_thr) Util.__format_text(result_line) result_list[key] = list(map(lambda x: {'key': x[0], 'col': x[1], 'val': x[2]}, result_line)) return result_list @staticmethod def __get_col_loc(text_list): col_list = [] for line in text_list: for cell in line: for col in Util.col_list: if cell and re.match('^(' + col + ')$', str(cell[0])) is not None: col_list.append([cell[0], cell[1], cell[2], cell[1] + (cell[2] - cell[1]) / 2]) return col_list @staticmethod def __check_col(text_line, col_list, thr=5): result_line = [] for col in col_list: cell_list = [] for cell in text_line: d_l = abs(col[1] - cell[1]) d_r = abs(col[2] - cell[2]) d_c = abs(col[3] - (cell[1] + (cell[2] - cell[1]) / 2)) dis = 0 if (d_l < thr) or (d_r < thr) else d_c cell_list.append([text_line[0][0] + '(' + text_line[1][0] + ')', col[0], cell[0].replace(' ', ''), dis]) cell_list.sort(key=lambda x: x[3], reverse=False) if cell_list: result_line.append(cell_list[0]) return result_line @staticmethod def __format_text(text): for cell in text: cell[2] = (cell[2] if re.match( '^(\(?-?([0-9]*,)*[0-9]+\.?[0-9]*\)?)$', cell[2]) is not None else '') # cell[2] = re.sub('[(),]+', '', cell[2]) def run(pdf_path, key_list=None, col_list=None, page_list=None): #print('wwwwwwwwwwwwwwwwwww') if not key_list: return {} if col_list: Util.col_list = col_list #print(TAG, 'file path =', pdf_path) pdf_file = pdfplumber.open(pdf_path) text_ori = [] text_result = [] page_i = 0 for page in pdf_file.pages: page_i = page_i + 1 if page_list and page_i not in page_list: continue text_list, text_str = Util.get_page_text(page.extract_text_my()) text_ori.append(text_str) text_result.append(Util.get_value(text_list, key_list)) #print(TAG, 'pdf run end, page num =', page_i) pdf_file.close() return text_result, text_ori def one_row(data): with open('result.csv', 'a+', newline='', encoding='utf-8') as f: header = data.keys() writer = csv.DictWriter(f, header) writer.writeheader() writer.writerow(data) f.close() def multi_row(data): with open('results.csv', 'a+') as f: header = data.keys() def search_key(directory, query=None): chinese_target = ['ๆ”ถๅ…ฅ', 'ๅˆฉๆถฆ', '่ต„ไบง', '่ดŸๅ€บ', 'ๆƒ็›Š'] english_target = ['Revenues', 'Profit', 'asset', 'liabilities', 'equity', 'profit', 'revenues'] target = set() for i, v in directory.items(): if query: for q in query: try: if v.find(q)>=0: r = v.find(q) target.add(i) break except Exception as e: #print(e) pass else: for cw, ew in zip(chinese_target, english_target): try: if v.find(cw)>=0 or v.find(ew)>=0: r1 = v.find(cw) r2 = v.find(ew) target.add(i) break except Exception as e: #print(e) pass return target def specify_col(cols, colname): res = np.where(cols == colname) return res[0].min(), colname def merge_result(res1, res2): res3 = res1.combine_first(res2) return res3 finalized_result = dict() ''' ta = sys.argv finalized_result['target'] = list() for i in ta: if not (i == 'combine.py'): finalized_result['target'].append(i) print(finalized_result['target']) ''' finalized_result['target']=['ๅ•†่ญฝ', '้žๅปถ็จ…้ …่ณ‡็”ข'] df = tabula.read_pdf("../datafolder/demo.pdf", pages='4', encoding='utf-8') columns = df.columns columns_name = columns._data nn = list() vv = list() names = ['2014', '2013'] for name in names: v, n = specify_col(columns_name, name) finalized_result[name] = list() nn.append(n) vv.append(v) rows = df.index col1 = df.iloc[:, 0] col2 = df.iloc[:, 1] a, b = run("../datafolder/demo.pdf", finalized_result['target'] , ['2013', '2014'], [4]) if not(pd.isnull(col2).any()) and not (is_float_dtype(col2) and is_integer_dtype(col2)): #print("hello") DirOfTable = pd.concat([col1, col2], axis=0) #print(search_key(DirOfTable, ['profit'])) for digit in search_key(DirOfTable, ['profit']): for col, name in zip(vv, nn): #print(df.iloc[digit, col]) finalized_result[name].append(df.iloc[digit, col]) else: DirOfTable = col1 #print(search_key(DirOfTable, ['ๅ•†่ญฝ', '้žๅปถ็จ…้ …่ณ‡็”ข'])) for digit in search_key(DirOfTable, finalized_result['target']): for col, name in zip(vv, nn): #print(df.iloc[digit, col]) finalized_result[name].append(df.iloc[digit, col]) #print(finalized_result) print(a, type(a)) for i in a: one_row(i) df1 = pd.DataFrame(finalized_result) #print('tabula_result:\n') #print(df1) df1.to_csv("test.csv", index=False, sep=',', encoding='utf_8_sig') print("done\n")
true
758dcb1574ad7d8789c01505826013f0c254af56
Python
wert23239/SmashBot
/util.py
UTF-8
6,200
2.609375
3
[ "MIT" ]
permissive
import melee import pandas as pd import numpy as np import random from pathlib import Path from melee import Button from melee.enums import Action from keras_pandas.Automater import Automater from keras.models import model_from_json class Util: def __init__(self,logger=None,controller=None,config=None): self.x_list=[0,.25,.5,.75,1] self.y_list=[0,.25,.5,.75,1] self.button_list=[None, Button.BUTTON_B, Button.BUTTON_L, Button.BUTTON_Y, Button.BUTTON_Z, Button.BUTTON_A] self.logger=logger self.controller=controller self.startE=1 self.endE=.01 self.e=1.0 self.config=config self.action_set=set() if config: self.create_model() def create_model(self): json_file = open(self.config.model_stucture, 'r') loaded_model_json = json_file.read() json_file.close() self.model = model_from_json(loaded_model_json) self.model.compile(optimizer="Adam", loss='mae') if Path(self.config.model_weights).is_file(): print("Loading Model...") self.model.load_weights(self.config.model_weights) def do_attack(self,gamestate,ai_state,opponent_state): processed_input,processed_action = ( self.preprocess_input(gamestate,ai_state,opponent_state)) if np.random.rand(1) < self.e: action=random.randint(0,149) else: action=self.config.model_predict(self.model,processed_input,processed_action) self.action_set.add(action) x_cord,y_cord,button_choice=self.unconvert_attack(action) self.controller.simple_press(x_cord,y_cord,button_choice) if self.logger: self.logger.log("Buttons_Pressed_Converted", self.convert_attack(x_cord,y_cord,button_choice),concat="True") def convert_attack(self,x_cord,y_cord,button_choice): x_num=x_cord/.25 y_num=y_cord/.25 button_choice=self.button_list.index(button_choice) return int(x_num+y_num*5+button_choice*25 ) def unconvert_attack(self,action): button_choice=action//25 action=action%25 y_cord=action//5 action=action%5 x_cord=action return self.x_list[x_cord],self.y_list[y_cord],self.button_list[button_choice] def train(self,rows): Y_train,X_train,action_train=self.preprocess_rows(rows) history=self.model.fit([X_train,action_train], Y_train,batch_size=128, epochs=3,validation_split=.1,verbose=0) self.save_model() if self.e>self.endE: self.e=self.e-.005 action_size=len(self.action_set) self.action_set.clear() return history.history['val_loss'][-1],self.e,action_size def save_model(self): json_string = self.model.to_json() with open(self.config.model_stucture,'w') as json_file: json_file.write(json_string) self.model.save_weights(self.config.model_weights) def preprocess_rows(self,rows): df=pd.DataFrame.from_dict(rows) df["Opponent_Percent_Change"] = df["Opponent_Percent_Change"].shift(-1) df["AI_Percent_Change"] = df["AI_Percent_Change"].shift(-1) df["Opponent_Stock_Change"] = df["Opponent_Stock_Change"].shift(-1) df["AI_Stock_Change"] = df["AI_Stock_Change"].shift(-1) df.drop(len(df)-1,inplace=True) #reward df['target'] = df.apply (lambda row: ( (int(row["AI_Percent_Change"])>0)*-.1+ (int(row["AI_Stock_Change"])<0)*-1+ (int(row["Opponent_Percent_Change"])>0)*.1+ (int(row["Opponent_Stock_Change"])<0)*1 ),axis=1) df[["Opponent_Facing", "AI_Facing","target"]] *= 1 discount_factor=.99 current_reward=0 df=df.drop(columns=['AI_Action', 'Opponent_Action', 'Buttons Pressed', 'Opponent_Percent_Change', 'AI_Percent_Change',"AI_Stock_Change","Opponent_Stock_Change"]) reward_avg=0 reward_min=0 for i in reversed(df.index): df.loc[i,"target"]=df.loc[i,"target"]+discount_factor*current_reward current_reward=df.loc[i,"target"] reward_avg+=current_reward reward_min=min(reward_min,current_reward) print("Reward Average: ",reward_avg/len(df)) print("Min Reward: ",reward_min) Y_train=df['target'].astype(float).values X_train=df[df.columns.difference(['target', 'Buttons_Pressed_Converted'])].astype(float).values action_train=df['Buttons_Pressed_Converted'].astype(int).values return Y_train,X_train,action_train def preprocess_input(self,gamestate,ai_state,opponent_state): df= pd.DataFrame({ 'Frame':[gamestate.frame], 'Opponent_x':[(opponent_state.x)], 'Opponent_y':[(opponent_state.y)], 'AI_x' : [(ai_state.x)], 'AI_y' : [(ai_state.y)], 'Opponent_Facing' : [(opponent_state.facing)], 'AI_Facing' : [(ai_state.facing)], 'Opponent_Action_Num' : [(Action(opponent_state.action).value)], 'AI_Action_Num' : [(Action(ai_state.action).value)], 'Opponent_Action_Frame' : [(opponent_state.action_frame)], 'AI_Action_Frame' : [(ai_state.action_frame)], 'Opponent_Jumps_Left' : [(opponent_state.jumps_left)], 'AI_Jumps_Left' : [(ai_state.jumps_left)], 'Opponent_Stock' : [(opponent_state.stock)], 'AI_Stock' : [(ai_state.stock)], 'Opponent_Percent' : [(opponent_state.percent)], 'AI_Percent' : [(ai_state.percent)] }) df[["Opponent_Facing", "AI_Facing"]] *= 1 df_test=df.head(1) result=df.head(1).astype(float).values result=np.tile(result,(149,1)) return result,np.array(range(149))
true
76d752fd634565f7aee4b36e841fa13f68f38829
Python
Nitin2611/15_Days-Internship-in-python-and-django
/DAY 3/task5.py
UTF-8
110
3.703125
4
[]
no_license
x = 46 y = 53 if x > y: print("x is greater number") if y > x: print("y is greater number")
true
fe0edb52088967b5f63fd9eb20ce089398a2c27a
Python
ooooo-youwillsee/wechat-data-structures-and-algorithms
/1-50/27/main.py
UTF-8
400
3.234375
3
[]
no_license
# coding=utf-8 class Solution: def solution(self): sum = 0 for i in range(2, 5 * pow(9, 5) + 1): if self.sum4(i) == i: sum += i return sum def sum4(self, n): sum = 0 while n: sum += pow(n % 10, 5) n //= 10 return sum if __name__ == '__main__': s = Solution() print(s.solution())
true
cd2f90b535285d46dfccf2e407f9543511935c34
Python
tanyabudinova/hack-bulgaria-Python101
/week6/Generators/book_reader.py
UTF-8
661
3.28125
3
[]
no_license
from os import system def book(*files): for file in files: with open(file, 'r') as f: for line in f: yield line def read_chapter(next_line, book_lines): while next_line[0] != '#': print(next_line.strip()) next_line = next(book_lines) system("""bash -c 'read -s -n 1 -p "Press space to continue..."'""") print() print(next_line) read_chapter(next(book_lines), book_lines) def book_reader(*files): book_lines = book(*files) print(next(book_lines)) next_line = next(book_lines) try: read_chapter(next_line, book_lines) except StopIteration: pass
true
d861f5dfa4b79c83463924d3dd81bbed7542836e
Python
brunolcarli/AlgoritmosELogicaDeProgramacaoComPython
/livro/code/capitulo5/exemplo49.py
UTF-8
1,951
3.8125
4
[]
no_license
#entrar com a disciplina disciplina = input("Insira sua disciplina: ") #Entrar com a quantidade de alunos da turma quantidade = int(input("Insira o numero de alunos da turma: ")) #a turma e uma lista com tamanho igual a quantidade informada turma = [alunos for alunos in range(quantidade)] #para cada aluno na turma for aluno in turma: #informe os dados do aluno e guarde em um dicionario turma[aluno] = {'nome':input("Insira o nome do aluno: "), 'notas':[float(input("Insira a nota: ")) for notas in range(4)], 'media':0, 'sit': '', } #calcule a media referenciaando-a pelo indice turma[aluno]['media'] = ( turma[aluno]['notas'][0] + turma[aluno]['notas'][1] + turma[aluno]['notas'][2] + turma[aluno]['notas'][3]) / 4 #as notas estao dentro de uma lista no dicionario que esta dentro da lista da turma #agora vamos verificar se o aluno esta aprovado if turma[aluno]['media'] < 6.0: turma[aluno]['sit'] = 'Reprovado' elif turma[aluno]['media'] > 6.0 and turma[aluno]['media'] < 7.0: turma[aluno]['sit'] = 'Recuperacao' else: turma[aluno]['sit'] = 'Aprovado' #depois que seu loop receber todos os alunos vamos informar os resultados na tela print("Disciplina: %s" % disciplina) #escreva a disciplina for aluno in turma: #para cada aluno na turma print("Nome: %s " % aluno['nome'].capitalize()) #escreva o nome bi = 1 #vamos usar este bi para indicar o bimestre for notas in aluno['notas']: #aninhamos um for para contar as notas na lista do dicionario print("Nota %i : %.1f" % (bi, notas)) #Eescreva as notas da lista de notas bi += 1 #incremenete o bimestre print("Media Final: %.1f" % aluno['media']) #mostre a media final print("Resultado: %s" % aluno['sit']) #mostre o resultado
true
2b811bbef7640de0c2f78f5fa8ae95ae380e469c
Python
mzhuang1/lintcode-by-python
/็ฎ€ๅ•/141. x็š„ๅนณๆ–นๆ น.py
UTF-8
486
3.984375
4
[]
no_license
# -*- coding: utf-8 -*- """ ๅฎž็Žฐ int sqrt(int x) ๅ‡ฝๆ•ฐ๏ผŒ่ฎก็ฎ—ๅนถ่ฟ”ๅ›ž x ็š„ๅนณๆ–นๆ นใ€‚ ๆ ทไพ‹ sqrt(3) = 1 sqrt(4) = 2 sqrt(5) = 2 sqrt(10) = 3 """ class Solution: """ @param x: An integer @return: The sqrt of x """ def sqrt(self, x): # write your code here if x == 0: return 0 if x == 1: return 1 for i in range(int(x/2)+1): if i ** 2 <= x and (i + 1) ** 2 > x: return i
true
2439bbaa8001a50e3088ff10ff792bf725370d2e
Python
Susros/NUesc
/model/svm_gridsearch_plot.py
UTF-8
2,351
3.171875
3
[ "MIT" ]
permissive
""" SVM Grid Search Plot This script load Grid Search results and plot heatmap for C Parameters vs Gamma Parameters vs Accuracy. Author: Kelvin Yin """ import sys import pickle import plotly.graph_objects as go from plotly.subplots import make_subplots # Output Directory OUTPUT_DIR = 'output/' # Grid Search Parmaeters for plotting param_C = ['{1e-04}', '{1e-03}', '{1e-02}', '{1e-01}', '{1.0}', '{1e+01}', '{1e+02}', '{1e+03}', '{1e+04}', '{1e+05}', '{1e+06}', '{1e+07}', '{1e+08}'] param_gamma = ['{1e-11}', '{1e-10}', '{1e-09}', '{1e-08}', '{1e-07}', '{1e-06}', '{1e-05}', '{1e-04}', '{1e-03}', '{1e-02}', '{1e-01}', '{1.0}', '{10.0}'] # Load grid search result try: gridsearch = pickle.load(open(OUTPUT_DIR + 'svm_gridsearch.p', 'rb')) except IOError: print("Could not load SVM Grid Search result. Please make sure to run SVM Grid Search before running this script.") sys.exit(1) ''' Sort out data for plotting. Construct data for heatmap plotting to the following matrix: g1 g2 g3 ... gn ---------------------------- C1 [v1, v2, v3, ... , vn], C2 [v1, v2, v3, ... , vn], Cn ... Where g is gamma parameter and C is C parameter ''' gridsearch_index = 0 heatmap_data = [] # For checking the best parameters highest_accuracy = 0 highest_accuracy_C_index = 0 highest_accuracy_gamma_index = 0 for i in range(len(param_C)): # Chunk it for each parmaeter C chunk = [] for j in range(len(param_gamma)): # Convert accuracy into percentage accuracy_perct = round(gridsearch[gridsearch_index] * 100, 2) chunk.append(accuracy_perct) if (accuracy_perct > highest_accuracy): highest_accuracy = accuracy_perct highest_accuracy_C_index = i highest_accuracy_gamma_index = j gridsearch_index += 1 heatmap_data.append(chunk) ''' Plot Heatmap ''' fig = go.Figure(data = go.Heatmap(z = heatmap_data, x = param_gamma, y = param_C)) fig.update_layout( title = 'SVM Grid Search', xaxis_title = 'Gamma Parameter', yaxis_title = 'C Parameter' ) fig.show() ''' Show the best parameters ''' print("The best parameters:") print("==========================") print("C = ", param_C[highest_accuracy_C_index]) print("Gamma = ", param_gamma[highest_accuracy_gamma_index]) print("Accuracy = ", highest_accuracy)
true
f2a3d40f08af6ae9ca6643e5766f61691883fcde
Python
guilhermeafonsoch/neural-networks
/cancer-de-mama.py
UTF-8
2,139
3
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 21:45:34 2021 @author: guilh """ import numpy as np from sklearn import datasets def sigmoid(soma): return 1 / (1 + np.exp(-soma)) #DERIVADA PARCIAL DA SIGMOID def derivadaSigmoid(sig): return sig * (1 - sig) #database base = datasets.load_breast_cancer() entradas = base.data valoresSaida = base.target saidas = np.empty([569, 1], dtype=int) for i in range(569): saidas[i] = valoresSaida[i] #pesos aleatorios com a quantidade de neuronios pesos0 = 2*np.random.random((30,5)) - 1 pesos1 = 2*np.random.random((5,1)) - 1 epocas = 10000 taxaDeAprendizagem = 0.3 momento = 1 for i in range(epocas): camadaEntrada = entradas #CAMADA OCULTA somaDaSinapse0 = np.dot(camadaEntrada, pesos0) camadaOculta = sigmoid(somaDaSinapse0) #ULTIMA CAMADA somaDaSinapse1 = np.dot(camadaOculta, pesos1) camadaDeSaida = sigmoid(somaDaSinapse1) #ERRO = RESPOSTA CORRETA - RESPOSTA ERRADA erroDaCamadaDeSaida = saidas - camadaDeSaida mediaAbsolutaDoErro = np.mean(abs(erroDaCamadaDeSaida)) print("\nErro de --> " + str(mediaAbsolutaDoErro)) #DERIVADA E O DELTA DA CAMDADA DE SAIDA derivadaDeSaida = derivadaSigmoid(camadaDeSaida) deltaDeSaida = erroDaCamadaDeSaida * derivadaDeSaida #Para fazer a multiplicacao de peso com o delta de saida pesos1Transposta = pesos1.T #Formula = DeltaDeSaida * pesos * derivada sigmoide da camada oculta deltaCamadaOculta = deltaDeSaida.dot(pesos1Transposta) * derivadaSigmoid(camadaOculta) #Transposta da camada oculta para a multiplicacao de matrizes camadaOcultaTransposta = camadaOculta.T #atualizacao dos pesos da saida novosPesosSaida = camadaOcultaTransposta.dot(deltaDeSaida) pesos1 = (pesos1 * momento) + (novosPesosSaida * taxaDeAprendizagem) #atualizacao dos pesos da camda oculta camadaEntradaTransposta = camadaEntrada.T novosPesosCamadaOculta = camadaEntradaTransposta.dot(deltaCamadaOculta) pesos0 = (pesos0 * momento) + (novosPesosCamadaOculta * taxaDeAprendizagem)
true
87bb86d4da9d0aa719d0d6e30592d5f4b0b9ecda
Python
DevMan-VR/minizinc
/repo/readMKP.py
UTF-8
1,318
2.84375
3
[]
no_license
class readMKP: def read_MkpProblems(): problems = dict(); problems['data'] = [] problems['capacidad'] = [] problems['beneficio'] = [] problems['pesos'] = [] problems['optimo'] = [] f = open("./mkp_problems.txt", "r") lines = f.readlines() for line in lines: if '#' in line: data = lines[lines.index(line)+1].split() data = list(map(int, data)) nmochilas = data[1] capacidad = lines[lines.index(line)+2].split() capacidad = list(map(float, capacidad)) beneficio = lines[lines.index(line)+3].split() beneficio = list(map(float, beneficio)) optimo = float(lines[lines.index(line)+4+nmochilas]) pesos = [] #print(data) problems['data'].append(data) #print(capacidad) problems['capacidad'].append(capacidad) #print(beneficio) problems['beneficio'].append(beneficio) for knapsack in range(lines.index(line)+4,lines.index(line)+4+nmochilas): mochila_pesos = lines[knapsack].split() mochila_pesos = list(map(float, mochila_pesos)) pesos.append(mochila_pesos) #print(pesos) problems['pesos'].append(pesos) #print(optimo) problems['optimo'].append(optimo) f.close() return problems
true
d192873f077d2ff920b0a69161d9ebeacecb71ad
Python
ll0816/My-Python-Code
/decorator/decorator_with_function_args.py
UTF-8
907
3.859375
4
[]
no_license
# !/usr/bin/python # -*- coding: utf-8 -*- # Decorator function with Function Args # Liu L. # 12-05-15 import datetime def decorator_maker_with_args(decorator_arg1): def decorator(func): def wrapper(*args): print "Calling function: {} at {} with decorator arguments: {} and function arguments {}".\ format(func.__name__, datetime.datetime.now(), decorator_arg1, args) func(*args) print "Finished calling: {}".format(func.__name__) return wrapper return decorator @decorator_maker_with_args("Apollo 11 Landing") def print_name(*args): print "My full name is -- {} {} --".format(*args) if __name__ == '__main__': print_name("Tranquility base", "To Houston") def print_age(*args): print "My age is -- {} --".format(*args) decorated_func = decorator_maker_with_args("Boston")(print_age) decorated_func(23)
true
2bffd1f93ade43d54ca1a2f9fa505cfa7550d0f7
Python
FarsBein/python-terminal-chat
/client.py
UTF-8
931
3.046875
3
[]
no_license
import threading import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 59000)) def client_receive(): while True: try: message = client.recv(1024).decode('utf-8') if message == "quit" or message == "q": break else: print(f"received: {message}") except: print('Error in client_receive!') break client.close() def client_send(): while True: try: message = input("") client.send(message.encode('utf-8')) if message == "quit" or message == "q": break except: print('Error in client_send!') break client.close() receive_thread = threading.Thread(target=client_receive) receive_thread.start() send_thread = threading.Thread(target=client_send) send_thread.start()
true
9bc07e166414ebb22ce002bf520b22de140e769f
Python
DR-84/winc_backend_opdrachten
/opdracht_031_class_objects_2/class_objects_2.1.py
UTF-8
3,532
3.28125
3
[]
no_license
# is het idee van de opdracht dat we onze code/functions uit "return value" # herschrijven? of gaat het het om het eind resultaat. # -------------- opdracht 1------------------ class Player: def __init__(self, name, num, team): self.full_name = name self.id = num self.team = team class Goals: def __init__(self, num, minute): self.id = num self.minute = minute player_list = [ Player("Heinz Stuy", 1, "AFC Ajax"), Player("Horst Blankenburg", 2, "AFC Ajax"), Player("Barry Hulshoff", 3, "AFC Ajax"), Player("Gerrie Mรผhren", 4, "AFC Ajax"), Player("Ruud Krol", 5, "AFC Ajax"), Player("Wim Suurbier", 6, "AFC Ajax"), Player("Johan Neeskens", 7, "AFC Ajax"), Player("Sjaak Swart", 8, "AFC Ajax"), Player("Arie Haan", 9, "AFC Ajax"), Player("Johan Cruyff", 10, "AFC Ajax"), Player("Dick van Dijk", 11, "AFC Ajax"), Player("Johnny Rep", 12, "AFC Ajax"), Player("Dick Beukhof", 13, "Vitesse"), Player("Nico Kunst", 14, "Vitesse"), Player("Ben Gerritsen", 15, "Vitesse"), Player("Willy Melchers", 16, "Vitesse"), Player("Ben Bosma", 17, "Vitesse"), Player("Bram van Kerkhof", 18, "Vitesse"), Player("Herman Veenendaal", 19, "Vitesse"), Player("Willy Veenstra", 20, "Vitesse"), Player("Co Prins", 21, "Vitesse"), Player("Theo Rutten", 22, "Vitesse"), Player("Henk Vleeming", 23, "Vitesse"), Player("Henk Hofs", 24, "Vitesse"), Player("John Meeuwsen", 25, "Vitesse"), ] goal_list = [ Goals(7, 10), Goals(7, 28), Goals(10, 32), Goals(10, 42), Goals(10, 47), Goals(11, 49), Goals(11, 51), Goals(4, 63), Goals(3, 70), Goals(19, 75), Goals(10, 78), Goals(11, 81), Goals(7, 88), ] home_team = "Ajax" def who_won(goals, players): team1_goals = [] team2_goals = [] for goal in goals: for player in players: team = player.team if goal.id == player.id: if team in team1_goals or len(team1_goals) == 0: team1_goals.append(team) else: team2_goals.append(team) if len(team1_goals) > len(team2_goals): winner = team1_goals loser = team2_goals else: winner = team2_goals loser = team1_goals win_points = str(len(winner)) lose_points = str(len(loser)) return f"{winner[0]} wint van {loser[0]} met {win_points}-{lose_points}." def get_goal_info(players, goal): for player in players: if goal.id == player.id: minute = goal.minute player_name = player.full_name team_name = player.team return { "minute": minute, "player_name": player_name, "team_name": team_name, } def print_match_report(items): for item in items: print(item) def generate_match_report(players, goals): report_lines = [] home = 0 away = 0 for goal in goals: goals_full_info = [] goals_full_info.append(get_goal_info(players, goal)) for goals in goals_full_info: if goals["team_name"] is home_team: home += 1 if goals["team_name"] is not home_team: away += 1 line = f"In de {goals['minute']}e minuut " line += f"scoort {goals['player_name']} voor " line += f"{goals['team_name']} het is {home}-{away}." report_lines.append(line) report_lines.append(who_won(goal_list, player_list)) return report_lines print_match_report(generate_match_report(player_list, goal_list))
true
85e9d3a895ac8eeb8293ea471e0785b792253860
Python
luoyt14/deeplearningHW
/hw2/codes/functions.py
UTF-8
5,630
2.765625
3
[]
no_license
import numpy as np def im2col(x, field_height, field_width, padding=1, stride=1): N, C, H, W = x.shape out_height = int((H + 2 * padding - field_height) / stride + 1) out_width = int((W + 2 * padding - field_width) / stride + 1) i0 = np.repeat(np.arange(field_height), field_width) i0 = np.tile(i0, C) i1 = stride * np.repeat(np.arange(out_height), out_width) j0 = np.tile(np.arange(field_width), field_height * C) j1 = stride * np.tile(np.arange(out_width), out_height) i = i0.reshape(-1, 1) + i1.reshape(1, -1) j = j0.reshape(-1, 1) + j1.reshape(1, -1) k = np.repeat(np.arange(C), field_height * field_width).reshape(-1, 1) p = padding x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant') cols = x_padded[:, k, i, j] cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1) return cols def conv2d_forward(input, W, b, kernel_size, pad): ''' Args: input: shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) W: weight, shape = c_out (#output channel) x c_in (#input channel) x k (#kernel_size) x k (#kernel_size) b: bias, shape = c_out kernel_size: size of the convolving kernel (or filter) pad: number of zero added to both sides of input Returns: output: shape = n (#sample) x c_out (#output channel) x h_out x w_out, where h_out, w_out is the height and width of output, after convolution ''' h_out = input.shape[2] + 2 * pad - kernel_size + 1 w_out = input.shape[3] + 2 * pad - kernel_size + 1 c_out = W.shape[0] c_in = W.shape[1] input_col2 = im2col(input, kernel_size, kernel_size, pad, 1) input_col2 = input_col2.T.reshape(h_out, w_out, input.shape[0], -1) w_col = W.reshape((c_out, c_in * kernel_size * kernel_size)) output = np.dot(input_col2, w_col.T) + b return output.transpose(2, 3, 0, 1) def conv2d_backward(input, grad_output, W, b, kernel_size, pad): ''' Args: input: shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) grad_output: shape = n (#sample) x c_out (#output channel) x h_out x w_out W: weight, shape = c_out (#output channel) x c_in (#input channel) x k (#kernel_size) x k (#kernel_size) b: bias, shape = c_out kernel_size: size of the convolving kernel (or filter) pad: number of zero added to both sides of input Returns: grad_input: gradient of input, shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) grad_W: gradient of W, shape = c_out (#output channel) x c_in (#input channel) x k (#kernel_size) x k (#kernel_size) grad_b: gradient of b, shape = c_out ''' _, c_in, h_in, w_in = input.shape _, c_out, h_out, w_out = grad_output.shape grad_output_col = im2col(grad_output, kernel_size, kernel_size, kernel_size - 1, 1) h_padded = grad_output.shape[2] + kernel_size - 1 w_padded = grad_output.shape[3] + kernel_size - 1 grad_output_col = grad_output_col.T.reshape(h_padded, w_padded, grad_output.shape[0], -1) W_reshaped = np.rot90(W, 2, (2, 3)).transpose(1, 0, 2, 3).reshape(c_in, -1) grad_input = np.dot(grad_output_col, W_reshaped.T).transpose(2, 3, 0, 1) grad_input = grad_input[:, :, pad: h_in + pad, pad: w_in + pad] input_col = im2col(input.transpose(1, 0, 2, 3), h_out, h_out, pad, 1) h_padded = input.shape[2] + 2 * pad - h_out + 1 w_padded = input.shape[3] + 2 * pad - h_out + 1 input_col = input_col.T.reshape(h_padded, w_padded, input.shape[1], -1) grad_W = np.dot(input_col, grad_output.transpose(1, 0, 2, 3).reshape(c_out, -1).T).transpose(3, 2, 0, 1) grad_b = np.sum(grad_output, axis=(0, 2, 3)) return grad_input, grad_W, grad_b def avgpool2d_forward(input, kernel_size, pad): ''' Args: input: shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) kernel_size: size of the window to take average over pad: number of zero added to both sides of input Returns: output: shape = n (#sample) x c_in (#input channel) x h_out x w_out, where h_out, w_out is the height and width of output, after average pooling over input ''' _, c_in, h_in, w_in = input.shape h_out = int((h_in + 2 * pad - kernel_size) / kernel_size + 1) w_out = int((w_in + 2 * pad - kernel_size) / kernel_size + 1) W = 1.0 / (kernel_size * kernel_size) * np.ones((c_in, c_in, kernel_size, kernel_size)) input_col2 = im2col(input, kernel_size, kernel_size, pad, kernel_size) input_col2 = input_col2.T.reshape(h_out, w_out, input.shape[0], -1) w_col = W.reshape((c_in, c_in * kernel_size * kernel_size)) output = np.dot(input_col2, w_col.T) return output.transpose(2, 3, 0, 1) def avgpool2d_backward(input, grad_output, kernel_size, pad): ''' Args: input: shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) grad_output: shape = n (#sample) x c_in (#input channel) x h_out x w_out kernel_size: size of the window to take average over pad: number of zero added to both sides of input Returns: grad_input: gradient of input, shape = n (#sample) x c_in (#input channel) x h_in (#height) x w_in (#width) ''' grad_input = grad_output.repeat(kernel_size, axis=2).repeat(kernel_size, axis=3) / (kernel_size * kernel_size) return grad_input[:, :, pad: grad_output.shape[2] * kernel_size - pad, pad: grad_output.shape[3] * kernel_size - pad]
true
ee3da7b40af8192dc6fe4b86d9f615bbf14714b9
Python
grayfox7744/quantLibrary
/utility/dataframefeed.py
UTF-8
1,112
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Mar 08 22:26:36 2016 @author: Administrator """ from pyalgotrade.barfeed import membf from pyalgotrade import dataseries from pyalgotrade import bar class Feed(membf.BarFeed): def __init__(self, frequency=bar.Frequency.DAY, maxLen=dataseries.DEFAULT_MAX_LEN): membf.BarFeed.__init__(self, frequency, maxLen) def barsHaveAdjClose(self): return True def addBarsFromDataFrame(self, instrument, df): loadedBars = [] for row in df.iterrows(): dateTime = row[0] open_ = row[1]['open'] high = row[1]['high'] low = row[1]['low'] close = row[1]['close'] volume = row[1]['volume'] try: adjclose = row[1]['adjclose'] except KeyError: adjclose = None bar_ = bar.BasicBar(dateTime, open_, high, low, close, volume, adjclose, self._BaseBarFeed__frequency) loadedBars.append(bar_) self.addBarsFromSequence(instrument, loadedBars)
true
77d6013525ce507a6e84141bcb2d7ef6432be94d
Python
ThunderFlurry/django-th
/django_th/tasks.py
UTF-8
9,079
2.515625
3
[ "BSD-3-Clause" ]
permissive
# coding: utf-8 from __future__ import unicode_literals from __future__ import absolute_import import arrow # django from django.conf import settings from django.core.cache import caches from django.utils.log import getLogger # django-rq from django_rq import job # trigger happy from django_th.services import default_provider from django_th.models import TriggerService from django_th.my_services import MyService # create logger logger = getLogger('django_th.trigger_happy') default_provider.load_services() def publish_log_outdated(published, data): """ lets log things about outdated data or data from the future... (a date from the future) :param published: publishing date :param data: the data of the current trigger :type published: string date :type data: dict """ if 'title' in data: sentence = "data outdated skipped : [{}] {}" logger.debug(sentence.format(published, data['title'])) else: sentence = "data outdated skipped : [{}] " logger.debug(sentence.format(published)) def publish_log_data(published, date_triggered, data): """ lets log everything linked to the data :param published: publishing date :param date_triggered: the last time a trigger has been proceeded :param data: the data of the current trigger :type published: string date :type date_triggered: string date :type data: dict """ if 'title' in data: sentence = "date {} >= triggered {} title {}" logger.debug(sentence.format(published, date_triggered, data['title'])) else: sentence = "date {} >= date triggered {}" logger.debug(sentence.format(published, date_triggered)) def log_update(service, to_update, status, count): """ lets log everything at the end :param service: service object :param to_update: boolean to check if we have to update :param status: is everything worked fine ? :param count: number of data to update :type service: service object :type to_update: boolean :type status: boolean :type count: interger """ if to_update: if status: logger.info("{} - {} new data".format(service, count)) else: logger.info("{} AN ERROR OCCURS ".format(service)) else: logger.info("{} nothing new ".format(service)) def update_trigger(service): """ update the date when occurs the trigger :param service: service object to update """ now = arrow.utcnow().to(settings.TIME_ZONE).format( 'YYYY-MM-DD HH:mm:ss') TriggerService.objects.filter(id=service.id).update(date_triggered=now) def get_published(published='', which_date=''): """ get the published date from the provider or set a default date (today in fact) if this service runs for the first time :param published: service object to update :param which_date: service object to update :type published: string data :type which_date: string date """ if published is not None: # get the published date of the provider published = arrow.get(published).to(settings.TIME_ZONE) # store the date for the next loop # if published became 'None' which_date = published # ... otherwise set it to 00:00:00 of the current date if which_date == '': # current date which_date = arrow.utcnow().replace( hour=0, minute=0, second=0).to( settings.TIME_ZONE) published = which_date if published is None and which_date != '': published = which_date return published, which_date @job def reading(service): """ get the data from the service and put theme in cache :param service: service object to read """ datas = () # flag to know if we have to update to_update = False # flag to get the status of a service status = False # counting the new data to store to display them in the log # provider - the service that offer data service_provider = default_provider.get_service( str(service.provider.name.name)) # check if the service has already been triggered # if date_triggered is None, then it's the first run if service.date_triggered is None: logger.debug("first time {}".format(service)) to_update = True status = True # run run run else: # 1) get the data from the provider service # get a timestamp of the last triggered of the service kw = {'token': service.provider.token, 'trigger_id': service.id, 'date_triggered': service.date_triggered} datas = getattr(service_provider, '__init__')(service.provider.token) datas = getattr(service_provider, 'read_data')(**kw) if len(datas) > 0: to_update = True status = True log_update(service, to_update, status, len(datas)) @job def read_data(): """ The purpose of this tasks is to put data in cache because of the read_data function of each service """ trigger = TriggerService.objects.filter(status=True).select_related( 'consumer__name', 'provider__name') for service in trigger: reading.delay(service) @job('high') def publishing(service): """ the purpose of this tasks is to get the data from the cache then publish them :param service: service object where we will publish :type service: object """ # flag to know if we have to update to_update = False # flag to get the status of a service status = False # counting the new data to store to display them in the log count_new_data = 0 # provider - the service that offer data service_provider = default_provider.get_service( str(service.provider.name.name)) # consumer - the service which uses the data service_consumer = default_provider.get_service( str(service.consumer.name.name)) # check if the service has already been triggered # if date_triggered is None, then it's the first run if service.date_triggered is None: logger.debug("first run {}".format(service)) to_update = True status = True # run run run else: # 1) get the data from the provider service kw = {'trigger_id': service.id} datas = getattr(service_provider, 'process_data')(**kw) if datas is not None and len(datas) > 0: consumer = getattr(service_consumer, '__init__')( service.consumer.token) consumer = getattr(service_consumer, 'save_data') published = '' which_date = '' # 2) for each one for data in datas: if settings.DEBUG: from django_th.tools import to_datetime published = to_datetime(data) published, which_date = get_published(published, which_date) date_triggered = arrow.get( str(service.date_triggered), 'YYYY-MM-DD HH:mm:ss').to(settings.TIME_ZONE) publish_log_data(published, date_triggered, data) # the consummer will save the data and return if success or not status = consumer(service.id, **data) else: count_new_data = len(datas) to_update = True # let's log log_update(service, to_update, status, count_new_data) # let's update if to_update and status: update_trigger(service) @job('high') def publish_data(): """ the purpose of this tasks is to get the data from the cache then publish them """ trigger = TriggerService.objects.filter(status=True).select_related( 'consumer__name', 'provider__name') for service in trigger: publishing.delay(service) @job('low') def get_outside_cache(): """ the purpose of this tasks is to recycle the data from the cache with version=2 in the main cache """ all_packages = MyService.all_packages() for package in all_packages: cache = caches[package] # http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk for service in cache.iter_keys('th_*'): try: # get the value from the cache version=2 service_value = cache.get(service, version=2) # put it in the version=1 cache.set(service, service_value) # remote version=2 cache.delete_pattern(service, version=2) except ValueError: pass
true
aac99e1f9ca3816465d60fd950c388131954ba55
Python
shokri-matin/Python_Basics_OOP
/MRO.py
UTF-8
436
3.171875
3
[]
no_license
class X: i = 0 class Y: i = 1 class Z: i = 2 class A(X, Y): pass class B(Y, Z): pass class M(B, A, Z): pass AObj = A() print(AObj.i) BObj = B() print(BObj.i) MObj = M() print(MObj.i) # Output: # [<class '__main__.M'>, <class '__main__.B'>, # <class '__main__.A'>, <class '__main__.X'>, # <class '__main__.Y'>, <class '__main__.Z'>, # <class 'object'>] print(A.mro()) print(B.mro()) print(M.mro())
true
5a5aef44c8c6c3130d60ba653f47923c53242587
Python
joansanchez/MapReduce
/task5/model1/reducer.py
UTF-8
211
3.140625
3
[]
no_license
#!/usr/bin/env python2 import sys range = [] for range_years in sys.stdin: year = range_years.strip().split("\t") range.append(year[1]) range.append(year[2]) print (min(range) + "\t" + max(range))
true
e075c11d4348674d81362fb80e9a37db1b434b39
Python
miaozaiye/PythonLearning
/miaozaiye/introcs-python/helloworld.py
UTF-8
364
2.5625
3
[ "MIT" ]
permissive
#----------------------------------------------------------------------- # helloworld.py #----------------------------------------------------------------------- import stdio # Write 'Hello, World' to standard output. stdio.writeln('Hello, World') #----------------------------------------------------------------------- # python helloworld.py # Hello, World
true
404c0ae1dbe01022c3667f89f26e99223f3948d3
Python
sunsetoversunset/data-mutations
/Indexing/indexer-intersections.py
UTF-8
1,182
2.515625
3
[]
no_license
#!/usr/bin/env python3 import fiona import shapely.geometry import csv import sys import os debug = False def process(f): inFile = f outFileN = "intersections-n.csv" outFileS = "intersections-s.csv" with fiona.open(inFile) as pointsSrc: lineSrc = fiona.open('../Street Data/sunset-single-line.gpkg') for s in lineSrc: # print ("Shape here") lineGeom = shapely.geometry.shape(s['geometry']) with open(outFileN,'w') as outFileN: with open(outFileS,'w') as outFileS: writerN = csv.DictWriter(outFileN, fieldnames=['intersection','index']) writerN.writeheader() writerS = csv.DictWriter(outFileS, fieldnames=['intersection','index']) writerS.writeheader() for s in pointsSrc: if s['geometry'] == None: continue p = shapely.geometry.shape(s['geometry']) t = {} idx = lineGeom.project(p,normalized=True) t['intersection'] = s['properties']['name'] # t['bearing'] = s['properties']['bearing'] t['index'] = idx if s['properties']['south']: writerS.writerow(t) if s['properties']['north']: writerN.writerow(t) for file in sys.argv[1:]: process(file)
true
5296309d359c6e02ef109a704912056cf407afdb
Python
matiasbrunofornero/Products-Tkinter
/index.py
UTF-8
3,304
3.328125
3
[]
no_license
from tkinter import ttk from tkinter import * import sqlite3 class Product: db_name = 'database.db' def __init__(self, window): self.wind = window self.wind.title('Products Application') # Creating a Frame Container frame = LabelFrame(self.wind, text='Register a Product') frame.grid(row=0, column=0, columnspan=3, pady=20) # Name input Label(frame, text='Name: ').grid(row=1, column=0) self.name = Entry(frame) self.name.focus() self.name.grid(row=1, column=1) # Price input Label(frame, text='Price: ').grid(row=2, column=0) self.price = Entry(frame) self.price.grid(row=2, column=1) # Buttons ttk.Button(frame, text='Save Product', command=self.add_product).grid(row=3, columnspan=2, sticky=W + E) # Output Messages self.message = Label(text='', fg='red') self.message.grid(row=3, column=0, columnspan=2, sticky=W + E) # Table self.tree = ttk.Treeview(height=10, columns=2) self.tree.grid(row=4, column=0, columnspan=2) self.tree.heading('#0', text='Name', anchor=CENTER) self.tree.heading('#1', text='Price', anchor=CENTER) # Buttons (Edit and Delete) ttk.Button(text='Delete', command=self.delete_product).grid(row=5, column=0, sticky=W + E) ttk.Button(text='Edit').grid(row=5, column=1, sticky=W + E) self.get_products() def run_query(self, query, parameters=()): with sqlite3.connect(self.db_name) as conn: cursor = conn.cursor() result = cursor.execute(query, parameters) conn.commit() return result def get_products(self): # Cleaning table records = self.tree.get_children() for element in records: self.tree.delete(element) query = 'SELECT * FROM product ORDER BY name DESC' db_rows = self.run_query(query) for row in db_rows: self.tree.insert('', 0, text=row[1], values=row[2]) def validation(self): return len(self.name.get()) != 0 and len(self.price.get()) != 0 def add_product(self): if self.validation(): query = 'INSERT INTO product VALUES(NULL, ?, ?)' parameters = (self.name.get(), self.price.get()) self.run_query(query, parameters) self.message['text'] = 'Product {} added successfully'.format(self.name.get()) self.name.delete(0, END) self.price.delete(0, END) else: self.message['text'] = 'Name or Price are required' self.get_products() def delete_product(self): self.message['text'] = '' try: self.tree.item(self.tree.selection())['text'][0] except IndexError as e: self.message['text'] = 'Please, select a product' return self.message['text'] = '' name = self.tree.item(self.tree.selection())['text'] query = 'DELETE FROM product WHERE name = ?' self.run_query(query, (name,)) self.message['text'] = '{} successfully deleted'.format(name) self.get_products() if __name__ == '__main__': window = Tk() application = Product(window) window.mainloop()
true
13f5c2f10381d57983b836f83c219fe74fdfb41c
Python
8589/codes
/python/cookbook/strings/variables_to_str.py
UTF-8
1,002
2.96875
3
[]
no_license
class Info: def __init__(self, name, n): self.name = name self.n = n class safesub(dict): def __missing__(self, key): return '{' + key + '}' if __name__ == '__main__': from minitest import * with test("format"): s = '{name} has {n} messages.' s.format(name='Guido', n=37).must_equal('Guido has 37 messages.') name = 'Guido' n = 37 # format_map for python3 # s.format_map(vars()).must_equal('Guido has 37 messages.') s.format(**vars()).must_equal('Guido has 37 messages.') # vars().pp() a = Info('Guido',37) vars(a).must_equal({'n': 37, 'name': 'Guido'}) s.format(**vars(a)).must_equal('Guido has 37 messages.') # del a.n # vars(a).must_equal({ 'name': 'Guido'}) # s.format(**vars(a)).must_equal('Guido has 37 messages.') # del n # s.format(**safesub(vars())).must_equal('Guido has 37 messages.') pass
true
8b3fbee9b4ab861616bdef95b1fa60cc2356c124
Python
hypothesis/h
/tests/h/paginator_test.py
UTF-8
9,206
2.84375
3
[ "BSD-2-Clause", "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
from unittest import mock import pytest from webob.multidict import NestedMultiDict from h.paginator import paginate, paginate_query class TestPaginate: def test_current_page_defaults_to_1(self, pyramid_request): """If there's no 'page' request param it defaults to 1.""" pyramid_request.params = {} page = paginate(pyramid_request, 600, 10) assert page["cur"] == 1 @pytest.mark.parametrize( "page_param,expected", [ # If the current page is the first page. ("1", [1, 2, 3, 4, "...", 60]), # If the current page is the last page. ("60", [1, "...", 57, 58, 59, 60]), # If the current page is in the middle. ("30", [1, "...", 27, 28, 29, 30, 31, 32, 33, "...", 60]), # If the current page is near the first page. ("2", [1, 2, 3, 4, 5, "...", 60]), # If the current page is near the last page. ("59", [1, "...", 56, 57, 58, 59, 60]), ], ) def test_numbers_large_result_set(self, pyramid_request, page_param, expected): pyramid_request.params = {"page": page_param} assert paginate(pyramid_request, 600, 10)["numbers"] == expected @pytest.mark.parametrize( "page_param,expected", [ # If the current page is the first page. ("1", [1, 2, 3, 4, 5]), # If the current page is the last page. ("5", [1, 2, 3, 4, 5]), # If the current page is in the middle. ("3", [1, 2, 3, 4, 5]), ], ) def test_numbers_small_result_set(self, pyramid_request, page_param, expected): pyramid_request.params = {"page": page_param} assert paginate(pyramid_request, 50, 10)["numbers"] == expected @pytest.mark.parametrize( "page_param,expected", [ # Normally the current page just comes directly from the request's # 'page' param. ("32", 32), # If the 'page' param is less than 1 the current page is clipped to 1. ("-3", 1), ("0", 1), # If the 'page' param isn't a number the current page defaults to 1. ("foo", 1), # If the 'page' param is greater than the number of pages the current # page is clipped to the number of pages. ("100", 60), ], ) def test_current_page(self, pyramid_request, page_param, expected): pyramid_request.params = {"page": page_param} page = paginate( pyramid_request, # With 600 items in total and 10 items per page there are 60 pages. 600, 10, ) assert page["cur"] == expected @pytest.mark.parametrize( "total,page_size,expected", [ # Normally 'max' is just total / page_size. (600, 10, 60), # Total doesn't divide evenly into page_size. (605, 10, 61), # If total is less than page size there should be one page. (6, 10, 1), ], ) def test_max(self, pyramid_request, total, page_size, expected): assert paginate(pyramid_request, total, page_size)["max"] == expected @pytest.mark.parametrize( "page_param,expected", [ # Normally 'next' is simply the current page + 1. ("32", 33), # If the current page is the last page then 'next' is None. ("60", None), ], ) def test_next(self, pyramid_request, page_param, expected): pyramid_request.params = {"page": page_param} assert paginate(pyramid_request, 600, 10)["next"] == expected @pytest.mark.parametrize( "page_param,expected", [ # Normally 'prev' is simply the current page - 1. ("32", 31), # If the current page is the first page then 'prev' is None. ("1", None), ], ) def test_prev(self, pyramid_request, page_param, expected): pyramid_request.params = {"page": page_param} assert paginate(pyramid_request, 600, 10)["prev"] == expected @pytest.mark.parametrize( "params,expected", [ # Normally url_for() just replaces the 'page' param with the requested # new page number. ([{"page": "32"}], {"page": 26}), # If there is no 'page' param it just adds a 'page' param for the # requested page. ([{}], {"page": 26}), # Existing query params (other than 'page') should be preserved. ( [{"q": "user:jeremydean", "foo": "bar"}], {"q": ["user:jeremydean"], "foo": ["bar"], "page": 26}, ), ( [{"q": "user:jeremydean", "foo": "bar", "page": "32"}], {"q": ["user:jeremydean"], "foo": ["bar"], "page": 26}, ), # Repeated params should be preserved. ([{"foo": "one"}, {"foo": "two"}], {"foo": ["one", "two"], "page": 26}), ], ) def test_url_for(self, pyramid_request, params, expected): pyramid_request.params = NestedMultiDict(*params) pyramid_request.current_route_path = mock.Mock(spec_set=["__call__"]) url_for = paginate(pyramid_request, 600, 10)["url_for"] url = url_for(page=26) # Request the URL for page 26. pyramid_request.current_route_path.assert_called_once_with(_query=expected) assert url == pyramid_request.current_route_path.return_value @pytest.mark.usefixtures("paginate") class TestPaginateQuery: # The current page that will be returned by paginate(). CURRENT_PAGE = 3 # The page_size argument that will be passed to paginate_query(). PAGE_SIZE = 10 def test_it_calls_the_wrapped_view_callable( self, pyramid_request, view_callable, wrapped ): """It calls the wrapped view callable to get the SQLAlchemy query.""" wrapped(mock.sentinel.context, pyramid_request) view_callable.assert_called_once_with(mock.sentinel.context, pyramid_request) def test_it_calls_paginate(self, paginate, pyramid_request, wrapped): """It calls paginate() to get the paginator template data.""" wrapped(mock.sentinel.context, pyramid_request) paginate.assert_called_once_with( pyramid_request, mock.sentinel.total, self.PAGE_SIZE ) def test_it_offsets_the_query(self, wrapped, pyramid_request, query): """ It offsets the query by the correct amount. It offsets the query so that only the results starting from the first result that should be shown on the current page (as returned by paginate()) are fetched from the db. """ wrapped(mock.sentinel.context, pyramid_request) # The current page is 3, and there are 10 results per page, so we # would expect the 20 first results (the first two pages) to be offset. query.offset.assert_called_once_with(20) def test_it_limits_the_query(self, wrapped, pyramid_request, query): """ It limits the query by the correct amount. It limits the query so that only the results up to the last result that should be shown on the current page are fetched from the db. """ wrapped(mock.sentinel.context, pyramid_request) query.limit.assert_called_once_with(self.PAGE_SIZE) def test_it_returns_the_query_results(self, wrapped, pyramid_request): results = wrapped(mock.sentinel.context, pyramid_request)["results"] assert results == mock.sentinel.all def test_it_returns_the_total(self, wrapped, pyramid_request): total = wrapped(mock.sentinel.context, pyramid_request)["total"] assert total == mock.sentinel.total def test_it_returns_the_paginator_template_data( self, wrapped, paginate, pyramid_request ): page = wrapped(mock.sentinel.context, pyramid_request)["page"] assert page == paginate.return_value @pytest.fixture def paginate(self, patch): return patch("h.paginator.paginate", return_value={"cur": self.CURRENT_PAGE}) @pytest.fixture def query(self): """Return a mock SQLAlchemy Query object.""" mock_query = mock.Mock(spec_set=["count", "offset", "limit", "all"]) mock_query.count.side_effect = lambda: mock.sentinel.total mock_query.offset.side_effect = lambda n: mock_query mock_query.limit.side_effect = lambda n: mock_query mock_query.all.side_effect = lambda: mock.sentinel.all return mock_query @pytest.fixture def view_callable(self, query): """Return a mock view callable for paginate_query() to wrap.""" view_callable = mock.Mock(return_value=query, spec_set=["__call__", "__name__"]) view_callable.__name__ = "mock_view_callable" return view_callable @pytest.fixture def wrapped(self, view_callable): """Return a mock view callable wrapped in paginate_query().""" return paginate_query(view_callable, self.PAGE_SIZE)
true
7ed7e99d239e416f176efe2ca9bcde677188afbf
Python
Eliacim/Checkio.org
/Python/Incinerator/The-warriors.py
UTF-8
2,577
4.1875
4
[]
no_license
''' https://py.checkio.org/en/mission/the-warriors/ I'm sure that many of you have some experience with computer games. But have you ever wanted to change the game so that the characters or a game world would be more consistent with your idea of the perfect game? Probably, yes. In this mission (and in several subsequent ones, related to it) youโ€™ll have a chance "to sit in the developer's chair" and create the logic of a simple game about battles. Let's start with the simple task - one-on-one duel. You need to create the class Warrior, the instances of which will have: 2 parameters - health (equal to 50 points) and attack (equal to 5 points) 1 property - is_alive, which can be True (if warrior's health is > 0) or False (in the other case). In addition you have to create the second unit type - Knight, which should be the subclass of the Warrior but have the increased attack - 7. Also you have to create a function fight(), which will initiate the duel between 2 warriors and define the strongest of them. The duel occurs according to the following principle: Every turn, the first warrior will hit the second and this second will lose his health in the same value as the attack of the first warrior. After that, if he is still alive, the second warrior will do the same to the first one. The fight ends with the death of one of them. If the first warrior is still alive (and thus the other one is not anymore), the function should return True, False otherwise. Input: The warriors. Output: The result of the duel (True or False). Precondition: 2 types of units All given fights have an end (for all missions). ''' class Warrior: def __init__(self): self.health = 50 self.attack = 5 def attacked(self, unit): self.health -= unit.attack if unit.is_alive else 0 @property def is_alive(self): return self.health > 0 class Knight(Warrior): def __init__(self): self.health = 50 self.attack = 7 def fight(unit_1, unit_2): while unit_1.is_alive and unit_2.is_alive: unit_2.attacked(unit_1) unit_1.attacked(unit_2) return unit_1.is_alive if __name__ == '__main__': chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) is True assert fight(dave, carl) is False assert chuck.is_alive is True assert bruce.is_alive is False assert carl.is_alive is True assert dave.is_alive is False assert fight(carl, mark) is False assert carl.is_alive is False
true
d1e3abda9585ad5ea89939937c81faabc84bee5b
Python
AlbertFutureLab/OpenSentiment
/IntegratedTSA/test/haha.py
UTF-8
2,134
2.703125
3
[]
no_license
from tensorflow import keras import tensorflow as tf import numpy as np class MyModel(keras.Model): def __init__(self, num_classes=10, *args, **kwargs): print(args, kwargs) super(MyModel, self).__init__(name='my_model', *args, **kwargs) self.num_classes = num_classes self.dense_1 = tf.layers.Dense(units=30, activation='relu') self.dense_2 = tf.layers.Dense(units=num_classes, activation='softmax') # Define your layers here. # self.x, self.y = inputs def call(self, inputs): # Define your forward pass here, # using layers you previously defined (in `__init__`). x, y = inputs x = self.dense_1(x + y) # x = self.dense_1(inputs) x = self.dense_2(x) return x def compute_output_shape(self, input_shape): # You need to override this function if you want to use the subclassed model # as part of a functional-style model. # Otherwise, this method is optional. shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.num_classes return tf.TensorShape(shape) data = np.random.random((100, 30)).astype(np.float32) data = (data, data) label = np.random.random((100, 10)).astype(np.float32) val_data = np.random.random((50, 30)).astype(np.float32) val_data = (val_data, val_data) val_label = np.random.random((50, 10)).astype(np.float32) train_dataset = tf.data.Dataset.from_tensor_slices((data, label)).batch(100).repeat() train_dataset_1 = tf.data.Dataset.from_tensor_slices((data, label)).batch(100).repeat() dev_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_label)).batch(50).repeat() inputinputs = (tf.keras.Input(shape=[None, 30], name='x'), tf.keras.Input(shape=[None, 30], name='y')) tf.keras.backend.set_session(session=tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)))) model = MyModel(num_classes=10) model.compile(optimizer=tf.train.GradientDescentOptimizer(0.5), loss='categorical_crossentropy', metrics=['accuracy']) print(model.built) model.fit(train_dataset, epochs=200, steps_per_epoch=1000, validation_data=train_dataset, validation_steps=1000)
true
e95e097a6f0183ba62469363450d186d4a28665d
Python
jaeyun95/Programmers
/level2/level2_ex46.py
UTF-8
889
3.578125
4
[]
no_license
#(46) ๊ด„ํ˜ธ ๋ณ€ํ™˜ def balance_check(p): check = 0 for index,char in enumerate(p): if char == '(': check += 1 else: check -= 1 if check == 0: return index + 1 def right_check(u): check = [u[0]] for char in u[1:]: if len(check) == 0: return False if char == '(': check.append('(') else: check.pop() return True if not len(check) else False def solution(p): if not p or right_check(p): return p u, v = p[:balance_check(p)], p[balance_check(p):] if right_check(u): answer = solution(v) return u + answer else: answer = '(' answer += solution(v) answer += ')' u = list(u[1:-1]) for index in range(len(u)): if u[index] == '(': u[index] = ')' else: u[index] = '(' answer += ''.join(u) return answer
true
3ad0917ea6082036a301ae16667cba12008f24b3
Python
deepthi2105/GFG
/Array/CyclicallyRotateArray.py
UTF-8
127
2.984375
3
[]
no_license
def rotatearr(a): a[:]=a[len(a)-1:]+a[:len(a)-1] return a a=list(map(int,input().split(" "))) print(rotatearr(a))
true
456a823989044276744a3e367dc0b7638bd7430e
Python
hyoretsu/uri-online-judge
/python/beginner/1009.py
UTF-8
143
3.546875
4
[]
no_license
_employeeName = input() fixedSalary = float(input()) salesBonus = float(input()) print(f"TOTAL = R$ {fixedSalary + (salesBonus * 0.15):.2f}")
true
37d6d9c916fcd909ce8fdb82945ed11145d8603c
Python
nathhje/EvolutionaryComputing
/Old/run_results.py
UTF-8
998
2.515625
3
[]
no_license
import sys, os sys.path.insert(0, 'evoman') from environment import Environment from ai_controller import player_controller from operator import itemgetter from smart_functions import * import random import matplotlib.pyplot as plt index = 0 experiment_name = 'dummy_demo' if not os.path.exists(experiment_name): os.makedirs(experiment_name) import glob import errno path = '/Users/Julia/Dropbox/Master/Evolutionary computing/EvolutionaryComputing/bestresults/bestresultsDensitylevel1mutation0.01/*.txt' files = glob.glob(path) for file in files: index += 1 f = open(file, "r") copy = open("output.txt", "w") for line in f: copy.write(line) # initializes environment with ai player using random controller, playing against static enemy env = Environment(experiment_name=experiment_name, player_controller=player_controller(), speed="fastest", enemies = [1]) alle = env.play() with open("run/test.txt", "a") as txt_file: txt_file.write(str(index) + ": " + str(alle) + "\n")
true
beba238cdf8ce68f7a2162fc0a92f244c2ec869d
Python
chain-bot/alert
/firestore/__init__.py
UTF-8
1,168
2.6875
3
[]
no_license
import logging import firebase_admin import os from firebase_admin import credentials, firestore logger = logging.getLogger(__name__) FIRESTORE_JSON = os.getenv('FIRESTORE_ADMIN') if FIRESTORE_JSON is None: logger.warning("LOCAL USE") else: with open("firestore-admin.json", "w") as jsonFile: jsonFile.write(FIRESTORE_JSON) cred = credentials.Certificate('firestore-admin.json') firebase_admin.initialize_app(cred) FIRESTORE_CLIENT = firestore.client() def get_ath_data(exchange: str): doc_ref = FIRESTORE_CLIENT.collection('ATH').document(exchange) return doc_ref.get().to_dict() def set_exchange_ath_data(exchange: str, base: str, quote: str, ath: float): doc_ref = FIRESTORE_CLIENT.collection('ATH').document(exchange) doc_ref.set({base: {quote: ath}}, merge=True) if __name__ == "__main__": from dotenv import load_dotenv import json load_dotenv(dotenv_path='../../.env') TEST_EXCHANGE = 'TEST_EXCHANGE' ath_data = get_ath_data(TEST_EXCHANGE) print(json.dumps(ath_data, indent=2)) set_exchange_ath_data(TEST_EXCHANGE, 'BTC', 'USDT', 1) set_exchange_ath_data(TEST_EXCHANGE, 'ETH', 'BTC', 1)
true
eef3bc8bbff3f27b12d5c539fcfccddf43c38fa2
Python
0xhrsh/rendezvous_with_.py
/writer.py
UTF-8
267
2.875
3
[]
no_license
# data writer import json f = open('data.json','a') print("enter number of data to be added") n=input() #print("n") #n=10 i=0 while i<int(n): print("Enter Accno and Pasw respectively") x =dict(accno=input(),pasw=input()) json.dumps(x) #pprint(json.dumps(x)) i+=1
true
0e9a24d332b2cbf6eddc6b9b7f30f984232c20d2
Python
AsimPoptani/mhealth-playground
/Stuffs/Over_powered_neural_network_model_UF_.py
UTF-8
3,843
2.78125
3
[]
no_license
from helper_functions import mhealth_get_dataset import random import tensorflow as tf import numpy as np from collections import defaultdict # Hyperparameters # This is how many samples per col data_length = 2 # Prep data # Get the dataset dataset=mhealth_get_dataset() # shuffle dataset random.shuffle(dataset) # get 8 training users and 2 test users training_users,test_data = dataset[:6], dataset[6:] training_data_pre = defaultdict(list) test_data_pre =defaultdict(list) counter=0 previous_label=None to_put=[] for user in training_users: for user_data in user['data']: if not previous_label==user_data[23]: counter=1 to_put=[] previous_label=user_data[23] user_data.pop() to_put+=user_data elif previous_label==user_data[23]: counter+=1 user_data.pop() to_put+=user_data if counter == data_length: training_data_pre[previous_label].append(to_put) to_put=[] counter=0 previous_label=None to_put=[] for user in test_data: for user_data in user['data']: if not previous_label==user_data[23]: counter=1 to_put=[] previous_label=user_data[23] user_data.pop() to_put+=user_data elif previous_label==user_data[23]: counter+=1 user_data.pop() to_put+=user_data if counter == data_length: test_data_pre[previous_label].append(to_put) to_put=[] training_data,training_labels=[],[] test_data,test_labels=[],[] def get_one_hot(targets, nb_classes): res = np.eye(nb_classes)[np.array(targets).reshape(-1)] return res.reshape(list(targets.shape)+[nb_classes]) for training_label,training in training_data_pre.items(): for train in training: training_labels.append(int(training_label)) training_data.append(train) training_data=np.array(training_data) for training_label,training in test_data_pre.items(): for train in training: test_labels.append(int(training_label)) test_data.append(train) test_data=np.array(test_data) training_labels_len=len(training_labels) labels=training_labels+test_labels labels=get_one_hot(np.array(labels),13) training_labels=labels[:training_labels_len] test_labels=labels[training_labels_len:] # Okay lets create our model model = tf.keras.models.Sequential([ tf.keras.layers.Dense(data_length*23), # Our input layer tf.keras.layers.Dense(500,activation=tf.keras.activations.relu), # tf.keras.layers.Dense(500), tf.keras.layers.Dense(13,activation=tf.keras.activations.softmax) # Our output layer we have 13 classifcations ]) # Compile our model # model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy']) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(training_data,training_labels,validation_data=(test_data,test_labels),epochs=100) # -9.2305,3.9479,-4.0236,0.10884,-0.058608,3.4836,-7.467,-8.0885,0.24675,-0.78799,-0.21807,0.19791,18.714,5.4366,2.2399,-5.5648,7.5238,0.47255,-0.25051,1.0172,9.3079,-2.787,-15.309,9 # -8.6677,3.5852,-4.5615,-0.054422,0.22606,-0.75304,-7.1983,-5.9716,0.24675,-0.78799,-0.21807,0.25394,7.7039,9.586,-0.92224,-5.7833,9.6692,0.47255,-0.25051,1.0172,4.6822,1.4321,-15.444,9 test_array = np.array([[-9.2305,3.9479,-4.0236,0.10884,-0.058608,3.4836,-7.467,-8.0885,0.24675,-0.78799,-0.21807,0.19791,18.714,5.4366,2.2399,-5.5648,7.5238,0.47255,-0.25051,1.0172,9.3079,-2.787,-15.309,-8.6677,3.5852,-4.5615,-0.054422,0.22606,-0.75304,-7.1983,-5.9716,0.24675,-0.78799,-0.21807,0.25394,7.7039,9.586,-0.92224,-5.7833,9.6692,0.47255,-0.25051,1.0172,4.6822,1.4321,-15.444]]) print(model.predict([test_array])[0][8]*100)
true
494d22d9ee09c62abab7635da3de97c55ab4915b
Python
NeonedOne/Basic-Python
/First Lab (1)/Short Small Talk.py
UTF-8
552
3.5625
4
[]
no_license
# ะะปะตะบัะตะน ะ“ะพะปะพะฒะปะตะฒ, ะณั€ัƒะฟะฟะฐ ะ‘ะกะ‘ะž-07-19 answer = input("ะัƒ ั‡ั‚ะพ, ะบะฐะบ ะฝะฐัั‚ั€ะพะตะฝะธะต?\n") if "ั…ะพั€ะพัˆะตะต" in answer or "ะฟั€ะตะบั€ะฐัะฝะพ" in answer: print("ะžั‚ะปะธั‡ะฝะพ, ัƒ ะผะตะฝั ั‚ะพะถะต ะฒัั‘ ั…ะพั€ะพัˆะพ ))") elif "ะฟะปะพั…ะพ" in answer or "ัƒะถะฐัะฝะพ" in answer: print("ะะธั‡ะตะณะพ, ัะบะพั€ะพ ะฒัั‘ ะฝะฐะปะฐะดะธั‚ัั") elif "!" in answer or "?" in answer: print("ัะผะพั†ะธะพะฝะฐะปัŒะฝะตะฝัŒะบะพ, ะฝะพ ั ะฝะต ะฟะพะฝะธะผะฐั‚ัŒ") else: print("ะพั‚ะฒะตั‚ัŒ ะปะฐะบะพะฝะธั‡ะฝะตะต, ั ะฝะต ะฟะพะฝะธะผะฐั‚ัŒ")
true
5ccc9877ddfcb635e6cac051e2e51043db55178b
Python
beOk91/baekjoon2
/baekjoon9086.py
UTF-8
115
3.328125
3
[]
no_license
n=int(input()) for _ in range(n): text=input() print(text*2 if len(text)==1 else text[0]+text[len(text)-1])
true
197c63e22ff0ed45a1e113018f89564d04467160
Python
KritiBhardwaj/PythonExercises
/functions.py
UTF-8
2,233
4.375
4
[]
no_license
# # Q1 Convert fahrenheit input to celcius # celcius = (fahrenheit - 32)* 5/9 def convert_to_C(input_in_F): temp_in_F = float(input_in_F) celcius = (temp_in_F - 32) * (5/9) print(f"Temperature {temp_in_F}F in celcius is: {celcius: .2f}C ") input_in_F = input("Enter temperature in Fahrenheit: ") convert_to_C(input_in_F) #Q2 Write a program that calculates the mean of a list of numbers def calculate_mean(total_sum, num_items): mean = (total_sum/num_items) print(total_sum) print(num_items) print(mean) number = input("Enter a number:") total_sum = 0 num_items = 0 while number: total_sum = total_sum + int(number) number = input("Enter a number:") num_items +=1 # while number != "": # total_sum = total_sum + int(number) # number = input("Enter a number:") # # if number != "": # # num_items +=1 # num_items +=1 calculate_mean(total_sum, num_items) #q3 function to read csv and format output import csv colour_data = [] def read_csv_file(filepath): with open(filepath) as file: reader = csv.reader(file) for line in reader: colour_data.append(line) return read_csv_file def format_colour_line(colour_data): for row in colour_data: print(f"{row[1].strip():<15}{row[2].strip():<15}{row[4].strip()}") read_csv_file("ReadingWriting/exercise_data/colours_20.csv") format_colour_line(colour_data) #4 groceries = [ ["Baby Spinach", 2.78], ["Hot Chocolate", 3.70], ["Crackers", 2.10], ["Bacon", 9.00], ["Carrots", 0.56], ["Oranges", 3.08] ] total_bill = 0 unit_cost_List = groceries def calculate_cost(unit_price, number_purchase): total_item_cost = unit_price * number_purchase return total_item_cost for item in groceries: unit_price = item[1] number_purchase = int(input(f"How many {item[0]}: ")) unit_cost = round(calculate_cost(unit_price, number_purchase),2) item.append(unit_cost) # print(unit_cost_List) # print() # print(f"====Izzy's Food Emporium====") # for item in newList: # # print(f"{newList[0]:<20} : {newList[1]:2f}") # print(f"{item[0]:<20} : ${item[1]:.2f}") # print('============================') # print(f"{'$':>24}{groceryCost:.2f}")
true
09343f6d188e26b4814842e9d02efcfa1206129a
Python
cqemail/pyda
/is_triangle.py
UTF-8
1,867
4.15625
4
[]
no_license
# -*- coding:utf-8 -*- # __author = 'c08762' """่พ“ๅ…ฅ3ไธชๆ•ฐ๏ผŒๅˆคๆ–ญ่ƒฝๅฆ็ป„ๆˆไธ‰่ง’ๅฝข""" def is_positive(numb): """่พ“ๅ…ฅๅˆๆณ•ๆ€งๆฃ€ๆŸฅ๏ผŒๅฟ…้กป่พ“ๅ…ฅๆญฃๆ•ฐ๏ผŒไธๆ”ฏๆŒ็ง‘ๅญฆ่ฎกๆ•ฐๆณ•""" try: float(numb) except: return False else: if float(numb) <= 0: return False else: return True def is_pythagoras(a, b, c): """็›ด่ง’ไธ‰่ง’ๅฝขๅˆคๆ–ญ""" if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2: return True else: return False num_1 = input("Pls enter the 1st number:\n") while not is_positive(num_1): num_1 = input("That's not a valid number, try again:\n") num_2 = input("Pls enter the 2nd number:\n") while not is_positive(num_2): num_2 = input("That's not a valid number, try again:\n") num_3 = input("Pls enter the 3rd number:\n") while not is_positive(num_3): num_3 = input("That's not a valid number, try again:\n") # ๅฐ†่พ“ๅ…ฅ็š„ๅญ—็ฌฆไธฒ่ฝฌๆขไธบๆ•ฐๅญ—๏ผŒๅนถ็”จcopy่ฟ›่กŒ่ฎก็ฎ— num1 = float(num_1) num2 = float(num_2) num3 = float(num_3) if num1 + num2 > num3 and num2 + num3 > num1 and num1 + num3 > num2: if num1 == num2 == num3: print("{}\n{}\n{}\nๅฏไปฅ็ป„ๆˆ็ญ‰่พนไธ‰่ง’ๅฝข" .format( num_1,num_2,num_3)) elif num1 == num2 or num1 == num3 or num2 == num3: if is_pythagoras(num1,num2,num3): print("{}\n{}\n{}\nๅฏไปฅ็ป„ๆˆ็ญ‰่…ฐ็›ด่ง’ไธ‰่ง’ๅฝข".format(num_1, num_2, num_3)) else: print("{}\n{}\n{}\nๅฏไปฅ็ป„ๆˆ็ญ‰่…ฐไธ‰่ง’ๅฝข".format(num_1, num_2, num_3)) elif is_pythagoras(num1,num2,num3): print("{}\n{}\n{}\nๅฏไปฅ็ป„ๆˆ็›ด่ง’ไธ‰่ง’ๅฝข".format(num_1, num_2, num_3)) else: print("{}\n{}\n{}\nๅฏไปฅ็ป„ๆˆๆ™ฎ้€šไธ‰่ง’ๅฝข".format(num_1, num_2, num_3)) else: print("{}\n{}\n{}\nไธ่ƒฝ็ป„ๆˆไธ‰่ง’ๅฝข".format(num_1, num_2, num_3))
true
0ba95845c9a52d5a6a969bec2b2cdb984ab3183b
Python
USTC-Titanic/webapp
/user.py
UTF-8
9,836
2.5625
3
[]
no_license
import re, random, hashlib, json from string import ascii_letters as letters from page import PageHandler, admin_username from database import Database # ้šๆœบ็”Ÿๆˆ้•ฟๅบฆไธบ 5 ็š„ salt, ็”ฑๅคงๅฐๅ†™ๅญ—ๆฏๆž„ๆˆ def make_salt(length=5): # salt = [] # for i in range(length): # salt.append(random.choice(letters)) # return ''.join(salt) return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(username, password, salt=None): if not salt: salt = make_salt() enc = (username + password + salt).encode('utf-8') # digest is returned as a string object containing only hexadecimal digits passwd_hash = hashlib.sha256(enc).hexdigest() return '%s,%s' % (salt, passwd_hash) def check_pw_hash(username, password, passwd_hash): salt = passwd_hash.split(',')[0] return passwd_hash == make_pw_hash(username, password, salt) class User(object): def __init__(self, form): self.uid = str(form.get('uid')) self.username = form.get('username') self.password = form.get('password') self.nickname = form.get('nickname') self.email = form.get('email') class Record(User): def insert(self): sql = 'insert into users (username, passwd_hash, nickname, email) values (?, ?, ?, ?)' passwd_hash = make_pw_hash(self.username, self.password) args = (self.username, passwd_hash, self.nickname, self.email) record_list = Database().query_db(sql, args) return record_list def retrieve(self): sql = 'select * from users where username = ?' args = (self.username, ) record_list = Database().query_db(sql, args) return record_list def retrieve_all(self): sql = "select uid, username, nickname, email from users where username <> '%s'" % admin_username args = () record_list = Database().query_db(sql, args) resp = [] for record in record_list: resp.append(dict(record)) return json.dumps(resp) def cnt_all(self): sql = 'select count(*) cnt from users' args = () res = Database().query_db(sql, args)[0]['cnt'] return res def update(self): if len(self.password) != 0: sql = 'update users set passwd_hash = ?, nickname = ?, email = ? where username = ?' passwd_hash = make_pw_hash(self.username, self.password) args = (passwd_hash, self.nickname, self.email, self.username) else: sql = 'update users set nickname = ?, email = ? where username = ?' args = (self.nickname, self.email, self.username) record_list = Database().query_db(sql, args) return record_list def update_password(self): sql = 'update users set passwd_hash = ? where username = ?' passwd_hash = make_pw_hash(self.username, self.password) args = (passwd_hash, self.username) record_list = Database().query_db(sql, args) return record_list def delete(self): sql = 'delete from users where username = ?' args = (self.username, ) record_list = Database().query_db(sql, args) return record_list # ๆฃ€ๆŸฅ็”จๆˆทๅใ€ๅฏ†็ ใ€้‚ฎ็ฎฑๆ˜ฏๅฆ็ฌฆๅˆ่ง„ๅˆ™ re_username = re.compile(r'^[a-zA-Z0-9_-]{3,16}$') re_password = re.compile(r'^.{6,16}$') re_nickname = re.compile(r'^.{3,16}$') re_email = re.compile(r'^[\S]+@[\S]+.[\S]+$') def check_valid(form): if 'username' not in form or 'password' not in form or 'nickname' not in form or 'email' not in form: return False elif not re_username.match(form['username']): return False elif not re_password.match(form['password']): return False elif not re_nickname.match(form['nickname']): return False elif not re_email.match(form['email']): return False else: return True # ๆฃ€ๆŸฅ็”จๆˆทๅๆ˜ฏๅฆๅฏ็”จ def check_usable(form): # ๅฆ‚ๆžœๆ•ฐๆฎๅบ“ไธญๅทฒ็ปๅญ˜ๅœจ่ฎฐๅฝ•, ่ฏดๆ˜Ž่ฏฅ็”จๆˆทๅๅทฒ็ป่ขซๅ ็”จไบ† if len(Record(form).retrieve()) > 0: return False else: return True class SignupHandler(PageHandler): def get(self): filename = 'user/signup.html' if self.is_valid_cookies(): return self.redirect_to_target('/') else: return self.render_file(filename) def post(self): form = self.get_form() # ๆฃ€ๆŸฅ็”จๆˆทๅ, ๅฏ†็ , ๆ˜ต็งฐ, ้‚ฎ็ฎฑๆ˜ฏๅฆ็ฌฆๅˆ่ง„ๅˆ™ if check_valid(form) == True: # ๆฃ€ๆŸฅ็”จๆˆทๅๆ˜ฏๅฆๅฏ็”จ if check_usable(form) == True: return self.register(form) else: return self.render('taken') else: return self.render('error') def register(self, form): record = Record(form) record.insert() record_list = record.retrieve() if len(record_list) > 0: record = dict(record_list[0]) user = User(record) # ็™ปๅฝ•ๅนถ่ฎพ็ฝฎ cookie return self.login(user) else: return 'errorio' class SigninHandler(PageHandler): def get(self): filename = 'user/signin.html' if self.is_valid_cookies(): return self.redirect_to_target('/') else: return self.render_file(filename) def post(self): us_form = self.get_form() us_username = us_form.get('username') us_password = us_form.get('password') record_list = Record(us_form).retrieve() if len(record_list) > 0: record = dict(record_list[0]) s_passwd_hash = record.get('passwd_hash') if check_pw_hash(us_username, us_password, s_passwd_hash): user = User(record) # sign in and set cookie return self.login(user) return self.render('error') class SignoutHandler(PageHandler): def get(self): return self.logout() def post(self): return self.logout() class AdminHandler(PageHandler): def is_admin(self): if self.is_valid_cookies(): username = self.get_username() if username == admin_username: return True return False # return True def get(self): filename = 'user/admin.html' # return self.render_file(filename) if self.is_admin(): if self.get_args('q') == 'json': form = {} username = self.get_args('username') if username: form['username'] = username record_list = Record(form).retrieve() resp = [] for record in record_list: resp.append(dict(record)) if len(resp) == 0: resp = 'error' else: resp = json.dumps(resp) else: resp = Record({}).retrieve_all() return self.render(resp) # resp = '{"cnt": "%d",' % record.cnt_all() + '"userlist": %s}' % record.retrieve_all() # resp = Record({}).cnt_all() # resp = Record({}).retrieve_all() else: return self.render_file(filename) return self.redirect_to_target('/signin') # CRUD def post(self): filename = 'user/admin.html' return self.render_file(filename) if self.is_admin(): ''' do restful crud post -- create get --- retrieve, select put --- update delete --- delete param ?limit=10 --- ๆŒ‡ๅฎš่ฟ”ๅ›ž่ฎฐๅฝ•็š„ๆ•ฐ้‡ ''' return self.render('') return self.redirect_to_target('/signin') def put(self): # update try: if self.is_admin(): form = self.get_form() record = Record(form) record.update() return self.render('ok') else: return self.render('error') except Exception as e: return self.render('error') def delete(self): try: if self.is_admin(): username = self.get_args('username') form = {'username': username} record = Record(form) record.delete() return self.render('ok') else: return self.render('error') except Exception as e: return self.render('error') class ProfileHandler(PageHandler): def get(self): filename = 'user/profile.html' return self.render_file(filename) def put(self): us_form = self.get_form() us_username = us_form.get('username') us_old_password = us_form.get('old_password') us_password = us_form.get('password') # TODO: regex user = {'username': us_username} query = Record(user) record_list = query.retrieve() if len(record_list) > 0: record = dict(record_list[0]) s_passwd_hash = record.get('passwd_hash') if check_pw_hash(us_username, us_old_password, s_passwd_hash): query.password = us_password query.update_password() return self.render('ok') return self.render('error') # form = {'username': 'ustcadmin', 'password': 'captainJ', 'nickname': 'admin', 'email': 'admin@ustc.titanic'} # record = Record(form) # record.insert() # form = {'username': 'Alice', 'password': '321456', 'nickname': 'alice', 'email': 'alice@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Bob', 'password': '321456', 'nickname': 'bob', 'email': 'bob@edu.b'} # record = Record(form) # record.insert() # form = {'username': 'Clark', 'password': '321456', 'nickname': 'clark', 'email': 'clark@edu.a'} # record = Record(form) # record.insert() # form = {'username': 'Dirk', 'password': '321456', 'nickname': 'dirk', 'email': 'dirk@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Eva', 'password': '321456', 'nickname': 'eva', 'email': 'eva@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Falcon', 'password': '321456', 'nickname': 'falcon', 'email': 'falcon@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Green', 'password': '321456', 'nickname': 'green', 'email': 'green@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Hilbert', 'password': '321456', 'nickname': 'hilbert', 'email': 'Hilbert@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Isaias', 'password': '321456', 'nickname': 'Isaias', 'email': 'Isaias@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Jack', 'password': '321456', 'nickname': 'Jack', 'email': 'Jack@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Karl', 'password': '321456', 'nickname': 'karl', 'email': 'karl@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Lee', 'password': '321456', 'nickname': 'Lee', 'email': 'lee@edu.c'} # record = Record(form) # record.insert() # form = {'username': 'Melon', 'password': '321456', 'nickname': 'Melon', 'email': 'melon@edu.c'} # record = Record(form) # record.insert()
true
5f9e50bf14ca1c8c17ddafb2314552034e485f0f
Python
jeevitharajasekhar/Python_11_am_Offline
/Day02_Datatypes/Ex2.py
UTF-8
139
2.640625
3
[]
no_license
#list type append mobiles = [ 'Samsung', 'Lg', 'Sony', 'Mi', 'RedMe', 'Vivo', 'Oppo', 'Lg', 'Sony'] mobiles.append('Iphone') print(mobiles)
true
c0c94798a31f304a1afc3601599b95836e72a98e
Python
ane4katv/STUDY
/Basic Algorithms/Bit Manipulation/from_book_5.1_combine_2_binary_range.py
UTF-8
1,153
3.5625
4
[]
no_license
def insert_bin_to_another(N, M, i, j): left_border = ~((1 << j) - 1) right_border = (1 << i) - 1 mask = left_border | right_border obnulenie = N & mask result = obnulenie | M << i return bin(result) print(insert_bin_to_another(221, 10, 2, 6)) """ N, M 32 bit nums i, j bit positions Insert M between i and j of N N 1101 1101 M 10 10 ------------- res: 1110 1001 1. Unset i to j in N: 1101 1101 -> 1100 0001 a. Create a mask out of ones that has โ€˜0โ€™ from i to j and rest are โ€˜1โ€™: 1100 0011 - left border: 1100 0000 ~ (1 << j) - 1 - right border: 0000 0011 (1 << i) - 1 - combining borders left | right: 1100 0000 | 0000 0011 -------------- 1100 0011 b. created mask & N = obnulenie: 1101 1101 & 1100 0011 -------------- 1100 0001 2. obnulenie | M << i = result: 1100 0001 | 0010 1000 --------------- 1110 1001 # unsigned_int = signed_int + 2**32 """
true
71890ef18ba587ca79c15bb75cea4c8cec82a2fd
Python
fog-gates/Markov-Chain-Sentence-Generator
/markov.py
UTF-8
1,094
3.453125
3
[]
no_license
testTxt = "the theremin is theirs, ok? This is a theremin. This is not anything but a theremin." nGrams = [] nextChar = [] import random #Creates the nGram object which stores the necessary information class nGram: def __init__(self, name, count, next): self.ngram = name self.count = count next = [next] self.nextChar = next def __repr__(self): return(str(self.ngram) + "-" + str(self.count) + "-" + str(self.nextChar)) def __eq__(self, other): return self.ngram == other.ngram i = 0 while i < len(testTxt): if i + 3 < len(testTxt): gram = nGram(testTxt[i:i + 3], 1, testTxt[i + 3]) else: break if gram in nGrams: nGrams[nGrams.index(gram)].count += 1 nGrams[nGrams.index(gram)].nextChar.append(testTxt[i + 3]) nGrams.append(gram) else: nGrams.append(gram) i += 3 print(nGrams) k = 0 while k < 10: a = random.randint(0, len(nGrams) - 1) b = random.randint(0, len(nGrams[a].nextChar) - 1) print(nGrams[a].ngram + nGrams[a].nextChar[b]) k += 1
true
a82dbed0dbfcae8accd9f7872871b8d8b59447bc
Python
commaai/panda
/tests/elm_throughput.py
UTF-8
1,030
2.828125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import socket import threading import select class Reader(threading.Thread): def __init__(self, s, *args, **kwargs): super(Reader, self).__init__(*args, **kwargs) self._s = s self.__stop = False def stop(self): self.__stop = True def run(self): while not self.__stop: s.recv(1000) def read_or_fail(s): ready = select.select([s], [], [], 4) assert ready[0], "Socket did not receive data within the timeout duration." return s.recv(1000) def send_msg(s, msg): s.send(msg) res = b'' while not res.endswith(">"): res += read_or_fail(s) return res if __name__ == "__main__": s = socket.create_connection(("192.168.0.10", 35000)) send_msg(s, b"ATZ\r") send_msg(s, b"ATL1\r") print(send_msg(s, b"ATE0\r")) print(send_msg(s, b"ATS0\r")) print(send_msg(s, b"ATSP6\r")) print("\nLOOP\n") while True: print(send_msg(s, b"0100\r")) print(send_msg(s, b"010d\r"))
true
58cd10a448ebd2efeed5077874db310ec42e9a37
Python
LawerenceLee/coding_dojo_projects
/python_stack/hospital.py
UTF-8
1,776
3.625
4
[]
no_license
import hashlib class Patient(): def __init__(self, name, allergies=""): self.name = name self.allergies = allergies self.bed_number = None self.id = hashlib.sha512(name + allergies).hexdigest()[-8:].upper() def __str__(self): return "PATIENT-ID: {}\nNAME: {}\nALLERGIES: {}\nBED No.: {}".format( self.id, self.name, self.allergies, self.bed_number) class Hospital(): patients = [] def __init__(self, name, capacity): self.name = name self.capacity = capacity self.beds = range(1, self.capacity+1) def admit(self, patient): if len(self.patients) == self.capacity: print("Hospital is Full, Sorry") else: patient.bed_number = self.beds.pop() self.patients.append(patient) print("Patient has been successfully admitted") def discharge(self, patient_name): for patient in self.patients: if patient.name == patient_name: self.beds.append(patient.bed_number) self.patients.remove(patient) print("Patient Successfully Discharged") else: print("Patient Not Found") def __str__(self): return "Hospital: {}\nCapacity: {}\nNo. of Patients: {}".format( self.name, self.capacity, len(self.patients) ) joe = Patient("Joe Shmoe") print(joe) bates_hospital = Hospital("Bates Hospital", 2) print(bates_hospital) print("") bates_hospital.admit(joe) print(bates_hospital) print("") print(joe) print("") betty = Patient("Betty") print(betty) print("") bates_hospital.admit(betty) print(bates_hospital) print("") print(betty) print("") bates_hospital.discharge("Joe Shmoe") print(bates_hospital)
true
a3983f2eaa5c87c11ba09a61567c591882829f4f
Python
pedro-f-nogueira/TV-data-analysis
/03_text_mining/gen_t_python_programs.py
UTF-8
1,415
2.8125
3
[]
no_license
# coding=utf-8 """ .. module:: gen_t_python_programs.py :synopsis: This module generates cleans the program description and determines its the language .. moduleauthor:: Pedro Nogueira <pedro.fig.nogueira@gmail.com> """ import os import sys path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if not path in sys.path: sys.path.insert(1, path) del path import utilities.utilities as util import re as re def fix_season(self): """ This function removes the t1, t2... from its input example input -> paramedics t1 output -> paramedics """ self = re.sub('\s+', ' ', self).strip() match = re.findall('.+?(?= t\d|Ep\d| - E p.)', self) if match: return ''.join(match).strip() else: return self.strip() if __name__ == '__main__': print 'Fetching table...' df = util.get_df_from_conn('SELECT * FROM t_programs;') print 'Calculating features' # Removing t1, t2 from the name... df['NAME'] = df['NAME'].apply(fix_season) df['CLEAN_DESCR'] = df.DESCRIPTION.apply(util.review_words) print 'Detecting language...' # Will need to switch the project interpreter... this needs attention df['LANGUAGE'] = df.DESCRIPTION.apply(util.detect_language) print 'Writing the table to the database...' util.write_table_to_my_sql(df, 't_python_programs', 'ALTER TABLE T_PYTHON_PROGRAMS ADD PRIMARY KEY (ID)') print 'Success'
true
ef8d7b56016b415cdb1ca4fb4a74685491ae10d5
Python
NamanBalaji/Python-programs
/Tic Tak Toe.py
UTF-8
2,618
3.515625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 11:07:48 2020 @author: Naman Balaji """ entries =[' ',' ',' ',' ',' ',' ',' ',' ',' '] win = '' player = 'player1' def draw_board(val): print(val[6]+'|'+val[7]+'|'+val[8]) print('-|-|-') print(val[3]+'|'+val[4]+'|'+val[5]) print('-|-|-') print(val[0]+'|'+val[1]+'|'+val[2]) def player_input(): p1marker = '' p2marker = '' while (p1marker != 'X' and p1marker != 'O'): p1marker = input("Player1, what do you choose X or O: ") if p1marker == 'X': p2marker = 'O' else: p2marker = 'X' return [p1marker, p2marker] def handle_turn(player): global marker print(player + "'s turn.") position = input("Choose a position from 1-9: ") valid = False while not valid: while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]: position = input("Choose a position from 1-9: ") position = int(position) - 1 if entries[position] == " ": valid = True else: print("Position already taken.") if player =='player1': entries[position] = markers[0] else: entries[position] = markers[1] draw_board(entries) def check_winner(): global win global markers if entries[0]==entries[1]==entries[2]!=" " or entries[3]==entries[4]==entries[5]!=" " or entries[6]==entries[7]==entries[8]!=" ": if entries[0]== markers[0] or entries[3]== markers[0] or entries[7]== markers[0]: win = 'Player1' else: win = "Player2" elif entries[0]==entries[6]==entries[3]!=" " or entries[4]==entries[1]==entries[7]!=" " or entries[8]==entries[5]==entries[2]!=" ": if entries[0]== markers[0] or entries[4]== markers[0] or entries[8]== markers[0]: win = 'Player1' else: win = "Player2" elif entries[0]==entries[4]==entries[8]!=" " or entries[6]==entries[4]==entries[2]!=" ": if entries[4] == markers[0]: win = 'Player1' else: win = 'Player2' else: if " " not in entries: win = "Tie" print("It's a tie") def change_turn(): global player if player == 'player1': player = 'player2' else: player = 'player1' markers = player_input() draw_board(entries) while win =='': handle_turn(player) check_winner() change_turn() if win!='Tie' and win!='': print(win+' is the winner')
true
e67ff1d116b92f9e367ef24b2254082fd9db4765
Python
stratosgear/eve-swagger
/eve_swagger/definitions.py
UTF-8
1,871
2.734375
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- """ eve-swagger.definitions ~~~~~~~~~~~~~~~~~~~~~~~ swagger.io extension for Eve-powered REST APIs. :copyright: (c) 2016 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from collections import OrderedDict from flask import current_app as app def definitions(): definitions = OrderedDict() for rd in app.config['DOMAIN'].values(): title = rd['item_title'] definitions[title] = _object(rd['schema']) return definitions def _object(schema): props = {} required = [] for field, rules in schema.items(): if rules.get('required') is True: required.append(field) props[field] = _type_and_format(rules) field_def = {} field_def['type'] = 'object' field_def['properties'] = props if len(required): field_def['required'] = required return field_def def _type_and_format(rules): resp = {} map = { 'dict': ('object',), 'list': ('array',), 'objectid': ('string', 'objectid'), 'datetime': ('string', 'date-time'), 'float': ('number', 'float'), } eve_type = rules.get('type') if eve_type is None: return resp type = map.get(eve_type, (eve_type,)) resp['type'] = type[0] if type[0] == 'object': # we don't support 'valueschema' rule if 'schema' in rules: resp.update(_object(rules['schema'])) elif type[0] == 'array': type = 'array' if 'schema' in rules: resp['items'] = _type_and_format(rules['schema']) else: # 'items' is mandatory for swagger, we assume it's a list of # strings resp['items'] = {'type': 'string'} else: try: resp['format'] = type[1] except IndexError: pass return resp
true
b6ff62db13829c24d908adbeb098c45a3d76bdd7
Python
streppneumo/isp
/CellScribe/logic.py
UTF-8
2,013
3.234375
3
[]
no_license
from foundation import Composite, Added from registry import Registered class Logicable(object): # this is an Abstract Base Class def __and__(self, other): return And(self, other) def __rand__(self, other): return self.__and__(other) def __or__(self, other): return Or(self, other) def __ror__(self, other): return self.__or__(other) def __invert__(self): return Not(self) def __str__(self): return self.name class Not(Logicable, Composite): def __init__(self, expr): self.expression = expr def __str__(self): return "Not[{e}]".format(e=str(self.expression)) @property def members(self): return [self.expression] class Junction(Logicable, Composite): def __init__(self, left, right, operator=None): self.left = left self.right = right self.operator = operator @property def members(self): return [self.left, self.right] def __str__(self): return "{op}[{left}, {right}]".format(op=self.operator, left=str(self.left), right=str(self.right)) class Or(Junction): def __init__(self, left, right): Junction.__init__(self, left, right, operator="Or") class And(Junction): def __init__(self, left, right): Junction.__init__(self, left, right, operator="And") class Implication(Composite, Registered, Added): def __init__(self, subject, predicate): self.subject = subject self.predicate = predicate self.register() self.add() @property def members(self): return self.subject.members + self.predicate.members class If(Implication): def __str__(self): return "If[" + str(self.subject) + ", " + str(self.predicate) + "]" class Iff(Implication): def __str__(self): return "Iff[" + str(self.subject) + ", " + str(self.predicate) + "]"
true
8189aa8fdd5a5db89eee2104826a6a7eed4c9d6a
Python
SeonJongYoo/Algorithm
/BOJ/ForCodingTest/Bruteforce-Permutation/BeforPermutation.py
UTF-8
1,294
3.0625
3
[]
no_license
# ์ด์ „ ์ˆœ์—ด # import sys # import itertools as it # # # n = int(sys.stdin.readline().rstrip()) # inp = list(map(int, sys.stdin.readline().rstrip().split())) # ck = False # for i in range(1, n+1): # if i == inp[i-1]: # ck = True # else: # ck = False # break # if ck: # print(-1) # else: # flag = False # seq = [i for i in range(n, 0, -1)] # perm = it.permutations(seq) # for x in perm: # if flag: # for y in x: # print(y, end=" ") # sys.exit(0) # for j in range(n): # if inp[j] == x[j]: # flag = True # else: # flag = False # break # ๊ทœ์น™์„ฑ ์ฐพ๊ธฐ import sys n = int(sys.stdin.readline().rstrip()) inp = list(map(int, sys.stdin.readline().rstrip().split())) for i in range(n-1, -1, -1): if i == 0: print(-1) elif i > 0 and inp[i] < inp[i-1]: idx = 0 for j in range(i, n): if inp[i-1] > inp[j]: idx = j tmp = inp[idx] inp[idx] = inp[i-1] inp[i-1] = tmp arr1 = inp[:i] arr2 = inp[i:] arr2.sort(reverse=True) res = arr1 + arr2 for x in res: print(x, end=" ") break
true
4a171e15bb6f2f3edf088401afa8a0a3464f4fa4
Python
MinCheng123/Python
/leetcode/28 Implement strStr().py
UTF-8
1,225
3.34375
3
[]
no_license
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ ans=0 flag=0 complete=0 if len(haystack)==0 and len(needle)==0: return 0 if len(haystack)==0 or len(needle)>len(haystack) : return -1 for index in range(len(haystack)): index_temp=index if len(haystack)-index >= len(needle): for index2 in range(len(needle)): if haystack[index_temp]== needle[index2]: if flag==0: ans=index index2+=1 index_temp+=1 else: if flag==0: ans=-1 break if index2==len(needle): complete=1 if complete==1: flag=1 return ans stack="aaa" needle="a" abc=Solution() answer=abc.strStr(stack,needle) print(answer)
true
86570fa1ff2ceb6c5241ca33dfed85d2ba67c7b2
Python
switchell1990/Python-Exercises
/stars_diamond_shape_5.py
UTF-8
1,094
4.34375
4
[]
no_license
def star_diamand_shape(n): """ Write a program that produce the following output giving an integer input n. Expected Output: n=1 n=2 n=3 n=4 n=5 n=9 * * * * * * * *** *** *** *** * *** ***** ***** * *** ******* * ********* ******* ***** *** * """ space = n // 2 stars = 1 # outer loop for the number of rows. for row in range(1, n + 1): # inner loop for the number of spaces. for j in range(1, space + 1): for k in range(1, stars + 1): print (count, end = "") else: # Ask for user input for number of rows they would like. n = int(input("Enter a number: ")) # passing n to the function star_diamand_shape(n)
true
652ad6c3772764d7275318dc965bc2ac4ce436c0
Python
mjamesruggiero/tripp
/tripp/dimensionality.py
UTF-8
1,651
3.046875
3
[ "BSD-3-Clause" ]
permissive
import algebra import gradient from functools import partial def direction(w): mag = algebra.magnitude(w) return [w_i / mag for w_i in w] def directional_variance_i(x_i, w): """the variance of the row x_i in the direction determined by w""" return algebra.dot(x_i, direction(w)) ** 2 def directional_variance(X, w): """the variance of the data in the direction determined w""" return sum(directional_variance_i(x_i, w) for x_i in X) def directional_variance_gradient_i(x_i, w): """the contribution of row x_i to the gradient of the direction-w variance""" projection_length = algebra.dot(x_i, direction(w)) return [2 * projection_length * x_ij for x_ij in x_i] def directional_variance_gradient(X, w): return algebra.vector_sum(directional_variance_gradient_i(x_i, w) for x_i in X) def first_principal_component(X): """the direction that maximizes the directional_variance function""" guess = [1 for _ in X[0]] unscaled_maximizer = gradient.maximize_batch( partial(directional_variance, X), partial(directional_variance_gradient, X), guess ) return direction(unscaled_maximizer) def first_principal_component_sgd(X): """there is no 'y' value, so we pass in a vector of Nones and functions that ignore that input""" guess = [1 for _ in X[0]] unscaled_maximizer = gradient.maximize_stochastic( lambda x, _, w: directional_variance_i(x, w), lambda x, _, w: directional_variance_gradient_i(x, w), X, [None for _ in X], guess) return direction(unscaled_maximizer)
true
c30edb19eb8da668da638726ca7d351d0d802ea3
Python
AdamZhouSE/pythonHomework
/Code/CodeRecords/2420/60699/239378.py
UTF-8
290
3.078125
3
[]
no_license
cnt=int(input()) def func(e): while e > 0: if e % 10 == 0: return False e//=10 return True for i in range(1,cnt//2+1): if func(i) and func(cnt-i): list1=[] list1.append(i) list1.append(cnt-i) print(list1) break
true
362086e41eda543491c4e0966bcf5fb22c93fdc1
Python
ninadangchekar96/ga-learner-dsmp-repo
/Census---First-Project-using-Numpy/code.py
UTF-8
1,416
3.34375
3
[ "MIT" ]
permissive
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here data = np.genfromtxt(path,delimiter=",",skip_header=1) census = np.concatenate((data,new_record)) # -------------- #Code starts here age = census[:,0] max_age = np.max(age) min_age = np.min(age) age_mean = np.mean(age) age_std = np.std(age) # -------------- #Code starts here race_0 = census[census[:,2] == 0] race_1 = census[census[:,2] == 1] race_2 = census[census[:,2] == 2] race_3 = census[census[:,2] == 3] race_4 = census[census[:,2] == 4] len_0 = len(race_0) len_1 = len(race_1) len_2 = len(race_2) len_3 = len(race_3) len_4 = len(race_4) race_list = [len_0,len_1,len_2,len_3,len_4] minority_race=race_list.index(min(race_list)) # -------------- #Code starts here senior_citizens = census[census[:,0] > 60] #list of senior working_hours_sum = np.sum(senior_citizens[:,6]) senior_citizens_len = len(senior_citizens) avg_working_hours = working_hours_sum / senior_citizens_len print(avg_working_hours.round(2)) # -------------- #Code starts here high = census[census[:,1] > 10] low = census[census[:,1] <= 10] avg_pay_high = np.mean(high[:,7]) avg_pay_low = np.mean(low[:,7]) print(avg_pay_high.round(2)) print(avg_pay_low.round(2))
true
58fb5fed71fde71f14ce6f9618084309bc19236a
Python
Parthi3610/pandas_workbook
/src/chapter02/c2_df2.py
UTF-8
811
2.9375
3
[]
no_license
import pandas as pd import numpy as np #college = pd.read_csv("C:/Users/preet/PycharmProjects/pandas_workbook/src/data/college.csv") colleges = pd.read_csv("../data/college.csv", index_col="INSTNM") colleges_ugds= colleges.filter(like="UGDS_") print(colleges_ugds) name = "Northwest-Shoals Community College" print(colleges_ugds.loc[name]) print(colleges_ugds.loc[name].round(2)) print((colleges_ugds.loc[name]+.0001).round(2)) colleges_ugds_fin = ( (colleges_ugds + 0.00501) // .01 / 100 ) print(colleges_ugds_fin.head()) print((colleges_ugds_fin+.000001).round(2)) print(colleges_ugds.add(0.00501).floordiv(.01).div(100)) print(colleges_ugds == 0.0333) college_self_comp = colleges_ugds.fillna("") == colleges_ugds.fillna("") print(college_self_comp.all()) print(colleges_ugds.isna().sum())
true
fe283bd2ba37fee9d8bb02ab12f0a62b55f90b3d
Python
SakshamDhiman180/Facial-recognition-system
/faces-train.py
UTF-8
1,857
2.78125
3
[]
no_license
import os from PIL import Image import numpy as np import cv2 import pickle import time BASE_DIR=os.path.dirname(os.path.abspath(__file__))# returning the dir path image_dir = os.path.join(BASE_DIR,"images")# looking for images folder face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml') recognizer= cv2.face.LBPHFaceRecognizer_create() current_id=0 label_ids={} y_labels=[] x_train=[] for root,dirs,files in os.walk(image_dir): #iterating through the images file for file in files: path= os.path.join(root,file)#getting path of the img label = os.path.basename(root).replace(" ","-")#getting label of the img #print(label,path) if not label in label_ids: label_ids[label] = current_id # asigning the no. id to labels current_id += 1 id_= label_ids[label] #print(label_ids) #y_labels.append(label) #x_train.append(path) pil_image=Image.open(path).convert("L") #converting img into grayscale image_array = np.array(pil_image,"uint8")#converting pixel values in numpy array (image to no.) #print(image_array) faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.2 ,minNeighbors=5) for (x,y,w,h) in faces: roi = image_array[y:y+h,x:x+w] x_train.append(roi) y_labels.append(id_) #print(y_labels) #print(x_train) with open("labels.pickle",'wb') as f: #writeing labels in bytes format and saving it in labels.pickle pickle.dump(label_ids, f) recognizer.train(x_train, np.array(y_labels))# training cmd recognizer.save("trainner.yml")#saving the trained data in trainner.yml file print("training done") print("***ALL SET TO RECOGNIZE SOME FaCES***") time.sleep(3.0) print("open * faces.py * file") time.sleep(2.0)
true
63ea0337d8c90851029671e1ba131460a7a3711e
Python
tenebrion/slack_bot
/google_shorten_url.py
UTF-8
723
3.109375
3
[]
no_license
import json import requests import remove_chars from misc import apis # Setting up initial variables API_KEY = apis.google() def return_shorter_url(url): """ This simple method will take a long url and return a short url :param url: :return: """ # found out that the entries were coming over in this format: <http://www.someurl.com> full_url = f"https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}" fixed_url = remove_chars.clean_text(url) payload = {"longUrl": fixed_url} headers = {"content-type": "application/json"} # making a post to google API r = requests.post(full_url, data=json.dumps(payload), headers=headers).json() return f"Short URL: {r['id']}"
true