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
54124b431890f909225b91effeec27bde1035547
Python
Xiangfeidetangyuan/Medicine
/Inform/Inform_DB_helper.py
UTF-8
3,882
2.734375
3
[]
no_license
import sqlite3 class Inform: def __init__(self, medicineName, remarks, frequency, hour, minute, id): self.medicinename = medicineName self.remarks = remarks self.frequency = frequency self.hour = hour self.minute = minute self.id = 1 class InformDBHelper: def __init__(self, db_name, username): self.db_name = db_name self.username = username # 加入数据库 def add(self, curinform): # print("插入数据……") connection = sqlite3.connect(self.db_name) cursor = connection.cursor() try: sql2 = "INSERT INTO inform (userName, medicineName, remarks, frequency, Time_Hour, Time_Minute, status) values ('{}','{}','{}','{}','{}','{}','{}')" sql = sql2.format(self.username, curinform.medicinename, curinform.remarks, curinform.frequency, curinform.hour, curinform.minute, 1) cursor.execute(sql) connection.commit() connection.close() # print("插入提醒成功") except Exception as e: print(e) # 查 def findALLInform(self): connection = sqlite3.connect(self.db_name) #print("连接数据库成功") cursor = connection.cursor() try: sql2 = "SELECT medicineName,remarks,frequency,Time_Hour,Time_Minute " \ ",informId ,status FROM inform WHERE inform.userName= ('{}')" sql = sql2.format(self.username) informlist = cursor.execute(sql) inform_result_list = informlist.fetchall() connection.commit() connection.close() # print("查找结果成功") if len(inform_result_list) == 0: # print("结果为0") return None else: return inform_result_list except Exception as e: print(e) # 设置状态 def setStatus(self, id, status): # print("设置状态……" + str(status)) connection = sqlite3.connect(self.db_name) cursor = connection.cursor() try: sql = "UPDATE inform set status= '{}' WHERE inform.informID ='{}'".format(status, id) cursor.execute(sql) connection.commit() connection.close() # print("设置状态成功……") except Exception as e: print(e) # 设置次数 def setFrequdency(self, id, frequdency): # print("设置次数……") connection = sqlite3.connect(self.db_name) cursor = connection.cursor() try: sql = "UPDATE inform SET frequency='{}' WHERE inform.informId= '{}'".format(frequdency, id) cursor.execute(sql) connection.commit() connection.close() # print("设置次数成功……") except Exception as e: print(e) # 删除 def delInform(self, id): # print("删除数据……", id) connection = sqlite3.connect(self.db_name) cursor = connection.cursor() try: sql = "DELETE FROM inform WHERE inform.informId = '{}'".format(id) cursor.execute(sql) connection.commit() connection.close() # print("删除数据成功……") except Exception as e: print(e) def getEmail(self): connection = sqlite3.connect(self.db_name) cursor = connection.cursor() try: email = cursor.execute("SELECT userEmail From user WHERE userName = '%s' " % self.username) res = email.fetchall() connection.commit() connection.close() print("获取邮箱成功……", res[0][0]) return res[0][0] except Exception as e: print(e)
true
01ab82a4b8b92bdfe6ff932b11bf4cdab01e8b44
Python
Aravind-Venugopal/TitanicRoulette
/titanic_model.py
UTF-8
2,198
2.890625
3
[]
no_license
import pandas as pd import numpy as np import re, joblib from sklearn.ensemble import RandomForestClassifier train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') deck = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8} data = [train, test] for dataset in data: dataset['Cabin'] = dataset['Cabin'].fillna("U0") dataset['Deck'] = dataset['Cabin'].map( lambda x: re.compile("([a-zA-Z]+)").search(x).group()) dataset['Deck'] = dataset['Deck'].map(deck) dataset['Deck'] = dataset['Deck'].fillna(0) dataset['Deck'] = dataset['Deck'].astype(int) # we can now drop the cabin feature train = train.drop(['Cabin'], axis=1) test = test.drop(['Cabin'], axis=1) data = [train, test] for dataset in data: mean = train["Age"].mean() std = test["Age"].std() is_null = dataset["Age"].isnull().sum() # compute random numbers between the mean, std and is_null rand_age = np.random.randint(mean - std, mean + std, size=is_null) # fill NaN values in Age column with random values generated age_slice = dataset["Age"].copy() age_slice[np.isnan(age_slice)] = rand_age dataset["Age"] = age_slice dataset["Age"] = train["Age"].astype(int) common_value = 'S' data = [train, test] genders = {"male": 0, "female": 1} ports = {"S": 0, "C": 1, "Q": 2} for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value) dataset['Fare'] = dataset['Fare'].fillna(0) dataset['Fare'] = dataset['Fare'].astype(int) dataset['Sex'] = dataset['Sex'].map(genders) dataset['Embarked'] = dataset['Embarked'].map(ports) train = train.drop(['Ticket', 'Name'], axis=1) test = test.drop(['Ticket', 'Name'], axis=1) X_train = train.drop(["Survived", 'PassengerId'], axis=1) Y_train = train["Survived"] X_test = test.drop("PassengerId", axis=1).copy() # random forest model training random_forest = RandomForestClassifier(n_estimators=100) random_forest.fit(X_train, Y_train) Y_prediction = random_forest.predict(X_test) # random_forest.score(X_train, Y_train) acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2) # Save model as pickle file joblib.dump(random_forest, "model.pkl")
true
cc5e892addaaa7b8aeec7d79d90a7eb8dc531f5a
Python
a-johnston/pls-not-concave
/optimize.py
UTF-8
1,580
3.515625
4
[]
no_license
""" Some experiment with convex optimization """ def _eval_offset(f, X, i, offset): temp = list(X) temp[i] += offset return f(*temp) def _subgradient(f, X, step=1e-12): G = [0] * len(X) for i in range(len(X)): y1 = _eval_offset(f, X, i, step) y2 = _eval_offset(f, X, i, -step) G[i] = (y1 - y2) / (2 * step) return tuple(G) def _squared_magnitude(X): return sum([x ** 2 for x in X]) def optimize(f, n, start=None, block=10, error=1e-9, gradient=_subgradient): """ Assuming f is a convex function taking n real arguments, returns an approximation of the minima of f. Optionally takes a given starting point, block size, error, and gradient function which otherwise default to the 0 point of R^n, 10, 1e-3, and a naive subgradient calculation respectively. """ X = list(start or (0,) * n) error **= 2 bounds = [[None, None] for _ in range(n)] power = [1 for _ in range(n)] while True: G = gradient(f, X) m = _squared_magnitude(G) if m < error: break g = max(G, key=lambda x: abs(x)) i = G.index(g) if g >= 0: bounds[i][1] = X[i] if g <= 0: bounds[i][0] = X[i] temp = 0 if bounds[i][0] and bounds[i][1]: temp = (bounds[i][0] + bounds[i][1]) / 2 elif bounds[i][0]: temp = X[i] + block ** power[i] power[i] += 1 else: temp = X[i] - block ** power[i] power[i] += 1 X[i] = temp return X
true
10c0ed3d5a7208cc045c3d426fac3fa82bfce55d
Python
SilasHenderson/Python_OpenGL
/snake.py
UTF-8
2,589
3.65625
4
[]
no_license
# gl Snake {Silas Henderson 2019} # -- press keys up, down, left, right to move snake import numpy import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * # -------------------------- Snake Class ---------------------------------- class Snake: def __init__(self): # Init pygame.init() # -- start pygame pygame.display.set_mode((500, 500), DOUBLEBUF|OPENGL) # -- open window gluOrtho2D(0, 500, 0, 500) # -- set window dims glClearColor(.1, .1, .1, 1) # -- background color self.head = numpy.array([50, 50]) # -- snake head self.tail = numpy.array([50, 50]) # -- snake tail self.dir = numpy.array([ 1, 0]) # -- snake travel direction self.spd = 1 # -- snake travel speed def update(self): # Update self.spd = self.spd + .02 # -- increase speed self.head = self.head + self.spd*self.dir # -- move head self.tail = numpy.append(self.tail, self.head) # -- add pts to tail glBegin(GL_LINE_STRIP) # -- draw pts for i in range(1, numpy.size(self.tail)/2): glVertex3f(snake.tail[2*i], snake.tail[2*i-1] , 0) glEnd() pygame.display.flip() # -- update screen pygame.time.wait(10) # -- pause glClear(GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT) def keys(self): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.dir = numpy.array([ 0, 1]) if event.key == pygame.K_DOWN: self.dir = numpy.array([ 0,-1]) if event.key == pygame.K_LEFT: self.dir = numpy.array([-1, 0]) if event.key == pygame.K_RIGHT: self.dir = numpy.array([ 1, 0]) def game(self): while snake.head[0] > 0 and snake.head[0] < 500 and \ snake.head[1] > 0 and snake.head[1] < 500: snake.update() snake.keys() # -------------------------- Loop ------------------------------ snake = Snake() snake.game()
true
e717a56782f3a3d47d067f544ac52a4cd62f4e7e
Python
rhender007/python-ps
/built_in_functions/zip_ex02.py
UTF-8
172
3.59375
4
[]
no_license
a = [1, 2, 3, 4, 5] b = [11, 12, 13, 14, 15] result = [] for first, second in zip(a, b): result.append(first + second) print(result) # output: [12, 14, 16, 18, 20]
true
f74acadb3112cc6623cb47ccc50ab4e4f8397171
Python
Aasthaengg/IBMdataset
/Python_codes/p03838/s579436739.py
UTF-8
227
3.28125
3
[]
no_license
x, y = map(int, input().split()) if x*y < 0: print(abs(abs(x)-abs(y))+1) elif x*y == 0: if x < y: print(y-x) else: print(x-y+1) else: if x < y: print(y-x) else: print(x-y+2)
true
3dbf0d8287a871b8b3cd91ccfaad5dc1b4e03a4b
Python
Scavi/RpgCrawler
/AppStart.py
UTF-8
3,594
2.96875
3
[]
no_license
import os import logging import argparse from core.RpgCrawler import RpgCrawler from interaction.AbstractIO import AbstractIO from interaction.ConsoleIO import ConsoleIO from sheet.AbstractSpreadAccess import AbstractSpreadAccess from sheet.GSpreadAccess import GSpreadAccess def create_argument_parser() -> argparse.ArgumentParser: """ Creates the argument parser with the mandatory and optional parameters of this application :return the argument parser of the application """ parser = argparse.ArgumentParser() parser.add_argument("--d", required=False, choices=[True, False], type=bool, help="Ein optionaler Parameter um Debug-Informationen der Anwendung herauszuschreiben.") parser.add_argument("--f", required=True, help="Ein erforderlicher Parameter der den Namen des Start Google Sheets angibt.") return parser def determine_excel_sheet_name(arguments: argparse.Namespace) -> str: """ Determines the name of the excel sheet to be crawled from the start parameter of the application :param arguments the program arguments accessible by argparse :return the name of the target excel sheet""" return str(arguments.f).strip() def create_spread_access(spread_sheet_name: str) -> AbstractSpreadAccess: """Creates the access to the spread sheet. Uses the permission file for the spread sheet access :return the spread sheet access """ root_path = os.path.dirname(os.path.realpath(__file__)) permission_path = os.path.join(root_path, 'permissions/RpgCrawler-b8b181033387.json') return GSpreadAccess(spread_sheet_name, permission_path) def create_crawler(spread_access: AbstractSpreadAccess, io: AbstractIO) -> RpgCrawler: """Creates the crawler that iterates the excel sheets :param spread_access the spread sheet access :param io the io interaction interface for the user :return the excel sheet crawler """ return RpgCrawler(spread_access, io) def create_io(): """ the interface to the user (input / output) :return the io interface of the user """ return ConsoleIO() def init_log(arguments: argparse.Namespace) -> None: """ Sets the root logger and the application logger to debug :param arguments the program arguments accessible by argparse :return: """ if arguments.d: formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') crawl_logic_stream = logging.StreamHandler() crawl_logic_stream.setLevel(logging.DEBUG) crawl_logic_stream.setFormatter(formatter) logging.getLogger(RpgCrawler.ID).setLevel(logging.DEBUG) logging.getLogger('').setLevel(logging.DEBUG) logging.getLogger('').addHandler(crawl_logic_stream) def main(): """ The main method of the application. Creates the required objects and initiates the program execution """ print("#################################################") print("######### RPG Crawler v0.50 (30.05.2018) ########") print("#################################################") argument_parser = create_argument_parser() arguments = argument_parser.parse_args() init_log(arguments) excel_sheet_name = determine_excel_sheet_name(arguments) spread = create_spread_access(excel_sheet_name) io = create_io() crawler = create_crawler(spread, io) while True: iteration = io.iterations() if iteration == 0: break for i in range(1, iteration + 1): crawler.crawl() if __name__ == '__main__': main()
true
50c08eba4237452e1cf76b1412390254a85a6a89
Python
jjguti/aoc2020
/4/1.py
UTF-8
616
2.671875
3
[]
no_license
def validate(entry, required_fields): for field in required_fields: if field not in entry: return False return True entries = [] entry = {} with open("input") as f: for line in f: line = line.strip() if not line: entries.append(entry) entry = {} else: for field in line.split(" "): key, value = field.split(":") entry[key] = value entries.append(entry) required = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] print(list(map(lambda x: validate(x, required), entries)).count(True))
true
140734be7b0ebe08a193862c606524fd6b803cb2
Python
mohitraj/mohitcs
/Learntek_code/10_july_18/list3.py
UTF-8
90
2.53125
3
[]
no_license
GoT = ["Tyrion","Sansa", "Arya","Joffrey","Ned-Stark"] a = GoT.pop(2) print a print GoT
true
ded370bd1ef6fc56ccea309ef447f581815150ba
Python
ch3rolll/CarND-Behavioral-Cloning-P3
/model_nvi.py
UTF-8
5,513
2.609375
3
[]
no_license
import os import csv import pandas import cv2 import sklearn import numpy as np from random import shuffle from sklearn.model_selection import train_test_split from keras.models import Sequential, Model from keras.regularizers import l2 from keras.layers import Flatten, Dense, Activation, Lambda, Conv2D, pooling, Cropping2D, Dropout from keras.utils import plot_model os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0,1" samples = [] with open('driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) train_samples, validation_samples = train_test_split(samples, test_size=0.2) correction =0.2 dropout = 1. def generator(samples, batch_size=32): num_samples = len(samples) while 1: # Loop forever so the generator never terminates shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset+batch_size] images = [] angles = [] images_flipped = [] for batch_sample in batch_samples: name = './IMG/'+batch_sample[0].split('/')[-1] center_image = cv2.imread(name) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) images_flipped.append(np.fliplr(center_image)) # trim image to only see section with road X_train = np.array(images) y_train = np.array(angles) X_train = np.append(X_train, images_flipped,axis=0) y_train = np.append(y_train, np.negative(y_train),axis=0) yield sklearn.utils.shuffle(X_train, y_train) # ch, row, col = 3, 80, 320 # Trimmed image format # model = Sequential() # # Preprocess incoming data, centered around zero with small standard deviation # model.add(Cropping2D(cropping=((50,30), (0,0)), input_shape=(160,320,3))) # # Normalize # model.add(Lambda(lambda x: x/127.5 - 1., # input_shape=(row, col, ch), # output_shape=(row, col, ch))) def generator_all(samples, batch_size=32): num_samples = len(samples) while 1: # Loop forever so the generator never terminates shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset+batch_size] images = [] angles = [] images_flipped = [] for batch_sample in batch_samples: name = './IMG/'+batch_sample[0].split('/')[-1] center_image = cv2.imread(name) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) images_flipped.append(np.fliplr(center_image)) # For the left images left_name = './IMG/'+batch_sample[1].split('/')[-1] left_image = cv2.imread(left_name) left_angle = center_angle + correction images.append(left_image) angles.append(left_angle) images_flipped.append(np.fliplr(left_image)) # For the right images right_name = './IMG/'+batch_sample[2].split('/')[-1] right_image = cv2.imread(right_name) right_angle = center_angle - correction images.append(right_image) angles.append(right_angle) images_flipped.append(np.fliplr(right_image)) # trim image to only see section with road X_train = np.array(images) y_train = np.array(angles) X_train = np.append(X_train, images_flipped,axis=0) y_train = np.append(y_train, np.negative(y_train),axis=0) yield sklearn.utils.shuffle(X_train, y_train) # compile and train the model using the generator function train_generator = generator_all(train_samples, batch_size=32) validation_generator = generator_all(validation_samples, batch_size=32) # normalization model = Sequential() model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(160,320,3))) model.add(Cropping2D(cropping=((65, 25), (0, 0)))) # Allow the model to choose the appropriate color space # https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9 model.add(Conv2D(3, kernel_size=(1, 1), strides=(1, 1), activation='linear')) model.add(Conv2D(24, kernel_size=(5, 5), strides=(2, 2), activation='relu')) model.add(Conv2D(36, kernel_size=(5, 5), strides=(2, 2), activation='relu')) model.add(Conv2D(48, kernel_size=(5, 5), strides=(2, 2), activation='relu')) model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) model.add(Flatten()) model.add(Dense(1164, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(100, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(50, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='linear')) plot_model(model,to_file='model.png',show_shapes=True) model.compile(loss='mse', optimizer='adam') model.fit_generator(train_generator, steps_per_epoch= len(train_samples), validation_data=validation_generator, validation_steps=len(validation_samples), epochs=5) model.save('model_nvi_e3.h5')
true
b648ec1c1dbe3dd69568c117a45f199e94805a63
Python
ITISFoundation/osparc-simcore
/services/dask-sidecar/src/simcore_service_dask_sidecar/computational_sidecar/task_shared_volume.py
UTF-8
1,758
2.515625
3
[ "MIT" ]
permissive
import asyncio import logging import shutil from dataclasses import dataclass from pathlib import Path from types import TracebackType logger = logging.getLogger(__name__) @dataclass(frozen=True) class TaskSharedVolumes: base_path: Path def __post_init__(self) -> None: for folder in ["inputs", "outputs", "logs"]: folder_path = self.base_path / folder if folder_path.exists(): logger.warning( "The path %s already exists. It will be wiped out now.", folder_path ) self.cleanup() assert not folder_path.exists() # nosec folder_path.mkdir(parents=True) logger.debug( "created %s in %s", f"{folder=}", f"{self.base_path=}", ) @property def inputs_folder(self) -> Path: return self.base_path / "inputs" @property def outputs_folder(self) -> Path: return self.base_path / "outputs" @property def logs_folder(self) -> Path: return self.base_path / "logs" def cleanup(self) -> None: try: shutil.rmtree(self.base_path) except OSError: logger.exception( "Unexpected failure removing '%s'." "TIP: Please check if there are permission issues.", self.base_path, ) raise async def __aenter__(self) -> "TaskSharedVolumes": return self async def __aexit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, ) -> None: await asyncio.get_event_loop().run_in_executor(None, self.cleanup)
true
db868a76b8ddc2fbabf60e033e21c264c21ee556
Python
singcl/pypy
/python_100_days/1.11_csv1.py
UTF-8
454
3.28125
3
[]
no_license
#!usr/bin/python # -*- coding: utf-8 -*- """ 读取CSV数据 Version: 0.1 Author: singcl Date: 2019-01-30 """ import csv filename = 'example.csv' try: with open(filename) as f: reader = csv.reader(f) data = list(reader) except FileNotFoundError: print("无法打开文件", filename) else: for item in data: # "%-30s 左对齐 最多显示30个字符 print("%-30s%-20s%-10s" % (item[0], item[1], item[2]))
true
591b5335d4506564825caa7e73feaf40ecfa4b11
Python
ScottBogen/current-song-lyrics
/connector.py
UTF-8
1,058
2.921875
3
[]
no_license
import requests import json import spotipy from song import Song from spotipy.oauth2 import SpotifyOAuth # This class will represent the part of the program that fetches Spotify's API and returns a song object class SongFetcher(): def __init__(self, scope): self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) # returns as JSON def get_currently_playing_song_as_JSON(self): response = self.sp.currently_playing( market=None, additional_types=None) return response def get_artist_from_JSON(self, json): artist = json['item']['artists'][0]['name'] return artist def get_track_from_JSON(self, json): track = json['item']['name'] return track def get_song(self): response = self.get_currently_playing_song_as_JSON() song = None if response is not None: track = self.get_track_from_JSON(response) artist = self.get_artist_from_JSON(response) song = Song(track, artist) return song
true
756de45127fec174edca13b6cf1dd5493d25db54
Python
saitejapa/new
/new_multiple.py
UTF-8
310
3.65625
4
[]
no_license
def main(): num = input('Insert number:') output = sumOfMultiples(num) print(output) def sumOfMultiples(param): j = 0 i = 0 for i in range(i, param): if (i % 3 ==0) or (i % 5 == 0) and (i % 15 != 0): j = j + i return j if __name__ == '__main__': main()
true
41b56fe11c2a320e938cbe8f40985508df408e90
Python
mrchenbo/jvm-in-python
/instructions/base/method_invoke_logic.py
UTF-8
388
2.921875
3
[]
no_license
def InvokeMethod(invokerFrame, method): thread = invokerFrame.Thread() newFrame = thread.NewFrame(method) thread.PushFrame(newFrame) argSlotSlot = method.ArgSlotCount() if argSlotSlot > 0: i = argSlotSlot - 1 while i>=0: slot = invokerFrame.OperandStack().PopSlot() newFrame.LocalVars().SetSlot(i, slot) i -= 1
true
0a454319ece95305db588167fa0a35f7988a72c8
Python
perkinsml/dfsummary_package_PyPI
/dfsummary/dfsummary.py
UTF-8
12,056
3.359375
3
[ "MIT" ]
permissive
from .dfsummary_helpers import return_df_summary, return_heatmap_data from matplotlib import cm, pyplot as plt import pandas as pd import numpy as np import seaborn as sns class DfSummary(object): """The DfSummary object is a dataframe object with methods to provide descriptive statistics and formatted visualisations for EDA.""" # Initialise class variables for formatting of visualisations ncols=3 # Default number of columns in subplots cmap=cm.get_cmap('tab10') # Default colormap fs=9 # Default font size def __init__(self, df): """Method for initialising a DfSummary object. Args: df: Pandas Dataframe. A dataframe containing continuous and/or discrete data. A Pandas Series will be cast as a dataframe. Returns: DfSummary object """ # If data df is (incorrectly) a Series, cast as a dataframe if isinstance(df, pd.Series): self.df=df.to_frame() else: self.df=df # Calculate number of subplots rows required for visulisations of numeric data self.nrows = int(np.ceil(len(self.df.select_dtypes(include=np.number).columns) \ / (1.0*self.ncols))) if self.nrows<=1: self.nrows +=1 def return_summary(self): """Display df summary information and descriptive statistics to screen. This method also calls the return_df_summary(df) method, which returns additional descriptive statitics for the df. These statistics are assigned to the df_summary attribute of the DfSummary object. Any non-numeric columns to be excluded from this summary should be excluded from the DfSummary object before instantiation. Args: None Returns: None """ print(f'Dataframe shape: {self.df.shape}') print(f'Total number of null values in data: {self.df.isnull().sum().sum()}') print('\nFirst 5 rows of data:') display(self.df.head()) print('\nLast 5 rows of data:') display(self.df.tail()) print('\n'+'-'*12+'\nDATA SUMMARY\n'+'-'*12) # Call function to display and assign additional descriptive statistics for df self.df_summary = return_df_summary(self.df) display(self.df_summary) def return_histograms(self): """Create and return a figure with histograms for each numeric column in the DfSummary object. All NaN values are excluded from histograms. The number of NaN values dropped for each field is displayed in the subplot title for each field. Args: None Returns: fig: fig object. A figure that includes histograms with summary statistics for each folumn in the DfSummary object. """ # Initialise figure and axes fig, axes = plt.subplots(nrows=self.nrows, ncols=self.ncols, figsize=(15, self.nrows*4)) # Initialise subplot counter to enable removal of unrequired subplot axes counter = 0 # Assign numeric data for histograms df=self.df.select_dtypes(include=np.number) # Loop through each subplot cell in axes grid for i in range(self.nrows): for j in range(self.ncols): ax = axes[i][j] # Generate histogram for each df column, including vertical lines for the # mean and 25th, 50th & 75th percentiles. Note, null values are excluded. if counter < len(df.columns): # Drop null values in column before plotting data col_no_null = df.loc[df[df.columns[counter]].notnull(), df.columns[counter]] ax.hist(col_no_null, color=self.cmap(counter%10), alpha=0.9) ax.axvline(col_no_null.mean(), ls='-', lw=0.9, c='black', label='Mean') ax.axvline(col_no_null.median(), ls='--', lw=0.9, c='black', label='Median') ax.axvline(col_no_null.quantile(0.25), ls='--', lw=0.9, c='dimgray', label='25th percentile') ax.axvline(col_no_null.quantile(0.75), ls='-', lw=0.9, c='dimgray', label='75th percentile') # Configure axis labels and display title ax.set_xlabel('Value', fontsize=self.fs) ax.set_ylabel('Value count', fontsize=self.fs) ax.set_title(f'{df.columns[counter]}: ' \ f'\n({df[df.columns[counter]].isnull().sum()} NaN values dropped)', \ fontsize=self.fs+2) ax.grid(color='lightgray') # Configure legend leg = ax.legend(loc='best', fontsize=self.fs) leg.draw_frame(False) # Remove subplot axis for subplot cells without data to plot else: ax.set_axis_off() # Increment subplot counter counter += 1 # Configure figure layout and assign figure title fig.tight_layout(pad=3.0) fig.suptitle('Histograms of numeric data fields', fontsize=self.fs+5, y=1.0) plt.close(fig) return fig def return_heatmap(self, method='pearson', drop_criteria=None): """Create and return a figure with a heatmap of correlations between numeric columns in the DfSummary object. This method calls the return_heatmap_data function and assigns the returned correlation matrix as the heatmap_data attribute of the DfSummary object. Args: method: string. Method to be used for calculating correlation between df columns ('pearson' (default), 'spearman' or 'kendall') drop_criteria: string or list of columns for determining data to drop before calculating correlations. 'any_rows': drop any data rows with NaNs 'any_cols': drop any data columns with NaNs list: list of columns to be used for determing NaN data to drop. Any rows with NaNs in this list of columns will be dropped from the data. None (default): no rows or columns with NaNs are dropped from the data. If None, pairwise correlations are calculated. Returns: fig: fig object. A heatmap of correlation coefficients between each column in df if sufficient data remains after dropping NaNs. """ # Assign numeric data for heatmap visulisation df=self.df.select_dtypes(include=np.number) if df.shape[1]<2 or method.lower() not in ['pearson', 'spearman', 'kendall']: print('Invalid data or correlation method provided for heatmap to be generated.') return # Call function to return data to be included in heatmap based on # specified correlation method and null value dropping criteria self.heatmap_data = return_heatmap_data(df, method, drop_criteria) if self.heatmap_data['corrs'].notnull().sum().sum() == 0: print('There is no data left for calcualting pair-wise correlations.') else: # Initialise figure and axes fig, ax = plt.subplots(figsize=(20, 20)) # Add ticks and axis for colorbar to control its size and position cbar_ticks =[-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1] cbar_ax = fig.add_axes([0.85, 0.2, 0.02, 0.6]) # Create a mask for the upper triangle of the heatmap mask = np.zeros_like(self.heatmap_data['corrs'], dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Generate heatmap sns.heatmap(self.heatmap_data['corrs'], mask=mask, vmin=-1, vmax=1, annot=True, annot_kws={"size":self.fs}, cmap="RdBu_r", cbar_kws=dict(ticks=cbar_ticks), cbar_ax=cbar_ax, ax=ax) # Configure axis labels and assign figure title ax.set_xticklabels(ax.xaxis.get_ticklabels(), fontsize=self.fs+4, rotation=90) ax.set_yticklabels(ax.yaxis.get_ticklabels(), fontsize=self.fs+4, rotation=0) title = (f"Heatmap of {method.capitalize()} correlation between numeric fields with " f"{self.heatmap_data['drop_count']} {self.heatmap_data['title_text']} dropped") ax.set_title(title, fontsize=self.fs+7) # Adjust font size of colorbar cax = plt.gcf().axes[-1] cax.tick_params(labelsize=self.fs+4) plt.close(fig) return fig def return_boxplots(self, swarmplot=False): """ Create and return a boxplot of data in numeric columns. NaN values are excluded from plots. The number of excluded NaN values will be displayed in the subplot title for each field. The function has the option to overlay a swarmplot, displaying a maximum of 2,000 data points. Args: swarmplot: Boolean (default=False). Overlay a swarmplot of up to 2,000 data points randomly selected from numeric data columns if swarmplot=True. Returns: fig: fig object. Boxplots of data for each numeric data column, with optional swarmplot """ # Initialise figure and axes fig, axes = plt.subplots(nrows=self.nrows, ncols=self.ncols, figsize=(14, self.nrows*4)) # Initialise subplot counter to enable removal of unrequired subplot axes counter = 0 # Assign numeric data for boxplots visulisation df=self.df.select_dtypes(include=np.number) # Loop through each subplot cell in axes grid for i in range(self.nrows): for j in range(self.ncols): ax = axes[i][j] # Generate box and optional swarmplot for each df.column. Note null values are excluded. if counter < len(df.columns): # Drop null values in columnn before plotting data col_no_null = df.loc[df[df.columns[counter]].notnull(), df.columns[counter]] sns.boxplot(data=pd.DataFrame(col_no_null), linewidth=1.2, width=0.75, fliersize=0, \ color=self.cmap(counter%10), saturation=0.9, ax=ax) # Generate swarmplot if required if swarmplot and len(col_no_null)<=2000: sns.swarmplot(data=pd.DataFrame(col_no_null), linewidth=0.6, size=0.9, color='darkblue', ax=ax) elif swarmplot and len(col_no_null)>2000: print(f"There are {len(col_no_null)} non-null data points in the '{df.columns[counter]}' field. " f"2000 random points (only) will be plotted in the swarmplot.") sns.swarmplot(data=pd.DataFrame(col_no_null.sample(2000)), linewidth=0.6, size=0.9, color='darkblue', ax=ax) # Configure axis labels and display title ax.set_xticks([]) ax.set_ylabel('Value', fontsize=self.fs) ax.set_title(f'{df.columns[counter]}: \n' \ f'({df[df.columns[counter]].isnull().sum()} NaN values dropped)', fontsize=self.fs+2) ax.grid(color='lightgray') # Remove subplot axis for subplot cells without data else: ax.set_axis_off() # Increment subplot counter counter += 1 # Configure figure layout and assign figure title fig.tight_layout(pad=3.0) if swarmplot: plot_type = 'Swarmplots' else: plot_type = 'Boxplots' fig.suptitle(f'{plot_type} of numeric data fields', fontsize=self.fs+5, y=1.0) plt.close(fig) return fig
true
519831dc8f85dcf2b6dcb3a26ceda35429711f40
Python
tomer-melamed/dataScienceProject
/Scrappers/scrapper_one.py
UTF-8
2,054
2.78125
3
[]
no_license
from Scrappers.scrappers import Scrapers from lxml import etree class ScrapperOne(Scrapers): BASE_URL = 'http://www.fullbooks.com' MAX_REQUESTS = 100 def get_text(self): response = self.request(url=self.BASE_URL) tree = etree.HTML(response.text) refrences = tree.xpath('/html/body/div/table[2]/tr[1]/td[@width="50%"]/ul/li/font/a/@href') refrences += tree.xpath('/html/body/div/table[2]/tr[1]/td[@width="50%"]/font/ul/li/a/@href') all_books = self.get_books(refrences) all_parts = self.get_all_parts(all_books) return self.get_text_from_parts(all_parts) def get_books(self, refrences): all_books = [] for url in refrences: response = self.request(self.BASE_URL + '/' + url) tree = etree.HTML(response.text) books_ref = tree.xpath('/html/body/div/table/tr/td/font/ul/li/a/@href') all_books += books_ref return all_books def get_all_parts(self, all_books): all_parts = [] request_counter = 0 try: for book in all_books: if request_counter > self.MAX_REQUESTS: return all_parts request_counter += 1 response = self.request(self.BASE_URL + '/' + book) tree = etree.HTML(response.text) try: book_parts = tree.xpath('/html/body/div/table/tr/td/font/ul/li/a/@href') except: book_parts = book self.delay(1/5) all_parts += book_parts except: return all_parts return all_parts def get_text_from_parts(self, all_parts): all_texts = [] for part in all_parts: response = self.request(self.BASE_URL + '/' + part) all_texts.append(response.text) return all_texts def get_name(self): return 'scraper_1' # a = ScrapperOne() # a.get_text()
true
88d3678b6449d1e4af65268b911f3ca3c1e73fef
Python
tible/TT
/tileMatrixPool.py
UTF-8
452
3.015625
3
[]
no_license
import time tilePool = [] tilePoolCount = [] for i in range(0,11): for j in range(0,11): print '*********', i, '*', j, '=', i*j if i*j not in tilePool: tilePool.append(i*j) tilePoolCount.append(1) else: tilePoolCount[tilePool.index(i*j)]+=1 # time.sleep(1) print '-----------------' print tilePool print tilePoolCount print len(tilePool), len(tilePoolCount)
true
9e42ca38fb9beec93741c63dc1187455ac186d02
Python
Stephanie199/NTU-FYP-URECA
/topic_detection/preproc.py
UTF-8
2,614
3.078125
3
[]
no_license
#!/usr/bin/env python #Preprocessing files import nltk from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem import PorterStemmer from num2words import num2words from ast import literal_eval import numpy as np import itertools import sys import codecs import re import string def remove_stopwords(res): result=[] stopset=set(stopwords.words("english")) for item in res: filtered=[word for word in item if word not in stopset] result.append(filtered) #print(result) print("Task 1: Stopwords removed successfully") return result def lem_data(apos): lem=[] wordnet_lemmatizer=WordNetLemmatizer() for each in apos: final=[] for n in each: r=wordnet_lemmatizer.lemmatize(n) final.append(r) lem.append(final) print("Task 2: Lemmatization completed successfully!") return lem def stem_data(dt): stem=[] apos=[] stemmer=PorterStemmer() for each in dt: final=[] for n in each: r=stemmer.stem(n) final.append(r) stem.append(final) stem=[[digitsToWords(subitem) for subitem in item] for item in stem] print("Task 3: Stemming, number to text conversion done") with codecs.open("files/processed.txt", "w", 'utf8') as f: for eachitem in stem: for every in eachitem: f.write(every+' ') f.write('\n') f.close() return stem def digitsToWords(item): if isinstance(item, (int, long)): return num2words(item) if isinstance(item, (str, unicode)) and item.isdigit(): return num2words(int(item)) return item def remove_apos(stemmed): for suffix in ["'s", "'v", "'t", "'d", "'r", "'"]: if stemmed.endswith(suffix): return stemmed[:-len(suffix)] return stemmed #print(n) dataset=[] quotes_to_remove = [u"'", u"\u2019", u"\u2018"] lines = [] res=[] with codecs.open("files/textfile.txt", "r", "utf-8") as f: for line in f: dataset.append(line.lower().strip().split()) print(dataset) for l in dataset: new=[] for word in l: for quote in quotes_to_remove: word=word.replace(quote,"") new.append(word) res.append(new) punc=res punc=[[x.strip(string.punctuation) for x in y] for y in punc] lines=[sum((line for line in punc if line), [])] print(punc) print("Task 1: Apostrophe and punctuation removed") nostop=remove_stopwords(lines) lemmed=lem_data(nostop) apos=stem_data(lemmed)
true
c34b3c77a7ce57bd274aadcc9e82b634b7f1b6d4
Python
zzz136454872/leetcode
/allCellsDistOrder.py
UTF-8
1,115
3.125
3
[]
no_license
from typing import * class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: queue=[] visited=[[False for j in range(C)] for i in range(R)] visited[r0][c0]=True queue.append([r0,c0]) out=[[r0,c0]] while len(queue)>0: r,c=queue.pop(0) if r>0 and not visited[r-1][c]: visited[r-1][c]=True queue.append([r-1,c]) out.append([r-1,c]) if c>0 and not visited[r][c-1]: visited[r][c-1]=True queue.append([r,c-1]) out.append([r,c-1]) if c < C-1 and not visited[r][c+1]: visited[r][c+1]=True queue.append([r,c+1]) out.append([r,c+1]) if r < R-1 and not visited[r+1][c]: visited[r+1][c]=True queue.append([r+1,c]) out.append([r+1,c]) return out R = 2 C = 2 r0 = 0 c0 = 1 sl=Solution() print(sl.allCellsDistOrder(R,C,r0,c0))
true
f3cd52078453b8d710cca3b8e7706f9954d1e921
Python
lpmeyer/pyiron_base
/pyiron_base/database/manager.py
UTF-8
6,490
2.546875
3
[ "BSD-3-Clause" ]
permissive
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. """ A class for mediating connections to SQL databases. """ from pyiron_base.generic.util import Singleton from pyiron_base.settings.generic import Settings from pyiron_base.database.generic import DatabaseAccess import os s = Settings() __author__ = "Jan Janssen, Liam Huber" __copyright__ = ( "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH" " - Computational Materials Design (CM) Department" ) __version__ = "0.0" __maintainer__ = "Liam Huber" __email__ = "huber@mpie.de" __status__ = "development" __date__ = "Sep 24, 2021" class DatabaseManager(metaclass=Singleton): def __init__(self): self._database = None self._use_local_database = False self._database_is_disabled = s.configuration["disable_database"] @property def database(self): return self._database @property def using_local_database(self): return self._use_local_database @property def database_is_disabled(self): return self._database_is_disabled @property def project_check_enabled(self): if self.database_is_disabled: return False else: return s.configuration["project_check_enabled"] @property def connection_timeout(self): """ Get the connection timeout in seconds. Zero means close the database after every connection. Returns: int: timeout in seconds """ return s.configuration["connection_timeout"] @connection_timeout.setter def connection_timeout(self, val): s.configuration["connection_timeout"] = val def open_connection(self): """ Internal function to open the connection to the database. Only after this function is called the database is accessable. """ if self._database is None and not self.database_is_disabled: self._database = DatabaseAccess( s.configuration["sql_connection_string"], s.configuration["sql_table_name"], timeout=s.configuration["connection_timeout"] ) def switch_to_local_database(self, file_name="pyiron.db", cwd=None): """ Swtich to an local SQLite based database. Args: file_name (str): SQLite database file name cwd (str/None): directory where the SQLite database file is located in """ if self.using_local_database: s.logger.log("Database is already in local mode or disabled!") else: if cwd is None and not os.path.isabs(file_name): file_name = os.path.join(os.path.abspath(os.path.curdir), file_name) elif cwd is not None: file_name = os.path.join(cwd, file_name) self.close_connection() self.open_local_sqlite_connection(connection_string="sqlite:///" + file_name) def open_local_sqlite_connection(self, connection_string): self._database = DatabaseAccess(connection_string, s.configuration["sql_table_name"]) self._use_local_database = True self._database_is_disabled = False def switch_to_central_database(self): """ Switch to central database """ if self._use_local_database: self.close_connection() self._database_is_disabled = s.configuration["disable_database"] if self.database_is_disabled: self._database = None else: self._database = DatabaseAccess( s.configuration["sql_connection_string"], s.configuration["sql_table_name"], ) self._use_local_database = False else: s.logger.log("Database is already in central mode or disabled!") def switch_to_viewer_mode(self): """ Switch from user mode to viewer mode - if viewer_mode is enable pyiron has read only access to the database. """ if s.configuration["sql_view_connection_string"] is not None and not self.database_is_disabled: if self._database.viewer_mode: s.logger.log("Database is already in viewer mode!") else: self.close_connection() self._database = DatabaseAccess( s.configuration["sql_view_connection_string"], s.configuration["sql_view_table_name"], ) self._database.viewer_mode = True else: print("Viewer Mode is not available on this pyiron installation.") def switch_to_user_mode(self): """ Switch from viewer mode to user mode - if viewer_mode is enable pyiron has read only access to the database. """ if s.configuration["sql_view_connection_string"] is not None and not self.database_is_disabled: if self._database.viewer_mode: self.close_connection() self._database = DatabaseAccess( s.configuration["sql_connection_string"], s.configuration["sql_table_name"], ) self._database.viewer_mode = True else: s.logger.log("Database is already in user mode!") else: print("Viewer Mode is not available on this pyiron installation.") def close_connection(self): """ Internal function to close the connection to the database. """ if self._database is not None: self._database.conn.close() self._database = None def top_path(self, full_path): """ Validated that the full_path is a sub directory of one of the pyrion environments loaded. Args: full_path (str): path Returns: str: path """ if full_path[-1] != "/": full_path += "/" if not self.project_check_enabled: return None for path in s.configuration["project_paths"]: if path in full_path: return path raise ValueError( "the current path {0} is not included in the .pyiron configuration. {1}".format( full_path, s.configuration["project_paths"] ) )
true
3cf8c7dc71ad0acc78666fb3897bcfb6ef10a08e
Python
menstruated/discord-leave-groups
/leave.py
UTF-8
3,357
2.6875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import discord, asyncio import os import shutil import subprocess from discord.ext import commands import json import time import sys import datetime import random import ctypes if not os.path.exists('config.json'): data = { 'token': "", 'prefix': "", } with open('config.json', 'w') as f: json.dump(data, f) config = json.loads(open("config.json","r").read()) token = config['token'] prefix = config['prefix'] def getembed(text): embed = discord.Embed( description=text, color=0x2f3136 ) return embed def checkConfig(): if not token == "" and not prefix == "": return else: if token == "": config['token'] = input('What is your token?\n') if prefix == "": config['prefix'] = input('Please choose a prefix for your commands e.g "+"\n') open('config.json','w+').write(json.dumps(config,indent=4,sort_keys=True)) print('The program will now close so everything works correctly.') time.sleep(5) sys.exit() return Client = discord.Client() Client = commands.Bot( description='cnr selfbot', command_prefix=config['prefix'], self_bot=True ) Client.remove_command('help') def getav(url, user): return discord.Embed(title='Avatar', color=0x2f3136).set_image(url=url).set_footer(text=user) @Client.event async def on_ready(): os.system('cls') width = shutil.get_terminal_size().columns def ui(): print() print() print("[+] Made by cnr [+]".center(width)) print() print(f"Current User: {Client.user}".center(width)) print(f"User ID: {Client.user.id}".center(width)) print() print(f"Prefix: {prefix}".center(width)) print(f"Date: {datetime.date.today().strftime('%d, %B %Y')}".center(width)) print() print("Commands:".center(width)) print(f" {prefix}leave - LEAVE THE FUCKING CHANNELS".center(width)) ui() @Client.command() async def leave(ctx): await ctx.message.delete() args = ctx.message.content.split() if len(args) == 1: text = f""" **Invalid Parse Of Arguments** `{args[0]}` **[partial group name]** """ embed = getembed(text) try: await ctx.send(embed=embed,delete_after=30) except: await ctx.send(f">>> {text}") else: args.pop(0) groupname = ' '.join(args) counter = 0 for channel in Client.private_channels: if isinstance(channel, discord.GroupChannel): if groupname in str(channel): try: await channel.leave() counter +=1 ctypes.windll.kernel32.SetConsoleTitleW( f"Discord group leaver / Left [{counter}] " f"github.com/terrorist" ) print(f'Left channel {channel}') except: pass print(f'Left {counter} channels in total.') checkConfig() Client.run(config['token'], bot=False, reconnect=True)
true
47ca9b85e69454cceb01a635759ca73e92271b91
Python
micdm/loto-tools
/btce/prices.py
UTF-8
2,183
2.703125
3
[]
no_license
#!/usr/bin/env python # curl https://btc-e.nz/api/3/ticker/ltc_rur-eth_rur-eth_btc-dsh_btc-nmc_usd-ppc_usd-nmc_btc-dsh_usd-eur_usd-eth_eur-ltc_usd-nvc_btc-dsh_eur-usd_rur-ltc_eur-btc_usd-ltc_btc-eth_ltc-ppc_btc-btc_eur-dsh_rur-eth_usd-nvc_usd-dsh_ltc-eur_rur-btc_rur-dsh_eth > data/last.data 2> /dev/null && curl https://btc-e.nz/api/3/info > data/info.data 2> /dev/null && python3 prices.py data/last.data data/info.data from decimal import Decimal, ROUND_DOWN import json import sys QUANTIZE_VALUE = Decimal('0.0001') START_CURRENCY = 'usd' START_AMOUNT = Decimal('1') PRICE_PART = Decimal('0.998') def handle_tick(prices: dict, limits: dict): moves = {} for key, price in prices.items(): currency1, currency2 = key.split('_') moves[(currency1, currency2)] = price moves[(currency2, currency1)] = 1 / price return max(get_profit_chains(moves, limits), key=lambda values: values[1] / len(values[0])) def get_profit_chains(moves, limits): chains = [(START_CURRENCY,)] while chains: chain = chains.pop() for pair, price in moves.items(): if chain[-1] == pair[0]: new_chain = chain + (pair[1],) if pair[1] == START_CURRENCY: profit = get_chain_profit(new_chain, moves, limits) if profit > 1: yield new_chain, profit elif pair[1] not in chain: chains.append(new_chain) def get_chain_profit(chain, moves, limits): amount = START_AMOUNT for pair in zip(chain[:-1], chain[1:]): amount = (amount * moves[pair] * PRICE_PART).quantize(limits[pair], rounding=ROUND_DOWN) return (amount / START_AMOUNT).quantize(QUANTIZE_VALUE) limits = {} for key, info in json.load(open(sys.argv[2]))['pairs'].items(): currency1, currency2 = key.split('_') value = Decimal('0.' + '0' * (info['decimal_places'] - 1) + '1') limits[(currency1, currency2)] = value limits[(currency2, currency1)] = value for line in open(sys.argv[1]): data = json.loads(line) print(handle_tick(dict((key, Decimal(value['last'])) for key, value in data.items()), limits))
true
dbb377282dd81783b6bb1b55b628fb1f2eab4e60
Python
destinationunknown/HackerRank
/Contests/Week of Code 37/average rating of top employees.py
UTF-8
605
3.328125
3
[]
no_license
'''input 5 84 92 61 50 95 ''' #!/bin/python from __future__ import print_function import os import sys from decimal import Decimal, ROUND_HALF_UP def averageOfTopEmployees(rating): #r average = 0.0 count = 0 for rat in rating: if rat >= 90 and rat <= 100: average += rat count += 1 average = Decimal(average/count + 0.0005).quantize(Decimal("0.01"), ROUND_HALF_UP) print (average) if __name__ == '__main__': n = int(raw_input()) rating = [] for _ in xrange(n): rating_item = int(raw_input()) rating.append(rating_item) averageOfTopEmployees(rating)
true
3733280a1d43002ccaf2c28e7499cf331aff788b
Python
vaspahomov/chess
/game_serializer.py
UTF-8
302
2.75
3
[]
no_license
import pickle class GameSerializer: def __init__(self): pass def save_game(self, figures): with open("figures.json") as figures_file: pickle.dump(figures, figures_file) def load_game(self): figures = pickle.load("game.json") return figures
true
afdd0990e1d7ce8d7de79649dab1a0165cc796c2
Python
demisto/content
/Packs/AzureSentinel/Scripts/MicrosoftSentinelConvertEntitiesToTable/MicrosoftSentinelConvertEntitiesToTable_test.py
UTF-8
1,485
3.40625
3
[ "MIT" ]
permissive
def test_format_entity(): """ Given: - An entity When: - calling format_entity function Then: - Validate the entity is formatted correctly """ entity = {'name': 'test', 'kind': 'test_kind', 'type': 'test_type', 'properties': {'testProp': 'test_value'}} expected = {'name': 'test', 'kind': 'test_kind', 'testProp': 'test_value'} from MicrosoftSentinelConvertEntitiesToTable import format_entity result = format_entity(entity) assert result == expected CONTEXT_RESULTS = ('[{"name": "test", "kind": "test_kind", "properties": {"testProp": "test_value", "isDomainJoined": true}},' '{"name": "test2", "kind": "test_kind2", "properties": {"testProp": "test_value2", "testProp2": "test_value3",' '"isDomainJoined": false}}]') EXPECTED_TABLE = "|Name|Kind|Test Prop|Is Domain Joined|Test Prop 2|\n" \ "|---|---|---|---|---|\n" \ "| test | test_kind | test_value | true | |\n" \ "| test2 | test_kind2 | test_value2 | false | test_value3 |\n" def test_convert_to_table(): """ Given: - A list of entities in string format When: - calling convert_to_table function Then: - Validate the table is created correctly """ from MicrosoftSentinelConvertEntitiesToTable import convert_to_table result = convert_to_table(CONTEXT_RESULTS) assert result.readable_output == EXPECTED_TABLE
true
e82ac23da9ac3f6b4b9e4a27d85b416fd347b4cd
Python
kmgowda/kmg-leetcode-python
/flower-planting-with-no-adjacent/flower-planting-with-no-adjacent.py
UTF-8
716
3.34375
3
[ "Apache-2.0" ]
permissive
// https://leetcode.com/problems/flower-planting-with-no-adjacent class Solution(object): def gardenNoAdj(self, N, paths): """ :type N: int :type paths: List[List[int]] :rtype: List[int] """ neighbors = dict() for i, j in paths: neighbors.setdefault(i-1, []).append(j-1) neighbors.setdefault(j-1, []).append(i-1) flowers = [0]*N #flowers to be planted at garden 1, ... N for i in range(N): #garden 1-N available = {1, 2, 3, 4} #flower 1-4 if i in neighbors: available -= {flowers[j] for j in neighbors[i]} flowers[i] = available.pop() return flowers
true
9cb7c116ef373c34d76648f8ca7e5e71e3d5bbfd
Python
chenchingnien/III_Project
/PTT_Crawler/defmeta.py
UTF-8
1,655
2.859375
3
[]
no_license
import requests from bs4 import BeautifulSoup title = str() def get_page_meta(url): jar = requests.cookies.RequestsCookieJar() jar.set("over18", "1", domain="www.ptt.cc") # 先做最基礎的判斷, 非公告和版規我回傳答案 if not "公告" in title and not "版規" in title: response = requests.get(url, cookies=jar).text html = BeautifulSoup(response) content = html.find("div", id="main-content") # 準備我們要回傳的字典 result = {} values = content.find_all("span", class_="article-meta-value") # 先把文章資訊記錄在字典裡 result["author"] = values[0].text result["board"] = values[1].text result["title"] = values[2].text result["time"] = values[3].text meta = content.find_all("div", class_="article-metaline") for m in meta: m.extract() right_meta = content.find_all("div", class_="article-metaline-right") for single_meta in right_meta: single_meta.extract() pushes = content.find_all("div", class_="push") score = 0 for single_push in pushes: pushtag = single_push.find("span", class_="push-tag").text if "推" in pushtag: score = score + 1 elif "噓" in pushtag: score = score - 1 single_push.extract() # 分數和內容 result["score"] = score result["content"] = content.text return result # 公告和版規我就直接回傳 None else: return None
true
f6af38af46ed2f72406558e15cdfe4c0687f75e7
Python
nachtsky1077/word_embedding_brand
/brand/main.py
UTF-8
2,636
2.921875
3
[]
no_license
from argparse import ArgumentParser import traceback import gensim import numpy as np import json from .debiasing import EmbeddingDebias from .utils import get_embedding_mat if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--pretrained_file', action='store', type=str, required=True, help='pretrained word embedding file name') parser.add_argument('--method', action='store', type=str, default='Hard', help='debias method') parser.add_argument('--subspace_dim', action='store', type=int, default=1, help='number of eigen-vectors preserved for bias subspace') parser.add_argument('--subspace_words', action='store', type=str, default='she,he;her,his;woman,man;Mary,John;herself,himself;daughter,son;mother,father;gal,guy;girl,boy;female,male', help='D sets of words, has to be in the form: w1_d1,w2_d1,...;w1_d2,w2_d2,...;...') parser.add_argument('--neutral_words', action='store', default='nurse', help='E sets of words, same format as subspace_words') parser.add_argument('--cfg', action='store', type=str, default='None', help='configuration file') args = parser.parse_args() try: # load w2v word embeddings b_flag = True if 'bin' in args.pretrained_file else False kv = gensim.models.KeyedVectors.load_word2vec_format(args.pretrained_file, binary=b_flag, limit=500000) except Exception: print('Fail to load pretrained word2vec model.') traceback.print_exc() exit(-1) if args.cfg == 'None': ds = [[word for word in D.split(',')] for D in args.subspace_words.split(';')] else: with open(args.cfg, 'r') as f: cfg = json.load(f) ds = cfg['definite_sets'] # prepare direction matrix sets dmat = [] for _, words in enumerate(ds): mat = get_embedding_mat(words, kv) dmat.append(np.asarray(mat)) es = [[word for word in E.split(',')] for E in args.neutral_words.split(';')] debias_worker = EmbeddingDebias(dmat, embedding=kv, k=args.subspace_dim, method=args.method) print('Debiasing worker initialization completed.') print('Debiasing using {}-debias method for word sets {}'.format(args.method, es)) subspace, new_embeddings = debias_worker.debiasing(es) print('subspace shape:', subspace.shape) for i, e in enumerate(es): for j, word in enumerate(e): print('Before debiasing:') print('{} : {}'.format(word, kv[word])) print('After debiasing:') print('{} : {}'.format(word, new_embeddings[i][j]))
true
a9c3539f330740dd3419f4906e60ca7844fa6f61
Python
jiadaizhao/LeetCode
/0601-0700/0668-Kth Smallest Number in Multiplication Table/0668-Kth Smallest Number in Multiplication Table.py
UTF-8
439
2.859375
3
[ "MIT" ]
permissive
class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: if m > n: m, n = n, m low = 1 high = m * n while low < high: mid = (low + high) // 2 count = 0 for i in range(1, m + 1): count += min(mid // i, n) if count < k: low = mid + 1 else: high = mid return low
true
edcb6ead35a3e0f365fe71591a008fea06b33061
Python
starschen/learning
/introduction_MIT/12_4强队的获胜概率.py
UTF-8
1,807
3.65625
4
[]
no_license
#encoding:utf8 #12.4强队的获胜概率 #模拟世界职业棒球大赛 import random import pylab def playSeries(numGames,teamProb): '''假定是numGames奇数,teamProb是0到1之间的浮点数,如果强队会获胜返回True''' numWon=0 for game in range(numGames): if random.random()<=teamProb: numWon+=1 return (numWon>numGames//2) def simSeries(numSeries): prob=0.5 fracWon=[] probs=[] while prob<=1.0: seriesWon=0.0 for i in range(numSeries): if playSeries(7,prob): seriesWon+=1 fracWon.append(seriesWon/numSeries) probs.append(prob) prob+=0.01 pylab.plot(probs,fracWon,linewidth=5) pylab.xlabel('Probability of Winning a Game') pylab.ylabel('Probability of Winning a Series') pylab.axhline(0.95) pylab.ylim(0.5,1.1) pylab.title(str(numSeries)+'Seven-Game Series') # simSeries(400) # pylab.show() #一场比赛应该有多少局 def findSeriesLEngth(teamProb): numSeries=200 maxLen=2500 step=10 def fracWon(teamProb,numSeries,seriesLen): won=0.0 for series in range(numSeries): if playSeries(seriesLen,teamProb): won+=1 return won/numSeries winFrac=[] xvals=[] for seriesLen in range(1,maxLen,step): xvals.append(seriesLen) winFrac.append(fracWon(teamProb,numSeries,seriesLen)) pylab.plot(xvals,winFrac,linewidth=5) pylab.xlabel('Length of Series') pylab.xlabel('Length of Series') pylab.ylabel('Probability of Winning Series') pylab.title(str(round(teamProb,4))+'Probability of Better Team Winning a Game') pylab.axhline(0.95) YanksPRob=0.636 PhilsProb=0.574 findSeriesLEngth(YanksPRob/(YanksPRob+PhilsProb)) pylab.show()
true
b9924b546c35f3ee58579e4efc41c274183ca739
Python
camdentest/public-test
/NameProgram.py
UTF-8
508
4.625
5
[]
no_license
# Sample Program name = input("Hi! What is your name? ") print("\nHello " + name + "!") firstLetter = name[0].capitalize() if firstLetter >= "A" and firstLetter <= "H": print("Your name is at the beginning of the alphabet") elif firstLetter >= "I" and firstLetter <= "R": print("Your name is in the middle of the alphabet") elif firstLetter >= "S" and firstLetter <= "Z": print("Your name is at the end of the alphabet") else: print("The first letter of your name isn't in the alphabet")
true
9bf009c67eed9d5e3054dedd19da012aef00ff3a
Python
asmodehn/aiokraken
/aiokraken/model/tests/strats/st_asset.py
UTF-8
734
2.671875
3
[ "GPL-1.0-or-later", "MIT" ]
permissive
import functools import pandas as pd from aiokraken.model.asset import AssetClass, Asset from hypothesis import strategies as st # Using partial call here to delay evaluation (and get same semantics as potentially more complex strategies) AssetClassStrategy = functools.partial(st.sampled_from, AssetClass) @st.composite def AssetStrategy(draw): return Asset( altname= draw(st.text(max_size=5)), aclass = draw(st.text(max_size=5)), decimals= draw(st.integers()), display_decimals= draw(st.integers()) ) if __name__ == '__main__': for n in range(1, 10): print(repr(AssetClassStrategy().example())) for n in range(1, 10): print(repr(AssetStrategy().example()))
true
7dc3dda377b0bf72b6cd363dcc722365adaaa0c2
Python
akashrl/Apriori-Algorithm-Python
/association-rules.py
UTF-8
8,499
2.734375
3
[]
no_license
#alankala import pandas as pd import numpy as np from collections import Counter import itertools from pprint import pprint import copy from random import randint import matplotlib.pyplot as plt import sys filename = sys.argv[1] minsup = float(sys.argv[2]) minconf = float(sys.argv[3]) df = pd.read_csv(filename, keep_default_na=False) df.replace({False : 0, True : 1}, inplace=True) # df.replace(True, 1, inplace=True) df = pd.get_dummies(df.astype(str), columns=['city', 'state', 'alcohol', 'noiseLevel', 'attire', 'priceRange']) # print(df) # boolean_headers = ['goodForGroups', 'open', 'delivery', 'waiterService', 'caters'] # for (columnName, columnData) in df.iteritems(): # print('Colunm Name : ', columnName) # print('Column Contents : ', columnData.values) delimiter = "&&" # Get Candidate Sets and Prune them def apriori_generator(L_k, k): Ck = {} keys = list(L_k.keys()) # print(keys) total_keys = len(keys) # Joining L_k-1 with itself to get probable L_k for i in range(total_keys): for j in range(i+1, total_keys): cnt = 0 temp_key_1 = keys[i].split(delimiter) temp_key_2 = keys[j].split(delimiter) for attr in temp_key_1: if attr in temp_key_2: cnt += 1 if cnt == k-1: new_set = set(temp_key_1 + temp_key_2) new_key = delimiter.join(list(new_set)) Ck[new_key] = 0 # Perform pruning candidate_keys = list(Ck) # print(L_k) # print(candidate_keys) for key in candidate_keys: keys = key.split(delimiter) subsets = list(set(itertools.combinations(keys,k))) for subset in subsets: sub_key = delimiter.join(subset) # print(sub_key) if sub_key not in L_k: del Ck[key] break # print(Ck) return Ck def apriori(min_sup, df): L_k = [] Li = {} array = df.values.astype('int32') # print(array) min_sup_count = int(min_sup*len(df)) # print("Minimum Support Count: ", min_sup_count) for i in range(0, len(df.columns)): if np.sum(array[:, i]) >= min_sup_count: Li[df.columns[i]] = np.sum(array[:,i]) L_k.append(Li) # print(Li) k = 1 while len(L_k[k-1]) > 0: Li = {} Ck = apriori_generator(L_k[k-1], k) # Get support for each keyset candidate_keys = list(Ck) for key in candidate_keys: intersection_set = np.ones(len(array)) for item in key.split(delimiter): column_idx = df.columns.get_loc(item) intersection_set = np.logical_and(intersection_set, array[:, column_idx]) Ck[key] += np.sum(intersection_set) # print(np.sum(intersection_set)) if Ck[key] < min_sup_count: del Ck[key] L_k.append(Ck) k += 1 return L_k L_k = apriori(minsup, df) # for i in L_k: # print(i) def apriori_confidence(L_k, min_conf): # For single variable consequents rules = [] rhs = list(L_k[0].keys()) for consequent in rhs: for i in range(0, len(L_k)-1): for itemsets in list(L_k[i].keys()): numerator = 0 confidence = 0 key_1 = itemsets + delimiter + consequent key_2 = consequent + delimiter + itemsets if key_1 in L_k[i+1]: numerator = L_k[i+1][key_1] elif key_2 in L_k[i+1]: numerator = L_k[i+1][key_2] if numerator != 0: confidence = float(numerator)/L_k[i][itemsets] if confidence >= min_conf: rules.append([(itemsets, consequent), confidence, numerator]) return rules rules = apriori_confidence(L_k, minconf) rules_count = {} for i in rules: splitted = i[0][0].split(delimiter) length = len(splitted) if str(length) not in rules_count: rules_count[str(length)] = 1 else: rules_count[str(length)] += 1 print() for i in range(1, len(L_k)-1): print("FREQUENT-ITEMS " + str(i+1) + " " + str(len(L_k[i]))) print() for key in rules_count.keys(): if rules_count[key] > 0 and int(key) > 1: print("ASSOCIATION-RULES " + key + " " + str(rules_count[key])) # to_plot = np.array([[0.25, 0.75]]) # items_cnt = [] # rules_cnt = [] # for entry in to_plot: # L_k = apriori(entry[0], df) # rules = apriori_confidence(L_k, entry[1]) # total_item = 0 # total_rule = 0 # for i in range(1, len(L_k)-1): # total_item += len(L_k[i]) # for i in rules: # splitted = i[0][0].split(delimiter) # length = len(splitted) # if str(length) not in rules_count: # rules_count[str(length)] = 1 # else: # rules_count[str(length)] += 1 # for key in rules_count.keys(): # if rules_count[key] > 0 and int(key) > 1: # total_rule += rules_count[key] # items_cnt.append(total_item) # # print(total_rule) # rules_cnt.append(total_rule) # # print(total_item, total_rule) # print(items_cnt) # print(rules_cnt) # print((to_plot[:, 0], items_cnt)) # fig, ax = plt.subplots(figsize=(20, 10)) # ax.plot(to_plot[:, 0], items_cnt) # ax.scatter(to_plot[:, 0], items_cnt) # fig.suptitle('Values of |I| and |R| at Minsup = 25% and Minconf = 75%', fontsize=20) # ax.set_xlabel('Minsup', fontsize=18) # ax.set_ylabel('Item Count', fontsize=18) # for i in range(1): # string = '|I|=' + str(items_cnt[i]) + ' ' + '|R|=' + str(rules_cnt[i]) # ax.annotate(string, (to_plot[i][0], items_cnt[i]), size=14) # plt.show() # to_plot = np.array([[0.10, 0.75], [0.30, 0.75], [0.50, 0.75]]) # items_cnt = [] # rules_cnt = [] # for entry in to_plot: # L_k = apriori(entry[0], df) # rules = apriori_confidence(L_k, entry[1]) # total_item = 0 # total_rule = 0 # for i in range(1, len(L_k)-1): # total_item += len(L_k[i]) # for i in rules: # splitted = i[0][0].split(delimiter) # length = len(splitted) # if str(length) not in rules_count: # rules_count[str(length)] = 1 # else: # rules_count[str(length)] += 1 # for key in rules_count.keys(): # if rules_count[key] > 0 and int(key) > 1: # total_rule += rules_count[key] # items_cnt.append(total_item) # # print(total_rule) # rules_cnt.append(total_rule) # # print(total_item, total_rule) # print(items_cnt) # print(rules_cnt) # fig, ax = plt.subplots(figsize=(20, 10)) # ax.plot(to_plot[:, 0], items_cnt) # ax.scatter(to_plot[:, 0], items_cnt) # fig.suptitle('Values of |I| and |R| over varying minsup', fontsize=20) # ax.set_xlabel('Minsup', fontsize=18) # ax.set_ylabel('Item Count', fontsize=18) # for i in range(3): # string = '|I|=' + str(items_cnt[i]) + ' ' + '|R|=' + str(rules_cnt[i]) # ax.annotate(string, (to_plot[i][0], items_cnt[i]), size=14) # plt.show() # to_plot = np.array([[0.25, 0.40], [0.25, 0.60], [0.25, 0.80]]) # items_cnt = [] # rules_cnt = [] # for entry in to_plot: # L_k = apriori(entry[0], df) # rules = apriori_confidence(L_k, entry[1]) # total_item = 0 # total_rule = 0 # for i in range(1, len(L_k)-1): # total_item += len(L_k[i]) # for i in rules: # splitted = i[0][0].split(delimiter) # length = len(splitted) # if str(length) not in rules_count: # rules_count[str(length)] = 1 # else: # rules_count[str(length)] += 1 # for key in rules_count.keys(): # if rules_count[key] > 0 and int(key) > 1: # total_rule += rules_count[key] # items_cnt.append(total_item) # # print(total_rule) # rules_cnt.append(total_rule) # # print(total_item, total_rule) # print(items_cnt) # print(rules_cnt) # fig, ax = plt.subplots(figsize=(20, 10)) # ax.plot(to_plot[:, 1], items_cnt) # ax.scatter(to_plot[:, 1], items_cnt) # fig.suptitle('Values of |I| and |R| over varying minconf', fontsize=20) # ax.set_xlabel('Minconf', fontsize=18) # ax.set_ylabel('Item Count', fontsize=18) # for i in range(3): # string = '|I|=' + str(items_cnt[i]) + ' ' + '|R|=' + str(rules_cnt[i]) # ax.annotate(string, (to_plot[i][1], items_cnt[i]), size = 14) # plt.show()
true
f583c9fb165af3966bad7024f5e605896a98257f
Python
Sennevs/custom_tensorflow_snippets
/metrics/backward_kl_divergence.py
UTF-8
894
3.125
3
[ "MIT" ]
permissive
import tensorflow as tf class BackwardKLDivergence(tf.keras.metrics.KLDivergence): def __init__(self, name='backward_kl_divergence', **kwargs): """ Custom Keras metric that calculates backward KL-Divergence, which is just the KLDivergence metric class in Keras with the y_true and y_pred parameters switched. """ super(BackwardKLDivergence, self).__init__(name=name, **kwargs) return def update_state(self, y_true, y_pred, sample_weight=None): return super(BackwardKLDivergence, self).update_state(y_pred, y_true, sample_weight=sample_weight) # Example code # y_pred = tf.constant([[0.1, 0.9], [0, 1]]) # y_true = tf.constant([[0.8, 0.2], [0.1, 0.9]]) # sw = tf.constant([0.5, 0.5]) # bkld = BackwardKLDivergence() # bkld.update_state(y_true, y_pred, sample_weight=sw) # print(f'Backward KL-Divergence: {bkld.result()}')
true
2980d2db7eec31248f67b36616111e2143353c01
Python
gconybear/soccer-highlights
/app.py
UTF-8
2,201
2.65625
3
[]
no_license
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import api_call app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY]) server = app.server DROPDOWN_WIDTH = '500px' DROPDOWN_COLOR = '#000000' global data data = api_call.getHighlights() # data = { # 'a': [(1,2,4)] # } # style={'padding-left':'25px'} league_drop = html.Div(children=[dcc.Dropdown(id='league-drop', options=[ {'label': i, 'value': i} for i in sorted(list(data.keys())) ], placeholder="Choose League / Competition....", style={'width': DROPDOWN_WIDTH, 'color': DROPDOWN_COLOR})]) body = html.Div([ dbc.Row( [ html.H1(children=["Soccer Highlights"]), ], justify="center", align="center", className="h-50" ), html.Br(), dbc.Row([ # dbc.Col(html.Label('Choose League and Match: ')), dbc.Col(html.Div(league_drop)), dbc.Col(html.Div(id='second-drop-con')) ], align='center'), html.Br(), html.Hr(), html.Div(id='vid') ]) app.layout = dbc.Container([body]) @app.callback( Output('second-drop-con', 'children'), [Input('league-drop', 'value')] ) def second_drop(val): games = data[val] games_embed = [(x[0], x[2]) for x in games] second = dcc.Dropdown(id='game-drop', options=[ {'label': game, 'value': source} for (game, source) in games_embed ], placeholder="Choose Match...", style={'width': DROPDOWN_WIDTH, 'color': DROPDOWN_COLOR}) return second @app.callback( Output('vid', 'children'), [Input('league-drop', 'value'), Input('game-drop', 'value')] ) def show_vid(league, source): out = html.Center([ html.Div([ html.Iframe(src=source, style={'width': '100%', 'height':'100%'}) ], style={'width': '1000px', 'height':'750px'}) ]) return out if __name__ == "__main__": app.run_server(debug=False, port=7050)
true
3c62e862e56a06aabb5cc2633a8d1ac6b9e2df17
Python
Tawkat/Bengali-Spell-Checker-and-Auto-Correction-Suggestion-for-MS-Word
/spell checker/spell_checker.py
UTF-8
2,726
2.9375
3
[]
no_license
from flask import Flask, jsonify import re import sys import tkinter as tk import numpy as np import pandas as pd import json import codecs words = [] with codecs.open('freq_lt_15.txt', mode='r', encoding='utf-8') as f: for line in f: words.append(line.split(' ')[0]) w_rank = {} for i, word in enumerate(words): w_rank[word] = i WORDS = w_rank def words(text): return re.findall(r'\w+', text.lower()) def P(word): """ Probability of `word` use inverse of rank as proxy, returns 0 if the word isn't in the dictionary :param word: The word we want the probability for :rtype: object """ return - WORDS.get(word, 0) def correction(word): """ Most probable spelling correction for word :param word: Incorrect word :return: The most probable candidate """ # return max(candidates(word), key=P) def candidates(word): """ Generate possible spelling corrections for word :param word: Input word :return: All probable candidate words in 1 or 2 edit distance away """ return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word]) def known(words): """ The subset of `words` that appear in the dictionary of WORDS :param words: List - list of words :return: List - Words that exist in the dictionary """ return set(w for w in words if w in WORDS) def edits1(word): """ All edits that are one edit away from `word` :param word(str): input :return: set of words that are 1 edit distance way """ letters = 'ঁংঃঅআইঈউঊঋএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) def edits2(word): """ All edits that are two edit away from `word` :param word(str): input :return: set of words that are 2 edit distance way """ return (e2 for e1 in edits1(word) for e2 in edits1(e1)) def correctSentence(text): """ Return the list of corrected word :param text: input sentence :return: list of corrected words """ words = text.split(' ') return [correction(word) for word in words]
true
0b28357b3c769cfc3bd5d3cb4b79fce2f79bc7d2
Python
mkalinin/eth2.0-specs
/test_libs/pyspec/eth2spec/debug/random_value.py
UTF-8
4,841
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
from random import Random from typing import Any from enum import Enum UINT_SIZES = [8, 16, 32, 64, 128, 256] basic_types = ["uint%d" % v for v in UINT_SIZES] + ['bool', 'byte'] random_mode_names = ["random", "zero", "max", "nil", "one", "lengthy"] class RandomizationMode(Enum): # random content / length mode_random = 0 # Zero-value mode_zero = 1 # Maximum value, limited to count 1 however mode_max = 2 # Return 0 values, i.e. empty mode_nil_count = 3 # Return 1 value, random content mode_one_count = 4 # Return max amount of values, random content mode_max_count = 5 def to_name(self): return random_mode_names[self.value] def is_changing(self): return self.value in [0, 4, 5] def get_random_ssz_object(rng: Random, typ: Any, max_bytes_length: int, max_list_length: int, mode: RandomizationMode, chaos: bool) -> Any: """ Create an object for a given type, filled with random data. :param rng: The random number generator to use. :param typ: The type to instantiate :param max_bytes_length: the max. length for a random bytes array :param max_list_length: the max. length for a random list :param mode: how to randomize :param chaos: if true, the randomization-mode will be randomly changed :return: the random object instance, of the given type. """ if chaos: mode = rng.choice(list(RandomizationMode)) if isinstance(typ, str): # Bytes array if typ == 'bytes': if mode == RandomizationMode.mode_nil_count: return b'' if mode == RandomizationMode.mode_max_count: return get_random_bytes_list(rng, max_bytes_length) if mode == RandomizationMode.mode_one_count: return get_random_bytes_list(rng, 1) if mode == RandomizationMode.mode_zero: return b'\x00' if mode == RandomizationMode.mode_max: return b'\xff' return get_random_bytes_list(rng, rng.randint(0, max_bytes_length)) elif typ[:5] == 'bytes' and len(typ) > 5: length = int(typ[5:]) # Sanity, don't generate absurdly big random values # If a client is aiming to performance-test, they should create a benchmark suite. assert length <= max_bytes_length if mode == RandomizationMode.mode_zero: return b'\x00' * length if mode == RandomizationMode.mode_max: return b'\xff' * length return get_random_bytes_list(rng, length) # Basic types else: if mode == RandomizationMode.mode_zero: return get_min_basic_value(typ) if mode == RandomizationMode.mode_max: return get_max_basic_value(typ) return get_random_basic_value(rng, typ) # Vector: elif isinstance(typ, list) and len(typ) == 2: return [get_random_ssz_object(rng, typ[0], max_bytes_length, max_list_length, mode, chaos) for _ in range(typ[1])] # List: elif isinstance(typ, list) and len(typ) == 1: length = rng.randint(0, max_list_length) if mode == RandomizationMode.mode_one_count: length = 1 if mode == RandomizationMode.mode_max_count: length = max_list_length return [get_random_ssz_object(rng, typ[0], max_bytes_length, max_list_length, mode, chaos) for _ in range(length)] # Container: elif hasattr(typ, 'fields'): return typ(**{field: get_random_ssz_object(rng, subtype, max_bytes_length, max_list_length, mode, chaos) for field, subtype in typ.fields.items()}) else: print(typ) raise Exception("Type not recognized") def get_random_bytes_list(rng: Random, length: int) -> bytes: return bytes(rng.getrandbits(8) for _ in range(length)) def get_random_basic_value(rng: Random, typ: str) -> Any: if typ == 'bool': return rng.choice((True, False)) if typ[:4] == 'uint': size = int(typ[4:]) assert size in UINT_SIZES return rng.randint(0, 2**size - 1) if typ == 'byte': return rng.randint(0, 8) else: raise ValueError("Not a basic type") def get_min_basic_value(typ: str) -> Any: if typ == 'bool': return False if typ[:4] == 'uint': size = int(typ[4:]) assert size in UINT_SIZES return 0 if typ == 'byte': return 0x00 else: raise ValueError("Not a basic type") def get_max_basic_value(typ: str) -> Any: if typ == 'bool': return True if typ[:4] == 'uint': size = int(typ[4:]) assert size in UINT_SIZES return 2**size - 1 if typ == 'byte': return 0xff else: raise ValueError("Not a basic type")
true
945f773e2d9fc40b592f830c7c97d1262869944c
Python
priyadharshinikrishnana/pro
/pro7.py
UTF-8
272
3.03125
3
[]
no_license
priya1=int(input()) priya2=list(map(int,input().split())) viji=0 for x in range(len(priya2)-2): for y in range(x+1,len(priya2)-1): for z in range(y+1,len(priya2)): if priya2[x]<priya2[y]<priya2[z] and x<y<z: viji=viji+1 print(viji)
true
33bbce4312f752fc595d5103b023aeaab31b7ff4
Python
Ntakato/AtCoder
/ABC133/b.py
UTF-8
495
3.15625
3
[]
no_license
import math def dis(n,x,y): distance = 0 for i in range(len(x)): distance += (x[i]-y[i])*(x[i]-y[i]) # print(distance) return math.sqrt(distance) n,d = [int(i) for i in input().split()] x = [[int(i) for i in input().split()] for i in range(n)] # print(x) ans = 0 for i in range(n): for j in range(i+1,n): # print(dis(d,x[i],x[j])) # print(dis(d,x[i],x[j]).is_integer()) if(dis(d,x[i],x[j]).is_integer()): ans += 1 print(ans)
true
7a35a586185aa441183a08b6ae4f31af4f347a22
Python
channghiep/snake_game
/main.py
UTF-8
1,257
3.234375
3
[]
no_license
from turtle import Turtle, Screen import time from snake import Snake from food import Food from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.snake_up, "w") screen.onkey(snake.snake_down, "s") screen.onkey(snake.snake_left, "a") screen.onkey(snake.snake_right, "d") game_on = True while game_on: screen.update() time.sleep(0.1) snake.moving_forward() #Detect contact with food if snake.head.distance(food) < 15: food.refresh() snake.extend() scoreboard.add_score() #Detect collision if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: # scoreboard.game_over() # for block in range(0,len(snake.blocks)): # snake.blocks[block].goto(1000,1000) # game_on = False scoreboard.reset() snake.reset() # snake = Snake( ) #Detect collision with tail for block in snake.blocks[1:]: if snake.head.distance(block) < 10: game_on = False scoreboard.game_over() screen.exitonclick()
true
7d3af9e433d5cbaf94699721f0b9ab8b7dcd9254
Python
jiyabing/learning
/开班笔记/python基础部分/day16/code/try_except1.py
UTF-8
929
4.34375
4
[]
no_license
#此示例示意用try-except语句来捕获异常 def div_apple(n): '此示例用分苹果来示意捕获异常' print('%d个苹果你想要分给几个人?' %n) s = input('输入人数:') cnt = int(s) #<--此处可能会引起ValueError类型的错误 result = n / cnt #<--此处可能会引起ZeroDivisionError类型的错误 print('每人分了',result,'个苹果') try: div_apple(10) #第一种 except ValueError: print('发生了值错误,以转为正常状态') except ZeroDivisionError: print('发生了被零除的错误') #也可如下: except (ValueError,ZeroDivisionError): print('发生错误') except: print('其他的所有异常都有我来处理') else: #此处语句只有在没有发生异常时才会执行 print('没有错误发生,苹果分完') finally: print('有或没有异常,都会执行') print('程序正常退出')
true
0fd6640655df9fb6e97f357cd5a2feb27b9b2517
Python
kalvare/machine_learning
/core/unit_tests/test_activations.py
UTF-8
493
2.578125
3
[ "MIT" ]
permissive
import unittest import torch import numpy as np from core.activations.activations import relu_grad class TestActivations(unittest.TestCase): def test_relu_gradient(self): x = torch.zeros(4, 100) x[2, 62] = 1 x[3, 79] = 15 x[1, 43] = 0 x[0, 29] = -5 grad = relu_grad(x) self.assertTrue(grad[2, 62] == 1) self.assertTrue(grad[3, 79] == 1) self.assertTrue(grad[1, 43] == 0) self.assertTrue(grad[0, 29] == 0)
true
3a5e080ee20cd348ced277f49c79b5ad762b0073
Python
leduykhanh/codehehiew
/question3.py
UTF-8
5,619
3.328125
3
[]
no_license
from collections import OrderedDict, deque from copy import copy, deepcopy class Vertex(object): def __init__(self, name, weight): self.name = name self.weight = weight def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __hash__(self): return hash((self.name, self.weight)) def __str__(self): return '(' + self.name + ',' + str(self.weight) + ')' def __repr__(self): return '(' + self.name + ',' + str(self.weight) + ')' class DAGraph(object): def __init__(self): """ Construct a new DAGraph with no vertices or edges. """ self.reset_graph() def has_vertex(self, vertex): for k in self.graph: if k.name == vertex.name: return True return False def add_vertex(self, vertex, graph=None): """ Add a vertex if it does not exist yet, or error out. """ if not graph: graph = self.graph if self.has_vertex(vertex): raise KeyError('vertex %s already exists' % vertex_name) graph[vertex] = set() def add_edge(self, ind_vertex, dep_vertex, graph=None): if not graph: graph = self.graph if ind_vertex not in graph or dep_vertex not in graph: raise KeyError('one or more vertices do not exist in graph') test_graph = deepcopy(graph) test_graph[ind_vertex].add(dep_vertex) is_valid, message = self.validate(test_graph) if is_valid: graph[ind_vertex].add(dep_vertex) def ind_vertices(self, graph=None): """ Returns a list of all vertices in the graph with no dependencies. """ if graph is None: graph = self.graph dependent_vertices = set(vertex for dependents in graph.values() for vertex in dependents) return [vertex for vertex in graph.keys() if vertex not in dependent_vertices] def validate(self, graph=None): graph = graph if graph is not None else self.graph if len(self.ind_vertices(graph)) == 0: return False, 'no independent vertices detected' try: self.topological_sort(graph) except ValueError: return False, 'failed topological sort' return True, 'valid' def topological_sort(self, graph=None): """ Returns a topological ordering of the DAGraph. Raises an error if this is not possible (graph is not valid). """ if graph is None: graph = self.graph in_degree = {} for u in graph: in_degree[u] = 0 for u in graph: for v in graph[u]: in_degree[v] += 1 queue = deque() for u in in_degree: if in_degree[u] == 0: queue.appendleft(u) l = [] while queue: u = queue.pop() l.append(u) for v in graph[u]: in_degree[v] -= 1 if in_degree[v] == 0: queue.appendleft(v) if len(l) == len(graph): return l else: raise ValueError('graph is not acyclic') def find_all_paths(self, start, path=[]): path = path + [start] if start not in self.graph: return [] if len(self.graph[start]) == 0: return [path] paths = [] for vertex in self.graph[start]: if vertex not in path: new_paths = self.find_all_paths(vertex, path) for new_path in new_paths: paths.append(new_path) return paths """ Function code """ def find_optimal_path(self, start): all_paths = self.find_all_paths(start) sum_weights = 0 optimal_path = [] for path in all_paths: current_sum = sum(v.weight for v in path) if current_sum > sum_weights: sum_weights = current_sum optimal_path = path return optimal_path """ Time complexity : O(ve), v is the number of vertices, e is the number of edges """ def reset_graph(self): self.graph = OrderedDict() """ Test Code """ import unittest class TestFlattenMethods(unittest.TestCase): def test_the_example(self): a = Vertex("A", 1) b = Vertex("B", 2) c = Vertex("C", 2) g = DAGraph() g.add_vertex(a) g.add_vertex(b) g.add_vertex(c) g.add_edge(a, b) g.add_edge(b, c) g.add_edge(a, c) r = g.find_optimal_path(a) er = [a, b, c] self.assertEqual(r, er) def test_second(self): a = Vertex("A", 1) b = Vertex("B", 2) c = Vertex("C", 3) d = Vertex("D", 4) e = Vertex("E", 5) g = DAGraph() g.add_vertex(a) g.add_vertex(b) g.add_vertex(c) g.add_vertex(d) g.add_vertex(e) g.add_edge(a, b) g.add_edge(b, c) g.add_edge(b, d) g.add_edge(d, e) g.add_edge(c, e) r = g.find_optimal_path(a) er = [a, b, d, e] self.assertEqual(r, er) if __name__ == '__main__': unittest.main() """ Bonus : If the graph is cyclic (don't call validate method), to avoid infinite loop, we only visit the vertex if it's not in the path. The condition to stop is the vertex has no neighbours that doesn't belong to the path: len([v for v in self.graph[start] if v not in path]) == 0: """
true
b0952fe725570375d3f8dd23f0cf0ed191b03e42
Python
SimonBerens/StuyHacksVII
/utils/authenticate.py
UTF-8
2,533
3.296875
3
[]
no_license
import sqlite3 from werkzeug.security import generate_password_hash, check_password_hash def register_user(username, password, repassword): ''' Attempts to register a user and enter it in the users table. Returns a tuple containing a boolean indicating success and a message to flash to the user. ''' if username == '' or password == '' or repassword == '': return (False, "Please fill in all fields.") elif password != repassword: return (False, "Passwords do not match!") with sqlite3.connect("cyber.db") as db: c = db.cursor() if user_exists(username): return (False, "Username {} already exists.".format(username)) else: pw_hash = generate_password_hash(password) command = "INSERT INTO profiles (username, password) VALUES(?, ?);" c.execute(command, (username, pw_hash)) db.commit() return (True, "Successfully registered {}".format(username)) def user_exists(username): ''' Returns whether a user with the given username exists ''' with sqlite3.connect("cyber.db") as db: c = db.cursor() command = "SELECT * FROM profiles WHERE username = ?" c.execute(command, (username,)) return len(c.fetchall()) > 0 def login_user(username, password): ''' Attempts to log in a user by checking the users table. Returns a tuple containing a boolean indicating success and a message to flash to the user. ''' if username == '' or password == '': return (False, "Username or password missing!") with sqlite3.connect("cyber.db") as db: c = db.cursor() command = "SELECT username, password, userid FROM profiles;" c.execute(command) for user in c: if user and username == user[0]: if check_password_hash(user[1], password): return (True, "Successfully logged in!", user[2]) return (False, "Incorrect username or password.", 0) def is_loggedin(session): ''' Given a session, returns the username of the user if the user is logged in. Otherwise, returns False. ''' if session.get('loggedin') is None: return False return session.get('loggedin') def get_userid(session): name = is_loggedin(session) with sqlite3.connect("cyber.db") as db: c = db.cursor() command = "SELECT userid FROM profiles WHERE username = ?" c.execute(command, (name,)) return c.fetchone()[0]
true
d1421b78db5ba84d402752f4f0a9edce9f28a433
Python
gjwlsdnr0115/Computer_Programming_Homework
/lab4_2015198005/lab4_p1.py
UTF-8
557
4.1875
4
[]
no_license
# user input income = int(input('Enter the taxable income in USD: ')) # initializing tax variable tax = 0 if income <= 750: tax = income * 0.01 elif income <= 2250: tax = (income - 750) * 0.02 + 7.50 elif income <= 3750: tax = (income - 2250) * 0.03 + 37.50 elif income <= 5250: tax = (income - 3750) * 0.04 + 82.50 elif income <= 7000: tax = (income - 5250) * 0.05 + 142.50 else: tax = (income - 7000) * 0.06 + 230.00 # print result using 2 digits precision after the fractional point print('Tax due:', format(tax, '.2f'), 'USD')
true
c0fb26d9cb757c972f03f4ccd27a46c227e98046
Python
handevmin/DataStructure-and-Algorithm
/DP/1904_01타일.py
UTF-8
182
2.921875
3
[]
no_license
import sys n = int(sys.stdin.readline()) memory = [0]*1000001 memory[1] = 1 memory[2] = 2 for i in range(3,n+1): memory[i] = (memory[i-1] + memory[i-2]) %15746 print(memory[n])
true
5157c5df50c576c7b12ac81fa84a9f6f52fde196
Python
ashutosh-narkar/LeetCode
/stock_market_1.py
UTF-8
860
4.65625
5
[]
no_license
#!/usr/bin/env python ''' Beating the stock market Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. ''' def bestBuySell(stock): buy, sell, minPrice, maxProfit = [0] * 4 for i in range(len(stock)): if stock[i] < stock[minPrice]: minPrice = i profit = stock[i] - stock[minPrice] if profit > maxProfit: maxProfit = profit sell = i buy = minPrice return (buy, sell, maxProfit) if __name__ == '__main__': stock = [1, 3, 0, 8, 7, 6, 9] buy, sell, profit = bestBuySell(stock) print 'Buy on day {}. Sell on day {}. Profit is ${}'.format(buy, sell, profit)
true
a114eed2c512166df0689cc5050d156d668abbc0
Python
daniel-reich/ubiquitous-fiesta
/4gDNqQB355FFGFFWN_9.py
UTF-8
137
2.625
3
[]
no_license
def available_spots(lst, num): return sum([ (lst[idx-1] % 2) == num % 2 or (lst[idx] % 2 == num %2) for idx in range(1,len(lst)) ])
true
221c51da39c5f021ab042e8c3820e22cfa38d879
Python
ukyo/roman-ngram
/roman2ngram.py
UTF-8
1,751
3.015625
3
[]
no_license
#!/usr/bin/python #coding: utf8 import sys alphabet = 'abcdefghijklmnopqrstuvwxyz-,.' row = [a for a in alphabet] spliter = ' ' def print_row_label(): return spliter + spliter.join(row) def build_col_label(n): short_col = [] if n > 2: short_col = ['^'] short_col_ = short_col[:] for i in range(n - 3): short_col__ = short_col_[:] for x in short_col__: for y in row: short_col__.append(x + y) short_col_ = short_col__ short_col.extend(short_col_) col = ['^'] + row for i in range(n - 2): col_ = [] for x in col: for y in row: col_.append(x + y) col = col_ short_col.extend(col) return short_col def build_table(x, y): zeros = [0 for i in range(x)] return [zeros[:] for i in range(y)] def count(line, n, table, col): history = ['' for i in range(n - 2)] history.append('^') for c in line[:-1]: try: table[col.index(''.join(history))][row.index(c)] += 1 history = history[1:] history.append(c) except: pass def print_table_iter(table, col): yield print_row_label() for i, v in enumerate(table): yield col[i] + spliter + spliter.join([str(x) for x in v]) if __name__ == '__main__': if len(sys.argv) != 2: print 'error' quit() n = int(sys.argv[1]) if n < 2: print 'not support unigram' quit() col = build_col_label(n) table = build_table(len(row), len(col)) for line in sys.stdin: count(line, n, table, col) for line in print_table_iter(table, col): sys.stdout.write(line + '\n')
true
e2823ceb160865a3c2432956daf6d5a3b73f6dde
Python
wkuling/Clash-of-Clans-Bot-TH10
/Balloonion.sikuli/Alligator_farmer.py
UTF-8
37,375
2.71875
3
[]
no_license
from datetime import * from math import * from random import * #cocWindow = False # things to do: # 1) full troop employment certainty 2) hold down click instead of once at a time cocWindow = App("Bluestacks").window(0) timestamps = { 'testing': False, 'start': False, 'trainTroops': False, 'clearObstacles': False, 'collectResources': False, 'collectStats': False, 'donateTroops': False, '_lastInteraction': False } # Barbarians # Archers # Giants # Goblins # Wall Breakers # Balloons # Wizards # Healers # Dragons # P.E.K.K.A myArmy = [110, 110, 0, 0, 0, 0, 0, 0, 0, 0] # Barch 90 Barbs, 90 Archers, 0 WB # myArmy = [0, 80, 12, 44, 8, 0, 0, 0, 0, 0] # Farming Mix 80 Archers, 12 Giants, 44 Goblins, 8 WB tranches = [28, 28, 27, 27] # troops in tranches for deploy trainTimes = [20, 25, 120, 30, 120, 480, 480, 900, 1800, 2700] # TODO: Fix OCR (Make DE conditional on whether they are high enough to have DE) minGoldToAttack = 200000 minElixirToAttack = 200000 minDeToAttack = 0 def attack(): if startAttacking() == False: return False for i in range(0, 400): if isGoodOpponent() == True: if deployTroops() == True: finishBattleAndGoHome() return True else: return False else: if nextOpponent() == False: return False return True def startAttacking(): try: sleep(1) cocWindow.find("1420258650866.png").click() updateTimestamp('_lastInteraction') sleep(2) cocWindow.find("1420258681129.png").click() updateTimestamp('_lastInteraction') sleep(1) if (cocWindow.exists("1420258722056.png")): cocWindow.find("1420258740243.png").click() updateTimestamp('_lastInteraction') return True except: print "Error starting the attack process" return False def nextOpponent(): try: cocWindow.find("1420259749784.png").click() updateTimestamp('_lastInteraction') sleep(2) cocWindow.wait("1433579795554.png", 20) sleep(2) return True except: print "Error in searching for new opponent" sleep(4) zoomOutAndCenter() return False def allPumpsFull(): # This function searches for empty pumps. If any exists, it's not an attractive base # numberOfNicePumps = 0 # print "Starting pump checking..." # try: # if cocWindow.exists(Pattern("1434901654010.png").similar(0.95)): # print "Ooh... found some three stripes... counting them now!" # numberOfNicePumps += len(list([x for x in cocWindow.findAll(Pattern("1434901654010.png").similar(0.95))])) # Three stripe pumps # if cocWindow.exists(Pattern("1434900842456.png").similar(0.95)): # print "Ooh... found some two stripes... counting them now!" # numberOfNicePumps += len(list([x for x in cocWindow.findAll(Pattern("1434900842456.png").similar(0.95))])) # Two stripe pumps # print "Number of Nice Pumps found: ", numberOfNicePumps ## capture(cocWindow) # if numberOfNicePumps >= 1: # return True # else: # return False # except: # print "Error in checking pumps :(" # return False # output = True # if (cocWindow.exists(Pattern("1433793684004.png").similar(0.95))): # output = False # print "Pump check failed on 1" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1433793722614.png").similar(0.95))): # output = False # print "Pump check failed on 2" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1433875561726.png").similar(0.95))): # output = False # print "Pump check failed on 3" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1434046957414.png").similar(0.95))): # output = False # print "Pump check failed on 4" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1434096321731.png").similar(0.95))): # output = False # print "Pump check failed on 5" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1434182793660.png").similar(0.95))): # output = False # print "Pump check failed on 6" # cocWindow.getLastMatch().highlight(1) # else: # if (cocWindow.exists(Pattern("1434192871182.png").similar(0.95))): # output = False # print "Pump check failed on 7" # cocWindow.getLastMatch().highlight(1) output=False if (cocWindow.exists("1435204895251.png")): print "Found near empty elixer tank level 11" if (cocWindow.exists("1435205063908.png")): print "Found near empty gold vault level 11" output = True print output return output def hasTHLeftRight(): leftRegion = Region((cocWindow.x + 67), (cocWindow.y + 112), 480, 800) rightRegion = Region((cocWindow.x + 950), (cocWindow.y + 112), 480, 800) leftRegion.highlight(1) rightRegion.highlight(1) if (leftRegion.exists(Pattern("1434599502845.png").similar(0.85))): return True if (rightRegion.exists(Pattern("1434599502845.png").similar(0.85))): return True if (leftRegion.exists(Pattern("1434599616920.png").similar(0.85))): return True if (rightRegion.exists(Pattern("1434599616920.png").similar(0.85))): return True return False def isGoodOpponent(): ## TODO: Test for high level TH/defense/walls/etc try: goldRegion = Region((cocWindow.x + 67), (cocWindow.y + 112), 160, 34) elixirRegion = Region((cocWindow.x + 64), (cocWindow.y + 149), 160, 34) deRegion = Region((cocWindow.x + 64), (cocWindow.y + 188), 125, 34) # goldRegion.highlight(3) # elixirRegion.highlight(3) # Note: need to move this to inner part of if statement for efficiency... gold = numberOCR(goldRegion, 'opponentLootgd') elixir = numberOCR(elixirRegion, 'opponentLoote') ratio = gold / float(elixir) # de = numberOCR(deRegion, 'opponentLootgd') print "Gold: ", gold print "Elixir: ", elixir print "Ratio: ", ratio sometime = randint(0,5) print "Sleeping for: ", sometime sleep(sometime) # print "Dark Elixir: ", de # Increasing the trophy count # if hasTHLeftRight(): # return True # Going for LOOT!! if (gold >= minGoldToAttack and elixir >= minElixirToAttack and ratio <= 1.15 and ratio >= 0.85): print "OK... Gold, Elixer and Ratio are fine :)" if allPumpsFull(): print "OK... Pumps are cool!!" return True return False except: print "isGoodOpponent() Something went wrong :(" print sys.exc_info()[0] print sys.exc_info()[1] return False def deployTroops(): # TODO: Check for full-ish collectors and deploy troops differently if they exist (around all edges) print "[+] Deploying troops" zoomOutAndCenter() try: # landmark = cocWindow.find("attack_landmark.png") landmark = cocWindow.find("attack_landmark2.png") landmark.highlight(1) Settings.DelayAfterDrag = 0.1 Settings.DelayBeforeDrop = 0.3 Settings.MoveMouseDelay = 0.3 dragDrop(landmark.getCenter(), Location(cocWindow.x + 68, cocWindow.y + 462)) updateTimestamp('_lastInteraction') Settings.DelayAfterDrag = 0.3 Settings.DelayAfterDrop = 0.3 Settings.MoveMouseDelay = 0.3 landmark = cocWindow.find(Pattern("attack_landmark2.png").similar(0.75)) landmark.highlight(1) # Necessary to prevent "flinging" the screen... except: print "[!] Could not find attack landmark. Aborting attack." cocWindow.find("1420258809432.png").click() updateTimestamp('_lastInteraction') return False deployPoints = [] # Derived from original deploypoints. Estimated linear relationship y=f(x)=ax+b # Starting with leftabove line a=0.7687 b=-110.7 xmin=40 xmax=335 deploytroups = tranches[0] stepsize=ceil((xmax-xmin)/(deploytroups-1)) for x in range(xmin, xmax, stepsize): y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) over = deploytroups - (1 + floor((xmax-xmin)/stepsize)) for i in range(over): x = xmin y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) # Now the leftunder line a=-0.758 b=-49.66 xmin=40 xmax=450 deploytroups = tranches[1] stepsize=ceil((xmax-xmin)/(deploytroups-1)) for x in range(xmin, xmax, stepsize): y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) over = deploytroups - (1 + floor((xmax-xmin)/stepsize)) for i in range(over): x = xmin y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) # Now the rightabove line a=-0.845 b=1085.6 xmin=980 xmax=1386 deploytroups = tranches[2] stepsize=ceil((xmax-xmin)/(deploytroups-1)) for x in range(xmin, xmax, stepsize): y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) over = deploytroups - (1 + floor((xmax-xmin)/stepsize)) for i in range(over): x = xmin y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) # Now the rightbelow line a=0.7746 b=-1159 xmin=980 xmax=1386 deploytroups = tranches[3] stepsize=ceil((xmax-xmin)/(deploytroups-1)) for x in range(xmin, xmax, stepsize): y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) over = deploytroups - (1 + floor((xmax-xmin)/stepsize)) for i in range(over): x = xmin y = ceil(a*x + b) deployPoints.append(Location((landmark.getX() + x), (landmark.getY() + y))) # deployPoints.append(Location((landmark.getX() + 286), (landmark.getY() + 113))) # deployPoints.append(Location((landmark.getX() + 237), (landmark.getY() + 78))) # deployPoints.append(Location((landmark.getX() + 200), (landmark.getY() + 47))) # deployPoints.append(Location((landmark.getX() + 148), (landmark.getY() + 14))) # deployPoints.append(Location((landmark.getX() + 110), (landmark.getY() - 20))) # deployPoints.append(Location((landmark.getX() + 104), (landmark.getY() - 130))) # deployPoints.append(Location((landmark.getX() + 160), (landmark.getY() - 169))) # deployPoints.append(Location((landmark.getX() + 201), (landmark.getY() - 204))) # deployPoints.append(Location((landmark.getX() + 260), (landmark.getY() - 248))) # deployPoints.append(Location((landmark.getX() + 315), (landmark.getY() - 290))) # deployPoints.append(Location((landmark.getX() + 360), (landmark.getY() - 325))) # deployPoints.append(Location((landmark.getX() + 425), (landmark.getY() - 372))) # deployPoints.append(Location((landmark.getX() + 1000), (landmark.getY() + 241))) # deployPoints.append(Location((landmark.getX() + 1057), (landmark.getY() + 197))) # deployPoints.append(Location((landmark.getX() + 1130), (landmark.getY() + 138))) # deployPoints.append(Location((landmark.getX() + 1190), (landmark.getY() + 90))) # deployPoints.append(Location((landmark.getX() + 1251), (landmark.getY() + 29))) # deployPoints.append(Location((landmark.getX() + 1318), (landmark.getY() - 14))) # deployPoints.append(Location((landmark.getX() + 1352), (landmark.getY() - 42))) # deployPoints.append(Location((landmark.getX() + 1386), (landmark.getY() - 85))) # deployPoints.append(Location((landmark.getX() + 1351), (landmark.getY() - 122))) # deployPoints.append(Location((landmark.getX() + 1279), (landmark.getY() - 176))) # deployPoints.append(Location((landmark.getX() + 1229), (landmark.getY() - 213))) # deployPoints.append(Location((landmark.getX() + 1163), (landmark.getY() - 266))) # deployPoints.append(Location((landmark.getX() + 1100), (landmark.getY() - 312))) # deployPoints.append(Location((landmark.getX() + 1040), (landmark.getY() - 353))) Settings.MoveMouseDelay = 0.01 try: troops_barbarians = cocWindow.find("troops_barbarians.png") except: troops_barbarians = False try: troops_archers = cocWindow.find("troops_archers.png") except: troops_archers = False try: troops_barbking = cocWindow.find("troops_barbking.png") except: troops_barbking = False try: troops_archqueen = cocWindow.find("1434104532219.png") except: troops_archqueen = False left_lower = 0 left_upper = ((len(deployPoints) / 2) - 1) right_lower = (len(deployPoints) / 2) right_upper = (len(deployPoints) - 1) print "Left bounds: ", left_lower, ", ", left_upper print "Right bounds: ", right_lower, ", ", right_upper # Deploy in tranches oldnumb = 0 newnumb = 0 for tra in range(4): newnumb += tranches[tra] # First the barbs troops_barbarians.click() print "Deploying barbs..." for i in range(oldnumb, newnumb): cocWindow.click(deployPoints[i]) # Now the archers troops_archers.click() print "Deploying archies..." for i in range(oldnumb, newnumb): cocWindow.click(deployPoints[i]) oldnumb=newnumb # Deploy the barbarians first # if troops_barbarians != False: # print "Deploying Barbs..." # troops_barbarians.click() # # for i in range(0, myArmy[0]): # cocWindow.click(deployPoints[i]) # # #for i in range(0, (myArmy['barbarian'] / 2)): # # cocWindow.click(deployPoints[randint(right_lower, right_upper)]) # Then the wallbreakers # if troops_wallbreakers != False: # troops_wallbreakers.click() # for i in range(0, (myArmy[4] / 2)): # loc = randint(left_lower, right_upper) # cocWindow.click(deployPoints[loc]) # cocWindow.click(deployPoints[loc]) # # Then deploy the archers # if troops_archers != False: # print "Deploying archies..." # troops_archers.click() # for i in range(0, myArmy[1]): # cocWindow.click(deployPoints[i]) #for i in range(0, (myArmy['archer'] / 2)): # cocWindow.click(deployPoints[randint(right_lower, right_upper)]) # Then the Barb King and Archqueen if available clickpoint = randint(0, right_upper) if troops_barbking != False: troops_barbking.click() cocWindow.click(deployPoints[clickpoint]) if troops_archqueen != False: troops_archqueen.click() cocWindow.click(deployPoints[clickpoint]) sleep(8) if troops_barbking != False: troops_barbking.click() if troops_archqueen != False: troops_archqueen.click() # Cleanup if necessary if (cocWindow.exists("troops_barbarians.png")): troops_barbarians.click() for i in range(220): cocWindow.click(deployPoints[clickpoint]) if (cocWindow.exists("troops_archers.png")): troops_archers.click() for i in range(220): cocWindow.click(deployPoints[clickpoint]) print "[+] Troops have all been deployed" updateTimestamp('_lastInteraction') Settings.MoveMouseDelay = 0.5 return True def campsFull(): try: output = False cocWindow.find("1435988759411.png").click() if(cocWindow.exists(Pattern("1435988801923.png").similar(0.90))): output = True cocWindow.find(Pattern("1420240870546.png").similar(0.90)).click() return output except: print "[INFO] Error in checking whether camps are full" return False def finishBattleAndGoHome(): # TODO: Collect (via OCR) stats about the battle # and record them for later analysis and review cocWindow.wait("1420266239930.png", 180) if (cocWindow.exists("1420266239930.png")): cocWindow.find("1420266239930.png").click() updateTimestamp('_lastInteraction') return True else: return False def trainTroops(troops): # Routine to train troops for attack # - Train equal amount across all barracks # -- 45 Barbs, 45 Archers, 3/2 Wallbreakers # # - Set timer for 24 minutes to begin next attack zoomOutAndCenter() print "[+] Training new troops" village = Region((cocWindow.x + 210), (cocWindow.y + 85), 1025, 790) # Divide up the troops that need to be trained # between the 4 barracks we have to train with # # 0 = Barbarians # 1 = Archers # 2 = Giants # 3 = Goblins # 4 = Wall Breakers # 5 = Balloons # 6 = Wizards # 7 = Healers # 8 = Dragons # 9 = PEKKAs theBarracks = [ [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0] ] totalTroops = 0 for (index, count) in enumerate(troops): theBarracks[0][index] = floor((count / 4)) theBarracks[1][index] = floor((count / 4)) theBarracks[2][index] = floor((count / 4)) theBarracks[3][index] = floor((count / 4)) totalTroops += count if (count % 4 > 0): for i in range(0, (count % 4)): j = barracksWithLeastTroops(theBarracks) theBarracks[j][index] += 1 if totalTroops == 0: return try: cocWindow.find("1436077197737.png").click() updateTimestamp('_lastInteraction') cocWindow.find(Pattern("1434481359875.png").similar(0.90)).click() updateTimestamp('_lastInteraction') sleep(1) # Make sure barracks are empty, no remaining 'to be trained groups': Settings.MoveMouseDelay = 0.5 for i in range (6): while (cocWindow.exists(Pattern("1435776186163.png").similar(0.95))): mouseMove(Pattern("1435776186163.png").similar(0.95)) mouseDown(Button.LEFT) sleep (3) mouseUp() sleep (0.5) cocWindow.find(Pattern("1434481359875.png").similar(0.90)).click() sleep (1) cocWindow.find(Pattern("1436077656548.png").targetOffset(-126,1)).click() updateTimestamp('_lastInteraction') sleep(1) # And only now... Let's train! for i in range(4): for (index, qty) in enumerate(theBarracks[i]): if qty > 0: if index == 0: target = cocWindow.find("1435776344624.png") # Barbarians elif index == 1: target = cocWindow.find("1435776359366.png") # Archers elif index == 2: target = cocWindow.find("1435776373005.png") # Giants elif index == 3: target = cocWindow.find("1435776384049.png") # Goblins elif index == 4: target = cocWindow.find("1435776394238.png") # Wallbreakers elif index == 5: target = cocWindow.find("1435776406520.png") # Balloons elif index == 6: target = cocWindow.find("1435776416822.png") # Wizards elif index == 7: target = cocWindow.find("1435776425678.png") # Healers elif index == 8: target = cocWindow.find("1435776435271.png") # Dragons elif index == 9: target = cocWindow.find("1435776479905.png") # PEKKAs else: print "Invalid index: ", index Settings.MoveMouseDelay = 0.05 for n in range(0, qty): target.click() updateTimestamp('_lastInteraction') Settings.MoveMouseDelay = 0.5 cocWindow.find("1420308052116.png").click() updateTimestamp('_lastInteraction') sleep(0.5) cocWindow.find("1420240870546.png").click() updateTimestamp('_lastInteraction') updateTimestamp('trainTroops') sleep(2) except: print "Error training new troops" if cocWindow.exists("1420240870546.png"): cocWindow.find("1420240870546.png").click() print sys.exc_info()[0] print sys.exc_info()[1] def barracksWithLeastTroops(barracks): lowest_time = calcTrainTime(barracks[0]) lowest_i = 0; for (i, barrack) in enumerate(barracks): time = calcTrainTime(barrack) if time < lowest_time: lowest_i = i; lowest_time = time return lowest_i def calcTrainTime(barrack): time = 0 for (i, count) in enumerate(barrack): time += (count * trainTimes[i]) return time def donateTroops(): # Routine to donate troops to clan members # - Open sidebar # - Find/click [Donate] button(s) # - Donate troops (Archers?) until icon is gray # - Track troops donated # - Retrain donated troops # - Update timers (_lastInteraction, donate, buildTroops, etc.) donations = 0 fSidebar() try: for donate in cocWindow.findAll(Pattern("1420237685511.png").similar(0.80)): donate.click() updateTimestamp('_lastInteraction') sleep(1) donateDialog = Region((donate.x + 88), (donate.y - 175), 765, 435) Settings.MoveMouseDelay = 0 while donateDialog.exists(Pattern("1420238079816.png").similar(0.90), 0): donateDialog.getLastMatch().click() donations += 1 updateTimestamp('_lastInteraction') sleep(0.5) Settings.MoveMouseDelay = 0.5 print "Donated ", donations, " archers" except: print "[-] Nobody has asked for donations. Moving on." # print sys.exc_info()[0] # print sys.exc_info()[1] _closeSidebar() updateTimestamp('donateTroops') if (donations > 0): trainTroops({ 'archer': donations }) return def _openSidebar(): try: if cocWindow.exists("1420308399291.png",0): cocWindow.getLastMatch().click() sleep(1) return True else: print "Sidebar opener doesn't exist" return False except: print "[!] Could not open sidebar" return False def _closeSidebar(): try: if cocWindow.exists("1420238603713.png", 0): cocWindow.getLastMatch().click() updateTimestamp('_lastInteraction') sleep(2) return True else: print "Sidebar closer doesn't exist" return False except: print "[!] Could not close sidebar" return False def collectResources(): resources = ["1420235690079.png", "1420231189687.png" ,Pattern("1420230934586.png").similar(0.80)] window = Region((cocWindow.x + 210), (cocWindow.y + 85), 1025, 790) for resource in resources: try: for _temp in window.findAll(resource): _temp.click() updateTimestamp('_lastInteraction') except: print "[!] There was an error collecting resources" updateTimestamp('collectResources') return # TODO def removeObstacles(): # Routine to find and remove obstacles pass # TODO def observeVillageStats(): # Routine to collect/OCR village stats # And return them in an array/dictionary... # Or maybe right them to a file? pass # Starts BlueStacks Player # Opens Clash of Clans app # Centers village on the screen # # Returns: True if succeeded, False if anything failed def startClashOfClans(): startAndFocusApp() waitVanish("1420181477444.png", FOREVER) sleep(3) cocWindow = App("Bluestacks").window(0) recentApps = Region((cocWindow.x + 8), (cocWindow.y + 110), 1430, 150) try: recentApps.find(Pattern("1420182034354.png").exact()).click() cocWindow.wait("1420182438717.png", 30) cocWindow.waitVanish("1420182438717.png", FOREVER) # cocWindow.wait("1420225678008.png", FOREVER) # Test for recent enemy raid dialog if cocWindow.exists("1420255908709.png"): cocWindow.getLastMatch().click() updateTimestamp('_lastInteraction') sleep(1) else: sleep(3) zoomOutAndCenter() except: print "[!] Could not find COC icon, assuming game is already started..." updateTimestamp('start') return True # Takes a string as arg1 and updates that # timestamp (if it exists) with the current # datetime. def updateTimestamp(timer): if timer in timestamps: timestamps[timer] = datetime.now() else: print "[!] Invalid timestamp: " + timer return # Zooms the screen all the way out # # TODO: Reliably center the village on the map # # Returns: True on success, False otherwise def zoomOutAndCenter(): try: startAndFocusApp() print "[+] Zooming out and centering village" type("-", Key.CTRL) sleep(0.5) type("-", Key.CTRL) sleep(0.5) type ("-", Key.CTRL) sleep(0.5) updateTimestamp('_lastInteraction') except: print "[!] Something went wrong while trying to zoom out..." return False return True def startAndFocusApp(): try: switchApp("C:\Program Files (x86)\BlueStacks\HD-StartLauncher.exe") sleep(1) except: print "[!] Could not start/focus the BlueStacks Player" return False return True # Checks to see if we've been kicked for being idle # If so, it will reload the game and reset the village # so we can pick up where we left off. # # TODO: Check for recent attack dialog when we return to from idle def checkIdle(): output=False if (cocWindow.exists("1434261314820.png")): cocWindow.find("1434261314820.png").click() sleep(15) output = True if (cocWindow.exists("1434081589892.png")): cocWindow.find("1434081589892.png").click() sleep(15) output = True if (cocWindow.exists("1420184095574.png")): cocWindow.find("1420184095574.png").click() sleep(15) output = True if (cocWindow.exists("1435094547913.png")): cocWindow.find("1435094547913.png").click() sleep(15) output = True if (cocWindow.exists("1434339266059.png")): cocWindow.find("1434339266059.png").click() sleep(15) output = True zoomOutAndCenter() return output def preventIdle(): # Exception handling is done in main loop # try: #cocWindow.find("1420776357181.png").click() #updateTimestamp('_lastInteraction') #sleep(2) #cocWindow.find("1420240870546.png").click() # #sleep(2) _openSidebar() sleep(5) _closeSidebar() sleep(5) updateTimestamp('_lastInteraction') def testOcr(): try: goldRegion = selectRegion("Select Loot") gold = numberOCR(goldRegion, 'opponentLoot') print "Loot: ", gold except: print "Failed :(" print sys.exc_info()[0] print sys.exc_info()[1] return def numberOCR(Reg, ocrType): if ocrType == 'opponentLootgd': numberImages = [Pattern("1435777897467.png").similar(0.95), Pattern("1435777964859.png").similar(0.95),Pattern("1435777974432.png").similar(0.95),Pattern("1435777991728.png").similar(0.95),Pattern("1435778017035.png").similar(0.95),Pattern("1435778042241.png").similar(0.95),Pattern("1435778076500.png").similar(0.95),Pattern("1435778104099.png").similar(0.95),Pattern("1435778149456.png").similar(0.95),Pattern("1435778172200.png").similar(0.95)] # numberImages = [Pattern("oppLoot_0.png").exact(),Pattern("oppLoot_1.png").exact(),Pattern("oppLoot_2.png").exact(),Pattern("oppLoot_3.png").similar(0.95),Pattern("oppLoot_4.png").similar(0.95),Pattern("oppLoot_5.png").exact(),Pattern("oppLoot_6.png").exact(),Pattern("oppLoot_7.png").similar(0.95),Pattern("oppLoot_8.png").exact(),Pattern("oppLoot_9.png").exact()] elif ocrType == 'opponentLoote': numberImages = [Pattern("1435778405976.png").similar(0.95),Pattern("1435778430683.png").similar(0.95),Pattern("1435778455587.png").similar(0.95),Pattern("1435778468876.png").similar(0.95),Pattern("1435778476135.png").similar(0.95),Pattern("1435778529622.png").similar(0.95),Pattern("1435778699082.png").similar(0.95),Pattern("1435778722192.png").similar(0.95),Pattern("1435778733921.png").similar(0.95),Pattern("1435778761846.png").similar(0.95)] # numberImages = [Pattern("1433590442780.png").similar(0.95), Pattern("1433590463994.png").similar(0.95),Pattern("1433590478196.png").similar(0.95),Pattern("1433590489070.png").similar(0.95),Pattern("1433590524020.png").similar(0.95),Pattern("1433590578269.png").similar(0.95),Pattern("1433590609952.png").similar(0.95),Pattern("1433590626580.png").similar(0.95),Pattern("1433590636277.png").similar(0.95),Pattern("1433590666869.png").similar(0.95)] digitalNumber = 0 resultList = list() # Reg.highlight(3) for x in numberImages: if Reg.exists(x,0): Reg.findAll(x) #digital find result into list digitalList = list(Reg.getLastMatches()) #convert list into tuple(image, digital) for y in digitalList: #resultList.append(tuple(y,0)) t = (y,digitalNumber) resultList.append(t) digitalNumber = digitalNumber+1 sortedResultList = sorted(resultList,key=lambda x: x[0].x) #print sortedResultList ret = 0 listLen = len(sortedResultList) for x, i in enumerate(sortedResultList): ret += 10 **(listLen - x - 1) * i[1] return ret def secondsSinceLast(ts): diff = datetime.now() - ts; return diff.seconds def timeToTrainArmy(): return (28*25 + 27*20) # boost on >> /4 def initialise(): print "[INFO] RESTART at: " + str(datetime.now()) startAndFocusApp() checkIdle() print "[INFO] Ready to go at: " + str(datetime.now()) # To Do: check which troups have been trained and clean up the mess # Main "game loop" #if (startClashOfClans() == True): # print "Clash of Clans has started and is ready to go!" # while (True): # Make sure we weren't kicked for being idle # print "[+] Idle Check" # checkIdle() # # Collect resources every 10 minutes # if ((timestamps['collectResources'] == False) or (secondsSinceLast(timestamps['collectResources']) > 600)): # print "[+] Time to collect resources" # collectResources() # else: # print "[INFO] Time since last collected resources: ", secondsSinceLast(timestamps['collectResources']), "/ 600" # # Donate troops every 5 minutes # if ((timestamps['donateTroops'] == False) or (secondsSinceLast(timestamps['donateTroops']) > 300)): # print "[+] Time to donate troops" # donateTroops() # Train new troops and attack after the last trainTroops() finishes # if ((timestamps['trainTroops'] == False) or (secondsSinceLast(timestamps['trainTroops']) > timeToTrainArmy())): # print "+-------------------------------------------------------+" # print "| |" # print "| |" # print "+-------------------------------------------------------+" # print "" # sleep(2) # print "+-------------------------------------------------------+" # print "| |" # print "| WARNING |" # print "| |" # print "+-------------------------------------------------------+" # print "" # sleep(2) # print "+-------------------------------------------------------+" # print "| |" # print "| WARNING |" # print "| |" # print "+-------------------------------------------------------+" # print "" # startAndFocusApp() # sleep(10) # print "[+] Idle Check" # checkIdle() # sleep(5) # print "[+] Time to train troops and attack" # trainTroops(myArmy) # attack() # else: # print "[INFO] Time since troops were trained: ", secondsSinceLast(timestamps['trainTroops']), "/", timeToTrainArmy() # # Perform an interaction with the game to prevent idling out if 30 seconds has passed with no interaction # if ((timestamps['_lastInteraction'] == False) or (secondsSinceLast(timestamps['_lastInteraction']) > 60)): # print "[+] Interacting with the screen to prevent getting kicked for too much idle time" # if preventIdle() == False: # print "Something went wrong, aborting in case Sidebar didn't close." # break # else: # print "[INFO] Time since last interaction: ", secondsSinceLast(timestamps['_lastInteraction']) # Sleep 20 seconds before running the loop again # sleep(20) # ------------------------------------------------------ # Initialising: checks for initial army trained def attackLoop(): try: checkIdle() zoomOutAndCenter() if ((timestamps['trainTroops'] == False) or (secondsSinceLast(timestamps['trainTroops']) > timeToTrainArmy()) or (campsFull() == True)): print "[INFO] Time to clean up, train and then attack..." if (timestamps['trainTroops'] == True): print "[INFO] secondsSinceLast: ", secondsSinceLast(timestamps['trainTroops']), "/", timeToTrainArmy() else: print "[INFO] timestamps[traintroops] is False" trainTroops(myArmy) attack() while ((secondsSinceLast(timestamps['trainTroops'])<timeToTrainArmy()) and (campsFull() == False)): print "[INFO] Time since troops were trained: ", secondsSinceLast(timestamps['trainTroops']), "/", timeToTrainArmy() preventIdle() except: print "[INFO] Error with Bluestacks player detected at: " + str(datetime.now()) print "[INFO] Value for timestamps[trainTroops]: " + str(timestamps['trainTroops']) initialise() # Main 'program' HAHA initialise() sleep(2) while True: attackLoop() # #checkIdle() #sleep(2) #for i in range(50): # trainTroops(myArmy) # attack() # checkIdle() # # now wait until the new attack can start :)... # print "[INFO] Time since troops were trained: ", secondsSinceLast(timestamps['trainTroops']), "/", timeToTrainArmy() # while (secondsSinceLast(timestamps['trainTroops'])<timeToTrainArmy()): # checkIdle() # preventIdle() # collectResources() # donateTroops() # trainTroops(myArmy) # zoomOutAndCenter() # attack() # allPumpsFull() # isGoodOpponent()
true
ed575178d2aa0e477ed988c7c8f8565660e3f1f6
Python
KumarAmbuj/GEEKSFORGEEKS-DYNAMIC-PROGRAMING
/96.TABULATION.py
UTF-8
459
3.015625
3
[]
no_license
def findmaxvalue(arr): dp=[[0 for i in range(len(arr))]for j in range(len(arr))] for g in range(len(arr)): i=0 j=g turn=g+1 while(j<len(arr)): if g==0: dp[i][j]=arr[i] else: dp[i][j]=max(arr[i]*turn+dp[i+1][j],arr[j]*turn+dp[i][j-1]) i+=1 j+=1 print(dp[0][len(arr)-1]) arr = [ 1, 3, 1, 5, 2 ] findmaxvalue(arr)
true
e4ae4360924eae832f965b9f0e49ffea49020ef3
Python
tncardoso/dermis
/src/gen.py
UTF-8
3,091
2.71875
3
[ "BSD-3-Clause" ]
permissive
from jinja2 import Template from enum import Enum class Type(Enum): UINT = 0 INT = 1 CHARP = 2 FILEP = 3 VOIDP = 4 SIZET = 5 def c_type(self): if self.value == Type.UINT.value: return 'unsigned int' elif self.value == Type.INT.value: return 'int' elif self.value == Type.CHARP.value: return 'char*' elif self.value == Type.FILEP.value: return 'FILE*' elif self.value == Type.VOIDP.value: return 'void*' elif self.value == Type.SIZET.value: return 'size_t' def lua_to(self): if self.value == Type.UINT.value: return 'lua_tointeger' elif self.value == Type.INT.value: return 'lua_tointeger' elif self.value == Type.CHARP.value: return 'lua_tostring' elif self.value == Type.FILEP.value: return 'lua_topointer' elif self.value == Type.VOIDP.value: return 'lua_topointer' elif self.value == Type.SIZET.value: return 'lua_tointeger' def lua_is(self): if self.value == Type.UINT.value: return 'lua_isnumber' elif self.value == Type.INT.value: return 'lua_is_number' elif self.value == Type.CHARP.value: return 'lua_isstring' elif self.value == Type.FILEP.value: return 'lua_islightuserdata' elif self.value == Type.VOIDP.value: return 'lua_islightuserdata' elif self.value == Type.SIZET.value: return 'lua_isnumber' def lua_push(self): if self.value == Type.UINT.value: return 'lua_pushinteger' elif self.value == Type.INT.value: return 'lua_pushinteger' elif self.value == Type.CHARP.value: return 'lua_pushstring' elif self.value == Type.FILEP.value: return 'lua_pushlightuserdata' elif self.value == Type.VOIDP.value: return 'lua_pushlightuserdata' elif self.value == Type.SIZET.value: return 'lua_pushinteger' class Arg(object): def __init__(self, type, name): self.type = type self.name = name def declaration(self): return '%s %s'%(self.type.c_type(), self.name) class Function(object): def __init__(self, name, ret, args): self.name = name self.ret = ret self.args = args def args_declaration(self): return ', '.join(map(lambda x: x.declaration(), self.args)) def args_types(self): return ', '.join(map(lambda x: x.type.c_type(), self.args)) def args_names(self): return ', '.join(map(lambda x: x.name, self.args)) def generate(functions): with open('main.c.template', 'r') as f: t = Template(f.read()) ret = t.render( functions=functions, ) return ret def main(): functions = [ Function('sleep', Type.UINT, [ Arg(Type.UINT, 'seconds'), ]), Function('fgets', Type.CHARP, [ Arg(Type.CHARP, 'str'), Arg(Type.INT, 'num'), Arg(Type.FILEP, 'stream'), ]), Function('malloc', Type.VOIDP, [ Arg(Type.SIZET, 'size'), ]), ] print(generate(functions)) if __name__ == '__main__': main()
true
e16d2b94c66cc8e618aab0198d291c4b7cd7955a
Python
lcsm29/project-euler
/py/py_0219_skew-cost_coding.py
UTF-8
1,046
3.5625
4
[ "MIT" ]
permissive
# Solution of; # Project Euler Problem 219: Skew-cost coding # https://projecteuler.net/problem=219 # # Let A and B be bit strings (sequences of 0's and 1's). If A is equal to the # leftmost length(A) bits of B, then A is said to be a prefix of B. For # example, 00110 is a prefix of 001101001, but not of 00111 or 100110. A # prefix-free code of size n is a collection of n distinct bit strings such # that no string is a prefix of any other. For example, this is a prefix-free # code of size 6:0000, 0001, 001, 01, 10, 11Now suppose that it costs one # penny to transmit a '0' bit, but four pence to transmit a '1'. Then the # total cost of the prefix-free code shown above is 35 pence, which happens to # be the cheapest possible for the skewed pricing scheme in question. In # short, we write Cost(6) = 35. What is Cost(109) ? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n = 1000 i = 10000 prob_id = 219 timed.caller(dummy, n, i, prob_id)
true
d3086f904bdba90b49619f34af4323f49313fc7e
Python
brian-rose/lowtran
/lowtran/plots.py
UTF-8
523
2.703125
3
[ "MIT" ]
permissive
from matplotlib.pyplot import figure def plottrans(trans,log): ax = figure().gca() for tran in trans.T: ax.plot(tran.wavelength_nm,tran,label=str(tran.zenith_angle.values)) ax.set_xlabel('wavelength [nm]') ax.set_ylabel('transmission (unitless)') ax.set_title('zenith angle [deg] = '+str(trans.zenith_angle.values)) ax.legend(loc='best') ax.grid(True) if log: ax.set_yscale('log') ax.set_ylim(1e-5,1) ax.invert_xaxis() ax.autoscale(True,axis='x',tight=True)
true
a7dffeb1a23f0c20bf8bb372c3747a74dce90423
Python
ApexPredator-InfoSec/header_check
/headers.py
UTF-8
4,744
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/python3 #Title: headers.py #Author: ApexPredator #License: MIT #Github: https://github.com/ApexPredator-InfoSec/header_check #Description: This script take a URL or list or URLs as arguments and tests for the headers: 'Strict-Transport-Security', 'Content-Security-Policy', 'X-Frame-Options', and 'Server' import requests import argparse import socket from urllib3.exceptions import InsecureRequestWarning parser = argparse.ArgumentParser(prog='headers.py', usage='python3 -t <target> -f <file contianing target list> -d\npython3 headers.py -t https://securityheaders.com -d\npython3 headers.py -f urls.txt') #build argument list parser.add_argument('-t', '--target', help='Target URL', required=False) parser.add_argument('-f', '--file', help='File Containing Target URLs', required=False) parser.add_argument('-d','--debug', help='Debug with proxy', required=False, action = 'store_const', const = True) args = parser.parse_args() s = requests.session() requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) #disable SSL verification warning to cleanup output http_proxy = 'http://127.0.0.1:8080' #define proxy address to enable using BURP or ZAP proxyDict = { #define proxy dictionary to enable using BURP or ZAP "http" : http_proxy, "https" : http_proxy } if args.debug: proxy = proxyDict #enable proxy if -d or --debug is present else: proxy = False #disable proxy is -d or --debug is not present def test_url(target): print("[+] Sending get request to target and checking header....") res = s.get(target, verify=False, proxies=proxy) #perform get request on url, disble SSL verification to prevent error for sites with invalid certs, proxy if proxy is enabled if 'https://' in target: #test for https url test_headers(target, res, 'Strict-Transport-Security') #test for Strict-Transport-Security header test_headers(target, res, 'Content-Security-Policy') #test for Content-Security-Policy test_headers(target, res, 'X-Frame-Options') #test for X-Frame-Options header test_headers(target, res, 'Server') #test for Server header elif 'http://' in target: #test for http url test_header(target, res, 'Content-Security-Policy') #test for Content-Security-Policy test_header(target, res, 'X-Frame-Options') #test for X-Frame-Options header test_header(target, res, 'Server') #test for Server header else: print("%s is an invalid URL" %target) #print invalid url if not https or http def test_headers(target, res, header): print("[+]Testing headers for %s" %target + ' IP: ' + socket.gethostbyname(target[8:])) #print URL being tested and its IP if header in res.headers: #test if the header passed to test_headers is in the get response headers print("[+] %s is enabled" %header) #print header is enabled print("[+] Value of %s header is: %s" %(header,res.headers[header])) #print value of header else: print("[-] !!!! %s is not enabled on %s" %(header,target) + ' IP: ' + socket.gethostbyname(target[8:])) #print header is not enabled if it is not present, display URL and IP def test_header(target, res, header): print("[+]Testing headers for %s" %target + ' IP: ' + socket.gethostbyname(target[7:])) #print URL being tested and its IP if header in res.headers: #test if header passed to test_header is in the get response headers print("[+] %s is enabled" %header) #print the header is enabled print("[+] Value of %s header is: %s" %(header,res.headers[header])) #print the vlaue of the header else: print("[-] !!!! %s is not enabled on %s" %(header,target) + ' IP: ' + socket.gethostbyname(target[7:])) #print header is not enabled if header is not found in get response header, display URL and IP def main(): if args.target: #test it -t or --target were passed and set target with value passed target = args.target test_url(target) elif args.file: #test if -f or --file were passed and set target with file named passed file = args.file with open(file, 'r') as target_list: #open file passed for line in target_list.readlines(): #read the lines in target = line.strip() #set target print("\n[+]Fetching URL from file.......\n") test_url(target) #test the url currently set in target else: print("[-]Either -t or -f arguments are required\nusage: python3 headers.py -t <target> -f <file contianing target list> -d\npython3 headers.py -t https://securityheaders.com -d\npython3 headers.py -f urls.txt") #print help message if neither -t or -f is passed if __name__ == '__main__': main()
true
9f38bec32b42b9ab003e2bc7516560dd365b92b7
Python
Vaziri-Mahmoud/travisTest
/code.py
UTF-8
597
3.4375
3
[]
no_license
class mahmoud98(): ''' def pr(): print("Hi\nTravis CI test lang:python ") print("Happy new year : ", 1398, " :) ") print("\n") def nump(): import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) arr2 = np.power(arr, 2) print(arr2) ''' def op(a, b): if a == b: return('a = b') else: raise ValueError("Error a != b") def op2(a): return a * 2 def op3(a): return a - 2 ''' if __name__ == '__main__': mahmoud98.pr() # nump() mahmoud98.op(5, 3) mahmoud98.op2(18) '''
true
d44305e0877321dd1332ce3b6051284a2422e6c3
Python
changhoonhahn/Gal_agar
/util.py
UTF-8
2,059
2.71875
3
[]
no_license
import os import numpy as np from numpy import Inf def code_dir(): return os.path.dirname(os.path.realpath(__file__)).split('util')[0] def elements(vals, lim=[-Inf, Inf], vis=None, vis_2=None, get_indices=False, dtype=np.int32): ''' Get the indices of the input values that are within the input limit, that also are in input vis index array (if defined). Either of limits can have same range as vals. Import array, range to keep, prior indices of vals array to keep, other array to sub-sample in same way, whether to return selection indices of input vis array. ''' if not isinstance(vals, np.ndarray): vals = np.array(vals) # check if input array if vis is None: vis = np.arange(vals.size, dtype=dtype) else: vals = vals[vis] vis_keep = vis # check if limit is just one value if np.isscalar(lim): keeps = (vals == lim) else: # sanity check - can delete this eventually if isinstance(lim[0], int) and isinstance(lim[1], int): if lim[0] == lim[1]: raise ValueError('input limit = %s, has same value' % lim) if lim[0] != lim[1] and 'int' in vals.dtype.name: print '! elements will not keep objects at lim[1] = %d' % lim[1] if not np.isscalar(lim[0]) or lim[0] > -Inf: keeps = (vals >= lim[0]) else: keeps = None if not np.isscalar(lim[1]) or lim[1] < Inf: if keeps is None: keeps = (vals < lim[1]) else: keeps *= (vals < lim[1]) elif keeps is None: keeps = np.arange(vals.size, dtype=dtype) if get_indices: if vis_2 is not None: return vis_keep[keeps], vis_2[keeps], np.arange(vis.size, dtype=dtype)[keeps] else: return vis_keep[keeps], np.arange(vis.size, dtype=dtype)[keeps] else: if vis_2 is not None: return vis_keep[keeps], vis_2[keeps] else: return vis_keep[keeps]
true
0e355404626c871f21ef5bf4e9136fa19f6e5f6c
Python
WhateverYoung/openmc
/openmc/filter.py
UTF-8
28,338
2.640625
3
[ "MIT" ]
permissive
from collections import Iterable import copy from numbers import Real, Integral import sys import numpy as np from openmc import Mesh from openmc.summary import Summary import openmc.checkvalue as cv if sys.version_info[0] >= 3: basestring = str _FILTER_TYPES = ['universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy', 'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup'] class Filter(object): """A filter used to constrain a tally to a specific criterion, e.g. only tally events when the particle is in a certain cell and energy range. Parameters ---------- type : str The type of the tally filter. Acceptable values are "universe", "material", "cell", "cellborn", "surface", "mesh", "energy", "energyout", and "distribcell". bins : Integral or Iterable of Integral or Iterable of Real The bins for the filter. This takes on different meaning for different filters. See the OpenMC online documentation for more details. Attributes ---------- type : str The type of the tally filter bins : Integral or Iterable of Real The bins for the filter num_bins : Integral The number of filter bins mesh : Mesh or None A Mesh object for 'mesh' type filters. stride : Integral The number of filter, nuclide and score bins within each of this filter's bins. """ # Initialize Filter class attributes def __init__(self, type=None, bins=None): self._type = None self._num_bins = 0 self._bins = None self._mesh = None self._stride = None if type is not None: self.type = type if bins is not None: self.bins = bins def __eq__(self, other): if not isinstance(other, Filter): return False elif self.type != other.type: return False elif len(self.bins) != len(other.bins): return False elif not np.allclose(self.bins, other.bins): return False else: return True def __ne__(self, other): return not self == other def __hash__(self): return hash(repr(self)) def __deepcopy__(self, memo): existing = memo.get(id(self)) # If this is the first time we have tried to copy this object, create a copy if existing is None: clone = type(self).__new__(type(self)) clone._type = self.type clone._bins = copy.deepcopy(self.bins, memo) clone._num_bins = self.num_bins clone._mesh = copy.deepcopy(self.mesh, memo) clone._stride = self.stride memo[id(self)] = clone return clone # If this object has been copied before, return the first copy made else: return existing def __repr__(self): string = 'Filter\n' string += '{0: <16}{1}{2}\n'.format('\tType', '=\t', self.type) string += '{0: <16}{1}{2}\n'.format('\tBins', '=\t', self.bins) return string @property def type(self): return self._type @property def bins(self): return self._bins @property def num_bins(self): if self.bins is None: return 0 elif self.type in ['energy', 'energyout']: return len(self.bins) - 1 elif self.type in ['cell', 'cellborn', 'surface', 'universe', 'material']: return len(self.bins) else: return self._num_bins @property def mesh(self): return self._mesh @property def stride(self): return self._stride @type.setter def type(self, type): if type is None: self._type = type elif type not in _FILTER_TYPES: msg = 'Unable to set Filter type to "{0}" since it is not one ' \ 'of the supported types'.format(type) raise ValueError(msg) self._type = type @bins.setter def bins(self, bins): if self.type is None: msg = 'Unable to set bins for Filter to "{0}" since ' \ 'the Filter type has not yet been set'.format(bins) raise ValueError(msg) # If the bin edge is a single value, it is a Cell, Material, etc. ID if not isinstance(bins, Iterable): bins = [bins] # If the bins are in a collection, convert it to a list else: bins = list(bins) if self.type in ['cell', 'cellborn', 'surface', 'material', 'universe', 'distribcell', 'delayedgroup']: cv.check_iterable_type('filter bins', bins, Integral) for edge in bins: cv.check_greater_than('filter bin', edge, 0, equality=True) elif self.type in ['energy', 'energyout']: for edge in bins: if not cv._isinstance(edge, Real): msg = 'Unable to add bin edge "{0}" to a "{1}" Filter ' \ 'since it is a non-integer or floating point ' \ 'value'.format(edge, self.type) raise ValueError(msg) elif edge < 0.: msg = 'Unable to add bin edge "{0}" to a "{1}" Filter ' \ 'since it is a negative value'.format(edge, self.type) raise ValueError(msg) # Check that bin edges are monotonically increasing for index in range(len(bins)): if index > 0 and bins[index] < bins[index-1]: msg = 'Unable to add bin edges "{0}" to a "{1}" Filter ' \ 'since they are not monotonically ' \ 'increasing'.format(bins, self.type) raise ValueError(msg) # mesh filters elif self.type == 'mesh': if not len(bins) == 1: msg = 'Unable to add bins "{0}" to a mesh Filter since ' \ 'only a single mesh can be used per tally'.format(bins) raise ValueError(msg) elif not cv._isinstance(bins[0], Integral): msg = 'Unable to add bin "{0}" to mesh Filter since it ' \ 'is a non-integer'.format(bins[0]) raise ValueError(msg) elif bins[0] < 0: msg = 'Unable to add bin "{0}" to mesh Filter since it ' \ 'is a negative integer'.format(bins[0]) raise ValueError(msg) # If all error checks passed, add bin edges self._bins = np.array(bins) @num_bins.setter def num_bins(self, num_bins): cv.check_type('filter num_bins', num_bins, Integral) cv.check_greater_than('filter num_bins', num_bins, 0, equality=True) self._num_bins = num_bins @mesh.setter def mesh(self, mesh): cv.check_type('filter mesh', mesh, Mesh) self._mesh = mesh self.type = 'mesh' self.bins = self.mesh.id @stride.setter def stride(self, stride): cv.check_type('filter stride', stride, Integral) if stride < 0: msg = 'Unable to set stride "{0}" for a "{1}" Filter since it ' \ 'is a negative value'.format(stride, self.type) raise ValueError(msg) self._stride = stride def can_merge(self, other): """Determine if filter can be merged with another. Parameters ---------- other : Filter Filter to compare with Returns ------- bool Whether the filter can be merged """ if not isinstance(other, Filter): return False # Filters must be of the same type elif self.type != other.type: return False # Distribcell filters cannot have more than one bin elif self.type == 'distribcell': return False # Mesh filters cannot have more than one bin elif self.type == 'mesh': return False # Different energy bins are not mergeable elif 'energy' in self.type: return False else: return True def merge(self, other): """Merge this filter with another. Parameters ---------- other : Filter Filter to merge with Returns ------- merged_filter : Filter Filter resulting from the merge """ if not self.can_merge(other): msg = 'Unable to merge "{0}" with "{1}" ' \ 'filters'.format(self.type, other.type) raise ValueError(msg) # Create deep copy of filter to return as merged filter merged_filter = copy.deepcopy(self) # Merge unique filter bins merged_bins = list(set(np.concatenate((self.bins, other.bins)))) merged_filter.bins = merged_bins merged_filter.num_bins = len(merged_bins) return merged_filter def is_subset(self, other): """Determine if another filter is a subset of this filter. If all of the bins in the other filter are included as bins in this filter, then it is a subset of this filter. Parameters ---------- other : Filter The filter to query as a subset of this filter Returns ------- bool Whether or not the other filter is a subset of this filter """ if not isinstance(other, Filter): return False elif self.type != other.type: return False elif self.type in ['energy', 'energyout']: if len(self.bins) != len(other.bins): return False else: return np.allclose(self.bins, other.bins) for bin in other.bins: if bin not in self.bins: return False return True def get_bin_index(self, filter_bin): """Returns the index in the Filter for some bin. Parameters ---------- filter_bin : Integral or tuple The bin is the integer ID for 'material', 'surface', 'cell', 'cellborn', and 'universe' Filters. The bin is an integer for the cell instance ID for 'distribcell' Filters. The bin is a 2-tuple of floats for 'energy' and 'energyout' filters corresponding to the energy boundaries of the bin of interest. The bin is an (x,y,z) 3-tuple for 'mesh' filters corresponding to the mesh cell interest. Returns ------- filter_index : Integral The index in the Tally data array for this filter bin. See also -------- Filter.get_bin() """ try: # Filter bins for a mesh are an (x,y,z) tuple if self.type == 'mesh': # Convert (x,y,z) to a single bin -- this is similar to # subroutine mesh_indices_to_bin in openmc/src/mesh.F90. if (len(self.mesh.dimension) == 3): nx, ny, nz = self.mesh.dimension val = (filter_bin[0] - 1) * ny * nz + \ (filter_bin[1] - 1) * nz + \ (filter_bin[2] - 1) else: nx, ny = self.mesh.dimension val = (filter_bin[0] - 1) * ny + \ (filter_bin[1] - 1) filter_index = val # Use lower energy bound to find index for energy Filters elif self.type in ['energy', 'energyout']: deltas = np.abs(self.bins - filter_bin[1]) / filter_bin[1] min_delta = np.min(deltas) if min_delta < 1E-3: filter_index = deltas.argmin() - 1 else: raise ValueError # Filter bins for distribcells are "IDs" of each unique placement # of the Cell in the Geometry (integers starting at 0) elif self.type == 'distribcell': filter_index = filter_bin # Use ID for all other Filters (e.g., material, cell, etc.) else: val = np.where(self.bins == filter_bin)[0][0] filter_index = val except ValueError: msg = 'Unable to get the bin index for Filter since "{0}" ' \ 'is not one of the bins'.format(filter_bin) raise ValueError(msg) return filter_index def get_bin(self, bin_index): """Returns the filter bin for some filter bin index. Parameters ---------- bin_index : Integral The zero-based index into the filter's array of bins. The bin index for 'material', 'surface', 'cell', 'cellborn', and 'universe' filters corresponds to the ID in the filter's list of bins. For 'distribcell' tallies the bin index necessarily can only be zero since only one cell can be tracked per tally. The bin index for 'energy' and 'energyout' filters corresponds to the energy range of interest in the filter bins of energies. The bin index for 'mesh' filters is the index into the flattened array of (x,y) or (x,y,z) mesh cell bins. Returns ------- bin : 1-, 2-, or 3-tuple of Real The bin in the Tally data array. The bin for 'material', surface', 'cell', 'cellborn', 'universe' and 'distribcell' filters is a 1-tuple of the ID corresponding to the appropriate filter bin. The bin for 'energy' and 'energyout' filters is a 2-tuple of the lower and upper energies bounding the energy interval for the filter bin. The bin for 'mesh' tallies is a 2-tuple or 3-tuple of the x,y or x,y,z mesh cell indices corresponding to the bin in a 2D/3D mesh. See also -------- Filter.get_bin_index() """ cv.check_type('bin_index', bin_index, Integral) cv.check_greater_than('bin_index', bin_index, 0, equality=True) cv.check_less_than('bin_index', bin_index, self.num_bins) if self.type == 'mesh': # Construct 3-tuple of x,y,z cell indices for a 3D mesh if len(self.mesh.dimension) == 3: nx, ny, nz = self.mesh.dimension x = bin_index / (ny * nz) y = (bin_index - (x * ny * nz)) / nz z = bin_index - (x * ny * nz) - (y * nz) filter_bin = (x, y, z) # Construct 2-tuple of x,y cell indices for a 2D mesh else: nx, ny = self.mesh.dimension x = bin_index / ny y = bin_index - (x * ny) filter_bin = (x, y) # Construct 2-tuple of lower, upper energies for energy(out) filters elif self.type in ['energy', 'energyout']: filter_bin = (self.bins[bin_index], self.bins[bin_index+1]) # Construct 1-tuple of with the cell ID for distribcell filters elif self.type == 'distribcell': filter_bin = (self.bins[0],) # Construct 1-tuple with domain ID (e.g., material) for other filters else: filter_bin = (self.bins[bin_index],) return filter_bin def get_pandas_dataframe(self, data_size, summary=None): """Builds a Pandas DataFrame for the Filter's bins. This method constructs a Pandas DataFrame object for the filter with columns annotated by filter bin information. This is a helper method for the Tally.get_pandas_dataframe(...) method. This capability has been tested for Pandas >=0.13.1. However, it is recommended to use v0.16 or newer versions of Pandas since this method uses Pandas' Multi-index functionality. Parameters ---------- data_size : Integral The total number of bins in the tally corresponding to this filter summary : None or Summary An optional Summary object to be used to construct columns for distribcell tally filters (default is None). The geometric information in the Summary object is embedded into a Multi-index column with a geometric "path" to each distribcell instance. NOTE: This option requires the OpenCG Python package. Returns ------- pandas.DataFrame A Pandas DataFrame with columns of strings that characterize the filter's bins. The number of rows in the DataFrame is the same as the total number of bins in the corresponding tally, with the filter bin appropriately tiled to map to the corresponding tally bins. For 'cell', 'cellborn', 'surface', 'material', and 'universe' filters, the DataFrame includes a single column with the cell, surface, material or universe ID corresponding to each filter bin. For 'distribcell' filters, the DataFrame either includes: 1. a single column with the cell instance IDs (without summary info) 2. separate columns for the cell IDs, universe IDs, and lattice IDs and x,y,z cell indices corresponding to each (with summary info). For 'energy' and 'energyout' filters, the DataFrame include a single column with each element comprising a string with the lower, upper energy bounds for each filter bin. For 'mesh' filters, the DataFrame includes three columns for the x,y,z mesh cell indices corresponding to each filter bin. Raises ------ ImportError When Pandas is not installed, or summary info is requested but OpenCG is not installed. See also -------- Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() """ # Attempt to import Pandas try: import pandas as pd except ImportError: msg = 'The Pandas Python package must be installed on your system' raise ImportError(msg) # Initialize Pandas DataFrame df = pd.DataFrame() # mesh filters if self.type == 'mesh': # Initialize dictionary to build Pandas Multi-index column filter_dict = {} # Append Mesh ID as outermost index of mult-index mesh_key = 'mesh {0}'.format(self.mesh.id) # Find mesh dimensions - use 3D indices for simplicity if (len(self.mesh.dimension) == 3): nx, ny, nz = self.mesh.dimension else: nx, ny = self.mesh.dimension nz = 1 # Generate multi-index sub-column for x-axis filter_bins = np.arange(1, nx+1) repeat_factor = ny * nz * self.stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_dict[(mesh_key, 'x')] = filter_bins # Generate multi-index sub-column for y-axis filter_bins = np.arange(1, ny+1) repeat_factor = nz * self.stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_dict[(mesh_key, 'y')] = filter_bins # Generate multi-index sub-column for z-axis filter_bins = np.arange(1, nz+1) repeat_factor = self.stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_dict[(mesh_key, 'z')] = filter_bins # Initialize a Pandas DataFrame from the mesh dictionary df = pd.concat([df, pd.DataFrame(filter_dict)]) # distribcell filters elif self.type == 'distribcell': level_df = None if isinstance(summary, Summary): # Attempt to import the OpenCG package try: import opencg except ImportError: msg = 'The OpenCG package must be installed ' \ 'to use a Summary for distribcell dataframes' raise ImportError(msg) # Extract the OpenCG geometry from the Summary opencg_geometry = summary.opencg_geometry openmc_geometry = summary.openmc_geometry # Use OpenCG to compute the number of regions opencg_geometry.initialize_cell_offsets() num_regions = opencg_geometry.num_regions # Initialize a dictionary mapping OpenMC distribcell # offsets to OpenCG LocalCoords linked lists offsets_to_coords = {} # Use OpenCG to compute LocalCoords linked list for # each region and store in dictionary for region in range(num_regions): coords = opencg_geometry.find_region(region) path = opencg.get_path(coords) cell_id = path[-1] # If this region is in Cell corresponding to the # distribcell filter bin, store it in dictionary if cell_id == self.bins[0]: offset = openmc_geometry.get_cell_instance(path) offsets_to_coords[offset] = coords # Each distribcell offset is a DataFrame bin # Unravel the paths into DataFrame columns num_offsets = len(offsets_to_coords) # Initialize termination condition for while loop levels_remain = True counter = 0 # Iterate over each level in the CSG tree hierarchy while levels_remain: levels_remain = False # Initialize dictionary to build Pandas Multi-index # column for this level in the CSG tree hierarchy level_dict = {} # Initialize prefix Multi-index keys counter += 1 level_key = 'level {0}'.format(counter) univ_key = (level_key, 'univ', 'id') cell_key = (level_key, 'cell', 'id') lat_id_key = (level_key, 'lat', 'id') lat_x_key = (level_key, 'lat', 'x') lat_y_key = (level_key, 'lat', 'y') lat_z_key = (level_key, 'lat', 'z') # Allocate NumPy arrays for each CSG level and # each Multi-index column in the DataFrame level_dict[univ_key] = np.empty(num_offsets) level_dict[cell_key] = np.empty(num_offsets) level_dict[lat_id_key] = np.empty(num_offsets) level_dict[lat_x_key] = np.empty(num_offsets) level_dict[lat_y_key] = np.empty(num_offsets) level_dict[lat_z_key] = np.empty(num_offsets) # Initialize Multi-index columns to NaN - this is # necessary since some distribcell instances may # have very different LocalCoords linked lists level_dict[univ_key][:] = np.NAN level_dict[cell_key][:] = np.NAN level_dict[lat_id_key][:] = np.NAN level_dict[lat_x_key][:] = np.NAN level_dict[lat_y_key][:] = np.NAN level_dict[lat_z_key][:] = np.NAN # Iterate over all regions (distribcell instances) for offset in range(num_offsets): coords = offsets_to_coords[offset] # If entire LocalCoords has been unraveled into # Multi-index columns already, continue if coords is None: continue # Assign entry to Universe Multi-index column if coords._type == 'universe': level_dict[univ_key][offset] = coords._universe._id level_dict[cell_key][offset] = coords._cell._id # Assign entry to Lattice Multi-index column else: # Reverse y index per lattice ordering in OpenCG level_dict[lat_id_key][offset] = coords._lattice._id level_dict[lat_x_key][offset] = coords._lat_x level_dict[lat_y_key][offset] = \ coords._lattice.dimension[1] - coords._lat_y - 1 level_dict[lat_z_key][offset] = coords._lat_z # Move to next node in LocalCoords linked list if coords._next is None: offsets_to_coords[offset] = None else: offsets_to_coords[offset] = coords._next levels_remain = True # Tile the Multi-index columns for level_key, level_bins in level_dict.items(): level_bins = np.repeat(level_bins, self.stride) tile_factor = data_size / len(level_bins) level_bins = np.tile(level_bins, tile_factor) level_dict[level_key] = level_bins # Initialize a Pandas DataFrame from the level dictionary if level_df is None: level_df = pd.DataFrame(level_dict) else: level_df = pd.concat([level_df, pd.DataFrame(level_dict)], axis=1) # Create DataFrame column for distribcell instances IDs # NOTE: This is performed regardless of whether the user # requests Summary geometric information filter_bins = np.arange(self.num_bins) filter_bins = np.repeat(filter_bins, self.stride) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_bins = filter_bins df = pd.DataFrame({self.type : filter_bins}) # If OpenCG level info DataFrame was created, concatenate # with DataFrame of distribcell instance IDs if level_df is not None: level_df = level_df.dropna(axis=1, how='all') level_df = level_df.astype(np.int) df = pd.concat([level_df, df], axis=1) # energy, energyout filters elif 'energy' in self.type: bins = self.bins num_bins = self.num_bins # Create strings for template = '({0:.1e} - {1:.1e})' filter_bins = [] for i in range(num_bins): filter_bins.append(template.format(bins[i], bins[i+1])) # Tile the energy bins into a DataFrame column filter_bins = np.repeat(filter_bins, self.stride) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_bins = filter_bins df = pd.concat([df, pd.DataFrame({self.type + ' [MeV]' : filter_bins})]) # universe, material, surface, cell, and cellborn filters else: filter_bins = np.repeat(self.bins, self.stride) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_bins = filter_bins df = pd.concat([df, pd.DataFrame({self.type : filter_bins})]) return df
true
0cae4b7ea5266dfd655c8543ffd1edf8cbcc7350
Python
Sheikh-A/El_Gamal_Ecryption_v1
/elgamal.py
UTF-8
907
2.703125
3
[]
no_license
import random #import random from library from params import p from params import g def keygen(): get_random = random.randint(1,p) #set SK sk = get_random #set pk pk = pow(g, sk, p) return pk,sk def encrypt(pk,m): #define r rand = random.randint(1,p) r = rand # formula goes here c1 = pow(g, r, p) #formula goes here c2 = (pow(pk, r, p) * (m % p)) % p return [c1,c2] def decrypt(sk,c): c0 = c[0] #use array index c1 = c[1] #use array index funcC0 = pow(c0, sk, p) #Modular Inverse funcC1 = c1 * pow(funcC0, -1, p) #Define M m = pow(funcC1, 1, p) return m # testkey = keygen() # print(testkey) # sk = testkey[1] # pk = testkey[0] # print("sk", sk) # print("pk", pk) # message = 819191 # print("message", message) # encry = encrypt(pk, message) # print(encry) # decry = decrypt(sk, encry) # print(decry)
true
98bb79074b5a4eeb0df29456b91e855307cbd517
Python
lshapz/video-workbook
/012.py
UTF-8
218
3.71875
4
[]
no_license
# my_range = range(1, 21) # my_list = list(my_range) # new_list = [] # for i in my_list: # i *= 10 # new_list.append(i) # print(new_list) print([10 * x for x in my_range]) # list comprehension # a lot faster!
true
86b15f58bb5b9e0123d051975d6e0c3d8c22b37b
Python
J051p/Python
/Operators.py
UTF-8
537
3.71875
4
[]
no_license
# Aritmetički operatori x = 5 y = 5 print (x + y) print (x - y) print (x * y) print (x / y) print (x % y) print (x ** y) print (x // y) # Operatori pridruživanja x = 5 print(x) # x = 5 x +=3 print(x) # x = x + 3 x-=3 print(x) # x = x - 3 x *=3 print(x) # x = x * 3 x /=3 print(x) # x = x / 3 x %=3 print(x) # x = x % 3 x //=3 print(x) # x = x // 3 x **=3 print(x) # x = x ** 3 x &=3 print(x) # x = x & 3 x |= 3 print(x) # x = x | 3 x ^=3 print(x) # x = x ^ 3 x >>=3 print(x) # x = >> 3 x <<=3 print(x) # x = x << 3
true
f9099edc4b8f7ee2570cff2591ae0a025a5dcec0
Python
samdawes/iD-Emory-Python-Projects
/Pygame/Platformer/coinBase.py
UTF-8
390
3.53125
4
[]
no_license
#Expand to see the coin class. import pygame class Coin(pygame.sprite.Sprite): image = None #When a coin is created, provide an x and #y position for it to be drawn at. def __init__(self, x, y): super().__init__() self.image = self.image = pygame.Surface([20, 20]) self.image.fill((185, 100, 0)) self.rect = pygame.Rect(x, y, 20, 20)
true
560f8b98f53596061d037666ed34b1134f6776fc
Python
iangat/pdsnd_github
/bikeshare_igt.py
UTF-8
12,750
3.828125
4
[]
no_license
# ----------------------------------------------------------------------------- # # Project 2 - Python # Explore US Bikeshare Data # # Description # Use Python to understand U.S. bikeshare data. Calculate statistics and have an # interactive environment where a user chooses the data and filter for a dataset # to analyze. The user can filter the information by day of week and/or month. # Also the user can choose to inspect the raw data. # # Creation date: 18/11/2019 By: Ian Garcia-Tsao # Updated: 21/11/2019 # # ----------------------------------------------------------------------------- import time import pandas as pd import numpy as np CITY_DATA = {'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv'} def ask_value(input_msg, choice_list): """ Ask the user to pick a value from a list of choices. All choices in the list must be lowercase. Returns: (str) value - value picked by the user """ # Form the input message num_choices = 1 for choice in choice_list: if num_choices < len(choice_list): input_msg += choice.title() + ', ' else: input_msg += 'or ' + choice.title() + ' >> ' num_choices += 1 # Ask for a choice and check if it is valid while True: value = input(input_msg).lower() if value in choice_list: break else: print('\nNot a valid choice ({}). Please try again.'.format(value)) return value def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # Form the city list city_list = [city_name for city_name in CITY_DATA.keys()] city_list.append('none') # Ask for city city = ask_value('Choose a city (or None - exit out): ', city_list) month = None day = None filter_option = None if city != 'none': # Ask for filter option filter_list = ['month', 'day', 'both', 'none'] filter_option = ask_value('Choose a filter option from the ' + 'following list: ', filter_list) days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun'] # Depending on filter option get user input for month, day, both or # none if filter_option == 'month': month = ask_value('Choose a month: ', months) elif filter_option == 'day': day = ask_value('Choose a day: ', days) elif filter_option == 'both': month = ask_value('Choose a month: ', months) day = ask_value('Choose a day: ', days) print('-'*79) return city, month, day, filter_option def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # Should be able to find always the city, given it had to be picked from # a list, but it's safer to check on it. if CITY_DATA.get(city) is None: return None, None city_df = pd.read_csv(CITY_DATA.get(city)) raw_df = city_df.copy() # Convert Start Time column to date/datetime city_df['Start Time'] = pd.to_datetime(city_df['Start Time']) # Create a column with the name of the month city_df['Month'] = city_df['Start Time'].map(lambda x: x.strftime('%b').lower()) # Create a column with the day of the week city_df['DOW'] = city_df['Start Time'].map(lambda x: x.strftime('%a').lower()) # Create a column with hour city_df['Hour'] = city_df['Start Time'].map(lambda x: x.strftime('%H')) # Filter the resulting table according to user's choices of month and day if (month is not None) and (day is not None): df = city_df[(city_df['Month'] == month) & (city_df['DOW'] == day)] elif month is not None: df = city_df[city_df['Month'] == month] elif day is not None: df = city_df[city_df['DOW'] == day] else: df = city_df return df, raw_df def print_filter_options(df, filter_option): """ Prints the filter options chosen by the user """ print('Filter options') print('--------------') if filter_option == 'month': print('Month: {}\n'.format(df['Start Time'].iloc[0].strftime('%B'))) elif filter_option == 'day': print('Day: {}\n'.format(df['Start Time'].iloc[0].strftime('%A'))) elif filter_option == 'both': print('Month: {}'.format(df['Start Time'].iloc[0].strftime('%B'))) print('Day: {}\n'.format(df['Start Time'].iloc[0].strftime('%A'))) else: print('None\n') def time_stats(df, filter_option): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() print_filter_options(df, filter_option) msg = 'Most common {}: {}, Count: {:,}.' # display the most common month if (filter_option != 'month') and (filter_option != 'both'): print(msg.format('month', df['Month'].value_counts().index[0].title(), df['Month'].value_counts()[0])) # display the most common day of week if (filter_option != 'day') and (filter_option != 'both'): print(msg.format('day of week', df['DOW'].value_counts().index[0].title(), df['DOW'].value_counts()[0])) # display the most common start hour print(msg.format('hour', df['Hour'].value_counts().index[0], df['Hour'].value_counts()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*79) def station_stats(df, filter_option): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() print_filter_options(df, filter_option) msg = 'Most common {}: {}, Count: {:,}.' # display most commonly used start station print(msg.format('start station', df['Start Station'].value_counts().index[0], df['Start Station'].value_counts()[0])) # display most commonly used end station # display most commonly used start station print(msg.format('end station', df['End Station'].value_counts().index[0], df['End Station'].value_counts()[0])) # display most frequent combination of start station and end station trip df['Start-End'] = df['Start Station'] + ' to ' + df['End Station'] print(msg.format('trip', df['Start-End'].value_counts().index[0], df['Start-End'].value_counts()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*79) def h_m_s(seconds): """ Given time in seconds, returns hours, minutes and seconds""" hours = seconds // 3600 seconds = seconds - (hours * 3600) minutes = seconds // 60 seconds = seconds - (minutes * 60) return int(hours), int(minutes), seconds def trip_duration_stats(df, filter_option): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() print_filter_options(df, filter_option) msg = '{} travel time: {:2,}h {:2,}m {:2.0f}s' # display total travel time print(msg.format('Total ', *h_m_s(df['Trip Duration'].sum()))) # display mean travel time print(msg.format('Average', *h_m_s(df['Trip Duration'].mean()))) # display minimum travel time print(msg.format('Minimum', *h_m_s(df['Trip Duration'].min()))) # display maximum travel time print(msg.format('Maximum', *h_m_s(df['Trip Duration'].max()))) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*79) def user_stats(df, filter_option): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() print_filter_options(df, filter_option) # Display counts of user types msg = '{:11}:{:10,}' print('Count per user type') print('-------------------') user_types_count = df.groupby('User Type').count() for user_type in user_types_count.index: print(msg.format(user_type, user_types_count['Start Time'][user_type])) # Display counts of gender if 'Gender' in df.columns: msg = '{:7}:{:10,}' print('\nCount per gender') print('-------------------') df['Gender'].fillna('Unknown', inplace=True) gender_count = df.groupby('Gender').count() for gender in gender_count.index: print(msg.format(gender, gender_count['Start Time'][gender])) # Display the most common start hour per gender msg = '{:7}: {:2}, Count: {:6,}.' print('\nMost common hour per gender') print('----------------------------') female_df = df.groupby('Gender').get_group('Female') print(msg.format('Female', female_df['Hour'].value_counts().index[0], female_df['Hour'].value_counts()[0])) male_df = df.groupby('Gender').get_group('Male') print(msg.format('Male', male_df['Hour'].value_counts().index[0], male_df['Hour'].value_counts()[0])) unknown_df = df.groupby('Gender').get_group('Unknown') print(msg.format('Unknown', unknown_df['Hour'].value_counts().index[0], unknown_df['Hour'].value_counts()[0])) # Display earliest, most recent, and most common year of birth if 'Birth Year' in df.columns: print('\nYear of birth') print('-------------------') print('Oldest user : {:.0f}'.format(df['Birth Year'].min())) if df['Birth Year'].min() < 1900: print(' (year is not possible)') print('Youngest user : {:.0f}'.format(df['Birth Year'].max())) if df['Birth Year'].max() > 2016: print(' (year is not possible)') df['Birth Year'] = df['Birth Year'].astype(str).map(lambda x: x[0:4]) msg = 'Most common year: {}, Count: {:,}.' if df['Birth Year'].value_counts().index[0] == 'nan': print(msg.format(df['Birth Year'].value_counts().index[1], df['Birth Year'].value_counts()[1])) else: print(msg.format(df['Birth Year'].value_counts().index[0], df['Birth Year'].value_counts()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*79) def display_raw_data(df): """ Shows the original content of the data frame, 5 rows at a time, until the users quits. """ msg = 'Would you like to see the first 5 rows of raw data? ' answer = ask_value(msg, ['y', 'n']) step = 5 rows = 0 while (answer == 'y') and (rows < len(df)): print('-'*79) print(df.loc[rows: rows + step - 1]) print('-'*79) rows += step msg = 'Would you like to continue seeing raw data? ' answer = ask_value(msg, ['y', 'n']) def main(): while True: city, month, day, filter_option = get_filters() if city != 'none': df, raw_df = load_data(city, month, day) time_stats(df, filter_option) station_stats(df, filter_option) trip_duration_stats(df, filter_option) user_stats(df, filter_option) display_raw_data(raw_df) msg = 'Would you like to restart? Enter ' restart = ask_value(msg, ['y', 'n']) if restart != 'y': break else: print('-'*79) else: break print('\nGood bye!') if __name__ == "__main__": main()
true
36a7a59983508bbae10078b0bad4b665d4fba956
Python
michallkanak/artificial-intelligence
/GeneticAlgoritm/source.py
UTF-8
7,682
2.921875
3
[ "MIT" ]
permissive
import numpy as np from operator import itemgetter import random import time # time waching start_time = time.time() population_size = 100 gen = 100 Px = 0.7 # 0.8 roul # 0.7 tour Pm = 0.15 # 0.04 roul # 0.1 tour Tour = 5 repeats_range = 10; global_best = 0 global_worst = 0 global_mean = 0 file = open("data/had12.dat") for line in file: print(line) # Wczytaj plik od poczatku file.seek(0) length = int(file.readline()) file.readline() # Wczytaj macierz przeplywow flow = list() for x in range(0, length): row = list() values = file.readline().split() for value in values: row.append(int(value)) flow.append(row) flow = np.matrix(flow) file.readline() # Wczytaj macierz odleglosci distances = list() for x in range(0, length): row = list() values = file.readline().split() for value in values: row.append(int(value)) distances.append(row) distances = np.matrix(distances) # Zamknij plik file.close() # Kazdy genotyp jest generowany jako losowa lista bez powtorzen # od 0 do x (gdzie x to dlugosc chromosomu, parametr length). def generate_first_pop(population_size, length): return [ [ 0, random.sample(range(0, length), length) ] for y in range(0, population_size) ] # Funkcja celu - liczenie kosztu - odleglosci def fitness(permutation, length, flow, distances): cost = 0 for x in range(0, length): f1 = permutation[x] for y in range(0, length): f2 = permutation[y] cost += flow.item(x, y) * distances.item(f1, f2) return cost # Sortowanie def sort(population): return sorted(population, key=itemgetter(0)) # Selekcja - metoda turniejowa def tournament_selection(population, tour): new_population = list() while len(new_population) < population_size: random_indexes = random.sample(range(0, population_size), tour) choices = list() for index in random_indexes: choices.append(population[index]) choices = sort(choices) new_population.append(choices[0]) return new_population # Selekcja - metoda ruletki def roulette_selection(population, population_size): new_pop = list() total_fit = 1 scores = list() for item in population: scores.append(item[0]) total_fit += item[0] worst = scores[np.argmax(scores)] normalized_scores = list() calc_scores = list() for x in range(0, population_size): temp = (worst - scores[x] + 1) / (total_fit + 1) normalized_scores.append([temp, population[x]]) calc_scores.append(temp) normalized_scores = sort(normalized_scores) sorted_scores = sorted(calc_scores, key=float) sum = np.sum(sorted_scores) for _ in range(0, population_size - 1): random_numb = random.uniform(0, sum) if random_numb < sorted_scores[0]: new_pop.append(normalized_scores[0][1]) continue count = 1 count_sum = sorted_scores[0] while random_numb > count_sum: count_sum += sorted_scores[count] count += 1 new_pop.append(normalized_scores[count - 1][1]) new_pop.append(normalized_scores[np.argmax(calc_scores)][1]) return new_pop # Wyliczanie kosztu dla wszystkich genotypow z populacji def evaluation(population, population_size, length, flow, distances): new_population = list() for x in range(0, population_size): cost = fitness(population[x][1], length, flow, distances) # dolaczamy koszt na poczatek danej populacji - by nie potwarzac procesu new_population.append([cost, population[x][1]]) return new_population # Krzyzowanie - na podstawie pradopodobienstwa krzyzowania dokonujemy standardowego przestawienia genow # dla wczesniej wybranych losowo # okreslajac punkt ciecia w sposob pseudolosowym przed przypisaniem zmian naprawaimy geny def crossover(population, px, population_size, length): pairs = list() for x in range(0, int(population_size / 2)): parent1 = int(random.random() * population_size) parent2 = int(random.random() * population_size) probability = random.random() pairs.append([probability, parent1, parent2]) for pair in pairs: if pair[0] > px: continue index = int(random.random() * (length - 2) + 1) population[pair[1]][1] = repair(population[pair[1]][1][:index] + population[pair[2]][1][index:], length) population[pair[2]][1] = repair(population[pair[2]][1][:index] + population[pair[1]][1][index:], length) return population # naprawiamy uszkodzone geny poprzez sprawdzenie powtorzen i oznaczenie ich # a nastepnie dodanie nieuzywanych jeszcze liczb def repair(permutation, length): used = list() for x in range(0, length): if permutation[x] in used: permutation[x] = -1 continue used.append(permutation[x]) not_used = list() for x in range(0, length): if x not in used: not_used.append(x) not_used_index = 0 for x in range(0, length): if permutation[x] == -1: permutation[x] = not_used[not_used_index] not_used_index += 1 return permutation # Mutacja - poprzez zamiane miejscami polega na wylosowaniu 2 roznych genow (2 roznych liczb w wektorze) # oraz zamianie ich miejscami. def mutation(population, Pm, population_size, length): for x in range(0, population_size): prob = random.random() if prob > Pm: continue indexes = random.sample(range(0, length), 2) temp = population[x][1][indexes[0]] population[x][1][indexes[0]] = population[x][1][indexes[1]] population[x][1][indexes[1]] = temp return population # TESTY print("population_size, gen, Px, Pm, Tour, repeats_range | roulette") print("{}, {}, {}, {}, {}, {}".format(population_size, gen, Px, Pm, Tour, repeats_range)) print("Uruchomienie, Generacja, Najlepszy, Średni, Najgorszy") for x in range(0, repeats_range): population = generate_first_pop(population_size, length) population = evaluation(population, population_size, length, flow, distances) # Glowna petla programu - odpowiada za: # utworzenie wymaganej liczby pokolen, krzyzowanie, mutacje, # wyliczanie kosztu dla kazdej populacji # okresla kolejnosc wykonywania operacji for x2 in range(0, gen): population = tournament_selection(population, Tour) # population = roulette_selection(population, population_size) population = crossover(population, Px, population_size, length) population = mutation(population, Pm, population_size, length) population = evaluation(population, population_size, length, flow, distances) # sortowanie tak by otrzymac najlepsza populacje (z najmniejszym kosztem) sort_population = sort(population) sum = 0 for perm in sort_population: sum += perm[0] mean = int(sum / population_size) print("{}, {}, {}, {}, {}".format(x, x2, sort_population[0][0], mean, sort_population[population_size - 1][0])) best = sort_population[0] worst = sort_population[population_size - 1] global_best += best[0] global_worst += worst[0] global_mean += mean global_mean = global_mean / repeats_range global_worst = global_worst / repeats_range global_best = global_best / repeats_range print("{}, {}, {}".format(global_best, global_mean, global_worst)) print("\t".join([str(s + 1) for s in best[1]])) print() print("Wynik algorytmu: " + str(best[0])) print("Czas wykonania: ") print((time.time() - start_time))
true
72d066f9561670619539fd4901edc07d59b96ebe
Python
Karzen/SoundGuard
/Scripts/soundguard_control.py
UTF-8
3,668
2.84375
3
[]
no_license
#This module is used for communication between the service and the controller import socket """ Control options: l - Reload settigs v - Reload volume limit p - Pause timer c - Resume timer r - Reset timer d - Disconnect t - Request timer status m - Request device status i - Request pause status """ class SoundGuradControlServer: # It runs on the service and waits for commands and requests from the controller serversocket = None client = None running = False timer = None def __init__(self, timer): #In the constructor, we create the server socket self.timer = timer self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind(("127.0.0.1", 3008)) def serve(self): print("Control server started\n") self.running = True self.serversocket.listen(1) while self.running: self.client, addr = self.serversocket.accept() if addr[0] != "127.0.0.1": self.client.close() continue self.handleClient() def shutdown(self): self.running = False sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.connect(("127.0.0.1", 3008)) sk.send(b'd') sk.close() def handleClient(self): while True: try: data = self.client.recv(1) except: return data = data.decode("utf-8") if data == "v": self.timer.loadVolumeLimit() elif data == "l": self.timer.loadSettings() elif data == "p": self.timer.paused = True elif data == "c": self.timer.paused = False elif data == "r": self.timer.resetTimer() elif data == "d": self.client.close() return elif data == "t": self.client.send(str.encode(str(self.timer.toWait[self.timer.currentMode]))) elif data == "m": self.client.send(str.encode(str(self.timer.currentMode))) elif data == "i": toSend = "0" if self.timer.paused: toSend = "1" self.client.send(str.encode(str(toSend))) class SoundGuardControlClient: # It is used by the controller and, of course, it sends requests and commands to the service @staticmethod def getConnectedSocket(): sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sk.connect(("127.0.0.1", 3008)) return sk except: return None @staticmethod def sendCommand(command): sk = SoundGuardControlClient.getConnectedSocket() if sk == None: return sk.send(str.encode(command)) sk.send(b'd') sk.close() @staticmethod def getTimer(): sk = SoundGuardControlClient.getConnectedSocket() if sk == None: return sk.send(b't') timer = sk.recv(256) timer = int(timer.decode("utf-8")) sk.send(b'd') sk.close() return timer @staticmethod def getStatus(stat): sk = SoundGuardControlClient.getConnectedSocket() if sk == None: return None sk.send(str.encode(stat)) mode = sk.recv(1) mode = int(mode.decode("utf-8")) sk.send(b'd') sk.close() return mode
true
8930e4067e5ec17634e107d8327bd47898446e81
Python
michaelpradel/LExecutor
/src/lexecutor/predictors/NaiveValuePredictor.py
UTF-8
742
2.890625
3
[ "MIT" ]
permissive
from .ValuePredictor import ValuePredictor from ..Logging import logger class Toy: pass class NaiveValuePredictor(ValuePredictor): def name(self, iid, name): v = Toy() logger.info(f"{iid}: Predicting for name {name}: {v}") return v def call(self, iid, fct, fct_name, *args, **kwargs): v = Toy() logger.info(f"{iid}: Predicting for call: {v}") return v def attribute(self, iid, base, attr_name): v = Toy() logger.info(f"{iid}: Predicting for attribute {attr_name}: {v}") return v def binary_operation(self, iid, left, operator, right): v = 3 logger.info(f"{iid}: Predicting result of {operator} operation: {v}") return v
true
90af2dfc7fefa65f99b18b023e7b32294679391d
Python
betty29/code-1
/recipes/Python/221132_Generator_integer_partitions_iterative/recipe-221132.py
UTF-8
624
2.9375
3
[ "MIT", "Python-2.0" ]
permissive
def partitions(n): if n <= 0: return m = int((1 + sqrt(1 + 8 * n)) / 2) - 1 p = [(1, n)] yield p while p[-1][0] != n: # or equivalently p[0][1] != 1 rest = 0 times, number = p.pop() if number == 1: rest += times times, number = p.pop() times -= 1 rest += number if times > 0: p.append((times, number)) number -= 1 times, rest = divmod(rest, number) p.append((times, number)) if rest > 0: p.append((1, rest)) assert len(p) <= m # preallocation possible yield p
true
7d2820bdf55e2a62e6d84252e732224188ef09c4
Python
Aasthaengg/IBMdataset
/Python_codes/p03776/s265286417.py
UTF-8
795
2.796875
3
[]
no_license
import sys def input(): return sys.stdin.readline().strip() def mapint(): return map(int, input().split()) sys.setrecursionlimit(10**9) N, A, B = mapint() Vs = list(mapint()) Vs.sort(reverse=True) from collections import defaultdict, Counter from math import factorial, gcd count = defaultdict(int) c = Counter(Vs) ans = 0 ans_2 = (0, 0) for i in range(A, B+1): val = sum(Vs[:i]) if val/i>=ans-0.000000000000001: ans = val/i lowest_cnt = 0 lowest = Vs[i-1] for j in range(i): if Vs[j]==lowest: lowest_cnt += 1 val, i = val//gcd(val, i), i//gcd(val, i) count[(val, i)] += factorial(c[lowest])/factorial(lowest_cnt)/factorial(c[lowest]-lowest_cnt) ans_2 = (val, i) print(ans) print(round(count[ans_2]))
true
1b09345c2a53f60460d0b38375fd09c52af1d1ed
Python
TsinghuaWangZiXuan/Flybrain
/Codes/Bert/tokenization.py
UTF-8
811
2.546875
3
[]
no_license
import sentencepiece as spm def tokenization(mode, dna_file=None): if mode == 'build': sp = spm.SentencePieceTrainer sp.Train(input='./data/all_gene_sequence.txt', vocab_size=5000, model_prefix='./model/mypiece', model_type='bpe') elif mode == 'train': sp = spm.SentencePieceProcessor(model_file='./model/mypiece.model') seq = open(dna_file, 'r') tokens_list = [] for line in seq: tokens = sp.encode(line[:-1]) tokens_list.append(tokens) return tokens_list elif mode == 'test': sp = spm.SentencePieceProcessor(model_file='./model/mypiece.model') print(sp.decode([4999])) if __name__ == '__main__': tokenization('test')
true
d465ce6512ce049f65d29aa9ddb5a872bb96dd55
Python
huzichunjohn/python_study
/thread_test.py
UTF-8
513
3.125
3
[]
no_license
#!/bin/env python import threading import time class TestThread(threading.Thread): is_stop = False def __init__(self): threading.Thread.__init__(self) def run(self): print self.is_stop while not self.is_stop: print "this is a test." time.sleep(2) print "exit ......" def stop(self): print "stop ......" self.is_stop = True if __name__ == "__main__": t = TestThread() t.start() print "sleep 5s ......" time.sleep(5) t.stop()
true
3db4070a600587a7be300954c70f1ebbe5515b80
Python
yunqu/PYNQ
/pynq/lib/arduino/arduino_grove_buzzer.py
UTF-8
4,446
2.625
3
[ "BSD-3-Clause", "MIT" ]
permissive
# Copyright (c) 2016, Xilinx, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import Arduino from . import ARDUINO_GROVE_G1 from . import ARDUINO_GROVE_G2 from . import ARDUINO_GROVE_G3 from . import ARDUINO_GROVE_G4 from . import ARDUINO_GROVE_G5 from . import ARDUINO_GROVE_G6 from . import ARDUINO_GROVE_G7 __author__ = "Parimal Patel" __copyright__ = "Copyright 2016, Xilinx" __email__ = "pynq_support@xilinx.com" ARDUINO_GROVE_BUZZER_PROGRAM = "arduino_grove_buzzer.bin" CONFIG_IOP_SWITCH = 0x1 PLAY_TONE = 0x3 PLAY_DEMO = 0x5 class Grove_Buzzer(object): """This class controls the Grove Buzzer. The grove buzzer module has a piezo buzzer as the main component. The piezo can be connected to digital outputs, and will emit a tone when the output is HIGH. Alternatively, it can be connected to an analog pulse-width modulation output to generate various tones and effects. Hardware version: v1.2. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. """ def __init__(self, mb_info, gr_pin): """Return a new instance of an GROVE_Buzzer object. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. gr_pin: list A group of pins on arduino-grove shield. """ if gr_pin not in [ARDUINO_GROVE_G1, ARDUINO_GROVE_G2, ARDUINO_GROVE_G3, ARDUINO_GROVE_G4, ARDUINO_GROVE_G5, ARDUINO_GROVE_G6, ARDUINO_GROVE_G7]: raise ValueError("Buzzer group number can only be G1 - G7.") self.microblaze = Arduino(mb_info, ARDUINO_GROVE_BUZZER_PROGRAM) self.microblaze.write_mailbox(0, gr_pin) self.microblaze.write_blocking_command(CONFIG_IOP_SWITCH) def play_tone(self, tone_period, num_cycles): """Play a single tone with tone_period for num_cycles Parameters ---------- tone_period : int The period of the tone in microsecond. num_cycles : int The number of cycles for the tone to be played. Returns ------- None """ if tone_period not in range(1, 32768): raise ValueError("Valid tone period is between 1 and 32767.") if num_cycles not in range(1, 32768): raise ValueError("Valid number of cycles is between 1 and 32767.") self.microblaze.write_mailbox(0, [tone_period, num_cycles]) self.microblaze.write_blocking_command(PLAY_TONE) def play_melody(self): """Play a melody. Returns ------- None """ self.microblaze.write_blocking_command(PLAY_DEMO)
true
1b09cdd1b6987de67b7f860ce9903b67f54e159b
Python
minrk/ipython-svn-archive
/google-rkern/trunk/notabene/formatter.py
UTF-8
3,420
2.953125
3
[]
no_license
"""Base Formatter class for notebooks. """ import textwrap class Formatter(object): """Abstract base class implementing some useful common methods. Subclass and implement a format_sheet(sheet) method. """ def __init__(self, notebook): self.notebook = notebook ## self.inputs = {} ## self.special_inputs = {} ## self.outputs = {} ## self.figures = {} ## for logid, log in notebook.logs.iteritems(): ## inputs = notebook._get_tag_dict('input', logid=logid) ## for k, v in inputs.iteritems(): ## self.inputs[logid, k] = v ## special_inputs = notebook._get_tag_dict('special-input', ## logid=logid) ## for k, v in special_inputs.iteritems(): ## self.special_inputs[logid, k] = v ## outputs = notebook._get_tag_dict('output', logid=logid) ## for k, v in outputs.iteritems(): ## self.outputs[logid, k] = v ## figures = notebook._get_tag_dict('figure', logid=logid) ## for k, v in figures.iteritems(): ## self.figures[logid, k] = v ## def indent(self, text, spaces): """Add a given number of spaces to the beginning of each line in text. """ lines = text.strip().split('\n') tab = ' '*spaces lines = [tab + x for x in lines] lines.append('') return '\n'.join(lines) def format_input(self, elem): """Format an <input> element. """ text = elem.text number = elem.attrib['number'] PS1 = 'In [%s]: ' % number PS2 = '...: '.rjust(len(PS1)) lines = text.strip().split('\n') lines[0] = PS1 + lines[0] for i in xrange(1, len(lines)): lines[i] = PS2 + lines[1] lines.append('') return '\n'.join(lines) def format_output(self, elem): """Format an <output> element. """ text = elem.text.strip() number = elem.attrib['number'] PS3 = 'Out[%s]: ' % number lines = text.split('\n') if len(lines) == 1: template = '%s%s\n' else: template = '%s\n%s\n' return template % (PS3, text) def format_figure(self, elem): """Format a <figure> element. """ caption = elem.text if caption and caption.strip(): caption = self.indent(textwrap.wrap(caption), 2) return 'Fig[%s]: %s\n\n%s\n' % (elem.attrib['number'], elem.attrib['filename'], caption) else: return 'Fig[%s]: %s\n' % (elem.attrib['number'], elem.attrib['filename']) def format_block(self, block): """Format an <ipython-block> tag. """ texts = [] logid = block.get('logid', 'default-log') for cell in block: number = cell.get('number') type = cell.get('type') elem = self.notebook.get_from_log(type, number, logid=logid) if type in ('input', 'special-input'): texts.append(self.format_input(elem)) elif type in ('output',): texts.append(self.format_output(elem)) else: raise NotImplementedError return '\n'.join(texts)
true
00008a4ef1c4f0f8b5ec161ab280c497edbfdc07
Python
wk1219/Data-Science
/Analysis/linear_regression.py
UTF-8
374
2.96875
3
[]
no_license
from sklearn.linear_model import LinearRegression import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("random-linear-regression/test.csv") df.head() X = df["x"] y = df["y"] line_fitter = LinearRegression() line_fitter.fit(X.values.reshape(-1,1), y) plt.plot(X, y, 'o') plt.plot(X, line_fitter.predict(X.values.reshape(-1,1))) plt.show()
true
9916c5b84b9af77107e8fe7950257beee6c4ea39
Python
Aashish07/PythonPractice
/DataTypes/Iterations.py
UTF-8
582
4.96875
5
[]
no_license
# Iterations or looping can be performed in python by ‘for’ and ‘while’ loops. # Apart from iterating upon a particular condition, we can also iterate on strings, lists, and tuples. # 1. While loop :----- i = 1 while (i < 10): print(i) i += 1 # Output :- 1 2 3 4 5 6 7 8 9 # 2. For loop :----- s = "Hello World" for i in s : print (i) # 3. For loop on list :------ L = [1, 4, 5, 7, 8, 9] for i in L: print (i) # 4. For loop with range :------ for i in range(0, 10): print (i)
true
6a493c460891ab7afeab34665053aca27d41724e
Python
thefuyang/testpython
/work2/cookie.py
UTF-8
573
2.546875
3
[]
no_license
# coding=utf-8 __author__ = 'YIN' import cookielib import urllib2 import urllib filename = 'cookie.txt' values = {"username": "admin", "password": "hisense"} data = urllib.urlencode(values) cookie = cookielib.MozillaCookieJar(filename) handler = urllib2.HTTPCookieProcessor(cookie) url = 'http://localhost/guke/admin/php/login.php' opener = urllib2.build_opener(handler) response = opener.open(url, data) print(response.read()) for item in cookie: print "Name = " + item.name print "Value = " + item.value cookie.save(ignore_discard=True, ignore_expires=True)
true
251c103647744e8b9196ad8f979a0b8ef074641e
Python
hersle/euler
/003/3.py
UTF-8
176
3.1875
3
[]
no_license
def factorize(n): for d in range(2, int(n**0.5) + 1): if n % d == 0: return [d] + factorize(n / d) return [n] print (max(factorize(600851475143)))
true
97df2ed06f5af65bd895e078a80cef7243f464ea
Python
jiafangdi-guang/CDA2.0_tools
/Step1.1_File_preprocessing/专利数据库导出数据.py
UTF-8
1,855
2.90625
3
[]
no_license
# 构建的合作关系网络是一个无向有权图 import json import os def get_graph_inf(graph_path, json_path): txt_file = open(graph_path, 'r', encoding='UTF-16') nodes_list = [] links_list = [] for each_line in txt_file: if each_line[:4] == 'pad:': nodes_temper = each_line[4:-1].replace(' ', '').split('|') nodes_list += nodes_temper for i in range(len(nodes_temper)): for j in range(i + 1, len(nodes_temper)): links_list.append([nodes_temper[i], nodes_temper[j]]) # 写入字典 nodes_list = sorted(list(set(nodes_list))) nodes_dict = [] for i in range(len(nodes_list)): nodes_dict.append({'name': nodes_list[i], 'group': 1}) links_dict = [] links_temper = [] for i in range(len(links_list)): if links_list[i] not in links_temper: links_temper.append(links_list[i]) links_dict.append({'source': nodes_list.index(links_list[i][0]), 'target': nodes_list.index(links_list[i][1]), 'value': 1}) else: links_dict[links_temper.index(links_list[i])]['value'] += 1 graph_inf = {'nodes': nodes_dict, 'links': links_dict} json.dump(graph_inf, open(json_path, 'w', encoding='UTF-8')) if __name__ == '__main__': # 修改处 txt_name = '专利数据库导出数据_示例.txt' txt_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'Step1.1_文件预处理\\data_输入', txt_name) json_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'Step1.1_文件预处理\\result_输出', os.path.splitext(txt_name)[0] + '.json') get_graph_inf(txt_path, json_path) print('数据预处理完成!')
true
3dc6b34efb50a20b941a900aacf2d956173bb492
Python
rifatmondol/Python-Exercises
/125 - [Strings] Letra Por Símbolo.py
UTF-8
432
4.25
4
[]
no_license
#125 - Write a Python program to get a string from a given string where all occurrences of its first char # have been changed to '$', except the first char itself. def subst(frase): if letra in frase: subs = frase.rsplit(letra, 1) novo = simb.join(subs) return novo else: return 'NULL' frase = input('Digite uma frase: ') letra = input('Digite uma letra: ') simb = '$' print(subst(frase))
true
0e5f32a8615360778ad04eecf8a4c6d478fe956a
Python
poojaaj/Coding_practice
/bestTimeToBuyStock.py
UTF-8
257
3.5
4
[]
no_license
def bestTimeToBuyStock(prices): j = 1 sum = 0 for i in range(len(prices)-1): if prices[j]-prices[i] > 0: sum += prices[j] - prices[i] j = j + 1 return sum prices = [7,1,5,3,6,4] print(bestTimeToBuyStock(prices))
true
3f1ec0d6336428143671963f057c2e3509bf9761
Python
Aasthaengg/IBMdataset
/Python_codes/p03450/s263780883.py
UTF-8
1,006
3.140625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[13]: import sys from collections import deque input = sys.stdin.readline # In[14]: N, M = map(int, input().split()) # In[2]: link = [[] for _ in range(N)] for _ in range(M): L, R, D = map(int, input().split()) link[L-1].append((R-1, D)) link[R-1].append((L-1, -D)) # In[9]: def func(): houmon = [False] * N x = [0] * N for start in range(N): if houmon[start]: continue stack = deque([start]) while stack: n1 = stack.pop() houmon[n1] = True for n2, d in link[n1]: if houmon[n2]: if x[n2] != x[n1] + d: return False else: x[n2] = x[n1] + d stack.append(n2) # if max(x) - min(x) > 10 ** 9: # return False return True # In[10]: if func(): print('Yes') else: print('No') # In[ ]:
true
c4c9819e3bc1a0220c35ebc8e44b8dd5b653566d
Python
Speaky10k/teletext-twitter
/teletext-twitter/processor.py
UTF-8
1,423
2.703125
3
[ "MIT" ]
permissive
# teletext-twitter - creates pages for vbit2 teletext system # (c) Mark Pentler 2018 (https://github.com/mpentler) # see README.md for details on getting it running or run with -h # text processor module import textwrap import re def tweet_remove_emojis(tweet): # remove pesky emoji characters emoji_pattern = re.compile("[" # our unicode ranges go here. this will need frequent tweaking u"\U00002300-\U000023FF" # misc technical u"\U000024C2-\U0001F251" # enclosed characters including flags u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F600-\U0001F67F" # emoticons u"\U0001F680-\U0001F9FF" # transport & map symbols "]+", flags=re.UNICODE) tweet = emoji_pattern.sub(r'', tweet) return tweet def tweet_remove_urls(tweet): # all tweets are https t.co links, so this is all we need url_pattern = re.compile("https://\S+") tweet = url_pattern.sub('[LINK]', tweet) return tweet def charsub(text): # Now our character substitutions. The teletext English character set doesn't support a lot of characters! text = text.replace("’", "'") text = text.replace("_", "-") text = text.replace("#", "_") text = text.replace("“", "\"") text = text.replace("…", "...") return text
true
0a055984630963e2d69a779531401ed450f36919
Python
Vedant-Dev/leetcode-solution
/Python/search_in_rotated_sorted_array.py
UTF-8
233
3.265625
3
[]
no_license
class Solution: def search(self, nums: List[int], target: int) -> int: lb = 0 ub = len(nums) - 1 while lb <= ub: if nums[lb] == target: return lb if nums[ub] == target: return ub lb += 1 ub -= 1 return -1
true
1712f09a30ae4ca8ceff6212fe64613d06cc16a4
Python
samaypanwar/Algorithms
/SortingAlgorithms/main.py
UTF-8
607
2.703125
3
[]
no_license
import os os.chdir("SortingAlgorithms/") from sorting import Sort import numpy as np import yaml if __name__ == "__main__": with open('config.yaml') as file: config = yaml.safe_load(file) file.close() try: MAX_SIZE = config.get("MAX_SIZE") except: raise ValueError('Max size of random array not defined') sort = Sort() sortingAlgorithms = [algo for algo in dir(Sort) if not algo.startswith("_")] for algo in sortingAlgorithms: randomArray = list(np.random.randint(10000, size=MAX_SIZE)) randomArray = eval("sort." + algo + "(randomArray)")
true
91cd7a074a954562ee4ca871ebcf0a1f5ca3da69
Python
renlei-great/git_window-
/python数据结构/python黑马数据结构/排序于搜索/插入排序_test.py
UTF-8
1,177
4.03125
4
[]
no_license
lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] # 插入排序 # 将前面看做有序集合,将后面看做无序,操作后面每一个无序元素, def insert_sort(lista): n = len(lista) for j in range(1, n): for i in range(j, 0, -1): if lista[i] > lista[i-1]: break lista[i], lista[i-1] = lista[i-1], lista[i] insert_sort(lista) # print(lista) # 冒泡排序 # 两俩相比,最大的在后面 def hmmp_sort(lista): n = len(lista) sign = False for j in range(1, n-1): for i in range(n-j): if lista[i] > lista[i+1]: lista[i], lista[i + 1] = lista[i + 1], lista[i] sign = True if sign: break hmmp_sort(lista) print(lista) # def mp_sort(lista): # n = len(lista) # for i in range(1, n): # # 外循环,每多循环一次,内循环就少循环一次,因为内循环每循环一次就保证了在最后会产生一个有序元素 # for j in range(0, n-i): # if lista[j] > lista[j+1]: # lista[j], lista[j+1] = lista[j+1], lista[j] # # mp_sort(lista) # print(lista)
true
147cd93ba88bd50ce02468a63ebf68ed5a0e0439
Python
betty29/code-1
/recipes/Python/578415_Truecolor_Mandelbrot_Fractal/recipe-578415.py
UTF-8
1,512
3.40625
3
[ "MIT" ]
permissive
# True-color Mandelbrot Fractal # FB36 - 20130113 import math from PIL import Image imgx = 800; imgy = 800 image = Image.new("RGB", (imgx, imgy)) pixels = image.load() xa = -2.0; xb = 1.0 ya = -1.5; yb = 1.5 maxIt = 256 # of iterations # find max values for |x|, |y|, |z| maxAbsX = 0.0; maxAbsY = 0.0; maxAbsZ = 0.0 for ky in range(imgy): b = ky * (yb - ya) / (imgy - 1) + ya for kx in range(imgx): a = kx * (xb - xa) / (imgx - 1) + xa c = complex(a, b); z = c for i in range(maxIt): z = z * z + c if abs(z) > 2.0: break if abs(z.real) > maxAbsX: maxAbsX = abs(z.real) if abs(z.imag) > maxAbsY: maxAbsY = abs(z.imag) if abs(z) > maxAbsZ: maxAbsZ = abs(z) # paint for ky in range(imgy): b = ky * (yb - ya) / (imgy - 1) + ya for kx in range(imgx): a = kx * (xb - xa) / (imgx - 1) + xa c = complex(a, b); z = c for i in range(maxIt): z = z * z + c if abs(z) > 2.0: break v0 = int(255 * abs(z.real) / maxAbsX) v1 = int(255 * abs(z.imag) / maxAbsY) v2 = int(255 * abs(z) / maxAbsZ) v3 = int(255 * abs(math.atan2(z.imag, z.real)) / math.pi) v = v3 * 256 ** 3 + v2 * 256 ** 2 + v1 * 256 + v0 colorRGB = int(16777215 * v / 256 ** 4) red = int(colorRGB / 65536) grn = int(colorRGB / 256) % 256 blu = colorRGB % 256 pixels[kx, ky] = (red, grn, blu) image.save("MandelbrotFractal.png", "PNG")
true
d1adef5795b5919175f8381186ccda0df85d578d
Python
tichmangono/python_interactive_programming
/CourseraMainProj.py
UTF-8
19,849
3.484375
3
[]
no_license
#----------------------------------------- # EXTENDED GUESS THE NUMBER MINI-PROJ #----------------------------------------- # This is the same project as week 2 and allows user to input guesses # in a range of their choice (>10) until they run out of guesses, quit, # guess the right number # Extra Features added #--includes a customizable range (enter your own max number), # and changes the message #--draws dynamic output msgs on canvas instead of just in console #--Shows the results of the the last game played #--Shows an extensive STATS or score board with #--games won #--games lost #--games quit i.e. you start playing a game and then decide to # change the range, test this by selecting a range, guessing # less than the max number of chances, then change range # the number of games quit will increase by one # and change #--total played import simplegui import random import math # helper function to start and restart the game won=lost=quit=played=0 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(0) line3= "Game "+ str(won+lost+quit+1) +" Results: In progress..." guess_range=100 announcement="Caution: Check the console to confirm results!" def new_game(): # initialize global variables used in your code here global guess_range,chances_left,secret_number, played, line1, line2, line3 line1=line2="" if guess_range==1000: secret_number=random.randrange(0,guess_range) chances_left=int(math.ceil(math.log(guess_range,2))) line1="Welcome! Guess range is: "+str(guess_range) line2="You have "+str(chances_left)+" chances left." print "\n=====\n", line1, "\n", line2 else: secret_number=random.randrange(0,guess_range) chances_left=int(math.ceil(math.log(guess_range,2))) line1="Welcome! Guess range is: "+str(guess_range) line2="You have "+str(chances_left)+" chances left." print "\n=====\n", line1, "\n", line2 # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global guess_range, stats, won,lost,quit,played guess_range=100 if chances_left not in (0, int(math.ceil(math.log(guess_range,2)))): quit += 1 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) else: stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) new_game() # remove this when you add your code def range1000(): # button that changes the range to [0,1000) and starts a new game global guess_range, stats, won,lost,quit,played guess_range=1000 if chances_left not in (0, int(math.ceil(math.log(guess_range,2)))): quit += 1 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) else: stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) new_game() def input_newRange(newRange): # input box that lets the user choose their own range global line1,line2, line3 global guess_range, stats, won,lost,quit,played if newRange.isdigit() and int(newRange)>=10: if chances_left not in (0, int(math.ceil(math.log(guess_range,2)))): guess_range=int(newRange) quit += 1 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) else: guess_range=int(newRange) stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) new_game() elif newRange.isdigit() and int(newRange)<10: line1= ":-(" line2 = "Invalid range, range must be >10. Try again" print line2 else: line1= ":-(" line2 = "Invalid range, numbers only. Try again" print line2 def input_guess(guess): # main game logic goes here global line1, line2,line3,secret_number,chances_left global played,quit,won,lost,stats n=int(guess) line1="Your guess was " +str(n) print "\nYour Guess was",n, "." chances_left -=1 if n==secret_number: won += 1 played += 1 #quit=played-won-lost line3= "Previous game results: Correct. Thank you for playing!" print line3 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) new_game() elif n<secret_number and chances_left>0: line2="Go higher. You have "+str(chances_left)+" chances left." print line2 elif n>secret_number and chances_left>0: line2="Go lower. You have "+ str(chances_left)+" chances left." print line2 else: lost += 1 played += 1 #quit=played-won-lost line3= "Previous game results: Game-over, the secret number was "+str(secret_number)+"." print line3 stats="STATS: Total Played-"+str(won+lost+quit)+" | Won-"+str(won)+" | Lost-"+str(lost)+" | Quit-"+str(quit) new_game() def draw(canvas): # enables an extra draw feature to show results on canvas canvas.draw_text(stats, [20,150],18,"orange") canvas.draw_text(line3, [20,120],14,"gray") canvas.draw_text(line1, [20,40],20,"yellow") canvas.draw_text(line2, [20,70],18,"red") canvas.draw_text(announcement, [20,220],12,"white") # create frame frame=simplegui.create_frame("Guess the Number", 430,250) input1=frame.add_input("Enter your guess below:", input_guess, 95) input2=frame.add_input("Customize range:", input_newRange, 95) button1=frame.add_button("Range 0-100", range100, 100) button2=frame.add_button("Range 0-1000", range1000, 100) frame.set_draw_handler(draw) # register event handlers for control elements and start frame frame.start() # call new_game new_game() # always remember to check your completed program against the grading rubric ########################################################### # MY SIMPLE GUI CAR, ORIGINAL PROJECT, YAY! ########################################################### # This program will make the car move across and up the screen # forward, right to left # then reverse, left to right # maybe also down and up import simplegui #initialize global variables for the positions interval=1 width=1000 height=350 cruise=0.05 level=0.1 speed=cruise altitude=0 # position the road, r r1=[10,200] ; r2=[width-10,200] # position the main body of the car, b b1=[715,185];b2=[735,185];b3=[735,155];b4=[700,155];b5=[675,135] b6=[615,135];b7=[575,155];b8=[535,160];b9=[535,185] # position the front door window, fd fd1=[580,155];fd2=[615,137];fd3=[642,137];fd4=[642,155] # position the back door window, bd bd1=[645,155];bd2=[645,137];bd3=[675,137];bd4=[695,155] # position the front wheel, fw fw=[580,185] # position the back wheel, bw bw=[700, 185] # position the head in the car, h h=[625,145] car_position=[b1,b2,b3,b4,b5,b6,b7,b8,b9,fd1,fd2,fd3,fd4,bd1,bd2,bd3,bd4,fw,bw,h] line1="Position b1 = "+str(b1) + "and b9 = "+str(b9) def park(): # function to reset everything and get the car back to start global r1,r2, b1,b2,b3,b4,b5,b6,b7,b8,b9,fd1,fd2,fd3,fd4 global bd1,bd2,bd3,bd4,fw,bw,h, car_position, speed, altitude # position the road, r r1=[10,200] ; r2=[width-10,200] # position the main body of the car, b b1=[715,185];b2=[735,185];b3=[735,155];b4=[700,155];b5=[675,135] b6=[615,135];b7=[575,155];b8=[535,160];b9=[535,185] # position the front door window, fd fd1=[580,155];fd2=[615,137];fd3=[642,137];fd4=[642,155] # position the back door window, bd bd1=[645,155];bd2=[645,137];bd3=[675,137];bd4=[695,155] # position the front wheel, fw fw=[580,185] # position the back wheel, bw bw=[700, 185] # position the head in the car, h h=[625,145] car_position=[b1,b2,b3,b4,b5,b6,b7,b8,b9,fd1,fd2,fd3,fd4,bd1,bd2,bd3,bd4,fw,bw,h] speed=0 altitude=0 # Handler for the timer def tick_drive(): #change position of the car to make it move forward global car_position, speed, altitude, position, line1,b1,b9 for i in car_position: if i[0] < 0: i[0]= i[0] % width i[0] -= speed #i[1] -= altitude elif i[0] > width: i[0]= i[0] % width i[0] -= speed #i[1] -= altitude elif i[1] < 0: i[1] = i[1] % height #i[0] -= speed i[1] -= altitude elif i[1] > height: i[0]= i[0] % height i[0] -= speed #i[1] -= altitude else: i[0] -= speed i[1] -= altitude line1="Position b1 = "+str(b1) + "and b9 = "+str(b9) # Button to go forward def forward(): global speed if speed==0: speed = cruise else: speed=abs(speed) # Button to increase speed def accelerator(): global speed if speed==0: speed = cruise else: speed *= 2 # Button to reduce speed #def decelerator(): # global speed # if speed > 0: # speed -= 1 # Emergency brakes def emergency_brake(): global speed, altitude speed=0 altitude=0 # Button to reverse def reverse(): global speed if speed==0: speed = -cruise elif speed>0: speed *= -1 else: pass # Button to ramp up or fly def fly(): global b1, b9, altitude #if 20<b1[1]<186 and 20<b9[1]<186 and 20<b1[0]<980 and 20<b9[0]<980: altitude = level # Button to land or go down def land(): global altitude, b1, b9 altitude = -level # Handler to draw the car position def draw(canvas): global r1,r2, b1,b2,b3,b4,b5,b6,b7,b8,b9,fd1,fd2,fd3,fd4 global bd1,bd2,bd3,bd4,fw,bw,h # draw label of the car on canvas canvas.draw_text("My simpleGUI car", [160,30], 20, "Orange") # draw a blue line for the road, r canvas.draw_line(r1, r2, 5, "Blue") # draw the main body of the car, b canvas.draw_polygon([b1,b2,b3,b4,b5,b6,b7,b8,b9], 1,"red", "red") # draw the front door window, fd canvas.draw_polygon([fd1,fd2,fd3,fd4],1,"orange", "yellow") # draw the back door window, bd canvas.draw_polygon([bd1,bd2,bd3,bd4],1, "orange", "yellow") #draw the front wheel, fw canvas.draw_circle(fw, 13, 1, "black", "black") # draw the back wheel, bw canvas.draw_circle(bw, 13, 1, "black", "black") # draw the head in the car, h canvas.draw_circle(h,6,1,"black", "black") canvas.draw_text(line1,[700,210], 10, "Orange") #create frame and callbacks to event handlers frame=simplegui.create_frame("My Frame", width, height) frame.set_canvas_background("Brown") frame.add_button("Forward",forward, 150) frame.add_button("Reverse",reverse, 150) frame.add_button("UP!", fly, 150) frame.add_button("DOWN!", land, 150) frame.add_button("Accelerate",accelerator, 150) #frame.add_button("Decelerate",decelerator, 150) frame.add_button("Emergency Brake", emergency_brake, 150) frame.add_button("PARK THE CAR", park, 150) #register draw handler frame.set_draw_handler(draw) #register timer timer1=simplegui.create_timer(interval, tick_drive) #start frame frame.start() timer1.start() ################################################ # THE STOPWATCH GAME ################################################ # template for "Stopwatch: The Game" import simplegui import time # define global variables interval= 100 tracker = 0 stops = 0 hits = 0 status="StopWatch" # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): # returns format A:BC.D if t <10: D = t % 10 C = (t - D)/10 B = 0 A = 0 return str(A)+":"+str(B)+str(C)+"."+str(D) elif t < 100: D = t % 10 C = (t - D)/10 B = (t - C*10- D)/60 A = 0 return str(A)+":"+str(B)+str(C)+"."+str(D) elif t <600: D = t % 10 C = (t %100 - D)/10 B = (t - C*10 -D)/100 A = 0 return str(A)+":"+str(B)+str(C)+"."+str(D) elif t >= 600: D = t % 10 C = (t %100 - D)/10 B = (t % 600 -D)/100 A = (t - B*100 - C*10 -D)/600 return str(A)+":"+str(B)+str(C)+"."+str(D) # define event handlers for buttons; "Start", "Stop", "Reset" def start(): global tracker, hits, stops, status status="Watch running..." timer.start() def stop(): global tracker, hits, stops, status # check if timer running not_running = not timer.is_running() if not_running: status="Start watch first!" else: timer.stop() if float(tracker % 10) < 1: hits +=1 stops += 1 status=":-) Got'Em, Ha!" else: stops += 1 status=":-( You missed." def reset(): global tracker, hits, stops, status timer.stop() tracker = 0 hits = 0 stops = 0 status = "StopWatch" # define event handler for timer with 0.1 sec interval def tick(): global tracker tracker += 1 #print tracker # define draw handler def draw(canvas): canvas.draw_polygon([[80,185],[80,140],[230,140],[230,185]],5, "black", "orange") canvas.draw_text(format(tracker), [95,180], 50, "black") canvas.draw_text(str(hits)+"/"+str(stops), [230,35],25, "white") canvas.draw_text(status, [20,35], 25, "yellow") canvas.draw_circle([155, 160],105,10,"black") # create frame frame=simplegui.create_frame("StopWatch",300,300) # register event handlers timer = simplegui.create_timer(interval, tick) frame.set_draw_handler(draw) frame.set_canvas_background("brown") start = frame.add_button("START", start, 120) stop = frame.add_button("STOP", stop, 120) reset = frame.add_button("RESET", reset, 120) # start frame frame.start() # Please remember to review the grading rubric #-------------------------------------------------------------- # FINAL MINI PROJ WEEK 4: PONG #-------------------------------------------------------------- # Implementation of classic arcade game Pong import simplegui import random import math # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 #LEFT = False #RIGHT = True direction = random.choice(['LEFT', 'RIGHT']) ball_pos = [WIDTH / 2, HEIGHT / 2] paddle1_vel = 0 paddle2_vel = 0 rules1 = "Instructions:" rules2 = """ This is Pong! This is a two-player game. However, if you have no friends, do not worry because this is also a good opportunity to battle your left hand vs. your right hand! """ rules3=""" Left controls: Up - 'w' Down - 's' """ rules4 =""" Right Controls: Up - 'up arrow' Down - 'down arrow' """ rules5=""" Push RESTART to do just that. Enjoy! """ blank=" " # initialize ball_pos and ball_vel for new bal in middle of table # if direction is RIGHT, the ball's velocity is upper right, else upper left def spawn_ball(direction): global ball_pos, ball_vel # these are vectors stored as lists ball_pos = [WIDTH / 2, HEIGHT / 2] v_horiz = random.randrange(120, 140) v_vert = random.randrange(60, 180) if direction == 'LEFT': #spawn up and left ball_vel = [-v_horiz/60, -v_vert/60] elif direction == 'RIGHT': #spawn up and right ball_vel = [v_horiz/60, -v_vert/60] else: pass # define event handlers def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel,direction # these are numbers global score1, score2 # these are ints direction = random.choice(['LEFT', 'RIGHT']) paddle1_pos = HEIGHT / 2 paddle2_pos = HEIGHT / 2 score1 = 0 score2 = 0 spawn_ball(direction) def draw(canvas): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel # draw mid line and gutters canvas.draw_circle([WIDTH / 2, HEIGHT / 2], 50, 1, 'white') canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") # update ball ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] if ball_pos[1] >= HEIGHT - 1 - BALL_RADIUS or ball_pos[1] <= BALL_RADIUS: ball_vel[1] = -ball_vel[1] elif ball_pos[0]<=BALL_RADIUS + PAD_WIDTH and abs(ball_pos[1]-paddle1_pos) < HALF_PAD_HEIGHT + BALL_RADIUS: ball_vel[0] = -ball_vel[0] * 1.1 elif ball_pos[0]>=WIDTH - 1 - BALL_RADIUS - PAD_WIDTH and abs(ball_pos[1]-paddle2_pos)< HALF_PAD_HEIGHT + BALL_RADIUS: ball_vel[0] = -ball_vel[0] * 1.1 elif ball_pos[0] >= WIDTH - 1 - BALL_RADIUS - PAD_WIDTH: score1 += 1 spawn_ball('LEFT') elif ball_pos[0] <= BALL_RADIUS + PAD_WIDTH: score2 += 1 spawn_ball('RIGHT') else: ball_vel[0] = ball_vel[0] # draw ball canvas.draw_circle(ball_pos, BALL_RADIUS, 1, 'white', 'white') # update paddle's vertical position, keep paddle on the screen paddle1_pos += paddle1_vel paddle2_pos += paddle2_vel if paddle1_pos <= HALF_PAD_HEIGHT or paddle1_pos >= HEIGHT - 1 - HALF_PAD_HEIGHT: paddle1_vel = 0 if paddle2_pos <= HALF_PAD_HEIGHT or paddle2_pos >= HEIGHT - 1 - HALF_PAD_HEIGHT: paddle2_vel = 0 # get ball speed speed ="Ball Speed: "+ str(abs(ball_vel[0]*60))+ " px/sec" # draw paddles canvas.draw_line([0,paddle1_pos + HALF_PAD_HEIGHT],[0, paddle1_pos - HALF_PAD_HEIGHT], PAD_WIDTH, 'yellow') canvas.draw_line([WIDTH, paddle2_pos + HALF_PAD_HEIGHT], [WIDTH, paddle2_pos - HALF_PAD_HEIGHT], PAD_WIDTH, 'yellow') # determine whether paddle and ball collide # draw scores canvas.draw_text(str(score1), [WIDTH / 4, 50], 50, 'white') canvas.draw_text(str(score2), [3*WIDTH / 4, 50], 50, 'white') canvas.draw_text(speed, [WIDTH /2-100, HEIGHT], 15, 'yellow') def keydown(key): global paddle1_vel, paddle2_vel if key == simplegui.KEY_MAP['up'] and paddle2_pos > HALF_PAD_HEIGHT: paddle2_vel -= 10 elif key == simplegui.KEY_MAP['down'] and paddle2_pos<= HEIGHT - 1 - HALF_PAD_HEIGHT: paddle2_vel += 10 elif key == simplegui.KEY_MAP['w'] and paddle1_pos > HALF_PAD_HEIGHT: paddle1_vel -= 10 elif key == simplegui.KEY_MAP['s'] and paddle1_pos <= HEIGHT - 1 - HALF_PAD_HEIGHT: paddle1_vel += 10 else: pass def keyup(key): global paddle1_vel, paddle2_vel if key == simplegui.KEY_MAP['up']: paddle2_vel = 0 elif key == simplegui.KEY_MAP['down']: paddle2_vel = 0 elif key == simplegui.KEY_MAP['w']: paddle1_vel = 0 elif key == simplegui.KEY_MAP['s']: paddle1_vel = 0 else: pass def restart(): new_game() # create frame frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) frame.add_label(rules1, 210) frame.add_label(blank, 210) frame.add_label(rules2, 210) frame.add_label(blank, 210) frame.add_label(rules3, 210) frame.add_label(blank, 210) frame.add_label(rules4, 210) frame.add_label(blank, 210) frame.add_label(rules5, 210) frame.add_label(blank, 210) frame.add_button("RESTART", restart, 120) # start frame new_game() frame.start()
true
5e1d5e7a2fc30bf1f5bab85d28e9cc213989a319
Python
Amara-Manikanta/Python-GUI
/PYQT5/Games/RockPapperScissorsGame.py
UTF-8
4,072
2.890625
3
[ "MIT" ]
permissive
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QFont, QPixmap from PyQt5.QtCore import QTimer from random import randint font = QFont("Times", 14) buttonFont = QFont("Arial", 12) computerScore = 0 playerScore = 0 class Windows(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Using Spinboxes") self.setGeometry(350, 150, 550, 500) self.UI() def UI(self): ############################Score Borad############################# self.scorecomputerText = QLabel("Computer Score : ", self) self.scorecomputerText.move(30, 20) self.scorecomputerText.setFont(font) self.scorePlayerText = QLabel("Your Score : ", self) self.scorePlayerText.setFont(font) self.scorePlayerText.move(330, 20) ##########################Images################################### self.imageComputer = QLabel(self) self.imageComputer.setPixmap(QPixmap("Images/rock.png")) self.imageComputer.move(50, 100) self.imagePlayer = QLabel(self) self.imagePlayer.setPixmap(QPixmap("Images/rock.png")) self.imagePlayer.move(330, 100) self.imagegame = QLabel(self) self.imagegame.setPixmap(QPixmap("Images/game.png")) self.imagegame.move(230, 145) ##################Buttons######################### startButton = QPushButton("Start", self) startButton.setFont(buttonFont) startButton.move(90, 250) startButton.clicked.connect(self.funcstart) stopButton = QPushButton("Stop", self) stopButton.setFont(buttonFont) stopButton.move(350, 250) stopButton.clicked.connect(self.funcstop) ######################Timer########################## self.timer = QTimer(self) self.timer.setInterval(50) self.timer.timeout.connect(self.playGame) self.show() def playGame(self): self.rndcomputer = randint(1, 3) if self.rndcomputer == 1: self.imageComputer.setPixmap(QPixmap("Images/rock.png")) elif self.rndcomputer == 2: self.imageComputer.setPixmap(QPixmap("Images/paper.png")) else: self.imageComputer.setPixmap(QPixmap("Images/scissors.png")) self.rndplayer = randint(1, 3) if self.rndplayer == 1: self.imagePlayer.setPixmap(QPixmap("Images/rock.png")) elif self.rndplayer == 2: self.imagePlayer.setPixmap(QPixmap("Images/paper.png")) else: self.imagePlayer.setPixmap(QPixmap("Images/scissors.png")) def funcstart(self): self.timer.start() def funcstop(self): global computerScore global playerScore self.timer.stop() if (self.rndcomputer == 1 and self.rndplayer == 1) or (self.rndcomputer == 2 and self.rndplayer == 2) or ( self.rndcomputer == 3 and self.rndplayer == 3): mbox = QMessageBox.information(self, "Information", "Draw Game") elif (self.rndcomputer == 1 and self.rndplayer == 2) or (self.rndcomputer == 2 and self.rndplayer == 3) or ( self.rndcomputer == 3 and self.rndplayer == 1): mbox = QMessageBox.information(self, "Information", "you win!") playerScore += 1 self.scorePlayerText.setText("Your Score:" + str(playerScore)) elif (self.rndcomputer == 1 and self.rndplayer == 3) or (self.rndcomputer == 2 and self.rndplayer == 1) or ( self.rndcomputer == 3 and self.rndplayer == 2): mbox = QMessageBox.information(self, "Information", "Computer wins!") computerScore += 1 self.scorecomputerText.setText("Computer Score:" + str(computerScore)) if computerScore == 5 or playerScore == 5: mbox = QMessageBox.information(self, "Information", "Game Over") sys.exit() def main(): App = QApplication(sys.argv) window = Windows() sys.exit(App.exec_()) if __name__ == '__main__': main()
true
a8b8bc715a16dafd0549c5f6793fe7e11999fc66
Python
nihal-wadhwa/Computer-Science-1
/Labs/Lab02/scenery.py
UTF-8
4,758
4
4
[]
no_license
""" Author: Nihal Wadhwa Turtle Scenery: This program's purpose is to create a scenery with two houses of varying sizes and a tree. """ import turtle as tt import math def init() : """ Moves the turtle 275 units to the left to set up for the beginning of the phrase. Precondition: turtle is down Precondition: turtle is at default position Postcondition: turtle is 275 units left of the default poistion, facing right. """ tt.up() tt.left(180) tt.forward(275) tt.right(180) tt.down() def rect(x,y): """ Draws rectangle with width x, and height y Precondition: turtle is at the bottom left of the rectangle, facing right Postcondition: turtle has drawn the rectangle, ending at the bottom left of the rectangle, facing right """ tt.down() tt.forward(x) tt.left(90) tt.forward(y) tt.left(90) tt.forward(x) tt.left(90) tt.forward(y) tt.left(90) def triangle(b,h): """ Draws an isosoceles triangle with base b and height h. Precondition: turtle is at the bottom left of the triangle, facing left Postcondition: turtle draws the triangle, ending at the bottom left of the triangle, facing left """ L = math.sqrt((h**2)+((b/2)**2)) angle = math.degrees(math.asin(h/L)) tt.forward(b) tt.right(180-angle) tt.forward(L) tt.right(2*angle) tt.forward(L) tt.right(180-angle) def house(base, height, h, hcolor): """ Draws a house with a roof and windows. Takes in the parameters of base, height, height of roof (h), and color of house (hcolor) Precondition: turtle is located at the bottom left of the house, facing right Precondition: turtle is down Precondition: Paramaters base, height, and h are integers. hcolor is a string Postcondition: turtle draws the house, ending at the bottom right of the house, facing right """ tt.color(hcolor) tt.begin_fill() rect(base,height) tt.end_fill() tt.forward((base/2)-(base/10)) tt.color('brown') tt.begin_fill() rect(base/5,height/4) tt.end_fill() tt.up() tt.forward((base/2)+(base/10)) tt.left(90) tt.forward(height) tt.left(90) tt.down() tt.color('black') tt.begin_fill() triangle(base,h) tt.end_fill() tt.up() tt.left(90) tt.forward((height/10)*6) tt.right(90) tt.forward((base/10)*3) tt.right(180) tt.color('grey') tt.begin_fill() rect(base/5,base/5) tt.end_fill() tt.up() tt.left(180) tt.forward((base/10)*6) tt.right(180) tt.color('grey') tt.begin_fill() rect(base/5,base/5) tt.end_fill() tt.up() tt.forward((base/10)*9) if ((base/height) > 1): tt.right(90) tt.forward((height/10)*4) tt.left(90) tt.color('black') return (base*height) else: tt.left(90) tt.forward((height/10)*3) tt.left(90) tt.forward((base/10)*3) tt.right(180) tt.color('grey') tt.begin_fill() rect(base/5,base/5) tt.end_fill() tt.up() tt.left(180) tt.forward((base/10)*6) tt.right(180) tt.color('grey') tt.begin_fill() rect(base/5,base/5) tt.end_fill() tt.up() tt.forward((base/10)*9) tt.right(90) tt.forward((height/10)*7) tt.left(90) tt.color('black') return (base*height) def tree (h,w,r): """ Draws a tree of height h, width w, and radius r. Precondition: turtle is at the bottom of the tree, facing right Precondition: turtle is down Postcondition: turtle has drawn a tree, ending at the bottom of the tree, facing right """ tt.color('brown') tt.pensize(w) tt.down() tt.left(90) tt.forward(h) tt.right(90) tt.color('green') tt.begin_fill() tt.circle(r) tt.end_fill() tt.up() tt.left(90) tt.backward(h) tt.right(90) tt.up() tt.pensize(1) tt.color('black') def main(): """ Draws two houses and a tree. Precondition: turtle is up Precondition: turtle is at default position Postcondition: turtle has drawn two houses and a tree, ending at the bottom right of the second house. """ init() print("big facade is", house(100,200,60,'yellow'), "square units.") tt.forward(100) tree(200,5,50) tt.forward(100) print("small facade is",house(150,100,80,'cyan'), "square units.") main() tt.done()
true
6d531d5cdec17148cc495952735943d18bb734a3
Python
Egor-Ozhmegoff/Python-for-network-engineers
/solutions/07_files/task_7_2b.py
UTF-8
1,420
2.84375
3
[]
no_license
# -*- coding: utf-8 -*- """ Задание 7.2b Дополнить скрипт из задания 7.2a: * вместо вывода на стандартный поток вывода, скрипт должен записать полученные строки в файл config_sw1_cleared.txt При этом, должны быть отфильтрованы строки, которые содержатся в списке ignore. Строки, которые начинаются на '!' отфильтровывать не нужно. Ограничение: Все задания надо выполнять используя только пройденные темы. """ from sys import argv ignore = ["duplex", "alias", "Current configuration"] src_file, dst_file = argv[1], "config_sw1_cleared.txt" with open(src_file) as src, open(dst_file, 'w') as dst: for line in src: skip_line = False for ignore_word in ignore: if ignore_word in line: skip_line = True break if not line.startswith("!") and not skip_line: dst.write(line) # вариант решения с for/else with open(src_file) as src, open(dst_file, 'w') as dst: for line in src: for ignore_word in ignore: if line.startswith("!") or ignore_word in line: break else: dst.write(line)
true
45ee30bbe8e533b63d30bcb70063983ca86524bd
Python
MichaelK8/Media-library-Clean-PY3
/image-test.py
UTF-8
442
2.6875
3
[]
no_license
import pyautogui as pg print("skript jede\n") btnMove = pg.locateCenterOnScreen('btn-move-middle.png') locPath = pg.locateOnScreen('path.png') if locPath != None: print("našel jsem screenshot path") print(locPath) elif btnMove != None: print("našel jsem screenshot move\n") pg.moveTo(btnMove, duration=0.4, tween=pg.easeInOutQuad) pg.click(button='right', clicks=2, interval=0.25) else: print("žádný screenshot jsem nenašel")
true
c7f68bffcde6efdebc363baad3559f4a420bf3b0
Python
fgerce/DSP-Entregas
/Pruebas TP1/Prueba FFT y desparramo.py
UTF-8
2,399
3.0625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 28 21:06:34 2019 @author: fede """ from Modulos import instrumentos as ins import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np N = 1000 # muestras fs = 1000 # Hz a0 = 1 # Volts p0 = 0 # radianes f0 = fs/4 f1 = f0 + 0.01 f2 = f0 + 0.25 f3 = f0 + 0.5 "Generador de señal" tt0, signal0 = ins.generador_senoidal (fs, f0, N, a0, p0) tt1, signal1 = ins.generador_senoidal (fs, f1, N, a0, p0) tt2, signal2 = ins.generador_senoidal (fs, f2, N, a0, p0) tt3, signal3 = ins.generador_senoidal (fs, f3, N, a0, p0) "Graficador temporal, esto solo tiene sentido para frecuencias muy bajas." "En el orden de fs/10 ya se rompe todo" """ plt.plot(tt,signal) plt.legend(loc='upper right') plt.xlabel('Tiempo [t]') plt.ylabel('Amplitud [V]') plt.title("Señal: Senoidal") """ modulo0, fase0, ww0 = ins.analizador_espectro(signal0, fs) modulo1, fase1, ww1 = ins.analizador_espectro(signal1, fs) modulo2, fase2, ww2 = ins.analizador_espectro(signal2, fs) modulo3, fase3, ww3 = ins.analizador_espectro(signal3, fs) f0_0 = 20*np.log10(modulo0[int(f0)]) f0_1 = 20*np.log10(modulo1[int(f0)]) f0_2 = 20*np.log10(modulo2[int(f0)]) f0_3 = 20*np.log10(modulo3[int(f0)]) fady_0 = 20*np.log10(modulo0[int(f0+1)]) fady_1 = 20*np.log10(modulo1[int(f0+1)]) fady_2 = 20*np.log10(modulo2[int(f0+1)]) fady_3 = 20*np.log10(modulo3[int(f0+1)]) sum_resto_frecuencias0 = ins.sumatoria_modulo_cuadrado(modulo0) - modulo0[int(f0)] sum_resto_frecuencias1 = ins.sumatoria_modulo_cuadrado(modulo1) - modulo1[int(f0)] sum_resto_frecuencias2 = ins.sumatoria_modulo_cuadrado(modulo2) - modulo2[int(f0)] sum_resto_frecuencias3 = ins.sumatoria_modulo_cuadrado(modulo3) - modulo3[int(f0)] plt.figure("Analizador espectro") plt.subplot(2,1,1) plt.title("Modulo y fase señal") plt.plot(ww0, modulo0, label='fs') plt.plot(ww1, modulo1, label='+ 0.1') plt.plot(ww2, modulo2, label='+ 0.2') plt.plot(ww3, modulo3, label='+ 0.3') plt.legend(loc='upper right') plt.grid() plt.xlabel("Frecuencia") plt.ylabel("Amplitud") plt.subplot(2,1,2) plt.xlabel("Frecuencia") plt.ylabel("Fase") plt.plot(ww0, fase0, "co") plt.plot(ww1, fase1, "go") plt.plot(ww2, fase2, "bo") plt.plot(ww3, fase3, "ro") plt.legend(loc='upper right') plt.grid() plt.tight_layout()
true
10ac23146ce36b4bd2b2b6c674ce5e150e46466e
Python
A-Jatin/Chat-Bot
/bot.py
UTF-8
950
2.890625
3
[]
no_license
import pandas as pd import re from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity pd.set_option('display.max_colwidth',200) df=pd.read_csv('a.csv') convo = df.iloc[:,0] clist = [] def qa_pairs(x): cpairs = re.findall(": (.*?)(?:$|\n)", x) clist.extend(list(zip(cpairs, cpairs[1:]))) convo.map(qa_pairs); convo_frame = pd.Series(dict(clist)).to_frame().reset_index() convo_frame.columns = ['q', 'a'] vectorizer = TfidfVectorizer(ngram_range=(1,3)) vec = vectorizer.fit_transform(convo_frame['q']) def get_response(q): my_q = vectorizer.transform([q]) cs = cosine_similarity(my_q, vec) rs = pd.Series(cs[0]).sort_values(ascending=False) rsi = rs.index[0] return convo_frame.iloc[rsi]['a'] print("Hey!") while(1 is 1): ans=input() if(ans=="exit" or ans== "Exit"): break print("Bot : " + get_response(ans))
true
e68a3e089acbe173178500fb81ae3d278933de8d
Python
Tospaa/NamazVakit
/namaz2.py
UTF-8
6,920
3
3
[]
no_license
# -*- coding: cp1254 -*- """This is basically a web scraping program for getting praying times from a site. You use a city name as the input and program scrapes it to give you the wanted values. This program uses tkinter as GUI library and bs4 as parsing and manipulating html data. Written by Musa Ecer musaecer@gmail.com This program was designed for Python 3 """ import urllib.request from bs4 import BeautifulSoup import tkinter from time import strftime from os.path import isfile __author__ = "Musa Ecer" __version__ = "0.3" __email__ = "musaecer@gmail.com" def sehir_bul(): sehir = giris.get() sehir = sehir.replace("İ", "I") # büyük i harfi olunca lower() fonksiyonu saçmalıyo. onu burda hallettim. sehir = sehir.lower() sehir = sehir.replace("ş", "s") sehir = sehir.replace("ı", "i") sehir = sehir.replace("ğ", "g") sehir = sehir.replace("ö", "o") sehir = sehir.replace("ü", "u") sehir = sehir.replace("ç", "c") if sehir == "adapazari" or sehir == "sakarya": sehir = "adapazari-sakarya" if sehir == "kocaeli": sehir = "izmit" if sehir == "afyonkarahisar": sehir = "afyon" return sehir def site_bul(): sehir = sehir_bul() sehirlink = "http://www.namazvakti.net/turkiye/{0}-diyanet-ezan-vakitleri.html".format(sehir) page = urllib.request.urlopen(sehirlink) site = BeautifulSoup(page, "lxml") # lxml kütüphanesi yoksa bunu html.parser olarak değiştirebilirsin. return site def kontrol(): with open("data.txt") as f: defter = f.readlines() defter2 = defter[0].split() if defter2[0] == strftime("%d") and defter2[1] == strftime("%m") and defter2[2] == strftime("%y"): durum = False for i in defter: i2 = i.split() if i2[0] == sehir_bul(): durum = True break return durum else: return False def main_func(*args): bilgiEtiket["fg"] = "black" bilgiEtiket["text"] = "Hesaplanıyor..." bilgiEtiket.update_idletasks() if not isfile("data.txt"): with open("data.txt", "w") as f: f.write("Selam sana ey\nDunya\n") with open("data.txt") as f: kitap = f.readlines() if kontrol(): arblist = [] for item in kitap: arblist = item.split() if arblist[0] == sehir_bul(): break sabahLabel["text"] = arblist[1] ogleLabel["text"] = arblist[2] ikindiLabel["text"] = arblist[3] aksamLabel["text"] = arblist[4] yatsiLabel["text"] = arblist[5] bilgiEtiket["text"] = " " else: try: site = site_bul() sabahLabel["text"] = vakit("v im", site) ogleLabel["text"] = vakit("v og", site) ikindiLabel["text"] = vakit("v ik", site) aksamLabel["text"] = vakit("v ak", site) yatsiLabel["text"] = vakit("v ya", site) bilgiEtiket["text"] = "Sonlandırılıyor..." bilgiEtiket.update_idletasks() if (kitap[0].split()[0] + kitap[0].split()[1] + kitap[0].split()[2]) == strftime("%d%m%y"): with open("data.txt", "a") as veri: veri.write( sehir_bul() + " " + sabahLabel["text"] + " " + ogleLabel["text"] + " " + ikindiLabel["text"] + " " + aksamLabel["text"] + " " + yatsiLabel["text"] + "\n" ) else: with open("data.txt", "w") as veri: veri.write(strftime("%d %m %y") + "\n") veri.write( sehir_bul() + " " + sabahLabel["text"] + " " + ogleLabel["text"] + " " + ikindiLabel["text"] + " " + aksamLabel["text"] + " " + yatsiLabel["text"] + "\n" ) bilgiEtiket["text"] = " " except IndexError: sabahLabel["text"] = "00:00" ogleLabel["text"] = "00:00" ikindiLabel["text"] = "00:00" aksamLabel["text"] = "00:00" yatsiLabel["text"] = "00:00" bilgiEtiket["fg"] = "red" bilgiEtiket["text"] = "Şehri yanlış girdiniz." except urllib.error.URLError: sabahLabel["text"] = "00:00" ogleLabel["text"] = "00:00" ikindiLabel["text"] = "00:00" aksamLabel["text"] = "00:00" yatsiLabel["text"] = "00:00" bilgiEtiket["fg"] = "red" bilgiEtiket["text"] = "İnternet yok." def vakit(vak, sitesite): vakitlist = [] for ul in sitesite.find_all("ul", vak): # "ul" tagi içinde "vak" classında olanları al for li in ul.find_all("li"): # yukarıda aldığın "ul"ların içindeki "li" taglarını al vakitlist.append(li.get_text()) # yukarıda bulduğun "li" taglarını "vakitlist"e ekle strvakit = vakitlist[1][-5:] # listeden ikinci elemanı al ve bu elemanın da son 5 karakterini al, gerisini sil return strvakit pencere = tkinter.Tk() pencere.resizable(False, False) pencere.title("Namaz Vakit v0.3") pencere.wm_iconbitmap("info") pencere.bind("<Return>", main_func) label1 = tkinter.Label(text="Şehir giriniz: ") giris = tkinter.Entry() giris.insert(0, "Afyon") buton = tkinter.Button(text="Hesapla", command=main_func) label2 = tkinter.Label(text="Sabah Namazı: ", font=("Helvetica", 20)) label3 = tkinter.Label(text="Öğle Namazı: ", font=("Helvetica", 20)) label4 = tkinter.Label(text="İkindi Namazı: ", font=("Helvetica", 20)) label5 = tkinter.Label(text="Akşam Namazı: ", font=("Helvetica", 20)) label6 = tkinter.Label(text="Yatsı Namazı: ", font=("Helvetica", 20)) bilgiEtiket = tkinter.Label(text=" ", font=("Helvetica", 20)) sabahLabel = tkinter.Label(text="00:00", font=("Helvetica", 20)) ogleLabel = tkinter.Label(text="00:00", font=("Helvetica", 20)) ikindiLabel = tkinter.Label(text="00:00", font=("Helvetica", 20)) aksamLabel = tkinter.Label(text="00:00", font=("Helvetica", 20)) yatsiLabel = tkinter.Label(text="00:00", font=("Helvetica", 20)) label1.grid(row=0, column=0, sticky="w") giris.grid(row=0, column=1, padx=10) buton.grid(row=1, column=0, columnspan=2, sticky="we", pady=20) label2.grid(row=2, column=0, sticky="w") label3.grid(row=3, column=0, sticky="w") label4.grid(row=4, column=0, sticky="w") label5.grid(row=5, column=0, sticky="w") label6.grid(row=6, column=0, sticky="w") sabahLabel.grid(row=2, column=1, padx=10) ogleLabel.grid(row=3, column=1, padx=10) ikindiLabel.grid(row=4, column=1, padx=10) aksamLabel.grid(row=5, column=1, padx=10) yatsiLabel.grid(row=6, column=1, padx=10) bilgiEtiket.grid(row=7, column=0, columnspan=2) tkinter.mainloop()
true
a3e3ae1f672cc9429f08375274e0683f9585cf4b
Python
bryangalindo/centrans_soc_scraper
/utils.py
UTF-8
562
2.875
3
[ "MIT" ]
permissive
from bs4 import BeautifulSoup from database import Database import requests def make_soup(url): ''' Retrieves html code from url ''' headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko)' ' Version/11.1.2 Safari/605.1.15'} response = requests.get(url, headers=headers) if response.status_code != 200: print('Oops, you\'ve come across status code error: %s' % str(response.status_code)) return BeautifulSoup(response.content, "html.parser")
true
1c55658b754016da81f280a3500352c52ea1225c
Python
Abhiroopmokshagna/Dynamic_Programming
/fibonacci.py
UTF-8
278
3.515625
4
[]
no_license
def fibonacci(n, lookup): if(lookup[n] == None): lookup[n] = fibonacci(n-1,lookup) + fibonacci(n-2, lookup) return lookup[n] lookup = [None] * 101 lookup[0] = 0 lookup[1] = 1 def main(): print(fibonacci(16, lookup)) if __name__ == '__main__': main()
true
84132de9f878e0a531d1e997ed75bf3af6dac36e
Python
Smy281677623/PowerTool
/test/MathUtil.py
UTF-8
950
3.390625
3
[]
no_license
# -*- coding:utf-8 -*- import numpy as np import math class MathUtils(object): def __init__(self): self.a_ = None self.b_ = None self.c_ = None def fit(self, x_train, y_train): assert x_train is not None and y_train is not None, \ "x_train, y_train can not be None" x = np.array(x_train) y = np.array(y_train) return self._predict(x, y) def _predict(self, x , y): f1 = np.polyfit(x, y, 2) return f1 def main(): a = MathUtils() x = [598, 722, 798, 878, 956, 1033, 1108, 1188, 1263] y = [1151, 2051, 3249, 3249, 3841, 4433, 5025, 5617, 6212] result = a.fit(x, y) print(result[0]) print(result[1]) print(result[2]) # c print(int(round(round(result[0], 8) * 1000000, 2))) # b print(int(round(result[1], 8) * 10000)) # a print(int(round(result[2], 8) * 10000)) if __name__ == '__main__': main()
true
3ed9623a6689509349714a6898350f7b3757db5d
Python
wafarifki/Hacktoberfest2021
/Python/Get Free Courses/free-course/freecourse.py
UTF-8
1,753
3.28125
3
[]
no_license
import requests from bs4 import BeautifulSoup ''' Scrapes Free Courses Detail from Disudemy ''' baseurl = "https://www.discudemy.com/search/" def req(url): respponse = requests.get(url).text return respponse class Courses: def __init__(self, topic) -> None: self.topic = topic content = req((baseurl + self.topic)) html_content = BeautifulSoup(content, "html.parser") self.content_in_div = html_content.find("div", "content") def get_course_title(self): course_title = (self.content_in_div.find("a", "card-header")).text return course_title def get_course_desc(self): course_description = (self.content_in_div.find("div", "description")).text return course_description def get_course_thumbnail(self): image_link = (self.content_in_div.find("amp-img"))["src"] return image_link def get_courselink(self): disudemy_course_link = (self.content_in_div.find("a", "card-header"))["href"] disudemy_takecourse_button = req(disudemy_course_link) disudemy_couponlink = (BeautifulSoup(disudemy_takecourse_button, "html.parser")).find("div", "ui center aligned basic segment") downloadpagelink = (disudemy_couponlink.find("a"))["href"] lastpage = req(downloadpagelink) link = ( BeautifulSoup(lastpage, "html.parser") .find("div", "ui segment") .find("a")["href"] ) return link if __name__ == "__main__": topic = input("Input Topic or Course name: ") course = Courses(topic=topic) print(course.get_course_title()) print(course.get_course_desc().strip()) print(course.get_course_thumbnail()) print(course.get_courselink())
true
7d4cd6e96bc232d0d45f050937f01ae5f1d0c67e
Python
KJfamily33/NSFW_Detection
/detector.py
UTF-8
3,477
2.890625
3
[ "MIT" ]
permissive
from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model from keras.layers import Input, Dense, merge from keras.applications.resnet50 import ResNet50 import numpy as np class Detector(object): def __init__(self, img_shape, n_dense): '''Initializes the detector network: ----------- img_shape: tuple A tuple denoting the image shape that the network is trained on. Should be of the form (height,width,channels) n_dense: int Number of units in the dense layers that are put on top of the pre trained ResNet. Returns: -------- Initialized detector network. ''' self.model = self.get_pre_resnet(img_shape, n_dense) def get_pre_resnet(self, input_shape, n_dense): '''Loads the pretrained Keras ResNet, adds 2 trainable dense layers and returns the compiled graph: ----------- input_shape: tuple A tuple denoting the image shape that the network is trained on. Should be of the form (height,width,channels) n_dense: int Number of units in the dense layers that are put on top of the pre trained ResNet. Returns: -------- Compiled detector network. ''' base_model = ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=input_shape) x = base_model.output f_1 = Flatten()(x) n1 = BatchNormalization()(f_1) fc1 = Dense(n_dense)(n1) r1 = Activation('relu')(fc1) n2 = BatchNormalization()(r1) fc2 = Dense(n_dense)(n2) r2 = Activation('relu')(fc2) n3 = BatchNormalization()(r2) fc3 = Dense(2)(n3) final = Activation('softmax')(fc3) res_net = Model(input=base_model.input, output=final) for layer in base_model.layers: layer.trainable = False res_net.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return res_net def train_on_batch(self, X,Y): '''Same method as in the Keras API: ----------- X: np.array Numpy array containing the training data of shape (n_samples, height, width, channels) Y: np.array Corresponding labels for the training data. Returns: -------- None ''' self.model.train_on_batch(X.astype(np.float32), Y) def predict(self, X): '''Returns rounded predictions on the given data: ----------- X: np.array Numpy array containing the data of shape (n_samples, height, width, channels) Returns: -------- Prediction: np.array Numpy array containing the predictions with either 1 or 0 ''' return np.round(self.model.predict(X)[:,1]) def save_weights(self, path): '''Same method as in the Keras API: ----------- path: str Filename of the model to be saved Returns: -------- None ''' self.model.save_weights(path) def load_weights(self, path): '''Same method as in the Keras API: ----------- path: str Filename of the model to be loaded Returns: -------- None ''' self.model.load_weights(path)
true
78a60757ec97de757f81bb1bd1c030d2a12a28dd
Python
tavog96/distribuidosProyecto
/lacusClient_p2pTest/app_infrastructure/resourceManagement/resourceDirectoryScan.py
UTF-8
1,221
2.796875
3
[ "MIT" ]
permissive
import os class filesScaner: defaultAppPath = '' def __init__(self, appPath = '.'): super().__init__() self.defaultAppPath = appPath def filesPathScan (self): files = [] # r=root, d=directories, f = files for r, d, f in os.walk(self.defaultAppPath): for file in f: if (r==self.defaultAppPath): files.append(file) return files def fileInfoScan (self, filepath): fileInfoResult = {} fileMetaStats = os.stat(self.defaultAppPath+'/'+filepath) fileInfoResult['name'] = filepath fileInfoResult['size'] = fileMetaStats.st_size fileInfoResult['lastmodificate'] = fileMetaStats.st_mtime return fileInfoResult def filesInfoScan (self): filesInfo2Return=[] filespaths = self.filesPathScan() for eachFilepath in filespaths: if '.py' not in eachFilepath and eachFilepath != "__pycache__": filesInfo2Return.append(self.fileInfoScan(eachFilepath)) return filesInfo2Return def testPrintableFilesInfo (self): filesInfo = self.filesInfoScan() print (filesInfo)
true