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
8608f26fc7a86737e5d44f7623280d40b9a7cb5b
Python
minhhienvo368/OOP_challenges
/3.python-pangram/pangram.py
UTF-8
652
3.828125
4
[]
no_license
# Write a program check if a string is a pangram import string import re def strip_punctuation(word: str) -> str: #eleminate puntuation function exclude = set(string.punctuation) word = ''.join(char for char in word if char not in exclude) return word def is_pangram(text: str) -> bool: text = re.sub('"', '', text) text = text.rstrip() text = strip_punctuation(text.lower()) for char in string.ascii_lowercase: if char not in text: return False return True is_pangram("'Victor jagt zwölf Boxkämpfer quer über den' ' großen Sylter Deich.'") # COACHES' NOTE: Very clean and nice code. No remarks.
true
f9d83778c399eb21c1f778f236ea85c458e62d6a
Python
ZqLiu7/Yelp_Analytics
/text_preprocessing.py
UTF-8
2,054
3.09375
3
[]
no_license
from nltk.corpus import stopwords from nltk.stem import LancasterStemmer, WordNetLemmatizer from string import digits, punctuation from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC def text_processing(string): remove_digits = str.maketrans('', '', digits) remove_punctuations = str.maketrans("", "", punctuation) cach_stopwords = set([text.translate(remove_punctuations) for text in stopwords.words('english')]) lemmatizer = WordNetLemmatizer() stemmer = LancasterStemmer() # convert to lower case lower_string = string.lower() # remove all the punctuations no_punc_string = lower_string.translate(remove_punctuations) # remove all digits no_digit_string = no_punc_string.translate(remove_digits) # split the string splited_string = no_digit_string.split() # remove stop words splited_string_stop = [word for word in splited_string if word not in cach_stopwords] # call lemmatizer lemmatized_words = [lemmatizer.lemmatize(word) for word in splited_string_stop] # call stemmer stemmed_words = [stemmer.stem(word) for word in lemmatized_words] return ( " ".join(stemmed_words)) def data_processing(df): df_new=df[df.stars.isin([1,5])] text=df_new.text y=df_new.stars text.index=df_new.shape[0] sample_reviews=[] for i in range(0, text.size): sample_reviews.append(text_processing(text[i])) return(sample_reviews) tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2)) X=tfidf_vectorizer.fit_transform(sample_reviews) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101) logreg = LogisticRegression() logreg.fit(X_train, y_train) y_pred = logreg.predict(X_test) score_log = logreg.score(X_test, y_test) print(score_log) svm = LinearSVC(C=1) svm.fit(X_train, y_train) y_pred = svm.predict(X_test) score_svm = svm.score(X_test, y_test) print(score_svm)
true
3e40938b0f301b560b625043910f38c14c0f9227
Python
ChungJunn/word2vec
/cbow.py
UTF-8
4,543
3.015625
3
[]
no_license
''' implement CBOW model with KJV bible dataset code adopted from https://towardsdatascience.com/understanding-feature-engineering-part-4-deep-learning-methods-for-text-data-96c44370bbfa ''' from nltk.tokenize.simple import SpaceTokenizer from nltk.stem.porter import PorterStemmer from nltk.corpus import gutenberg from model import CBOWModel from torch.utils.data import Dataset, DataLoader import torch import torch.nn as nn import torch.optim as optim import nltk import numpy as np import re import sys import time class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): if word not in self.word2idx: self.idx2word.append(word) self.word2idx[word] = len(self.idx2word) - 1 return self.word2idx[word] def __len__(self): return len(self.idx2word) def normalize(line): stemmer = PorterStemmer() stop_words = nltk.corpus.stopwords.words('english') res = [] for word in line: word = re.sub(r'[^a-zA-Z\s]', '', word) word = word.lower() word = word.strip() if word == "" or word in stop_words: pass else: res.append(stemmer.stem(word)) return " ".join(res) class CBOWDataset(Dataset): def __init__(self, x, y): ''' args : npndarray of x and y return : dataLoader ''' self.x = torch.from_numpy(x).type(torch.LongTensor) self.y = torch.from_numpy(y).type(torch.LongTensor) def __len__(self): return self.x.shape[0] def __getitem__(self, idx): return (self.x[idx], self.y[idx]) def generate(sents, c, dictionary): ''' args : npndarray of strings return : context-target pair as list ''' tokenizer = SpaceTokenizer() xs=[] ys=[] for sent in sents: sent = tokenizer.tokenize(sent) start = c end = len(sent) for i in range(start, end - c): context=[] for j in range(-c, c+1): if j==0: pass else: context.append(dictionary.word2idx[sent[i+j]]) xs.append(context) ys.append(dictionary.word2idx[sent[i]]) x = np.vstack(xs) y = np.vstack(ys) return x, y def batchify(pairs): ''' args: generated pairs (list of lists) return: x npndarray, y npndarray ''' xs = [] ys = [] for n in range(0, len(pairs)): xs.append(pairs[n][0]) ys.append(pairs[n][1]) x = np.vstack(xs) y = np.vstack(ys) return x, y def train(): # CPU training #import pdb; pdb.set_trace() model.train() total_loss = 0 for i, (x, y) in enumerate(dataloader): # forward out = model(x) y = y.view(-1) # loss and backward loss = criterion(out, y) total_loss += loss.item() loss.backward() optimizer.step() # logging if (i % log_interval) == 0 and i != 0: #TODO : # 1) implement training function print("batch_idx {:d} | loss {:.4f}".format(i, total_loss / log_interval)) # 2) wrap up preprocessing -> create dataloader in certain form total_loss = 0 if __name__ == "__main__": tokenizer = SpaceTokenizer() normalize_corpus = np.vectorize(normalize) raw = gutenberg.sents('bible-kjv.txt') start_time = time.time() norm = normalize_corpus(raw[:100]) elapsed = time.time() - start_time # fill out dictionary dictionary = Dictionary() for sent in norm: words = tokenizer.tokenize(sent) for word in words: dictionary.add_word(word) ''' print("length of dict: ", len(dictionary)) print("word2idx: ", dictionary.word2idx) print("idx2dict: ", dictionary.idx2word) ''' # generate pairs start_time = time.time() pairs = generate(norm, 2, dictionary) elapsed = time.time() - start_time x, y = batchify(pairs) print(x[:10]) print(y[:10]) sys.exit(0) dataset = CBOWDataset(x, y) dataloader = DataLoader(dataset, batch_size=32, shuffle=True) model = CBOWModel(len(dictionary), 100) # variables log_interval = 10 criterion = nn.CrossEntropyLoss() optimizer = optim.RMSprop(model.parameters(), lr=0.01) for epoch in range(10): train()
true
8032bd1c0c8e0adf90bf52635344ef922c8dfce0
Python
jackwillson642/Python
/asc.py
UTF-8
207
3.390625
3
[]
no_license
a = [9,6,5,3,2] t = 0 for i in range(0,4): for j in range(i+1,4): if a[i]>a[j]: t = a[i] a[i] = a[j] a[j] = t for k in range(0,5): print(a[k], end =',')
true
9e7ee24d7ebb344e8471555a613eddcd697b6266
Python
matteobarbera/AdventOfCode2019
/Tests/intcode_test.py
UTF-8
3,984
2.765625
3
[]
no_license
import os import unittest from contextlib import redirect_stdout from io import StringIO from unittest import mock from Intcode import Intcode class TestIntcode(unittest.TestCase): def setUp(self): self.computer = Intcode() def tearDown(self) -> None: self.computer.program = None def test_init(self): self.assertTrue(self.computer.program is None) def test_addition(self): self.computer.new_program([1001, 1, 1, 0, 99]) self.assertEqual(list(self.computer.program.values()), [2, 1, 1, 0, 99]) def test_multiplication_1(self): self.computer.new_program([1002, 3, 2, 3, 99]) self.assertEqual(list(self.computer.program.values()), [1002, 3, 2, 6, 99]) def test_multiplication_2(self): self.computer.new_program([1002, 4, 99, 5, 99, 0]) self.assertEqual(list(self.computer.program.values()), [1002, 4, 99, 5, 99, 9801]) def test_program(self): self.computer.new_program([1001, 1, 1001, 4, 99, 5, 6, 0, 99]) self.assertEqual(list(self.computer.program.values()), [30, 1, 1001, 4, 1002, 5, 6, 0, 99]) def test_unknown_opcode(self): self.assertRaises(KeyError, self.computer.new_program([98, 0, 0, 99])) @mock.patch("builtins.input", side_effect=["1"]) def test_immediate_mode(self, inp): stdout = StringIO() with redirect_stdout(stdout): file_path = (os.path.dirname(__file__)) + "/immediate_mode_test_input.csv" with open(file_path, "r") as f: self.computer.new_program(list(map(int, next(f).split(",")))) self.assertEqual(stdout.getvalue(), "0\n0\n0\n0\n0\n0\n0\n0\n0\n13210611\n") def test_equal_to(self): stdout = StringIO() with redirect_stdout(stdout): self.computer.new_program([3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], user_input=[1]) self.computer.new_program([3, 3, 1108, -1, 8, 3, 4, 3, 99], user_input=[8]) self.assertEqual(stdout.getvalue(), "0\n1\n") @mock.patch("builtins.input", side_effect=["1", "8"]) def test_less_than(self, inp): stdout = StringIO() with redirect_stdout(stdout): self.computer.new_program([3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]) self.computer.new_program([3, 3, 1107, -1, 8, 3, 4, 3, 99]) self.assertEqual(stdout.getvalue(), "1\n0\n") def test_jump(self): stdout = StringIO() with redirect_stdout(stdout): self.computer.new_program([3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], user_input=[1]) self.computer.new_program([3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], user_input=[0]) self.assertEqual(stdout.getvalue(), "1\n0\n") @mock.patch("builtins.input", side_effect=["7", "8", "9"]) def test_program_2(self, inp): stdout = StringIO() with redirect_stdout(stdout): for i in range(3): self.computer.new_program([3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]) self.assertEqual(stdout.getvalue(), "999\n1000\n1001\n") def test_large_number(self): self.computer.new_program([1102, 34915192, 34915192, 7, 4, 7, 99, 0]) self.assertEqual(self.computer.program_output[0], 1219070632396864) def test_large_number_2(self): self.computer.new_program([104, 1125899906842624, 99]) self.assertEqual(self.computer.program_output[0], 1125899906842624) def test_relative_mode(self): program = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99] self.computer.new_program(program) self.assertEqual(self.computer.program_output, program) if __name__ == '__main__': unittest.main()
true
b312e1a32736fcc8dfa4831827fc641a50f729fe
Python
Aasthaengg/IBMdataset
/Python_codes/p03131/s448704270.py
UTF-8
147
2.796875
3
[]
no_license
K, A, B = map(int, input().split()) if A >= B - 1 or K <= A - 1: print(1 + K) else: r = K - (A - 1) print(r // 2 * (B - A) + A + r % 2)
true
c33c1042804a09ac7cef8155ae8bdb20b0096a5b
Python
MohammedAlbaqerH/Machine-learning-from-scratch
/PCA/pca.py
UTF-8
751
3
3
[]
no_license
import numpy as np class PCA: def __init__(self, dim = 2): self.dim = dim self.components = None self.mean = None def fit(self, X): #callate mean self.mean = X.mean(axis = 0) self.std = X.std(axis = 0) #callate coverance matrix X = (X - self.mean)/(self.std) cov = X.T@X #calculate eigvactor, eigvalue eigvalue, eigvactor = np.linalg.eig(cov) eigvactor = eigvactor.T idxs = np.argsort(eigvalue)[::-1] eigvalue = eigvalue[idxs] eigvactor = eigvactor[idxs] self.components = eigvactor[0:self.dim] def transform(self, X): X = X - self.mean X = np.dot(X, self.components.T) return X
true
bc47b0352b3d24dd1cc0fdf81e6737e260af6d4d
Python
cesern/Seminario-de-CsC-2018-1
/Tareas 1/CESB-sumaMatrices.py
UTF-8
1,044
2.640625
3
[]
no_license
"""import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import numpy as np N = 32 BLOCKS = 2 THREADS = 16 mod = SourceModule( #include <stdio.h> #define N 32 __global__ void montecarlo(float *a, float *b,float *c) { int indice = threadIdx.x + blockIdx.x*blockDim.x; if((x[indice]*x[indice] + y[indice]*y[indice]) <=1.0) { atomicAdd(contador,1);//contador++; //printf("Contador: %d\n",*contador); } } """#) import numpy as np #x = np.array([1 for i in range(N*N)]).astype(np.float32) #y = np.array([i for i in range(N*N)]).astype(np.float32) x = np.random.randn(1000).astype(np.float32) y = np.random.randn(1000).astype(np.float32) contador = np.array([0]).astype(np.float32) """ montecarlo = mod.get_function("montecarlo") montecarlo(cuda.In(a), cuda.In(b), cuda.Out(c), block=(BLOCKS,BLOCKS,1), grid=(THREADS,THREADS,1) ) #print( np.sum(a*b) ) print( c )""" print (x) print (y) print (contador)
true
550ef09bcf8b54157905ff9934970cca1697985d
Python
martinbonardi/Explicit-Content-Classifier-using-ResNet
/GUI/gui.py
UTF-8
1,775
2.71875
3
[ "Apache-2.0" ]
permissive
import tkinter as tk from tkinter import filedialog, Text import tkinter.font as font import os import model_predict import model_predict root = tk.Tk() root.title("Explicit Content Classifier") myFont = font.Font(family='Playfair Display') def openf(): foldername = filedialog.askdirectory(initialdir='/', title='Select Folder') global directory directory = foldername def predictions(): for widget in frame.winfo_children(): widget.destroy() cn, cs = model_predict.predict(directory) lab = tk.Label(frame, text = "Done!! \n") lab.config(font =("Playfair Display", 18)) lab.pack() l1 = tk.Label(frame, text = "NSFW Files Count : " + str(cn) + '\n') l1.config(font =("Playfair Display", 18)) l1.pack() l2 = tk.Label(frame, text = "SFW Files Count : " + str(cs)) l2.config(font =("Playfair Display", 18)) l2.pack() canvas = tk.Canvas(root, height = 400, width = 800, bg = '#29465B') canvas.pack() frame = tk.Frame(root, bg = 'white') frame.place(relwidth=0.8, relheight=0.7, relx=0.1, rely=0.1) Folder = tk.Button(root, text = 'Choose Folder', padx = 10, pady = 5, fg = 'white', bg = '#29465B', command = openf, width=27, font = myFont) Folder.pack(side = tk.LEFT) predict = tk.Button(root, text = 'Predict', padx = 10, pady = 5, fg = 'white', bg = '#29465B', command = predictions, width=27, font = myFont) predict.pack(side = tk.LEFT) des = tk.Button(root, text = 'Exit', padx = 10, pady = 5, fg = 'white', bg = '#29465B', command = root.destroy, width=27, font = myFont) des.pack(side = tk.LEFT) root.mainloop()
true
f43c3b1c015ae1d9eb7a70a4f436139b06f50c65
Python
alexlwn123/kattis
/Python/kastenlauf.py
UTF-8
640
2.890625
3
[]
no_license
def main(): cases = int(input()) while cases: nstores = int(input()) x0,y0 = map(int, input().split()) stores = [(x0,y0)] for _ in range(nstores): x,y = map(int, input().split()) stores.append((x,y)) x1,y1 = map(int, input().split()) isGood = {i:False for i in range(len(stores))} edges = [] for i in range(len(stores)): for j in range(len(stores)): if x1 == x0 and y1 == y0: continue dist = abs(x1-x0) + abs(y1-y0) cases -= 1 if __name__ == '__main__': main()
true
50734673f182e663d24da1aa9d541a867ab81d20
Python
tranmanhhung1941996/web_flask_python
/ticket_app/app/ticket_scraper_thegioididong.py
UTF-8
1,931
2.75
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from lxml import html import requests import re from pprint import pprint head = 'https://www.thegioididong.com' mid = '/tim-kiem?key=' def get_post_thegioididong(thegioididong_name): name = '+'.join(thegioididong_name.lower().split()) page = requests.get(head + mid + name) tree = html.fromstring(page.text) posts_pages = get_pages(tree) post_info = get_post_info(posts_pages) return post_info def get_pages(root): pprint("get_pages_thegioididong") post_urls = root.xpath('//li/a/@href') trees = [] for i in range(len(post_urls)): if i < 10: page = requests.get(head + post_urls[i]) tr = html.fromstring(page.text) trees.append(tr) return trees def get_post_info(posts_pages): post_info = [] stt = 0 for post in posts_pages: tensanpham = post.xpath('//div[@class="rowtop"]/h1//text()') if not tensanpham: pass else: stt = stt + 1 price = post.xpath("//aside[@class='price_sale']/div[@class='area_price']/strong//text()") if not price: price = post.xpath("//aside[@class='price_sale']/div[@class='boxshock']/div[@class='boxshockheader']/label/strong//text()") if not price: price = "Not Found" if price != "Not Found": price = price[0] detail = post.xpath("//ul[@class='policy']/li//text()") if not detail: detail = post.xpath("//ul[@class='policy ']/li//text()") if not detail: detail = "Nothing" if detail != "Nothing": detail = " ".join(detail) rate = post.xpath("//div[@class='ratingresult']/span[@class='star']") if not rate: rate = "None" else: rate = str(len(rate)*2) + "/10" post_info.append((stt, tensanpham[0], price, detail, rate)) return post_info if __name__ == "__main__": thegioididong_name = raw_input("Event to search for: ") results = get_post_thegioididong(thegioididong_name) for r in results: print(r)
true
981cb5fcd12dba7a6567bf5891496e3b577444f4
Python
goelhardik/programming
/leetcode/super_ugly_number/tle_but_correct_sol.py
UTF-8
2,226
3.609375
4
[]
no_license
class Heap(object): def __init__(self): self.heap = [-1] self.size = 0 def insert(self, num): self.size += 1 self.heap.append(num) self.perc_up(self.size) def perc_up(self, index): p = index // 2 while (p >= 1): if (self.heap[p] > self.heap[index]): self.swap(self.heap, p, index) index = p p = p // 2 else: return def swap(self, nums, i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp def extract_min(self): if (self.size == 0): return None ans = self.heap[1] tmp = self.heap.pop() self.size -= 1 if (self.size == 0): pass else: self.heap[1] = tmp self.perc_down(1) return ans def perc_down(self, index): left = index * 2 right = left + 1 smallest = index if (left <= self.size and self.heap[left] < self.heap[smallest]): smallest = left if (right <= self.size and self.heap[right] < self.heap[smallest]): smallest = right if (smallest != index): self.swap(self.heap, smallest, index) self.perc_down(smallest) class Solution(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int :type primes: List[int] :rtype: int """ heap = Heap() count = 0 uglies = [] # first super ugly number heap.insert(1) while (count < n): flag = 0 num = heap.extract_min() # skip duplicates if ((len(uglies) > 0) and (num == uglies[len(uglies) - 1])): continue uglies.append(num) count += 1 if (num in primes): flag = 1 if (count < n): for prime in primes: if (flag == 1 and prime < num): pass else: heap.insert(num * prime) return uglies[n - 1]
true
aa915214de3632caf6a46eccbf35b210a347793f
Python
KKDJOSEPH/GUI_OCM
/OCMhap/controller/AnimatedMapController.py
UTF-8
5,334
2.921875
3
[ "MIT" ]
permissive
import folium import folium.plugins import pandas import branca import numpy import geopandas import os import pkg_resources import webbrowser class AnimatedMapController(object): """ An AnimatedMapController represents a controller used for the creation of an animated map. """ county_geo_data = geopandas.read_file( pkg_resources.resource_filename(__name__, "../resources/data/cb_2018_us_county_500k.shp")) county_data = pandas.read_csv( pkg_resources.resource_filename(__name__, "../resources/data/uscounties.csv"), dtype=str) def __init__(self, controller, data): """ Initialize an AnimatedMapController. :param controller: The analysis controller controlling this object. :param data: The data frame from which to generate the animated map. """ self._controller = controller self._data = data self._column_name = None self._file_name = os.path.join(os.pardir, "map.html") @property def data(self): """The data object""" return self._data @property def column_name(self): """The column name of the data to plot""" return self._column_name @column_name.setter def column_name(self, column_name): """Set the column name of the data to plot""" if column_name not in self._data.attributes: raise ValueError("invalid column name") self._column_name = column_name def _validate_county_codes(self): """ Validate the county codes in the data. :return: true if the county codes represent valid FIPS county codes. """ county_codes = set(self.data.data["FIPS_State_Code"] + self.data.data["FIPS_County_Code"]) known_codes = set(self.county_data["county_fips"].astype(str)) unknown_codes = county_codes.difference(known_codes) if len(unknown_codes) > 0: self._controller.message("Invalid FIPS codes: {}".format(unknown_codes)) return False return True def _add_table_popup_to_map(self, folium_map, county_data): """ Add a popup to the folium map containing an html table of the county data. :param folium_map: the map to add the popup to. :param county_data: the county data, including Year, the column of interest, and lat and lng. """ html_table = county_data[["Year", self.column_name]].to_html() branca_frame = branca.element.IFrame(html=html_table, width=200, height=400) popup = folium.Popup(branca_frame, parse_html=True) folium.Marker( location=[list(county_data["lat"])[0], list(county_data["lng"])[0]], popup=popup ).add_to(folium_map) def generate_map(self): if "FIPS_State_Code" not in self.data.attributes or \ "FIPS_County_Code" not in self.data.attributes or \ "Year" not in self.data.attributes: self._controller.message("Data must contain the following columns: " "FIPS_State_Code, FIPS_County_Code, Year.") return if not self._validate_county_codes(): return if os.path.isfile(self._file_name): os.remove(self._file_name) data = self.data.data.copy() data["FIPS"] = data["FIPS_State_Code"] + data["FIPS_County_Code"] data = pandas.merge(data, self.county_data, left_on="FIPS", right_on="county_fips", how="left") data = pandas.merge(data, self.county_geo_data, left_on=["FIPS_State_Code", "FIPS_County_Code"], right_on=["STATEFP", "COUNTYFP"], how="left") data[self.column_name] = data[self.column_name].astype(float) folium_map = folium.Map(title='OCM_Map', location=[numpy.mean(data["lat"].astype(float)), numpy.mean(data["lng"].astype(float))], zoom_start=8) data["time"] = (pandas.to_datetime(data["Year"], format="%Y").astype(int) / 10 ** 9 + 100000).astype(str) color_map = branca.colormap.linear.YlOrRd_09.scale( data[self.column_name].min(), data[self.column_name].max()) data["color"] = data[self.column_name].map(color_map) counties = numpy.unique(data["FIPS_County_Code"]) style_dict = dict() for i, county in enumerate(counties): county_data = data.loc[data["FIPS_County_Code"] == county] self._add_table_popup_to_map(folium_map, county_data) time_color_map = dict() for _, row in county_data.iterrows(): time_color_map[row["time"]] = {"color": row["color"], "opacity": 0.7} style_dict[i] = time_color_map folium.plugins.TimeSliderChoropleth( data=geopandas.GeoDataFrame(data[["geometry"]]).drop_duplicates().reset_index(drop=True).to_json(), styledict=style_dict, ).add_to(folium_map) color_map.add_to(folium_map) color_map.caption = self.column_name folium_map.save(outfile=self._file_name) folium_map.render() webbrowser.open(self._file_name, new=2)
true
fbaed351cf23796d90a6ab89df8425dfb53f7791
Python
LJamieson/Robot
/robot_controls/scripts/test.py
UTF-8
408
2.828125
3
[]
no_license
import time import forwardsSerial moveClass = forwardsSerial.motors() sensorClass = forwardsSerial.sensors() moveClass.forward(0.5) time.sleep(1) moveClass.stop() time.sleep(1) print(sensorClass.get_temperature()) #moveClass.backward(0.8) time.sleep(1) #moveClass.brake() #time.sleep(2) #moveClass.set_left_motor_speed(1) #time.sleep(1) #moveClass.set_right_motor_speed(0.5) #time.sleep(3) moveClass.stop()
true
607999bc4ff911d0ffc6fbeca6546a452318e449
Python
IdealDestructor/LighterDetect-YoloV5
/divideData.py
UTF-8
857
3.21875
3
[ "Apache-2.0" ]
permissive
# -*- coding:UTF-8 -*- #制作训练集和验证集、测试集。 import os, random, shutil def moveFile(fileDir): pathDir = os.listdir(fileDir) #取图片的原始路径 filenumber=len(pathDir) rate=0.05 #自定义抽取图片的比例,比方说100张抽10张,那就是0.1 picknumber=int(filenumber*rate) #按照rate比例从文件夹中取一定数量图片 sample = random.sample(pathDir, picknumber) #随机选取picknumber数量的样本图片 print (sample) for name in sample: shutil.move(fileDir+name, tarDir+name) shutil.move(labelDir+name[:-4]+".txt", tarlabelDir+name[:-4]+".txt") return if __name__ == '__main__': fileDir = "./images/" tarDir = "./varImages/" labelDir = "./labels/" tarlabelDir = "./varLabels/" moveFile(fileDir)
true
9fb5c7189fba919cfe17e4354978f5b072fd58fc
Python
guacamole56/MYOB-ops-technical-test
/myob_ops_technical_test/helper.py
UTF-8
570
2.75
3
[]
no_license
import os def get_last_commit_sha(file_name='version.txt'): if os.path.exists(file_name): try: with open(file_name, 'r') as version_file: # If version.txt is available and readable use the version in it. return version_file.read().strip() except Exception: # If accessing the file fails return: return 'Unknown/Error' else: # Otherwise return development. This is the expected version to be shown # during local development phase. return 'Development'
true
0cc5758a27b37bffe511cc975be85b7af0ac9981
Python
CollinHU/TextEntityExtraction
/Deprecated/dict_construct_01_fuzzy_match.py
UTF-8
1,073
2.8125
3
[]
no_license
import csv import pandas as pd import nltk from nltk import sent_tokenize,word_tokenize, pos_tag, ne_chunk from nltk.stem.snowball import SnowballStemmer from nltk.metrics.distance import edit_distance max_dist = 1 def fuzzy_match(w1,w2): return edit_distance(w1,w2) <= max_dist def match_key(w_list, key): for w in w_list: if fuzzy_match(w,key): return True return False merged_key_dict = {} s_list = pd.read_csv('data/dictionary_01.csv') key_list = s_list['key'].values merged_key_dict[key_list[0]] = [key_list[0]] for item in key_list[1:]: is_not_key = True for k in merged_key_dict.keys(): if match_key(merged_key_dict[k],item): merged_key_dict[k].append(item) is_key = False break if(is_not_key): merged_key_dict[item] = [item] df_key = [] df_key_list = [] for key, value in merged_key_dict.items(): df_key.append(key) df_key_list.append(value) df_dic = {'key':df_key,'key_list':df_key_list} df = pd.DataFrame(df_dic) df.to_csv('test.csv') print 'finished'
true
30dce61075ddabe77a1b9c757e40397b58cc3feb
Python
gutierrezalexander111/PycharmProjects
/Tests/subprocess.py
UTF-8
372
2.84375
3
[]
no_license
#!/usr/bin/env python """Dictionary implementation for demonstrating a Python dictionary.""" import subprocess def MyNetworkAddress(): popen_obj = subprocess.Popen(("ifconfig", "en0"), stdout=subprocess.PIPE) open_pipe = popen_obj.stdout words = open_pipe.read().split() index = words.index("inet") return words[index +1] print MyNetworkAddress()
true
2504ae8aeacbdb221b779be678c9ee68247deabb
Python
LeishaBurford/AdventOfCode2019
/Day8.py
UTF-8
1,109
3.046875
3
[]
no_license
from pathlib import Path data_folder = Path("./PuzzleData/") file_to_open = data_folder / "Day8.txt" with open(file_to_open) as input: pixels = [int(pixel.strip()) for pixel in input.read()] def getLayers(pixels, width, height): layerSize = width * height return [pixels[x:x+layerSize] for x in range(0, len(pixels), layerSize)] width = 25 height = 6 layers = getLayers(pixels, width, height) zeroCount = (layers[0].count(0),layers[0]) for layer in layers: zeros = layer.count(0) if zeros < zeroCount[0]: zeroCount = (zeros, layer) print('Part 1: ',zeroCount[1].count(1) * zeroCount[1].count(2)) finalImage = layers.pop(0) for index, pixel in enumerate(finalImage): currentPixel = pixel while currentPixel == 2: for layer in layers: currentPixel = layer[index] if currentPixel != 2: break finalImage[index] = currentPixel a = [finalImage[x:x+25] for x in range(0, int(len(finalImage)), 25)] print('Part 2:') for row in a: print(' '.join([str('*' if pixel == 1 else ' ') for pixel in row]))
true
2ea60e310c78ad8e428d7c56f7464c4fa1bf6f6a
Python
Recomandation-System-Simplon/api_recommandation
/app/utils.py
UTF-8
5,168
2.5625
3
[]
no_license
from os import pipe import pandas as pd from flask import current_app import numpy as np from app.db import db import json def format_data_user(to_read_data, ratings_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: to_read_data,ratings_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ user = pd.concat([to_read_data.user_id, ratings_data.user_id]) user = user.sort_values() user = user.drop_duplicates() user = user.to_frame() user = user.reset_index() user = user.drop(columns={"index"}) user.user_id = user.user_id.astype("Int64") return user def format_data_rates(ratings_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: ratings_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ rates = ratings_data.rating rates = rates.sort_values() rates = rates.drop_duplicates() rates = rates.to_frame() rates = rates.reset_index() rates = rates.drop(columns="index") rates = rates.reset_index() rates = rates.rename(columns={"index": "ratings_id"}) rates = rates.rename(columns={"rating": "ratings"}) rates.ratings_id = rates.ratings_id + 1 colonne_int = ["ratings_id","ratings"] for col in colonne_int: rates[col] = rates[col].astype("Int64") return rates def format_data_books(book_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: book_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ liste_colonne_drop = [ "work_id", "books_count", "isbn", "average_rating", "language_code", "image_url", "small_image_url", "ratings_count", "work_ratings_count", "work_text_reviews_count", "ratings_1", "ratings_2", "ratings_3", "ratings_4", "ratings_5", ] books = book_data for i in liste_colonne_drop: books = books.drop(columns=i) colonne_int = ["book_id","goodreads_book_id","isbn13","original_publication_year"] for col in colonne_int: books[col] = books[col].astype("Int64") books = books.rename(columns={"isbn13": "isbn"}) return books def format_data_ratings(ratings_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: ratings_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ ratings = ratings_data.rename(columns={"rating": "ratings_id"}) colonne_int = ["user_id","book_id","ratings_id"] for col in colonne_int: ratings[col] = ratings[col].astype("Int64") return ratings def format_data_to_read(to_read_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: to_read_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ to_read = to_read_data to_read = to_read.reset_index() to_read = to_read.rename(columns={"index": "to_read_id"}) to_read.to_read_id = to_read.to_read_id + 1 colonne_int = ["to_read_id","user_id","book_id"] for col in colonne_int: to_read[col] = to_read[col].astype("Int64") return to_read def format_data_tags(tags_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: tags (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ tags = tags_data tags.tag_id = tags.tag_id + 1 tags.tag_id = tags.tag_id.astype("Int64") return tags def format_data_goodread_book(book_data: pd.DataFrame): """Permet de formatter les champs du dataframe afin de les conformer au type de la BDD Args: book_data (pd.DataFrame): dataframe provenant du fichier csv Returns: pd.DataFrame: Le dataframe converti """ goodread_book = book_data goodread_book = goodread_book.goodreads_book_id goodread_book = goodread_book.sort_values() goodread_book = goodread_book.drop_duplicates() goodread_book = goodread_book.to_frame() goodread_book = goodread_book.reset_index() goodread_book = goodread_book.drop(columns={"index"}) goodread_book.goodreads_book_id = goodread_book.goodreads_book_id.astype("Int64") return goodread_book def format_data_book_tag(book_tags_data: pd.DataFrame): book_tags = book_tags_data book_tags = book_tags.reset_index() book_tags = book_tags.rename(columns={"index":"id"}) book_tags.id = book_tags.id +1 book_tags.tag_id = book_tags.tag_id + 1 book_tags = book_tags.drop(columns={"count"}) return book_tags
true
26ad38638c8463f5c982ccffa4a386245d7ad53c
Python
austincqdo/treehacks
/app.py
UTF-8
3,002
2.59375
3
[]
no_license
from flask import Flask, render_template, request from scraper import get_votes from project import output_data app = Flask(__name__) ## Make API calls in this file. Use name of elected official as first two parameters for get_votes(). ## 'select' is the third param. @app.route('/') def index(): return render_template("index.html") @app.route('/result', methods=['GET', 'POST']) def result(): if request.method == 'POST': select_iss = request.form.get('issues') print(select_iss) select_loc = request.form.get('location') print(select_loc) double_dict = output_data(select_loc) for candidate in double_dict: double_dict[candidate]['votes'] = get_votes(double_dict[candidate]['First Name'], \ double_dict[candidate]['Last Name'], select_iss) double_dict[candidate]['Phone #'] = "N/A" if double_dict[candidate]['votes'] == []: double_dict[candidate]['votes'] = ["N/A"] if double_dict[candidate]['First Name'] == "Eleini": double_dict[candidate]['First Name'] = "Eleni" double_dict[candidate]['Bio'] = "In 1992, Eleni started her career as a staff member of the California Democratic Party in Sacramento and worked in the historic election, which elected two women to the U.S. Senate and turned California blue. \ After the election, Eleni joined her family business, AKT Development, one of California’s most respected housing development firms. Over the next 18 years, Eleni worked her way up from project manager to president. \ Her work delivering housing for middle-class families in the Sacramento region earned her recognition as one of Sacramento’s most prominent businesswomen.\ In 2010, Eleni was appointed by President Barack Obama as the U.S. Ambassador to Hungary and served side-by-side President Obama and Secretary Hillary Clinton promoting democracy." double_dict[candidate]['Phone #'] = "(415) 857-0921" double_dict[candidate]['donations'] = ["Kounalakis, Eleni Tsakopolous: $7,679,896.00", "California Association of Realtors: $29,200.00", \ "Northern California Regional Council of Carpenters: $29,200.00", "Spanos Companies, including Alex G Spanos & Affiliated Entities: $19,600.00"] if double_dict[candidate]['First Name'] == "Marc": double_dict[candidate]['Phone #'] = "(650) 691-2121" double_dict[candidate]['donations'] = ["Berman, Marc: $73,700", "Pivot Group Inc.: $18,534", "California Association Of Realtors: $17,000", \ "Northern California Regional Council Of Carpenters: $15,000"] if double_dict[candidate]['First Name'] == "Anna": double_dict[candidate]['Phone #'] = "(650) 323-2984" double_dict[candidate]['donations'] = ["Votesane PAC: $58,000", "Oracle Corp: $21,480", "Stanford University: $19,350", \ "Kleiner, Perkins et al: $18,900"] return render_template('result.html', first=double_dict['Candidate0'], second=double_dict['Candidate1'], \ third=double_dict['Candidate5'], area=select_loc, topic=select_iss.replace("_", " ")) if __name__ == "__main__": app.run(debug=True)
true
e4e8d9796ee950cbdd1d18b07936350bb8ed9afc
Python
kaskang99/Projeto_final_Super_Fox
/sprites.py
UTF-8
5,699
2.921875
3
[]
no_license
# Sprite classes for game from config import * import pygame as pg from os import path from random import choices from assets import * vec = pg.math.Vector2 dir = path.dirname(__file__) mob_dir = path.join(dir, 'assets') class Player(pg.sprite.Sprite): def __init__(self, game): #no arquivo MAIN.py - self.player = Player(self) - o init precisa de mais de 1 argumento, já que não é mais Player() e sim Player(self) pg.sprite.Sprite.__init__(self) self.game = game #Agora a classe Player tem como referência o jogo. self.walking = False self.jumping = False self.current_frame = 0 self.last_update = 0 self.load_images() self.dir = path.dirname(__file__) self.snd_dir = path.join(self.dir, 'snd') self.jump_sound = pg.mixer.Sound(path.join(self.snd_dir, 'fox_jump.wav')) self.image = self.standing_frame[0] self.image.set_colorkey(PLAYER_GREEN) self.rect = self.image.get_rect() self.rect.center = (WIDTH/2, 600) self.pos = vec(WIDTH/5, HEIGHT/2) self.vel = vec(0,0) self.acc = vec(0,0) def load_images(self): self.standing_frame = [self.game.fox_sprite.get_image(56, 4, 46, 35)] for frame in self.standing_frame: frame.set_colorkey(PLAYER_GREEN) self.walk_frame_r=[self.game.fox_sprite.get_image(0, 0, 45, 36), self.game.fox_sprite.get_image(114, 2, 46, 36)] for frame in self.walk_frame_r: frame.set_colorkey(PLAYER_GREEN) self.walk_frame_l=[] for frame in self.walk_frame_r: frame.set_colorkey(PLAYER_GREEN) self.walk_frame_l.append(pg.transform.flip(frame, True, False)) self.jump_frame = self.game.fox_sprite.get_image(229, 0, 38, 40) self.jump_frame.set_colorkey(PLAYER_GREEN) def jump(self): #pular somente se estiver em uma plataforma ou estiver no chao self.rect.x += 1 #adicionei um pixel para o retângulo do jogador (verificar se tem ou não uma plataforma) hits = pg.sprite.spritecollide(self, self.game.platforms, False) self.rect.x -= 1 #retirei o pixel de verificação if hits: self.vel.y = -PLAYER_JUMP self.jump_sound.play() def update(self): self.animate() self.acc = vec(0,PLAYER_GRAVITY) keys = pg.key.get_pressed() if keys[pg.K_RIGHT]: self.acc.x = PLAYER_ACC # implementacao do atrito self.acc.x += self.vel.x * PLAYER_FRICTION #eq of motion self.vel += self.acc if abs(self.vel.x) < 0.1: self.vel.x = 0 self.pos += self.vel + 0.5*self.acc # jogador sai pra fora da tela e volta do outro lado if self.pos.x > WIDTH: self.pos.x = 0 if self.pos.x < 0: self.pos.x = WIDTH self. rect.midbottom = self.pos def animate(self): now = pg.time.get_ticks() if self.vel.x != 0: self.walking=True else: self.walking = False #animacao de andar if self.walking: if now - self.last_update>300: self.last_update = now self.current_frame = (self.current_frame + 1) % len(self.walk_frame_l) bottom = self.rect.bottom if self.vel.x>0: self.image = self.walk_frame_r[self.current_frame] else: self.image = self.walk_frame_l[self.current_frame] self.rect = self.image.get_rect() self.rect.bottom = bottom #animacao quando estiver parado if not self.jumping and not self.walking: if now - self.last_update > 200: self.last_update = now self.current_frame = (self.current_frame + 1) % len(self.standing_frame) bottom = self.rect.bottom self.image = self.standing_frame[self.current_frame] self.rect = self.image.get_rect() self.rect.bottom = bottom class Platform(pg.sprite.Sprite): def __init__(self, game, x, y): pg.sprite.Sprite.__init__(self) self.game = game images = self.game.spritesheet.get_image(0, 288, 380, 94) self.image = images self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y class Spritesheet: #utility class for loading and parsing spritesheets def __init__(self, filename): self.spritesheet = pg.image.load(filename).convert_alpha() #self.cloud_spritesheet = pg.image.load(filename).convert() def get_image(self, x, y, w, h): # grab an image out of a larger spritesheet image = pg.Surface((w,h),pg.SRCALPHA) image.blit(self.spritesheet, (0, 0), (x, y, w, h)) image = pg.transform.scale(image, ((3*w)//4, (3*h)//4)) #resize image return image class Mob(pg.sprite.Sprite): def __init__(self, game, x, y): pg.sprite.Sprite.__init__(self) self.game = game images = pg.image.load(path.join(mob_dir, 'lion_dir.png')) self.image = images self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y class Flag(pg.sprite.Sprite): def __init__(self, game, x, y): pg.sprite.Sprite.__init__(self) self.game = game images = pg.image.load(path.join(mob_dir, 'flagRed.png')) self.image = images self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y
true
6ea9fe55ffa3a929f7ff4007cbe12da79f1213a3
Python
ao9000/tic-tac-toe-ai
/game/player.py
UTF-8
2,472
3.890625
4
[]
no_license
""" Player class Handles everything related to move selection by the bot or the human player. """ from bot.minimax import minimax_soft_alpha_beta, get_depth import random from math import inf class Player: """ Player class A player can be a human or bot. """ def __init__(self, bot, state, mark): """ Constructor for Person class. :param bot: type: bool True if the player is a bot, else False for human player :param state: type: int Integer representing the player's state (0 or 1 or 2) 0 - BLANK_STATE 1 - HUMAN_STATE 2 - BOT_STATE :param mark: type: str String representing the player's mark. (Noughts or crosses) (X or O) """ self._bot = bot self._state = state self._mark = mark @property def bot(self): return self._bot @property def state(self): return self._state @property def mark(self): return self._mark @staticmethod def convert_index_to_move(index): """ Converts user input index (1-9) into move indexes. (<row_index>, <column_index>) :param index: type: int User input selected move index (1-9) :return: type: tuple Selected move index in numpy array format (<row_index>, <column_index>) """ index_to_move_dict = { 1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2) } return index_to_move_dict[index] def make_move(self, board): """ Calls the minimax algorithm if the player is a bot, else request user input for human player. :param board: type: numpy.ndarray The current state of the Tic Tac Toe board game Input for the minimax algorithm to find the optimal move :return: type: tuple Selected move index in numpy array format (<row_index>, <column_index>) """ if self._bot: # Minimax algorithm _, moves = minimax_soft_alpha_beta(board, get_depth(board), True, -inf, +inf) move = random.choice(moves) else: # Prompt the user to select a move index = input("Enter move: ") move = Player.convert_index_to_move(int(index)) return move
true
d039698f7a347ee5c7c52c9fd94361d30a88fc62
Python
wesinalves/neuralnet
/my_perceptron.py
UTF-8
1,055
3.21875
3
[ "Apache-2.0" ]
permissive
''' simple implementation of rosemblat's perceptron Wesin Alves ''' import numpy as np ##set parameters num_inputs = 4 lr = 0.1 bias = np.random.normal() # input signals inputs = [np.array([int(y) for y in bin(x).lstrip("0b").zfill(num_inputs)]) for x in range(2**num_inputs)] print("Shape of input:") for x in inputs: print(x) ##weight array weights = np.random.randn(num_inputs) ## forward function def forward(W,x): return 1 if np.dot(W,x) + bias > 0 else 0 # set target function (NAND) def target(x): return int (not (x[0] and x[1])) ## backward number_of_errors = -1 while number_of_errors !=0: number_of_errors = 0 print ("Beginning iteration") print ("Bias: {:.3f}".format(bias)) print ("Weights:", ", ".join( "{:.3f}".format(wt) for wt in weights)) for x in inputs: error = target(x) - forward(weights, x) if error: number_of_errors += 1 bias = bias + lr * error weights = weights + lr * error * x print ("Number of errors:", number_of_errors, "\n")
true
885c37c5771ae84f8b2baf332fa2f210094cf1b4
Python
ILister1/core-project
/service3/app.py
UTF-8
538
2.53125
3
[]
no_license
from flask import Flask, request, Response import random app = Flask(__name__) @app.route('/setting', methods=['GET', 'POST']) def setting(): #settings = ["a mysterious cavern", "an intimidating room", "a dreamlike headspace"] #return Response(random.choice(settings), mimetype="text/plain") settings = ["an empty room", "a perfect place", "a second chance"] return Response(random.choice(settings), mimetype="text/plain") if __name__=="__main__": app.run(debug=True, host='0.0.0.0', port=5002)
true
37671a630f215b5fbfba6b7786893682a9675063
Python
mvonpapen/swem
/swem/metrics.py
UTF-8
6,977
3.03125
3
[ "MIT" ]
permissive
"""Implementation of certain useful metrics.""" from __future__ import annotations import json import torch from swem.utils.classes import ClfMetricTracker, KeyDependentDefaultdict class ClassificationReport: """A class for tracking various metrics in a classification task. The class is particularly useful when doing handling a dataset batch-wise where metrics should be aggregated over the whole dataset. Args: target_names (list[str | int] | None): Labels in the classification task in the same order as the output of the model. binary (bool): Whether or not we are doing binary classification (i.e. the model output is the pre-sigmoid logit for the positive class). Defaults to False. from_probas (bool): If True we interpret the input as probabilities instead of logits. This is only relevant when dealing with binary classification (since in the multiclass setting the predicted label is an argmax which is the same for logits and probabilities). Defaults to False. Examples: >>> report = ClassificationReport(target_names=["A", "B"]) >>> logits = torch.tensor([[1,0], [0,1], [1,0]]) >>> labels = torch.tensor([0, 0, 1]) >>> report.update(logits, labels) >>> report.get() { "num_samples": 3, "accuracy": 0.3333333333333333, "class_metrics": { "A": { "support": 2, "recall": 0.5, "precision": 0.5, "f1_score": 0.5 }, "B": { "support": 1, "recall": 0.0, "precision": 0.0, "f1_score": null } } } >>> mask = torch.tensor([1,1,0]) >>> report.reset() >>> report.update(logits, labels, mask) >>> report.get() { "num_samples": 2, "accuracy": 0.5, "class_metrics": { "A": { "support": 2, "recall": 0.5, "precision": 1.0, "f1_score": 0.6666666666666666 }, "B": { "support": 0, "recall": null, "precision": 0.0, "f1_score": null } } } """ def __init__( self, target_names: list[str | int] | None = None, binary: bool = False, from_probas: bool = False, ): self.target_names = target_names self.binary = binary self.from_probas = from_probas self.num_samples = 0 self.num_correct = 0 self.class_metrics = KeyDependentDefaultdict(ClfMetricTracker) def reset(self): """Reset all tracked values.""" self.num_samples = 0 self.num_correct = 0 self.class_metrics = KeyDependentDefaultdict(ClfMetricTracker) def __repr__(self) -> str: state = self.get() if state is None: return "" return json.dumps(state, indent=2) def get( self, ) -> dict[str, int | float | dict] | None: """Get the current state of all tracked metrics.""" if self.num_samples == 0: return None return { "num_samples": self.num_samples, "accuracy": self.num_correct / self.num_samples, "class_metrics": { name: { "support": met.support, "recall": met.recall, "precision": met.precision, "f1_score": met.f1_score, } for name, met in self.class_metrics.items() }, } def update( self, logits: "array_like", labels: "array_like", mask: "array_like" | None = None, ): """Update the tracked metrics with the results from a new batch. The inputs can be any type that can be turned into a torch.Tensor ("array_like"). Args: logits (array_like): Output of the model in the classification task (pre-softmax/sigmoid if self.from_probas is False or probabilites if self.from_probas is True). labels (array_like): The correct labels. mask (array_like | None): A 0/1-mask telling us which samples to take into account (where mask is 1). Defaults to None. Shapes: - logits: :math:`(*, \\text{num_classes})` if self.binary is False otherwise :math:`(*,)` where * is any number of dimensions. - labels: :math:`(*,)` where * is the same as for logits. - mask: :math:`(*,)` where * is the same as for logits. """ logits = ( logits.clone().detach() if isinstance(logits, torch.Tensor) else torch.tensor(logits) ) labels = ( labels.clone().detach() if isinstance(labels, torch.Tensor) else torch.tensor(labels) ) if self.binary: num_classes = 2 if self.from_probas: preds = (logits > 0.5).to(dtype=torch.int64) else: preds = (logits > 0).to(dtype=torch.int64) else: num_classes = logits.size(-1) preds = torch.argmax(logits, dim=-1) assert ( preds.size() == labels.size() ), f"Expected predictions and labels to have the same shape but got {preds.shape} and {labels.shape}." if mask is None: mask = torch.ones_like(labels, dtype=torch.bool, device=labels.device) else: mask = ( mask.clone().detach() if isinstance(mask, torch.Tensor) else torch.tensor(mask) ).to(dtype=torch.bool) assert ( labels.size() == mask.size() ), f"Expected mask and labels to have the same shape but got {mask.shape} and {labels.shape}." mask = mask.view(-1) labels = labels.view(-1) preds = preds.view(-1) self.num_samples += torch.sum(mask).item() self.num_correct += torch.sum((labels == preds) * mask).item() for i in range(num_classes): if self.target_names is None: name = i else: name = self.target_names[i] label_mask = labels == i preds_mask = preds == i self.class_metrics[name].tp += torch.sum( label_mask * preds_mask * mask ).item() self.class_metrics[name].fp += torch.sum( (~label_mask) * preds_mask * mask ).item() self.class_metrics[name].fn += torch.sum( label_mask * (~preds_mask) * mask ).item()
true
05e536af40aeebab4c6d1cf79bfaa9437bbe7e72
Python
mikekeda/maps
/core/tests_models.py
UTF-8
554
2.609375
3
[ "MIT" ]
permissive
from django.test import TestCase from core.models import get_unique_slug, Category class MapsModelsTest(TestCase): def test_models_catagory(self): slug = get_unique_slug(Category, "Test title") self.assertEqual(slug, "test-title") category_obj = Category(title="Test title") category_obj.save() self.assertEqual(category_obj.slug, "test-title") self.assertEqual(str(category_obj), "Test title") slug = get_unique_slug(Category, "Test title") self.assertEqual(slug, "test-title-1")
true
c8eda30a8fcd7fbd496a10cd39a173842b26983f
Python
akaufman10/scrapeDyno
/scrapedyno/scrapers.py
UTF-8
7,601
3.171875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Jun 19 15:09:21 2016 @author: alex """ import pandas as pd import os import time from .scrapely_mod import MonkeyPatch import hashlib import scrapely from .utilities import HTMLTableParser, isnumber def advanced_scraper(website,data=None): ''' website: website type object with selenium browser data: values contain the data that should be used to create the template. Keys contain arbitrary lables. See https://github.com/scrapy/scrapely for example of the dictionary format. ''' MonkeyPatch() page_id = hashlib.sha1(website.url).hexdigest() filename = 'scrapers/%s' % page_id scraper = scrapely.ScraperMod() #the scraper object gets imported from the MonkeyPatch function if not os.path.isfile(filename): file = open(filename,'w') scraper.train_mod(website,data) scraper.tofile(file) file.close else: file = open(filename,'r+') scraper = scraper.fromfile(file) file.close() newData = scraper.scrape_mod(website) newFrame = pd.DataFrame(newData, index=[0]) newFrame['time'] = (time.strftime("%H:%M:%S")) newFrame['date'] = (time.strftime("%d/%m/%Y")) return newFrame def basic_table_scraper(website, table_number=None,row_numbers=None): ''' allows you to specify the exact parts of the table you want to scrape. In addition to selecting the table numbers, you can also select the row numbers. use the print_tables function on the scrapetool to identify table and row numbers (indexed from 0) ''' if not table_number or not row_numbers: raise KeyError('This scraper needs you to tell it which table and rows to scrape using table_number= and row_number= as keyword arguments') html = website.browser.page_source parser = HTMLTableParser() parser.feed(html) try: table = parser.tables[table_number] data = pd.DataFrame(columns=table[row_numbers[0]]) except IndexError: print 'the scraper could not find the right table or row, this will be handled by the scrape function' return print 'the following columns were assigned for scraping: ' + ", ".join(table[row_numbers[0]]) for i in range(len(row_numbers)): if i == 0: #skip the first row, since it defines variables not data pass else: values = table[row_numbers[i]] tempData = pd.DataFrame(data=[values], columns=table[row_numbers[0]]) data = data.append(tempData) data['time'] = (time.strftime("%H:%M:%S")) data['date'] = (time.strftime("%d/%m/%Y")) return data class all_tables_scraper(object): ''' a scraper that can return all tables on a page, return a single table, or return specified rows from a single table ''' @staticmethod def run(website, transpose=False, get_tables=None, get_rows=None): ''' This unbound method is automatically run when the scraper is specified in the scrapeTool. transpose : boolean indicating if variables names are listed on the left side instead of top get_table : scrape only a specific table number get_rows : scrape only specified rows from table NOTE: use the Dino's print_tables function to view tables available for scraping ''' transpose_temp = False # set temporary transpose boolean to False as default if get_rows and not get_tables: #logical check that user selected a table to scrape rows from raise KeyError('You need to specify a single table for scraping using the get_table key') html = website.browser.page_source #get html parser = HTMLTableParser() #assign parser object parser.feed(html) #pass html to parser object dataList = [] #create empty list to hold dataframes if tables > 1 if get_tables: #if a specific table is specified copyTables = parser.tables parser.tables = [] #reset the parser.tables to be an empty list [parser.tables.append(table) for table in [copyTables[i] for i in get_tables]] #pull out each table assigned in get_tables and reassign it to parser.tables for i in range(len(parser.tables)): # for each table table = parser.tables[i] #assign table for scraping if get_rows: #if rows are scraped, table = list(table[i] for i in get_rows) #replace the table with only the desired rows data = pd.DataFrame(data=table[1:], columns=table[0]) #assign table data to a dataframe, using the first row as the column values #begin checking procedure to determine if table should be transposed allStrings = True #assume all the table's values are strings sideStrings = True #assume all values in col=0 are strings topStrings = True #assume all values in row=0 are strings allStrings_temp = allStrings sideStrings_temp = sideStrings topStrings_temp = topStrings for j in range(len(table)): #for each row in the table try: valuetest = table[j][j].encode('ascii','ignore') #get the diagonal value allStrings = not isnumber(valuetest) #test if the value is a number except IndexError: #if col < row, move on pass if allStrings_temp != allStrings: #if the value is a number, stop checking break for j in range(len(table)): #for each row in the table valuetest = table[j][0].encode('ascii','ignore') #get the value of the first col sideStrings = not isnumber(valuetest) #test if its a number if sideStrings_temp != sideStrings: #i if the value is a number, stop checking break for j in range(len(table[0])): #for each col in the table valuetest = table[0][j].encode('ascii','ignore') #get the value of the first col topStrings = not isnumber(valuetest) #test if its a number if topStrings_temp != topStrings: #if the value us a number, stop checking break notAllStrings = not allStrings #create a flag that is true if not all values are strings notTopStrings = not topStrings #create a flag that is true if not all values in the top row are strings if sideStrings & notTopStrings & notAllStrings: #if the table has numbers but all the values in the first col are strings, assume the table is "sideways" transpose_temp = True if transpose or transpose_temp: # if the table should be transposed data = data.transpose() #transpose the data data.columns = data.iloc[0] #use the first row of data as column names print("Sideways table detected, transposing. Set sideTable=False to prevent this action") transpose_temp = False #reset temporary transpose variable #add time and date to the data data['time'] = (time.strftime("%H:%M:%S")) data['date'] = (time.strftime("%d/%m/%Y")) dataList.append(data) #add the dataset to the list of scraped tables return dataList
true
9c673f9ad31bcdb3c65c3a1c46c6b1c775e04ab7
Python
fdbesanto2/carbon-budget
/analyses/loss_in_raster.py
UTF-8
2,078
2.8125
3
[]
no_license
import subprocess import datetime import os import sys sys.path.append('../') import constants_and_names as cn import universal_util as uu # Calculates a range of tile statistics def loss_in_raster(tile_id, raster_type, output_name, lat, mask): print "Calculating loss area for tile id {0}...".format(tile_id) xmin, ymin, xmax, ymax = uu.coords(tile_id) # start time start = datetime.datetime.now() # Name of the loss time loss_tile = '{0}.tif'.format(tile_id) # The raster that loss is being analyzed inside raster_of_interest = '{0}_{1}.tif'.format(tile_id, raster_type) # Output file name outname = '{0}_{1}.tif'.format(tile_id, output_name) # Only processes the tile if it is inside the latitude band (north of the specified latitude) if ymax > lat and os.path.exists(raster_of_interest): print "{} inside latitude band and peat tile exists. Processing tile.".format(tile_id) # If the user has asked to create just a mask of loss as opposed to the actual output values if mask == "True": calc = '--calc=(A>=1)*(A+1)/(A+1)*B' # If the user has asked to output the actual loss values if mask == "False": # Equation argument for converting emissions from per hectare to per pixel. # First, multiplies the per hectare emissions by the area of the pixel in m2, then divides by the number of m2 in a hectare. calc = '--calc=A*B' # Argument for outputting file out = '--outfile={}'.format(outname) print "Masking loss in {} by raster of interest...".format(tile_id) cmd = ['gdal_calc.py', '-A', loss_tile, '-B', raster_of_interest, calc, out, '--NoDataValue=0', '--co', 'COMPRESS=LZW', '--overwrite'] subprocess.check_call(cmd) print "{} masked".format(tile_id) else: print "{} outside of latitude band. Skipped tile.".format(tile_id) # Prints information about the tile that was just processed uu.end_of_fx_summary(start, tile_id, output_name)
true
9a8f443794538a0145ff272d67e5ee446b3fc728
Python
x1He/leetcode_practice
/problems/find_mode_in_BST_501/__init__.py
UTF-8
606
3.046875
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import Counter class Solution: def findMode(self, root: TreeNode) -> List[int]: def dfs(root, res): if root: res[root.val] += 1 dfs(root.left, res) dfs(root.right, res) if not root: return [] res = Counter() dfs(root, res) t = res.most_common()[0][1] return [int(k) for k,v in res.items() if v == t]
true
20b278dcdfd6217f2b806e9845b1e3cad51efd27
Python
vyahello/upgrade-python-kata
/kata/07/number_of_decimal_digits.py
UTF-8
498
4.375
4
[ "MIT" ]
permissive
""" Determine the total number of digits in the integer (n>=0) given as input to the function. For example, 9 is a single digit, 66 has 2 digits and 128685 has 6 digits. Be careful to avoid overflows/underflows. All inputs will be valid. """ def digits(number: int) -> int: """Counts number of digits. Args: number (int): given input number Examples: >>> assert digits(66) == 2 """ return len(str(number)) if __name__ == "__main__": print(digits(66))
true
c94541369561c6fd76eaee5de6c31b4ce8f8b08e
Python
leandrotartarini/python_exercises
/secondWorld/ex056.py
UTF-8
596
4.0625
4
[]
no_license
sumage = 0 olderman = 0 oldername = '' woman20 = 0 for p in range(1,5): print(f'----- {p} PERSON') name = str(input('Name: ')).strip() age = int(input('Age: ')) sex = str(input('M/F: ')).strip() sumage += age if p == 1 and sex in 'Mm': olderman = age oldername = name if sex in 'Mm' and age > olderman: oldername = age oldername = name if sex in 'Ff' and age < 20: woman20 = woman20 + 1 average = sumage / 4 print(f'Age avarage is {average}') print(f'The oldest man is {oldername} and he is {olderman} years old') print(f'There is {woman20} women under 20 yo')
true
6ab2113a5cb70f1959d304f320c673aee40ed4e4
Python
joeADSP/adventofcode2020
/12/1.py
UTF-8
2,018
4
4
[]
no_license
def load_data(): with open("data.txt", "r") as f: data = f.read().splitlines() return data def parse_instruction(instruction): command = instruction[:1] units = int(instruction[1:]) return command, units class Ferry: def __init__(self): self._x = 0 self._y = 0 self._vector_x = 1 self._vector_y = 0 def move_east(self, units): self._x += units return def move_west(self, units): self._x -= units return def move_north(self, units): self._y += units return def move_south(self, units): self._y -= units return def forward(self, units): self._x += self._vector_x * units self._y += self._vector_y * units return def rotate_clockwise(self, degrees): self._rotate(degrees) return def rotate_anticlockwise(self, degrees): self._rotate(360 - degrees) return def _rotate(self, degrees): steps = degrees // 90 for i in range(steps): self._vector_x, self._vector_y = self._vector_y, -self._vector_x return @property def manhattan_distance(self): return abs(self._x) + abs(self._y) def main(): data = load_data() ferry = Ferry() for instruction in data: command, units = parse_instruction(instruction) if command == "N": ferry.move_north(units) if command == "E": ferry.move_east(units) if command == "S": ferry.move_south(units) if command == "W": ferry.move_west(units) if command == "F": ferry.forward(units) if command == "R": ferry.rotate_clockwise(units) if command == "L": ferry.rotate_anticlockwise(units) print(ferry.manhattan_distance) return if __name__ == "__main__": main()
true
b5b36c2cc7feea7cd2cd2cf41b5fdefbe65e396e
Python
iomgaa/Learning-Deeplearning-for-100-days
/1 day/1 day.py
UTF-8
2,862
3.234375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd # In[2]: dataset = pd.read_csv('Data.csv')#读取csv文件 X = dataset.iloc[ : , :-1].values#.iloc[行,列] Y = dataset.iloc[ : , 3].values # : 全部行 or 列;[a]第a行 or 列 # [a,b,c]第 a,b,c 行 or 列 # In[3]: print(X); print(Y); # In[4]: from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0)# 建立替换规则:将值为Nan的缺失值以均值做替换 imput = imputer.fit(X[ : , 1:3])# 应用模型规则 X[ : , 1:3] = imput.transform(X[ : , 1:3]) # # imputer # # 可选参数 # # strategy: 'mean'(默认的), ‘median’中位数,‘most_frequent’出现频率最大的数 # axis: 0(默认), 1 # copy: True(默认), False # 输出 # # numpy数组,之后可转化为DataFrame形式 # 属性: # # Imputer.statistics_可以查看每列的均值/中位数 # 特别说明:最好将imputer应用于整个数据集。因为虽然现在可能只有某一个属性存在缺失值,但是在新的数据中(如测试集)可能其他的属性也存在缺失值 # # [详解](http://www.dataivy.cn/blog/3-1-%e6%95%b0%e6%8d%ae%e6%b8%85%e6%b4%97%ef%bc%9a%e7%bc%ba%e5%a4%b1%e5%80%bc%e3%80%81%e5%bc%82%e5%b8%b8%e5%80%bc%e5%92%8c%e9%87%8d%e5%a4%8d%e5%80%bc%e7%9a%84%e5%a4%84%e7%90%86-2%e4%bb%a3%e7%a0%81/#more-1075) # In[5]: from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder()#即将离散型的数据转换成 00 到 n−1n−1 之间的数,这里 nn 是一个列表的不同取值的个数,可以认为是某个特征的所有不同取值的个数。 X[ : , 0] = labelencoder_X.fit_transform(X[ : , 0]) # In[6]: print(X) # In[7]: onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() labelencoder_Y = LabelEncoder() Y = labelencoder_Y.fit_transform(Y) # [关于sklearn中的OneHotEncoder](https://www.jianshu.com/p/39855db1ed0b) # # [OneHotEncoder独热编码和 LabelEncoder标签编码](https://www.cnblogs.com/king-lps/p/7846414.html) # # [scikit-learn 中 OneHotEncoder 解析](https://www.cnblogs.com/zhoukui/p/9159909.html) # In[8]: print(X); # In[9]: print(Y); # In[10]: #from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split( X , Y , test_size = 0.2, random_state = 0) # [train_test_split用法](https://blog.csdn.net/mrxjh/article/details/78481578) # In[11]: from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train)#归一化 X_test = sc_X.transform(X_test) # In[12]: print(X_train); print(X_test); # In[ ]:
true
a592b93c285c1122ee45e9eaff95dc1452794a0c
Python
anton-trapeznikov/RecipeParser
/apps/parser/core.py
UTF-8
12,976
2.640625
3
[ "MIT" ]
permissive
from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.conf import settings from urllib.parse import urlparse, urljoin from bs4 import BeautifulStoneSoup as Soup from abc import ABCMeta, abstractmethod import urllib.request import time import json import uuid import re import os class UrlParser(object): ''' Класс ищет на сайте все адреса, соответствующие регулярному выражению и сохраняет их в файле. Имеет единственный публичный метод parse, возвращающий путь к файлу с урлами. Использует настройки парсера: PARSER__URL_SOURCE PARSER__SITEMAP_URL PARSER__CELL_HOMEPAGE PARSER__RECIPE_URL_TEMPLATE ''' def __init__(self): # URL-ы рецептов self._urls = set() # Все обнаруженные на сайте адреса. Применяется при парсинге html self._finds = set() # Обработанные адреса. Применяется при парсинге html self._processed = set() #Интервал в секундах между парсингом html страниц. Целое число. self.sleep_time = 1 # Валидаторы self._recipe_validator = URLValidator(regex=settings.PARSER__RECIPE_URL_TEMPLATE) self._url_validator = URLValidator() self.json_file_path = None def parse(self): ''' Метод формирует JSON список url с рецептами сайта и сохраняет его в MEDIA_ROOT/parser/source.js. В зависимости от настроек анализирует карту сайта или же парсит html-страницы. ''' # Парсинг по карте сайта if hasattr(settings, 'PARSER__URL_SOURCE') and settings.PARSER__URL_SOURCE == 'sitemap': xml = None if not hasattr(settings, 'PARSER__SITEMAP_URL') or not settings.PARSER__SITEMAP_URL: print('PARSER__SITEMAP_URL is not defined') else: try: with urllib.request.urlopen(settings.PARSER__SITEMAP_URL) as response: xml = response.read() except Exception: xml = None if xml: sitemap = Soup(xml) urls = sitemap.findAll('url') for u in urls: loc = u.find('loc').string self._add_location(loc) else: # Парсинг по тегам html-страниц if not hasattr(settings, 'PARSER__CELL_HOMEPAGE') or not settings.PARSER__CELL_HOMEPAGE: print('PARSER__CELL_HOMEPAGE is not defined') return False # Счетчик рекурсивных вызовов метода _parse_html self._recursion_counter = 0 self._parse_html(settings.PARSER__CELL_HOMEPAGE) self._save() return self.json_file_path def _add_location(self, location): ''' Метод добавляет локацию в self._urls если она соответствует регулярному выражению. ''' try: self._recipe_validator(location) self._urls.add(location) except ValidationError: pass def _save(self): ''' Метод сохраняет сериализованный в JSON список урлов с рецептами. Файл сохраняется в MEDIA_ROOT/parser/source.js. ''' if self.json_file_path is None: directory = os.path.join(settings.MEDIA_ROOT, 'parser') if not os.path.exists(directory): os.makedirs(directory) self.json_file_path = os.path.join(directory, 'source.js') if os.path.exists(self.json_file_path): os.remove(self.json_file_path) with open(self.json_file_path, 'w') as outfile: json.dump(list(self._urls), outfile) def _build_link(self, url, location_parts): ''' Метод формирует и возвращает ссылку приведенную к абсолютной или None, если ссылка некоректна. ''' href = None scheme = location_parts.scheme domain = location_parts.netloc location = location_parts.path site = '%s://%s' % (scheme, domain) if url: if url[0] == '/': # Ссылка относительно корня сайта href = urljoin(site, url) elif url[:len(site)] == site: # Абсолютная ссылка href = url elif url[:len(domain)] == domain: # Ссылка без протокола href = '%s://%s' % (scheme, url) elif '://' in url: # Ссылка на другой домен или протокол href = None elif 'javascript:' in url: # JS href = None elif url[0] == '#': # Якорь href = None elif 'mailto:' in url: href = None else: # Ссылка относительно текущего документа (или ссылка с GET вида ?...) doc = urljoin(site, location) href = urljoin(doc, url) return href def _parse_html(self, url): ''' Метод загружает страницу из url и обрабатывает все ссылки на ней присутствующие. Рекурсивно вызывает самого себя для первой из еще не обработанных ссылок, т.о. парсится весь сайт. ''' html = None page_content = None self._processed.add(url) self._recursion_counter += 1 try: with urllib.request.urlopen(url) as response: html = response.read() except Exception: html = None print('Unable to load url %s' % url) if html: try: page_content = Soup(html) except Exception: page_content = None if page_content: stop_list = ('#', '', '/') for a in page_content.find_all('a', href=True): if a['href'] not in stop_list: href = self._build_link(url=a['href'], location_parts=urlparse(url)) if href: try: self._url_validator(href) except ValidationError: print('%s is not valid url' % href) else: self._finds.add(href) self._add_location(url) unprocessed = self._finds - self._processed print('Всего страниц: %s. Обработано страниц: %s. Найдено рецептов: %s. Последний URL: %s' % (len(self._finds), len(self._processed), len(self._urls), url)) # На каждом 20-ом вызове данного метода сохраняем self._urls if self._recursion_counter % 20: self._save() self._recursion_counter = 0 if unprocessed: if self.sleep_time > 0: time.sleep(self.sleep_time) next_url = list(unprocessed)[0] self._parse_html(next_url) class ContentParser(object): __metaclass__ = ABCMeta ''' Класс сериализует рецепты с загружаемых страниц в виде json-файлов. Для использования необходимо переопределить в потомке абстрактный метод _parse_html в соответствии с содержимым карточки рецепта конкретного сайта с рецептами. Единственный публичный метод parse итеративно загружает страницы из json-файла, обрабатывает их с помощью метода _parse_html и сохраняет в виде json файла. ''' def __init__(self, file_path=None): ''' file_path -- абсолютный путь к JSON файлу со списком урлов. Если file_path не определен, то метод попытается загрузить данные из MEDIA_ROOT/parser/source.js. ''' if file_path is None: directory = os.path.join(settings.MEDIA_ROOT, 'parser') file_path = os.path.join(directory, 'source.js') if not os.path.exists(file_path): raise Exception('JSON file not found') with open(file_path) as input_file: try: urls = json.load(input_file) except Exception: urls = [] self._urls = urls self._urls_length = len(self._urls) self._url_validator = URLValidator() self._site = None #Интервал в секундах между парсингом html страниц. Целое число. self.sleep_time = 1 def parse(self): ''' Каждая из страниц self._urls парсится методом _parse_html, если результат, возвращенный _parse_html, отличен от None, то результат сохраняется методом _save_recipe. ''' for url in self._urls: html = None if not hasattr(self, '_recipe_count'): self._recipe_count = 1 else: self._recipe_count += 1 try: self._url_validator(url) except ValidationError: print('%s is not valid url' % url) else: try: location_parts=urlparse(url) self._site = '%s://%s' % (location_parts.scheme, location_parts.netloc) with urllib.request.urlopen(url) as response: html = Soup(response.read()) except Exception: html = None if html: recipe = self._parse_html(html=html) if recipe: self._save_recipe(recipe=recipe) print('Всего загружено: %s\%s' % (self._recipe_count, self._urls_length)) if self.sleep_time > 0: time.sleep(self.sleep_time) @abstractmethod def _parse_html(self, html): ''' Метод принимает bs4-объект html страницы. Метод должен возвратить None или словарь описывающий рецепт вида: { 'name': None, 'summary': None, 'ingredients': [], 'image': [], 'recipeInstructions': None, 'cookTime': None, 'recipeYield': None, 'resultPhoto': None, 'category': [], } Все ключи словаря, кроме category, должны быть заполнены в соответствии с логикой микроразметки Яндекс Рецептов. Ключ category -- структура товара в каталоге целевого сайта ''' raise NotImplementedError('Abstract method raise') def _save_recipe(self, recipe): ''' Сохранение словара с рецептом в json-файл. Файл размещается в в MEDIA_ROOT/parser/recipes/ ''' recipe_id = uuid.uuid4().hex js_recipe = json.dumps(recipe) parser_directory = os.path.join(settings.MEDIA_ROOT, 'parser') recipe_dir = os.path.join(parser_directory, 'recipes') if not os.path.exists(recipe_dir): os.makedirs(recipe_dir) recipe_fullpath = os.path.join(recipe_dir, '%s.js' % recipe_id) if os.path.exists(recipe_fullpath): os.remove(recipe_fullpath) with open(recipe_fullpath, 'w') as rf: rf.write(js_recipe)
true
545a3bad558e3b220e24a64d99c98a0035d86eb1
Python
namntran/modern_python3_bootcamp
/BooleanandConditionalLogic/logicalNot.py
UTF-8
465
4.125
4
[]
no_license
age = int(input("What is your age?")) # age 2-8 years is $2 tickets # age 65 years + is $5 tickets # everyone else is $10 tickets if not ((age >= 2 and age <= 8) or age >= 65 or age <2): print("you pay $10 dollars and not entitled to discount") elif age >= 65: print("you pay $5 and are entiled to senior discount") elif age >= 2 and age <= 8: print("you pay $2 and are entitled to child discount") else: print("please don't cry during the movie")
true
394e7a913feed987f6e8dbee9c15bbb7619ac530
Python
WinrichSy/Codewars_Solutions
/Python/7kyu/MinimizeSumOfArray.py
UTF-8
224
3.5
4
[]
no_license
#Minimize Sum Of Array (Array Series #1) #https://www.codewars.com/kata/5a523566b3bfa84c2e00010b def min_sum(arr): arr = sorted(arr) ans = sum([arr[i]*arr[len(arr)-i-1] for i in range(len(arr)//2)]) return ans
true
f6d37f28c0b45537d80273e3d53e4e8afd48337b
Python
naoto0804/atcoder_practice
/contests/abc/19/195/c.py
UTF-8
1,007
2.609375
3
[]
no_license
import sys, re from collections import deque, defaultdict, Counter from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd from itertools import accumulate, permutations, combinations, product from operator import itemgetter, mul from copy import deepcopy from string import ascii_lowercase, ascii_uppercase, digits from bisect import bisect, bisect_left from heapq import heappush, heappop from functools import reduce import numpy as np def input(): return sys.stdin.readline().strip() def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def ZIP(n): return zip(*(MAP() for _ in range(n))) sys.setrecursionlimit(10 ** 9) INF = float('inf') mod = 10 ** 9 + 7 N = INT() if N < 1000: print(0) exit() n = N n_comma = 0 ans = 0 while n >=1000: n_comma += 1 n = n // 1000 ans += n_comma * (N + 1 - (1000 ** n_comma)) for i in range(1, n_comma): ans += i * (1000 ** (i + 1) - 1000 ** i) print(ans)
true
626d7665c135cbdc6d35e7f81a40ad73632ede69
Python
Atollye/search4letters
/letters_search.py
UTF-8
276
3.53125
4
[]
no_license
#!/usr/bin/env python3 def search4letters(phrase, letters='aeiou'): """ Returns the set of vowels found in 'phrase'""" return set(letters).intersection(set(phrase)) if __name__ == "__main__": phrase = input() res = search4letters(phrase) print(str(res))
true
7a6482d2fab5497cb391dfdc1339f802e9cfc368
Python
Rasquin/python-test
/vending_machine_challenge.py
UTF-8
2,831
4.1875
4
[]
no_license
#Challenge I """"Change the function so that instead of a list of coins, the function works with a dictionary that contains the coin denominations, and the quantity of each coin available. By default, assume there are 20 of each coin, but this can be overridden by passing a dictionary to the function as with the previous example. If a coin that would normally be used to make change isn't available the program should attempt to use smaller coins to make up the change. If it is not possible to make the change with the coins available, the function should raise an error.""" from byotest import * # from byotest we import everything # Create a dictionary with denomination of coin and its quantity as key, value usd_coins = [100:20, 50:20, 25:20, 10:20, 5:20, 2:20, 1:20] eur_coins = [200:20, 100:20, 50:20, 20:20, 10:20, 5:20, 2:20, 1:20] def get_change(amount, coins=eur_coins): """ Takes the payment amount and returns the change `amount` the amount of money that we need to provide change for `coins` is the set of coins that we need to get change for (i.e. the set of available coins) Returns a list of coin values """ change = [] # Unlike a list, looping through a dictionary does not keep the order. # Therefore we use `sorted()` to sort the order. 'coins.key()' to move between the keys. This will start with the # lowest by default, so we use `reverse=True` to start with the highest # denomination. The `while` ends when the domination quantity reaches 0. # An exception is thrown if there are insufficient coins to give change. for denomination in sorted(coins.key(), reverser=True): #As long as the coin is less than or equal to the amount, it will carry on adding it. #Before was an "if" while denomination <= amount and coins[denomination] > 0: amount -= denomination coins[denomination] -=1 change.append(denomination) if amount != 0: raise Exception("Insufficient coins to give change.") return change # Write our tests for our code test_are_equal(get_change(0), []) test_are_equal(get_change(1), [1]) test_are_equal(get_change(2), [2]) test_are_equal(get_change(5), [5]) test_are_equal(get_change(10), [10]) test_are_equal(get_change(20), [20]) test_are_equal(get_change(50), [50]) test_are_equal(get_change(100), [100]) test_are_equal(get_change(3), [2, 1]) test_are_equal(get_change(7), [5, 2]) test_are_equal(get_change(9), [5, 2, 2]) test_are_equal(get_change(35, usd_coins), [25, 10]) #here we are choosing the list of coins and their Key:value pars. test_are_equal(get_change(5, {2: 1, 1: 4}), [2, 1, 1, 1]) test_exception_was_raised(get_change, (5, {2: 1, 1: 2}), "Insufficient coins to give change.") print("All tests pass!")
true
f5052bffc0c3dda66faba0426795fa12dcf3cd70
Python
Infinidrix/competitive-programming
/Take 2 Week 4/shortestBridge.py
UTF-8
2,044
3.296875
3
[]
no_license
class Solution: def connect_dots(self, A, x, y, visited): neighbors = [[1, 0], [0, 1], [-1, 0], [0, -1]] outline = set() path = collections.deque() path.append((x, y)) visited.add((x, y)) while path: land = path.popleft() for neighbor in neighbors: new_x = land[0] + neighbor[0] new_y = land[1] + neighbor[1] if not (0 <= new_x < len(A) and 0 <= new_y < len(A)): continue if A[new_x][new_y] == 1 and (new_x, new_y) not in visited: visited.add((new_x, new_y)) path.append((new_x, new_y)) elif A[new_x][new_y] == 0: outline.add((new_x, new_y, 0)) return outline def find_one(self, A): visited = set() for line in range(len(A)): for i in range(len(A)): if A[line][i] == 1: outline = self.connect_dots(A, line, i, visited) return visited, outline def shortestBridge(self, A: List[List[int]]) -> int: neighbors = [[1, 0], [0, 1], [-1, 0], [0, -1]] visited, outline = self.find_one(A) print(f'Visited: {visited}') path = collections.deque() path.extend(outline) while path: point = path.popleft() for neighbor in neighbors: new_x = point[0] + neighbor[0] new_y = point[1] + neighbor[1] if not (0 <= new_x < len(A) and 0 <= new_y < len(A)): continue if A[new_x][new_y] == 1 and (new_x, new_y) not in visited: print(f"Point: {point}, coords: {(new_x, new_y)}") return point[2] + 1 elif A[new_x][new_y] == 0 and (new_x, new_y) not in outline: outline.add((new_x, new_y)) path.append((new_x, new_y, point[2] + 1))
true
942333568e40a0cc4eda568937e388977af29d65
Python
Sosthene00/hd_derivation_workshop
/ecc/ecc.py
UTF-8
12,623
3.09375
3
[]
no_license
# Elliptic Curves library for cryptography import hmac, hashlib from ecc.util import * from io import BytesIO P = pow(2, 256) - pow(2, 32) - 977 A = 0 B = 7 Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 class FieldElement: def __init__(self, num, prime): if num == None or prime == None: error = 'None value not allowed' raise ValueError(error) if num >= prime or num < 0: error = f'{num} not in field range 0 to {prime - 1}' raise ValueError(error) self.num = num self.prime = prime def __repr__(self): # this overwrite the standard `print()` function return f'FieldElement {self.prime}({self.num})' def __eq__(self, other): # this overwrite the standard `==` operator if other is None: return False # return an error instead of simply False? # you need two things to compare, if not it should fail return self.num == other.num and self.prime == other.prime def __ne__(self, other): # this overwrite the standard `!=` operator return not self == other def __add__(self, other): if self.prime != other.prime: raise TypeError('Cannot add two numbers in different Fields') num = (self.num + other.num) % self.prime return self.__class__(num, self.prime) # return self.__class__ means retur a new object of the same class def __sub__(self, other): if self.prime != other.prime: raise TypeError('Cannot substract two numbers in different Fields') num = (self.num - other.num) % self.prime return self.__class__(num, self.prime) def __mul__(self, other): if self.prime != other.prime: raise TypeError('Cannot multiply two numbers in different Fields') num = (self.num * other.num) % self.prime return self.__class__(num, self.prime) def __pow__(self, exponent): n = exponent % (self.prime - 1) num = pow(self.num, n, self.prime) return self.__class__(num, self.prime) def __truediv__(self, other): if self.prime != other.prime: raise TypeError('Cannot divide two numbers in different Fields') num = self.num * pow(other.num, (self.prime-2), self.prime) % self.prime return self.__class__(num, self.prime) def __rmul__(self, coefficient): coef = self.__class__(coefficient, self.prime) return self * coef class Point: def __init__(self, x, y, a, b): self.a = a self.b = b self.x = x self.y = y if self.x is None and self.y is None: return if self.y**2 != self.x**3 + self.a * self.x + self.b: raise ValueError(f'({self.x}, {self.y}) is not on the curve') def __eq__(self, other): return self.x == other.x and self.y == other.y \ and self.a == other.a and self.b == other.b def __ne__(self, other): return not (self == other) def __repr__(self): if self.x is None: return 'Point(infinity)' else: return f'Point({self.x}, {self.y})_{self.a}_{self.b}' def __add__(self, other): if self.a != other.a or self.b != other.b: raise TypeError(f'Points {self}, {other} are not on the same curve') if self.x is None: return other if other.x is None: return self if self.x == other.x and self.y != other.y: return self.__class__(None, None, self.a, self.b) if self == other and self.y == 0 * self.x: return self.__class__(None, None, self.a, self.b) if self.x != other.x: m = (other.y - self.y) / (other.x - self.x) x = pow(m, 2) - self.x - other.x y = m * (self.x - x) - self.y return self.__class__(x, y, self.a, self.b) if self == other: m = (3 * pow(self.x, 2) + self.a) / (2 * self.y) x = pow(m, 2) - 2 * self.x y = m * (self.x - x) - self.y return self.__class__(x, y, self.a, self.b) def __rmul__(self, coefficient): coef = coefficient current = self result = self.__class__(None, None, self.a, self.b) while coef: if coef & 1: result += current current += current coef >>= 1 return result class S256Field(FieldElement): def __init__(self, num, prime=None): super().__init__(num=num, prime=P) def __repr__(self): return '{:x}'.format(self.num).zfill(64) def sqrt(self): return self**((P + 1) // 4) class S256Point(Point): def __init__(self, x, y, a=None, b=None): a, b = S256Field(A), S256Field(B) if type(x) == int: super().__init__(x=S256Field(x), y=S256Field(y), a=a, b=b) else: super().__init__(x=x, y=y, a=a, b=b) def __repr__(self): if self.x is None: return 'S256Point(infinity)' else: return f'S256Point({self.x}, {self.y})' def __rmul__(self, coefficient): coef = coefficient % N return super().__rmul__(coef) def verify(self, m, sig): z = generate_secret(m) s_inv = pow(sig.s, N - 2, N) u = z * s_inv % N v = sig.r * s_inv % N total = u * G + v * self return total.x.num == sig.r def verify_schnorr(self, m, sig): e = ecc.util.generate_secret(ecc.util.to_string(self, sig.r, m)) return sig.s * G == sig.r + e * self def sec(self, compressed=True): if compressed: if self.y.num % 2 == 0: return b'\x02' + self.x.num.to_bytes(32, 'big') else: return b'\x03' + self.x.num.to_bytes(32, 'big') else: return b'\x04' + self.x.num.to_bytes(32, 'big') \ + self.y.num.to_bytes(32, 'big') def hash160(self, compressed=True): return hash160(self.sec(compressed)) def address(self, compressed=True, testnet=False): h160 = self.hash160(compressed) if testnet: prefix = b'\x6f' else: prefix = b'\x00' return encode_base58_checksum(prefix + h160) @classmethod def parse(self, sec_bin): if sec_bin[0] == 4: x = int.from_bytes(sec_bin[1:33], 'big') y = int.from_bytes(sec_bin[33:65], 'big') return S256Point(x=x, y=y) is_even = sec_bin[0] == 2 x = S256Field(int.from_bytes(sec_bin[1:], 'big')) alpha = x**3 + S256Field(B) beta = alpha.sqrt() if beta.num % 2 == 0: even_beta = beta odd_beta = S256Field(P - beta.num) else: even_beta = S256Field(P - beta.num) odd_beta = beta if is_even: return S256Point(x, even_beta) else: return S256Point(x, odd_beta) def create_commitment(self, domain, protocol, msg): # implementation of LNPBP 1 # hash domain and protocol domain_digest = hashlib.sha256(domain.encode('utf-8')).digest() protocol_digest = hashlib.sha256(protocol.encode('utf-8')).digest() # hash both tags' hashes with the msg lnpbp1_msg = domain_digest + protocol_digest + msg.encode('utf-8') # HMAC s and P to get the tweaking factor f HMAC = hmac.new(self.sec(), None, hashlib.sha256) HMAC.update(lnpbp1_msg) f = int.from_bytes(HMAC.digest(), 'big') # assert f < p try: f < P except: print("ERROR: tweak overflow secp256k1 order") # Compute a new PrivateKey with f as secret return PrivateKey(f) def tweak_pubkey(self, tweak): # add F to P return self + tweak def verify_commitment(self, domain, protocol, msg, commitment): return self + self.create_commitment(domain, protocol, msg).point == commitment G = S256Point(Gx, Gy) class PrivateKey: def __init__(self, secret): if type(secret) is not int: self.secret = generate_secret(secret) else: self.secret = secret self.point = self.secret * G def hex(self): return '{:x}'.format(self.secret).zfill(64) def sign(self, z): #z = generate_secret(m) k = self.deterministic_k(z) r = (k * G).x.num k_inv = pow(k, N - 2, N) s = (z + r * self.secret) * k_inv % N if s > N / 2: s = N - s return Signature(r, s) def sign_schnorr(self, m): z = ecc.util.generate_secret(m) k = self.deterministic_k(z) R = k * G e = ecc.util.generate_secret(ecc.util.to_string(self.point, R, m)) s = k + e * self.secret % N return Signature(R, s) def deterministic_k(self, z): k = b'\x00' * 32 v = b'\x01' * 32 if z > N: z -= N z_bytes = z.to_bytes(32, 'big') secret_bytes = self.secret.to_bytes(32, 'big') s256 = hashlib.sha256 k = hmac.new(k, v + b'\x00' + secret_bytes + z_bytes, s256).digest() v = hmac.new(k, v, s256).digest() k = hmac.new(k, v + b'\x01' + secret_bytes + z_bytes, s256).digest() v = hmac.new(k, v, s256).digest() while True: v = hmac.new(k, v, s256).digest() candidate = int.from_bytes(v, 'big') if candidate >= 1 and candidate < N: return candidate # <2> k = hmac.new(k, v + b'\x00', s256).digest() v = hmac.new(k, v, s256).digest() def wif(self, compressed=True, testnet=False): secret_bytes = self.secret.to_bytes(32, 'big') if testnet: prefix = b'\xef' else: prefix = b'\x80' if compressed: suffix = b'\x01' else: suffix = b'' return encode_base58_checksum(prefix + secret_bytes + suffix) def tweak_privkey(self, tweak): return (self.secret + tweak) % P # TODO: straighten up this method @classmethod def from_wif(self, wif): num = 0 for c in wif: num *= 58 num += BASE58_ALPHABET.index(c) combined = num.to_bytes(38, byteorder='big') checksum = combined[-4:] if hash256(combined[:-4])[:4] != checksum: raise ValueError('bad private key {} {}'.format(checksum, hash256(combined[:-4])[:4])) combined = combined[:-4] if combined[-1] == 1: secret = combined[:-1] return secret[1:] class Signature: def __init__(self, r, s): self.r = r self.s = s def __repr__(self): return 'Signature({:x},{:x})'.format(self.r, self.s) def der(self): rbin = self.r.to_bytes(32, byteorder='big') # remove all null bytes at the beginning rbin = rbin.lstrip(b'\x00') # if rbin has a high bit, add a \x00 if rbin[0] & 0x80: rbin = b'\x00' + rbin result = bytes([2, len(rbin)]) + rbin # <1> sbin = self.s.to_bytes(32, byteorder='big') # remove all null bytes at the beginning sbin = sbin.lstrip(b'\x00') # if sbin has a high bit, add a \x00 if sbin[0] & 0x80: sbin = b'\x00' + sbin result += bytes([2, len(sbin)]) + sbin return bytes([0x30, len(result)]) + result @classmethod def parse(cls, signature_bin): s = BytesIO(signature_bin) compound = s.read(1)[0] if compound != 0x30: raise SyntaxError("Bad Signature") length = s.read(1)[0] if length + 2 != len(signature_bin): raise SyntaxError("Bad Signature Length") marker = s.read(1)[0] if marker != 0x02: raise SyntaxError("Bad Signature") rlength = s.read(1)[0] r = int.from_bytes(s.read(rlength), 'big') marker = s.read(1)[0] if marker != 0x02: raise SyntaxError("Bad Signature") slength = s.read(1)[0] s = int.from_bytes(s.read(slength), 'big') if len(signature_bin) != 6 + rlength + slength: raise SyntaxError("Signature too long") return cls(r, s)
true
7ca88b6d11a43434a66520ce565af8d0648d4556
Python
vvveracruz/learn-py
/zhang-intro/ex3.py
UTF-8
4,552
4.21875
4
[]
no_license
import math def two_a(): ''' A program that asks the ser for a float x_0 an prints the value of f(x) = x^3 - 3x + 1 at x_0 ''' x = float ( raw_input( "Please enter your value for x_0: " ) ) print( x ** 3 - 3*x + 1 ) def two_b(): ''' A function that asks the user for their name, then prints "Hello `name`!" ''' name = str ( raw_input( "What is your name? " ) ) print( "Hello %s!" % name ) def two_c(): ''' A function that asks the user for an integer, and then displays the number of digits in the integer, and the logarithm of the integer ''' n = int ( raw_input( "Choose an integer: " ) ) logn = math.log(n) count = 0 num = n while ( num > 0 ): num = num // 10 count = count + 1 print( "%d has %d digits." % (n, count)) print( "The logarithm of %d is %.2f." % (n, logn)) def two_d(): ''' A function that asks the user for an integer, and then displays the number of digits in the integer to the power of 3. ''' n = int ( raw_input( "Choose an integer: " ) ) n3 = n ** 3 count = 0 num = n3 while ( num > 0 ): num = num // 10 count = count + 1 print( "{}, which is {} to the power of three, has {} digits".format( n3, n, count )) def two_e(): ''' A function which asks the user to input a string s and displays the following string: "s***s***s". ''' s = str ( raw_input( "What is your motto? " ) ) print( "{}***{}***{}".format(s, s, s ) ) def two_f(): ''' A function which asks the user for a string and displays a string that repeats the input string n times, where n is the length of the input string. ''' s = str ( raw_input( "What is your motto? " ) ) n = 0 string = s while n < len(s) - 1: n += 1 string = string + s print( string ) def centerString( s, border, lineLength ): ''' A function used in three() ''' if (len( s ) % 2) == 0: #name is even padding = ( lineLength - 2 - len(s) ) / 2 sLine = border + ' ' * padding + s + ' ' * padding + border + '\n' else: paddingLeft = int( math.floor( ( lineLength - 2 - len(s) ) / 2 ) ) paddingRight = paddingLeft + 1 sLine = border + ' ' * paddingLeft + s + ' ' * paddingRight + border + '\n' return sLine def three(): ''' A function that asks the user for their name, and a short message under 50 characters, and displays it. ''' name = str ( raw_input( "What is your name? " ) ) message = str ( raw_input( "What is your message? " ) ) lineLength = 40 border = '*' fullLine = border * lineLength + '\n' emptyLine = border + ' ' * ( lineLength - 2 ) + border + '\n' nameLine = centerString( 'Hello '+ name, border, lineLength) if len( message ) < ( lineLength - 2 ): messageLine = centerString( message, border, lineLength ) else: messageLine = getFormattedMessage( message, lineLength, border) print( fullLine + emptyLine + nameLine + emptyLine + messageLine + emptyLine + fullLine) def getFormattedMessage( rawMessage, lineLength, border ): ''' ''' # INIT messageLength = lineLength - 2*len(border) - 2 wordList = rawMessage.split(' ') formattedLine = '' formattedMessage = '' for word in wordList: if len(word) + len(formattedLine) + 1 >= messageLength: formattedLine = centerString( formattedLine, border, lineLength ) formattedMessage = formattedMessage + formattedLine formattedLine = word else: formattedLine = formattedLine + ' ' + word formattedLine = centerString( formattedLine, border, lineLength ) formattedMessage = formattedMessage + formattedLine return formattedMessage def four(): ''' A program that asks for user input and performs conversions. ''' choice = None choiceMessage = "What conversion do you need help with?\n\n1 - Celsius to Fahrenheit,\n2 - Fahrenheit to Celsius,\n3 - Meter to foot,\n4 - Foot to meter,\n5 - Acre to square meter,\n6 - Square meter to acre,\n7 - Pound to kilogram,\n8 - Kilogram to pound conversion.\n\nEnter a digit from 1 to 8 here: " choiceError = "\nThat's not an option. Please enter a digit from 1 to 8 here: " choice = int( raw_input( choiceMessage ) ) while True: if choice in range(8): break else: choice = int( raw_input( choiceError ) ) if __name__ == '__main__': four()
true
e2735b2d80a90b5910a87b5888bcb3a9f1151df4
Python
code-knayam/DataStructureAlgorithms
/code-wars/004.order_weight.py
UTF-8
889
3.359375
3
[ "MIT" ]
permissive
def sum_dg(st): sum = 0 for c in st: sum = sum + int(c) return sum def order_weight(strng): strng = strng.split(" ") leng = len(strng) for i in range(leng): for j in range(leng-1): if sum_dg(strng[j]) > sum_dg(strng[j+1]): temp = strng[j] strng[j] = strng[j+1] strng[j+1] = temp if sum_dg(strng[j]) == sum_dg(strng[j+1]): if strng[j+1] < strng[j]: temp = strng[j] strng[j] = strng[j+1] strng[j+1] = temp return " ".join(strng) # def order_weight(_str): # return ' '.join(sorted(sorted(_str.split(' ')), key=lambda x: sum(int(c) for c in x))) print(order_weight("103 123 4444 99 2000")) print(order_weight("2000 10003 1234000 44444444 9999 11 11 22 123 "))
true
278d89221a835656fa8273adb5250a24b960a8b9
Python
cholla-bear/ProjectEuler
/lib/prime.py
UTF-8
2,270
3.40625
3
[]
no_license
from collections import defaultdict import itertools from itertools import takewhile, islice from math import sqrt from functools import lru_cache, reduce from operator import mul import numpy as np @lru_cache(maxsize=None) def prime_factors(n): '''Returns a dictionary of prime factors with their counts''' prime_factors = defaultdict(int) while n % 2 == 0: prime_factors[2] += 1 n = n/2 trial_factor = 3 while n > 1: q, r = divmod(n, trial_factor) if r == 0: n = q prime_factors[trial_factor] += 1 else: trial_factor += 2 return prime_factors def proper_divisors(n): '''Return a list of divisors of n, including 1 but excluding n''' if n == 0: raise ValueError if n == 1: return [1] pf = prime_factors(n) raised_factors = [] for factor, power in pf.items(): raised_factors.append([factor**n for n in range(power+1)]) factor_components = itertools.product(*raised_factors) proper_divisors = [reduce(mul, xs) for xs in factor_components] proper_divisors.remove(n) return proper_divisors def take_primes(n): '''Returns a list of the first n primes''' return list(islice(primes(), n)) def primes(): '''Return a generator of prime numbers''' known_primes = [] yield 2 test_num = 3 while True: limit = sqrt(test_num) filtered_primes = takewhile(lambda x: x <= limit, known_primes) if not any(test_num % p == 0 for p in filtered_primes): known_primes.append(test_num) yield test_num test_num += 2 @lru_cache(maxsize=None) def is_prime(n): if n <= 1: return False elif n == 2: return True elif n % 2 == 0: return False else: for trial_divisor in range(3, int(sqrt(n)) + 1, 2): if n % trial_divisor == 0: return False return True def relatively_prime(a, b): prime_factors_a = prime_factors(a) prime_factors_b = prime_factors(b) return set(prime_factors_a).isdisjoint(set(prime_factors_b)) def sieve(n): # Help from here: # https://stackoverflow.com/questions/49936222/an-efficient-sieve-of-eratosthenes-in-python flags = np.ones(n, dtype=bool) flags[0] = flags[1] = False for i in range(2, int(sqrt(n)) + 1): if flags[i]: flags[i*i::i] = False return np.flatnonzero(flags)
true
5f62927b10ebf68540e71465cf74de9e2844155a
Python
silky/bell-ppls
/env/lib/python2.7/site-packages/observations/r/cps_85.py
UTF-8
2,278
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def cps_85(path): """Data from the 1985 Current Population Survey (CPS85) The Current Population Survey (CPS) is used to supplement census information between census years. These data consist of a random sample of persons from the CPS85, with information on wages and other characteristics of the workers, including sex, number of years of education, years of work experience, occupational status, region of residence and union membership. A data frame with 534 observations on the following variables. - `wage` wage (US dollars per hour) - `educ` number of years of education - `race` a factor with levels `NW` (nonwhite) or `W` (white) - `sex` a factor with levels `F` `M` - `hispanic` a factor with levels `Hisp` `NH` - `south` a factor with levels `NS` `S` - `married` a factor with levels `Married` `Single` - `exper` number of years of work experience (inferred from `age` and `educ`) - `union` a factor with levels `Not` `Union` - `age` age in years - `sector` a factor with levels `clerical` `const` `manag` `manuf` `other` `prof` `sales` `service` Data are from http://lib.stat.cmu.edu/DASL. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `cps_85.csv`. Returns: Tuple of np.ndarray `x_train` with 534 rows and 11 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'cps_85.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/mosaicData/CPS85.csv' maybe_download_and_extract(path, url, save_file_name='cps_85.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
true
2f7e99d39aea40ebaecbc15c8740a7ceb884ccdd
Python
cmobrien123/Python-for-Everybody-Courses-1-through-4
/Ch8Asnt8.5.py
UTF-8
1,120
3.9375
4
[]
no_license
# Exercise 8.5: Write a program to read through the mail box data and when you # find the line that starts with "From", you will split the line into words # using the split function. We are interested in who sent the message, which is # second word on the From line. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line and print out the second word for each From line, # then you will also count the number of From (not From:) lines and print out a # count at the end. # This is a good sample output with a few lines removed: # python fromcount.py # Enter a file name: mbox-short.txt # stephen.marquard@uct.ac.za # louis@media.berkeley.edu # zqian@umich.edu # [... some output removed...] # ray@media.berkeley.edu # cwen@iupui.edu # cwen@iupui.edu # cwen@iupui.edu # There were 27 lines in the file with From as the first word # fname = input('Add mbox-short.txt: ') # fname = 'mbox-short.txt' fh = open(fname) # print(fh) count = 0 for line in fh: line= line.rstrip() if not line.startswith('From:'): continue words= line.split() email=words[1] print(email) count = count + 1 # print('There were', count, 'lines in the file with From as the first word')
true
fead1309187f3a507941fceee14b9ec1d7520659
Python
Dexels/app-tools
/apptools/image/core/scale.py
UTF-8
396
2.578125
3
[]
no_license
from apptools.image.core.json import json_get class Scale(object): def __init__(self, multiplier, directory): self.multiplier = multiplier self.directory = directory @classmethod def load_from_json(cls, json): multiplier = float(json_get('multiplier', json)) directory = json_get('directory', json, False) return cls(multiplier, directory)
true
c6b215d145fdc672643837f098aa2faba1c45093
Python
luizapozzobon/myo_project
/refactored_raw.py
UTF-8
5,557
2.625
3
[ "MIT" ]
permissive
from myo_raw import * import pygame import pandas as pd import datetime from copy import copy from time import sleep, time DEBUG = False class MyoRawHandler: def __init__(self, tty=None): self.m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None) self.create_connection() self.emg = [] self.gyro = [] self.acc = [] self.quat = [] def create_connection(self): self.m.add_emg_handler(self.proc_emg) self.m.add_imu_handler(self.proc_imu) self.m.connect() #self.m.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) #self.m.add_pose_handler(lambda p: print('pose', p)) def test_hz(self, samples=100): start = time.time() for i in range(samples): self.m.run(1) elapsed_time = time.time() - start print("Elapsed time: {} | {} samples".format(elapsed_time, samples)) def proc_emg(self, emg, moving, times=[]): if DEBUG: print("Current EMG: ", emg) self.emg = emg def proc_imu(self, quat, acc, gyro): if DEBUG: print("IMU data: ", quat, acc, gyro) self.gyro = gyro self.acc = acc self.quat = quat def get_data(self): """ run calls recv_packet function from BT class -> recv_packet function: receives byte message from serial (which is myo's dongle) the message is treated by BT's function proc_byte -> proc_byte function: add first few bytes to buffer to calculate the packet length then, reads message of calculated package length and deletes the buffer returns a Packet class the returned packet has a 'typ' section, which has to be equal to 0x80 if that conditions is true, the packet is sent to handle_event function -> handle_event function: """ self.m.run(1000) return {'emg': self.emg, 'gyro': self.gyro, 'orientation': self.quat} def capture_movement(self, label, captures=400, description=""): self.tag = "myo" self.width = 200 self.height = 200 self.screen = pygame.display.set_mode((self.width, self.height)) self.all_data = pd.DataFrame(columns=["Sensor 0", "Sensor 1", "Sensor 2", "Sensor 3", "Sensor 4", "Sensor 5", "Sensor 6", "Sensor 7", "Gyro 0", "Gyro 1", "Gyro 2", "Orientation 0", "Orientation 1", "Orientation 2", "Orientation 3"]) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: self.all_data.to_csv("datasets/" + self.tag + '-' + description + "-" + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + "-" + ".csv") sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_KP_ENTER: print("----- Started movement capture -----") emg_data = self.get_data()["emg"] while(len(emg_data) != 8): emg_data = self.get_data()["emg"] if len(emg_data) >= 8: break batch_df = pd.DataFrame(columns=["Timestamp", "Label", "Sensor 0", "Sensor 1", "Sensor 2", "Sensor 3", "Sensor 4", "Sensor 5", "Sensor 6", "Sensor 7", "Gyro 0", "Gyro 1", "Gyro 2", "Orientation 0", "Orientation 1", "Orientation 2", "Orientation 3"]) start_time = time() reading_time = time() for i in range(captures): #while reading_time-start_time < 1: reading_time = time() batch_data = self.get_data() emg = [e for e in batch_data["emg"]] gyro = [g for g in batch_data["gyro"]] #acc = [a for a in batch_data["acc"]] orient = [o for o in batch_data["orientation"]] all_data = emg + gyro + orient #print(len(all_data)) #print(all_data) try: batch_df = batch_df.append({"Timestamp": reading_time-start_time, 'Label': label, 'Sensor 0': all_data[0], 'Sensor 1': all_data[1], 'Sensor 2': all_data[2], 'Sensor 3': all_data[3], 'Sensor 4': all_data[4],'Sensor 5': all_data[5],'Sensor 6': all_data[6],'Sensor 7': all_data[7], 'Gyro 0': all_data[8], 'Gyro 1': all_data[9], 'Gyro 2': all_data[10], 'Orientation 0': all_data[11], 'Orientation 1': all_data[12], 'Orientation 2': all_data[13], 'Orientation 3': all_data[14]}, ignore_index=True) except: pass print(batch_df.shape) self.all_data = self.all_data.append(batch_df) print("All data: ", self.all_data) print("----- End of movement capture -----") if event.key == pygame.K_c: del self.all_data self.tag = raw_input("Digite o novo tag do movimento") def get_loop(): while True: teste = myo.get_data() #print("Teste: ", teste) myo = MyoRawHandler() #myo.test_hz() myo.capture_movement(label=0, captures=500, description="movimento-ricardo-ruim") #get_loop()
true
7ed042a68bf8407b7bcf88dde7f00a5133cd6878
Python
Hibiscusofxp/wxz-card-bot
/bot.py
UTF-8
18,182
2.5625
3
[]
no_license
# -*- coding: utf-8 -*- import random import datetime import json import os import itertools, math import stats import collections random.seed() """ Bot implementation. Should be reloadable """ leaderboard = {} accept_challenge = 0 offer_challenge = 0 in_challenge = False def checkDir(fn): dn = os.path.dirname(fn) if not os.path.isdir(dn): os.makedirs(dn) return fn class Bot(object): def __init__(self, socket): self.socket = socket self.gameId = None self.opponentId = None self.game = None self.logger = None pass def handleMessage(self, msg): if msg["type"] == "request": if msg["state"]["game_id"] != self.gameId: self.gameId = msg["state"]["game_id"] self.game = Game(msg) if msg['state']['opponent_id'] != self.opponentId: self.opponentId = msg['state']['opponent_id'] print "--- New Opponent %s (%s) ---" % (self.opponentId, stats.PLAYERS[self.opponentId] if self.opponentId in stats.PLAYERS else "unknown") logfn = "strates/%s/%s/%s.log" % (STRATEGY, self.opponentId, datetime.datetime.now().strftime("%Y%m%dT%H%M%S")) logfn = checkDir(logfn) self.logger = open(logfn, "w") response = self.game.handleRequest(msg) self.socket.send(response) elif msg['type'] == "result": pass if self.game: self.game.handleResult(msg) if self.logger: self.logger.write(json.dumps(msg)) self.logger.write("\n") if self.logger and msg['type'] == "request": self.logger.write(json.dumps(response)) self.logger.write("\n") class Deck(list): def __init__(self): self.extend(8 for x in range(0, 14)) self[0] = 0 self.remaining = 104 def removeCard(self, card): if self[card] > 0: self[card] -= 1 self.remaining -= 1 elif card < 13: #Justification: Guesses the lowest possible self.removeCard(card + 1) def getLowestRemaining(self): """ Return the lowest card that is still available in the entire deck """ for n in range(1, 14): if self[n] > 0: return n class Game(object): def __init__(self, msg): self.gameId = msg['state']['game_id'] self.opponentId = msg['state']['opponent_id'] self.playerNumber = msg['state']['player_number'] self.handId = None self.hand = None self.hands = [] self.cards = [] #Not used (yet) self.other_cards = [] #Not used (yet) self.deck = Deck() self.bad_ass = 0 self.counter = None print("New game started: " + str(self.gameId) + " with " + str(self.opponentId)) bad_ass_players = set([25, 41, 9, 17, 42, 31]) if self.playerNumber in bad_ass_players: # self.bad_ass = 1 pass #print msg def handleRequest(self, msg): global in_challenge in_challenge = msg['state']['in_challenge'] if msg["state"]['hand_id'] != self.handId or not self.hand: if self.hand: self.hands.append(self.hand) #@consider Should we also do estimate for op based on min? for card in self.hand.cards: self.deck.removeCard(card) if len(self.hands) % 10 == 0: self.deck = Deck() self.handId = msg['state']['hand_id'] self.hand = Hand(msg, self) return self.hand.handleRequest(msg) def handleResult(self, msg): global leaderboard global accept_challenge global offer_challenge global in_challenge if not self.opponentId in leaderboard: leaderboard[self.opponentId] = { "won": 0, "lost": 0, "handwon": 0, "handlost": 0, "handwonA": 0, "handlostA": 0, "handwonO": 0, "handlostO": 0, "oliver_accept": 0, "ppp_accept": 0, "lost_cause": collections.Counter(), "won_cause": collections.Counter(), } obj = leaderboard[self.opponentId] self.counter = obj if msg['result']['type'] == "game_won": if msg['result']['by'] == self.playerNumber: obj['won'] += 1 print " Won Game %s" % (float(obj['won']) / float(obj['won'] + obj['lost']) * 100 ,) if not in_challenge: obj['won_cause']['overflow'] += 1 elif offer_challenge: obj['won_cause']['offer'] += 1 else: obj['won_cause']['accept'] += 1 else: obj['lost'] += 1 print " Lost Game %s" % (float(obj['won']) / float(obj['won'] + obj['lost']) * 100 ,) if not in_challenge: obj['lost_cause']['overflow'] += 1 elif offer_challenge: obj['lost_cause']['offer'] += 1 else: obj['lost_cause']['accept'] += 1 elif msg['result']['type'] == "hand_done": if 'by' in msg['result']: if msg['result']['by'] == self.playerNumber: obj['handwon'] += 1 else: obj['handlost'] += 1 if accept_challenge == 1 and in_challenge: print "accept" if 'by' in msg['result']: if msg['result']['by'] == self.playerNumber: obj['handwonA'] += 1 print " Won Hand %s" % (float(obj['handwonA']) / float(obj['handwonA'] + obj['handlostA']) * 100 ,) else: obj['handlostA'] += 1 print " Lost Hand %s" % (float(obj['handwonA']) / float(obj['handwonA'] + obj['handlostA']) * 100 ,) elif offer_challenge == 1 and in_challenge: print "offer" if 'by' in msg['result']: if msg['result']['by'] == self.playerNumber: obj['handwonO'] += 1 print " Won Hand %s" % (float(obj['handwonO']) / float(obj['handwonO'] + obj['handlostO']) * 100 ,) else: obj['handlostO'] += 1 print " Lost Hand %s" % (float(obj['handwonO']) / float(obj['handwonO'] + obj['handlostO']) * 100 ,) if self.hand: self.hand.handleResult(msg) def useMyCard(self, card): pass def estimateOpponentCard(self, card): self.deck.removeCard(card) def response(msg, **response): return {"type": "move", "request_id": msg['request_id'], "response": dict(response)} class Hand(object): def __init__(self, msg, parent): self.cards = msg['state']['hand'] self.cardAvg = float(sum(self.cards)) / 5.0 if len(self.cards) == 5: self.cardMedian = self.cards[2] for card in self.cards: parent.deck.removeCard(card) self.spent_cards = [] self.parent = parent self.other_cards = [] self.lastCard = None pass def getWinpercen(self, my_cards_in, his_cards_in, my_tricks_in, his_tricks_in, this_winnum, this_tienum): my_tricks = my_tricks_in his_tricks = his_tricks_in for idx, ele in enumerate(my_cards_in, start = 0): numWin = 0 numTie = 0 my_cards = list(my_cards_in) my_cards.remove(ele) for hisele in his_cards_in: my_tricks1 = int(my_tricks) his_tricks1 = int(his_tricks) if ele > hisele: my_tricks1 = my_tricks1 + 1 elif ele < hisele: his_tricks1 = his_tricks1 + 1 his_cards1 = list(his_cards_in) his_cards1.remove(hisele) for his_cards_per in itertools.permutations(his_cards1): # print ele , my_cards , " VS " , hisele , his_cards_per my_tricks2 = int(my_tricks1) his_tricks2 = int(his_tricks1) for idx1 in range(0, len(my_cards)): if my_cards[idx1] > his_cards_per[idx1]: my_tricks2 += 1 elif my_cards[idx1] < his_cards_per[idx1]: his_tricks2 += 1 # print my_tricks2, his_tricks2 if (my_tricks2 > his_tricks2): numWin += 1 elif (my_tricks2 == his_tricks2): numTie += 1 this_winnum[idx] += numWin this_tienum[idx] += numTie def getBestCardAndPercen(self, level, my_cards, my_winnum, my_tienum, totalNum, his_cards, deck, my_tricks, his_tricks): if level == len(my_cards): self.getWinpercen(my_cards, his_cards, my_tricks, his_tricks, my_winnum, my_tienum) totalNum[0] += math.factorial(len(my_cards)) # for idx, ele in enumerate(this_winpercen): # my_winpercen[idx] += ele # for idx, ele in enumerate(this_tiepercen): # my_tiepercen[idx] += ele else: if level == 0: pickCard = 1 else: pickCard = his_cards[level - 1] while (pickCard <= 13 and deck[pickCard] == 0): pickCard += 1 while (pickCard <= 13): his_cards[level] = pickCard deck[pickCard] -= 1 self.getBestCardAndPercen(level + 1, my_cards, my_winnum, my_tienum, totalNum, his_cards, deck, my_tricks, his_tricks) deck[pickCard] += 1 pickCard += 1 while (pickCard <= 13 and deck[pickCard] == 0): pickCard += 1 def getCardPosInDeck(self, ele, deck): total = 0 tienum = 0 winnum = 0 for card, num in enumerate(deck): total += num if card < ele: winnum += num elif card == ele: tienum += num return { 'win': float(winnum) / total, 'tie': float(tienum) / total, 'lose': float(total - winnum - tienum) / total } def getBestPer(self, my_cards, deck, my_tricks, his_tricks): winex = float(my_tricks) for ele in my_cards: percens = self.getCardPosInDeck(ele, deck) winex += percens['win'] + percens['tie'] / 2.0 return winex # value is 0 to 5 # my_winnum = [] # my_tienum = [] # his_cards = [] # totalNum = [0] # for idx in range(0, len(my_cards)): # my_winnum.append(0) # my_tienum.append(0) # his_cards.append(0) # self.getBestCardAndPercen(0, my_cards, my_winnum, my_tienum, totalNum, his_cards, deck, my_tricks, his_tricks) # return ( float(my_winnum[0]) + float(my_tienum[0]) / 2 ) / totalNum[0] def challengeOfferStrat(self, msg): my_tricks = msg['state']['your_tricks'] his_tricks = msg['state']['their_tricks'] left_tricks = 5 - msg['state']['total_tricks'] my_points = msg['state']['your_points'] his_points = msg['state']['their_points'] x = my_tricks - his_tricks extfact = my_points - his_points if his_points == 9: return 1 if his_points >7 and my_points < 4: return 1 avg = float(sum(self.cards) / len(self.cards)) if my_tricks == 1 and his_tricks == 2: if avg > 10.5: return 1 else: return 0 if self.parent.bad_ass == 1: thres1 = 0.1 thres2 = 1.5 else: thres1 = 0.5 thres2 = 3.5 if x == -2: return 0 if 0.5*(avg-7)/6.0 - 0.3*extfact/10.0 + 0.2*his_points/10.0 > thres1: return 1 if self.getBestPer(self.cards, self.parent.deck, my_tricks, his_tricks) > thres2: # if 0.45*(avg-7)/6.0 - 0.3*extfact/10.0 - 0.05*x/5.0 + 0.2*his_points/10.0 > 0.3: return 1 if x - left_tricks >= 0: #always right return 1 return 0 def challengeReceiveStrat(self, msg): my_tricks = msg['state']['your_tricks'] his_tricks = msg['state']['their_tricks'] left_tricks = 5 - msg['state']['total_tricks'] my_points = msg['state']['your_points'] his_points = msg['state']['their_points'] x = my_tricks - his_tricks extfact = my_points - his_points avg = 0 if his_points == 9: return 1 if -x - left_tricks > 0: #always right return 0 if x - left_tricks > 0: #always right return 1 if len(self.cards) > 0: avg = float(sum(self.cards) / len(self.cards)) else: avg = float(self.spent_cards[len(self.spent_cards) - 1]) if x == 2: return 0 if my_tricks == 1 and his_tricks == 2: if avg > 10: return 1 else: return 0 if self.parent.bad_ass == 1: thres1 = 0.8 thres2 = 5 else: thres1 = 0.5 thres2 = 3 uncertainty = 0.025*left_tricks/5.0 + 0.05*x/3.0 + 0.25*extfact/10.0 + 0.5*(avg-7) /3.0 + 0.05*his_points/9.0 + 0.125*len(self.cards)/5.0 if uncertainty > thres1: print "****Oliver Accept" if (self.parent.counter): self.parent.counter['oliver_accept'] += 1 return 1 if self.getBestPer(self.cards, self.parent.deck, my_tricks, his_tricks) > thres2: print "****PPPPPP Accept" if (self.parent.counter): self.parent.counter['ppp_accept'] += 1 return 1 # if extfact < -2: # return 1 # if x - left_tricks < 0: # return 0 return 0 def handleRequest(self, msg): global accept_challenge global offer_challenge if msg["request"] == "request_card": #@todo Remove for performance if msg['state']['can_challenge']: if self.challengeOfferStrat(msg) == 1: offer_challenge = 1 return response(msg, type="offer_challenge") else: offer_challenge = 0 if len(self.cards) > len(msg['state']['hand']): self.cards = msg['state']['hand'] # if sorted(self.cards) != sorted(msg['state']['hand']): # print "**** Warning: Mismatched hands %s != %s ****" % (repr(self.cards), msg['state']['hand']) # self.cards = msg['state']['hand'] cardToPlay = self.getCardToPlay(msg) self.cards.remove(cardToPlay) self.spent_cards.append(cardToPlay) self.lastCard = cardToPlay self.parent.useMyCard(cardToPlay) return response(msg, type="play_card", card=cardToPlay) elif msg["request"] == "challenge_offered": # if self.cardAvg > 6 and self.cardMedian > 6: # return response(msg, type="accept_challenge") if self.challengeReceiveStrat(msg) == 1: accept_challenge = 1 return response(msg, type="accept_challenge") else: accept_challenge = 0 return response(msg, type="reject_challenge") def getCardToPlay(self, msg): if len(self.cards) == 5: #5 cards, don't know anything? Give low 66% card return self.cards[2] elif len(self.cards) == 4: if msg['state']['their_tricks'] == 0: #Won last card, their cards are small. return self.cards[2] if len(self.cards) - (msg['state']['their_tricks'] - msg['state']['your_tricks']) > 1: cardsCount = 0 for i in range(1, min(self.cards) + 1): cardsCount += self.parent.deck[i] if float(cardsCount) / float(self.parent.deck.remaining) < 0.1: return min(self.cards) # return max(self.cards) value = 0 count = 0 for i in range(1, 13 + 1): value += i * self.parent.deck[i] count += self.parent.deck[i] avg = value / count + 1 while (avg <=13 and avg not in self.cards): avg += 1 if avg > 13: avg = min(self.cards) return avg def handleResult(self, msg): if msg['result']['type'] == "trick_tied": self.other_cards.append(self.lastCard) self.parent.estimateOpponentCard(self.lastCard) elif msg['result']['type'] == "trick_won": if msg['result']['card'] != self.lastCard: self.other_cards.append(msg['result']['card']) self.parent.estimateOpponentCard(msg['result']['card']) elif msg['result']['by'] == msg['your_player_num']: #ooops, don't know what their card is. Estimate lowest lowestEstimate = self.parent.deck.getLowestRemaining() #self.other_cards.append(lowestEstimate) self.parent.estimateOpponentCard(lowestEstimate) else: #They won?! Should be my card + 1 #self.other_cards.append(self.lastCard + 1) self.parent.estimateOpponentCard(self.lastCard + 1) STRATEGY = "rand-challenge"
true
825dca0ba445a58e59d2c1473b732b8b4b68d149
Python
mksingh8/google_Search_Automation_Framwork_Python
/testCases/test_google_search.py
UTF-8
842
2.75
3
[]
no_license
from pageObjects.searchPage import SearchPage from utilities.logGeneration import LogGen from utilities.readConfig import ReadConfig class Test_001_Google_Search: logger = LogGen.log() url = ReadConfig.get_application_url() def test_google_search_method(self, setup): self.logger.info("*** test_google_search_method ***") self.driver = setup self.driver.get(self.url) self.logger.info("Invoking browser") self.logger.info("Initializing the search page object") self.sp = SearchPage(self.driver) self.sp.set_text_to_search("red wine") if 'Search' in self.driver.title: self.logger.info("Title matched") assert True else: self.logger.error("title did not match") assert False self.driver.close()
true
b95523aeb3d0244c7548c0aaade9400b939f63dc
Python
husanpy/Programming-in-python-Coursera-MIPT
/1 Diving in python/Homework/2 Data structures and functions/key_value_storage.py
UTF-8
740
2.65625
3
[ "MIT" ]
permissive
import os import tempfile import argparse import json # command line arguments parser parser = argparse.ArgumentParser() parser.add_argument('--key') parser.add_argument('--val') args = parser.parse_args() storage_path = os.path.join(tempfile.gettempdir(), 'storage.data') # storage_path = 'storage.data' if os.path.isfile(storage_path): with open(storage_path, 'r') as f: data = json.load(f) if args.val: if args.key in data: data[args.key].append(args.val) else: data[args.key] = [args.val] with open(storage_path, 'w') as f: json.dump(data, f) else: if args.key in data: values = ', '.join(data[args.key]) print(values) else: print(None) else: with open(storage_path, 'w') as f: json.dump({}, f)
true
1d6e3d41cadd52cecf6ed30798b3ab5a9fa83cf1
Python
alirezahi/DataMining
/Codes/p4-f.py
UTF-8
454
2.5625
3
[]
no_license
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import csv x = [ [], [], [], [], ] r = [] with open('iris.data','r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: if len(row): for i in range(4): x[i].append(float(row[i])) a = np.array(x[i]) corr = np.corrcoef(x[0],x[1]) print("corr coef is ==> \n" + str(corr)+"\n\n")
true
6a12ae933e63d510f3b57f38c5d3f18131c0d74e
Python
kordejong/my_devenv
/script/build_target.py
UTF-8
1,605
2.65625
3
[]
no_license
#!/usr/bin/env python_wrapper """ Build target. Usage: build_target.py [--build_type=<bt>] (--object | --project | --test) <name> build_target.py -h | --help Options: -h --help Show this screen. --build_type=<bt> Build type. --object Build object. --project Build project. --test Run unit test. name Name of target. """ import os import sys import docopt sys.path.append(os.path.join(os.path.dirname(__file__), "..", "source")) import devenv @devenv.checked_call def build_object( source_pathname, build_type): devenv.build_object(source_pathname, build_type) @devenv.checked_call def build_project( directory_pathname, build_type): devenv.build_objects(directory_pathname, build_type) @devenv.checked_call def run_unit_test( directory_pathname, build_type): devenv.build_objects(directory_pathname, build_type) devenv.run_unit_tests(directory_pathname, build_type) if __name__ == "__main__": arguments = docopt.docopt(__doc__) name = arguments["<name>"] build_type = \ arguments["--build_type"] if \ arguments["--build_type"] is not None else \ os.environ["MY_DEVENV_BUILD_TYPE"] if \ "MY_DEVENV_BUILD_TYPE" in os.environ else \ "Debug" if arguments["--object"]: result = build_object(name, build_type) elif arguments["--project"]: result = build_project(name, build_type) elif arguments["--test"]: result = run_unit_test(name, build_type) sys.exit(result)
true
b2bcfd36943494411442c7a894e582872104bd95
Python
ra536/network
/stopo.py
UTF-8
625
2.734375
3
[]
no_license
""" How to run: $ sudo mn --custom ~/path/to/python/file --topo stopo """ from mininet.topo import Topo class STopo( Topo ): "Simple topology example." def createSwitchWithHosts ( self, name ): newSwitch = self.addSwitch( 's%s' % (name,) ) for i in range(1,4): newHost = self.addHost( 'h%s_%d' % (name, i) ) self.addLink( newHost, newSwitch ) return newSwitch def __init__( self ): "Create custom topo." # Initialize topology Topo.__init__( self ) # Add remote access switches d1 = self.createSwitchWithHosts( 'D1' ) topos = { 'stopo': ( lambda: STopo() ) }
true
96b95b29fdbc3569b09b013fd2c0bb9e6297ea5c
Python
bramyarao/2D-POISSON-PYTHON
/2D POISSON PYTHON/_2D_POISSON_PYTHON.py
UTF-8
6,518
2.8125
3
[]
no_license
#========================================================= # NUMERICAL ANALYSIS: USING MESHFREE METHOD # USING THE REPRODUCING KERNEL COLLOCATION METHOD TO SOLVE # THE 2D POISSONS PROBLEM #========================================================= import numpy as np import matplotlib.pyplot as plt from matplotlib import interactive import math # Files import forming_NS_NC import forming_A import ShapeFunction #------------------------- #INPUT PARAMETERS #------------------------- showPlot = True #Plotting is done if true printStatements = True #Printing is done if true #Domain xdim1 = 0.0 xdim2 = 1.0 ydim1 = 0.0 ydim2 = 1.0 num_pts = np.array([10,10,40,40], float) #num_pts = np.array([5,5,5,5], float) #print(num_pts.dtype) # No. of Source points in the each direction NS_x = num_pts[0] # No. of Source points in the x-direction NS_y = num_pts[1] # No. of Source points in the y-direction # No. of Collocation points in the each direction CP_x = num_pts[2] #No. of Collocation points in the x-direction CP_y = num_pts[3] #No. of Collocation points in the y-direction #------------------------- # SOURCE POINTS #------------------------- NS = forming_NS_NC.forming_SourcePts(xdim1, xdim2, ydim1, ydim2, NS_x, NS_y) #------------------------- # COLLOCATION POINTS #------------------------- NC, NI_c, NEB = forming_NS_NC.forming_CollocationPts(xdim1, xdim2, ydim1, ydim2, CP_x, CP_y) #----------------------------------------------------------------------- # ----------------------------POISSONS---------------------------------- #----------------------------------------------------------------------- basis = 2 # Code only works for quadratic basis # No. of source points and total number of collocation points no_NS = NS.shape[0] # Getting the number of rows in NS no_NC = NC.shape[0] no_NEB = NEB.shape[0] h = 1/(math.sqrt(no_NS)-1); ss = (basis+1)*h # Support size for the RK SF sq_alphag = no_NS # Weight for the essential boundary sq_alphah = 1.0 # Weight for the natural boundary #------------------------------------------------------------------------- # Solving the differntial equation # the A matriz will be of size no_NC x no_NS since u(x,y) is a scalar #------------------------- # Forming A matrix #------------------------- A1 = forming_A.part_of_NI(NC, NS, ss) A2 = forming_A.part_of_NEB(NEB,NS,ss,sq_alphag) A = np.concatenate((A1,A2)) #------------------------- # Forming b vector #------------------------- b = np.zeros((no_NC+no_NEB,1)) no_int = NC.shape[0] int_1 = 0 # INTERIOR force term for int_2 in range(no_int): xtemp = NC[int_2,0] ytemp = NC[int_2,1] b[int_1] = b[int_1] + (xtemp**2 + ytemp**2)*math.exp(xtemp*ytemp) int_1 += 1 # int_1 is getting incremented # EB force terms for int_2 in range(NEB.shape[0]): xtemp = NEB[int_2,0] ytemp = NEB[int_2,1] b[int_1] = b[int_1] + sq_alphag*math.exp(xtemp*ytemp) int_1 += 1 #------------------------- # Solving the system #------------------------ AT = np.transpose(A) Afinal = np.matmul(AT,A) bfinal = np.matmul(AT,b) a = np.linalg.solve(Afinal,bfinal) # Least squares solution ,rcond=None #----------------------------------------------------------------------- # Comparing Solutions Along the Diagonal through (0,0) & (1,1) #----------------------------------------------------------------------- x_con = np.linspace(xdim1,xdim2,20) y_con = np.linspace(ydim1,ydim2,20) u_con = np.zeros((len(x_con),1)) u_exact_con = np.zeros((len(x_con),1)) for int1 in range(len(x_con)): x = x_con[int1] y = y_con[int1] P = ShapeFunction.required_nodes(x,y,NS,ss) SI = ShapeFunction.SF_2D(x,y,NS,P,ss) # for getting uh value of u_approx at each of the points (x,y) u_con[int1,0] = np.matmul(SI,a) # Finding u_exact at the point (x,y) u_exact_con[int1,0] = math.exp(x*y) # Diagonal length DL = np.zeros((len(x_con),1)) for int6 in range(len(x_con)): DL[int6,0] = math.sqrt((x_con[int6])**2 + (y_con[int6])**2) #----------------------------------------------------------------------- # Plotting the numerical solution #----------------------------------------------------------------------- uScatter = np.zeros((NC.shape[0],1)) uScatter_exact = np.zeros((NC.shape[0],1)) for int1 in range(NC.shape[0]): x = NC[int1,0] y = NC[int1,1] P = ShapeFunction.required_nodes(x,y,NS,ss) SI = ShapeFunction.SF_2D(x,y,NS,P,ss) # for getting uh value of u_approx at each of the points (x,y) uScatter[int1,0] = np.matmul(SI,a) # Finding u_exact at the point (x,y) uScatter_exact[int1,0] = math.exp(x*y) #------------------------- # PRINTING #------------------------- if (printStatements == True): print('Source points %d' %NS.shape[0]) print('Collocation points %d' %NC.shape[0]) print('Interior collocation points %d' %NI_c.shape[0]) print('EB collocation points %d' %NEB.shape[0]) #------------------------- #PLOTTING #------------------------- if showPlot == True: plt.figure(1) plt.scatter(NS[:,0], NS[:,1], c="r", marker="o") plt.xlabel("x") plt.ylabel("y") plt.axis('equal') plt.title("Source Points") interactive(True) plt.show() plt.figure(2) plt.scatter(NI_c[:,0], NI_c[:,1], c="b", marker="o", label='Interior') plt.scatter(NEB[:,0], NEB[:,1], c="k", marker="o", label='Essential boundary') plt.xlabel("x") plt.ylabel("y") plt.axis('equal') plt.title("Collocation Points") plt.legend() plt.show() plt.figure(3) plt.plot(DL, u_con, 'ko', label='RKCM') plt.plot(DL, u_exact_con, 'k--', label='Analytical') plt.xlabel("Diagonal length") plt.ylabel("u(x,y)") plt.xlim(0.0,1.5) plt.ylim(0.9,3.0) plt.legend() plt.show() plt.figure(4) fig4=plt.scatter(NC[:,0], NC[:,1], c=uScatter[:,0],cmap='hsv') plt.colorbar(fig4) plt.xlabel("x") plt.ylabel("y") plt.title("u(x,y) Numerical (RKCM)") plt.show() plt.figure(5) fig5=plt.scatter(NC[:,0], NC[:,1], c=uScatter_exact[:,0],cmap='hsv') plt.colorbar(fig5) plt.xlabel("x") plt.ylabel("y") plt.title("u(x,y) Analytical (Exact)") interactive(False) plt.show() # For Saving: plt.savefig('ScatterPlot.png') # To show all figures at a time: # - only first and last figures use interactive, middle ones do not # - also first figure should have interactive(True) # - and last one should have interactive(False)
true
0d144acf38f5b86ad6561eeb200594a985f5f3d2
Python
ajchristie/matasano-challenges
/set1.py
UTF-8
5,719
3.234375
3
[]
no_license
#!/usr/bin/env python2 from collections import Counter # for challenge 1: convert hex to base64 def hexToB64(h): return h.decode('hex').encode('base64') # for challenge 2: return XOR of two fixed length strings def fXOR(s1, s2): if len(s1) != len(s2): print 'Give me equal length buffers!' return None b1 = int(s1, 16) b2 = int(s2, 16) result = b1 ^ b2 return format(result, 'x') # for challenge 3: break a caesar cipher def basicScore(c): # returns proportion of ascii characters in array c (sufficient here) filtered = filter(lambda x: 'a' <= x <= 'z' or 'A' <= x <= 'Z' or x == ' ', c) return float(len(filtered)) / len(c) # N.B. a middle ground between these two would be to score each decryption against occurrences of just ETAOIN SHRDLU, which might help with multiple samples tying for the best freqScore. def freqScore(c): # returns total deviation from english letter frequencies in array c freqs = [('a', 8.167), ('b', 1.492), ('c', 2.782), ('d', 4.253), ('e', 12.702), ('f', 2.228), ('g', 2.015), ('h', 6.094), ('i', 6.966), ('j', 0.153), ('k', 0.772), ('l', 4.025), ('m', 2.406), ('n', 6.749), ('o', 7.507), ('p', 1.929), ('q', 0.095), ('r', 5.987), ('s', 6.327), ('t', 9.056), ('u', 2.758), ('v', 0.978), ('w', 2.36), ('x', 0.15), ('y', 1.974), ('z', 0.074)] filtered = filter(lambda x: 'a' <= x <= 'z' or 'A' <= x <= 'Z', c) l = len(c) filtered = ''.join(filtered).lower() counts = Counter(filtered) delta = 0 for ch in freqs: delta += abs((float(counts[ch[0]]) / l) - ch[1]) return delta # would it be better to normalize this somehow? def deCaesar(s): hex_decoded = s.decode('hex') results = [] for i in xrange(1, 255): xord = [chr(ord(c) ^ i) for c in hex_decoded] results.append([freqScore(xord), ''.join(xord), chr(i)]) results.sort(key=lambda x: x[0], reverse=False) ## do the extra sorting for troubleshooting purposes; can return ranked list instead of just max return results[0] # for challenge 4: detect a Caesared ciphertext def findCaesar(l): results = [] for ct in l: hex_decoded = ct.decode('hex') for i in xrange(1, 255): xord = [chr(ord(c) ^ i) for c in hex_decoded] results.append([freqScore(xord), basicScore(xord), ''.join(xord), chr(i)]) results.sort(key=lambda x: x[0], reverse=False) results.sort(key=lambda x: x[1], reverse=True) # N.B. the basic sort is the better detector for this challenge return results[0] # for challenge 5: Implement Vigenere cipher def vigenere(p, k): # we'll assume everything's coming in ascii for this keylength = len(k) ciphertext = [] for i, letter in enumerate(p): ciphertext.append(chr(ord(letter) ^ ord(k[i % keylength]))) return ''.join(ciphertext).encode('hex') # for exercise 6: Break Vigenere def hammingDistance(b1, b2): return sum(bin(i ^ j).count('1') for i, j in zip(b1, b2)) def makeSegments(a, n): num_segs = len(a) / n segs = [] for i in xrange(0, num_segs*n, n): segs.append(a[i:i+n]) return segs from itertools import combinations def findKeyLength(ctextbytes): min_index = 100 guess = 40 #results = [] for keylength in xrange(2, 41): segs = makeSegments(ctextbytes, keylength) round_min = 100 for ind in combinations(range(len(segs)), r=2): index = float(hammingDistance(segs[ind[0]], segs[ind[1]])) / keylength if index == 0.0: break # too good to be true elif index < round_min: round_min = index else: # accept results only if index stayed positive if round_min <= min_index: min_index = round_min guess = keylength #results.append([keylength, min_index]) # for troubleshooting return guess def breakCaesar(ctbytes): # differs from version above in assuming input is a bytearray results = [] for i in xrange(1, 255): xord = [chr(c ^ i) for c in ctbytes] results.append([freqScore(xord), basicScore(xord), ''.join(xord), chr(i)]) results.sort(key=lambda x: x[0], reverse=False) results.sort(key=lambda x: x[1], reverse=True) return results[0] def breakVig(ctbytes): l = findKeyLength(ctbytes) num_blocks = len(ctbytes) / l pad_length = (l - (len(ctbytes) % l)) % l for _ in xrange(pad_length): ctbytes.append(4) rows = makeSegments(ctbytes, l) columns = zip(*rows) columns = [bytearray(col) for col in columns] shifts = [] decryption = [] for col in columns: _, _, dec, shift = breakCaesar(col) decryption.append(dec) # string shifts.append(shift) key = ''.join(shifts) rows = zip(*decryption) ptext = ''.join([''.join(row) for row in rows]) return key, ptext[:len(ctbytes)] def loadCT(): with open('6.txt', 'r') as f: data = f.readlines() data = [line.strip() for line in data] ctext = ''.join(data) dctext = ctext.decode('base64') return bytearray(dctext) # for challenge 7: AES-ECB from Crypto.Cipher import AES def AES128ECB(ctext): ciphertext = ctext.decode('base64') dcrypt = AES.new('YELLOW SUBMARINE', AES.MODE_ECB) print dcrypt.decrypt(ciphertext) # for challenge 8: detect AES-ECB from collections import Counter def catch128ECB(ctexts): results = [] for ctext in ctexts: segs = makeSegments(ctext, 16) ctr = Counter(segs) results.append([ctext, ctr.most_common(1)]) results.sort(key=lambda x: x[1], reverse=True) return results[0]
true
75582afe56bebaa8b16a0b08b64c0a4765e97318
Python
raymonstah/Hacking-Ciphers
/Reverse/reverse.py
UTF-8
354
4.09375
4
[]
no_license
# Reverse Cipher # The first example of Hacking Secret Ciphers # A simple, weak cipher to encrypt a string. # Raymond Ho message = raw_input("Enter your string: ") # Look at this pythonic way.. print message[::-1] # The uglier way translated = '' i = len(message) - 1 while i >= 0: translated = translated + message[i] i -= 1 print(translated)
true
0e4e63c731825edb4c2dcffa3dad8aecef45d96a
Python
Shusovan/Basic-Python-Programming
/Swapping_List.py
UTF-8
350
3.75
4
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[4]: def swapList(): lst=[] size=int(input('Enter the size of array: ')) for i in range(1,size+1): n=int(input('enter the elements: ')) lst.append(n) temp = lst[0] lst[0] = lst[size - 1] lst[size - 1] = temp return lst print(swapList())
true
b20418c1b111d82c673c6f559c31cd990d69b048
Python
MrCodemaker/python_work
/files and exceptions/user_like_proggramming.py
UTF-8
310
3.140625
3
[]
no_license
filename = 'user_reasons_like_programming.txt' prompt = "\nPlease enter, why you like programming?: " prompt += "\nEnter the 'quit' to end the order!" message = "" while message != 'quit': with open(filename, 'w') as file_object: message = input(prompt) file_object.write(print(message))
true
9e76f74807d27235af0edc427c79e6f9db12586d
Python
searcy/ASpaceASnake
/upload-new-subjects.py
UTF-8
1,333
2.734375
3
[ "MIT" ]
permissive
#!/usr/bin/env python import glob, json, datetime # Setting up the log import asnake.logging as logging logname = 'logs/new_subject_upload_' + datetime.datetime.now().strftime('%Y-%m-%d-T-%H-%M') + '.log' logfile = open(logname, 'w') logging.setup_logging(stream=logfile) logger = logging.get_logger('upload-new-subjects') # Bring in the client to work at a very basic level. from asnake.client import ASnakeClient # Create and authorize the client client = ASnakeClient() client.authorize() def upload_json_as_new_subjects(file_dir,batch): '''Actually run the upload. Simply sets up the log, gathers the JSON, and then uploads each. This is a simple post because it's creating new ones and doesn't need any kind of number.''' logger.info("upload_start", batch_name=batch) subjects = glob.glob(file_dir + '/' + '*.json') # globs all the .json objects in the directory where the files are located. for file in subjects: subject = json.load(open(file)) response = client.post('subjects', json=subject).json() response['title'] = subject['title'] logger.info('upload_subject', response=response) logfile.close() batch = input("Name your upload batch: ") subject_location = input("The full or relative path to your batch: ") upload_json_as_new_subjects(subject_location,batch)
true
fdef180fc0cef71ad2ed1046547879300026aea4
Python
Jbruslind/ECE44x_Senior_Design
/Computer Science/MircobialAnalysisTool/colonyCounter.py
UTF-8
1,885
2.75
3
[ "MIT" ]
permissive
import cv2 import numpy as np; import os font = cv2.FONT_HERSHEY_SIMPLEX text_loc = (20, 40) font_scale = 1 font_color = (255,0,0) line_type = 2 def analyzeImage(imageNumber): #setup colonyCount = 0 # initalizes cwd = os.getcwd() fileName = cwd + "/images/" + str(imageNumber) + ".jpg" #import sample image image = cv2.imread(fileName, cv2.IMREAD_GRAYSCALE) #Setup SimpleBlobDetector parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = 0 params.maxThreshold = 100 # Filter by Area. params.filterByArea = True params.minArea = 1 params.maxArea = 1000 # Filter by Circularity params.filterByCircularity = True params.minCircularity = 0 params.maxCircularity = 1 # Filter by Convexity params.filterByConvexity = True params.minConvexity = 0.1 # Filter by Inertia params.filterByInertia = False params.minInertiaRatio = 0.05 # Create a detector with the parameters detector = cv2.SimpleBlobDetector_create(params) # Detect colonies. identifiers = detector.detect(image) colonyCount = len(identifiers) # place yellow circles around blobs. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im_with_identifiers = cv2.drawKeypoints(image, identifiers, np.array([]), (0,255,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) im_with_count = cv2.putText(im_with_identifiers, str(colonyCount), text_loc, font, font_scale, font_color, line_type) # Show display image with keypoints and count #cv2.imshow("Sample " + str(imageNumber), im_with_count) cv2.imwrite("/home/pi/Documents/deltaImageProcessor/images_with_keys/" + str(imageNumber) + ".jpg", im_with_count) #cv2.waitKey(500) return colonyCount
true
48cb8db9158188087c00eaf745faafb3d4d2c929
Python
ailyanlu1/leetcode-4
/Python/001_Two Sum.py
UTF-8
495
2.953125
3
[]
no_license
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ht = dict() for i in range(len(nums)): ht[nums[i]] = i + 1 for i in range(len(nums)): lt = target - nums[i] if ht.get(lt, None) is not None: if ht[lt] == i + 1: continue return [min(i + 1, ht[lt]), max(i + 1, ht[lt])]
true
fd75aa8114e41b366f42738324d7b5b12f6f2aea
Python
rravicha/pdfdrive
/flask-api/engine/forms.py
UTF-8
8,355
3.0625
3
[]
no_license
from math import sqrt, atan2, ceil, degrees from datetime import datetime as dt from copy import deepcopy from flask.logging import default_handler import logging log_f="%(levelname)s %(asctime)s - %(message)s -->%(lineno)d |%(module)s " logging.basicConfig( filename="monitor.txt", level=logging.DEBUG, format=log_f, filemode='a+' ) l=logging.getLogger() l.addHandler(default_handler) class Compute: def __init__(self,req): l.info(f"Request : {req}") self.player =str(req.get('ply')) self.dimensions =[int(i) for i in req.get('dim').split(',')] self.pos =[int(i) for i in req.get ('pp').split(',')] self.guard_pos =[int(i) for i in req.get ('tp').split(',')] self.distance =int(req.get('dist')) self.room_x = self.dimensions[0] self.room_y = self.dimensions[1] self.player_x = self.pos[0] self.player_y = self.pos[1] self.guard_x = self.guard_pos[0] self.guard_y = self.guard_pos[1] self.max_distance = self.distance self.max_x = self.player_x + self.distance + 1 self.max_y = self.player_y + self.distance + 1 self.out=None def validate(self): if not(1<self.room_x<=1250): self.out=f"dimension (x {self.room_x}) of the room should be <= than 1250 " if not(1<self.room_y<=1250): self.out=f"dimension (y {self.room_y}) of the room should be <= than 1250 " if ((self.player_x==self.guard_x) and (self.player_y==self.guard_y)): self.out=f"player and target shouldn't be sharing same position{self.player_x,self.guard_x,self.player_y,self.guard_y}" if (not(0<self.player_x<self.room_x) or not(0<self.player_y<self.room_y)): self.out=f"player is positioned self.outside the room {self.player_x,self.player_y} dim {self.room_x,self.room_y}" if (not(0<self.guard_x<self.room_x) or not(0<self.guard_y<self.room_y)): self.out=f"target is positioned self.outside the room {self.guard_x,self.guard_y} dim {self.room_x,self.room_y}" if not(1<self.max_distance<=10000): self.out=f"distance is limited to range of 1-10000 but received {self.max_distance}" if self.out == None: return True,self.out else: l.critical(f"Validation Error : {self.out}") return False,self.out def get_dist(self, point_x, point_y): """Gets distance between player and a point""" dist = sqrt((point_x - self.player_x) ** 2 + (point_y - self.player_y) ** 2) return dist def get_angle(self, point_x, point_y): """Gets angle between player and a point in RAD""" angle = atan2(point_y - self.player_y, point_x - self.player_x) # print(f"point_x {point_x} point_y {point_x} angle {angle}") return angle def get_first_quadrant(self): """gets the number of copies that need to be done along the axis and gets all the guard and player coords""" num_copies_x = ceil(self.max_x / self.room_x) num_copies_x = int(num_copies_x) num_copies_y = ceil(self.max_y / self.room_y) num_copies_y = int(num_copies_y) player_exp_x = [] player_exp_y = [] guard_exp_x = [] guard_exp_y = [] # Loop expands along the x axis for i in range(0, num_copies_x + 1, 1): temp_player_y_list = [] temp_guard_y_list = [] r_x = self.room_x * i if len(player_exp_x) == 0: n_p_p_x = self.player_x else: n_p_p_x = (r_x - player_exp_x[-1][0]) + r_x player_exp_x.append([n_p_p_x, self.player_y, 1]) if len(guard_exp_x) == 0: n_g_p_x = self.guard_x else: n_g_p_x = (r_x - guard_exp_x[-1][0]) + r_x guard_exp_x.append([n_g_p_x, self.guard_y, 7]) # Loop expands along the x axis for j in range(1, num_copies_y + 1, 1): r_y = self.room_y * j if len(temp_guard_y_list) == 0: n_g_p_y = (r_y - self.guard_y) + r_y temp_guard_y_list.append(n_g_p_y) else: n_g_p_y = (r_y - temp_guard_y_list[-1]) + r_y temp_guard_y_list.append(n_g_p_y) guard_exp_y.append([n_g_p_x, n_g_p_y, 7]) if len(temp_player_y_list) == 0: n_p_p_y = (r_y - self.player_y) + r_y temp_player_y_list.append(n_p_p_y) else: n_p_p_y = (r_y - temp_player_y_list[-1]) + r_y temp_player_y_list.append(n_p_p_y) player_exp_y.append([n_p_p_x, n_p_p_y, 1]) return player_exp_x + guard_exp_x + player_exp_y + guard_exp_y def other_quadrants(self, matrix): """Uses the list from the first quadrant and flips its to the other 3 quadrants""" q2 = deepcopy(matrix) q2t = [-1, 1] q2f = [] for j in range(len(q2)): list = [q2[j][i] * q2t[i] for i in range(2)] dist = self.get_dist(list[0], list[1]) if dist <= self.max_distance: list.append(matrix[j][2]) q2f.append(list) q3 = deepcopy(matrix) q3t = [-1, -1] q3f = [] for j in range(len(q3)): list = [q3[j][i] * q3t[i] for i in range(2)] dist = self.get_dist(list[0], list[1]) if dist <= self.max_distance: list.append(matrix[j][2]) q3f.append(list) q4 = deepcopy(matrix) q4t = [1, -1] q4f = [] for j in range(len(q3)): list = [q4[j][i] * q4t[i] for i in range(2)] dist = self.get_dist(list[0], list[1]) if dist <= self.max_distance: list.append(matrix[j][2]) q4f.append(list) return q2f, q3f, q4f def filter_target_hit(self, matrix): """Uses a dict with angles as key Filters by range and by distance of the same angle (closer always wins)""" target = {} for i in range(len(matrix)): dist = self.get_dist(matrix[i][0], matrix[i][1]) angle = self.get_angle(matrix[i][0], matrix[i][1]) test_a = self.max_distance >= dist > 0 test_b = angle not in target test_c = angle in target and dist < target[angle][1] if test_a and (test_b or test_c): target[(angle)] = [matrix[i], dist] return target @staticmethod def return_count(dict): count = 0 for key in dict: if dict[key][0][2] == 7: count += 1 return count def calculate(self): st=dt.utcnow() try: q1 = self.get_first_quadrant() q2, q3, q4 = self.other_quadrants(q1) final_list = q1 + q2 + q3 + q4 final_dict = self.filter_target_hit(final_list) rads=[] final_angles=[] for key,val in final_dict.items(): if int(val[0][2])==7: if (float(key)) <0: rads.append(float(key)) else: rads.append(float(key)) deg=[degrees(r) for r in rads] for d in deg: if d<0: final_angles.append(abs(d)+float(180)) else: final_angles.append(d) except Exception as e: l.critical(str(e)) return str(e) et=dt.utcnow() tt=str(et-st) resp = { 'player':self.player, 'no_of_direction':len(final_angles), 'angles':final_angles, 'time taken':tt } l.info(f"Response : {resp}") return resp """ Makes a room instance with all the parameters given Generates all possible points in the first quadrant Get all position in all other quadrants Filters the Original player, and all unattainable guards """
true
5378b62b2a24fb21b14a58dcc272580e6365c06c
Python
osu-mlpp/mlpp-playground
/curve_analysis/osu_dump/osu_db.py
UTF-8
1,617
2.890625
3
[ "MIT" ]
permissive
# Go ahead and replace db_names with how you named your dumps. Make sure it's in the same order # Each dump should still start with osu_ ex. osu_random_2019_11_01 from curve_analysis.bin.config import * import mysql.connector from tqdm import tqdm class OsuDB: password = SQL_PASSWORD host = SQL_HOST user = SQL_USER def __init__(self, names=None): self.dbs = [] if names is None: self.names = SQL_DB_NAMES else: self.names = names for db_name in self.names: self.dbs.append(self.connect_db('osu_' + db_name)) def connect_db(self, name): return mysql.connector.connect( host=self.host, user=self.user, passwd=self.password, database=name ) # Creates a 'super' table by combining calls on OsuDB.fetch for all dbs def fetch_all(self, table_name, columns=None): ret = [] print('- Fetching {} from ({}) dumps'.format(columns, len(self.dbs))) for db in tqdm(self.dbs): table = OsuDB.fetch(db, table_name, columns) ret.extend(table) return ret # Takes a subset of columns from a table in db @staticmethod def fetch(db, table_name, columns=None): selection = '* ' if columns is not None: selection = '' for i in range(len(columns)): selection += columns[i] + (', ' if i + 1 != len(columns) else ' ') cur = db.cursor(buffered=True) cur.execute('select ' + selection + 'from ' + table_name) return cur.fetchall()
true
06d9f2f947d972d115f4c2d3740bb445996e5905
Python
joelsmith80/modern-django
/project/races/helpers.py
UTF-8
126
2.515625
3
[ "MIT" ]
permissive
def get_option( key, type = int ): from .models import SiteOption obj = SiteOption() return obj.get_option( key )
true
fb218e2621c3170a07fff6aa39a9274a002d75f6
Python
ducnguyen1911/ReinforcementLearning
/non_deterministic_case.py
UTF-8
6,102
2.640625
3
[]
no_license
import math __author__ = 'duc07' import numpy import random import matplotlib.pyplot as plt GAMMA = 0.9 GOAL_STATE = 6 e = 0.2 # greedy parameter g_numb_same_q = 0 g_prev_q_arr = numpy.zeros((12, 4)) g_cur_q_arr = numpy.zeros((12, 4)) g_dict_action = {0: -4, 1: 4, 2: -1, 3: 1} # 0: up, 1: down, 2: left, 3: right g_q_diff = [] g_numb_visit_arr = numpy.zeros((12, 4)) g_reward_arr = numpy.zeros((12, 4)) g_est_e_arr = numpy.zeros((12, 4)) # Randomly select a state def select_state(): states = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11] return random.choice(states) # Return only legal actions from state s def select_act(s): acts = [] for a, v in g_dict_action.iteritems(): if is_legal(s, a): acts.append(a) randi = random.randint(0, len(acts) - 1) return acts[randi] def select_act_with_e_greedy(s): if random.random() > e: return select_act(s) # random policy else: return get_max_q_index(s) # max Q # Revise this function for non-deterministic case def is_legal(s, a): ns = s + g_dict_action[a] if ns in range(0, 12): if (a in [2, 3] and ns / 4 == s / 4) or (a in [0, 1]): return True return False def get_reward(s, a): return 100 if s + g_dict_action[a] == GOAL_STATE else 0 def get_move_probs(s, a): move_probs = [0, 0, 0, 0] legal_numb = 4 for i in range(0, 4): if not is_legal(s, i): legal_numb -= 1 for i in range(0, 4): if i == a: move_probs[i] = 0.7 elif is_legal(s, i): numb_left = legal_numb - 1 if is_legal(s, a) else legal_numb move_probs[i] = (1 - 0.7) / numb_left return move_probs # [0.7, 0.15, 0.15, 0] def gen_rand_action(move_probs): r = 0 p = -1 while r >= p: x = math.ceil(random.random() * len(move_probs)) - 1 x = int(x) p = move_probs[x] r = random.random() return x def get_next_state(s, a): move_probs = get_move_probs(s, a) actual_a = gen_rand_action(move_probs) return s + g_dict_action[actual_a], actual_a # Return max Q from a given state s. Consider all legal actions from that state def get_max_q(s): return max(g_cur_q_arr[s]) def get_max_q_index(s): if s < 0: return 0 temp_q = [] temp_q[:] = g_cur_q_arr[s] for i in range(0, len(temp_q)): if not is_legal(s, i): temp_q[i] = -99 return numpy.argmax(temp_q) def check_end_condition(): # print g_cur_q_arr # print g_prev_q_arr global g_numb_same_q if (g_prev_q_arr is not None) and (g_prev_q_arr == g_cur_q_arr).all(): g_numb_same_q += 1 else: g_numb_same_q = 0 return True if g_numb_same_q >= 50 else False def calc_alpha(s, a): return round(float(1) / (1 + g_numb_visit_arr[s][a]), 2) def calc_expect_value(): global g_est_e_arr arr = g_reward_arr[:][:] / g_numb_visit_arr[:][:] g_est_e_arr[:][:] = arr for i in (2, 5, 7, 10): print 'Expected value for S', i + 1, ': ', arr[i] def do_episodes(): global g_cur_q_arr global g_reward_arr global g_numb_visit_arr s = select_state() # randomly select a state while s != GOAL_STATE: a = select_act_with_e_greedy(s) # with probability, greedy vs. random g_numb_visit_arr[s][a] += 1 # check this point --------------------------------- ********************** s_next, actual_a = get_next_state(s, a) # check this with stochastic case -------- *** ----------------------- r = get_reward(s, actual_a) g_reward_arr[s][a] += r # update observed reward alpha = calc_alpha(s, a) # g_cur_q_arr[s][a] = r + GAMMA * get_max_q(s_next) # update table entry for Q(s,a) g_cur_q_arr[s][a] = (1 - alpha) * g_prev_q_arr[s][a] g_cur_q_arr[s][a] += alpha * (r + get_max_q(s_next)) g_cur_q_arr[s][a] = round(g_cur_q_arr[s][a], 2) s = s_next def reset_q_arrs(): global g_prev_q_arr global g_cur_q_arr global g_numb_same_q global g_q_diff global g_numb_visit_arr global g_reward_arr g_prev_q_arr = numpy.zeros((12, 4)) g_cur_q_arr = numpy.zeros((12, 4)) g_cur_q_arr += random.random() * 0.0001 g_numb_visit_arr = numpy.zeros((12, 4)) g_reward_arr = numpy.zeros((12, 4)) g_q_diff = [] g_numb_same_q = 0 def Q_learning(): reset_q_arrs() global g_prev_q_arr i = 0 while not check_end_condition(): i += 1 print 'iter: ', i q_diff = numpy.sum(numpy.abs(g_cur_q_arr[:][:] - g_prev_q_arr[:][:])) g_q_diff.append(q_diff) g_prev_q_arr[:][:] = g_cur_q_arr do_episodes() calc_expect_value() # ====================================== is it right to call it here???? ===================== def plot_q_diff(): plt.plot(g_q_diff) plt.ylabel('Q diff') plt.show() def run(et): print 'e = ', et global e e = et Q_learning() g_cur_q_arr[g_cur_q_arr < 0.5] = -99 print 'g_cur_q_arr: ', numpy.around(g_cur_q_arr, 3) print 'g_q_diff: ', g_q_diff plot_q_diff() # Calculate Probability * maxQ def calc_pm(s, a): move_probs = get_move_probs(s, a) # ==================== ???? not quite sure here ===================== max_q = [get_max_q(s + g_dict_action[ta]) if is_legal(s, ta) else 0 for ta in (0, 1, 2, 3)] return numpy.sum(numpy.array(move_probs) * numpy.array(max_q)) def validate_condition(): # print Q table for S3, S6, S8, S11 for s in (2, 5, 7, 10): print 'Q(s, a) for S', s + 1, ': ', g_cur_q_arr[s][:] # print right side of the formula in problem 6 p_arr = numpy.zeros((12, 4)) for s in (2, 5, 7, 10): for a in (0, 1, 2, 3): p_arr[s][a] = calc_pm(s, a) for s in (2, 5, 7, 10): print 'Expected value for S', s + 1, ': ', g_est_e_arr[s][:] + GAMMA * p_arr[s][:] def main(): run(0.0) # validate_condition() run(0.2) run(0.5) run(1.0) # arr = get_move_probs(0, 0) # print arr if __name__ == "__main__": main()
true
add12e183a9909e23839a429f1b83932726c57d9
Python
JHussle/Python
/Collections/collections.py
UTF-8
474
3.984375
4
[]
no_license
import os from os import system system('clear') array = (87, 10, 2, 46, 22, 19, 66) print(type(array)) print(array) for number in array: print(number) #List cars = ["BMW", "Audi", "VW", "Ford", "Honda", "Chevy"] print(cars) print(type(cars)) cars.sort() for car in cars: print(car) numbers = [6, 3, 8, 1, 2, 8, 3] print("Before sorting list") for n in numbers: print(n) print() print("After sorting the list") numbers.sort() for n in numbers: print(n)
true
27cd7b203f7d143c45988445b92c00185dba9733
Python
geekstor/jeju-dl-camp-2018
/util/util.py
UTF-8
2,567
2.59375
3
[]
no_license
import tensorflow as tf from configuration import ConfigurationManager from function_approximator import GeneralNetwork, Head def get_vars_with_scope(scope): return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope) def get_copy_op(scope1, scope2): train_variables = get_vars_with_scope(scope1) target_variables = get_vars_with_scope(scope2) assign_ops = [] for main_var in train_variables: for target_var in target_variables: if str(main_var.name).replace(scope1, "") == \ str(target_var.name).replace(scope2, ""): assign_ops.append(tf.assign(target_var, main_var)) print("Copying Ops.:", len(assign_ops)) return tf.group(*assign_ops) def get_session(cfg_params: ConfigurationManager): required_params = [] tf_params = cfg_params.parse_and_return_dictionary("TENSORFLOW", required_params) config = tf.ConfigProto() if "ALLOW_GPU_GROWTH" not in tf_params or not tf_params["ALLOW_GPU_GROWTH"]: config.gpu_options.allow_growth = True if "INTRA_OP_PARALLELISM" in tf_params: config.intra_op_parallelism_threads = tf_params["INTRA_OP_PARALLELISM"] if "INTER_OP_PARALLELISM" in tf_params: config.inter_op_parallelism_threads = tf_params["INTER_OP_PARALLELISM"] return tf.Session(config=config) def build_train_and_target_general_network_with_head( head, cfg_parser ): with tf.variable_scope("train_net"): train_network_base = GeneralNetwork(cfg_parser) train_network = head( cfg_parser, train_network_base) with tf.variable_scope("target_net"): target_network_base = GeneralNetwork(cfg_parser) target_network = head( cfg_parser, target_network_base) copy_operation = get_copy_op("train_net", "target_net") saver = tf.train.Saver(var_list=get_vars_with_scope("train_net") + get_vars_with_scope("target_net"), max_to_keep=100, keep_checkpoint_every_n_hours=1) return [train_network_base, train_network, target_network_base, target_network, copy_operation, saver] def huber_loss(u, kappa): return tf.where(tf.abs(u) <= kappa, tf.square(u) * 0.5, kappa * (tf.abs(u) - 0.5 * kappa)) def asymmetric_huber_loss(u, kappa, tau): delta = tf.cast(u < 0, tf.float32) if kappa == 0: return (tau - delta) * u else: return tf.abs(tau - delta) * huber_loss(u, kappa)
true
ea9925c02b20b0a1d351c7433b93e4cfaad3e76b
Python
reedan88/QAQC_Sandbox
/Calibration/Parsers/Parsers/DOSTACalibration.py
UTF-8
6,132
3.03125
3
[]
no_license
#!/usr/bin/env python import datetime import re import csv import pandas as pd from zipfile import ZipFile from dateutil.parser import parse from xml.etree.ElementTree import XML class DOSTACalibration(): def __init__(self, uid): self.serial = '' self.uid = uid self.coefficients = {'CC_conc_coef': None, 'CC_csv': None} self.notes = {'CC_conc_coef': None, 'CC_csv': None} @property def uid(self): return self._uid @uid.setter def uid(self, d): r = re.compile('.{5}-.{6}-.{5}') if r.match(d) is not None: self.serial = d.split('-')[2] self._uid = d else: raise Exception(f"The instrument uid {d} is not a valid uid. Please check.") def load_qct(self, filepath): """ Function which parses the output from the QCT check-in and loads them into the DOSTA object. Args: filepath - the full directory path and filename Raises: ValueError - checks if the serial number parsed from the UID matches the serial number stored in the file. Returns: self.coefficients - populated coefficients dictionary self.date - the calibration dates associated with the calibration values self.type - the type (i.e. 16+/37-IM) of the CTD self.serial - populates the 5-digit serial number of the instrument """ self.source_file(filepath) data = {} with open(filepath, errors='ignore') as file: reader = csv.reader(file, delimiter='\t') for row in reader: data.update({reader.line_num: row}) for key, info in data.items(): # Find the serial number from the QCT check-in and compare to UID if 'serial number' in [x.lower() for x in info]: serial_num = info[-1].zfill(5) if self.serial != serial_num: raise ValueError( f'Serial number {serial_num.zfill(5)} from the QCT file does not match {self.serial} from the UID.') else: pass # Find the svu foil coefficients if 'svufoilcoef' in [x.lower() for x in info]: self.coefficients['CC_csv'] = [float(n) for n in info[3:]] # Find the concentration coefficients if 'conccoef' in [x.lower() for x in info]: self.coefficients['CC_conc_coef'] = [float(n) for n in info[3:]] def load_docx(self, filepath): """ Take the path of a docx file as argument, return the text of the file, and parse the QCT test date """ WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' def get_docx_text(filepath): """ Take the path of a docx file as argument, return the text in unicode. """ with ZipFile(filepath) as document: xml_content = document.read('word/document.xml') tree = XML(xml_content) paragraphs = [] for paragraph in tree.getiterator(PARA): texts = [node.text for node in paragraph.getiterator(TEXT) if node.text] if texts: paragraphs.append(''.join(texts)) return '\n\n'.join(paragraphs) document = get_docx_text(filepath) for line in document.splitlines(): if 'test date' in line.lower(): date = parse(line, fuzzy=True) self.date = date.strftime('%Y%m%d') def source_file(self, filepath): """ Routine which parses out the source file and filename where the calibration coefficients are sourced from. """ dcn = filepath.split('/')[-2] filename = filepath.split('/')[-1] self.source = f'Source file: {dcn} > {filename}' def add_notes(self, notes): """ This function adds notes to the calibration csv based on the calibration coefficients. Args: notes - a dictionary with keys of the calibration coefficients which correspond to an entry of desired notes about the corresponding coefficients Returns: self.notes - a dictionary with the entered notes. """ keys = notes.keys() for key in keys: self.notes[key] = notes[key] def write_csv(self, outpath): """ This function writes the correctly named csv file for the ctd to the specified directory. Args: outpath - directory path of where to write the csv file Raises: ValueError - raised if the CTD object's coefficient dictionary has not been populated Returns: self.to_csv - a csv of the calibration coefficients which is written to the specified directory from the outpath. """ # Run a check that the coefficients have actually been loaded for key in self.coefficients.keys(): if self.coefficients[key] is None: raise ValueError(f'No coefficients for {key} have been loaded.') # Create a dataframe to write to the csv data = {'serial': [self.serial]*len(self.coefficients), 'name': list(self.coefficients.keys()), 'value': list(self.coefficients.values()), 'notes': list(self.notes.values()) } df = pd.DataFrame().from_dict(data) # Add in the source df['notes'].iloc[0] = self.source # Generate the csv name csv_name = self.uid + '__' + self.date + '.csv' # Now write to check = input(f"Write {csv_name} to {outpath}? [y/n]: ") if check.lower().strip() == 'y': df.to_csv(outpath+'/'+csv_name, index=False)
true
279c27637628504c2318d4c099b73e5a96d35e38
Python
benumbed/rapid-rest
/src/rapidrest_dummyapi/v1/recursive/__init__.py
UTF-8
701
2.53125
3
[ "BSD-3-Clause-Clear" ]
permissive
from flask import jsonify, make_response from rapidrest.apiresource import ApiResource, ApiResponse class Recursive(ApiResource): endpoint_name = "recursive" description = "Recursive endpoint" def get(self, obj_id=""): """ Example of a GET @param obj_id: @return { description_of_the_return_value } """ if obj_id: resp = make_response((jsonify({"recursive_get": True, "id": obj_id}), 200)) else: resp = make_response((jsonify({"recursive_get": True}), 200)) return resp def post(self): """ """ return ApiResponse(body={"recursive_post": True}, status_code=200)
true
25f2e8db95edf1487e2880ee4bbfc76dfb68c88c
Python
Ebyy/python_projects
/Classes/modifying_attributes_by_method.py
UTF-8
3,058
3.671875
4
[]
no_license
class Car(): """Simulate method for summary.""" def __init__(self,make,model,year): """Initialize attributes to describe car.""" self.make = make self.model = model self.year = year def update_odometer(self, mileage): """Set odometer reading to a given value.""" self.odometer_reading = mileage def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = "\n" + str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a statement thart show the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_old_car = Car('toyota','corolla',2016) print(my_old_car.get_descriptive_name()) my_old_car.update_odometer(65) my_old_car.read_odometer() #Conditions can also be used within classes class Car(): """Simulate method for summary.""" def __init__(self,make,model,year): """Initialize attributes to describe car.""" self.make = make self.model = model self.year = year def update_odometer(self, mileage): """Set odometer reading to a given value. Reject reduction alterations to the reading.""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print ("You can't roll back the odometer!") def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = "\n" + str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a statement thart show the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_old_car.update_odometer(45) my_old_car.read_odometer() #incrementing a value through a method. class Car(): """Simulate method for summary.""" def __init__(self,make,model,year): """Initialize attributes to describe car.""" self.make = make self.model = model self.year = year def update_odometer(self, mileage): """Set odometer reading to a given value.""" self.odometer_reading = mileage def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = "\n" + str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a statement thart show the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.") def increment_odometer(self,miles): """Add the given amount to the odometer.""" self.odometer_reading += miles my_used_car = Car('subaru','outback',2013) print (my_used_car.get_descriptive_name()) my_used_car.update_odometer(23500) my_used_car.read_odometer() my_used_car.increment_odometer(100) my_used_car.read_odometer()
true
0316a0adfe8446bfb49aa70f12efe25f99907ba2
Python
alben/sandbox
/AOC2017/AOC01/sol.py
UTF-8
255
3.140625
3
[]
no_license
TEST1 = '1122' SOL1 = 3 TEST2 = '1111' SOL2 = 4 TEST3 = '1234' SOL3 = 0 TEST4 = '91212129' SOL4 = 9 target = TEST2 total = 0 for i, item in enumerate(target, 1): i = i % len(target) if item == target[i]: total += int(item) print(total)
true
58946e689951557816b8a6bdc91f8313e41f79ea
Python
poojakancherla/Problem-Solving
/Leetcode Problem Solving/DataStructures/Linked Lists/206-reverse-linked-list.py
UTF-8
1,218
4
4
[]
no_license
class Node: def __init__(self, val): self.val = val self.next = None ###### Iterative ######## def reverseList_iter(head): currNode = head prevNode, nextNode = None, None while currNode: nextNode = currNode.next currNode.next = prevNode prevNode = currNode currNode = nextNode return prevNode ##################################################################################################################################################### ###### Recursive ###### def reverseList_rec(head): if not head: return None if not head.next: return head nextNode = head.next head.next = None rest = reverseList_rec(nextNode) nextNode.next = head return rest ###################################################################################################################################################### # Creating the linked list head = Node(1) a = Node(2) b = Node(3) c = Node(4) d = Node(5) head.next = a a.next = b b.next = c c.next = d # newHead = reverseList_iter(head) newHead = reverseList_rec(head) # Printing the new list curr = newHead while(curr): print(curr.val) curr = curr.next
true
60bb63dc9b569d9ecc0ee9bc6103c9b5a7945b2e
Python
andreapdr/word-class-embeddings
/src/model/helpers.py
UTF-8
1,654
2.640625
3
[]
no_license
import torch import torch.nn as nn from torch.nn import functional as F def init_embeddings(pretrained, vocab_size, learnable_length): pretrained_embeddings = None pretrained_length = 0 if pretrained is not None: pretrained_length = pretrained.shape[1] assert pretrained.shape[0] == vocab_size, 'pre-trained matrix does not match with the vocabulary size' pretrained_embeddings = nn.Embedding(vocab_size, pretrained_length) pretrained_embeddings.weight = nn.Parameter(pretrained, requires_grad=False) learnable_embeddings = None if learnable_length > 0: learnable_embeddings = nn.Embedding(vocab_size, learnable_length) embedding_length = learnable_length + pretrained_length assert embedding_length > 0, '0-size embeddings' return pretrained_embeddings, learnable_embeddings, embedding_length def embed( model, input): input_list = [] if model.pretrained_embeddings: input_list.append(model.pretrained_embeddings(input)) if model.learnable_embeddings: input_list.append(model.learnable_embeddings(input)) return torch.cat(tensors=input_list, dim=2) def embedding_dropout( input, drop_range, p_drop=0.5, training=True): if p_drop > 0 and training and drop_range is not None: p = p_drop drop_from, drop_to = drop_range m = drop_to - drop_from #length of the supervised embedding l = input.shape[2] #total embedding length corr = (1 - p) input[:, :, drop_from:drop_to] = corr * F.dropout(input[:, :, drop_from:drop_to], p=p) input /= (1 - (p * m / l)) return input
true
c9711a276a356f283c6a2d34bb7c3608e3a335a7
Python
sandeep-18/think-python
/Chapter05/example05_boolean.py
UTF-8
348
4.4375
4
[]
no_license
# Sandeep Sadarangani 3/12/18 # A function that takes in two numbers and determines if they are equal def equality(num1, num2): isEqual = 0 if num1 == num2: isEqual = 1 return isEqual x = 7 y = 7 equality_check = equality(x, y) if equality_check: print("Numbers are equal") else: print("Numbers are not equal")
true
3874cfcb2188bcb18c3850a90b55ff5be07d8cae
Python
21tushar/Python-Tutorials
/os module(sentdex).py
UTF-8
156
3.078125
3
[]
no_license
import os dir1 = os.getcwd() print(dir1) os.mkdir('newdir') import time time.sleep(5) os.rename('newdir', 'newdir1') time.sleep(5) os.rmdir('newdir1')
true
57dd683a0884b38cdce07c5903d1164d43454d27
Python
Globaxe/crispy-disco
/lex.py
UTF-8
1,557
2.75
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Sep 27 09:19:51 2017 @author: cedric.pahud """ import ply.lex as lex from ply.lex import TOKEN reserved_words = ( 'BPM', 'START', 'STOP', 'REP', 'ARP', 'PAUSE', ) notes = ( 'do', 'do\#', 're', 're\#', 'mi', 'mi\#', 'fa', 'fa\#', 'sol', 'sol\#', 'la', 'la\#', 'si', 'si\#' ) tokens =( 'NUMBER', 'NOTE', 'ID', 'SIGNAL', 'NEWLINE' ) + tuple(map(lambda s: s.upper(),reserved_words)) literals = r'();={}[],+-' notes = [note+str(i) for note in notes for i in range(1,9)] @TOKEN(r'|'.join(notes)) def t_NOTE(t): return t @TOKEN(r'|'.join(['sine','saw','pulse','square'])) def t_SIGNAL(t): return t # peut être changer genre peu pas commencer par maj ou autre pour pas que ça empiète avec note def t_ID(t): r'[A-Za-z_]\w*' if t.value in reserved_words: t.type = t.value.upper() return t def t_NUMBER(t): r'\d+(\.\d+)?' t.value = int(t.value) return t def t_NEWLINE(t): r'\n+' t.lexer.lineno+=len(t.value) return t def t_comment(t): r'\#.*\n*' t.lexer.lineno+=t.value.count('\n') t_ignore = ' \t' def t_error(t): print("illegal character '%s'"%t.value[0]) t.lexer.skip(1) lex.lex() if __name__ == "__main__": import sys prog = open(sys.argv[1]).read() lex.input(prog) while 1: tok = lex.token() if not tok: break print("line %d: %s(%s)"%(tok.lineno, tok.type, tok.value))
true
48e7abbe4a7ef642537a6042f442414dc2e39c81
Python
maggiebauer/hb_project
/seed.py
UTF-8
5,613
2.609375
3
[]
no_license
"""Utility file to seed company_insights database from FullContact API and Crunchbase data csb in seed_data/""" from sqlalchemy import func from model import FCCompany from model import SMLink from model import CompanyLink from model import IndustryType from model import CompanyIndustry from model import CBCompany from model import FundingRound from model import FundingType from model import MarketType from model import CompanyMarket from model import connect_to_db, db from server import app import datetime import csv ########################################################################### # Crunchbase data seeding def load_market_types(): """Load market types from seed_data/cbfundings into database.""" print("MarketTypes") MarketType.query.delete() # Read cbrounds.csv file and insert data rounds_csv = open('seed_data/project_cbrounds.csv') rounds_reader = csv.reader(rounds_csv) market_type_dict = {} for row in rounds_reader: market_names = row[2].split('|') for item in market_names: if item not in market_type_dict: market_type_dict[item] = True market_type = MarketType(market_type=item) db.session.add(market_type) db.session.commit() def load_funding_types(): """Load funding types from seed_data/cbfundings into database.""" print("FundingTypes") FundingType.query.delete() funding_type_dict = {} # Read cbrounds.csv file and insert data rounds_csv = open('seed_data/project_cbrounds.csv') rounds_reader = csv.reader(rounds_csv) for row in rounds_reader: if (row[8], row[9]) not in funding_type_dict: funding_type_dict[(row[8], row[9])] = True funding_type = FundingType(funding_type_name=row[8], funding_type_code=row[9]) db.session.add(funding_type) db.session.commit() def load_cb_companies(): """Load cbcompanies from seed_data/cbcompanies into database.""" print("CBCompanies") CBCompany.query.delete() # Get market types to populate foreign key for market_types table all_market_types = MarketType.query.all() market_type_dict = {} for m_type in all_market_types: market_type_dict[m_type.market_type] = m_type.market_type_id # Read cbcompanies.csv file and insert data companies_csv = open('seed_data/project_cbcompanies.csv') companies_reader = csv.reader(companies_csv) for row in companies_reader: cb_company = CBCompany( cb_company_name=row[1].lower(), cb_url=row[2], cb_permalink=row[0], # market_type_id=market_type_dict[row[3]], state_code=row[7], city_name=row[9], first_funding=row[12] if row[12] else None, total_funding=int(float(row[4])) if row[4] != '-' else None) db.session.add(cb_company) db.session.commit() markets = row[3].split('|') for item in markets: company_market = CompanyMarket( cb_company_id=cb_company.cb_company_id, market_type_id=market_type_dict[item]) db.session.add(company_market) db.session.commit() def load_cb_rounds(): """Load cbrounds from seed_data/cbrounds into database.""" print("CBRounds") FundingRound.query.delete() # Get funding types to populate foreign key for funding_rounds table all_funding_types = FundingType.query.all() funding_type_dict = {} for f_type in all_funding_types: funding_type_dict[(f_type.funding_type_name, f_type.funding_type_code)] = f_type.funding_type_id # # Get market types to populate foreign key for market_types table # all_market_types = MarketType.query.all() # market_type_dict = {} # for m_type in all_market_types: # market_type_dict[m_type.market_type] = m_type.market_type_id # Get company ids for foreign key in the funding_rounds table all_company_ids = CBCompany.query.all() company_id_dict = {} for company in all_company_ids: company_id_dict[company.cb_permalink] = company.cb_company_id # Read cbrounds.csv file and insert data rounds_csv = open('seed_data/project_cbrounds.csv') rounds_reader = csv.reader(rounds_csv) for row in rounds_reader: cb_round = FundingRound(funded_amt=row[11], funded_date=row[10], # market_type_id=market_type_dict[row[2]], cb_company_id=company_id_dict[row[0]], funding_type_id=funding_type_dict[(row[8], row[9])]) db.session.add(cb_round) db.session.commit() # def load_company_markets(): # """Load company markets from seed_data/cbcompanies into database.""" # print("CompanyMarket") # CompanyMarket.query.delete() # # Get market types to populate foreign key for market_types table # all_market_types = MarketType.query.all() # market_type_dict = {} # for m_type in all_market_types: # market_type_dict[m_type.market_type] = m_type.market_type_id ############################################################################ if __name__ == "__main__": connect_to_db(app) # In case tables haven't been created, create them # db.create_all() # Import different types of data load_market_types() load_funding_types() load_cb_companies() load_cb_rounds()
true
5378fb010cc94b740993e4a30439ee5e9c86514d
Python
GeographicaGS/GeoLibs-Dator
/dator/transformers/pandas.py
UTF-8
1,107
2.671875
3
[ "MIT" ]
permissive
from dator.schemas import validator, TransformerSchema class Pandas(): def __init__(self, options): self.options = validator(options, TransformerSchema) def transform(self, df): if self.options.get('time', None): field = self.options['time']['field'] start = self.options['time'].get('start', None) finish = self.options['time'].get('finish', None) filters = True df[field] = df[field].dt.tz_convert(None) if start: filters &= df[field] >= start if finish: filters &= df[field] < finish df = df[filters] if self.options.get('time', None) and 'step' in self.options['time']: df[field] = df[field].dt.floor(self.options['time']['step']) df = df.groupby(self.options['aggregate']['by']).agg(self.options['aggregate']['fields']) df = df.reset_index() if isinstance(df.columns[0], tuple): # Flatting columns df.columns = ['_'.join(filter(None, col)) for col in df.columns] return df
true
08c26de6cc8874f72c286e57f89e2b615157e05c
Python
yisha0307/PYTHON-STUDY
/RUNOOB/test01.py
UTF-8
168
3.234375
3
[]
no_license
# -*- coding: UTF-8 -*- # python2 x = 'a' y = 'b' # 换行输出 print x print y print '-------------' # 不换行输出 print x, print y, #不换行输出 print x, y
true
d29237afc8e03c9f9068449a486ed891505acda4
Python
dominikjurinic/geometric-integrator
/python-implementation/lie_bracket.py
UTF-8
150
2.578125
3
[]
no_license
import numpy as np def lie_bracket(skew_x, skew_y): skew_x_out = np.matmul(skew_x,skew_y) - np.matmul(skew_y,skew_x) return skew_x_out
true
7c84cf4b444a6747b2ccd4aea11b3250159f692b
Python
AP-Class-Activities/Final-Project-T-11
/store_class.py
UTF-8
8,063
3.28125
3
[]
no_license
import random sellers_id = dict() sellers = dict() products = dict() costumers = dict() class Store: net_profit = 0 # variable to store the net profit of the store until this moment def __init__(self, address, website_url, telephone_number): self.address = address self.website_url = website_url self.telephone_number = telephone_number # method to approve a seller registration request @staticmethod def approve_seller(name, last_name, distance_to_inventory, address, phone_number, email): approval = input("Do you approve a seller with following details: type yes or no \n" "name: {}, last name: {}, distance to inventory: {}, address: {}, phone number: {}," " email: {}".format(name, last_name, distance_to_inventory, address, phone_number, email)) if approval.lower() == "yes": return True else: raise PermissionError # method to approve a product listing request @staticmethod def approve_product(product, quantity, product_id, sellers_id, price): approval = input("Do you approve a product with following details: type yes or no \n" "product name: {}, quantity: {}, product id: {}, seller id: {}," " product price: {}".format(product, quantity, product_id, sellers_id, price)) if approval.lower() == "yes": return True else: raise PermissionError # method to approve a costumer order request @staticmethod def approve_order(item, seller_id, costumer_id, price, quantity): approval = input("Do you approve an order with following details: type yes or no \n" "item name: {}, quantity: {}, seller id: {}, costumer id: {}," "unit price: {}".format(item, quantity, seller_id, costumer_id, price)) if approval.lower() == "yes": return True else: raise PermissionError # method to remove a specific costumer @staticmethod def remove_costumer(costumer_id): del costumers[costumer_id] # method to remove a specific seller @staticmethod def remove_seller(seller_id): del sellers[seller_id] # method to see specific seller details @staticmethod def seller_details(seller_id): # below results is a list of form [name, last name, address, list of orders, balance, phone number, # email, rates, sales, suspension, distance to inventory, products] and the indices are # corresponding to each of these item seller_details = sellers[seller_id] print("current status and details of the seller is: \n", "name: {}\n".format(seller_details[0]), "last name: {}\n".format([seller_details[1]]), "address: {}\n".format(seller_details[2]), "phone: {}\n".format(seller_details[5]), "email: {}\n".format(seller_details[6]), "suspension status: {}\n".format(seller_details[9]), "balance: {}\n".format(seller_details[4]), "with-held credit: {}\n".format(store_cash_desk[seller_id]), "average rate: {} and detailed ratings is: {}\n".format(sum(seller_details[7])/len(seller_details[7]), seller_details[7]), "sales: {}\n".format(str(seller_details[8])), "list of orders: {}\n".format(seller_details[3]), "profit: {}\n".format(seller_details[12]), "incomes: {}\n".format(seller_details[13]), "costs: {}\n".format(seller_details[14]), "products: {}\n".format(seller_details[11]), "distance: {}\n".format(seller_details[10])) # method to list specific costumer details @staticmethod def costumer_details(costumer_id): # below results is a list of form [name, last name, address, phone_number, email, credit, cart, favorites, # last_shopping] and the indices are corresponding to each of these item. print("current status and details of the costumer is: \n", "name: {}\n".format(costumer_details[0]), "last name: {}\n".format([costumer_details[1]]), "address: {}\n".format(costumer_details[2]), "phone: {}\n".format(costumer_details[3]), "email: {}\n".format(costumer_details[4]), "balance: {}\n".format(costumer_details[5]), "current cart(shopping basket): {}\n".format(costumer_details[6]), "favorites: {}\n".format(costumer_details[7]), "shopping history: {}\n".format(costumer_details[8])) # method to calculate approximate shipping time def shipping_time_calculator(self, costumer_id, seller_id): print("your address is: {}".format(self.address)) print("the costumer address is: {}".format(costumers[costumer_id][2])) distance_to_costumer = int(input("estimate the approximate time from inventory to costumer in minutes: ")) distance_to_seller = sellers[seller_id][10] return "approximate shipping time is: " + str(distance_to_seller) + str(distance_to_costumer) # method to generate gift cards @staticmethod def gift_card_generator(code, year, month, day, specified_costumers_list, usage_count, specified_products, percent): expire_date = datetime.date(int(year), int(month), int(day)) # determining expiration date via date object specified_costumers = dict.fromkeys(specified_costumers_list, usage_count) # determining allowed costumers # adding generated gift card to gift cards dictionary by below code: gift_cards[code] = [expire_date, specified_costumers, specified_products, percent] class Product: def __init__(self, product, quantity, product_id, sellers_id, price,color): # to check if store approves this product to be listed on it's catalogue or not if Store.approve_product([product, quantity, product_id, sellers_id, price,color]) is True: # to check if a product is not available in the store by another seller if product not in products.keys(): assert len(str(product_id)) == 6 # check if the length of the product id is exactly 6 or not self.product = product # assigning product name self.product_id = "PR" + str(product_id) # assigning product id self.sellers_id = [sellers_id] # assigning seller id self.price = price # assigning it's price self.color = color # assigning color self.comments = dict() # empty dictionary of comments to be filled by costumers opinions self.quantity = quantity # assigning product quantity # adding new product to the dictionary of all products to be inserted to database later in below format: products[self.product] = [self.product_id, self.sellers_id, self.price, self.comments, quantity,color] # if it is available then: else: products[product][1].append(sellers_id) # append the new seller to the existing list of sellers products[product][-1] += quantity # increase the quantity by the amount which new seller wish to add # if store does not permit the new product: else: raise PermissionError if color not in ['blue', 'black', 'red', 'yellow', 'white']: raise Error('the value of color should be [blue, black, red, yellow and white] ') self.color = color # Available colors for a product def get_price(self, number_to_be_bought): if number_to_be_bought > quantity: return Error("Your purchase is more than the number available!") else: return price * number_to_be_bought
true
bb9ecafe59dec227f8d0a5a07ec741e3b331d3ff
Python
HimanshuSRTOp/advanced-verification
/cogs/setup.py
UTF-8
6,995
2.53125
3
[]
no_license
import discord import asyncio import json from discord.ext import commands from discord.utils import get # ------------------------ COGS ------------------------ # def is_allowed(ctx): return ctx.message.author.id == 754453123971547266 class SetupCog(commands.Cog, name="setup command"): def __init__(self, bot): self.bot = bot # ------------------------------------------------------ # @commands.command(name = 'verify', aliases=["captcha"], usage="<on/off>", description="Enable or disable the captcha system.") @commands.has_permissions(administrator = True) @commands.cooldown(1, 3, commands.BucketType.member) @commands.guild_only() async def verify(self, ctx, onOrOff): onOrOff = onOrOff.lower() if onOrOff == "on": embed = discord.Embed(title = f"**Nyssa Verification System**", description = f"**Set up the captcha protection includes the creation of :**\n\n- captcha verification channel\n- log channel\n- temporary role\n\n**Do you want to set up the captcha protection? \"__yes__\" or \"__no__\".**", color = 0xff0000) embed.set_image(url="https://miro.medium.com/max/2000/1*7YuxXLpRNzhvWSWnQGuMTg.png") await ctx.channel.send(embed = embed) # Ask if user are sure def check(message): if message.author == ctx.author and message.content in ["yes", "no",]: return message.content try: msg = await self.bot.wait_for('message', timeout=30.0, check=check) if msg.content == "no": await ctx.channel.send("The set up of the captcha protection was abandoned.") else: try: loading = await ctx.channel.send("Creation of captcha protection...") # Data with open("configuration.json", "r") as config: data = json.load(config) # Create role temporaryRole = await ctx.guild.create_role(name="untested") # Hide all channels for channel in ctx.guild.channels: if isinstance(channel, discord.TextChannel): await channel.set_permissions(temporaryRole, read_messages=False) elif isinstance(channel, discord.VoiceChannel): await channel.set_permissions(temporaryRole, read_messages=False, connect=False) # Create captcha channel captchaChannel = await ctx.guild.create_text_channel('verification') await captchaChannel.set_permissions(temporaryRole, read_messages=True, send_messages=True) await captchaChannel.set_permissions(ctx.guild.default_role, read_messages=False) await captchaChannel.edit(slowmode_delay= 5) # Create log channel if data["logChannel"] is False: logChannel = await ctx.guild.create_text_channel(f"{self.bot.user.name}-logs") await logChannel.set_permissions(ctx.guild.default_role, read_messages=False) data["logChannel"] = logChannel.id # Edit configuration.json # Add modifications data["captcha"] = True data["temporaryRole"] = temporaryRole.id data["captchaChannel"] = captchaChannel.id newdata = json.dumps(data, indent=4, ensure_ascii=False) with open("configuration.json", "w") as config: config.write(newdata) await loading.delete() embed = discord.Embed(title = f"**CAPTCHA WAS SET UP WITH SUCCESS**", description = f"The captcha was set up with success.", color = 0x2fa737) # Green await ctx.channel.send(embed = embed) except Exception as error: embed = discord.Embed(title=f"**ERROR**", description=f"An error was encountered during the set up of the captcha.\n\n**ERROR :** {error}", color=0xe00000) # Red embed.set_footer(text="Join the Support Server for help!") return await ctx.channel.send(embed=embed) except (asyncio.TimeoutError): embed = discord.Embed(title = f"**TIME IS OUT**", description = f"{ctx.author.mention} has exceeded the response time (30s).", color = 0xff0000) await ctx.channel.send(embed = embed) elif onOrOff == "off": loading = await ctx.channel.send("Deletion of captcha protection...") with open("configuration.json", "r") as config: data = json.load(config) # Add modifications data["captcha"] = False # Delete all noDeleted = [] try: temporaryRole = get(ctx.guild.roles, id= data["temporaryRole"]) await temporaryRole.delete() except: noDeleted.append("temporaryRole") try: captchaChannel = self.bot.get_channel(data["captchaChannel"]) await captchaChannel.delete() except: noDeleted.append("captchaChannel") # Add modifications data["captchaChannel"] = False newdata = json.dumps(data, indent=4, ensure_ascii=False) # Edit configuration.json with open("configuration.json", "w") as config: config.write(newdata) await loading.delete() embed = discord.Embed(title = f"**CAPTCHA WAS DELETED DISABLED**", description = f"Why would you do that...", color = 0x2fa737) # Green await ctx.channel.send(embed = embed) if len(noDeleted) > 0: errors = ", ".join(noDeleted) embed = discord.Embed(title = f"**CAPTCHA DELETION ERROR**", description = f"**Error(s) detected during the deletion of the ** ``{errors}``.", color = 0xe00000) # Red await ctx.channel.send(embed = embed) else: embed = discord.Embed(title=f"**ERROR**", description=f"The setup argument must be on or off\nFollow the example : ``{self.bot.command_prefix}setup <on/off>``", color=0xe00000) # Red embed.set_footer(text="Join the Support Server for help!") return await ctx.channel.send(embed=embed) # ------------------------ BOT ------------------------ # def setup(bot): bot.add_cog(SetupCog(bot))
true
f57f54a554449ebb6d01bf8b8ec422511fdb7b9a
Python
20c/munge
/src/munge/config.py
UTF-8
7,040
3.015625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
import collections import copy import os from urllib.parse import urlsplit import munge import munge.util # this wouldn't work with tabular data # need metaclass to allow users to set info once on class # TODO rename to BaseConfig, set standard setup for Config? class Config(collections.abc.MutableMapping): """ class for storing and manipulating data for config files """ # internal base for defaults _base_defaults = { "config": {}, # directory to look for config in "config_dir": None, # name of config file "config_name": "config", "codec": None, "autowrite": False, "validate": False, } def __init__(self, **kwargs): """ accepts kwargs to set defaults data=dict to set initial data read=dir to open a dir try_read=dir to try to open a dir (and not throw if it doesn't read) """ # use derived class defaults if available if hasattr(self, "defaults"): self._defaults = self._base_defaults.copy() self._defaults.update(self.defaults) else: self._defaults = self._base_defaults.copy() # override anything passed to kwargs for k, v in list(kwargs.items()): if k in self._defaults: self._defaults[k] = v self.data = kwargs.get("data", self.default()) self._meta_config_dir = "" if "read" in kwargs: self.read(kwargs["read"]) if "try_read" in kwargs: self.try_read(kwargs["try_read"]) def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def __delitem__(self, key): del self.data[key] def __iter__(self): return iter(self.data) def __len__(self): return len(self.data) def copy(self): rv = self.__class__(data=self.data.copy()) # copy meta rv._meta_config_dir = self._meta_config_dir return rv def get_nested(self, *args): """ get a nested value, returns None if path does not exist """ data = self.data for key in args: if key not in data: return None data = data[key] return data def default(self): return copy.deepcopy(self._defaults["config"]) def clear(self): self.data = self.default() self._meta_config_dir = None @property def meta(self): if not self._meta_config_dir: return {} return { "config_dir": self._meta_config_dir, } def read(self, config_dir=None, config_name=None, clear=False): """ read config from config_dir if config_dir is None, clear to default config clear will clear to default before reading new file """ # TODO should probably allow config_dir to be a list as well # get name of config directory if not config_dir: config_dir = self._defaults.get("config_dir", None) if not config_dir: raise KeyError("config_dir not set") # get name of config file if not config_name: config_name = self._defaults.get("config_name", None) if not config_name: raise KeyError("config_name not set") conf_path = os.path.expanduser(config_dir) if not os.path.exists(conf_path): raise OSError(f"config dir not found at {conf_path}") config = munge.load_datafile(config_name, conf_path, default=None) if not config: raise OSError(f"config file not found in {conf_path}") if clear: self.clear() munge.util.recursive_update(self.data, config) self._meta_config_dir = conf_path return self def try_read(self, config_dir=None, **kwargs): """ try reading without throwing an error config_dir may be a list of directories to try in order, if so it will return after the first successful read other args will be passed direction to read() """ if isinstance(config_dir, str): config_dir = (config_dir,) for cdir in config_dir: try: self.read(cdir, **kwargs) return cdir except OSError as e: pass def write(self, config_dir=None, config_name=None, codec=None): """ writes config to config_dir using config_name """ # get name of config directory if not config_dir: config_dir = self._meta_config_dir if not config_dir: raise OSError("config_dir not set") # get name of config file if not config_name: config_name = self._defaults.get("config_name", None) if not config_name: raise KeyError("config_name not set") if codec: codec = munge.get_codec(codec)() else: codec = munge.get_codec(self._defaults["codec"])() config_dir = os.path.expanduser(config_dir) if not os.path.exists(config_dir): os.mkdir(config_dir) codec.dumpu(self.data, os.path.join(config_dir, "config." + codec.extension)) class MungeConfig(Config): defaults = {"config": {}, "config_dir": "~/.munge", "codec": "yaml"} def find_cls(name, extra_schemes={}): if name in extra_schemes: return munge.get_codec(extra_schemes[name]["type"]) return munge.get_codec(name) class MungeURL(collections.namedtuple("MungeURL", "cls url")): pass # TODO change extra_schemes to full config dict def parse_url(url, extra_schemes={}): """ parse a munge url type:URL URL.type examples: file.yaml yaml:file.txt http://example.com/file.yaml yaml:http://example.com/file.txt mysql://user:password@localhost/database/table django:///home/user/project/settings_dir.settings/app_name/model """ if not url: raise ValueError("url cannot be empty") cls = None res = urlsplit(url) # check config first if res.scheme in extra_schemes: # TODO - nerge these with any existing and recurse addr = extra_schemes[res.scheme] if "type" in addr: cls = find_cls(res.scheme, extra_schemes) if "url" in addr: url = addr["url"] if cls: res = urlsplit(url) return MungeURL(cls, res) # TODO - nerge these with any existing and recurse return parse_url(url) if res.scheme: cls = find_cls(res.scheme, extra_schemes) # check file extension if not cls: (rest, sep, ext) = url.rpartition(".") cls = find_cls(ext, extra_schemes) if not cls: raise ValueError("unable to find codec for %s" % url) return MungeURL(cls, res)
true
1fba1fb390bf6750d2cf0b6ac72a39c6d42022a7
Python
akaliutau/cs-problems-python
/problems/array/Solution1566.py
UTF-8
1,334
3.8125
4
[ "MIT" ]
permissive
""" Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. Example 1: Input: arr = [1,2,4,4,4,4], m = 1, k = 3 Output: true Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less. IDEA: ___ ___ ___ 1,2, 1,2, 1,2 b1 b2 b3 Go though block [b_i], comparing it simultaneously with block [b_i+1] if total length of filled cells == (k - 1) * m, pattern found Like so: b1 -> b2 b2 -> b3 """ from typing import List class Solution1566: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: comonLength = 0 n = len(arr) for i in range(n - m): if arr[i] == arr[i+m]: comonLength += 1 else: comonLength = 0 if comonLength == (k-1) * m: return True return False
true
2345a224340ec193bce61ac20e1979df3093270c
Python
pekkajauhi/Breakout
/game_stats.py
UTF-8
637
2.8125
3
[]
no_license
class GameStats(): """Track game statistics for breakout.""" def __init__(self, bo_settings): """Initialize statistics.""" self.bo_settings = bo_settings self.reset_stats() # Start breakout in an inactive state self.game_active = False # High score should never be reset with open('high_score.txt') as file_object: contents = file_object.read() self.high_score = int(contents) def reset_stats(self): """Initialize statistics that can change during the game.""" self.balls_left = self.bo_settings.ball_limit self.score = 0
true
ae50a29fe52039970a683cb050719537da37f047
Python
narupi/Competitive-programming
/atcoder/abc124/b.py
UTF-8
241
3.078125
3
[]
no_license
n = int(input()) h = list(map(int, input().split())) ans = 0 flag = True for i in reversed(range(n)): flag = True for j in range(i): if h[i] < h[j]: flag = False if flag: ans += 1 print(ans)
true
08d0349d2f3ae92cefad8838ef8a6c9d7dfde1e0
Python
singhujjwal/python
/2017_May23/proc/subprocess/wait_process.py
UTF-8
246
3.046875
3
[]
no_license
#!/usr/bin/env python from subprocess import Popen from time import sleep p = Popen("./slow_program.py") for i in range(5): print "Main program: counting ", i sleep(1) ret = p.wait() print "Child process exited with exit code", ret
true
920aeff8167d0f25c5dcab75dce5ee26a6a78b88
Python
miaohf/flask-vue-book-library
/app/resources/book.py
UTF-8
5,510
2.546875
3
[]
no_license
import re from flask import request from flask_restful import Resource, inputs, reqparse from flask_jwt_extended import create_access_token, jwt_required, jwt_optional from sqlalchemy.orm import subqueryload from app.models import Book, Author, Category from app.helpers import PaginationFormatter def book_rules(): str_regex = r'^[\w ]+$' printable_regex = r''' ^[a-z0-9!"#$%&\'()*+,-./:;<=>?@\\^_`{|}~\[\] \t\n\r\x0b\x0c]+$ '''.strip() parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('isbn', required=True, trim=True, help='ISBN is required', location='json') parser.add_argument('title', required=True, type=inputs.regex(str_regex, re.IGNORECASE), trim=True, help='Title is required', location='json') parser.add_argument('num_of_pages', required=True, type=inputs.positive, help='Number of pages is required and must be a positive number', location='json') parser.add_argument('publisher', required=True, type=inputs.regex(str_regex, re.IGNORECASE), trim=True, help='Publisher is required', location='json') parser.add_argument('publication_date', required=True, type=inputs.date, help='Publication date is required and must be a valid date', location='json') parser.add_argument('about', required=True, type=inputs.regex(printable_regex, re.IGNORECASE), trim=True, help='About is required', location='json') parser.add_argument('authors', required=True, type=int, action='append', help='Author is required', location='json') parser.add_argument('categories', required=True, type=int, action='append', help='Category is required', location='json') return parser def append_authors_to_book(book, authors): if not authors: return if book.id: book.authors = [] book.save() for author_id in authors: author = Author.find(author_id) if author: book.authors.append(author) def append_categories_to_book(book, categories): if not categories: return if book.id: book.categories = [] book.save() for category_id in categories: category = Category.find(category_id) if category: book.categories.append(category) class BookListAPI(Resource): def __init__(self): self.parser = book_rules() self.sort_order = (Book.publication_date.desc(), Book.title,) super(BookListAPI, self).__init__() def get(self): page = request.args.get('page', 1, type=int) limit = request.args.get('limit', 10, type=int) search = request.args.get('search', '', type=str) pagination = None if search.strip(): pagination = self.searched_books(search.strip(), page, limit) else: pagination = self.unsearched_books(page, limit) books = [book.json() for book in pagination.items] return PaginationFormatter(pagination, books).data @jwt_required def post(self): data = self.parser.parse_args() if Book.query.filter(Book.isbn == data.get('isbn')).first(): return dict(message='ISBN already exists'), 409 authors = data.pop('authors', []) categories = data.pop('categories', []) book = Book(**data) append_authors_to_book(book, authors) append_categories_to_book(book, categories) book.save() return book.json(), 201 def searched_books(self, search_value, page, limit): value = '%{}%'.format(search_value) return Book.query.filter(Book.title.like(value)). \ order_by(*self.sort_order). \ paginate(page=page, per_page=limit, error_out=False) def unsearched_books(self, page, limit): return Book.query.order_by(*self.sort_order). \ paginate(page=page, per_page=limit, error_out=False) class BookAPI(Resource): def __init__(self): self.parser = book_rules() super(BookAPI, self).__init__() def get(self, id): load_options = ( subqueryload(Book.authors), subqueryload(Book.categories), ) book = Book.find_or_fail(id, load_options=load_options) data = book.json() data['authors'] = [book.json() for book in book.authors] data['categories'] = [categories.json() for categories in book.categories] return data @jwt_required def put(self, id): book = Book.find_or_fail(id) data = self.parser.parse_args() authors = data.pop('authors', []) categories = data.pop('categories', []) for key, value in data.items(): if key == 'isbn' and self.check_for_isbn(id, value): return dict(message='ISBN already exists'), 409 setattr(book, key, value) append_authors_to_book(book, authors) append_categories_to_book(book, categories) book.save() return book.json() @jwt_required def delete(self, id): book = Book.find_or_fail(id) book.delete() return None, 204 def check_for_isbn(self, id, isbn): return Book.query.filter(Book.id != id, Book.isbn == isbn).first()
true
0a3f81d6d3a8f73c54a106349a173c3326eca34f
Python
majopa/python_projects
/Common Word List.py
UTF-8
436
3.640625
4
[]
no_license
# Author : Matthew Palomar # Class: 8/27/15 # Desc: Creates a list of commonly used words in a given file # Input: file name (fname) fname = raw_input("Enter file name: ") fh = open(fname) lst = list() allWords = list() for line in fh: linebuffer = line.rstrip().split() for words in linebuffer: allWords.append(words) for words in allWords: if not words in lst: lst.append(words) print sorted(lst) raw_input()
true
a4fa5a09eb3e5dcfcf7d579d4d89cb83f53476af
Python
chrislevn/Coding-Challenges
/Orange/DP_III_LIS/The_Tower_of_Babylon.py
UTF-8
1,259
3.1875
3
[]
no_license
from itertools import permutations result = [] path = [] last = -1 def printLIS(a): global last b = [] i = last while i != -1: b.append(a[i]) i = path[i] for i in range(len(b) - 1, -1, -1): print(b[i], end=' ') def LIS_Triple(a): global last, result, path length = 0 path = [-1] * len(a) result = [a[i][2] for i in range(len(a))] for i in range(1, len(a)): for j in range(i): if a[i][0] > a[j][0] and a[i][1] > a[j][1] and result[i] < result[j] + a[i][2]: result[i] = result[j] + a[i][2] path[i] = j for i in range(len(a)): if length < result[i]: last = i length = result[i] return max(result) if __name__ == '__main__': n = int(input()) count = 1 while n != 0: arr = [] for i in range(n): temp_arr = list(map(int, input().split())) temp = list(permutations(temp_arr)) arr.extend(temp) arr = sorted(arr) print("Case {}: maximum height = {}".format(count, LIS_Triple(arr))) count += 1 n = int(input())
true
b08714d2c04223fe06689019ea0af66a8e0bb144
Python
ZoroOP/Problem-Solving-With-Algorithms-And-Data-Structures
/4_Recursion/tower_of_hanoi.py
UTF-8
981
4.0625
4
[ "MIT" ]
permissive
""" Write recursive algorithm that rolves the Tower of Hanoi problem. Explanation: The key to the simplicity of this algorithm is that we make two different recursive calls. The first recursive call moves all but the bottom disk on the initial tower to an intermediate pole. The next line simply moves the bottom disk to its final resting place. Then the second recursive call moves the tower from the intermediate pole on top of the largest disk. The base case is detected when the tower height is 0, there is no task to be completed so move_tower simply returns. """ def move_tower(height, from_pole, to_pole, with_pole): if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(fp, tp): print("moving disk from", fp, "to", tp) def main(): move_tower(4, "A", "C", "B") if __name__ == "__main__": main()
true
20597b990f90ee77062ddbe9652fbb6c144d8500
Python
Jane11111/Leetcode2021
/069.py
UTF-8
297
3.515625
4
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2021-04-18 12:46 # @Author : zxl # @FileName: 069.py class Solution: def mySqrt(self, x: int) -> int: x1 = x while x1*x1>x : x1 = int(0.5*(x1+x/x1)) return x1 x = 5 obj = Solution() ans = obj.mySqrt(x) print(ans)
true
9ac44e880e6d6570fd6b4f2a2b3e927e6dad93b6
Python
dedkoster/audio_preproccesing
/audio_data_generator.py
UTF-8
15,409
3.03125
3
[ "Apache-2.0" ]
permissive
"""Utilities for real-time audio data augmentation. URL: - https://github.com/keras-team/keras/blob/master/keras/preprocessing/image.py """ import os import threading import numpy as np import pandas as pd from glob import glob1 as glob from librosa.output import write_wav from librosa.effects import time_stretch from librosa.core import load as load_audio from keras_preprocessing import get_keras_submodule backend = get_keras_submodule('backend') keras_utils = get_keras_submodule('utils') class AudioDataGenerator(object): """Generate batches of audio data with real-time data augmentation. The data will be looped over (in batches). # Arguments shift: Float > 0. Range of random shift. Randomly adds a shift at the beginning or end of the audio data. noise: Float > 0 (default: 0.005). Volume of added white noise. volume: Float > 0. Volume of audio data. stretch: Float > 0. Stretch factor. If `rate > 1`, then the signal is sped up. If `rate < 1`, then the signal is slowed down. bg_noise_dir: String. The path to the directory with audio files of background noise. bg_noise_volume: Float (default: 0.1). (only relevant if `bg_noise_dir` is set). Volume of background noise. # Examples Example of using `.flow(x, y)`: ```python df_data = pd.read_excel('data.xlsx') datagen = AudioDataGenerator(noise=0, bg_noise_dir='background_noise') # fits the model on batches with real-time data augmentation: model.fit_generator(datagen.flow(dataframe_data=df_data, batch_size=2), steps_per_epoch=len(x_train) / 2, epochs=epochs) # sortagrad for e in range(epochs): print('Epoch', e) if epochs < 2: sortagrad = 10 elif epochs < 6: sortagrad = 20 else: sortagrad = None for x_batch, y_batch in datagen.flow(dataframe_data=df_data, batch_size=batch_size, sorting='asc', top_count=sortagrad): model.fit(x_batch, y_batch) ``` """ def __init__(self, shift=0., noise=0.005, volume=1., stretch=0., bg_noise_dir='', bg_noise_volume=.05): self.shift = shift self.noise = noise self.stretch = stretch self.volume = volume self.bg_noise_dir = bg_noise_dir self.bg_noise_volume = bg_noise_volume if self.shift: if self.shift < 0.: raise ValueError("Shift can't be negative number") if self.noise: if self.noise < 0.: raise ValueError("Noise can't be negative number") if self.volume: if self.volume < 0.: raise ValueError("Volume can't be negative number") if self.stretch: if self.stretch < 0.: raise ValueError("Volume can't be negative number") def flow(self, dataframe_data=None, batch_size=32, sorting=None, save_to_dir=None, save_prefix='', stuffing=0., top_count=None, seed=None, shuffle=None): """Takes data & label from dataframe, generates batches of augmented data. # Arguments dataframe_data: DataFrame. The dataframe of audio data. It must contain 3 columns: transcript, wav_filename, wav_filesize. batch_size: Int (default: 32). sorting: None or string. Sorts audio data by size in ascending (asc) or descending (desc) order. save_to_dir: None or str (default: None). This allows you to optionally specify a directory to which to save the augmented audio data being generated (useful for listening what you are doing). save_prefix: Str (default: `''`). Prefix to use for filenames of saved audio data (only relevant if `save_to_dir` is set). stuffing: Float (default: 0.). Range from -1 to 1. The value that fills the audio when the size increases. top_count: None or int. Number of first audio from the dataset used for fitting. seed: Int (default: None). # Returns An `DataFrameIterator` yielding tuples of `(x, y)` where `x` is a numpy array of augmented audio data and `y` is a numpy array of corresponding labels. """ return DataFrameIterator(self, dataframe_data=dataframe_data, batch_size=batch_size, sorting=sorting, save_to_dir=save_to_dir, save_prefix=save_prefix, stuffing=stuffing, top_count=top_count, shuffle=shuffle, seed=seed) def transform(self, x, sr): """Applies the audio conversion. # Arguments x: numpy array. The audio signal. sr: int. Audio sample rate. # Returns A transformed version (x, sr) of the input. """ input_length = len(x) if self.stretch: x = time_stretch(x, self.stretch) if len(x) > input_length: x = x[:input_length] else: x = np.pad(x, (0, max(0, int(input_length - len(x)))), "constant") if self.shift: x = np.pad(x, (int(self.shift * sr), 0) if np.random.random() < 0.5 else (0, int(self.shift * sr)), 'constant') if len(x) > input_length: x = x[:input_length] if self.noise: x = x + self.noise * np.random.randn(len(x)) if self.bg_noise_dir: bg_noise_data = glob(self.bg_noise_dir, "*.wav") index_chosen_bg_file = int(len(bg_noise_data) * np.random.random()) x_bg, sr_bg = load_audio(os.path.join(self.bg_noise_dir, bg_noise_data[index_chosen_bg_file])) x_bg_rand = x_bg[int(len(x_bg) * np.random.random()):] while input_length > len(x_bg_rand): x_bg_rand = np.concatenate([x_bg_rand, x_bg]) if len(x_bg_rand) > input_length: x_bg = x_bg_rand[:input_length] x = x + (x_bg * self.bg_noise_volume) if self.volume: x = x * self.volume return x, sr class Iterator(keras_utils.Sequence): """Base class for audio data iterators. """ def __init__(self, n, batch_size, shuffle, seed): self.n = n self.batch_size = batch_size self.seed = seed self.shuffle = shuffle self.batch_index = 0 self.epochs = 0 self.total_batches_seen = 0 self.lock = threading.Lock() self.index_array = None self.index_generator = self._flow_index() def _set_index_array(self): self.index_array = np.arange(self.n) if self.shuffle: self.index_array = np.random.permutation(self.n) def __getitem__(self, idx): if idx >= len(self): raise ValueError('Asked to retrieve element {idx}, ' 'but the Sequence ' 'has length {length}'.format(idx=idx, length=len(self))) if self.seed is not None: np.random.seed(self.seed + self.total_batches_seen) self.total_batches_seen += 1 if self.index_array is None: self._set_index_array() index_array = self.index_array[self.batch_size * idx: self.batch_size * (idx + 1)] return self._get_batches_of_transformed_samples(index_array) def __len__(self): return (self.n + self.batch_size - 1) // self.batch_size # round up def on_epoch_end(self): self.epochs += 1 self._set_index_array() def reset(self): self.batch_index = 0 def _flow_index(self): # Ensure self.batch_index is 0. self.reset() while 1: if self.seed is not None: np.random.seed(self.seed + self.total_batches_seen) if self.batch_index == 0: self._set_index_array() current_index = (self.batch_index * self.batch_size) % self.n if self.n > current_index + self.batch_size: self.batch_index += 1 else: self.batch_index = 0 self.total_batches_seen += 1 yield self.index_array[current_index: current_index + self.batch_size] def __iter__(self): # Needed if we want to do something like: # for x, y in data_gen.flow(...): return self def __next__(self, *args, **kwargs): return self.next(*args, **kwargs) def _get_batches_of_transformed_samples(self, index_array): """Gets a batch of transformed samples. # Arguments index_array: Array of sample indices to include in batch. # Returns A batch of transformed samples. """ raise NotImplementedError class DataFrameIterator(Iterator): """Iterator capable of reading audio data from the dataframe. # Arguments audio_data_generator: Instance of `AudioDataGenerator` to use for transformations audio data. dataframe_data: DataFrame. The dataframe of audio data. It must contain 3 columns: transcript, wav_filename, wav_filesize. batch_size: Int (default: 32). Size of a batch/ sorting: None or string. Sorts audio data by size in ascending (asc) or descending (desc) order. save_to_dir: None or str (default: None). This allows you to optionally specify a directory to which to save the augmented audio data being generated (useful for listening what you are doing). save_prefix: Str (default: `''`). Prefix to use for filenames of saved audio data (only relevant if `save_to_dir` is set). stuffing: Float (default: 0.). Range from -1 to 1. The value that fills the audio when the size increases. top_count: None or int. Number of first audio from the dataset used for fitting. seed: Int (default: None). """ def __init__(self, audio_data_generator, dataframe_data=None, batch_size=32, sorting=None, save_to_dir=None, save_prefix='', stuffing=0., top_count=None, shuffle=None, seed=None): self.dataframe_data = dataframe_data self.sorting = sorting self.top_count = top_count self.audio_data_generator = audio_data_generator self.save_prefix = save_prefix self.save_to_dir = save_to_dir self.stuffing = stuffing self.shuffle = shuffle if isinstance(self.dataframe_data, pd.DataFrame): if self.dataframe_data.columns.size != 3: raise ValueError("Your dataframe must have this columns: transcript, wav_filename, wav_filesize") self.dataframe_data.columns = np.arange(len(self.dataframe_data.columns)) else: raise ValueError("Pass the dataframe in this parameter.") if 1. < stuffing < -1.: raise ValueError("Stuffing must be in the range from -1 to 1.") if self.sorting: if self.sorting not in ('asc', 'desc'): raise ValueError("sorting can be: 'asc' or 'desc'") if self.sorting == 'asc': ascend = True elif self.sorting == 'desc': ascend = False self.dataframe_data.sort_values([2], ascending=ascend, inplace=True) if self.top_count: self.dataframe_data = self.dataframe_data.head(self.top_count) self.samples = len(self.dataframe_data) if self.sorting: self.dataframe_data.index = range(self.samples) if self.save_to_dir: if not os.path.exists(self.save_to_dir): os.makedirs(self.save_to_dir) super(DataFrameIterator, self).__init__(self.samples, batch_size, self.shuffle, seed) def _get_batches_of_transformed_samples(self, index_array): print("Batch index:", self.batch_index) index_array.sort() # find max size in batch filtered_df = self.dataframe_data.loc[self.dataframe_data.index.isin(index_array)] bigfile_in_batch = filtered_df.loc[filtered_df[2].idxmax()] max_audiosize_in_batch = int(bigfile_in_batch[2]) # when stretching slow down the audio we change max_audiosize_in_batch by stretch rate if self.audio_data_generator.stretch and (self.audio_data_generator.stretch < 1): max_audiosize_in_batch = int(max_audiosize_in_batch * (1 + self.audio_data_generator.stretch)) # when shift is happens we change max_audiosize_in_batch accordingly if self.audio_data_generator.shift: _, max_sr = load_audio(bigfile_in_batch[1]) max_audiosize_in_batch = int(max_audiosize_in_batch + (self.audio_data_generator.shift * max_sr)) batch_x = np.zeros( (len(index_array),) + (max_audiosize_in_batch,), dtype=backend.floatx()) batch_y = [0] * len(index_array) for i, j in enumerate(index_array): current_audiofile = self.dataframe_data.iloc[j] y = current_audiofile[0] x, sr = load_audio(current_audiofile[1]) if len(x) < max_audiosize_in_batch: x = np.pad(x, (0, max(0, int(max_audiosize_in_batch - len(x)))), "constant", constant_values=(self.stuffing)) x, sr = self.audio_data_generator.transform(x, sr) # optionally save augmented audio to disk for debugging purposes if self.save_to_dir: fname = '{prefix}_{index}_{hash}.wav'.format( prefix=self.save_prefix, index=j, hash=np.random.randint(1e7)) write_wav(os.path.join(self.save_to_dir, fname), x, sr) batch_x[i] = x batch_y[i] = y return batch_x, batch_y def next(self): """For python 2.x. # Returns The next batch. """ with self.lock: index_array = next(self.index_generator) return self._get_batches_of_transformed_samples(index_array)
true
cd0bedd73f04045061f1a3b144ff67478e33149f
Python
alexbyz/HW070172
/l04/ch3/ex1.py
UTF-8
560
4.3125
4
[]
no_license
#exercise 1 #Alexander Huber #volume and surface of a sphere # V = 4/3pi*r^2 # A = 4pi * r^2 # (unit) as it does not matter for the programm if its in cm, inches or some fantasy-unit import math def main(): print("calculates the Surface Area and the Volume of a Sphere\n") rad = float(input("what is the radius? ")) vol = 4/3 * math.pi * rad**3 sur = 4 * math.pi * rad**2 print("The surface of a sphere with a radius of ",rad, "(unit) is ", sur, "(unit^2), the volume is", vol, "(unit^3)\n") input("Press a key to end the programm") main()
true
d6e4a3476bf2ec2c36200932ad85ade811a5bd5e
Python
jonathan-mothe/ListaDeExercicios
/funcoes/ex007.py
UTF-8
557
3.609375
4
[]
no_license
def valor_pagamento(valor, dias_atraso): if (valor < 0): return None if (dias_atraso > 0): multa = valor * 0.03 adicional_atraso = valor * (dias_atraso * 0.01) return valor + multa + adicional_atraso else: return valor # Entrada de Dados valor = 1 while (valor != 0): valor = float(input('Informe o valor da prestacao: ')) if (valor != 0): dias_atraso = int(input('Informe a quantidade de dias de atraso: ')) print("Valor a ser pago: %.2f" % valor_pagamento(valor, dias_atraso))
true
9692503ae6fbcabc5b8259705bc4bed26db0df37
Python
atharvac/Celeste-TFNeuralNet
/data_manip.py
UTF-8
694
2.765625
3
[]
no_license
import pandas as pd import numpy as np import cv2 from collections import Counter import random combos = ['L', 'R', 'C', 'X', 'Z', 'CR', 'CU', 'CL', 'CD', 'UZ', 'DZ', 'RX', 'LX', 'RUX', 'LUX', 'DRX', 'DLX', 'CDRX', 'NaN'] data = np.load("training_data.npy", allow_pickle=True) d = pd.DataFrame(data) count = Counter(d[1].apply(np.argmax)) print(count) for x in count.keys(): print(f"{combos[x]} : {count[x]}, ", end='') print() np.random.shuffle(data) idxs = [] for i, x in enumerate(data): if np.argmax(x[1]) == 1: idxs.append(i) print(f"\nIndexes are {len(idxs)}") print(f"Total Data: {len(data)}") #data = np.delete(data, idxs[:1600], axis=0) #np.save("training_data", data)
true
1fce555b3b409a52b72523771d426a0876283985
Python
Raghibshams456/Python_building_blocks
/Numpy_worked_examples/032_numpy_cauchy.py
UTF-8
359
3.34375
3
[]
no_license
""" Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) """ import numpy as np X = np.arange(8) Y = X + 0.5 C = 1.0 / np.subtract.outer(X, Y) print(np.linalg.det(C)) """ PS C:\Users\SP\Desktop\DiveintoData\Numpy> python .\032_numpy_cauchy.py 3638.163637117973 PS C:\Users\SP\Desktop\DiveintoData\Numpy> """
true
c4097559ee470090205ae8a4776acc0748dadeac
Python
tugra-alp/Data-Science-Projects
/Project1-Bengaluru House Project/preProcessingPart.py
UTF-8
4,934
3.453125
3
[]
no_license
#%% import pandas as pd import numpy as np from matplotlib import pyplot as plt import matplotlib #%% # link of dataset = 'https://www.kaggle.com/amitabhajoy/bengaluru-house-price-data' data = pd.read_csv("Bengaluru_House_Data.csv") #%% ---- DATA CLEANING ---- # Removing unnecessary features data = data.drop(['area_type','society','balcony','availability'], axis = 'columns') #%% # data.isnull().sum() data = data.dropna() #%% # 4 BHK = 4 Bedroom - bhk (Bedrooms Hall Kitchen) # tokenize example : data['size'][1].split(' ')[0] data['BHK'] = (data['size'].apply(lambda x: x.split(' ')[0])).astype(float) #%% to detect range values in total_sqft def is_float(x): try: float(x) except: return False return True data[~data['total_sqft'].apply(is_float)].head() #%% to convert range values to single value (taking mean of them) in total_sqft def convert_sqft_to_num(x): tokens = x.split('-') if len(tokens) == 2: return (float(tokens[0])+float(tokens[1]))/2 try: return float(x) except: return None #convert_sqft_to_num('1120 - 1145') : an example to see how func works df = data.copy() df['total_sqft'] = df['total_sqft'].apply(convert_sqft_to_num) df = df[df.total_sqft.notnull()] #%% ---------- Feature Engineering ------------ df1 = df.copy() #this new feature will help outlier detection df1['per_ft_price'] = df1['price']*100000 / df1['total_sqft'] #%% Dim. Reduction for 'location' column. # Any location having less than 10 data points should be tagged as "other" location. df1.location = df1.location.apply(lambda x: x.strip()) location_stats = df1['location'].value_counts(ascending=False) less_than_10_loc = location_stats[location_stats <= 10] df1.location = df1.location.apply(lambda x: 'other' if x in less_than_10_loc else x) #%% # There are some disproportion between size and total_sqft # for per bedroom , 300 sq ft is expected. (300 sq feet = 27.8 m^2) # i.e 2 bhk apartment is minimum 600 sqft. df1[(df1.total_sqft/df1.BHK)<300].head() # i.e; BHK:6 total_sqft: 1020.0 is data error. df2 = df1[~(df1.total_sqft/df1.BHK<300)] # without data errors ( 744 points removed) #%% Outlier Removal Using Standard Deviation and Mean # removing outliers for per location and according to their std & mean def remove_pfp_outliers(df): df_out = pd.DataFrame() for key, subdf in df.groupby('location'): m = np.mean(subdf.per_ft_price) st = np.std(subdf.per_ft_price) reduced_df = subdf[(subdf.per_ft_price>(m-st)) & (subdf.per_ft_price<=(m+st))] df_out = pd.concat([df_out,reduced_df],ignore_index=True) return df_out df3 = remove_pfp_outliers(df2) #%% comparing house price 2 and 3 BHK with given a location to DETECT another outliers def plot_scatter_chart(df,location): bhk2 = df[(df.location==location) & (df.BHK==2)] bhk3 = df[(df.location==location) & (df.BHK==3)] matplotlib.rcParams['figure.figsize'] = (15,10) plt.scatter(bhk2.total_sqft,bhk2.price,color='blue',label='2 BHK', s=50) plt.scatter(bhk3.total_sqft,bhk3.price,marker='+', color='green',label='3 BHK', s=50) plt.xlabel("Total Square Feet Area") plt.ylabel("Price (Lakh Indian Rupees)") plt.title(location) plt.legend() plot_scatter_chart(df3,"Rajaji Nagar") #%% i.e: we should remove the price of 3 bedroom apartment is less than 2 bedroom apartment (with same square ft area) def remove_bhk_outliers(df): exclude_indices = np.array([]) for location, location_df in df.groupby('location'): bhk_stats = {} for bhk, bhk_df in location_df.groupby('BHK'): bhk_stats[bhk] = { 'mean': np.mean(bhk_df.per_ft_price), 'std': np.std(bhk_df.per_ft_price), 'count': bhk_df.shape[0] } for bhk, bhk_df in location_df.groupby('BHK'): stats = bhk_stats.get(bhk-1) if stats and stats['count']>5: exclude_indices = np.append(exclude_indices, bhk_df[bhk_df.per_ft_price<(stats['mean'])].index.values) return df.drop(exclude_indices,axis='index') df4 = remove_bhk_outliers(df3) df4.shape # removed 2925 outlier #%% plot same scatter after removing outliers plot_scatter_chart(df4,"Rajaji Nagar") #%% bathroom outliers # total bath = total bed + 1 max (Anything above that is an outlier or a data error and can be removed) df4[df4.bath>df4.BHK+2] # to see outliers df5 = df4[df4.bath<=df4.BHK+1] #%% after preprocessing we dont need some features anymore df6 = df5.drop(['size','per_ft_price'],axis='columns') #per_ft_price is used only outlier detection #'BHK' feature instead of 'size' #%% Use One Hot Encoding For Location col. dummies = pd.get_dummies(df6.location) df7 = pd.concat([df6,dummies.drop('other',axis='columns')],axis='columns') #%% saving pre-processed dataframe as csv file finaldf = df7.drop('location',axis='columns') #finaldf.to_csv("preProcessedData.csv")
true