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
4248ae07c3fef6fe774a0a34072cfb181221b424
Python
YeungJonathan/Project_Euler
/14.py
UTF-8
433
2.921875
3
[]
no_license
def collatz(num): if num % 2 == 1: num = 3 * num + 1 else: num = num // 2 return num check = {1:1} maxValue = 1 maxNum = 1 for num in range(2,2000001): item = num count = 1 final = 0 while item != 1: if item in check.keys(): count = count + check[item] break else: item = collatz(item) count = count + 1 if count > maxValue: maxNum = num maxValue = count check[num] = count print(maxNum)
true
1efe56618600ecbcd0d36d9f44957671db306d27
Python
gaoyucai/Python_Project
/Python_day2/login.py
UTF-8
1,538
3.421875
3
[]
no_license
# Author:GaoYuCai #导入第三方库时,自动在里进行查找 #默认第三方库存放在site-packags中 #Python解释性语言 #数据类型初识 #1.数字 #2.type()查看数据的数据类型 #bool类型 1表示True 0 表示 False #三元运算 #例子: result= 值1 if 条件 else 值2 #进制 二进制 八进制 十进制 十六进制 #bytes 数据类型 字节数据类型不同于字符串 #把二级制 转换成字符串 --> decode #把字符串 转换成 二进制 --> encode #masg="我爱北京天安门" #print(masg.encode(encoding="utf-8")) #print(masg.encode().decode()) names=["zhangyang","guyun","xuliangchen","shhao"] print(names[0]) print(names[1:2])#顾头不顾尾,切片 print(names[-2:])#机器数数是从左往右数的 names.append("leihaidong") names.insert(0,"gaoyucai") print(names) #name=names.pop() #del names[2] #name=names.remove("gaoyucai") #print(name) #print(names) #count=names.index("leihaidong") #print(names[count]) #print(names.count("gaoyucai")) #print(names.clear())#清空列表 #names.reverse()#翻转 #names.sort(reverse=True) #print(names) #names.extend(name2) #del name2 #name2=names.copy() #print(names) #print(name2) #names[0]="高宇才" #print(names) #print(name2)#浅copy仅仅copy第一层 #name3=names[:] #print(name3) #import copy #name4=copy.copy(names) #name5=copy.deepcopy(names) #print(names[0:-1:2])#循环跳着打印 '''三种实现浅copy的方法: import copy person=['name',['a',100]] p1=copy.copy(person) p2=person[:] p3=list(person) '''
true
95587d872deb31cc6bf15ec5fb99d25407bc9370
Python
jonfelix1/alegov2
/src/main.py
UTF-8
3,175
2.921875
3
[]
no_license
import cv2 import glob import numpy as np import multiprocessing import time from numba import jit # import matplotlib.pyplot as plt from tempfile import TemporaryFile arrV = TemporaryFile() # Operators @jit(nopython = True) def euclidean_distance(arrVector1, arrVector2): # Besar dari arrVector1 dan arrVector2 harus sama sum = 0 for i in range(len(arrVector1)): sum += (arrVector1[i] - arrVector2[i])**2 return sum**0.5 @jit(nopython = True) def cosine_similarity(arrVector1, arrVector2): # Besar dari arrVector1 dan arrVector2 harus sama v = 0 w = 0 vw = 0 for i in range(len(arrVector1)): v += arrVector1[i]**2 w += arrVector2[i]**2 vw += arrVector1[i]*arrVector2[i] v = v**0.5 w = w**0.5 return vw/(v*w) # Load data agak lama gara-gara itemnya 10770 # cv2.imshow('Pic',img_database[3]) # cv2.waitKey(0) def extract_features(image, vector_size=32): alg = cv2.KAZE_create() kps = alg.detect(image) kps = sorted(kps, key = lambda x: -x.response)[:vector_size] kps, desc = alg.compute(image, kps) desc = desc.flatten() needed_size = (vector_size * 64) if (desc.size < needed_size): desc = np.concatenate([desc, np.zeros(needed_size - desc.size)]) # except cv2.error as e: # print (("Error: "), e) # return None return desc def best10match_cosine(img, arrDescription, arrImg): img_f = extract_features(img) temp = [] for i in range(len(arrDescription)): temp.append(cosine_similarity(img_f, arrDescription[i])) cv2.imshow('AA', img) cv2.waitKey(0) top_10_idx = np.argsort(temp)[-10:] for i in top_10_idx: cv2.imshow('Pic', arrImg[i]) cv2.waitKey(0) return def best10match_euclid(img, arrDescription, arrImg): img_f = extract_features(img) temp = [] for i in range(len(arrDescription)): temp.append(euclidean_distance(img_f, arrDescription[i])) cv2.imshow('AA', img) cv2.waitKey(0) top_10_idx = np.argsort(temp)[-10:] for i in top_10_idx: cv2.imshow('Pic', arrImg[i]) cv2.waitKey(0) return def main(): img_database = [] for img in glob.glob("img/*.jpg"): img_database.append(cv2.imread(img)) print("Image loading done") img_description = [] for i in range(100): img_description.append(extract_features(img_database[i])) # for i in range(5): # print(img_description[i]) # Save file dan load file (ntar cuman load) np.save(arrV, img_description) _ = arrV.seek(0) a = np.load(arrV) print(euclidean_distance(img_description[0], img_description[2])) print(cosine_similarity(img_description[0], img_description[2])) print(len(img_description[0])) print(euclidean_distance(a[0], a[2])) print(cosine_similarity(a[0], a[2])) print(len(a[0])) # Testing (contoh) img = cv2.imread("img/Test/zendaya14.jpg") # best10match_cosine(img,img_description,img_database) best10match_euclid(img,img_description,img_database) starttime = time.time() main() print('That took {} seconds'.format(time.time()-starttime))
true
506752f0c19db816ccaa14e2d20e3e8e30dc9df0
Python
syp0000/ooowah
/hard.py
UTF-8
463
3.765625
4
[]
no_license
#### input: list #### [1,4,5,2,3,4,2,4,6,6,2,5] #### output: # Odd Number: 5 # Even Numnber: #### def o(l): even = 0 odd = 0 for x in l: if x % 2 == 0: even = even + 1 else: odd = odd + 1 print("even: " + str(even)) print("odd: " + str(odd)) print("total: " + str(odd+even)) print("lengh: " + str(len(l))) if __name__== "__main__": lhhh = [1,4,5,2,3,4,2,4,6,6,2,5] o(lhhh)
true
74dcc17308c27ea58c66d1bf835e279a7186b704
Python
CptIdea/labs6
/lab9/n1.py
UTF-8
1,780
3.328125
3
[]
no_license
import io import PySimpleGUI as sg def getPretty(students): return '\n'.join([x[0] + ' - ' + ' '.join(x[1]) for x in students.items()]) def addStudent(students): layout = [ [sg.Text("#"), sg.Input(default_text=f'{len(students) + 1}', key='num', size=(0, 10))], [sg.Text("ФИО:"), sg.Input(key='name', size=(0, 20), default_text='Александров Александр Александрович')], [sg.Text("Возраст:"), sg.Input(key='age', default_text='20', size=(0, 10)), sg.Text("Группа:"), sg.Input(key='group', default_text='ВКБ12', size=(0, 10))], [sg.Button('OK')] ] ans_window = sg.Window(layout=layout, title='Сделай свой выбор!') while True: event, values = ans_window.read() if event == sg.WINDOW_CLOSED or event == 'Назад': ans_window.close() return if event == 'OK': students[values['num']] = [values['name'],values['age'],values['group']] break ans_window.close() def window(): sg.theme('LightGray1') layout = [ [sg.Button("Вывод")], [sg.Text("*здесь появится ответ*", key='ans', size=(70, 0))], [sg.Button("Добавить кого-нибудь", key='add')] ] nom_window = sg.Window(title="NomSelector3000", layout=layout) students = { '1': ['Иванов Иван Иванович', '23', 'ВКБ22'], '2': ['Петров Петр Петрович', '23', 'ВКБ23'], '3': ['Семенов Семен Семенович', '23', 'ВКБ21'] } while True: event, values = nom_window.read() if event == sg.WINDOW_CLOSED or event == 'Назад': break if event == 'add': addStudent(students) nom_window['ans'].update(f'{getPretty(students)}')
true
63cb632e0c3e7c6a35f43725fad0d693422c55f3
Python
crcrpar/chainer
/chainer/distributions/chisquare.py
UTF-8
2,110
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import numpy import chainer from chainer.backends import cuda from chainer import distribution from chainer.functions.math import digamma from chainer.functions.math import exponential from chainer.functions.math import lgamma from chainer.utils import cache class Chisquare(distribution.Distribution): """Chi-Square Distribution. The probability density function of the distribution is expressed as .. math:: p(x;k) = \\frac{1}{2^{k/2}\\Gamma(k/2)}x^{k/2-1}e^{-x/2} Args: k(:class:`~chainer.Variable` or :ref:`ndarray`): Parameter of distribution. """ def __init__(self, k): super(Chisquare, self).__init__() self.__k = k @cache.cached_property def k(self): return chainer.as_variable(self.__k) @cache.cached_property def _half_k(self): return 0.5 * self.k @property def batch_shape(self): return self.k.shape @cache.cached_property def entropy(self): return ( self._half_k + numpy.log(2.) + lgamma.lgamma(self._half_k) + (1 - self._half_k) * digamma.digamma(self._half_k)) @property def event_shape(self): return () def log_prob(self, x): return ( - lgamma.lgamma(self._half_k) - self._half_k * numpy.log(2.) + (self._half_k - 1) * exponential.log(x) - 0.5 * x) @cache.cached_property def mean(self): return self.k @property def params(self): return {'k': self.k} def sample_n(self, n): xp = chainer.backend.get_array_module(self.k) if xp is cuda.cupy: eps = xp.random.chisquare( self.k.data, (n,)+self.k.shape, dtype=self.k.dtype) else: eps = xp.random.chisquare( self.k.data, (n,)+self.k.shape).astype(self.k.dtype) noise = chainer.Variable(eps) return noise @property def support(self): return 'positive' @cache.cached_property def variance(self): return 2 * self.k
true
dd43e3451ac55a5e4b6fcaab887cf2cee7a933e6
Python
hinderling/CIED
/library/functions.py
UTF-8
5,372
2.5625
3
[]
no_license
from glob import glob from os.path import basename from PIL import Image import numpy as np from skimage import exposure from skimage.filters.rank import enhance_contrast from matplotlib import pyplot as plt from skimage.morphology import disk, binary_opening, skeletonize from skimage.filters.rank import mean_bilateral from math import ceil, sqrt from skimage.morphology import disk, binary_dilation import csv import math from math import ceil, floor import statistics def preprocess(image): """ apply adaptive histgram equalization, sharpening filter may not be needed Pixel values are now floats between 0 and 1 """ image = exposure.equalize_adapthist(image) return image def show(image, title=None): """ Show image :param image: numpy image :param title: Title :return: None """ plt.imshow(image) plt.title(title) plt.show() return None def showhist(image): """ Display histogram for image :param image: numpy image :return: None """ plt.subplot(121) plt.imshow(image, cmap=plt.get_cmap('gray')) plt.subplot(122) plt.hist(image.flatten(), 256, range=(0, 1)) plt.show() return None def binary_filter(image, threshold=False, percentage=0.6, size=15): """ :param image: :param threshold: set threshold manually :param percentage: get brightest percentage of image :return: biary mask """ if not threshold: ord_img = np.sort(image.flatten()) value = ceil(len(ord_img) * percentage) if value < len(ord_img): threshold = ord_img[value] else: print("threshold too high") threshold = 0.5 binary = image > threshold binary = binary_opening(binary, selem=disk(size)) return binary def order(blobs, tolerance = 0, blob = True): """ :param blobs: Result from blob detection :return: matrix of the format: [[1 x1 y1] [2 x2 y2] [ ... ] [12 x12 y12] """ chain = [] options = [] if blob: angles_vec = angles(blobs) start = int(angles_vec[0][0]) for i, blob in enumerate(blobs): y, x, r = blob if i == start: chain.append((x, y)) else: options.append((x, y)) else: for i, element in enumerate(blobs): c,x,y = element if i == 11: chain.append((x, y)) # elif i == 10: else: options.append((x, y)) all_chains = [] all_options = [] # find second point(s) edge = 0 # ground truth min_dist = DISTANCES[edge][0] max_dist = DISTANCES[edge][1] mean_dist = DISTANCES[edge][1] for option in options: last = chain[-1] l = distance(last, option) if floor(min_dist)-(mean_dist*tolerance/100) < l < ceil(max_dist)+(mean_dist*tolerance/100): temp_chain = chain.copy() temp_chain.append(option) temp_options = options.copy() temp_options.remove(option) all_chains.append(temp_chain) all_options.append(temp_options) if len(all_chains) == 0: print("Order of points could not be determined") numbers = [x + 1 for x in range(len(chain))] chain = np.column_stack([numbers, chain]) return chain # else: # chain = all_chains[0] # numbers = [x + 1 for x in range(len(chain))] # chain = np.column_stack([numbers, chain]) # return chain # find 3rd - 12th points while all_chains: options = all_options.pop() chain = all_chains.pop() edge = len(chain)-1 # ground truth min_dist = DISTANCES[edge][0] max_dist = DISTANCES[edge][1] mean_dist = DISTANCES[edge][2] min_angle = DISTANCES[edge - 1][0] max_angle = DISTANCES[edge - 1][1] mean_angle = DISTANCES[edge - 1][2] # comparing angles x1, y1 = chain[-2] x2, y2 = chain[-1] for option in options: x3, y3 = option y_v1 = y2 - y1 x_v1 = x2 - x1 v1 = (x_v1, y_v1) y_v2 = y3 - y2 x_v2 = x3 - x2 v2 = (x_v2, y_v2) a = angle(v1, v2) l = distance((x2, y2), option) if floor(min_dist)-(mean_dist*tolerance/100) < l < ceil(max_dist)+(mean_dist*tolerance/100) \ and floor(min_angle)-(mean_angle*tolerance/100) < a < ceil(max_angle)+(mean_angle*tolerance/100): temp_chain = chain.copy() temp_options = options.copy() temp_chain.append(option) temp_options.remove(option) all_chains.append(temp_chain) all_options.append(temp_options) if len(temp_chain) == 12: print("success") chain = temp_chain numbers = [x + 1 for x in range(len(chain))] chain = np.column_stack([numbers, chain]) return chain print(len(all_chains)) print("Order of points could not be determined") numbers = [x+1 for x in range(len(chain))] chain = np.column_stack([numbers, chain]) return chain
true
86f04f224946268518810a98814b83f08fe30366
Python
iqeeingh/chat
/r2.py
UTF-8
1,698
3.296875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Feb 13 10:39:29 2021 @author: wayne count person speak workd number tip: 前3 n[:3]=0~2、中間2~4 n[2:4]、結尾 n[-2:] """ def read_file (filename): lines = [] #宣告清單 with open (filename , 'r', encoding = 'utf-8-sig') as f: for line in f: lines.append(line.strip()) #strip del /n return lines def convert(lines): person = None Allen_count = 0 Allen_Sticker_count = 0 Allen_img_count = 0 Viki_count = 0 Viki_Sticker_count = 0 Viki_img_count = 0 for line in lines: s = line.split(' ') time = s[0] name = s[1] if name == 'Allen': if s[2] =='貼圖': Allen_Sticker_count += 1 elif s[2] == '圖片': Allen_img_count += 1 else: for m in s[2:]: Allen_count += len(m) elif name == 'Viki': if s[2] =='貼圖': Viki_Sticker_count += 1 elif s[2] == '圖片': Viki_img_count += 1 else: for m in s[2:]: Viki_count += len(m) print('Allen說了', Allen_count ,'字,傳了', Allen_Sticker_count, '個貼圖,傳了',Allen_img_count, '張圖片' ) print('Viki說了', Viki_count,'字,傳了', Viki_Sticker_count, '個貼圖,傳了', Viki_img_count, '張圖片' ) def write_file(filename, lines): with open (filename , 'w')as f: for line in lines: f.write(line + '\n') def main(): lines = read_file('LINE-Viki.txt') lines = convert(lines) # write_file('output.txt',lines) main()
true
280aa6565176d17d77e7b89ae231b30316850f1b
Python
sandeep82945/opiniondigest
/src/beam_search.py
UTF-8
9,824
2.625
3
[ "Apache-2.0" ]
permissive
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch class Search(object): def __init__(self, vocab_size, pad, unk, eos): self.pad = pad self.unk = unk self.eos = eos self.vocab_size = vocab_size self.scores_buf = None self.indices_buf = None self.beams_buf = None def _init_buffers(self, t): if self.scores_buf is None: self.scores_buf = t.new() self.indices_buf = torch.LongTensor().to(device=t.device) self.beams_buf = torch.LongTensor().to(device=t.device) def step(self, step, lprobs, scores): """Take a single search step. Args: step: the current search step, starting at 0 lprobs: (bsz x input_beam_size x vocab_size) the model's log-probabilities over the vocabulary at the current step scores: (bsz x input_beam_size x step) the historical model scores of each hypothesis up to this point Return: A tuple of (scores, indices, beams) where: scores: (bsz x output_beam_size) the scores of the chosen elements; output_beam_size can be larger than input_beam_size, e.g., we may return 2*input_beam_size to account for EOS indices: (bsz x output_beam_size) the indices of the chosen elements beams: (bsz x output_beam_size) the hypothesis ids of the chosen elements, in the range [0, input_beam_size) """ raise NotImplementedError def set_src_lengths(self, src_lengths): self.src_lengths = src_lengths class BeamSearch(Search): def __init__(self, vocab_size, pad, unk, eos): super().__init__(vocab_size, pad, unk, eos) def step(self, step, lprobs, scores, output_beam_size): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() if step == 0: # at the first step all hypotheses are equally likely, so use # only the first beam lprobs = lprobs[:, ::beam_size, :].contiguous() else: # make probs contain cumulative scores for each hypothesis lprobs.add_(scores[:, :, step - 1].unsqueeze(-1)) torch.topk( lprobs.view(bsz, -1), k=min( # Take the best 2 x beam_size predictions. We'll choose the first # beam_size of these which don't predict eos to continue with. output_beam_size * 2, lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad ), out=(self.scores_buf, self.indices_buf), ) torch.div(self.indices_buf, vocab_size, out=self.beams_buf) self.indices_buf.fmod_(vocab_size) return self.scores_buf, self.indices_buf, self.beams_buf class BeamSearchNMT(Search): """Google's Neural Machine Translation beam search implementation: https://arxiv.org/pdf/1609.08144.pdf """ def __init__(self, vocab_size, pad, unk, eos, alpha=0.6): super().__init__(vocab_size, pad, unk, eos) self.alpha = alpha def step(self, step, lprobs, scores, output_beam_size): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() # Calculate if step == 0: # at the first step all hypotheses are equally likely, so use # only the first beam lprobs = lprobs[:, ::beam_size, :].contiguous() else: # make probs contain cumulative scores for each hypothesis lprobs.add_(scores[:, :, step - 1].unsqueeze(-1)) # Update by length penalty length_penalty = self._length_penalty(step) scores = lprobs / length_penalty torch.topk( scores.view(bsz, -1), k=min( # Take the best 2 x beam_size predictions. We'll choose the first # beam_size of these which don't predict eos to continue with. output_beam_size * 2, scores.view(bsz, -1).size(1) - 1, # -1 so we never select pad ), out=(self.scores_buf, self.indices_buf), ) torch.div(self.indices_buf, vocab_size, out=self.beams_buf) self.indices_buf.fmod_(vocab_size) return self.scores_buf, self.indices_buf, self.beams_buf def _length_penalty(self, step): """Length penalty: lp(Y) = ((5+|Y|)^alpha)/(5+1)^alpha Args: step: the current search step, starting at 0 Returns: length_penalty: float length penalty of current step. """ return ((step+1)/6.0)**self.alpha def _coverage_penalty(self, attn): """Coverage penalty: cp(X;Y) =beta * sum(log(min(attn_i_j, 1.0))) Args: attn: (bsz x beam_size x src_seqlen) the total attention prob of i-th source word. Return: coverage_penalty: (bsz x beam_size) or 0.0 the coverage penalty for each beam. TOOD (@xiaolan): finish implementation """ return 0.0 class DiverseBeamSearch(Search): """Diverse Beam Search. See "Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models" for details. We only implement the Hamming Diversity penalty here, which performed best in the original paper. Recommended setting in original paper: num_groups: "Setting G=beam_size allows for the maximum exploration of the space," diversity_strength: "We find a wide range of λ values (0.2 to 0.8) work well for most tasks and datasets." """ def __init__(self, vocab_size, pad, unk, eos, num_groups, diversity_strength=0.5): super().__init__(vocab_size, pad, unk, eos) self.num_groups = num_groups self.diversity_strength = -diversity_strength self.diversity_buf = None self.beam = BeamSearch(vocab_size, pad, unk, eos) def step(self, step, lprobs, scores, output_beam_size): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() num_groups = self.num_groups if beam_size > 1 else 1 if beam_size % num_groups != 0: raise ValueError( 'DiverseBeamSearch requires --beam to be divisible by the number of groups' ) # initialize diversity penalty if self.diversity_buf is None: self.diversity_buf = lprobs.new() torch.zeros(lprobs[:, 0, :].size(), out=self.diversity_buf) scores_G, indices_G, beams_G = [], [], [] for g in range(num_groups): lprobs_g = lprobs[:, g::num_groups, :] scores_g = scores[:, g::num_groups, :] if step > 0 else None # apply diversity penalty if g > 0: lprobs_g = torch.add(lprobs_g, self.diversity_strength, self.diversity_buf.unsqueeze(1)) else: lprobs_g = lprobs_g.contiguous() scores_buf, indices_buf, beams_buf = self.beam.step(step, lprobs_g, scores_g, output_beam_size) beams_buf.mul_(num_groups).add_(g) scores_G.append(scores_buf.clone()) indices_G.append(indices_buf.clone()) beams_G.append(beams_buf.clone()) # update diversity penalty self.diversity_buf.scatter_add_( 1, indices_buf, self.diversity_buf.new_ones(indices_buf.size()) ) # interleave results from different groups self.scores_buf = torch.stack(scores_G, dim=2, out=self.scores_buf).view(bsz, -1) self.indices_buf = torch.stack(indices_G, dim=2, out=self.indices_buf).view(bsz, -1) self.beams_buf = torch.stack(beams_G, dim=2, out=self.beams_buf).view(bsz, -1) return self.scores_buf, self.indices_buf, self.beams_buf class NgramBlocking: def __init__(self, no_repeat_ngram_size): """ Ngram blocking: avoid generating sequences with repetitive n-grams. """ self.no_repeat_ngram_size = no_repeat_ngram_size def update(self, step, sequence, lprobs): """ Update lprobs: set token probability as -math.inf for repetitive n-grams """ blocked_ngrams = self._gen_blocked_ngram(sequence[:step+1]) banned_tokens = self._gen_banned_tokens(step, sequence, blocked_ngrams) lprobs[banned_tokens] = -math.inf return lprobs def _gen_blocked_ngram(self, sequence): """ Generate a dict of ngrams that already exist in previous sequence. e.g., Given a sequence of: [0, 1, 2, 3, 4] And no_repeat_ngram_size = 3, The blocked ngrams are: { (0, 1): [2] (1, 2): [3] (2, 3): [4] } Modified from https://github.com/pytorch/fairseq/sequence_generator.py#L338-L450 """ blocked_ngrams = {} for ngram in zip(*[sequence[i:].tolist() for i in range(self.no_repeat_ngram_size)]): blocked_ngrams[tuple(ngram[:-1])] = blocked_ngrams.get(tuple(ngram[:-1]), []) + [ngram[-1]] return blocked_ngrams def _gen_banned_tokens(self, step, sequence, blocked_ngrams): """ Generate tokens that should be banned for (step+1). """ banned_tokens = [] if step+2-self.no_repeat_ngram_size < 0: return banned_tokens ngram_index = tuple(sequence[step+2-self.no_repeat_ngram_size:step+1].tolist()) return blocked_ngrams.get(ngram_index, [])
true
e91fa52674ae5970108580a8359fc2f7106ffeb1
Python
hwhehr/zhouzhi
/zhouzhi/zhou/smt.py
UTF-8
1,045
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- import smtplib from email.mime.text import MIMEText def send_email(msg_to,url): smtp_ssl_port = 465 smtp_server = "smtp.qq.com" msg_from = "549537094@qq.com" smtp_password = "poltxmcsfqgkbcig" subject = "周知绑定邮箱" content=u"""" <p>用户您好,您的用户正在绑定周知邮箱,如果是您的用户请点击此链接,如果不是您的账户请不要管,如果链接无法点击清复制链接到浏览器地址栏中打开</p> <p><a href="http://118.89.217.235:8000/">绑定我的邮箱</a></p> <p>http://118.89.217.235:8000/%s</p> """%url msg = MIMEText(content, "html", 'utf-8') msg['Subject'] = subject msg['From'] = "周知官方账户" msg['To'] = msg_to server = smtplib.SMTP_SSL(smtp_server, smtp_ssl_port) server.login(msg_from, smtp_password) try: server.sendmail(msg_from, msg_to, msg.as_string()) print("发送成功") except Exception as e: print(e) print("发送失败") finally: server.quit() print("exit")
true
bcdca92900dfc8144cdb0554321c72c52f68ba99
Python
swarajd/WebAssemblyDisassembler
/scripts/parsemd.py
UTF-8
378
2.96875
3
[]
no_license
md = """| `i32.reinterpret/f32` | `0xbc` | | | | `i64.reinterpret/f64` | `0xbd` | | | | `f32.reinterpret/i32` | `0xbe` | | | | `f64.reinterpret/i64` | `0xbf` | | |""".split("\n") for line in md: parts = line.split("|") hex_ = parts[2].replace(' ', '').replace('`', '') name_ = parts[1].replace(' ', '').replace('`', '') print("\t{} : '{}',".format(hex_, name_))
true
362af75df5ba55c5bda79d4443ba4ebc8bbfbaad
Python
allanedgard/Cloud-Energy-Saver
/header.py
UTF-8
1,640
2.515625
3
[ "MIT" ]
permissive
#coding: utf-8 import requests, ast, os, time def get(): domain = 'Default' login = 'admin' password = '123456' project = 'admin' headers = {'Content-Type':'application/json'} body = """ { "auth": { "identity": { "methods": [ "password" ], "password": { "user": { "domain": { "name": \""""+ domain +"""\" }, "name": \""""+ login +"""\", "password": \""""+ password +"""\" } } }, "scope": { "project": { "domain": { "name": \""""+ domain +"""\" }, "name": \""""+ project +"""\" } } } } """ now = time.time() # timestamp atual try: modified = os.path.getmtime('token.txt') # última modificação do arquivo except: modified = 0 # caso o arquivo não exista, modified será zero, assim entrará no else para gerar o token if now - modified < 3600: file = open("token.txt", "r+") header = file.read() else: r = requests.post('http://controller:5000/v3/auth/tokens', data=body, headers=headers) token = r.headers['X-Subject-Token'] header = "{'X-Auth-Token':'"+token+"'}" # Dicionário com o Token que será utilizado no cabeçalho das consultas via API file = open("token.txt", "w+") file.write(header) file.close() header = ast.literal_eval(header) # Dicionário com o Token que será utilizado no cabeçalho das consultas via API return header
true
6f82315f7b0f0f9f5ce1a1d308b8af60500a0f77
Python
YWithT/PAT
/乙/1006.py
UTF-8
463
3.734375
4
[]
no_license
def printS(x): for i in range(0, x): print("S", end="") def printB(x): for i in range(0, x): print("B", end="") def printG(x): for i in range(0, x): print(i + 1, end="") a = input() if len(a) == 1: x = int(a) printG(x) if len(a) == 2: S = int(a[0]) G = int(a[1]) printS(S) printG(G) if len(a) == 3: B = int(a[0]) S = int(a[1]) G = int(a[2]) printB(B) printS(S) printG(G)
true
10029dcc9bfe6b0204d932503ccc0da792eeae36
Python
gidona18/hashcode
/2019/main.py
UTF-8
1,815
3.015625
3
[ "Apache-2.0" ]
permissive
from collections import namedtuple Pic = namedtuple('Pic', ['idx','type','tags']) def read_file(path): lines = [] with open(path, 'r') as f: lines = f.read().splitlines() lines = [line.split() for line in lines[1:]] pics = [Pic(idx, pic[0], pic[2:]) for idx, pic in enumerate(lines)] return (pics) def main(ipath, opath): # Read picture tags from file. pics = read_file(ipath) # Sort tags. idx = 0; while idx < len(pics): pics[idx] = Pic( pics[idx].idx, pics[idx].type, sorted(pics[idx].tags)) idx += 1 # Sort pics by tags. pics.sort(key=lambda p: p.tags) lst = [] idx = 0; while idx < len(pics): try: if pics[idx].type == 'H': lst.append([pics[idx]]) elif pics[idx].type == 'V' and pics[idx+1].type == 'H': pics[idx], pics[idx+1] = pics[idx+1], pics[idx] lst.append([pics[idx]]) elif pics[idx].type == 'V' and pics[idx+1].type == 'V': lst.append([pics[idx], pics[idx+1]]) idx += 1 except IndexError: pass idx += 1 # Write with open(opath, 'w') as f: f.write(str(len(lst)) + '\n') idx = 0; while idx < len(lst): if lst[idx][0].type == 'H': f.write(str(lst[idx][0].idx) + '\n') if lst[idx][0].type == 'V': f.write( str(lst[idx][0].idx) + ' ' + str(lst[idx][1].idx) + '\n') idx += 1 main('a_example.txt', 'a_out.txt') main('b_lovely_landscapes.txt', 'b_out.txt') main('c_memorable_moments.txt', 'c_out.txt') main('d_pet_pictures.txt', 'd_out.txt') main('e_shiny_selfies.txt', 'e_out.txt')
true
c342c82214c3c9086f7e24e0105731064e2ddd60
Python
Drsncnzdmr/myprojects
/House Pricing/data_prep.py
UTF-8
5,199
3.21875
3
[]
no_license
# Data Preprocessing Functions import numpy as np import pandas as pd from sklearn import preprocessing def outlier_thresholds(dataframe, col_name): # thresholdsları bulmak için yazdığımız fonksiyon. quartile1 = dataframe[col_name].quantile(0.05) quartile3 = dataframe[col_name].quantile(0.95) interquantile_range = quartile3 - quartile1 up_limit = quartile3 + 1.5 * interquantile_range low_limit = quartile3 - 1.5 * interquantile_range return low_limit, up_limit def check_outlier(dataframe, col_name): # outlier olup olmadığını kontrol etme fonksiyonu low_limit, up_limit = outlier_thresholds(dataframe, col_name) if dataframe[(dataframe[col_name] > up_limit) | (dataframe[col_name] < low_limit)].any(axis=None): return True else: return False # işlenebilir olması için return kullanıldı. def grab_outliers(dataframe, col_name, index=False): """ Aykırı değerleri yakalamak için yazdık. Aykırı değer var mı yok mu bakar. Aykırı değer varsa bunları getirir. Aykırı değer indexlerini saklayıp saklamayacağını belirtmek için argüman verdik. """ low, up = outlier_thresholds(dataframe,col_name) #thresholds değerleri hesaplandı if dataframe[((dataframe[col_name] < low) | (dataframe[col_name] > up))].shape[0] > 10: # Aykırı değer kaç tane olduğunu tutar. 10 dan büyükse aşağıda head attırdık. print(dataframe[((dataframe[col_name] < low) | (dataframe[col_name] > up))].head()) else: print(dataframe[((dataframe[col_name] < low) | (dataframe[col_name] > up))]) # 10 dan büyük değilse hepsini yazdır. if index: outlier_index = dataframe[((dataframe[col_name] < low) | (dataframe[col_name] > up))].index return outlier_index def remove_outlier(dataframe, col_name): """ Outlier thresholds ile alt üst limitleri hesaplar. up limitten büyük low limitten küçük olmayanlara göre filtrele return et. """ low_limit, up_limit = outlier_thresholds(dataframe, col_name) df_without_outliers = dataframe[~((dataframe[col_name] < low_limit) | (dataframe[col_name] > up_limit))] return df_without_outliers def replace_with_thresholds(dataframe, col_name): """ Alt sınır 0 dan büyükse alt sınır olanları alt sınır ile baskıla üst sınırdan büyük olanalrı üst limitle baskıla Alt sınır 0 dan büyük değilse üst sınıra göre baskılama yap """ low_limit, up_limit = outlier_thresholds(dataframe, col_name) if low_limit > 0: dataframe.loc[(dataframe[col_name] < low_limit), col_name] = low_limit dataframe.loc[(dataframe[col_name] > up_limit), col_name] = up_limit else: dataframe.loc[(dataframe[col_name] > up_limit), col_name] = up_limit def missing_values_table(dataframe, na_name = False): na_cols = [col for col in dataframe.columns if dataframe[col].isnull().sum() > 0] n_miss = dataframe[na_cols].isnull().sum().sort_values(ascending=False) ratio = (dataframe[na_cols].isnull().sum() / dataframe.shape[0] * 100).sort_values(ascending=False) missing_df = pd.concat([n_miss, np.round(ratio, 2)], axis=1, keys=['n_miss', 'ratio']) print(missing_df, end="\n") if na_name: return na_cols def missing_vs_target(dataframe, target, na_columns): temp_df = dataframe.copy() for col in na_columns: temp_df[col + '_NA_FLAG'] = np.where(temp_df[col].isnull(), 1, 0) na_flags = temp_df.loc[:, temp_df.columns.str.contains("_NA_")].columns for col in na_flags: print(pd.DataFrame({"TARGET_MEAN": temp_df.groupby(col)[target].mean(), "Count": temp_df.groupby(col)[target].count()}), end="\n\n\n") def label_encoder(dataframe, binary_col): labelencoder = preprocessing.LabelEncoder() dataframe[binary_col] = labelencoder.fit_transform(dataframe[binary_col]) return dataframe def one_hot_encoder(dataframe, categorical_cols, drop_first = False): dataframe = pd.get_dummies(dataframe, columns=categorical_cols, drop_first=drop_first) return dataframe def rare_analyser(dataframe, target, rare_perc): rare_columns = [col for col in dataframe.columns if dataframe[col].dtypes == 'O' and (dataframe[col].value_counts() / len(dataframe) < rare_perc).any(axis=None)] for col in rare_columns: print(col, ":", len(dataframe[col].value_counts())) print(pd.DataFrame({"COUNT": dataframe[col].value_counts(), "RATIO": dataframe[col].value_counts() / len(dataframe), "TARGET_MEAN": dataframe.groupby(col)[target].mean()}), end="\n\n\n") def rare_encoder(dataframe, rare_perc): temp_df = dataframe.copy() rare_columns = [col for col in temp_df.columns if temp_df[col].dtypes == "O" and (temp_df[col].value_counts() / len(temp_df) < rare_perc).any(axis=None)] for var in rare_columns: tmp = temp_df[var].value_counts() / len(temp_df) rare_labels = tmp[tmp < rare_perc].index temp_df[var] = np.where(temp_df[var].isin(rare_labels), 'Rare', temp_df[var]) return temp_df
true
c93f5f997bb64e55106aced7bddc85c8eecf0ca7
Python
sum008/python-backup
/kinematics/inverse_kinematics_3degree_of_freedom.py
UTF-8
2,920
3.0625
3
[]
no_license
''' Created on Jun 17, 2020 @author: Sumit ''' import pygame as p import math p.init() window=(600,600) display=p.display.set_mode(window) points=[[300,300],[350,300],[400,300],[450,300]] fps=30 run=True length=50 fix=(300,300) count=0 while run: display.fill((255,255,255)) for event in p.event.get(): if event.type==p.QUIT: run=False mouse=p.mouse.get_pos() t=math.atan2(mouse[1]-fix[1],mouse[0]-fix[0]) print(t) if fix[0]-3*length>mouse[0] or fix[1]-3*length>mouse[1] or fix[0]+3*length<mouse[0] or fix[1]+3*length<mouse[1]: angle2=0 angle1=t angle3=0 else: l=math.sqrt((mouse[0]-fix[0])**2+(mouse[1]-fix[1])**2) c=math.sqrt((fix[0]-points[2][0])**2+(fix[1]-points[2][1])**2) ct=math.atan2(fix[1]-points[2][1], fix[0]-points[2][0]) if l!=0 and c!=0 : x=(c**2+l**2-length**2)/(2*c*l) try: t1=math.acos(x) except: print(x,"ee") t1=math.acos(x%0.017428) y=(c**2+length**2-l**2)/(2*c*length) try: t2=math.acos(y) except: print(y,"sfs") t2=math.acos(y%0.017428) x1=(length**2+c**2-length**2)/(2*c*length) try: alpha=math.acos(x1) except: alpha=math.acos(int(x1)) y1=(length**2+c**2-length**2)/(2*length*c) try: gama=math.acos(y1) except: gama=math.acos(int(y1)) beta=(2*length**2-c**2)/(2*length**2) try: angle2=3.14-math.acos(beta) except: pass angle1=t-(alpha+t1) angle3=3.14-(gama+t2) points[1][0]=fix[0]+int(length*math.cos(angle1)) points[1][1]=fix[1]+int(length*math.sin(angle1)) points[2][0]=points[1][0]+int(length*math.cos(angle2+angle1)) points[2][1]=points[1][1]+int(length*math.sin(angle2+angle1)) points[3][0]=points[2][0]+int(length*math.cos(angle3+angle2+angle1)) points[3][1]=points[2][1]+int(length*math.sin(angle3+angle2+angle1)) p.draw.line(display, (0,0,0),fix,(int(points[1][0]),int(points[1][1])), 1) p.draw.circle(display, (0,0,0), (points[1][0],points[1][1]), 4, 4 ) p.draw.line(display, (0,0,0),(int(points[1][0]),int(points[1][1])),(int(points[2][0]),int(points[2][1])), 1) p.draw.line(display, (0,0,0),(int(points[2][0]),int(points[2][1])),(int(points[3][0]),int(points[3][1])), 1) p.display.flip() p.time.Clock().tick(fps)
true
8273924019d7f3467728ba2a1837f48fe2459f80
Python
leogiraldimg/DP1
/Lista03/e.py
UTF-8
111
3.28125
3
[]
no_license
n = int(input()) result = 0 k = 0 while (k < n): result += (k + 1) * (n - k) - k k += 1 print(result)
true
b302ba9d4aecfe9056bb7bb4ac9a766548a154a5
Python
ChenJing0204/plinth-test-suite
/ci_interface/if/start_remake.py
UTF-8
486
2.625
3
[]
no_license
#! /usr/bin/env python import os import sys #para [1]: the path of target table place #get the current path pwd = os.path.split(os.path.realpath(__file__))[0] targetdir = sys.argv[1] if targetdir == '': print("target path is not provide!exit") sys.exit(0) os.chdir(pwd) #cp table_remake.py to target dir os.system('cp table_remake.py %s'%targetdir) #mv to target dir os.chdir(targetdir) os.system('python table_remake.py') os.system('rm table_remake.py') os.chdir(pwd)
true
852725042a4b88ae949fd12b7d84c97ad706d886
Python
nareshmuthyala/Assignment_2.3
/Assignment_2.3.py
UTF-8
68
3.46875
3
[]
no_license
word = input("Enter the word") print("Reverse word is :"+word[::-1])
true
cd7cff504c798f28666b537cbd8191d72203e9c2
Python
markriedl/gaige
/rl/Controller.py
UTF-8
3,973
3.34375
3
[ "MIT" ]
permissive
import sys from Observation import * from Reward import * from Action import * from Agent import * from Environment import * import numpy # Training episodes episodes = 500 # how often to report training results trainingReportRate = 100 # play the interactive game? # 0: human does not play # 1: human plays as the bot # 2: human plays as the enemy play = 2 #Max reward received in any iteration maxr = None # Set up environment for initial training gridEnvironment = Environment() gridEnvironment.randomStart = False gridEnvironment.enemyMode = 1 gridEnvironment.verbose = 0 # Set up agent gridAgent = Agent(gridEnvironment) gridAgent.verbose = False # This is where learning happens for i in range(episodes): # Train gridAgent.agent_reset() gridAgent.qLearn(gridAgent.initialObs) # Test gridAgent.agent_reset() gridAgent.executePolicy(gridAgent.initialObs) # Report totalr = gridAgent.totalReward if maxr == None or totalr > maxr: maxr = totalr if i % trainingReportRate == 0: print "iteration:", i, "total reward", totalr, "max reward:", maxr # Reset the environment for policy execution gridEnvironment.verbose = 1 gridEnvironment.randomStart = False gridEnvironment.enemyMode = 1 gridAgent.verbose = True print "Execute Policy" gridAgent.agent_reset() gridAgent.executePolicy(gridAgent.initialObs) print "total reward", gridAgent.totalReward ### HOW TO PLAY ### w: up ### s: down ### a: left ### d: right ### q: smash (if playing as the bot) ### reset: start the game over ### quit: end game if play == 1: # Play as the bot print "PLAY!" gridAgent.agent_reset() gridAgent.verbose = 0 gridEnvironment.enemyMode = 1 # change this if you want gridEnvironment.verbose = 0 totalr = 0.0 while(True): # print the map gridEnvironment.printEnvironment() print "total player reward:", totalr # Player move print "Move?" move = None x = sys.stdin.readline() if x.strip() == "reset": # reset the game state gridAgent.agent_reset() totalr = 0.0 print "PLAY!" continue # I feel so bad about this elif x.strip() == "quit": # quit game break elif x[0] == '0' or x[0] == 'w': #up move = 0 elif x[0] == '1' or x[0] == 's': #down move = 1 elif x[0] == '2' or x[0] == 'a': #left move = 2 elif x[0] == '3' or x[0] == 'd': #right move = 3 elif x[0] == '4' or x[0] == 'q': #smash move = 4 act = Action() act.actionValue = move newobs, reward = gridEnvironment.env_step(act) print "reward received:", reward.rewardValue totalr = totalr + reward.rewardValue elif play == 2: # play as the enemy print "PLAY!" gridAgent.agent_reset() gridAgent.verbose = 0 gridEnvironment.enemyMode = 4 # don't change this gridEnvironment.verbose = 0 obs = gridAgent.copyObservation(gridAgent.initialObs) totalr = 0.0 while(True): # print the map gridEnvironment.printEnvironment() print "total bot reward:", totalr # Enemy (player) move print "Move?" move = None x = sys.stdin.readline() if x.strip() == "reset": # reset the game state gridAgent.agent_reset() obs = gridAgent.copyObservation(gridAgent.initialObs) totalr = 0.0 print "PLAY!" continue # I feel so bad about this elif x.strip() == "quit": # quit game break elif x[0] == '0' or x[0] == 'w': #up move = 0 elif x[0] == '1' or x[0] == 's': #down move = 1 elif x[0] == '2' or x[0] == 'a': #left move = 2 elif x[0] == '3' or x[0] == 'd': #right move = 3 gridEnvironment.nextEnemyMove = move # execute greedy policy act = Action() act.actionValue = gridAgent.greedy(obs) print "bot action:", gridEnvironment.actionToString(act.actionValue) print "enemy action:", gridEnvironment.actionToString(move) # bot and enemy (player) actions happen here newobs, reward = gridEnvironment.env_step(act) print "reward received:", reward.rewardValue totalr = totalr + reward.rewardValue obs = copy.deepcopy(newobs)
true
c5a02aca63370575ed5463fb4c6fe4affccd6a9a
Python
fanxingzhang/leetcode-grind
/find-all-duplicates-in-an-array.py
UTF-8
371
3.03125
3
[]
no_license
class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ ret = [] for i in range(len(nums)): n = abs(nums[i]) - 1 if nums[n] < 0: ret.append(n + 1) else: nums[n] *= -1 return ret
true
9f1e4e4568d4456aa76a5e0a5b940f329d17c2fe
Python
JuBagnoli/mypythoncode
/isbn2.py
UTF-8
200
2.921875
3
[]
no_license
ISBN = input("enter ISBN") ISBN_odd = 0 ISBN_even = 0 for float in range_odd (0,10,2): print(total(float*3)) for float in range_even (1,12,2): print(total) print(range_odd + range_even)/10
true
3dc445bc6719b55c408e35870841035386484dc6
Python
Steven4869/Simple-Python-Projects
/excercise19.py
UTF-8
897
4.21875
4
[]
no_license
#Matrix addition rows1 = int(input("Enter the Number of rows : ")) column1 = int(input("Enter the Number of Columns: ")) rows2 = int(input("Enter the Number of rows : ")) column2 = int(input("Enter the Number of Columns: ")) if(rows1==rows2 and column1==column2): print("Enter the elements of First Matrix:") A = [[int(input()) for i in range(column1)] for i in range(rows1)] print("First Matrix is: ") for n in A: print(n) print("Enter the elements of Second Matrix:") B = [[int(input()) for i in range(column2)] for i in range(rows2)] for n in B: print(n) C = [[0 for i in range(column1)] for i in range(rows1)] for i in range(rows1): for j in range(column1): C[i][j] = A[i][j] + B[i][j] print("The Sum of Above two Matrices is : ") for r in C: print(r) else: print("Matrix addition cannot be done")
true
9deb370637ce3bbe5d8b492843260c93b280c67d
Python
meialbiol/python-library
/library/forms.py
UTF-8
1,107
2.609375
3
[]
no_license
from django import forms from django.core.exceptions import ValidationError from .models import Book import datetime class BookForm(forms.ModelForm): class Meta: model = Book fields = ['author', 'title', 'description', 'isbn', 'year'] widgets = { 'description': forms.Textarea(attrs={'cols': 80, 'class': 'materialize-textarea'}), 'year': forms.NumberInput(attrs={'min': '0', 'max': '9999', 'step': '1'}) } class RenewBookForm(forms.Form): renewal_date = forms.DateField(help_text="Seleccione una fecha entra hoy y 4 semanas (por defecto 3 semanas)") def clean_renewal_date(self): data = self.cleaned_data['renewal_date'] # Chek date is not in the past if data < datetime.date.today(): raise ValidationError(('Invalid date - renewal in past')) # Check date is in range librarian allowed to change (+4 weeks). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(('Invalid date - renewal more than 4 weeks ahead')) return data
true
46fc08b45cb95b1daa9e4db9820ddc2ef94d8c16
Python
welikepig/YahooMusic
/resultGet.py
UTF-8
1,390
2.546875
3
[]
no_license
import numpy dataDir='/Users/zhiyuanchen/Documents/python/' file_name_test=dataDir + 'out2.txt' output_file= dataDir + 'new1.txt' fTest= open(file_name_test, 'r') fOut = open(output_file, 'w') ii=0 outstr='' su_vec=[0]*6 pt=numpy.zeros(shape=(6,1)) for line in fTest: arr_test=line.strip() su_vec[ii]= float(arr_test) ii=ii+1 #every 6 lines output once if ii==6: ii=0 for nn in range(0,6): if su_vec[nn]==max(su_vec): pt[nn,0]=1 su_vec[nn]=-2000000 break for nn in range(0,6): if su_vec[nn]==max(su_vec): pt[nn,0]=1 su_vec[nn]=-2000000 break for nn in range(0,6): if su_vec[nn]==max(su_vec): pt[nn,0]=1 su_vec[nn]=-2000000 break #put the highest three value as"1" #could be changed to lowest 3 value as"0" by change zeros martix to ones #max function to min for jj in range(0,6): outstr=str(int(pt[jj,0])) fOut.write(outstr+'\n') outstr='' pt=numpy.zeros(shape=(6,1)) fTest.close() fOut.close()
true
e67acca4ad9403403c223d71e7c448483faa5d8a
Python
SubhamoySengupta/iron-worker-uploads
/resize_watermarks/hyve/input_params.py
UTF-8
1,713
2.578125
3
[]
no_license
import sys, json def get_data_from_payload(code): #return trim_payload('//hyve-users/12345/photos/__w-160-240-360-480-720-1080__/1.png') payload_file = None payload = None for i in range(len(code)): if code[i] == "-payload" and (i + 1) < len(code): payload_file = code[i + 1] with open(payload_file,'r') as f: payload = json.loads(f.read()) return trim_payload(payload) break def get_credentials(): cred_file = open('credentials.txt', 'r') response = {} try: for line in cred_file.readlines(): strings = line.split('=') if len(strings) == 2: response[strings[0].strip()] = strings[1].strip() if len(response) == 0: return False else: return response except: return None def trim_payload(payload): link = payload['url'] if '__w-' in link: sys.exit(0) link = link[2:] #remove // from front bucket = link.split('/')[0] output_bucket = bucket[:bucket.find('-')] + '-' + link.split('/')[1] slug = link.split('/')[2] Type = link.split('/')[3] image_name = link.split('/')[4] response = dict( bucket = bucket, output_bucket = output_bucket, slug = slug, image_name = image_name, progressive = True, compression = 80, type = Type ) #extra options if 'progressive' in payload and type(payload['progressive']) is str: response['progressive'] = eval_bool(payload['progressive']) if 'compression' in payload and type(payload['compression']) is int: response['compression'] = payload['compression'] if 'type' in payload: response['type'] = payload['type'] return response def eval_bool(value): if value == 'True': return True else: return False
true
d56e988c97f1fb831a2cf6b8f40c31fa58a819af
Python
bpramod123/imdb_review
/imdb_analysis.py
UTF-8
1,730
3.171875
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[4]: conda install matplotlib # In[14]: import pandas as pd import matplotlib from matplotlib import pyplot as plt import seaborn as sns import numpy as np df=pd.read_csv(r'C:\Users\gunda\Desktop\projs\movies.csv') # In[8]: df # In[41]: #dropping null value rows df1 = df.dropna() df1 # In[42]: df1['budget']=df1['budget'].astype('int64') df1['gross']=df1['gross'].astype('int64') # In[43]: df1 # In[44]: #getting the top budget films df.sort_values(by=['budget'],inplace=False, ascending=False) # In[49]: #dropping duplicates df1.drop_duplicates(inplace=True) # In[55]: #scatter plot of each movie's budget vs gross plt.scatter(x=df1['budget'], y=df1['gross']) plt.title('budget vs gross') plt.ylabel('budget') plt.xlabel('gross') plt.show() # In[52]: df.head() # In[53]: df.tail() # In[63]: #using seaborn bud vs gross sns.regplot(x='budget',y='gross', data=df1) # In[64]: #correlation df1.corr() # In[65]: df1.setindex("score") df1 # In[67]: df1.set_index("budget", inplace = True) # In[68]: df1 # In[69]: df.corr(method='spearman') # In[70]: corr_mat=df1.corr(method='pearson') sns.heatmap(corr_mat, annot=True) plt.show() # In[76]: df1_numerized=df1 for col_name in df1_numerized.columns: if(df1_numerized[col_name].dtype=='object'): df1_numerized[col_name]=df1_numerized[col_name].astype('category') df1_numerized[col_name]=df1_numerized[col_name].cat.codes df1_numerized # In[78]: corr_mat=df1_numerized.corr(method='pearson') sns.heatmap(corr_mat, annot=True) plt.title("Correlation matrix") plt.xlabel("Movie features") plt.xlabel("Movie features") plt.show() # In[ ]:
true
5c72412dac960bfae453a0fcbe7122b7f69a16b4
Python
jakeisnt/philosofound
/flaskr/queries.py
UTF-8
4,986
2.671875
3
[]
no_license
# answer.answer_id -> [question.question_id, question.text] # Accesses the question data associated with an Answer ID def get_question(db, answerId): question = db.execute( 'SELECT q.question_id, q.text' ' FROM question q JOIN answer a on(q.question_id = a.question_id)' ' WHERE a.answer_id = ?', (answerId,) ).fetchone() # question.question_id -> [answer_id, answer.text, num_respondents] # retrieves all of the answers to a given question id # excludes answers that a user has reported def get_question_answers(db, questionId, userId): return db.execute( 'SELECT a.answer_id, a.text' ' FROM answer a JOIN choose c on(a.answer_id = c.answer_id)' ' WHERE a.question_id = ?' (questionId,) ).fetchall() # question.question_id -> Number # counts all of the answers associated with a given question def count_answers(db, questionId): return db.execute( 'SELECT COUNT(c.user_id) as answer_count' ' FROM answer a JOIN choose c on(a.answer_id == c.answer_id)' ' WHERE a.question_id == ?' ' GROUP BY a.answer_id', (questionId,) ).fetchone()['answer_count'] # answer.answer_id -> Number # counts the number of times this answer was chosen def times_answer_chosen(db, answerId): return db.execute( 'SELECT COUNT(user_id) as count' ' FROM choose' ' WHERE answer_id = ?', (answerId,) ).fetchone()['count'] # answer.answer_id, demographic -> [demographic, num_responses, num_chose, percent_chose, answer_selected] # computes user statistics by demographic information for some answer and chosen demographic # formatting the string is fine as demographic is limited to a certain enumeration of categories def get_demographic_info(db, answerId, demographic): num_responses = times_answer_chosen(db, answerId) if demographic in ["gender", "income", "party", "geography"]: return db.execute( 'SELECT {} as demographic, ? as num_responses, COUNT(c.user_id) as num_chose, ((COUNT(c.user_id) * 100) / ?) as percent_chose, ? as answer_selected'.format(demographic) + ' FROM choose c JOIN user u on(c.user_id = u.user_id)' ' WHERE answer_id = ?' ' GROUP BY gender' ' ORDER BY gender', (num_responses, num_responses, answerId, answerId) ).fetchall() else: return None # question.question_id, answer.answer_text -> Boolean # determines whether a question has a duplicate answer in the database def has_duplicate_answer(db, questionId, answer_text): return db.execute( 'SELECT *' ' FROM answer' ' WHERE answer.question_id = ? AND answer.text LIKE ?;', (questionId, answer_text,) ).fetchone() != None # answer.answer_id -> Boolean # determines whether the current user has already voted for an answer def has_duplicate_vote(db, answer_id, user_id): return db.execute( 'SELECT *' ' FROM choose' ' WHERE answer_id == ? AND user_id == ?', (answer_id, user_id)).fetchall() != None # question.text -> Boolean # determines whether a question already exists def has_duplicate_question(db, question_text): return db.execute( 'SELECT *' ' FROM question' ' WHERE question.text LIKE ?', (question_text,) ).fetchone() != None # question.question_id, user.user_id, answer.answer_text -> answer.answer_id # creates an answer for a user and votes for that answer # EFFECT: Creates answer and vote in database def create_answer(db, question_id, user_id, answer_text): # creates the answer db.execute( 'INSERT INTO answer (text, question_id, author_id)' ' VALUES (?, ?, ?)', (answer_text, question_id, user_id), ) # gets the answer's id answer_id = db.execute( 'SELECT answer.answer_id' ' FROM answer' ' WHERE answer.text = ? AND answer.question_id = ?', (answer_text, question_id) ).fetchone()['answer_id'] # if the user has not already voted for this answer if not has_duplicate_vote(db, answer_id, user_id): # user automatically chooses an answer they create db.execute( 'INSERT INTO choose (user_id, answer_id)' ' VALUES (?, ?)', (user_id, answer_id) ) return answer_id # question.text, user.user_id -> question.question_id # creates a question and returns its id # EFFECT: creates a question in the question database def create_question(db, question_text, user_id): # creates a question db.execute( 'INSERT INTO question (text, author_id)' ' VALUES (?, ?)', (question_text, user_id), ) # gets the id of the just-generated question return db.execute( 'SELECT question.question_id as question_id' ' FROM question' ' WHERE question.text = ?', (question_text,) ).fetchone()['question_id']
true
c6dd4f6eaeedccd18d4018bd09419b6b258a8e40
Python
Velasko/Hackaton-da-Nasa
/04 - boolean.py
UTF-8
226
3.921875
4
[]
no_license
x = 27 y = 16 #x, y = 27, 16 print("x == 47:", x == 47 ) print("x == y :", x == y) print("x binario: ", bin(x)) print("y binario: ", bin(y)) print("x and y:", x and y, bin(x and y)) print("x or y:", x or y, bin(x or y))
true
c8494cd91256c5fc78167a00d13df445837d67bf
Python
ajithkmr2/Assignments
/MVC/controller.py
UTF-8
426
2.890625
3
[]
no_license
from model import Currency import view def showPrice(query_value): #gets list of all Currency objects currency_price = Currency.getCurrencyData(query_value) #calls view return view.showData(currency_price) def start(): view.startView() input_option = input('Enter [INR / EUR / CAD / AUD / JPY / ALL] :') return showPrice(input_option) if __name__ == "__main__": #calls controller function start()
true
cb54d949dc8beea59ab723cd11503f61a18b57a2
Python
kh7160/algorithm
/BOJ/11650.py
UTF-8
150
3.15625
3
[]
no_license
n = int(input()) num_lst = [list(map(int, input().split())) for _ in range(n)] num_lst.sort(key=lambda x:(x[0], x[1])) for _ in num_lst: print(*_)
true
f6cea9ee777ead2c81219d0f2536713b8e490f80
Python
nicolekenig/Search_Engine
/indexer.py
UTF-8
7,302
2.90625
3
[]
no_license
import utils from parser_module import Parse from stemmer import Stemmer # DO NOT MODIFY CLASS NAME class Indexer: # DO NOT MODIFY THIS SIGNATURE # You can change the internal implementation as you see fit. def __init__(self, config): self.inverted_idx = {} self.postingDict = {} self.config = config self.stemming = "n" self.tweet_dict = {} self.pars = Parse() self.reversed_inverted_index = {} # DO NOT MODIFY THIS SIGNATURE # You can change the internal implementation as you see fit. def add_new_doc(self, document, documents_list_length=10000): """ This function perform indexing process for a document object. Saved information is captures via two dictionaries ('inverted index' and 'posting') :param document: a document need to be indexed. :return: - """ try: document_dictionary = document.term_doc_dictionary # self.countDoc += 1 for term in document_dictionary.keys(): if self.stemming == 'y': my_stemmer = Stemmer() term = my_stemmer.stem_term(term) # Update inverted index and posting if term not in self.inverted_idx.keys(): self.inverted_idx[term] = [1, [ (document_dictionary[term], document.tweet_id)]] # amount of doc, freq in the doc, doc id. else: self.inverted_idx[term][0] += 1 # amount of doc self.inverted_idx[term][1].append((document_dictionary[term], document.tweet_id)) # freq in the doc # doc id if term not in self.postingDict.keys(): self.postingDict[term] = [(document.tweet_id, document_dictionary[term])] else: self.postingDict[term].append((document.tweet_id, document_dictionary[term])) # self.countTweet -= 1 if document.tweet_id not in self.tweet_dict.keys(): self.tweet_dict[document.tweet_id] = [[term, document_dictionary[term]], 1, 0] # [term,freq in tweet], amount of unique terms in tweet, amount of terms in tweet elif document_dictionary[term] > self.tweet_dict[document.tweet_id][0][ 1]: # tweet exist, compering between freq in two terms if self.tweet_dict[document.tweet_id][0][ 1] == 1: # before change term check if the last term is unique self.tweet_dict[document.tweet_id][ 1] += 1 # last term is unique: add to the amount of uniqe terms in tweet self.tweet_dict[document.tweet_id][0] = [term, document_dictionary[term]] # change between the terms self.tweet_dict[document.tweet_id][2] += 1 elif document_dictionary[term] == 1: # tweet exist, not most common, check if unique self.tweet_dict[document.tweet_id][1] += 1 self.tweet_dict[document.tweet_id][2] += 1 except: # print('problem in indexer : add_new_doc') # print(traceback.print_exc()) pass def rebuild_inverted_index(self): try: temp_dict = {} for term, val in self.inverted_idx.items(): is_lower_letter = term.islower() word_upper = term.upper() word_lower = term.lower() amount = int(val[0]) data = val[1] if is_lower_letter and term in temp_dict: # my word is lower and lower exist in temp dict temp_dict[term][0][0] += amount temp_dict[term][1].extend(data) elif is_lower_letter and word_upper in temp_dict: # my word is lower but upper is in temp dict new_data = temp_dict[word_upper][1] + data temp_dict[term] = [[temp_dict[word_upper][0][0] + amount], new_data] # replace temp_dict.pop(word_upper) elif not is_lower_letter and word_upper in temp_dict: # my word is upper and upper in temp dict temp_dict[word_upper][0][0] += amount temp_dict[word_upper][1].extend(data) # append elif not is_lower_letter and word_lower in temp_dict: # my word is upper and lower in temp dict temp_dict[word_lower][0][0] += amount temp_dict[word_lower][1].extend(data) # append elif is_lower_letter: # my word is lower and not exist in temp dict temp_dict[term] = [[amount], data] # add else: # my word is upper and not exist in temp dict temp_dict[word_upper] = [[amount], data] # add self.inverted_idx = temp_dict for key, data in self.inverted_idx.items(): self.build_terms_in_tweet_doc(key, data[1]) except: # print(traceback.print_exc()) pass def build_terms_in_tweet_doc(self, term, data): try: for tuple in data: if tuple != None: id = tuple[1] freq = tuple[0] if id in self.reversed_inverted_index: if term not in self.reversed_inverted_index[id]: self.reversed_inverted_index[id].append((term, freq)) else: self.reversed_inverted_index[id] = [(term, freq)] except: # print(traceback.print_exc()) pass # DO NOT MODIFY THIS SIGNATURE # You can change the internal implementation as you see fit. def load_index(self, fn): """ Loads a pre-computed index (or indices) so we can answer queries. Input: fn - file name of pickled index. """ # print('Load ', fn) # if fn[len(fn)-4:] == '.pkl': # fn = fn[0:len(fn)-4] fn = 'idx_bench' inverted_index = utils.load_obj(fn) return inverted_index # DO NOT MODIFY THIS SIGNATURE # You can change the internal implementation as you see fit. def save_index(self, fn): """ Saves a pre-computed index (or indices) so we can save our work. Input: fn - file name of pickled index. """ utils.save_obj(self.inverted_idx, fn) # feel free to change the signature and/or implementation of this function # or drop altogether. def _is_term_exist(self, term): """ Checks if a term exist in the dictionary. """ return term in self.postingDict # feel free to change the signature and/or implementation of this function # or drop altogether. def get_term_posting_list(self, term): """ Return the posting list from the index for a term. """ return self.postingDict[term] if self._is_term_exist(term) else []
true
26d09bb65b10dd9d9c54f759a2f433608061a91b
Python
HyunminKo/Algorithm
/Python-Algorithm/kakao/Round2_4.py
UTF-8
1,503
2.796875
3
[]
no_license
N=0 M=0 matrixA = [] matrixB = [] dx = [-1,0,1,0] dy = [0,1,0,-1] visited = [[0 for i in range(101)] for j in range(101)] def bfs(row,col): global N, M, visited visited[row][col] = 1 q = [(row,col)] count = 0 if matrixA[row][col] != matrixB[row][col]: count = - 1 flag = True while q: location = q.pop(0) for i in range(len(dx)): nx = location[0] + dx[i] ny = location[1] + dy[i] if nx < 0 or ny < 0 or nx >= N or ny >= M or visited[nx][ny] == 1 or matrixB[nx][ny] == 0: continue if matrixA[nx][ny] != matrixB[nx][ny]: count = - 1 visited[nx][ny] = 1 q.append((nx,ny)) flag = False if count == 0 and flag: if matrixA[row][col] == matrixB[row][col]: return 1 if count == 0: return 1 else: return 0 def countMatches(grid1, grid2): global N, M,visited N = len(grid1) M = len(grid1[0]) result = 0 for line in grid1: matrixA.append([int(x) for x in line]) for line in grid2: matrixB.append([int(x) for x in line]) for row in range(N): for col in range(M): if matrixB[row][col] != 0: if visited[row][col] == 0: result += bfs(row,col) return result grid1= [ '0100', '1001', '0011', '0011'] grid2= [ '0101', '1001', '0011', '0011'] print(countMatches(grid1,grid2))
true
a95fb8a6eafa736692ecb93cc01e935591017d95
Python
NearJiang/Python-route
/多重继承.py
UTF-8
473
2.890625
3
[]
no_license
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> class Base1: def foo1(self): print('我是foo1,我为Base1带盐') >>> class Base2: def foo2(self): print('我是foo2,我为Base2带盐') >>> class a(Base1, Base2): pass >>> b=a() >>> b.foo1() 我是foo1,我为Base1带盐 >>> b.foo2() 我是foo2,我为Base2带盐 >>>
true
6fae8dddf94194b28f8d4883b16af9ee778c32fd
Python
darcyknox/COSC326
/etude-1/etude-1.py
UTF-8
7,284
3.5
4
[]
no_license
import re import sys # Etude-1 Email Addresses # Author: Darcy Knox # Date: March 2020 # The program takes string input(s) from the user, and determines whether the # string is a valid email address according to the specifications outlined in # the Etude 1 Problem Description # Function to match the mailbox part of the address def matchMailbox(str): validMailboxPattern = re.compile(r'^[A-Z0-9]+([-_\.]?[A-Z0-9]+)*$', re.IGNORECASE) match = validMailboxPattern.match(str) return bool(match) # Function to find an @ symbol in a string def matchAt(str): validAt = re.compile(r'(@|_at_)') match = validAt.search(str) return bool(match) # Function to find the right-most @ symbol in a string def findAtPos(str): nonSymbol = str.rfind('_at_') symbol = str.rfind('@') if symbol > nonSymbol: return symbol elif (symbol < nonSymbol): return nonSymbol else: return None # Function to match the domain part of the address def matchDomain(str): validDomain = re.compile(r'^([A-Z0-9]+((\.)?[A-Z0-9]+)*)+(\.|_dot_)$', re.IGNORECASE) match = validDomain.match(str) return bool(match) # Function to search for whether a string attempts to use an IP address def hasIPDomain(str): validIP = re.compile(r'\[.+\]$') match = validIP.search(str) return bool(match) # Function to match a valid IP address def matchIPDomain(str): validIP = re.compile(r'^\[((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\]$') match = validIP.match(str) return bool(match) # Function to find a valid extension at the end of a string def matchExt(str): validExt = re.compile(r'(co\.nz|com\.au|co\.uk|com|co\.us|co\.ca)$', re.IGNORECASE) match = validExt.search(str) return bool(match) # Function to match a fully valid domain and extension def matchDomainAndExt(str): validDomainAndExt = re.compile(r'^([A-Z0-9]+((\.)?[A-Z0-9]+)*)+(\.|_dot_)(co\.nz|com\.au|co\.uk|com|co\.us|co\.ca)$', re.IGNORECASE) match = validDomainAndExt.match(str) return bool(match) # Function to check for any whitespace within a string def containsWhitespace(str): whitespace = re.compile(' ') match = whitespace.search(str) return bool(match) # Function to check for any invalidities def fullMatch(str): if containsWhitespace(str): print (str + " <- Address contains whitespace") return # if a valid extension is used # replace the _dot_ preceding the extension first if matchExt(str): # If extension is preceded with _dot_ it is changed to a . immediately # Position of dot may be different depending on the extension if (str[-3:] == "com"): if (str[-8:-3] == "_dot_"): str = str[:-8] + "." + str[-3:] #replace _dot_ with . elif (str[-6:] == "com.au"): if (str[-11:-6] == "_dot_"): str = str[:-11] + "." + str[-6:] #replace _dot_ with . else: if (str[-10:-5] == "_dot_"): str = str[:-10] + "." + str[-5:] #replace _dot_ with . #str = str.replace('_dot_', '.') # if there's no @ symbol if not matchAt(str): print (str + " <- Missing @ symbol") return else: # replace the furthest right instance of _at_ with @ # all other _at_ instances are considered literal _at_ # note: _at_ is 4 chars long if str[findAtPos(str):findAtPos(str) + 4] == "_at_": str = str[:findAtPos(str)] + "@" + str[(findAtPos(str) + 4):] str = str.replace('_dot_', '.') splitAddress = re.split('(@)', str) # split at the @ symbol # if there are more than 3 parts to the address if len(splitAddress) > 3: print (str + " <- Too many @ symbols") return # separate string into 3 parts mailbox = splitAddress[0] # mailbox is the part before the @ symbol atSymbol = splitAddress[1] # atSymbol is the @ symbol domainAndExt = splitAddress[2] # domainAndExt is the part after the @symbol # mailbox doesn't fit the regex if not matchMailbox(mailbox): consecutiveSeparators = re.compile(r'(\.|-|_)(\.|-|_)') if bool(consecutiveSeparators.search(mailbox)): print (str + " <- Mailbox contains consecutive separators") # cannot contain consecutive separators (mailbox) return elif len(mailbox) == 0: print (str + " <- Missing mailbox") return else: print (str + " <- Invalid mailbox") return if not matchDomainAndExt(domainAndExt): # if there is an error in the domain or extension consecutiveDots = re.compile(r'(\.|_dot_)(\.|_dot_)') # looks for two dots next to eachother if bool(consecutiveDots.search(domainAndExt)): print (str + " <- Domain contains consecutive separators") # cannot contain consecutive separators (domain) return # evaluate the extension first validExt = re.compile(r'(co\.nz|com\.au|co\.uk|com|co\.us|co\.ca)$', re.IGNORECASE) domainAndExtSplit = re.split(validExt, domainAndExt) # split at the extension domain = domainAndExtSplit[0] # first part is the domain # if there is an invalid extension (extension doesn't split) if len(domainAndExtSplit) < 2: dotSeparator = re.compile(r'[A-Z0-9]\.[A-Z0-9]', re.IGNORECASE) # says if there are no two characters separated by a dot, there must be a missing extension if not hasIPDomain(domainAndExt) and not re.search(dotSeparator, domainAndExt): print (str + " <- Missing extension") return elif not hasIPDomain(domainAndExt): print (str + " <- Invalid extension") return elif hasIPDomain(domainAndExt) and len(domainAndExt.split('[')[0]) > 0: print(str + " <- IP address cannot have preceeding domain") return elif not matchIPDomain(domain): print (str + " <- Invalid IP address") return else: ext = domainAndExtSplit[1] # second part is the extension if domain[-1] != ".": print (str + " <- Missing extension") return if not matchDomain(domain): # if the domain doesn't match the regex if len(domain) == 0 or domain == ".": # if the domain is a dot or nothing print (str + " <- Missing domain") return elif not hasIPDomain(domainAndExt): # if the domain and extension is not an IP print (str + " <- Invalid domain") # the domain is invalid return # Valid email print (str.replace('_dot_', '.').lower()) #replace the _dot_s return def main(): # User Input for line in sys.stdin: line = line.strip() fullMatch(line) if __name__ == "__main__": main()
true
1267e60553bc50bcf04659e3fedff549a274537f
Python
disa-mhembere/Guided-Assembler
/src/csc_matrix2.py
UTF-8
1,396
3.125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#!/usr/bin/python # csc_matrix2.py # Created by Disa Mhembere on 2013-11-21. # Email: disa@jhu.edu # Copyright (c) 2013. All rights reserved. import scipy from scipy.sparse.csc import csc_matrix import numpy as np from exceptions import IndexError class csc_matrix2(csc_matrix): """ Sub-class of lil_matrix that allows permits popping rows off """ def pop_row(self, ): if self.shape[0] == 0: raise IndexError('Cannot pop a matrix with rows = 0') self.rows = np.delete(self.rows, self.shape[0]-1, 0) # clean up self.data = np.delete(self.data, self.shape[0]-1, 0) # clean up self._shape = (self._shape[0]-1, self.shape[1]) def append_col(self, sp_mat=None, init=True): """ Add a column to the sparse matrix given another sp_mat to append. Used when adding a new letter to the alphabet. @param sp_mat: the sparse matrix to be appended to the self object """ self._shape = (self._shape[0], self.shape[1]+1) if sp_mat is not None: self[:,-1] = sp_mat elif init: self[self.shape[0]-1, self.shape[1]-1] = 1 def append_row(self, ): """ Append a row to the bottom of a lil_matrix2 object """ self.rows = np.append(self.rows, 0) self.rows[-1] = [] self.data = np.append(self.data, 0) self.data[-1] = [] self._shape = (self._shape[0]+1, self.shape[1]) # Note we never remove columns -- too expensive
true
49f16a8c5eda49bb6e1d464e98bdb94d5b6d60c0
Python
MathieuSoul/PhyStat_Project
/Test/simulationWolrd.py
UTF-8
9,465
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ import networkx as nx import random from math import sqrt from networkx.readwrite import json_graph import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import imageio import seaborn import forceatlas themeColors = {"alive": "blue", "infected": "orange", "dead": "red", "recovered": "green"} drawgif = 1; class Person: idct = 1; def __init__(self, world): #When infected, first check if disease is already in diseases, if not, check resistances self.infections = {} self.id = Person.idct; Person.idct+=1; self.resistances = {} self.world = world; self.alive = 1; self.color = themeColors["alive"] self.recoveryRate = random.uniform(.9, .99) self.resistance = .9 #self.resistanceCoeff = random.uniform(.5, 1)*(self.age-40)^2*(1/1600) def infect(self, disease, wasResistant): baseDeathTime = 32; self.infections[disease.id] = Infection(self, disease, baseDeathTime*disease.pathogenicity, self.recoveryRate); disease.infected+=1; if wasResistant: disease.resistant-=1; else: disease.susceptible-=1; self.color = themeColors["infected"] return self.infections[disease.id] def recover(self, infection): try: self.infections[infection.disease.id] = 0 infection.disease.infected-=1; infection.disease.resistant+=1; except: print("Infection not on list. Is this vaccination?"); self.color = themeColors["recovered"] self.resistances[infection.disease.id] = self.resistance def checkDisease(a, b): newInfections = [] for diseaseid, infection in a.infections.items(): if b.infections.get(diseaseid, 0)==0 and infection!=0: resistance = b.resistances.get(diseaseid, -1); #si la disease n'est pas dans les resistances, on l'y ajoute avec une resistance de -1 if resistance!=-1: #la disease est dans la liste des resistances, la resistance est de 0.9 test = random.uniform(0, 1) test2 = random.uniform(0, 1) if(test2>resistance) and (test<infection.disease.virulence): b.infect(infection.disease, 1); newInfections.append(infection.disease.id) #else: #print("individual resisted infection!") else: #la disease n'est pas dans la liste des resistances test = random.uniform(0, 1) if(test<infection.disease.virulence): b.infect(infection.disease, 0); newInfections.append(infection.disease.id) return newInfections def interact(self, otherActor): if(self.alive==1 and otherActor.alive==1): a = Person.checkDisease(self, otherActor); b = Person.checkDisease(otherActor, self); '''if(len(a)>0): print("Infections from A to B:", a) if(len(b)>0): print("Infections from B to A:", b)''' def die(self, disease): if(self.alive==1): self.alive = 0; disease.infected-=1; disease.dead+=1; self.color = themeColors["dead"] def tick(self): if(self.alive==1): for diseaseid, infection in self.infections.items(): if(infection!=0): infection.tick() class Infection: def __init__(self, host, disease, timeToDeath, recoveryRate): self.host = host; self.disease = disease; self.timeToDeath = timeToDeath; self.recoveryRate = recoveryRate; self.id = disease.id; self.recovered = 0; def tick(self): if not self.recovered: self.timeToDeath-=1; if self.timeToDeath<1: self.host.die(self.disease) else: test = random.uniform(0, 1) if(test>self.recoveryRate): self.host.recover(self) self.recovered = 1; class Disease: idct = 1; def __init__(self, name, world, virulence, pathogenicity): self.name = name; self.id = Disease.idct; Disease.idct+=1; self.virulence = virulence; #Determines how likely the pathogen is to spread from one host to the next self.pathogenicity = pathogenicity; #Determines how much disease the pathogen creates in the host (aka number of days w/o recovery until death) self.susceptible = world.popsize; self.infected = 0; self.resistant = 0; self.dead = 0; self.world = world; self.historyS = {}; self.historyI = {}; self.historyR = {} self.historyD = {} world.diseaseList.append(self); #These two functions are not currently in use. They don't fit into the current model '''def mutateVirulence(self, virulenceJitter = .05): self.virulence = self.virulence + random.uniform(-virulenceJitter, virulenceJitter) def mutatePathogenicity(self, pathoJitter = .1): self.pathogenicity = self.pathogenicity + random.uniform(-pathoJitter, pathoJitter)''' def tick(self, age): self.historyS[age] = self.susceptible; self.historyI[age] = self.infected; self.historyR[age] = self.resistant; self.historyD[age] = self.dead; def summary(self): historyFrame = pd.DataFrame({"1-S": self.historyS, "2-I": self.historyI, "3-R": self.historyR, "4-D": self.historyD}); historyFrame["time"] = historyFrame.index return historyFrame; class World: def __init__(self, initPopulation, vaccination_percent, k, p): self.popsize = initPopulation; self.population = [] self.diseaseList = []; self.age = 0; self.vaccination_percent = vaccination_percent for indv in range(initPopulation): self.population.append(Person(self)); self.worldgraph = nx.newman_watts_strogatz_graph(initPopulation, k, p); #small world graph mappin = {num: per for (num, per) in enumerate(self.population)} nx.relabel_nodes(self.worldgraph, mappin, copy=False) #self.nodeLayout = nx.spring_layout(self.worldgraph, scale=200, k=1/(50*sqrt(self.popsize))) self.nodeLayout = forceatlas.forceatlas2_layout(self.worldgraph, iterations=10) nx.set_node_attributes(self.worldgraph, 'color', themeColors["alive"]) def draw(self): if(drawgif): nodeColors = [x.color for x in nx.nodes(self.worldgraph)] plt.figure(figsize=(8,6)) plt.title("Network at Age "+str(self.age)) nx.draw(self.worldgraph, pos=self.nodeLayout, node_color=nodeColors, node_size=30, hold=1) plt.savefig("graphseries/graph"+str(self.age).zfill(4)+".png", dpi=250) plt.close() def tick(self): self.age+=1; if(self.age%4 == 0): print("Drawing network; Age is "+str(self.age)) self.draw(); interactions = random.sample(self.worldgraph.edges(), self.popsize) for edge in interactions: edge[0].interact(edge[1]) for person in self.population: person.tick(); for disease in self.diseaseList: disease.tick(self.age) def runSim(self, nsteps): for i in range(nsteps): self.tick(); def summary(self): histories = {} for disease in self.diseaseList: histories[disease.name] = disease.summary(); return histories; def main(popsize, vaccination_percent, k, p): # os.system("rm Test/graphseries/*.png") earth = World(popsize, vaccination_percent, k, p) earth.tick() flu = Disease("1918 Flu", earth, 0.8, 1); earth.population[0].infect(flu, 0) earth.population[1].infect(flu, 0) for i in range(int(earth.vaccination_percent*earth.popsize)): infection = earth.population[i+2].infect(flu, False) earth.population[i+2].recover(infection) earth.runSim(120) if(drawgif): png_dir = "graphseries" images = [] for subdir, dirs, files in os.walk(png_dir): for file in files: file_path = os.path.join(subdir, file) if file_path.endswith(".png"): images.append(imageio.imread(file_path)) imageio.mimsave('graphseries/movie.gif', images, duration =0.3) return(earth) def run_simulation(popsize, vaccination_percent, k, p): earth = main(popsize, vaccination_percent, k, p) history = earth.summary() for name, x in history.items(): y = pd.melt(x, id_vars="time") print(y) fg = seaborn.FacetGrid(data=y, hue='variable', hue_order=['1-S','2-I','3-R','4-D'], aspect=1.61) fg.map(plt.plot, 'time', 'value').add_legend() plt.show(block=False) return earth, calculate_ro(earth) def calculate_ro(earth): listI = sorted(earth.diseaseList[0].historyI.items()) x, yI = zip(*listI) max_index = yI.index(max(yI)) listS = sorted(earth.diseaseList[0].historyS.items()) x, yS = zip(*listS) return 1/((1-earth.vaccination_percent)*yS[max_index]) print(run_simulation(1000, 0, 3, 0.027)[1])
true
fcaab9c86cd7a73ef14ec77b38698ad894136899
Python
csc202summer19/lectures
/02_recursion/recursive_functions.py
UTF-8
398
4.0625
4
[]
no_license
def power(a, n): """ Compute a^n. """ # NOTE: a^n = a * a * a * ... * a # a^n = a * a^(n - 1) if n == 0: return 1 else: return a * power(a, n - 1) def factorial(n): """ Compute n!. """ # NOTE: n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 # n! = n * (n - 1)! if n == 0: return 1 else: return n * factorial(n - 1)
true
5da006e536bc9c8fbc23c2ae35079caab874e3b5
Python
AlexanderHeimann-EH/Testautomation
/CiCDTMstudioTest/Source/Demos/pytools-186e88affa1d/pytools_186e88affa1d/Python/Tests/TestData/ProfileTest/Program.py
UTF-8
88
2.59375
3
[]
no_license
import time def f(): for i in xrange(10000): time.sleep(0) f()
true
78bfe27d36067b049e6f34e0d0851dbe6c60a70d
Python
arkadiuszpasek/wuwuzela
/src/types/string.py
UTF-8
129
3.234375
3
[]
no_license
class String(): def __init__(self, input): self.value = str(input) def __str__(self): return self.value
true
6fe31ea47a5bd68551d259c7ffe3431b52c1e0c3
Python
analyticd/FlowTradingTools
/testpanel.py
UTF-8
1,642
2.578125
3
[]
no_license
import wx class TestNoteBook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 500)) panel = wx.Panel(self) vsizer = wx.BoxSizer(wx.VERTICAL) toppanel = wx.Panel(panel) bottompanel = wx.Panel(panel) notebook = wx.Notebook(bottompanel) posterpage = wx.Panel(notebook) listpage = wx.Panel(notebook) notebook.AddPage(posterpage, 'posters') notebook.AddPage(listpage, 'list') sizer1 = wx.BoxSizer(wx.VERTICAL) sizer2 = wx.BoxSizer(wx.VERTICAL) btn = wx.Button(toppanel, label="Refresh Front data") sizer1.Add(btn,1, wx.EXPAND, 2) txt = wx.TextCtrl(toppanel,-1,'this is a test') sizer1.Add(txt,1, wx.EXPAND, 2) toppanelsizer=wx.BoxSizer(wx.VERTICAL) toppanelsizer.Add(sizer1,0, wx.ALL|wx.EXPAND, 2) toppanelsizer.Add(sizer2,0, wx.ALL|wx.EXPAND, 2) toppanel.SetSizer(toppanelsizer) toppanel.Layout() vsizer.Add(toppanel, 0.25, wx.EXPAND) vsizer.Add(bottompanel, 1, wx.EXPAND) #vsizer.Add(sizer1, 1, wx.EXPAND) ##### Added code ( bottompanel_sizer = wx.BoxSizer(wx.VERTICAL) bottompanel_sizer.Add(notebook, 1, wx.EXPAND) bottompanel.SetSizer(bottompanel_sizer) toppanel.SetBackgroundColour('blue') # not needed, to distinguish bottompanel from toppanel ##### Added code ) panel.SetSizer(vsizer) app = wx.App() frame = TestNoteBook(None, -1, 'notebook') frame.Show() app.MainLoop()
true
33eaf01f9ee0867587573eb1924f3bf73c901bb2
Python
jeromepan/Timus-Online-Judge-Solution
/1280.py
UTF-8
984
3.328125
3
[]
no_license
def main(): before = [None]*(100000 + 1) after = [None]*(100000 + 1) orders = [None]*(1000 + 1) numOfSubjects, numOfLimitations = input().split() numOfSubjects = int(numOfSubjects) numOfLimitations = int(numOfLimitations) for indexOfLimitation in range(1, numOfLimitations+1): before[indexOfLimitation], after[indexOfLimitation] = input().split() before[indexOfLimitation] = int(before[indexOfLimitation]) after[indexOfLimitation] = int(after[indexOfLimitation]) subject = input().split() for indexOfSubject in range(1, numOfSubjects+1): orders[int(subject[indexOfSubject-1])] = indexOfSubject isCorrect = True for indexOfLimitation in range(1, numOfLimitations+1): if orders[before[indexOfLimitation]] > orders[after[indexOfLimitation]]: isCorrect = False break if isCorrect: print("YES") else: print("NO") if __name__ == "__main__": main()
true
555ac88ddebbdd5a5c05d65094eaf5d6eae17ee4
Python
PietroMelzi/potion
/potion/meta/smoothing_constants.py
UTF-8
1,326
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 12 14:09:49 2019 @author: matteo """ import math def gauss_smooth_const(max_feat, std): psi = 2 * max_feat / (math.sqrt(2 * math.pi) * std) kappa = max_feat**2 / std**2 xi = max_feat**2 / std**2 return psi, kappa, xi def std_smooth_const(): psi = 4 / math.sqrt(2 * math.pi * math.e) kappa = 2 xi = 2 return psi, kappa, xi def gibbs_smooth_const(max_feat, temp): psi = 2 * max_feat / temp kappa = 4 * max_feat**2 / temp**2 xi = 2 * max_feat**2 / temp**2 return psi, kappa, xi def gauss_lip_const(max_feat, max_rew, disc, std): lip = 2 * max_feat**2 * max_rew / (std* (1 - disc))**2 * ( 1 + 2 * disc / (math.pi * (1 - disc))) return lip def std_lip_const(max_rew, disc): lip = 4 * max_rew / (1 - disc)**2 * ( 1 + 4 * disc / (math.pi * math.e * (1 - disc))) return lip def gibbs_lip_const(max_feat, max_rew, disc, temp): lip = 2 * max_feat**2 * max_rew / (temp * (1 - disc))**2 * ( 3 + 4 * disc / (1 - disc)) return lip def pirotta_coeff(max_feat, max_rew, disc, std, action_vol): return max_rew * max_feat**2 / ((1 - disc)**2 * std**2) * \ (action_vol / (math.sqrt(2 * math.pi) * std) + disc / (2 * (1 - disc)))
true
dd69c5966a6c1accd15acb41fa3fa4af9895e572
Python
ProditorMagnus/WML_tree_tools
/py_files/wmlparser3.py
UTF-8
27,576
2.96875
3
[]
no_license
#!/usr/bin/env python3 # encoding: utf-8 """ This parser uses the --preprocess option of wesnoth so a working wesnoth executable must be available at runtime if the WML to parse contains preprocessing directives. Pure WML can be parsed as is. For example: wml = "" [unit] id=elve name=Elve [abilities] [damage] id=Ensnare [/dama ge] [/abilities] [/unit] "" p = Parser() cfg = p.parse_text(wml) for unit in cfg.get_all(tag = "unit"): print(unit.get_text_val("id")) print(unit.get_text_val("name")) for abilities in unit.get_all(tag = "abilitities"): for ability in abilities.get_all(tag = ""): print(ability.get_name()) print(ability.get_text_val("id")) Because no preprocessing is required, we did not have to pass the location of the wesnoth executable to Parser. The get_all method always returns a list over matching tags or attributes. The get_name method can be used to get the name and the get_text_val method can be used to query the value of an attribute. """ import os, glob, sys, re, subprocess, argparse, tempfile, shutil import atexit from typing import Union tempdirs_to_clean = [] tmpfiles_to_clean = [] @atexit.register def cleaner(): for temp_dir in tempdirs_to_clean: shutil.rmtree(temp_dir, ignore_errors=True) for temp_file in tmpfiles_to_clean: os.remove(temp_file) class WMLError(Exception): """ Catch this exception to retrieve the first error message from the parser. """ def __init__(self, parser=None, message=None): if parser: self.line = parser.parser_line self.wml_line = parser.last_wml_line self.message = message self.preprocessed = parser.preprocessed def __str__(self): return """WMLError: %s %s %s %s """ % (str(self.line), self.preprocessed, self.wml_line, self.message) class StringNode: """ One part of an attribute's value. Because a single WML string can be made from multiple translatable strings we model it as a list of several StringNode each with its own text domain. """ def __init__(self, data: bytes): self.textdomain = None # non-translatable by default self.data = data def wml(self) -> bytes: if not self.data: return b"" return self.data def debug(self): if self.textdomain: return "_<%s>'%s'" % (self.textdomain, self.data.decode("utf8", "ignore")) else: return "'%s'" % self.data.decode("utf8", "ignore") def __str__(self): return "StringNode({})".format(self.debug()) def __repr__(self): return str(self) class AttributeNode: """ A WML attribute. For example the "id=Elfish Archer" in: [unit] id=Elfish Archer [/unit] """ def __init__(self, name, location=None): self.name = name self.location = location self.value = [] # List of StringNode def wml(self) -> bytes: s = self.name + b"=\"" for v in self.value: s += v.wml().replace(b"\"", b"\"\"") s += b"\"" return s def debug(self): return self.name.decode("utf8") + "=" + " .. ".join( [v.debug() for v in self.value]) def get_text(self, translation=None) -> str: """ Returns a text representation of the node's value. The translation callback, if provided, will be called on each partial string with the string and its corresponding textdomain and the returned translation will be used. """ r = "" for s in self.value: ustr = s.data.decode("utf8", "ignore") if translation: r += translation(ustr, s.textdomain) else: r += ustr return r def get_binary(self): """ Returns the unmodified binary representation of the value. """ r = b"" for s in self.value: r += s.data return r def get_name(self): return self.name.decode("utf8") def __str__(self): return "AttributeNode({})".format(self.debug()) def __repr__(self): return str(self) class TagNode: """ A WML tag. For example the "unit" in this example: [unit] id=Elfish Archer [/unit] """ def __init__(self, name, location=None): self.name = name self.location = location # List of child elements, which are either of type TagNode or # AttributeNode. self.data = [] self.speedy_tags = {} def wml(self) -> bytes: """ Returns a (binary) WML representation of the entire node. All attribute values are enclosed in quotes and quotes are escaped (as double quotes). Note that no other escaping is performed (see the BinaryWML specification for additional escaping you may require). """ s = b"[" + self.name + b"]\n" for sub in self.data: s += sub.wml() + b"\n" s += b"[/" + self.name.lstrip(b'+') + b"]\n" return s def debug(self): s = "[%s]\n" % self.name.decode("utf8") for sub in self.data: for subline in sub.debug().splitlines(): s += " %s\n" % subline s += "[/%s]\n" % self.name.decode("utf8").lstrip('+') return s def get_all(self, **kw): """ This gets all child tags or child attributes of the tag. For example: [unit] name=A name=B [attack] [/attack] [attack] [/attack] [/unit] unit.get_all(att = "name") will return two nodes for "name=A" and "name=B" unit.get_all(tag = "attack") will return two nodes for the two [attack] tags. unit.get_all() will return 4 nodes for all 4 sub-elements. unit.get_all(att = "") Will return the two attribute nodes. unit.get_all(tag = "") Will return the two tag nodes. If no elements are found an empty list is returned. """ if len(kw) == 1 and "tag" in kw and kw["tag"]: return self.speedy_tags.get(kw["tag"].encode("utf8"), []) r = [] for sub in self.data: ok = True for k, v in list(kw.items()): v = v.encode("utf8") if k == "tag": if not isinstance(sub, TagNode): ok = False elif v != b"" and sub.name != v: ok = False elif k == "att": if not isinstance(sub, AttributeNode): ok = False elif v != b"" and sub.name != v: ok = False if ok: r.append(sub) return r def get_text_val(self, name, default=None, translation=None, val=-1): """ Returns the value of the specified attribute. If the attribute is given multiple times, the value number val is returned (default behaviour being to return the last value). If the attribute is not found, the default parameter is returned. If a translation is specified, it should be a function which when passed a unicode string and text-domain returns a translation of the unicode string. The easiest way is to pass it to gettext.translation if you have the binary message catalogues loaded. """ x = self.get_all(att=name) if not x: return default return x[val].get_text(translation) def get_binary(self, name, default=None): """ Returns the unmodified binary data for the first attribute of the given name or the passed default value if it is not found. """ x = self.get_all(att=name) if not x: return default return x[0].get_binary() def append(self, node): """ Appends a child node (must be either a TagNode or AttributeNode). """ self.data.append(node) if isinstance(node, TagNode): if node.name not in self.speedy_tags: self.speedy_tags[node.name] = [] self.speedy_tags[node.name].append(node) def get_name(self): return self.name.decode("utf8") def __str__(self): return "TagNode({})".format(self.get_name()) def __repr__(self): return str(self) class RootNode(TagNode): """ The root node. There is exactly one such node. """ def __init__(self): TagNode.__init__(self, None) def debug(self): s = "" for sub in self.data: for subline in sub.debug().splitlines(): s += subline + "\n" return s def __str__(self): return "RootNode()" def __repr__(self): return str(self) class Parser: def __init__(self, wesnoth_exe=None, config_dir=None, data_dir=None): """ wesnoth_exe - Wesnoth executable to use. This should have been configured to use the desired data and config directories. config_dir - The Wesnoth configuration directory, can be None to use the wesnoth default. data_dir - The Wesnoth data directory, can be None to use the wesnoth default. After parsing is done the root node of the result will be in the root attribute. """ self.wesnoth_exe = wesnoth_exe self.config_dir = None if config_dir: self.config_dir = os.path.abspath(config_dir) self.data_dir = None if data_dir: self.data_dir = os.path.abspath(data_dir) self.keep_temp_dir = None self.temp_dir = None self.no_preprocess = (wesnoth_exe is None) self.preprocessed = None self.verbose = False self.last_wml_line = "?" self.parser_line = 0 self.line_in_file = 42424242 self.chunk_start = "?" def parse_file(self, path, defines="") -> RootNode: """ Parse the given file found under path. """ self.path = path if not self.no_preprocess: self.preprocess(defines) return self.parse() def parse_binary(self, binary: bytes, defines="") -> RootNode: """ Parse a chunk of binary WML. """ td, tmpfilePath = tempfile.mkstemp(prefix="wmlparser_", suffix=".cfg") with open(tmpfilePath, 'wb') as temp: temp.write(binary) os.close(td) self.path = tmpfilePath tmpfiles_to_clean.append(tmpfilePath) if not self.no_preprocess: self.preprocess(defines) return self.parse() def parse_text(self, text, defines="") -> RootNode: """ Parse a text string. """ return self.parse_binary(text.encode("utf8"), defines) def preprocess(self, defines): """ This is called by the parse functions to preprocess the input from a normal WML .cfg file into a preprocessed .plain file. """ if self.keep_temp_dir: output = self.keep_temp_dir else: output = tempfile.mkdtemp(prefix="wmlparser_") tempdirs_to_clean.append(output) self.temp_dir = output commandline = [self.wesnoth_exe] if self.data_dir: commandline += ["--data-dir", self.data_dir] if self.config_dir: commandline += ["--config-dir", self.config_dir] commandline += ["--preprocess", self.path, output] if defines: commandline += ["--preprocess-defines", defines] if self.verbose: print((" ".join(commandline))) p = subprocess.Popen(commandline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if self.verbose: print((out + err).decode("utf8")) self.preprocessed = output + "/" + os.path.basename(self.path) + \ ".plain" if not os.path.exists(self.preprocessed): first_line = open(self.path).readline().strip() raise WMLError(self, "Preprocessor error:\n" + " ".join(commandline) + "\n" + "First line: " + first_line + "\n" + out.decode("utf8") + err.decode("utf8")) def parse_line_without_commands_loop(self, line: bytes) -> Union[None, bytes]: """ Once the .plain commands are handled WML lines are passed to this. """ if not line: return if line.strip(): self.skip_newlines_after_plus = False if self.in_tag: self.handle_tag(line) return if self.in_arrows: arrows = line.find(b'>>') if arrows >= 0: self.in_arrows = False self.temp_string += line[:arrows] self.temp_string_node = StringNode(self.temp_string) self.temp_string = b"" self.temp_key_nodes[self.commas].value.append( self.temp_string_node) self.in_arrows = False return line[arrows + 2:] else: self.temp_string += line return quote = line.find(b'"') if not self.in_string: arrows = line.find(b'<<') if arrows >= 0 and (quote < 0 or quote > arrows): self.parse_line_without_commands(line[:arrows]) self.in_arrows = True return line[arrows + 2:] if quote >= 0: if self.in_string: # double quote if quote < len(line) - 1 and line[quote + 1] == b'"'[0]: self.temp_string += line[:quote + 1] return line[quote + 2:] self.temp_string += line[:quote] self.temp_string_node = StringNode(self.temp_string) if self.translatable: self.temp_string_node.textdomain = self.textdomain self.translatable = False self.temp_string = b"" if not self.temp_key_nodes: raise WMLError(self, "Unexpected string value.") self.temp_key_nodes[self.commas].value.append( self.temp_string_node) self.in_string = False return line[quote + 1:] else: self.parse_outside_strings(line[:quote]) self.in_string = True return line[quote + 1:] else: if self.in_string: self.temp_string += line else: self.parse_outside_strings(line) def parse_line_without_commands(self, line): while True: line = self.parse_line_without_commands_loop(line) if not line: break def parse_outside_strings(self, line): """ Parse a WML fragment outside of strings. """ if not line: return if line.startswith(b"#textdomain "): self.textdomain = line[12:].strip().decode("utf8") return if not self.temp_key_nodes: line = line.lstrip() if not line: return # Is it a tag? if line.startswith(b"["): self.handle_tag(line) # No tag, must be an attribute. else: self.handle_attribute(line) else: for i, segment in enumerate(line.split(b"+")): segment = segment.lstrip(b" \t") if i > 0: # If the last segment is empty (there was a plus sign # at the end) we need to skip newlines. self.skip_newlines_after_plus = not segment.strip() if not segment: continue if segment.rstrip(b" ") == b"_": self.translatable = True segment = segment[1:].lstrip(b" ") if not segment: continue self.handle_value(segment) def handle_tag(self, line): end = line.find(b"]") if end < 0: if line.endswith(b"\n"): raise WMLError(self, "Expected closing bracket.") self.in_tag += line return tag = (self.in_tag + line[:end])[1:] self.in_tag = b"" if tag.startswith(b"/"): self.parent_node = self.parent_node[:-1] elif tag.startswith(b"+") and self.parent_node and self.parent_node[-1].get_all(tag=tag[1:].decode()): node_to_append_to = self.parent_node[-1].get_all(tag=tag[1:].decode())[-1] self.parent_node.append(node_to_append_to) else: node = TagNode(tag, location=(self.line_in_file, self.chunk_start)) if self.parent_node: self.parent_node[-1].append(node) self.parent_node.append(node) self.parse_outside_strings(line[end + 1:]) def handle_attribute(self, line): assign = line.find(b"=") remainder = None if assign >= 0: remainder = line[assign + 1:] line = line[:assign] self.commas = 0 self.temp_key_nodes = [] for att in line.split(b","): att = att.strip() node = AttributeNode(att, location=(self.line_in_file, self.chunk_start)) self.temp_key_nodes.append(node) if self.parent_node: self.parent_node[-1].append(node) if remainder: self.parse_outside_strings(remainder) def handle_value(self, segment): def add_text(segment): segment = segment.rstrip() if not segment: return n = len(self.temp_key_nodes) maxsplit = n - self.commas - 1 if maxsplit < 0: maxsplit = 0 for subsegment in segment.split(b",", maxsplit): self.temp_string += subsegment.strip() self.temp_string_node = StringNode(self.temp_string) self.temp_string = b"" self.temp_key_nodes[self.commas].value.append( self.temp_string_node) if self.commas < n - 1: self.commas += 1 # Finish assignment on newline, except if there is a # plus sign before the newline. add_text(segment) if segment.endswith(b"\n") and not self.skip_newlines_after_plus: self.temp_key_nodes = [] def parse(self) -> RootNode: """ Parse preprocessed WML into a tree of tags and attributes. """ # parsing state self.temp_string = b"" self.temp_string_node = None self.commas = 0 self.temp_key_nodes = [] self.in_string = False self.in_arrows = False self.textdomain = "wesnoth" self.translatable = False self.root = RootNode() self.parent_node = [self.root] self.skip_newlines_after_plus = False self.in_tag = b"" command_marker_byte = bytes([254]) input = self.preprocessed if not input: input = self.path for rawline in open(input, "rb"): compos = rawline.find(command_marker_byte) self.parser_line += 1 # Everything from chr(254) to newline is the command. if compos != 0: self.line_in_file += 1 if compos >= 0: self.parse_line_without_commands(rawline[:compos]) self.handle_command(rawline[compos + 1:-1]) else: self.parse_line_without_commands(rawline) if self.keep_temp_dir is None and self.temp_dir: if self.verbose: print(("removing " + self.temp_dir)) shutil.rmtree(self.temp_dir, ignore_errors=True) return self.root def handle_command(self, com): if com.startswith(b"line "): self.last_wml_line = com[5:] _ = self.last_wml_line.split(b" ") self.chunk_start = [(_[i + 1], int(_[i])) for i in range(0, len(_), 2)] self.line_in_file = self.chunk_start[0][1] elif com.startswith(b"textdomain "): self.textdomain = com[11:].decode("utf8") else: raise WMLError(self, "Unknown parser command: " + com) def get_all(self, **kw): return self.root.get_all(**kw) def get_text_val(self, name, default=None, translation=None): return self.root.get_text_val(name, default, translation) def jsonify(tree, verbose=False, depth=1): """ Convert a Parser tree into JSON If verbose, insert a linebreak after every brace and comma (put every item on its own line), otherwise, condense everything into a single line. """ import json def node_to_dict(n): d = {} tags = set(x.get_name() for x in n.get_all(tag="")) for tag in tags: d[tag] = [node_to_dict(x) for x in n.get_all(tag=tag)] for att in n.get_all(att=""): d[att.get_name()] = att.get_text() return d print(json.dumps(node_to_dict(tree), indent=depth if verbose else None)) def xmlify(tree, verbose=False, depth=0): import xml.etree.ElementTree as ET def node_to_et(n): et = ET.Element(n.get_name()) for att in n.get_all(att=""): attel = ET.Element(att.get_name()) attel.text = att.get_text() et.append(attel) for tag in n.get_all(tag=""): et.append(node_to_et(tag)) return et ET.ElementTree(node_to_et(tree.get_all()[0])).write( sys.stdout, encoding="unicode") if __name__ == "__main__": arg = argparse.ArgumentParser() arg.add_argument("-a", "--data-dir", help="directly passed on to wesnoth.exe") arg.add_argument("-c", "--config-dir", help="directly passed on to wesnoth.exe") arg.add_argument("-i", "--input", help="a WML file to parse") arg.add_argument("-k", "--keep-temp", help="specify directory where to keep temp files") arg.add_argument("-t", "--text", help="WML text to parse") arg.add_argument("-w", "--wesnoth", help="path to wesnoth.exe") arg.add_argument("-d", "--defines", help="comma separated list of WML defines") arg.add_argument("-T", "--test", action="store_true") arg.add_argument("-j", "--to-json", action="store_true") arg.add_argument("-v", "--verbose", action="store_true") arg.add_argument("-x", "--to-xml", action="store_true") args = arg.parse_args() if not args.input and not args.text and not args.test: sys.stderr.write("No input given. Use -h for help.\n") sys.exit(1) if (args.wesnoth and not os.path.exists(args.wesnoth)): sys.stderr.write("Wesnoth executable not found.\n") sys.exit(1) if not args.wesnoth: print("Warning: Without the -w option WML is not preprocessed!", file=sys.stderr) if args.test: print("Running tests") p = Parser(args.wesnoth, args.config_dir, args.data_dir) if args.keep_temp: p.keep_temp_dir = args.keep_temp if args.verbose: p.verbose = True only = None def test2(input, expected, note, function): if only and note != only: return input = input.strip() expected = expected.strip() p.parse_text(input) output = function(p).strip() if output != expected: print("__________") print(("FAILED " + note)) print("INPUT:") print(input) print("OUTPUT:") print(output) print("EXPECTED:") print(expected) print("__________") else: print(("PASSED " + note)) def test(input, expected, note): test2(input, expected, note, lambda p: p.root.debug()) test( """ [test] a=1 [/test] """, """ [test] a='1' [/test] """, "simple") test( """ [+foo] a=1 [/foo] """, """ [+foo] a='1' [/foo] """, "+foo without foo in toplevel") test( """ [foo] [+bar] a=1 [/bar] [/foo] """, """ [foo] [+bar] a='1' [/bar] [/foo] """, "+foo without foo in child") test( """ [test] [foo] a=1 [/foo] [/test] """, """ [test] [foo] a='1' [/foo] [/test] """, "subtag, part 1") test( """ [test] [foo] a=1 [/foo] [/test] [+test] [+foo] [/foo] [/test] """, """ [test] [foo] a='1' [/foo] [/test] """, "subtag, part 2") test( """ [test] a, b, c = 1, 2, 3 [/test] """, """ [test] a='1' b='2' c='3' [/test] """, "multi assign") test( """ [test] a, b = 1, 2, 3 [/test] """, """ [test] a='1' b='2, 3' [/test] """, "multi assign 2") test( """ [test] a, b, c = 1, 2 [/test] """, """ [test] a='1' b='2' c= [/test] """, "multi assign 3") test( """ #textdomain A #define X _ "abc" #enddef #textdomain B [test] x = _ "abc" + {X} [/test] """, """ [test] x=_<B>'abc' .. _<A>'abc' [/test] """, "textdomain") test( """ [test] x,y = _1,_2 [/test] """, """ [test] x='_1' y='_2' [/test] """, "underscores") test( """ [test] a = "a ""quoted"" word" [/test] """, """ [test] a='a "quoted" word' [/test] """, "quoted") test( """ [test] code = << "quotes" here ""blah"" >> [/test] """, """ [test] code=' "quotes" here ""blah"" ' [/test] """, "quoted2") test( """ foo="bar"+ "baz" """, """ foo='bar' .. 'baz' """, "multi line string") test( """ #define baz "baz" #enddef foo="bar"+{baz} """, """ foo='bar' .. 'baz' """, "defined multi line string") test( """ foo="bar" + "baz" # blah """, """ foo='bar' .. 'baz' """, "comment after +") test( """ #define baz "baz" #enddef foo="bar" {baz} """, """ foo='bar' .. 'baz' """, "defined string concatenation") test( """ #define A BLOCK [{BLOCK}] [/{BLOCK}] #enddef {A blah} """, """ [blah] [/blah] """, "defined tag") test2( """ [test] a=1 b=2 a=3 b=4 [/test] """, "3, 4", "multiatt", lambda p: p.get_all(tag = "test")[0].get_text_val("a") + ", " + p.get_all(tag = "test")[0].get_text_val("b")) sys.exit(0) p = Parser(args.wesnoth, args.config_dir, args.data_dir) if args.keep_temp: p.keep_temp_dir = args.keep_temp if args.verbose: p.verbose = True if args.input: p.parse_file(args.input, args.defines) elif args.text: p.parse_text(args.text, args.defines) if args.to_json: jsonify(p.root, True) print() elif args.to_xml: print('<?xml version="1.0" encoding="UTF-8" ?>') print('<root>') xmlify(p.root, True, 1) print('</root>') else: print((p.root.debug()))
true
f0188e0b79e7f0c78c063117163f7fdce50986c9
Python
KristineYW/DS-Unit-3-Sprint-2-SQL-and-Databases
/module2-sql-for-analysis/insert_rpg_char_inv.py
UTF-8
2,719
3.015625
3
[ "MIT" ]
permissive
import os from dotenv import load_dotenv import sqlite3 import psycopg2 from psycopg2.extras import execute_values load_dotenv() # looks inside the .env file for some env vars # passes env var values to python var DB_HOST = os.getenv("DB_HOST", default="OOPS") DB_NAME = os.getenv("DB_NAME", default="OOPS") DB_USER = os.getenv("DB_USER", default="OOPS") DB_PASSWORD = os.getenv("DB_PASSWORD", default="OOPS") # what is the filepath to connect to our sqlite database? DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "module1-introduction-to-sql", "rpg_db.sqlite3") class SqliteService_inventory(): def __init__(self, db_filepath=DB_FILEPATH): self.connection = sqlite3.connect(db_filepath) self.cursor = self.connection.cursor() def fetch_characters_inventory(self): return self.cursor.execute("SELECT * FROM charactercreator_character_inventory;").fetchall() class ElephantSQLService_inventory(): def __init__(self): self.connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST) self.cursor = self.connection.cursor() def create_characters_inventory_table(self): create_query = """ DROP TABLE IF EXISTS characters_inventory; -- allows this to be run idempotently, avoids psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "characters__inventory_pkey" DETAIL: Key (character_id)=(1) already exists. CREATE TABLE IF NOT EXISTS characters_inventory ( id SERIAL PRIMARY KEY, character_id INT, item_id INT ); """ print(create_query) self.cursor.execute(create_query) self.connection.commit() def insert_characters_inventory(self, characters_inventory): """ Param characters_inventory needs to be a list of tuples, each representing a row to insert (each should have each column) """ insertion_query = """ INSERT INTO characters_inventory (id, character_id,item_id) VALUES %s """ execute_values(self.cursor, insertion_query, characters_inventory) self.connection.commit() if __name__ == "__main__": # # EXTRACT (AND MAYBE TRANSFORM IF NECESSARY) # sqlite_service = SqliteService_inventory() characters_inventory = sqlite_service.fetch_characters_inventory() print(type(characters_inventory), len(characters_inventory)) print(type(characters_inventory[0]), characters_inventory[0]) # # LOAD # pg_service = ElephantSQLService_inventory() pg_service.create_characters_inventory_table() pg_service.insert_characters_inventory(characters_inventory)
true
6a4978de579271cbac24749266e89b97e9b3afde
Python
MichelleZ/leetcode
/algorithms/python/countVowelsPermutation/countVowelsPermutation.py
UTF-8
616
3.078125
3
[]
no_license
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/count-vowels-permutation/ # Author: Miao Zhang # Date: 2021-04-17 class Solution: def countVowelPermutation(self, n: int) -> int: kMod = 10 ** 9 + 7 a, e, i, o, u = 1, 1, 1, 1, 1 for k in range(2, n + 1): aa = (e + i + u) % kMod ee = (a + i) % kMod ii = (e + o) % kMod oo = i % kMod uu = (i + o) % kMod a = aa e = ee i = ii o = oo u = uu return (a + e + i + o + u) % kMod
true
f90349b5a46e46574072c30246b0cb99e23159b0
Python
emilyvroth/cs1
/lecture/lecture6/boolean.py
UTF-8
169
3.25
3
[]
no_license
x = 15 y = -15 z = 32 print(x == y and y < z) print(x == y or y < z) print(x == abs(y) and y <z) print(x == abs(y) or y <z) print(not x == abs(y)) print(not x != abs(y))
true
43a71c40490275763712a79f64ba54ff7af3e294
Python
mathminds/csci-utils
/src/csci_utils/file/tests.py
UTF-8
2,562
3.25
3
[]
no_license
import os from csci_utils.io.enhancedwrite import atomic_write from csci_utils.file.parquet import ( get_parquet_column, get_parquet_file_name, convert_xls_to_parquet, ) from tempfile import TemporaryDirectory from unittest import TestCase from pandas import DataFrame class ParquetTests(TestCase): def test_get_parquet_file_name_with_path(self): """Ensure filename changes to appropriate extension""" filename = "/data/fakefile.txt" self.assertEqual("/data/fakefile.parquet", get_parquet_file_name(filename)) def test_get_parquet_file_name_no_path(self): """Ensure filename changes to appropriate extension""" filename = "fakefile.txt" self.assertEqual("fakefile.parquet", get_parquet_file_name(filename)) def test_get_parquet_column(self): """Ensure a column can be retrieved from a parquet file""" # create a data frame for testing test_list = [1, 2] test_column = "test_1" test_dict = {test_column: test_list, "test_2": [3, 4]} test_dict = DataFrame(data=test_dict) # create a temporary directory and write the df as a parquet file for test with TemporaryDirectory() as tmp: fp = os.path.join(tmp, "test.parquet") with atomic_write(fp, as_file=False) as pf: test_dict.to_parquet(pf) self.compare_columns(fp, test_column, test_list) def test_convert_xls_to_parquet(self): """Ensure a Parquet file can be created from and Excel file""" # create a data frame for testing test_list = [1, 2] test_column = "test_1" test_dict = {test_column: test_list, "test_2": [3, 4]} test_dict = DataFrame(data=test_dict) # create a temporary directory and write the df as a parquet file for test with TemporaryDirectory() as tmp: fp = os.path.join(tmp, "test.xls") with atomic_write(fp, as_file=False) as pf: test_dict.to_excel(pf, "Sheet1") parquet_file = convert_xls_to_parquet(fp, "Sheet1") self.assertTrue(os.path.exists(parquet_file)) self.compare_columns(parquet_file, test_column, test_list) def compare_columns(self, file, test_column, test_list): column_values = get_parquet_column(file, test_column).tolist() # compare the test list against what was retrieved from parquet file for i, j in zip(column_values, test_list): if i != j: self.fail("Values do not match")
true
0dbaea791805310e9b9e4dd342ab7da747f891fd
Python
lizhao0211/HtmlManipulate
/designer/RunMainWinHorLayout.py
UTF-8
437
2.53125
3
[]
no_license
import sys import MainWinHorLayout from PyQt5.QtWidgets import QApplication, QMainWindow if __name__ == '__main__': # 创建QApplication类的实例 app = QApplication(sys.argv) # 创建一个窗口 mainWindow = QMainWindow() ui = MainWinHorLayout.UI_MainWindow ui.setupUi(mainWindow) mainWindow.show() # 进入程序的主循环,并通过exit函数确保主循环安全结束 sys.exit(app.exec_())
true
28a0311befca9e7db2d0d8a2ab785e71e92b7c76
Python
DoctorLai/ACM
/binarysearch/Candy-Race/Candy-Race.py
UTF-8
538
3.03125
3
[]
no_license
# https://helloacm.com/teaching-kids-programming-minmax-dynamic-programming-algorithm-game-of-picking-numbers-at-two-ends/ # https://binarysearch.com/problems/Candy-Race # HARD, DP class Solution: def solve(self, P): n = len(P) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = P[i] for i in range(n - 2, -1, -1): for j in range(i + 1, n): dp[i][j] = max(P[i] - dp[i + 1][j], P[j] - dp[i][j - 1]) return dp[0][-1] > 0
true
ff701233d551181b183b9bc39b4f01b19d62d26e
Python
CVanchieri/CS-Unit5-HashTables
/applications/histo/histo.py
UTF-8
569
3.28125
3
[]
no_license
# Your code here import re store = {} def printHistogram(word, count): print(f"{word}:{' ' * (16 - len(word))}{'#' * count}") with open('./robin.txt', 'r') as file: for line in file: for word in line.split(): word = re.sub('\W+', '', word.lower()) if not word.isalpha(): continue if word not in store: store[word] = 1 else: store[word] += 1 store = sorted(list(store.items()), key = lambda item: item[1], reverse = True) for word in range(len(store) - 1): printHistogram(store[word][0], store[word][1])
true
651c15a6f7053e7fca86b5e08604d651bae6bc4d
Python
Francesco-Ghizzo/TCC
/Script/Console QGIS/Non Commentati/Spectral_Radiance_L5.py
UTF-8
2,220
2.671875
3
[]
no_license
## Spectral Radiance (L) landsat 5 from qgis.core import * from PyQt4.QtGui import QInputDialog import os from osgeo import gdal def get_landsat_dir(): landsat_dir = QInputDialog.getText(None, '', 'Insira o caminho da pasta com as imagens Landsat 5:\n')[0] return landsat_dir def get_landsat_band(dirPath, bandNum): bandStr = str(bandNum) imageName = os.path.basename(dirPath) + "_B" + bandStr + ".TIF" imagePath = dirPath + "/" + imageName imageDict = {'fileName': imageName, 'fullPath': imagePath} return imageDict def spectral_radiance(bandNum, DN): LMIN = (-1.765, -3.576, -1.502, -1.763, -0.411, 1.238, -0.137) LMAX = (178.941, 379.055, 255.695, 242,303, 30.178, 15.600, 13.156) L = ((LMAX[bandNum-1] - LMIN[bandNum-1])/255)*(DN) + LMIN[bandNum-1] return L landsat_dir_path = get_landsat_dir() os.chdir(landsat_dir_path) landsat_bands = [None] for i in range(1, 8): bandDict = get_landsat_band(landsat_dir_path, i) landsat_bands.append(bandDict) for i in range(1, 8): input_dataset = gdal.Open(landsat_bands[i]['fileName']) if input_dataset is None: print "layer " + str(i) + " failed to load" else: print "layer " + str(i) + " loaded" input_band = input_dataset.GetRasterBand(1) gtiff_driver = gdal.GetDriverByName('GTiff') output_filename = "Spectral Radiance_B" + str(i) + ".TIF" output_dataset = gtiff_driver.Create(output_filename, input_band.XSize, input_band.YSize, 1, input_band.DataType) output_dataset.SetProjection(input_dataset.GetProjection()) output_dataset.SetGeoTransform(input_dataset.GetGeoTransform()) if output_dataset is None: print "failed to create output layer " + str(i) else: print "output layer " + str(i) + " created" input_data = input_band.ReadAsArray() output_band = output_dataset.GetRasterBand(1) output_band.WriteArray(spectral_radiance(i, input_data)) # if ? # print "failed to write to output layer " + str(i) # else: # print "output layer " + str(i) + " written" output_dataset.FlushCache()
true
0337d9aebbaa780fd76d8c5b482d6e40e72b3e22
Python
TheTacoScott/stormcity
/lib/worker.py
UTF-8
2,260
2.59375
3
[]
no_license
import threading import time import lib try: from urlparse import urlparse as urlparse except: from urllib.parse import urlparse try: import Queue as queue except: import queue class Fetcher(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.stop = threading.Event() self.status_lock = threading.Lock() self.status = "" self.status_time = -1 self.purge_time = 60 #shouldn't run in all threads if we ever were to have more than one, should probably be a seperate thread all-to-gether at some point def purge_cache(self): with lib.results_lock: to_delete = [] for url in lib.results: thetime = lib.results[url]["time"] if time.time() - thetime >= self.purge_time: to_delete.append(url) for key in to_delete: del lib.results[key] def set_next_purge(self): self.next_purge = time.time() + self.purge_time def job_update(self,url,data): with lib.results_lock: lib.results[url] = {"time":time.time(),"data":data} def set_status(self,text): with self.status_lock: self.status = text self.status_time = time.time() def get_status(self): with self.status_lock: return (self.status,self.status_time) def run(self): self.set_next_purge() self.set_status("Worker Startup") while not self.stop.is_set(): #purged old results if time.time() > self.next_purge: self.set_status("Purging Old Cache") self.purge_cache() self.set_next_purge() #get a url from the queue to work on self.set_status("Checking for work...") try: self.url_to_process = lib.work_q.get(block=True,timeout=0.25) except queue.Empty: continue #process job here parsed_uri = urlparse(self.url_to_process) if parsed_uri.hostname in lib.url_handlers: data = lib.url_handlers[parsed_uri.hostname](self.url_to_process) else: data = lib.url_handlers["GLOBAL"](self.url_to_process) #add results to job dict self.job_update(self.url_to_process,data) self.set_status("Fetching:" + self.url_to_process) if self.stop.is_set(): break self.set_status("Worker Shutdown")
true
49b170388d2c3c5c8b27ec98f00158a6b91fa467
Python
zhahang0/caffe-luolongqiang
/python/deepFashion/get_category10_images.py
UTF-8
1,712
2.796875
3
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
import numpy as np from numpy import array import os, sys, time, argparse, shutil def get_category_images(input_txt, output_dir): fi = open(input_txt, 'r') cls_name_list = ['3-Blouse', '6-Cardigan', '11-Jacket', '16-Sweater', '17-Tank', '18-Tee', '19-Top', '32-Shorts', '33-Skirt', '41-Dress'] # output_dir = 'data/deepFashion/category_partition' if not os.path.exists(output_dir): os.makedirs(output_dir) for cls_name in cls_name_list: cls_output_dir = output_dir + '/' + cls_name if not os.path.exists(cls_output_dir): os.mkdir(cls_output_dir) for i, line in enumerate(list(fi)): line_list = line.strip().split() img_file_name = line_list[0] img_cls = line_list[-1] output_file_name = output_dir + '/' + img_cls + '/' + str(i) + '.jpg' shutil.copy(img_file_name, output_file_name) print i, output_file_name #end def get_args(): parser = argparse.ArgumentParser(description='get category images') parser.add_argument('-i', dest='input_txt', help='train\val\test.txt', default=None, type=str) parser.add_argument('-d', dest='output_dir', help='output_partition_dir', default=None, type=str) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args if __name__ == '__main__': args = get_args() input_txt = args.input_txt output_dir = args.output_dir tic = time.clock() print 'get partition images, begin...' get_category_images(input_txt, output_dir) print 'get partition images, done' toc = time.clock() print 'running time:{} seconds'.format(toc-tic)
true
576a9b04335a2d98931fb8b9f941e88ffeb1ae38
Python
afhuertass/santander
/scripts/nn/model.py
UTF-8
967
2.53125
3
[]
no_license
from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import BatchNormalization from keras.layers import Dropout def get_model( input_features , nhidden ): model = Sequential() model.add( Dense( nhidden , input_dim = input_features ) ) model.add( Activation("elu" , name = "l1") ) model.add( BatchNormalization() ) model.add(Dense(nhidden)) model.add( Activation("elu" , name = "l2") ) model.add ( Dropout( 0.2 ) ) model.add( BatchNormalization() ) model.add( Dense(nhidden ) ) model.add(Activation("elu" , name = "l3") ) model.add ( Dropout( 0.2 ) ) model.add( BatchNormalization() ) model.add( Dense( nhidden ) ) model.add(Activation("elu" , name = "l4") ) model.add ( Dropout( 0.2 ) ) #model.add( BatchNormalization() ) model.add( Dense( 1 , activation="linear") ) #model.add( Activation("activation='linear'")) #model.add( Activation("relu" , name = "output") ) return model
true
eda1da79874631d55b7fda5ddf6053fd27ee5087
Python
UWPCE-PythonCert-ClassRepos/py220-online-201904-V2
/students/elaine_x/lesson06/assignment/src/expand_records.py
UTF-8
2,461
3.1875
3
[]
no_license
''' expand records to one million records and assign unique id to them ''' import logging import csv import uuid import random #global CCNUMBER_LIST, DATA_LIST, SENTENCE_LIST logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger(__name__) def read_csv(filename): '''read data from csv''' with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') old_record = [] ccnumber_list = [] date_list = [] sentence_list = [] for i, row in enumerate(reader): lrow = list(row) old_record.append(lrow) #collecting data pool for expansion if i > 1: ccnumber_list.append(lrow[4]) date_list.append(lrow[5]) sentence_list.append(lrow[6]) #LOGGER.info('csv contains %s', new_ones) #LOGGER.info('date_list %s', date_list) return old_record, ccnumber_list, date_list, sentence_list def generate(num1, num2): '''generate up to 1,000,000 records''' new_record = list(map(create_entry, range(num1, num2))) #alternative way #new_record = [] #for i in range(num1, num2): #1,000,000 #guid = str(uuid.uuid4()) #randomly select from ccnumber, date and sentence pool #ccnumber = random.choice(ccnumber_list) #date = random.choice(date_list) #sentence = random.choice(sentence_list) #row = [i, guid, i, i, ccnumber, date, sentence] #new_record.append(row) #LOGGER.info('expanded record is %s', new_record) return new_record def create_entry(index): '''create an entry row, called by map function''' guid = str(uuid.uuid4()) ccnumber = random.choice(CCNUMBER_LIST) date = random.choice(DATE_LIST) sentence = random.choice(SENTENCE_LIST) return [index, guid, index, index, ccnumber, date, sentence] def write_to_csv(filename, data): '''write data to csv''' with open(filename, 'w', encoding='utf-8') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"') writer.writerows(data) if __name__ == "__main__": INPUT_FILENAME = "../data/exercise.csv" ORIGINAL_DATA, CCNUMBER_LIST, DATE_LIST, SENTENCE_LIST = \ read_csv(INPUT_FILENAME) EXPANDED_DATA = generate(10, 1000001) OUTPUT_FILENAME = "../data/exercise2.csv" DATA = ORIGINAL_DATA + EXPANDED_DATA write_to_csv(OUTPUT_FILENAME, DATA)
true
193be8f6ff7593438f3d12d8e8c480dbd33adee5
Python
waddling/adventofcode-2019
/day04/part1.py
UTF-8
750
3.6875
4
[]
no_license
#!/usr/bin/env python3 import sys def check_adjacent_digits(n): n = str(n) for i in range(len(n) - 1): if int(n[i]) == int(n[i+1]): return True return False def check_increasing_digits(n): n = str(n) for i in range(len(n) - 1): if int(n[i]) > int(n[i+1]): return False return True if __name__ == "__main__": for line in sys.stdin: start, end = map(int, line.strip().split('-')) count = 0 for n in range(start, end + 1): if not check_adjacent_digits(n): continue elif not check_increasing_digits(n): continue else: count += 1 print(count)
true
6ced24ae8c47ec64aa9cef59475582bcb49cfe84
Python
Richiewong07/Python-Exercises
/python-assignments/list/sum_the_numbers.py
UTF-8
288
4.625
5
[]
no_license
# 1. Sum the Numbers # Given an list of numbers, print their sum. When I say given something, just make something up and store it in a variable. num_list = [1, 2, 3, 4, 5] def sum(numbers): total = 0 for num in numbers: total += num print(total) sum(num_list)
true
43486f5bf01e869830e3d47fe3774d29b2f3ecd4
Python
AK-1121/code_extraction
/python/python_1641.py
UTF-8
184
2.71875
3
[]
no_license
# How can I declare a 5x5 grid of numbers in Python? boardPieces = [["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"]]
true
931f24b9b8925a9838c52d7eca339a11f15de36e
Python
thetaprimeio/flyingking-checkers
/MachineLearningModules/PerformanceSystem.py
UTF-8
41,535
3.28125
3
[ "MIT" ]
permissive
####################################################################### # File name: PerformanceSystem.py # # Author: PhilipBasaric # # # # Description: Performance System of a Checkers machine-learning AI. # # Contains the methods that generate a game trace with move selection # # performed by a supplied target function hypothesis. This module # # contains the hard-coded game logic define by the game of checkers. # # # ####################################################################### import random, time, copy # This is the performance system object. It is responsible for producing the game trace used by the critic module class PerformanceSystem: # This function performs all actions that constitute a turn def runGame(self, gameState, v1, v2): # Update game state attributes gameState.info = [len(gameState.blackPieces), len(gameState.redPieces), len(gameState.blackKings), len(gameState.redKings), len(gameState.redThreat), len(gameState.blackThreat)] self.move(gameState, v1, v2) # If one side has no pieces, game is over if len(gameState.redPieces) == 0 and len(gameState.redKings) == 0 or len(gameState.blackPieces) == 0 and len(gameState.blackKings) == 0: gameState.isOver = True # Simple function that outputs the contents of the checkers board to the console def drawBoard(self, board): print() print(" ", end=" ") for k in range(0,8): print(k, end="") print(" ", end="") print("") for i in range(0,len(board)): print(i, end=" ") for j in range(0,len(board)): print(board[i][j], end=" ") print("") # This function performs a move for a given player def move(self, gameState, v1, v2): # Get set of legal moves with current board state legalMoves = self.getLegalMoves(gameState.currentTurn, gameState.redPieces, gameState.blackPieces, gameState.redKings, gameState.blackKings, gameState.redThreat, gameState.blackThreat, gameState.board) # Check for stalemate if len(legalMoves) == 0: gameState.isOver = True return # Else proceed by obtaining and making the best move else: bestMove = self.getBestMove(gameState, legalMoves, v1, v2) # get the best move from legalMoves self.makeMove(gameState, bestMove) # make the best move using bestMove # This function probes every move and returns a 2D list containing the set of legal moves def getLegalMoves(self, currentTurn, redPieces, blackPieces, redKings, blackKings, redThreat, blackThreat, board): legalMoves = [] # array to be returned # Call getKingMoves - logic for King function self.getKingMoves(legalMoves, currentTurn, redPieces, blackPieces, redKings, blackKings, redThreat, blackThreat, board) # The following code block accounts for all possible moves on the red player's side of the board if currentTurn == "red": for piece in redPieces: # move UP and to the RIGHT if (piece[0] - 1) > -1 and (piece[1] + 1) < 8: # check bounds # Regular diagonal if board[piece[0] - 1][piece[1] + 1] == " ": legalMoves.append([redPieces.index(piece), piece[0]-1, piece[1]+1, -1, "regular", "None"]) # Elimination if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds # Regular Elimination if board[piece[0] - 1][piece[1] + 1] == "b" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(blackPieces, piece[0]-1, piece[1]+1) redThreat.append(threat) legalMoves.append([redPieces.index(piece), piece[0]-2, piece[1]+2, threat, "regular", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] + 1] == "B" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(blackKings, piece[0]-1, piece[1]+1) redThreat.append(threat) legalMoves.append([redPieces.index(piece), piece[0]-2, piece[1]+2, threat, "regular", "king"]) # move UP and to the LEFT if (piece[0] - 1) > -1 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] - 1][piece[1] - 1] == " ": legalMoves.append([redPieces.index(piece), piece[0]-1, piece[1]-1, -1, "regular", "None"]) # Elimination if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] - 1][piece[1] - 1] == "b" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(blackPieces, piece[0]-1, piece[1]-1) redThreat.append(threat) legalMoves.append([redPieces.index(piece), piece[0]-2, piece[1]-2, threat, "regular", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] - 1] == "B" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(blackKings, piece[0]-1, piece[1]-1) redThreat.append(threat) legalMoves.append([redPieces.index(piece), piece[0]-2, piece[1]-2, threat, "regular", "king"]) # The following code block accounts for all possible moves on the black player's side of the board elif currentTurn == "black": for piece in blackPieces: # move DOWN and to the RIGHT if (piece[0] + 1) < 8 and (piece[1] + 1) < 8: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] + 1] == " ": legalMoves.append([blackPieces.index(piece), piece[0]+1, piece[1]+1, -1, "regular", "None"]) # Elimination if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] + 1] == "r" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(redPieces, piece[0]+1, piece[1]+1) blackThreat.append(threat) # add black threat legalMoves.append([blackPieces.index(piece), piece[0]+2, piece[1]+2, threat, "regular", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] + 1] == "R" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(redKings, piece[0]+1, piece[1]+1) blackThreat.append(threat) # add black threat legalMoves.append([blackPieces.index(piece), piece[0]+2, piece[1]+2, threat, "regular", "king"]) # move DOWN and to the LEFT if (piece[0] + 1) < 8 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] - 1] == " ": legalMoves.append([blackPieces.index(piece), piece[0]+1, piece[1]-1, -1, "regular", "None"]) # Elimination if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] - 1] == "r" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(redPieces, piece[0]+1, piece[1]-1) blackThreat.append(threat) # add black threat legalMoves.append([blackPieces.index(piece), piece[0]+2, piece[1]-2, threat, "regular", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] - 1] == "R" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(redKings, piece[0]+1, piece[1]-1) blackThreat.append(threat) # add black threat legalMoves.append([blackPieces.index(piece), piece[0]+2, piece[1]-2, threat, "regular", "king"]) return legalMoves # Helper function to getLegalMoves - details game code for King behaviour def getKingMoves(self, legalMoves, currentTurn, redPieces, blackPieces, redKings, blackKings, redThreat, blackThreat, board): # For red player if currentTurn == "red": for piece in redKings: # move UP and to the RIGHT if (piece[0] - 1) > -1 and (piece[1] + 1) < 8: # check bounds # Regular diagonal if board[piece[0] - 1][piece[1] + 1] == " ": legalMoves.append([redKings.index(piece), piece[0]-1, piece[1]+1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds # Regular elimination if board[piece[0] - 1][piece[1] + 1] == "b" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(blackPieces, piece[0]-1, piece[1]+1) redThreat.append(threat) legalMoves.append([redKings.index(piece), piece[0]-2, piece[1]+2, threat, "king", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] + 1] == "B" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(blackKings, piece[0]-1, piece[1]+1) redThreat.append(threat) legalMoves.append([redKings.index(piece), piece[0]-2, piece[1]+2, threat, "king", "king"]) # move UP and to the LEFT if (piece[0] - 1) > -1 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] - 1][piece[1] - 1] == " ": legalMoves.append([redKings.index(piece), piece[0]-1, piece[1]-1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] - 1][piece[1] - 1] == "b" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(blackPieces, piece[0]-1, piece[1]-1) redThreat.append(threat) legalMoves.append([redKings.index(piece), piece[0]-2, piece[1]-2, threat, "king", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] - 1] == "B" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(blackKings, piece[0]-1, piece[1]-1) redThreat.append(threat) legalMoves.append([redKings.index(piece), piece[0]-2, piece[1]-2, threat, "king", "king"]) # move DOWN and to the RIGHT if (piece[0] + 1) < 8 and (piece[1] + 1) < 8: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] + 1] == " ": legalMoves.append([redKings.index(piece), piece[0]+1, piece[1]+1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] + 1] == "b" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(blackPieces, piece[0]+1, piece[1]+1) redThreat.append(threat) # add black threat legalMoves.append([redKings.index(piece), piece[0]+2, piece[1]+2, threat, "king", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] + 1] == "B" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(blackKings, piece[0]+1, piece[1]+1) redThreat.append(threat) # add black threat legalMoves.append([redKings.index(piece), piece[0]+2, piece[1]+2, threat, "king", "king"]) # move DOWN and to the LEFT if (piece[0] + 1) < 8 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] - 1] == " ": legalMoves.append([redKings.index(piece), piece[0]+1, piece[1]-1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] - 1] == "b" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(blackPieces, piece[0]+1, piece[1]-1) redThreat.append(threat) # add black threat legalMoves.append([redKings.index(piece), piece[0]+2, piece[1]-2, threat, "king", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] - 1] == "B" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(blackKings, piece[0]+1, piece[1]-1) redThreat.append(threat) # add black threat legalMoves.append([redKings.index(piece), piece[0]+2, piece[1]-2, threat, "king", "king"]) elif currentTurn == "black": for piece in blackKings: # move UP and to the RIGHT if (piece[0] - 1) > -1 and (piece[1] + 1) < 8: # check bounds # Regular diagonal if board[piece[0] - 1][piece[1] + 1] == " ": legalMoves.append([blackKings.index(piece), piece[0]-1, piece[1]+1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds # Regular Elimination if board[piece[0] - 1][piece[1] + 1] == "r" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(redPieces, piece[0]-1, piece[1]+1) blackThreat.append(threat) legalMoves.append([blackKings.index(piece), piece[0]-2, piece[1]+2, threat, "king", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] + 1] == "R" and board[piece[0] - 2][piece[1] + 2] == " ": threat = self.getIndex(redKings, piece[0]-1, piece[1]+1) blackThreat.append(threat) legalMoves.append([blackKings.index(piece), piece[0]-2, piece[1]+2, threat, "king", "king"]) # move UP and to the LEFT if (piece[0] - 1) > -1 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] - 1][piece[1] - 1] == " ": legalMoves.append([blackKings.index(piece), piece[0]-1, piece[1]-1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] - 1][piece[1] - 1] == "r" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(redPieces, piece[0]-1, piece[1]-1) blackThreat.append(threat) legalMoves.append([blackKings.index(piece), piece[0]-2, piece[1]-2, threat, "king", "regular"]) # King Elimination if board[piece[0] - 1][piece[1] - 1] == "R" and board[piece[0] - 2][piece[1] - 2] == " ": threat = self.getIndex(redKings, piece[0]-1, piece[1]-1) blackThreat.append(threat) legalMoves.append([blackKings.index(piece), piece[0]-2, piece[1]-2, threat, "king", "king"]) # move DOWN and to the RIGHT if (piece[0] + 1) < 8 and (piece[1] + 1) < 8: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] + 1] == " ": legalMoves.append([blackKings.index(piece), piece[0]+1, piece[1]+1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] + 1] == "r" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(redPieces, piece[0]+1, piece[1]+1) blackThreat.append(threat) # add black threat legalMoves.append([blackKings.index(piece), piece[0]+2, piece[1]+2, threat, "king", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] + 1] == "R" and board[piece[0]+2][piece[1]+2] == " ": threat = self.getIndex(redKings, piece[0]+1, piece[1]+1) blackThreat.append(threat) # add black threat legalMoves.append([blackKings.index(piece), piece[0]+2, piece[1]+2, threat, "king", "king"]) # move DOWN and to the LEFT if (piece[0] + 1) < 8 and (piece[1] - 1) > -1: # check bounds # Regular Diagonal if board[piece[0] + 1][piece[1] - 1] == " ": legalMoves.append([blackKings.index(piece), piece[0]+1, piece[1]-1, -1, "king", "None"]) # Diagonal Elimination if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds # Regular Elimination if board[piece[0] + 1][piece[1] - 1] == "r" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(redPieces, piece[0]+1, piece[1]-1) blackThreat.append(threat) # add black threat legalMoves.append([blackKings.index(piece), piece[0]+2, piece[1]-2, threat, "king", "regular"]) # King Elimination if board[piece[0] + 1][piece[1] - 1] == "R" and board[piece[0]+2][piece[1]-2] == " ": threat = self.getIndex(redKings, piece[0]+1, piece[1]-1) blackThreat.append(threat) # add black threat legalMoves.append([blackKings.index(piece), piece[0]+2, piece[1]-2, threat, "king", "king"]) # This is a helper function to getLegalMoves - It retrives the index of the piece that has been eliminated def getIndex(self, pieces, i, j): for piece in pieces: if piece[0] == i and piece[1] == j: return pieces.index(piece) # return the index of the piece that has been eliminated return None # This function retrives the best move from legalMoves using the target function hypothesis def getBestMove(self, gameState, legalMoves, v1, v2): rand = random.randint(3,4) if rand % 2 == 0: return legalMoves[random.randint(0,len(legalMoves)-1)] prediction = [] bestMove = [] if len(legalMoves) == 1: return legalMoves[0] for move in legalMoves: if gameState.currentTurn == "red": prediction.append(self.getPrediction(gameState, move, v1)) elif gameState.currentTurn == "black": prediction.append(self.getPrediction(gameState, move, v2)) maxVal = max(prediction) for move in legalMoves: if gameState.currentTurn == "red": if self.getPrediction(gameState, move, v1) == maxVal: bestMove = move elif gameState.currentTurn == "black": if self.getPrediction(gameState, move, v2) == maxVal: bestMove = move return bestMove # This function gets the output of the target hypothesis evaluated at the game state that succeeds a given move def getPrediction(self, gameState, move, v): # get blackThreat and redThreat by calling the functions if gameState.currentTurn == "red": v4 = v[4]*self.getRedThreat(gameState, move) v5 = v[5]*len(gameState.blackThreat) elif gameState.currentTurn == "black": v5 = v[5]*self.getBlackThreat(gameState, move) v4 = v[4]*len(gameState.redThreat) # Logic for red if gameState.currentTurn == "red": if move[4] == "regular": if move[1] == 0: v1 = v[1]*len(gameState.redPieces) - 1 v3 = v[3]*len(gameState.redKings) + 1 else: v1 = v[1]*len(gameState.redPieces) v3 = v[3]*len(gameState.redKings) elif move[4] == "king": v1 = v[1]*len(gameState.redPieces) v3 = v[3]*len(gameState.redKings) if move[5] == "None": v0 = v[0]*len(gameState.blackPieces) v2 = v[2]*len(gameState.blackKings) elif move[5] == "regular": v0 = v[0]*len(gameState.blackPieces) - 1 v2 = v[2]*len(gameState.blackKings) elif move[5] == "king": v0 = v[0]*len(gameState.blackPieces) v2 = v[2]*len(gameState.blackKings) - 1 # Logic for black elif gameState.currentTurn == "black": if move[4] == "regular": if move[1] == 0: v1 = v[1]*len(gameState.blackPieces) - 1 v3 = v[3]*len(gameState.blackKings) + 1 else: v1 = v[1]*len(gameState.blackPieces) v3 = v[3]*len(gameState.blackKings) elif move[4] == "king": v1 = v[1]*len(gameState.blackPieces) v3 = v[3]*len(gameState.blackKings) if move[5] == "None": v0 = v[0]*len(gameState.redPieces) v2 = v[2]*len(gameState.redKings) elif move[5] == "regular": v0 = v[0]*len(gameState.redPieces) - 1 v2 = v[2]*len(gameState.redKings) elif move[5] == "king": v0 = v[0]*len(gameState.redPieces) v2 = v[2]*len(gameState.redKings) - 1 val = v0 + v1 + v2 + v3 + v4 + v5 return val # This function finds the number of black pieces threatned by red for a given hypothetical move def getRedThreat(self, gameState, move): board = gameState.board i = move[1] j = move[2] redThreat = 0 # Make deep copies to avoid aliasing issues tempRedPieces = copy.deepcopy(gameState.redPieces) tempRedKings = copy.deepcopy(gameState.redKings) # Make hypothetical move if move[4] == "regular": tempRedPieces[move[0]] = [i, j] # update location of piece elif move[4] == "king": tempRedKings[move[0]] = [i, j] # update location of piece # Scan the board for threats made by regular red pieces for piece in tempRedPieces: # check UP and to the RIGHT if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] - 1][piece[1] + 1] == "b" and board[piece[0] - 2][piece[1] + 2] == " ": redThreat = redThreat + 1 elif board[piece[0] - 1][piece[1] + 1] == "B" and board[piece[0] - 2][piece[1] + 2] == " ": redThreat = redThreat + 1 # check UP and to the LEFT if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] - 1][piece[1] - 1] == "b" and board[piece[0] - 2][piece[1] - 2] == " ": redThreat = redThreat + 1 elif board[piece[0] - 1][piece[1] - 1] == "B" and board[piece[0] - 2][piece[1] - 2] == " ": redThreat = redThreat + 1 # Scan the board for threats made by red kings for piece in tempRedKings: # check UP and to the RIGHT if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] - 1][piece[1] + 1] == "b" and board[piece[0] - 2][piece[1] + 2] == " ": redThreat = redThreat + 1 elif board[piece[0] - 1][piece[1] + 1] == "B" and board[piece[0] - 2][piece[1] + 2] == " ": redThreat = redThreat + 1 # check UP and to the LEFT if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] - 1][piece[1] - 1] == "b" and board[piece[0] - 2][piece[1] - 2] == " ": redThreat = redThreat + 1 elif board[piece[0] - 1][piece[1] - 1] == "B" and board[piece[0] - 2][piece[1] - 2] == " ": redThreat = redThreat + 1 # check DOWN and to the RIGHT if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] + 1][piece[1] + 1] == "b" and board[piece[0]+2][piece[1]+2] == " ": redThreat = redThreat + 1 elif board[piece[0] + 1][piece[1] + 1] == "B" and board[piece[0]+2][piece[1]+2] == " ": redThreat = redThreat + 1 # check DOWN and to the LEFT if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] + 1][piece[1] - 1] == "b" and board[piece[0]+2][piece[1]-2] == " ": redThreat = redThreat + 1 elif board[piece[0] + 1][piece[1] - 1] == "B" and board[piece[0]+2][piece[1]-2] == " ": redThreat = redThreat + 1 return redThreat # This function finds the number of red pieces threatned by black for a given hypothetical move def getBlackThreat(self, gameState, move): board = gameState.board i = move[1] j = move[2] blackThreat = 0 # Make deep copies to avoid aliasing issues tempBlackPieces = copy.deepcopy(gameState.blackPieces) tempBlackKings = copy.deepcopy(gameState.blackKings) # Make hypothetical move if move[4] == "regular": tempBlackPieces[move[0]] = [i, j] # update location of piece elif move[4] == "king": tempBlackKings[move[0]] = [i, j] # update location of piece # Scan the board for threats made by regular black pieces for piece in tempBlackPieces: # check DOWN and to the RIGHT if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] + 1][piece[1] + 1] == "r" and board[piece[0]+2][piece[1]+2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] + 1][piece[1] + 1] == "R" and board[piece[0]+2][piece[1]+2] == " ": blackThreat = blackThreat + 1 # check DOWN and to the LEFT if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] + 1][piece[1] - 1] == "r" and board[piece[0]+2][piece[1]-2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] + 1][piece[1] - 1] == "R" and board[piece[0]+2][piece[1]-2] == " ": blackThreat = blackThreat + 1 # Scan the board for threats made by black kings for piece in tempBlackKings: # check UP and to the RIGHT if (piece[0] - 2) > -1 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] - 1][piece[1] + 1] == "r" and board[piece[0] - 2][piece[1] + 2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] - 1][piece[1] + 1] == "R" and board[piece[0] - 2][piece[1] + 2] == " ": blackThreat = blackThreat + 1 # check UP and to the LEFT if (piece[0] - 2) > -1 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] - 1][piece[1] - 1] == "r" and board[piece[0] - 2][piece[1] - 2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] - 1][piece[1] - 1] == "R" and board[piece[0] - 2][piece[1] - 2] == " ": blackThreat = blackThreat + 1 # move DOWN and to the RIGHT if (piece[0] + 2) < 8 and (piece[1] + 2) < 8: # check double bounds if board[piece[0] + 1][piece[1] + 1] == "r" and board[piece[0]+2][piece[1]+2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] + 1][piece[1] + 1] == "R" and board[piece[0]+2][piece[1]+2] == " ": blackThreat = blackThreat + 1 # check DOWN and to the LEFT if (piece[0] + 2) < 8 and (piece[1] - 2) > -1: # check double bounds if board[piece[0] + 1][piece[1] - 1] == "r" and board[piece[0]+2][piece[1]-2] == " ": blackThreat = blackThreat + 1 elif board[piece[0] + 1][piece[1] - 1] == "R" and board[piece[0]+2][piece[1]-2] == " ": blackThreat = blackThreat + 1 return blackThreat # This function makes a given move by updating the game board, the pieces lists, and removing any eliminated pieces def makeMove(self, gameState, move): i = move[1] # row position of target location on board j = move[2] # column position of target location on board if gameState.currentTurn == "red": if move[4] == "regular": # Regular Diagonal if move[3] == -1: gameState.board[i][j] = "r" gameState.board[gameState.redPieces[move[0]][0]][gameState.redPieces[move[0]][1]] = " " # add whitespace to previous position gameState.redPieces[move[0]][0] = i # update row position of red piece gameState.redPieces[move[0]][1] = j # update column position of red piece # Elimination elif move[3] > -1: # Regular Elimination if move[5] == "regular": gameState.board[i][j] = "r" gameState.board[gameState.redPieces[move[0]][0]][gameState.redPieces[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.blackPieces[move[3]][0]][gameState.blackPieces[move[3]][1]] = " " gameState.blackPieces.pop(move[3]) gameState.redPieces[move[0]][0] = i # update row position of red piece gameState.redPieces[move[0]][1] = j # update column position of red piece # King Elimination elif move[5] == "king": gameState.board[i][j] = "r" gameState.board[gameState.redPieces[move[0]][0]][gameState.redPieces[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.blackKings[move[3]][0]][gameState.blackKings[move[3]][1]] = " " gameState.blackKings.pop(move[3]) gameState.redPieces[move[0]][0] = i # update row position of red piece gameState.redPieces[move[0]][1] = j # update column position of red piece # Promotion to king if i == 0: gameState.board[i][j] = "R" gameState.redKings.append(gameState.redPieces[move[0]]) # add a new red king gameState.redPieces.pop(move[0]) # remove the promoted piece from redPieces if move[4] == "king": if move[3] == -1: # No piece being eliminated gameState.board[i][j] = "R" gameState.board[gameState.redKings[move[0]][0]][gameState.redKings[move[0]][1]] = " " # add whitespace to previous position gameState.redKings[move[0]][0] = i # update row position of red piece gameState.redKings[move[0]][1] = j # update column position of red piece else: # Regular Elimination if move[5] == "regular": gameState.board[i][j] = "R" gameState.board[gameState.redKings[move[0]][0]][gameState.redKings[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.blackPieces[move[3]][0]][gameState.blackPieces[move[3]][1]] = " " gameState.blackPieces.pop(move[3]) gameState.redKings[move[0]][0] = i # update row position of red piece gameState.redKings[move[0]][1] = j # update column position of red piece # King Elimination elif move[5] == "king": gameState.board[i][j] = "R" gameState.board[gameState.redKings[move[0]][0]][gameState.redKings[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.blackKings[move[3]][0]][gameState.blackKings[move[3]][1]] = " " gameState.blackKings.pop(move[3]) gameState.redKings[move[0]][0] = i # update row position of red piece gameState.redKings[move[0]][1] = j # update column position of red piece gameState.currentTurn = "black" elif gameState.currentTurn == "black": if move[4] == "regular": # Regular Diagonal if move[3] == -1: gameState.board[i][j] = "b" gameState.board[gameState.blackPieces[move[0]][0]][gameState.blackPieces[move[0]][1]] = " " # add whitespace to previous position gameState.blackPieces[move[0]][0] = i # update row position of red piece gameState.blackPieces[move[0]][1] = j # update column position of red piece else: # Regular Elimination if move[5] == "regular": gameState.board[i][j] = "b" gameState.board[gameState.blackPieces[move[0]][0]][gameState.blackPieces[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.redPieces[move[3]][0]][gameState.redPieces[move[3]][1]] = " " gameState.redPieces.pop(move[3]) gameState.blackPieces[move[0]][0] = i # update row position of red piece gameState.blackPieces[move[0]][1] = j # update column position of red piece # King Elimination elif move[5] == "king": gameState.board[i][j] = "b" gameState.board[gameState.blackPieces[move[0]][0]][gameState.blackPieces[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.redKings[move[3]][0]][gameState.redKings[move[3]][1]] = " " gameState.redKings.pop(move[3]) gameState.blackPieces[move[0]][0] = i # update row position of red piece gameState.blackPieces[move[0]][1] = j # update column position of red piece # Promotion to king if i == 7: gameState.board[i][j] = "B" gameState.blackKings.append(gameState.blackPieces[move[0]]) # add a new black king gameState.blackPieces.pop(move[0]) # remove black piece if move[4] == "king": if move[3] == -1: # No piece being eliminated gameState.board[i][j] = "B" gameState.board[gameState.blackKings[move[0]][0]][gameState.blackKings[move[0]][1]] = " " # add whitespace to previous position gameState.blackKings[move[0]][0] = i # update row position of red piece gameState.blackKings[move[0]][1] = j # update column position of red piece # Regular Elimination if move[5] == "regular": gameState.board[i][j] = "B" gameState.board[gameState.blackKings[move[0]][0]][gameState.blackKings[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.redPieces[move[3]][0]][gameState.redPieces[move[3]][1]] = " " gameState.redPieces.pop(move[3]) gameState.blackKings[move[0]][0] = i # update row position of red piece gameState.blackKings[move[0]][1] = j # update column position of red piece # King Elimination elif move[5] == "king": gameState.board[i][j] = "B" gameState.board[gameState.blackKings[move[0]][0]][gameState.blackKings[move[0]][1]] = " " # add whitespace to previous position gameState.board[gameState.redKings[move[3]][0]][gameState.redKings[move[3]][1]] = " " gameState.redKings.pop(move[3]) gameState.blackKings[move[0]][0] = i # update row position of red piece gameState.blackKings[move[0]][1] = j # update column position of red piece gameState.currentTurn = "red" # This function takes as input an initial board state and function hypothesis and produces a list containing the game trace for a given game def getTrace(self, trainingExperiment, currentHypothesis1, currentHypothesis2): redTraceHistory = [] blackTraceHistory = [] board = copy.deepcopy(trainingExperiment) v1 = copy.deepcopy(currentHypothesis1) v2 = copy.deepcopy(currentHypothesis2) # 2D List containing red pieces and their positions on the above board redPieces = [ [5, 1], [5, 3], [5, 5], [5, 7], [6, 0], [6, 2], [6, 4], [6, 6], [7, 1], [7, 3], [7, 5], [7, 7], ] # 2D List containing black pieces and their positions on the above board blackPieces = [ [0, 0], [0, 2], [0, 4], [0, 6], [1, 1], [1, 3], [1, 5], [1, 7], [2, 0], [2, 2], [2, 4], [2, 6], ] redKings = [] # List of red kings is empty at game start blackKings = [] # List of black kings is empty at game start redThreat = [] # List of black pieces threatned by red is empty at game start blackThreat = [] # List of red pieces threatned by black is empty at game start currentTurn = "red" # Assume red always goes first at start of game gameState = GameState(currentTurn, redPieces, blackPieces, redKings, blackKings, redThreat, blackThreat, board) # Instantiate the initial game state while gameState.isOver == False: # Keep iterating until game is over if gameState.currentTurn == "red": redTraceHistory.append(gameState.info) elif gameState.currentTurn == "black": blackTraceHistory.append(gameState.info) if len(redTraceHistory) > 10000: # Impose hard limit on number of turns break self.runGame(gameState, v1, v2) if gameState.currentTurn == "red": redTraceHistory.append(gameState.info) elif gameState.currentTurn == "black": blackTraceHistory.append(gameState.info) return [redTraceHistory, blackTraceHistory]
true
a5de5b8629b94bb6cc55750202e7b230c6d8d8b1
Python
IgnacioSallaberry/RICS
/histogramas monomeros y oligomeros.py
UTF-8
5,276
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Apr 9 20:25:06 2019 @author: Ignacio Sallaberry """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import re guardar_imagenes = True #============================================================================== # Tipografía de los gráficos #============================================================================== plt.close('all') # amtes de graficar, cierro todos las figuras que estén abiertas SMALL_SIZE = 54 MEDIUM_SIZE = 70 BIGGER_SIZE = 75 plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=22) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title #mpl.rcParams['axes.linewidth'] = 1 ## maneja el ancho de las lineas del recuadro de la figura #============================================================================== #============================================================================== #23hs_cell4_rics_cyto_DIFFERENCE_DIFUSION with open('C:\\Users\\ETCasa\\Desktop\\monomeros_NandB_histograma.txt') as fobj: monomeros = fobj.read() monomeros = re.split('\t|\n', monomeros) monomeros.remove('X') monomeros.remove('BarSeries1') monomeros.remove('') monomeros.remove('') with open('C:\\Users\\ETCasa\\Desktop\\oligomeros_NandB_histograma.txt') as fobj: oligomeros = fobj.read() oligomeros = re.split('\t|\n', oligomeros) oligomeros.remove('X') oligomeros.remove('BarSeries1') oligomeros.remove('') oligomeros.remove('') MONOMEROS_brillo=[] MONOMEROS_pixel=[] OLIGOMEROS_brillo=[] OLIGOMEROS_pixel=[] i=0 while i< len(monomeros): MONOMEROS_brillo.append(float(monomeros [i])) MONOMEROS_pixel.append(float(monomeros [i+1])) OLIGOMEROS_brillo.append(float(oligomeros [i])) OLIGOMEROS_pixel.append(float(oligomeros [i+1])) i+=2 #============================================================================== #============================================================================== # CALCULAR LA MEDIA, LA DESVIACIÓN ESTÁNDAR DE LOS DATOS y EL NÚMERO TOTAL DE CUENTAS #============================================================================== # #mu_ajuste_MONOM=np.mean(MONOMEROS_brillo) # media #sigma_ajuste_MONOM=np.std(MONOMEROS_brillo) #desviación estándar std = sqrt(mean(abs(x - x.mean())**2)) #N_ajuste_MONOM=len(MONOMEROS_pixel) # número de mediciones #std_err_ajuste_MONOM= sigma_ajuste_MONOM / N_ajuste_MONOM # error estándar # # # #def Gaussiana(mu,sigma): # # x_inicial = 0 # x_final = mu+2*sigma # x_gaussiana=np.linspace(x_inicial,x_final,num=100) # armo una lista de puntos donde quiero graficar la distribución de ajuste # ## gaussiana3=(1/np.sqrt(2*np.pi*(sigma**2)))*np.exp((-.5)*((x_gaussiana-mu)/(sigma))**2) # gaussiana3=np.exp((-.5)*((x_gaussiana-mu)/(sigma))**2) # # return (x_gaussiana,gaussiana3) ###============================================================================== ### Diferencias ajuste por Difusion ###============================================================================== # #plt.plot(Gaussiana(2.7,0.48)[0], # Gaussiana(2.7,0.48)[1], # '--', color='tomato', label='Ajuste: Difusión \n $\mu$= {:10.3E} $\\sigma$ = {:10.3E}'.format(mu_ajuste_MONOM, sigma_ajuste_MONOM) # # ) plt.figure(figsize=(19,12)) plt.bar(MONOMEROS_brillo, MONOMEROS_pixel,linewidth=3,log=True, color='darkcyan') plt.xlim([0,max(OLIGOMEROS_brillo)+1]) #plt.xlim([0,max(MONOMEROS_brillo)+1]) plt.ylim([0,max(MONOMEROS_pixel)]) plt.xlabel('Brillo') plt.ylabel('Número\n de píxeles') plt.tick_params(which='minor', length=8, width=3.5) plt.tick_params(which='major', length=10, width=5) figManager = plt.get_current_fig_manager() #### esto y la linea de abajo me maximiza la ventana de la figura figManager.window.showMaximized() #### esto y la linea de arriba me maximiza la ventana de la figura plt.show() if guardar_imagenes: plt.savefig('C:\\Users\\ETCasa\\Desktop\\histograma_monomeros.svg', format='svg') plt.figure(figsize=(19,12)) plt.bar(OLIGOMEROS_brillo, OLIGOMEROS_pixel,linewidth=3,log=True, color='darkcyan') plt.xlabel('Brillo') plt.ylabel('Número\n de píxeles') plt.xlim([0,max(OLIGOMEROS_brillo)+1]) plt.ylim([0,max(MONOMEROS_pixel)]) plt.tick_params(which='minor', length=8, width=3.5) plt.tick_params(which='major', length=10, width=5) figManager = plt.get_current_fig_manager() #### esto y la linea de abajo me maximiza la ventana de la figura figManager.window.showMaximized() #### esto y la linea de arriba me maximiza la ventana de la figura plt.show() if guardar_imagenes: plt.savefig('C:\\Users\\ETCasa\\Desktop\\histograma_oligomeros.svg', format='svg')
true
a4771a0fdfcc7fcb247892a4bda2943ca2ae1ea2
Python
ash/amazing_python3
/166-filter.py
UTF-8
256
4.625
5
[]
no_license
# Using "filter" to select items # bases on some condition # Here's the condition: def is_odd(x): return x % 2 data = [1, 2, 3, 4, 5, 6, 7, 8, 9] data = filter(is_odd, data) # Object of the "filter" type data = list(data) # a list again print(data)
true
cb3a778c81a05268a4a93ab4487f4f88b0fef2a8
Python
lucaspsimpson/IndividualProject
/python/QuadTree.py
UTF-8
3,124
3.21875
3
[]
no_license
import numpy as np from matplotlib import pyplot as plt #---------------------------------------------------------------------- # This function adjusts matplotlib settings for a uniform feel in the textbook. # Note that with usetex=True, fonts are rendered with LaTeX. This may # result in an error if LaTeX is not installed on your system. In that case, # you can set usetex to False. from astroML.plotting import setup_text_plots setup_text_plots(fontsize=8, usetex=False) # We'll create a QuadTree class which will recursively subdivide the # space into quadrants class QuadTree: """Simple Quad-tree class""" # class initialization function def __init__(self, data, mins, maxs, depth=3): self.data = np.asarray(data) # data should be two-dimensional #assert self.data.shape[1] == 2 if mins is None: mins = data.min(0) if maxs is None: maxs = data.max(0) self.mins = np.asarray(mins) self.maxs = np.asarray(maxs) self.sizes = self.maxs - self.mins self.children = [] mids = 0.5 * (self.mins + self.maxs) xmin, ymin = self.mins xmax, ymax = self.maxs xmid, ymid = mids if depth > 0: # split the data into four quadrants data_q1 = data[(data[:, 0] < mids[0]) & (data[:, 1] < mids[1])] data_q2 = data[(data[:, 0] < mids[0]) & (data[:, 1] >= mids[1])] data_q3 = data[(data[:, 0] >= mids[0]) & (data[:, 1] < mids[1])] data_q4 = data[(data[:, 0] >= mids[0]) & (data[:, 1] >= mids[1])] # recursively build a quad tree on each quadrant which has data if data_q1.shape[0] > 0: self.children.append(QuadTree(data_q1, [xmin, ymin], [xmid, ymid], depth - 1)) if data_q2.shape[0] > 0: self.children.append(QuadTree(data_q2, [xmin, ymid], [xmid, ymax], depth - 1)) if data_q3.shape[0] > 0: self.children.append(QuadTree(data_q3, [xmid, ymin], [xmax, ymid], depth - 1)) if data_q4.shape[0] > 0: self.children.append(QuadTree(data_q4, [xmid, ymid], [xmax, ymax], depth - 1)) def draw_rectangle(self, ax, depth): """Recursively plot a visualization of the quad tree region""" if depth is None or depth == 0: rect = plt.Rectangle(self.mins, *self.sizes, zorder=2, ec='#000000', fc='none') ax.add_patch(rect) if depth is None or depth > 0: for child in self.children: child.draw_rectangle(ax, depth - 1)
true
365282b11461190ca825f1143b2d17dfb13c8b4e
Python
tomato-pan/Aim_to_offer
/useAlgorothms/isSymmetric.py
UTF-8
1,647
3.796875
4
[]
no_license
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque class Solution: # 递归 def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True def is_mirror(t1, t2): if t1 is None and t2 is None: return True if t1 is None or t2 is None or t1.val != t2.val: return False return is_mirror(t1.left, t2.right) and is_mirror(t1.right, t2.left) return is_mirror(root.left,root.right) # 迭代 def isSymmetric1(self, root: TreeNode) -> bool: if root is None: return True d = deque() d.appendleft(root.left) d.append(root.right) while d: left = d.popleft() right = d.pop() if not left and not right:continue if not left or not right or left.val != right.val:return False d.appendleft(left.right) d.appendleft(left.left) d.append(right.left) d.append(right.right) return True def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: if not root:return False if not root.left and not root.right: return root.val==targetSum return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val) if __name__ == '__main__': t1 = TreeNode(val=3) t1.left = TreeNode(val=1) t1.right = TreeNode(val=1) s = Solution() print(s.isSymmetric1(t1)) print(s.hasPathSum(t1,3))
true
208d65cc41059e5ad3b49ca6138f1c27d1df4b44
Python
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/42_5.py
UTF-8
2,779
4.09375
4
[]
no_license
Python – Remove after substring in String Given a String, remove all characters after particular substring. > **Input** : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “for” > **Output** : geeksforgeeks is best for > **Explanation** : everything removed after for. > > **Input** : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “is” > **Output** : geeksforgeeks is > **Explanation** : everything removed after is. **Method #1 : Using index() + len() + slicing** In this, we first get the index of substring to perform removal after, add to that its length using len() and then slice off elements after that string using slicing. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Remove after substring in String # Using index() + len() + slicing # initializing strings test_str = 'geeksforgeeks is best for geeks' # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # slicing off after length computation res = test_str[:test_str.index(sub_str) + len(sub_str)] # printing result print("The string after removal : " + str(res)) --- __ __ **Output** The original string is : geeksforgeeks is best for geeks The string after removal : geeksforgeeks is best **Method #2 : Using regex() ( for stripping off after numeric occurrence)** This is solution to a slightly different problem in which the string removal is required after numeric occurrence. We employ match operation and it retains all before match is found. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Remove after substring in String # Using regex() ( for stripping off after numeric occurrence) import re # initializing strings test_str = 'geeksforgeeks is best 4 geeks' # printing original string print("The original string is : " + str(test_str)) # slicing after the numeric occurrence res = re.match(r"(.*\d+)", test_str).group() # printing result print("The string after removal : " + str(res)) --- __ __ **Output** The original string is : geeksforgeeks is best 4 geeks The string after removal : geeksforgeeks is best 4 Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
true
40670baacf0b5f95bc382fa63657997b1e171c28
Python
MegumiDavid/python-projects
/turtle_python/angulos.py
UTF-8
1,080
3.4375
3
[]
no_license
from turtle import Turtle, Screen turtle = Turtle() turtle.shape("turtle") turtle.color("light salmon") #turtle.dot(size=5) #for c in range (50): # turtle.pendown() # turtle.forward(10) # turtle.penup() # turtle.forward(10) #def the_beauty_of_simetric() pen_color = ['dark orange','firebrick','medium violet red','forest green', 'medium sea green','cornflower blue','yellow','salmon','red'] i = 0 for c in range (3,11): color = pen_color[i] for i in range (c): turtle.pencolor(color) turtle.forward(100) turtle.right(360/c) i+=1 ''' for c in range(4): turtle.forward(100) turtle.right(90) for c in range(5): turtle.forward(100) turtle.right(72) for c in range(6): turtle.forward(100) turtle.right(60) for c in range(7): turtle.forward(100) turtle.right(51.4285714286) for c in range(8): turtle.forward(100) turtle.right(45) ''' ''' jimmy_the_turtle.forward(100) jimmy_the_turtle.right(90) jimmy_the_turtle.forward(100) jimmy_the_turtle.right(90) jimmy_the_turtle.forward(100) ''' screen = Screen() screen.exitonclick
true
57b3b7ee8abb12ededc518bfd4ee21a32f3664f1
Python
Cvmaggio/ReinforcementLearningSutton-Barto
/examples/Example4-9GamblersProblem.py
UTF-8
1,576
2.875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from copy import deepcopy maxCapital = 128 theta = .00000000000001 gamma = 1 pH = .4 largestAvailableBet = {} for s in range(0,maxCapital+1): largestAvailableBet[s] = min(s,maxCapital-s) V = np.zeros(maxCapital + 1) R = np.zeros(maxCapital + 1) V[maxCapital] = 1 #Reward for reaching terminal state sweeps = [] sweepsmeta = [] def psrsa(pH,s,a): if s == 0: return {s:1} if s == maxCapital: return {s:1} return {(s+a):pH,(s-a):(1-pH)} def bellman(s,retType: bool): bestAction = 0 maxValue = 0 for a in range(largestAvailableBet[s]+1): probs = psrsa(pH,s,a) value = sum((probs[k]*(R[k]+gamma*V[k])) for k in probs) if value > maxValue+10e-16: bestAction = a maxValue = value # if value >= maxValue: # bestAction = a # maxValue = value if retType: return bestAction return maxValue def valueIteration(): while True: delta = 0 for s in range(1,maxCapital): vi = V[s] V[s] = bellman(s,False) delta = max(delta, abs(vi-V[s])) sweeps.append(deepcopy(V)) if delta < theta: break actions = [0] for s in range(1,maxCapital): actions.append(bellman(s,True)) return actions if __name__ == "__main__": actions = valueIteration() print(actions) plt.figure() for sweep in sweeps: plt.plot(sweep) plt.figure() plt.plot(actions,'o') plt.show()
true
fd2949b19e83963d3704256e063f532f4433639d
Python
StyvenSoft/degree-python
/Lesson7_ChallengeLoops/3-Greetings.py
UTF-8
296
4.28125
4
[ "MIT" ]
permissive
#Write your function here def add_greetings(names): new_list = [] for name in names: new_list.append("Hello, " + name) return new_list #Uncomment the line below when your function is done print(add_greetings(["Owen", "Max", "Sophie"])) # ['Hello, Owen', 'Hello, Max', 'Hello, Sophie']
true
89fb9a8aee44e7bbeb6f36c0ed2319d4fc6d74bf
Python
IlkoAng/Python-Advanced-Softuni
/Exercise 4 Comprehensions/02. Words Lengths.py
UTF-8
90
3.75
4
[]
no_license
text = input().split(", ") print(f', '.join([f"{name} -> {len(name)}" for name in text]))
true
8cacaa0353b8c4ae7a3972a3743728dd3434bdae
Python
yanigisawa/coffee-scale
/test_coffee_scale.py
UTF-8
3,846
2.71875
3
[ "MIT" ]
permissive
import unittest import coffee_scale as cs from datetime import datetime, timedelta class CoffeeTest(unittest.TestCase): def setUp(self): self.scale = cs.CoffeeScale() def test_whenValueChangesLessThanThreshold_LogIsNotWritten(self): self.scale._currentWeight = 20 self.scale._threshold = 5 shouldLogItem = self.scale.shouldLogWeight(21) self.assertEquals(False, shouldLogItem) def test_whenValueChangesGreaterThanThreshold_LogIsWritten(self): self.scale._currentWeight = 1 self.scale._threshold = 5 shouldLogItem = self.scale.shouldLogWeight(7) self.assertEquals(True, shouldLogItem) def test_whenValueIsAtLowThreshold_PotHasBeenLifted(self): potIsLifted = self.scale.potIsLifted() self.assertEquals(True, potIsLifted) def test_whenLoopedConfiguredTimes_PostMessageToHipchat(self): self.scale._loopCount = 40 self.assertEquals(True, self.scale.shouldPostToHipChat()) def test_whenLoopCountNotEqualConfiguredTimes_MessageNotPostedToHipChat(self): for i in range(40): self.scale._loopCount = i self.assertEquals(False, self.scale.shouldPostToHipChat()) def test_hipchatUserIsGiven_WithAMultipleOfNumberOfMugsInPot(self): self.scale._currentWeight = 2264 self.scale._mugAmounts = self.scale.calculateMugAmounts(2380) self.scale._potWeight = 906 self.assertEquals(5, self.scale.getAvailableMugs()) self.scale._currentWeight = 1999 self.assertEquals(4, self.scale.getAvailableMugs(), "{0} did not equal 4 mugs".format(self.scale._currentWeight)) self.scale._currentWeight = 1733 self.assertEquals(3, self.scale.getAvailableMugs()) self.scale._currentWeight = 1467 self.assertEquals(2, self.scale.getAvailableMugs()) self.scale._currentWeight = 1201 self.assertEquals(1, self.scale.getAvailableMugs()) def test_whenWeightWithin90PercentMinus10GramsOfFullMug_RegisterNextAvailableMug(self): self.scale._currentWeight = 1164 self.scale._mugAmounts = self.scale.calculateMugAmounts(2380) self.scale._potWeight = 906 self.assertEquals(1, self.scale.getAvailableMugs()) self.scale._currentWeight = 1430 self.assertEquals(2, self.scale.getAvailableMugs()) self.scale._currentWeight = 1696 self.assertEquals(3, self.scale.getAvailableMugs()) self.scale._currentWeight = 1962 self.assertEquals(4, self.scale.getAvailableMugs()) self.scale._currentWeight = 2228 self.assertEquals(5, self.scale.getAvailableMugs()) def test_hipChatMessage_IncludesNumberOfMugs_AndWeightOfPot(self): self.scale._currentWeight = 1173 params = self.scale.getHipchatParameters() totalAvailableMugs = len(self.scale._mugAmounts) self.assertEquals("{0} / {1}".format( self.scale.getAvailableMugs(), totalAvailableMugs), params['from']) self.assertEquals("{0} / {1}".format( self.scale._currentWeight, self.scale._mugAmounts[totalAvailableMugs - 1]), params['message']) def test_environmentVariables_AreSet(self): self.assertTrue(self.scale.environment) self.assertTrue(self.scale.redisMessageQueue) def test_ledMessage_containsOnlyMugsRemaining(self): self.scale._currentWeight = 2000 self.scale._mostRecentLiftedTime = datetime.now() self.assertEqual("-u {0} -t 4 mugs::".format( float(4) / 5), self.scale.getLedMessage()[1]) self.scale._currentWeight = 100 print(self.scale.getLedMessage()) self.assertTrue(self.scale.getLedMessage()[0] in self.scale._animations) def main(): unittest.main() if __name__ == '__main__': main()
true
b638357308fe417c8ba59736e8e9f680564435ff
Python
MikhailKaraganov/Repos1
/invest.py
UTF-8
265
3.09375
3
[]
no_license
START_SUM = 400000 NDS = 0.13 RATE = 0.07 nds = START_SUM * NDS def invest(start_sum, years): if (years >= 1): return start_sum + start_sum*RATE + invest(start_sum + start_sum*RATE, years - 1) else: return 0 print(invest(400000,30))
true
b9758bd6543997fedf63ac7cc00be09d1b898f81
Python
RameshOswal/forensic-audio-analysis
/audio.py
UTF-8
982
2.71875
3
[]
no_license
import librosa import numpy as np import matplotlib.pyplot as plt from subprocess import run # Parameters sampling_rate = 44100 # All clips will be converted to this rate duration = None # Clips will be trimmed to this length (seconds) def import_wav(file, plot=False): # Import raw data try: raw_data = librosa.load(file, sr=sampling_rate, mono=False, duration=duration) except: raise IOError('Give me an audio file which I can read!!') # Only use one channel if len(raw_data[0].shape) > 1: raw_data = (raw_data[0][0], raw_data[1]) if plot: plt.plot(raw_data[0]) plt.show() return raw_data def split_clips(file_list, location="./downloads/processed/", length="10"): for file in file_list: file_comp = file.split("/") file_noext = file_comp[-1][:-4] run(["ffmpeg", "-i", file, "-f", "segment", "-segment_time", length, "-c", "copy", location + file_noext + "_%03d.wav"])
true
a4aa9255757bbf1d37bda2f9abcbe2e32cb52f49
Python
Faydiamond/tablesfrec
/tablefrecuency.py
UTF-8
3,732
3.234375
3
[]
no_license
class table: def __init__(self): self.valores = [] self.xi =[] self.frabsoluta= [] self.frabsolutaacum =[] self.frerel =[] self.frerelper =[] self.frerelacumm =[] self.frerelacummper =[] self.muestra = int(input('por favor digite el numero total de datos de la muestra'))-1 #print('el valor de la muestra es: ' , self.muestra) self.agregar_Valores() self.mostrar_valores() self.all_calcules() self.frrelativee() self.frepercent() self.frepercentacum() #self.Shows() self.datfr() self.piee() self.barr() def agregar_Valores(self): self.i = 0 while (self.i<=self.muestra): self.valor = input('por favor digite el valor ') self.valores.append(self.valor) self.i+=1 def mostrar_valores(self): import collections self.howw = collections.Counter(self.valores) def all_calcules(self): self.x= 0 self.frrelativa = 0 for self.xii,self.frabs in self.howw.items(): self.x = self.x + self.frabs self.xi.append(self.xii) self.frabsoluta.append(self.frabs) self.frabsolutaacum.append(self.x ) def frrelativee(self): self.frrelative = 0 self.frrelativeacum = 0 for y in self.frabsoluta: self.frrelative = (y/(self.muestra+1)) self.frrelativeacum = self.frrelativeacum + self.frrelative self.frerel.append(self.frrelative) self.frerelacumm.append(self.frrelativeacum) def frepercent(self): for g in self.frerel: self.frpercent = g *100 #print('geeee', self.frpercent) self.frerelper.append(self.frpercent) def frepercentacum(self): for f in self.frerelacumm: self.facuper = f * 100 self.frerelacummper.append(self.facuper) def Shows(self): print('total de la muestra: ' ,self.valores) print ("xi",self.xi) print ("frecuencia absoluta ",self.frabsoluta) print ("frecuencia absoluta acumulada" ,self.frabsolutaacum) print ("frecuencia relativa : " , self.frerel) print ("frecuencia relativa en porcentaje: " , self.frerelper) print ("frecuencia relativa acumulada : " , self.frerelacumm) print ("frecuencia relativa acumulada en porcentaje: " , self.frerelacummper) def datfr(self): import pandas as pd #import matplotlib.pyplot as plt zippedList = list(zip(self.xi,self.frabsoluta, self.frabsolutaacum, self.frerel,self.frerelper,self.frerelacumm,self.frerelacummper)) self.table = pd.DataFrame(zippedList, columns = ['xi','FRecuencia absoluta','Frecuencia acumulada','Frecuencia relativa','Frecuencia relativa %','Frecuencia relativa acumulada','Frecuencia relativa acumulada %'], index= self.xi) #print(zippedList) print(self.table) def piee(self): import matplotlib.pyplot as plt myl=self.table['xi'] size = self.table['Frecuencia relativa %'] fig1, ax1 = plt.subplots() ax1.pie(size, labels=myl, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') plt.show() def barr (self): import matplotlib.pyplot as plt myl=self.table['xi'] size = self.table['Frecuencia relativa %'] fig, ax = plt.subplots() ax.set_ylabel('Porcentaje') ax.set_title('Porcentaje de frecuencia relativa') plt.bar(myl, size) plt.savefig('percentfrecuenciarelativa.png') plt.show() f=table()
true
7389c8ed64825a3dfe62bd7094175ad9b341bb41
Python
bahattin-urganci/python-training
/tuple.py
UTF-8
1,571
4.28125
4
[ "MIT" ]
permissive
def returntwo(v1,v2): c1=v1**v2 c2=v2*v1 #tuple üretmek aşağıdaki kadar basit parantez içerisinde ne döndürmek istiyorsan bas geç return (c1,c2) values = returntwo(2,4) print(values) # Define shout_all with parameters word1 and word2 def shout_all(word1,word2): # Concatenate word1 with '!!!': shout1 shout1=word1+"!!!" # Concatenate word2 with '!!!': shout2 shout2=word2+"!!!" # Construct a tuple with shout1 and shout2: shout_words shout_words=(shout1,shout2) # Return shout_words return shout_words # Pass 'congratulations' and 'you' to shout_all(): yell1, yell2 yell1,yell2=shout_all('congratulations','you') # Print yell1 and yell2 print(yell1) print(yell2) # Define three_shouts def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1),inner(word2),inner(word3)) # Call three_shouts() and print print(three_shouts('a', 'b', 'c')) # Define echo def echo(n): """Return the inner_echo function.""" # Define inner_echo def inner_echo(word1): """Concatenate n copies of word1.""" echo_word = word1 * n return echo_word # Return inner_echo return inner_echo # Call echo: twice twice = echo(2) # Call echo: thrice thrice=echo(3) # Call twice() and thrice() then print print(twice('hello'), thrice('hello'))
true
74d98e8359734e5ab434b63a9f396b124f42a8b6
Python
gviejo/Gohal
/run/Keramati/ReScience/Selection.py
UTF-8
6,365
2.625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Selection.py Class of for model selection when training first model <- Keramati et al, 2011 Copyright (c) 2013 Guillaume VIEJO. All rights reserved. """ import sys import os import numpy as np from fonctions import * class Keramati(): """Class that implement Keramati models for action selection """ def __init__(self, kalman,depth,phi, rau, sigma, tau): self.kalman = kalman self.depth = depth; self.phi = phi; self.rau = rau;self.sigma = sigma; self.tau = tau self.actions = kalman.actions; self.states = kalman.states self.values = createQValuesDict(kalman.states, kalman.actions) self.rfunction = createQValuesDict(kalman.states, kalman.actions) self.vpi = dict.fromkeys(self.states,list()) self.rrate = [0.0] self.state = None self.action = None self.transition = createTransitionDict(['s0','s0','s1','s1'], ['pl','em','pl','em'], ['s1','s0','s0',None], 's0') #<====VERY BAD============== NEXT_STATE = TRANSITION[(STATE, ACTION)] def initialize(self): self.values = createQValuesDict(self.states, self.actions) self.rfunction = createQValuesDict(self.states, self.actions) self.vpi = dict.fromkeys(self.states,list()) self.rrate = [0.0] self.state = None self.action = None self.transition = createTransitionDict(['s0','s0','s1','s1'], ['pl','em','pl','em'], ['s1','s0','s0',None], 's0') def chooseAction(self, state): self.state = state self.kalman.predictionStep() vpi = computeVPIValues(self.kalman.values[0][self.kalman.values[self.state]], self.kalman.covariance['cov'].diagonal()[self.kalman.values[self.state]]) for i in range(len(vpi)): if vpi[i] >= self.rrate[-1]*self.tau: depth = self.depth self.values[0][self.values[(self.state, self.actions[i])]] = self.computeGoalValue(self.state, self.actions[i], depth-1) else: self.values[0][self.values[(self.state, self.actions[i])]] = self.kalman.values[0][self.kalman.values[(self.state,self.actions[i])]] self.action = getBestActionSoftMax(state, self.values, self.kalman.beta) return self.action def updateValues(self, reward, next_state): self.updateRewardRate(reward, delay = 0.0) self.kalman.updatePartialValue(self.state, self.action, next_state, reward) self.updateRewardFunction(self.state, self.action, reward) self.updateTransitionFunction(self.state, self.action) def updateRewardRate(self, reward, delay = 0.0): self.rrate.append(((1-self.sigma)**(1+delay))*self.rrate[-1]+self.sigma*reward) def updateRewardFunction(self, state, action, reward): self.rfunction[0][self.rfunction[(state, action)]] = (1-self.rau)*self.rfunction[0][self.rfunction[(state, action)]]+self.rau*reward def updateTransitionFunction(self, state, action): #This is cheating since the transition is known inside the class #Plus assuming the transition are deterministic nextstate = self.transition[(state, action)] for i in [nextstate]: if i == nextstate: self.transition[(state, action, nextstate)] = (1-self.phi)*self.transition[(state, action, nextstate)]+self.phi else: self.transition[(state, action, i)] = (1-self.phi)*self.transition[(state, action, i)] def computeGoalValue(self, state, action, depth): next_state = self.transition[(state, action)] if next_state == None: return self.rfunction[0][self.rfunction[(state, action)]] + self.kalman.gamma*self.transition[(state, action, next_state)]*np.max(self.kalman.values[0][self.kalman.values[self.transition[None]]]) else: tmp = np.max([self.computeGoalValueRecursive(next_state, a, depth-1) for a in self.values[next_state]]) value = self.rfunction[0][self.rfunction[(state, action)]] + self.kalman.gamma*self.transition[(state, action, next_state)]*tmp return value def computeGoalValueRecursive(self, state, a, depth): action = self.values[(state, self.values[state].index(a))] next_state = self.transition[(state, action)] if next_state == None: return self.rfunction[0][self.rfunction[(state, action)]] + self.kalman.gamma*self.transition[(state, action, next_state)]*np.max(self.kalman.values[0][self.kalman.values[self.transition[None]]]) elif depth == 0: return self.rfunction[0][self.rfunction[(state, action)]] + self.kalman.gamma*self.transition[(state, action, next_state)]*np.max(self.kalman.values[0][self.kalman.values[self.transition[None]]]) else: tmp = np.max([self.computeGoalValueRecursive(next_state, a, depth-1) for a in self.values[next_state]]) return self.rfunction[0][self.rfunction[(state, action)]] + self.kalman.gamma*self.transition[(state, action, next_state)]*tmp """ def computeGoalValue(self, state, action, depth): #Cheating again. Only one s' is assumed to simplify nextstate = self.transition[(state, action)] print state, action, nextstate if nextstate == None: ns = self.transition[None] tmp = self.transition[(state, action, nextstate)]*np.max(self.kalman.values[0][self.kalman.values[ns]]) return self.rfunction[0][self.rfunction[(state, action)]]+self.kalman.gamma*tmp elif depth: tmp = self.transition[(state, action, nextstate)]*np.max([self.computeGoalValue(state, self.values[(state,a)], depth-1) for a in range(len(self.values[nextstate]))]) return self.rfunction[0][self.rfunction[(state, action)]]+self.kalman.gamma*tmp else: tmp = self.transition[(state, action, nextstate)]*np.max(self.kalman.values[0][self.kalman.values[nextstate]]) return self.rfunction[0][self.rfunction[(state, action)]]+self.kalman.gamma*tmp """
true
a95896c066efac96cc2969e2ba56d97855be5958
Python
zekeriyasari/optimization
/optimize/tools.py
UTF-8
4,503
3.375
3
[]
no_license
from optimize.constants import * import numpy as np import matplotlib.pyplot as plt def estimate_gradient(f, x, h=DERIV_TOL): n = x.size df = np.zeros(n) for k in range(n): delta = np.zeros(n) delta[k] = h df[k] = (f(x + delta) - f(x - delta)) / (2 * h) return df def line_along(f, x, d): def g(alpha): return f(x + alpha * d) def dg(alpha): return estimate_gradient(f, x + alpha * d).dot(d) return g, dg def cubic_interpolation(g, dg, s=1, cubic_tol=CUBIC_TOl): # Determine initial interval a = 0 b = s while not (dg(b) >= 0 and g(b) >= g(a)): a = b b *= 2 # Update current interval alpha = None while abs(a - b) > cubic_tol: ga = g(a) gb = g(b) dga = dg(a) dgb = dg(b) z = 3 * (ga - gb) / (b - a) + dga + dgb w = np.sqrt(z ** 2 - dga * dgb) alpha = b - (dgb + w - z) / (dgb - dga + 2 * w) * (b - a) if dg(alpha) >= 0 or g(alpha) >= g(a): b = alpha elif dg(alpha) < 0 or g(alpha) < g(a): a = alpha return alpha # step size def armijo(f, x, d, dfx, sigma=SIGMA, b=B, s=S): fx = f(x) m = 0 while fx - f(x + b ** m * s * d) < -sigma * b ** m * s * dfx.dot(d): m += 1 alpha = b ** m * s return alpha # step size def stopping_criteria(i, dfx0, dfx, max_iter=MAX_ITER, grad_tol=GRAD_TOL): return (np.linalg.norm(dfx) / np.linalg.norm(dfx0)) > grad_tol and i < max_iter def steepest_descent(f, df, x0, line_search='armijo'): dfx0 = df(x0) x = x0 dfx = df(x) d = -dfx i = 0 while stopping_criteria(i, dfx0, dfx): # Determine step size alpha = None if line_search == 'armijo': alpha = armijo(f, x, d, dfx) elif line_search == 'cubic_interpolation': g, dg = line_along(f, x, d) alpha = cubic_interpolation(g, dg) # Update current point x += alpha * d # Update iteration number i += 1 # Update gradient and descent direction dfx = df(x) d = -dfx return x, f(x), i def test(): # Test quadratic function def quadratic(x): return x[0] ** 2 + x[1] ** 2 + 5. # Test quadratic function gradient def dquadratic(x): return np.array([2 * x[0], 2 * x[1]]) # Test rosenbrock function def rosenbrock(x): return (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2 # Test rosenbrock function gradient def drosenbrock(x): return np.array([-2 + 2 * x[0] - 400 * x[0] * (x[1] - x[0] ** 2), 200 * (x[1] - x[0] ** 2)]) # Test steepest descent print('\nMinimizing quadratic function with armijo...') x0 = np.array([5., 5.]) x_min, fx_min, niter = steepest_descent(quadratic, dquadratic, x0, line_search='armijo') print('xmin: {}\nfmin: {}\nNumber of iterations: {}'.format(x_min, fx_min, niter)) # # Test quadratic function # print('\nMinimizing quadratic function with cubic interpolation...') # x0 = np.array([5., 5.]) # x_min, fx_min, niter = steepest_descent(quadratic, dquadratic, x0, line_search='cubic_interpolation') # print('xmin: {}\nfmin: {}\nNumber of iterations: {}'.format(x_min, fx_min, niter)) print('\nMinimizing rosenbrock function with armijo...') x0 = np.array([5., 5.]) x_min, fx_min, niter = steepest_descent(rosenbrock, drosenbrock, x0, line_search='armijo') print('xmin: {}\nfmin: {}\nNumber of iterations: {}'.format(x_min, fx_min, niter)) print('\nMinimizing rosenbrock function cubic interpolation...') x0 = np.array([5., 5.]) x_min, fx_min, niter = steepest_descent(rosenbrock, drosenbrock, x0, line_search='cubic_interpolation') print('xmin: {}\nfmin: {}\nNumber of iterations: {}'.format(x_min, fx_min, niter)) # scipy.optimize.minimize test print('\nMinimizing rosenbrock function with scipy.optimize.minimize...') from scipy.optimize import minimize res = minimize(rosenbrock, x0) print(res) # Test line_along by drawing curves x0 = np.array([0., 2.]) d = np.array([1, 0]) g, dg = line_along(rosenbrock, x0, d) t = np.arange(-2., 2., 0.01) gt = np.zeros(t.size) for n in range(t.size): gt[n] = g(t[n]) plt.plot(t, gt) plt.title('Rosenbrock function 1D curve') plt.show() if __name__ == '__main__': test() pass
true
600cd78514a9e8041ca92f388b7497afa31615f7
Python
TheLordBaski/adbmirror
/adbmirror/glue.py
UTF-8
682
2.796875
3
[ "Apache-2.0" ]
permissive
import threading from multiprocessing import Pipe class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.pipe_ext, self.pipe_int = Pipe() def read(self): msgs = [] while self.pipe_ext.poll(): msgs.append(self.pipe_ext.recv()) return msgs def write(self, data): self.pipe_ext.send(data) def internal_read(self): msgs = [] while self.pipe_int.poll(): msgs.append(self.pipe_int.recv()) return msgs def internal_write(self, data): self.pipe_int.send(data)
true
30b8eb26653988fc91932897cdffc697031d9f66
Python
mprinc/NLP
/nlangp-001-coursera/src/nlp/TaggingPreprocessing.py
UTF-8
7,721
2.625
3
[]
no_license
import sys import re from collections import defaultdict from TaggingCountsUnigram import TaggingCountsUnigram from TaggingCountsViterbi import TaggingCountsViterbi from nlp.TaggingCountsViterbi import TaggingCountsViterbi def defaultTree(): return defaultdict(defaultTree); class TaggingPreprocessing(object): RARE_WORD = "_RARE_"; RARE_COUNT = 5; RARE_NUMERIC = "_RARE_NUMERIC_"; RARE_ALL_NUMERIC = "_RARE_ALL_NUMERIC_"; RARE_ALL_NON_ALFANUMERIC = "_RARE_ALL_NON_ALFANUMERIC_"; RARE_ALL_CAP = "_RARE_ALL_CAP_"; RARE_LAST_CAP = "_RARE_LAST_CAP_"; RARE_FIRST_CAP = "_RARE_FIRST_CAP_"; @staticmethod def WordNormalize(word): #word = word.lower(); return word; @staticmethod def getRareWordClass(word): rex_number = re.compile(r'\d'); # at least one numeric rex_all_number = re.compile(r'^\s*(\d+)\s*$'); # all numeric rex_all_non_alfanumeric = re.compile(r'[^A-Za-z\d]'); # at least one non alfanumeric rex_all_cap = re.compile(r'^\s*([A-Z]+)\s*$'); # all capital rex_last_cap = re.compile(r'^\s*.+[A-Z]\s*$'); # at least some non-capital, but last is capital rex_first_cap = re.compile(r'^\s*[A-Z].+\s*$'); # at least some non-capital, but first is capital #r'\b\S*[a-z]\S*[A-Z]\b' rareWordClass = TaggingPreprocessing.RARE_WORD; if(rex_all_number.search(word)): print ("find all numeric word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_ALL_NUMERIC; elif(rex_number.search(word)): #print ("find numeric word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_NUMERIC; elif(rex_all_non_alfanumeric.search(word)): print ("find non alfanumeric word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_ALL_NON_ALFANUMERIC; elif(rex_all_cap.search(word)): #print ("find All Cap word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_ALL_CAP; elif(rex_last_cap.search(word)): #print ("find Last Cap word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_LAST_CAP; elif(rex_first_cap.search(word)): #print ("find First Cap word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_FIRST_CAP; else: #print ("findRareWords word: %s" % (word)); rareWordClass = TaggingPreprocessing.RARE_WORD; return rareWordClass; def __init__(self): self.filenameIn = ""; self.filenameOut = ""; self.wordsCount = defaultTree(); self.wordsRaw = []; self.tagsRaw = []; self.wordsRare = defaultTree(); def load(self, filenameIn): self.filenameIn = filenameIn print("Preprocessing reading started ..."); self.wordsCount = defaultTree(); self.wordsRaw = []; self.tagsRaw = []; self.wordsRare = defaultTree(); try: self.file = open(self.filenameIn) except Exception: print "[BukvikParser:parseFile]: problem opening file filenameIn = ", self.filenameIn sys.exit(1) lineNo = 0 # http://docs.python.org/2/library/re.html rex_word_tag = re.compile(r'^\s*(\S+)\s+(\S*)\s*$') # word tag for line in self.file: lineNo=lineNo+1; match = rex_word_tag.search(line) if match: var_word = match.group(1); var_tag = match.group(2); #preprocessing word var_word = TaggingPreprocessing.WordNormalize(var_word); self.wordsRaw.append(var_word); self.tagsRaw.append(var_tag); if(not self.wordsCount.has_key(var_word)): self.wordsCount[var_word] = 0; self.wordsCount[var_word] = self.wordsCount[var_word] + 1; if(lineNo < 100): print ("Word tag: word: %s, tag: %s, count: %d" % (var_word, var_tag, self.wordsCount[var_word])); else: self.wordsRaw.append(""); self.tagsRaw.append(""); print("Preprocessing reading finished ..."); def findRareWordsClasses(self, withClassess): print("Finding rare words started ..."); wordNo = 0; #for count, word in enumerate(self.wordsCount): for word, count in self.wordsCount.items(): #print "findRareWords word:" + word + ", count:" + str(count) if(count<TaggingPreprocessing.RARE_COUNT): if(wordNo<50): print ("word: %s, count: %d" % (word, count)); if(not withClassess): self.wordsRare[word] = TaggingPreprocessing.RARE_WORD; else: self.wordsRare[word] = TaggingPreprocessing.getRareWordClass(word); wordNo = wordNo + 1; print("Finding rare words finished ..."); def saveUnigram(self, filenameOut): self.filenameOut = filenameOut print("Preprocessing saving started ..."); try: self.file = open(self.filenameOut, "w") except Exception: print "[BukvikParser:parseFile]: problem opening file filenameIn = ", self.filenameIn sys.exit(1) wordNo = 0 while wordNo < len(self.wordsRaw): word = self.wordsRaw[wordNo]; if(self.wordsRare.has_key(word)): self.file.write(TaggingPreprocessing.RARE_WORD); else: self.file.write(word); self.file.write(" " + self.tagsRaw[wordNo] + "\n"); wordNo = wordNo+1; self.file.close(); print("Preprocessing saving finished ..."); def saveViterbi(self, filenameOut, withClassess): self.filenameOut = filenameOut print("Preprocessing saving started ..."); try: self.file = open(self.filenameOut, "w") except Exception: print "[BukvikParser:parseFile]: problem opening file filenameIn = ", self.filenameIn sys.exit(1) wordNo = 0 #newSentence = True; #previousWord = ""; while wordNo < len(self.wordsRaw): # We do not need to preprocess sentences since count_freqs script is doing it for us in this case #if(newSentence): #self.file.write(TaggingCountsViterbi.WORD_START + " " + TaggingCountsViterbi.TAG_START + "\n"); #self.file.write(TaggingCountsViterbi.WORD_START + " " + TaggingCountsViterbi.TAG_START + "\n"); #newSentence = False; word = self.wordsRaw[wordNo]; word_final = word; if(self.wordsRare.has_key(word)): if(not withClassess): word_final = self.wordsRare[word]; else: word_final = self.getRareWordClass(word); tag_final = self.tagsRaw[wordNo]; # We do not need to preprocess sentences since count_freqs script is doing it for us in this case #if(previousWord == TaggingCountsViterbi.WORD_STOP_CHECK and word == ''): #self.file.write(TaggingCountsViterbi.WORD_STOP + " " + TaggingCountsViterbi.TAG_STOP); #self.file.write("\n"); #newSentence = True; #else: self.file.write(word_final + " " + tag_final + "\n"); #previousWord = word; wordNo = wordNo+1; self.file.close(); print("Preprocessing saving finished ...");
true
a714c29fa0baeec212a0f2eed841a3b7183b1d21
Python
brunobstoll/LA-Sist-Completo
/LA-Intervencao/model/PreProcessamentoDB.py
UTF-8
3,762
2.671875
3
[]
no_license
import model.dataBase as db import model.MetaDadosDB as meta import model.ImportacaoDB as imp def RetornarValoresColuna(idTabela, idColuna): tabela = imp.ObterTabela(idTabela) coluna = meta.ObterColuna(idColuna) sql_table = tabela.nome if not (tabela.sql_destino == None or tabela.sql_destino == ''): sql_table = tabela.sql_destino sql = 'SELECT COUNT(*) AS qtd, ' + coluna.sql + ' as COL FROM "' + sql_table + '" GROUP BY COL' #resultado = db.consultarSQL(sql) resultado = db.consultarSQLDataFrame(sql) return resultado def GerarSqlQuartil(tabela, coluna, tp): tpDisc = '' if tp == 'E': tpDisc = 'DISTINCT' sqlTexto = """ SELECT *, CASE WHEN coluna <= Q1 THEN 'Q1' WHEN coluna <= Q2 THEN 'Q2' WHEN coluna <= Q3 THEN 'Q3' ELSE 'Q4' END AS QUARTIL FROM ( SELECT *, (SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) AS QTD, (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 1), 1) Q1, (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 2), 1) Q2, (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 3), 1) Q3 FROM ( SELECT {{tpQuartil}} {{coluna}} AS coluna FROM {{tabela}}) AS T ORDER BY 1 ) AS T LIMIT 1""" sqlNumero = """ SELECT *, CASE WHEN coluna <= Q1 THEN 'Q1' WHEN coluna <= Q2 THEN 'Q2' WHEN coluna <= Q3 THEN 'Q3' ELSE 'Q4' END AS QUARTIL FROM ( SELECT *, (SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) AS QTD, (SELECT {{tpQuartil}} CAST({{coluna}} AS FLOAT) FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 1), 1) Q1, (SELECT {{tpQuartil}} CAST({{coluna}} AS FLOAT) FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 2), 1) Q2, (SELECT {{tpQuartil}} CAST({{coluna}} AS FLOAT) FROM {{tabela}} ORDER BY 1 LIMIT (((SELECT COUNT(*) FROM (SELECT {{tpQuartil}} {{coluna}} FROM {{tabela}})) / 4) * 3), 1) Q3 FROM ( SELECT {{tpQuartil}} CAST({{coluna}} AS FLOAT) AS coluna FROM {{tabela}}) AS T ORDER BY 1 ) AS T LIMIT 1""" objTabela = imp.ObterTabelaPorNome(tabela) objColuna = meta.ObterColunaPorTabNome(objTabela.id, coluna) if objColuna.tipo == 'N': sql = sqlNumero.replace('{{tabela}}', tabela).replace('{{coluna}}', coluna).replace('{{tpQuartil}}', tpDisc) else: sql = sqlTexto.replace('{{tabela}}', tabela).replace('{{coluna}}', coluna).replace('{{tpQuartil}}', tpDisc) resultado = db.consultarSQLDataFrame(sql) if objColuna.tipo == 'N': sqlResultado = 'CASE WHEN CAST(' + str(coluna) + ' AS FLOAT) <= ' + str(resultado['Q1'][0]) + ' THEN \'Q1\' WHEN CAST(' + str(coluna) + ' AS FLOAT) <= ' + str(resultado['Q2'][0]) + ' THEN \'Q2\' WHEN CAST(' + str(coluna) + ' AS FLOAT) <= ' + str(resultado['Q3'][0]) + ' THEN \'Q3\' ELSE \'Q4\' END' else: sqlResultado = 'CASE WHEN ' + str(coluna) + ' <= ' + str(resultado['Q1'][0]) + ' THEN \'Q1\' WHEN ' + str(coluna) + ' <= ' + str(resultado['Q2'][0]) + ' THEN \'Q2\' WHEN ' + str(coluna) + ' <= ' + str(resultado['Q3'][0]) + ' THEN \'Q3\' ELSE \'Q4\' END' return sqlResultado def DiscretizarCampo(idColuna, nome, expressao): colunaDiscr = meta.ObterColuna(idColuna) colunaDiscr.sql = expressao meta.SalvarColuna(colunaDiscr)
true
2d7bdb70a3a9cde06012f0de32bf342d2c6b2bd7
Python
kingssafy/til
/ps/codeforces/1144/1144B.py
UTF-8
282
2.78125
3
[]
no_license
N = int(input()) arr = list(map(int, input().split())) arr.sort() flag = 1 before = N; k = arr[-1]%2 odd = [] even = [] for a in arr: if a % 2: odd.append(a) else: even.append(a) if len(odd) == len(even): print(0) else: print(min(odd[0], even[0]))
true
f4a4301af449e7d2901fea7dadfcf96f1cc596a7
Python
prashant-repo-test/python_data_science
/Abstract class.py
UTF-8
338
3.984375
4
[]
no_license
from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def calculate_salary(self,sal): pass class Developer(Employee): def calculate_salary(self,sal): final_salary = sal * 1.1 return final_salary emp_1 = Developer() print(emp_1.calculate_salary(10000))
true
bb5b49e8c343e07a57ae55232a81b60729b8c6ec
Python
nwinds/jugar
/algo_I_py/path_compression_qu.py
UTF-8
817
3.5
4
[]
no_license
# inspired by union find demo identity = [] for i in range(10): identity.append(i) # root of number #I made an understandable ver def root(you): while identity[you] != you: dad = identity[you] oldman = identity[dad] identity[you] = oldman you = identity[you] # shorter: #while identity[you] != you: #identity[you] = identity[identity[you]] #you = identity[you] return you def connected(a, b): ra = root(a) rb = root(b) return ra == rb def union(a, b): ra = root(a) rb = root(b) if ra == rb: return identity[ra] = rb print(identity) union(1,2) union(3,4) union(5,6) union(7,8) union(7,9) union(2,8) union(0,5) union(1,9) print(identity) print('size of connected components: %d' % len(identity))
true
1b9d9991cc8596764420d5392cc85958a3b8454f
Python
SeaWar741/ITC
/1er_Semestre/stark.py
UTF-8
2,818
3.609375
4
[]
no_license
clave= 23412 totaladul=0 totalnin= 0 saldotarjeta=1000 validar = int(input("ingrese clave de acceso >")) print("Bienvenido a restaurate ABC") while validar != 23412: print ("Clave incorrecta") validar = int(input("ingrese clave de acceso >")) print("MENU PRINCIPAL") print("Ingrese la opcion que desea") opcion = int(input("Menu adulto (1), Menu niño(2), Realizar pago (3), Recarga de tarjeta (4), Salir(5) \n>")) while opcion != 5: if opcion == 1: pregunta= "si" while pregunta == "si": seleccionadul= int(input("Seleccione un platillo del menu, Arroz a la mexicana $95 (1), Mole poblano $78 (2), Crema de brocoli $60 (3) \n>")) if seleccionadul == 1: totaladul += 95 elif seleccionadul == 2: totaladul += 78 elif seleccionadul == 3: totaladul += 60 pregunta=input("quieres seguir ordenando?<si><no> >") if opcion == 2: pregunta= "si" while pregunta == "si": seleccionnin= int(input("Seleccione un platillo del menu, Nugets de pollo $56 (1), Mini pizza $90 (2), Hamburguesa $60 (3) \n>")) if seleccionnin == 1: totalnin += 56 elif seleccionnin == 2: totalnin += 90 elif seleccionnin == 3: totalnin += 60 pregunta=input("quieres seguir ordenando?<si><no> >") if opcion == 3: propina= input("desea agregar propina? >") if propina == "si": porcentaje = int(input("ingrese el porcetaje de propina que desee agregar ($) >")) if porcentaje<10: print ("la propina debe de ser mayor al 10%") porcentaje = int(input("ingrese el porcetaje de propina que desee agregar ($) >")) ajuste = (porcentaje * .01) + 1 totalgeneral = (totaladul + totalnin) * ajuste print ("el total por adultos es $:", totaladul) print ("el total por niños es $:" , totalnin) print ("el total general es $:" , totaladul + totalnin) opcion=5 if opcion == 4: optionrecargar=input ("desea recargar su tarjeta ?<si><no> >") if optionrecargar.lower() == "si": recarga_de_tarjeta = int(input("Ingresar cantidad ($) >")) saldotarjeta = saldotarjeta+recarga_de_tarjeta print("Ahora tienes: $"+str(saldotarjeta)) if opcion!=5: opcion = int(input("Menu adulto (1), Menu niño(2), Realizar pago (3), Recarga de tarjeta (4), Salir(5) \n>")) print("Total de adultos: ",totaladul) print("Total de ninos: ",totalnin) print ("el total general es $:" , totaladul + totalnin)
true
b6e984fae15a2a3ae64e2823b2b3252623ac7b78
Python
deeuu/supriya
/supriya/ugens/Rand.py
UTF-8
450
2.546875
3
[ "MIT" ]
permissive
import collections from supriya import CalculationRate from supriya.synthdefs import UGen class Rand(UGen): """ A uniform random distribution. :: >>> supriya.ugens.Rand.ir() Rand.ir() """ ### CLASS VARIABLES ### __documentation_section__ = "Noise UGens" _ordered_input_names = collections.OrderedDict([("minimum", 0.0), ("maximum", 1.0)]) _valid_calculation_rates = (CalculationRate.SCALAR,)
true
2e86bd083112f6d161bc5b67dd1b1586d39c9caf
Python
SindreSvendby/pgnToFen
/pgnToFen.py
UTF-8
30,292
2.75
3
[ "MIT" ]
permissive
#!/bin/python # coding=utf8 from __future__ import print_function from __future__ import division from functools import partial import math import re import os class PgnToFen: fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR' whiteToMove = True internalChessBoard = [ 'R','N','B','Q','K','B','N','R', 'P','P','P','P','P','P','P','P', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', 'p','p','p','p','p','p','p','p', 'r','n','b','q','k','b','n','r'] enpassant = '-' castlingRights = 'KQkq' DEBUG = False lastMove = 'Before first move' fens = [] result = '' def getFullFen(self): return self.getFen() + ' ' + ('w ' if self.whiteToMove else 'b ') + self.enpassant + ' ' + (self.castlingRights if self.castlingRights else '-') def getFen(self): fenpos = '' for n in reversed((8,16,24,32,40,48,56,64)): emptyPosLength = 0; for i in self.internalChessBoard[n-8:n]: if(i is not '1'): if(emptyPosLength is not 0): fenpos = fenpos + str(emptyPosLength); emptyPosLength = 0 fenpos = fenpos + i else: emptyPosLength = emptyPosLength + 1 if(emptyPosLength is not 0): fenpos = fenpos + str(emptyPosLength); fenpos = fenpos + '/' fenpos = fenpos[:-1] return fenpos def printFen(self): print(self.getFen()) def moves(self, moves): if isinstance(moves, str): nrReCompile = re.compile('[0-9]+\.') transformedMoves = nrReCompile.sub('', moves) pgnMoves = transformedMoves.replace(' ', ' ').split(' ') result = pgnMoves[-1:][0] if(result in ['1/2-1/2', '1-0', '0-1']): self.result = result pgnMoves = pgnMoves[:-1] print('pgnMoves') print(pgnMoves) return self.pgnToFen(pgnMoves) else: return self.pgnToFen(moves) def pgnFile(self, file): pgnGames = { 'failed' : [], 'succeeded' : [], } started = False game_info = [] pgnMoves = '' for moves in open(file, 'rt').readlines(): if moves[:1] == '[': #print('game_info line: ', moves) game_info.append(moves) continue if moves[:2] == '1.': started = True if (moves == '\n' or moves == '\r\n') and started: try: #print('Processing ', game_info[0:6]) pgnToFen = PgnToFen() pgnToFen.resetBoard() fens = pgnToFen.moves(pgnMoves).getAllFens() pgnGames['succeeded'].append((game_info, fens)) except ValueError as e: pgnGames['failed'].append((game_info, '"' + pgnToFen.lastMove + '"', pgnToFen.getFullFen(), e)) except TypeError as e: pgnGames['failed'].append((game_info, '"' + pgnToFen.lastMove + '"', pgnToFen.getFullFen(), e)) except IndexError as e: raise IndexError(game_info, '"' + pgnToFen.lastMove + '"', pgnToFen.getFullFen(), e) pgnGames['failed'].append((game_info, '"' + pgnToFen.lastMove + '"', pgnToFen.getFullFen(), e)) except ZeroDivisionError as e: pgnGames['failed'].append((game_info, '"' + pgnToFen.lastMove + '"', pgnToFen.getFullFen(), e)) finally: started = False game_info = [] pgnMoves = '' if(started): pgnMoves = pgnMoves + ' ' + moves.replace('\n', '').replace('\r', '') return pgnGames def pgnToFen(self, moves): try: loopC = 1 for move in moves: self.lastMove = move self.DEBUG and print('=========') self.DEBUG and print('Movenumber',loopC) self.DEBUG and print('TO MOVE:', 'w' if self.whiteToMove else 'b') self.DEBUG and print('MOVE:', move) self.move(move) self.DEBUG and print('after move:') self.DEBUG and self.printBoard() loopC = loopC + 1 self.fens.append(self.getFullFen()) self.sucess = True return self except ValueError: print('Converting PGN to FEN failed.') print('Move that failed:', self.lastMove) self.printBoard() print(self.getFullFen()) self.fens = [] self.sucess = False def move(self, move): try: self.lastMove = move self.handleAllmoves(move) if(self.whiteToMove): self.whiteToMove = False else: self.whiteToMove = True return self except ValueError: self.DEBUG and print('Converting PGN to FEN failed.') self.DEBUG and print('Move that failed:', self.lastMove) self.DEBUG and self.printBoard() self.DEBUG and print('FEN:', self.getFullFen()) def getAllFens(self): return self.fens def handleAllmoves(self, move): move = move.replace('+', '') move = move.replace('#', '') promote = '' if(move.find('=') > -1): promote = move[-1] move = move[:-2] if(move.find('-O') != -1): self.castelingMove(move) return; toPosition = move[-2:] move = move[:-2] if len(move) > 0: if move[0] in ['R','N','B','Q','K']: officer = move[0] move = move[1:] else: officer = 'P' else: officer = 'P' takes = False if 'x' in move: takes = True move = move[:-1] specificRow = "" specificCol = "" if len(move) > 0: if move in ['1','2','3','4','5','6','7','8']: specificRow = move elif move in ['a','b','c','d','e','f','g','h']: specificCol = move elif len(move) == 2: specificCol = move[0] specificRow = move[1] if(officer != 'P'): self.enpassant = '-' if(officer == 'N'): self.knightMove(toPosition, specificCol, specificRow) elif(officer == 'B'): self.bishopMove(toPosition, specificCol, specificRow) elif(officer == 'R'): self.rookMove(toPosition, specificCol, specificRow) elif(officer == 'Q'): self.queenMove(toPosition, specificCol, specificRow) elif(officer == 'K'): self.kingMove(toPosition, specificCol, specificRow) elif(officer == 'P'): self.pawnMove(toPosition, specificCol, specificRow, takes, promote) def castelingMove(self, move): if(len(move) == 3): #short castling if(self.whiteToMove): self.internalChessBoard[7] = '1' self.internalChessBoard[6] = 'K' self.internalChessBoard[5] = 'R' self.internalChessBoard[4] = '1' self.castlingRights = self.castlingRights.replace('KQ','') else: self.internalChessBoard[63] = '1' self.internalChessBoard[62] = 'k' self.internalChessBoard[61] = 'r' self.internalChessBoard[60] = '1' self.castlingRights = self.castlingRights.replace('kq', '') else: # long castling if(self.whiteToMove): self.internalChessBoard[0] = '1' self.internalChessBoard[2] = 'K' self.internalChessBoard[3] = 'R' self.internalChessBoard[4] = '1' self.castlingRights = self.castlingRights.replace('KQ', '') else: self.internalChessBoard[60] = '1' self.internalChessBoard[59] = 'r' self.internalChessBoard[58] = 'k' self.internalChessBoard[56] = '1' self.castlingRights = self.castlingRights.replace('kq', '') def queenMove(self, move, specificCol, specificRow): column = move[:1] row = move[1:2] chessBoardNumber = self.placeOnBoard(row, column) piece = 'Q' if self.whiteToMove else 'q' possibelPositons = [i for i, pos in enumerate(self.internalChessBoard) if pos == piece] self.internalChessBoard[chessBoardNumber] = piece self.validQueenMoves(possibelPositons, move, specificCol, specificRow) def validQueenMoves(self, posistions, move, specificCol, specificRow): newColumn = self.columnToInt(move[:1]) newRow = self.rowToInt(move[1:2]) newPos = self.placeOnBoard(newRow + 1, move[:1]) potensialPosisitionsToRemove=[] for pos in posistions: (existingRow, existingCol) = self.internalChessBoardPlaceToPlaceOnBoard(pos) diffRow = int(existingRow - newRow) diffCol = int(self.columnToInt(existingCol) - newColumn) if diffRow == 0 or diffCol == 0 or diffRow == diffCol or -diffRow == diffCol or diffRow == -diffCol: if not specificCol or specificCol == existingCol: if not specificRow or (int(specificRow) -1) == int(existingRow): xVect = 0 yVect = 0 if abs(diffRow) > abs(diffCol): xVect = -(diffCol / abs(diffRow)) yVect = -(diffRow / abs(diffRow)) else: xVect = -(diffCol / abs(diffCol)) yVect = -(diffRow / abs(diffCol)) checkPos = pos nothingInBetween = True while(checkPos != newPos): checkPos = int(checkPos + yVect * 8 + xVect) if(checkPos == newPos): continue if self.internalChessBoard[checkPos] != "1": nothingInBetween = False if nothingInBetween: potensialPosisitionsToRemove.append(pos) if len(potensialPosisitionsToRemove) == 1: correctPos = potensialPosisitionsToRemove[0]; else: if len(potensialPosisitionsToRemove) == 0: raise ValueError('Cant find a valid posistion to remove', potensialPosisitionsToRemove) notInCheckLineBindNewPos = partial(self.notInCheckLine, self.posOnBoard('K')) correctPosToRemove = list(filter(notInCheckLineBindNewPos, potensialPosisitionsToRemove)) if len(correctPosToRemove) > 1: raise ValueError('Several valid positions to remove from the board') if len(correctPosToRemove) == 0: raise ValueError('None valid positions to remove from the board') correctPos = correctPosToRemove[0] self.internalChessBoard[correctPos] = "1" return def rookMove(self, move, specificCol, specificRow): column = move[:1] row = move[1:2] chessBoardNumber = self.placeOnBoard(row, column) piece = 'R' if self.whiteToMove else 'r' possibelPositons = [i for i, pos in enumerate(self.internalChessBoard) if pos == piece] self.internalChessBoard[chessBoardNumber] = piece self.validRookMoves(possibelPositons, move, specificCol, specificRow) def validRookMoves(self, posistions, move, specificCol, specificRow): newColumn = self.columnToInt(move[:1]) newRow = self.rowToInt(move[1:2]) newPos = self.placeOnBoard(newRow + 1, move[:1]) potensialPosisitionsToRemove=[] if(len(posistions) == 1): self.internalChessBoard[posistions[0]] = "1" return for pos in posistions: (existingRow, existingCol) = self.internalChessBoardPlaceToPlaceOnBoard(pos) diffRow = int(existingRow - newRow) diffCol = int(self.columnToInt(existingCol) - newColumn) if diffRow == 0 or diffCol == 0: if not specificCol or specificCol == existingCol: if not specificRow or (int(specificRow) -1) == int(existingRow): xVect = 0 yVect = 0 if abs(diffRow) > abs(diffCol): xVect = -(diffCol / abs(diffRow)) yVect = -(diffRow / abs(diffRow)) else: xVect = -(diffCol / abs(diffCol)) yVect = -(diffRow / abs(diffCol)) checkPos = pos nothingInBetween = True while(checkPos != newPos): checkPos = int(checkPos + yVect * 8 + xVect) if(checkPos == newPos): continue if self.internalChessBoard[checkPos] != "1": nothingInBetween = False if nothingInBetween: potensialPosisitionsToRemove.append(pos) if len(potensialPosisitionsToRemove) == 1: correctPos = potensialPosisitionsToRemove[0]; else: if len(potensialPosisitionsToRemove) == 0: raise ValueError('Cant find a valid posistion to remove', potensialPosisitionsToRemove) notInCheckLineBindNewPos = partial(self.notInCheckLine, self.posOnBoard('K')) correctPosToRemove = list(filter(notInCheckLineBindNewPos, potensialPosisitionsToRemove)) if len(correctPosToRemove) > 1: raise ValueError('Several valid positions to remove from the board') correctPos = correctPosToRemove[0] if(correctPos == 0): self.castlingRights = self.castlingRights.replace('Q', '') elif(correctPos == 63): self.castlingRights = self.castlingRights.replace('k', '') elif(correctPos == 7): self.castlingRights = self.castlingRights.replace('K', '') elif(correctPos == (63-8)): self.castlingRights = self.castlingRights.replace('q', '') self.internalChessBoard[correctPos] = "1" return def kingMove(self, move, specificCol, specificRow): column = move[:1] row = move[1:2] chessBoardNumber = self.placeOnBoard(row, column) piece = 'K' if self.whiteToMove else 'k' lostCastleRights = 'Q' if self.whiteToMove else 'q' kingPos = [i for i, pos in enumerate(self.internalChessBoard) if pos == piece] self.castlingRights = self.castlingRights.replace(piece, '') self.castlingRights = self.castlingRights.replace(lostCastleRights, '') self.internalChessBoard[chessBoardNumber] = piece self.internalChessBoard[kingPos[0]] = '1' def bishopMove(self, move, specificCol, specificRow): column = move[:1] row = move[1:2] chessBoardNumber = self.placeOnBoard(row, column) piece = 'B' if self.whiteToMove else 'b' possibelPositons = [i for i, pos in enumerate(self.internalChessBoard) if pos == piece] self.internalChessBoard[chessBoardNumber] = piece self.validBishopMoves(possibelPositons, move, specificCol, specificRow) def validBishopMoves(self, posistions, move, specificCol, specificRow): newColumn = self.columnToInt(move[:1]) newRow = self.rowToInt(move[1:2]) newPos = self.placeOnBoard(newRow + 1, move[:1]) potensialPosisitionsToRemove = [] for pos in posistions: (existingRow, existingCol) = self.internalChessBoardPlaceToPlaceOnBoard(pos) diffRow = int(existingRow - newRow) diffCol = int(self.columnToInt(existingCol) - newColumn) if diffRow == diffCol or -diffRow == diffCol or diffRow == -diffCol: if not specificCol or specificCol == existingCol: if not specificRow or (int(specificRow) -1) == int(existingRow): xVect = 0 yVect = 0 if abs(diffRow) > abs(diffCol): xVect = -(diffCol / abs(diffRow)) yVect = -(diffRow / abs(diffRow)) else: xVect = -(diffCol / abs(diffCol)) yVect = -(diffRow / abs(diffCol)) checkPos = pos nothingInBetween = True while(checkPos != newPos): checkPos = int(checkPos + yVect * 8 + xVect) if(checkPos == newPos): continue if self.internalChessBoard[checkPos] != "1": nothingInBetween = False if nothingInBetween: potensialPosisitionsToRemove.append(pos) if len(potensialPosisitionsToRemove) == 1: correctPos = potensialPosisitionsToRemove[0]; else: if len(potensialPosisitionsToRemove) == 0: raise ValueError('Cant find a valid posistion to remove', potensialPosisitionsToRemove) notInCheckLineBindNewPos = partial(self.notInCheckLine, self.posOnBoard('K')) correctPosToRemove = list(filter(notInCheckLineBindNewPos, potensialPosisitionsToRemove)) if len(correctPosToRemove) > 1: raise ValueError('Several valid positions to remove from the board') correctPos = correctPosToRemove[0] self.internalChessBoard[correctPos] = "1" def knightMove(self, move, specificCol, specificRow): column = move[:1] row = move[1:2] chessBoardNumber = self.placeOnBoard(row, column) piece = 'N' if self.whiteToMove else 'n' knightPositons = [i for i, pos in enumerate(self.internalChessBoard) if pos == piece] self.internalChessBoard[chessBoardNumber] = piece self.validKnighMoves(knightPositons, move, specificCol, specificRow) def validKnighMoves(self, posistions, move, specificCol, specificRow): newColumn = self.columnToInt(move[:1]) newRow = self.rowToInt(move[1:2]) potensialPosisitionsToRemove = [] for pos in posistions: (existingRow, existingCol) = self.internalChessBoardPlaceToPlaceOnBoard(pos) validatePos = str(int(existingRow - newRow)) + str(int(self.columnToInt(existingCol) - newColumn)) if validatePos in ['2-1','21','1-2','12','-1-2','-12','-2-1','-21']: if not specificCol or specificCol == existingCol: if not specificRow or (int(specificRow) -1) == int(existingRow): potensialPosisitionsToRemove.append(pos) if len(potensialPosisitionsToRemove) == 1: correctPos = potensialPosisitionsToRemove[0]; else: if len(potensialPosisitionsToRemove) == 0: raise ValueError('Cant find a valid posistion to remove', potensialPosisitionsToRemove) notInCheckLineBindNewPos = partial(self.notInCheckLine, self.posOnBoard('K')) correctPosToRemove = list(filter(notInCheckLineBindNewPos, potensialPosisitionsToRemove)) if len(correctPosToRemove) > 1: raise ValueError('Several valid positions to remove from the board') if len(correctPosToRemove) == 0: raise ValueError('None valid positions to remove from the board') correctPos = correctPosToRemove[0] self.internalChessBoard[correctPos] = "1" return def pawnMove(self, toPosition, specificCol, specificRow, takes, promote): column = toPosition[:1] row = toPosition[1:2] prevEnpassant = self.enpassant self.enpassant = '-' chessBoardNumber = self.placeOnBoard(row, column) if(promote): piece = promote if self.whiteToMove else promote.lower() else: piece = 'P' if self.whiteToMove else 'p' self.internalChessBoard[chessBoardNumber] = piece if(takes): removeFromRow = (int(row) - 1) if self.whiteToMove else (int(row) + 1) posistion = self.placeOnBoard(removeFromRow, specificCol) piece = self.internalChessBoard[posistion] = '1' if(prevEnpassant != '-'): enpassantPos = self.placeOnBoard(prevEnpassant[1], prevEnpassant[0]) toPositionPos = self.placeOnBoard(toPosition[1], toPosition[0]) if(prevEnpassant == toPosition): if(self.whiteToMove == True): self.internalChessBoard[chessBoardNumber - 8] = '1' else: self.internalChessBoard[chessBoardNumber + 8] = '1' return else: #run piece one more time if case of promotion piece = 'P' if self.whiteToMove else 'p' self.updateOldLinePos(piece,chessBoardNumber, toPosition) def updateOldLinePos(self, char, posistion, toPosition): startPos = posistion counter = 0; piece = '' step = 8 while(posistion >= 0 and posistion < 64): if(piece == char): if(abs(posistion - startPos) > 10): (row, column) = self.internalChessBoardPlaceToPlaceOnBoard(startPos) rowAdjustedByColor = -1 if self.whiteToMove else 1 enpassant = str(column) + str(int(row) + 1 + rowAdjustedByColor) self.enpassant = enpassant else: self.enpassant = '-' piece = self.internalChessBoard[posistion] = '1' return; else: if(self.whiteToMove == True): posistion = posistion - step self.enpassant = '-' else: posistion = posistion + step self.enpassant = '-' piece = self.internalChessBoard[posistion] def placeOnBoard(self, row, column): # returns internalChessBoard place return 8 * (int(row) - 1) + self.columnToInt(column); def internalChessBoardPlaceToPlaceOnBoard(self, chessPos): column = int(chessPos) % 8 row = math.floor(chessPos/8) return (row, self.intToColum(column)) def rowToInt(self, n): return int(n)-1 def columnToInt(self, char): # TODO: char.toLowerCase??? if(char == 'a'): return 0 elif(char == 'b'): return 1 elif(char == 'c'): return 2 elif(char == 'd'): return 3 elif(char == 'e'): return 4 elif(char == 'f'): return 5 elif(char == 'g'): return 6 elif(char == 'h'): return 7 def intToColum(self, num): # TODO: char.toLowerCase??? if(num == 0): return 'a' elif(num == 1): return 'b' elif(num == 2): return 'c' elif(num == 3): return 'd' elif(num == 4): return 'e' elif(num == 5): return 'f' elif(num == 6): return 'g' elif(num == 7): return 'h' def resetBoard(self): self.fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR' self.whiteToMove = True self.enpassant = '-' self.internalChessBoard = [ 'R','N','B','Q','K','B','N','R', 'P','P','P','P','P','P','P','P', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', '1','1','1','1','1','1','1','1', 'p','p','p','p','p','p','p','p', 'r','n','b','q','k','b','n','r'] self.result = '' def printBoard(self): loop = 1 for i in self.internalChessBoard: print(i, end=' ') if(loop%8 == 0): print() loop = loop + 1 def notInCheckLine(self, kingPos, piecePos): """ Verifies that the piece is not standing in "line of fire" between and enemy piece and your king as the only piece :returns: True if the piece can move """ return self.checkLine(kingPos, piecePos) def checkLine(self, kingPos, piecePos): (kingRowInt, kingColumn) = self.internalChessBoardPlaceToPlaceOnBoard(kingPos) kingColumnInt = self.columnToInt(kingColumn) (pieceRowInt, pieceColumn) = self.internalChessBoardPlaceToPlaceOnBoard(piecePos); pieceColumnInt = self.columnToInt(pieceColumn) diffRow = int(kingRowInt - pieceRowInt) diffCol = int(kingColumnInt - pieceColumnInt) if (abs(diffRow) != abs(diffCol)) and diffRow != 0 and diffCol != 0: return True if abs(diffRow) > abs(diffCol): xVect = (diffCol / abs(diffRow)) yVect = -(diffRow / abs(diffRow)) else: xVect = -(diffCol / abs(diffCol)) yVect = -(diffRow / abs(diffCol)) checkPos = kingPos nothingInBetween = True while checkPos != piecePos and (checkPos < 64 and checkPos >= 0): checkPos = int(checkPos + yVect * 8 + xVect) if(checkPos == piecePos): continue if self.internalChessBoard[checkPos] != "1": #print('Something between king and piece, returning a false value') # Piece between the king and the piece can not be a self-disvoery-check. return True #print('No piece between the king and the piece, need to verify if an enemy piece with the possibily to go that direction exist') # No piece between the king and the piece, need to verify if an enemy piece with the possibily to go that direction exist columnNr = (piecePos % 8) searchRow = pieceRowInt if(xVect == 1): columnsLeft = 7- columnNr else: columnsLeft = columnNr posInMove = (yVect * 8) + xVect while checkPos >= 0 and checkPos < 64 and columnsLeft > -1: columnsLeft = columnsLeft - abs(xVect) checkPos = int(checkPos + posInMove) currentRow = math.floor(checkPos/8) if(checkPos < 0 or checkPos > 63): continue if self.internalChessBoard[checkPos] in self.getOppositePieces(["Q", "R"]) and xVect == 0: return False elif self.internalChessBoard[checkPos] in self.getOppositePieces(["Q", "R"]) and yVect == 0 and searchRow == currentRow: return False elif self.internalChessBoard[checkPos] in self.getOppositePieces(["Q", "B"]) and (abs(xVect) == abs(yVect)): return False elif self.internalChessBoard[checkPos] != "1": return True return True def getOppositePieces(self, pieces): """" Takes a list of pieces and returns it in uppercase if blacks turn, or lowercase if white. """ return map(lambda p: p.lower() if self.whiteToMove else p.upper(), pieces) def posOnBoard(self, piece): """ :param piece: a case _sensitiv_ one letter string. Valid 'K', 'Q', 'N', 'P', 'B', 'R', will be transformed to lowercase if it's black's turn to move :return int|[int]: Returns the posistion(s) on the board for a piece, if only one pos, a int is return, else a list of int is returned """ correctPiece = piece if self.whiteToMove else piece.lower() posistionsOnBoard = [i for i, pos in enumerate(self.internalChessBoard) if pos == correctPiece] if len(posistionsOnBoard) == 1: return posistionsOnBoard[0] else: return posistionsOnBoard if __name__ == "__main__": f = open("1999.txt", "r") g = open("production.txt", "w") h = open("fails.txt", "w") for line in f: pgnFormat = line[2:-1] winner = line[0] if winner == "W": win_text = " 1 0 0" elif winner == "R": win_text = " 0 1 0" elif winner == "B": win_text = " 0 0 1" else: print("error") converter = PgnToFen() converter.resetBoard() mid_liste = [] try: for move in pgnFormat.split(' '): converter.move(move) mid_liste.append(converter.getFullFen() + win_text) for unit in mid_liste: g.write(unit + "\n") except: h.write(line) f.close() g.close() h.close()
true
56af3fa98729a14a6c12a805457f6f213b7ab8b1
Python
cash2one/xai
/xai/brain/wordbase/adjectives/_tidy.py
UTF-8
483
2.703125
3
[ "MIT" ]
permissive
#calss header class _TIDY(): def __init__(self,): self.name = "TIDY" self.definitions = [u'having everything ordered and arranged in the right place, or liking to keep things like this: ', u'(of amounts of money) large: '] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'adjectives' def run(self, obj1, obj2): self.jsondata[obj2] = {} self.jsondata[obj2]['properties'] = self.name.lower() return self.jsondata
true
1ec927e2750a3b8ac90625ff40b562f87afb7004
Python
PilKvas/BootCamp
/code_wars/Century From Year.py
UTF-8
268
2.9375
3
[]
no_license
"""The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc. """ def century(year): century = year // 100 if year % 100 == 0: return century return century + 1
true
d759340f3dc453c9cec22269f128c5971c4603f3
Python
777GE90/pokedex
/tests/test_server.py
UTF-8
5,348
2.671875
3
[]
no_license
import unittest from unittest.mock import patch from server import app class PokemonTests(unittest.TestCase): def setUp(self): app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False self.app = app.test_client() @patch("modules.pokeapi.PokeAPIWrapper.get_pokemon_species_by_name") def test_pokemon_get(self, mock_get_pokemon): """ Assert the GET Pokemon endpoint always returns the same result as the get_pokemon_species_by_name method """ result = { "name": "mewtwo", "habitat": "rare", "isLegendary": True, "description": "Some description", } status_code = 200 mock_get_pokemon.return_value = (result, status_code) response = self.app.get("/pokemon/mewtwo") self.assertEqual(response.status_code, 200) pokemon_json = response.json self.assertEqual(pokemon_json, result) result = {"message": "Error: Not Found"} status_code = 404 mock_get_pokemon.return_value = (result, status_code) response = self.app.get("/pokemon/mewtwo") self.assertEqual(response.status_code, 404) pokemon_json = response.json self.assertEqual(pokemon_json, result) @patch( "modules.funtranslations.FunTranslationsAPIWrapper." "translate_shakespeare" ) @patch("modules.funtranslations.FunTranslationsAPIWrapper.translate_yoda") @patch("modules.pokeapi.PokeAPIWrapper.get_pokemon_species_by_name") def test_pokemon_translated_get_bad_status( self, mock_get_pokemon, mock_yoda, mock_shakespeare ): """ Tests that translation is not attempted when getting the Pokemon failed """ result = {"message": "Error: Not Found"} status_code = 404 mock_get_pokemon.return_value = (result, status_code) response = self.app.get("/pokemon/translated/mewtwo") mock_yoda.assert_not_called() mock_shakespeare.assert_not_called() self.assertEqual(response.status_code, status_code) self.assertEqual(response.json, result) @patch( "modules.funtranslations.FunTranslationsAPIWrapper." "translate_shakespeare" ) @patch("modules.funtranslations.FunTranslationsAPIWrapper.translate_yoda") @patch("modules.pokeapi.PokeAPIWrapper.get_pokemon_species_by_name") def test_pokemon_translated_get_correct_translator( self, mock_get_pokemon, mock_yoda, mock_shakespeare ): """ Tests that the correct translator is used depending on the get_pokemon response """ poke_result = { "name": "mewtwo", "habitat": "rare", "isLegendary": True, "description": "hello, world", } poke_status_code = 200 mock_get_pokemon.return_value = (poke_result, poke_status_code) yoda_result = { "translation": "Force be with you,World", } yoda_status_code = 200 mock_yoda.return_value = (yoda_result, yoda_status_code) response = self.app.get("/pokemon/translated/mewtwo") mock_yoda.assert_called() mock_shakespeare.assert_not_called() poke_result["description"] = yoda_result["translation"] self.assertEqual(response.status_code, poke_status_code) self.assertEqual(response.json, poke_result) poke_result = { "name": "mewtwo", "habitat": "rare", "isLegendary": False, "description": "hello, world", } poke_status_code = 200 mock_get_pokemon.return_value = (poke_result, poke_status_code) shakespeare_result = { "translation": "Valorous morrow to thee, sir, ordinary", } shakespeare_status_code = 200 mock_shakespeare.return_value = ( shakespeare_result, shakespeare_status_code, ) response = self.app.get("/pokemon/translated/mewtwo") mock_shakespeare.assert_called() poke_result["description"] = shakespeare_result["translation"] self.assertEqual(response.status_code, shakespeare_status_code) self.assertEqual(response.json, poke_result) @patch("modules.funtranslations.FunTranslationsAPIWrapper.translate_yoda") @patch("modules.pokeapi.PokeAPIWrapper.get_pokemon_species_by_name") def test_pokemon_translated_get_ft_failure( self, mock_get_pokemon, mock_yoda ): """ Tests that the default description is returned if the Fun Translation fails for whatever reason """ poke_result = { "name": "mewtwo", "habitat": "rare", "isLegendary": True, "description": "hello, world", } poke_status_code = 200 mock_get_pokemon.return_value = (poke_result, poke_status_code) yoda_result = { "message": "Error: It broke!", } yoda_status_code = 500 mock_yoda.return_value = (yoda_result, yoda_status_code) response = self.app.get("/pokemon/translated/mewtwo") mock_yoda.assert_called() self.assertEqual(response.status_code, poke_status_code) self.assertEqual(response.json, poke_result)
true
a6ca972b598d4aad177c5874d3415cba3e79cca5
Python
adam-lim1/MarchMadnessML
/mmml/mmml/game_results.py
UTF-8
9,711
3.125
3
[]
no_license
import pandas as pd import numpy as np import math import sys def win_probs(*, home_elo, road_elo, hca_elo): """ Home and road team win probabilities implied by Elo ratings and home court adjustment. """ h = math.pow(10, home_elo/400) r = math.pow(10, road_elo/400) a = math.pow(10, hca_elo/400) denom = r + a*h home_prob = a*h / denom road_prob = r / denom return home_prob, road_prob def update(*, winner, home_elo, road_elo, hca_elo, k, probs=False): """ Update Elo ratings for a given match up. """ home_prob, road_prob = win_probs(home_elo=home_elo, road_elo=road_elo, hca_elo=hca_elo) if winner[0].upper() == 'H': home_win = 1 road_win = 0 elif winner[0].upper() in ['R', 'A', 'V']: # road, away or visitor are treated as synonyms home_win = 0 road_win = 1 else: raise ValueError('unrecognized winner string', winner) new_home_elo = home_elo + k*(home_win - home_prob) new_road_elo = road_elo + k*(road_win - road_prob) if probs: return new_home_elo, new_road_elo, home_prob, road_prob else: return new_home_elo, new_road_elo def getNumericSeed(seed): seed = seed[1:].lstrip("0") if seed[-1] in ['a', 'b']: seed = seed[:-1] return int(seed) def update_progress_bar(current, total): """ Prints progress inplace. To be used with iterative function. :param current: numeric. Current stage :param total: numeric. Total number of stages (end goal) :return: None """ barLength = 24 # Modify this to change the length of the progress bar progress = float(current) / float(total) block = int(round(barLength * progress)) text = "\rProgress: [{block}]: {current} / {total}".format( block=("=" * max((block - 1), 0) + ">" + " " * (barLength - block)), current=current, total=total) sys.stdout.write(text) sys.stdout.flush() class gameResults: def __init__(self, df): self.df = df def toHomeAwayFormat(self, seed=42): """ Takes DF of game results with WTeam/LTeam format and returns DF of game results scrambled with HomeTeam/AwayTeam format. Adds column of AWin (binary indicator) """ df = self.df np.random.seed(seed=seed) df['rand'] = np.random.rand(df.shape[0]) df['NLoc'] = np.where(df['WLoc'] == "N", 1, 0) df_H = df.query('WLoc == "H" or (WLoc == "N" and rand > 0.5)') df_A = df.query('WLoc == "A" or (WLoc == "N" and rand <= 0.5)') df_H = df_H.drop('WLoc', axis=1) for col in list(df_H.columns).copy(): if col[0] == "W": df_H = df_H.rename(columns={col:('H'+col[1:])}) if col[0] == "L": df_H = df_H.rename(columns={col:('A'+col[1:])}) df_H['HWin'] = 1 df_H['AWin'] = 0 # Flip W/L to B/A for half of games df_A = df_A.drop('WLoc', axis=1) for col in list(df_A.columns).copy(): if col[0] == "W": df_A = df_A.rename(columns={col:('A'+col[1:])}) if col[0] == "L": df_A = df_A.rename(columns={col:('H'+col[1:])}) df_A['HWin'] = 0 df_A['AWin'] = 1 home_away_results = df_H.append(df_A, sort=True) return home_away_results def toSeasonAggFormat(self): """ Duplicate results from raw results DF to allow for season-aggregations. Transforms H/A view to Team/Opponent. Each game is represented 2x in resulting DF (once in terms of Team A and once in terms of Team B) """ df_a = self.toHomeAwayFormat().copy() df_b = df_a.copy() for col in list(df_a.columns).copy(): if col[0] == "H": df_a = df_a.rename(columns={col:(col[1:])}) if col[0] == "A": df_a = df_a.rename(columns={col:('Opp'+col[1:])}) #df_a['Win'] = 1 for col in list(df_b.columns).copy(): if col[0] == "H": df_b = df_b.rename(columns={col:('Opp'+col[1:])}) if col[0] == "A": df_b = df_b.rename(columns={col:(col[1:])}) df_c = df_a.append(df_b, sort=True) return df_c def getSeasonStats(self): """ Aggregate game by game stats to the Team/Season level. Calculate various advanced stats """ df_season_agg = self.toSeasonAggFormat() # Calculate Possessions for each game df_season_agg['possessions'] = 0.5 * (df_season_agg['FGA'] + 0.475 * df_season_agg['FTA'] - df_season_agg['OR'] + df_season_agg['TO']) \ + 0.5 * (df_season_agg['OppFGA'] + 0.475 * df_season_agg['OppFTA'] - df_season_agg['OppOR'] + df_season_agg['OppTO']) # Aggregate to Season Summary Level season_stats = df_season_agg.groupby(['TeamID', 'Season']).sum() season_stats = season_stats.rename(columns={'Win':'wins'}) # Season Advanced Stats season_stats['o_eff'] = season_stats['Score'] / season_stats['possessions'] * 100 season_stats['d_eff'] = season_stats['OppScore'] / season_stats['possessions'] * 100 season_stats['net_eff'] = season_stats['o_eff'] - season_stats['d_eff'] season_stats.drop('DayNum', axis=1, inplace=True) season_stats.drop('OppTeamID', axis=1, inplace=True) season_stats.drop('rand', axis=1, inplace=True) return season_stats def getElo(self, hca_elo=65, k=20, initial_elo=1500.0): # Transform W/L to H/A results format home_away_results = self.toHomeAwayFormat() # Define Initialized Elo Dict elo_dict = {} for season in set(home_away_results['Season']): HTeams = list(set(home_away_results.query('Season == {}'.format(season))['HTeamID'])) ATeams = list(set(home_away_results.query('Season == {}'.format(season))['ATeamID'])) teams_list = list(set(HTeams + ATeams)) elo_dict[season] = {j:[initial_elo] for j in teams_list} # Ensure game results are sorted home_away_results.sort_values(['Season', 'DayNum'], inplace=True) # Iterate through game results, updating elo dict current_progress = 0 for i in home_away_results.index: update_progress_bar(current_progress, home_away_results.shape[0]) # Get TeamID's and Season HTeamID = int(home_away_results.loc[i]['HTeamID']) ATeamID = int(home_away_results.loc[i]['ATeamID']) season = int(home_away_results.loc[i]['Season']) # Determine true winner if home_away_results.loc[i]['HWin']==1: winner = "H" else: winner = "A" # Previous Elo Scores home_elo_initial = elo_dict[season][HTeamID][-1] away_elo_initial = elo_dict[season][ATeamID][-1] # Calculate Elo update, accounting for Home Court Advantage if home_away_results.loc[i]['NLoc'] == 1: # No home court advantage at neutral site h_elo_update, a_elo_update = update(winner=winner, home_elo=home_elo_initial, road_elo=away_elo_initial, hca_elo=0, k=k) else: h_elo_update, a_elo_update = update(winner=winner, home_elo=home_elo_initial, road_elo=away_elo_initial, hca_elo=hca_elo, k=k) # Update Elo scores in dict elo_dict[season][HTeamID].append(h_elo_update) elo_dict[season][ATeamID].append(a_elo_update) current_progress = current_progress + 1 # Convert Nested elo Dict to DataFrame elo_df = pd.DataFrame(pd.DataFrame.from_dict(elo_dict).stack(), columns=['elo']) elo_df['last_elo'] = elo_df['elo'].apply(lambda x: x[-1]) elo_df.index.set_names(['TeamID', 'Season'], inplace=True) return elo_df def getBase(self): """ Format DataFrame for use as base of model data w/ key info only. To be used on Tournament results """ home_away_results = self.toHomeAwayFormat() base = home_away_results[['HTeamID', 'ATeamID', 'Season','DayNum','HWin', 'HScore', 'AScore']] return base # def getTourneySeedWinPct(self, seeds, current_season): # tourney_results = self.df.query('Season < {}'.format(current_season)) # seeds['numeric_seed'] = seeds['Seed'].apply(lambda x: getNumericSeed(x)) # results_seeded = tourney_results.merge(seeds, left_on=['WTeamID', 'Season'], right_on=['TeamID', 'Season'], how='left')\ # .merge(seeds, left_on=['LTeamID', 'Season'], right_on=['TeamID', 'Season'], how='left', suffixes=('_W', '_L'))[['Season', 'numeric_seed_W', 'numeric_seed_L']] # wins = results_seeded.pivot_table(index='numeric_seed_W', columns='numeric_seed_L', aggfunc=np.count_nonzero) # results_seeded_reverse = results_seeded.copy().rename(columns={'numeric_seed_W':'numeric_seed_L1','numeric_seed_L':'numeric_seed_W1'}) # results_seeded_reverse = results_seeded_reverse.rename(columns={'numeric_seed_W1':'numeric_seed_W','numeric_seed_L1':'numeric_seed_L'}) # stacked = results_seeded[['Season', 'numeric_seed_W', 'numeric_seed_L']].append(results_seeded_reverse[['Season', 'numeric_seed_W', 'numeric_seed_L']], sort=True) # games = stacked.pivot_table(index='numeric_seed_W', columns='numeric_seed_L', aggfunc=np.count_nonzero) # win_pct = wins/games # np.fill_diagonal(win_pct.values, -999) # win_pct.fillna(-999, inplace=True) # games.fillna(-999, inplace=True) # return win_pct, games
true
97745a79bfc41e7713cf81f5359aea1d1014b605
Python
Laxmivadekar/file
/from xyz file .py
UTF-8
2,601
3.34375
3
[]
no_license
f=open('xyz.txt') content=f.read() print(content) f.close() print('_____________________________________________________________________') #================================================================================= # f=open('xyz.txt','r') # f.read() # f.close() print('____________________________no. of charactes we want yo read_________________________________________') f=open('xyz.txt') content=f.read(100) print(content) f.close() print('_____________________________________________________________________') #=============================================================================== f=open('xyz.txt') content=f.read(11) print('1:',content) content=f.read(1) print('2:',content) f.close() print('____________________________rt-Read in text format________________________________________') #============================================================================= f=open('xyz.txt','rt') content=f.read() for line in content: print(line) print('______________________________rt-as it is before but one extra line after every line_______________________________________') #=============================================================================== f=open('xyz.txt','rt') for line in f: print(line) print('_________________________________rt -side by side____________________________________') #================================================================================ f=open('xyz.txt','rt') for line in f: print(line,end='') f.close() print('_____________________________________________________________________') #================================================================================ f=open('xyz.txt') content=f.read(11) print('1:',content) content=f.read(1) print('2:',content) f.close() print('_________________________Readline____________________________________________') #================================================================================ f=open('xyz.txt','rt') print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) # f.close() print('________________________________readlines_________________________________________________') #========================================================================================= f=open('xyz.txt','rt') print(f.readlines()) print("______________________________________________________________________________") #=========================================================================================== f=open('abc.txt','a') a=f.write('\n**you are lucky**') print(a) f.close()
true
448784979c9edc5a47e210b51f3eb317f81dad70
Python
rajeshpandey2053/Python_assignment_3
/merge_sort.py
UTF-8
939
3.78125
4
[]
no_license
def merge(left, right, arr): i = 0 j =0 k = 0 while ( i < len(left) and j < len(right)): if (left[i] <= right[j]): arr[k] = left[i] i = i + 1 else: arr[k] = right[j] j = j + 1 k = k + 1 # if remaining in left while(i < len(left)): arr[k] = left[i] i = i +1 k = k + 1 # if remaining in right while(i < len(right)): arr[k] = right[i] i = i +1 k = k + 1 def merge_sort(arr): if len(arr)<2: return mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) merge(left, right,arr) #main function arr = list() num = int(input("Enter the number of elements in the list")) for _ in range(num): arr.append(int(input("Enter item: "))) merge_sort(arr) print("The sorted list through merge sort is : ", arr)
true
0cac4b6446a187c980d92ab66ac51b79b7317841
Python
pujanthakrar/ECON-425-Machine-Learning
/dataTrans.py
UTF-8
1,436
3.28125
3
[]
no_license
import numpy as np from pandas import read_csv #### functions ##### Function1: import data def download_data(fileLocation, fields): ''' Downloads the data for this script into a pandas DataFrame. Uses columns indices provided ''' frame = read_csv( fileLocation, # Specify the file encoding # Latin-1 is common for data from US sources encoding='latin-1', #encoding='utf-8', # UTF-8 is also common # Specify the separator in the data sep=',', # comma separated values # Ignore spaces after the separator skipinitialspace=True, # Generate row labels from each row number index_col=None, # No header names header=None, # use the first line as headers usecols=fields ) # Return the entire frame return frame #### Function 2: transform data to numbers def transtonumber(string,names): output = np.zeros((1,len(string))) for i in range(len(string)): for j in range(len(names)): if string[i] == names[j]: output[0][i] = j return output #### Function 3: data normalization def rescaleNormalization(dataArray): min = dataArray.min() denom = dataArray.max() - min newValues = [] for x in dataArray: newX = (x - min) / denom newValues.append(newX) return newValues
true
1e0c2f6d0ce9a2b280b7a24ba4b8d60b78c63090
Python
dollcg24/diab_risk
/backend/server/apps/ml/tests.py
UTF-8
1,794
2.578125
3
[ "MIT" ]
permissive
from django.test import TestCase from apps.ml.registry import MLRegistry from apps.ml.risk_classifier.random_forest import RandomForestClassifier class MLTests(TestCase): def test_rf_algorithm(self): input_data = { "gender": "f", "age": "B", "bmi": "overweight", "heredity": "n", "calorie": "y", "sleep": "regular", "bp": "normal", "smoke": "y", "alcohol": "y", "mental": "n", "physical": "n", "skin": "y", "pcos": "y" } my_alg = RandomForestClassifier() response = my_alg.compute_prediction(input_data) #self.assertEqual('OK', response['status']) self.assertTrue('label' in response) self.assertEqual('h', response['label']) self.assertEqual('m', response['label']) self.assertEqual('l', response['label']) def test_registry(self): registry = MLRegistry() self.assertEqual(len(registry.endpoints), 0) endpoint_name = "risk_classifier" algorithm_object = RandomForestClassifier() algorithm_name = "random forest" algorithm_status = "production" algorithm_version = "0.0.1" algorithm_owner = "Piotr" algorithm_description = "Random Forest with simple pre- and post-processing" algorithm_code = inspect.getsource(RandomForestClassifier) # add to registry registry.add_algorithm(endpoint_name, algorithm_object, algorithm_name, algorithm_status, algorithm_version, algorithm_owner, algorithm_description, algorithm_code) # there should be one endpoint available self.assertEqual(len(registry.endpoints), 1)
true
55993b7622919e184c954442a55898667fe06988
Python
maheel/aws-security-hub-automated-response-and-remediation
/source/LambdaLayers/utils.py
UTF-8
4,675
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
#!/usr/bin/python ############################################################################### # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License Version 2.0 (the "License"). You may not # # use this file except in compliance with the License. A copy of the License # # is located at # # # # http://www.apache.org/licenses/ # # # # or in the "license" file accompanying this file. This file is distributed # # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express # # or implied. See the License for the specific language governing permis- # # sions and limitations under the License. # ############################################################################### import json import re from awsapi_cached_client import AWSCachedClient class StepFunctionLambdaAnswer: """ Maintains a hash of AWS API Client connections by region and service """ status = '' message = '' executionid = '' affected_object = '' remediation_status = '' logdata = [] def __init__(self): """Set message and status - minimum required fields""" self.status = '' self.message = '' self.remediation_status = '' self.logdata = [] def __str__(self): return json.dumps(self.__dict__) def json(self): return self.__dict__ def update_status(self, status): """Set status""" self.status = status def update_message(self, message): """Set status""" self.message = message def update_logdata(self, logdata): """Set logdata (list)""" self.logdata = logdata def update_executionid(self, executionid): """Set execution id (string)""" self.executionid = executionid def update_affected_object(self, affected_object): """Set affected_object (string)""" self.affected_object = affected_object def update_remediation_status(self, status): """Set execution id (string)""" self.remediation_status = status def update(self, answer_data): if "status" in answer_data: self.update_status(answer_data['status']) if "message" in answer_data: self.update_message(answer_data['message']) if "remediation_status" in answer_data: self.update_remediation_status(answer_data['remediation_status']) if "logdata" in answer_data: self.update_logdata(answer_data['logdata']) if "executionid" in answer_data: self.update_executionid(answer_data['executionid']) if "affected_object" in answer_data: self.update_affected_object(answer_data['affected_object']) def resource_from_arn(arn): """ Strip off the leading parts of the ARN: arn:*:*:*:*: Return what's left. If no match, return the original predicate. """ arn_pattern = re.compile(r'arn\:[\w,-]+:[\w,-]+:.*:[0-9]*:(.*)') arn_match = arn_pattern.match(arn) answer = arn if arn_match: answer = arn_match.group(1) return answer def partition_from_region(region_name): """ returns the partition for a given region Note: this should be a Boto3 function and should be deprecated once it is. On success returns a string On failure returns NoneType """ parts = region_name.split('-') try: if parts[0] == 'us' and parts[1] == 'gov': return 'aws-us-gov' elif parts[0] == 'cn': return 'aws-cn' else: return 'aws' except: return def publish_to_sns(topic_name, message, region=None): """ Post a message to an SNS topic """ AWS = AWSCachedClient(region) # cached client object partition = None if region: partition = partition_from_region(region) else: partition = 'aws' region = 'us-east-1' topic_arn = 'arn:' + partition + ':sns:' + region + ':' + AWS.account + ':' + topic_name json_message = json.dumps({"default":json.dumps(message)}) message_id = AWS.get_connection('sns', region).publish( TopicArn=topic_arn, Message=json_message, MessageStructure='json' ).get('MessageId', 'error') return message_id
true
90bba9cc0edc8b8c652c0e9a8f567a057209605f
Python
L-avender/AID1905
/PycharmProjects/python_file/month2/day13/flags.py
UTF-8
378
3.15625
3
[]
no_license
""" flags.py flags 扩展功能 """ import re s="""Hello 北京""" #只能匹配ASCII编码 # regex=re.compile(r"\w+",flags=re.ASCII) #不区分大小写 #regex=re.compile(r'[a-z]+',flags=re.IGNORECASE) #可以匹配换行 #regex=re.compile(r".+",flags=re.S) #^,$匹配每一行的开头结尾位置 regex=re.compile(r"^北京",flags=re.M) l=regex.findall(s) print(l)
true
4c16f2c3fe79ba66b280599fb509243d5b0414b5
Python
raviverma2791747/Hacktober-DSA
/ELLIPSE.PY
UTF-8
1,887
4.125
4
[]
no_license
# Mid-Point Ellipse Algorithm C019322 def midptellipse(rx, ry, xc, yc): x = 0 y = ry # Initial decision parameter of region 1 d1 = ((ry * ry) - (rx * rx * ry) + (0.25 * rx * rx)) dx = 2 * ry * ry * x dy = 2 * rx * rx * y # For region 1 while (dx < dy): # Using 4-way symmetry print("(", x + xc, ",", y + yc, ")") print("(", -x + xc, ",", y + yc, ")") print("(", x + xc, ",", -y + yc, ")") print("(", -x + xc, ",", -y + yc, ")") # Checking and updating value of decision parameter based on algorithm if (d1 < 0): x += 1 dx = dx + (2 * ry * ry) d1 = d1 + dx + (ry * ry) else: x += 1 y -= 1 dx = dx + (2 * ry * ry) dy = dy - (2 * rx * rx) d1 = d1 + dx - dy + (ry * ry) # Decision parameter : - region 2 d2 = (((ry * ry) * ((x + 0.5) * (x + 0.5))) + ((rx * rx) * ((y - 1) * (y - 1))) - (rx * rx * ry * ry)) # Plotting points : - region 2 while (y >= 0): # using 4-way symmetry print("(", x + xc, ",", y + yc, ")") print("(", -x + xc, ",", y + yc, ")") print("(", x + xc, ",", -y + yc, ")") print("(", -x + xc, ",", -y + yc, ")") # Checking and updating parameter value based on algorithm if (d2 > 0): y -= 1 dy = dy - (2 * rx * rx) d2 = d2 + (rx * rx) - dy else: y -= 1 x += 1 dx = dx + (2 * ry * ry) dy = dy - (2 * rx * rx) d2 = d2 + dx - dy + (rx * rx) if __name__ == '__main__': x1 = int(input("Enter x1 ")) y1 = int(input("Enter y1 ")) x2 = int(input("Enter x2 ")) y2 = int(input("Enter y2 ")) midptellipse(x1, y1, x2, y2)
true
2f514794f1a5dcb74aa6421f3d192276b65f6444
Python
guard1000/Everyday-coding
/190113_더 맵게.py
UTF-8
470
3.296875
3
[]
no_license
import heapq def solution(scoville, K): answer = 0 heapq.heapify(scoville) while len(scoville) >1: if scoville[0] >= K: return answer answer += 1 tmp = scoville[0] heapq.heappop(scoville) tmp += (scoville[0]*2) heapq.heappop(scoville) heapq.heappush(scoville, tmp) if scoville[0] > K: return answer else: return -1 s=[1, 3, 2, 9, 10, 12] k=7 print(solution(s,k))
true
7156f25014ad728695f24543ba25b922ab8789ce
Python
beader/tianchi-3rd_security
/models/cnn.py
UTF-8
797
2.5625
3
[]
no_license
import tensorflow as tf from tensorflow.keras.layers import Input, MaxPool1D, Conv1D, GlobalMaxPool1D, Concatenate, Dense def build_cnn_model(num_classes, feat_size, name='cnn'): input_seq = Input(shape=(None, feat_size), dtype='float32') x = MaxPool1D(5, strides=2)(input_seq) conv1 = Conv1D(64, kernel_size=3, strides=1, activation='relu')(x) conv1 = GlobalMaxPool1D()(conv1) conv2 = Conv1D(64, kernel_size=5, strides=2, activation='relu')(x) conv2 = GlobalMaxPool1D()(conv2) conv3 = Conv1D(64, kernel_size=7, strides=3, activation='relu')(x) conv3 = GlobalMaxPool1D()(conv3) x = Concatenate()([conv1, conv2, conv3]) x = Dense(num_classes, activation='softmax')(x) model = tf.keras.Model(inputs=input_seq, outputs=x, name=name) return model
true
630eb253b214d7844b49c5defc0f69f68dfb0aaf
Python
moret/sparse-rdf
/tests/test_path_index.py
UTF-8
1,002
3
3
[]
no_license
from app.persistance import db def test_exist(): from app.persistance import pi assert pi def test_replace_all_paths_with_two_paths(): paths = [['nod1', 'edge1', 'nod2'], ['nod2', 'edge2', 'nod3']] db.replace_all_paths(paths) assert 2 == db.count_paths() def test_replace_all_paths_doesnt_change_nodes(): nodes = ['nod1', 'nod2', 'nod3'] db.replace_all_nodes(nodes) paths = [['nod1', 'edge1', 'nod2'], ['nod2', 'edge2', 'nod3']] db.replace_all_paths(paths) assert 3 == db.count_nodes() assert 2 == db.count_paths() def test_stored_path_returns_as_list(): paths = [['nod1', 'edge1', 'nod2'], ['nod2', 'edge2', 'nod3']] db.replace_all_paths(paths) assert isinstance(db.get_path(1), list) def test_stored_paths_maintains_order(): paths = [['nod1', 'edge1', 'nod2'], ['nod2', 'edge2', 'nod3']] db.replace_all_paths(paths) assert ['nod1', 'edge1', 'nod2'] == db.get_path(0) assert ['nod2', 'edge2', 'nod3'] == db.get_path(1)
true
985c4c9e3cb951cdc39ba58611de5fb99e598f24
Python
tylerauerbeck/poolboy
/operator/gpte/util.py
UTF-8
3,472
2.890625
3
[]
no_license
import collections import copy import datetime import jinja2 import json class TimeStamp(object): def __init__(self, set_datetime=None): if isinstance(set_datetime, datetime.datetime): self.datetime = set_datetime elif isinstance(set_datetime, str): self.datetime = datetime.datetime.strptime(set_datetime, "%Y-%m-%dT%H:%M:%SZ") else: self.datetime = set_datetime def __call__(self, arg): return TimeStamp(arg) def __str__(self): return self.datetime.strftime('%FT%TZ') def add(self, interval): if interval.endswith('d'): self.datetime = self.datetime + datetime.timedelta(days=int(interval[0:-1])) elif interval.endswith('h'): self.datetime = self.datetime + datetime.timedelta(hours=int(interval[0:-1])) elif interval.endswith('m'): self.datetime = self.datetime + datetime.timedelta(minutes=int(interval[0:-1])) elif interval.endswith('s'): self.datetime = self.datetime + datetime.timedelta(seconds=int(interval[0:-1])) else: raise Exception("Invalid interval format %s" % (interval)) return self @property def utcnow(self): return TimeStamp(datetime.datetime.utcnow()) jinja2env = jinja2.Environment( block_start_string='{%:', block_end_string=':%}', comment_start_string='{#:', comment_end_string=':#}', variable_start_string='{{:', variable_end_string=':}}' ) jinja2env.filters['to_json'] = lambda x: json.dumps(x) def dict_merge(dct, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``dct``. :param dct: dict onto which the merge is executed :param merge_dct: dct merged into dct :return: None """ # FIXME? What about lists within dicts? Such as container lists within a pod? for k, v in merge_dct.items(): if k in dct \ and isinstance(dct[k], dict) \ and isinstance(merge_dct[k], collections.Mapping): dict_merge(dct[k], merge_dct[k]) else: dct[k] = copy.deepcopy(merge_dct[k]) def defaults_from_schema(schema): obj = {} for prop, property_schema in schema.get('properties', {}).items(): if 'default' in property_schema and prop not in obj: obj[prop] = property_schema['default'] if property_schema['type'] == 'object': defaults = defaults_from_schema(property_schema) if defaults: if not prop in obj: obj[prop] = {} dict_merge(obj[prop], defaults) if obj: return obj def jinja2process(template, variables): variables = copy.copy(variables) variables['timestamp'] = TimeStamp() j2template = jinja2env.from_string(template) return j2template.render(variables) def recursive_process_template_strings(template, variables={}): if isinstance(template, dict): return { k: recursive_process_template_strings(v, variables) for k, v in template.items() } elif isinstance(template, list): return [ recursive_process_template_strings(item) for item in template ] elif isinstance(template, str): return jinja2process(template, variables) else: return template
true