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
9a1b9bd6f73050cb215613bdf1e0923e4c200866
Python
nyucusp/gx5003-fall2013
/jsa325/Assignment 1/problem2.py
UTF-8
536
3.03125
3
[]
no_license
import sys import math <<<<<<< HEAD jollyValue = True ======= >>>>>>> d6f40eeb85f30f87d7da17a58e366c13cf23b728 n = int(sys.argv[1]) inp = sys.argv[2:] intList = map(int, inp) # map integers to list out = [] for i in range(1, n): out.append(math.fabs(inp[i] - inp[i - 1])) out.sort() val = 0 for i in range(1, n): if out[i - 1] == i: val = val + 1 if val == n - 1: print "Jolly" else: <<<<<<< HEAD print "Not Jolly" ======= print "Not Jolly" >>>>>>> d6f40eeb85f30f87d7da17a58e366c13cf23b728
true
f1f77f7d8fd15a27a4413f68f1e5b632846d7b2e
Python
darkismus/mooc-ohjelmointi-21
/osa04-07a_alkioiden_arvojen_muutokset/test/test_alkioiden_arvojen_muutokset.py
UTF-8
2,547
2.71875
3
[]
no_license
import unittest from unittest.mock import patch from tmc import points from tmc.utils import load_module, reload_module, get_stdout, check_source from functools import reduce from random import randint exercise = 'src.alkioiden_arvojen_muutokset' def f(d): return '\n'.join(d) def getcor(l): ls = list(range(1, 6)) i = 0 s = [] while l[i] != -1: ls[l[i]] = l[i+1] i += 2 s.append(str(ls)) return s @points('4.alkoiden_arvojen_muutokset') class AlkioidenArvojenMuutoksetTest(unittest.TestCase): @classmethod def setUpClass(cls): with patch('builtins.input', side_effect =["-1"]): cls.module = load_module(exercise, 'fi') def test_syotteet1(self): values = (0,100,-1) with patch('builtins.input', side_effect = [str(x) for x in values]): reload_module(self.module) output = get_stdout() output_list = output.split("\n") cor = getcor(values) mssage = """\nHuomaa, että tässä tehtävässä mitään koodia EI TULE SIJOITTAA lohkon if __name__ == "__main__": sisälle """ #\n{mssage}") self.assertTrue(len(output)>0, f"Ohjelmasi ei tulosta mitään kun syöte on {values}\n{mssage}") self.assertEqual(len(output_list), len(cor), f"Ohjelmasi tulisi tulostaa {len(cor)} riviä, nyt se tulostaa {len(output_list)} riviä kun syöte on: {values}") r = 1 for l1,l2 in zip(cor, output_list): self.assertEqual(l1.strip(), l2.strip(), f"Tulostus väärin rivillä {r}: ohjelman pitäisi tulostaa\n{l1}\nmutta se tulostaa\n{l2}\nkun syöte on {values}") r += 1 def test_syotteet2(self): values = (1,25,3,333,2,-543,-1) with patch('builtins.input', side_effect = [str(x) for x in values]): reload_module(self.module) output = get_stdout() output_list = output.split("\n") cor = getcor(values) self.assertEqual(len(output_list), len(cor), f"Ohjelmasi tulisi tulostaa {len(cor)} riviä, nyt se tulostaa {len(output_list)} riviä kun syöte on: {values}") r = 1 for l1,l2 in zip(cor, output_list): self.assertEqual(l1.strip(), l2.strip(), f"Tulostus väärin rivillä {r}: ohjelman pitäisi tulostaa\n{l1}\nmutta se tulostaa\n{l2}\nkun syöte on {values}") r += 1 if __name__ == '__main__': unittest.main()
true
e0302440874c23a58d11fe527d89f264b1457e25
Python
senecal-jjs/IMBD
/Revenue_Prediction.py
UTF-8
8,177
3.125
3
[]
no_license
import numpy as np import random import collections from operator import itemgetter from scipy.stats.stats import pearsonr from scipy.stats.stats import spearmanr from sklearn.neighbors.kde import KernelDensity from sklearn.linear_model import LogisticRegression from sklearn.neural_network import MLPClassifier from Tkinter import * import matplotlib.pyplot as plt import os '''This module contains the functionality to perfrom the revenue prediction analysis''' '''Print each of the correlations''' '''Print the logistic regression and mlp score''' def calculate(frame, data): numerical_data = data[0] # fb_likes, budget, revenue, release year, runtime categorical_data = data[1] # revenues associated with each genre # Calculate revenue summary statistics for the Genres stat = collections.namedtuple('stat', ('mean', 'min', 'max', 'stdev')) genre_revenue_stat = {} # Revenue Statistics associated with each genre for key in categorical_data.keys(): genre_revenue_stat[key] = stat(round(np.mean(categorical_data[key]), 2), round(np.min(categorical_data[key]), 2), round(np.max(categorical_data[key]), 2), round(np.std(categorical_data[key]), 2)) print(sorted(genre_revenue_stat, key=lambda k: genre_revenue_stat[k][0])) # Calculate correlations among numerical data types p_fb_likes = pearsonr(numerical_data.fb_likes, numerical_data.revenue) p_budget = pearsonr(numerical_data.budget, numerical_data.revenue) p_release = pearsonr(numerical_data.release, numerical_data.revenue) p_runtime = pearsonr(numerical_data.runtime, numerical_data.revenue) s_fb_likes = spearmanr(numerical_data.fb_likes, numerical_data.revenue) s_budget = spearmanr(numerical_data.budget, numerical_data.revenue) s_release = spearmanr(numerical_data.release, numerical_data.revenue) s_runtime = spearmanr(numerical_data.runtime, numerical_data.revenue) data_pt = collections.namedtuple('data_pt', ('budget', 'fb_likes', 'revenue', 'release', 'runtime')) associated_data = [] for i in range(len(numerical_data.budget)): associated_data.append(data_pt(numerical_data.budget[i], numerical_data.fb_likes[i], numerical_data.revenue[i], numerical_data.release[i], numerical_data.runtime[i])) # Create revenue classes sorted_revenue = sorted(associated_data, key=itemgetter(2)) index1 = int(len(sorted_revenue)/4) index2 = index1*2 index3 = index1*3 class1 = sorted_revenue[:index1] class2 = sorted_revenue[index1:index2] class3 = sorted_revenue[index2:index3] class4 = sorted_revenue[index3:] # Assign class labels to the data labeled_data = [] for instance in class1: labeled_data.append(([instance.budget, instance.fb_likes, instance.release, instance.runtime], 0)) for instance in class2: labeled_data.append(([instance.budget, instance.fb_likes, instance.release, instance.runtime], 1)) for instance in class3: labeled_data.append(([instance.budget, instance.fb_likes, instance.release, instance.runtime], 2)) for instance in class4: labeled_data.append(([instance.budget, instance.fb_likes, instance.release, instance.runtime], 3)) # Assign data to training and testing sets cut = int(0.66 * len(sorted_revenue)) random.shuffle(labeled_data) training_data = labeled_data[:cut] testing_data = labeled_data[cut:] # Separate data and targets X = [] Y = [] for instance in training_data: X.append(instance[0]) Y.append(instance[1]) X = np.array(X) Y = np.array(Y) model = LogisticRegression() model.fit(X, Y) # Separate testing data Xt =[] Yt = [] for instance in testing_data: Xt.append(instance[0]) Yt.append(instance[1]) log_score = model.score(Xt, Yt) mlp = MLPClassifier(hidden_layer_sizes=(30, 30), activation='tanh', max_iter = 500, verbose=False, shuffle=True) mlp.fit(X, Y) mlp_score = mlp.score(Xt, Yt) # Print results to screen frame.text.insert(INSERT, "Correlation Results:\nCast Facebook Likes & Revenue, Pearson: %.2f; Spearman: %.2f\n" "Budget and Revenue, Pearson: %.2f; Spearman: %.2f\n" "Release Year and Revenue, Pearson: %.2f; Spearman: %.2f\n" "Runtime and Revenue, Pearson: %.2f; Spearman: %.2f\n" "\nLogistic Regression Classification Accuracy: %.2f\n" "\nNeural Network Classification Accuracy: %.2f\n" "\n" % (p_fb_likes[0], s_fb_likes[0], p_budget[0], s_budget[0], p_release[0], s_release[0], p_runtime[0], s_runtime[0], log_score, mlp_score)) for key in genre_revenue_stat.keys(): frame.text.insert(END, "\n" + str(key) + ": " + str(genre_revenue_stat[key]) + "\n") # Calculate probability distribution for each genre distributions = {} for key in categorical_data.keys(): X = categorical_data[key] X = np.array(X) X = X.reshape(-1, 1) x_grid = np.linspace(0, 309404152, 100000) kde = KernelDensity(kernel='gaussian', bandwidth=10000000).fit(X) log_pdf = kde.score_samples(x_grid[:, np.newaxis]) distributions[key] = np.exp(log_pdf) frame.ax.plot(x_grid, np.exp(log_pdf)) frame.ax.set_title(str(key) + " Revenue Probability Distribution") frame.ax.set_xlabel("Revenue (USD)") frame.ax.set_ylabel("Probability") frame.f.savefig("Plots/" + str(key) + "_revenue_dist") frame.ax.cla() # Save correlation plots to file frame.ax.scatter(numerical_data.budget, numerical_data.revenue) frame.ax.set_title("Budget vs Revenue") frame.ax.set_xlabel("Budget (USD)") frame.ax.set_ylabel("Revenue (USD)") frame.f.savefig("Plots/_budget_revenue_corr") frame.ax.cla() frame.ax.scatter(numerical_data.fb_likes, numerical_data.revenue) frame.ax.set_title("Cast Facebook Likes vs Revenue") frame.ax.set_xlabel("Cast Facebook Likes") frame.ax.set_ylabel("Revenue (USD)") frame.f.savefig("Plots/_cast_fb_likes_revenue_corr") frame.ax.cla() frame.ax.scatter(numerical_data.release, numerical_data.revenue) frame.ax.set_title("Release Year vs Revenue") frame.ax.set_xlabel("Release Year") frame.ax.set_ylabel("Revenue (USD)") frame.f.savefig("Plots/_release_year_revenue_corr") frame.ax.cla() frame.ax.scatter(numerical_data.runtime, numerical_data.revenue) frame.ax.set_title("Runtime vs Revenue") frame.ax.set_xlabel("Runtime (min)") frame.ax.set_ylabel("Revenue (USD)") frame.f.savefig("Plots/_runtime_revenue_corr") frame.ax.cla() # Save bar charts of mean revenue means = [] stdev = [] names = [] for key in genre_revenue_stat.keys(): if key == "Sci-Fi" or key == "Family" or key == "Adventure" or key == "Animation": means.append(genre_revenue_stat[key].mean) stdev.append(genre_revenue_stat[key].stdev) names.append(key) ind = np.arange(len(means)) frame.ax.set_ylabel('Revenue (USD)') frame.ax.set_title('Revenue by Genre') frame.ax.set_xticks([p + 0.2 for p in ind]) frame.ax.set_xticklabels(names) frame.ax.bar(ind, means, width = 0.5) frame.f.savefig("Plots/bar_genre_revenue") frame.ax.cla() # Send plot of top revenue earning genre probability distributions to GUI frame.ax.plot(x_grid, distributions['Animation'], label="Animation") frame.ax.plot(x_grid, distributions['Family'], label="Family") frame.ax.plot(x_grid, distributions['Adventure'], label="Adventure") frame.ax.plot(x_grid, distributions['Sci-Fi'], label="Sci-Fi") frame.ax.set_title("Probability Dist. for Top Revenue Earning Genres") frame.ax.set_xlabel('Revenue (USD)') frame.ax.set_ylabel('Probability') handles, labels = frame.ax.get_legend_handles_labels() frame.ax.legend(handles, labels)
true
6e51c67de8b6d43e05ba3f30950702f02f1de368
Python
huomanyan/old_build
/untitled1/train.py
UTF-8
1,431
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu May 16 15:51:16 2019 @author: lenovo """ import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import numpy as np from sklearn.utils import shuffle from lenet_slim import Lenet tf.reset_default_graph() mnist = read_data_sets("data/", one_hot=True) lenet = Lenet() with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) step = 4000 for i in range(step): raw_batch_xs, batch_ys = mnist.train.next_batch(100) #shape: (100,784) (100,10) # reshape batch_xs into [None, 32, 32, 1] batch_xs = raw_batch_xs.reshape(-1, 28, 28, 1) batch_xs = np.pad(batch_xs, ((0,0),(2,2),(2,2),(0,0)), 'constant') batch_xs, batch_ys = shuffle(batch_xs, batch_ys) _, loss, acur = sess.run([lenet.train_step, lenet.loss, lenet.accuracy], feed_dict={lenet.x:batch_xs, lenet.y_:batch_ys, lenet.keep_prob:0.5}) if i%100==0: print("Step", i, "Training [accuracy, loss]: [", acur, ",", loss, "]") raw_test_xs = mnist.test.images test_xs = raw_test_xs.reshape(-1, 28, 28, 1) test_xs = np.pad(test_xs, ((0,0),(2,2),(2,2),(0,0)), 'constant') print('Testing [accuracy, loss]:', sess.run([lenet.accuracy, lenet.loss], feed_dict={lenet.x:test_xs, lenet.y_:mnist.test.labels, lenet.keep_prob:1.0}))
true
146d4ab1ddaa0d9d414d9d6db91bbb6f65eaf987
Python
iamzhanghao/Security_Lab
/lab6/present.py
UTF-8
3,868
2.734375
3
[]
no_license
#!/usr/bin/env python3 # Present skeleton file for 50.020 Security # Oka, SUTD, 2014 #constants fullround=31 #S-Box Layer sbox=[0xC,0x5,0x6,0xB,0x9,0x0,0xA,0xD,0x3,0xE,0xF,0x8,0x4,0x7,0x1,0x2] #S-Box Layer inverse sbox_inv=[] for i in range(16): sbox_inv.append(0) counter = 0 for i in range(16): sbox_inv[sbox[i]] = counter counter += 1 #PLayer pmt=[0,16,32,48,1,17,33,49,2,18,34,50,3,19,35,51,\ 4,20,36,52,5,21,37,53,6,22,38,54,7,23,39,55,\ 8,24,40,56,9,25,41,57,10,26,42,58,11,27,43,59,\ 12,28,44,60,13,29,45,61,14,30,46,62,15,31,47,63] #PLayer inverse pmt_inv = [] for i in range(len(pmt)): pmt_inv.append(0) counter = 0 for i in range(len(pmt)): pmt_inv[pmt[i]] = counter counter += 1 # Rotate left: 0b1001 --> 0b0011 rol = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) # Rotate right: 0b1001 --> 0b1100 ror = lambda val, r_bits, max_bits: \ ((val & (2**max_bits-1)) >> r_bits%max_bits) | \ (val << (max_bits-(r_bits%max_bits)) & (2**max_bits-1)) def genRoundKeys(key): roundkeys = [] for round in range(1, fullround + 1): # (K1 ... K32) roundkeys.append(key >> 16) # 1.Shift keycopy = key key = 0 key += keycopy >>19 key += (keycopy & (2 ** 19 - 1)) << 61 # 2.Sbox keycopy = key key = 0 key += sbox[keycopy >> 76] << 76 key += keycopy & (2 ** 76 - 1) # 3. XOR key ^= round << 15 return roundkeys def addRoundKey(state,Ki): return state ^ Ki def sBoxLayer(state, mode): ans = 0x0 for i in range(16): if mode == 'e': ans += sbox[(state >> (i * 4)) & 0xF] << (i * 4) if mode == 'd': ans += sbox_inv[(state >> (i * 4)) & 0xF] << (i * 4) return ans def pLayer(state, mode): ans = 0x0 for i in range(64): if mode == 'e': ans += ((state >> i) & 0x01) << pmt[i] if mode == 'd': ans += ((state >> i) & 0x01) << pmt_inv[i] return ans def present_rounds(plain, key, rounds, mode): roundKeys = genRoundKeys(key) state = plain if mode == 'e': for i in range(rounds - 1): state = addRoundKey(state, roundKeys[i]) state = sBoxLayer(state,mode='e') state = pLayer(state,mode='e') return addRoundKey(state, roundKeys[rounds - 1]) if mode == 'd': for i in range(rounds - 1): state = addRoundKey(state, roundKeys[rounds-i-1]) state = pLayer(state,mode='d') state = sBoxLayer(state,mode='d') return addRoundKey(state, roundKeys[0]) def present(plain, key): return present_rounds(plain, key, fullround,'e') def present_inv(plain, key): return present_rounds(plain, key, fullround,'d') if __name__=="__main__": plain1 = 0x0000000000000000 key1 = 0x00000000000000000000 cipher1 = present(plain1,key1) plain11 = present_inv(cipher1,key1) # print(format(cipher1,'x')) # print(format(plain11,'x')) assert plain1 == plain11 plain2 = 0x0000000000000000 key2 = 0xFFFFFFFFFFFFFFFFFFFF cipher2 = present(plain2,key2) plain22 = present_inv(cipher2,key2) # print(format(cipher2,'x')) # print(format(plain22,'x')) assert plain2 == plain22 plain3 = 0xFFFFFFFFFFFFFFFF key3 = 0x00000000000000000000 cipher3 = present(plain3,key3) plain33 = present_inv(cipher3,key3) # print(format(cipher3,'x')) # print(format(plain33,'x')) assert plain3 == plain33 plain4 = 0xFFFFFFFFFFFFFFFF key4 = 0xFFFFFFFFFFFFFFFFFFFF cipher4 = present(plain4,key4) plain44 = present_inv(cipher4,key4) # print(format(cipher4,'x')) # print(format(plain44,'x')) assert plain4 == plain44
true
dc830daab6218a6f6224ecfac6283f6612f89ffb
Python
SharanyaMarathe/Advance-Python
/calci.py
UTF-8
288
3.65625
4
[]
no_license
def add(num1,num2): return num1+num2 def sub(num1,num2): return num1-num2 if __name__ == "__main__": alpha=10 beta=20 total=add(alpha,beta) print("sum: ",total) subtarct=sub(alpha,beta) print("Difference: ",subtarct)
true
75d6d6fa327a2087b47a98cbbffcb6a7e51cfd7a
Python
momendoufu/foldersorter
/FolderSorter_v2.py
UTF-8
2,498
2.890625
3
[]
no_license
import sys import os import shutil import pathlib from pathlib import Path import glob import re ############################################################# print(f'\ncwd: {os.path.dirname(__file__)}\n') PATH = sys.argv[1] if not os.path.exists(PATH): print(f'specified folder does not exist') sys.exit() os.chdir(PATH) print(f'Folder location: {os.getcwd()}') # 'tmp/**\\' , recursive=True dirname = [os.path.basename(p.rstrip(os.sep)) for p in glob.iglob('**' + os.sep)] print(f'list of directory name: {dirname}\n') path_and_dirname = [] for i in dirname: sublist =[] for j in range(2): sublist.append(i) path_and_dirname.append(sublist) folder_len = len(path_and_dirname) print(f'number of directories: {folder_len}\n') ############################################################# def moveFolder(folder, dst): os.makedirs(dst, exist_ok=True) if not Path(dst + '/' + folder).exists(): shutil.move(folder, dst) ############################################################# target = '(?<=\[).+?(?=\])' pattern = re.compile(target) moved = 0 delete = [] for i in range(folder_len): m = pattern.search(path_and_dirname[i][0]) if m: #include[] path_and_dirname[i][1] = m.group() else: #not include[] moveFolder(path_and_dirname[i][0], 'Unsorted/') delete.append(i) moved += 1 #end condition if folder_len - (i + moved) <= 1: break #正順(プラス方向)にリストの要素をdeleteするとインデックスが一つずつずれていってしまうので逆順にリストを参照させる([::-1]と同じ) for i in reversed(delete): del path_and_dirname[i] net_folder_num = len(path_and_dirname) print(f'path_and_dirname: {len(path_and_dirname)}\n') print(f'net_folder_num: {net_folder_num}\n') ############################################################# for i in range(net_folder_num): target = str(path_and_dirname[i][1]) originalFolder = True print(f'target: {target}') for j in range(i+1, net_folder_num): print(f'Folder name: {path_and_dirname[j][1]}\n') if target in path_and_dirname[j][0]: if originalFolder: moveFolder(str(path_and_dirname[i][0]), 'Sorted/' + str(path_and_dirname[i][1])) originalFolder = False moveFolder(str(path_and_dirname[j][0]), 'Sorted/' + str(path_and_dirname[j][1])) else: continue
true
7351bb01713806b1397577dbb7e9bd10e63ac893
Python
watir/nerodia
/nerodia/elements/button.py
UTF-8
704
2.890625
3
[ "MIT" ]
permissive
import six from .input import Input from ..meta_elements import MetaHTMLElement @six.add_metaclass(MetaHTMLElement) class Button(Input): """ Class representing button elements This class covers both <button> and <input type="submit|reset|image|button" /> elements """ VALID_TYPES = ['button', 'reset', 'submit', 'image'] @property def text(self): """ Returns the text of the button. For input elements, returns the 'value' attribute. For button elements, returns the inner text. :rtype: str """ if self.tag_name == 'input': return self.value else: return super(Button, self).text
true
c2cfd7f9ee4aa1a6ea3d6a80b5af13c2f7ecc4e2
Python
tmu-nlp/100knock2021
/pan/chapter06/X58.py
UTF-8
1,683
3.25
3
[]
no_license
#正則化パラメータの変更 import time import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression if __name__ == '__main__': start = time.time() X_train = pd.read_table('train.feature.txt', header = None) Y_train = pd.read_table('train.txt', header = None)[1] X_valid = pd.read_table('valid.feature.txt', header = None) Y_valid = pd.read_table('valid.txt', header = None)[1] X_test = pd.read_table('test.feature.txt', header = None) Y_test = pd.read_table('test.txt', header = None)[1] # 正則化パラメータを変えながらモデルを学習する C_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4] train_acc = [] valid_acc = [] test_acc = [] for c in C_candidate: clf = LogisticRegression(penalty = 'l2', solver = 'sag', random_state = 0, C = c) clf.fit(X_train, Y_train) train_acc.append(accuracy_score(Y_train, clf.predict(X_train))) valid_acc.append(accuracy_score(Y_valid, clf.predict(X_valid))) test_acc.append(accuracy_score(Y_test, clf.predict(X_test))) # 正解率を表示する print(train_acc) print(valid_acc) print(test_acc) # 処理時間 = 終了時刻 - 開始時刻 elapsed_time = time.time() - start print(f'{elapsed_time} [sec]') # 正解率をグラフとして表示する plt.plot(C_candidate, train_acc, label='train') plt.plot(C_candidate, valid_acc, label='valid') plt.plot(C_candidate, test_acc, label='test') plt.xscale('log') plt.xlabel('C') plt.ylabel('Accuracy') plt.legend() plt.show()
true
7246520b4773032de34d90e147332f78084880c1
Python
richard9219/predict_api_by_flask-tensorflow
/train.py
UTF-8
1,293
2.890625
3
[]
no_license
# -*- coding:utf-8 -*- # 导入panda,keras 和tensorflow import pandas as pd from tensorflow.keras.models import Sequential #顺序模型 from tensorflow.keras.layers import Dense #全链接层 # 加载样本数据集,划分为x和y DataFrame df = pd.read_csv("https://github.com/bgweber/Twitch/raw/master/Recommendations/games-expand.csv") df_data = df.drop(['label'], axis=1) df_labl = df['label'] train_data = df_data.loc[0:20000] train_targets = df_labl.loc[0:20000] test_data = df_data.loc[20001:] test_targets = df_labl.loc[20001:] # 训练次数 epochs = 200 # 搭建模型 model = Sequential() model.add(Dense(64, activation='relu', input_shape=(train_data.shape[1],))) model.add(Dense(64, activation='relu')) model.add(Dense(1)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) #优化器选择的是Adam,损失函数为MSE函数 # 训练模型 history = model.fit(train_data, train_targets, batch_size=32, #批次大小为32 epochs=epochs, #循环次数为 之前定义的200 validation_data=(test_data, test_targets), #验证集 shuffle=True) #打乱标签 # 以H5格式保存模型 model.save("model.h5")
true
6fbaf595b812927579de3154aa0deed6001ae126
Python
millerjl1980/student_spotlight_map_filter
/main.py
UTF-8
426
4.0625
4
[]
no_license
add_one = lambda num: num + 1 # print(add_one(5)) # add_together = lambda x, y: x + y # print(add_together("Hello", " World")) # odd_nums = [num for num in range(20) if num %2 != 0] # even_nums = [num for num in range(30) if num %2 == 0] # print(odd_nums) # print(even_nums) # sums = list(map(add_together, odd_nums, even_nums)) # print(sums) # three_factor = list(filter(lambda x: x%3 == 0, sums)) # print(three_factor)
true
6637ce8016d1ea774dd9faa378b3cd0863665f0d
Python
sxg133/code-to-html
/code_to_html.py
UTF-8
6,218
2.90625
3
[]
no_license
import re class CommentStyle: SCRIPT, C = range(2) class CodeConverter: """Convert code to HTML markup""" def keyword_class(): doc = "The CSS class of language keywords." def fget(self): return self._keyword_class def fset(self, value): self._keyword_class = value return locals() keyword_class = property(**keyword_class()) def string_class(): doc = "The CSS class of string and character literals." def fget(self): return self._string_class def fset(self, value): self._string_class = value return locals() string_class = property(**string_class()) def comment_class(): doc = "The CSS class for comments." def fget(self): return self._comment_class def fset(self, value): self._comment_class = value return locals() comment_class = property(**comment_class()) def line_number_class(): doc = "The CSS class for line numbers." def fget(self): return self._line_number_class def fset(self, value): self._line_number_class = value return locals() line_number_class = property(**line_number_class()) def spaces_for_tabs(): doc = "The number of spaces to use for tabs." def fget(self): return self._spaces_for_tabs def fset(self, value): self._spaces_for_tabs = value return locals() spaces_for_tabs = property(**spaces_for_tabs()) def show_line_numbers(): doc = "Show or hide line numbers." def fget(self): return self._show_line_numbers def fset(self, value): self._show_line_numbers = value return locals() show_line_numbers = property(**show_line_numbers()) def comment_style(): doc = "Set language comment style (c or script)" def fget(self): return self._comment_style def fset(self, value): self._comment_style = value return locals() comment_style = property(**comment_style()) def __init__(self, keyword_list, single_line_comment = "//", multi_line_comment="(/\*|\*/)"): self.re_word = re.compile(r'[a-zA-Z0-9_]+') self.re_keyword = re.compile('(' + '|'.join(keyword_list) + ')') self.keyword_class = 'keyword' self.string_class = 'string' self.comment_class = 'comment' self.spaces_for_tabs = 4 self.show_line_numbers = True self.line_number_class = 'line-number' self.comment_style = CommentStyle.C def __check_token(self, token): if token == ' ': return '&nbsp;' elif token == '\t': return '&nbsp;' * self.spaces_for_tabs elif token == '<': return '&lt;' elif token == '>': return '&gt;' return token def __check_word(self, word): if self.re_keyword.match(word): return '<span class="' + self.keyword_class + '">' + word + '</span>' return word def __is_start_comment(self, t, prev_t): return (prev_t == '/' and t in ['/', '*'] and self.comment_style == CommentStyle.C) or (t == '#' and self.comment_style == CommentStyle.SCRIPT) def __is_end_comment(self, t, prev_t): return t == '/' and prev_t == '*' and self.comment_style == CommentStyle.C def __is_single_line_comment(self, t): return (t == '/' and self.comment_style == CommentStyle.C) or (t == '#' and self.comment_style == CommentStyle.SCRIPT) def __is_comment_character(self, t): return (t in ['/', '*'] and self.comment_style == CommentStyle.C) or (t == '#' and self.comment_style == CommentStyle.SCRIPT) def __is_comment_symbol(self, prev_t, t): if t == '#' and self.comment_style == CommentStyle.SCRIPT: return True symbol = prev_t + t return symbol in ['/*', '*/', '//'] def __parse_codeline(self, line, in_comment): tokens = list(line) word = list() html = list() in_string = False string_starter = '' prev_t = '' single_line_comment = False if in_comment: html.append('<span class="' + self.comment_class + '">') for t in tokens: match = self.re_word.match(t) if match: word.append(t) else: if word: # end of a new word new_word = ''.join(word) if not (in_string or in_comment): new_word = self.__check_word(new_word) # is the word a keyword? html.append(new_word) word = list() if t in ['"', "'"] and not in_comment: if in_string: if string_starter != t: html.append(t) elif string_starter == t and prev_t == '\\': # escaped quote html.append(t) elif string_starter == t: # end of string html.append(t + '</span>') in_string = False else: # start of string html.append('<span class="' + self.string_class + '">' + t) string_starter = t in_string = True elif self.__is_comment_character(t): if self.__is_start_comment(t, prev_t): in_comment = True elif self.__is_end_comment(t, prev_t): in_comment = False html.append(t + '</span>') if in_comment: html.append('<span class="' + self.comment_class + '">' + prev_t + t) single_line_comment = self.__is_single_line_comment(t) # this handles a comment character that wasn't used for a comment (gets skipped on previous iteration) elif self.__is_comment_character(prev_t) and not in_comment and not self.__is_comment_symbol(prev_t, t): new_token = self.__check_token(prev_t) + self.__check_token(t) html.append(new_token) else: new_token = self.__check_token(t) html.append(new_token) prev_t = t # check word one last time because end of line token isn't picked up if word: html.append( self.__check_word( "".join(word) ) ) if in_comment: html.append('</span>') in_comment = not single_line_comment return in_comment, "".join(html) def convert_to_html(self, code): """Convert code to HTML markup and return as string.""" html = '<table class="code"><tbody>' in_comment = False for line_number,line in enumerate(code.split('\n')): html += '<tr>' if self.show_line_numbers: html += '<td class="' + self.line_number_class + '">' + str(line_number) + '</td>' html += '<td class="code">' in_comment, html_line = self.__parse_codeline(line, in_comment) html += html_line + '</td>' html += '</tr>' html += '</tbody></table>' return html
true
0def8a4e7c74aaad4c1bb8f14867e39b5f6e78f6
Python
AleKiller21/crud-rest-api
/services/GameService.py
UTF-8
2,718
2.578125
3
[]
no_license
from services.UtilService import check_fields_existance_in_payload import services.MessageService as MessageService from dao.GameDao import create_game, retrieve_game, get_games, update_game, delete_game def add_game(payload): try: if check_fields_existance_in_payload(payload, 'name', 'developer', 'publisher', 'price', 'description', 'image'): game = create_game(payload) if game: return MessageService.generate_success_message('', game.to_dictionary()) else: return MessageService.generate_custom_message('The game could not be created', 500) else: return MessageService.missing_fields_request except Exception as e: return MessageService.generate_internal_server_error(e) def get_game(name): try: game = retrieve_game(name) if game: return MessageService.generate_success_message('', game.to_dictionary()) else: return MessageService.generate_custom_message('The game was not found', {}) except Exception as e: return MessageService.generate_internal_server_error(e) def get_all_games(name): try: result = get_games(name) games = [] for game in result: games.append(game.to_dictionary()) if len(games): return MessageService.generate_success_message('', games) else: return MessageService.generate_custom_message('No games were found', []) except Exception as e: return MessageService.generate_internal_server_error(e) def modify_game(payload): try: if check_fields_existance_in_payload(payload, 'id', 'name', 'developer', 'publisher', 'description', 'price'): game = update_game(payload) if game: return MessageService.generate_success_message('', game.to_dictionary()) else: return MessageService.generate_custom_message('No game with that id was found', {}) else: return MessageService.missing_fields_request except Exception as e: MessageService.generate_internal_server_error(e) def remove_game(payload): try: if check_fields_existance_in_payload(payload, 'id'): game = delete_game(payload['id']) if game: return MessageService.generate_success_message('', game.to_dictionary()) else: return MessageService.generate_custom_message('The game could not be removed', {}) else: return MessageService.missing_fields_request except Exception as e: return MessageService.generate_internal_server_error(e)
true
29477801414fbb1cbc03b33cec7e6eecb2ce9e52
Python
brudolce/codewars
/4-kyu/Breadcrumb Generator.py
UTF-8
1,354
3.109375
3
[]
no_license
def generate_bc(url, separator): if '//' in url: url = url[url.index('//') + 2:] url = url.rstrip('/') try: for i, c in enumerate(url): if c in ['?', '#']: url = url[0:i] break menus = url.split('/')[1:] if menus and 'index.' == menus[-1][0:6]: menus = menus[:-1] if not menus: return '<span class="active">HOME</span>' breadcrumb = '<a href="/">HOME</a>' for i, e in enumerate(menus[:-1]): breadcrumb += separator + '<a href="/{}/">{}</a>'.format('/'.join(menus[:i + 1]), get_element_name(e)) breadcrumb += separator + '<span class="active">{}</span>'.format(get_element_name(menus[-1])) return breadcrumb except: return url ignore_words = ["the", "of", "in", "from", "by", "with", "and", "or", "for", "to", "at", "a"] def get_element_name(element): acronyms = element.split('-') for i, c in enumerate(acronyms[-1]): if c == '.': acronyms[-1] = acronyms[-1][:i] break if len(element) > 30: for i, c in reversed(list(enumerate(acronyms))): if c in ignore_words: acronyms.pop(i) return ''.join([s[0].upper() for s in acronyms]) return ' '.join([s.upper() for s in acronyms])
true
8ee0fd697d457e7d5c994acec752f00afe408251
Python
yoryos/dragonfly
/Visualiser/StdpVisualiser.py
UTF-8
3,014
2.546875
3
[]
no_license
from pyqtgraph.Qt import QtCore, QtGui from Visualiser.RasterVisualiser import RasterVisualiser from Visualiser.VisualiserComponent import VisualiserComponent class StdpVisualiser(VisualiserComponent): def __init__(self, afferent_data=None, output_data=None, default_history=50): VisualiserComponent.__init__(self) self.window = QtGui.QGroupBox() self.window.setContentsMargins(0, 0, 0, 0) self.layout = QtGui.QVBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.window.setLayout(self.layout) self.title = QtGui.QLabel("STDP") self.title.setAlignment(QtCore.Qt.AlignCenter) self.layout.addWidget(self.title) self.data_layout = QtGui.QHBoxLayout() self.data_layout.setContentsMargins(0, 0, 0, 0) self.layout.addLayout(self.data_layout) self.control_layout = QtGui.QHBoxLayout() self.layout.addLayout(self.control_layout) self.info = QtGui.QLabel("") self.widgets = [] if afferent_data is not None: self.widgets.append(RasterVisualiser(afferent_data, title="Afferents", parent=self)) if output_data is not None: self.widgets.append(RasterVisualiser(output_data, size=5, y_ticks=True, title="Output", parent=self)) self.reset_zoom_button = QtGui.QPushButton("Reset Zooms") self.reset_zoom_button.clicked.connect(self.reset_zoom) self.control_layout.addWidget(self.reset_zoom_button) self.history_length_input = QtGui.QSpinBox() self.history_length_input.setRange(0, self.steps) self.history_length_input.setValue(default_history) self.history_length_input.valueChanged.connect(self.reset_zoom) self.history_length_input_label = QtGui.QLabel("History Length") self.control_layout.addWidget(self.history_length_input_label) self.control_layout.addWidget(self.history_length_input) self.control_layout.addWidget(self.info) self.control_layout.addStretch() for w in self.widgets: self.data_layout.addWidget(w.window) def reset_zoom(self): i = self.history_length_input.value() for plot in self.widgets: plot.reset_zoom(i) return i @property def steps(self): if len(self.widgets) > 0: if not all(self.widgets[0].steps == w.steps for w in self.widgets): print "The two stdp plots have different number of steps" return min(self.widgets, key=lambda x: x.steps).steps return 0 def reset_to_start(self): for w in self.widgets: w.reset_to_start() def update(self): for plot in self.widgets: if not plot.update(): return False return True def save(self, name=None, dir=".", index=None, fmt=".png"): i = 0 for w in self.widgets: i += w.save(name=None, dir=".", index=None, fmt=".png") return i
true
258697bf9ceee23b81f042c7387fa0e979e53d2b
Python
lisaong/mldds-courseware
/05_Deploy/web/models.py
UTF-8
2,021
2.96875
3
[ "MIT" ]
permissive
import numpy as np import pandas as pd import pickle import os import boto3 class AutoMpg_Sklearn: def __init__(self, model_path): """Loads the model files""" self.X_scaler = pickle.load(open(os.path.join(model_path, 'X_scaler.pickle'), 'rb')) self.y_scaler = pickle.load(open(os.path.join(model_path, 'y_scaler.pickle'), 'rb')) self.model = pickle.load(open(os.path.join(model_path, 'model.pickle'), 'rb')) def preprocess(self, X): """Scales the raw input data""" return self.X_scaler.transform(X) def postprocess(self, yhat): """Unscales the raw predictions""" return self.y_scaler.inverse_transform(yhat) def predict(self, X): """Gets a prediction using the raw input data""" input_X_scaled = self.preprocess(X) yhat = self.model.predict(input_X_scaled) return self.postprocess(yhat) def get_model_files(): dest_path = os.getenv('MODEL_PATH', None) bucket_name = os.getenv('S3_BUCKET', None) if bucket_name is not None: s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) bucket.download_file('X_scaler.pickle', f'{dest_path}/X_scaler.pickle') bucket.download_file('y_scaler.pickle', f'{dest_path}/y_scaler.pickle') bucket.download_file('model.pickle', f'{dest_path}/model.pickle') else: dest_path = '..' # try a local relative path return dest_path if __name__ == '__main__': # for testing purposes m = AutoMpg_Sklearn('..') df = pd.read_csv('../auto-mpg.data-nans.txt', delim_whitespace=True, # the data uses whitespaces as separators instead of commas na_values=['?', 'NA'], # to handle '?' in the horsepower column names=['mpg', 'cylinders', 'displacement', 'horsepower', # data has no column names 'weight', 'acceleration', 'model_year', 'origin', 'car_name']) print(m.predict(df.loc[:, 'cylinders':'origin']))
true
c3050066c34c76a83137010998bce17790c4c9d1
Python
caiknife/test-python-project
/src/ProjectEuler/p014.py
UTF-8
878
3.875
4
[]
no_license
#!/usr/bin/python # coding: UTF-8 """ @author: CaiKnife Longest Collatz sequence Problem 14 The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. """ from euler import collatz_seq max_len = 0 number = 0 for x in range(1, 1000000): seq_len = len(collatz_seq(x)) if max_len < seq_len: number = x max_len = seq_len print number
true
1cdf72d694a5e85ea5e7c83daf412980c58f1b09
Python
yangwenbo99/CityHack-Team7-HongTakAgreement
/shitty_code/entity_name.py
UTF-8
2,306
2.578125
3
[]
no_license
import re import wf MAX_FREQUENT_WORDS = 300 MAX_TESTED_FREQUENT_WORDS = 100 MAX_FRONT_PAGES_NUMBER = 3 with open('./postal_address_words.txt', 'r') as f: _address_word_list = [r for r in f] with open('./word_frequencies.txt', 'r') as f: _word_requency_list = wf.read_word_frequence(f, MAX_FREQUENT_WORDS) def from_pages(pages): """ @param: pages in the document soup """ res = from_last_page(pages[-1]) if res is None: pass if res is not None: parent = res.parent bbox = parent['bbox'] position = tuple(bbox.split(',')) accendant = parent while accendant.name != 'page': accendant = accendant.parent page = int(accendant['id']) - 1 return { 'value': res.get_text(), 'page': page, 'position': position} def from_last_page(page): """ @param page: soup of the last page @return the <content> holding the name found or None if not found """ lmt_re = re.compile('Ltd|limited|corporation|' + \ 'corperated|corp|inc|incoperation', flags=re.IGNORECASE) res = page.find('content', string=lmt_re) if res is not None: return res contents = page.find_all('content') last = None for content in contents: if last is not None and is_address(content): res = last if res is not None: return res return res def is_address(s): """ determine whether s is an address """ for word in _address_word_list: if word in s: return True return False def from_front_pages(pages, page_limits=3): """ @param page: soups of the pages @return the <content> holding the name found or None if not found """ upper_bound = min(len(pages), page_limits) word_frequencies = wf.wf_in_soups(pages[:upper_bound]) word_frequencies_l = [(k, word_frequencies[k]) for k in word_frequencies] word_frequencies_l.sort(key=lambda x : - x[1]) upper_bound = min(len(word_frequencies_l), MAX_TESTED_FREQUENT_WORDS) selected_word_frequencies = word_frequencies_l[:upper_bound] special_words = [wf[0] for word in selected_word_frequencies \ if word not in _word_requency_list] pass
true
d7f882756ccae902bee289e75a2f025bf59e66af
Python
JorgeCCV/Taller2
/Primera_Letra_JorgeC.py
UTF-8
308
3.453125
3
[]
no_license
import turtle t=turtle.Pen() t.forward(100) t.left(90) t.forward(200) t.left(180) t.left(90) t.forward(80) t.left(90) t.forward(40) t.right(270) t.forward(200) t.right(270) t.forward(40) t.right(270) t.forward(80) t.left(270) t.forward(160) t.left(270) t.forward(60) t.right(270) t.forward(50)
true
6c12a15c41416bbde87641c54368a2978fec34cc
Python
matrixleon18/SHUFE
/basic/day1.py
UTF-8
769
4.1875
4
[]
no_license
# basic data type # int print(int(32)) # float print(float(32)) # string print(str(32)) # bool: True/False print(bool(32)) # nothing print() # bool print(32 == 0) # bool print(32 is 0) # bool print(32 and True) print(32 and False) print(0 and True) print(0 and False) # Tuple a = (1, 2, 3) # index start from 0 print(a.index(2)) # list a = [1, 2, 3, 4, 5] b = list([1, 2, 3, 4, 5]) print(a) print(b) # string b = 'a33bcde' print(b) # count how many char/str in the string print(b.count('3')) # find 1st char/str position in the string print(b.index('3')) # convert string to tuple c = tuple('a33bcde') print(c) # convert string to list print(list(b)) # dict f = dict({'k1': 1, 'k2': 2, 'k3': 3}) g = {'k1': 1, 'k2': 2, 'k3': 3} # they are same print(f) print(g)
true
ca65763e120d7b8d6e41a44dbb9bd395dc206c65
Python
Greyvar/client
/var/makeResourceSheet.py
UTF-8
1,307
2.65625
3
[]
no_license
#!/usr/bin/env python3 import sys from PIL import Image import argparse parser = argparse.ArgumentParser(); parser.add_argument("--paper_width", default = 2480) parser.add_argument("--paper_height", default = 3508) parser.add_argument("--tile_size", default = 256) parser.add_argument("--tileMargin", default = 40) parser.add_argument("--pageMargin", default = 50) parser.add_argument("--tiles", nargs = "*", default = []) parser.add_argument("--entities", nargs = "*", default = []) args = parser.parse_args(); list_images = [] for tileRef in args.tiles: list_images.append("../res/img/textures/tiles/" + tileRef + ".png") for entRef in args.entities: list_images.append("../res/img/textures/entities/" + entRef + ".png") new_image = Image.new("RGBA", (args.paper_width, args.paper_height), (255, 0, 0, 0)) x = args.pageMargin y = args.pageMargin for resource_filename in list_images: if x + args.tile_size + (args.pageMargin * 2) > args.paper_width: x = args.pageMargin y += args.tile_size + args.tileMargin open_image = Image.open(resource_filename) open_image = open_image.resize((args.tile_size, args.tile_size)) box = (x, y) print(box) new_image.paste(open_image, box) x += args.tile_size + args.tileMargin new_image.save("out.png")
true
4fecf2050fdfc27341cc2ee73e2d8597a88d87e1
Python
agatanyc/RC
/algorithms_DS/basic_ds/queue_2stacks.py
UTF-8
1,224
4.4375
4
[]
no_license
"""Implement a queue with 2 stacks. Your queue should have an enqueue and a dequeue function and it should be "first in first out" (FIFO).""" class Stack(): def __init__(self): self.items = [] def add(self, item): return self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def size(self): return len(self.items) def pick(self): return self.items[-1] class Queue(): def __init__(self): self.items = Stack() self.temp = Stack() def enqueue(self, item): self.items.add(item) def dequeue(self): if self.temp.is_empty(): for i in range(self.items.size()): self.temp.add(self.items.pop()) return self.temp.pop() else: return self.temp.pop() if __name__ == '__main__': s = Stack() s.add(5) s.add(6) s.pop() assert s.pick() == 5 assert not s.is_empty() assert s.size() == 1 q = Queue() q.enqueue(3) q.enqueue(4) q.enqueue(5) print q.dequeue() q.enqueue(6) print q.dequeue() print q.dequeue() print q.dequeue()
true
46ca5f6b14ac52c628d120c5e6a2b2f7ea9eac73
Python
Kitware/vtk-examples
/src/Python/Tutorial/Tutorial_Step5.py
UTF-8
4,891
2.984375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python """ ========================================================================= Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ """ # First access the VTK module (and any other needed modules) by importing them. # noinspection PyUnresolvedReferences import vtkmodules.vtkRenderingOpenGL2 from vtkmodules.vtkCommonColor import vtkNamedColors from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera from vtkmodules.vtkRenderingCore import ( vtkActor, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer ) def main(argv): colors = vtkNamedColors() # # Next we create an instance of vtkConeSource and set some of its # properties. The instance of vtkConeSource 'cone' is part of a # visualization pipeline (it is a source process object) it produces data # (output type is vtkPolyData) which other filters may process. # cone = vtkConeSource() cone.SetHeight(3.0) cone.SetRadius(1.0) cone.SetResolution(10) # # In this example we terminate the pipeline with a mapper process object. # (Intermediate filters such as vtkShrinkPolyData could be inserted in # between the source and the mapper.) We create an instance of # vtkPolyDataMapper to map the polygonal data into graphics primitives. We # connect the output of the cone source to the input of this mapper. # coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) # # Create an actor to represent the cone. The actor orchestrates rendering # of the mapper's graphics primitives. An actor also refers to properties # via a vtkProperty instance, and includes an internal transformation # matrix. We set this actor's mapper to be coneMapper which we created # above. # coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(colors.GetColor3d('Bisque')) # # Create the Renderer and assign actors to it. A renderer is like a # viewport. It is part or all of a window on the screen and it is # responsible for drawing the actors it has. We also set the background # color here. # ren1 = vtkRenderer() ren1.AddActor(coneActor) ren1.SetBackground(colors.GetColor3d('MidnightBlue')) # # Finally we create the render window which will show up on the screen. # We put our renderer into the render window using AddRenderer. We also # set the size to be 300 pixels by 300. # renWin = vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(300, 300) renWin.SetWindowName('Tutorial_Step5') # # The vtkRenderWindowInteractor class watches for events (e.g., keypress, # mouse) in the vtkRenderWindow. These events are translated into # event invocations that VTK understands (see VTK/Common/vtkCommand.h # for all events that VTK processes). Then observers of these VTK # events can process them as appropriate. iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # # By default the vtkRenderWindowInteractor instantiates an instance # of vtkInteractorStyle. vtkInteractorStyle translates a set of events # it observes into operations on the camera, actors, and/or properties # in the vtkRenderWindow associated with the vtkRenderWinodwInteractor. # Here we specify a particular interactor style. style = vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) # # Unlike the previous scripts where we performed some operations and then # exited, here we leave an event loop running. The user can use the mouse # and keyboard to perform the operations on the scene according to the # current interaction style. When the user presses the 'e' key, by default # an ExitEvent is invoked by the vtkRenderWindowInteractor which is caught # and drops out of the event loop (triggered by the Start() method that # follows. # iren.Initialize() iren.Start() # # Final note: recall that observers can watch for particular events and # take appropriate action. Pressing 'u' in the render window causes the # vtkRenderWindowInteractor to invoke a UserEvent. This can be caught to # popup a GUI, etc. See the Tcl Cone5.tcl example for an idea of how this # works. if __name__ == '__main__': import sys main(sys.argv)
true
0f7f074783c90de68dc1f57b2e9a9d6423e9c922
Python
Silver-L/keras_projects
/vae/ResVAE.ver3/predict_spe.py
UTF-8
3,117
2.78125
3
[ "MIT" ]
permissive
""" * @predict specificity * @Author: Zhihui Lu * @Date: 2018/09/03 """ import os import time import numpy as np import argparse import SimpleITK as sitk import csv from keras import backend as K from keras.models import load_model import dataIO as io # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" def predict_spe(): parser = argparse.ArgumentParser(description='py, test_data_list, name_list, outdir') parser.add_argument('--model', '-i1', default='', help='model') parser.add_argument('--truth_data_txt', '-i2', default='', help='name list') parser.add_argument('--outdir', '-i3', default='', help='outdir') args = parser.parse_args() if not (os.path.exists(args.outdir)): os.mkdir(args.outdir) latent_dim = 32 n_gen = 1 # load ground truth ground_truth = io.load_matrix_data(args.truth_data_txt, 'int32') print(ground_truth.shape) # aset network decoder = load_model(args.model) specificity = [] for i in range(n_gen): # # generate shape # sample_z = np.full(latent_dim, 0) # sample_z = np.array([sample_z]) sample_z = np.random.normal(0, 1.0, (1, latent_dim)) # print(sample_z.shape) preds = decoder.predict(sample_z) preds = preds[:, :, :, :, 0] # # EUDT eudt_image = sitk.GetImageFromArray(preds[0]) eudt_image.SetSpacing([1, 1, 1]) eudt_image.SetOrigin([0, 0, 0]) # label label = np.where(preds[0] > 0, 0, 1) label_image = sitk.GetImageFromArray(label) label_image.SetSpacing([1, 1, 1]) label_image.SetOrigin([0, 0, 0]) # calculate ji case_max_ji = 0. for image_index in range(ground_truth.shape[0]): ji = jaccard(label, ground_truth[image_index]) if ji > case_max_ji: case_max_ji = ji specificity.append([case_max_ji]) # output image io.write_mhd_and_raw(eudt_image, '{}.mhd'.format(os.path.join(args.outdir, 'EUDT', str(i+1)))) io.write_mhd_and_raw(label_image, '{}.mhd'.format(os.path.join(args.outdir, 'label', str(i+1)))) # output csv file # with open(os.path.join(args.outdir, 'specificity.csv'), 'w', newline='') as file: # writer = csv.writer(file) # writer.writerows(specificity) # writer.writerow(['specificity:', np.mean(specificity)]) print('specificity = %f' % np.mean(specificity)) def zero_loss(y_true, y_pred): return K.zeros_like(y_pred) def jaccard(im1, im2): im1 = np.asarray(im1).astype(np.bool) im2 = np.asarray(im2).astype(np.bool) if im1.shape != im2.shape: raise ValueError("Shape mismatch: im1 and im2 must have the same shape.") intersection = np.logical_and(im1, im2) union = np.logical_or(im1, im2) if float(intersection.sum()) == 0.: return 0. else: return intersection.sum() / float(union.sum()) if __name__ == '__main__': start = time.time() predict_spe() process_time = time.time() - start print(process_time)
true
7b5a77a3425bfd1036be983def717bbd44a3d3bb
Python
Kiran8206/TakeAway-Data-Aggregation
/TakeAway.py
UTF-8
1,468
2.859375
3
[]
no_license
# Databricks notebook source from pyspark.sql import SparkSession import pyspark.sql.functions as F from pyspark.sql.types import DoubleType # Creation of Spark Session object and initial Dataframe spark = SparkSession.builder.getOrCreate() df = spark.read.format("Json").option("inferSchema", "true").load("/FileStore/tables/TakeAway/data.json") #Transformations to explode and flatten the nested structs df1 = df.withColumn("orders", F.explode("orders")).select("customerId", F.col("orders.orderId").alias("orderId"), F.col("orders.basket").alias("basket")).drop("orders") df2 = df1.withColumn("basket", F.explode("basket").alias("basket")).select("customerId", "orderId", F.col("basket.productId").alias("productId"), F.col("basket.productType").alias("productType"), F.col("basket.grossMerchandiseValueEur").alias("grossMerchandiseValueEur")) #UDF to calculate the Net Merchandise values of an order def netMerchCal(x, y): if x == "beverage": return y+0.09*y elif x == "hot food": return y+0.15*y else: return y+0.07*y #Regester the UDF netMerch_udf = F.udf(lambda a, b : netMerchCal(a, b), DoubleType()) #Adding a new column to store the Net Merchandise value of a product df3 = df2.withColumn("netMerch", netMerch_udf("productType", "grossMerchandiseValueEur")) #Aggregating the Net merchandise values of all products for an orderID df3.groupBy("orderId").agg(F.sum("netMerch")).repartition(1).write.parquet("/output/result.parquet")
true
0e6d5d0bb7562a02e24a229b260cb399d2972a5f
Python
asdfasadfasfa/Some_Scripts
/service/ldap_unauth.py
UTF-8
961
2.5625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import ldap3 import re def get_plugin_info(): plugin_info = { "name": "ldap 未授权", "desc": "导致数据库敏感信息泄露,严重可导致服务器被入侵。", "grade": "高", "type": "service", "keyword": "service:ldap port:389", } return plugin_info def poc(arg): check_port = lambda x:x if re.match(r"(.*?):(\d+)$",x) else x+':389' host,port = check_port(arg).split(':') timeout = 5 try: server = ldap3.Server(host, get_info=ldap3.ALL, connect_timeout=timeout) conn = ldap3.Connection(server, auto_bind=True) if len(server.info.naming_contexts) > 0: return True except Exception: return if __name__ == '__main__': import sys if len(sys.argv) != 2: print("{} IP[:port]".format(sys.argv[0])) else: print("{} {}".format(sys.argv[1],poc(sys.argv[1])))
true
20402cca9bf3590c52a35755453d2fa0ae3e16b0
Python
jmnosal/GA-DSI-projects
/project-02/Project2_Classes.py
UTF-8
4,731
3.515625
4
[]
no_license
class OSM: #Creates a new Online Store Machine that creates new stores of a given inventory type def __init__(self, name, *args): self.number_of_stores = 0 self.list_of_stores = [] self.type_of_inv = list(args) self.name = name def createOnlineStore(self, store): # create new instance of Class OnlineStore self.list_of_stores.append(store) self.number_of_stores += 1 return OnlineStore(store, [x for x in self.type_of_inv]) #The function passes the store name and the inventory types # to the OnlineStore instance class OnlineStore: #Online stores that receive and sell inventory of a type inherited from the OSM def __init__(self, name, *args): self.name = name self.type_of_inv = list(args)[0] self.inventory = {k:0 for k in self.type_of_inv} self.inventorySold = {k:0 for k in self.type_of_inv} self.customerList = [] def addInventory(self, type_of_inventory, amount): # add inventory to 'inventory' if type_of_inventory not in self.inventory: print 'This type of inventory not sold here.' #Check to ensure the type of inventory is sold at the store else: self.inventory[type_of_inventory] += amount return self.inventory def sellInventory(self, type_of_inventory, amount): #remove inventory from 'inventory' and assign to customer purchase history if type_of_inventory not in self.inventory: print 'This type of inventory not sold here.' #Check to ensure the type of inventory is sold at the store else: self.inventory[type_of_inventory] -= amount self.inventorySold[type_of_inventory] += amount return self.inventory def summaryInventory(self): # summarize current inventory levels print '{0} has a current inventory of: {1}'.format(self.name, self.inventory) return self.inventory def addCustomer(self, name): # creates a new instance of class Customer and assigns it to the OnlineStore customerList self.customerList.append(name) return Customer(name, self.name, [x for x in self.type_of_inv]) def summarizePurchaseHistory(self): # totals all purchases minus returns for all customers print '{0} has sold the following items: {1}'.format(self.name, self.inventorySold) return self.inventorySold def storeProfile(self): #summary of a store's inventory type, number of customers and who they are print '{0} is a store that sells {1}. It currently has {2} customers, who are: {3}'.format\ (self.name, self.type_of_inv, len(self.customerList), self.customerList) class Customer: #Customers have unique names and can purchase items from the stores that create them def __init__(self, name, inst, *args): self.purchaseHistory = {} self.name = name self.type_of_inv = list(args)[0] self.inst = inst def purchaseItem(self, item, quantity, store): #Purchase items from the OnlineStore if item not in self.type_of_inv: print 'That type of product not sold in this store.' #Checks if the item requested is sold at the store else: if store.inventory[item] - quantity < 0: print "{0} does not have enough {1} to place the order.".format(self.inst, item) #Checks that the item is in stock elif item not in self.purchaseHistory.keys(): self.purchaseHistory[item] = quantity store.sellInventory(item, quantity) #Adds a new Key/value pair to the customer's purchase dictionary if it is a new item else: self.purchaseHistory[item] = self.purchaseHistory[item] + quantity store.sellInventory(item, quantity) #Adds the quantity return {item:quantity} #assigns an item to the customer purchaseHistory and subtracts it from the store inventory def customerProfile(self): print 'This is {0}, who is a customer of {1} and has purchased the following items: {2}'.format(self.name, self.inst, self.purchaseHistory) Books = OSM('Books', 'books', 'cds', 'newspaper') Borders = Books.createOnlineStore('Borders') print Borders.inventory Borders.addInventory('cds', 100) Borders.addInventory('books', 200) Borders.addInventory('fish', 50) print Borders.inventory print Borders.inventorySold Borders.storeProfile() Bob = Borders.addCustomer('Bob') Borders.storeProfile() Bob.customerProfile() Bob.purchaseItem('cds', 50, Borders) Borders.summarizePurchaseHistory() Bob.customerProfile() Bob.purchaseItem('newspaper', 2, Borders)
true
2bc04973dbd1af6c4821e8e6d50cfd0f97cb8932
Python
paaja90/pyladies
/lekce 06/rodnecislo_2.py
UTF-8
2,149
3.78125
4
[]
no_license
def spravny_format(cislo): while True: if cislo.isalpha(): #tady se mě ty try/except bloky nezdály, když bych tím ověřovala zda zadal integer, tak to neuzná '/' a s tím .isalpha si to nerozumnělo print('Rodné číslo neobsahuje pismena') cislo = input('Zadej rodné číslo znovu:') elif len(cislo) == 11: rozdelene_cislo = cislo.split('/') while True: # a tady jsem je teda zkusila použít, ale nefunguje to, protože když zadám nesprávný formát tak vrátí True :D takhle se ten try/except nepoužívá, což? len(rozdelene_cislo[0]) == 6 and len(rozdelene_cislo[1]) == 4 and cislo[6] == '/' try: return True except: print('Špatně zadané rodné číslo') return False else: print('Špatně zadané rodné číslo') cislo = input('Zadej rodné číslo znovu:') def delitelnost(cislo): rozdelene_cislo = cislo.split('/') bez_lomitka = rozdelene_cislo[0] + rozdelene_cislo[1] licha_mista = bez_lomitka[::2] suda_mista = bez_lomitka[1::2] soucet_licha = 0 for i in licha_mista: soucet_licha = soucet_licha + int(i) soucet_suda = 0 for i in suda_mista: soucet_suda = soucet_suda + int(i) if soucet_licha - soucet_suda %11: #rozdil cisel na liche a sude pozici je dělitelny 11, takže RD je dělitelné 11ti. return True else: return False def datum_narozeni(cislo): rok = '' if int(cislo[:2]) < 21 and int(cislo[:2]) >= 0: rok = 2000 + int(cislo[:2]) else: int(cislo[:2]) > 21 and int(cislo[:2]) < 99 rok = 1900 + int(cislo[:2]) mesic = '' if int(cislo[2:3]) > 12: mesic = int(cislo[2:3]) - 50 else: mesic = int(cislo[2:3]) den = cislo[4:6] print('Datum narození je:',den + '.'+ str(mesic) + '.' + str(rok)) def pohlavi(cislo): if int(cislo[2:3]) > 12: print('žena') else: print('muž') print(spravny_format(input('Zadej rodne cislo:')))
true
513ba0024a28d9872f63d86023a3c7b15228c067
Python
coomdan/codebase
/python/key-renamer/key-renamer.py
UTF-8
885
2.875
3
[]
no_license
# import glob, os.path, shutil key_path = "key-files/" input_dir = key_path + "unverified" archive_dir = key_path + "archive" pattern = "test-keyfile*.keys" def find_files(pattern): files = glob.glob(input_dir + '/' + pattern) return files def verify_keyfiles(files): verified_files = [] for file in files: if os.path.isfile(file): verified_files.append(file) if not verified_files: print("No valid files found!") return verified_files def rename_files(files, archive, src, dst, destination): print(files) for file in files: shutil.copyfile(file, archive + "/" + file.rsplit('/',1)[1]) shutil.move(file, input_dir + "/" + file.rsplit('/',1)[1].replace(src, dst)) files = find_files(pattern) verified_files = verify_keyfiles(files) rename_files(verified_files, archive_dir, "test", "live", input_dir)
true
c91c3d8b0b69ec6ed9cf8b8c8f8fac64cbd25da2
Python
AnthonyZero/python-accumulation
/custom_scrapy.py
UTF-8
3,169
2.9375
3
[]
no_license
#!/usr/bin/env python # encoding: utf-8 ''' @author: AnthonyZero @file: custom_scrapy.py @time: 2018/11/20 10:46 @desc: 自定义简单scrapy框架 ''' import types from twisted.internet import defer #特殊的socket对象(不会发请求 手动移除) from twisted.web.client import getPage #socket对象 from twisted.internet import reactor #事件循环 import queue class Request(object): def __init__(self, url, callback): self.url = url self.callback = callback class Response(object): def __init__(self, body, request): self.body = body self.request = request self.url = request.url @property def text(self): return self.body.decode('utf-8') # 自己的业务爬虫 class BaiduSpider(object): name = "baidu" start_url = ["http://www.baidu.com", "http://news.baidu.com/"] def start_request(self): for url in self.start_url: yield Request(url, self.parse) def parse(self, response): print(response, response.url) # yield Request("http://www.baidu.com", self.parse) # 请求队列 queue = queue.Queue() class Engine(object): def __init__(self): self._close = None self._max_currentcy = 5 self._crawling = [] # 正在进行调度的请求 def get_reponse_callback(self, content, request): self._crawling.remove(request) response = Response(content, request) result = request.callback(response) if isinstance(result, types.GeneratorType): for req in result: queue.put(req) # yield的请求又继续放入队列 def next_request(self): if queue.qsize() == 0 and len(self._crawling) == 0: # 所有调度都完成 self._close.callback(None) return if len(self._crawling) >= self._max_currentcy: return while len(self._crawling) < self._max_currentcy: try: request = queue.get(block = False) self._crawling.append(request) d_defer = getPage(request.url.encode('utf-8')) # 页面下载完成 get_reponse_callback 调用用户spider中自定义的parse方法 并且将新请求加入到调度器 d_defer.addCallback(self.get_reponse_callback, request) d_defer.addCallback(lambda _:reactor.callLater(0, self.next_request)) except Exception as e: return @defer.inlineCallbacks def crawl(self, spider): # 开始调度爬虫 # Download start_quest = iter(spider.start_request()) while True: try: queue.put(next(start_quest)) # 往队列中放入request对象 except StopIteration as ex: break # 去调度器取request 发起请求 reactor.callLater(0, self.next_request) self._close = defer.Deferred() yield self._close _active = set() engine = Engine() spider = BaiduSpider() d = engine.crawl(spider) _active.add(d) defer_list = defer.DeferredList(_active) defer_list.addBoth(lambda a: reactor.stop()) reactor.run()
true
2955dc07b1947c84836956342061647950104c50
Python
tokuD/atcoder
/Practice/031.py
UTF-8
1,383
2.609375
3
[]
no_license
# from __future__ import annotations from typing import List,Union import sys input = sys.stdin.readline from collections import deque # from itertools import permutations,combinations # from bisect import bisect_left,bisect_right # import heapq # sys.setrecursionlimit(10**5) def main(): X,Y = map(int, input().split()) G = [] G.append([0]*(X+2)) for _ in range(Y): r = [0] + list(map(int, input().split())) + [0] G.append(r) G.append([0]*(X+2)) dxdy1 = [(-1,0),(0,-1),(1,-1),(1,0),(1,1),(0,1)] dxdy0 = [(-1,0),(-1,-1),(0,-1),(1,0),(0,1),(-1,1)] visited = [[False]*(X+2) for _ in range(Y+2)] ans = 0 Q = deque() #* Q[y,x] Q.appendleft((0,0)) while len(Q) > 0: y,x = Q.popleft() if visited[y][x]: continue visited[y][x] = True if y % 2 == 1: for dx,dy in dxdy1: if not (0<=x+dx<X+2 and 0<=y+dy<Y+2): continue if G[y+dy][x+dx] == 1: ans += 1 continue Q.append((y+dy,x+dx)) else: for dx,dy in dxdy0: if not (0<=x+dx<X+2 and 0<=y+dy<Y+2): continue if G[y+dy][x+dx] == 1: ans += 1 continue Q.append((y+dy,x+dx)) print(ans) if __name__ == '__main__': main()
true
02721c9e4a39f1efddfc2df38384dc249760f268
Python
hwinter/practicecodes
/dih_create_goes_times.py
UTF-8
1,049
2.859375
3
[]
no_license
from datetime import datetime from datetime import timedelta # # #Needs Docs! # #Name: dih_create_goes_times # #Purpose: takes times created by IDL goes finder and puts them in '%d-%m-%Y %H:%M:%S.%f' format # #Inputs: list of GOES times # #Outputs: list of AIA suitable times # #Examples gah = dih_create_goes_times(['01-May-2012 00:00:00.00']) # #Written: 8/1/14 Dan Herman daniel.herman@cfa.harvard.edu # # # def dih_create_goes_times(time_list): month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] new_time_list = [] time_diff_list = [] for member in time_list: index_list = [i for i, j in enumerate(month_list) if j == member[3:6]] new_member = member[0:3] + str(index_list[0]+1) + '-20' + member[7:22] new_time_list.append(new_member) #for member in new_time_list: #first_time = datetime.strptime(new_time_list[0],'%d-%m-%Y %H:%M:%S.%f') #now_time = datetime.strptime(member,'%d-%m-%Y %H:%M:%S.%f') #diff = now_time-first_time #diff_num = diff.total_seconds() #time_diff_list.append(diff_num) return new_time_list
true
70b81494d57119f2f3e07e4b2ab23b1400c050ad
Python
creek0810/sic-macro-processor
/macroProcessor/macroProcessor.py
UTF-8
4,147
2.796875
3
[]
no_license
class MacroProcessor: def __init__(self, file_path): self.def_table = {} self.path = file_path def _is_comment(self, cur_line): return cur_line.startswith(".") def _is_macro_def(self, cur_line): split_data = cur_line.split() return len(split_data) >= 2 and split_data[1] == "MACRO" # return name of current macro call def _parse_name(self, cur_line): split_data = cur_line.split() return ( split_data[0] if split_data[0] in self.def_table else split_data[1] ) def _is_macro_call(self, cur_line): split_data = cur_line.split() # general macro call if len(split_data) >= 2: return ( split_data[0] in self.def_table or split_data[1] in self.def_table ) # no label no arg macro call elif len(split_data) >= 1: return split_data[0] in self.def_table return False def _parse_arg(self, cur_line): if self._is_macro_def(cur_line): return cur_line.replace(",", " ").split()[2:] macro_name = self._parse_name(cur_line) split_data = cur_line.strip().replace(",", " ").split() start = split_data.index(macro_name) + 1 return split_data[start:] def _expand_macro(self, lines, i): cur_line = lines[i] # print comment comment = cur_line.lstrip() print(f".{comment}") # if cur_line has label label = cur_line.split()[0] if label not in self.def_table: print(label, end=" ") # start expand cur_arg = self._parse_arg(cur_line) macro_name = self._parse_name(cur_line) cur_macro = self.def_table[macro_name] i = 0 while i < len(cur_macro["body"]): cur_line = cur_macro["body"][i] # define the macro which is defined in macro if self._is_macro_def(cur_line): i = self._define_macro(cur_macro["body"], i) # general instruction else: # replace arg for idx, arg in enumerate(cur_macro["arg"]): cur_line = cur_line.replace(arg, cur_arg[idx]) print(cur_line) i += 1 def _define_macro(self, lines, i): macro_body = [] macro_name = lines[i].split()[0] macro_arg = self._parse_arg(lines[i]) level = 1 # i = a var to iterate lines # skip first line i += 1 # construct macro body while level > 0: cur_line = lines[i] i += 1 # skip comment if self._is_comment(cur_line): continue split_data = cur_line.split() macro_body.append(cur_line) if self._is_macro_def(cur_line): level += 1 elif len(split_data) >= 1 and split_data[0] == "MEND": level -= 1 # update def table self.def_table[macro_name] = { "arg": macro_arg, # delete last MEND instruction "body": macro_body[:-1], } # return cur line num return i def process(self): with open(self.path, "r") as file: raw_data = file.readlines() lines = [x.replace("\n", "") for x in raw_data] i = 0 while i < len(lines): cur_line = lines[i] # skip comment if self._is_comment(cur_line): i += 1 # define macro elif self._is_macro_def(cur_line): i = self._define_macro(lines, i) # expand macro elif self._is_macro_call(cur_line): self._expand_macro(lines, i) i += 1 # general instruction else: print(lines[i]) i += 1
true
fbf864e62058623e24e7933aa18f5205eca92601
Python
Jungerson/Manual
/scripts/insert_items.py
UTF-8
867
2.609375
3
[]
no_license
#!/usr/bin/env python import sys import csv import json import boto3 if len(sys.argv) != 3: print("Usage: python3 insert_items.py <csv file> <deploy stage>") sys.exit(-1) client = boto3.client('dynamodb', region_name='us-east-1') csv_file = sys.argv[1] stage = sys.argv[2] with open(csv_file) as f: reader = csv.reader(f, delimiter=",") line = 0 data = {} for row in reader: line = line + 1 if line == 1: data_type = row elif line == 2: header = row else: c = 0 for col in row: if data_type[c] == 'BOOL': if col == "1": col = True else: col = False data[header[c]] = { data_type[c]: col } c = c + 1 print(data) response = client.put_item( TableName = 'VisionAware-' + stage, Item = data )
true
a4f30db37646e31ef265212ad47dda4476957214
Python
konchunas/pyrs
/examples/monkeytype/main.py
UTF-8
278
3.765625
4
[ "MIT" ]
permissive
# please refer to __init__.py file for an explanation def has_even(numbers): for num in numbers: if num % 2 == 0: return True return False def main(): vec = [1,9,2,5,4] even_exists = has_even(vec) print("Has even number", even_exists)
true
9206d9a745da78a0ce01b50908c23c08f1e2eac7
Python
DanishKhan14/DumbCoder
/Python/Expression/Tree/minDepth.py
UTF-8
1,006
3.515625
4
[]
no_license
#!/usr/bin/python def minDepth(self, root): # Recursive """ :param self: :param root: :return: """ if root is None: return 0 if root.left is None and root.right is None: return 1 if root.left is None: return 1 + self.minDepth(root.right) if root.right is None: return 1 + self.minDepth(root.left) return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 def minDepth(self, root): #Iterative """ Use Level Order Traversal or BFS :param self: :param root: :return: """ depth, level = 0, [root] while level and level[0]: depth += 1 temp = [] for n in level: if not n.left and not n.right: return depth temp.extend([kid for kid in (n.left, n.right) if kid]) level = temp return depth
true
22b521ca6644618be9ba10b9b5cb5fb7c653ab78
Python
ammeyer/genetics-curriculum
/rosalind.py
UTF-8
11,665
2.796875
3
[]
no_license
import math import itertools import re def count_nucleotides(s): """Description here""" return s.count('A') + ' ' + s.count('C') + ' ' + s.count('G') + ' ' + s.count('T') #sequence = "CCTGAGAACGCTACAGCGGCGAGCGACGTACAGGCAAGGAGGCTACTGAGTACATTTATGTTGATTCTATACAATGGTCGTCACAATAATAGGACACCCCCATAAAGTGGCAAGTTAGTTAGGTGGGGGTTAATTAGCCCCGGTGAGGCCCCGCCACGAGCCTTAATCCATAGGTACTTAAGGCCGTACACGAGAGATAGCGCTCTCCATTACAGCTCTTCTACAACGCACCTAAAGCCGGAAAAGGCGAGCACATTTGCTAGGCGGGCCGAAGTCTCTCCCGGCAGTCAGTTATAAAAATCATTCAATCTAGCAAACGCTGAATTTGCCAAACCCGTCTTTAAAGCTAATTGTTCGGCTTCAGCTATCGACATCCGCACGGGTCGGAAAATAGATTGTCGGAAGTGTGCGAACGGTGACCCTATGGCCACCCCTTAGATACGTATACGCTGGCCTATAAGCTAGGAGAGCAGGTGTAAAGGTCCACTCGGATGCTTTGAGACCCACTTCCTGACGTGGCCAAGATGAAGGGCACAATTCGCTGCCAAGTTCCAATGTCATCCGATGTGGTAGGCGCACTCCGGCCGTATCCCTGTGTTGTAGGCAACTATAACTAGATGGGAGTCCCGTTTACCTCATTTCCAGGATTGCACTCTCAGCTCTCCATGGAGCACTTTTTCTCTTTCGTCAACGGAAAAGCGACTCCCGGGGCCAGTGGCAGAATTTTGGTCAGTGATTACGCCTAGGTAATGGTGGGGTGGCGAGCTTCATCTTTTCGCAGCCTGGTCGCGGAGTGAGAAACGGTTGGCGAAGTTTCAGGGAGGCCACGCAGATAATCGTCCCCGGGGAATTCTGCGCACATGCCCTTTGGACAGCATCGGATTGGACTAGGTTTGCAAAATGAGAAGCGCCACTAG" #print(count_nucleotides(sequence)) def transcribe(dnastring): """Description here""" rnastring = "" for c in dnastring: if c == "T": rnastring += "U" else: rnastring += c return rnastring #sequence = "ATTTGAGCTCGTAACCGCAATCATAACACCCAAATGTGATAACGAACGTAAACCGTGGTGAACCCCCGGGCGTCAGTATTCGTCCCACATGCGCGGTAGTCTCTAAAATTCTTAAAATAGGTGAGTCCCTTGGACCCTTCGCTTATCTACCGCTCAGGACCCTGGTCTATGAGTCGACCATCTGGCTTGGTTCGGCTCGAACTAAGACCACGGGCAGTCGCTCATCCTGGGGACCAAGATCCAGGATTCGTAGGACTGACATTACACGAGTGATCTGCCTTAACGTATTGTACGGTGTGGAGTCGCGACAAACAGCATTGAAAAGTCGCGTGCCGCTCCTGGGTAAGGTCAACACTCCCGTAGACGAACCTGCGTCTCGAAGTACGGGTCACCATAACAACTCGGGGTTGCCCAGCTTTTGGCGCGTTCTAGTTAGCTCACGGGGCTTTTTCTCGGTGAACGGAGCAGGAAGATCGCGAGTGCATATCGGTAGAAAGTCAATGCCGTGAGACGGCAGGAGAGATGTGAGGGTGCGCTAACTCGACACCATCGTATGGGAGTAAATCACGCGATACTCACGTTGACTCGTTGTCGCCAATCGTCCCAGGAAGCGTTTCGTGATTGACGATGAGGTCCGGAAGTTCGCCCCCAACGGGGTCTTCCCATCCTGTGCGAGCTTTTTTAGGATCTAGCCAACTTCACATCCTACCTGATTTTTAAAACCAACGGGACTTTTACTCCACACGGGCGTCACTGGCAACTCATGGAATGACCTTCCTGGCCCTATTCCCCCAGCACAAAGGTAGCGGGGAGCGCCCAGGCGAGTTAATAGCCAGGCACCAAGGTCCGTCAGTGATTCCTCGCCCGAGCGACGTTGTTTGCGAGATCCTCGTATCCGGATGGCTCGGATGATAATGTAGAAGCTTCGACTGGGACAGGTCTTTCAAGGGATACTAGCCACTAATATCGG" #print(transcribe(sequence)) def reverse_complement(dnastring): """Description here""" reverse = dnastring[::-1] rnastring = "" for c in reverse: if c == "A": rnastring += "T" elif c == "T": rnastring += "A" elif c == "C": rnastring += "G" elif c == "G": rnastring += "C" return rnastring #sequence = "TCGCACTCGCTCGTGCGACCTATTATAAGCCGACGCTCTCTATTGACTTTTGCGTTTTATTTTACGAGGTGGGAATGCTATATGATTCGTCATGCTTGAACGTCTGTGGACAGGATGAAACAAATAGTCACAGTAGGAGGTGCGGCAGCTTTAGAAGCACGTGACTAGGTAATGGCAGCGTATCGCGGGGACGGCGCTCGGCCATCCCTGTGAAATTTAAAATATTGATTTTTATAGGGATTGGCAAATTCCCTTTGCTTGGCGAGCTGCACCGGTAGGATATGTTTTAGAGGCTGTATCAGGACTAGTTAAAACTATAGTATTTAGGCCCGTTCGCTTAGACGGCTCAAGTAAGAAACTAAGCCAGTCAGGTGGGACACAGTTCGCATTGCCTCTGTCGCCACTCTTATAAGCGAGCCCTGAGCATTCTATAGTTTTACTATTCACACTTGAAACTCGTCCGACCTCCTTCGCGCATCACCTGCACATAATCGGGATGACATGAAGCTGTATCGTCCATCTTTTTCCCGAAAACGATGTAAACGTACTTATGCCTGTCGGGCCGTTTCATAAGTCTGGTTCAATGCTTACGAGTTTACTAGACTATACCCTCGCGTGACTTTGAAAGCTCTTGCGCAGGTGCAATCGTAACAATCCCACTGACTCTTGTTGATTAACGGCTTCATCGTAAAGCTTGTAAACTTGGGCCTGGCCAGGTGTCGGAGATCGGGAACTTTGACTAAGACTCCCACATTACCAGTATATTCAAGCTTATACTGAGCGTCGGGTAACAGAAATTCTAAGCCCATTCTAAACTGCCTTATTCTCGGCATGCGGAAAGGGCTTAGGAATCGGAGTTACAAGAGTGAAAATAATCCGATATTTGCGAGTAAGACGGGTCGCCAGTGAGCTCCAGTTCACTAG" #print(reverse_complement(sequence)) def compute_gc_content(fastafile): """Description here""" ratios = {} curr_string = "" for line in open(fastafile): # print line # print ratios if line[0] == ">": if curr_string: gcratio = float(gc) / (float(totallen)) ratios[curr_string] = gcratio gc = 0 totallen=0 curr_string = line[1:] else: gc += line.count("G") + line.count("C") totallen += len(line) - 1 # print gc # print len(line) gcratio = float(gc) / (float(totallen)) ratios[curr_string] = gcratio maxkey = max(ratios, key=ratios.get) print ratios[maxkey] * 100 #compute_gc_content("rosalind_gc.txt") def hamming_distance(s,t): """Description here""" i = 0 count = 0 if len(s) == len(t): while i < len(s): if s[i] != t[i]: count += 1 i += 1 return count # string1 = "GAAGACAGTGGACCTTGAGGTCTGAAGCTAGAGTCAATATTTGGTGGGTGCAGTCCCGGTACTCCCTATCCAATTATTATAGCCCTGTAGGAACTACGCTAATCTTTGCCTTCAACGGTACAAAGGCTCCACCTGCAGTCGAATCGGTACATGTAGTACAGAGAGAGTGAGTTGTAAGTAGGGATGATCGTCGTCGTGGGTTCTAATACTCAATGTGATCGTCTACGTATCAGTAATTTTTACATTACCCCTGCGCCTACTTCCTGGGGGGTATGTGAAGGTGCCATCCCCGTACTTCTGCGCGGAAGTCTATAATCCCAATATTGCATTCCGCCCTCAAGGACTTCTCAATTTAGTATGATGTGCACACGGGCTCCAACTGCGCTGTAAAGACCGGGACCCGGGCAGGTAATAGGTTCAGCCCAGAGCCCGCATATTCCACTGGGGTGTTGCCAATCTTATTCGGTCCATCGTAGCTAGATCTGAGTCCCCGCGACACAAAGCTTGTTGCGATCGGTAGGACTAGCACTTCTGGACTTGCTTGCCAGCCGAAGTATCAGAAGGTGGACTTTCCTGAACACCTGCGTACGGGACTGAGCCAACCAGTCAAAAGTCAGGGCGGCTATCAGACTAATCTTGAACTGACACGATGCAACTTGCCAATAACGGCAACCGAGTTGAAACCCTCTCCCAACATAAGAGAGCCCCCTCTCTCACTTTTTGAAGCATTTTGAGAAGATATCAACTCAACAAGGAAGTATGTCTAGCCGTTCCCTGTTTGAAACGTCCAAACATCGCGACTCGGTAAAAACAAACGACCGCGGCCTCCGGAACACGTCAATGGTGACGTTCCTAACTAGTAGCTGGGATAACAATTCCCCACAGGTAGCACCTTCTAGTTGTTTAGCCT" # string2 = "GCAGTGATGGGGTTTAGTTGGCTTAATCTAGAGTCAATATAACGCACAATGAGTCCACAGAGGCGCTATACCCATATACTGCCCTGTTACGCACAACGGAAATCTTCGCCAGCGACGGCAAAAAGGTCACGGCGCAGGGACAGTCAGGAAAATTAATAGTGTGACAGTGAGTTCTAGTAACGGAGGATAGGTGTCATGGCTTCTCTTACGAGATGCGTGCACCCCGGTCACACGTAACACTCCAAGCAACCTGCGCGTACATCGTCGAACGTATACCATGGTGTTCCGCGTTAAAAGCTGGCTGAACGTCGATCATTTAACTGTAATCTACCTAGACGTAGGACATCAATACCCGGAGGAATGGGCACACAAACTGAATTTGGGTGTGAACGACTGTAGTCAGGACAGGTTCTGGCTTCGTATAACAGGTTTGATGATCTACCTGACTTATCCGATGTACATCAGGCTCAGTTCACCTATCACTGTCTCCGGGCGACACATGACTCACTTCTTTTTATAGGTCTCTCATTTCTGGCCCCGCGAACCACCCTAAATAAACGAAGGCATTCCGTAGAAACCAATCAGGCCCGACAATGAGCCAGCCAGCACAAATTGGGTTCCGCCAGCATTCGAATGTAGATTTGATATAATGTGCACTGGCAATCACTTCATTTGGGGGGAGCCTATTTCATCAAGCAGTTAAGGCTCCTCGCTAAGTATATGAAGCATGTGACAAACTAAACGAGTCAACGAGGCCGGCTAGCGTACCTGTGCCAGTTCCAAACCTCTACTCTTCGAGACACGACAAACACAAAACAGCGTGGGTCCAAGCGCAGAAAAAGGGTGGTCTTCCTAGCTATTAGCTATTACTCCAAGTACTGAACTATCCCACCTGGATGGAGTGTAGCAA" #print(hamming_distance(string1, string2)) def recurrence_rabbits(n,k): """Description here""" curr = 1 next = 1 i = 2 while i < n: temp = curr curr = next next = curr + k * temp i += 1 return next # print(recurrence_rabbits(31, 4)) def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) def mendel(dd, dr, rr): """Description here""" total = dd + dr + rr p_rr_rr = float(nCr(rr, 2)) / float(nCr(total, 2)) p_dr_dr = float(nCr(dr, 2)) / float(nCr(total, 2)) p_dr_rr = (float(nCr(rr, 1) * nCr(dr, 1))) / float(nCr(total, 2)) p_offspringisrr = p_rr_rr * 1 + p_dr_dr * 0.25 + p_dr_rr * 0.5 return 1 - p_offspringisrr #print(mendel(17,22,24)) # A dictionary of RNA 3-letter codons mapped to the 1-letter protein abbreviation they translate to. rnacodons = {"UUU":"F", "UUC":"F", "UUA":"L", "UUG":"L", "UCU":"S", "UCC":"S", "UCA":"S", "UCG":"S", "UAU":"Y", "UAC":"Y", "UAA":"", "UAG":"", "UGU":"C", "UGC":"C", "UGA":"", "UGG":"W", "CUU":"L", "CUC":"L", "CUA":"L", "CUG":"L", "CCU":"P", "CCC":"P", "CCA":"P", "CCG":"P", "CAU":"H", "CAC":"H", "CAA":"Q", "CAG":"Q", "CGU":"R", "CGC":"R", "CGA":"R", "CGG":"R", "AUU":"I", "AUC":"I", "AUA":"I", "AUG":"M", "ACU":"T", "ACC":"T", "ACA":"T", "ACG":"T", "AAU":"N", "AAC":"N", "AAA":"K", "AAG":"K", "AGU":"S", "AGC":"S", "AGA":"R", "AGG":"R", "GUU":"V", "GUC":"V", "GUA":"V", "GUG":"V", "GCU":"A", "GCC":"A", "GCA":"A", "GCG":"A", "GAU":"D", "GAC":"D", "GAA":"E", "GAG":"E", "GGU":"G", "GGC":"G", "GGA":"G", "GGG":"G",} def translate(mrna): i = 0 protein = "" while i < len(mrna): codon = mrna[i:i+3] protein += rnacodons[codon] i += 3 return protein # sequence = "" # print(translate(sequence)) def find_motif(dnastring, motif): string = "(?=" + motif + ")" indexstring = "" for item in [m.start() for m in re.finditer(string, dnastring)]: indexstring += str(item+1) + " " return indexstring # dnastring = "AATTTCGAATTTCGACCACTTGGATTTCGACCACAATTTCGACATTTCGACATTTCGAGATTTCGAATTTCGAGCTATTTCGAACGATTTCGACGTAATTTCGACAGCATTATTTCGACTGATTTCGAGGAGATTTCGAAATTTCGAATTTCGATTGGATTTCGATAAGAGGCGTCATTTCGACACATTTCGAGCATTTCGAATTTCGAATTTCGAATTTCGAACATTTCGATTAATTTCGACAATTTCGATGCCATTTCGATGCCTGGCATTTCGAGTGATTTCGATGTGTATTTCGAGGATTTCGATCGAATTTCGAAATTTCGAATTTCGATATTTCGAGCCCATTTCGATGATTTCGAGTCCCCCCATTTCGAAATCCTAGAATTTCGACATACATGGCACATTTCGACATTTCGAATTTCGATGCATTTCGATATTTCGAATTTCGAATTTCGAATTTCGAATTTCGAAATTTCGACATTTCGATAATTTCGAAGAATTTCGATTGACAGGGACATTTCGATGATTTCGAATTTCGATGATTTCGAATTTCGATGCACAAATTTCGAAATTTCGACATTTCGAGAATTTCGATTTCCTTAGATTTCGATGGTTATTTCGATATTTCGACAGATTTCGAATTTCGAGTTATCCTAATTTCGAATTTCGAATTTCGAGCGATAAACCCTTGATTTCGATATTTCGAATTTCGAGCACCCATAAAATTTCGAACCCGTTTAACGAGGTGTATTTCGACGCTATTTCGAATTTCGATATTTCGAATTTCGAGTGACTTATTTCGATGATTTCGAGTATTTCGAATTTCGAGTGTCACATTTCGAACGTATCTCATTTCGAAGCTAACTC" # motif = "ATTTCGAAT" # print(find_motif(dnastring,motif)) def fasta_parser(fastafile): """Takes a FASTA file as input and returns a list of [label, sequence] pairs.""" toreturn = [] key = None for line in open(fastafile): if line[0] == ">": if key: toreturn.append([key, value]) key = line[1:].strip() value = "" else: value += line.strip() toreturn.append([key, value]) return toreturn # print(fasta_parser("rosalind_cons.txt")) def consensus_profile(fastafile): data = fasta_parser(fastafile) nucleotides = ["A", "C", "G", "T"] A = [] C = [] G = [] T = [] i = 0 while i < len(data[0][1]): # iterate through indices counts_i = {} for j in data: #iterate through strings base = j[1][i] # ith character in string of jth pair if base in counts_i: counts_i[base] += 1 else: counts_i[base] = 1 for nuc in nucleotides: if nuc in counts_i: if nuc == "A": A.append(counts_i[nuc]) elif nuc == "C": C.append(counts_i[nuc]) elif nuc == "G": G.append(counts_i[nuc]) elif nuc == "T": T.append(counts_i[nuc]) counts_i[nuc] else: if nuc == "A": A.append(0); elif nuc == "C": C.append(0); elif nuc == "G": G.append(0); elif nuc == "T": T.append(0); i += 1 A.insert(0,"A") C.insert(0,"C") G.insert(0,"G") T.insert(0,"T") lols = [A, C, G, T] length = len(A) consensus = consensus_string(lols, length) print consensus for base in lols: s = base[0] + ": " for num in base[1:]: s += str(num) + " " print s def consensus_string(listoflists, length): consensus = "" i = 1 while i < length: max_value = 0 max_label = "" for l in listoflists: if l[i] > max_value: max_value = l[i] max_label = l[0] consensus += max_label i += 1 return consensus # consensus_profile("rosalind_cons (1).txt") def expected_offspring(AAAA, AAAa, AAaa, AaAa, Aaaa, aaaa): return 2 * ((AAAA * 1) + (AAAa * 1) + (AAaa * 1) + (AaAa * 0.75) + (Aaaa * 0.5) + (aaaa * 0)) # print(expected_offspring(18863, 19124, 18095, 17294, 16670, 19520)) def permutations(n): item = 1 lst = [] while item <= n: lst.append(item) item += 1 permutations = list(itertools.permutations(lst)) print len(permutations) for l in permutations: line = "" for item in l: line += str(item) + " " print line # permutations(5) def fib(n, m): rabbits = [1] + [0]*(n-1) i = 1 while i < n: j = 1 new_rabbits = 0 while j <= m: if j <= i: new_rabbits += rabbits[i-j] j += 1 rabbits[i] = new_rabbits i += 1 return rabbits print(fib(6,3))
true
fe16ab3a1249f0fa8c93b3616ab962e746459049
Python
tobikausk/Python-Module-of-the-Week
/session1_Decorators/printtime.py
UTF-8
389
3.109375
3
[ "MIT" ]
permissive
""" Exercise — a decorator which times function execution Write 'printtime' decorator which prints how long a function took to execute. @printtime def loooong(): s = 0 for i in range(1000000): s += i**2 return s >>> looong() looong took 5.0323423 s 333332833333500000 >>> time.time() >>> time.time() 1441180399.3036400 >>> time.time() 1441180400.3567457 """ ...
true
dff9ffa93f01a8d38bc426d30a79f071b22eac5e
Python
vivek1262/Initialprog.github.io
/simpleIf.py
UTF-8
102
3.53125
4
[]
no_license
x=10 if (x==10): print('x value is ',x); else: print('x value is ',x,'from else');
true
9bf55038a43a5cb94b419091170ee89444b6a416
Python
filmackay/flypy
/flypy/compiler/frontend/utils.py
UTF-8
1,110
2.703125
3
[ "BSD-2-Clause" ]
permissive
# -*- coding: utf-8 -*- """ Utilities for working with bytecode. """ from __future__ import print_function, division, absolute_import import collections import functools class SortedMap(collections.Mapping): '''Immutable ''' def __init__(self, seq): self._values = [] self._index = {} for i, (k, v) in enumerate(sorted(seq)): self._index[k] = i self._values.append((k, v)) def __getitem__(self, k): i = self._index[k] return self._values[i][1] def __len__(self): return len(self._values) def __iter__(self): return (k for k, v in self._values) def cache(fn): @functools.wraps(fn) def cached_func(self, *args, **kws): if self in cached_func.cache: return cached_func.cache[self] ret = fn(self, *args, **kws) cached_func.cache[self] = ret return ret cached_func.cache = {} def invalidate(self): if self in cached_func.cache: del cached_func.cache[self] cached_func.invalidate = invalidate return cached_func
true
b1e38ba5a6ee837853fb424306b994fbe5f0566b
Python
ml-in-programming/ml-on-source-code-models
/psob_authorship/features/java/line_metrics/LineMetricsCalculator.py
UTF-8
5,878
2.59375
3
[ "Apache-2.0" ]
permissive
import logging import os import subprocess from collections import defaultdict from typing import Dict, Set, List import torch from psob_authorship.features.utils import get_absfilepaths, \ divide_ratio_with_handling_zero_division, \ divide_nonnegative_with_handling_zero_division class LineMetricsCalculator: LOGGER = logging.getLogger('metrics_calculator') def get_metrics(self, filepaths: Set[str]) -> torch.Tensor: return torch.tensor([ self.ratio_of_blank_lines_to_code_lines(filepaths), self.ratio_of_comment_lines_to_code_lines(filepaths), self.ratio_of_block_comments_to_all_comment_lines(filepaths) ]) def ratio_of_blank_lines_to_code_lines(self, filepaths: Set[str]) -> float: """ Blank line is a line consisting only of zero or several whitespaces. More formally in UML notation: blank line = whitespace[0..*] Code line is any line that is not blank line or comment line. :param filepaths: paths to files for which metric should be calculated :return: blank lines metric """ return divide_nonnegative_with_handling_zero_division( sum([self.blank_lines_for_file[filepath] for filepath in filepaths]), sum([self.code_lines_for_file[filepath] for filepath in filepaths]), self.LOGGER, "calculating ratio of blank lines to code lines for " + str(filepaths) ) def ratio_of_comment_lines_to_code_lines(self, filepaths: Set[str]) -> float: """ Comment line is a line that starts (without regard to leading whitespaces) with "//" or located in commented block. If any symbol (except whitespace) exists before "//" and it is not located in commented block then this line is accounted as code line not a comment line. Code line is any line that is not blank line or comment line. :param filepaths: paths to files for which metric should be calculated :return: comment lines metric """ return divide_nonnegative_with_handling_zero_division( sum([self.comment_lines_for_file[filepath] for filepath in filepaths]), sum([self.code_lines_for_file[filepath] for filepath in filepaths]), self.LOGGER, "calculating ratio of comment lines to code lines for " + str(filepaths) ) def ratio_of_block_comments_to_all_comment_lines(self, filepaths: Set[str]) -> float: """ Block comment size is number of comment lines in block comment. :param filepaths: paths to files for which metric should be calculated :return: block comment lines metric """ return divide_ratio_with_handling_zero_division( sum([self.comment_lines_for_file[filepath] - self.single_line_comments_for_file[filepath] for filepath in filepaths]), sum([self.comment_lines_for_file[filepath] for filepath in filepaths]), self.LOGGER, "calculating ratio of block comments to all comment lines for " + str(filepaths) ) def __init__(self, language_config: Dict[str, str], dataset_path: str) -> None: self.language_config = language_config self.LOGGER.info("Started calculating line metrics") super().__init__() self.dataset_path = dataset_path self.single_line_comments_for_file: Dict[str, int] = defaultdict(lambda: 0) self.blank_lines_for_file: Dict[str, int] = defaultdict(lambda: 0) self.comment_lines_for_file: Dict[str, int] = defaultdict(lambda: 0) self.code_lines_for_file: Dict[str, int] = defaultdict(lambda: 0) self.calculate_metrics_for_file() self.LOGGER.info("End calculating line metrics") def calculate_metrics_for_file(self) -> None: self.count_single_line_comments_for_file() cloc_output = self.get_cloc_output() for cloc_file_output in cloc_output.splitlines(): if not cloc_file_output.startswith(self.language_config['language_name']): continue splitted = cloc_file_output.split(',') filepath = os.path.abspath(splitted[1]) self.blank_lines_for_file[filepath] = int(splitted[2]) self.comment_lines_for_file[filepath] = int(splitted[3]) self.code_lines_for_file[filepath] = int(splitted[4]) def get_cloc_output(self) -> str: """ Runs cloc external program and calculates number of blank, comment and code lines by file for dataset_path. """ return subprocess.run(["cloc", self.dataset_path, "--by-file", "--quiet", "--csv"], check=True, stdout=subprocess.PIPE) \ .stdout.decode("utf-8") def count_single_line_comments_for_file(self) -> None: """ Counts number of single line comments. Line is single line commented if it starts with "//" (without regard to leading whitespaces) and is located not inside comment block. Now it doesn't works correctly in such case: /* //this single line comment will be counted, but shouldn't. */ But this case appears too rare so implementation of it can wait. """ filepaths = get_absfilepaths(self.dataset_path) for filepath in filepaths: self.single_line_comments_for_file[filepath] = self.count_single_line_comments(filepath) def count_single_line_comments(self, filepath: str) -> int: with open(filepath) as file: return sum(line.lstrip().startswith("//") for line in file) @staticmethod def get_metric_names() -> List[str]: return [ "ratio_of_blank_lines_to_code_lines", "ratio_of_comment_lines_to_code_lines", "ratio_of_block_comments_to_all_comment_lines" ]
true
4ad18e0796dd70f419112be7815e3f21df281d6e
Python
soongon/python-auto
/ask-money.py
UTF-8
1,351
2.859375
3
[]
no_license
import openpyxl import smtplib import email import pprint def get_not_paid_members(ws): not_paid_list = [] for row_index in range(2, ws.max_row + 1): if '미결제' in ws.cell(row_index, 4).value: not_paid_list.append( [ws.cell(row_index, 1).value, ws.cell(row_index, 2).value]) return not_paid_list def send_email_for_ask_money(members): smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login('soongon', 'password') for member in members: # 텍스트 파일 msg = email.mime.multipart.MIMEMultipart("alternative") msg["From"] = 'soongon@gmail.com' msg["To"] = member[1] msg["Subject"] = member[0] + '님 회비납부 요망' contents = '회비 부탁해요' text = email.mime.text.MIMEText(_text=contents, _charset="utf-8") msg.attach(text) smtp.sendmail('soongon@gmail.com', member[1], msg.as_string()) print(member[0] + '님에게 메일 전송 완료') smtp.quit() def report_ask_money_result_to_me(): pass def main(): wb = openpyxl.load_workbook('수강생_결제정보.xlsx') ws = wb['결제정보'] not_paid_members = get_not_paid_members(ws) send_email_for_ask_money(not_paid_members) report_ask_money_result_to_me() main()
true
8e015026ae3c4b2fc98288e09eb5b4cff27edff8
Python
Jeremy277/exercise
/pytnon-month01/month01-shibw-notes/day01-shibw/demo01-input&print.py
UTF-8
574
3.90625
4
[]
no_license
#注释 给别人看的 不是让计算机执行的 #注释写的是对代码的描述 #input叫做一种函数 作用是接受用户的输入内容 # = 的作用是将右边得到的结果赋值给左边 #写程序时 可能先写右侧 后写左侧 str1 = input('请输入...') #print也是一种函数 作用是向终端输入内容 print('hello world') #有交互 #接受用户输入内容 输出对应的结果 str2 = input('请输入第二次内容...') #ctrl + z 撤销上次操作 #shift+alt + 上下箭头移动行 print(str2)
true
2d22f9f05596a6d2eeb5ba07be2fd819ce931425
Python
bobby-palko/100-days-of-python
/33/ui.py
UTF-8
2,166
3.40625
3
[]
no_license
from tkinter import * from quiz_brain import QuizBrain THEME_COLOR = "#375362" QUESTION_FONT = ("Arial", 14, "italic") SCORE_FONT = ("Arial", 10, "bold") class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = Tk() self.window.title("Quizzler") self.window.config(padx=20, pady=20, bg=THEME_COLOR) self.score = Label(text="Score: 0", bg=THEME_COLOR, fg="white", font=SCORE_FONT) self.score.grid(row=0, column=1) self.canvas = Canvas(height=250, width=300, bg="white") self.q_text = self.canvas.create_text( 150, 125, width=280, font=QUESTION_FONT, text="Hello!", fill=THEME_COLOR ) self.canvas.grid(row=1, column=0, columnspan=2, pady=50) true_img = PhotoImage(file="images/true.png") self.true_btn = Button(image=true_img, highlightthickness=0, command=lambda: self.btn_pressed("True")) self.true_btn.grid(row=2, column=0) false_img = PhotoImage(file="images/false.png") self.false_btn = Button(image=false_img, highlightthickness=0, command=lambda: self.btn_pressed("False")) self.false_btn.grid(row=2, column=1) self.get_next_question() self.window.mainloop() def get_next_question(self): self.canvas.configure(bg="white") if self.quiz.still_has_questions(): self.score.config(text=f"Score: {self.quiz.score}") question = self.quiz.next_question() self.canvas.itemconfig(self.q_text, text=question) else: self.canvas.itemconfig(self.q_text, text="You've reached the end of the quiz!") self.true_btn.config(state="disabled") self.false_btn.config(state="disabled") def btn_pressed(self, answer: str): self.give_feedback(self.quiz.check_answer(answer)) def give_feedback(self, is_right): if is_right: self.canvas.configure(bg="green") else: self.canvas.configure(bg="red") self.window.after(1000, self.get_next_question)
true
d0e3fe268012e5a3087c48a2f4b673b78a8574df
Python
all1m-algorithm-study/2021-1-Algorithm-Study
/week2/Group6/boj2839_donghoonKang.py
UTF-8
359
3.171875
3
[]
no_license
N = int(input()) M = N // 5 five, three = 0, 0 flag = False while M != 0: Ncopy = N Ncopy = Ncopy - M*5 if Ncopy % 3 == 0: five = M three = Ncopy // 3 break M -= 1 if M == 0: flag = True if flag == True and N % 3 == 0: print(N//3) elif flag == True and N % 3 != 0: print(-1) else: print(five+three)
true
9df7685ee95a0c8480dc2efea89c6e014dac7faf
Python
pseudogram/pendulum_v0
/optimizers.py
UTF-8
10,966
2.71875
3
[]
no_license
from deap import creator from deap import base from deap import tools import numpy as np import random import gym from rnn import Basic_rnn, FullyConnectedRNN from pprint import pprint import environment # ------------------------------------------------------------------------------ # SET UP: OpenAI Gym Environment # ------------------------------------------------------------------------------ class MicrobialGA: def __init__(self, env, agent, EPISODES=3, STEPS=200, POPULATION_SIZE=16, CROSS_PROB=0.5, NUM_GEN=2000, DEME_SIZE=3 ): # self.ENV_NAME = 'Pendulum-v0' self.EPISODES = EPISODES # Number of times to run envionrment when evaluating self.STEPS = STEPS # Max number of steps to run run simulation self.env = env # # # Used to create controller # obs_dim = env.observation_space.shape[0] # Input to controller (observ.) # action_dim = env.action_space.shape[0] # Output from controller (action) # nodes = 10 # Unconnected nodes in network in the # dt = 0.05 # dt for the environment, found in environment source code # dt = 1 # Works the best, 0.05 causes it to vanish # ---------------------------------------------------------------------- # SET UP: TensorFlow Basic_rnn # ---------------------------------------------------------------------- self.agent = agent # ---------------------------------------------------------------------- # SET UP GA PARAMETERS # ---------------------------------------------------------------------- self.POPULATION_SIZE = POPULATION_SIZE self.CROSS_PROB = CROSS_PROB self.NUM_GEN = NUM_GEN # Number of generations self.DEME_SIZE = DEME_SIZE # from either side # ------------------------------------------------------------------------------ # CREATE GA # ------------------------------------------------------------------------------ # Creates a Fitness class, with a weights attribute. # 1 means a metric that needs to be maximized = the value # -1 means the metric needs to be minimized. All OpenAI creator.create("FitnessMax", base.Fitness, weights=(1.0,)) # Creates a class Individual, that is based on a numpy array as that is the # class used for the weights passed to TensorFlow. # It also has an attribute that is a Fitness, when setting the attribute # it automatically calls the __init__() in Fitness initializing the # weight (1) creator.create("Individual", np.ndarray, fitness=creator.FitnessMax) # ============================================================================== self.toolbox = base.Toolbox() # Create a function 'attr_item' to return the 'ID' of one item # num_nodes = num_inputs+1 = 20 self.NUM_PARAMS = self.agent.num_params # create a function 'individual'. It takes an individual and instantiates # it with a numpy array of size, NUM_PARAMS and type float32 # Set the weights to a value n where, -0.1 < n < 0.1 self.toolbox.register("attr_floats", lambda n: (np.random.rand( n).astype( np.float32)-0.5)*2, self.NUM_PARAMS) self.toolbox.register("individual", tools.initIterate, creator.Individual, self.toolbox.attr_floats) # create a function 'population' that generates a list of individuals, x long. # NB: As repeat init takes 3 parameters, and as the first 2 have been given. # only one is needed. self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) # ---------------------------------------------------------------------- # Register all functions from below and more # ---------------------------------------------------------------------- self.toolbox.register("evaluate", self.evaluate) self.toolbox.register("crossover", self.cross) self.toolbox.register("mutate", self.mutate) # toolbox.register("select", tools.selRandom, k=2) self.toolbox.register("select", self.selDeme, deme_size=DEME_SIZE) self.hof = tools.HallOfFame(1, np.array_equal) # Store the best 3 individuals self.stats = tools.Statistics(lambda ind: ind.fitness.values) self.stats.register("avg", np.mean, axis=0) self.stats.register("std", np.std, axis=0) self.stats.register("min", np.min, axis=0) self.stats.register("max", np.max, axis=0) self.logbook = tools.Logbook() self.logbook.header = ['gen', 'nevals'] + self.stats.fields # ------------------------------------------------------------------------------ # Evaluation function of GA # ------------------------------------------------------------------------------ def evaluate(self, individual, MAX_REWARD=0): """Lends heavily from evaluate.py""" # Load weights into RNN self.agent.set_weights(individual) total_reward = 0 for episode in range(self.EPISODES): # print("Starting Episode: {}".format(episode)) # Starting observation observation = self.env.reset() episode_reward = 0 next_state = np.random.rand(self.agent.state_size, 1).astype( dtype=np.float32) for step in range(self.STEPS): # env.render() observation = np.reshape(observation,(3,1)) # print(observation.shape) action, next_state = self.agent.percieve(observation, next_state) observation, reward, done, _ = self.env.step(action) episode_reward += reward # print('step',step, 'action', action, 'observation', observation) if done: break # print("Episode {} = {}".format(episode, episode_reward)) total_reward += episode_reward # print(self.agent.get_weights()) # returns the average reward for number of episodes run total_reward /= self.EPISODES print(total_reward) return total_reward def evaluateTester(self, individual): print(-np.sum(np.abs(individual))) return [-np.sum(np.abs(individual))] def cross(self, winner, loser): """Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. Is ind1 the winner or ind2??? """ for i in range(self.NUM_PARAMS): if np.random.rand() < self.CROSS_PROB: loser[i] = winner[i] return loser def mutate(self, individual): """Adds or subtracts 1% with a chance of 1/NUM_PARAMS""" # TODO: Increase speed of mutation for i in range(self.NUM_PARAMS): if np.random.rand() < (1/self.NUM_PARAMS): individual[i] += individual[i] * (np.random.rand()-0.5)*0.01 return individual # TODO: create function to select 2 indiviuals within close proximity def selDeme(self, individuals, deme_size): """Select *k* individuals at random from the input *individuals* with replacement. The list returned contains references to the input *individuals*. :param individuals: A list of individuals to select from. :param k: The number of individuals to select. :returns: A list of selected individuals. This function uses the :func:`~random.choice` function from the python base :mod:`random` module. """ one = np.random.randint(self.POPULATION_SIZE) _next = np.random.randint(1, deme_size + 1) if np.random.rand() < 0.5: _next = -_next two = (one + _next) % self.POPULATION_SIZE return individuals[one], individuals[two] def run(self,verbosity=1): if(verbosity>0): print('Initializing population.') pop = self.toolbox.population(n=self.POPULATION_SIZE) CXPB, MUTPB = 0.5, 0.2 # Evaluate the entire population fitnesses = map(self.toolbox.evaluate, pop) for ind, fit in zip(pop, fitnesses): # Set fitness property of individual to fit. ind.fitness.values = fit self.hof.update(pop) record = self.stats.compile(pop) self.logbook.record(gen=0, nevals=0, **record) # Start Tournament for g in range(1, self.NUM_GEN+1): if(verbosity>0): print('Running generation {}'.format(g)) # Select the next generation individuals # Selecting uses an object reference so no need to put individuals back # TODO: Make selection function that returns a tuple of individuals, # TODO: the first, a winner, the second the loser. chosen = self.toolbox.select(pop) # print(chosen[0].fitness.getValues) # print(chosen[1].fitness.values) # select winner and loser if chosen[0].fitness > chosen[1].fitness: winner = chosen[0] loser = chosen[1] elif chosen[1].fitness > chosen[0].fitness: winner = chosen[1] loser = chosen[0] else: continue del loser.fitness.values # print(winner.fitness.values) # print(winner.fitness.valid) # Apply crossover self.toolbox.crossover(winner, loser) # Apply mutation self.toolbox.mutate(loser) loser.fitness.values = self.toolbox.evaluate(loser) self.hof.update(pop) record = self.stats.compile(pop) self.logbook.record(gen=g, nevals=0, **record) if(verbosity>0): print('Completed optimization.') return pop # Test the MicrobialGA algorithm works if __name__ == "__main__": from rnn import FullyConnectedRNN import gym import tensorflow as tf n = 10 # number of nodes to test ENV_NAME = 'Pendulum-v0' env = gym.make(ENV_NAME) EPISODES = 3 # Number of times to run envionrment when evaluating STEPS = 200 # Max number of steps to run run simulation observation_space = env.observation_space.shape[ 0] # Input to controller (observ.) action_space = env.action_space.shape[0] # Output from controller (action) agent = FullyConnectedRNN(observation_space,action_space,n) opti = MicrobialGA(env, agent, EPISODES=1, NUM_GEN=100) opti.run()
true
60333008a07d076a1f5b35144d6372e90bc9910a
Python
MagicWishMonkey/artofoldindia
/scrape.py
UTF-8
5,354
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- from selenium import webdriver from fuze import toolkit, util driver = webdriver.Chrome() def scrape_category(category): uri = "http://www.artofoldindia.com/product-category/%s" % category driver.get(uri) breadcrumb = driver.find_element_by_id("breadcrumb") breadcrumb = breadcrumb.find_elements_by_tag_name("a") breadcrumb = breadcrumb[1] breadcrumb = breadcrumb.text category = "%s/%s" % (breadcrumb.strip().lower(), category.strip().lower()) product_entries = [] products = driver.find_element_by_class_name("products") products = products.find_elements_by_tag_name("li") products = [{"category": category, "url": product.find_element_by_tag_name("a").get_attribute("href")} for product in products] product_entries.extend(products) while True: try: next = driver.find_element_by_class_name("nav-next") next = next.find_element_by_tag_name("a") except: next = None if next is None: break href = next.get_attribute("href") if href is None: break driver.get(href) products = driver.find_element_by_class_name("products") products = products.find_elements_by_tag_name("li") products = [{"category": category, "url": product.find_element_by_tag_name("a").get_attribute("href")} for product in products] product_entries.extend(products) return product_entries def scrape_product(product): # product["url"] = "http://www.artofoldindia.com/shop/horse-on-stand/" name = product["url"].split("/") name = name[len(name) - 2] if name[len(name) - 1] == "" else name[len(name) - 1] product["name"] = name driver.get(product["url"]) title = driver.find_element_by_class_name("product_title") product["title"] = title.text sku = driver.find_element_by_class_name("sku") product["sku"] = sku.text.split(":")[1].strip() try: price = driver.find_element_by_class_name("price").text if len(price.strip()) > 1: product["price"] = price.strip() except: pass try: quantity = driver.find_element_by_class_name("stock").text if len(quantity.strip()) > 1: quantity = quantity.strip() if quantity.find(u"–") > -1: quantity = quantity.split(u"–")[1] quantity = quantity.strip().split(" ")[0] if quantity.isdigit() is True: product["quantity"] = int(quantity) except: pass description = driver.find_element_by_id("tab-description") parts = description.find_elements_by_tag_name("p") description = [] for part in parts: if part.text.lower().startswith("made in india"): continue description.append(part.text) product["description"] = "\n".join(description) try: driver.find_element_by_class_name("tabs").find_elements_by_tag_name("li")[1].click() product["attributes"] = {} attributes = driver.find_element_by_class_name("shop_attributes") attributes = attributes.find_elements_by_tag_name("tr") for x, attribute in enumerate(attributes): key = attribute.find_element_by_tag_name("th") try: key = key.find_element_by_tag_name("p") except: pass key = key.text val = attribute.find_element_by_tag_name("td") try: val = val.find_element_by_tag_name("p") except: pass val = val.text if not key: continue product["attributes"][key] = val except: pass photos = [] images = driver.find_element_by_class_name("images") default = images.find_element_by_tag_name("a") default = default.get_attribute("href") photos.append(default) thumbnails = driver.find_element_by_class_name("thumbnails") thumbnails = thumbnails.find_elements_by_tag_name("a") for thumbnail in thumbnails: try: thumbnail = thumbnail.get_attribute("href") photos.append(thumbnail) except: pass product["images"] = photos return product categories = [ "lighting", "mirrors", "misc-accessories", "rugs", "antiques", "doors", "celing", "columns", "arches", "misc", "seating", "tables", "armoires", "trunks", "consoles" ] # catalogue = [] # for category in categories: # products = scrape_category(category) # catalogue.extend(products) # products = toolkit.json(catalogue, indent=2) # util.file("/Work/personal/artofoldindia/products.json").write_text(products) products = toolkit.unjson(util.file("/Work/personal/artofoldindia/products.json").read_text()) for product in products: if product.get("name", None) is not None: continue try: product = scrape_product(product) util.file("/Work/personal/artofoldindia/products.json").write_text(toolkit.json(products)) # print toolkit.json(product, indent=2) except Exception, ex: print product["url"] message = "ERROR SCRAPING PRODUCT: %s -> %s" % (product["url"], ex.message) print message print ""
true
239a5babfec5b5fecb3e9a11f6a168d75fa779b6
Python
LadislavVasina1/PythonStudy
/ProgramFlow/trueFalse.py
UTF-8
285
3.875
4
[]
no_license
day = "Monday" temperature = 30 raining = True if (day == "Saturday" and temperature > 27) or not raining: print("Go swimming.") else: print("Learn Python") name = input("Enter your name: ") if name: print(f"Hi, {name}") else: print("Are you the man with no name?")
true
7cd84097affd4516f216d295526853bc252eb7e7
Python
standardgalactic/kuhner-python
/mutation_clusters/classify_bysize.py
UTF-8
4,800
2.875
3
[]
no_license
# classify.py Mary Kuhner and Jon Yamato 2018/04/02 # This program receives the output of bamscore.py # to answer the question "For two mutations close enough together # that they might be in the same read, how often are they actually both # present on a read spanning both their positions?" # NOTE: BAM is zero based. VCF is one based. Subtract 1 from your VCF # mutation position before looking it up in BAM! # WARNING: We wrote this code against a BAM file where paired reads had the # same name, but this is not standardized: it will NOT WORK RIGHT if paired # reads append /1, /2 or _1, _2 or _a, _b or anything like that! import os from os import path from os import mkdir import matplotlib.pyplot as plt import lucianSNPLibrary as lsl read_cutoff = 5 # how many non ref/alt bases can we tolerate at a mutation pair # before throwing it out? max_unexpected_bases = 5 # lowest acceptable mapping quality for a read min_quality = 25 resultdir = "results/" outdir = "analysis/" if not(path.isdir(outdir)): mkdir(outdir) # functions def hasbin(result,bin): if result[bin] > read_cutoff: return True return False def score_read(base1,base2,mut1,mut2,scorearray): chr1,pos1,ref1,alt1 = mut1 chr2,pos2,ref2,alt2 = mut2 # score the mutation if base1 == ref1 and base2 == ref2: scorearray[0] += 1 if base1 == ref1 and base2 == alt2: scorearray[1] += 1 if base1 == alt1 and base2 == ref2: scorearray[2] += 1 if base1 == alt1 and base2 == alt2: scorearray[3] += 1 scorearray[4] += 1 def summarize(pairlist, cisdists, transdists, nesteddists): # taxonomy: # less than 12 total reads: toosmall # just bin0: wt # just bin1 or just bin2: missed # all three bins: fourgamete # bins 1 and 2 but not 3: trans # bin 3 alone: cis # bin 3 with bin 1 or 2 but not both: nested results = {} results["noreads"] = 0 results["anomaly"] = 0 results["toosmall"] = 0 results["wt"] = 0 results["missed"] = 0 results["fourgamete"] = 0 results["cis"] = 0 results["trans"] = 0 results["nested"] = 0 for tally in pairlist: pos1 = int(tally[6]) pos2 = int(tally[7]) dist = pos2 - pos1 # noreads if tally[4] == 0: results["noreads"] += 1 continue # anomaly unexpected_bases = tally[4] - sum(tally[0:4]) if unexpected_bases > max_unexpected_bases: results["anomaly"] += 1 continue # toosmall if tally[4] < 12: results["toosmall"] += 1 continue # wt if not hasbin(tally,1) and not hasbin(tally,2) and not hasbin(tally,3): results["wt"] += 1 continue # missed if hasbin(tally,1) and not hasbin(tally,2) and not hasbin(tally,3): results["missed"] += 1 continue if not hasbin(tally,1) and hasbin(tally,2) and not hasbin(tally,3): results["missed"] += 1 continue # fourgamete if hasbin(tally,1) and hasbin(tally,2) and hasbin(tally,3): results["fourgamete"] += 1 continue # trans if hasbin(tally,1) and hasbin(tally,2) and not hasbin(tally,3): results["trans"] += 1 transdists.append(dist) continue # cis if not hasbin(tally,1) and not hasbin(tally,2) and hasbin(tally,3): results["cis"] += 1 cisdists.append(dist) continue # nested if (hasbin(tally,1) or hasbin(tally,2)) and hasbin(tally,3): results["nested"] += 1 nesteddists.append(dist) continue print("found anomaly:",tally) assert False return results ######################################################################## # main program rfiles = [] for root, dirs, files in os.walk(resultdir): for file in files: if file.endswith("_results.txt"): rfiles.append(file) cisdists = [] transdists = [] nesteddists = [] for rfile in rfiles: data = [] (pid, sid, A, B) = rfile.split("_")[0:4] if not(A=='1' and B=='1'): continue for line in open(resultdir + rfile,"r"): line = line.rstrip().split() datum = [] for entry in line: entry = int(entry) datum.append(entry) data.append(datum) # classify by distances ############################################################ # write reports results = summarize(data, cisdists, transdists, nesteddists) lsl.createPrintAndSaveHistogram(cisdists, "Cis Distances", 0.5, xdata="distance", axis=(-20, 500, 0)) lsl.createPrintAndSaveHistogram(transdists, "Trans Distances", 0.5, xdata="distance", axis=(-20, 500, 0)) lsl.createPrintAndSaveHistogram(nesteddists, "Nested Distances", 0.5, xdata="distance", axis=(-20, 500, 0)) plt.ylim(0, 400) plt.hist(cisdists, 100) plt.hist(transdists, 100) plt.hist(nesteddists, 100) plt.show() plt.close()
true
96e2a52db5d6e3a9014b3bd2fdff198a005bdd21
Python
andreaowu/IPaddresses
/onesify.py
UTF-8
1,187
2.96875
3
[]
no_license
from scapy.all import * import re import json class ProcessPacket: def __init__(self): ''' Initializes constants needed to process the packet and then processes the packet ''' self.get_input() def get_input(self): '''Reads given pcap file and parses it''' user_directory = "/Users/andreawu/Downloads/cfd/correct_stream.pcap" self.process_pcap(user_directory) def process_pcap(self, pcap_file): '''Processes each packet in packet capture Input: - pcap_file: packet capture file to be processed Output: - This function doesn't return anything, but it creates a pcap file with the new IP/MAC addresses ''' packets = rdpcap(pcap_file) ind = 0 # Loop through each individual packet in the pcap file for p in packets: if p[IP].src == "178.248.225.226": # Write new pcap file new_filename = str(ind) + "outside.pcap" else: new_filename = str(ind) + "inside.pcap" ind += 1 wrpcap(new_filename, p) p = ProcessPacket()
true
923f7091e165c3f8a0a628e27db832bdd1b7ab21
Python
jzraiti/Coverage_Algorithm_Enviornmental_Sampling_Autonomous_Surface_Vehicle
/Project_Files/Jasons_Functions/trim_edges.py
UTF-8
3,205
3.109375
3
[]
no_license
#Jasons script for trimming edges import matplotlib.pyplot as plt # import sys # sys.path.append("/home/jasonraiti/Documents/GitHub/USC_REU/Project_Files/Jasons_Functions/") from skeleton_to_graph import * # graph = skeleton_to_graph(path) from open_or_show_image import * # image = open_image(path) , show_image(image) from locate_nodes import * # total_skeleton,node_locations,edge_locations,endpoint_locations,island_locations = locate_nodes(path) def trim_edges(path,weight_threshold): """takes in path to image and weight threshold to trim from :param path: path to image :type path: string :param weight_threshold: the threshold number of pixels and edge needs to be trimmed :type option: int :rtype: new_array = an array of just the points on retained edges , new_image = the complete image array including background area :return: edge and image arrays with trimmed edges """ graph = skeleton_to_graph(path) image = open_image(path) #start by opening the image, choose image in the function total_skeleton,node_locations,edge_locations,endpoint_locations,island_locations = locate_nodes(path) new_array= [] trimmed = [] graph = skeleton_to_graph(path) for (s,e) in graph.edges(): ps = graph[s][e]['pts'] start = [ ps[0,1],ps[0,0] ] end = [ ps[-1,1],ps[-1,0] ] if ( (start in endpoint_locations) or (end in endpoint_locations) ): # ------weight < theshold AND endpoints are not nodes # print('edge found') if graph[s][e]['weight'] < weight_threshold: #print('trim this one') trimmed.append(graph[s][e]['pts']) plt.plot(ps[:,1], ps[:,0], 'green') else: #print('nah leave em be') new_array.append(graph[s][e]['pts']) plt.plot(ps[:,1], ps[:,0], 'red') else: #print("no matches") new_array.append(graph[s][e]['pts']) plt.plot(ps[:,1], ps[:,0], 'red') plt.imshow(image, cmap='gray') #map the image to black and white, white representing the line # name = 'trimmed_' + str(path) # name = name.replace("/", "_") # name = name.replace(".", "_") # name = str(name) + '.png' # plt.savefig(name, format="png") plt.show() ''' THIS IS THE OLD WAY OF DOING IT # ------- make new "image array" that can be written using cv2 ----- black_image = np.zeros((image.shape[0],image.shape[1])) # get black background # ---------------- get trimmed skeleton new_image = black_image for edge in new_array: for point in edge: # print(point[0], point[1]) new_image[point[0]][point[1]] = 255 ''' #lets try doing this the opposite way and only take out pixels marked for being trimmed trimmed_image = image # get original image for edge in trimmed: for point in edge: trimmed_image[point[0]][point[1]] = 0 new_image = trimmed_image print("warning from trim_edges: new_array return value is no longer accurate") return new_array , new_image
true
a52eaf4bec2109785b15c32b97f6bbde875f8fa4
Python
roiei/algo
/leet_code/1652. Defuse the Bomb.py
UTF-8
934
3.203125
3
[]
no_license
import time from util.util_list import * from util.util_tree import * import copy import collections class Solution: def decrypt(self, code: [int], k: int) -> [int]: res = [] n = len(code) reversed = False if k < 0: code = code[::-1] k *= -1 reversed = True for i, num in enumerate(code): start = (i + 1)%n end = (start + k)%n if start > end: res += sum(code[start:] + code[:end]), else: res += sum(code[start:end]), return res if not reversed else res[::-1] stime = time.time() #print([12,10,16,13] == Solution().decrypt(code = [5,7,1,4], k = 3)) print([12,5,6,13] == Solution().decrypt(code = [2,4,9,3], k = -2)) print('elapse time: {} sec'.format(time.time() - stime)) # 2 4 9 3 # 3 9 4 2
true
8e6264e959113ac87e6928c2f8ffee467fe7aace
Python
yumendy/LeetCode
/Python/Next Greater Element I.py
UTF-8
547
3.34375
3
[]
no_license
class Solution(object): def nextGreaterElement(self, findNums, nums): """ :type findNums: List[int] :type nums: List[int] :rtype: List[int] """ self.nums = nums return map(self.next_num_in_nums, findNums) def next_num_in_nums(self, num): try: index = self.nums.index(num) + 1 for n in self.nums[index:]: if n > num: return n else: return -1 except: return -1
true
d953612de31d5b43e19ce926c26529997040681d
Python
A-Amani/gfkTasks
/Task3/Modelling/Model.py
UTF-8
4,192
2.78125
3
[]
no_license
import os from pathlib import Path import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier, LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import MultinomialNB from sklearn import metrics import pandas.core.series as pdSeries from loguru import logger from config import * class Model(object): def __init__(self, run_mode: str = ""): self.run_mode = run_mode if len(run_mode) > 0 else config["run_mode"] self.model_folder = config["model_folder"] self.model_selection = config["model_selection"] self.model_file_name = f"{self.model_folder}/model.pkl" self.final_feature_col = config['final_feature_col'] self.model = None if self.run_mode == RUN_MODE.PREDICT.value: self.prediction_col = config["prediction_col"] self.output_file_name = config["output_file_name"] logger.info(f"! do model {self.run_mode}, active model is {self.model_selection} !") def construct_preProcessing_pipline(self): descriptive_features_pipeline = Pipeline(steps= [ ('CountVectorizer', CountVectorizer()), ('Tfidf', TfidfTransformer()) ] ) preprocessing_pipeline = ColumnTransformer(transformers= [ ('preprocessing_pipeline',descriptive_features_pipeline, self.final_feature_col) ] ) return preprocessing_pipeline def construct_classifier_pipline(self): if self.model_selection == 'svm': classifier_pipline = SGDClassifier() elif self.model_selection == 'naive_bayes': classifier_pipline = MultinomialNB() elif self.model_selection == 'knn': classifier_pipline = KNeighborsClassifier() elif self.model_selection == 'logistic_regression': classifier_pipline = LogisticRegression() return classifier_pipline def construct_model_pipline(self, preprocessing_pipeline, classifier_pipline): pipe = Pipeline(steps= [ ('preprocessor', preprocessing_pipeline), ('classifier', classifier_pipline) ] ) return pipe def run(self, data): if self.run_mode == RUN_MODE.TRAIN.value: x_train, y_train, x_test, y_test = data pp = self.construct_preProcessing_pipline() clf = self.construct_classifier_pipline() pipe = self.construct_model_pipline(pp,clf) self.model = pipe.fit(x_train, y_train) Model.save_model(model=self.model, file_name=self.model_file_name) logger.info(f"! saved model: {self.model_selection} to {self.model_file_name} !") self.evaluate_model(x_test, y_test, self.model) if self.run_mode == RUN_MODE.PREDICT.value: self.model = Model.load_model(file_name=self.model_file_name) x = data y = self.model.predict(x) logger.info(f"predicted categories are: {y}") return y def evaluate_model(self, x_test: pdSeries.Series, y_test: pdSeries.Series, pipe:Pipeline): predicted = pipe.predict(x_test) logger.info("model accuracy is: %.3f \n" % pipe.score(x_test, y_test) ) logger.info(metrics.classification_report(y_test, predicted, target_names=y_test.unique())) @staticmethod def save_model(model, file_name:str): """ """ if file_name != "": with open(file_name, 'wb') as fp: pickle.dump(model, fp) @staticmethod def load_model(file_name: str): try: fn = os.path.join(Path(__file__).parents[1], file_name) with open(fn, 'rb') as fp: return pickle.load(fp) except FileNotFoundError: raise FileNotFoundError("! model doesn't exist! need to train first !")
true
fe94424473237809ce3c5f0be9a40181e219949e
Python
emplam27/Python-Algorithm
/SWE_Ploblems/D2_1979_단어퍼즐.py
UTF-8
918
2.734375
3
[]
no_license
import sys sys.stdin = open("input.txt", "r") T = int(input()) for t in range(1, T + 1): N, K = map(int, input().split()) board = [list(map(int, input().split())) for _ in range(N)] New_board = [[0] * N for _ in range(N)] cnt = 0 for i in range(N): sum_num = 0 for j in range(N): if board[i][j] == 1: sum_num += 1 if board[i][j] == 0: if sum_num == K: cnt += 1 sum_num = 0 if sum_num == K: cnt += 1 sum_num = 0 for i in range(N): sum_num = 0 for j in range(N): if board[j][i] == 1: sum_num += 1 if board[j][i] == 0: if sum_num == K: cnt += 1 sum_num = 0 if sum_num == K: cnt += 1 sum_num = 0 print('#%d' %t, cnt)
true
17fe94a87be4767a9513211760d44e4635c4252e
Python
dambac/NTU
/scripts/definitions/models/m_classic_xavier.py
UTF-8
2,289
2.859375
3
[]
no_license
import torch encoder_hidden_size = 2048 classifier_hidden_size = 2048 output_size = 2 class MClassicXavier(torch.nn.Module): @staticmethod def create(input_size): net: MClassicXavier = MClassicXavier(input_size) # initialization function, first checks the module type, # then applies the desired changes to the weights def init_normal(m): if type(m) == torch.nn.Linear: torch.nn.init.uniform_(m.weight) # use the modules apply function to recursively apply the initialization net.apply(init_normal) return net def __init__(self, input_size): super(MClassicXavier, self).__init__() """ Siamese Network """ self.siamese_linear1 = torch.nn.Linear(input_size, encoder_hidden_size) self.siamese_activation1 = torch.nn.LeakyReLU() self.siamese_linear2 = torch.nn.Linear(encoder_hidden_size, encoder_hidden_size) self.siamese_activation2 = torch.nn.LeakyReLU() self.siamese_linear3 = torch.nn.Linear(encoder_hidden_size, classifier_hidden_size) self.siamese_activation3 = torch.nn.LeakyReLU() """ Pooling both """ self.poller = torch.nn.MaxPool1d(2) """ Classifier """ self.class_linear1 = torch.nn.Linear(classifier_hidden_size, classifier_hidden_size) self.class_activation1 = torch.nn.LeakyReLU() self.class_linear2 = torch.nn.Linear(classifier_hidden_size, classifier_hidden_size) self.class_activation2 = torch.nn.LeakyReLU() self.class_linear3 = torch.nn.Linear(classifier_hidden_size, output_size) self.class_activation3 = torch.nn.LeakyReLU() def forward(self, X): """ X.shape = (batch, views, encoding_size) """ X = self.siamese_activation1(self.siamese_linear1(X)) X = self.siamese_activation2(self.siamese_linear2(X)) X = self.siamese_activation3(self.siamese_linear3(X)) X = X.permute(0, 2, 1) X = self.poller(X).squeeze(2) X = self.class_activation1(self.class_linear1(X)) X = self.class_activation2(self.class_linear2(X)) X = self.class_activation3(self.class_linear3(X)) return X
true
8c5696eadc00cc8e9053b0a9bb0a6406a6674e25
Python
shweta2425/ML-Python
/Week2/Array3.py
UTF-8
438
4.25
4
[]
no_license
# Write a Python program to get the number of occurrences of a specified element in an array. from Week2.Utilities import utility class Array3: # creating class obj obj = utility.User() # Accepts array from user arr1 = obj.accepts() def Count(self): num = int(input("enter ele to count")) cnt = self.arr1.count(num) print("\n Occurrence of", num, "is :", cnt) obj = Array3() obj.Count()
true
92c71e98d4cafea278ca94cf43f30c765987082c
Python
GuidoPaul/Deep-Learning-Nanodegree-Foundation
/intro-to-tensorflow/miniflow/nn.py
UTF-8
3,210
2.890625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: nn.py import numpy as np from sklearn.datasets import load_boston from sklearn.utils import shuffle, resample from miniflow import Input, Linear, Sigmoid, MSE, topological_sort, forward_pass, forward_and_backward, sgd_update # ---------------------------------------------- ''' x, y, z = Input(), Input(), Input() add = Add(x, y, z) mul = Mul(x, y, z) feed_dict = {x: 10, y: 20, z: 5} graph = topological_sort(feed_dict=feed_dict) output1 = forward_pass(add, graph) output2 = forward_pass(mul, graph) print("{} + {} + {} = {} (according to miniflow)".format( feed_dict[x], feed_dict[y], feed_dict[z], output1)) print("{} * {} * {} = {} (according to miniflow)".format( feed_dict[x], feed_dict[y], feed_dict[z], output2)) ''' # ---------------------------------------------- X, W, b = Input(), Input(), Input() f = Linear(X, W, b) g = Sigmoid(f) X_ = np.array([[-1., -2.], [-1, -2]]) W_ = np.array([[2., -3], [2., -3]]) b_ = np.array([-3., -5]) feed_dict = {X: X_, W: W_, b: b_} graph = topological_sort(feed_dict) forward_pass(graph) print(g.value) # ---------------------------------------------- y, a = Input(), Input() cost = MSE(y, a) y_ = np.array([1, 2, 3]) a_ = np.array([4.5, 5, 10]) feed_dict = {y: y_, a: a_} graph = topological_sort(feed_dict) forward_pass(graph) print(cost.value) # ---------------------------------------------- X, W, b = Input(), Input(), Input() y = Input() f = Linear(X, W, b) a = Sigmoid(f) cost = MSE(y, a) X_ = np.array([[-1., -2.], [-1, -2]]) W_ = np.array([[2.], [3.]]) b_ = np.array([-3.]) y_ = np.array([1, 2]) feed_dict = { X: X_, y: y_, W: W_, b: b_, } graph = topological_sort(feed_dict) forward_and_backward(graph) # return the gradients for each Input gradients = [t.gradients[t] for t in [X, y, W, b]] print(gradients) # ---------------------------------------------- # Load data data = load_boston() X_ = data['data'] y_ = data['target'] # Normalize data X_ = (X_ - np.mean(X_, axis=0)) / np.std(X_, axis=0) n_features = X_.shape[1] n_hidden = 10 W1_ = np.random.randn(n_features, n_hidden) b1_ = np.zeros(n_hidden) W2_ = np.random.randn(n_hidden, 1) b2_ = np.zeros(1) # Neural network X, y = Input(), Input() W1, b1 = Input(), Input() W2, b2 = Input(), Input() l1 = Linear(X, W1, b1) s1 = Sigmoid(l1) l2 = Linear(s1, W2, b2) cost = MSE(y, l2) feed_dict = {X: X_, y: y_, W1: W1_, b1: b1_, W2: W2_, b2: b2_} epochs = 1000 # Total number of examples m = X_.shape[0] batch_size = 11 steps_per_epoch = m // batch_size graph = topological_sort(feed_dict) trainables = [W1, b1, W2, b2] print("Total number of examples = {}".format(m)) # Step 4 for i in range(epochs): loss = 0 for j in range(steps_per_epoch): # Step 1 # Randomly sample a batch of examples X_batch, y_batch = resample(X_, y_, n_samples=batch_size) # Reset value of X and y Inputs X.value = X_batch y.value = y_batch # Step 2 forward_and_backward(graph) # Step 3 sgd_update(trainables) loss += graph[-1].value print("Epoch: {}, Loss: {:.3f}".format(i + 1, loss / steps_per_epoch))
true
24089e78e3040e37a8954861b3d4866eae0402d6
Python
jnech1997/hash-code
/main.py
UTF-8
4,452
2.984375
3
[]
no_license
import networkx as nx from submit import create_submit_file # HashMap key: streets, val: # of times hit by any path streetHits = {} carStarts = {} streetTimes = {} totalDuration = 0 def createGraph(filename): f = open(filename, "r") DG = nx.DiGraph() Lines = f.readlines() count = 0 numIntersections = 0 numStreets = 0 numCars = 0 bonus = 0 # Strips the newline character for line in Lines: count += 1 if count == 1: totalDuration, numIntersections, numStreets, numCars, bonus = line.split() elif (count <= 1 + int(numStreets)): startIntersect, endIntersect, streetName, streetTime = line.split() DG.add_edge(startIntersect, endIntersect) DG[startIntersect][endIntersect]['weight'] = int(streetTime) DG[startIntersect][endIntersect]['name'] = streetName streetTimes[streetName] = streetTime else: carInfo = line.split() numStreetsCarWantsToTravel = carInfo[0] path = carInfo[1:] for i in range(len(path)): street = path[i] if i > 0: if street in streetHits: streetHits[street] += 1 else: streetHits[street] = 1 else: if street in carStarts: carStarts[street] += 1 else: carStarts[street] = 1 return DG def main(filename): DG = createGraph(filename) sortedStreetHits = sorted(streetHits.items(), key=lambda v: v[1], reverse=True) mostHits = sortedStreetHits[0][1] sortedCarStarts = sorted(carStarts.items(), key=lambda v: v[1], reverse=True) mostStarts = sortedCarStarts[0][1] numNodes = DG.number_of_nodes() intersections = [] incomingStreets = [] orders = [] for n in DG: intersections.append(n) numIncomingIntersections = 0 orderList = [] intersectionMaxCarStarts = 0 intersectionMaxStreetHits = 0 intersectionMaxStreetTime = 0 for _, _, data in DG.in_edges(n, data=True): streetName = data['name'] if streetName in streetHits: incomingEdgeStreetHits = streetHits[streetName] else: incomingEdgeStreetHits = 0 if (incomingEdgeStreetHits > intersectionMaxStreetHits): intersectionMaxStreetHits = incomingEdgeStreetHits if streetName in carStarts: incomingEdgeCarStarts = carStarts[streetName] else: incomingEdgeCarStarts = 0 if (incomingEdgeCarStarts > intersectionMaxCarStarts): intersectionMaxCarStarts = incomingEdgeCarStarts incomingEdgeStreetTime = streetTimes[streetName] if (int(incomingEdgeStreetTime) > intersectionMaxStreetTime): intersectionMaxStreetTime = int(incomingEdgeStreetTime) for _, _, data in DG.in_edges(n, data=True): numIncomingIntersections += 1 duration = str(assignTimeVal(data['name'], intersectionMaxCarStarts, intersectionMaxStreetHits, intersectionMaxStreetTime)) orderList.append((data['name'], duration)) incomingStreets.append(numIncomingIntersections) orders.append(orderList) # create submission file create_submit_file(filename, numNodes, intersections, incomingStreets, orders) def assignTimeVal(streetName, maxCarStarts, maxStreetHits, maxStreetTime): if streetName in streetHits: hits = streetHits[streetName] else: hits = 0 if streetName in carStarts: starts = carStarts[streetName] else: starts = 0 if maxCarStarts == 0: maxCarStarts = 1000000000 if maxStreetHits == 0: maxStreetHits = 1000000000 time = streetTimes[streetName] startsRatio = float(starts)/float(maxCarStarts) hitsRatio = float(hits)/float(maxStreetHits) timeRatio = float(time)/float(maxStreetTime) duration = startsRatio * 0.2 + hitsRatio * 2 + timeRatio if (duration < 1): duration = 1 return int(duration) if __name__ == "__main__": filenames = ["exampleInput.txt", "byTheOcean.txt", "checkmate.txt", "dailyCommute.txt", "etoile.txt", "foreverJammed.txt"] for file in filenames: main(file)
true
e7136a53586ba4ee5022b86970bce3b835902dce
Python
melalex/NM2_RGR1
/bin/power_method/max_eigen_pair.py
UTF-8
880
2.546875
3
[]
no_license
import numpy as np import itertools def max_eigen_pair(matrix, eps, p, delta): dimension = len(matrix) y = np.ones(dimension).reshape(dimension, 1) lambda_next = np.full(dimension, 9.) z_next = y / np.linalg.norm(y) s = [i for i in range(dimension)] k = 0 for k in itertools.count(1): z_prev = z_next lambda_prev = np.copy(lambda_next) y = np.dot(matrix, z_prev) s_prev = s s = [index for index, value in enumerate(z_prev) if value > delta] s_inter = list(set(s_prev) & set(s)) lambda_next = y / z_prev if k % p == 0: z_next = y / np.linalg.norm(y) else: z_next = y if (np.absolute(lambda_next[s_inter] - lambda_prev[s_inter]) <= eps).all(): break return (np.sum(lambda_next[s])) / len(s), z_next / np.linalg.norm(z_next), k
true
19bdd0ce59e5e736a0bf4ed06ac70155b45d5a4c
Python
ZoranPandovski/al-go-rithms
/cryptography/steganography/python/steganography.py
UTF-8
4,403
2.71875
3
[ "CC0-1.0" ]
permissive
import getopt import math import os import struct import sys import wave def hide(sound_path, file_path, output_path, num_lsb): sound = wave.open(sound_path, "r") params = sound.getparams() num_channels = sound.getnchannels() sample_width = sound.getsampwidth() num_frames = sound.getnframes() num_samples = num_frames * num_channels max_bytes_to_hide = (num_samples * num_lsb) // 8 filesize = os.stat(file_path).st_size if filesize > max_bytes_to_hide: required_LSBs = math.ceil(filesize * 8 / num_samples) raise ValueError("Input file too large to hide, " "requires {} LSBs, using {}" .format(required_LSBs, num_lsb)) print("Using {} B out of {} B".format(filesize, max_bytes_to_hide)) print(sample_width) if sample_width == 1: # samples are unsigned 8-bit integers fmt = "{}B".format(num_samples) mask = (1 << 8) - (1 << num_lsb) min_sample = -(1 << 8) elif sample_width == 2: # samples are signed 16-bit integers fmt = "{}h".format(num_samples) mask = (1 << 15) - (1 << num_lsb) min_sample = -(1 << 15) else: raise ValueError("File has an unsupported bit-depth") raw_data = list(struct.unpack(fmt, sound.readframes(num_frames))) sound.close() input_data = memoryview(open(file_path, "rb").read()) data_index = 0 sound_index = 0 values = [] buffer = 0 buffer_length = 0 done = False print(input_data[1]) while not done: while buffer_length < num_lsb and data_index // 8 < len(input_data): buffer += (input_data[data_index // 8] >> (data_index % 8) ) << buffer_length bits_added = 8 - (data_index % 8) buffer_length += bits_added data_index += bits_added current_data = buffer % (1 << num_lsb) buffer >>= num_lsb buffer_length -= num_lsb while (sound_index < len(raw_data) and raw_data[sound_index] == min_sample): values.append(struct.pack(fmt[-1], raw_data[sound_index])) sound_index += 1 if sound_index < len(raw_data): current_sample = raw_data[sound_index] sound_index += 1 sign = 1 if current_sample < 0: current_sample = -current_sample sign = -1 altered_sample = sign * ((current_sample & mask) | current_data) values.append(struct.pack(fmt[-1], altered_sample)) if data_index // 8 >= len(input_data) and buffer_length <= 0: done = True while sound_index < len(raw_data): values.append(struct.pack(fmt[-1], raw_data[sound_index])) sound_index += 1 sound_steg = wave.open(output_path, "w") sound_steg.setparams(params) sound_steg.writeframes(b"".join(values)) sound_steg.close() def recover(sound_path, output_path, num_lsb, bytes_to_recover): sound = wave.open(sound_path, "r") num_channels = sound.getnchannels() sample_width = sound.getsampwidth() num_frames = sound.getnframes() num_samples = num_frames * num_channels if (sample_width == 1): # samples 8 bits fmt = "{}B".format(num_samples) min_sample = -(1 << 8) elif (sample_width == 2): # samples 16 bits fmt = "{}h".format(num_samples) min_sample = -(1 << 15) else: raise ValueError("File has an unsupported bit-depth") raw_data = list(struct.unpack(fmt, sound.readframes(num_frames))) mask = (1 << num_lsb) - 1 output_file = open(output_path, "wb+") data = bytearray() sound_index = 0 buffer = 0 buffer_length = 0 while (bytes_to_recover > 0): next_sample = raw_data[sound_index] if (next_sample != min_sample): buffer += (abs(next_sample) & mask) << buffer_length buffer_length += num_lsb sound_index += 1 while (buffer_length >= 8 and bytes_to_recover > 0): current_data = buffer % (1 << 8) buffer >>= 8 buffer_length -= 8 data += struct.pack('1B', current_data) bytes_to_recover -= 1 output_file.write(bytes(data)) output_file.close()
true
10f2932c8db894ab19afcb847f455d69de9b0e40
Python
welcomeying/movie_trailer_website
/entertainment_center.py
UTF-8
1,154
2.9375
3
[]
no_license
import media import fresh_tomatoes # My favorite movies despicable_me = media.Movie("Despicable Me", "Despicable masters and his Minions", "https://upload.wikimedia.org/wikipedia/en/thumb/d/db/Despicable_Me_Poster.jpg/220px-Despicable_Me_Poster.jpg", "https://www.youtube.com/watch?v=zzCZ1W_CUoI") despicable_me_2 = media.Movie("Despicable Me 2", "Second story of despicable masters and his Minions", "https://upload.wikimedia.org/wikipedia/en/2/29/Despicable_Me_2_poster.jpg", "https://www.youtube.com/watch?v=yM9sKpQOuEw") despicable_me_3 = media.Movie("Despicable Me 3", "Third story of despicable masters and his Minions", "https://upload.wikimedia.org/wikipedia/en/9/91/Despicable_Me_3_%282017%29_Teaser_Poster.jpg", "https://www.youtube.com/watch?v=6DBi41reeF0") # List of movies movies = [despicable_me, despicable_me_2, despicable_me_3] fresh_tomatoes.open_movies_page(movies)
true
992239bdc29910de44bedbaf400ab9783e1752be
Python
PeizeSun/OneNet
/tests/layers/test_roi_align.py
UTF-8
5,389
2.625
3
[ "MIT", "Apache-2.0" ]
permissive
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import numpy as np import unittest import cv2 import torch from fvcore.common.benchmark import benchmark from detectron2.layers.roi_align import ROIAlign class ROIAlignTest(unittest.TestCase): def test_forward_output(self): input = np.arange(25).reshape(5, 5).astype("float32") """ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 """ output = self._simple_roialign(input, [1, 1, 3, 3], (4, 4), aligned=False) output_correct = self._simple_roialign(input, [1, 1, 3, 3], (4, 4), aligned=True) # without correction: old_results = [ [7.5, 8, 8.5, 9], [10, 10.5, 11, 11.5], [12.5, 13, 13.5, 14], [15, 15.5, 16, 16.5], ] # with 0.5 correction: correct_results = [ [4.5, 5.0, 5.5, 6.0], [7.0, 7.5, 8.0, 8.5], [9.5, 10.0, 10.5, 11.0], [12.0, 12.5, 13.0, 13.5], ] # This is an upsampled version of [[6, 7], [11, 12]] self.assertTrue(np.allclose(output.flatten(), np.asarray(old_results).flatten())) self.assertTrue( np.allclose(output_correct.flatten(), np.asarray(correct_results).flatten()) ) # Also see similar issues in tensorflow at # https://github.com/tensorflow/tensorflow/issues/26278 def test_resize(self): H, W = 30, 30 input = np.random.rand(H, W).astype("float32") * 100 box = [10, 10, 20, 20] output = self._simple_roialign(input, box, (5, 5), aligned=True) input2x = cv2.resize(input, (W // 2, H // 2), interpolation=cv2.INTER_LINEAR) box2x = [x / 2 for x in box] output2x = self._simple_roialign(input2x, box2x, (5, 5), aligned=True) diff = np.abs(output2x - output) self.assertTrue(diff.max() < 1e-4) def _simple_roialign(self, img, box, resolution, aligned=True): """ RoiAlign with scale 1.0 and 0 sample ratio. """ if isinstance(resolution, int): resolution = (resolution, resolution) op = ROIAlign(resolution, 1.0, 0, aligned=aligned) input = torch.from_numpy(img[None, None, :, :].astype("float32")) rois = [0] + list(box) rois = torch.from_numpy(np.asarray(rois)[None, :].astype("float32")) output = op.forward(input, rois) if torch.cuda.is_available(): output_cuda = op.forward(input.cuda(), rois.cuda()).cpu() self.assertTrue(torch.allclose(output, output_cuda)) return output[0, 0] def _simple_roialign_with_grad(self, img, box, resolution, device): if isinstance(resolution, int): resolution = (resolution, resolution) op = ROIAlign(resolution, 1.0, 0, aligned=True) input = torch.from_numpy(img[None, None, :, :].astype("float32")) rois = [0] + list(box) rois = torch.from_numpy(np.asarray(rois)[None, :].astype("float32")) input = input.to(device=device) rois = rois.to(device=device) input.requires_grad = True output = op.forward(input, rois) return input, output def test_empty_box(self): img = np.random.rand(5, 5) box = [3, 4, 5, 4] o = self._simple_roialign(img, box, 7) self.assertTrue(o.shape == (7, 7)) self.assertTrue((o == 0).all()) for dev in ["cpu"] + ["cuda"] if torch.cuda.is_available() else []: input, output = self._simple_roialign_with_grad(img, box, 7, torch.device(dev)) output.sum().backward() self.assertTrue(torch.allclose(input.grad, torch.zeros_like(input))) def test_empty_batch(self): input = torch.zeros(0, 3, 10, 10, dtype=torch.float32) rois = torch.zeros(0, 5, dtype=torch.float32) op = ROIAlign((7, 7), 1.0, 0, aligned=True) output = op.forward(input, rois) self.assertTrue(output.shape == (0, 3, 7, 7)) def benchmark_roi_align(): from detectron2 import _C def random_boxes(mean_box, stdev, N, maxsize): ret = torch.rand(N, 4) * stdev + torch.tensor(mean_box, dtype=torch.float) ret.clamp_(min=0, max=maxsize) return ret def func(N, C, H, W, nboxes_per_img): input = torch.rand(N, C, H, W) boxes = [] batch_idx = [] for k in range(N): b = random_boxes([80, 80, 130, 130], 24, nboxes_per_img, H) # try smaller boxes: # b = random_boxes([100, 100, 110, 110], 4, nboxes_per_img, H) boxes.append(b) batch_idx.append(torch.zeros(nboxes_per_img, 1, dtype=torch.float32) + k) boxes = torch.cat(boxes, axis=0) batch_idx = torch.cat(batch_idx, axis=0) boxes = torch.cat([batch_idx, boxes], axis=1) input = input.cuda() boxes = boxes.cuda() def bench(): _C.roi_align_forward(input, boxes, 1.0, 7, 7, 0, True) torch.cuda.synchronize() return bench args = [dict(N=2, C=512, H=256, W=256, nboxes_per_img=500)] benchmark(func, "cuda_roialign", args, num_iters=20, warmup_iters=1) if __name__ == "__main__": if torch.cuda.is_available(): benchmark_roi_align() unittest.main()
true
44321594545280581ac469e900190f0bee5d27e3
Python
phoenixperry/Python_101_class
/day18/scratch_c.py
UTF-8
175
3.453125
3
[]
no_license
#empty dictionary letter_count = {} letter_count ["one"] = 2 print(letter_count.get("one",0)+5) # letter_count[letter] = letter_count.get(letter, 0)+1 print(letter_count)
true
1c8a9a0a14213ee1a6d318d56e1d64e492293f3c
Python
ajross/AirMetBot
/Weather.py
UTF-8
787
2.875
3
[]
no_license
from config import CHECKWX_API_KEY import requests class Weather: 'Class for providing weather reports, and caching them for performance.' def __init__(self): self.__apiKey = CHECKWX_API_KEY def __getRemoteWeather(self, icaoCode): headers = {'X-API-Key': self.__apiKey} resp = requests.get("https://api.checkwx.com/metar/" + icaoCode, headers=headers) if(resp.status_code == requests.codes.ok): weather = resp.json()['data'][0] elif(resp.status_code == requests.codes.notfound): weather = "Station " + icaoCode + " not found" else: weather = "Weather unavailable for " + icaoCode return weather def getMetar(self, icaoCode): return self.__getRemoteWeather(icaoCode)
true
9d4de14c9de61be007f9295cb6f553975357a580
Python
martinrein/BarberShopTracker
/registration.py
UTF-8
27,789
2.796875
3
[]
no_license
from tkinter import * from tkinter import messagebox import json import os import ast class Registration(Tk): def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) self.initial_values() self.setup_window() def initial_values(self): """ """ self.barber_choice = StringVar() self.date_choice = StringVar() # Set Variables for Questionnaire Answers self.q1_value = StringVar() self.q2_value = StringVar() self.q3_value = StringVar() self.q4_value = StringVar() self.q5_value = StringVar() self.q6_value = StringVar() self.q7_value = StringVar() self.q8_value = StringVar() self.q9_value = StringVar() self.q10_value = StringVar() def setup_window(self): """ This function creates the initial widgets for the program. """ # Create Window self.resizable(width=False, height=False) self.geometry('550x650') self.title("CEE Barber Shop") # Create Frames self.main_frame = Frame(self) label_header = Label(self.main_frame, text="Registration Form", width=20,font=("bold",30)) self.registration_setup() # Place Frame self.main_frame.place(height=650, width=550) label_header.place(relx=0.5, rely=0.05, anchor=CENTER) # Create Button self.nextButton = Button(self.main_frame, text="Next >>", width=10, command = self.confirm_registration) self.nextButton.place(relx=0.5, rely=0.96, anchor=CENTER) def registration_setup(self): # Create Frame for Registration Form self.frame_register_form = LabelFrame(self.main_frame, text = " CEE Barber Shop ", \ pady=50,labelanchor=N,bd=5,font=("bold",20), relief=RIDGE) # Create Registration Label Widgets label_1 = Label(self.frame_register_form, text="Name", width=10,font=("bold",12)) label_2 = Label(self.frame_register_form, text="Contact No.", width=10,font=("bold",12)) label_3 = Label(self.frame_register_form, text="Email", width=10,font=("bold",12)) label_4 = Label(self.frame_register_form, text="Address", width=10,font=("bold",12)) label_5 = Label(self.frame_register_form, text="Barber", width=10,font=("bold",12)) label_6 = Label(self.frame_register_form, text="Date", width=10,font=("bold",12)) label_7 = Label(self.frame_register_form, text="Time", width=10,font=("bold",12)) # Create Registration Entry Widgets self.entry_1 = Entry(self.frame_register_form, width=30) self.entry_2 = Entry(self.frame_register_form, width=30) self.entry_3 = Entry(self.frame_register_form, width=30) self.entry_4 = Entry(self.frame_register_form, width=30) # Get List of Barbers from text file 'barbers.txt' and create Barber Dropdown Menu with open('barbers.txt', 'r') as f: barbers_list = json.loads(f.read()) barbers_list.insert(0,"-- Select a Barber --") self.barber_choice.set(barbers_list[0]) barber_dropdown = OptionMenu(self.frame_register_form, self.barber_choice, *barbers_list) # Get List of Available Dates from text file 'open_dates.txt' and create Date Dropdown Menu with open('open_dates.txt', 'r') as f: date_list = json.loads(f.read()) date_list.insert(0,"-- Select from Available Dates --") self.date_choice.set(date_list[0]) date_dropdown = OptionMenu(self.frame_register_form, self.date_choice, *date_list) timeButton = Button(self.frame_register_form, text="-- Select an Appointment --", width=21, command = self.select_time) # Place Widgets on the Frame self.frame_register_form.pack(fill="both", expand=True,padx=20, pady=60) label_1.place(relx=0.05, rely=-0.05) label_2.place(relx=0.09, rely=0.05) label_3.place(relx=0.05, rely=0.15) label_4.place(relx=0.07, rely=0.25) label_5.place(relx=0.06, rely=0.35) label_6.place(relx=0.05, rely=0.45) label_7.place(relx=0.05, rely=0.55) self.entry_1.place(relx=0.6, rely=-0.025, anchor=CENTER) self.entry_2.place(relx=0.6, rely=0.075, anchor=CENTER) self.entry_3.place(relx=0.6, rely=0.175, anchor=CENTER) self.entry_4.place(relx=0.6, rely=0.275, anchor=CENTER) barber_dropdown.place(relx=0.315, rely=0.345) date_dropdown.place(relx=0.315, rely=0.445) timeButton.place(relx=0.51, rely=0.58, anchor=CENTER) def select_time(self): """ This function asks the user to select a time slot to schedule their appointment. """ if (str(self.barber_choice.get()) != "-- Select a Barber --") & \ (str(self.date_choice.get()) != "-- Select from Available Dates --"): self.time_window = Toplevel() self.time_window.geometry('250x550') self.time_window.title('Select an Appointment') # Create Schedule File if the file does not exist yet schedule_file_name = self.date_choice.get() + ' - ' + self.barber_choice.get() + '.txt' if (os.path.exists('./' + schedule_file_name)) == False: schedule_dict = {"10:00 AM - 10:30 AM":"","10:30 AM - 11:00 AM":"",\ "11:00 AM - 11:30 AM":"","11:30 AM - 12:00 PM":"","12:00 PM - 12:30 PM":"",\ "12:30 PM - 1:00 PM":"","1:00 PM - 1:30 PM":"","1:30 PM - 2:00 PM":"",\ "2:00 PM - 2:30 PM":"","2:30 PM - 3:00 PM":"","3:00 PM - 3:30 PM":"",\ "3:30 PM - 4:00 PM":"","4:00 PM - 4:30 PM":"","4:30 PM - 5:00 PM":"",\ "5:00 PM - 5:30 PM":"","5:30 PM - 6:00 PM":"","6:00 PM - 6:30 PM":"",\ "6:30 PM - 7:00 PM":""} with open(schedule_file_name, 'w') as file: file.write(json.dumps(schedule_dict)) # Read the file and place on a variable file_schedule = open(schedule_file_name, 'r') sched_contents = file_schedule.read() schedule_dict = ast.literal_eval(sched_contents) file_schedule.close() # Create Buttons for available slots and slots taken if schedule_dict['10:00 AM - 10:30 AM'] == "": button_1000am = Button(self.time_window, text="10:00 AM - 10:30 AM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1000am)) button_1000am.place(relx=0.5, rely=0.1, anchor=CENTER) else: red_1000am = Button(self.time_window, text="10:00 AM - 10:30 AM",height=1,width=20,\ fg='red', command = self.time_taken) red_1000am.place(anchor="c", relx=0.5, rely=0.1) if schedule_dict['10:30 AM - 11:00 AM'] == "": button_1030am = Button(self.time_window, text="10:30 AM - 11:00 AM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1030am)) button_1030am.place(relx=0.5, rely=0.15, anchor=CENTER) else: red_1030am = Button(self.time_window, text="10:30 AM - 11:00 AM",height=1,width=20,\ fg='red', command = self.time_taken) red_1030am.place(anchor="c", relx=0.5, rely=0.15) if schedule_dict['11:00 AM - 11:30 AM'] == "": button_1100am = Button(self.time_window, text="11:00 AM - 11:30 AM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1100am)) button_1100am.place(relx=0.5, rely=0.2, anchor=CENTER) else: red_1100am = Button(self.time_window, text="11:00 AM - 11:30 AM",height=1,width=20,\ fg='red', command = self.time_taken) red_1100am.place(anchor="c", relx=0.5, rely=0.2) if schedule_dict['11:30 AM - 12:00 PM'] == "": button_1130am = Button(self.time_window, text="11:30 AM - 12:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1130am)) button_1130am.place(relx=0.5, rely=0.25, anchor=CENTER) else: red_1130am = Button(self.time_window, text="11:30 AM - 12:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_1130am.place(anchor="c", relx=0.5, rely=0.25) if schedule_dict['12:00 PM - 12:30 PM'] == "": button_1200pm = Button(self.time_window, text="12:00 PM - 12:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1200pm)) button_1200pm.place(relx=0.5, rely=0.3, anchor=CENTER) else: red_1200pm = Button(self.time_window, text="12:00 PM - 12:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_1200pm.place(anchor="c", relx=0.5, rely=0.3) if schedule_dict['12:30 PM - 1:00 PM'] == "": button_1230pm = Button(self.time_window, text="12:30 PM - 1:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_1230pm)) button_1230pm.place(relx=0.5, rely=0.35, anchor=CENTER) else: red_1230pm = Button(self.time_window, text="12:30 PM - 1:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_1230pm.place(anchor="c", relx=0.5, rely=0.35) if schedule_dict['1:00 PM - 1:30 PM'] == "": button_100pm = Button(self.time_window, text="1:00 PM - 1:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_100pm)) button_100pm.place(relx=0.5, rely=0.4, anchor=CENTER) else: red_100pm = Button(self.time_window, text="1:00 PM - 1:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_100pm.place(anchor="c", relx=0.5, rely=0.4) if schedule_dict['1:30 PM - 2:00 PM'] == "": button_130pm = Button(self.time_window, text="1:30 PM - 2:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_130pm)) button_130pm.place(relx=0.5, rely=0.45, anchor=CENTER) else: red_130pm = Button(self.time_window, text="1:30 PM - 2:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_130pm.place(anchor="c", relx=0.5, rely=0.45) if schedule_dict['2:00 PM - 2:30 PM'] == "": button_200pm = Button(self.time_window, text="2:00 PM - 2:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_200pm)) button_200pm.place(relx=0.5, rely=0.5, anchor=CENTER) else: red_200pm = Button(self.time_window, text="2:00 PM - 2:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_200pm.place(anchor="c", relx=0.5, rely=0.5) if schedule_dict['2:30 PM - 3:00 PM'] == "": button_230pm = Button(self.time_window, text="2:30 PM - 3:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_230pm)) button_230pm.place(relx=0.5, rely=0.55, anchor=CENTER) else: red_230pm = Button(self.time_window, text="2:30 PM - 3:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_230pm.place(anchor="c", relx=0.5, rely=0.55) if schedule_dict['3:00 PM - 3:30 PM'] == "": button_300pm = Button(self.time_window, text="3:00 PM - 3:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_300pm)) button_300pm.place(relx=0.5, rely=0.6, anchor=CENTER) else: red_300pm = Button(self.time_window, text="3:00 PM - 3:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_300pm.place(anchor="c", relx=0.5, rely=0.6) if schedule_dict['3:30 PM - 4:00 PM'] == "": button_330pm = Button(self.time_window, text="3:30 PM - 4:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_330pm)) button_330pm.place(relx=0.5, rely=0.65, anchor=CENTER) else: red_330pm = Button(self.time_window, text="3:30 PM - 4:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_330pm.place(anchor="c", relx=0.5, rely=0.65) if schedule_dict['4:00 PM - 4:30 PM'] == "": button_400pm = Button(self.time_window, text="4:00 PM - 4:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_400pm)) button_400pm.place(relx=0.5, rely=0.7, anchor=CENTER) else: red_400pm = Button(self.time_window, text="4:00 PM - 4:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_400pm.place(anchor="c", relx=0.5, rely=0.7) if schedule_dict['4:30 PM - 5:00 PM'] == "": button_430pm = Button(self.time_window, text="4:30 PM - 5:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_430pm)) button_430pm.place(relx=0.5, rely=0.75, anchor=CENTER) else: red_430pm = Button(self.time_window, text="4:30 PM - 5:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_430pm.place(anchor="c", relx=0.5, rely=0.75) if schedule_dict['5:00 PM - 5:30 PM'] == "": button_500pm = Button(self.time_window, text="5:00 PM - 5:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_500pm)) button_500pm.place(relx=0.5, rely=0.8, anchor=CENTER) else: red_500pm = Button(self.time_window, text="5:00 PM - 5:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_500pm.place(anchor="c", relx=0.5, rely=0.8) if schedule_dict['5:30 PM - 6:00 PM'] == "": button_530pm = Button(self.time_window, text="5:30 PM - 6:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_530pm)) button_530pm.place(relx=0.5, rely=0.85, anchor=CENTER) else: red_530pm = Button(self.time_window, text="5:30 PM - 6:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_530pm.place(anchor="c", relx=0.5, rely=0.85) if schedule_dict['6:00 PM - 6:30 PM'] == "": button_600pm = Button(self.time_window, text="6:00 PM - 6:30 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_600pm)) button_600pm.place(relx=0.5, rely=0.9, anchor=CENTER) else: red_600pm = Button(self.time_window, text="6:00 PM - 6:30 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_600pm.place(anchor="c", relx=0.5, rely=0.9) if schedule_dict['6:30 PM - 7:00 PM'] == "": button_630pm = Button(self.time_window, text="6:30 PM - 7:00 PM",height=1,width=20,\ fg="green", command = lambda: self.submit_time(button_630pm)) button_630pm.place(relx=0.5, rely=0.95, anchor=CENTER) else: red_630pm = Button(self.time_window, text="6:30 PM - 7:00 PM",height=1,width=20,\ fg='red', command = self.time_taken) red_630pm.place(anchor="c", relx=0.5, rely=0.95) else: messagebox.showerror("Invalid","Please select a Barber and Date") def submit_time(self, button): """ This function asks the user to confirm their time slot choice. """ self.timeslot_str = button["text"] selected_time = messagebox.askokcancel("Confirm Time Slot","You selected "+ \ self.timeslot_str +".\n\nDo you want to schedule this time slot?") # Display the selected time slot on the main window if selected_time == 1: self.label_time = Label(self.main_frame, text="> Selected Time: " + self.timeslot_str, width=30,font=("bold",12)) self.label_time.place(relx=0.3, rely=0.6) self.time_window.destroy() def time_taken(self): """ This function outputs an error message. It would ask the user to select another time slot. """ messagebox.showerror("Slot Taken", "This time slot has been taken. Please select another time slot.") def confirm_registration(self): """ This function asks the user to view and confirm their inputs. If the user confirms, the questionnaire form would appear. """ confirmation = messagebox.askokcancel("Confirm Registration","Name: " + self.entry_1.get() + \ "\nContact No.: " + self.entry_2.get() + "\nEmail: " + self.entry_3.get() + "\nAddress: " + \ self.entry_4.get() + "\nBarber: " + self.barber_choice.get() + "\nDate: " + \ self.date_choice.get() + "\nTime: " + self.timeslot_str) if confirmation == 1: self.questionnaire() def questionnaire(self): """ This function creates and display a questionnaire form. The form consists 10 questions that will be answered by using radiobuttons of 'Yes' and 'No'. """ # Create Blank Frame self.questionnaire_frame = Frame(width=500, height=475) self.questionnaire_frame.place(in_=self.main_frame, anchor="c", relx=.5, rely=.52) # Remove unnecessary Widget self.nextButton.destroy() # Create Label Widgets label_header = Label(self.main_frame, text="Questionnaire", width=20,font=("bold",30)) label_header.place(relx=0.5, rely=0.05, anchor=CENTER) label_yes = Label(self.questionnaire_frame, text="YES", width=3,font=("arial bold",12)) label_yes.place(relx=0.795, rely=0) label_no = Label(self.questionnaire_frame, text="NO", width=3,font=("arial bold",12)) label_no.place(relx=0.895, rely=0) label_ifyes_1 = Label(self.questionnaire_frame, text="If YES please state here: ", width=17,font=("bold",12)) label_ifyes_1.place(relx=0.055, rely=0.52) label_ifyes_2 = Label(self.questionnaire_frame, text="If YES please state here: ", width=17,font=("bold",12)) label_ifyes_2.place(relx=0.055, rely=0.64) # Create Question Label Widgets q1 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="1. Have you been experiencing any colds lately?") q2 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="2. Have you had a fever lately?") q3 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="3. Have you been experiencing any cough lately?") q4 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="4. Have you been experiencing any shortness of breath\n lately?") q5 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="5. Have you been experiencing any sore throat lately?") q6 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="6. Do you have any case of asthma or any other\n disease?") q7 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="7. In the past 30 days have you been to any other\n country?") q8 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="8. Do you have any senior citizens at home? ") q9 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="9. Do you work in any healthcare organization?") q10 = Label(self.questionnaire_frame, width=40, font=("bold",12), anchor=W, justify=LEFT,\ text="10. Do you agree to follow the rules and regulations\n regarding COVID-19 safety and precautions?") # Create Question Entry Widgets self.q6_entry = Entry(self.questionnaire_frame, width=19) self.q7_entry = Entry(self.questionnaire_frame, width=19) # Create Yes or No Radio Buttons Radiobutton(self.questionnaire_frame, variable = self.q1_value, value = "YES").place(relx=0.8, rely=0.048) Radiobutton(self.questionnaire_frame, variable = self.q1_value, value = "NO").place(relx=0.9, rely=0.048) self.q1_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q2_value, value = "YES").place(relx=0.8, rely=0.125) Radiobutton(self.questionnaire_frame, variable = self.q2_value, value = "NO").place(relx=0.9, rely=0.125) self.q2_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q3_value, value = "YES").place(relx=0.8, rely=0.207) Radiobutton(self.questionnaire_frame, variable = self.q3_value, value = "NO").place(relx=0.9, rely=0.207) self.q3_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q4_value, value = "YES").place(relx=0.8, rely=0.288) Radiobutton(self.questionnaire_frame, variable = self.q4_value, value = "NO").place(relx=0.9, rely=0.288) self.q4_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q5_value, value = "YES").place(relx=0.8, rely=0.368) Radiobutton(self.questionnaire_frame, variable = self.q5_value, value = "NO").place(relx=0.9, rely=0.368) self.q5_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q6_value, value = "YES").place(relx=0.8, rely=0.447) Radiobutton(self.questionnaire_frame, variable = self.q6_value, value = "NO").place(relx=0.9, rely=0.447) self.q6_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q7_value, value = "YES").place(relx=0.8, rely=0.57) Radiobutton(self.questionnaire_frame, variable = self.q7_value, value = "NO").place(relx=0.9, rely=0.57) self.q7_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q8_value, value = "YES").place(relx=0.8, rely=0.685) Radiobutton(self.questionnaire_frame, variable = self.q8_value, value = "NO").place(relx=0.9, rely=0.685) self.q8_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q9_value, value = "YES").place(relx=0.8, rely=0.765) Radiobutton(self.questionnaire_frame, variable = self.q9_value, value = "NO").place(relx=0.9, rely=0.765) self.q9_value.set(0) Radiobutton(self.questionnaire_frame, variable = self.q10_value, value = "YES").place(relx=0.8, rely=0.85) Radiobutton(self.questionnaire_frame, variable = self.q10_value, value = "NO").place(relx=0.9, rely=0.85) self.q10_value.set(0) # Create Submit Button submitButton = Button(self.main_frame, text="Submit", width=10, command = self.submit_registration) # Place Questionnaire Widgets q1.place(relx=0.01, rely=0.05) q2.place(relx=0.01, rely=0.13) q3.place(relx=0.01, rely=0.21) q4.place(relx=0.01, rely=0.29) q5.place(relx=0.01, rely=0.37) q6.place(relx=0.01, rely=0.45) q7.place(relx=0.01, rely=0.57) q8.place(relx=0.01, rely=0.69) q9.place(relx=0.01, rely=0.77) q10.place(relx=0.01, rely=0.85) self.q6_entry.place(relx=0.58, rely=0.541, anchor=CENTER) self.q7_entry.place(relx=0.58, rely=0.661, anchor=CENTER) submitButton.place(relx=0.5, rely=0.95, anchor=CENTER) def get_customer(self): """ This function gets all inputs from the registration form. Then it calls a function to save these information into a text file. """ customer = 'Name: ' + self.entry_1.get() + '\nContact No.: ' + self.entry_2.get() + '\nEmail: ' + \ self.entry_3.get() + '\nAddress: ' + self.entry_4.get() + '\nBarber: ' + \ self.barber_choice.get() + '\nDate: ' + self.date_choice.get() + '\nTime: ' + \ self.timeslot_str self.save_to_file(customer) def get_question(self): """ This function gets the radiobutton answers from the questionnaire form. Then it calls a function to save these information into a text file. """ answers = '\nQuestion 1-5: ' + str(self.q1_value.get()) + ', ' + str(self.q2_value.get()) + ', ' + \ str(self.q3_value.get()) + ', ' + str(self.q4_value.get()) + ', ' + str(self.q5_value.get()) + \ '\nQuestion 6-10: ' + str(self.q6_value.get()) + ', ' + str(self.q7_value.get()) + ', ' + \ str(self.q8_value.get()) + ', ' + str(self.q9_value.get()) + ', ' + str(self.q10_value.get()) self.save_to_file(answers) def get_question_stated(self): """ This function gets the answer from question 6 and 7 from the questionnaire form. Then it calls a function to save these information into a text file. """ stated = '\nQuestion 6 Stated: ' + self.q6_entry.get() + '\nQuestion 7 Stated: ' + self.q7_entry.get() + '\n\n' self.save_to_file(stated) def save_to_file(self, info): """ This function saves the registered user's information into a text file. """ text_file = open("registered_users.txt", 'a') text_file.write(info) text_file.close() def submit_registration(self): """ This function asks the user to confirm their registration. If the response is 'OK', it saves all inputs of the user into a text file. Then it automatically exits the program. """ response = messagebox.askokcancel("Confirm Registration","Do you want to submit your registration?") if response == 1: self.get_customer() self.get_question() self.get_question_stated() # Read the file and place on a variable schedule_file_name = self.date_choice.get() + ' - ' + self.barber_choice.get() + '.txt' file_schedule = open(schedule_file_name, 'r') sched_contents = file_schedule.read() schedule_dict = ast.literal_eval(sched_contents) file_schedule.close() # Places the selected time slot into the file schedule_dict[self.timeslot_str] = self.entry_1.get() + ' - ' + self.entry_2.get() with open(schedule_file_name, 'w') as file: file.write(json.dumps(schedule_dict)) self.quit() app = Registration() app.mainloop()
true
ef85149740680a0067bdb0d88c5407b2e3d4026e
Python
gil9red/SimplePyScripts
/get_geolocation.py
UTF-8
1,393
2.59375
3
[ "CC-BY-4.0" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "ipetrash" import json from urllib.request import urlopen def get_geolocation() -> dict: # SOURCE: https://github.com/Pure-L0G1C/FleX/blob/da8f30f9204a65df57063ed74b3e79a2a79a7bfc/payload/modules/geo.py location = { "Ip": None, "Country": None, "City": None, "State": None, "Zipcode": None, "Timezone": None, "Latitude": None, "Longitude": None, "GoogleMapsLink": None, } try: rs = urlopen("http://ip-api.com/json").read() data = json.loads(rs, encoding="utf-8") latitude = data["lat"] longitude = data["lon"] location["Ip"] = data["query"] location["Country"] = data["country"] location["City"] = data["city"] location["State"] = data["regionName"] location["Zipcode"] = data["zip"] location["Timezone"] = data["timezone"] location["Latitude"] = latitude location["Longitude"] = longitude # SOURCE: https://github.com/maldevel/IPGeoLocation/blob/master/core/IpGeoLocation.py#L97 link = f"http://www.google.com/maps/place/{latitude},{longitude}/@{latitude},{longitude},16z" location["GoogleMapsLink"] = link except: pass return location if __name__ == "__main__": print(get_geolocation())
true
08b121438849a4abd88d762d16b037fc14437a49
Python
priyankstilt/flask-token-validation-with-compression-boilerplate
/models/authentication/v1/token_validation.py
UTF-8
1,654
3.015625
3
[]
no_license
''' Class to handle the basic authentication token matching ''' from flask import g, jsonify from flask_httpauth import HTTPBasicAuth from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) class TokenValidator(object): ''' Class using basic http authentication of flask to secure the end point ''' SECRET_KEY = 'This is test' @staticmethod def generate_auth_object(): ''' Return the basic authentication object ''' token_validator = TokenValidator() return token_validator @staticmethod def generate_token(): ''' Generate authentication token ''' # This key should be changed to config file based method # Second parameter can be expiration at the moment, there is no expiration serializer = Serializer(TokenValidator.SECRET_KEY) return serializer.dumps({'id': 1}) # Right now its 1 default ID it should be user id @staticmethod def verify_token(token): ''' Verify token passed to the end point ''' serializer = Serializer(TokenValidator.SECRET_KEY) try: data = serializer.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token return data HTTP_BASIC_AUTH = HTTPBasicAuth() @HTTP_BASIC_AUTH.verify_password def verify_password(username_or_token, password): ''' Verify token passed to the end point, password is useless at the moment ''' user = TokenValidator.verify_token(username_or_token) return user
true
0b9a42862060a6f1c670cc038ab74167621585f0
Python
s22615/cwWPR7-8
/FizzBuzz.py
UTF-8
409
3.890625
4
[]
no_license
n=int(input("Podaj liczbe")) #liczby for i in range(1, n+1): if i%3==0: print(i, "Fizz") if i%5==0: print(i, "Buzz") if i%3==0 and i%5==0: print(i, "FizzBuzz") #stringi for i in range(1, n+1): fizz_buzz=[] if i % 3 == 0: fizz_buzz.append("Fizz") if i % 5 == 0: fizz_buzz.append("Buzz")`,` if fizz_buzz: print(i, "".join(fizz_buzz))
true
0180b0834898ad5759800266ab3bc96ab54a8c41
Python
javawizard/afn
/afn/python/src/afn/processutils.py
UTF-8
1,910
3.421875
3
[]
no_license
""" (This is still a work in progress, and doesn't actually work yet.) Library similar to subprocess but that should fix a number of issues I have with it. For instance, the existence of subprocess.call/check_call/check_output as separate from, say, methods on subprocess's Popen class always drove me nuts. processutils's Process class will have the equivalent functionality present as methods that can be called. I also think it would be fun to write some classes and functions to implement shell-like things such as pipes, stream redirection (to/from files), perhaps an easy way to yield lines from a process, and so on. And maybe even have it log when things are invoked, although I really don't like Python's logging module so I might skip that for now. So the idea is that one can do things like: Process([...]).wait().check().get_output() which will wait until the process is done, check to make sure it succeeded (and throw an exception if it exited with anything other than 0), then return its stdout and stderr as strings. (I might have check() implicitly wait() as well, as there's not much point to doing anything else.) Things will return self where possible to facilitate easy chaining of calls as needed. """ class Process(object): def __init__(self, command, environment): raise NotImplementedError def wait(self): # Wait for this process to finish, then return self pass def check(self, exit_codes=[0]): # Throw exception if exit code not in exit_codes, otherwise return # self pass def get_output(self): # Return stdout and stderr, maybe have a separate function for each # and have one that returns both pass @property def return_code(self): pass def get_code_and_output(self): # Returns stdout, stderr, and return_code pass
true
9996a7f14f72f3e0f9e7755d8303e26f2812d155
Python
andriisoldatenko/fan
/uva_answers/10783/main.py
UTF-8
421
3.0625
3
[ "MIT" ]
permissive
import pprint import sys import re FILE = sys.stdin #FILE = open('sample.in') test_cases = int(FILE.readline().strip()) def gen_odds(n, m): results = [] for x in range(n, m+1): if x % 2 != 0: results.append(x) return results for t in range(test_cases): a = int(FILE.readline().strip()) b = int(FILE.readline().strip()) print('Case {}: {}'.format(t+1, sum(gen_odds(a, b))))
true
18734b11475c3ad7d38d5cdf2e9df16aa7a535c0
Python
nachosca/python-practice
/session28_map.py
UTF-8
741
3.46875
3
[]
no_license
# map # filter # lambda # def sqr(num): # return num**2 # l = [10,20,30,40,50,60] # l2=list(map(sqr,l)) # print(l2) # def add(num1, num2): # return num1+num2 # l1 = [100,200,300,400,500] # l2 = [10,20,30,40,50] # result = list(map(add,l1,l2)) # print(result) # l = [100,115,120,125,130,140] # def check_num(num): # return num % 2 == 0 # result = list(filter(check_num,l)) # print(result) # lambda # l = [10,20,30,40,50,60] # result = list(map(lambda num1:num1**2, l)) # print(result) # l = [100,115,120,125,130,140] # result = list(filter(lambda num:num%2==0,l)) # print(result) d = {1:50,2:40,3:30,4:20,5:10} l = sorted(d.items(),key=lambda x:x[1]) # l = sorted(d.items(),reverse=True) print(l) # help(sorted)
true
63e8d0de4a9d725a4fd59948a3307f8aaf49228e
Python
linjiafengyang/Python
/DataAnalysis/learnNumpy4.py
UTF-8
626
3.296875
3
[]
no_license
import numpy as np """ 通过数组来进行文件的输入和输出 """ # np.save和np.load # 数组会以未压缩的原始二进制模式被保存,后缀为.npy arr = np.arange(10) np.save('./some_array', arr) print(np.load('./some_array.npy')) # 用np.savez能保存多个数组,还可以指定数组对应的关键字, # 不过是未压缩的npz格式 np.savez('./array_archive.npz', a=arr, b=arr) # 加载.npz文件的时候,得到一个dict object arch = np.load('./array_archive.npz') print(arch['b']) # 可以用np.savez_compressed来压缩文件 np.savez_compressed('./array_compressed.npz', a=arr, b=arr)
true
6b6cae51331339745afff9dcd81975dc80be54c9
Python
yuchiu54/google-foobar-chanllenge
/level3/FindTheAccessCodes/solution.py
UTF-8
410
3.5625
4
[]
no_license
def solution(l): # store the possibility of each node for future use possibilities = [0] * len(l) triples = 0 for i in range(len(l)): for j in range(i): if l[i] % l[j] == 0: # update possibility possibilities[i] += 1 # add possibility of l[j] from possibilities triples += possibilities[j] return triples
true
d5c6cb078dbb91e50711c5060704e0415c0d2556
Python
wangtonylyan/Algorithms
/ds/tree/binary/size.py
UTF-8
577
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- # data structure: size balanced tree from bst import SelfBalancingBinarySearchTree, BinarySearchTreeTest class SizeBalancedTree(SelfBalancingBinarySearchTree): class Node(SelfBalancingBinarySearchTree.Node): __slots__ = ['size'] def __init__(self, key, value): super(SizeBalancedTree.Node, self).__init__(key, value) self.size = 0 def __init__(self): super(SizeBalancedTree, self).__init__() if __name__ == '__main__': BinarySearchTreeTest(SizeBalancedTree).testcase() print 'done'
true
3ff86873ad75374b39081e959e89c082c4f75dc8
Python
trefalmadore/week7.visualisation.matplot
/main.py
UTF-8
493
3.375
3
[]
no_license
from matplotlib import pyplot as plt agesX = [20, 25,30, 35, 40, 45, 50,55, 60,65] salaryY = [18000, 20000,25000,28000,30000,35000,40000,45000,50000,50000] agesX2 = [20, 25,30, 35, 40, 45, 50,55, 60,65] salaryY2 = [16000, 18000,22000,24000,28000,30000,32000,35000,40000,45000] plt.plot(agesX, salaryY,"--", label = '2020') plt.plot(agesX2, salaryY2,"x", label ='2010') plt.xlabel('Ages') plt.ylabel('Salary') plt.title('This is a avarage salary in Uninted Kindom') plt.legend() plt.show()
true
92f2af6341e116c6e50b382373156beb953e0f59
Python
ssh0/growing-string
/triangular_lattice/interactive.py
UTF-8
8,437
3.015625
3
[ "MIT" ]
permissive
#! /usr/bin/env python # -*- coding:utf-8 -*- # # written by ssh0, October 2014. from __future__ import print_function __doc__ = '''Jupyter Notebook like Gtk wrapper class. You can create Scalebar, Switch, ComboBox via simple interface. usage example: >>> from gtk_wrapper import interactive >>> def f(a, b=20): ... return a + b ... >>> w = interactive(f, a=(0, 20), b=20) (you can add buttons and label here manually) (then, you should add the next line) >>> w.display() (and you can get the result for f(a, b) by) 32 (or get the arguments with a dictionary) >>> w.result >>> w.kwargs {'a': 8, 'b': 24} ''' from gi.repository import Gtk import inspect class Interactive(Gtk.Window): def __init__(self, func, title='title', **kwargs): self.__doc__ = __doc__ self.func = func self.kwargs = dict() args, varargs, keywords, defaults = inspect.getargspec(self.func) d = [] if defaults: for default in defaults: d.append(default) self.kwdefaults = dict(zip(args[len(args) - len(defaults):], d)) else: self.kwdefaults = dict() Gtk.Window.__init__(self, title=title) hbox = Gtk.Box(spacing=6) self.add(hbox) self.listbox = Gtk.ListBox() self.listbox.set_selection_mode(Gtk.SelectionMode.NONE) hbox.pack_start(self.listbox, True, True, 0) self.status = Gtk.Label() for kw, arg in kwargs.items(): kw = str(kw) arg_type = type(arg) if arg_type == tuple: # type check for elements in tuple argtype = self.type_check(arg) if argtype == str: self.combobox_str(kw, arg) else: self.scale_bar(kw, arg, argtype) elif arg_type == int or arg_type == float: self.scale_bar(kw, [arg], arg_type) elif arg_type == bool: self.switch(kw, arg) elif arg_type == str: self.label(arg) self.kwargs[kw] = arg elif arg_type == dict: self.combobox_dict(kw, arg) else: raise TypeError row = Gtk.ListBoxRow() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50) row.add(hbox) hbox.pack_start(self.status, True, True, 10) self.status.set_text(str(self.kwargs)) self.listbox.add(row) def display(self): self.connect("delete-event", Gtk.main_quit) self.show_all() Gtk.main() def status_change(self): self.status.set_text(str(self.kwargs)) self.kwargs_for_function = self.kwdefaults self.kwargs_for_function.update(self.kwargs) self.result = self.func(**self.kwargs_for_function) def set_value(self, kw, new_value): # if argument is already given in func, use it for a default one if kw in self.kwdefaults: self.kwargs[kw] = self.kwdefaults[kw] return self.kwdefaults[kw] else: self.kwargs[kw] = new_value return new_value def type_check(self, arg): argtype = type(arg[0]) if not all([type(a) == argtype for a in arg]): raise TypeError("""types in a tuple must be the same. int or float: Scalebar str : Combobox""") return argtype def add_label(self, kw, parent): label = Gtk.Label(kw, xalign=0) parent.pack_start(label, True, True, 10) def scale_bar(self, kw, arg, argtype): def scale_interact(scale, _type): if _type == int: self.kwargs[kw] = int(scale.get_value()) else: self.kwargs[kw] = float(scale.get_value()) self.status_change() # length check for tuple len_arg = len(arg) if len_arg > 3 or len_arg == 0: raise IndexError("tuple must be 1 or 2 or 3 element(s)") if argtype == int: scale_digit = 0 elif argtype == float: scale_digit = 2 else: raise TypeError("arg must be int or float") # set the values if len_arg == 3: scale_from = arg[0] scale_to = arg[1] scale_digit = arg[2] elif len_arg == 2: scale_from = arg[0] scale_to = arg[1] else: scale_from = arg[0] * (-1) scale_to = arg[0] * 3 # create scale widget in listbox row = Gtk.ListBoxRow() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50) row.add(hbox) label = Gtk.Label(kw, xalign=0) hbox.pack_start(label, False, True, 10) scale = Gtk.Scale() scale.set_range(scale_from, scale_to) scale.set_digits(scale_digit) scale.set_value(self.set_value(kw, arg[0])) scale.set_draw_value(True) scale.connect('value-changed', scale_interact, argtype) hbox.pack_start(scale, True, True, 10) self.listbox.add(row) def switch(self, kw, arg): def on_switch_activated(switch, gparam): self.kwargs[kw] = switch.get_active() self.status_change() # create switch widget in listbox row = Gtk.ListBoxRow() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50) row.add(hbox) self.add_label(kw, hbox) switch = Gtk.Switch() switch.connect("notify::active", on_switch_activated) switch.set_active(self.set_value(kw, arg)) hbox.pack_start(switch, False, False, 10) self.listbox.add(row) def combobox_str(self, kw, arg): def on_combo_changed(combo): tree_iter = combo.get_active() if tree_iter is not None: self.kwargs[kw] = arg[tree_iter] self.status_change() argstore = Gtk.ListStore(str) for a in arg: argstore.append([a]) # create combobox widget in listbox row = Gtk.ListBoxRow() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50) row.add(hbox) self.add_label(kw, hbox) combo = Gtk.ComboBox.new_with_model(argstore) combo.connect("changed", on_combo_changed) renderer_text = Gtk.CellRendererText() combo.pack_start(renderer_text, True) combo.add_attribute(renderer_text, "text", 0) combo.set_active(arg.index(self.set_value(kw, arg))) hbox.pack_start(combo, False, False, True) self.listbox.add(row) def combobox_dict(self, kw, arg): def on_combo_changed(combo): tree_iter = combo.get_active() if tree_iter is not None: self.kwargs[kw] = values[tree_iter] self.status_change() argstore = Gtk.ListStore(str) keys = list(arg.keys()) values = list(arg.values()) for a in keys: argstore.append([a]) # create combobox widget in listbox row = Gtk.ListBoxRow() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50) row.add(hbox) self.add_label(kw, hbox) combo = Gtk.ComboBox.new_with_model(argstore) combo.connect("changed", on_combo_changed) renderer_text = Gtk.CellRendererText() combo.pack_start(renderer_text, True) combo.add_attribute(renderer_text, "text", 0) combo.set_active(values.index(self.set_value(kw, arg))) hbox.pack_start(combo, False, False, True) self.listbox.add(row) if __name__ == '__main__': from gi.repository import Gtk def f(x=12, y=20, z='III', o=False, i=20): print("x: {0}, y: {1}, z: {2}, o: {3}, i: {4}".format(x, y, z, o, i)) def b1(button): print(w.kwargs) buttons = [('b1', b1), ('exit', Gtk.main_quit)] w = Interactive(f, x=10, y=(1., 100.), z=("ZZZ", "III", "foo", "bar"), i={'0': 0, '10': 10, '20': 20}, o=True ) row = Gtk.ListBoxRow() hbox = Gtk.HBox(spacing=10) row.add(hbox) for b in buttons: button = Gtk.Button(b[0]) button.connect('clicked', b[1]) hbox.pack_start(button, True, True, 0) w.listbox.add(row) w.display()
true
c0802ff18906d122c186c8b97d5bc9a3aff4b43f
Python
hailua54/algorithm
/ai/python/matplotlib_test.py
UTF-8
1,134
3.1875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt x = np.arange(-5., 5., 0.1) np.set_printoptions(precision=3) with np.printoptions(precision=3, suppress=True): print(x*x) y = x*x + 10*np.sin(x) plt.plot(x, y) plt.axis([0, 5, -10, 20]) #plt.show() #momentum Gradient Descent ---------------- ''' v0 = 0 v1 = p*v0 + k*f'(x0) x1 = x0 - v1 = x0 - p*v1 - k*f'(x0) ... note: 0 < p < 1: v->0 adjust |v| by modify (p, k) ''' #f(x) = x^2 + 10 sin(x) #f'(x) = 2x + 10 cos(x) def grad(x): return 2*x + 10*np.cos(x) def normal_GD(N, x, k): v = 0 i = 0 while i < N: if abs(grad(x)) < 1e-3: break x = x - k*grad(x) i += 1 return (x, i) r = normal_GD(200, 5, 0.05) print("1. normal_GD %.3f, %d"%r) r = normal_GD(200, 5, 0.1) print("2. normal_GD %.3f, %d"%r) def momentum_GD(N, x, p, k): v = 0 i = 0 while i < N: if abs(grad(x)) < 1e-3: break v = p*v + k*grad(x) x = x - p*v - k*grad(x) i += 1 return (x, i) r = momentum_GD(200, 5, 0.9, 0.05) print("1. momentum_GD %.3f, %d"%r) r = momentum_GD(200, 5, 0.9, 0.1) print("2. momentum_GD %.3f, %d"%r)
true
5a27f174f80b348d4ea9be6fde44743784926f4e
Python
Parth-Shah-Tool-Kit/complete-python-tutorial
/part3/string_functions.py
UTF-8
331
3.625
4
[]
no_license
statement = "He is a good boy. He is a good singer." s = "Hi" print(len(statement)) # print the length print(statement.lower()) # lower case print(statement.upper()) # upper case print(statement.title()) # do captial of initial character print(statement.count("o")) # counts the presence of the argumeny
true
9e631d28d9f3611f87b5b528e464f7202f34cfe2
Python
R-Fischer47/Intro-to-Data-Science
/Assignment4/linked_list.py
UTF-8
1,511
4.0625
4
[]
no_license
## # Simple linked list classes # # Nothing to see here folks ## class Node: def __init__(self, data): self.item = data self.ref = None class LinkedList: def __init__(self): # Currently Empty self.start_node = None # Current Size self.size = 0 def insert_at_front(self, data): new_node = Node(data) new_node.ref = self.start_node self.start_node = new_node self.size += 1 def insert_at_end(self, data): new_node = Node(data) if self.start_node is None: self.start_node = new_node self.size += 1 return n = self.start_node while n.ref is not None: n = n.ref n.ref = new_node self.size += 1 # Function to search the list # # We make this flexible with an optional parameter for the user # to include their own comparison function # # WARNING: This function returns the *FIRST* match regardless of # method used. def search(self, data, search_func = None): n = self.start_node while n is not None: if search_func is None: if n.item == data: return n.item else: if search_func(n.item, data) is True: return n.item n = n.ref return None # testing function def print_list(self): if self.start_node is None: print("List is empty.") else: n = self.start_node while n is not None: print(n.item) n = n.ref
true
871b1ce48b77fa17cf4f0701484cfa9607389b1f
Python
subarna-sahoo/Python3_Practice
/+tv & -tv aug\18.py
UTF-8
204
3.53125
4
[]
no_license
# Separeting positive numbers & negetive numbers > p_list = [] n_list = [] for i in range(-5,10): if i > 0: p_list.append(i) if i < 0: n_list.append(i) print(p_list) print(n_list)
true
7ae7575587ff985925b7885fe11b298a7e636a81
Python
SamalAbenova/seminar2
/main.py
UTF-8
228
3.171875
3
[]
no_license
from mybox import MyBox box = MyBox() box.add(1) box.add('Two') box.add(4.5) box.add('box') box.add(7) box.add('Done') box.remove('Two') if ('One' in box) and (len(box) > 0): box.remove('One') for i in box: print(i)
true
211a58154707e80fbaa14119b73a9db6282535ed
Python
fujimuram/sfmmesh
/python/houghLines.py
UTF-8
2,022
3.375
3
[]
no_license
import numpy as np import cv2 IMAGE_PATH = "./thinning4_2_hough/net2.png" # 読み込む画像 def main(): image = cv2.imread(IMAGE_PATH) # 画像読み込み image2 = cv2.imread(IMAGE_PATH) # 画像読み込み gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # グレースケール化 outLineImage = cv2.Canny(gray, 120, 250, apertureSize = 3) # 輪郭線抽出 #cv2.imwrite("./thinning4_2_hough/outLine.png", outLineImage) # ファイル保存 hough_lines(image, outLineImage) # ハフ変換による直線抽出 cv2.imwrite("./thinning4_2_hough/result_hough.png", image) # ファイル保存 hough_lines_p(image2, outLineImage) # 確率的ハフ変換による直線抽出 cv2.imwrite("./thinning4_2_hough/result_houghP.png", image2) # ファイル保存 # ハフ変換で直線を抽出する関数 def hough_lines(image, outLineImage): result = image lines = cv2.HoughLines(outLineImage, rho=1, theta=np.pi/180, threshold=245) # ハフ変換で直線抽出 print("hough_lines: ", len(lines)) for line in lines: rho, theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(result,(x1,y1),(x2,y2),(0,0,255),2) # 赤色で直線を引く return result # 確率的ハフ変換で直線を抽出する関数 def hough_lines_p(image, outLineImage): resultP = image # 確率的ハフ変換で直線を抽出 lines = cv2.HoughLinesP(outLineImage, rho=1, theta=np.pi/180, threshold=200, minLineLength=100, maxLineGap=70) print("hough_lines_p: ", len(lines)) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(resultP,(x1,y1),(x2,y2),(0,255,0),2) # 緑色で直線を引く return resultP if __name__ == '__main__': main()
true
21683102bdac1e77ff682500481f8417fa81419a
Python
Furkanbstm/GlobalAIHubPythonCourse
/hub/hw1,2,3/hw1.py
UTF-8
309
3.078125
3
[]
no_license
list_of_evens = [0, 2, 4] list_of_odds = [1, 3, 5] list_of_both = list_of_evens + list_of_odds list_of_both = list_of_evens + list_of_odds list_of_merge = list_of_both.sort() final_liste = list(list_of_both) final_list = list([ i*2 for i in list_of_both]) for i in final_list: print(i)
true
d6de695c9176c7c94bebc7b2320b5786f73f1749
Python
i2sheri/puzzles
/pythonchallenge.com/level_09.py
UTF-8
214
2.953125
3
[]
no_license
"""first and second are available in Level 9""" import Image, ImageDraw img = Image.open('good.jpg') draw = ImageDraw.Draw(img) draw.polygon(first, 'red') draw.polygon(second, 'red') img.save('super.png', 'png')
true
b07e28a1026767fbc72c6dd0ddd7496bde7596e9
Python
srajulu/Cricket-match-ML
/61.py
UTF-8
1,369
3.546875
4
[]
no_license
import pandas as pd df=pd.read_csv("E:\matches.csv") #list of cities where match conducted using unique() print("Unique cities where matches were conducted") print(df.city.unique()) #list of teams played the match using unique() print("List of all teams played for T20") print(df.team1.unique()) #total number of matches in 2010,2015,2017 a1=(df.season == 2015).sum() a2=(df.season == 2010).sum() a3=(df.season == 2017).sum() print("Total matches in 2010,2015 and 2017: ",a1+a2+a3) #matches held in bangalore b=(df.city == 'Bangalore').sum() print("Total matches in Bangalore: ",b) #Count of match in APRIL-2017 m=df[ (df['date'].str.endswith('-04-17') )] print(m['date'].count()) #number of matches tie c=(df.result == 'tie').sum() print("Number of times the result was TIE: ",c) #number of matches in which SK Raina was player of match print("Number of times SK Raina was player of the match: ",(df.player_of_match == 'SK Raina').sum()) #Count of Toss won by each team print(df['toss_winner'].value_counts() ) #number of matches in which Yuvi was player of match print("Number of times Yuvi was player of the match: ",(df.player_of_match == 'Yuvraj Singh').sum()) #team that won maximum matches in 2014 m=df[ (df['season']==2014 )] print(m['winner'].value_counts().index[0] ) print(m['winner'].value_counts().values[0] )
true
1b0f37a667195d7419b733da16be96c5257a16bb
Python
navrobot/ros_monitor
/src/ros_monitor/socket_monitor.py
UTF-8
2,100
2.65625
3
[]
no_license
import time, copy, threading import dpkt, pcap import rospy def parse_bin_ip(bin_ip): ''' Parse a string containing the binary data for an IPv4 IP. Returns a string with the human readable ip of the form xxx.xxx.xxx.xxx ''' if not len(bin_ip) == 4: raise ValueError('Cannot parse IP; invalid number of bytes: %d' % len(bin_ip)) return '.'.join('%d' % ord(x) for x in bin_ip) class SocketMonitor(threading.Thread): def __init__(self, iface): self.socket_stats_lock = threading.Lock() self.socket_stats = {} self.pc = pcap.pcap(iface, promisc=False) # only doing TCP connections right now; since this # is what ROS topics use self.pc.setfilter('tcp') threading.Thread.__init__(self) def get_socket_stats(self): with self.socket_stats_lock: return copy.copy(self.socket_stats) def make_key_for_packet(self, pkt): p = dpkt.ethernet.Ethernet(pkt) if 'tcp' in dir(p.ip): src = parse_bin_ip(p.ip.src) dst = parse_bin_ip(p.ip.dst) dport = p.ip.tcp.dport sport = p.ip.tcp.sport return (src, sport, dst, dport) else: return None def handle_packet(self, pkt): key = self.make_key_for_packet(pkt) with self.socket_stats_lock: if not key in self.socket_stats: self.socket_stats[key] = {} if not 'total_bytes' in self.socket_stats[key]: self.socket_stats[key]['total_bytes'] = 0 self.socket_stats[key]['total_bytes'] += len(pkt) def run(self): for ts, pkt in self.pc: # FIXME this only checks for shutdown when a packet is receieved if rospy.is_shutdown(): return self.handle_packet(pkt) if __name__ == '__main__': output_period = 1.0 smon = SocketMonitor('eth0') smon.start() while not rospy.is_shutdown(): stats = smon.get_socket_stats() print stats time.sleep(1.0)
true
d94a692d2ad37a703d904b340df95b5c08099c5f
Python
uktechreviews/pioneers
/Code_ninjas.py
UTF-8
722
2.828125
3
[]
no_license
#This bit is set up by Mr Organ our mentor import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) pin = 17 pin2 = 18 GPIO.setup(pin,GPIO.OUT) GPIO.setup(pin2,GPIO.OUT) GPIO.setwarnings(False) #This is our code from here print("") print ("") print("") print("") print("") print("") print("") print("") print ("We are team >CodeNinjas_") print ("We want to make you laugh!") print ("What is your name?") name = input() print ("Do you like Minecraft TNT?") time.sleep(5) print ("5") time.sleep(1) print ("4") time.sleep(1) print ("3") time.sleep(1) print ("2") time.sleep(1) print ("1") GPIO.output(pin,1) time.sleep(10) GPIO.output(pin,0) print ("You have been pranked " + name) print ("Ha Ha Ha Ha Ha")
true
7fb97bbe1cb81ddd1452e6852e89017a8985331b
Python
brukidm/AoC2020
/Day09/2.py
UTF-8
529
2.953125
3
[]
no_license
with open(r"input") as f: lines = f.read().split("\n") for i in range(len(lines)): if int(lines[i]) > 22406676: limit = i break start = 0 end = 2 while start < limit: while end < limit: seq = lines[start:end] total = sum(map(int, seq)) if total == 22406676: ints = [int(i) for i in seq] print(max(ints) + min(ints)) exit end += 1 start += 1 end = start + 1
true
503699c556dc71d11449dc86b600ae819df5bf8c
Python
IT-eng-max/python
/Twitter bot.py
UTF-8
1,056
3.046875
3
[ "MIT" ]
permissive
#library to access twitter api #pip3 install tweepy import tweepy import time #built in #verify our account auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.me() #print(user.name) --> all in the library #print(user.screen_name) #print(user.followers_count) #generous bot def limit_handle(cursor): try: while True: yield cursor.next() except tweepy.RateLimitError: time.sleep(300) #mili seconds search_string = 'python' numbersOfTweets = 2 for tweet in tweepy.Cursor(api.search, search_string).items(numbersOfTweets): try: tweet.retweet() print('I liked that tweet') except tweepy.TweepError as e: print(e.reason) except StopIteration: break #for follower in limit_handler(tweepy.Cursor(api.followers).items()): #if follower.name == 'username': #follower.follow() #break #stop looping #print(follower.name) #problem heating the api #follow back copy that user name
true
b320f274e546eee96aa9e3a01943a7cb05484be6
Python
lawhw/opencv_tf_py
/c4/03_dlib.py
UTF-8
2,533
3.09375
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- import face_recognition import cv2 from PIL import Image, ImageDraw import numpy def dlib(): video_capture = cv2.VideoCapture(0) while cv2.waitKey(1) == -1 and True: ret, frame = video_capture.read() find_facial_features(frame) def find_facial_features(image): # if path is None: # video_capture = cv2.VideoCapture(0) # image = video_capture # else: # image = face_recognition.load_image_file(path) # Load the jpg file into a numpy array # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) # print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) # Create a PIL imagedraw object so we can draw on the picture # pil_image = Image.fromarray(image) # frame = cv2.cvtColor(numpy.asarray(pil_image), cv2.COLOR_RGB2BGR) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image # for facial_feature in face_landmarks.keys(): # print("The {} in this face has the following points: {}".format(facial_feature, # face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! for facial_feature in face_landmarks.keys(): #d.line(face_landmarks[facial_feature], width=5) # print(facial_feature) for i in range(len(face_landmarks[facial_feature])): cv2.circle(image, face_landmarks[facial_feature][i], 0, (55, 255, 155), 5) cv2.imshow('find_facial_features', image) def find_facial_features1(path): image = face_recognition.load_image_file(path) # Load the jpg file into a numpy array face_landmarks_list = face_recognition.face_landmarks(image) pil_image = Image.fromarray(image) frame = cv2.cvtColor(numpy.asarray(pil_image), cv2.COLOR_RGB2BGR) for face_landmarks in face_landmarks_list: for facial_feature in face_landmarks.keys(): for i in range(len(face_landmarks[facial_feature])): cv2.circle(frame, face_landmarks[facial_feature][i], 0, (55, 255, 155), 5) cv2.imshow('find_facial_features', frame) cv2.waitKey() def main(): # image = face_recognition.load_image_file("./image/0001.jpg") find_facial_features1("./image/0001.jpg") # dlib() if __name__ == '__main__': main()
true
4857cd3567846abf60bf378299b19e4ea1048ad4
Python
brandonmorgan01/beer_recommendation_final_project
/model.py
UTF-8
2,372
2.609375
3
[]
no_license
import sklearn from sklearn.neighbors import KNeighborsClassifier import pandas as pd import os import numpy as np # import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction import text from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score from numpy import nan as Nan import random def myfunct(form): desc = 'Stout' abv = float(form[0]) df = pd.read_csv("cleanedfinalbeerdata.csv") form.pop(0) print(form) #removing the ABV df2 = pd.DataFrame([[33050, "UserBeer", Nan, form[0], abv, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, abv]], columns=list(df.columns.values)) form.pop(0) if(len(form)>0): for desc in form: dfAdd = pd.DataFrame([[33050, "UserBeer", Nan, desc, abv, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, Nan, abv]], columns=list(df.columns.values)) df2= pd.concat([df2, dfAdd]) df3 = pd.concat([df,df2]) print(len(df3.index)) """ form is always structured with abv first, hence abv = float(form[0]) currently, not set up to hand multiple descriptions """ df3.loc[df3['id'] == 'UserBeer'] finaldf1 = df3[(df3.description.notnull())] documents = np.ndarray.tolist(finaldf1['description'].values) my_stop_words = text.ENGLISH_STOP_WORDS.union(["beer"]) vectorizer = TfidfVectorizer(stop_words=my_stop_words, decode_error='replace', encoding='utf-8') X = vectorizer.fit_transform(documents) kmeans = KMeans(n_clusters=30) srmdata = np.array(list(zip(finaldf1['newabv'].values)), X) kmeans.fit(srmdata) predicted_clusters = kmeans.predict(srmdata) finaldf1['predicted group'] = predicted_clusters finaldf1[finaldf1['id'].str.contains('UserBeer')] chosenbeergroup = finaldf1[finaldf1['id'].str.contains('UserBeer')]['predicted group'].values[0] filterdf = finaldf1[finaldf1['predicted group']==chosenbeergroup] filterdf.head() selectarr = [] numberingroup = filterdf['id'].count() for x in range(0, 6): selectarr.append (random.randint(0, int(numberingroup))) finaluserdf = filterdf.iloc[selectarr] print(finaluserdf["description"],finaluserdf["name"]) return finaluserdf
true
386fa079f750b402f70cb6c7055e9332d4939a37
Python
umangbhatia786/PythonPractise
/GeeksForGeeks/Strings/remove_nth_char.py
UTF-8
550
4.5625
5
[]
no_license
#Python code to remove nth character from a string def remove_nth_char(input_str,n): if n > len(input_str): raise ValueError('Value of n cannot be greater than the length of the string') else: if n == 1: return input_str[1:] elif n == len(input_str): return input_str[:-n] else: return input_str[:n-1] + input_str[n:] input_str = 'UmangBhatia' char_to_remove = 4 print(f'String after removing {char_to_remove}th character is: {remove_nth_char(input_str,char_to_remove)}')
true
3f8134798c88cba3ea1a7f09eb1fea48c31a7cab
Python
bunshue/vcs
/_4.python/__code/機器學習基礎數學第二版/ch20/ch20_5.py
UTF-8
620
3.515625
4
[]
no_license
# ch20_5.py import numpy as np import matplotlib.pyplot as plt x = np.array([8, 9, 10, 7, 8, 9, 5, 7, 9, 8]) y = np.array([12, 15, 16, 18, 6, 11, 3, 12, 11, 16]) x_mean = np.mean(x) y_mean = np.mean(y) xpt1 = np.linspace(0, 12, 12) ypt1 = [y_mean for xp in xpt1] # 平均購買次數 ypt2 = np.linspace(0, 20, 20) xpt2 = [x_mean for yp in ypt2] # 平均滿意度 plt.scatter(x, y) # 滿意度 vs 購買次數 plt.plot(xpt1, ypt1, 'g') # 平均購買次數 plt.plot(xpt2, ypt2, 'g') # 平均滿意度 plt.grid() plt.show()
true
375c885a6d620763d2efe137f01d318dbbd77f78
Python
mkudamatsu/election_campaign_promises
/SConstruct
UTF-8
1,821
2.578125
3
[]
no_license
# Comments are copy-and-pasted from # http://zacharytessler.com/2015/03/05/data-workflows-with-scons/ # https://github.com/gslab-econ/ra-manual/wiki/SCons import os env = Environment(ENV = {'PATH' : os.environ['PATH']}, IMPLICIT_COMMAND_DEPENDENCIES = 0) # The Environment() call sets up a build environment that you can use to set various build options. # ENV = {'PATH' : os.environ['PATH']} gives SCons access to the PATH environment variable. # IMPLICIT_COMMAND_DEPENDENCIES = 0 tells SCons to not track the executables of any commands used, which will be different across machines. env.Decider('MD5-timestamp') # By default, SCons uses MD5 hashes of file contents to determine whether an input file has changed. When working with even moderately sized data files, computing these hashes on every build can take a very long time. The MD5-timestamp option instructs SCons to first check file timestamps, and only compute the MD5 hash if the timestamp has changed, to confirm that file is actually different. This can speed things up dramatically. Export('env') # This makes env available to code in all your SConscript files. Note that the objects to export are passed as strings. env.Command( target = '#build_temp/smd_year_winner_voteshare_margin.dta', source = [ '#input/data_asahi-todai/data/nameid_year_all.csv', '#input/data_japanese-elections/data/lower_house_results.csv', '#code_build/smd_year_winner_voteshare_margin.do' ], action = 'StataMP -e code_build/smd_year_winner_voteshare_margin.do && mv smd_year_winner_voteshare_margin.log log' ) # In the source and target paths, the "#" identifies a path as relative to the top-level SConstruct file, which is useful if you want all your build outputs in one place, regardless of where the SConscript file is.
true
ab4f8511d3a74b80b264dbbab60040dfc6dd3cf5
Python
Emilyyyyyyyyyyyyyy-prog/Pygame-project
/танки.py
UTF-8
28,216
2.828125
3
[]
no_license
import pygame import os import random import sys import uuid class Tank: def __init__(self, level, side, pos=None, direction=None): global sprites self.health = 100 self.speed = 1 self.side = side self.level = level self.control = [pygame.K_SPACE, pygame.K_w, pygame.K_d, pygame.K_s, pygame.K_a] self.state = 'alive' self.image = sprites.subsurface(64, 0, 26, 30) if pos: self.rect = pygame.Rect(pos, (26, 26)) else: self.rect = pygame.Rect((0, 0), (26, 26)) if not direction: self.direction = random.choice(['up', 'down', 'right', 'left']) else: self.direction = direction self.pressed = [False] * 4 def draw(self): global screen if self.state == 'alive': screen.blit(self.image, self.rect.topleft) elif self.state == 'exploding': self.explosion.draw() def explode(self): if self.state != 'dead': self.state = 'exploding' self.explosion = Explosion(self.rect.topleft) def fire(self): global bullets, fired_bullets if self.state != 'alive': gtimer.destroy(self.timer_uuid_fire) return False bullet = Bullet(level, self.rect.topleft, self.direction) if self.side == 'player': bullet.owner = 'player' fired_bullets += 1 else: bullet.owner = 'enemy' bullets.append(bullet) return True def rotate(self, direction, fixed_pos=True): self.direction = direction if direction == 'up': self.image = self.image_up if fixed_pos: self.rect.top -= 5 elif direction == 'down': self.image = self.image_down if fixed_pos: self.rect.top += 5 elif direction == 'right': self.image = self.image_right if fixed_pos: self.rect.left += 5 else: self.image = self.image_left if fixed_pos: self.rect.left -= 5 def turn_around(self): if self.direction == 'up': self.rotate('down') elif self.direction == 'down': self.rotate('up') elif self.direction == 'left': self.rotate('right') else: self.rotate('left') def update(self, time_passed): if self.state == 'exploding': if not self.explosion.active: self.state = 'dead' del self.explosion def bullet_impact(self, friendly_fire=False, damage=50): global play_sounds, sounds if not friendly_fire: self.health -= damage if self.health < 1: if self.side == 'enemy' and play_sounds: sounds['explosion'].play() self.explode() return True if self.side == 'enemy': return False else: return True class Enemy(Tank): def __init__(self, level, side='enemy', pos=None, direction=None): global enemies, sprites Tank.__init__(self, level, side='enemy', pos=None, direction=None) self.level = level self.rect = pygame.Rect(pos, (26, 26)) self.image = sprites.subsurface(64, 0, 26, 30) self.image_up = self.image self.image_down = pygame.transform.rotate(self.image, 180) self.image_left = pygame.transform.rotate(self.image, 90) self.image_right = pygame.transform.rotate(self.image, 270) self.rotate(self.direction, False) self.path = self.generate_path(self.direction) self.timer_uuid_fire = gtimer.add(20000, lambda: self.fire()) self.side = side def move(self): global enemies, player if self.state != 'alive': return if not self.path: self.path = self.generate_path(None, True) new_pos = self.path.pop(0) if self.direction == 'up' and new_pos[1] < 0: self.path = self.generate_path(self.direction, True) return elif self.direction == 'right' and new_pos[0] > width - 30: self.path = self.generate_path(self.direction, True) return elif self.direction == 'down' and new_pos[1] > height - 30: self.path = self.generate_path(self.direction, True) return elif self.direction == 'left' and new_pos[0] < 0: self.path = self.generate_path(self.direction, True) return new_rect = pygame.Rect(new_pos, (26, 26)) if new_rect.collidelist(self.level.obstacle_rects) != -1: self.path = self.generate_path(self.direction, True) return for enemy in enemies: if enemy != self and new_rect.colliderect(enemy.rect): self.turn_around() self.path = self.generate_path(self.direction) return if new_rect.colliderect(player.rect): self.turn_around() self.path = self.generate_path(self.direction) return self.rect.topleft = new_rect.topleft def update(self, time_passed): Tank.update(self, time_passed) if self.state == 'alive': self.move() elif self.state == 'exploding' and not self.explosion.active: self.state = 'dead' del self.explosion def generate_path(self, direction=None, fixed_direction=False): all_directions = ['up', 'down', 'right', 'left'] if not direction: if self.direction == 'up': oposite_direction = 'down' elif self.direction == 'down': oposite_direction = 'up' elif self.direction == 'right': oposite_direction = 'left' else: oposite_direction = 'right' directions = all_directions random.shuffle(directions) directions.remove(oposite_direction) directions.append(oposite_direction) else: if direction == 'up': oposite_direction = 'down' elif direction == 'down': oposite_direction = 'up' elif direction == 'right': oposite_direction = 'left' else: oposite_direction = 'right' directions = all_directions random.shuffle(directions) directions.remove(oposite_direction) directions.remove(direction) directions.insert(0, direction) directions.append(oposite_direction) x = self.rect.left // tile_width y = self.rect.top // tile_height new_direction = None max_x = width // tile_width max_y = height // tile_height for dir in directions: if dir == 'up' and y > 1: new_pos_rect = self.rect.move(0, -10) if new_pos_rect.collidelist(self.level.obstacle_rects) == -1: new_direction = dir break elif dir == 'right' and x < max_x - 3: new_pos_rect = self.rect.move(10, 0) if new_pos_rect.collidelist(self.level.obstacle_rects) == -1: new_direction = dir break elif dir == 'down' and y < max_y - 3: new_pos_rect = self.rect.move(0, 10) if new_pos_rect.collidelist(self.level.obstacle_rects) == -1: new_direction = dir break elif dir == 'left' and x > 1: new_pos_rect = self.rect.move(-10, 0) if new_pos_rect.collidelist(self.level.obstacle_rects) == -1: new_direction = dir break if not new_direction: new_direction = oposite_direction if fixed_direction and new_direction == self.direction: fixed_direction = False self.rotate(new_direction, fixed_direction) positions = [] x = self.rect.left y = self.rect.top pixels = int(random.randint(1, 12) * 32) + 3 if new_direction == 'up': for px in range(0, pixels, self.speed): positions.append([x, y - px]) if new_direction == 'right': for px in range(0, pixels, self.speed): positions.append([x + px, y]) if new_direction == 'down': for px in range(0, pixels, self.speed): positions.append([x, y + px]) if new_direction == 'left': for px in range(0, pixels, self.speed): positions.append([x - px, y]) return positions class Player(Tank): def __init__(self, level, side='player', pos=None, direction=None): global sprites Tank.__init__(self, level, side='player', pos=None, direction=None) self.level = level self.start_pos = pos self.start_direction = direction self.rect.topleft = self.start_pos self.image = sprites.subsurface(0, 0, 32, 32) self.image_up = self.image self.image_down = pygame.transform.rotate(self.image, 180) self.image_left = pygame.transform.rotate(self.image, 90) self.image_right = pygame.transform.rotate(self.image, 270) if not direction: self.rotate('up', False) else: self.rotate(direction, False) self.side = side def move(self, direction): global player, enemies if self.state == 'exploding' and not self.explosion.active: self.state = 'dead' del self.explosion if self.state != 'alive': return if self.direction != direction: self.rotate(direction, False) if direction == 'up': new_pos = [self.rect.left, self.rect.top - self.speed] if new_pos[1] < 0: return elif direction == 'right': new_pos = [self.rect.left + self.speed, self.rect.top] if new_pos[0] > width - 30: return elif direction == 'down': new_pos = [self.rect.left, self.rect.top + self.speed] if new_pos[1] > height - 30: return else: new_pos = [self.rect.left - self.speed, self.rect.top] if new_pos[0] < 0: return player_rect = pygame.Rect(new_pos, (26, 26)) if player_rect.collidelist(self.level.obstacle_rects) != -1: return for enemy in enemies: if player_rect.colliderect(enemy.rect): return self.rect.topleft = (new_pos[0], new_pos[1]) class Explosion: def __init__(self, pos, interval=None, images=None): global sprites self.pos = [pos[0] - 16, pos[1] - 16] self.active = True if not interval: interval = 100 if not images: images = [sprites.subsurface(0, 80 * 2, 32 * 2, 32 * 2), sprites.subsurface(32 * 2, 80 * 2, 32 * 2, 32 * 2), sprites.subsurface(64 * 2, 80 * 2, 32 * 2, 32 * 2)] images.reverse() self.images = images self.image = self.images.pop() gtimer.add(interval, lambda: self.update(), len(self.images) + 1) def draw(self): global screen screen.blit(self.image, self.pos) def update(self): if len(self.images): self.image = self.images.pop() else: self.active = False class Level: def __init__(self, level_map): global sprites self.tile_size = 16 self.tile_brick = sprites.subsurface(96, 128, 16, 16) self.tile_grass = sprites.subsurface(112, 144, 16, 16) self.obstacle_rects = [] self.load_level(level_map) def load_level(self, level_map): filename = 'maps/' + str(level_map) if not os.path.isfile(filename): return False file = open(filename, 'r') data = file.read().split('\n') self.tile_map = [] x, y = 0, 0 for row in data: for letter in row: if letter == '#': tile_type = self.tile_brick elif letter == '.': tile_type = self.tile_grass else: continue tile = TileRect(x, y, self.tile_size, self.tile_size, tile_type) if tile_type == self.tile_brick: self.obstacle_rects.append(tile) self.tile_map.append(tile) x += self.tile_size x = 0 y += self.tile_size return True def draw(self): global screen for tile in self.tile_map: screen.blit(tile.type, tile.topleft) class TileRect(pygame.Rect): def __init__(self, left, top, width, height, type): pygame.Rect.__init__(self, left, top, width, height) self.type = type class Bullet: def __init__(self, level, pos, direction, damage=50, speed=2): global sprites self.level = level self.direction = direction self.damage = damage self.owner = None self.image = sprites.subsurface(150, 148, 6, 8) if direction == 'up': self.rect = pygame.Rect(pos[0] + 11, pos[1] - 8, 6, 8) elif direction == 'right': self.image = pygame.transform.rotate(self.image, 270) self.rect = pygame.Rect(pos[0] + 26, pos[1] + 11, 8, 6) elif direction == 'down': self.image = pygame.transform.rotate(self.image, 180) self.rect = pygame.Rect(pos[0] + 11, pos[1] + 26, 6, 8) else: self.image = pygame.transform.rotate(self.image, 90) self.rect = pygame.Rect(pos[0] - 8, pos[1] + 11, 8, 6) self.explosion_images = [sprites.subsurface(0, 160, 64, 64), sprites.subsurface(64, 160, 64, 64)] self.speed = speed self.state = 'active' def draw(self): global screen if self.state == 'active': screen.blit(self.image, self.rect.topleft) elif self.state == 'exploding': self.explosion.draw() def update(self): global player, enemies, bullets if self.state == 'exploding' and not self.explosion.active: self.destroy() del self.explosion if self.state != 'active': return if self.direction == 'up': self.rect.topleft = [self.rect.left, self.rect.top - self.speed] if self.rect.top < 0: if play_sounds and self.owner == 'player': sounds['steel'].play() self.explode() return elif self.direction == 'right': self.rect.topleft = [self.rect.left + self.speed, self.rect.top] if self.rect.left > width - self.rect.width: if play_sounds and self.owner == 'player': sounds['steel'].play() self.explode() return elif self.direction == 'down': self.rect.topleft = [self.rect.left, self.rect.top + self.speed] if self.rect.top > height - self.rect.height: if play_sounds and self.owner == 'player': sounds['steel'].play() self.explode() return else: self.rect.topleft = [self.rect.left - self.speed, self.rect.top] if self.rect.left < 0: if play_sounds and self.owner == 'player': sounds['steel'].play() self.explode() return rects = self.level.obstacle_rects if self.rect.collidelistall(rects): self.explode() return for bull in bullets: if self.state == 'active' and bull.owner != self.owner and \ bull != self and self.rect.colliderect(bull.rect): self.destroy() self.explode() return for enemy in enemies: if enemy.state == 'alive' and self.rect.colliderect(enemy.rect): if enemy.bullet_impact(self.owner == 'enemy'): self.destroy() return if player.state == 'alive' and self.rect.colliderect(player.rect): if player.bullet_impact(self.owner == 'player'): self.destroy() return def destroy(self): self.state = 'removed' def explode(self): if self.state != 'removed': self.state = 'exploding' self.explosion = Explosion([self.rect.left - 13, self.rect.top - 13], None, self.explosion_images) class Timer(object): def __init__(self): self.timers = [] def add(self, interval, callback, repeat=-1): options = { 'interval': interval, 'callback': callback, 'repeat': repeat, 'times': 0, 'time': 0, 'uuid': uuid.uuid4() } self.timers.append(options) return options['uuid'] def destroy(self, uuid_num): for timer in self.timers: if timer['uuid'] == uuid_num: self.timers.remove(timer) return def update(self, time_passed): for timer in self.timers: timer['time'] += time_passed if timer['time'] > timer['interval']: timer['time'] -= timer['interval'] timer['times'] += 1 if -1 < timer['repeat'] == timer['times']: self.timers.remove(timer) try: timer['callback']() except: try: self.timers.remove(timer) except: pass def start(text, gameover=False): fon_1 = pygame.transform.scale(load_image('background1.png'), (width, height)) fon_2 = pygame.transform.scale(load_image('background2.png'), (width, height)) fon_3 = pygame.transform.scale(load_image('background3.png'), (width, height)) cloud1 = pygame.transform.scale(load_image('cloud1.png'), (46, 21)) cloud2 = pygame.transform.scale(load_image('cloud2.png'), (147, 54)) cloud3 = pygame.transform.scale(load_image('cloud3.png'), (55, 28)) tank = pygame.transform.scale(load_image('tank.png'), (270, 150)) screen.blit(fon_1, (0, 0)) screen.blit(fon_2, (0, 0)) screen.blit(fon_3, (0, 0)) screen.blit(cloud1, (300, 50)) screen.blit(cloud2, (400, 100)) screen.blit(cloud3, (700, 50)) screen.blit(tank, (400, 300)) font = pygame.font.Font(None, 50) text_coord = 30 for line in text: string_rendered = font.render(line, 1, pygame.Color('black')) intro_rect = string_rendered.get_rect() text_coord += 10 intro_rect.top = text_coord intro_rect.x = 10 text_coord += intro_rect.height screen.blit(string_rendered, intro_rect) while 1: for i in pygame.event.get(): if i.type == pygame.QUIT: terminate() if i.type == pygame.KEYDOWN: if gameover: if i.key == pygame.K_n: return 'New_game' elif i.key == pygame.K_b: return 'New_map' elif i.key == pygame.K_q: terminate() else: if i.key == pygame.K_ESCAPE: return False else: return True elif i.type == pygame.MOUSEBUTTONDOWN and not gameover: return True pygame.display.flip() clock.tick(fps) def load_image(name): fullname = 'images/' + name image = pygame.image.load(fullname) return image def draw(): level.draw() player.draw() for enemy in enemies: enemy.draw() for bull in bullets: bull.draw() pygame.display.flip() def generate_enemies(number): count = 0 while count < number: enemy_pos = random.choice(enemy_possible_points) if enemy_pos not in enemy_positions: enemy_positions.append(enemy_pos) new_enemy = Enemy(level, pos=enemy_pos) enemies.append(new_enemy) count += 1 def terminate(): pygame.quit() sys.exit() if __name__ == '__main__': pygame.init() size = width, height = 800, 800 tile_width = tile_height = 16 screen = pygame.display.set_mode(size, pygame.FULLSCREEN) if '-w' in sys.argv[1:]: screen = pygame.display.set_mode(size) os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' clock = pygame.time.Clock() fps = 50 play_sounds = False pygame.mixer.pre_init(44100, -16, 1, 512) gtimer = Timer() start_text = ['Игра в танки', '---------------------------------------------------------', 'Правила игры:', 'Движение - кнопками WASD', 'Выстрел - кнопка ПРОБЕЛ.', 'Игра идет до полного уничтожения', 'танков противника', 'или поражения игрока.', '', 'Звуки вкл/выкл кпокой M', '---------------------------------------------------------', 'Запуск с ключом -w открывает игру в окне', '', 'Приятной игры!'] if not start(start_text): screen = pygame.display.set_mode(size) os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' sprites = pygame.transform.scale(pygame.image.load('images/sprites.gif'), [192, 224]) pygame.display.set_icon(sprites.subsurface(0, 0, 26, 26)) sounds = dict() sounds['start'] = pygame.mixer.Sound('sounds/gamestart.ogg') sounds['end'] = pygame.mixer.Sound('sounds/gameover.ogg') sounds['bg'] = pygame.mixer.Sound('sounds/background.ogg') sounds['fire'] = pygame.mixer.Sound('sounds/fire.ogg') sounds['explosion'] = pygame.mixer.Sound('sounds/explosion.ogg') sounds['brick'] = pygame.mixer.Sound('sounds/brick.ogg') sounds['steel'] = pygame.mixer.Sound('sounds/steel.ogg') bullets = [] maps = ['map1.txt', 'map2.txt', 'map3.txt'] map_number = 0 level = Level(maps[map_number]) play_sounds = True if play_sounds: sounds['start'].play() gtimer.add(4300, lambda: sounds['bg'].play(-1), 1) enemies = [] enemy_possible_points = [] for i in range(10, width - 30, 30): for j in range(10, height - 30, 30): if not (40 < i < width - 50 and 40 < j < height - 50) and \ (i, j) not in enemy_possible_points: enemy_possible_points.append((i, j)) enemy_positions = [] generate_enemies(10) player = Player(level, pos=(width // 2, height // 2)) shot_enemies = 0 fired_bullets = 0 running = True time_passed = clock.tick(20) while running: for i in pygame.event.get(): if i.type == pygame.QUIT: running = False terminate() if i.type == pygame.KEYDOWN: if i.key == pygame.K_m: play_sounds = not play_sounds if play_sounds: gtimer.add(4330, lambda: sounds['bg'].play(-1), 1) else: for sound in sounds: sounds[sound].stop() if i.key == pygame.K_ESCAPE: screen = pygame.display.set_mode(size) os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' if player.state == 'alive': try: index = player.control.index(i.key) except: pass else: if index == 0: if player.fire() and play_sounds: sounds['fire'].play() elif index == 1: player.pressed[0] = True elif index == 2: player.pressed[1] = True elif index == 3: player.pressed[2] = True else: player.pressed[3] = True elif i.type == pygame.KEYUP: if player.state == 'alive': try: index = player.control.index(i.key) except: pass else: if index == 1: player.pressed[0] = False elif index == 2: player.pressed[1] = False elif index == 3: player.pressed[2] = False elif index == 4: player.pressed[3] = False if player.state == 'alive': if player.pressed[0]: player.move('up') elif player.pressed[1]: player.move('right') elif player.pressed[2]: player.move('down') elif player.pressed[3]: player.move('left') if player.state == 'dead' or len(enemies) == 0: if player.state == 'dead': top_text = 'Игра окончена! Ты ПрОиГрАл Гыгыгыгыг' else: top_text = 'Победа!' if play_sounds: for sound in sounds: sounds[sound].stop() sounds['end'].play() if fired_bullets: statistics = 'составляет ' + str(int(shot_enemies / fired_bullets * 200)) + '%' else: statistics = 'не определена' gameover_text = [top_text, '---------------------------------------------------------', 'Уничножено врагов: ' + str(shot_enemies), 'Выпущено снарядов: ' + str(fired_bullets), 'Точность стрельбы: ' + str(statistics), 'N - начать заново', 'B - начать с другой картой', 'Q - завершить игру'] next_step = start(gameover_text, gameover=True) if next_step == 'New_map': map_number = (map_number + 1) % len(maps) if next_step: bullets.clear() enemies.clear() del gtimer.timers[:] del player level = Level(maps[map_number]) generate_enemies(10) shot_enemies = 0 fired_bullets = 0 player = Player(level, pos=(width // 2, height // 2)) if play_sounds: sounds['start'].play() gtimer.add(4300, lambda: sounds['bg'].play(-1), 1) player.update(time_passed) for bull in bullets: if bull.state == 'removed': bullets.remove(bull) else: bull.update() for enemy in enemies: enemy.update(time_passed) if enemy.state == 'dead': enemies.remove(enemy) shot_enemies += 1 gtimer.update(time_passed) screen.fill(pygame.Color('black')) draw()
true
061257ea67c9f6625d2bb7c9f63c52d86e5e7e8a
Python
hbobenicio/python-examples
/asyncio-examples/multiple-requests/server.py
UTF-8
650
2.84375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """A simple http server using aiohttp. Note here the difference between time.sleep (blocking) and asyncio.sleep (non-blocking). Remember that we must avoid blocking the event loop thread to let the event loop switch the execution context to other coroutines. """ import asyncio from aiohttp import web async def list_users_handler(request): await asyncio.sleep(3) return web.json_response( ['Fulano', 'Beltrano', 'Cicrano'] ) if __name__ == '__main__': app = web.Application() app.add_routes([ web.get('/users', list_users_handler) ]) web.run_app(app)
true
f1b523ea3fcebc66ccf9569b0368be74ba87a766
Python
vamotest/yandex_algorithms
/12_02_basic_data_structures/O. Encryption.py
UTF-8
205
3.28125
3
[]
no_license
def anagram(f, d): n = 0 for i in range(len(f)-len(d)+1): if sorted(d) == sorted(f[i:len(d)+i]): n += 1 print(n) if __name__ == '__main__': anagram(input(), input())
true
47874600b8aba5e1fa1a952e6ac2ff6f4521169f
Python
ai-jpl/pre-jlp-r
/test.py
UTF-8
221
2.5625
3
[]
no_license
import cabocha from cabocha.analyzer import CaboChaAnalyzer analyzer = CaboChaAnalyzer() tree = analyzer.parse("日本語の形態素解析はすごいです。") for chunk in tree: for token in chunk: print(token)
true
9c4d2a405972fc7d53919c386846e59719b00322
Python
Aasthaengg/IBMdataset
/Python_codes/p03806/s864116878.py
UTF-8
846
3.125
3
[]
no_license
# -*- coding: utf-8 -*- """ D - Mixing Experiment https://atcoder.jp/contests/abc054/tasks/abc054_d """ import sys def solve(N, Ma, Mb, items): d = dict() d[(0, 0)] = 0 for a, b, c in items: nd = dict() for k, v in d.items(): t = d.get((k[0], k[1]), float('inf')) + c if d.get((k[0]+a, k[1]+b), float('inf')) > t: nd[(k[0]+a, k[1]+b)] = t d.update(nd) res = [] for k, v in d.items(): if k == (0, 0): continue a, b = k if a*Mb == b*Ma: res.append(v) return min(res) if res else -1 def main(args): N, Ma, Mb = map(int, input().split()) items = [[int(i) for i in input().split()] for _ in range(N)] ans = solve(N, Ma, Mb, items) print(ans) if __name__ == '__main__': main(sys.argv[1:])
true