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
fc77827ccdb3ab5bcdbe3be8055c01ed3823420f
Python
diegofregolente/30-Days-Of-Python
/22_Day_Web_scraping/1.py
UTF-8
966
2.96875
3
[ "Apache-2.0" ]
permissive
import requests from bs4 import BeautifulSoup import pandas as pd import json url = 'https://archive.ics.uci.edu/ml/datasets.php' r = requests.get(url) content = r.content # pegar todo conteudo dessa pagina soup = BeautifulSoup(content, 'lxml') # modificar a leitura para que possamos trabalhar table = soup.find(name='table', border="1", cellpadding="5") # procura a table onde vamos extrair os dados df_full = pd.read_html(str(table))[0] # executa o dataF que gera uma colunaXlinhas df_full.columns = ['Name', 'Data Types', 'Default Task', 'Attribute Types', 'Instances', 'Attributes', 'Year'] # coloca nome nas colunas df_full = df_full.drop(index=0) # exclui a linha com o nome das colunas data_for_json = {'data': df_full.to_dict('records')} # cria um dicionario com a chave data que coloca todos os dados do pandas with open('UCL.json', 'w', encoding='utf-8') as fp: # salva o documento em 1 json fp.write(json.dumps(data_for_json, ensure_ascii=False))
true
f51fff63b4b2974d2d37beccd4132ce4ad85f6ce
Python
sflin/clopper
/src/Distributor.py
UTF-8
8,156
2.671875
3
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 13 10:14:33 2017 @author: selin """ import random import parser from MvnCommitWalker import MvnCommitWalker from MvnVersionWalker import MvnVersionWalker from TestSuite import TestSuite class Distributor(object): """Generates test suite based on strategy defined in json. Output of format: [ [[version-inst1],[tests-inst1]], [[versions-inst2],[tests-inst3]], [[version-inst3],[tests-inst3]], ..., [[versions-instx],[tests-instx]] ] """ def __init__(self, data, strategy=None): self.action = None self.data = data if strategy: self.action = strategy() def get_suite(self): if(self.action): return self.action.get_suite(self) else: raise UnboundLocalError('Exception raised, no such strategyClass!') class VersionDistributor(object): """Version ranges, all tests for 3 instances, generates output of format [[[v1],[None]],[[v2],[None]],[[v3],[None]]]""" def get_target(self, data): kwargs = {'mode':'commit-mode','skip-noncode':False, 'start':None, 'end':None, 'step':None} mapping = {'mode':'--mode', 'skip-noncode':'--skip-noncode', 'start':'--from', 'end':'--to', 'step':'--step'} for key in mapping.keys(): try: kwargs[key] = data['CL-params'][mapping[key]] except KeyError: continue if data['CL-params'].has_key('-b') and data['CL-params']['-b'] == 'versions': backend = MvnVersionWalker(data['CL-params']['-f']) else: backend = MvnCommitWalker(data['CL-params']['-f']) target = backend.generate_version_list(**kwargs) return target def split(self, target, total): x = len(target)/total bigger = len(target)%total suite = TestSuite() [suite.append(target[i*(x+1):(i+1)*(x+1)]) for i in range(bigger)] [suite.append(target[(bigger*(x+1))+i*x:(bigger*(x+1))+(i+1)*x]) for i in range(total - bigger)] random.shuffle(suite) return suite def get_suite(self, instance): suite = TestSuite() result = TestSuite() total_inst = instance.data['total'] target = self.get_target(instance.data) [target.append(None) for x in range(0, total_inst - len(target))] suite = self.split(target, total_inst) result = result.nest(suite, total_inst*[[None]], total_inst) return result class RandomVersionDistributor(object): """Random versions, all tests.""" def get_target(self, data): kwargs = {'mode':'commit-mode','skip-noncode':False, 'start':None, 'end':None, 'step':None} mapping = {'mode':'--mode', 'skip-noncode':'--skip-noncode', 'start':'--from', 'end':'--to', 'step':'--step'} for key in mapping.keys(): try: kwargs[key] = data['CL-params'][mapping[key]] except KeyError: continue if data['CL-params'].has_key('-b') and data['CL-params']['-b'] == 'versions': backend = MvnVersionWalker(data['CL-params']['-f']) else: backend = MvnCommitWalker(data['CL-params']['-f']) target = backend.generate_version_list(**kwargs) return target def split(self, target, total): random.shuffle(target) x = len(target)/total bigger = len(target)%total suite = TestSuite() [suite.append(target[i*(x+1):(i+1)*(x+1)]) for i in range(bigger)] [suite.append(target[(bigger*(x+1))+i*x:(bigger*(x+1))+(i+1)*x]) for i in range(total - bigger)] return suite def get_suite(self, instance): suite = TestSuite() result = TestSuite(content='random') total_inst = instance.data['total'] target = self.get_target(instance.data) [target.append(None) for x in range(0, total_inst - len(target))] suite = self.split(target, total_inst) result = result.nest(suite, total_inst*[[None]], total_inst) return result class TestDistributor(object): """All versions, random tests for 3 instances, generates output of format [[[None],[t1]],[[None],[t2]],[[None],[t3]]]""" def get_target(self, data): if '--tests' in data['CL-params']: if data['CL-params']['-t']=='benchmark': tests = data['CL-params']['--tests'].replace("$","").replace("'", "").split('|') else: tests = data['CL-params']['--tests'].replace("'", "").replace(" ","").split(',') return tests target = parser.parse(data) return target def split(self, target, total): random.shuffle(target) x = len(target)/total bigger = len(target)%total suite = TestSuite() [suite.append(target[i*(x+1):(i+1)*(x+1)]) for i in range(bigger)] [suite.append(target[(bigger*(x+1))+i*x:(bigger*(x+1))+(i+1)*x]) for i in range(total - bigger)] return suite def get_suite(self, instance): suite = TestSuite() result = TestSuite() total_inst = instance.data['total'] target = self.get_target(instance.data) [target.append(None) for x in range(0, total_inst - len(target))] suite = self.split(target, total_inst) result = result.nest(total_inst*[[None]], suite, total_inst) return result class RMIT(object): """Generate Testsuite according to the RMIT-principle.""" def get_versions(self, data): kwargs = {'mode':'commit-mode','skip-noncode':False, 'start':None, 'end':None, 'step':None} mapping = {'mode':'--mode', 'skip-noncode':'--skip-noncode', 'start':'--from', 'end':'--to', 'step':'--step'} for key in mapping.keys(): try: kwargs[key] = data['CL-params'][mapping[key]] except KeyError: continue if data['CL-params'].has_key('-b') and data['CL-params']['-b'] == 'versions': backend = MvnVersionWalker(data['CL-params']['-f']) else: backend = MvnCommitWalker(data['CL-params']['-f']) target = backend.generate_version_list(**kwargs) return target def get_tests(self, data): if '--tests' in data['CL-params']: if data['CL-params']['-t']=='benchmark': tests = data['CL-params']['--tests'].replace("$","").replace("'", "").split('|') else: tests = data['CL-params']['--tests'].replace("'", "").replace(" ","").split(',') return tests target = parser.parse(data) return target def split(self, target, total): random.shuffle(target) x = len(target)/total bigger = len(target)%total suite = TestSuite() [suite.append(target[i*(x+1):(i+1)*(x+1)]) for i in range(bigger)] [suite.append(target[(bigger*(x+1))+i*x:(bigger*(x+1))+(i+1)*x]) for i in range(total - bigger)] return suite def get_suite(self, instance): versions = self.get_versions(instance.data) tests = self.get_tests(instance.data) result = TestSuite(content='random') tuples = [] for v in versions: [tuples.append([v, t]) for t in tests] random.shuffle(tuples) total_inst = instance.data['total'] result = self.split(tuples, total_inst) suite = TestSuite(content='random') for element in result: v = [] t = [] [v.append(item[0]) for item in element] [t.append(item[1]) for item in element] suite.append([v, t]) return suite
true
acf9031e8fa28a8debbb0c6b5165946ad6ed07b5
Python
ankursharma7/100-Days-Of-Code
/Day 8/Project 1/main.py
UTF-8
1,159
4.28125
4
[]
no_license
import random #snake water gun or rock paper scissors def gameWin(you, comp): #If two values are equal declare a tie if comp == you: return None #check for all possibilities when comp choose s elif comp == 's': if you == 'w': return False elif you == 'g': return True #check for all possibilities when comp choose w elif comp == 'w': if you == 'g': return False elif you == 's': return True #check for all possibilities when comp choose g elif comp == 'g': if you == 's': return False elif you == 'w': return True print("Comp Turn = Snake(1), Water(2), Gun(3)?") randNo = random.randint(1 , 3) print(randNo) if randNo == 1: comp = "s" elif randNo == 2: comp = "w" elif randNo == 3: comp = "g" you = input("Your's Turn = Snake(1), Water(2), Gun(3)?") a = gameWin(comp, you) print(f"Computer Choose {comp}") print(f"You Choose {you}") if a == None: print("The Game Is Tie!") elif a: print("You Win!") else: print("You Loose!")
true
c73248891412d702c62f7afd6edf9763eb74f679
Python
Albertchamberlain/DailyScripts
/判断特定值.py
UTF-8
519
3.515625
4
[]
no_license
f = open('x.txt', 'rb') data = int(f.read(1).encode('hex'), 16) print (data) print (bin(data)) mask = 0b11110000 print (mask) res = data & mask print (res) #首先是打开文件,用read()函数读进去一个字节,用16进制进行编码. # 编码之后会变成一个str类型,这时对它进行转换,int()函数可以将一个str转换成int类型. # int()函数的第二个参数代表了进制。 # mask为11110000,我用mask和要处理的字节进行与,可以得到数据前四位的内容
true
7638ffdffbc7119480c1992a3e4c4067fc616d0c
Python
KingJeremyNg/cps305
/lab08/test.py
UTF-8
950
2.984375
3
[]
no_license
import unittest from parserTools import parse class tester(unittest.TestCase): def testEmpty(self): result = parse([]) self.assertEqual(result, []) def testOne(self): result = parse(['1']) self.assertEqual(result, ['1', [], []]) def testFactorial(self): result = parse(['2', '!']) self.assertEqual(result, ['!', ['2', [], []], []]) def testList(self): result = parse([['4', '+', '3'], '*', '7']) self.assertEqual(result, ['*', ['+', ['4', [], []], ['3', [], []]], ['7', [], []]]) def testLongList(self): result = parse([['4', '+', '3'], '*', '7', '+', ['4', '+', [['3', '+', '1'], '!']]]) self.assertEqual(result, ['+', ['*', ['+', ['4', [], []], ['3', [], []]], ['7', [], []]], ['+', ['4', [], []], ['!', ['+', ['3', [], []], ['1', [], []]], []]]]) if __name__ == '__main__': unittest.main(argv=['first-arg-is-ignored'], exit=False)
true
bca33fdae2ebd1fc09ade1bcabf802bcfe140f2c
Python
HarborDong/LeetCode
/Python/210.Course_Schedule_II.py
UTF-8
1,069
3.125
3
[]
no_license
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: self.indegree = [0] * numCourses self.outdegree = {} self.res = [] for pair in prerequisites: if pair[1] in self.outdegree: self.outdegree[pair[1]].append(pair[0]) else: self.outdegree[pair[1]] = [pair[0]] self.indegree[pair[0]] += 1 self.res = [i for i in range(numCourses) if self.indegree[i] == 0] start = 0; end = len(self.res) while start != end: if self.res[start] in self.outdegree: for j in self.outdegree[self.res[start]]: self.indegree[j] -= 1 if self.indegree[j] == 0: self.res.append(j) end += 1 elif self.indegree[j] < 0: return [] start += 1 if end == numCourses: return self.res else: return []
true
e69215e5b3aca7117a5dc3350025d6df94209148
Python
anr96/GoogleNgrams
/FindBigrams.py
UTF-8
3,527
3.671875
4
[]
no_license
import os """ This program determines that if both words of the bigram in the desired input file are found in the English adjectives dictionary, the bigram and its metadata will be added to a list of adjectival bigrams A dictionary of unique adjectival bigrams is subsequently created from the adjectival bigrams list {bigram : occurrences} """ class LingClass(object): # lists for English adjectives and adjectival bigrams, dictionary for unique terms & their count dictionary = [] adj_bigram = [] unique_dictionary = {} # counter variables adj_total = 0 counter = 0 unique_counter = 0 # open bigram file and open the two files that the results will be written to def __init__(self, bigram_file_name): self.bigram_file_name = bigram_file_name self.bigram_file = open(os.path.expanduser('~/Documents/googlebooks-eng-all-2gram-20120701-%s' % bigram_file_name), 'r') self.nonunique_output = open(os.path.expanduser('~/Documents/%s_results_both' % bigram_file_name), 'w') self.unique_output = open(os.path.expanduser('~/Documents/%s_unique' % bigram_file_name), 'w') self.open_dictionary() # opens dictionary of adjectives def open_dictionary(self): dictionary_file = open(os.path.expanduser('~/Documents/clean_dictionary.txt'), 'r') df_lines = dictionary_file.readlines() for phrase in df_lines: self.dictionary.append(phrase.split()[0]) dictionary_file.close() self.check_if_bigram() # if both words in the bigram are in the adjective dictionary, add them to the proper list def check_if_bigram(self): for bigram in self.bigram_file: if (bigram.lower().split()[0] in self.dictionary) and (bigram.lower().split()[1] in self.dictionary): self.adj_bigram.append(bigram) self.non_unique_bigram_list() # write to file the list of adjectival bigrams and total of unique/non-unique phrases def non_unique_bigram_list(self): for i in self.adj_bigram: self.nonunique_output.write(i) print(i) self.adj_total += 1 print(self.adj_total) self.nonunique_output.write("\n\nTotal of adjectival bigrams: ") self.nonunique_output.write(str(self.adj_total) + "\n") self.unique_bigram_list() # write to file only unique items and the total times that phrase occurred def unique_bigram_list(self): for i in self.adj_bigram: bigram = i.lower().split()[0] + " " + i.lower().split()[1] if bigram in self.unique_dictionary: pass else: # set the counter back to 0 for each new adj bigram self.counter = 0 self.counter += 1 self.unique_dictionary[bigram] = self.counter for i in self.unique_dictionary: print(i, ":", self.unique_dictionary[i]) self.unique_output.write(str(i) + ": " + str(self.unique_dictionary[i]) + "\n") self.unique_counter += 1 print(self.unique_counter) self.nonunique_output.write("Total of unique bigrams: ") self.nonunique_output.write(str(self.unique_counter)) self.nonunique_output.close() self.unique_output.write("\nTotal of unique bigrams: ") self.unique_output.write(str(self.unique_counter)) self.unique_output.close() file_name = input("Enter a bigram file to be parsed:\n") file = LingClass(file_name)
true
34d49192f97f53465bc3ba7d970af48efd02c61b
Python
etture/algorithms_practice
/leetcode/102_binary_tree_level_order_traversal/solution.py
UTF-8
3,233
3.125
3
[]
no_license
# Basic imports -------------------------------------------- from __future__ import annotations import sys # 파이썬 기본 재귀 limit이 1000이라고 함 --> 10^6으로 manual하게 설정 sys.setrecursionlimit(10**6) from os.path import dirname, abspath, basename, normpath root = abspath(__file__) while basename(normpath(root)) != 'algo_practice': root = dirname(root) sys.path.append(root) from utils.Tester import Tester, Logger logger = Logger(verbose=False) import pprint pp = pprint.PrettyPrinter() # ---------------------------------------------------------- # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if root is None: return [] level = 0 cur_level, next_level = [root], list() answer = list() cur_level_answer = list() while len(cur_level) > 0: cur_node = cur_level.pop(0) cur_level_answer.append(cur_node.val) if cur_node.left: next_level.append(cur_node.left) if cur_node.right: next_level.append(cur_node.right) if len(cur_level) == 0: answer.append(cur_level_answer) cur_level_answer = list() cur_level = next_level next_level = list() return answer class Helper: def run(self, _input: List[int]) -> List[List[int]]: root_node = None prev_level_nodes = list() cur_level_nodes = list() idx = 0 left_filled = False while idx < len(_input): # print(f'idx: {idx}, prev: {prev_level_nodes}, cur: {cur_level_nodes}') val = _input[idx] if idx == 0: root_node = TreeNode(val) prev_level_nodes.append(root_node) idx += 1 elif len(prev_level_nodes) == 0: prev_level_nodes = cur_level_nodes cur_level_nodes = list() left_filled = False else: node = TreeNode(val) if val is not None else None if not left_filled: prev_level_nodes[0].left = node left_filled = True else: prev_level_nodes[0].right = node prev_level_nodes.pop(0) left_filled = False if node is not None: cur_level_nodes.append(node) idx += 1 sol = Solution() return sol.levelOrder(root_node) if __name__ == '__main__': sol = Helper() test_cases = [ ([[3,9,20,None,None,15,7]], [[3],[9,20],[15,7]]), ([[1]], [[1]]), ([[]], []), ] Tester.factory(test_cases, func=lambda input: sol.run(*input)).run(unordered_output=False)
true
db5e083caade936ad0c0446a7ef480266aadd7b9
Python
alicesilva/P1-Python-Problemas
/1131.py
UTF-8
687
3.40625
3
[]
no_license
#coding: utf-8 cont = 0 cont_inter = 0 cont_gremio = 0 cont_empates = 0 while True: entrada = raw_input() dados = entrada.split() inter = int(dados[0]) gremio = int(dados[1]) print "Novo grenal (1-sim 2-nao)" resposta = int(raw_input()) cont += 1 if inter > gremio: cont_inter += 1 if gremio > inter: cont_gremio += 1 if inter == gremio: cont_empates += 1 if resposta == 2: break print "%d grenais" %cont print "Inter:%d" %cont_inter print "Gremio:%d" %cont_gremio print "Empates:%d" %cont_empates if cont_inter > cont_gremio: print "Inter venceu mais" elif cont_inter < cont_gremio: print "Gremio venceu mais" elif cont_empates != 0: print "Nao houve vencedor"
true
48fa6eda1e93598d1108c8083ee02bd108aa53e3
Python
TheWildMonk/cheap-flight-finder-app-project
/main.py
UTF-8
2,012
2.796875
3
[]
no_license
# Import necessary libraries from data_manager import DataManager from flight_data import FlightData from flight_search import FlightSearch from notification_manager import NotificationManager # Constants DEPARTURE_CITY = "DHAKA" DEPARTURE_CITY_IATA_CODE = "DAC" # Sheety object definition sheet_data_manager = DataManager() sheet_data = sheet_data_manager.sheety_get_response() # Flight data object definition flight_data_manager = FlightData() # Notification Manager object definition notification = NotificationManager() # 1. Update IATA Code of destination cities # 2. Extract lowest flight price for destination cities for each_city in sheet_data["prices"]: if each_city["iataCode"] == "": # Flight search object definition flight_search_manager = FlightSearch(city=each_city["city"]) location_data = flight_search_manager.kiwi_get_location() each_city["iataCode"] = location_data["locations"][0]["code"] sheet_data_manager.sheety_put_request(each_city["iataCode"], each_city["id"]) else: pass # Extract destination city & cheapest flight cost from kiwi API response flight_details = flight_data_manager.flight_search_get_request(iata_code=each_city["iataCode"]) try: outbound_date = (flight_details[0]["route"][0]["local_departure"]).split("T")[0] inbound_date = (flight_details[0]["route"][1]["local_departure"]).split("T")[0] except IndexError: print(f"There's no flight for {each_city['iataCode']}") else: if flight_details: if flight_details[0]["price"] < each_city["lowestPrice"]: notification.send_message(price=flight_details[0]["price"], dep_city=DEPARTURE_CITY, dep_ap_iata_code=DEPARTURE_CITY_IATA_CODE, arr_city=each_city["city"], arr_ap_iata_code=each_city["iataCode"], outbound_date=outbound_date, inbound_date=inbound_date)
true
0cc70fb29c0666b08734f68d44edf38eb94655a4
Python
ArthurDJ/CW1
/assign1.py
UTF-8
6,676
3.25
3
[]
no_license
# MCMCS Coursework 1 # Luc Berthouze 2020-11-01 from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from matplotlib import colors as c import random # Definition of Complex landscape def ComplexLandscape(x, y): return 4 * (1 - x) ** 2 * np.exp(-(x ** 2) - (y + 1) ** 2) - 15 * (x / 5 - x ** 3 - y ** 5) * np.exp( -x ** 2 - y ** 2) - (1. / 3) * np.exp(-(x + 1) ** 2 - y ** 2) - 1 * ( 2 * (x - 3) ** 7 - 0.3 * (y - 4) ** 5 + (y - 3) ** 9) * np.exp(-(x - 3) ** 2 - (y - 3) ** 2) # Definition of gradient of Complex landscape def ComplexLandscapeGrad(x, y): g = np.zeros(2) g[0] = -8 * np.exp(-(x ** 2) - (y + 1) ** 2) * ((1 - x) + x * (1 - x) ** 2) - 15 * np.exp(-x ** 2 - y ** 2) * ( (0.2 - 3 * x ** 2) - 2 * x * (x / 5 - x ** 3 - y ** 5)) + (2. / 3) * (x + 1) * np.exp( -(x + 1) ** 2 - y ** 2) - 1 * np.exp(-(x - 3) ** 2 - (y - 3) ** 2) * ( 14 * (x - 3) ** 6 - 2 * (x - 3) * (2 * (x - 3) ** 7 - 0.3 * (y - 4) ** 5 + (y - 3) ** 9)) g[1] = -8 * (y + 1) * (1 - x) ** 2 * np.exp(-(x ** 2) - (y + 1) ** 2) - 15 * np.exp(-x ** 2 - y ** 2) * ( -5 * y ** 4 - 2 * y * (x / 5 - x ** 3 - y ** 5)) + (2. / 3) * y * np.exp( -(x + 1) ** 2 - y ** 2) - 1 * np.exp(-(x - 3) ** 2 - (y - 3) ** 2) * ( (-1.5 * (y - 4) ** 4 + 9 * (y - 3) ** 8) - 2 * (y - 3) * ( 2 * (x - 3) ** 7 - 0.3 * (y - 4) ** 5 + (y - 3) ** 9)) return g # Definition of Simple landscape def SimpleLandscape(x, y): return np.where(1 - np.abs(2 * x) > 0, 1 - np.abs(2 * x) + x + y, x + y) # Definition of gradient of Simple landscape def SimpleLandscapeGrad(x, y): g = np.zeros(2) if 1 - np.abs(2 * x) > 0: if x < 0: g[0] = 3 elif x == 0: g[0] = 0 else: g[0] = -1 else: g[0] = 1 g[1] = 1 return g # Function to draw a surface (equivalent to ezmesh in Matlab) # See argument cmap of plot_surface instruction to adjust color map (if so desired) def DrawSurface(fig, varxrange, varyrange, function): """Function to draw a surface given x,y ranges and a function.""" ax = fig.gca(projection='3d') xx, yy = np.meshgrid(varxrange, varyrange, sparse=False) z = function(xx, yy) ax.plot_surface(xx, yy, z, cmap='RdBu') # color map can be adjusted, or removed! fig.canvas.draw() return ax # Function implementing gradient ascent def GradAscent(StartPt, NumSteps, LRate): PauseFlag = 1 h = 0 for i in range(NumSteps): # TO DO: Calculate the 'height' at StartPt using SimpleLandscape or ComplexLandscape a = StartPt[0] b = StartPt[1] # z = SimpleLandscape(a, b) z = ComplexLandscape(a, b) # TO DO: Plot point on the landscape # Use a markersize that you can see well enough (e.g., * in size 10) # plt.plot(a, b, z, marker='o', markersize=10) # TO DO: Calculate the gradient at StartPt using SimpleLandscapeGrad or ComplexLandscapeGrad # j = ComplexLandscapeGrad(a, b) j = SimpleLandscapeGrad(a, b) nx = j[0] ny = j[1] # TO DO: Calculate the new point and update StartPt mx = a + LRate * nx my = b + LRate * ny StartPt[0] = mx StartPt[1] = my # Ensure StartPt is within the specified bounds (un/comment relevant lines) StartPt = np.maximum(StartPt, [-2, -2]) StartPt = np.minimum(StartPt, [2, 2]) # StartPt = np.maximum(StartPt, [-3, -3]) # StartPt = np.minimum(StartPt, [7, 7]) if z >= 4: h = 1 Z.append(1) X.append(i) break if h == 0: Z.append(0) # Pause to view output '''if PauseFlag: x = plt.waitforbuttonpress()''' # TO DO: Mutation function # Returns a mutated point given the old point and the range of mutation def Mutate(OldPt, MaxMutate): # TO DO: Select a random distance MutDist to mutate in the range (-MaxMutate,MaxMutate) MutatedPt = OldPt m = random.uniform(-MaxMutate, MaxMutate) n = random.randint(0, 1) # TO DO: Randomly choose which element of OldPt to mutate and mutate by MutDist if n == 1: MutatedPt[0] += m else: MutatedPt[1] += m return MutatedPt # Function implementing hill climbing def HillClimb(StartPt, NumSteps, MaxMutate): PauseFlag = 1 h = 0 for i in range(NumSteps): # TO DO: Calculate the 'height' at StartPt using SimpleLandscape or ComplexLandscape a, b = StartPt z = ComplexLandscape(a, b) # z = SimpleLandscape(a, b) # TO DO: Plot point on the landscape # Use a markersize that you can see well enough (e.g., * in size 10) # plt.plot(a, b, z, marker='o', markersize=10) # Mutate StartPt into NewPt NewPt = Mutate(np.copy(StartPt), MaxMutate) # Use copy because Python passes variables by references (see Mutate function) # Ensure NewPt is within the specified bounds (un/comment relevant lines) NewPt = np.maximum(NewPt, [-2, -2]) NewPt = np.minimum(NewPt, [2, 2]) # NewPt = np.maximum(NewPt,[-3,-3]) # NewPt = np.minimum(NewPt,[7,7]) # TO DO: Calculate the height of the new point e = NewPt[0] f = NewPt[1] g = ComplexLandscape(e, f) # g = SimpleLandscape(e, f) # TO DO: Decide whether to update StartPt or not if g > z: StartPt = NewPt if z >= 4: h = 1 Z.append(1) X.append(i) break if h == 0: Z.append(0) # Pause to view output if PauseFlag: x = plt.waitforbuttonpress() # Template # Plot the landscape (un/comment relevant line) # plt.ion() # fig = plt.figure() # ax = DrawSurface(fig, np.arange(-2,2.025,0.025), np.arange(-2,2.025,0.025), SimpleLandscape) # ax = DrawSurface(fig, np.arange(-3,7.025,0.025), np.arange(-3,7.025,0.025), ComplexLandscape) # Enter maximum number of iterations of the algorithm, learning rate and mutation range NumSteps = 50 LRate = 0.1 MaxMutate = 1 global Z, X Z = [] X = [] # TO DO: choose a random starting point with x and y in the range (-2, 2) for simple landscape, (-3,7) for complex landscape '''x = random.randrange(-2, 2) y = random.randrange(-2, 2) x = random.randrange(-3, 7) y = random.randrange(-3, 7) StartPt = [] StartPt.append(x) StartPt.append(y)''' # Find maximum (un/comment relevant line) # GradAscent(StartPt,NumSteps,LRate) # HillClimb(StartPt,NumSteps,MaxMutate)
true
f05d33c6c43c2b68077f76fd53632a832e6e7128
Python
AlbertGithubHome/Bella
/python/feature_test.py
UTF-8
195
3.21875
3
[]
no_license
#feature test # 1, 3, 5, 7,...,21 L = [] n = 1 while n <= 21: L.append(n) n = n + 2 print(L) L2 = list(range(1, 22, 2)) print('L2 =', L2) L3 = list(range(22))[1::2] print('L3 =', L3)
true
4ce3ad4f422af0f428eabf37b80303bdc6238ce8
Python
kyhoon001/Linux-Class
/raspberryPi/light/sw-led-blink.py
UTF-8
408
3.109375
3
[]
no_license
import RPi.GPIO as GPIO import time LED,SW = 18,4 GPIO.setmode(GPIO.BCM) GPIO.setup(LED,GPIO.OUT) GPIO.setup(SW, GPIO.IN,pull_up_down = GPIO.PUD_DOWN) print("Press the button") while True : GPIO.output(LED,False) if GPIO.input(SW)==GPIO.HIGH: print("Button pressed!") GPIO.output(LED,True) time.sleep(1) print("Press the button (CTRL-C to exit)") GPIO.cleanup()
true
e017308c22c5f145775fb5cf8fa9542e15ecaa90
Python
chodges11/Assignment_05
/CDInventory.py
UTF-8
4,575
3.640625
4
[]
no_license
# ------------------------------------------# # Title: CDInventory.py # Desc: Starter Script for Assignment 05 # Change Log: (Who, When, What) # Charles Hodges(hodges11@uw.edu), 2021-Aug-08, Created File # ------------------------------------------# # Variables dctRow = {} # Dictionary data row. lstTbl = [] # List of dictionaries to hold data. objFile = None # file object. strChoice = '' # User input. # Strings keyArtist = 'Artist' keyId = 'ID' keyTitle = 'Title' strAdd = 'a' strAddSuccessMsg = 'Added a CD to the inventory.' strArtistName = 'Enter the Artist\'s Name: ' strCdTitle = 'Enter the CD\'s Title: ' strCdWasDeletedMsg = "CD with ID {} was deleted." strDelete = 'd' strDeleteById = "Which CD would you like to remove? Indicate using 'ID': " strDisplay = 'i' strEnterId = 'Enter an ID#: ' strErrorMsg = 'Please choose either l, a, i, d, s or x!' strExit = 'x' strFileName = 'CDInventory.txt' strInputHdr = '\nThe Magic CD Inventory' strLoad = 'l' strLoadSuccessMsg = 'Loading complete.' strMenu1 = """ [l] Load Inventory from file(*This will overwrite any unsaved data*) [a] Add CD [i] Display Current Inventory [d] Delete CD from Inventory [s] Save Inventory to file [x] exit """ strMenuOptions = 'l, a, i, d, s, or x: ' strRead = 'r' strSave = 's' strSaveSuccessMsg = 'Saved to text file.' strWrite = 'w' # Get user Input print(strInputHdr) while True: # Display menu allowing the user to choose usage intent. print(strMenu1) # convert choice to lower case at time of input. strChoice = input(strMenuOptions).lower() print() # Empty line for readability. # Exit the program. if strChoice == strExit: break # Load existing data. if strChoice == strLoad: # If the file does not yet exist, create it, to avoid # a FileNotFoundError. This will NOT overwrite # the current data, if it exists already. text_file = open(strFileName, strAdd) text_file.close() # Reset the Table first lstTbl = [] # Then load data from text file. with open(strFileName, strRead) as objFile: for row in objFile: lstRow = row.strip().split(',') dicRow = { 'ID': int(lstRow[0]), 'Title': lstRow[1], 'Artist': lstRow[2] } lstTbl.append(dicRow) print(strLoadSuccessMsg) print() # Empty line for readability # Add data to the table. elif strChoice == strAdd: intId = int(input(strEnterId)) strTitle = input(strCdTitle) strArtist = input(strArtistName) dctRow = {keyId: intId, keyTitle: strTitle, keyArtist: strArtist} lstTbl.append(dctRow) print() # Empty line for readability print(strAddSuccessMsg) print() # Empty line for readability # Display the current data to the user. elif strChoice == strDisplay: print("{: <5} {: <20} {: <20}".format("ID", "| Title", "| Artist")) print("{: <5} {: <20} {: <20}".format("--", "| -----", "| ------")) counter = 0 for row in lstTbl: dctRowToLst = list(lstTbl[counter].values()) lstToStr = ','.join([str(elem) for elem in dctRowToLst]) split_lines = lstToStr.split(",") id_num, title, artist = split_lines print("{: <5} {: <20} {: <20}".format ( id_num, "| " + title, "| " + artist) ) counter += 1 print() # Empty line for readability. # Delete an entry elif strChoice == strDelete: deleteId = int(input(strDeleteById)) for items in range(len(lstTbl)): if lstTbl[items]['ID'] == deleteId: del lstTbl[items] print(strCdWasDeletedMsg.format(deleteId)) break print() # Empty line for readability. # Save the data to a text file. elif strChoice == strSave: with open(strFileName, strWrite) as objFile: counter = 0 for row in lstTbl: idNum, title, artist = lstTbl[counter].values() objFile.write(str(idNum) + ',' + title + "," + artist + '\n') counter += 1 print(strSaveSuccessMsg) print() # Empty line for readability. else: print(strErrorMsg)
true
629096e4ce1753459f2829635c3139f19a3a582a
Python
lovemonkey257/dfir-tools
/json-to-elastic/import-to-es.py
UTF-8
1,334
2.828125
3
[]
no_license
#! /usr/bin/python import os import json import sys import argparse from datetime import datetime from elasticsearch import Elasticsearch def parse_date(utcTime,fmt): return datetime.strptime(utcTime, fmt) def from_iso8601(utcTime): return parse_date(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ") def from_epoch(epoch): return datetime.fromtimestamp(float(epoch)) def isodate(d): return d.isoformat('T') parser = argparse.ArgumentParser(description='Import JSON docs into Elasticsearch') parser.add_argument('--index', help='Elastic Index to use') parser.add_argument('--estype', help='Elastic type (_type)') args = parser.parse_args() es_index_name = args.index es_doc_type = args.estype es = Elasticsearch() c=0 print "Import starts.." for json_str in sys.stdin: j = json.loads(json_str) ### Modify/Add to your JSON here ### For example ES is picky about dates - use the included routines to munge dates into correct format ### From an epoch: isodate(from_epoch(doc["my_epoch_date"])) ### From a string formatted as DD-MM-YYYY try: isodate(parse_date("20-02-1997","%d-%m-%Y")) try: es.index(index=es_index_name, doc_type=es_doc_type, timeout=60, body=j) except Exception,e: print e pass finally: c=c+1 print "Import finished. ",c," records imported"
true
a4fd0d1a9c70833eaecfff2664ecf11a6262d532
Python
mertkanyener/Exercises
/decode_web.py
UTF-8
446
3.21875
3
[]
no_license
import requests from bs4 import BeautifulSoup #loading content from the desired URL base_url = 'http://www.nytimes.com' r = requests.get(base_url) #Decoding webpage soup = BeautifulSoup(r.text) #find and loop through all elements on the page with the #class name "story-heading" for i in soup.find_all(class_="story-heading"): if i.a: print(i.a.text.replace("\n", " ").strip()) else: print(i.contents[0].strip())
true
cb0569ccdd15ae1146ff67f5587d48fa9a47202c
Python
hburne11/Burnell_H_python-data
/data/barchart2.py
UTF-8
367
3.3125
3
[ "MIT" ]
permissive
import matplotlib.pyplot as plt gender = ['Men', 'Women'] medals = [281, 179] width = 0.35 x_labels = [0, 50, 100, 150, 200] y_labels = ['Men', 'Women'] plt.xlabel("Gender") plt.ylabel("Medals") plt.bar(gender, medals) plt.show()
true
8e45b8738dc065cc6ed614ce20ca3642d4c05f33
Python
AdamDzierzko/CS50
/w7-movies, houses/houses/roster.py
UTF-8
751
3.1875
3
[]
no_license
import csv import sys from cs50 import SQL if len(sys.argv) != 2: # check start print("error") sys.exit(1) db = SQL("sqlite:///students.db") house = sys.argv[1] # house name data = db.execute("SELECT * FROM students WHERE house = ? ORDER BY last, first", house) # select from db l = len(data) for i in range(l): if(data[i]["middle"] == None): # if middle is none print(data[i]["first"] + " " + data[i]["last"] + ", born " + str(data[i]["birth"])) else: # with middle name print(data[i]["first"] + " " + data[i]["middle"] + " " + data[i]["last"] + ", born " + str(data[i]["birth"])) # TODO
true
d3108b427338961451413b4ffab71e3c841ec2c1
Python
frmsaul/pyh3
/h3/node.py
UTF-8
1,583
3.359375
3
[ "MIT" ]
permissive
import collections import json from h3math import Point4d """ The node structure storing all attributes of a tree node. """ class Node(object): """ The node constructor. :param int node_id: the id of node in the node lookup table in tree object :param int parent_id: the id of parent node in the node lookup table in tree object, default None :param int depth: the depth of this node in the tree, deault 0 :param int tree_size: the subtree size of the node, ie. the number of nodes blow this node, default 1 :param float radius: the node's hemisphere radius, ie. the distance to its children, default 0 :param float area: the node's hemisphere area, default 0 :param int band: the band which the node's hemisphere is placed in its parent's hemisphere, default -1 :param float theta: the angle of the node's hemisphere rotating around Z axis in spherical space, default 0 :param float phi: the angle between the node and Z axis in spherical space, default 0 :param Point4d coord: the node's 3D coordinate in cartesisan space, default to Point4d(0,0,0,0) """ def __init__(self, node_id, parent_id=None, depth=0, tree_size=1, radius=0, area=0): self.node_id = node_id self.children = set() self.parent = parent_id self.depth = depth self.tree_size = tree_size self.radius = radius self.area = area self.band = -1 self.theta = 0 self.phi = 0 self.coord = Point4d() def __repr__(self): return "<{0}>".format(self.node_id)
true
641fbe324aa4b7af08ac169c3009a03c9df2809c
Python
My-Students/Echo-UDP-Client-Server
/Bagnis/00021_serverECHOUDP.py
UTF-8
353
2.90625
3
[]
no_license
""" Server ECHO UDP """ import socket #creazione del socket s= socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) #bind del server per esporlo sulla rete s.bind(("127.0.0.1", 1250)) #funzionamento (legge il messaggio e lo restituisce) data, address = s.recvfrom(4096) s.sendto(data, address) #chiusura del socket s.close()
true
04aea845d5eddf0ea3cbac1b13b0631c4ab14896
Python
shivanshc/gcloud-utils
/listVPNTunnels.py
UTF-8
3,307
2.6875
3
[]
no_license
""" The service lists all the VPN tunnels created or connected to a Google Cloud project for all the projects associated with the account. Sample usage: python3 listVPNTunnels.py Sample output: For project My Project 40050, the VPN tunnels are: +-----------------+-------------+-------------+ | VPN Tunnel Name | Region Name | Description | +-----------------+-------------+-------------+ | vpn-2-tunnel-1 | us-east1 | | +-----------------+-------------+-------------+ Enter a VPN tunnel name to get more detailed info or c to continue: vpn-2-tunnel-1 Enter the region name for the chosen pool: us-east1 {'creationTimestamp': '2018-01-17T07:40:10.744-08:00', 'description': '', 'detailedStatus': 'No incoming packets from peer', 'id': '3979416647993839797', 'ikeVersion': 2, 'kind': 'compute#vpnTunnel', 'localTrafficSelector': ['0.0.0.0/0'], 'name': 'vpn-2-tunnel-1', 'peerIp': '35.194.137.221', 'region': 'https://www.googleapis.com/compute/v1/projects/lyrical-diagram-192415/regions/us-east1', 'selfLink': 'https://www.googleapis.com/compute/v1/projects/lyrical-diagram-192415/regions/us-east1/vpnTunnels/vpn-2-tunnel-1', 'sharedSecret': '*************', 'sharedSecretHash': 'AH2iNNV7JY3AnmLMl6HSGe-H0dEz', 'status': 'NO_INCOMING_PACKETS', 'targetVpnGateway': 'https://www.googleapis.com/compute/v1/projects/lyrical-diagram-192415/regions/us-east1/targetVpnGateways/vpn-2'} Enter a VPN tunnel name to get more detailed info or c to continue:c """ import googleapiclient.discovery from google.cloud import resource_manager from prettytable import PrettyTable from pprint import pprint t = PrettyTable(["VPN Tunnel Name", "Region Name", "Description"]) client = resource_manager.Client() compute = googleapiclient.discovery.build('compute', 'v1') for project in client.list_projects(): projId = project.project_id projName = project.name request = compute.regions().list(project=projId) print ("For project " + projName + ", the VPN tunnels are:") while request is not None: response = request.execute() for regionItem in response['items']: regionName = regionItem['name'] vpnRequest = compute.vpnTunnels().list(project=projId, region=regionName) while vpnRequest is not None: vpnResponse = vpnRequest.execute() if 'items' in vpnResponse: for vpnTunnel in vpnResponse['items']: name = vpnTunnel['name'] description = vpnTunnel['description'] t.add_row([name, regionName, description]) vpnRequest = compute.vpnTunnels().list_next(previous_request=vpnRequest, previous_response=vpnResponse) request = compute.regions().list_next(previous_request=request, previous_response=response) print (t) t.clear_rows() user_choice = input("Enter a VPN tunnel name to get more detailed info or c to continue: ") while user_choice != "c": regionName = input("Enter the region name for the chosen pool: ") request = compute.vpnTunnels().get(project=projId, region=regionName, vpnTunnel=user_choice) response = request.execute() pprint(response) user_choice = input("Enter a VPN tunnel name to get more detailed info or c to continue: ")
true
e0309b36f3306e95801d3bc04a114ebce56d515a
Python
fernandoyto/challenges
/productothernumbers/product_of_other_numbers.py
UTF-8
482
3.453125
3
[]
no_license
import numpy def get_products_of_all_ints_except_at_index(int_list): n = len(int_list) if n <= 1: raise Exception("List must have at least 2 elements") results = [0] * n for i in range(n): if i == 0: results[i] = numpy.prod(int_list[i + 1:]) elif i == n - 1: results[i] = numpy.prod(int_list[:i]) else: results[i] = numpy.prod(int_list[i + 1:]) * numpy.prod(int_list[:i]) return results
true
066eb2d5e5ee043af0cd382b9ada25b124b66a33
Python
pratikdk/dsaprobs_s1
/graphs/22_all_strongly_connected_components_kosaraju.py
UTF-8
1,940
3.546875
4
[]
no_license
from collections import defaultdict class Graph: def __init__(self, v_count): self.V = v_count self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) #self.graph[v].append(u) def dfs_util(self, u, visited, stack): visited[u] = True for v in self.graph[u]: if visited[v] == False: self.dfs_util(v, visited, stack) stack = stack.append(u) def dfs_util_print(self, u, visited, scc): visited[u] = True #print(u, end=" ") scc.append(u) for v in self.graph[u]: if visited[v] == False: self.dfs_util_print(v, visited, scc) def transpose_graph(self): g = Graph(self.V) for u in self.graph: for v in self.graph[u]: g.add_edge(v, u) return g def print_SCCs(self): stack = [] visited = [False] * self.V # Run DFS to check forward connectivity for i in range(self.V): if visited[i] == False: self.dfs_util(i, visited, stack) # reverse the graph gr = self.transpose_graph() # Pop from stack and run DFs to check backward connectivity visited = [False] * self.V all_scc = [] while stack: u = stack.pop() if visited[u] == False: scc = [] gr.dfs_util_print(u, visited, scc) all_scc.append(scc) #print("") return all_scc if __name__ == "__main__": g = Graph(5) g.add_edge(1, 0) g.add_edge(0, 2) g.add_edge(2, 1) g.add_edge(0, 3) g.add_edge(3, 4) print(g.print_SCCs()) # g = Graph(11) # g.add_edge(1, 2) # g.add_edge(1, 10) # g.add_edge(10, 9) # g.add_edge(3, 4) # g.add_edge(3, 5) # g.add_edge(5, 6) # g.add_edge(7, 8) # g.print_SCCs()
true
3c774dac4e19b710e4143a5c7ed3e37ed75b0847
Python
nadnik13/ML
/knn.py
UTF-8
5,783
2.765625
3
[]
no_license
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import operator import random import sklearn .base from sklearn import preprocessing from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.preprocessing import scale from sklearn.neighbors import KNeighborsClassifier import pylab as plt from sklearn.feature_extraction.text import CountVectorizer def load_dataset(filename): data = pd.read_csv(filename) y = np.ndarray.tolist(data['bin_month'].values) del data['bin_month'] print(data[:1]) data = preprocessing.normalize(data) # нормализую данные print(data[:1]) X = data return X, y def get_response(neighbors): range_elem_on_class = [0, 0] for i in range(neighbors.size): range_elem_on_class[int(neighbors[i])] += 1 if range_elem_on_class[0] < range_elem_on_class[1]: return 1 else: return 0 def get_accuracy(write_value, predictions): correct = 0 for x in range(len(write_value)): if write_value[x] == predictions[x]: correct += 1 # print("correct: ", correct, "from ",len(write_value)) return (correct/float(len(write_value))) * 100.0 class kNN(object): """ Simple kNN classifier """ def __init__(self, n_neighbors): self.n_neighbors = n_neighbors # количество соседей self.X = None #признаки self.y = None #принадлежность классу def fit(self, X, y): #загружае данные для обучения self.X = X self.y = y def predict(self, X): # передаем тестовые данные y_predict = np.zeros(X.shape[0]) for i in range(X.shape[0]): dists = np.zeros((self.X.shape[0], 2)) # создаем массив и высчитывае дистанцию для каждого элемента for j in range(self.X.shape[0]): dists[j][0] = np.linalg.norm(X[i] - self.X[j], ord = None) #дистанция dists[j][1] = j #индекс элемента, до которого считаем расстояние dists.view('i8,i8').sort(order=['f0'], axis=0) #нужно для сортировки по растоянию f0-колонка дистанции nearest_neighbors_dist = dists[:self.n_neighbors] # n первых (дистанция, индекс classes_nearest_neighbors = np.zeros(nearest_neighbors_dist.shape[0]) #массив классов ближайших элементов for p in range(nearest_neighbors_dist.shape[0]): # не вышло без for index = int(nearest_neighbors_dist[p][1]) #index елемента X classes_nearest_neighbors[p] = self.y[index] # значение класса 0 или 1 y_predict[i] = get_response(classes_nearest_neighbors) # получаем, класс нового элемента return y_predict if __name__ == '__main__': from sklearn.datasets import fetch_20newsgroups newsgroups_train = fetch_20newsgroups(subset='train') targets = ['sci.med', 'rec.sport.baseball'] documents = fetch_20newsgroups(data_home='./', subset='all', categories=targets) y = documents.target[:100] vectorizer = CountVectorizer() X = vectorizer.fit_transform(documents.data[:100]).toarray() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=50) score = np.zeros(50) accuracy_my_knn_list = np.zeros(50) accuracy_lib_knn_list = np.zeros(50) for i in range(1, 50): my_knn = kNN(i) my_knn.fit(X_train, y_train) y_predict = my_knn.predict(X_test) accuracy_my_knn = get_accuracy(y_test, y_predict) accuracy_my_knn_list[i] = accuracy_my_knn lib_knn = KNeighborsClassifier(n_neighbors=i) lib_knn.fit(X_train, y_train) y_predict = lib_knn.predict(X_test) accuracy_lib_knn = get_accuracy(y_test, y_predict) accuracy_lib_knn_list[i] = accuracy_lib_knn score[i] = accuracy_my_knn - accuracy_lib_knn plt.figure('difference_text') plt.plot([i for i in range(0, 50)], score, color='black') plt.figure('cross_val_my_text') plt.bar([i for i in range(0, 50)], accuracy_my_knn_list, color='red') plt.figure('cross_val_lib_text') plt.bar([i for i in range(0, 50)], accuracy_lib_knn_list, color='green') features, classes, = load_dataset("reload_forest_fire_simple.csv") X_train, X_test, y_train, y_test = train_test_split(features, classes, test_size=0.34, random_state=43) score = np.zeros(50) for i in range(1, 50): my_knn = kNN(i) my_knn.fit(X_train, y_train) y_predict = my_knn.predict(X_test) accuracy_my_knn = get_accuracy(y_test, y_predict) lib_knn = KNeighborsClassifier(n_neighbors=i) lib_knn.fit(X_train, y_train) y_predict = lib_knn.predict(X_test) accuracy_lib_knn = get_accuracy(y_test, y_predict) score[i] = accuracy_lib_knn - accuracy_my_knn plt.figure('difference') plt.plot([i for i in range(0, 50)], score, color='black') k_fold = KFold(n_splits=5, shuffle=True, random_state=42) scores = [] for i in range(1, 51): clf = KNeighborsClassifier(n_neighbors=i) score = cross_val_score(cv=k_fold, estimator=clf, scoring='accuracy', X=features, y=classes).mean() scores.append(score) plt.figure('cross_val') plt.bar([i for i in range(0, 50)], scores, color='red') print(max(scores), scores.index(max(scores)) + 1) features_scaled = scale(X=features) plt.show()
true
ce09c26b5093b701c8f82161482991502c30d6de
Python
Khaotang/CP3-Peeranat-Srisan
/Exercise5_2_Peeranat_S.py
UTF-8
399
3
3
[]
no_license
S = int(input("ระยะทางที่เคลื่อนที่ได้ :")) t = int(input("เวลาที่ใช้ในการเคลื่อนที่ :")) print("เมื่อระยะทาง =",S,"เมตร","และเวลา =",t,"วินาที") print("ความเร็ว =",S/t,"เมตร/วินาที") # IS Unit นะจ่ะ
true
ba3cec02a00efe24ec14fde21906e2f5abfdfbb3
Python
sakurasakura1996/Leetcode
/代码测试/test_deque_queue.py
UTF-8
715
4.21875
4
[]
no_license
""" 做了一个题目,发现对python中的数据结构不是很清楚,所以这里尝试看看 """ import queue q = queue.Queue() q.put(2) q.put(4) size = q.qsize() # 队列的长度 等价于 len() print(size) ans = q.get() # 出队列,并将出队列的元素返回 等价于 pop() print(ans) isEmpty = q.empty() print(isEmpty) # 上述是 queue包中的 Queue from collections import deque # collections库中的 deque是双向队列,可以操作头部和尾部 b = deque() # deque的操作和python中的列表操作很相似 b.append(2) b.appendleft(3) print(b) len = len(b) print(len) print(b.pop()) print("----") stack = [] stack.append(1) stack.append(2) a = stack.pop(1) print(a)
true
2123e026365eaaf178ba13ad777df1a510c64e85
Python
18817876219/sales_predict_new
/preprocess/process_order_cnt.py
UTF-8
2,859
2.953125
3
[]
no_license
import pandas as pd import numpy as np data = pd.read_csv('../raw_data/brand57.csv') restaurants = np.asanyarray(data["eleme_restaurant_id"].unique()).squeeze() sales = pd.DataFrame() date_range = pd.date_range(start='2017-04-21',end='2018-05-10') pydate_array = date_range.to_pydatetime() date_series = pd.Series(np.vectorize(lambda s: s.strftime('%Y-%m-%d'))(pydate_array)) sales['order_date'] = date_series print("天数:", len(date_series)) print("门店初始数量:", len(restaurants)) nan_remove_ratio_threshold = 0.2 columns = [] for restaurant_id in restaurants: sales1 = (data[data.eleme_restaurant_id == restaurant_id]) sales1 = sales1[['order_date','valid_order_cnt']] # sales1['valid_order_cnt'] = np.log(sales1['valid_order_cnt']) column_name = 'valid_order_cnt'+str(restaurant_id) sales1.rename(columns={'valid_order_cnt': column_name}, inplace=True) sales = pd.merge(sales, sales1, on='order_date', how='left') sales1 = sales[column_name] nan_num = len(sales1[np.isnan(sales1)]) # print(restaurant_id, "的nan数量为", nan_num) if nan_num/len(date_series) > nan_remove_ratio_threshold: sales.drop([column_name],axis=1,inplace=True) # print("移除",column_name) else: columns.append(column_name) print ("剩余门店数",(sales.columns.size - 1)) sales = sales.fillna(0) restaurants_new = [] for col in columns: sale1 = sales[col] num_list_new = [np.nan] * len(sale1) # 将为0的前后3天去掉 for index, item in enumerate(sale1): if item == 0: start = (index - 3) if index >= 3 else 0 end = (index + 4) if ((index + 4) < len(sale1)) else len(sale1) num_list_new[start:end] = [0] * (end - start) # 左边3个右边3个 else: if num_list_new[index] is np.nan: num_list_new[index] = item b = np.array(num_list_new) nonzero = b[b>0] nonzero = np.log(nonzero) # mean = nonzero.mean() #平均值 std = nonzero.std() #标准差 if std>0.5: print("col:", col, ", std", std) sales.drop([col], axis=1, inplace=True) else: s = pd.Series(num_list_new) # s = s.apply(lambda x: np.log(x) if x>0 else x) sales[col] = s sales.rename(columns={col: col[15:]}, inplace=True) print ("剩余门店数",(sales.columns.size - 1)) sales.set_index('order_date',inplace=True) print ("去掉最后一周含有0值的门店") # 去掉最后一周含有0值的门店 for column in sales.columns: index = (sales[column] == 0) index = list(index[len(index)-7:len(index)]) if True in index: sales.drop(column, axis=1, inplace=True) print(column) print ("剩余门店数",(sales.columns.size - 1)) # print(sales.columns.values) sales.T.to_csv('../processed_data/order_cnt.csv', sep=',')
true
dd6282e311be346c28323e4710aee3b5b228c2c7
Python
zenmeder/JKDatabaseSystem
/JKDatabaseSystem/TimeSeriesData.py
UTF-8
1,611
2.6875
3
[]
no_license
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" import happybase import datetime import pandas as pd class TimeSeriesData: NUMS_OF_PAST_DAYS = 20 def __init__(self, modelName, date, sensorId): self.modelName = modelName self.date = date self.sensorId = sensorId # 根据所给modelName, date, sensorId获取该sensorId下的date之前NUMS_OF_PAST_DAYS天的所有测孔的数据 def getData(self): connection = happybase.Connection('localhost') table = connection.table(self.modelName) endDate = datetime.datetime.strptime(self.date + ' 23:59:59', "%Y-%m-%d %H:%M:%S") startDate = endDate - datetime.timedelta(days=self.NUMS_OF_PAST_DAYS) endRow = self.date + ' 23:59:59|' + str(self.sensorId) startRow = datetime.datetime.strftime(startDate, "%Y-%m-%d %H:%M:%S") + '|' + str(self.sensorId) data = {} res = {} for key, value in table.scan(row_start=startRow, row_stop=endRow): key = bytes.decode(key) if key[key.index('|') + 1:] == str(self.sensorId): d = {} for (k, v) in value.items(): k = bytes.decode(k) d[int(k[k.index(':') + 1:])] = float(bytes.decode(v)) data[key[:key.index('|')]] = d df = pd.DataFrame(data=data).T for i in range(len(df.columns)): d1 = df[i] newd = pd.DataFrame(columns=['ds','y']) newd.ds = d1.index newd.y = d1.values res[i] = newd return res
true
eb87667a53f0c75792cfed7e539482e6ec31709f
Python
stuffyUdaya/Python
/1-9-17/intsandsums0-255.py
UTF-8
69
3.375
3
[]
no_license
sum = 0 for x in range(0,255): print x sum = sum+x print sum
true
c2f12db11d29b1325f3a497e6370ece2bc80a2b2
Python
pyvista/pyvista
/pyvista/demos/demos.py
UTF-8
15,906
3.015625
3
[ "MIT" ]
permissive
"""Demos to show off the functionality of PyVista.""" import time import numpy as np import pyvista as pv from pyvista import examples from .logo import text_3d def glyphs(grid_sz=3): """Create several parametric supertoroids using VTK's glyph table functionality. Parameters ---------- grid_sz : int, default: 3 Create ``grid_sz x grid_sz`` supertoroids. Returns ------- pyvista.PolyData Mesh of supertoroids. See Also -------- plot_glyphs Examples -------- >>> from pyvista import demos >>> mesh = demos.glyphs() >>> mesh.plot() """ n = 10 values = np.arange(n) # values for scalars to look up glyphs by # taken from: rng = np.random.default_rng() params = rng.uniform(0.5, 2, size=(n, 2)) # (n1, n2) parameters for the toroids geoms = [pv.ParametricSuperToroid(n1=n1, n2=n2) for n1, n2 in params] # get dataset where to put glyphs grid_sz = float(grid_sz) x, y, z = np.mgrid[:grid_sz, :grid_sz, :grid_sz] mesh = pv.StructuredGrid(x, y, z) # add random scalars rng_int = rng.integers(0, n, size=x.size) mesh.point_data['scalars'] = rng_int # construct the glyphs on top of the mesh; don't scale by scalars now return mesh.glyph( geom=geoms, indices=values, scale=False, factor=0.3, rng=(0, n - 1), orient=False ) def plot_glyphs(grid_sz=3, **kwargs): """Plot several parametric supertoroids using VTK's glyph table functionality. Parameters ---------- grid_sz : int, default: 3 Create ``grid_sz x grid_sz`` supertoroids. **kwargs : dict, optional All additional keyword arguments will be passed to :func:`pyvista.Plotter.add_mesh`. Returns ------- various See :func:`show <pyvista.Plotter.show>`. Examples -------- >>> from pyvista import demos >>> demos.plot_glyphs() """ # construct the glyphs on top of the mesh; don't scale by scalars now mesh = glyphs(grid_sz) kwargs.setdefault('specular', 1) kwargs.setdefault('specular_power', 15) kwargs.setdefault('smooth_shading', True) # create plotter and add our glyphs with some nontrivial lighting plotter = pv.Plotter() plotter.add_mesh(mesh, show_scalar_bar=False, **kwargs) return plotter.show() def orientation_cube(): """Return a dictionary containing the meshes composing an orientation cube. Returns ------- dict Dictionary containing the meshes composing an orientation cube. Examples -------- Load the cube mesh and plot it >>> import pyvista >>> from pyvista import demos >>> ocube = demos.orientation_cube() >>> pl = pyvista.Plotter() >>> _ = pl.add_mesh(ocube['cube'], show_edges=True) >>> _ = pl.add_mesh(ocube['x_p'], color='blue') >>> _ = pl.add_mesh(ocube['x_n'], color='blue') >>> _ = pl.add_mesh(ocube['y_p'], color='green') >>> _ = pl.add_mesh(ocube['y_n'], color='green') >>> _ = pl.add_mesh(ocube['z_p'], color='red') >>> _ = pl.add_mesh(ocube['z_n'], color='red') >>> pl.show_axes() >>> pl.show() """ cube = pv.Cube() x_p = text_3d('X+', depth=0.2) x_p.points *= 0.45 x_p.rotate_y(90, inplace=True) x_p.rotate_x(90, inplace=True) x_p.translate(-np.array(x_p.center), inplace=True) x_p.translate([0.5, 0, 0], inplace=True) # x_p.point_data['mesh'] = 1 x_n = text_3d('X-', depth=0.2) x_n.points *= 0.45 x_n.rotate_y(90, inplace=True) x_n.rotate_x(90, inplace=True) x_n.rotate_z(180, inplace=True) x_n.translate(-np.array(x_n.center), inplace=True) x_n.translate([-0.5, 0, 0], inplace=True) # x_n.point_data['mesh'] = 2 y_p = text_3d('Y+', depth=0.2) y_p.points *= 0.45 y_p.rotate_x(90, inplace=True) y_p.rotate_z(180, inplace=True) y_p.translate(-np.array(y_p.center), inplace=True) y_p.translate([0, 0.5, 0], inplace=True) # y_p.point_data['mesh'] = 3 y_n = text_3d('Y-', depth=0.2) y_n.points *= 0.45 y_n.rotate_x(90, inplace=True) y_n.translate(-np.array(y_n.center), inplace=True) y_n.translate([0, -0.5, 0], inplace=True) # y_n.point_data['mesh'] = 4 z_p = text_3d('Z+', depth=0.2) z_p.points *= 0.45 z_p.rotate_z(90, inplace=True) z_p.translate(-np.array(z_p.center), inplace=True) z_p.translate([0, 0, 0.5], inplace=True) # z_p.point_data['mesh'] = 5 z_n = text_3d('Z-', depth=0.2) z_n.points *= 0.45 z_n.rotate_x(180, inplace=True) z_n.translate(-np.array(z_n.center), inplace=True) z_n.translate([0, 0, -0.5], inplace=True) return { 'cube': cube, 'x_p': x_p, 'x_n': x_n, 'y_p': y_p, 'y_n': y_n, 'z_p': z_p, 'z_n': z_n, } def orientation_plotter(): """Return a plotter containing the orientation cube. Returns ------- pyvista.Plotter Orientation cube plotter. Examples -------- >>> from pyvista import demos >>> plotter = demos.orientation_plotter() >>> plotter.show() """ ocube = orientation_cube() pl = pv.Plotter() pl.add_mesh(ocube['cube'], show_edges=True) pl.add_mesh(ocube['x_p'], color='blue') pl.add_mesh(ocube['x_n'], color='blue') pl.add_mesh(ocube['y_p'], color='green') pl.add_mesh(ocube['y_n'], color='green') pl.add_mesh(ocube['z_p'], color='red') pl.add_mesh(ocube['z_n'], color='red') pl.show_axes() return pl def plot_wave(fps=30, frequency=1, wavetime=3, interactive=False, notebook=None): """Plot a 3D moving wave in a render window. Parameters ---------- fps : int, default: 30 Maximum frames per second to display. frequency : float, default: 1.0 Wave cycles per second (Hz). wavetime : float, default: 3.0 The desired total display time in seconds. interactive : bool, default: False Allows the user to set the camera position before the start of the wave movement. notebook : bool, optional When ``True``, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Returns ------- numpy.ndarray Position of points at last frame. Examples -------- >>> from pyvista import demos >>> out = demos.plot_wave() """ # camera position cpos = [ (6.879481857604187, -32.143727535933195, 23.05622921691103), (-0.2336056403734026, -0.6960083534590372, -0.7226721553894022), (-0.008900669873416645, 0.6018246347860926, 0.7985786667826725), ] # Make data X = np.arange(-10, 10, 0.25) Y = np.arange(-10, 10, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Create and plot structured grid sgrid = pv.StructuredGrid(X, Y, Z) # Get pointer to points points = sgrid.points.copy() mesh = sgrid.extract_surface() # Start a plotter object and set the scalars to the Z height plotter = pv.Plotter(notebook=notebook) plotter.add_mesh(mesh, scalars=Z.ravel(), show_scalar_bar=False, smooth_shading=True) plotter.camera_position = cpos plotter.show( title='Wave Example', window_size=[800, 600], auto_close=False, interactive_update=True ) # Update Z and display a frame for each updated position tdelay = 1.0 / fps tlast = time.time() tstart = time.time() while time.time() - tstart < wavetime: # get phase from start telap = time.time() - tstart phase = telap * 2 * np.pi * frequency Z = np.sin(R + phase) points[:, -1] = Z.ravel() # update plotting object, but don't automatically render plotter.update_coordinates(points, render=False) plotter.update_scalars(Z.ravel(), render=False) mesh.compute_normals(inplace=True) # Render and get time to render plotter.update() # time delay tpast = time.time() - tlast if tpast < tdelay and tpast >= 0 and not plotter.off_screen: time.sleep(tdelay - tpast) # store when rendering complete tlast = time.time() # Close movie and delete object plotter.close() return points def plot_ants_plane(notebook=None): """Plot two ants and airplane. Demonstrate how to create a plot class to plot multiple meshes while adding scalars and text. This example plots the following: .. code:: python >>> import pyvista >>> from pyvista import examples Load and shrink airplane >>> airplane = examples.load_airplane() >>> airplane.points /= 10 Rotate and translate ant so it is on the plane. >>> ant = examples.load_ant() >>> _ = ant.rotate_x(90, inplace=True) >>> _ = ant.translate([90, 60, 15], inplace=True) Make a copy and add another ant. >>> ant_copy = ant.translate([30, 0, -10], inplace=False) Create plotting object. >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(ant, 'r') >>> _ = plotter.add_mesh(ant_copy, 'b') Add airplane mesh and make the color equal to the Y position. >>> plane_scalars = airplane.points[:, 1] >>> _ = plotter.add_mesh( ... airplane, ... scalars=plane_scalars, ... scalar_bar_args={'title': 'Plane Y Location'}, ... ) >>> _ = plotter.add_text('Ants and Plane Example') >>> plotter.show() Parameters ---------- notebook : bool, optional When ``True``, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Examples -------- >>> from pyvista import demos >>> demos.plot_ants_plane() """ # load and shrink airplane airplane = examples.load_airplane() airplane.points /= 10 # rotate and translate ant so it is on the plane ant = examples.load_ant() ant.rotate_x(90, inplace=True) ant.translate([90, 60, 15], inplace=True) # Make a copy and add another ant ant_copy = ant.copy() ant_copy.translate([30, 0, -10], inplace=True) # Create plotting object plotter = pv.Plotter(notebook=notebook) plotter.add_mesh(ant, 'r') plotter.add_mesh(ant_copy, 'b') # Add airplane mesh and make the color equal to the Y position plane_scalars = airplane.points[:, 1] plotter.add_mesh( airplane, scalars=plane_scalars, scalar_bar_args={'title': 'Plane Y\nLocation'} ) plotter.add_text('Ants and Plane Example') plotter.show() def plot_beam(notebook=None): """Plot a beam with displacement. Parameters ---------- notebook : bool, optional When ``True``, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Examples -------- >>> from pyvista import demos >>> demos.plot_beam() """ # Create fiticious displacements as a function of Z location grid = examples.load_hexbeam() d = grid.points[:, 2] ** 3 / 250 grid.points[:, 1] += d # Camera position cpos = [ (11.915126303095157, 6.11392754955802, 3.6124956735471914), (0.0, 0.375, 2.0), (-0.42546442225230097, 0.9024244135964158, -0.06789847673314177), ] cmap = 'bwr' # plot this displaced beam plotter = pv.Plotter(notebook=notebook) plotter.add_mesh( grid, scalars=d, scalar_bar_args={'title': 'Y Displacement'}, rng=[-d.max(), d.max()], cmap=cmap, ) plotter.camera_position = cpos plotter.add_text('Static Beam Example') plotter.show() def plot_datasets(dataset_type=None): """Plot the pyvista dataset types. This demo plots the following PyVista dataset types: * :class:`pyvista.PolyData` * :class:`pyvista.UnstructuredGrid` * :class:`pyvista.ImageData` * :class:`pyvista.RectilinearGrid` * :class:`pyvista.StructuredGrid` Parameters ---------- dataset_type : str, optional If set, plot just that dataset. Must be one of the following: * ``'PolyData'`` * ``'UnstructuredGrid'`` * ``'ImageData'`` * ``'RectilinearGrid'`` * ``'StructuredGrid'`` Examples -------- >>> from pyvista import demos >>> demos.plot_datasets() """ allowable_types = [ 'PolyData', 'UnstructuredGrid', 'ImageData', 'RectilinearGrid', 'StructuredGrid', ] if dataset_type is not None: if dataset_type not in allowable_types: raise ValueError( f'Invalid dataset_type {dataset_type}. Must be one ' f'of the following: {allowable_types}' ) ########################################################################### # uniform grid image = pv.ImageData(dimensions=(6, 6, 1)) image.spacing = (3, 2, 1) ########################################################################### # RectilinearGrid xrng = np.array([0, 0.3, 1, 4, 5, 6, 6.2, 6.6]) yrng = np.linspace(-2, 2, 5) zrng = [1] rec_grid = pv.RectilinearGrid(xrng, yrng, zrng) ########################################################################### # structured grid ang = np.linspace(0, np.pi / 2, 10) r = np.linspace(6, 10, 8) z = [0] ang, r, z = np.meshgrid(ang, r, z) x = r * np.sin(ang) y = r * np.cos(ang) struct_grid = pv.StructuredGrid(x[::-1], y[::-1], z[::-1]) ########################################################################### # polydata points = pv.PolyData([[1.0, 2.0, 2.0], [2.0, 2.0, 2.0]]) line = pv.Line() line.points += np.array((2, 0, 0)) line.clear_data() tri = pv.Triangle() tri.points += np.array([0, 1, 0]) circ = pv.Circle() circ.points += np.array([1.5, 1.5, 0]) poly = tri + circ ########################################################################### # unstructuredgrid pyr = pv.Pyramid() pyr.points *= 0.7 cube = pv.Cube(center=(2, 0, 0)) ugrid = circ + pyr + cube + tri if dataset_type is not None: pl = pv.Plotter() else: pl = pv.Plotter(shape='3/2') # polydata if dataset_type is None: pl.subplot(0) pl.add_text('4. PolyData') if dataset_type in [None, 'PolyData']: pl.add_points(points, point_size=20) pl.add_mesh(line, line_width=5) pl.add_mesh(poly) pl.add_mesh(poly.extract_all_edges(), line_width=2, color='k') # unstructuredgrid if dataset_type is None: pl.subplot(1) pl.add_text('5. UnstructuredGrid') if dataset_type in [None, 'UnstructuredGrid']: pl.add_mesh(ugrid) pl.add_mesh(ugrid.extract_all_edges(), line_width=2, color='k') # ImageData if dataset_type is None: pl.subplot(2) pl.add_text('1. ImageData') if dataset_type in [None, 'ImageData']: pl.add_mesh(image) pl.add_mesh(image.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' # RectilinearGrid if dataset_type is None: pl.subplot(3) pl.add_text('2. RectilinearGrid') if dataset_type in [None, 'RectilinearGrid']: pl.add_mesh(rec_grid) pl.add_mesh(rec_grid.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' # StructuredGrid if dataset_type is None: pl.subplot(4) pl.add_text('3. StructuredGrid') if dataset_type in [None, 'StructuredGrid']: pl.add_mesh(struct_grid) pl.add_mesh(struct_grid.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' pl.show()
true
ed42f1c78258440d12a27dfb16fc8bc9bf4090b7
Python
lumee/unittest_repo
/first.py
UTF-8
604
3.203125
3
[]
no_license
import urllib2 class DataNotFound(Exception): pass class First(object): def get_data(self, path): req = urllib2.Request(path) try: response = urllib2.urlopen(req) except Exception: raise DataNotFound() return response.read() def post_data(self, destination, data): req = urllib2.Request(destination, data=data) urllib2.urlopen(req) def read_file(self, foo): with open(foo, 'r') as f: return f.read() #a = First() # #print a.read_file('file.txt') #print a.get_data('http://example.com')
true
a7b63bd71ae42d56d715895f02af9fe134a8958a
Python
MyrtleSoftware/myrtlespeech
/tests/builders/test_rnn.py
UTF-8
2,936
2.546875
3
[ "BSD-3-Clause" ]
permissive
import hypothesis.strategies as st import pytest import torch from hypothesis import assume from hypothesis import given from myrtlespeech.builders.rnn import build from myrtlespeech.model.rnn import RNN from myrtlespeech.protos import rnn_pb2 from tests.protos.test_rnn import rnns # Utilities ------------------------------------------------------------------- def rnn_match_cfg( rnn: RNN, rnn_cfg: rnn_pb2.RNN, input_features: int, batch_first: bool ) -> None: """Ensures RNN matches protobuf configuration.""" if rnn_cfg.rnn_type == rnn_pb2.RNN.LSTM: assert isinstance(rnn.rnn, torch.nn.LSTM) elif rnn_cfg.rnn_type == rnn_pb2.RNN.GRU: assert isinstance(rnn.rnn, torch.nn.GRU) elif rnn_cfg.rnn_type == rnn_pb2.RNN.BASIC_RNN: assert isinstance(rnn.rnn, torch.nn.RNN) else: raise ValueError(f"rnn_type {rnn_cfg.rnn_type} not supported by test") assert input_features == rnn.rnn.input_size assert rnn_cfg.hidden_size == rnn.rnn.hidden_size assert rnn_cfg.num_layers == rnn.rnn.num_layers assert rnn_cfg.bias == rnn.rnn.bias assert batch_first == rnn.rnn.batch_first assert rnn.rnn.dropout == 0.0 assert rnn_cfg.bidirectional == rnn.rnn.bidirectional if not ( rnn_cfg.rnn_type == rnn_pb2.RNN.LSTM and rnn_cfg.bias and rnn_cfg.HasField("forget_gate_bias") ): return hidden_size = rnn_cfg.hidden_size forget_gate_bias = rnn_cfg.forget_gate_bias.value for l in range(rnn_cfg.num_layers): bias = getattr(rnn.rnn, f"bias_ih_l{l}")[hidden_size : 2 * hidden_size] bias += getattr(rnn.rnn, f"bias_hh_l{l}")[ hidden_size : 2 * hidden_size ] assert torch.allclose( bias, torch.tensor(forget_gate_bias).to(bias.device) ) # Tests ----------------------------------------------------------------------- @given( rnn_cfg=rnns(), input_features=st.integers(1, 32), batch_first=st.booleans(), ) def test_build_rnn_returns_correct_rnn_with_valid_params( rnn_cfg: rnn_pb2.RNN, input_features: int, batch_first: bool ) -> None: """Test that build_rnn returns the correct RNN with valid params.""" rnn, rnn_output_size = build(rnn_cfg, input_features, batch_first) rnn_match_cfg(rnn, rnn_cfg, input_features, batch_first) @given( rnn_cfg=rnns(), input_features=st.integers(1, 128), invalid_rnn_type=st.integers(0, 128), ) def test_unknown_rnn_type_raises_value_error( rnn_cfg: rnn_pb2.RNN, input_features: int, invalid_rnn_type: int ) -> None: """Ensures ValueError is raised when rnn_type not supported. This can occur when the protobuf is updated and build_rnn is not. """ assume(invalid_rnn_type not in rnn_pb2.RNN.RNN_TYPE.values()) rnn_cfg.rnn_type = invalid_rnn_type # type: ignore with pytest.raises(ValueError): build(rnn_cfg, input_features=input_features)
true
a2be39048538d724c7092612adb9f4868f44f20f
Python
mleright/Python-quadratic-solver
/python quadratic solver.py
UTF-8
381
3.421875
3
[]
no_license
A = float(input('Enter a coefficient: ')) B = float(input('Enter b coefficient: ')) C = float(input('Enter c coefficient: ')) if A == 0: print('Since a = 0, function is not a quadratic.') else: SOLUTION1 = (-B+((B*B-4*A*C)**(1/2.0)))/(2*A) SOLUTION2 = (-B-((B*B-4*A*C)**(1/2.0)))/(2*A) print('solution 1 is:', SOLUTION1) print('solution 2 is:', SOLUTION2)
true
25b73fe56e6305595282b05d28ac53de6e5b3d70
Python
projetoeducapy/educa.py
/gamequiz.py
UTF-8
133,083
2.828125
3
[]
no_license
#Importações import pygame, sys from pygame.locals import * import educa def gamequiz(): #Inicialização pygame.init() tela = pygame.display.set_mode((850, 600)) pygame.display.set_caption('Game Quiz') pygame.mixer.init() #Audios audio_clique=pygame.mixer.Sound('audios/quiz/clique.ogg') #Cores preto = (0, 0, 0) #Imagens b1 = pygame.image.load('imagens/quiz/nuvem.png') b2 = pygame.image.load('imagens/quiz/nuvem.png') fundo = pygame.image.load('imagens/quiz/fundo.jpeg') voltar = pygame.image.load('imagens/quiz/voltar.png') #Textos pygame.font.init() fonte1 = pygame.font.SysFont('Arial Black', 45) fonte11= pygame.font.SysFont('Arial Black', 35) fonte2 = pygame.font.SysFont('Arial', 20) menu = fonte2.render('Menu Principal', 1, preto) portugues = fonte11.render('Português', 1, preto) matematica = fonte11.render('Matemática', 1, preto) #Tela inicial while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0] == True: x = pygame.mouse.get_pos()[0] y = pygame.mouse.get_pos()[1] if x > 10 and x < 50 and y > 10 and y < 50: audio_clique.play() educa.telajogos() if x > 35 and x < 355 and y > 260 and y < 430: audio_clique.play() inicio2('Português') if x > 430 and x < 750 and y > 260 and y < 430: audio_clique.play() inicio2('Matemática') if x > 725 and x < 830 and y > 570 and y < 590: audio_clique.play() educa.principal() pygame.time.Clock().tick(30) tela.blit(fundo, (0, 0)) tela.blit(voltar, (10, 10)) tela.blit(b1,(100, 260)) b1.blit(portugues, (45, 45)) tela.blit(b2,(430, 260)) b2.blit(matematica, (35, 45)) tela.blit(menu, (725, 570)) pygame.display.update() def placar(quantidade,disciplina): #Inicialização tela = pygame.display.set_mode((850, 600)) pygame.mixer.init() #Audios audio_efeito=pygame.mixer.Sound('audios/quiz/efeito.ogg') audio_placar=pygame.mixer.Sound('audios/quiz/bateria.ogg') audio_perdeu=pygame.mixer.Sound('audios/quiz/errada.ogg') #Imagens quant0 = pygame.image.load('imagens/quiz/zerou.jpg') quant1 = pygame.image.load('imagens/quiz/dez.jpg') quant2 = pygame.image.load('imagens/quiz/vinte.jpg') quant3 = pygame.image.load('imagens/quiz/trinta.jpg') quant4 = pygame.image.load('imagens/quiz/quarenta.jpg') quant5 = pygame.image.load('imagens/quiz/cinquenta.jpg') quant6 = pygame.image.load('imagens/quiz/sessenta.jpg') quant7 = pygame.image.load('imagens/quiz/setenta.jpg') quant8 = pygame.image.load('imagens/quiz/oitenta.jpg') quant9 = pygame.image.load('imagens/quiz/noventa.jpg') quant10 = pygame.image.load('imagens/quiz/cem.jpg') if quantidade==0: tela.blit(quant0, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==1: tela.blit(quant1, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==2: tela.blit(quant2, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==3: tela.blit(quant3, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==4: tela.blit(quant4, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==5: tela.blit(quant5, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==6: tela.blit(quant6, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==7: tela.blit(quant7, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==8: tela.blit(quant8, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==9: tela.blit(quant9, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) if quantidade==10: tela.blit(quant10, (0, 0)) pygame.display.update() audio_placar.play() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False inicio2(disciplina) def inicio2(disciplina): #Inicialização pygame.init() tela = pygame.display.set_mode((850, 600)) pygame.display.set_caption('Game Quiz/{}'.format(disciplina)) pygame.mixer.init() #Audios audio_clique=pygame.mixer.Sound('audios/quiz/clique.ogg') #Cores preto = (0, 0, 0) #Imagens b1 = pygame.image.load('imagens/quiz/nuvem.png') b2 = pygame.image.load('imagens/quiz/nuvem.png') b3 = pygame.image.load('imagens/quiz/nuvem.png') b4 = pygame.image.load('imagens/quiz/nuvem.png') fundo = pygame.image.load('imagens/quiz/fundo.jpeg') voltar = pygame.image.load('imagens/quiz/voltar.png') #Textos pygame.font.init() fonte1 = pygame.font.SysFont('Arial Black', 45) fonte2 = pygame.font.SysFont('Arial', 20) facil = fonte1.render('Fácil', 1, preto) medio = fonte1.render('Médio', 1, preto) dificil = fonte1.render('Difícil', 1, preto) ajuda = fonte1.render('Ajuda', 1, preto) menu = fonte2.render('Menu Principal', 1, preto) #Tela inicial while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0] == True: x = pygame.mouse.get_pos()[0] y = pygame.mouse.get_pos()[1] if x > 10 and x < 50 and y > 10 and y < 50: audio_clique.play() gamequiz() if x > 725 and x < 830 and y > 570 and y < 590: audio_clique.play() educa.principal() if x > 100 and x < 370 and y > 235 and y < 385: audio_clique.play() #Inicialização pygame.display.set_caption('Game Quiz/{}/Fácil'.format(disciplina)) pygame.mixer.init() #Audios audio_clique=pygame.mixer.Sound('audios/quiz/clique.ogg') audio_efeito=pygame.mixer.Sound('audios/quiz/efeito.ogg') audio_ganhou=pygame.mixer.Sound('audios/quiz/certa.ogg') audio_perdeu=pygame.mixer.Sound('audios/quiz/errada.ogg') #Imagens acertou = pygame.image.load('imagens/quiz/acertou.jpeg') errou = pygame.image.load('imagens/quiz/errou.jpeg') #Imagens de Português pp1 = pygame.image.load('imagens/quiz/pergunta1.jpg') pp2 = pygame.image.load('imagens/quiz/pergunta2.jpg') pp3 = pygame.image.load('imagens/quiz/pergunta3.jpg') pp4 = pygame.image.load('imagens/quiz/pergunta4.jpg') pp5 = pygame.image.load('imagens/quiz/pergunta5.jpg') pp6 = pygame.image.load('imagens/quiz/pergunta6.jpg') pp7 = pygame.image.load('imagens/quiz/pergunta7.jpg') pp8 = pygame.image.load('imagens/quiz/pergunta8.jpg') pp9 = pygame.image.load('imagens/quiz/pergunta9.jpg') pp10 = pygame.image.load('imagens/quiz/pergunta10.jpg') #Imagens de Matemática pm1 = pygame.image.load('imagens/quiz/perguntam1.jpg') pm2 = pygame.image.load('imagens/quiz/perguntam2.jpg') pm3 = pygame.image.load('imagens/quiz/perguntam3.jpg') pm4 = pygame.image.load('imagens/quiz/perguntam4.jpg') pm5 = pygame.image.load('imagens/quiz/perguntam5.jpg') pm6 = pygame.image.load('imagens/quiz/perguntam6.jpg') pm7 = pygame.image.load('imagens/quiz/perguntam7.jpg') pm8 = pygame.image.load('imagens/quiz/perguntam8.jpg') pm9 = pygame.image.load('imagens/quiz/perguntam9.jpg') pm10 = pygame.image.load('imagens/quiz/perguntam10.jpg') #Textos pygame.font.init() fonte = pygame.font.SysFont('Arial', 20) menu = fonte.render('Menu Principal', 1, preto) #Jogo if disciplina=="Português": #1° Questão tela.blit(pp1, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pp2, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pp3, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pp4, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pp5, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pp6, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pp7, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pp8, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pp9, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pp10, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if disciplina=="Matemática": #1° Questão tela.blit(pm1, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pm2, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pm3, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pm4, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pm5, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pm6, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pm7, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pm8, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pm9, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pm10, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if x > 430 and x < 700 and y > 235 and y < 385: audio_clique.play() #Inicialização pygame.display.set_caption('Game Quiz/{}/Médio'.format(disciplina)) pygame.mixer.init() #Audios audio_efeito=pygame.mixer.Sound('audios/quiz/efeito.ogg') audio_ganhou=pygame.mixer.Sound('audios/quiz/certa.ogg') audio_perdeu=pygame.mixer.Sound('audios/quiz/errada.ogg') #Imagens acertou = pygame.image.load('imagens/quiz/acertou.jpeg') errou = pygame.image.load('imagens/quiz/errou.jpeg') #Imagens de Português pp11 = pygame.image.load('imagens/quiz/pergunta11.jpg') pp12 = pygame.image.load('imagens/quiz/pergunta12.jpg') pp13 = pygame.image.load('imagens/quiz/pergunta13.jpg') pp14 = pygame.image.load('imagens/quiz/pergunta14.jpg') pp15 = pygame.image.load('imagens/quiz/pergunta15.jpg') pp16 = pygame.image.load('imagens/quiz/pergunta16.jpg') pp17 = pygame.image.load('imagens/quiz/pergunta17.jpg') pp18 = pygame.image.load('imagens/quiz/pergunta18.jpg') pp19 = pygame.image.load('imagens/quiz/pergunta19.jpg') pp20 = pygame.image.load('imagens/quiz/pergunta20.jpg') #Imagens de Matemática pm11 = pygame.image.load('imagens/quiz/perguntam11.jpg') pm12 = pygame.image.load('imagens/quiz/perguntam12.jpg') pm13 = pygame.image.load('imagens/quiz/perguntam13.jpg') pm14 = pygame.image.load('imagens/quiz/perguntam14.jpg') pm15 = pygame.image.load('imagens/quiz/perguntam15.jpg') pm16 = pygame.image.load('imagens/quiz/perguntam16.jpg') pm17 = pygame.image.load('imagens/quiz/perguntam17.jpg') pm18 = pygame.image.load('imagens/quiz/perguntam18.jpg') pm19 = pygame.image.load('imagens/quiz/perguntam19.jpg') pm20 = pygame.image.load('imagens/quiz/perguntam10.jpg') #Textos pygame.font.init() fonte = pygame.font.SysFont('Arial', 20) menu = fonte.render('Menu Principal', 1, preto) #Jogo if disciplina=="Português": #1° Questão tela.blit(pp11, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pp12, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pp13, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pp14, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pp15, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pp16, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pp17, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pp18, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pp19, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pp20, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if disciplina=="Matemática": #1° Questão tela.blit(pm11, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pm12, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pm13, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pm14, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pm15, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pm16, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pm17, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pm18, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pm19, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pm20, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if x > 100 and x < 370 and y > 360 and y < 510: audio_clique.play() #Inicialização pygame.display.set_caption('Game Quiz/{}/Difícil'.format(disciplina)) pygame.mixer.init() #Audios audio_efeito=pygame.mixer.Sound('audios/quiz/efeito.ogg') audio_ganhou=pygame.mixer.Sound('audios/quiz/certa.ogg') audio_perdeu=pygame.mixer.Sound('audios/quiz/errada.ogg') #Imagens acertou = pygame.image.load('imagens/quiz/acertou.jpeg') errou = pygame.image.load('imagens/quiz/errou.jpeg') #Imagens de Português pp21 = pygame.image.load('imagens/quiz/pergunta21.jpg') pp22 = pygame.image.load('imagens/quiz/pergunta22.jpg') pp23 = pygame.image.load('imagens/quiz/pergunta23.jpg') pp24 = pygame.image.load('imagens/quiz/pergunta24.jpg') pp25 = pygame.image.load('imagens/quiz/pergunta25.jpg') pp26 = pygame.image.load('imagens/quiz/pergunta26.jpg') pp27 = pygame.image.load('imagens/quiz/pergunta27.jpg') pp28 = pygame.image.load('imagens/quiz/pergunta28.jpg') pp29 = pygame.image.load('imagens/quiz/pergunta29.jpg') pp30 = pygame.image.load('imagens/quiz/pergunta30.jpg') #Imagens de Matemática pm21 = pygame.image.load('imagens/quiz/perguntam21.jpg') pm22 = pygame.image.load('imagens/quiz/perguntam22.jpg') pm23 = pygame.image.load('imagens/quiz/perguntam23.jpg') pm24 = pygame.image.load('imagens/quiz/perguntam24.jpg') pm25 = pygame.image.load('imagens/quiz/perguntam25.jpg') pm26 = pygame.image.load('imagens/quiz/perguntam26.jpg') pm27 = pygame.image.load('imagens/quiz/perguntam27.jpg') pm28 = pygame.image.load('imagens/quiz/perguntam28.jpg') pm29 = pygame.image.load('imagens/quiz/perguntam29.jpg') pm30 = pygame.image.load('imagens/quiz/perguntam30.jpg') #Textos pygame.font.init() fonte = pygame.font.SysFont('Arial', 20) menu = fonte.render('Menu Principal', 1, preto) if disciplina=="Português": #1° Questão tela.blit(pp21, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pp22, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pp23, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pp24, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pp25, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pp26, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pp27, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pp28, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pp29, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pp30, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if disciplina=="Matemática": #1° Questão tela.blit(pm21, (0, 0)) pygame.display.update() cont=0 sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #2° Questão tela.blit(pm22, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #3° Questão tela.blit(pm23, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #4° Questão tela.blit(pm24, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #5° Questão tela.blit(pm25, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #6° Questão tela.blit(pm26, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #7° Questão tela.blit(pm27, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #8° Questão tela.blit(pm28, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #9° Questão tela.blit(pm29, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False #10° Questão tela.blit(pm30, (0, 0)) pygame.display.update() sair=True while sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_b: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_c: tela.blit(acertou, (0, 0)) pygame.display.update() audio_ganhou.play() cont+=1 if event.key == pygame.K_d: tela.blit(errou, (0, 0)) pygame.display.update() audio_perdeu.play() if event.key == pygame.K_RIGHT: audio_efeito.play() sair=False placar(cont,disciplina) if x > 430 and x < 700 and y > 360 and y < 510: audio_clique.play() #Inicialização pygame.display.set_caption('Game Quiz/{}/Ajuda'.format(disciplina)) #Imagens ajuda = pygame.image.load('imagens/quiz/ajuda.jpg') #Tela inicial while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0] == True: x = pygame.mouse.get_pos()[0] y = pygame.mouse.get_pos()[1] if x > 10 and x < 50 and y > 10 and y < 50: audio_clique.play() inicio2(disciplina) if x > 725 and x < 830 and y > 570 and y < 590: audio_clique.play() educa.principal() pygame.time.Clock().tick(30) tela.blit(ajuda, (0, 0)) tela.blit(voltar, (10, 10)) tela.blit(menu, (725, 570)) pygame.display.update() pygame.time.Clock().tick(30) tela.blit(fundo, (0, 0)) tela.blit(b1,(100, 235)) b1.blit(facil, (100, 35)) tela.blit(b2,(430, 235)) b2.blit(medio, (93, 35)) tela.blit(b3,(100, 360)) b3.blit(dificil, (94, 35)) tela.blit(b4,(430, 360)) b4.blit(ajuda, (96, 35)) tela.blit(menu, (725, 570)) tela.blit(voltar, (10, 10)) pygame.display.update()
true
54357c6c5d5d980b7cf894e333a9d485f25f19d4
Python
CPS2018/Navigation
/pilot_v2/src/script/drive.py
UTF-8
6,285
2.609375
3
[]
no_license
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped, Quaternion import tf from mavros_msgs.srv import CommandBool from mavros_msgs.msg import State import math import Sensor import time from geometry_msgs.msg import PoseStamped from sensor_msgs.msg import LaserScan from decimal import * class drive(): # Init def __init__(self, lock): self._lock = lock self._curr_pose = PoseStamped() self.sense = Sensor.sensor() self.detect_data = LaserScan() self.height_data = LaserScan() rospy.Subscriber('/mavros/local_position/pose', PoseStamped, self._curr_pose_callback) self._pose_pub = rospy.Publisher('/mavros/setpoint_position/local', PoseStamped, queue_size=10) self._pose_msg = PoseStamped() self._pose_state = "posctr" self.set_state("posctr") ps = [0.0,0.0,2.0] self.set_msg(ps) # Current position callback def _curr_pose_callback(self, pos): self._curr_pose = pos # State def set_state(self, arg): self._lock.acquire() if arg == "posctr": self.state = self._pose_state self.msg = self._pose_msg self.pub = self._pose_pub self._lock.release() # Set msg (ish)? def set_msg(self, arg): if self.state == "posctr" and len(arg) == 3: self._lock.acquire() self._pose_msg.pose.position.x = arg[0] self._pose_msg.pose.position.y = arg[1] self._pose_msg.pose.position.z = arg[2] self._pose_msg.pose.orientation.x = 0 self._pose_msg.pose.orientation.y = 0 self._lock.release() # Set orientation/heading def set_orient(self, arg): curr_x = self._curr_pose.pose.position.x curr_y = self._curr_pose.pose.position.y azimuth = math.atan2(arg[1] - curr_y, arg[0] - curr_x) quaternion = tf.transformations.quaternion_from_euler(0, 0, azimuth) self._lock.acquire() self._pose_msg.pose.orientation.z = quaternion[2] self._pose_msg.pose.orientation.w = quaternion[3] self._lock.release() self.orientation = False while not self.orientation: self.z = self._curr_pose.pose.orientation.z self.w = self._curr_pose.pose.orientation.w self.qz = quaternion[2] self.qw =quaternion[3] if (abs(self.z) < (abs(self.qz)-0.1)) or (abs(self.w) < (abs(self.qw)-0.1)): self._lock.acquire() self._pose_msg.pose.orientation.z = quaternion[2] self._pose_msg.pose.orientation.w = quaternion[3] self._lock.release() else: print "Orientation set" self.orientation=True # Obstacle height def obstacle_height(self): curr_height = self._curr_pose.pose.position.z height_data = self.sense.get_height() diff = 0.0 if height_data: if (height_data.ranges[1]>0.0) and (height_data.ranges[1]<40.0): diff = curr_height - height_data.ranges[1] return diff # Sensor detection function #1 def detect_th(self, des_x, des_y): #Return 0 if ostacle is detected detect_data = self.sense.get_detection() if detect_data: #2=left #1=front #0=right if (detect_data.ranges[0] <= 7) and (detect_data.ranges[0] >= 0): #RIGHT RAY des_y = des_y + abs(detect_data.ranges[0] - 7) if detect_data.header.seq%10==0: print detect_data.ranges[0] if (detect_data.ranges[1] <= 7) and (detect_data.ranges[1] >= 0): #FRONT RAY des_x = des_x + (detect_data.ranges[1] - 7) if detect_data.header.seq % 10==0: print detect_data.ranges[1] if (detect_data.ranges[2] <= 7) and (detect_data.ranges[2] >= 0): #LEFT RAY des_y = des_y - abs(detect_data.ranges[0] - 7) if detect_data.header.seq % 10==0: print detect_data.ranges[2] return des_x, des_y # Sensor detection function #2 def detect_th1(self, des_x, des_y, start): # Return 0 if ostacle is detected detect_data = self.sense.get_detection() if detect_data: # 2=left # 1=front # 0=right if (detect_data.ranges[1] <= 4) and (detect_data.ranges[1] >= 0): # FRONT RAY Sensrange = detect_data.ranges[1] des_x = des_x - self.pose_controlFront(des_x, Sensrange, start.pose.position.x) des_y = des_y - self.pose_controlFront(des_y, Sensrange, start.pose.position.y) # 0=right if (detect_data.ranges[0] <= 4) and (detect_data.ranges[0] >= 0): # FRONT RAY Sensrange = detect_data.ranges[0] des_x = des_x - self.pose_controlFront(des_x, Sensrange, start.pose.position.x) des_y = des_y - self.pose_controlFront(des_y, Sensrange, start.pose.position.y) if (detect_data.ranges[2] <= 4) and (detect_data.ranges[2] >= 0): # FRONT RAY Sensrange = detect_data.ranges[2] des_x = des_x - self.pose_controlFront(des_x, Sensrange, start.pose.position.x) des_y = des_y - self.pose_controlFront(des_y, Sensrange, start.pose.position.y) #print des_x return des_x, des_y # Something wierd to decde negative/positive orientation def pose_controlFront(self, des, range, start): if des < start: return -(4 - range) return (4 - range) # Calculate distance to waypoint def dist2wp(self, goal): cx = float(self._curr_pose.pose.position.x) cy = float(self._curr_pose.pose.position.y) cz = float(self._curr_pose.pose.position.z) dx = float(goal.pose.position.x) dy = float(goal.pose.position.y) dz = float(goal.pose.position.z) distance = math.sqrt(math.pow(cx - dx, 2) + math.pow(cy - dy, 2) + math.pow(cz - dz, 2)) return distance
true
9678c5a0766aee36fdb810ad01ccea614d209537
Python
MArhEV/PyLearn
/08_functions/cities.py
UTF-8
198
3.5
4
[]
no_license
def describe_city(city, country='Poland'): text = f"{city}, {country}" return text.title() text = describe_city('Kielce') print(text) text2 = describe_city('Moscow', 'Russia') print(text2)
true
df3c33d8afafd7feb74e64b4488459e5dda4bcb1
Python
yyc1018/330
/plots_leastSquares.py
UTF-8
6,025
2.59375
3
[]
no_license
import pandas as pd import numpy as np import math as m import matplotlib.pyplot as plt import seaborn as sns from scipy.integrate import odeint ######################################################################################################################## # Load data ssData = pd.read_csv('/Users/katherine.yychow/OneDrive - Imperial College London/Year 3/Final year project/Code/Final ' 'Scripts/ssData.csv', index_col=0) stallData = pd.read_csv('/Users/katherine.yychow/OneDrive - Imperial College London/Year 3/Final year ' 'project/Code/Final Scripts/stallData.csv', index_col=0) resurData = pd.read_csv('/Users/katherine.yychow/OneDrive - Imperial College London/Year 3/Final year ' 'project/Code/Final Scripts/resurData.csv', index_col=0) ######################################################################################################################## # Replace all zeros in steady state and stall trajectories with NAN ssData.iloc[:, : 4794] = ssData.iloc[:, : 4794].replace(['0', 0], np.nan) stallData.iloc[:, : 8394] = stallData.iloc[:, : 8394].replace(['0', 0], np.nan) # Replace zeroes after 200s in resurrection trajectories with NAN resurData.iloc[:, 200: 15814] = resurData.iloc[:, 200: 15814].replace(['0', 0], np.nan) ######################################################################################################################## # Calculate mean of all trajectories ssMean_D300 = ssData.iloc[0: 33].mean(axis=0) ssMean_D500 = ssData.iloc[34: 63].mean(axis=0) ssMean_D1300 = ssData.iloc[64: 92].mean(axis=0) stallMean_D300 = stallData.iloc[0: 33].mean(axis=0) stallMean_D500 = stallData.iloc[34: 63].mean(axis=0) stallMean_D1300 = stallData.iloc[64: 92].mean(axis=0) resurMean_D300 = resurData.iloc[0: 23].mean(axis=0) resurMean_D500 = resurData.iloc[24: 45].mean(axis=0) resurMean_D1300 = resurData.iloc[46: 65].mean(axis=0) ######################################################################################################################## # Define Berg model def dNdtModel(N, t, k0, alpha, zeta): kon = k0 * (1 - m.e ** (-alpha / N)) koff = kon * m.e ** zeta return kon * (13 - N) - koff * N ######################################################################################################################## # Range of time points for each of the three phases t_ss = np.arange(-ssMean_D300.shape[0] / 10, 0, 0.1) t_stall = np.arange(0, 839.4, 0.1) t_resur = np.arange(839.4, 839.4 + 1581.4, 0.1) # Steady state mean ssGlobal_D300 = ssMean_D300.mean() ssGlobal_D500 = ssMean_D500.mean() ssGlobal_D1300 = ssMean_D1300.mean() ssGlobalList = [ssGlobal_D300, ssGlobal_D500, ssGlobal_D1300] # Range of time points for steady state mean t_all = np.arange(-ssMean_D300.shape[0] / 10, 839.4 + 1581.4, 0.1) ######################################################################################################################## # Initial values N0List = [6.18181818, 9.23333333, 10, 0.30434783, 0, 0] # Results from least squares minimisation k0 = 0.00890236 alpha = 2.11277947 zetaList = [0.62952840, -0.37997447, -1.23221807] ######################################################################################################################## # Plot fig, axes = plt.subplots(3, 1) sns.set_style("white") for i in range(3): # Steady state mean sns.lineplot(ax=axes[i], x=t_all, y=ssGlobalList[i], color='grey', linestyle='--', linewidth=2) for i in range(92): # All individual steady state trajectories if i <= 33: axes[0].plot(t_ss, ssData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) elif i <= 63: axes[1].plot(t_ss, ssData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) else: axes[2].plot(t_ss, ssData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) for i in range(92): # All individual stall trajectories if i <= 33: axes[0].plot(t_stall, stallData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) elif i <= 63: axes[1].plot(t_stall, stallData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) else: axes[2].plot(t_stall, stallData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) for i in range(65): # All individual resurrection trajectories if i <= 23: axes[0].plot(t_resur, resurData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) elif i <= 45: axes[1].plot(t_resur, resurData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) else: axes[2].plot(t_resur, resurData.iloc[i, :], color='grey', linestyle='--', linewidth=0.5) # Mean trajectories for steady state, stall, and resurrection sns.lineplot(ax=axes[0], x=t_ss, y=ssMean_D300, color='k', linewidth=2) sns.lineplot(ax=axes[1], x=t_ss, y=ssMean_D500, color='k', linewidth=2) sns.lineplot(ax=axes[2], x=t_ss, y=ssMean_D1300, color='k', linewidth=2) sns.lineplot(ax=axes[0], x=t_stall, y=stallMean_D300, color='k', linewidth=2) sns.lineplot(ax=axes[1], x=t_stall, y=stallMean_D500, color='k', linewidth=2) sns.lineplot(ax=axes[2], x=t_stall, y=stallMean_D1300, color='k', linewidth=2) sns.lineplot(ax=axes[0], x=t_resur, y=resurMean_D300, color='k', linewidth=2) sns.lineplot(ax=axes[1], x=t_resur, y=resurMean_D500, color='k', linewidth=2) sns.lineplot(ax=axes[2], x=t_resur, y=resurMean_D1300, color='k', linewidth=2) # Fitted curves as per the least squares minimisation results for i in range(3): axes[i].plot(t_stall, (odeint(dNdtModel, N0List[i], t_stall, args=(k0, alpha, zetaList[i]))), color='r', linewidth=2) axes[i].plot(t_resur, (odeint(dNdtModel, N0List[i + 3], t_resur, args=(k0, alpha, zetaList[i]))), color='r', linewidth=2) axes[i].set_xlim(-ssMean_D300.shape[0] / 10, 1700) axes[i].set_ylabel('N') axes[i].set_xlabel('t (s)') axes[i].set_ylim(0, 13) axes[0].set_title('300nm') axes[1].set_title('500nm') axes[2].set_title('1300nm') plt.show()
true
33ef168e398b702d2e42acf5527a889af0dd2ca8
Python
mirror731/python-project
/Unit Converter.py
UTF-8
3,927
3.625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun May 9 12:58:44 2021 @author: User convert unit in different parameter """ def temp(unit1,unit2,x): if unit1 == "Celsius" and unit2 == "Fahrenheit": ans = x*(9/5)+32 elif unit2 == "Celsius" and unit1 == "Fahrenheit": ans = (x-32)*(5/9) elif unit1 == "Celsius" and unit2 == "Kelvin": ans = x+273.15 elif unit2 == "Celsius" and unit1 == "Kelvin": ans = x-273.15 elif unit1 == "Kelvin" and unit2 == "Fahrenheit": ans = x*(9/5)-459.67 elif unit2 == "Kelvin" and unit1 == "Fahrenheit": ans = (x+459.67)*5/9 print(f"{x} in {unit1} is equal to {ans} in {unit2}") def length(unit1,unit2,x): if unit1 == "cm" and unit2 == "m": ans = x/100 elif unit2 == "cm" and unit1 == "m": ans = x*100 elif unit1 == "cm" and unit2 == "km": ans = x/100000 elif unit2 == "cm" and unit1 == "km": ans = x*100000 elif unit1 == "m" and unit2 == "km": ans = x/1000 elif unit2 == "m" and unit1 == "km": ans = x*1000 elif unit1 == "cm" and unit2 == "in": ans = x/2.54 elif unit2 == "cm" and unit1 == "in": ans = x*2.54 elif unit1 == "m" and unit2 == "in": ans = x/2.54*100 elif unit2 == "m" and unit1 == "in": ans = x*2.54/100 elif unit1 == "km" and unit2 == "in": ans = x/2.54*100000 elif unit2 == "km" and unit1 == "in": ans = x*2.54/100000 print(f"{x} {unit1} is equal to {ans:.4f} {unit2}") def weight(unit1,unit2,x): if unit1 == "g" and unit2 == "kg": ans = x/1000 elif unit2 == "g" and unit1 == "kg": ans = x*1000 elif unit1 == "kg" and unit2 == "lb": ans = x*2.205 elif unit2 == "kg" and unit1 == "lb": ans = x/2.205 elif unit1 == "g" and unit2 == "lb": ans = x/1000*2.205 elif unit2 == "g" and unit1 == "lb": ans = x*1000/2.205 elif unit1 == "oz" and unit2 == "lb": ans = x/16 elif unit2 == "oz" and unit1 == "lb": ans = x*16 elif unit1 == "kg" and unit2 == "oz": ans = x*16*2.205 elif unit2 == "kg" and unit1 == "oz": ans = x/16/2.205 elif unit1 == "g" and unit2 == "oz": ans = x*16*2.205/1000 elif unit2 == "g" and unit1 == "oz": ans = x/16/2.205*1000 print(f"{x} {unit1} is equal to {ans:.4f} {unit2}") import requests import json class CurrencyConverter(): def __init__(self,url): self.data = requests.get(url).json() self.currencies = self.data["rates"] def cur_convert(self,from_cur,to_cur,amount): initial_amount = amount if from_cur != "USD": # convert to USD first amount = amount / self.currencies[from_cur] amount = round(amount * self.currencies[to_cur], 4) # limit to 4 d.p. print(f"{initial_amount} {from_cur} is equal to {amount} {to_cur}") def main(): print("You can convert the following parameters") print("Temperature: Celsius, Fahrenheit, Kelvin") print("Length: cm, m, km, in") print("Weight: g, kg, lb, oz") print("Currency") unit1 = input("Enter the parameter you want to convert from: ") unit2 = input("Enter the parameter you want to convert to: ") x = float(input("Enter the value: ")) if unit1 and unit2 in ["cm","m","km","in"]: length(unit1,unit2,x) elif unit1 and unit2 in ["g","kg","lb","oz"]: weight(unit1,unit2,x) elif unit1 and unit2 in ["Celsius, Fahrenheit, Kelvin"]: temp(unit1,unit2,x) else: url = 'https://api.exchangerate-api.com/v4/latest/USD' converter = CurrencyConverter(url) converter.cur_convert(unit1,unit2,x) if __name__ == '__main__': main()
true
28dfdb424e4fb64043c592b7e46555ed191a257a
Python
linhai1111/cmdb_system
/CMDB_Project/client/test.py
UTF-8
977
3.140625
3
[]
no_license
############### 客户端发送动态令牌完成API验证 ############### import requests import time import hashlib # 生成动态令牌 ctime = time.time() # 动态时间戳 key = "asdfasdfasdfasdf098712sdfs" # 假定API发送过来的令牌 new_key = '%s|%s' % (key, ctime) # 在原有的随机字符串上加入动态时间,形成动态令牌 print(ctime) # 动态令牌通过md5进行加密 m = hashlib.md5() # 初始化md5 m.update(bytes(new_key, encoding='utf-8')) # 将动态令牌转换成字节,将由md5进行计算 md5_key = m.hexdigest() # 获得加密后的令牌 print(md5_key) md5_time_key = '%s|%s' % (md5_key, ctime) # 将生成动态令牌所需的时间一同发给API,让API进行md5进行加密,以便完成加密数据的比对 # 将添加了时间的动态令牌添加到请求头中发往API response = requests.get('http://127.0.0.1:8000/api/asset.html', headers={'OpenKey': md5_time_key}) print(response.text) # 获得响应结果
true
6064912b7d21df9d8b375c925c54262afd75fb58
Python
tims/addintent
/test_addintent.py
UTF-8
7,109
2.8125
3
[]
no_license
import unittest from addintent import * class TestGetMaximalGenerator(unittest.TestCase): def test_bottom(self): bottom = Concept([], ['a']) lattice = Lattice([]) self.assertEquals(get_maximal_generator(set(), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('a'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('ab'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('b'), bottom, lattice), bottom) def test_top_bottom(self): top = Concept([1], 'a') bottom = Concept([], 'ab') lattice = Lattice([ (top, bottom) ]) self.assertEquals(get_maximal_generator(set(), bottom, lattice), top) self.assertEquals(get_maximal_generator(set('a'), bottom, lattice), top) self.assertEquals(get_maximal_generator(set('ab'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('b'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('c'), bottom, lattice), bottom) def test_diamond(self): top = Concept([1, 2], []) left = Concept([1], 'a') right = Concept([2], 'b') bottom = Concept([], 'ab') lattice = Lattice([ (top, left), (top, right), (left, bottom), (right, bottom) ]) self.assertEquals(get_maximal_generator(set(), bottom, lattice), top) self.assertEquals(get_maximal_generator(set('a'), bottom, lattice), left) self.assertEquals(get_maximal_generator(set('ac'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('b'), bottom, lattice), right) self.assertEquals(get_maximal_generator(set('bc'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('ab'), bottom, lattice), bottom) self.assertEquals(get_maximal_generator(set('c'), bottom, lattice), bottom) class TestLattice(unittest.TestCase): def test_parents(self): top = Concept([1, 2], []) left = Concept([1], 'a') right = Concept([2], 'b') bottom = Concept([], 'ab') lattice = Lattice([ (top, left), (top, right), (left, bottom), (right, bottom) ]) self.assertEquals(lattice.parents(top), set()) self.assertEquals(lattice.parents(left), set([top])) self.assertEquals(lattice.parents(right), set([top])) self.assertEquals(lattice.parents(bottom), set([left, right])) class TestCreateLattice(unittest.TestCase): def test_trivial_lattice(self): rel = Relation([]) l = create_lattice_incrementally([], ['a'], rel) self.assertEquals(l.concepts, set([Concept([], 'a')])) class TestAddIntent(unittest.TestCase): def test_insert_into_middle(self): lattice = Lattice([]) bottom = Concept([], ['a', 'b']); lattice.add_concept(bottom) add_intent(1, set(), bottom, lattice) add_intent(2, set('b'), bottom, lattice) self.assertEquals(len(lattice.concepts), 3) self.assertEquals(lattice.parents(bottom), set([Concept([2], ['b'])])) self.assertEquals(lattice.children(lattice.top()), set([Concept([2], ['b'])])) def test_insert_into_lower_right_side(self): bottom = Concept([], 'abcded') lattice = Lattice([]) lattice.add_concept(Concept([], 'abcded')) add_intent(1, set(['a', 'b']), bottom, lattice) add_intent(2, set(['c', 'd']), bottom, lattice) lowerright = Concept([4], 'cde') add_intent(4, lowerright.intent, bottom, lattice) print 'CONCEPTS', lattice.concepts for c in lattice._relation.images: print c, '\t=>', lattice._relation.image(c) self.assertEquals(len(lattice.concepts), 5) self.assertEquals(lattice.parents(lowerright), set([Concept([2, 4], 'cd')])) self.assertEquals(lattice.parents(bottom), set([Concept([1], 'ab'), lowerright])) def test_insert_into_upper_left_and_lower_right_side(self): bottom = Concept([], 'abcd') lattice = Lattice([]) lattice.add_concept(bottom) add_intent(1, set(['a', 'b']), bottom, lattice) add_intent(2, set(['c', 'd']), bottom, lattice) self.assertEquals(len(lattice.concepts), 4) self.assertEquals(lattice.children(lattice.top()), set([Concept([1], 'ab'), Concept([2], 'cd')])) self.assertEquals(lattice.parents(lattice.bottom()), set([Concept([1], 'ab'), Concept([2], 'cd')])) add_intent(3, set('acd'), bottom, lattice) self.assertEquals(len(lattice.concepts), 6) self.assertEquals(lattice.children(lattice.top()), set([Concept([1, 3], 'a'), Concept([2, 3], 'cd')])) self.assertEquals(lattice.parents(lattice.bottom()), set([Concept([1], 'ab'), Concept([3], 'acd')])) self.assertEquals(lattice.children(Concept([1, 3], 'a')), set([Concept([1], 'ab'), Concept([3], 'acd')])) self.assertEquals(lattice.parents(Concept([3], 'acd')), set([Concept([1, 3], 'a'), Concept([2, 3], 'cd')])) def test_modify_existing_concept_with_same_intent(self): bottom = Concept([], 'ab') lattice = Lattice([]) lattice.add_concept(bottom) add_intent(1, set(['a']), bottom, lattice) self.assertEquals(len(lattice.concepts), 2) self.assertEquals(lattice.children(lattice.top()), set([lattice.bottom()])) self.assertEquals(lattice.parents(lattice.bottom()), set([lattice.top()])) self.assertEquals(lattice.top(), Concept([1], 'a')) self.assertEquals(lattice.bottom(), Concept([], 'ab')) add_intent(2, set(['a']), bottom, lattice) self.assertEquals(len(lattice.concepts), 2) self.assertEquals(lattice.children(lattice.top()), set([lattice.bottom()])) self.assertEquals(lattice.parents(lattice.bottom()), set([lattice.top()])) self.assertEquals(lattice.top(), Concept([1, 2], 'a')) self.assertEquals(lattice.bottom(), Concept([], 'ab')) def test_make_3_branches(self): bottom = Concept([], 'abc') lattice = Lattice([]) lattice.add_concept(bottom) add_intent(1, set(['a']), bottom, lattice) add_intent(2, set(['b']), bottom, lattice) add_intent(3, set(['c']), bottom, lattice) self.assertEquals(len(lattice.concepts), 5) self.assertEquals(lattice.top(), Concept([1, 2, 3], '')) self.assertEquals(lattice.bottom(), Concept([], 'abc')) def test_new_object_should_bubble_to_parent_concepts(self): bottom = Concept([], 'ab') lattice = Lattice([]) lattice.add_concept(bottom) add_intent(1, set(['a']), bottom, lattice) add_intent(2, set(['a', 'b']), bottom, lattice) self.assertEquals(len(lattice.concepts), 2) self.assertEquals(lattice.top(), Concept([1, 2], 'a')) self.assertEquals(lattice.bottom(), Concept([2], 'ab')) if __name__ == '__main__': unittest.main()
true
9f9efd39f95da5e2cb254687d2c33cb0b68a7587
Python
trinhgliedt/Algo_Practice
/2021_05_26_binary_search.py
UTF-8
575
3.9375
4
[]
no_license
def binary_search(container, item, left, right): if right < left: return -1 middle = (left+right)//2 if container[middle] == item: return middle elif container[middle] < item: print("checking on the right...") return binary_search(container, item, middle+1, right) elif container[middle] > item: print("checking on the left...") return binary_search(container, item, left, middle-1) arr = [-5, -3, 0, 6, 8, 10, 80] print(binary_search(arr, 10, 0, len(arr)-1)) print(binary_search(arr, 50, 0, len(arr)-1))
true
ecd2440eb2ca9f6853481818b474e154cf709921
Python
AdleySlbi/python-scrapy-project
/venv/demo/demo/spiders/aswxp.py
UTF-8
1,370
2.84375
3
[]
no_license
import scrapy # Création de la class aswxp (pour Adley Salabi Work Experiences) class aswxp(scrapy.Spider): name = "aswxp" # On renseigne l'url du portfolio start_urls = ["http://adleysalabi.com//"] # On parse la réponse def parse(self, response): # self.logger afin d'avooir un retour visuel que la spider à bien été lancée self.logger.info('Everything seems to be working :) ') # On décide de définir la class .workxp_one dans une variable workxps = response.css('div.workxp_one') # Puis on boucle sur toutes les div .workxp_one for workxp_one in workxps: # On renseigne chaque élément souhaité à l'aide de sélecteurs css yield { 'job': workxp_one.css('.workxp_job::text').get(), 'contrat': workxp_one.css('.workxp_type::text').get(), 'dates': workxp_one.css('.workxp_company_date>span:last-child::text').get(), 'company_name': workxp_one.css('.workxp_company_date>a::text').get(), 'company_url': workxp_one.css('.workxp_company_date>a::attr(href)').get(), 'resume': workxp_one.css('p::text').get(), 'skills': workxp_one.css('.workxp_skills_wrapper>span:last-child::text').get(), }
true
5febb2e297c924bbafa7e49f54682cb2fba90a76
Python
morganatmo/-afvinkopdr_5
/afv5 genen_vergelijken.py
UTF-8
999
3.390625
3
[]
no_license
sequence = 'ACTAGCAACCTCAAACAGACACCATGGTGCACCTGACTCCTGTGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCC' #def main(): # lijst1, lijst2 = getsequentie() # knipplaats(lijst1, lijst2) #def getsequentie(): # lijst1=[] # lijst2=[] # for regel in open ("enzymen.txt"): # enzym, seq = regel.split() # lijst1, append(enzym) # lijst2.append(seq.replace("^","")) # return lijst1, lijst2 #def knipplaats (lijst1, lijst2): # for i in range(len(lijst2)): # if (lijst2[i] in seq): # print ("match met", lijst1[i], "in positie", seq.index(lijst2[1])) # print(seq) #main() file = open("enzymen.txt", "r") for line in file: enzyme, seq = line.split() seq = seq.replace("^","") if seq in sequence: for i in range(len(seq)): if (seq[i] in sequence): print ("match met", enzyme[i], "op positie", sequence.index(seq[i])) print(sequence)
true
b74c2f00fc64c2bc1dea4b8f43c3f143159ecef9
Python
LavalleeAdamLab/sars-cov-2
/MotifEnumeration/FindMotifsInProteins.py
UTF-8
835
3.171875
3
[]
no_license
def search_protein_sequences_for_motifs(krogan_protein_list, window_size, motif_dictionary): """Finds motifs using a sliding window and inputs them in dictionary mapping to proteins in which they appear""" for seq_record in krogan_protein_list: window_begins = 0 window_ends = window_size while len(seq_record.seq[window_begins:window_ends]) == window_size: # Making sure the proteins accession id are unique if seq_record.id[3:9] not in motif_dictionary[seq_record.seq[window_begins:window_ends]]: motif_dictionary[seq_record.seq[window_begins:window_ends]].append(seq_record.id[3:9]) # Move the search window by one character from the start and end positions window_begins += 1 window_ends += 1 return motif_dictionary
true
f9c11839096abaa6947b28a4e0d6e8a361a1edb4
Python
engelsong/DataStructure
/02-线性结构2 Reversing Linked List_test.py
UTF-8
866
2.59375
3
[]
no_license
firstline = '00100 6 2'.split() userin = """00000 4 99999 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218""".split('\n') start = firstline[0] num = int(firstline[1]) K = int(firstline[2]) InPut = {} for i in userin: addr, data, nextone = i.split() InPut[addr] = [data, nextone] stack = [] keyword = start res = [] for t in range(len(InPut)): for k in xrange(K): stack.append(keyword) keyword = InPut[keyword][1] if keyword == '-1': break else: res += stack[::-1] stack = [] if keyword == '-1': if len(stack) < K: res += stack else: res += stack[::-1] break time = len(res) for x in xrange(time - 1): print '{} {} {}'.format(res[x], InPut[res[x]][0], res[x + 1]) print '{} {} {}'.format(res[-1], InPut[res[-1]][0], '-1')
true
85d44ceb91ec347b653fcb0fbba521a511343465
Python
Hereiam123/Python-Data-Excercises
/Data Visualization with Matplotlib/Matplotlib Starter.py
UTF-8
1,195
4.15625
4
[]
no_license
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 11) y = x**2 print(y) # Plot out data points plt.plot(x, y) # Add X, Y label and Title of plot plt.xlabel('X label') plt.ylabel('Y label') plt.title('Title') # Multiple subplots plt.subplot(1, 2, 1) plt.plot(x, y, 'r') plt.subplot(1, 2, 2) plt.plot(y, x, 'b') # Object oriented plot intro fig = plt.figure() # Setting axes values #Posistion and Sizing axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Plotting data on axes axes.plot(x, y) axes.set_xlabel('X Label') axes.set_ylabel('Y Label') axes.set_title('Set Title') # Set two figures on one canvas fig = plt.figure() axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) axes1.plot(x, y) axes1.set_title('Bigger Plot') axes2.plot(y, x) axes2.set_title('Smaller Plot') # Using subplots method fig = plt.figure() fig, axes = plt.subplots(nrows=2, ncols=2) # Show that this is an array of Matplotlib axes, and editable by index for current_ax in axes: print(current_ax) #axes[0].plot(x, y) #axes[0].set_title('First Plot') #axes[1].plot(y, x) #axes[1].set_title('Second Plot') # plt.tight_layout() # Show plots plt.show()
true
1a1a7182340ca81b99da0410d08eb0ed751ebfc0
Python
xrzy1985/python
/code(3.4)/arithmetic.py
UTF-8
849
4.25
4
[]
no_license
import random import sys import os # Arithmetic ''' Addition : + Subtraction : - Multiplication : * Division : / Modulus : % Exponential : ** Floor Division : // (division then discard remainder and rotate down) 14.5 would be changed to 14 ''' print("5 + 2 = ", 5+2) # 7 print("5 - 2 = ", 5-2) # 3 print("5 * 2 = ", 5*2) # 10 print("5 / 2 = ", 5/2) # 2.5 print("5 % 2 = ", 5%2) # 1 print("5 ** 2 = ", 5**2) # 25 print("5 // 2 = ", 5//2) # 2 # When performing arithmetic in any programming language you need to remember # ORDER OF OPERATION MATTERS # the code below will read the line, and do the arithmetic from left to right print("1 + 2 - 3 * 2 = ", 1+2-3*2) # -3 # The following will have completely different results than the code above print("(1 + 2 - 3) * 2 = ", (1+2-3)*2) # 0
true
9beca9b68dbf9b7de411c6f7afb49fec12c52492
Python
jjennyko/python1
/final_3.py
UTF-8
4,948
2.59375
3
[]
no_license
import pandas as pd datataipei = pd.read_csv("A_lvr_land_A.csv") datataichung = pd.read_csv("B_lvr_land_A.csv") datakaohsiung = pd.read_csv('E_lvr_land_A.csv') datanewtaipei = pd.read_csv('F_lvr_land_A.csv') print(datataipei.head()) datataipei = datataipei.drop(0) datataichung = datataichung.drop(0) datakaohsiung = datakaohsiung.drop(0) datanewtaipei = datanewtaipei.drop(0) datataipei['地區'] = '台北' datataichung['地區'] = '台中' datakaohsiung['地區'] = '高雄' datanewtaipei['地區'] = '新北' data = pd.concat([datataipei, datataichung, datakaohsiung, datanewtaipei], axis=0, join='inner').reset_index(drop=True) print(data.head()) print(data.info()) columns_mapping = {'鄉鎮市區':'towns', '交易標的':'transaction_sign', '土地區段位置建物區段門牌':'house_number', '土地移轉總面積平方公尺':'land_area_square_meter', '都市土地使用分區':'use_zoning', '非都市土地使用分區':'land_use_district', '非都市土地使用編定':'land_use', '交易年月日':'tx_dt', '交易筆棟數':'transaction_pen_number', '移轉層次':'shifting_level', '總樓層數':'total_floor_number', '建物型態':'building_state', '主要用途':'main_use', '主要建材':'main_materials', '建築完成年月':'complete_date', '建物移轉總面積平方公尺':'building_area_square_meter', '建物現況格局-房':'room_number', '建物現況格局-廳':'hall_number', '建物現況格局-衛':'health_number', '建物現況格局-隔間':'compartmented_number', '有無管理組織':'manages', '總價元':'total_price', '單價元平方公尺':'unit_price', '車位類別':'berth_category', '車位移轉總面積(平方公尺)':'berth_area_square_meter', '車位總價元':'berth_price', '備註':'note', '編號':'serial_number', '主建物面積':'main_building_area', '附屬建物面積':'auxiliary_building_area', '陽台面積':'balcony_area', '電梯':'elevator', '地區':'city' } analysis_columns = ['city','towns','main_use','use_zoning','total_price','building_area_square_meter', 'main_building_area', 'tx_dt','unit_price','room_number','hall_number','health_number'] columns_type = {'total_price': 'int','unit_price':'float','building_area_square_meter':'float', 'main_building_area': 'float', 'room_number': 'int','hall_number': 'int','health_number': 'int'} new_data = data.rename(columns=columns_mapping) new_data = new_data.loc[(new_data['main_use']=='住家用')&(new_data['use_zoning']=='住'),analysis_columns].dropna() print(new_data.info()) new_data = new_data.astype(columns_type) print(new_data.info()) print(new_data.head()) new_data['tx_dt_year'] = new_data['tx_dt'].apply(lambda x : int(x[:3])) new_data = new_data.loc[(new_data['tx_dt_year']==109)& (new_data['room_number']>=1)& (new_data['room_number']<=5)& (new_data['hall_number']>=1)& (new_data['hall_number']<=2)].reset_index(drop=True) print(new_data) new_data['buildin_area_square_feet'] = new_data['building_area_square_meter']*0.3025 new_data['main_buildin_area_square_feet'] = new_data['main_building_area']*0.3025 new_data['unit_price_square_feet'] = new_data['unit_price']/0.3025 print(new_data.describe()) # 發現最小值有0[tatal_price,building_area_square_meter] new_data = new_data.loc[(new_data['total_price']!=0)&(new_data['main_building_area']!=0)] print(new_data.describe()) new_data1 = new_data.loc[new_data['city']=='台北'].corr()[['total_price', 'unit_price_square_feet']] print(new_data1) import matplotlib.pyplot as plt new_data.boxplot(column=['unit_price_square_feet'], by='city', figsize=(16,6)) plt.xticks([1,2,3,4],['Taipei','Taichung','Kaohsiung','newTaipei']) plt.show() new_data.loc[new_data['city']=='台北'].boxplot(column=['total_price'], by='room_number', figsize=(16,6)) plt.show() from sklearn.preprocessing import LabelEncoder le = LabelEncoder().fit(new_data['towns'].values) new_data['new_towns'] = le.transform(new_data['towns'].values) print(new_data['new_towns'].head()) new_data.loc[new_data['city']=='台北'].boxplot(column=['unit_price_square_feet'], by='new_towns', figsize=(16,6)) plt.show() print(le.inverse_transform([26])) new_data2 = new_data.loc[new_data['city']=='台中'].corr()[['total_price','unit_price_square_feet']] print(new_data2) new_data.loc[new_data['city']=='台中'].boxplot(column='total_price', by='room_number', figsize=(16,6)) plt.show() new_data.loc[new_data['city']=='台中'].boxplot(column='unit_price_square_feet', by='new_towns', figsize=(16,6)) plt.show() print(le.inverse_transform([76]))
true
80fd78ff262653ca576f31492c1e97e6fa5cd2f8
Python
SphiwokuhleS/netcut
/netcut.py
UTF-8
787
2.53125
3
[]
no_license
#!/usr/bin/env python3 import netfilterqueue import os def forward_packets(): # forward packets that are stacked in the queue os.system('iptables -I FORWARD -j NFQUEUE --queue-num 0') def reset_iptables(): #reset iptables to normal os.system('iptables --flush') def process_packet(packet): #drop all packets coming torwads the target from the ap packet.drop() def accept_packets(packet): #if you want to forward the packets instead of dropping them packet.accept() reset_iptables() forward_packets() try: while True: queue = netfilterqueue.NetfilterQueue() queue.bind(0, process_packet) queue.run() except KeyboardInterrupt: print("\n\033[1;34;40m[-] Detected CNTL C. RESSETING IPTABLES BACK TO NORMAL......") reset_iptables()
true
b15f304d2f8931f9ee651e7132fe94567b7808f4
Python
QWQ-pixel/practice_python
/telegrams.py
UTF-8
169
3.703125
4
[]
no_license
def word(): # телеграммы letters = input() num_letters = len(letters) * 40 print(num_letters // 100, "p.", num_letters % 100, "коп.") word()
true
222da7a46c0a7912a8c613f0f17faa28101f81f2
Python
oilmcut2019/final-assign
/jupyter-u07157128/Quiz_Python_20190309.git/Quiz_5.py
UTF-8
260
3.359375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[3]: a = int(input()) if a == 3 or a == 4 or a == 5: print ('spring') elif a == 6 or a == 7 or a == a == 8: print ('summer') elif a == 9 or a == 10 or a == 11: print ('fall') else: print ('winter')
true
3f0103b82046813ccfa6593800d5bbbaf01264e2
Python
MilitaKocharovskaya/phyton3
/treeF.py
UTF-8
1,651
3.34375
3
[]
no_license
class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.key = data class Tree: def __init__(self): self.root = None self.data = None self.Node = None def find(self, data): p = self.root while (p is not None) and (p.key != data): if data > p.key: p = p.right else: p = p.left return p def add(self, data): p = self.find(data) node = Node(data) if self.root is None: self.root = node return p = self.root while True: if data < p.key: if p.left is None: p.left = node node.parent = p break else: p = p.left else: if p.right is None: p.right = node node.parent = p break else: p = p.right def print(self, root = 0): if root == 0: root = self.root if root is None: return if root.left is not None: self.print(root.left) a.append(root.data) if root.right is not None: self.print(root.right) return a tree = Tree() a = [] b = [] s = list(map(int, input().split())) for x in s: tree.add(x) tree.print() for x in a: if x not in b: b.append(x) for x in b: k = 0 for y in a: if y == x: k += 1 print(x, k)
true
2874c36b0d254031a8a27924ab6f9286ffe191c7
Python
mkdvice/Exercicios-udemy-sysOP
/Maior_Idade.py
UTF-8
507
3.8125
4
[]
no_license
# -*- coding: utf-8 -*- import datetime __author__ = "@MkDVice" print('Análise de idade.\n') ano = datetime.date.today().year # definindo o ano atual pela biblioteca datetime nasc = int(input('Qual é o ano de seu nascimento? ')) # entrada do ano de nascimento idade = (ano - nasc) # cálculo de idade ''' Condição para mostar se a pessoa é adulta (maior que 18 anos de idade) ou não adulta ''' if(idade >= 18): print('\nA pessoa é adulta') else: print('\nA pessoa não é adulta')
true
fa403bcdee16c8573c45356e3cb753e297932ad9
Python
lespinoza182/TTMelanomaESCOM
/Entrega1-25Sep2018.py
UTF-8
2,861
2.890625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: luisespinoza, manuelarreola """ from PIL import Image from matplotlib import pyplot as plt from numpy import array from collections import Counter import numpy as np import statistics import time import math tiempoInicial = time.time() rutaImagen = ("C:/Users/lespi/OneDrive/Documentos/TT/PruebasPython/LeerImagen/imagenes/lesion1.bmp") imagen = Image.open(rutaImagen) imagen.show() '''Imagen a Escala de Grises: Promedio''' imgGrisProm = imagen i = 0 while i < imgGrisProm.size[0]: j = 0 while j < imgGrisProm.size[1]: r, g, b = imgGrisProm.getpixel((i, j)) g = (r + g + b) / 3 gris = int(g) pixel = tuple([gris, gris, gris]) imgGrisProm.putpixel((i, j), pixel) j+=1 i+=1 imgGrisProm.show() '''Imagen a Escala de Grises: Método de Python''' imgGris = imagen.convert('L') imgGris.show() '''Filtro Máximo de la Imagen''' imgMax = imgGris [ren, col] = imgMax.size matriz = np.asarray(imgMax, dtype = np.float32) i = 0 while i < ren - 3: j = 0 while j < col - 3: submatriz = matriz[j:j+3,i:i+3] submatriz = submatriz.reshape(1, 9) nuevo = int(max(max(submatriz))) imgMax.putpixel((i + 1, j + 1),(nuevo)) j+=1 i+=1 imgMax.show() '''Filtro Mínimo de la Imagen''' imgMin = imgGris [ren, col] = imgMin.size matriz = np.asarray(imgMin, dtype = np.float32) i = 0 while i < ren - 3: j = 0 while j < col - 3: submatriz = matriz[j:j+3,i:i+3] submatriz = submatriz.reshape(1, 9) nuevo = int(min(min(submatriz))) imgMin.putpixel((i + 1, j + 1),(nuevo)) j+=1 i+=1 imgMin.show() '''Filtro Moda de la Imagen''' imgModa = imgGris [ren, col] = imgModa.size matriz = np.asarray(imgModa, dtype = np.float32) i = 0 while i < ren - 3: j = 0 while j < col - 3: submatriz = matriz[j:j+3,i:i+3] submatriz = submatriz.reshape(1, 9) nuevo = (max(submatriz)) data = Counter(nuevo) nuevo = data.most_common(1) nuevo = max(nuevo) nuevo = int(nuevo[0]) imgModa.putpixel((i + 1, j + 1),(nuevo)) j+=1 i+=1 imgModa.show() '''Filtro Mediana de la Imagen''' [ren, col] = imgGris.size matriz = np.asarray(imgGris, dtype = np.float32) i = 0 while i < ren - 3: j = 0 while j < col - 3: submatriz = matriz[j:j+3,i:i+3] submatriz = submatriz.reshape(1,9) nuevo = (max(submatriz)) nuevo = statistics.median(nuevo) nuevo = int(nuevo) imgGris.putpixel((i+1,j+1), (nuevo)) j += 1 i += 1 imagenMediana = imgGris imagenMediana.show() tiempoFin = time.time() print('El Proceso Tardo: ', tiempoFin - tiempoInicial, ' Segundos')
true
751ac58b1d68337393f267d524228342169e339c
Python
Redomeliu/Python
/编程题/第4章-2 统计素数并求和 (20分).py
UTF-8
499
3.515625
4
[]
no_license
def prime(p): from math import sqrt is_prime = True for index in range(int(sqrt(p)), 1, -1): if p % index == 0: is_prime = False break if p != 1 and is_prime: return True else: return False def PrimeSum(m, n): s = 0 count=0 for index in range(m, n+1): if prime(index): s += index count +=1 return count,s m, n = input().split() m = int(m) n = int(n) (a,b)=PrimeSum(m, n) print(a,b)
true
bf4bde0f55245a5a53e493093dc9561a0a977397
Python
mahnaz-ahmadi/pythonClass
/Student_Assistant.py
UTF-8
1,541
3.71875
4
[]
no_license
what_shape = input("what shape are you need ?\nchoice one of this shapes :\ \nRectangle\nSquare\nTriangle\nCircle\nTrapezius\nParallelogram\n*") what_calculate = input("What to calculate?\nchoice one of this opr :\ \nArea\nEnvironment\n*") def student_assistant(what_shape, what_calculat): if what_shape == "Triangle" and what_calculate == "Area": rule = float(input("plz enter rule value : ")) height = float(input("plz enter height value : ")) #print(f"Arae is = {rule * height / 2}") Area = rule * height / 2 return Area if what_shape == "Triangle" and what_calculate == "Environment": edge_one = float(input("plz enter edge_one value : ")) edge_two = float(input("plz enter edge_two value : ")) edge_three = float(input("plz enter edge_three value : ")) #print(f"Environment is = {edge_one + edge_two + edge_three}") Environment = edge_one + edge_two + edge_three return Environment if what_shape == "Circle" and what_calculate == "Area": redios = float(input("plz enter redios value : ")) #print(f"Arae is = {redios **2 * 3.14}") Area = redios **2 * 3.14 return Area if what_shape == "Circle" and what_calculate == "Environment": redios = float(input("plz enter redios value : ")) #print(f"Environment is = {redios * 2 * 3.14}") Environment = redios * 2 * 3.14 return Environment print(student_assistant(what_shape, what_calculate))
true
273cb0163feb684062ba3639d009ed3738ece7ce
Python
Hee-Jae/Algorithm
/boj/16236.py
UTF-8
2,103
3.078125
3
[]
no_license
from collections import deque def bfs(baby): size, a,b = baby fish = [] for i in range(N): for j in range(N): if 0 < sea[i][j] < size: fish.append((i,j)) dist = [] # print(fish) for fx,fy in fish: visited = [[0 for _ in range(N)] for _ in range(N)] n = 0 q = deque() q.append((a,b)) dx = [1,-1,0,0] dy = [0,0,1,-1] print("fish :",fx,fy) # print("a b :", a, b) while q: # print("q:",q) x,y = q.popleft() # print("x,y:",x,y) if visited[x][y] == 0: visited[x][y] = 1 for k in range(4): nx = x + dx[k] ny = y + dy[k] if 0 <= nx < N and 0 <= ny < N: # print("nx,ny:",nx,ny) print("visited[0][2] : ", visited[0][2]) if visited[nx][ny] == 0: # print("n,f",nx,ny,fx,fy) if nx == fx and ny == fy: n += 1 dist.append((n,nx,ny)) print("append:",n,nx,ny) q.clear() break elif sea[nx][ny] > size: visited[nx][ny] = 1 else: if(visited[nx][ny] == 0): visited[nx][ny] = 1 q.append((nx,ny)) n += 1 # print(visited) print("===") # print("n:",n) print(dist) return dist N = int(input()) sea = [list(map(int, input().split())) for _ in range(N)] size = 2 for i in range(N): for j in range(N): if sea[i][j] == 9: baby = (size,i,j) # 상어 위치 time = 0 mama = 1 while mama: size1, x1, y1 = baby feeds = bfs(baby) print("feeds :",feeds) # feeds = sorted(feeds, key = lambda) if not feeds: mama = 0 break break
true
f7f6753304fec91ac43e561d4f2434e3d94e1502
Python
danrdash/AdvancedLabinC
/ex3/ex3_server
UTF-8
1,297
2.96875
3
[]
no_license
#!/usr/bin/python2.7 -tt from socket import * import sys BUFFER_SIZE = 1024 ERROR_404 = 'HTTP/1.1 404 Not Found\r\nContent-type: text/html\r\nContent-length:' \ ' 113\r\n\r\n<html><head><title>Not Found</title></head><body>\r\nSorry, the ' \ 'object you requested was not found.\r\n</body></html>\r\n\r\n' def receive_request(LB_socket): end_of_request = False request = '' while not end_of_request: request += LB_socket.recv(BUFFER_SIZE) end_of_request = (request.count('\r\n\r\n') == 1) return request def is_valid_request(request): return request.count('GET /counter') == 1 def get_response(valid_request_num, is_valid_request): if is_valid_request: answer = 'HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: ' answer += '{}\r\n\r\n{}\r\n\r\n'.format(len(str(valid_request_num)), valid_request_num) else: answer = ERROR_404 return answer server_port = int(sys.argv[1]) s = socket() s.connect(('localhost', server_port)) valid_request_num = 0 while True: full_request = receive_request(s) if is_valid_request(full_request): valid_request_num += 1 response = get_response(valid_request_num, is_valid_request(full_request)) s.send(response)
true
4ce78aa46343a28740b067ee31d00ae290574655
Python
daniel-reich/turbo-robot
/CNpZrDFf3Ct7MzQrw_10.py
UTF-8
951
4.28125
4
[]
no_license
""" Create a function that takes two integers and returns `true` if a digit repeats three times in a row at any place in `num1` **AND** that same digit repeats two times in a row in `num2`. ### Examples trouble(451999277, 41177722899) ➞ True trouble(1222345, 12345) ➞ False trouble(666789, 12345667) ➞ True trouble(33789, 12345337) ➞ False ### Notes You can expect every test case to contain exactly two integers. """ def trouble(num1, num2): string1 = False string2 = False rep_num = 0 count = 1 for n in range(len(str(num1)) - 1): if str(num1)[n] == str(num1)[n+1]: count += 1 print(count) if count == 3: rep_num = int(str(num1)[n]) string1 = True count = 1 break if str(num2).count(str(rep_num)) >= 2: string2 = True print(str(string1) + ", " + str(string2)) if string1 and string2: return True else: return False
true
44c653e3d5bf7e187e1b3ae6609737a43864f8bf
Python
shifteight/python
/sicp/high_order_func.py
UTF-8
645
4.15625
4
[]
no_license
##################### # 高阶函数:函数作为参数 ##################### def summation(n, term, next): total, k = 0, 1 while k <= n: total, k = total + term(k), next(k) return total def identity(k): return k def cube(k): return pow(k, 3) def successor(k): return k + 1 def sum_naturals(n): return summation(n, identity, successor) def sum_cubes(n): return summation(n, cube, successor) # 另一个例子: 级数和逼近Pi def pi_term(k): denominator = k * (k + 2) return 8 / denominator def pi_next(k): return k + 4 def pi_sum(n): return summation(n, pi_term, pi_next)
true
7d7ab2c8ee16b8e5b9e6d3eb0a39ec0f5463e99a
Python
shadowshadow725/blank
/Model/Players/PlayerHuman.py
UTF-8
728
3.328125
3
[ "MIT" ]
permissive
from Model.Players.Player import Player from Model.Move import Move from Model.Checkers import Checkers class PlayerHuman(Player): """ PlayerHuman represents a standard piece of colour black or white and is restricted to move forwards diagonally. """ def __init__(self, player: str, checkers: Checkers): super().__init__(player, checkers) # def get_move(self, row: int, col: int, drow: int, dcol: int): """ Pygame will retrieve the coordinates of the tile and pass those into getMove to return a Move object. """ # Row, col are the coordinates of the piece you are moving onto some # tile: final_row, final_col return Move(row, col, drow, dcol)
true
05981899b77f7d661f2c86168511e374d43e09c3
Python
alexchonglian/readings
/effective-python/2020-05/item_15_example_05.py
UTF-8
143
2.75
3
[]
no_license
def my_func(**kwargs): for key, value in kwargs.items(): print('%s = %s' % (key, value)) my_func(goose='gosling', kangaroo='joey')
true
220c02fb56bf904200dc64298bc06e9d325e3795
Python
Yurisbk/Codigos-Python
/counting duplicates.py
UTF-8
415
3.59375
4
[]
no_license
def duplicate_count(text): i = 0 new_list = [] repetidas = [] for letra in text: if letra.lower() not in new_list: new_list.append(letra.lower()) else: repetidas.append(letra.lower()) for letra in new_list: if letra.lower() in repetidas: i = i + 1 return i print(duplicate_count("Indivisibilities"))
true
b6f555da450048ea8920f46dcc40e1bbc4fe31d6
Python
paularcoleo/dailyprog
/spelling_bee.py
UTF-8
627
3.1875
3
[]
no_license
import sys def main(letters, length): central_letter = letters[0] with open('words.txt', 'r') as fh: words = fh.read().splitlines() answers = [w for w in words if "'" not in w and central_letter in w and len(w) >= length and len(set(w) - set(letters)) == 0] print('\nANSWERS\n=======================') for answer in answers: extra = '*' if set(answer) == set(letters) else '' print(answer+extra) if __name__ == '__main__': letters = sys.argv[1] try: length = int(sys.argv[2]) except IndexError: length = 5 print(sys.argv) main(letters, length)
true
6c6d5ffdc0a2905e8531d5c794ac4eb294ab53d0
Python
CNfzq/Django-framework-learning
/Database/views_5.py
UTF-8
7,422
3.75
4
[]
no_license
from django.shortcuts import render from django.http import HttpResponse # Create your views here. """ '''数据库的相关操作一般在视图函数里写''' from . import models #导入模型文件,要使用里面的模型类(表) # 添加数据 def add_user(request): '''方法1:通过模型类,往里面传参,这个参数就是字段名,模型类会接收相应字段的值''' # 先实例化类,通过对象去保存 args=models.User(name='fzq',age=18) args.save() #保存对象到数据库里面 '''方法2:跟python里面类实例化一样的操作''' args1=models.User() #实例化对象 args1.name='辣椒' #通过对象.属性 args1.age=21 args1.save() '''方法3:User类提供一个objects对象,这个对象里面包含了很多方法,与上面几种方法相比较,该方法不用save()的操作,会自动帮我们保存的''' models.User.objects.create(name='fzq',age=21) #objects提供一个新建的方法create(),用来插入数据用的,但是,该方法不用再写save()方法保存了 '''方法4:和方法3差不多,但是又有区别。方法3假如有相同的值,一样会添加进去,没有去重的功能 方法4:如果存在了就不添加还会返回一个错误的页面,不存在就添加进去,有去的功能''' # models.User.objects.get_or_create(name='fzq',age=18) #数据库里有重复的值会返回报错 return HttpResponse('添加数据成功') # 查询数据 def search_user(request): ''' 1.查找所有数据: all()和filter()方法返回的是QuerySet对象. get()方式返回的单个对象,如果符合条件的对象有多个,则get报错! ''' data=models.User.objects.all() #查到数据库里所有的数据,返回的是一个QuerySet对象类型,所有的数据都在这个对象里 print(data) print(data[1]) #可用索引取值,也可以for循环遍历 print(data[1].name) #查字段的值 print(data[2:5]) #也可以支持切片,不支持负索引取值 '''2.查找某一条数据''' data1=models.User.objects.get(id=2) #get()查询的值必须是唯一的值,id是唯一的 print(data1) #输出的是User<id=2,name=fzq,age=18>,这是模型类实例对象,拿到的是表里面的一条数据 print(data1.name) print(data1.age) # data2 = models.User.objects.get(name='fzq') #会报错,get()只能拿数据是唯一的值,不能够重复的值 # print(data2) '''3.按照条件查询数据''' data3=models.User.objects.filter(name='fzq') #把自己需要的筛选条件加进去,查询重复的数据不会报错 print(data3) #返回的是QuerySet对象,可以索引取值 # QuerySet对象也提供了一些方法取值 print(data3.first()) #获取第一条数据 print(data3.last()) #获取最后一条数据 return HttpResponse('查询数据成功') ''' 数据库相关的接口(QuerySet API): 1.从数据库中查询出来的结果一般是一个集合,这个集合叫做 QuerySet. 2.QuerySet是可迭代对象. 3.QuerySet支持切片, 不支持负索引. 4.可以用list强行将QuerySet变成列表. ''' # 删除数据 def delete_user(request): ''' 某个对象是否有某种方法,可以通过dir(obj)来进行查看. ''' models.User.objects.filter(name='小付').delete() models.User.objects.get(name='小黄').delete() #get()返回的是实例的对象(类的实例),也就是表里面的一条数据 return HttpResponse('删除数据成功') # 更新数据 def update_user(request): '''方法1:直接使用update()方法修改''' models.User.objects.filter(name='小黄').update(name='辣椒') '''方法2:get()方法查询返回的是模型类实例对象,拿到的是表里面的一条数据 拿到的数据不能直接update(),只能通过实例.属性的方式去更新数据 ''' # 先查找到数据,再属性赋值修改 result=models.User.objects.get(name='小李子') result.name='李子' result.save() #切记:一定要保存 return HttpResponse('更新数据成功') '''把查询数据单独拿出来研究,常用的查询方法和查询条件''' '''查询方法''' # filter(**kwargs)方法:根据参数提供的提取条件,获取一个过滤后的QuerySet data=models.User.objects.filter(name='fzq',age=18) #多个条件用逗号(,)隔开即可 # exclude()方法:排除某个条件:排除 (name=辣椒) 的记录 data1=models.User.objects.exclude(name='辣椒') # 获取一个记录对象(表里面的一条数据) data2=models.User.objects.get(name='李子') # 注意:get()返回的对象具有唯一性质,如果符合条件的对象有多个,则会报错 # order_by:对查询出来的数据进行排序 data3=models.User.objects.order_by('age') # 多项排序 data4=models.User.objects.order_by('age','id') # 逆向排序 data5=models.User.objects.order_by('-age') #逆向排序就是在条件的前面加个负号 # 将返回来的QuerySet中的Model转换为字典 data6=models.User.objects.all().values() # 获取当前查询到的数据的总数 data7=models.User.objects.count() ''' 常用的查询条件: 查找对象的条件的意思是传给以上方法的一些参数。 相当于是SQL语句中的where语句后面的条件,语法为字段名__规则(是连着连个下划线哦) ''' '''查询条件''' # exact:相当于等于号(name='辣椒'),准确查询 result=models.User.objects.filter(name__exact='辣椒') print(result) # contains:包含,里面包含了什么东西,字段名name包含了‘小’字 result1=models.User.objects.filter(name__contains='小') print(result1) # startwith:以什么开始 result2=models.User.objects.filter(name__startwith='小') # endwith:以什么结尾 result3=models.User.objects.filter(name__endwith='q') # istartswith:同startwith,忽略大小写;iendswith:同endwith,忽略大小写 result4=models.User.objects.filter(name__istartwith='fzq') # in:成员所属,18或者21 resul5t=models.User.objects.filter(age__in=[18,21]) # range:范围所属,区间:18,19,20 result6=models.User.objects.filter(age__range=(18,20)) # gt:大于 result7=models.User.objects.filter(age__gt=20) # gte:大于等于 result8=models.User.objects.filter(age__gte=20) # lt:小于 result9=models.User.objects.filter(age__lt=20) # lte:小于等于 result0=models.User.objects.filter(age__lte=20) # isnull:判断是否为空 result11=models.User.objects.filter(name__isnull='辣椒') """ from .models import Ftest def add_ftest(request): # 添加数据 # Ftest.objects.create(name='fzq', age=21,note='我是fzq小弟') # ft=Ftest(name='GG',age=21,note='哈哈哈') # ft.save() # 查询+修改数据 # f1=Ftest.objects.get(name='辣椒') #返回的是单个实例 # f1.note='我是假辣椒' # f1.save() f2=Ftest.objects.filter(name='狒狒') #返回的是QuerySet对象 print(f2) # f2.update(name='小付fff') # f2.note='你好' # f2.save() '''更改失败,不能这样修改的,必须先获取,在filter()[0]获取,再更改''' f2[0].note='大神的' f2[0].save() return HttpResponse('成功')
true
2dbc28d6373d137b104447a93cbf65cbc0390fce
Python
IgorTomilov/Lesson-Python
/HW2_Task_2.py
UTF-8
892
4.28125
4
[]
no_license
# Перетворення в оберенне число # number = str (input ("Введіть чотирьохзначне число: ")) # numb_list = list(number) # numb_list.reverse() # number1 = "".join(numb_list) # # print("'Оберенене' число дорівнюватиме: ", number1) # Відсортування числа # number = str (input ("Введіть чотирьохзначне число: ")) # numb_list = list(number) # numb_list.sort() # # print("Відсортовані цифри дорівнюють: ", numb_list) # Добуток цифр числа number = int (input ("Введіть чотирьохзначне число: ")) d1 = number % 10 number = number // 10 d2 = number % 10 number = number // 10 d3 = number % 10 number = number // 10 print("Добуток цифр числа:", number * d1 * d2 * d3)
true
493334dae982fa4307c233234bc1ad00e9b3d5a4
Python
Muzashii/Exercicios_curso_python
/exercicios seção 6/ex 16.py
UTF-8
270
3.734375
4
[]
no_license
""" numeros naturais ate o numeor escolhido decrecente par """ numero = int(input(f'Digite um numero: ')) if(numero%2) == 0: numero -= 1 for num in range(numero, -1, -2): print(num) else: for num in range(numero, -1, -2): print(num)
true
9914919450299dae2d6a27bae8600d1604364a53
Python
iTeam-co/pytglib
/pytglib/api/functions/get_chat_member.py
UTF-8
847
2.984375
3
[ "MIT" ]
permissive
from ..utils import Object class GetChatMember(Object): """ Returns information about a single member of a chat Attributes: ID (:obj:`str`): ``GetChatMember`` Args: chat_id (:obj:`int`): Chat identifier member_id (:class:`telegram.api.types.MessageSender`): Member identifier Returns: ChatMember Raises: :class:`telegram.Error` """ ID = "getChatMember" def __init__(self, chat_id, member_id, extra=None, **kwargs): self.extra = extra self.chat_id = chat_id # int self.member_id = member_id # MessageSender @staticmethod def read(q: dict, *args) -> "GetChatMember": chat_id = q.get('chat_id') member_id = Object.read(q.get('member_id')) return GetChatMember(chat_id, member_id)
true
42928a1b9a93399414e2ae6cf03d68d3e5884b3d
Python
gainiu/pythonTestFile
/20201006.py
UTF-8
3,598
3.4375
3
[]
no_license
# class Restaurant(): # def __init__(self,restaurant_name,cuisine_type): # self.restaurant_name=restaurant_name # self.cuisine_type=cuisine_type # self.number_served=0 # def describe_restaurant(self): # print('Restaurant name: '+self.restaurant_name) # print('Cuisine type: '+self.cuisine_type) # def open_restaurant(self): # print('The restaurant is in business.') # def set_number_served(self,numbers): # self.number_served=numbers # def increment_number_served(self,numbers): # self.number_served+=numbers # class IceCreamStand(Restaurant): # def __init__(self, restaurant_name, cuisine_type,flavors): # super().__init__(restaurant_name, cuisine_type) # self.flavors=flavors # def show_icecream(self): # print('We have many kinds of icecream:') # for flavor in self.flavors: # print('-'+flavor) # my_icecream=IceCreamStand('ICE','icecream',['milk','chocolate','fruits']) # my_icecream.describe_restaurant() # my_icecream.show_icecream() # class User(): # def __init__(self,first_name,last_name,address): # self.first_name=first_name # self.last_name=last_name # self.address=address # def describe_user(self): # print('Full name: '+self.first_name+' '+self.last_name) # print('Address: '+self.address) # def greet_user(self): # print('Hello~'+self.first_name+' '+self.last_name) # class Admin(User): # def __init__(self,first_name,last_name,address): # super().__init__(first_name,last_name,address) # self.privilege=Privileges() # class Privileges(): # def __init__(self): # self.privileges=['can add post','can delete post','can ban user'] # def show_privileges(self): # print('Admin has the following privileges: ') # for privilege in self.privileges: # print('-'+privilege) # my_admin=Admin('xiao','min','china') # my_admin.privilege.show_privileges() class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print('This car has '+str(self.odometer_reading)+' miles on it.') def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print('You can\'t roll back an odometer!') def increment_odometer(self, miles): self.odometer_reading += miles class Battery(): def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print('This car has a '+str(self.battery_size)+'-kwh battery.') def get_range(self): if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = 'This car can go approximately '+str(range) message += ' miles on a full charge.' print(message) def upgrade_battery(self): if self.battery_size != 85: self.battery_size = 85 class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) my_tesla.battery.get_range() my_tesla.battery.upgrade_battery() my_tesla.battery.get_range()
true
79620941b4946f546f21445ec8871a7fd68e0e99
Python
s-nilesh/Leetcode-May2020-Challenge
/16-OddEvenLinkedList.py
UTF-8
1,266
3.828125
4
[]
no_license
#PROBLEM # Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. # You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. # Example 1: # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # Example 2: # Input: 2->1->3->5->6->4->7->NULL # Output: 2->3->6->7->1->5->4->NULL # Note: # The relative order inside both the even and odd groups should remain as it was in the input. # The first node is considered odd, the second node even and so on ... #SOLUTION # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: oddHead = oddTail = ListNode(None) evenHead = evenTail = ListNode(None) cnt = 1 while head: if cnt & 1: oddTail.next = oddTail = head else: evenTail.next = evenTail = head head = head.next cnt += 1 evenTail.next, oddTail.next = None, evenHead.next return oddHead.next
true
dc0776d8a745c3330c08eaa891ae63893aa2b27a
Python
Vaibhav-Bobde/Cricket-Match-Prediction
/Scripts/Feature_Selection.py
UTF-8
5,393
2.75
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection import RandomizedSearchCV from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn import svm from sklearn.neighbors import KNeighborsClassifier matches_data = pd.read_csv("G:\CSUF Study\ADBMS\Project\DataSet\IPL\processed_data.csv") outcome_var = ['winner'] l=['team1', 'team2', 'toss_winner','city','toss_decision','p1','p2','SAB','team1_bat_score', 'team2_bat_score','team1_ball_score','team2_ball_score'] predictor_var = l pd_var=[] for pp in l: pd_var.append(pp) X=matches_data[predictor_var] y=matches_data[outcome_var] clf = RandomForestClassifier() clf = clf.fit(X, y) print(X.shape) print(clf.feature_importances_) ll=zip(clf.feature_importances_,predictor_var) for importance,feature in ll: print(feature + ' =') print('%s' % '{0:.3%}'.format(importance)) # print feature,importance model = SelectFromModel(clf, prefit=True) X_new = model.transform(X) X_new.shape[1] #removing features--------------------- ii=1 print(len(predictor_var)) print(X_new.shape[1]) for importance,feature in ll: if ii<len(predictor_var)-X_new.shape[1]+3: print(feature) predictor_var.remove(feature) else: break ii+=1 print(len(predictor_var)) #Principal Component Analysis--------------------------- scaler = StandardScaler() X1=scaler.fit_transform(X) #using pca from sklearn import decomposition pca = decomposition.PCA() #all features train_x_fit=pca.fit_transform(X1) train_x_cov=pca.get_covariance() exp_var=pca.explained_variance_ratio_ #Percentage of variance explained by each of the selected components. # print exp_var.shape print(exp_var) zipped = zip(exp_var,pd_var) def getKey(item): return item[0] # zipped.sort() zipped=sorted(zipped, key=getKey) print(zipped) #plotting explained variance plt.figure(figsize=(10, 6)) plt.bar(range(exp_var.shape[0]), exp_var, alpha=0.5, align='center', label='individual explained variance') plt.ylabel('Explained variance ratios') plt.xlabel('Principal components ids') plt.legend(loc='best') plt.savefig('pca.png') plt.tight_layout() print("features to removed = ",zipped[:3]) predictor_var.remove('team2_ball_score') predictor_var.remove('team1_ball_score') predictor_var.remove('team2_bat_score') #Finding best parameters for Random Forest using GridSearchCV------------------ # Number of trees in random forest n_estimators = [int(i) for i in np.linspace(start = 200, stop = 2000, num = 10)] # Maximum number of levels in tree max_depth = [int(i) for i in np.linspace(10, 110, num = 11)] max_depth.append(None) # Number of features which we have to consider at every split max_features = ['auto', 'sqrt'] # Method for selecting samples for training each tree bootstrap = [True, False] # Minimum number of samples which are required to split a node min_samples_split = [2, 5, 10] # Minimum number of samples which are required at each leaf node min_samples_leaf = [1, 2, 4] # Create the random grid random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} print(random_grid) # First create the base model to tune # Random search of parameters, using 3 fold cross validation, # search across 100 different combinations, and use all available cores rfc = RandomForestClassifier() rf_random = RandomizedSearchCV(estimator = rfc, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1) rf_random.fit(matches_data[predictor_var],matches_data['winner']) print(rf_random.best_params_) print(rf_random.best_score_) print("----------------SVM Best Params-----------------------") C = 10. ** np.arange(-3, 8) gamma = 10. ** np.arange(-5, 4) print(C) param_grid = {'C': [0.001,0.01,0.1,1,10],'gamma':gamma,'kernel':['linear','rbf']} svm_clf = RandomizedSearchCV(svm.SVC(), param_distributions = param_grid,n_iter = 100, cv = 3, scoring='accuracy') svm_clf.fit(matches_data[predictor_var], matches_data['winner']) print(svm_clf.best_params_) print(svm_clf.best_score_) print("------------Logistic Regression Best Params-------------") param_grid_LR={ 'C': [0.001,0.01,0.1,1,10,100,1000], 'solver' : ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'] } logistic_clf = GridSearchCV(LogisticRegression(n_jobs=-1), param_grid_LR,cv=3, scoring='accuracy') logistic_clf.fit(matches_data[predictor_var], matches_data['winner']) print(logistic_clf.best_params_) print(logistic_clf.best_score_) params_knn = { "n_neighbors": np.arange(1, 31, 2), "metric": ["euclidean", "cityblock"], 'leaf_size':[1,2,3,5], 'weights':['uniform', 'distance'], 'algorithm':['auto', 'ball_tree','kd_tree','brute'] } knn_clf = RandomizedSearchCV(KNeighborsClassifier(n_jobs=-1), param_distributions = params_knn,n_iter = 200, cv = 3, scoring='accuracy') knn_clf.fit(matches_data[predictor_var], matches_data['winner']) print(knn_clf.best_params_) print(knn_clf.best_score_) print("OK")
true
290e0c893066ae6d0f86efeb33ee60532a2d0dd7
Python
zazf/CS_Homework
/wordcount.py
UTF-8
637
3.359375
3
[]
no_license
# This is mean to get your started # Accelerated Computer Science @ BDFZ Spring 2017 # Assignment: Word Counting # By Zhang Zhifei file = open(r"lear.txt", "r", encoding="utf-8-sig") wordcount={} words = file.read().lower().replace(',', '').replace('.','').replace('-',' ').replace('!','').replace('?','').replace(';','').replace('*','').replace('"','').replace("'",'').split() for word in words: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 copy = [] for k,v in wordcount.items(): copy.append((v, k)) copy = sorted(copy, reverse=True) for k in copy: print (k[1], k[0])
true
920051296556b1770e2b4d83d78e2844cd3e828a
Python
danningyu/UCLA-Dining-Menu
/request.py
UTF-8
4,248
2.828125
3
[]
no_license
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup from enum import Enum # from datetime import date, datetime import datetime from apscheduler.schedulers.blocking import BlockingScheduler import collections sched = BlockingScheduler() TEST_URL = 'http://menu.dining.ucla.edu/Menus' meal_period_key = {0:'Breakfast', 1:'Lunch', 2:'Dinner'} dining_hall_key = {0:'Covel', 1:'De Neve', 2:'Feast', 3:'Bruin Plate'} def simple_get(url): print('Downloading content from menu webpage...') try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): print('Successfully downloaded page.') return resp.content else: return None except RequestException as e: log_error('Error during requests to {0}:{1}'.format(url, str(e))) return None def is_good_response(resp): content_type = resp.headers['Content-Type'].lower() return(resp.status_code==200 and content_type is not None and content_type.find('html')>-1) def log_error(e): print(e) Items_And_Date = collections.namedtuple('Items_And_Date', ['items', 'date']) def separate_by_meal_period(html_file): #takes in html page, and places menu items in appropriate list #returns list of lists, one list for each meal period soup = BeautifulSoup(html_file, 'html.parser') dates_and_items = soup.find_all(['h2', 'h3', 'a']) #h2 for date, a for menu items # print(dates_and_items) # for num, item in enumerate(dates_and_items): # print(str(num) + str(item)) breakfast_items = [] lunch_items = [] brunch_items = [] dinner_items = [] food_items = [breakfast_items, brunch_items, lunch_items, dinner_items] dates_and_items = dates_and_items[41:] #eliminate headers dates_and_items = dates_and_items[:-5] #and footers index=0 date_time_obj = None for link in dates_and_items: try: # print(link.contents[0]) if (link.contents[0].find("Detailed Menu") != -1 or link.contents[0].find("Nutritive Analysis") != -1 or link.contents[0].find("Detailed") != -1): continue; if any('Breakfast Menu' in s for s in link): # print("Starting breakfast") index = 0 elif any('Brunch Menu' in s for s in link): # print("Starting brunch") index = 1 elif any('Lunch Menu' in s for s in link): # print("Starting lunch") index = 2 elif any('Dinner Menu' in s for s in link): # print("Starting dinner") index = 3 if(link.contents[0].find(' for ') != -1): # print("Found a menu time: " + link.contents[0]) #need spaces, otherwise fails on words like "California" contains_date = link.contents[0] menu_date = contains_date[contains_date.find(',')+2:] date_time_obj = menu_date # date_time_obj = datetime.datetime.strptime(menu_date, '%B %d, %Y') # print('Extracted date: ' + str(date_time_obj)) if(str(link).find('h3') != -1): food_items[index].append('\n' + link.contents[0].upper()+'\n') else: food_items[index].append(link.contents[0]+'\n') except IndexError: print("Empty item") continue; return_val = Items_And_Date(food_items, date_time_obj) return return_val def export_data(): print('Running program...') current_day = datetime.date.today() current_time = datetime.datetime.now().time() output = simple_get(TEST_URL) #get the webpage # print(output) print('Exporting data...') all_items_and_date = separate_by_meal_period(output) all_items = all_items_and_date[0] # for meal_period_items in all_items: # meal_period_items.append('\n') filename = "menu.txt" file1 = open(filename, "w+") if all_items_and_date[1] is not None: file1.writelines('UCLA Dining menu for ' + all_items_and_date[1]+ '\n') else: file1.write("No menu items found.\n") file1.writelines('Generated on ' + str(current_day) + ' ' + str(current_time) + ' PDT\n\n') for meal_items in all_items: if len(meal_items) != 0: file1.writelines(meal_items) file1.write('\n') file1.close() print('Done running program, will run again in 10 minutes...') #run once upon startup export_data() @sched.scheduled_job('interval', seconds=600) def timed_job(): print('Executing job on ' + str(datetime.datetime.now().time())) export_data() sched.start()
true
6dc591429b36753972391c8935e572488f500ca5
Python
mgungor1925/g-rsel-programlama--devi
/soru4.py
UTF-8
280
3.6875
4
[]
no_license
sayac = 0 for x in range(102, 988): yuzler = str(x)[0] onlar = str(x)[1] birler = str(x)[2] if yuzler != onlar and yuzler != birler and onlar != birler: sayac = sayac+1 print(x) print("Rakamları birbirinden farklı sayı toplamı : "+str(sayac))
true
d76623f8f3a5b574374f7bab170cc7de0754196e
Python
bgnori/online-judge
/project-euler/peprime.py
UTF-8
3,009
3.34375
3
[]
no_license
class Prime: ''' from 0021 ''' def __init__(self): self.primes = [2] self.count = 0 self.pomp = self.prime_seq() def _isprime(self, k): assert k <= self.known_lagest()*self.known_lagest() for x in self.primes: if x*x > k: return True if not k % x: return False assert False def known_lagest(self): return self.primes[-1] def prime_seq(self): n = 3 while True: if self._isprime(n): self.primes.append(n) self.count+=1 yield self.known_lagest() n+=2 assert False def extend(self, n): while self.known_lagest()*self.known_lagest() < n: self.pomp.next() def isprime(self, n): ''' >>> p = Prime() >>> p.isprime(2) True >>> p.isprime(29) True >>> p.isprime(30) False >>> p.isprime(1000) False ''' if n == 1: return False self.extend(n) return self._isprime(n) def decompose(self, n): ''' >>> p = Prime() >>> p.decompose(60) [2, 2, 3, 5] >>> p.decompose(3) [3] >>> p.decompose(220) [2, 2, 5, 11] >>> p.decompose(284) [2, 2, 71] ''' self.extend(n) r = [] for p in self.primes: d, m = divmod(n, p) while m == 0: n = d r.append(p) d, m = divmod(n, p) if n != 1: #fixd bug in 0012 r.append(n) return r def divisors(self, n): ''' >>> p = Prime() >>> p.divisors(28) set([1, 2, 4, 7, 14, 28]) ''' r = set() d = self.decompose(n) v = len(d) for i in range(pow(2, v)): mask = 1 x = 1 for j in range(v): if mask & i: x *= d[j] mask *=2 r.add(x) return r def proper_divisors(self, n): ''' >>> p = Prime() >>> p.proper_divisors(28) set([1, 2, 4, 7, 14]) >>> sorted(list(p.proper_divisors(220))) [1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110] ''' s = self.divisors(n) s.remove(n) return s def d(self, n): ''' >>> p = Prime() >>> p.d(220) 284 >>> p.d(284) 220 ''' return sum(self.proper_divisors(n)) def amicable(self, n): ''' >>> p = Prime() >>> p.amicable(220) 284 >>> a = p.amicable(5) >>> print a None >>> a = p.amicable(6) >>> print a ''' candidate = self.d(n) if n == self.d(candidate) and not (candidate == n): return candidate return None
true
8a6eb29884d7600e7064a1d8979227e7e54a1dfc
Python
sumeetgajjar/CS7610-F20
/lab1/test_multicast.py
UTF-8
10,340
2.515625
3
[]
no_license
#!/usr/bin/env python3 import logging import os import subprocess import unittest from concurrent.futures import ThreadPoolExecutor from typing import Dict, List, Callable def configure_logging(level=logging.INFO): logger = logging.getLogger() logger.setLevel(level) log_formatter = logging.Formatter("[%(process)d] %(asctime)s [%(levelname)s] %(name)s: %(message)s") console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) configure_logging(logging.DEBUG if os.getenv("VERBOSE", "0") == "1" else logging.INFO) NETWORK_BRIDGE = "cs7610-bridge" NETWORK_BRIDGE_EXISTS_CMD = f'docker network ls --quiet --filter name={NETWORK_BRIDGE}' NETWORK_BRIDGE_CREATE_CMD = f'docker network create --driver bridge {NETWORK_BRIDGE}' RUNNING_CONTAINERS_CMD = 'docker ps -a --quiet --filter name=sumeet-g*' STOP_CONTAINERS_CMD = 'docker stop {CONTAINERS}' REMOVE_CONTAINERS_CMD = 'docker rm {CONTAINERS}' START_CONTAINER_CMD = "docker run --detach" \ " --name {HOST} --network {NETWORK_BRIDGE} --hostname {HOST}" \ " -v {LOG_DIR}:/var/log/lab1 --env GLOG_log_dir=/var/log/lab1" \ " sumeet-g-prj1 {VERBOSE} --hostfile /hostfile {ARGS}" class ProcessInfo: def __init__(self, return_code: int, stdout: str, stderr: str) -> None: super().__init__() self.return_code = return_code self.stdout = stdout self.stderr = stderr class BaseSuite(unittest.TestCase): HOSTS = [] LOG_ROOT_DIR = 'logs' @classmethod def setUpClass(cls): super().setUpClass() with open('hostfile', 'r') as hostfile: cls.HOSTS = [host.strip() for host in hostfile.readlines()] logging.info(f'hosts: {cls.HOSTS}') cls.__create_logs_dir() cls.__setup_network_bridge() @classmethod def assert_process_exit_status(cls, name: str, p_info: ProcessInfo) -> None: assert p_info.return_code == 0, \ f"{name} failed, returncode: {p_info.return_code}, stdout: {p_info.stdout}, stderr: {p_info.stderr}" @classmethod def run_shell(cls, cmd: str) -> ProcessInfo: logging.debug(f"running cmd: {cmd}") p = subprocess.run(cmd.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE) return ProcessInfo(p.returncode, p.stdout.decode('UTF-8'), p.stderr.decode('UTF-8')) @classmethod def __setup_network_bridge(cls) -> None: p_exists = cls.run_shell(NETWORK_BRIDGE_EXISTS_CMD) cls.assert_process_exit_status("network bridge exists cmd", p_exists) if len(p_exists.stdout.strip()): logging.info(f"docker network bridge: {NETWORK_BRIDGE} exists") else: logging.info("docker network bridge does not exists, creating one") p_create = cls.run_shell(NETWORK_BRIDGE_CREATE_CMD) cls.assert_process_exit_status("network bridge create cmd", p_create) @classmethod def get_host_log_dir(cls, host: str) -> str: return os.path.abspath(f'{cls.LOG_ROOT_DIR}/{host}') @classmethod def get_verbose_logging_flag(cls) -> str: return f'--v {os.getenv("VERBOSE", 0)}' @classmethod def get_container_logs(cls, container_name: str) -> List[str]: p = cls.run_shell(f"docker logs {container_name}") cls.assert_process_exit_status("docker logs cmd", p) raw_log = p.stdout + os.linesep + p.stderr log_lines = [line.strip() for line in raw_log.strip().split(os.linesep)] return log_lines @classmethod def tail_container_logs(cls, container_name: str, callback: Callable[[str], bool]) -> None: continue_tailing = True with subprocess.Popen(['docker', 'logs', container_name, '-f'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p: while continue_tailing: line = p.stderr.readline() if not line: break line = line.decode('UTF-8') continue_tailing = callback(line) p.kill() @classmethod def __create_logs_dir(cls) -> None: for host in cls.HOSTS: host_log_dir = cls.get_host_log_dir(host) if os.path.isdir(host_log_dir): logging.info(f"log dir already exists: {host_log_dir}") else: logging.info(f"creating log dir: {host_log_dir}") os.makedirs(host_log_dir, exist_ok=True) @classmethod def stop_and_remove_running_containers(cls, remove_container=False) -> None: logging.info("stopping running containers") p_run = cls.run_shell(RUNNING_CONTAINERS_CMD) cls.assert_process_exit_status("running containers cmd", p_run) if p_run.stdout.strip(): running_containers = p_run.stdout.strip().split(os.linesep) logging.info(f"found running containers: {running_containers}") p_stop = cls.run_shell(STOP_CONTAINERS_CMD.format(CONTAINERS=" ".join(running_containers))) cls.assert_process_exit_status("stop containers cmd", p_stop) if remove_container: p_remove = cls.run_shell(REMOVE_CONTAINERS_CMD.format(CONTAINERS=" ".join(running_containers))) else: logging.info("no running containers found") class MulticastSuite(BaseSuite): @classmethod def setUpClass(cls): return super().setUpClass() def setUp(self) -> None: self.stop_and_remove_running_containers(remove_container=True) def tearDown(self) -> None: self.stop_and_remove_running_containers() def __get_app_args(self, host: str, senders: List[str], msg_count, drop_rate, delay, initiate_snapshot_count) -> Dict[str, str]: return { 'HOST': host, 'NETWORK_BRIDGE': NETWORK_BRIDGE, 'LOG_DIR': self.get_host_log_dir(host), 'VERBOSE': self.get_verbose_logging_flag(), 'ARGS': f" --senders {','.join(senders)}" f" --msgCount {msg_count}" f" --dropRate {drop_rate}" f" --delay {delay}" f" --initiateSnapshotCount {initiate_snapshot_count}" } @classmethod def __get_delivery_order(cls, host: str, expected_msg_count: int) -> List[str]: delivery_order = [] def __callback(line: str) -> bool: line = line.strip() if "delivering" in line: delivery_msg = line.split("]")[1] delivery_order.append(delivery_msg) logging.info(f"found delivery message for host: {host}, message: {delivery_msg}") return len(delivery_order) < expected_msg_count cls.tail_container_logs(host, __callback) return delivery_order def __assert_ordering_is_same_for_all_processes(self, expected_msg_count: int) -> None: with ThreadPoolExecutor(len(self.HOSTS)) as executor: futures = [executor.submit(self.__get_delivery_order, host, expected_msg_count) for host in self.HOSTS] delivery_orders = [future.result() for future in futures] for ix, delivery_order in enumerate(delivery_orders): self.assertTrue(delivery_order) self.assertEqual(delivery_orders[0], delivery_order, f"order of process {ix} does not match with that of process {0}") def __test_wrapper(self, senders: List[str], msg_count=0, drop_rate=0.0, delay=0, snapshot_initiator=None, initiate_snapshot_count=0) -> None: logging.info(f"senders for the test: {senders}") logging.info(f"args: msgCount: {msg_count}, dropRate: {drop_rate}, delay: {delay}, " f"initiateSnapshotCount: {initiate_snapshot_count}") for host in self.HOSTS: host_initiate_snapshot_count = initiate_snapshot_count if host == snapshot_initiator else 0 logging.info(f"starting container for host: {host}") p_run = self.run_shell( START_CONTAINER_CMD.format(**self.__get_app_args(host, senders=senders, msg_count=msg_count, drop_rate=drop_rate, delay=delay, initiate_snapshot_count=host_initiate_snapshot_count))) self.assert_process_exit_status(f"{host} container run cmd", p_run) expected_msg_count = len(senders) * msg_count logging.info("grepping message delivery in process logs") self.__assert_ordering_is_same_for_all_processes(expected_msg_count) def test_one_sender(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=4) def test_two_senders(self): self.__test_wrapper(senders=self.HOSTS[0:2], msg_count=4) def test_all_senders(self): self.__test_wrapper(senders=self.HOSTS, msg_count=4) def test_drop_half_messages(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=2, drop_rate=0.5) def test_drop_majority_messages(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=2, drop_rate=0.75) def test_delay_messages(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=2, delay=2000) def test_drop_delay_messages(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=2, drop_rate=0.25, delay=2000) def test_snapshot_with_one_sender(self): self.__test_wrapper(senders=self.HOSTS[0:1], msg_count=8, snapshot_initiator=self.HOSTS[0], initiate_snapshot_count=3) def test_snapshot_with_two_senders(self): self.__test_wrapper(senders=self.HOSTS[0:2], msg_count=8, snapshot_initiator=self.HOSTS[1], initiate_snapshot_count=3) def test_snapshot_with_all_senders(self): self.__test_wrapper(senders=self.HOSTS, msg_count=8, snapshot_initiator=self.HOSTS[-1], initiate_snapshot_count=3) if __name__ == '__main__': unittest.main()
true
a597ddc9f3ac98aec1cb7ec1fb9bcdb0dd818eec
Python
jayeshkhairnar19/Game
/CWH(Game).py
UTF-8
3,103
4.09375
4
[]
no_license
limit=1 count=0 computer_score=0 human_score=0 print('\t\t\t\tWELCOME TO THE GAME') print('Important rules for the game are given below') print('stone=s\nPaper=p\nScissor=c') print('You have only 21 chances to play the game and if you manage to score more than computer then you will be winner!') import random list=['s','p','c'] while(limit<=21): x=input('Enter your choice:') limit+=1 choice=random.choice(list) count+=1 print('The no of attempts are',count,'out of 21.') # print(choice) if(x==choice): #print(x) print("Computer's choice:",choice) print('Answers for both of you is same...so no points will be given') elif x=='s' and choice=='p': print("Computer's choice:",choice) print('Computer wins') computer_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) elif x=='s' and choice=='c': print("Computer's choice:",choice) print('Human wins') human_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) elif x=='p'and choice=='s': print("Computer's choice:",choice) print('Human wins') human_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) elif x=='p' and choice=='c': print("Computer's choice:",choice) print('Computer wins') computer_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) elif x=='c' and choice=='s': print("Computer's choice:",choice) print('Computer wins') computer_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) elif x=='c' and choice=='p': print("Computer's choice:",choice) print('Human wins') human_score+=1 print('Human score is:',human_score) print('computer score is:',computer_score) if human_score>computer_score: print('\nHUMAN WINS THE GAME AT THE END.And the score of human is',human_score,'and score of computer is',computer_score) print('Thanks for giving your time,hope you have enjoyed the game') elif human_score==computer_score: print('\nThe game is tied and the the score of human is',human_score,'and score of computer is',computer_score) print('Thanks for giving your time,hope you have enjoyed the game') else: print('\nCOMPUTER WINS THE GAME AT THE END.And the score of human is',human_score,'and score of computer is',computer_score) print('Thanks for giving your time,hope you have enjoyed the game')
true
72ef933b117cb367c230c7ee3c0895130fafd1d6
Python
Josrodjr/compiladores_proyecto3
/tables.py
UTF-8
6,191
2.71875
3
[]
no_license
from tabulate import tabulate class Tabla_simbolos: current_id = 0 current_location = 0 t_name = '' t_id = [] simbolo = [] location = [] number_of = [] tipo = [] ambito = [] def __init__(self, name): self.t_name = name self.current_id = 0 self.current_location = 0 self.simbolo = [] self.location = [] self.number_of = [] self.tipo = [] self.ambito = [] def insert_simbolo(self, s): self.simbolo.append(s) def insert_tipo(self, t): self.tipo.append(t) def insert_ambito(self, a): self.ambito.append(a) def insert_location(self, l): self.location.append(l) def insert_number_of(self, n): self.number_of.append(n) def assign_id(self): self.t_id.append(self.current_id) self.current_id = self.current_id + 1 def determine_location(self, type_size, count): found_location = self.current_location new_location = self.current_location + type_size*count self.current_location = new_location return found_location def create_entry(self, s, t, a, lo, no): self.assign_id() self.insert_simbolo(s) self.insert_tipo(t) self.insert_ambito(a) self.insert_location(self.determine_location(lo, no)) self.insert_number_of(no) def print_table(self): tabulate_matrix = [] for i in range(len(self.simbolo)): tabulate_matrix.append([self.t_id[i], self.simbolo[i], self.tipo[i], self.ambito[i], self.location[i], self.number_of[i]]) print('table name: '+self.t_name) print(tabulate(tabulate_matrix, headers=['id', 'simbolo', 'tipo', 'ambito', 'location', 'number_of'], tablefmt='github')) def return_table(self): tabulate_matrix = [] for i in range(len(self.simbolo)): tabulate_matrix.append([self.t_id[i], self.simbolo[i], self.tipo[i], self.ambito[i], self.location[i], self.number_of[i]]) return tabulate(tabulate_matrix, headers=['id', 'simbolo', 'tipo', 'ambito', 'location', 'number_of'], tablefmt='grid') class Tabla_tipos: current_id = 0 t_id = [] nombre = [] tamanio = [] tipo = [] def __init__(self): self.current_id = 0 self.t_id = [] self.nombre = [] self.tamanio = [] self.tipo = [] def insert_nombre(self, no): self.nombre.append(no) def insert_tamanio(self, ta): self.tamanio.append(ta) def insert_tipo(self, ti): self.tipo.append(ti) def assign_id(self): self.t_id.append(self.current_id) self.current_id = self.current_id + 1 def create_entry(self, no, ta, ti): self.assign_id() self.insert_nombre(no) self.insert_tamanio(ta) self.insert_tipo(ti) def generate_default_values(self): self.create_entry('int', 4, 'generico') self.create_entry('char', 1, 'generico') self.create_entry('boolean', 1, 'generico') self.create_entry('void', 0, 'generico') self.create_entry('struct', 4, 'generico') def search_type(self, typename): curr_index = 0 for value in self.nombre: if value == typename: return curr_index else: curr_index += 1 return -1 def search_size(self, typeid): def_size = 0 for index in range(len(self.t_id)): if self.t_id[index] == typeid: def_size = self.tamanio[index] return def_size def print_table(self): tabulate_matrix = [] for i in range(len(self.nombre)): tabulate_matrix.append([self.t_id[i], self.nombre[i], self.tamanio[i], self.tipo[i]]) print('table name: Tipos') print(tabulate(tabulate_matrix, headers=['id', 'nombre', 'tamaño', 'tipo'], tablefmt='github')) def return_table(self): tabulate_matrix = [] for i in range(len(self.nombre)): tabulate_matrix.append([self.t_id[i], self.nombre[i], self.tamanio[i], self.tipo[i]]) return tabulate(tabulate_matrix, headers=['id', 'nombre', 'tamaño', 'tipo'], tablefmt='grid') class Tabla_ambitos: current_id = 0 t_id = [] nombre = [] tipo = [] padre = [] def __init__(self): self.current_id = 0 self.t_id = [] self.nombre = [] self.tipo = [] self.padre = [] def insert_nombre(self, no): self.nombre.append(no) def insert_padre(self, pa): self.padre.append(pa) def insert_tipo(self, ti): self.tipo.append(ti) def assign_id(self): self.t_id.append(self.current_id) self.current_id = self.current_id + 1 def create_entry(self, no, pa, ti): self.assign_id() self.insert_nombre(no) self.insert_padre(pa) self.insert_tipo(ti) def generate_default(self, void_type): self.create_entry('Program', 'none', void_type) def search_ambito(self, ambitoname): curr_index = 0 for value in self.nombre: if value == ambitoname: return curr_index else: curr_index += 1 return -1 def print_table(self): tabulate_matrix = [] for i in range(len(self.nombre)): tabulate_matrix.append([self.t_id[i], self.nombre[i], self.tipo[i], self.padre[i]]) print('table name: Ambitos') print(tabulate(tabulate_matrix, headers=['id', 'nombre', 'tipo', 'padre'], tablefmt='github')) def return_table(self): tabulate_matrix = [] for i in range(len(self.nombre)): tabulate_matrix.append([self.t_id[i], self.nombre[i], self.tipo[i], self.padre[i]]) return tabulate(tabulate_matrix, headers=['id', 'nombre', 'tipo', 'padre'], tablefmt='grid')
true
0cfaa40354fd05997bf24129d15c630220293fe1
Python
emcoglab/ldm-train-and-evaluate
/scripts_clean_BBC/1_srt_deformat.py
UTF-8
1,911
2.609375
3
[]
no_license
""" =========================== Remove subtitle markup from .srt files, leaving only the subtitle content. =========================== Dr. Cai Wingfield --------------------------- Embodied Cognition Lab Department of Psychology University of Lancaster c.wingfield@lancaster.ac.uk caiwingfield.net --------------------------- 2017 --------------------------- """ import glob import sys import logging from os import path, mkdir import srt from ..ldm.utils.logging import log_message, date_format from ..ldm.preferences.preferences import Preferences logger = logging.getLogger(__name__) def main(start_over=False): raw_subs_dir = Preferences.bbc_processing_metas["raw"].path processed_subs_dir = Preferences.bbc_processing_metas["no_srt"].path if not path.isdir(processed_subs_dir): logger.warning(f"{processed_subs_dir} does not exist, making it.") mkdir(processed_subs_dir) subtitle_paths = list(glob.iglob(path.join(raw_subs_dir, '*.srt'))) for file_i, subtitle_path in enumerate(subtitle_paths): target_path = path.join(processed_subs_dir, path.basename(subtitle_path)) # If we've already processed this file, skip it. if path.isfile(target_path) and not start_over: logger.info(f"{file_i:05d}: SKIPPING {target_path}") continue with open(subtitle_path, mode="r", encoding="utf-8", errors="ignore") as subtitle_file: sub_file_content = subtitle_file.read() subs = list(srt.parse(sub_file_content)) with open(target_path, mode="w") as target_file: for sub in subs: target_file.write(sub.content + "\n") logger.info(f"{file_i:05d}: Processed {target_path}") if __name__ == "__main__": logging.basicConfig(format=log_message, datefmt=date_format, level=logging.INFO) logger.info("Running %s" % " ".join(sys.argv)) main() logger.info("Done!")
true
35cda96d7ad6e7950f19bd36f8fdd313cd786956
Python
FlavrHub/measurement_tagger
/modules/utils.py
UTF-8
2,333
3.328125
3
[]
no_license
"""Helper functions""" from functools import reduce from itertools import chain from importlib import import_module from collections.abc import Sequence from dataclasses import dataclass from typing import List, Any, Callable, Iterable, Iterator @dataclass(frozen=True) class Measurement: """Dataclass containing measurement value and unit""" value: str unit: str def __str__(self): return f"{self.value} {self.unit}" def map_funcs(obj: str, func_list: List[Callable]) -> str: """Apply series of functions to string""" return reduce(lambda o, func: func(o), func_list, obj) def lower(lst: List[str]) -> List[str]: """Lowercase a list of strings""" return [s.lower() for s in lst] def join(iterable: Iterable, sep: str = " ") -> str: """Join an interable with sep""" return sep.join(map(str, iterable)) def ints(start: int, end: int) -> Iterator: """The integers from start to end, inclusive""" return range(start, end + 1) def flatten(list_of_lists: List[List[Any]]) -> List[Any]: """Flatten a list of lists""" return list(chain.from_iterable(list_of_lists)) def overlapping(iterable: Iterable, n: int) -> Iterator: """Generate all (overlapping) n-element subsequences of iterable""" assert isinstance(iterable, Sequence) yield from (iterable[i: i + n] for i in range(len(iterable) + 1 - n)) def strip_list(lst: List[str]) -> List[str]: """Strip whitespace from list of strings""" return [l.strip() for l in lst if l is not None] def two_round(num: float) -> str: """Return str of num rounded to 2 sig""" return str(round(num, 2)) def get_class(module: str, class_: str) -> Any: """Get instantiated class given name and module""" clazz = getattr(import_module(module), class_) return clazz() def hyponyms(synset_name): """Given a WordNet synset name, return the lemmas of all its hyponyms in the WordNet semantic graph. Arguments: synset_name {str} -- a high-level synset Returns: {Set[str]} -- set of hyponyms """ from nltk.corpus import wordnet as wn synset = wn.synset(synset_name) hypos = list(synset.closure(lambda s: s.hyponyms())) lemmas = flatten([synset.lemma_names() for synset in hypos]) return {l.replace("_", " ") for l in lemmas}
true
7ab0df986640e046e932b82f0b45e4ab6f726e7e
Python
alice-biometrics/meiga
/tests/unit/test_result_attributes_of_object_type.py
UTF-8
1,960
2.984375
3
[ "MIT" ]
permissive
import pytest from meiga import Error, Failure, Result, Success @pytest.mark.unit class TestResultAttributesOfObjectType: def should_repr_a_success_result(self): result = Result(success=2) assert "Result[status: success | value: 2]" == result.__repr__() def should_repr_a_success(self): result = Success(2) assert "Result[status: success | value: 2]" == result.__repr__() def should_repr_a_failure_result(self): result = Result(failure=Error()) assert "Result[status: failure | value: Error]" == result.__repr__() def should_repr_a_failure(self): result = Failure(Error()) assert "Result[status: failure | value: Error]" == result.__repr__() def should_eq_two_equal_success_result(self): result_1 = Result(success=2) result_2 = Result(success=2) assert result_1 == result_2 def should_eq_two_different_success_result(self): result_1 = Result(success=2) result_2 = Result(success=3) assert result_1 != result_2 def should_eq_a_result_with_another_type(self): result_1 = Result(success=2) result_2 = "no_result_value" assert result_1 != result_2 def should_eq_two_equal_failure_result(self): result_1 = Result(failure=Error()) result_2 = Result(failure=Error()) assert result_1 == result_2 def should_eq_two_different_failure_result(self): result_1 = Result(failure=Error()) result_2 = Result(failure=Exception()) assert result_1 != result_2 @pytest.mark.parametrize( "result", [ Result(success="hello"), Result(failure=Exception()), Result(failure=Error()), Success("hello"), Failure(Exception()), Failure(Error()), ], ) def should_hashes_are_equal(self, result: Result): assert hash(result) == hash(result)
true
84df80dbd2d8aac3e6f493ca0790444eb0109b05
Python
sonthanhnguyen/projecteuler
/project_euler_37.py
UTF-8
3,196
4.59375
5
[]
no_license
""" Project Euler 37: Truncatable primes The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ import time import project_euler def find_prime_numbers_with_sieving(limit): """ Find all prime numbers less than a limit using sieving, except 2, 3, 5, 7 :param limit: the upper bound number :return: list containing all primes less than the limit """ # A boolean list, with index indicating number, value in that index is True if that number is prime, and # False otherwise primes = [True] * limit # 0 and 1 are not prime primes[0], primes[1] = [False] * 2 for index, value in enumerate(primes): # The first number with True is a prime, but the multiples of it are not if value is True: primes[index * 2::index] = [False] * (((limit - 1) // index) - 1) prime_list = [i for i in range(limit) if primes[i]] # Return prime list, except 2, 3, 5, 7 return prime_list[4:] def is_truncatable_prime(number): """ Decide if a number is a truncatable prime :param number: input number :return: True if the number is a truncatable, and False otherwise """ for i in range(1, len(str(number))): # Check if the number is NOT right truncatable if not project_euler.is_prime(int(str(number)[:i])): return False # Check if the number is NOT left truncatable if not project_euler.is_prime(int(str(number)[-i:])): return False # The number is truncatable return True def sum_truncatable_primes(): """ Find the sum of all 11 truncatable primes :return: the sum """ # NOTE: instead of searching for all prime numbers, and stop when we find the 11th truncatable prime, we define # the search space and hope that we will find all 11 truncatable primes in that space, if not, we increase the # the search space. # There is no guarantee that a certain search space contains all the numbers, but with a define search space, we # can use sieving to find all primes in such space, with faster speed. search_limit = 1000000 prime_list = find_prime_numbers_with_sieving(search_limit) the_sum = 0 counter = 0 for prime_number in prime_list: if is_truncatable_prime(prime_number): print("The truncatable prime is {0}".format(prime_number)) the_sum += prime_number counter += 1 # Found all 11 required prime, no need to check for more. if counter == 11: break return the_sum def main(): """ Test function """ start_time = time.time() result = sum_truncatable_primes() print("Result is {0}, found in {1} seconds".format(result, time.time() - start_time)) if __name__ == "__main__": main()
true
30e130251188822480387e4e47e99f5f741df5fb
Python
lamacii64/terminal_dungeon
/terminal_dungeon/map_loader.py
UTF-8
1,643
3.1875
3
[ "MIT" ]
permissive
import json from pathlib import Path import numpy as np MAP_DIR = Path("terminal_dungeon") / "maps" class Map: """ A helper class for easy loading of maps. Maps with sprites should have corresponding json file with same name as the map and extension `.sprites`. Each sprite in the file is a dict with keys "pos", "tex", for position and name of the texture the sprite uses. """ def __init__(self, map_name): # Load map with open(MAP_DIR / (map_name + ".txt")) as file: tmp = file.read() self._map = np.array([list(map(int, line)) for line in tmp.splitlines()]).T # Load sprites for map if (sprites_path := (MAP_DIR / (map_name + ".sprites"))).is_file(): with open(sprites_path) as file: sprites = json.load(file) self.sprites = [Sprite(**sprite) for sprite in sprites] else: self.sprites = [] def __getitem__(self, key): # We often would convert key to a tuple with ints when indexing the map elsewhere, so we just moved that logic to here: return self._map[int(key[0]), int(key[1])] class Sprite: """Helper class to simplify working with sprites.""" __slots__ = "pos", "tex", "relative" def __init__(self, pos, tex): self.pos = np.array(pos) self.tex = tex self.relative = np.array([0.0, 0.0]) @property def distance(self): return self.relative @ self.relative def __lt__(self, other): # Sprites are sorted in reverse from their distance to player in the renderer. return self.distance > other.distance
true
d0cdac11947630dc8d33a93d645b2b45c7324f77
Python
broadinstitute/viral-core
/file_utils.py
UTF-8
10,584
2.6875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#!/usr/bin/env python3 """ Utilities for dealing with files. """ __author__ = "tomkinsc@broadinstitute.org" __commands__ = [] import argparse import csv import logging import pandas import util.cmd import util.file import util.misc log = logging.getLogger(__name__) # ============================== # *** merge_tarballs *** # ============================== def merge_tarballs(out_tarball, in_tarballs, threads=None, extract_to_disk_path=None, pipe_hint_in=None, pipe_hint_out=None): ''' Merges separate tarballs into one tarball data can be piped in and/or out ''' util.file.repack_tarballs(out_tarball, in_tarballs, threads=threads, extract_to_disk_path=extract_to_disk_path, pipe_hint_in=pipe_hint_in, pipe_hint_out=pipe_hint_out) return 0 def parser_merge_tarballs(parser=argparse.ArgumentParser()): parser.add_argument( 'out_tarball', help='''output tarball (*.tar.gz|*.tar.lz4|*.tar.bz2|*.tar.zst|-); compression is inferred by the file extension. Note: if "-" is used, output will be written to stdout and --pipeOutHint must be provided to indicate compression type when compression type is not gzip (gzip is used by default). ''') parser.add_argument( 'in_tarballs', nargs='+', help=('input tarballs (*.tar.gz|*.tar.lz4|*.tar.bz2|*.tar.zst)') ) parser.add_argument('--extractToDiskPath', dest="extract_to_disk_path", help='If specified, the tar contents will also be extracted to a local directory.') parser.add_argument('--pipeInHint', dest="pipe_hint_in", default="gz", help='If specified, the compression type used is used for piped input.') parser.add_argument('--pipeOutHint', dest="pipe_hint_out", default="gz", help='If specified, the compression type used is used for piped output.') util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None))) util.cmd.attach_main(parser, merge_tarballs, split_args=True) return parser __commands__.append(('merge_tarballs', parser_merge_tarballs)) def parser_rename_fasta_sequences(parser=argparse.ArgumentParser()): parser.add_argument("in_fasta", help="input fasta sequences") parser.add_argument("out_fasta", help="output (renamed) fasta sequences") parser.add_argument("new_name", help="new sequence base name") parser.add_argument( "--suffix_always", help="append numeric index '-1' to <new_name> if only one sequence exists in <input> (default: %(default)s)", default=False, action="store_true", dest="suffix_always" ) util.cmd.common_args(parser, (('tmp_dir', None), ('loglevel', None), ('version', None))) util.cmd.attach_main(parser, main_rename_fasta_sequences) return parser def main_rename_fasta_sequences(args): ''' Renames the sequences in a fasta file. Behavior modes: 1. If input file has exactly one sequence and suffix_always is False, then the output file's sequence is named new_name. 2. In all other cases, the output file's sequences are named <new_name>-<i> where <i> is an increasing number from 1..<# of sequences> ''' n_seqs = util.file.fasta_length(args.in_fasta) with open(args.in_fasta, 'rt') as inf: with open(args.out_fasta, 'wt') as outf: if (n_seqs == 1) and not args.suffix_always: inf.readline() outf.write('>' + args.new_name + '\n') for line in inf: outf.write(line) else: i = 1 for line in inf: if line.startswith('>'): line = ">{}-{}\n".format(args.new_name, i) i += 1 outf.write(line) return 0 __commands__.append(('rename_fasta_sequences', parser_rename_fasta_sequences)) ## derived cols class Adder_Table_Map: def __init__(self, tab_file): self._mapper = {} self._default_col = None with open(tab_file, 'rt') as inf: reader = csv.DictReader(inf, delimiter='\t') self._col_name = reader.fieldnames[0] self._orig_cols = reader.fieldnames[1:] for row in reader: if all(v=='*' for k,v in row.items() if k in self._orig_cols): self._default_col = row.get(self._col_name) else: k = self._make_key_str(row) v = row.get(self._col_name, '') log.debug("setting {}={} if {}".format(self._col_name, v, k)) self._mapper[k] = v def _make_key_str(self, row): key_str = ':'.join('='.join((k,row.get(k,''))) for k in self._orig_cols) return key_str def extra_headers(self): return (self._col_name,) def modify_row(self, row): k = self._make_key_str(row) v = self._mapper.get(k) if v is None and self._default_col: v = row.get(self._default_col, '') row[self._col_name] = v return row class Adder_Source_Lab_Subset: def __init__(self, restrict_string): self._prefix = restrict_string.split(';')[0] self._restrict_map = dict(kv.split('=') for kv in restrict_string.split(';')[1].split(':')) def extra_headers(self): return (self._prefix + '_originating_lab', self._prefix + '_submitting_lab') def modify_row(self, row): if all((row.get(k) == v) for k,v in self._restrict_map.items()): row[self._prefix + '_originating_lab'] = row['originating_lab'] row[self._prefix + '_submitting_lab'] = row['submitting_lab'] return row def parser_tsv_derived_cols(parser=argparse.ArgumentParser()): parser.add_argument("in_tsv", type=str, help="input metadata") parser.add_argument("out_tsv", type=str, help="output metadata") parser.add_argument("--table_map", type=str, nargs='*', help="Mapping tables. Each mapping table is a tsv with a header. The first column is the output column name for this mapping (it will be created or overwritten). The subsequent columns are matching criteria. The value in the first column is written to the output column. The exception is in the case where all match columns are '*' -- in this case, the value in the first column is the column header name to copy over.") parser.add_argument("--lab_highlight_loc", type=str, help="This option copies the 'originating_lab' and 'submitting_lab' columns to new ones including a prefix, but only if they match certain criteria. The value of this string must be of the form prefix;col_header=value:col_header=value. For example, 'MA;country=USA:division=Massachusetts' will copy the originating_lab and submitting_lab columns to MA_originating_lab and MA_submitting_lab, but only for those rows where country=USA and division=Massachusetts.") util.cmd.common_args(parser, (('loglevel', None), ('version', None))) util.cmd.attach_main(parser, tsv_derived_cols, split_args=True) return parser def tsv_derived_cols(in_tsv, out_tsv, table_map=None, lab_highlight_loc=None): ''' Modify metadata table to compute derivative columns on the fly and add or replace new columns ''' adders = [] if table_map: for t in table_map: adders.append(Adder_Table_Map(t)) if lab_highlight_loc: adders.append(Adder_Source_Lab_Subset(lab_highlight_loc)) with open(in_tsv, 'rt') as inf: reader = csv.DictReader(inf, delimiter='\t') out_headers = reader.fieldnames for adder in adders: out_headers.extend(adder.extra_headers()) with open(out_tsv, 'wt') as outf: writer = csv.DictWriter(outf, out_headers, delimiter='\t') writer.writeheader() for row in reader: for adder in adders: adder.modify_row(row) writer.writerow(row) __commands__.append(('tsv_derived_cols', parser_tsv_derived_cols)) def parser_tsv_join(parser=argparse.ArgumentParser()): parser.add_argument("in_tsvs", nargs="+", type=str, help="input tsvs") parser.add_argument("out_tsv", type=str, help="output tsv") parser.add_argument("--join_id", type=str, required=True, help="column name to join on") util.cmd.common_args(parser, (('loglevel', None), ('version', None))) util.cmd.attach_main(parser, tsv_join, split_args=True) return parser def tsv_join(in_tsvs, out_tsv, join_id=None): ''' full outer join of tables ''' ''' schaluva implementation: df_list = list(pandas.read_csv(f, sep="\t") for f in in_tsvs) df_concat = pandas.concat(df_list, axis=0, ignore_index=True, sort=False).fillna('NA') pandas.DataFrame.to_csv(df_concat, out_tsv, sep='\t', na_rep='NA', index=False) but the above causes types to be parsed and re-outputted slightly differently (e.g. ints become floats) and importantly it doesn't actually join on a join key attempt to reimplement by hand ''' # prep all readers readers = list(csv.DictReader(open(fn, 'rt'), delimiter='\t') for fn in in_tsvs) # prep the output header header = [] for reader in readers: header.extend(reader.fieldnames) header = list(util.misc.unique(header)) if not join_id or join_id not in header: raise Exception() # merge everything in-memory out_ids = [] out_row_by_id = {} for reader in readers: for row in reader: row_id = row[join_id] row_out = out_row_by_id.get(row_id, {}) for h in header: # prefer non-empty values from earlier files in in_tsvs, populate from subsequent files only if missing if not row_out.get(h): row_out[h] = row.get(h, '') out_row_by_id[row_id] = row_out out_ids.append(row_id) out_ids = list(util.misc.unique(out_ids)) # write output with open(out_tsv, 'w', newline='') as outf: writer = csv.DictWriter(outf, header, delimiter='\t', dialect=csv.unix_dialect, quoting=csv.QUOTE_MINIMAL) writer.writeheader() writer.writerows(out_row_by_id[row_id] for row_id in out_ids) __commands__.append(('tsv_join', parser_tsv_join)) # ======================= def full_parser(): return util.cmd.make_parser(__commands__, __doc__) if __name__ == '__main__': util.cmd.main_argparse(__commands__, __doc__)
true
76c9ea0d0792a4bb74501f4617e066769175963f
Python
ChristophFrz/CS686-A3
/variable_elimination.py
UTF-8
7,942
3.3125
3
[]
no_license
''' factor0 = (['A'], {True: 0.7, False: 0.3}) factor1 = (['B'], {True: 0.4, False: 0.6}) factor2 = (['A', 'B', 'C'], {(False, False, False): 0.12, (False, False, True): 0.48, (False, True, True): 0.28, (False, True, False): 0.12, (True, False, True): 0.08, (True, False, False): 0.02, (True, True, True): 0.63, (True, True, False): 0.27}) factor3 = (['C', 'D'], {(False, False): 0.2, (False, True): 0.8, (True, True): 0.7, (True, False): 0.3}) ''' def sumout(factor, variable): # get the position of variable in the list of variables (factor[0]) pos = [i for i,x in enumerate(factor[0]) if x == variable] pos = pos[0] # assign var to the list of variables in factor[0] var = list(factor[0]) # remove the current variable var.remove(variable) # assign d to the dictionary with the CPT d = factor[1] # create new dictionary for the new probabilities and keys new_prob = {} #for all keys in the factor for i1 in range(len(d.keys())): # get all keys u = list(d.keys()) # get the specific keys at position i1 u_del = list(u[i1]) # delete the entry of the current variable (at pos) del u_del[pos] #for all keys after i1 for i2 in range(i1+1, len(d.keys())): # get the list of all keys v = list(d.keys()) # get the specific key at pos i2 v_del = list(v[i2]) # delete entry of current var at this position del v_del[pos] # check the length: important for creating the dictionary entries if len(u_del) > 1: # if remaining keys are the same if u_del == v_del: # add values to dict new_prob[tuple(u_del)] = d[u[i1]] + d[v[i2]] else: # if remaining keys are the same if u_del == v_del: # add values to dict new_prob[u_del[0]] = d[u[i1]] + d[v[i2]] # create new factor and return it new_factor = (var, new_prob) return new_factor def multiply(factor1, factor2): # list of variables from both factors var1 = list(factor1[0]) var2 = list(factor2[0]) # look for the first common variable in both lists for i in var1: for j in var2: if i == j: common_var = i break; # position of common variable in factor 1 pos1 = [i for i,x in enumerate(factor1[0]) if x == common_var] pos1 = pos1[0] # position of common variable in factor 2 pos2 = [i for i,x in enumerate(factor2[0]) if x == common_var] pos2 = pos2[0] # assign dictionaries to d1 and d2 d1 = factor1[1] d2 = factor2[1] # create new dictionary new_prob = {} # make a copy of var2 and delete the common variable from it tmp_var = list(var2) del tmp_var[pos2] # new list of variables consist of the values of var1 and the values of var2 without the common variable new_var = var1 + tmp_var # for all entries in the first factor for i1 in range(len(d1.keys())): # get all the keys all_keys1 = list(d1.keys()) # check the length of var1 and get specific key # problems when var1 is just a bool --> have to distinguish if len(var1) > 1: key1 = list(all_keys1[i1]) else: key1 = list([all_keys1[i1]]) # for all entries in factor2 for i2 in range(len(d2.keys())): # get all the keys all_keys2 = list(d2.keys()) # check length and get specific key if len(var2) > 1: key2 = list(all_keys2[i2]) else: key2 = list([all_keys2[i2]]) # check if the boolean of the common variable is the same if key1[pos1] == key2[pos2]: # create new dictionary key tmp_list = list(key2) del tmp_list[pos2] # if both factors consist of just one variable, the key is just key1[0] if len(var1) > 1 or len(var2) > 1: new_key = tuple(key1 + tmp_list) else: new_key = key1[0] new_prob[new_key] = d1[all_keys1[i1]] * d2[all_keys2[i2]] # create new factor and return new_factor = (new_var, new_prob) return new_factor def restrict(factor, variable, value): # get the variables of the factor var = list(factor[0]) # find the position of the variable pos = [i for i,x in enumerate(factor[0]) if x == variable] pos = pos[0] # d is now the dictionary d = factor[1] # create new list of variables without the specific variable new_var = list(var) del new_var[pos] # create new dictionary new_prob = {} # for all entries in the factor for i in range(len(d.keys())): # get all keys all_keys = list(d.keys()) # get key of position u1 key = list(all_keys[i]) # check if the bool fits to the value if key[pos] == value: # create the new key new_key = list(key) del new_key[pos] # again: distinguish according to the length of the variable list if len(new_key) > 1: new_key = tuple(new_key) new_prob[new_key] = d[all_keys[i]] else: new_prob[new_key[0]] = d[all_keys[i]] # create and return new factor new_factor = (new_var, new_prob) return new_factor def inference(factorList, queryVariables, orderedListOfHiddenVariables, evidenceList): # restrict factors that contain evidence to this value for evidence in list(evidenceList.keys()): for i in range(len(factorList)): tmp_fac = factorList[i] if evidence in tmp_fac[0]: print("Due to restiction of the variable ", evidence, " the factor ", factorList[i]) factorList[i] = restrict(tmp_fac, evidence, evidenceList[evidence]) print("is changed to: ", factorList[i], "\n") # create additional factor list to store factors that contain the hidden variable hiddenFactorList = [] # store original indices to delte them later hiddenFactorIndices = [] # for every hidden variable for hiddenVar in orderedListOfHiddenVariables: for i in range(len(factorList)): # get the factor from the list tmp_fac = factorList[i] # check if hiddenVar in the variable list if hiddenVar in tmp_fac[0]: # append the factor and the index to the corresponding list hiddenFactorList.append(tmp_fac) hiddenFactorIndices.append(i) # if the factor just contains the hiddenVar, it is a 'basic factor' # need this factor to multiply it with the other factors later if len(tmp_fac[0])==1: basis_factor = tmp_fac; # check if the length > 1 and more factors are stored in the list if len(hiddenFactorList) > 1: for i in range(len(hiddenFactorList)): # if the current factor is not the basic factor if hiddenFactorList[i] != basis_factor: # multiply it with the basic factor new_factor1 = multiply(hiddenFactorList[i], basis_factor) #print(new_factor1, " NEW FACTOR after multiply") # sumout the hiddenVar new_factor2 = sumout(new_factor1, hiddenVar) print("Variable elimination of ", hiddenVar, " leads to new factor: ", new_factor2, "\n") # and append it to the factor list factorList.append(new_factor2) else: # just sumout the hiddenVar new_factor2 = sumout(hiddenFactorList[0], hiddenVar) factorList.append(new_factor2) # delete used factors of the original list deleted = 0 #print(hiddenFactorIndices, ".. indeces....") for i in hiddenFactorIndices: # adapt index ind = i - deleted print("Due to variable elimination the following factor is deleted from the list: ", factorList[ind], "\n") del factorList[ind] #print(hiddenVar, " hV ", ind, factorList) deleted += 1 # initialize lists new again hiddenFactorList = [] hiddenFactorIndices = [] # now all factors should only depend on one variable # multiply them until just one factor is left while len(factorList) > 1: factorList[0] = multiply(factorList[0], factorList[1]) del factorList[1] # get and print the result result = normalize(factorList[0]) print("This is the resulting factor: ", result) def normalize(factor): sumOfProb = 0 factorKeys = list(factor[1].keys()) # sum up all values for i in range(len(factor[1].keys())): sumOfProb += factor[1][factorKeys[i]] # normalize it new_prob = {} for i in range(len(factor[1].keys())): new_prob[factorKeys[i]] = factor[1][factorKeys[i]]/sumOfProb # return new factor new_factor = (factor[0], new_prob) return new_factor
true
55b7bacf996fd94b7c5cf08b886b9664ed1b52cd
Python
limaries30/warpgrad
/src/warpgrad/warpgrad/utils.py
UTF-8
9,031
2.75
3
[ "Apache-2.0" ]
permissive
"""Utilities for WarpGrad. :author: Sebastian Flennerhag """ from collections import OrderedDict import os import torch from ._dict import load_state_dict def grad(x, y, model, params, criterion): """Compute new parameters with computation graph intact. Arguments: x (torch.Tensor): input tensor. y (torch.Tensor): target tensor. model (Warp): warped model. params (list): list of parameters to differentiate the loss with respect to. criterion (fun): task loss criterion. """ device = next(model.parameters()).device x = x.to(device, non_blocking=True) y = y.to(device, non_blocking=True) p = model(x, cache_parameters=False) loss = criterion(p, y) return torch.autograd.grad(loss, params, create_graph=True) def approx_step(x_outer, y_outer, model, criterion, scorer): """Compute approximate meta gradient (no inner step). Arguments: x_outer (torch.Tensor): input to obtain meta learner gradient. y_outer (torch.Tensor): target to obtain meta learner gradient. model (Warp): warped model. criterion (fun): task loss criterion. scorer (fun): scoring function (optional). """ device = next(model.parameters()).device x_outer = x_outer.to(device, non_blocking=True) y_outer = y_outer.to(device, non_blocking=True) pred_outer = model(x_outer, cache_parameters=False) loss_outer = criterion(pred_outer, y_outer) score_outer = None if scorer is not None: score_outer = scorer(pred_outer.detach(), y_outer.detach()) return loss_outer, score_outer def step(x_inner, y_inner, x_outer, y_outer, model, optimizer, criterion, scorer): """Compute gradients of meta-parameters using the WarpGrad objective. Arguments: x_inner (torch.Tensor): input to obtain task learner gradient. y_inner (torch.Tensor): target to obtain task learner gradient. x_outer (torch.Tensor): input to obtain meta learner gradient. y_outer (torch.Tensor): target to obtain meta learner gradient. model (Warp): warped model. optimizer (warpgrad.optim.SGD, warpgrad.optim.Adam): task optimizer, must be differentiable. criterion (fun): task loss criterion. scorer (fun): scoring function (optional). """ device = next(model.parameters()).device original_tparams = OrderedDict(model.named_adapt_parameters()) x_inner = x_inner.to(device, non_blocking=True) y_inner = y_inner.to(device, non_blocking=True) x_outer = x_outer.to(device, non_blocking=True) y_outer = y_outer.to(device, non_blocking=True) # Parameter update pred_inner = model(x_inner, cache_parameters=False) loss_inner = criterion(pred_inner, y_inner) backward(loss_inner, model.adapt_parameters(), create_graph=True) _, new_params = optimizer.step(retain_graph=True) replace(model.model, new_params, original_tparams) # Get forward loss pred_outer = model(x_outer, cache_parameters=False) loss_outer = criterion(pred_outer, y_outer) # Reset model parameters load_state_dict(model.model, original_tparams) score_inner = None score_outer = None if scorer is not None: score_inner = scorer(pred_inner.detach(), y_inner.detach()) score_outer = scorer(pred_outer.detach(), y_outer.detach()) return loss_outer, (loss_inner.detach(), score_inner, score_outer) def replace(model, new_params, old_params): """Helper for updating model dict in a back-prop compatible way.""" par_names = list(old_params.keys()) assert len(par_names) == len(new_params) new_state = OrderedDict(zip(par_names, new_params)) load_state_dict(model, new_state) for p in old_params.values(): p.grad = None # drop current gradients to avoid accumulating into them def backward(loss, args, create_graph=False): """Partial derivatives of loss wrt args.""" args = list(args) grads = torch.autograd.grad(loss, args, create_graph=create_graph) for p, g in zip(args, grads): p.backward(g) ############################################################################# def get_data(iterator, n_iterations): """Helper for setting up data.""" out = [] iterator.dataset.train() for i, batch in enumerate(iterator): out.append(batch) if i+1 == n_iterations: break return out def freeze(iterable): """Freeze params in module.""" for p in iterable: p.requires_grad = False def unfreeze(iterable): """Freeze params in module.""" for p in iterable: p.requires_grad = True def get_groups(parameters, opt_params, tensor=True): """Return layer-wise optimization hyper-parameters.""" groups = [] for p, lr, mom in zip(parameters, opt_params.lr, opt_params.momentum): if not tensor: lr = lr.item() mom = mom.item() groups.append({'params': p, 'lr': lr, 'momentum': mom}) return groups ############################################################################# def stem(fpath): """Returns task-id and iter-id.""" fname = str(os.path.basename(fpath).split('.')[0]) return fname.split('_') def load(path): """Load stored data in to task dict.""" files = sorted(os.listdir(path)) # sorting -> iter order mapped_files = {stem(f)[0]: [] for f in files} for fname in files: fpath = os.path.join(path, fname) n, i = stem(fname) assert len(mapped_files) == int(i) mapped_files[n].append(torch.load(fpath)) return mapped_files def clear(path): """delete all files in path.""" files = os.listdir(path) for f in files: os.unlink(os.path.join(path, f)) def state_dict_to_par_list(state_dict, par_names): """Prune a state_dict and return a list of parameters.""" return [tensor for name, tensor in state_dict.items() if name in par_names] def clone(tensor, device=None): """Clone a list of tensors.""" if not isinstance(tensor, torch.Tensor): return [clone(t) for t in tensor] cloned = tensor.detach().clone() cloned.requires_grad = tensor.requires_grad if device is not None: cloned = cloned.to(device) return cloned def clone_state(state_dict, *args, **kwargs): """Clone a list of tensors.""" cloned_state = OrderedDict() for n, p in state_dict.items(): cloned_state[n] = clone(p, *args, **kwargs) return cloned_state def copy_opt(param_states): """Copy buffers from an optimizer state.""" cloned_states = [] for param_state in param_states: cloned_state = OrderedDict() for k, v in param_state.items(): cloned_state[k] = v.clone().cpu() cloned_states.append(cloned_state) return cloned_states def copy(to_tensors, from_tensors): """Copy tensor data from one set of iterables to another.""" if isinstance(to_tensors, (list, tuple)): for p, q in zip(to_tensors, from_tensors): p.data.copy_(q.data) elif isinstance(to_tensors, (dict, OrderedDict)): for (n, p), (m, q) in zip(to_tensors.items(), from_tensors.items()): if n != m: raise ValueError( 'target state variable {}' 'does not match source state variable{}'.format(n, m)) p.data.copy_(q.data) else: raise ValueError('Unknown iterables type {}'.format(type(to_tensors))) def zero_grad(tensor_like): """Set tensor gradient to zero. Null op if argument is not a tensor. Argument: tensor_like: objects to zero grad for. If list, will iterate over elements. """ if isinstance(tensor_like, (tuple, list)): for p in tensor_like: zero_grad(p) if not hasattr(tensor_like, 'grad'): return if tensor_like.grad is None: if tensor_like.dim() == 0: tensor_like.grad = tensor_like.detach().clone() else: tensor_like.grad = tensor_like.new(*tensor_like.shape) tensor_like.grad.zero_() ############################################################################# def n_correct(logits, targets): """Number correct predictions. Args: logits (torch.Tensor): tensor of prediction logits. targets (torch.Tensor): tensor of class targets. """ _, predictions = logits.max(1) correct = (predictions == targets).sum().item() return correct def acc_fn(p, y): """Accuracy of discrete predictions.""" return n_correct(p, y) / y.size(0) def global_norm(tensors, detach=True, eps=1e-9): """Compute a global norm over a list of tensors.""" norm = 0. for tensor in tensors: tensor = tensor.view(-1) if detach: tensor = tensor.detach().data norm += torch.dot(tensor, tensor) # pylint: disable=no-member norm = norm.sqrt() return norm + eps
true
5b8bf0d8ffc0f07819fe3d6847342bb42062d4fa
Python
amar-enkhbat/signate_2020
/data_augmentation.py
UTF-8
1,347
2.828125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[110]: get_ipython().system('pip install googletrans') import numpy as np import pandas as pd from googletrans import Translator # In[51]: train = pd.read_csv('./input/train.csv') test = pd.read_csv('./input/test.csv') # # In[131]: def is_eng(word):#日本語を除外 kana_set = {chr(i) for i in range(12353, 12436)}#平仮名があれば日本語 word_set = set(word) if kana_set - word_set == kana_set: return True else: return False # In[54]: translator = Translator() # In[ ]: train_np = train.to_numpy() add_data = [] count=0 for i in range(train_np.shape[0]): trans_1 = translator.translate(train_np[i][1],src="en",dest='ja')#from eng to jp trans_2 = translator.translate(trans_1.text,src="ja",dest='en')#from jp to eng if is_eng(trans_2.text)==True:#if the text is eng add_data=np.append(add_data,[count+train_np.shape[0],trans_2.text,train_np[i][2]]) count=count+1 if i%100==0: print(i) add_data=add_data.reshape(-1,3) add_data # In[ ]: add_df = pd.DataFrame(data=add_data, columns=['id', 'description', 'jobflag']) add_df # In[138]: new_train = pd.concat([train,add_df],ignore_index=True) new_train # In[139]: new_train.to_csv("/content/drive/My Drive/Colab Notebooks/content/input/new_train_1.csv")
true
813c499d93fbe1047a078812e514800cd77f0c67
Python
sunnysong1204/61a-sp14-website
/slides/lect16.py
UTF-8
976
3.140625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
class Range: class _RangeIterator: def __init__(self, aRange): self.range = aRange self.i = self.range.low def __next__(self): if self.range.step < 0 and self.i <= self.range.high or \ self.range.step >= 0 and self.i >= self.range.high: raise StopIteration else: v = self.i self.i += self.range.step return v def __iter__(self): return self def __init__(self, *bounds): if len(bounds) == 1: self.low, self.high, self.step = 0, bounds[0], 1 elif len(bounds) == 2: self.low, self.high, self.step = bounds[0], bounds[1], 1 elif len(bounds) == 3: self.low, self.high, self.step = bounds else: raise TypeError("too many arguments to Range") def __iter__(self): return Range._RangeIterator(self)
true
33fbbc1fd8f5ef107094fd34209988228675aec6
Python
fly8764/LeetCode
/HashTable/974 subarraysDivByK.py
UTF-8
1,486
3.0625
3
[]
no_license
class Solution: #这题 k >2,所以不用考虑k=0 的情况 def subarraysDivByK(self, nums, k): # 从左往右累计求和时,每次保存当前位置累计和的取余结果 size = len(nums) if not size: # k= 0 不能直接排除 return 0 map = {} map[0] = 1 #初始化 对应于一上来就满足要求的情况,1代表这个 子串本身 zero = {} zero[0] = 1 summ = 0 cnt = 0 for i in range(size): summ += nums[i] if k: summ %= k if summ in map: cnt += map.get(summ) map[summ] = 1 + map.get(summ,0) else: if summ in zero: cnt += zero[summ] zero[summ] = 1+ zero.get(summ,0) return cnt # def subarraysDivByK(self, nums, k): # #暴力法,超时 # size = len(nums) # if not size or not k: # return 0 # dp = [0]*(size+1) # cnt = 0 # for i in range(1,size+1): # dp[i] = dp[i-1]+ nums[i-1] # # for l in range(size): # for r in range(l+1,size+1): # sub = dp[r]- dp[l] # if sub % k == 0: # cnt += 1 # return cnt if __name__ == '__main__': so = Solution() nums = [4,5,0,-2,-3,1] k = 5 res = so.subarraysDivByK(nums,k) print(res)
true
aaef0e72dd59f132f579eb73731aa26178218b4a
Python
AMshoka/OS
/Project2/Project2.py
UTF-8
1,195
2.65625
3
[ "MIT" ]
permissive
import queue import sys from threading import Thread import concurrent.futures from time import time import matplotlib.pyplot def caculate(identifier): finalanswer = 0 for i in range(len(l)): if i % Num == identifier: finalanswer = finalanswer ^ int(l[i]) Q.put(finalanswer) def check(n): if n> 40: return 40 else: return n global Num,lines Num= int(sys.argv[1]) name = str(sys.argv[2]) Num=check(Num) Q = queue.Queue() final_result = 0 file=open(name,'r') l=file.readlines() st = time() with concurrent.futures.ThreadPoolExecutor(max_workers=40) as exe: exe.map(caculate,range(Num)) while True: if(Q.empty()): break result = Q.get() final_result=final_result^result et = time() x=[5,10,15,20,25,30,35] y=[1.9992,3.4947,3.8882,4.9660,5.8611,6.4447,7.9535] matplotlib.pyplot.plot(x,y) matplotlib.pyplot.xlabel("Iteration") matplotlib.pyplot.ylabel("Time") matplotlib.pyplot.show() file = open('FinalResult_proj2.txt', 'w') file.write('\n'.join([("FinalResult:"),str(final_result),("Time:"), str(et-st)])) file.close()
true
7fdf532ae90a5d0a807b26886685b6dc243cb650
Python
PetarMinev/Python-Coursework
/Products.py
UTF-8
439
3.15625
3
[]
no_license
class products: def __init__(self): self.products = {} self.drinks = {"Айрян": 0.49, "Пепси": 1.29} self.piza = {"Малка": 2.49, "Средна": 3.49, "Голяма": 5} self.kebap = {"Малък": 3, "Среден": 4, "Голям": 5} def add(self, product, amount): self.prod = product self.amount = amount self.products[self.prod] = self.amount
true
10f0c6dcec53e8df45b9692707c647a21a433bad
Python
adriendbr/PV-marker-detection
/KalmanFilter.py
UTF-8
2,489
2.8125
3
[]
no_license
import numpy as np class KalmanFilter(object): def __init__(self, dt, u_x, u_y, std_acc, x_std_meas, y_std_meas): """ :param dt: sampling time (time for 1 cycle) :param u_x: acceleration in x-direction :param u_y: acceleration in y-direction :param std_acc: process noise magnitude :param x_std_meas: standard deviation of the measurement in x-direction :param y_std_meas: standard deviation of the measurement in y-direction """ # Define sampling time self.dt = dt # Define the control input variables self.u = np.block([[u_x],[u_y]]) # Initial State # Define the State Transition Matrix A self.A = np.block([[1, 0, self.dt, 0], [0, 1, 0, self.dt], [0, 0, 1, 0], [0, 0, 0, 1]]) # Define the Control Input Matrix B self.B = np.block([[(self.dt**2)/2, 0], [0, (self.dt**2)/2], [self.dt,0], [0,self.dt]]) # Define Measurement Mapping Matrix self.H = np.block([[1, 0, 0, 0], [0, 1, 0, 0]]) #Initial Process Noise Covariance self.Q = np.block([[(self.dt**4)/4, 0, (self.dt**3)/2, 0], [0, (self.dt**4)/4, 0, (self.dt**3)/2], [(self.dt**3)/2, 0, self.dt**2, 0], [0, (self.dt**3)/2, 0, self.dt**2]]) * std_acc**2 # Initial Measurement Noise Covariance self.R = np.block([[x_std_meas**2,0], [0, y_std_meas**2]]) # Initial Covariance Matrix def predict(self, x, P): # x_k =Ax_(k-1) + Bu_(k-1) # a priori estimate x = np.dot(self.A, x) + np.dot(self.B, self.u) # Calculate error covariance # P= A*P*A' + Q P = np.dot(np.dot(self.A, P), self.A.T) + self.Q return x, P def update(self, z, x, P): # S = H*P*H'+R S = np.dot(self.H, np.dot(P, self.H.T)) + self.R # Calculate the Kalman Gain # K = P * H'* inv(S) K = np.dot(np.dot(P, self.H.T), np.linalg.inv(S)) x = np.round(x + np.dot(K, (z - np.dot(self.H, x)))) I = np.eye(self.H.shape[1]) P = np.dot((I - np.dot(K, self.H)), P) return x, P
true
b779aea973abfaffe8e7f68a6d393e61a0c6d075
Python
gravesprite/seq2seq_with_deep_attention
/models/PointerNetwork.py
UTF-8
6,231
2.96875
3
[]
no_license
#!/usr/bin/env python """ Pointer Networks https://arxiv.org/abs/1506.03134 """ __author__ = "AL-Tam Faroq" __copyright__ = "Copyright 2020, UALG" __credits__ = ["Faroq AL-Tam"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Faroq AL-Tam" __email__ = "ftam@ualg.pt" __status__ = "Production" import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from seq2seq_with_deep_attention.RDN import EmbeddingLSTM class PointerNetwork(nn.Module): def __init__(self, in_features, hidden_size, batch_size, sos_symbol=-1, device='cpu'): super(PointerNetwork, self).__init__() # attributes self.in_features = in_features self.hidden_size = hidden_size self.batch_size = batch_size self.sos_symbol = sos_symbol # device if device is not 'cpu': if torch.cuda.is_available(): device = 'cuda:0' self.device = device # encoder/decoder self.encoder = EmbeddingLSTM(embedding_layer=nn.Linear(in_features=in_features, out_features=hidden_size), batch_size=self.batch_size, hidden_size=self.hidden_size, device=self.device ) # in figure 1b, we need to perfrom the decorder step by step # this is a curcial piece of pointer network and the main difference with seq2seq models # see the forward function for more details self.decoder_cell = EmbeddingLSTM(embedding_layer=nn.Linear(in_features=in_features, out_features=hidden_size), batch_size=self.batch_size, hidden_size=self.hidden_size, device=self.device, lstm_cell=True # LSTMCell ) # attention calculation paramaters see first lines in equation 3 in # u^i_j = v^\top tanh(W_1 e_j + W_2 d_i), \forall j \in (1, \cdots, n) # where e_j and d_i are the encoder and decoder hidden states, respectively. # W_1, and W_2 are learnable weights(square matrices), we represent them here by nn.Linear layers # v is also a vector of learnable weights, we represent it here by nn.Paramater self.W_1 = nn.Linear(in_features=hidden_size, out_features=hidden_size) self.W_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size) self.v = nn.Linear(in_features=hidden_size, out_features=1) self.to(self.device) def update_batch_size(self, batch_size): self.batch_size = batch_size self.encoder.batch_size = batch_size self.decoder_cell.batch_size = batch_size def forward(self, input_seq): """ Calculate the attention and produce the pointers keyword argumenents: input_seq -- the input sequence (batch_size, sequence_size, hidden_size) """ _, input_seq_length,_ = input_seq.shape ## get the encoder output encoder_output, hidden, _ = self.encoder(input_seq) # it returns output, hidden, embed ## get the decoder output # 1- we start by inserting the random or zeros to the encoder_cell # 2- the pointer network will produce a pointer from the softmax activation # 3- We use that pointer to select the embedded features from the input sequence # 4- we feed these selected features to the encoder_cell and get a new pointer # 5- we iterate the above steps until we collect pointers with the same size as the input # we will use them to calculate the loss function pointers = torch.empty((self.batch_size, input_seq_length)) attentions = torch.empty((self.batch_size, input_seq_length, input_seq_length)) # the initial state of the decoder_cell is the last state of the encoder decoder_cell_hidden = (hidden[0][-1, :, :], hidden[1][-1, :, :]) # each of size(num_layers=1, batch_size, hidden_size) # initialize the first input to the decoder_cell, zeros, random, or using the sos_symbol #decoder_cell_input = torch.rand((self.batch_size, 1)) # one is for the feature not the step #decoder_cell_input = torch.zeros((self.batch_size, 1)) # one is for the feature not the step decoder_cell_input = (torch.ones((self.batch_size, 1)) * self.sos_symbol).to(self.device) # one is for the feature not the step for i in range(input_seq_length): # 1 - calculate decoder hidden and cell states decoder_cell_output, decoder_cell_hidden_state, _ = self.decoder_cell(decoder_cell_input, decoder_cell_hidden, clear_state=False) decoder_cell_hidden = (decoder_cell_output, decoder_cell_hidden_state) # because it is an LSTMCell # 2 - used decoder_cell_output and encoder_output to calculate the attention: # u^i_j = v^\top tanh(W_1 e_j + W_2 d_i), \forall j \in (1, \cdots, n) # size of u is (batch_size, sequence_length, 1) # so we remove that last dimenstion # (batch_size X sequence_size X features) (batch_size X 1 X features) u = self.v(torch.tanh(self.W_1(encoder_output) + self.W_2(decoder_cell_output).unsqueeze(1))).squeeze(2) # # a^i_j = softmax(u^i_j) attentions[:, i, :] = F.log_softmax(u, dim=1) # we use the log for two reasons: # 1- avoid doing hot_one encoding # 2- mathematical stability _, max_pointer = attentions[:, i, :].max(dim=1) pointers[:, i] = max_pointer # create a new input # can be refactored to a single line but this is more readable decoder_cell_input = decoder_cell_input.clone() for j in range(self.batch_size): decoder_cell_input[j, :] = input_seq[j, max_pointer[j], :] return attentions, pointers
true
2c13144656111792bac00b9853bd2a42b6e3c01f
Python
pintr/openstack_monitoring
/utilities.py
UTF-8
999
3.234375
3
[]
no_license
import inspect def fc(conn, fun): """ Get the parameters of a function and call it :param conn: the connection for OpenStack commands :param fun: the function to call :return: the result of the function call """ par = dict() par['conn'] = conn params = set_params(fun, par) print(params) return fun(**params) def set_params(fun, my_params): """ Set the parameters required for a function :param fun: the function to analyze :param my_params: already set parameters :return: a dict containing keys and values of the parameters """ params = inspect.signature(fun).parameters res = dict() print('Parameters for function ' + fun.__name__) for key in my_params.keys(): if key in params: res[key] = my_params[key] for par in params: if par not in res.keys(): p = input("Value for {par}: ".format(par=par)) if p: res[par] = p return res
true
e4f9a4609efd22867f8b6c81f3e921bda4407ec1
Python
Haifen/nscc_csc110.09_14_1
/lab04/kauffmanL4_1.py
UTF-8
560
3.046875
3
[]
no_license
#!/bin/env python # $Header: nscc_csc110_201409/lab04/kauffman_L4_2.py, r1 201410161829 US/Pacific-New PDT UTC-0700 robink@northseattle.edu Lab $ TUIT_IN = 3000.0 INTEREST = 0.025 DURATION = 5 def muladd(acc, multiplicand): return acc + (acc * multiplicand) cost = float() total = float() for year in range(1, DURATION + 1): cost = muladd(cost or TUIT_IN, INTEREST) total += cost print("At year {0}, cost of attending school is {1}".format(year, cost)) print("After {0} of college, the total amount of the projected tuition will be: {1}".format(DURATION, total))
true
5962c8e757fecafb96244e4c31ea6920f9b795f4
Python
iamrizwan007/Decorator
/C6_DecorDemo1.py
UTF-8
388
3.390625
3
[]
no_license
def decor(func): def inner(): print("send the person to beauty parlour") print("showing person full of decoration") return inner @decor def display(): print("showing a person as it is") display() #PVM will check for decor, if yes then normal display will not execute, pass normal display as the input function to decor and the return the inner object(after executing)
true
21f1cc4c663686d7e1c43b0fbdba33a56cb6a242
Python
Elliotshui/avazu-ctr-prediction
/model/DeepModel.py
UTF-8
2,062
2.765625
3
[]
no_license
import tensorflow as tf import numpy as np class DeepModel: def __init__(self, args, graph, session): # copy args self.graph = graph self.session = session self.args = args feature_size = args['feature_size'] field_size = args['field_size'] embedding_size = args['embedding_size'] layers = args['layers'] lr = args['learning_rate'] num_layers = len(layers) with self.graph.as_default(): # model structure self.input = tf.placeholder(tf.int32, shape = [None, None]) self.label = tf.placeholder(tf.float32, shape = [None, 1]) self.embedding_w = tf.Variable( tf.random_normal([feature_size, embedding_size], 0.0, 0.1) ) self.embedding = tf.nn.embedding_lookup(self.embedding_w, self.input) self.embedding = tf.reshape(self.embedding, [-1, field_size * embedding_size]) self.dense_out = dict() self.dense_out[0] = tf.layers.dense( inputs=self.embedding, units=layers[0], activation=tf.nn.leaky_relu ) for i in range(1, num_layers): self.dense_out[i] = tf.layers.dense( inputs=self.dense_out[i - 1], units=layers[i], activation=tf.nn.leaky_relu ) self.logits = tf.layers.dense( inputs=self.dense_out[num_layers - 1], units=1, activation=None ) self.logits = tf.reshape(self.logits, [-1, 1]) self.pred = tf.nn.sigmoid(self.logits) # loss self.log_loss = tf.losses.log_loss(self.label, self.pred) self.loss = self.log_loss # optimizer self.optimizer = tf.train.AdamOptimizer( learning_rate=lr ) self.update = self.optimizer.minimize(self.loss) self.init = tf.global_variables_initializer() def init_weights(self): print("initializing weights...") self.session.run(self.init) def train_batch(self, input, label): loss, _ = self.session.run( [self.loss, self.update], feed_dict={self.input: input, self.label: label} ) return loss def eval(self, input, label): log_loss = self.session.run( self.log_loss, feed_dict={self.input: input, self.label: label} ) return log_loss
true
741a84807065105fc465f8c36fbd566639923c26
Python
pauloreis-ds/topBankStreamlit
/model.py
UTF-8
1,237
2.953125
3
[]
no_license
import pickle import pandas as pd from sklearn.metrics import recall_score def _load_model(): with open('./model/topBankModel.pkl', 'rb') as file: return pickle.load(file) def _preprocess_data(raw_data): raw_data = pd.get_dummies(raw_data, prefix=['geography'], columns=['geography']) raw_data = pd.get_dummies(raw_data, prefix=['gender'], columns=['gender'] ) data = raw_data.drop(columns=['exited', 'customer_id', 'surname', 'has_cr_card', 'tenure', 'total_revenue']) label = raw_data['exited'] return data, label class Model: def __init__(self): self.model = _load_model() self.label = None self.prediction = None self.prediction_probability = None def predict(self, raw_data): data, self.label = _preprocess_data(raw_data) self.prediction = self.model.predict(data) return self.prediction def predict_probability(self, raw_data): data, self.label = _preprocess_data(raw_data) self.prediction_probability = self.model.predict_proba(data)[:, 1] return self.prediction_probability def get_recall(self): return recall_score(self.label, self.prediction)
true
864c0cbbff7178f7eb5ec90e4c809824be2b335d
Python
MarekUlip/CollegePythonScripts
/AlgorithmsForBioinformatics/3seminar.py
UTF-8
5,974
2.609375
3
[]
no_license
import numpy as np seq_a = 'TATGTCATGC' seq_b = 'TACGTCAGC' table_map = {'A': 0, 'C': 1, 'G': 2, 'T': 3, '-': 4} # MRIP # opakujici sekvence jsou malymi pismeny def global_alignment(seq_a, seq_b): p_func = np.array([[0, 4, 2, 4, 8], [4, 0, 4, 2, 8], [2, 4, 0, 4, 8], [4, 2, 4, 0, 8], [8, 8, 8, 8, 10000]]) len_a = len(seq_a) + 1 len_b = len(seq_b) + 1 matrix = np.zeros((len_a, len_b), dtype=int) for i in range(1, len_a): matrix[i, 0] = matrix[i - 1, 0] + p_func[table_map.get('-'), table_map.get(seq_a[i - 1])] for i in range(1, len_b): matrix[0, i] = matrix[0, i - 1] + p_func[table_map.get(seq_b[i - 1]), table_map.get('-')] for i in range(1, len_a): for j in range(1, len_b): matrix[i, j] = min([matrix[i - 1, j] + p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], matrix[i, j - 1] + p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], matrix[i - 1, j - 1] + p_func[ table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])]]) # print(matrix) return matrix[len_a - 1, len_b - 1], matrix def local_alignment(seq_a, seq_b): p_func = np.array( [[2, -4, -4, -4, -6], [-4, 2, -4, -4, -6], [-4, -4, 2, -4, -6], [-4, -4, -4, 2, -6], [-6, -6, -6, -6, 100000]]) len_a = len(seq_a) + 1 len_b = len(seq_b) + 1 matrix = np.zeros((len_a, len_b), dtype=int) for i in range(1, len_a): matrix[i, 0] = 0 # matrix[i-1,0]+p_func[table_map.get('-'),table_map.get(seq_a[i-1])] for i in range(1, len_b): matrix[0, i] = 0 # matrix[0,i-1]+p_func[table_map.get(seq_b[i-1]),table_map.get('-')] for i in range(1, len_a): for j in range(1, len_b): matrix[i, j] = max([matrix[i - 1, j] + p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], matrix[i, j - 1] + p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], matrix[i - 1, j - 1] + p_func[table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])], 0]) # print(matrix) return max([max(row) for row in matrix]), matrix def resolve_diff_global(diff): if diff == 0: return 'M' elif diff == 2: return 'R' elif diff == 4: return 'R' elif diff == 8: return 'I' def resolve_diff_local(diff): if diff == 2: return 'M' elif diff == -4: return 'I' elif diff == -6: return 'R' def resolve_index(index, i, j): if index == 0: return i - 1, j elif index == 1: return i, j - 1 if index == 2: return i - 1, j - 1 def trace_back_global(matrix, seq_a, seq_b): p_func = np.array([[0, 4, 2, 4, 8], [4, 0, 4, 2, 8], [2, 4, 0, 4, 8], [4, 2, 4, 0, 8], [8, 8, 8, 8, 10000]]) i = len(seq_a) j = len(seq_b) traceback = "" while i != 0 and j != 0: # print("{} {}".format(i,j)) surrounding = [matrix[i - 1, j] + p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], matrix[i, j - 1] + p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], matrix[i - 1, j - 1] + p_func[table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])]] edit_vals = [p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], p_func[table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])]] # print(surrounding) best_index = surrounding.index(min(surrounding)) i, j = resolve_index(best_index, i, j) traceback += resolve_diff_global(edit_vals[best_index]) return traceback[::-1] def get_highest_num_index(matrix): highest_in_row = [max(row) for row in matrix] max_val = max(highest_in_row) i = np.where(highest_in_row == max_val)[0][0] j = np.where(matrix[i] == max_val)[0][0] return [i, j] def check_surrounding(matrix, i, j): if i - 1 < 0 or j - 1 < 0: return False if sum([matrix[i - 1, j], matrix[i, j - 1], matrix[i - 1, j - 1]]) == 0: return False return True def trace_back_local(matrix, seq_a, seq_b): p_func = np.array( [[2, -4, -4, -4, -6], [-4, 2, -4, -4, -6], [-4, -4, 2, -4, -6], [-4, -4, -4, 2, -6], [-6, -6, -6, -6, 100000]]) i, j = get_highest_num_index(matrix) traceback = "" can_trace = check_surrounding(matrix, i, j) safety = True while can_trace: # print("{} {}".format(i,j)) surrounding = [matrix[i - 1, j] + p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], matrix[i, j - 1] + p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], matrix[i - 1, j - 1] + p_func[table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])]] edit_vals = [p_func[table_map.get(seq_a[i - 1]), table_map.get('-')], p_func[table_map.get('-'), table_map.get(seq_b[j - 1])], p_func[table_map.get(seq_a[i - 1]), table_map.get(seq_b[j - 1])]] # print(surrounding) best_index = surrounding.index(max(surrounding)) i, j = resolve_index(best_index, i, j) traceback += resolve_diff_local(edit_vals[best_index]) can_trace = check_surrounding(matrix, i, j) if not can_trace and safety: can_trace = True safety = False return traceback[::-1] # print(global_alignment(seq_b,seq_a)) print("Global alignment result {}".format(global_alignment(seq_b, seq_a)[0])) print("Traceback global {}".format(trace_back_global(global_alignment(seq_b, seq_a)[1], seq_b, seq_a))) seq_a = 'TATATGCGGCGTTT' seq_b = 'GGTATGCTGGCGCTA' print("Local alignment result {}".format(local_alignment(seq_b, seq_a)[0])) print("Traceback local {}".format(trace_back_local(local_alignment(seq_b, seq_a)[1], seq_b, seq_a)))
true
8e4924dbd2bccbffc85b5bdc04b3b8b73967929f
Python
MosesGakuhi1857/Awards
/awardsApp/tests.py
UTF-8
3,903
2.59375
3
[ "MIT" ]
permissive
from django.test import TestCase from django.contrib.auth.models import User from .models import Profile, Project, Review, Rating class TestAppModelsClass(TestCase): def setUp(self): self.moses = User(id=4, username = "moses", email = "kingorimoses386@gmail.com",password = "12345678") # self.frank.save() self.profile = Profile(id=3, user= self.moses, bio='myself', profile_pic='maloly.jpg', location='Nairobi') # self.profile.save() self.project = Project(id=6,title = 'AIB',project_image = 'aib.jpg', description = 'Its all about', publisher = self.profile) # self.project.save() self.rating = Rating(id=5,project=self.project, design= 7, usability=8, content=8, score =7.67, rated_by = self.moses) # self.review.save_review() self.review = Review(id=7,project=self.project, review= 'Great idea', reviewed_by = self.moses) # self.review.save_review() # Teardown def tearDown(self): User.objects.all().delete() Profile.objects.all().delete() Project.objects.all().delete() Rating.objects.all().delete() Review.objects.all().delete() # Instances def test_user_instance(self): self.assertTrue(isinstance(self.frank, User)) def test_profile_instance(self): self.assertTrue(isinstance(self.profile, Profile)) def test_image_instance(self): self.assertTrue(isinstance(self.project, Project)) def test_instance(self): self.assertTrue(isinstance(self.rating, Rating)) def test_instance(self): self.assertTrue(isinstance(self.review, Review)) # Save method def test_save_Profile(self): self.profile.save() profiles = Profile.objects.all() self.assertTrue(len(profiles)> 0) def test_save_project(self): self.project.save() projects = Project.objects.all() self.assertTrue(len(projects)> 0) def test_save_rating(self): self.rating.save_rating() rating = Rating.objects.all() self.assertTrue(len(rating)> 0) def test_save_review(self): self.review.save_review() reviews = Review.objects.all() self.assertTrue(len(reviews)> 0) #Update method def test_update_profile(self): self.profile.save() profile = Profile.objects.last().id Profile.update_profile(profile,'The man') update_profile = Profile.objects.get(id = profile) self.assertEqual(update_profile.bio,'The man') def test_update_project(self): self.project.save() project = Project.objects.last().id Project.update_project(project, 'ML') new = Project.objects.get(id = project) self.assertEqual(new.title, 'ML') def test_update_rating(self): self.rating.save() rating = Rating.objects.last().id Rating.update_rating(rating, 6) update = Rating.objects.get(id = rating) self.assertEqual(update.design, 6) def test_update_review(self): self.review.save() review = Review.objects.last().id Review.update_review(review, "Great concept") update = Review.objects.get(id = review) self.assertEqual(update.review, "Great concept") #Delete Method def test_delete_project(self): self.project.delete_project() after_del = Project.objects.all() self.assertEqual(len(after_del),0) def test_delete_review(self): # before_del = Review.objects.all() # self.assertEqual(len(before_del),1) self.review.delete_review() after_del = Review.objects.all() self.assertTrue(len(after_del)==0) # search def test_search_by_title(self): self.project.save() project = Project.search_project('AIB') self.assertTrue(len(project)== 1)
true