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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f604ea2e3951a4fe114a46457ec486e1156d26a | Python | Kevinfu510/TridentFrame | /tridentframe_cli.py | UTF-8 | 10,338 | 2.96875 | 3 | [
"MIT"
] | permissive | import os
import string
from random import choices
from pprint import pprint
import click
from click import ClickException
from click import FileError
from PIL import Image
from apng import APNG
from colorama import init, deinit
@click.group()
def cli():
pass
img_exts = ['png', 'jpg', 'jpeg', 'gif', 'bmp']
static_img_exts = ['png', 'jpg']
animated_img_exts = ['gif', 'png']
@cli.command('rename')
@click.option('-n', '--name', help='Custom filename')
@click.argument('directory', type=click.Path(exists=True))
def rename(name, directory):
init()
if not os.path.isfile(directory):
raise FileError(directory, "Oi skrubman the path here seems to be a bloody file, should've been a directory")
if directory:
os.chdir(directory)
images = [(f, str.lower(f.split('.')[-1])) for f in os.listdir('.')
if not os.path.isdir(f) and '.' in f and str.lower(f.split('.')[-1]) in img_exts]
if not name:
name = ''.join(choices(string.ascii_letters, k=10))
pad_count = max(len(str(len(images))), 3)
click.secho(f"Renaming {len(images)} images...", fg='blue')
for index, (img, ext) in enumerate(images):
new_name = f"{name}_{str.zfill(str(index), pad_count)}.{ext}"
os.rename(img, new_name)
click.secho(f"{index + 1}. {img} -> {new_name}", fg='cyan')
click.secho(f"Done!!1", fg='blue')
deinit()
@cli.command('inspect')
@click.argument('file_path', type=click.Path(exists=True))
@click.option('-v', '--verbose', is_flag=True, help='Outputs more detailed information')
def inspect(file_path, verbose):
init()
if not os.path.isfile(file_path):
raise FileError(file_path, "Oi skrubman the path here seems to be a bloody directory, should've been a file")
file = str(os.path.basename(file_path))
abspath = os.path.abspath(file_path)
workpath = os.path.dirname(abspath)
if verbose:
click.secho(f"dir_path: {file_path}\nabspath: {abspath}\nworkpath: {workpath}\nfile: {file}",
fg='bright_cyan')
if os.getcwd() != workpath:
os.chdir(workpath)
ext = str.lower(os.path.splitext(file)[1])
print(ext)
if ext == '.gif':
try:
gif: Image = Image.open(file)
except Exception:
raise FileError(file, "M8 I don't even think this file is even an image file in the first place")
if gif.format != 'GIF' or not gif.is_animated:
raise FileError(file, "Sorry m9, the image you specified is not a valid animated GIF")
click.secho(f"Total frames: {gif.n_frames}", fg="cyan")
click.secho(f"First frame information", fg="cyan")
pprint(gif.info)
durations = []
for f in range(0, gif.n_frames):
gif.seek(f)
durations.append(gif.info['duration'])
duration = sum(durations) / len(durations)
fps = 1000 / duration
click.secho(f"Average duration per frame: {duration}ms", fg="cyan")
click.secho(f"Image FPS: {fps}", fg="cyan")
elif ext == '.png':
# try:
apng: APNG = APNG.open(file)
frames = apng.frames
frame_count = len(frames)
png_one, controller_one = frames[0]
pprint(png_one.__dict__)
pprint(controller_one.__dict__)
print(png_one.width)
# width = apng.width
# height = apng.height
# print(frame_count, width, height)
# except Exception:
# raise FileError(file, "M8 I don't even think this file is even an image file in the first place")
else:
raise ClickException("Only GIFs and PNGs are supported")
@cli.command('split')
@click.argument('file_path', type=click.Path(exists=True))
@click.option('-o', '--output_name', help='Name of the split gif images')
@click.option('-v', '--verbose', is_flag=True, help='Outputs more detailed information')
def split(file_path, output_name, verbose):
init()
if not os.path.isfile(file_path):
raise FileError(file_path, "Oi skrubman the path here seems to be a bloody directory, should've been a file")
file = str(os.path.basename(file_path))
abspath = os.path.abspath(file_path)
workpath = os.path.dirname(abspath)
if verbose:
click.secho(f"dir_path: {file_path}\nabspath: {abspath}\nworkpath: {workpath}\nfile: {file}",
fg='bright_cyan')
if os.getcwd() != workpath:
os.chdir(workpath)
# Custom output dirname and frame names if specified on the cli
if '.' not in file:
raise ClickException('Where the fuk is the extension mate?!')
if not output_name:
output_name = '_'.join(file.split('.')[:-1])
ext = str.lower(file.split('.')[-1])
if ext not in animated_img_exts:
raise ClickException('Only supported extensions are gif and apng. Sry lad')
# Output directory handling
dirname = output_name
# Create directory to contain all the frames if does not exist
if not os.path.exists(dirname):
os.mkdir(dirname)
click.secho(f"Creating directory {dirname}...", fg='cyan')
else:
click.secho(f"Directory {dirname} already exists, replacing the PNGs inside it...", fg='cyan')
# Image processing
if ext == 'gif':
try:
gif: Image = Image.open(file)
except Exception:
raise FileError(file, "M8 I don't even think this file is even an image file in the first place")
if gif.format != 'GIF' or not gif.is_animated:
raise FileError(file, "Sorry m9, the image you specified is not a valid animated GIF")
click.secho(f"{file} ({gif.n_frames} frames). Splitting GIF...", fg='cyan')
pad_count = max(len(str(gif.n_frames)), 3)
frame_nums = list(range(0, gif.n_frames))
with click.progressbar(frame_nums, empty_char=" ", fill_char="█", show_percent=True, show_pos=True) as frames:
for f in frames:
gif.seek(f)
gif.save(os.path.join(dirname, f"{output_name}_{str.zfill(str(f), pad_count)}.png"), 'PNG')
elif ext == 'png':
img: APNG = APNG.open(file)
iframes = img.frames
pad_count = max(len(str(len(iframes))), 3)
click.secho(f"{file} ({len(iframes)} frames). Splitting APNG...", fg='cyan')
# print('frames', [(png, control.__dict__) for (png, control) in img.frames][0])
with click.progressbar(iframes, empty_char=" ", fill_char="█", show_percent=True, show_pos=True) as frames:
for i, (png, control) in enumerate(frames):
png.save(os.path.join(dirname, f"{output_name}_{str.zfill(str(i), pad_count)}.png"))
click.secho(f"Done!!1", fg='cyan')
deinit()
@cli.command('compose')
@click.argument('dir_path', type=click.Path(exists=True))
@click.option('-x', '--extension', type=click.Choice(['gif', 'apng']), default='gif',
help='Output format extension (gif or apng). Defaults to gif')
@click.option('-f', '--fps', type=click.IntRange(1, 50), default=50, help='Frame rate of the output (1 to 50)')
@click.option('-o', '--output_name', help='Name of the resulting animated image')
@click.option('-t', '--transparent', is_flag=True, help='Use this for images with transparent background')
@click.option('-r', '--reverse', is_flag=True, help='Reverse the frames')
@click.option('-v', '--verbose', is_flag=True, help='Outputs more detailed information')
@click.option('-s', '--scale', type=click.FloatRange(0.1, 100), default=1.0, help='Rescale factor.')
def compose(dir_path, extension, fps, output_name, transparent, reverse, verbose, scale):
init()
if not os.path.isdir(dir_path):
raise FileError(dir_path, "Oi skrubman the path here seems to be a bloody file, should've been a directory")
abspath = os.path.abspath(dir_path)
framesdir = str(os.path.basename(abspath))
workpath = os.path.dirname(abspath)
if verbose:
click.secho(f"dir_path: {dir_path}\nabspath: {abspath}\nworkpath: {workpath}\nframesdir: {framesdir}",
fg='bright_cyan')
# print('argument', dir_path)
# print('framesdir absolute', framesdir)
# print('framesdir dirname', outdir)
# print('basename', basename)
if os.getcwd() != abspath:
os.chdir(abspath)
# If no name supplied, default name will be the framesdir folder name. Output will be in the same parent directory
# as the framesdir
if not output_name:
output_name = framesdir
output_name = os.path.join(workpath, output_name)
imgs = [f for f in os.listdir('.') if '.' in f and str.lower(f.split('.')[-1]) in img_exts]
# First check to make sure every file name have extensions
# if not all('.' in i for i in imgs):
# raise ClickException('Not all the file names have extensions')
# Second checks to make sure extensions are PNG and JPG, and are all uniform
# extensions = [str.lower(i.split('.')[-1]) for i in imgs]
# if any(x not in static_img_exts for x in extensions):
# raise ClickException('Only accepted extensions are PNG and JPG')
# if len(set(extensions)) > 1:
# raise ClickException('Images contain inconsistent file extensions')
duration = round(1000 / fps)
click.secho(f"{len(imgs)} frames @ {fps}fps", fg="cyan")
if extension == 'gif':
frames = [Image.open(i) for i in imgs]
frames.sort(key=lambda i: i.filename, reverse=reverse)
if scale != 1.0:
click.secho(f"Resizing image by {scale}...", fg="cyan")
frames = [f.resize((round(f.width * scale), round(f.height * scale))) for f in frames]
# pprint(frames[0].filename)
disposal = 0
if transparent:
disposal = 2
click.secho("Generating GIF...", fg="cyan")
frames[0].save(f"{output_name}.gif", optimize=False,
save_all=True, append_images=frames[1:], duration=duration, loop=0, disposal=disposal)
click.secho(f"Created GIF {output_name}.gif", fg="cyan")
elif extension == 'apng':
click.secho("Generating APNG...", fg="cyan")
click.secho(f"Created APNG {output_name}.png", fg="cyan")
imgs.sort(reverse=reverse)
APNG.from_files(imgs, delay=duration).save(f"{output_name}.png")
deinit()
if __name__ == '__main__':
cli()
| true |
122abbd7ecf65e6047035d8779e44a72dc07b745 | Python | NikiDimov/SoftUni-Python-Advanced | /exam_preparation_10_21/problem_2 - string_concatenation.py | UTF-8 | 1,004 | 3.5 | 4 | [] | no_license | text = input()
N = int(input())
matrix = [list(input()) for r in range(N)]
def find_player():
for r in range(N):
for col in range(N):
if matrix[r][col] == 'P':
return r, col
def move(x, y, text_line):
global player_position
if x not in range(0, N) or y not in range(0, N):
return text_line[:-1]
if str(matrix[x][y]).isalpha():
text_line += matrix[x][y]
matrix[player_position[0]][player_position[1]] = '-'
matrix[x][y] = 'P'
player_position = x, y
return text_line
player_position = find_player()
M = int(input())
for _ in range(M):
r, c = player_position[0], player_position[1]
command = input()
if command == 'left':
text = move(r, c - 1, text)
elif command == 'right':
text = move(r, c + 1, text)
elif command == 'up':
text = move(r - 1, c, text)
elif command == 'down':
text = move(r + 1, c, text)
print(text)
for row in matrix:
print(''.join(row))
| true |
7dae295d4916eb51fe783071b51312e88ce9348a | Python | JJnotJimmyJohn/CBA-stats-dev | /Archive/Sina_Scrape.py | UTF-8 | 1,043 | 2.625 | 3 | [] | no_license | import requests
# from bs4 import BeautifulSoup
import lxml.html as lh
import pandas as pd
import datetime
header = {'User-Agent': r'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) '
r'Chrome/41.0.2227.1 Safari/537.36'}
session = requests.Session()
base_url = r"http://cba.sports.sina.com.cn/cba/stats/playerstats/"
response = session.get(base_url, headers=header)
response.encoding = 'GBK'
doc = lh.fromstring(response.content)
rows = doc.xpath('//tr')
table_headers = [t.text_content() for t in rows[0]]
print(table_headers)
print(len(rows))
i = 0
table = []
#
for row in rows:
one_row = []
for cell in row:
txt = cell.text_content().strip()
one_row.append(txt)
table.append(one_row)
len(table)
player_stats_sina = pd.DataFrame(table[1:], columns=table[0])
player_stats_sina.rename(columns={"号码": '排名'}, inplace=True)
print(datetime.date.today())
player_stats_sina.to_csv(f'Player_Stats_{datetime.date.today()}.csv', index=False)
| true |
2e02a7fd34b5e086b063dee16f03762353d01f23 | Python | seidenfeder/neap | /parameterFitting/binImportance.py | UTF-8 | 2,999 | 3.0625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
##################################################################################################
#
# This script runs the specified prediction method (regression or classification) with every bin
# to evaluate which is the most important bin
#
############################################################################################
import os
import matplotlib.pyplot as plt
import numpy as np
from optparse import OptionParser
#this is necessary to get the parameters from the comand line
parser = OptionParser()
parser.add_option("-m", type="string", dest="method", help = "the method you want to use Support Vector Machine - Classification (SVC) or Regression (SVR) or Random Forest - Classification (RFC) or Regression (RFR) or Linear Regression (LR) default= RFC", default="RFC")
parser.add_option("-i",dest="input", help="This gives the path to the file with the input data (the output of the binning)")
parser.add_option("-l",dest="labels", help="This gives the path to the file with the labels")
(options, args) = parser.parse_args()
method=options.method
features=options.input
labels=options.labels
#run the method once for each bin
for i in range(0,160):
if(method == "RFC"):
os.system("python methods/classification.py -i "+features+" -l "+labels+" -n -c 5 -o ClassificationBins.txt -b"+ str(i))
score="AUC"
methodCoR="Classification" #tells if Regression or Classification
elif(method == "SVC"):
os.system("python methods/classification.py -i "+features+" -l "+labels+" -n -c 5 -o ClassificationBins.txt -m SVM -b"+ str(i))
score="AUC"
methodCoR="Classification"
elif(method == "RFR"):
os.system("python methods/regression.py -i "+features+" -m RF -n -c 5 -o RegressionBins.txt -b"+ str(i))
methodCoR="Regression"
score="r2"
elif(method == "SVR"):
os.system("python methods/regression.py -i "+features+" -m SVM -n -c 5 -o RegressionBins.txt -b"+ str(i))
score="r2"
methodCoR="Regression"
elif(method == "LR"):
os.system("python methods/regression.py -i "+features+" -n -c 5 -o RegressionBins.txt -b"+ str(i))
score="r2"
methodCoR="Regression"
#get the calculated score values from the file
aucs=[]
fileRF = open(methodCoR+"Bins.txt")
for line in fileRF.readlines():
lineSplit=line.split()
aucs.append(list(map(float,lineSplit[3:])))
#calculate the mean for each bin
aucMean = np.mean(aucs, axis=1)
aucMean = aucMean.flatten()
aucMean= aucMean.tolist()
#calculate the steps
numBins=int(len(aucMean)/2)
numBins2=int(len(aucMean)/4)
numBins4=int(len(aucMean)/8)
#make a plot with the mean values
plt.plot(aucMean)
plt.xlabel("Bin")
plt.ylabel("Mean of "+score+" Score")
plt.axvline(x=80,color='black')
plt.axvline(x=40,color='r')
plt.axvline(x=120,color='r')
plt.xticks(list(range(0,numBins*2+1,numBins4)),[-numBins2,-numBins4,'TSS',numBins4,'',-numBins4,'TTS',numBins4,numBins2])
plt.title(score+' Score of '+method+' for each Bin')
plt.savefig(method+'CompareBinsRFPlot.png')
#plt.show()
| true |
9a2c45997fd807a5b69aabf160cd1faa62246c2f | Python | mortie23/mssql-to-teradata | /function-lib/ddl-generate.py | UTF-8 | 6,996 | 2.625 | 3 | [] | no_license | #!/drives/c/Python38/python
# Author: Christopher Mortimer
# Date: 2020-08-26
# Desc: A script to generate the DDL for the staging tables and the views
# The output may need some manual modications but this is a starter
# Usage: Run from local session from the root repo directory
# ./function-lib/ddl-generate.py
import pandas as pd
import os
from time import gmtime, strftime
def datatype(dtype, dlength, dprecision, dscale):
'''
Data type MS-SQL to Teradata converstions
Parameters
@dtype: MS SQL type
@dlength: MS Sql length
@dprecision: MS SQL prescision
@dscale: MS SQL Scale
Return
datatype for Teradata
'''
if dtype in ['varchar', 'nvarchar']:
return 'varchar' + '(' + str(int(dlength)) + ')'
elif dtype == 'datetime':
return 'timestamp'
elif dtype == 'decimal':
return 'decimal(' + str(int(dprecision)) + ',' + str(int(dscale)) + ')'
elif dtype == 'numeric':
return 'numeric(' + str(int(dprecision)) + ',' + str(int(dscale)) + ')'
else:
return dtype
def datatypeStaging(dtype, dlength):
'''
Data type for Teradata staging table is all varchar of different lengths
Parameters
@dtype: MS SQL type
@dlength: MS SQL length
Return
datatype for Tetadata Staging
'''
if dtype in ['varchar', 'nvarchar']:
return 'varchar' + '(' + str(int(dlength)) + ')'
elif dtype == 'int':
return 'varchar(16)'
else:
return 'varchar(100)'
def colNameProc(dtype, colName):
'''
Hack function if extra processing is required in the view layer
Column names are shortened
Parameters
@dtype: MS SQL Data type
@colName: MS SQL column name
Return
Teradata column name
'''
if dtype == 'datetime':
return 'substr(' + colName + ',1,20)'
elif dtype == 'date':
return 'substr(' + colName + ',1,10)'
elif dtype in ['int', 'numeric']:
return 'nullif(' + colName + ",'')"
else:
return colName
def createViewDDL(ext):
'''
Create a staging to source image view
Parmeters
@ext: name of extract
'''
# Read the CSV that defines the table structure for the MS SQL table
filePathView = "./ddl/" + ext + '_V.sql'
if os.path.exists(filePathView):
os.remove(filePathView)
else:
print("Can not delete the file as it doesn't exists")
view = pd.read_csv('./extract/ddl_' + ext + '.csv')
viewFile = open(filePathView , "a+")
viewFile.write("-- Author: Automagic\n")
viewFile.write("-- Date: " + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + "\n")
viewFile.write("-- Desc: Table definition for " + ext + "\n\n")
viewFile.write('REPLACE VIEW PRD_ADS_NFL_DB.' + ext + '_V AS')
viewFile.write('\nSELECT')
# Loop through all the columns
for index, row in view.iterrows():
# On first row set this as the primary index
if row['ORDINAL_POSITION'] ==1:
viewLine = '\n TRYCAST(' + colNameProc(row['DATA_TYPE'],row['COLUMN_NAME']) + ' AS ' + datatype(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'],row['NUMERIC_PRECISION'],row['NUMERIC_SCALE']) + ') AS ' + row['COLUMN_NAME']
viewFile.write(viewLine)
else:
viewLine = '\n , TRYCAST(' + colNameProc(row['DATA_TYPE'],row['COLUMN_NAME']) + ' AS ' + datatype(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'],row['NUMERIC_PRECISION'],row['NUMERIC_SCALE']) + ') AS ' + row['COLUMN_NAME']
viewFile.write(viewLine)
# Finish off the file
viewFile.write('\n , CURRENT_USER AS EXTRACT_USER')
viewFile.write('\n , CURRENT_TIMESTAMP AS EXTRACT_TIMESTAMP')
viewLine = '\nFROM\n PRD_ADS_NFL_DB.' + ext + '\n;\n'
viewFile.write(viewLine)
def createStgDDL(ext):
'''
Create a staging table
Parmeters
@ext: name of extract
'''
# Read the CSV of the DDL
filePath = "./ddl/" + ext + '_STG.sql'
if os.path.exists(filePath):
os.remove(filePath)
else:
print("Can not delete the file as it doesn't exists")
ddl = pd.read_csv('./extract/ddl_' + ext + '.csv')
ddlFile = open(filePath , "a+")
ddlFile.write("-- Author: Automagic\n")
ddlFile.write("-- Date: " + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + "\n")
ddlFile.write("-- Desc: Table definition for " + ext + "\n\n")
ddlFile.write('DROP TABLE PRD_ADS_NFL_DB.' + ext + ';\n')
ddlFile.write('CREATE TABLE PRD_ADS_NFL_DB.' + ext + ' (')
# Loop through all the columns
for index, row in ddl.iterrows():
# On first row set this as the primary index
if row['ORDINAL_POSITION'] ==1:
primaryIndex = row['COLUMN_NAME']
ddlLine = '\n ' + row['COLUMN_NAME'] + ' ' + datatypeStaging(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'])
ddlFile.write(ddlLine)
else:
ddlLine = '\n , ' + row['COLUMN_NAME'] + ' ' + datatypeStaging(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'])
ddlFile.write(ddlLine)
# Finish off the file
ddlLine = '\n)\nPRIMARY INDEX (' + primaryIndex + ')\n;\n'
ddlFile.write(ddlLine)
createViewDDL(ext)
def createSrcDDL(ext):
'''
Create the source image table
Parmeters
@ext: name of extract
'''
# Read the CSV of the DDL
filePath = "./ddl/" + ext + '_SRC.sql'
if os.path.exists(filePath):
os.remove(filePath)
else:
print("Can not delete the file as it doesn't exists")
ddl = pd.read_csv('./extract/ddl_' + ext + '.csv')
ddlFile = open(filePath , "a+")
ddlFile.write("-- Author: Automagic\n")
ddlFile.write("-- Date: " + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + "\n")
ddlFile.write("-- Desc: Table definition for " + ext + "\n\n")
ddlFile.write('DROP TABLE EDW_PRD_ADS_HWD_AGPT_SRC_DB.' + ext + ';\n')
ddlFile.write('CREATE TABLE EDW_PRD_ADS_HWD_AGPT_SRC_DB.' + ext + ' (')
# Loop through all the columns
for index, row in ddl.iterrows():
# On first row set this as the primary index
if row['ORDINAL_POSITION'] ==1:
primaryIndex = row['COLUMN_NAME']
ddlLine = '\n ' + row['COLUMN_NAME'] + ' ' + datatype(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'],row['NUMERIC_PRECISION'],row['NUMERIC_SCALE'])
ddlFile.write(ddlLine)
else:
ddlLine = '\n , ' + row['COLUMN_NAME'] + ' ' + datatype(row['DATA_TYPE'],row['CHARACTER_MAXIMUM_LENGTH'],row['NUMERIC_PRECISION'],row['NUMERIC_SCALE'])
ddlFile.write(ddlLine)
# Finish off the file
ddlFile.write('\n , EXTRACT_USER VARCHAR(11)')
ddlFile.write('\n , EXTRACT_TIMESTAMP TIMESTAMP')
ddlLine = '\n)\nPRIMARY INDEX (' + primaryIndex + ')\n;\n'
ddlFile.write(ddlLine)
def createDDL(ext):
'''
Create all the Teradata structures required
Parameters
@ext: name of extract
'''
createStgDDL(ext)
createSrcDDL(ext)
createViewDDL(ext)
# Run for all extracts
createDDL('nfl_extracts')
createDDL('nfl_extracts')
createDDL('nfl_extracts')
createDDL('nfl_extracts')
createDDL('nfl_extracts') | true |
3fa78a930bdcea8f9d7cdfe14b507cad4eb6bf40 | Python | zwhitchcox/science-stuff | /combinatorics/0010_possibilities.py | UTF-8 | 250 | 3.75 | 4 | [] | no_license | import sys
# program to count password possibilities
n = int(input("Enter number of characters allowed in password (e.g. A-Z, a-z, 0-9 = 62): "))
k = int(input("Enter length of password: "))
print(f'The number of possible characters is {n**k:,}.') | true |
8422e64bfbf4e0608408c2d108bd4df449824fba | Python | it-zyk/PythonCode | /13_多任务/06_多线程共享全局变量_02.py | UTF-8 | 819 | 3.453125 | 3 | [] | no_license | import threading
import time
# 定义一个全局变量
g_num = 100
gl_list = ["11", "22"]
def test1(tempt):
global g_num
g_num += 1
tempt.append("34")
print("----- in test1 g_num=%s --------" % str(tempt))
def test2(tempt):
global g_num
g_num += 1
tempt.append("45")
print("----- in test2 g_num=%s --------" % str(tempt))
def main():
# target 指定将来在这个线程去哪里执行代码
# args 指定将来调用函数的时候,传递什么数据过去
t1 = threading.Thread(target = test1, args=(gl_list,))
t2 = threading.Thread(target = test2, args=(gl_list,))
t1.start()
time.sleep(1)
t2.start()
time.sleep(1)
print("----- in main g_num=%s --------" % str(gl_list))
if __name__ == "__main__":
main()
| true |
84602dc2a3ba898c1a29e74190a3f2b1cc1001b4 | Python | NikhilaBanukumar/GeeksForGeeks-and-Leetcode | /remove_duplicates_ll.py | UTF-8 | 1,561 | 3.359375 | 3 | [] | no_license | def median_3(a,b,c):
return a+b+c-(max(a,b,c)+min(a,b,c))
def median_4(a,b,c,d):
return (a+b+c+d-(max(a,b,c,d)+min(a,b,c,d)))/2
def median_two_sorted_arrays(a,b):
na=len(a)
nb=len(b)
mida=int((na-1)/2)
midb=int((nb-1)/2)
if na == 0 or nb == 0:
if nb == 0:
if na % 2 != 0:
return a[mida]
else:
return (a[mida] + a[mida - 1]) / 2
else:
if nb % 2 != 0:
return b[midb]
else:
return (b[midb] + b[midb - 1]) / 2
if na % 2 != 0:
amed = a[mida]
else:
amed = (a[mida] + a[mida - 1]) / 2
if nb % 2 != 0:
bmed = b[midb]
else:
bmed = (b[midb] + b[midb - 1]) / 2
if na==nb and na==2:
if amed>bmed:
return (a[0]+b[1])/2
else:
return (a[1]+b[0]) / 2
if na==1:
if nb==1:
return (a[0]+b[0])/2
if nb%2==0:
return median_3(a[0],b[midb],b[midb-1])
else:
return median_4(a[0],b[midb],b[midb-1],b[midb+1])
if nb==1:
if na==1:
return (a[0]+b[0])/2
if nb%2==0:
return median_3(b[0],a[mida],a[mida-1])
else:
return median_4(b[0],a[mida],a[mida-1],a[mida+1])
if amed==bmed:
return amed
elif amed>bmed:
return median_two_sorted_arrays(a[:mida+1],b[midb:])
elif bmed>amed:
return median_two_sorted_arrays(a[mida:],b[:midb+1])
print(median_two_sorted_arrays([1,2],[1,2,3])) | true |
1ed584528c5cd41c914d852327b9c12d4c791f14 | Python | LuizFelipeBG/CV-Python | /Mundo 2/ex54.py | UTF-8 | 272 | 3.59375 | 4 | [] | no_license | c1 = 0
c2 = 0
for c in range(1,8):
nas = int(input('Digite a data de nascimento: '))
if 2018 - nas > 18:
c1 += 1
else:
c2 += 1
print('existem {} pessoas que já são maiores de idade e {} que ainda não atingiram a maioridade!!'.format(c1,c2))
| true |
5d59327a9ed7dc2603aab97245ece07e67e68184 | Python | KidQuant/Finance | /algo_trading/quandl_data.py | UTF-8 | 2,453 | 3.375 | 3 | [] | no_license |
#quandl_data.py
from __future__ import print_function
import matplotlib.pyplot as plt
import pandas as pd
import requests
def construct_futures_symbols(symbol, start_year=2010, end_year=2014):
"""
Constructs a list of futures contract codes
for a particular symbol and timeframe.
"""
futures = []
## March, June, September and
#December delievery codes
months = 'HMUZ'
for y in range(start_year, end_year+1):
for m in months:
futures.append('%s%s%s' % (symbol, m, y))
return futures
def download_contract_from_quandl(contract, dl_dir):
"""
Download an individual futures contract from Quandl and then
store it to disk in the 'dl_dir' directory. An auth_token is
required, which is obtained from the Quandl upon sign-upself.
"""
#Construct the API call from the contract and auth_token
api_call = 'http://www.quandl.com/api/v1/datasets/'
api_call += 'OFDP/FUTURE_%s.csv' % contract
#If you wish to add an auth token for more downloads, simply
#comment the following line and replace MY_AUTH_TOKEN with
#your auth token in the line below
params = '?sort_order = asc'
#params = '?auth_token= = MY_AUTH_TOKEN&sort_order=asc'
full_url = "%s%s" % (api_call, params)
#Download the data from Quandl
data = requests.get(full_url).text
#Store the data to disk
fc = open('%s/%s.csv' % (dl_dir, contract), 'w')
fc.write(data)
fc.close()
def download_historical_contracts(symbols, dl_dir, start_year = 2010, end_year = 2014):
"""
Downloads all futures contracts for a specified symbol
between a start_year and an end_year.
"""
contracts = construct_futures_symbols(
symbols, start_year, end_year
)
for c in contracts:
print('Downloading contracts: %s' % c)
download_contract_from_quandl(c, dl_dir)
if __name__ == '__main__':
symbol = 'ES'
#Make sure you've created this
#relative directory beforehand
dl_dir = 'quandl/futures/ES'
#create the start and end years
start_year = 2013
end_year = 2017
#Download the contracts into the directory
download_historical_contracts(
symbol, dl_dir, start_year, end_year
)
#Open up a single contract via read_csv
# and plot the settle price
es = pd.io.parsers.read_csv(
"%s/ESH2014" % dl_dir, index_col ='Date'
)
es['Settle'].plot()
plt.show()
| true |
b0d39a2978216e6637db6ab842f9850fe34d1e89 | Python | JancisWang/leetcode_python | /593. 有效的正方形.py | UTF-8 | 1,031 | 3.375 | 3 | [] | no_license | '''
给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。
一个点的坐标(x,y)由一个有两个整数的整数数组表示。
示例:
输入: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
输出: True
注意:
所有输入整数都在 [-10000,10000] 范围内。
一个有效的正方形有四个等长的正长和四个等角(90度角)。
输入点没有顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
ls = [p1, p2, p3, p4]
ls.sort(key=lambda x:(x[0], x[1]))
def dist(x, y):
return (x[0]-y[0])**2 + (x[1]-y[1])**2
return dist(ls[0], ls[1]) == dist(ls[0], ls[2]) == dist(ls[1], ls[3]) == dist(ls[2], ls[3])!= 0 and dist(ls[0], ls[3])==dist(ls[1], ls[2]) | true |
90b1894601533f819103d38962509892ac0106bd | Python | Schiggebam/FightOfAIs3 | /src/ai/ai_blueprint.py | UTF-8 | 7,429 | 3.046875 | 3 | [] | no_license | from __future__ import annotations
from src.ai.AI_GameStatus import AI_GameStatus, AI_Move
from src.misc.game_constants import DiploEventType, debug, hint, Definitions
from src.misc.game_logic_misc import Logger
class AI_Diplo:
"""
Example class for inter-player diplomatics. Events are defined in the constants.
In principle, events have a lifetime, they will last at least this time.
If the cause of the event persists, the event will also remain active (its lifetime is set to its
original lifetime. Diplomacy is one-dimensional for now. Thus, an event has a value (rel_change)
to change the current diplomatic value.
For future iteration, a multidimensional setup can be imagined for more complex relations
An event is defined by its location. If the cause of the event moves, it will be triggered again.
Example a hostile army invades the claimed territory, one can throw an event with lifetime one to track
the army and to make sure, that no events are accumulated for the same cause.
IMPORTANT (!): If diplomacy is used, one has to call AI_Diplo.calc_round() per turn (do_move) to update the
events
"""
DIPLO_BASE_VALUE = float(5)
LOGGED_EVENTS = (DiploEventType.ENEMY_BUILDING_IN_CLAIMED_ZONE,
DiploEventType.ENEMY_ARMY_INVADING_CLAIMED_ZONE)
event_count = 0
class AI_DiploEvent:
""" Intern class to handle Events. They are broadcasted to the Logger"""
def __init__(self, event_id: int, target_id: int, rel_change: float, lifetime: int,
event: DiploEventType, description: str):
self.rel_change = rel_change
self.lifetime = lifetime
self.lifetime_max = lifetime
self.description = description
self.loc = (-1, -1)
self.event: DiploEventType = event
self.target_id: int = target_id
self.event_id = event_id
def add_loc(self, loc: (int, int)):
self.loc = loc
def __init__(self, other_players: [int], player_name: str):
self.diplomacy: [[int, float]] = []
self.events: [AI_Diplo.AI_DiploEvent] = []
self.name = player_name
for o_p in other_players:
self.diplomacy.append([o_p, float(AI_Diplo.DIPLO_BASE_VALUE)])
def add_event_no_loc(self, target_id: int, event: DiploEventType, rel_change: float, lifetime: int,):
self.add_event(target_id, (-1, -1), event, rel_change, lifetime)
def add_event(self, target_id: int, loc: (int, int), event: DiploEventType, rel_change: float, lifetime: int):
"""
add an event. For more details read class description.
will not add an event, if there is already an event with equal target_id, event_type and location
:param target_id: id of the owner of the cause of the event. For instance, the owner id of the hostile army
:param loc: location of the event. This will be used to identify if a event for this cause exists already
:param event: The type of the event, defined in constants
:param rel_change: relative change in one-dimensional diplomacy
:param lifetime: the lifetime of the event, for how long the effect persists
:return:
"""
# check if this exists already:
for e in self.events:
if e.target_id == target_id and e.event == event and e.loc == loc:
e.lifetime = e.lifetime_max
return
# otherwise, if event does not exist, yet
event_str = DiploEventType.get_event_description(event, loc)
ai_event = AI_Diplo.AI_DiploEvent(AI_Diplo.__next_id(), target_id, rel_change, lifetime, event, event_str)
ai_event.add_loc(loc)
self.events.append(ai_event)
if event in AI_Diplo.LOGGED_EVENTS:
Logger.log_diplomatic_event(event, rel_change, loc, lifetime, self.name)
print(self.events)
def calc_round(self):
"""
If diplomacy is used, this method has to be called every round, to adjust the lifetime of all events
:return:
"""
for diplo in self.diplomacy:
diplo[1] = AI_Diplo.DIPLO_BASE_VALUE
for e in self.events:
if e.target_id == diplo[0]:
diplo[1] = diplo[1] + e.rel_change
e.lifetime = e.lifetime - 1
to_be_removed = []
for e in self.events:
if e.lifetime <= 0:
to_be_removed.append(e)
for tbr in to_be_removed:
self.events.remove(tbr)
def get_diplomatic_value_of_player(self, player_id: int) -> float:
"""
returns a one-dimensional scalar, which represents the current relation to this player
:param player_id: opponent player id
:return:
"""
for d in self.diplomacy:
if d[0] == player_id:
return d[1]
def get_player_with_lowest_dv(self) -> int:
"""
:return: the player with the lowest diplomatic value. Useful for aggressive moves against least valued player
"""
lowest_value = float(100)
lowest_pid = -1
for pid, value in self.diplomacy:
if lowest_value > value:
lowest_value = value
lowest_pid = pid
return lowest_pid
@staticmethod
def __next_id() -> int:
AI_Diplo.event_count += 1
return AI_Diplo.event_count
class AI:
"""Superclass to a AI. Any AI must implement at least do_move and fill the move object"""
def __init__(self, name, other_players_ids: [int]):
"""the name of the ai"""
self.name = name
"""each ai can do (not required) diplomacy"""
self.diplomacy: AI_Diplo = AI_Diplo(other_players_ids, self.name)
"""this is used for development.
instead of printing all AI info to the console, one can use the dump to display stats in-game"""
self.__dump: str = ""
debug("AI (" + str(name) + ") is running")
def do_move(self, ai_state: AI_GameStatus, move: AI_Move):
"""upon completion of this method, the AI should have decided on its move"""
raise NotImplementedError("Please Implement this method")
def get_state_as_str(self) -> str:
"""used by the UI to display some basic information which is displayed in-game. For complex output, use _dump"""
pass
def _dump(self, d: str):
"""Depending on the game settings, this will either dump the output to:
- [if SHOW_AI_CTRL]the external AI ctrl window
- [if DEBUG_MODE]the console (should not be the first choice, very slow)
- [else]nowhere."""
if Definitions.SHOW_AI_CTRL:
self.__dump += d + "\n"
elif Definitions.DEBUG_MODE:
hint(d)
else:
pass
def dump_diplomacy(self):
"""method dumps active events in diplomacy. (with its lifetime and rel. change)"""
self._dump("Events: -------------------")
for event in self.diplomacy.events:
self._dump(f" {event.description} [lifetime: {event.lifetime}, rel. change: {event.rel_change}]")
def _reset_dump(self):
"""most likely, the AI should call this upon being called each turn. It will reset the string buffer"""
self.__dump = ""
def get_dump(self):
return self.__dump
| true |
b55327695f48c613466ad67ca2ceb540364d7e5f | Python | stefanpejcic/python | /if/lcalculator.py | UTF-8 | 1,309 | 4.25 | 4 | [] | no_license | """
Modification from this exercise: https://github.com/stefanpejcic/python/blob/master/if/calculator.py
to let user first specify a language and then run the calculator in their language.
"""
phrase1 = "Enter first operand? "
phrase2 = "Enter second operand? "
phrase3 = "Choose operation (add,sub,mul,div): "
phrase4 = "Result is: "
phrase5 = "Unknown operation"
lang = input('Choose language (sr,en,de): ')
if(lang=="sr"):
phrase1 = "Unesite prvi broj? "
phrase2 = "Unesite drugi broj? "
phrase3 = "Odaberite operaciju (add,sub,mul,div): "
phrase4 = "Rezultat je: "
phrase5 = "Nepoznata operacija"
elif(lang=="en"):
phrase1 = "Enter first operand? "
phrase2 = "Enter second operand? "
phrase3 = "Choose operation (add,sub,mul,div): "
phrase4 = "Result is: "
elif(lang=="de"):
phrase1 = "Geben Sie die erste Nummer ein? "
phrase2 = "Geben Sie die zweite Nummer ein? "
phrase3 = "Operation wählen (add,sub,mul,div): "
phrase4 = "Das Ergebnis ist: "
phrase5 = "Unbekannte Operation"
a = int(input(phrase1))
b = int(input(phrase2))
op = input(phrase3)
if(op=='add'):
print(phrase4, a + b)
elif(op=='sub'):
print(phrase4, a - b)
elif(op=='mul'):
print(phrase4, a * b)
elif(op=='div'):
print(phrase4, a / b)
else:
print(phrase5)
| true |
25941577cbc92e3f8eb7c8f304e1f0feb62543f5 | Python | QAMilestoneAcademy/PythonForBeginners | /ProgramFlow/if_learn.py | UTF-8 | 1,160 | 4.53125 | 5 | [] | no_license | #Statement following if condition are indented within if
#indented statements excute if condition within if bracket meets
name="Anuradha"
# if(name == "Anuradha"):
if(10>5):
print("10 is greater then 5")
#will execute in any condition
print("program ended")
#Let's guess the output:
spam = 7
if spam > 5:
print("five")
if spam > 8:
print("eight")
# An else statement follows an if statement, and contains code that is called when the if statement evaluates to False.
# As with if statements, the code inside the block should be indented.
x = 10
y = 20
if x > y:
print("if statement")
else:
print("else statement")
# The elif (short for else if) statement is a shortcut to use when chaining if and else statements.
# A series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True.
if not True:
print("1")
elif not (1 + 1 == 3):
print("2")
else:
print("3")
#boolean comparison if or else
age = 15
money = 500
if (age > 18 or money > 100):
print("Welcome")
#Find out the result:
x = 4
y = 2
if not 1 + 1 == y or x == 4 and 7 == 8:
print("Yes")
elif x > y:
print("No")
| true |
8543b3e334a2c43ef04f49d0b35a215a2a6eedbe | Python | Axl-M/telegram_bot | /convbot.py | UTF-8 | 4,046 | 2.765625 | 3 | [] | no_license | import logging
from typing import Dict
from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
TOKEN = "1485482332:AAHmcJJf1uFjfhEDxDQAK3m6eb4lOTb2LhE"
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
reply_keyboard = [
['Возраст', 'Любимый цвет'],
['Число братьев/сестер', 'Что-то еще...'],
['Закончить'],
]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
def facts_to_str(user_data: Dict[str, str]) -> str:
facts = list()
for key, value in user_data.items():
facts.append('{} - {}'.format(key, value))
return "\n".join(facts).join(['\n', '\n'])
def start(update: Update, context: CallbackContext):
update.message.reply_text(
"Привет, меня зовут Bot, я хочу поговорить с тобой. О чем о себе бы ты хотел бы рассказать?",
reply_markup=markup,
)
return CHOOSING
def regular_choice(update: Update, context: CallbackContext):
text = update.message.text
context.user_data['choice'] = text
update.message.reply_text(
# f'Про {text.lower()}? Да, я хотел бы об этом узнать!'
f'Да, я хотел бы об этом узнать!'
)
return TYPING_REPLY
def custom_choice(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
'Хорошо, но пришли мне сначала категорию ' 'например "Что я умею лучше всего"'
)
return TYPING_CHOICE
def received_information(update: Update, context: CallbackContext) -> int:
user_data = context.user_data
text = update.message.text
category = user_data['choice']
user_data[category] = text
del user_data['choice']
update.message.reply_text(
f"Аккуратно! Просто чтобы вы знали, вот что вы мне уже сказали:"
f"{facts_to_str(user_data)} Вы можете рассказать мне больше или изменить свое мнение"
" о чем-нибудь.",
reply_markup=markup,
)
return CHOOSING
def done(update: Update, context: CallbackContext) -> int:
user_data = context.user_data
if 'choice' in user_data:
del user_data['choice']
update.message.reply_text(
f"Я узнал о тебе следующее:" f"{facts_to_str(user_data)}" "До встречи!"
)
user_data.clear()
return ConversationHandler.END
def main() -> None:
updater = Updater(TOKEN, use_context=True)
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSING: [
MessageHandler(
Filters.regex('^(Возраст|Любимый цвет|Число братьев/сестер)$'), regular_choice
),
MessageHandler(Filters.regex('^Что-то еще...$'), custom_choice),
],
TYPING_CHOICE: [
MessageHandler(
Filters.text & ~(Filters.command | Filters.regex('^Закончить')), regular_choice
)
],
TYPING_REPLY: [
MessageHandler(
Filters.text & ~(Filters.command | Filters.regex('^Закончить$')),
received_information,
)
],
},
fallbacks=[MessageHandler(Filters.regex('^Закончить$'), done)],
)
dispatcher.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main() | true |
e16f3bf50854c33ce941584799156f328099ba10 | Python | tomstelk/BuyToLet-Tool | /mother.py | UTF-8 | 2,633 | 2.59375 | 3 | [] | no_license | __author__ = 'tomstelk'
import urlSearchResults
import htmlSearchResults
import unicodedata
import sqlite3
#Zoopla html navigation data
import zooplaHTMLSetup
#AirBnB html navigation data
import airBnBHTMLSetup
import insertTable
import time
#Text file containing postal districts
txtfilePostalDistricts="londonPostDistricts.txt"
#Search parameters
numBeds=1
numGuests=2
text_file = open(txtfilePostalDistricts, "r")
postDistricts = text_file.read().split('\n')
text_file.close()
todaysDate=time.strftime("%d/%m/%Y")
#SQLite Database
db_name='buy2letDB.sqlite'
#Assign URL, HTML xpaths, results table
#urlTemplate=zooplaHTMLSetup.zooplaURL
#xPaths=zooplaHTMLSetup.zooplaPaths
#xpathNextSearchResults=zooplaHTMLSetup.zoopsNextPath
#resultsTable=zooplaHTMLSetup.zooplaTable
#searchParams={'Geog':'postDistrict', 'NumBeds':numBeds}
urlTemplate=airBnBHTMLSetup.airBnBURL
xPaths=airBnBHTMLSetup.airBnBPaths
xpathNextSearchResults=airBnBHTMLSetup.airBnBNextPath
resultsTable=airBnBHTMLSetup.airBnBTable
searchParams=airBnBHTMLSetup.airBnBSearchParams
searchParams['numGuests']=numGuests
"""
for i in range(0,1):
searchParams['Geog']=postDistricts[i]
print searchParams['Geog']
searchURL=urlSearchResults.urlSearchResults(urlTemplate,searchParams)
print searchURL.url
tree=htmlSearchResults.htmlSearchResults(searchURL.url,xPaths,xpathNextSearchResults)
"""
#For each postal district get info and pop into database
#for i in range(0,len(postDistricts)):
for i in range(0,1):
print postDistricts[i]
#Do the searching on the internet
searchParams['Geog']=postDistricts[i]
searchURL=urlSearchResults.urlSearchResults(urlTemplate,searchParams)
print searchURL.url
#Scrape html using xpaths
tree=htmlSearchResults.htmlSearchResults(searchURL.url,xPaths,xpathNextSearchResults)
#Clean price string
tree.resultList['Price']= [unicodedata.normalize('NFKD',x.strip().replace(",","").replace(u"\u00A3","")).encode('ascii','ignore') for x in tree.resultList['Price']]
eg=list()
print (tree.resultList['ID'][0])
#Loop through search results pages and append hits
for j in range(1,len(tree.resultList['ID'])):
#eg.append([tree.resultList['ID'][i],tree.resultList['Price'][i],tree.resultList['Address'][i],searchParams['Geog'],searchParams['NumBeds']])
eg.append([tree.resultList['ID'][j],tree.resultList['Price'][j],tree.resultList['Address'][j],searchParams['Geog'],searchParams['numGuests']],todaysDate)
#insertTable.insertTable(db_name,resultsTable,eg) | true |
4dc965c309061e198cc0ce6cb6b7bb6af20eaf0d | Python | ignition-is-go/lucid-control | /django/lucid_api/services/groups_service_OLD.py | UTF-8 | 8,226 | 2.625 | 3 | [] | no_license | '''
Google Groups Service
for Lucid Control
JT
06/26/2017
'''
import service_template
import httplib2, json
import os
import re
from apiclient import discovery, errors
from oauth2client.service_account import ServiceAccountCredentials
class GroupsService(service_template.ServiceTemplate):
def __init__(self):
'''
Creates necessary services with Google Admin and Groups; also setups the logger.
'''
self._logger = self._setup_logger(to_file=True)
self._admin = self._create_admin_service()
self._group = self._create_groupsettings_service()
def create(self, project_id, title, silent=False):
'''
Creates Google Groups Group and adds necessary users to it.
'''
self._logger.info('Start Create Google Group for Project ID %s: %s', project_id, title)
group = self._admin.groups()
grp_settings = self._group.groups()
slug = self._format_slug(project_id, title)
reg = r'^([\w]+-[\w]+)'
grp_info = {
"email" : "{}@lucidsf.com".format(re.match(reg, slug).group()), # email address of the group
"name" : slug, # group name
"description" : "Group Email for {}".format(slug), # group description
}
# Setup our default settings.
dir_info = {
"showInGroupDirectory" : "true", # let's make sure this group is in the directory
"whoCanPostMessage" : "ALL_MEMBERS_CAN_POST", # this should be the default but...
"whoCanViewMembership" : "ALL_IN_DOMAIN_CAN_VIEW", # everyone should be able to view the group
"includeInGlobalAddressList" : "true", # In case anyone decides to become an Outlook user
"isArchived" : "true", # We want to keep all the great messages
}
try:
create_response = group.insert(body=grp_info).execute()
create_settings = grp_settings.patch(groupUniqueId=grp_info['email'], body=dir_info).execute()
self._logger.info('Created Google Group %s (ID: %s) with email address %s', grp_info['name'], project_id, grp_info['email'])
self._logger.debug('Create response = %s', create_response)
except errors.HttpError as err:
self._logger.error(err.message)
if err.resp.status == 409:
raise GroupsServiceError('Group already exists!')
else:
raise GroupsServiceError(err)
# With the group created, let's add some members.
emp_group = self.list_employees()
try:
for i in emp_group:
add_users = self._admin.members().insert(groupKey=grp_info['email'], body=({'email' : i})).execute()
self._logger.debug('Added %s to %s', i, grp_info['name'])
except errors.HttpError as err:
self._logger.error('Failed try while adding members: {}'.format(err))
raise GroupsServiceError('Problem adding members to group!')
return create_response['id']
def rename(self, project_id, new_title):
'''
Renames an existing google group.
'''
self._logger.info('Start Rename Google Group for Project ID %s to %s', project_id, new_title)
# 1. Check to see if the group even exists
try:
group_id = self.get_group_id(project_id)
except GroupsServiceError as err:
self._logger.debug('Group with project ID %s does not exist.', project_id)
raise GroupsServiceError("Could not find a project with ID # %s", project_id)
group = self._admin.groups()
slug = self._format_slug(project_id, new_title)
# 2. Create the JSON request for the changes we want
grp_info = {
# We leave out 'email' because we want the address to remain the same.
"name" : slug, # new group name
"description" : "Group Email for {}".format(slug), # new group description
}
# 3. Perform actual rename here.
try:
create_response = self._admin.groups().patch(groupKey=group_id, body=grp_info).execute()
self._logger.debug("Renamed Group ID %s to %s", project_id, slug)
except GroupsServiceError as err:
self._logger.error('Unable to rename group %s to %s', project_id, new_title)
raise GroupsServiceError('Unable to rename group %s to %s', project_id, new_title)
return ['id']
def archive(self, project_id):
'''
Archives an existing google group.
Read: Change archiveOnly to true.
'''
self._logger.info("Started Archive Google Group for Project ID %s", project_id)
# 1. Check to see if the group even exists
try:
group_id = self.get_group_id(project_id)
except GroupsServiceError as err:
self._logger.error("Group with project ID %s does not exist.", project_id)
raise GroupsServiceError("Can't archive, no project ID # %s", project_id)
grp_settings = self._group.groups()
em = "p-{}@lucidsf.com".format(project_id)
dir_info = {
"archiveOnly" : "true", # archive that bad boy
"whoCanPostMessage" : "NONE_CAN_POST", # this is a requirement for archiveOnly
"includeInGlobalAddressList" : "true", # don't need this anymore
}
# 2. Remove the group from the directory
try:
create_settings = grp_settings.patch(groupUniqueId=em, body=dir_info).execute()
self._logger.info("Archived group ID # %s.", project_id)
return ['id']
except GroupsServiceError as err:
self._logger.error("Unable to archive Google Group with ID # %s.", project_id)
GroupsServiceError("Ack! Can't archive ID # %s because: %s", project_id, err.message)
return ['id']
def get_group_id(self, project_id):
'''
Get the google group id (internal identifier)
'''
group = self._admin.groups()
response = group.list(customer='my_customer').execute()
project_id = str(project_id)
for i in response['groups']:
if project_id in i['name']:
return i['id']
raise GroupsServiceError("Could not find group #{}".format(project_id))
def list_groups(self):
'''
Print a list of groups to stdout
'''
group = self._admin.groups()
response = group.list(customer='my_customer').execute()
# For debugging purposes only
# print([r['name'] for r in response['groups']])
return response
def list_employees(self):
'''
Get a list of employees (members of the employees@lucidsf.com group)
'''
employee = self._admin.members()
l = employee.list(groupKey='employees@lucidsf.com').execute()
response = [r['email'] for r in l['members']]
return response
def _create_admin_service(self):
scopes = ['https://www.googleapis.com/auth/admin.directory.group']
with open("auths/lucid-control-b5aa575292fb.json",'r') as fp:
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json.load(fp),
scopes= scopes)
credentials = credentials.create_delegated('developer@lucidsf.com')
http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', credentials=credentials)
return service
def _create_groupsettings_service(self):
scopes = ['https://www.googleapis.com/auth/apps.groups.settings']
with open("auths/lucid-control-b5aa575292fb.json", 'r') as fp:
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json.load(fp),
scopes= scopes)
credentials = credentials.create_delegated('developer@lucidsf.com')
http = credentials.authorize(httplib2.Http())
service = discovery.build('groupssettings', 'v1', credentials=credentials)
return service
class GroupsServiceError(service_template.ServiceException):
pass | true |
9daef5250758a0f0950eae891bc7d34b6a3c187e | Python | skarensmoll/algorithms-tlbx | /week2_algorithmic_warmup/4_least_common_multiple/lcm.py | UTF-8 | 510 | 3.578125 | 4 | [] | no_license | # Uses python3
import sys
def gcd(a, b):
reminder = a % b
if reminder == 0 :
return b
return gcd(b, reminder)
def lcm_naive(a, b):
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def lcm(a, b):
return int(a * b / gcd(a, b))
if __name__ == '__main__':
input = input()
a, b = map(int, input.split())
first = min(a, b)
second = max(a, b)
print(lcm(first, second))
print(lcm_naive(first, second))
| true |
4bb5807d735b7bb21bd56e083dd13489ce8315ca | Python | JunguangJiang/FTP | /client/src/cmd.py | UTF-8 | 3,598 | 2.921875 | 3 | [
"MIT"
] | permissive | '''
FTP客户端的命令行程序
'''
from client import Client
import getpass
import sys
DEBUG_MODE=False
class ClientCmd:
'''ftp客户端命令行程序'''
def __init__(self, ip='127.0.0.1', port=21):
self.client = Client()
self.command_map = {
"get": self.client.get,
"reget": self.client.reget,
"put": self.client.put,
"reput": self.client.reput,
"append": self.client.append,
"ls": self.client.ls,
"cd": self.client.cd,
"mkdir": self.client.mkdir,
"pwd": self.client.pwd,
"rmdir": self.client.rmdir,
"system": self.client.system,
"rename": self.client.rename,
"sendport": self.client.sendport,
"passive": self.client.passive,
"bye": self.client.bye,
"quit":self.client.bye,
"size":self.client.size,
"delete":self.client.delete,
"open": self.__open,
"close": self.client.close,
"zip": self.client.zip,
"unzip": self.client.unzip,
"put_folder":self.client.put_folder,
"get_folder":self.client.get_folder
}
self.ip = ip
self.port = port
def __login(self):
'''
登录的交互过程
:return:返回登录是否成功
'''
username = input('Username:')
response = self.client.user(username)
if response.startswith("331"):
password = getpass.getpass('Password:')
response = self.client.password(password)
return response.startswith("230")
return False
def __open(self, ip='127.0.0.1', port=21):
'''为了在打开连接后,提示用户输入用户名、密码等信息,需要对client提供的open进一步封装'''
self.client.open(ip, port)
self.__login()
def __parse_input(self, input):
'''
对输入命令进行解析
:param input: 输入数据
:return: 如果输入合法,则返回需要调用的方法和传递给方法的参数;否则返回均为空
'''
args = input.split()
if(len(args) == 0):
return (None, None)
cmd = self.command_map.get(args[0])
if cmd: #存在该命令
return (cmd, args[1:])
else: #不存在该命令
return (None, None)
def __run_func(self, func, args):
'''
运行某个函数
:param func: 函数
:param args: 函数参数
:return:
'''
if func:
try:
func(*args)
except:
print("?Invalid argument")
else:
print("?Invalid command")
def run(self):
'''运行程序'''
welcome = self.client.open(self.ip, self.port)
if not welcome:
return
if DEBUG_MODE:
self.client.user("anonymous")
self.client.password("33")
else:
self.__login() # 登录界面
while True:
data = input('ftp>')
cmd_func, args = self.__parse_input(data)
self.__run_func(cmd_func, args)
if data.startswith("bye") or data.startswith("quit"):
break
if __name__ == '__main__':
import sys
argv = sys.argv
ip = '127.0.0.1'
port = 21
if(len(argv) >= 3):
port = int(argv[2])
if(len(argv) >= 2):
ip = argv[1]
clientCmd = ClientCmd(ip, port)
clientCmd.run()
| true |
14c7495e4230221e7d8ff42f5a07062f7d87ec03 | Python | YonseiMVP/DeepForAll | /lab06/lab-06-1-softmax_classifier.py | UTF-8 | 2,725 | 3.28125 | 3 | [] | no_license | # Lab 6 Softmax Classifier
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
use_gpu = False
# 4개의 feature , 8개의 instance, 차원은 instance x feature = 8 X 4
x_data = [[1, 2, 1, 1],
[2, 1, 3, 2],
[3, 1, 3, 4],
[4, 1, 5, 5],
[1, 7, 5, 5],
[1, 2, 5, 6],
[1, 6, 6, 6],
[1, 7, 7, 7]]
# x_data와 동일한 방식
y_data = [[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[1, 0, 0],
[1, 0, 0]]
# 입출력데이터를 넣기 위한 공간
X = tf.placeholder("float", [None, 4])
Y = tf.placeholder("float", [None, 3])
nb_classes = 3
# 변수선언(초기화 방법(차원),종류)노드 => trainable가능한
W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')
b = tf.Variable(tf.random_normal([nb_classes]), name='bias')
# hypothesis식을 정의 노드 (softmax 함수를 사용)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
# cross entropy error 노드
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
# gradientdescent방법으로 초기화(학습속도 설정)하는 노드+gradientdescent방법으로 cost를 최소화하는 노드
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
# GPU 사용 여부
if use_gpu == False:
config = tf.ConfigProto(
device_count={'GPU': 0} # GPU : 0이면 사용할 GPU 0개 -> CPU 사용
)
elif use_gpu == True:
config = tf.ConfigProto(
device_count={'GPU': 1} # GPU : 1이면 사용할 GPU 1개 -> GPU 사용
)
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
for step in range(2001):
sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
if step % 200 == 0: # 200회마다 cost 값 출력
print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))
print('--------------')
# Testing & One-hot encoding
a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9]]})
print(a, sess.run(tf.arg_max(a, 1)))
# 학습된 모델에 Test 데이터를 넣고 arg_max로 가장 큰 값의 index를 얻는다.
print('--------------')
b = sess.run(hypothesis, feed_dict={X: [[1, 3, 4, 3]]})
print(b, sess.run(tf.arg_max(b, 1)))
print('--------------')
c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0, 1]]})
print(c, sess.run(tf.arg_max(c, 1)))
print('--------------')
#한번에 데이터를 입력하여 모두 볼 수 있다.
all = sess.run(hypothesis, feed_dict={
X: [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]})
print(all, sess.run(tf.arg_max(all, 1)))
| true |
3c5bb7e25a3db93838ef367943904191c77afbb5 | Python | Didero/Ophidian | /ScrollableFrame.py | UTF-8 | 1,161 | 3.125 | 3 | [
"LicenseRef-scancode-secret-labs-2011",
"MIT"
] | permissive | import Tkinter
class ScrollableFrame(Tkinter.Frame):
def __init__(self, parentFrame, width, height):
Tkinter.Frame.__init__(self, parentFrame)
self.canvasWidth = width
self.canvasHeight = height
# For some reason you can't scroll Frames though, so we have to put everything in a Frame in a Canvas
self.canvas = Tkinter.Canvas(self, width=self.canvasWidth, height=self.canvasHeight, highlightthickness=0)
self.canvas.grid(column=0, row=0)
self.scrollbar = Tkinter.Scrollbar(self, command=self.canvas.yview)
self.scrollbar.grid(column=1, row=0, sticky=Tkinter.NS)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.innerFrame = Tkinter.Frame(self.canvas, width=self.canvasWidth, height=self.canvasHeight)
self.innerFrame.grid(column=0, row=0)
self.canvas.create_window((0, 0), window=self.innerFrame, anchor=Tkinter.NW)
self.innerFrame.bind('<Configure>', self.onSearchParametersFrameConfigure)
def onSearchParametersFrameConfigure(self, event):
"""Keep the canvas properly scrolled when configuring"""
self.canvas.configure(scrollregion=self.canvas.bbox('all'), width=self.canvasWidth, height=self.canvasHeight)
| true |
53cc50280141c81127cb798c9154a4b5124ea167 | Python | luabras/open-cv-basics | /opencv_resize.py | UTF-8 | 800 | 3.03125 | 3 | [] | no_license | import imutils
import cv2
path = "C:/pyimage/OpenCV 101 - OpenCV Basics/imagens/teste.jpg"
img = cv2.imread(path)
cv2.imshow("Original", img)
cv2.waitKey(0)
(h, w) = img.shape[:2]
# vamos mudar a largura para 150, entao vamos calcular o aspect ratio da nova largura
# para que a imagem n fique desproporcional
ratio = 150.0 / w
dim = (150, int(h * ratio))
resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
cv2.imshow("Resized (width)", resized)
cv2.waitKey(0)
# resize usando a algura 50
ratio2 = 50.0 / h
dim2 = (int(w * ratio2), 50)
resized2 = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
cv2.imshow("Resized (Height)", resized2)
cv2.waitKey(0)
resized = imutils.resize(img, width=100)
cv2.imshow("Resized via imutils", resized)
cv2.waitKey(0) | true |
c028ec7b91af8cd4b2a0f5dd9bfcf27ac9044df3 | Python | GrupoProgramacion/programacion-1-utec | /lunesSemana7.py | UTF-8 | 1,612 | 3.3125 | 3 | [] | no_license | # promedio
from functools import reduce
def mainPromedio():
n = int(input())
x = list(map(lambda x: int(input()), range(n)))
promedio = reduce(lambda x , y : (x + y), x) / len(x)
print(max(x))
print(min(x))
print(int(round(promedio,0)))
#mainPromedio()
def toString(n):
if n == 0:
return "cero"
elif n == 1:
return "uno"
elif n == 2:
return "dos"
elif n == 3:
return "tres"
elif n == 4:
return "cuatro"
elif n == 5:
return "cinco"
elif n == 6:
return "seis"
elif n == 7:
return "siete"
elif n == 8:
return "ocho"
elif n == 9:
return "nueve"
elif n == 10:
return "diez"
else:
return "número no válido"
#PY1_Elif
#print(toString(x))
def esmult(x,y):
if x % y == 0 :
return True
else :
return False
def mainMultiploAdeB(x,y):
if esmult(x,y) == True :
return str(x) + " es multiplo de " + str(y)
else :
return str(x) + " no es multiplo de " + str(y)
#print(mainMultiploAdeB(int(input()),int(input())))
def validInput():
out = int(input())
if out >= 3 :
return out
else :
print("Error al ingresar los datos")
raise SystemExit
def Dibujar(ancho,largo,borde,fondo):
for y in range(0,ancho):
for x in range(0,largo):
if y == 0 or y == ancho :
print(borde)
else:
print(fondo)
print("\n")
#Dibujar(validInput(),validInput(),input(),input())
| true |
96bb5adf68e9a327fe488f6b837055d4f14d5958 | Python | jingxm/RssReader | /app/models.py | UTF-8 | 4,359 | 2.53125 | 3 | [] | no_license | # coding:utf-8
from . import db, login_manager, app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import sys
from flask_table import Table, Col
'''
subscriptions = db.Table('Subscriptions',
db.Column('feed_id', db.Integer, db.ForeignKey('feed.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)
likes = db.Table('Likes',
db.Column('article_id', db.Integer, db.ForeignKey('article.id'), nullable=False, primary_key=True),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), nullable=False, primary_key=True)
)
'''
#用户类,包括用户名、密码、邮箱、评论、收藏、订阅,其中每名用户会有若干评论、收藏、订阅。
class User(db.Model, UserMixin):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key = True, nullable = False)
email = db.Column(db.String(100), nullable = False, unique = True)
username = db.Column(db.String(64), nullable = False, unique = True)
password_hash = db.Column(db.String(200))
comment = db.relationship('Comment', backref='users', lazy='dynamic')
#, backref = db.backref('users', lazy = 'dynamic'), backref = db.backref('users', lazy = 'dynamic')
subscriptions = db.relationship('Subscription', backref = 'users', lazy='dynamic')
likes = db.relationship('Like', backref = 'users', lazy='dynamic')
#注册callback,借此登录用户
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#简单的异常处理
@property
def password(self):
raise AttributeError('读取密码发生错误!')
#注册时将密码转为带盐哈希存储
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
#登录时验证密码
def password_verification(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return 'This user is %r' % self.username
#订阅频道类,包括频道项目、订阅用户(与用户有多对多关系)。
class Feed(db.Model):
__tablename__ = 'Feeds'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(200))
link = db.Column(db.String(200))
desc = db.Column(db.Text)
rss_url = db.Column(db.String(200))
img_url = db.Column(db.String(200))
def __repr__(self):
return 'This user is %r' % self.username
#频道文章类,包括对应频道(与评论一对多关系,与用户有多对多关系)。
class Article(db.Model):
__tablename__ = 'Articles'
id = db.Column(db.Integer, primary_key = True)
url = db.Column(db.String(200))
content = db.Column(db.Text)
title = db.Column(db.String(200))
comment = db.relationship('Comment', backref="articles", lazy="dynamic")
def __repr__(self):
return 'This user is %r' % self.username
#评论类,包括内容、时间、对于用户和文章。
class Comment(db.Model):
__tablename__ = 'Comments'
id = db.Column(db.Integer, primary_key = True)
content = db.Column(db.Text)
pub_date = db.Column(db.DateTime)
article_id = db.Column(db.Integer, db.ForeignKey(Article.id))
user_id = db.Column(db.Integer, db.ForeignKey(User.id))
def __repr__(self):
return 'This user is %r' % self.username
class Subscription(db.Model):
__tablename__ = 'Subscriptions'
user_id = db.Column(db.Integer, db.ForeignKey(User.id), primary_key = True)
feed_id = db.Column(db.Integer, db.ForeignKey(Feed.id), primary_key = True)
user = db.relationship('User', backref = 'user_subscriptions', lazy = 'joined')
feed = db.relationship('Feed', backref = 'feeds', lazy = 'joined')
def __repr__(self):
return 'This user is %r' % self.username
class Like(db.Model):
__tablename__ = 'Likes'
user_id = db.Column(db.Integer, db.ForeignKey(User.id), primary_key = True)
like_id = db.Column(db.Integer, db.ForeignKey(Article.id), primary_key = True)
user = db.relationship('User', backref = 'user_likes', lazy = 'joined')
like = db.relationship('Article', backref = 'articles', lazy = 'joined')
def __repr__(self):
return 'This user is %r' % self.username | true |
13cb20564686795c75199c06b68f997682194832 | Python | wtarr/GPX_UI | /Logic/CoordinateCalculations.py | UTF-8 | 813 | 3.21875 | 3 | [] | no_license | __author__ = 'William'
import math
class CoordinateCalculations:
""" A class to do necessary calculations
on lat/long coord data"""
__earthRadius = 6371
def calculateDistance(self, long1, lat1, long2, lat2):
""" Calculate distance between 2 coordinates
Source for algorithm
http://www.movable-type.co.uk/scripts/latlong.html"""
degreesLat = math.radians(lat2 - lat1)
degreesLong = math.radians(long2 - long1)
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
a = math.sin(degreesLat/2.) * math.sin(degreesLat/2.) \
+ math.sin(degreesLong/2.) * math.sin(degreesLong/2.) * math.cos(lat1) * math.cos(lat2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = self.__earthRadius * c
return d
| true |
946c07cf1c27bec76d6b08ecbfe49bb907fe1491 | Python | ch-tseng/handGesture | /handGesture.py | UTF-8 | 2,170 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
from libraryCH.device.lcd import ILI9341
lcd = ILI9341(LCD_size_w=240, LCD_size_h=320, LCD_Rotate=270)
videoDisplay = 2 #1 -> image, 2 -> bw
cap = cv2.VideoCapture(0)
fgbg = cv2.BackgroundSubtractorMOG()
while(True):
ret, frame = cap.read()
#th = cv2.erode(frame, None, iterations=3)
#th = cv2.dilate(th, None, iterations=3)
th = fgbg.apply(frame)
if(videoDisplay==1):
layer = frame.copy()
elif(videoDisplay==2):
zeros = np.zeros(frame.shape[:2], dtype = 'uint8')
layer = cv2.merge([zeros, zeros, th])
th2 = th.copy()
contours, hierarchy = cv2.findContours(th2,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
if(len(areas)>0):
max_index = np.argmax(areas)
cnt=contours[max_index]
x,y,w,h = cv2.boundingRect(cnt)
approx=cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(approx,returnPoints=True)
hull2 = cv2.convexHull(approx,returnPoints=False)
print("hull={}, hull2={}".format(len(hull), len(hull2) ))
#draw the points for the hull
if (hull is not None):
for i in range ( len ( hull ) ):
[x , y]= hull[i][0].flatten()
cv2.circle(layer,(int(x),int(y)),2,(0,255,0),-1)
cv2.circle(layer,(int(x),int(y)),5,(255,255,0),1)
cv2.circle(layer,(int(x),int(y)),8,(255,0,0),1)
#print ("Convex hull predict: " + str ( len(hull)-2 ))
if(len(hull2) > 3):
defect = cv2.convexityDefects(approx,hull2)
#draw the points for the defect
if (defect is not None):
for i in range(defect.shape[0]):
s,e,f,d = defect[i,0]
start = tuple(approx[s][0])
end = tuple(approx[e][0])
far = tuple(approx[f][0])
cv2.line(layer,start,end,[0,255,0],2)
cv2.circle(layer,far,5,[0,0,255],-1)
lcd.displayImg(layer)
| true |
359a1a65d7ed1e695f0bfa4ee6006978c94db475 | Python | django-stars/guitar | /guitar-package/guitar/guitar/patcher/item_patchers.py | UTF-8 | 7,206 | 2.875 | 3 | [
"MIT"
] | permissive | import re
class ValidationError(Exception):
pass
class CantApplyPatch(Exception):
pass
class ItemPatcher(object):
def apply_patch(self, content, patch):
"""
Write your code to apply patch to file content.
:param content: (str) file content
:param patch: patch objects
"""
pass
def apply(self, content, patch):
new_content = self.apply_patch(content, patch)
self.validate(new_content)
return new_content
def validate(self, file_obj):
pass
class SettingsPatcher(ItemPatcher):
def apply_patch(self, content, patch_obj):
# Now Just add code to end of file
#TODO: reformat code reindent.py?/?
content += '\n%s\n' % patch_obj['item_to_add']
return content
class ListPatcher(ItemPatcher):
def apply_patch(self, content, patch_obj, variable_name):
# Regular expression of list or tuple variable with open breckets
list_start_reg = r'^%s\s*= *[\(\[]+\n*' % variable_name
list_start = re.search(list_start_reg, content, re.M)
if not list_start:
raise CantApplyPatch('Cant find %s variable' % variable_name)
list_start = list_start.group()
# Regexp of middleware variable with list/tuple of midlewwares and start of next variable
list_variable_reg = r'^%s\s*= *[\(\[]+\n*([^\)\]]+)([\)\]]+\n*[A-Z_0-9= ]*)' % variable_name
try:
list_items_str, next_variable = re.search(list_variable_reg, content, re.M).groups()
except (AttributeError, ValueError):
raise CantApplyPatch
where = 'before' if patch_obj['before'] else 'after' if patch_obj['after'] else None
if where:
item_to_find = patch_obj[where]
else:
item_to_find = None
# Append new list item before or after given list item
item_to_append = "'%s'," % patch_obj['item_to_add']
if item_to_find:
list_items_str = self._append(list_items_str, item_to_find, item_to_append, where)
else:
list_items_str = self._append_to_end(list_items_str, item_to_append)
first_part, last_part = content.split(next_variable)
first_part, __ = first_part.split(list_start)
content = ''.join([first_part, list_start, list_items_str, next_variable, last_part])
return content
def _append_to_end(self, list_items_str, item_to_append):
reg = r'(\,?)[ \t]*$'
comma = re.search(reg, list_items_str).groups()[0]
if not comma:
list_items_str = self._add_comma(list_items_str)
return list_items_str + self._prepare_item_to_add(list_items_str, item_to_append)
def _prepare_item_to_add(self, list_items_str, item_to_append):
return self._get_identation(list_items_str) + item_to_append + '\n'
def _add_comma(self, string):
return re.sub(r'\n$', ',\n', string)
def _get_identation(self, list_items_str):
identation = re.search(r"([ \t]*)['\"]", list_items_str) or ''
if identation:
identation = identation.groups()[0]
return identation
def _append(self, list_items_str, item_to_find, item_to_append, where):
# Regexp
reg = r"[ \t]*'%s' *(,?)\n*" % item_to_find
has_item = re.search(reg, list_items_str)
if not has_item:
list_items_str = self._append_to_end(list_items_str, item_to_append)
else:
item_to_append = self._prepare_item_to_add(list_items_str, item_to_append)
item_to_find = has_item.group()
comma = has_item.groups()[0]
splited_list_data = list_items_str.split(item_to_find)
# Now only append before/after first found item
if where == 'after':
splited_list_data[1] = item_to_append + splited_list_data[1]
else:
splited_list_data[0] = splited_list_data[0] + item_to_append
if not comma:
item_to_find = re.sub(r'\n$', ',\n', item_to_find)
list_items_str = item_to_find.join(splited_list_data)
return list_items_str
class MiddlewarePatcher(ListPatcher):
def apply_patch(self, content, patch_obj):
return super(MiddlewarePatcher, self).apply_patch(content, patch_obj, 'MIDDLEWARE_CLASSES')
class AppsPatcher(ListPatcher):
def apply_patch(self, content, patch_obj):
return super(AppsPatcher, self).apply_patch(content, patch_obj, 'INSTALLED_APPS')
class UrlsPatcher(ItemPatcher):
def apply_patch(self, content, patch_obj):
# Split urls.py by 'url('
parts = content.split('url(')
item_to_find = patch_obj.get('before') or patch_obj.get('after')
# By default item will be added to end
place_id_to_append = len(parts) - 1
# If set parameter after or before what item should we add new - lets find it
if item_to_find:
index_where_item = None
# Find first entry
for i, part in enumerate(parts):
if item_to_find in part:
index_where_item = i
break
if index_where_item is not None:
if patch_obj.get('before'):
# Select item that goes before item that we found
place_id_to_append = index_where_item - 1
else:
place_id_to_append = index_where_item
item_to_append = self._prepare_item_to_append(patch_obj['item_to_add'])
if place_id_to_append == len(parts) - 1:
# If we add in end of list, add identation before
item_to_append = self._get_identation(content) + item_to_append
else:
item_to_append = item_to_append + self._get_identation(content)
parts[place_id_to_append] = self._append_after(
parts[place_id_to_append],
item_to_append)
return 'url('.join(parts)
def _get_identation(self, content):
reg = re.search(r'^(\s*)url\(', content, re.M)
identation = reg.groups()[0] if reg else ''
return identation
def _prepare_item_to_append(self, item_to_append):
return '%s,\n' % item_to_append
def _has_comma(self, string):
reg = re.search(r'(,)\s*$', string)
has_comma = True if reg and reg.groups()[0] else False
return has_comma
def _append_after(self, urlpattern_item, item_to_append):
closing_breckets_count = urlpattern_item.count(')')
if closing_breckets_count:
# Calculate difference between closing and opening breckets
closing_breckets_count = closing_breckets_count - urlpattern_item.count('(')
splited_items = urlpattern_item.split(')')
place_to_append = splited_items[-closing_breckets_count]
if not self._has_comma(place_to_append):
place_to_append = re.sub('\s*$', ',\n', place_to_append)
place_to_append += item_to_append
splited_items[-closing_breckets_count] = place_to_append
urlpattern_item = ')'.join(splited_items)
return urlpattern_item
| true |
7356d4b83515da5cdbe91b9f4cf68296a5f3b73d | Python | joan-kii/Automate-boring-stuff-with-Python | /Chapter 14/convertingSpreadsheetsOtherFormats.py | UTF-8 | 1,000 | 3.34375 | 3 | [] | no_license | #!python3
#convertingSpreadsheetsOtherFormats.py Convierte spreadsheets a otros formatos.
import ezsheets
def convertidor(archivo, formato):
""" Esta función convierte un archivo spredsheet a un formato
específico: '.xlsx', '.ods', '.csv', '.tsv', '.pdf'
o '.html'. """
# Carga el archivo.
ss = ezsheets.upload(archivo)
# Comprueba el formato de salida y realiza la descarga.
if formato == 'excel':
ss.downloadAsExcel()
elif formato == 'openoffice':
ss.downloadAsODS()
elif formato == 'csv':
ss.downloadAsCSV()
elif formato == 'tsv':
ss.downloadAsTSV()
elif formato == 'pdf':
ss.downloadAsPDF()
elif formato == 'html':
ss.downloadAsHTML()
else:
print('Elige un formatoo válido: excel, openoffice, csv, tsv, pdf o html.')
# LLama a la función y le pasa el archivo a convertir y el formato
# de salida.
convertidor('produceSales.xlsx', 'pdf')
| true |
cb5a742ef48f521e30ecec9d122bd59e38627ae6 | Python | disonvon/IP_multi_production | /IP_Solve.py | UTF-8 | 9,917 | 2.796875 | 3 | [] | no_license | from gurobipy import *
"""
use integer programming to solve 6 periods production decision problem with gurobi
in the case we have labor hourconstraint, reliability constraint, dynamic labor cost,
raw material constraint, storing, shipping constraints and advertising budget constraints
demands created by advertisements are dynamic
for more detail about the problem, see the files I attached"""
regular_hour_A = 1800
regular_hour_B = 2720
hour_limit = {
'A': 1800,
'B': 2720}
products = ['Aileron', 'Elevon', 'Flap']
period = [0, 1, 2, 3, 4, 5]
plant = ['A', 'B', 'C', 'D']
type = ['type1', 'type2', 'labor']
raw_material_A = 150000
raw_material_B = 4100
storing_A = 42
storing_B = 56
total_invest_limit = 140000
price = {
'Aileron': 5500,
'Elevon': 4860,
'Flap': 5850}
labor_cost = {
(0, 'A'): 30.5, (0, 'B'): 30.5, (0, 'C'): 46, (0, 'D'): 46,
(1, 'A'): 30.5, (1, 'B'): 30.5, (1, 'C'): 46, (1, 'D'): 46,
(2, 'A'): 32, (2, 'B'): 32, (2, 'C'): 48.2, (2, 'D'): 48.2,
(3, 'A'): 33.5, (3, 'B'): 33.5, (3, 'C'): 46.0, (3, 'D'): 46.0,
(4, 'A'): 33.5, (4, 'B'): 33.5, (4, 'C'): 46.0, (4, 'D'): 46.0,
(5, 'A'): 33.5, (5, 'B'): 33.5, (5, 'C'): 46.0, (5, 'D'): 46.0}
material_cost = {
('type1', 'A'): 2.50, ('type1', 'B'): 2.90, ('type1', 'C'): 2.50, ('type1', 'D'): 2.90,
('type2', 'A'): 3.40, ('type2', 'B'): 5.70, ('type2', 'C'): 3.40, ('type2', 'D'): 5.70}
shipping_cost = {
('Aileron', 'A'): 11.4, ('Aileron', 'B'): 12.20, ('Aileron', 'C'): 11.4, ('Aileron', 'D'): 12.20,
('Elevon', 'A'): 8.20, ('Elevon', 'B'): 8.80, ('Elevon', 'C'): 8.20, ('Elevon', 'D'): 8.80,
('Flap', 'A'): 9.70, ('Flap', 'B'): 10.20, ('Flap', 'C'): 9.70, ('Flap', 'D'): 10.20}
holding_cost = {'Aileron': 55.00, 'Elevon': 47.60, 'Flap': 60.00}
requirements = {
(0, 'Aileron'): 65, (0, 'Elevon'): 220, (0, 'Flap'): 135,
(1, 'Aileron'): 95, (1, 'Elevon'): 245, (1, 'Flap'): 170,
(2, 'Aileron'): 135, (2, 'Elevon'): 245, (2, 'Flap'): 195,
(3, 'Aileron'): 250, (3, 'Elevon'): 290, (3, 'Flap'): 160,
(4, 'Aileron'): 190, (4, 'Elevon'): 310, (4, 'Flap'): 210,
(5, 'Aileron'): 210, (5, 'Elevon'): 200, (5, 'Flap'): 190}
advertising_cost = {
'Aileron': 410, 'Elevon': 310, 'Flap': 440}
material_requirements = {
('Aileron', 'type1', 'A'): 185, ('Aileron', 'type2', 'A'): 8.4, ('Aileron', 'labor', 'A'): 8.6,
('Elevon', 'type1', 'A'): 225.00, ('Elevon', 'type2', 'A'): 0.00, ('Elevon', 'labor', 'A'): 7.00,
('Flap', 'type1', 'A'): 170, ('Flap', 'type2', 'A'): 10.6, ('Flap', 'labor', 'A'): 10.20,
('Aileron', 'type1', 'B'): 180, ('Aileron', 'type2', 'B'): 8.2, ('Aileron', 'labor', 'B'): 8.2,
('Elevon', 'type1', 'B'): 220, ('Elevon', 'type2', 'B'): 0.00, ('Elevon', 'labor', 'B'): 6.9,
('Flap', 'type1', 'B'): 165, ('Flap', 'type2', 'B'): 9.8, ('Flap', 'labor', 'B'): 9.7,
('Aileron', 'type1', 'C'): 185, ('Aileron', 'type2', 'C'): 8.4, ('Aileron', 'labor', 'C'): 8.6,
('Elevon', 'type1', 'C'): 225.00, ('Elevon', 'type2', 'C'): 0.00, ('Elevon', 'labor', 'C'): 7.00,
('Flap', 'type1', 'C'): 170, ('Flap', 'type2', 'C'): 10.6, ('Flap', 'labor', 'C'): 10.20,
('Aileron', 'type1', 'D'): 180, ('Aileron', 'type2', 'D'): 8.2, ('Aileron', 'labor', 'D'): 8.2,
('Elevon', 'type1', 'D'): 220, ('Elevon', 'type2', 'D'): 0.00, ('Elevon', 'labor', 'D'): 6.9,
('Flap', 'type1', 'D'): 165, ('Flap', 'type2', 'D'): 9.8, ('Flap', 'labor', 'D'): 9.7,}
#create model
m = Model('dpp')
#variables period i produce product m in plant A
p = m.addVars(period, products, plant, vtype=GRB.INTEGER, name='production')
#products created by advertisement
c = m.addVars(period, products, vtype=GRB.INTEGER, name='advertisement')
#numer of products shipped in period i of products A from plant A
ship = m.addVars(period, products, plant, vtype=GRB.INTEGER, name='shippment')
#number of products stored in period i of products A from plant A
sto = m.addVars(period, products, plant, vtype=GRB.INTEGER, name='storage')
# total revenue
obj = 0
for pro in products:
for i in period:
if i == 0:
obj += price[pro]*(requirements[i, pro] + c[i, pro])
elif i == 1:
obj += price[pro]*(requirements[i, pro] + c[i, pro] + 0.4*c[i-1, pro])
else:
obj+= price[pro]*(requirements[i, pro] + c[i, pro] + 0.4*c[i-1, pro] + 0.2*c[i-2, pro])
#labor, material, holding, shipping and advertising cost
for i in period:
for j in products:
for k in plant:
for l in type:
if l == 'labor':
obj -= labor_cost[i, k]*material_requirements[j, l, k]*p[i, j, k]#labor cost
else:
obj -= material_cost[l, k]*material_requirements[j, l, k]*p[i, j, k]#material cost
obj -= shipping_cost[j, k]*ship[i, j, k] + sto[i, j, k]*holding_cost[j]#holding cost + shipping cost
obj -= c[i, j] * advertising_cost[j]#advertising cost
#Set objective: total revenue - toal cost
obj = m.setObjective(obj, GRB.MAXIMIZE)
#Add constraints:
#Labor constraints---regular hours
m.addConstrs(sum(p[i, j, k]*material_requirements[j, 'labor', k] for j in products) <= hour_limit[k]
for i in period for k in ['A', 'B'])
#Labor reliablity
for i in period:
if i ==5:
break
m.addConstr(sum(p[i+1, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['A', 'C']) >=
0.95*sum(p[i, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['A', 'C']))
m.addConstr(sum(p[i+1, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['A', 'C']) <=
1.05*sum(p[i, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['A', 'C']))
m.addConstr(sum(p[i+1, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['B', 'D']) >=
0.95*sum(p[i, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['B', 'D']))
m.addConstr(sum(p[i+1, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['B', 'D']) <=
1.05*sum(p[i, j, k]*material_requirements[j, 'labor', k] for j in products for k in ['B', 'D']))
#material constraints
m.addConstrs(sum(material_requirements[j, 'type1', k]*p[i, j, k]
for k in plant for j in products) <= raw_material_A for i in period)
m.addConstrs(sum(material_requirements[j, 'type2', k]*p[i, j, k]
for k in plant for j in products) <= raw_material_B for i in period)
#storage and shipping constraints for 6 periods
for i in period:
if i == 0:
m.addConstrs(sum(ship[i, j, k] for k in ['A', 'C']) <= sum(p[i, j, k] for k in ['A', 'C'])
for j in products)
m.addConstrs(sum(ship[i, j, k] for k in ['B', 'D']) <= sum(p[i, j, k] for k in ['B', 'D'])
for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['A', 'C']) == sum(p[i, j, k] for k in ['A', 'C'])
- sum(ship[i, j, k] for k in ['A', 'C']) for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['B', 'D']) == sum(p[i, j, k] for k in ['B', 'D'])
- sum(ship[i, j, k] for k in ['B', 'D']) for j in products)
m.addConstrs(sum(ship[i, j, k] for k in plant) == requirements[i, j] + c[i, j] for j in products)
m.addConstrs(sum(sto[i, j, k] for j in products for k in ['A', 'C']) <= storing_A for i in period)
m.addConstrs(sum(sto[i, j, k] for j in products for k in ['B', 'D']) <= storing_B for i in period)
elif i == 1:
#period 2
m.addConstrs(sum(ship[i, j, k] for k in ['A', 'C']) <= sum(p[i, j, k] + sto[i-1, j, k]
for k in ['A', 'C']) for j in products)
m.addConstrs(sum(ship[i, j, k] for k in ['B', 'D']) <= sum(p[i, j, k] + sto[i-1, j, k]
for k in ['B', 'D']) for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['A', 'C']) == sum(p[i, j, k] + sto[i-1, j, k] - ship[i, j, k]
for k in ['A', 'C']) for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['B', 'D']) == sum(p[i, j, k] + sto[i-1, j, k] - ship[i, j, k]
for k in ['B', 'D']) for j in products)
m.addConstrs(sum(ship[i, j, k] for k in plant) == requirements[i, j] + c[i, j] + 0.4*c[i-1, j] for j in products)
else:
#period 3,4,5,6
m.addConstrs(sum(ship[i, j, k] for k in ['A', 'C']) <= sum(p[i, j, k] + sto[i-1, j, k]
for k in ['A', 'C']) for j in products)
m.addConstrs(sum(ship[i, j, k] for k in ['B', 'D']) <= sum(p[i, j, k] + sto[i-1, j, k]
for k in ['B', 'D']) for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['A', 'C']) == sum(p[i, j, k] + sto[i-1, j, k] - ship[i, j, k]
for k in ['A', 'C']) for j in products)
m.addConstrs(sum(sto[i, j, k] for k in ['B', 'D']) == sum(p[i, j, k] + sto[i-1, j, k] - ship[i, j, k]
for k in ['B', 'D']) for j in products)
m.addConstrs(sum(ship[i, j, k] for k in plant) == requirements[i, j] + c[i, j] + 0.4*c[i-1, j] +
0.2 * c[i-2, j] for j in products)
#advertising costs for 6 periods
m.addConstr(sum(advertising_cost[j]*c[i, j] for i in period for j in products) <= total_invest_limit )
# m.Params.outputFlag = 0
m.optimize()
origObjVal = m.ObjVal
for v in m.getVars():
print '%s %g' %(v.varName, v.x)
print 'Obj:',origObjVal
| true |
791facc61852748232b25bd621320ea4f1ee66b5 | Python | mareathj/thinkpython | /ch4/polygon.py | UTF-8 | 317 | 3.75 | 4 | [] | no_license | import turtle
import math
bob = turtle.Turtle()
def polygon(t,length,n):
for i in range(n):
t.fd(length)
t.lt(360/n)
def circle(t,r):
l = 2*r/100
polygon(t,l,100)
#def arc(t,r,angle):
l = 2*r/100
polygon(t,l, int(360/angle))
arc(bob,100,30)
#circle(bob,100)
#polygon(bob,20,7)
| true |
8e7019b32e61d1eefac8c6dad1d5573bad2ff81b | Python | chiakiphan/ner-product | /word2vec.py | UTF-8 | 3,790 | 2.671875 | 3 | [] | no_license | from dictionary_load import DictionaryLoader
import re
from underthesea import pos_tag
words = DictionaryLoader("/home/citigo/Downloads/1M_san_pham_my_pham.csv").words
lower_words = set([word.lower() for word in words])
def word2features(sent, position):
word = sent[position][0]
postag = sent[position][1]
features = {
'bias': 1.0,
'word.lower()': word.lower(),
'word[-3:]': word[-3:],
'word[-2:]': word[-2:],
'word.isalpha()': multi_word(word),
'word.digitand_comma()': digitand_comma(word),
'word.isupper()': word.isupper(),
'word.istitle()': word.istitle(),
'word.isdigit()': word.isdigit(),
'word.hasdigit()': check_digit(word),
'postag': postag,
'word.isstopword()': check_stopword(word),
'number_syllable': count_syllable(word),
}
if position > 0:
word1 = sent[position - 1][0]
word2 = word1+' '+word
if position < len(sent)-1:
word3 = word2+sent[position + 1][0]
else:
word3 = word2
postag1 = sent[position - 1][1]
features.update({
'-1:word.lower()': word1.lower(),
'-1:word1.lower()': word2.lower(),
'-1:word2.lower()': word3.lower(),
'-1:word.istitle()': word1.istitle(),
'-1:word.isalpha()': multi_word(word1),
'-1:word.isbidict()': text_is_in_dict(word2),
'-1:word.istridict()': text_is_in_dict(word3),
'-1:word.digitand_comma()': digitand_comma(word1),
'-1:word.isupper()': word1.isupper(),
'-1:word.isstopword()': check_stopword(word1),
'-1:word.hasdigit()': check_digit(word1),
'-1:postag': postag1,
'-1:number_syllable': count_syllable(word1),
# '-1:postag[:2]': postag1[:2],
})
else:
features['BOS'] = True
if position < len(sent)-1:
word1 = sent[position + 1][0]
word2 = word + ' ' + word1
if position > 0:
word3 = sent[position - 1][0] + word2
else:
word3 = word2
postag1 = sent[position + 1][1]
features.update({
'+1:word.lower()': word1.lower(),
'+1:word1.lower()': word2.lower(),
'+1:word2.lower()': word3.lower(),
'+1:word.istitle()': word1.istitle(),
'+1:word.digitand_comma()': digitand_comma(word1),
'+1:word.isdict()': text_is_in_dict(word2),
'+1:word.istridict()': text_is_in_dict(word3),
'+1:word.isalpha()': multi_word(word1),
'+1:word.isupper()': word1.isupper(),
'+1:word.hasdigit()': check_digit(word1),
'+1:word.isstopword()': check_stopword(word1),
'+1:postag': postag1,
'+1:number_syllable': count_syllable(word),
# '+1:postag[:2]': postag1[:2],
})
else:
features['EOS'] = True
return features
def sent2features(sent):
return [word2features(sent, i) for i in range(len(sent))]
def sent2labels(sent):
return [label for token, postag, label in sent]
def sent2tokens(sent):
return [token for token, postag, label in sent]
def check_stopword(word):
return True
def check_digit(word):
for c in word:
if str(c).isdigit():
return True
return False
def digitand_comma(word):
if '.' in word or ',' in word:
return True
return False
def count_syllable(word):
return len(str(word).split('_'))
def multi_word(word):
if ' ' in word:
return True
return False
def text_is_in_dict(word):
for words in lower_words:
if str(word).lower() in str(words).lower():
return True
return False
| true |
3ff414cbb46204920fd569bab5619e1184ced694 | Python | yanghh0/CV | /Facial Expression Recognition/preprocess.py | UTF-8 | 972 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding:utf8 -*-
import os
import cv2
import numpy as np
import pandas as pd
df = pd.read_csv(os.path.join('dataset', 'train.csv'))
x = df[['feature']]
y = df[['label']]
x.to_csv(os.path.join('dataset', 'data.csv'), index=False, header=False)
y.to_csv(os.path.join('dataset', 'label.csv'), index=False, header=False)
data = np.loadtxt(os.path.join('dataset', 'data.csv'))
if not os.path.isdir(os.path.join('dataset', 'face')):
os.mkdir(os.path.join('dataset', 'face'))
if not os.path.isdir(os.path.join('dataset', 'test')):
os.mkdir(os.path.join('dataset', 'test'))
"""
共有28709张图片,取前24000张图片作为训练集,其他图片作为验证集。
"""
for i in range(data.shape[0]):
faceImg = data[i, :].reshape((48, 48))
if i <= 24000:
cv2.imwrite(os.path.join('dataset', 'face', '{}.jpg').format(i), faceImg)
else:
cv2.imwrite(os.path.join('dataset', 'test', '{}.jpg').format(i), faceImg) | true |
a22f99a1490537d87e8e7b4ea70f991c2ddebb34 | Python | KimaniKibuthu/pneumonia-classification | /app.py | UTF-8 | 1,540 | 2.96875 | 3 | [] | no_license | import cv2
import numpy as np
import streamlit as st
import tensorflow as tf
@st.cache(allow_output_mutation=True)
def load_model():
model = tf.keras.models.load_model("tuned_model.h5")
return model
def main():
html_temp = """
<div style="background-color:tomato;padding:10px">
<h2 style="color:white;text-align:center;">Pneumonia Prediction Web App </h2>
</div>
"""
st.markdown(html_temp, unsafe_allow_html=True)
uploaded_file = st.file_uploader(" ", type=["jpeg", "jpg"])
model = load_model()
if uploaded_file is not None:
# Convert the file to an opencv image.
file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
opencv_image = cv2.imdecode(file_bytes, 1)
opencv_image = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)
resized = cv2.resize(opencv_image, (224, 224))
st.image(opencv_image, channels="RGB")
resized = tf.keras.applications.inception_v3.preprocess_input(resized)
img_reshape = resized[np.newaxis, ...]
if st.button("Predict"):
prediction = model.predict(img_reshape, batch_size=1)
if prediction < 0.5:
output = 'be healthy'
else:
output = 'have Pneumonia'
st.write("Classifying...")
st.success('You are likely to {}.'.format(output))
if st.button("Disclaimer"):
disclaimer = 'This is an estimate as to whether you have pneumonia or not'
st.success(disclaimer)
if __name__ == '__main__':
main()
| true |
1fb2de00b2c7527244dfbbdb61ed71a8b2a30992 | Python | EyssK/adventofcode2017 | /Day18.py | UTF-8 | 4,436 | 2.578125 | 3 | [] | no_license |
# part1
def step(regs, cmd, args, freq):
pc_diff = 1
args = args.split()
if len(args) > 1:
try:
args[1] = int(args[1])
except ValueError:
args[1] = regs[args[1]]
if cmd == "set":
regs[args[0]] = args[1]
elif cmd == "add":
regs[args[0]] += args[1]
elif cmd == "mul":
regs[args[0]] *= args[1]
elif cmd == "mod":
regs[args[0]] %= args[1]
elif cmd == "snd":
try:
args[0] = int(args[0])
except ValueError:
args[0] = regs[args[0]]
freq.append(args[0])
elif cmd == "rcv":
if regs[args[0]] != 0:
# break equivalent
pc_diff = 10000
elif cmd == "jgz":
try:
args[0] = int(args[0])
except ValueError:
args[0] = regs[args[0]]
pc_diff = args[1] if args[0] > 0 else 1
return pc_diff
# for part2
def step2(regs, cmd, args, freqin, freqout):
pc_diff = 1
args = args.split()
if len(args) > 1:
try:
args[1] = int(args[1])
except ValueError:
args[1] = regs[args[1]]
if cmd == "set":
regs[args[0]] = args[1]
elif cmd == "add":
regs[args[0]] += args[1]
elif cmd == "mul":
regs[args[0]] *= args[1]
elif cmd == "mod":
regs[args[0]] %= args[1]
elif cmd == "snd":
try:
args[0] = int(args[0])
except ValueError:
args[0] = regs[args[0]]
freqout.append(args[0])
elif cmd == "rcv":
try:
regs[args[0]] = freqin.pop(0)
except IndexError:
# nothing to pop -> wait here
pc_diff = 0
elif cmd == "jgz":
try:
args[0] = int(args[0])
except ValueError:
args[0] = regs[args[0]]
pc_diff = args[1] if args[0] > 0 else 1
return pc_diff
if __name__ == "__main__":
lines = list()
with open("input18", "r") as f:
for line in f:
lines.append(line[:-1])
# test
instruction_list_test = list()
instruction_list_test.append("set a 1")
instruction_list_test.append("add a 2")
instruction_list_test.append("mul a a")
instruction_list_test.append("mod a 5")
instruction_list_test.append("snd a")
instruction_list_test.append("set a 0")
instruction_list_test.append("rcv a")
instruction_list_test.append("jgz a -1")
instruction_list_test.append("set a 1")
instruction_list_test.append("jgz a -2")
# test activation
# lines = instruction_list_test
# create register used
reg_list = dict()
for instr in lines:
reg = instr.split()[1]
if reg not in reg_list:
reg_list[reg] = 0
freq = [0]
pc = 0
while pc in range(0,len(lines)):
cmd, args = lines[pc].split(' ', 1)
pc += step(reg_list, cmd, args, freq)
print(freq[-1])
# test
instruction_list_test = list()
instruction_list_test.append("snd 1")
instruction_list_test.append("snd 2")
instruction_list_test.append("snd p")
instruction_list_test.append("rcv a")
instruction_list_test.append("rcv b")
instruction_list_test.append("rcv c")
instruction_list_test.append("rcv d")
# test activation
# lines = instruction_list_test
# part2
# create register used
reg_list0 = dict()
for instr in lines:
reg = instr.split()[1]
if not reg.isdecimal() and reg not in reg_list0:
reg_list0[reg] = 0
# create register 2 used
reg_list1 = dict()
for instr in lines:
reg = instr.split()[1]
if not reg.isdecimal() and reg not in reg_list1:
reg_list1[reg] = 0
reg_list1['p'] = 1
freq0 = list()
freq1 = list()
pc0 = 0
pc1 = 0
count_send1 = 0
while pc0 in range(0,len(lines)) and pc1 in range(0,len(lines)):
cmd0, args0 = lines[pc0].split(' ', 1)
cmd1, args1 = lines[pc1].split(' ', 1)
inc_pc0 = step2(reg_list0, cmd0, args0, freq0, freq1)
prev_len = len(freq0)
inc_pc1 = step2(reg_list1, cmd1, args1, freq1, freq0)
cur_len = len(freq0)
if cur_len == prev_len + 1:
count_send1 += 1
if inc_pc0 == 0 and inc_pc1 == 0:
# deadlock !
break
else:
pc0 += inc_pc0
pc1 += inc_pc1
print(count_send1)
| true |
298192c88a293781f67efc5878d99657181be4c4 | Python | VRumay/WhatsappToCSV | /WhatsappToCSV.py | UTF-8 | 4,649 | 3.5 | 4 | [] | no_license |
"""
Whatsapp to CSV: Converts any chat file exported from whatsapp as .txt to a .csv file
with the most relevant columns for analysis.
Supports group chats, currently supporting english exports, with a possibility to extend it to spanish
"""
import os
import pandas as pd
import re
chatfile = r"C:\Users\Rumay-Paz\Desktop\Programming\WhatsappToCSV\WhatsApp Chat with 【_L u n w a v e 】.txt"
filename = (os.path.basename(chatfile)).split('.')[0]
# From a .txt file econded as utf8, build a pandas dataframe and use line jumps regex as separator - do not stop at lines that could not be parsed:
df= pd.read_csv(chatfile, sep = '(\r\n?|\n)+' , header=None,encoding='utf8',engine='python', error_bad_lines=False)
# Set the name of the single column in the dataframe so far:
df.columns = ['datetimesendermessage']
# Split that single column into 2 new columns where the ": " separator is first found, as it marks the colon at the end of the sender name:
datetimesendermessage = df['datetimesendermessage'].str.split(": ", n = 1, expand = True)
df['datetimesender'] = datetimesendermessage[0]
df['message'] = datetimesendermessage[1]
# Metachanges
titlechanged = 'changed the subject from'
numberchanged = 'changed to +'
adminappointed = " now an admin"
personadded = " added "
imagechanged = "changed this group's icon"
imagedeleted = "deleted this group's icon"
personleft = ' left'
personkicked = ' removed '
def metachanges(change, flag, message):
if str(df.loc[row, 'datetimesender']).find(change) > 0:
subjectchange = df.loc[row, 'datetimesender'].split(flag)
df.loc[row, 'datetimesender'] = subjectchange[0]
df.loc[row, 'metachange'] = (message)
df.loc[row, 'message'] = (subjectchange[1])
# Find lines with errors (line jumps as a separator tend to break longer messages on whatsapp chat), what this loop does is iterate over each row and check if the 'datetimesender' column
# does not have a date formatted
for row in range(1, len(df)):
if str(df.loc[row, 'datetimesender']).find(' AM - ') == -1 and str(df.loc[row, 'datetimesender']).find(' PM - ') == -1 :
df.loc[row, 'message'] = df.loc[row, 'datetimesender'] + str(df.loc[row, 'message'])
df.loc[row, 'datetimesender'] = df.loc[row-1, 'datetimesender']
# Check for chat title changes
metachanges(titlechanged, 'changed the subject from ', 'Conversation Title changed')
# Check for person number changes
metachanges(numberchanged, ' changed to ', 'Number changed to')
# Check for admin appointment
metachanges(adminappointed, "'re now an admin", 'Appointed as Admin')
# Check for new person added
metachanges(personadded, 'added', 'Added to the conversation')
# Check for group image changed
metachanges(imagechanged, "changed this group's icon", 'Conversation Image was changed')
# Check for group image deleted
metachanges(imagedeleted, "deleted this group's icon",'Conversation Image was deleted')
# Check for leaving person
metachanges(personleft, ' left', 'Left the Conversation')
# Check for removed person
metachanges(personkicked, ' removed ', 'Kicked from the Conversation')
# Datetime & Sender column
datetimesender = df['datetimesender'].str.split(" - ", n = 1, expand = True)
df['datetime'] = datetimesender[0]
df['sender'] = datetimesender[1].replace(" deleted this group's icon",'')
# Split 'datetime' column into Date & Time Columns
datetimesender = df['datetime'].str.split(", ", n = 1, expand = True)
df['date'] = datetimesender[0]
df['time'] = datetimesender[1]
# Extract emojis and save to 'emojis' column
df['emojis'] = df['message'][df['message'].str.contains(u"[^\U00000000-\U0000d7ff\U0000e000-\U0000ffff]", flags=re.UNICODE, na=False)] # replace match with contains
#df['emojis'] = df['emojis'].replace(f"[\s\w\d\\().:«»~-]","", regex=True, inplace=True) # Won't delete punctuation, but it would be more efficient.
abc123 = [' ','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','0','1','2','3','4','5','6', '7', '8', '9','!',',','.','?','¿','ñ','é','ó','á','ú','í','%','(',')','*','_','-','"','@','/',';',':','¡','=','+','’','[',']','>','“','”','&','#','【','','w','v','】']
for i in abc123:
df['emojis'] = df['emojis'].str.replace(i, "", regex=False)
df['emojis'] = df['emojis'].str.replace(i.upper(), "", regex=False)
# Keep only relevant columns
df = df[['date','time','sender','message','metachange','emojis']]
# Save excel file in cwd
df.to_csv(f'{filename}.csv',encoding='utf-8-sig',index=False)
| true |
64263fd4d8f00cabffed4695ed53619adbe69657 | Python | mart00n/introto6.00 | /ps1/ps1b_redo.py | UTF-8 | 482 | 3.28125 | 3 | [] | no_license | # mart00n
# 10/09/2016
bal = float(input('Enter balance: '))
intrate = float(input('Enter your annual interest rate: '))
monthrate = intrate / 12.0
payment = 10.0
loopbal = bal
while loopbal >= 0:
for i in range(1,13):
loopbal = loopbal * (1.0 + monthrate) - payment
if loopbal <= 0:
break
if loopbal >= 0:
payment += 10.0
loopbal = bal
else:
print('Pay', payment, 'per month to pay off your debt within 1 year.')
| true |
124cce782235cee629023d2df490ffab1bb22091 | Python | syseleven/python-cloudutils-libs | /syseleven/cloudutilslibs/utils.py | UTF-8 | 5,520 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python
from neutronclient.common.exceptions import NotFound as neutronclientNotFound
from novaclient.exceptions import NotFound as novaclientNotFound
from heatclient.exc import HTTPNotFound as heatclientHTTPNotFound
from copy import deepcopy
import sys
import logging
global LOG
LOG = logging.getLogger('cloudutils')
def get_floating_ip_from_heat_nova_neutron(stack, heatclient, neutronclient, novaclient):
""" gets floating IPs from a heat stack and returns (name, floatingip) as tuple """
ret = []
fields = {'stack_id': stack.stack_name}
stack_resources = heatclient.resources.list(**fields)
for stack_resource in stack_resources:
port_id = False
floatingip_address = False
# get floatingip_address and port_id
if stack_resource.resource_type == 'OS::Neutron::FloatingIP':
try:
floatingip = neutronclient.show_floatingip(stack_resource.physical_resource_id)['floatingip']
except neutronclientNotFound:
continue
floatingip_address = floatingip['floating_ip_address']
port_id = floatingip['port_id']
elif stack_resource.resource_type.startswith('sys11::floatport'):
try:
heat_ret = heatclient.stacks.get(stack_id=stack_resource.physical_resource_id).to_dict().get('outputs', [])
except heatclientHTTPNotFound:
continue
for output in heat_ret:
if output['output_key'] == 'floating_ip_address':
floatingip_address = output['output_value']
elif output['output_key'] == 'port':
port_id = output['output_value']
if port_id and floatingip_address:
port = neutronclient.show_port(port_id)['port']
device_id = port['device_id']
try:
server = novaclient.servers.get(device_id)
except novaclientNotFound:
continue
ret.append((server, floatingip_address))
return ret
def dict_merge(a, b):
'''recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.'''
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.iteritems():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(result[k], v)
else:
result[k] = deepcopy(v)
return result
def drilldownchoices(input, formatter=lambda x: str(x), always_keep_first=False, **keywords):
""" take list of hashs
ask user interactively which hash it wants
returns selected hash
"""
LOG.debug('drilldownchoices() %s', repr(input))
if 'last' in keywords:
last = keywords['last']
LOG.info('Only showing last %d entries.', last)
else:
last = None
counter = 0
results = list()
if len(input) == 1:
return input[0]
# TODO -1 for exit
print '-1) exit'
for x in input:
if last:
if (len(input) - counter) < last:
print (' %d) %s' % (counter, formatter(x)))
else:
print (' %d) %s' % (counter, formatter(x)))
counter += 1
user_input = get_input(' >')
if user_input == '-1':
sys.exit(-1)
elif user_input.isdigit() and int(user_input) < counter:
results += [(input[int(user_input)])]
else:
for x in input:
if user_input.lower() in formatter(x).lower():
results += [x]
if always_keep_first:
results = [input[0]] + results
LOG.debug(repr(results))
LOG.debug(repr(len(results)))
if len(results) > 1:
return drilldownchoices(results, formatter=formatter, always_keep_first=always_keep_first)
elif len(results) == 0:
return drilldownchoices(input, formatter=formatter, always_keep_first=always_keep_first)
# TODO if zero then do something
LOG.debug(results)
#LOG.info('Choice %s', repr(results[0]))
return results[0]
def safe_unicode(value, encoding='utf-8'):
"""Converts a value to unicode, even it is already a unicode string.
>>> from sys11.helpers import safe_unicode
>>> safe_unicode('spam')
u'spam'
>>> safe_unicode(u'spam')
u'spam'
>>> safe_unicode(u'spam'.encode('utf-8'))
u'spam'
>>> safe_unicode('\xc6\xb5')
u'\u01b5'
>>> safe_unicode(u'\xc6\xb5'.encode('iso-8859-1'))
u'\u01b5'
>>> safe_unicode('\xc6\xb5', encoding='ascii')
u'\u01b5'
>>> safe_unicode(1)
1
>>> print safe_unicode(None)
None
"""
if isinstance(value, unicode):
return value
elif isinstance(value, basestring):
try:
value = unicode(value, encoding)
except (UnicodeDecodeError):
value = value.decode('utf-8', 'replace')
return value
def convert_to_str(value):
""" Converts value to string.
Using safe_unicode, if value is basestring"""
if isinstance(value, basestring):
return safe_unicode(value)
else:
return str(value)
def get_input(value=u''):
""" Returns raw_input as type unicode """
input_ = raw_input('%s ' % value)
if input_:
return safe_unicode(input_)
else:
LOG.debug('No input given')
return ''
| true |
ded654f8afa4c0d6808422abb18728a61bc7b4c6 | Python | argriffing/xgcode | /20081201a.py | UTF-8 | 8,708 | 2.765625 | 3 | [] | no_license | """For each tree, reconstruct the topology from a single eigendecomposition.
"""
from StringIO import StringIO
import numpy as np
from SnippetUtil import HandlingError
import SnippetUtil
import Newick
import FelTree
import NewickIO
import TreeComparison
import MatrixUtil
import iterutils
from Form import CheckItem
import Form
import FormOut
#FIXME use const data
def get_form():
"""
@return: the body of a form
"""
# define the default tree lines
default_tree_lines = [
'(((a:0.05, b:0.05):0.15, c:0.2):0.8, x:1.0, (((m:0.05, n:0.05):0.15, p:0.2):0.8, y:1.0):1.0);',
'(a:1.062, c:0.190, (d:1.080, b:2.30):2.112);',
'((d:0.083, b:0.614):0.150, e:0.581, (c:1.290, a:0.359):1.070);',
'((b:1.749, d:0.523):0.107, e:1.703, (a:0.746, c:0.070):4.025);']
# define the list of form objects
form_objects = [
Form.MultiLine('trees', 'newick trees (one tree per line)',
'\n'.join(default_tree_lines)),
Form.Float('epsilon', 'non-negligible eigenvalue', '1e-9'),
Form.CheckGroup('options', 'show these tree sets', [
CheckItem('show_all',
'all reconstructed trees', True),
CheckItem('show_incomplete',
'incompletely resolved reconstructed trees', True),
CheckItem('show_conflicting',
'conflicting reconstructed trees', True),
CheckItem('show_negligible',
'trees with potentially informative but small loadings',
True)])]
return form_objects
def get_form_out():
return FormOut.Matrix()
class NegligibleError(Exception):
"""
This error is raised when a negligible loading is encountered.
"""
pass
class IncompleteError(Exception):
"""
This error is raised when a tree reconstruction cannot be completed.
"""
pass
class AnalysisResult:
"""
Attempt to reconstruct a tree from the eigendecomposition of the doubly centered distance matrix.
Report what happens when this is done.
"""
def __init__(self, tree, epsilon):
"""
@param tree: a newick tree in the felsenstein-inspired format
@param epsilon: determines whether loadings are considered negligible
"""
# clear some flags that describe events that occur during reconstruction
self.is_negligible = False
self.is_incomplete = False
self.is_conflicting = False
# define the trees
self.tree = tree
self.reconstructed_tree = None
# set the threshold for loading negligibility
self.epsilon = epsilon
# define some arbitrary ordering of tip names
self.ordered_names = [node.get_name() for node in tree.gen_tips()]
# get the distance matrix with respect to this ordering
D = tree.get_distance_matrix(self.ordered_names)
# get the Gower doubly centered matrix
G = MatrixUtil.double_centered(np.array(D))
# get the eigendecomposition of the Gower matrix
eigenvalues, eigenvector_transposes = np.linalg.eigh(G)
eigenvectors = eigenvector_transposes.T
self.sorted_eigensystem = list(reversed(list(sorted((abs(w), v) for w, v in zip(eigenvalues, eigenvectors)))))
# build the tree recursively using the sorted eigensystem
indices = set(range(len(self.ordered_names)))
try:
# try to reconstruct the tree
root = self._build_tree(indices, 0)
root.set_branch_length(None)
output_tree = Newick.NewickTree(root)
# convert the tree to the FelTree format
newick_string = NewickIO.get_newick_string(output_tree)
self.reconstructed_tree = NewickIO.parse(
newick_string, FelTree.NewickTree)
except NegligibleError:
self.is_negligible = True
except IncompleteError:
self.is_incomplete = True
else:
# compare the splits defined by the reconstructed tree
# to splits in the original tree
expected_partitions = TreeComparison.get_nontrivial_partitions(
self.tree)
observed_partitions = TreeComparison.get_nontrivial_partitions(
self.reconstructed_tree)
invalid_partitions = observed_partitions - expected_partitions
if invalid_partitions:
self.is_conflicting = True
def _build_tree(self, indices, depth):
"""
@param indices: a set of indices of taxa in the current subtree
@param depth: the depth of the current subtree
@return: the node representing the subtree
"""
root = Newick.NewickNode()
if not indices:
msg = 'trying to build a tree from an empty set of indices'
raise ValueError(msg)
elif len(indices) == 1:
index = list(indices)[0]
root.set_name(self.ordered_names[index])
else:
if depth >= len(self.sorted_eigensystem):
# the ordered eigenvector loading signs
# were unable to distinguish each taxon
raise IncompleteError()
negative_indices = set()
positive_indices = set()
negligible_indices = set()
w, v = self.sorted_eigensystem[depth]
for i in indices:
if abs(v[i]) < self.epsilon:
negligible_indices.add(i)
elif v[i] < 0:
negative_indices.add(i)
else:
positive_indices.add(i)
if negligible_indices:
# eigenvector loadings near zero are degenerate
raise NegligibleError()
for next_indices in (negative_indices, positive_indices):
if next_indices:
child = self._build_tree(next_indices, depth+1)
child.set_branch_length(1)
root.add_child(child)
child.set_parent(root)
return root
def get_response_lines(self, options):
"""
Yield lines that form the result of the analysis.
@param options: a subset of strings specifying what to show
"""
preamble_lines = []
error_lines = []
if 'show_incomplete' in options and self.is_incomplete:
error_lines.append('the sequential splits defined by the eigenvectors were insufficient to reconstruct the tree')
if 'show_conflicting' in options and self.is_conflicting:
error_lines.append('the reconstructed tree has a split that is incompatible with the original tree')
if 'show_negligible' in options and self.is_negligible:
error_lines.append('during reconstruction a negligible eigenvector loading was encountered')
if 'show_all' in options or error_lines:
preamble_lines.extend(['original tree:', NewickIO.get_newick_string(self.tree)])
if self.reconstructed_tree:
preamble_lines.extend(['reconstructed tree:', NewickIO.get_newick_string(self.reconstructed_tree)])
return preamble_lines + error_lines
def get_response_content(fs):
# get the newick trees.
trees = []
for tree_string in iterutils.stripped_lines(StringIO(fs.trees)):
# parse each tree
# and make sure that it conforms to various requirements
tree = NewickIO.parse(tree_string, FelTree.NewickTree)
tip_names = [tip.get_name() for tip in tree.gen_tips()]
if len(tip_names) < 4:
msg = 'expected at least 4 tips but found ' + str(len(tip_names))
raise HandlingError(msg)
if any(name is None for name in tip_names):
raise HandlingError('each terminal node must be labeled')
if len(set(tip_names)) != len(tip_names):
raise HandlingError('each terminal node label must be unique')
trees.append(tree)
# get the threshold for negligibility of an eigenvector loading
epsilon = fs.epsilon
if not (0 <= epsilon < 1):
raise HandlingError('invalid threshold for negligibility')
# get the set of selected options
selected_options = fs.options
# analyze each tree
results = []
for tree in trees:
results.append(AnalysisResult(tree, epsilon))
# create the response
out = StringIO()
for result in results:
for line in result.get_response_lines(selected_options):
print >> out, line
print >> out
# return the response
return out.getvalue()
| true |
3d6aab6e684a4a0778ea32525ae325e15673fbc8 | Python | amaotone/competitive-programming | /AtCoder/ABC089/D_practical_skill_test.py | UTF-8 | 390 | 2.78125 | 3 | [] | no_license | H, W, D = map(int, input().split())
p = {}
for i in range(H):
for j, value in enumerate(map(int, input().split())):
p[value] = (i, j)
cost = {}
for i in range(1, W * H + 1):
cost[i] = cost[i - D] + abs(p[i][0] - p[i - D][0]) + abs(p[i][1] - p[i - D][1]) if i > D else 0
Q = int(input())
for _ in range(Q):
L, R = map(int, input().split())
print(cost[R] - cost[L])
| true |
43061213659f7d98a7fab15d7d13875edd770edd | Python | laika-monkey/optimal_estimation | /shiscpltm.py | UTF-8 | 707 | 3.09375 | 3 | [] | no_license |
"""Print the begin and end times of an SHIS file"""
from argparse import ArgumentParser
from datetime import datetime, timedelta
from pyhdf import SD
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('shis_file', help='NetCDF SHIS file')
args = parser.parse_args()
shis_sd = SD.SD(args.shis_file)
print shis_time(shis_sd, 0)
print shis_time(shis_sd, -1)
def shis_time(shis_sd, idx):
year, month, day, second = (
shis_sd.select(v)[idx] for v in ['refTimeYear', 'refTimeMonth', 'refTimeDay',
'refTimeSec'])
return datetime(int(year), int(month), int(day)) + timedelta(seconds=second)
main()
| true |
e76d891134892ec95ce6fc82ce04afc5026e6a0d | Python | haitaoss/flask_study | /flask_code/day02_request/02_upload.py | UTF-8 | 755 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | # coding:utf-8
from flask import Flask, request
import sys
# 创建flask应用
app = Flask(__name__)
@app.route(r'/upload', methods=['POST'])
def upload():
"""接受前段传送过来的文件"""
file_obj = request.files.get('pic')
if file_obj is None:
# 表示没有发送文件
return '未上传文件'
# 将文件保存到本地
# with open('./demo.jpg', 'wb') as f:
# # 向文件写内容
# data = file_obj.read()
# f.write(data)
# 直接使用上传的文件对象里面的save方法保存
file_obj.save("./demo1.jpg")
return '上传成功'
# 启动flask web服务
if __name__ == '__main__':
# print(sys.path)
app.run(host='192.168.205.148', port=8080, debug=True)
| true |
75d8b9493eb19b5d7af213c43017bcbc27dc1080 | Python | LucasCFM/TP-Redes | /app/server/socket_connector.py | UTF-8 | 2,250 | 3.359375 | 3 | [] | no_license | '''
Client UPD connector
implements retransmission of messages sent
'''
import socket, json
from time import sleep
from app.utils.data import byte_to_json, json_to_byte
bufferSize = 1024
# Create a UDP socket at client side
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# UDPServerSocket.bind((localIP, localPort))
class Connector():
def __init__(self, server_ip: str, server_port: int):
global UDPServerSocket
self.server_ip = server_ip
self.server_port = server_port
UDPServerSocket.bind( (server_ip, server_port) )
'''
settimeout
https://stackoverflow.com/questions/2719017/how-to-set-timeout-on-pythons-socket-recv-method
'''
def set_timeout(self, timeout: float):
global UDPServerSocket
UDPServerSocket.settimeout(timeout)
def send_msg(self, byte_msg: bytearray, destiny_address: tuple):
global UDPServerSocket
self.set_timeout(3.0)
print(f'Sending byte msg: {byte_msg}')
print(f'to address: {destiny_address}')
try:
UDPServerSocket.sendto(byte_msg, destiny_address)
except Exception as e:
print('------ Exception while sending msg ------')
print(e)
raise e
# Get Message Example - https://wiki.python.org/moin/UdpCommunication
def get_message(self):
global UDPServerSocket
self.set_timeout(3.0)
try:
bytes_received, client_addrs = UDPServerSocket.recvfrom(bufferSize)
except Exception as e:
print('------ Exception while getting msg ------')
print(e)
print('retrying')
return
print(f'bytes received {bytes_received}')
return bytes_received, client_addrs
# def send_msg_received_confirmation(self, address : tuple):
# print(f'Sending confirmation message')
# confirmation_msg = {
# 'success': True
# }
# confimationByteMsg : bytearray = json_to_byte( confirmation_msg )
# print(f'Sending ...')
# self.send_msg( confimationByteMsg, address )
# print(f'Confirmation message sent!')
| true |
e9286d8b92258dba49ceda01ea0a0a77f551b3c5 | Python | Liset97/Sistema-de-Recuperacion-de-Informacion | /proccon.py | UTF-8 | 2,202 | 2.75 | 3 | [] | no_license | import json
import numpy as np
import procdoc as pd
#Realmente esto no lo hare asi, sino q para utilizar el modulo este tenga que mandar el diccionario de terminos
#
#En ListQuery guardare tuplas de la forma <id_q,text,[vector con todas las palabras]>
#
ListQuery=[]
def Query(query,list_term):
with open('datasets/'+query+'.json') as file:
data = json.load(file)
print(len(list_term))
for i in data:
text=data[i]["text"].lower()
new=text.split(' ')
for j in range(0,len(new)):
temp=new[j]
temp1=temp.split(',')
temp2=temp1[0].split('.')
temp3=temp2[0].split('?')
new[j]=temp3[0]
agregar=[]
for t in new:
if(not(pd.inutiles.__contains__(t))):
agregar.append(t)
tupla=(data[i]["id"],agregar,[0 for x in range(0,len(list_term))])
ListQuery.append(tupla)
count=0
for term in list_term:
for consulta in ListQuery:
suma=len([1 for x in consulta[1] if term==x])
consulta[2][count]=suma
count+=1
def PreparaQuery(text_consulta,id_new,lon_ter,list_term):
text_new=text_consulta.lower()
new=text_new.split(' ')
for j in range(0,len(new)):
temp=new[j]
temp1=temp.split(',')
temp2=temp1[0].split('.')
temp3=temp2[0].split('?')
new[j]=temp3[0]
agregar=[]
for t in new:
if(not(pd.inutiles.__contains__(t))):
agregar.append(t)
tupla=(id_new,agregar,[0 for x in range(0,lon_ter)])
count=0
for term in list_term:
suma=len([1 for x in agregar if term==x])
tupla[2][count]=suma
count+=1
return tupla
print(len(ListQuery))
relevancia={}
def Carga_Relevancia(rel):
with open('datasets/'+rel+'.json') as file:
data = json.load(file)
for i in data:
relevantes=[]
for j in data[i]:
relevantes.append(int(j))
relevancia[i]=relevantes
#print(relevancia)
| true |
e0505c45690be67b1987383e0ffa8b4293df0f82 | Python | KomaTech12/PiperWave3_PersonalPJ | /RasPi/senosrdata.py | UTF-8 | 3,100 | 2.8125 | 3 | [] | no_license | #! /usr/bin/python3
import RPi.GPIO as GPIO
import time
import datetime
import requests
import json
import redis
# Define GPIO Pin
Trigger = 16
Echo = 18
# Connect RedisCloud on PWS
r = redis.Redis(host='XXX', port='XXX', password='XXX')
# Initialize List
r.rpush('point0', 'NoData', 'NoData')
r.rpush('point10', 'NoData', 'NoData')
r.rpush('point20', 'NoData', 'NoData')
r.rpush('point30', 'NoData', 'NoData')
r.rpush('point40', 'NoData', 'NoData')
r.rpush('point50', 'NoData', 'NoData')
# Calculate distance
def checkdist():
GPIO.output(Trigger, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(Trigger, GPIO.LOW)
while not GPIO.input(Echo):
pass
t1 = time.time()
while GPIO.input(Echo):
pass
t2 = time.time()
return (t2-t1)*340/2
# Get the current date and time
def get_date():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
# Shape the sensor data to store DB
def shape_data(distance):
date = get_date()
result = {"distance": distance,
"date": date}
return result
# Set GPIO Pin
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Trigger,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(Echo,GPIO.IN)
### Main code ###
try:
while True:
d = checkdist()
df = "%0.2f" %d
result = shape_data(df)
print ('Distance: %s m' %result["distance"])
print ('Date: %s' %result["date"])
#r.set('date', result["date"])
#r.set('distance', result["distance"])
r.lset('point0', 0, r.lindex('point10', 0))
r.lset('point0', 1, r.lindex('point10', 1))
r.lset('point10', 0, r.lindex('point20', 0))
r.lset('point10', 1, r.lindex('point20', 1))
r.lset('point20', 0, r.lindex('point30', 0))
r.lset('point20', 1, r.lindex('point30', 1))
r.lset('point30', 0, r.lindex('point40', 0))
r.lset('point30', 1, r.lindex('point40', 1))
r.lset('point40', 0, r.lindex('point50', 0))
r.lset('point40', 1, r.lindex('point50', 1))
r.lset('point50', 0, result["date"])
r.lset('point50', 1, result["distance"])
print('point0-0: %s' %r.lindex('point0', 0))
print('point0-1: %s' %r.lindex('point0', 1))
print('point10-0: %s' %r.lindex('point10', 0))
print('point10-1: %s' %r.lindex('point10', 1))
print('point20-0: %s' %r.lindex('point20', 0))
print('point20-1: %s' %r.lindex('point20', 1))
print('point30-0: %s' %r.lindex('point30', 0))
print('point30-1: %s' %r.lindex('point30', 1))
print('point40-0: %s' %r.lindex('point40', 0))
print('point40-1: %s' %r.lindex('point40', 1))
print('point50-0: %s' %r.lindex('point50', 0))
print('point50-1: %s' %r.lindex('point50', 1))
if d < 0.10:
webhook_url = "XXX"
text = "The box is full, please check. XXX"
requests.post(webhook_url, data = json.dumps({
"text": text
}));
time.sleep(10)
except KeyboardInterrupt:
GPIO.cleanup()
print ('GPIO cleeanup and end!')
| true |
373423ca612a7692b22e81dead7a5f45cbcec091 | Python | willyrv/LDA_20newsgroups | /04_compose_matrices.py | UTF-8 | 2,448 | 2.78125 | 3 | [] | no_license | import numpy as np
import os
import h5py
from numpy.core.fromnumeric import size
path2partialresults = "./partial_0-1-2-15_35"
n_points = 140
# Create the files
with h5py.File("./distances_matrix.hdf5", "w") as f:
dset = f.create_dataset('distances', (n_points, n_points),
dtype=np.float, data=np.zeros([n_points, n_points]))
with h5py.File("./max_var_matrix.hdf5", "w") as f:
dset = f.create_dataset('max_variations', (n_points, n_points),
dtype=np.float, data=np.zeros([n_points, n_points]))
# Write the values to the distances matrix and the max_variation matrix
distance_file = h5py.File("./distances_matrix.hdf5", 'r+')
distance_matrix = distance_file['distances']
max_var_file = h5py.File("./max_var_matrix.hdf5", 'r+')
max_var_matrix = max_var_file['max_variations']
for i in range(n_points):
for j in range(i+1, n_points):
path = os.path.join(path2partialresults, "{}_{}_polyn_dist.txt".format(i, j))
with open(path, 'r') as f:
value = float(f.read())
distance_matrix[i, j] = value
distance_matrix[j, i] = value
path = os.path.join(path2partialresults, "{}_{}_max_var.txt".format(i, j))
with open(path, 'r') as f:
value = float(f.read())
max_var_matrix[i, j] = value
max_var_matrix[j, i] = value
distance_file.close()
max_var_file.close()
def test_matrix(path2partialresults, matrix_filename,
sufix = "_polyn_dist.txt", nvalues=100):
"""
Test if the matrix have been correctly created, i.e. verify that the content
of the file {papath2partialresults}/{i}_{j}_polyn_dist.txt be equal to the
value in Matrix[i, j].
The matrix is stored in hdf5 format.
ntimes: Number values to test
"""
f = h5py.File(matrix_filename, 'r')
data = f[list(f.keys())[0]]
n = data.shape[0]
pairs = np.random.randint(0, n, size=[nvalues, 2])
nb_errors = 0
for (i, j) in pairs:
row, column = np.sort([i, j])
if row == column:
column+=1
fname = os.path.join(path2partialresults, "{}_{}{}".format(row, column, sufix))
with open(fname, 'r') as f:
value = float(f.read())
if data[row, column] != value:
print("Problem with {}, {}".format(row, column))
nb_errors +=1
f.close()
print("{} errors detected".format(nb_errors))
| true |
9942d7eca5555f8e1d29f3184746a7e5d41a573d | Python | Ogaday/sapi-python-client | /tests/test_base.py | UTF-8 | 1,867 | 2.53125 | 3 | [
"MIT"
] | permissive | import unittest
import os
from requests import HTTPError
from kbcstorage.base import Endpoint
class TestEndpoint(unittest.TestCase):
"""
Test Endpoint functionality.
"""
def setUp(self):
self.root = os.getenv('KBC_TEST_API_URL')
self.token = 'some-token'
def test_get(self):
endpoint = Endpoint(self.root, '', self.token)
self.assertEqual(os.getenv('KBC_TEST_API_URL'), endpoint.root_url)
self.assertEqual(os.getenv('KBC_TEST_API_URL') + '/v2/storage/',
endpoint.base_url)
self.assertEqual('some-token',
endpoint.token)
def test_get_404(self):
endpoint = Endpoint(self.root, 'not-a-url', self.token)
self.assertEqual(os.getenv('KBC_TEST_API_URL') +
'/v2/storage/not-a-url',
endpoint.base_url)
with self.assertRaises(HTTPError):
endpoint.get(endpoint.base_url)
def test_get_404_2(self):
endpoint = Endpoint(self.root, '', self.token)
self.assertEqual(os.getenv('KBC_TEST_API_URL') +
'/v2/storage/',
endpoint.base_url)
with self.assertRaises(HTTPError):
endpoint.get('{}/not-a-url'.format(endpoint.base_url))
def test_post_404(self):
"""
Post to inexistent resource raises HTTPError.
"""
endpoint = Endpoint(self.root, '', self.token)
with self.assertRaises(HTTPError):
endpoint.post('{}/not-a-url'.format(endpoint.base_url))
def test_delete_404(self):
"""
Delete inexistent resource raises HTTPError.
"""
endpoint = Endpoint(self.root, 'delete', self.token)
with self.assertRaises(HTTPError):
endpoint.delete('{}/not-a-url'.format(endpoint.base_url))
| true |
269d8ad77c16e79e6cf8a1b1107e5a8ad29f0bb8 | Python | shg9411/algo | /algo_py/boj/bj4179.py | UTF-8 | 1,633 | 2.96875 | 3 | [] | no_license | import sys
from collections import deque
input = sys.stdin.readline
R, C = map(int, input().split())
visited = [[False for _ in range(C)] for _ in range(R)]
miro = []
jh = deque()
fire = deque()
for i in range(R):
miro.append(list(input().rstrip()))
for j in range(C):
if miro[i][j] == '.':
continue
visited[i][j] = True
if miro[i][j] == 'J':
jh.append([i, j])
elif miro[i][j] == 'F':
fire.append([i, j])
cnt = 0
while jh:
cnt += 1
for _ in range(len(fire)):
i, j = fire.popleft()
if i > 0 and not visited[i-1][j]:
visited[i-1][j] = True
fire.append([i-1, j])
if i < R-1 and not visited[i+1][j]:
visited[i+1][j] = True
fire.append([i+1, j])
if j > 0 and not visited[i][j-1]:
visited[i][j-1] = True
fire.append([i, j-1])
if j < C-1 and not visited[i][j+1]:
visited[i][j+1] = True
fire.append([i, j+1])
for _ in range(len(jh)):
i, j = jh.popleft()
if i == 0 or i == R-1 or j == 0 or j == C-1:
print(cnt)
exit()
if i > 0 and not visited[i-1][j]:
visited[i-1][j] = True
jh.append([i-1, j])
if i < R-1 and not visited[i+1][j]:
visited[i+1][j] = True
jh.append([i+1, j])
if j > 0 and not visited[i][j-1]:
visited[i][j-1] = True
jh.append([i, j-1])
if j < C-1 and not visited[i][j+1]:
visited[i][j+1] = True
jh.append([i, j+1])
print("IMPOSSIBLE") | true |
ca90af8d771c85e2eed9db230c04107892991026 | Python | AA19BD/PythonSummer | /Python-Inform/Списки/B.py | UTF-8 | 104 | 3.03125 | 3 | [] | no_license | l=list(map(int,input().split()))
for i in range(len(l)):
if l[i]%2==0:
print(l[i],end=" ") | true |
3ac18ff7eeafa8029801bd57b763f549c039d7c0 | Python | Saurabh23/Sentiment-Analysis-for-Predicting-Elections | /tweetsPreProcessing/pos_tagging.py | UTF-8 | 755 | 2.640625 | 3 | [] | no_license | import sys
import nltk
from nltk import word_tokenize, pos_tag
TAGFILE = 'tags.csv'
def collectPOSTAGS():
f = open(TAGFILE,'r+')
tags = f.read().split('\n')
print tags
return tags
def main(filename):
f = open(filename, 'r+')
text = f.read()
text = ''.join((c for c in text if 0 < ord(c) < 127))
tweets = text.split('\n')
tags = collectPOSTAGS()
fwtags = open(filename.split('.')[0]+'-selectedtags.csv','w')
for tweet in tweets:
words = word_tokenize(tweet)
taggedWords = pos_tag(words)
taggedWords = [tag for tag in taggedWords if tag[1] in tags]
bagofwords = ' '.join([w[0] for w in taggedWords])
if tweet != '':
fwtags.write(tweet+'>'+bagofwords+'\n')
f.close()
fwtags.close()
if __name__ == "__main__":
main(sys.argv[1])
| true |
07e5b243d0129b71b7a7ac8e58f2b8cf97e70580 | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4132/codes/1836_1273.py | UTF-8 | 172 | 2.5625 | 3 | [] | no_license | from numpy import *
from numpy.linalg import *
mat = array([[1,-1,0,0],[0,1,-1,0],[0,0,1,0],[1,0,0,1]])
vet= array([50,-120,350,870])
flu=dot(inv(mat),vet.T)
print(flu)
| true |
7043613876ad13d253f842eb1e45870ec5c3ad60 | Python | beddingearly/LMM | /151_Reverse_Words_in_a_String.py | UTF-8 | 494 | 3.390625 | 3 | [] | no_license | # coding=utf-8
'''
@Time : 2018/11/27 12:36
@Author : Zt.Wang
@Email : 137602260@qq.com
@File : 151_Reverse_Words_in_a_String.py
@Software: PyCharm
'''
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
a = s.strip().split(" ")
a.reverse()
while '' in a:
a.remove('')
return " ".join(a).strip()
if __name__ == '__main__':
a = Solution()
print a.reverseWords(" a b ") | true |
b5c88eb87bc7a303bebd4d1dd4975fb046a1ed07 | Python | Userfix/pytrain | /generator/contact.py | UTF-8 | 2,071 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
import string
import random
import os
import jsonpickle
import getopt
import sys
from model.contact import Contact
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 3
f = "data/contacts.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*5
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def random_phone(prefix, maxlen):
symbols = string.digits + "()-+ "*5
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def random_email(prefix, maxlen):
symbols = string.ascii_lowercase + string.digits + "-+_."*10
return prefix + "".join([(random.choice(symbols)+"@qwerty.com") for i in range(random.randrange(maxlen))])
testdata = [Contact(firstname="", middlename="", lastname="", nickname="",
title="", company="", address="", homephone="", email1=""
)] + [Contact(firstname=random_string("firstname", 10),
middlename=random_string("middlename", 20),
lastname=random_string("lastname", 15),
nickname=random_string("nickname", 15),
title=random_string("title", 15),
company=random_string("company", 15),
address=random_string("address", 15),
homephone=random_phone("phone-", 15),
email1=random_email("email-", 2)
)
for i in range(n)
]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as out:
jsonpickle.set_encoder_options("json", indent=2)
out.write(jsonpickle.encode(testdata))
| true |
ece0e047a17f1961c134614fce6eea3c3c69f4eb | Python | nabendu96/end_sem | /Q_8.py | UTF-8 | 1,435 | 3.46875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 12:04:59 2020
@author: nabendu
"""
#question_8
#solving boundary value problem #relaxation method
import numpy as np
import matplotlib.pyplot as plt
#boundary conditions
x0=0
y0=0
xf=1
yf=2
N=100 #number of mesh points
x=np.linspace(x0,xf,N)
h=(xf-x0)/(N-1)
target=0.00001 #target accuracy
y=np.zeros(N)
y[0]=y0
y[-1]=yf
solutions=[]
yprime=np.zeros(N)
count=0
#finding solution using relaxation
for m in range(1000000):
for i in range(N):
if(i==0 or i==N-1):
yprime[i]=y[i]
else:
yprime[i]=(y[i+1]+y[i-1]+4*h*h*x[i])/(2+4*h*h)
delta=max(abs(y-yprime))
for j in range(N):
y[j]=yprime[j]
if(delta<target): #checking accuracy condition
break
yexact=x+(np.exp(2)*(np.exp(2*x)-np.exp(-2*x)))/(np.exp(4)-1) #exact solution
plt.plot(x,y,'r',label=r'numerical result') #numerical solution
plt.plot(x,yexact,'--b',label=r'exact solution') #exact solution
plt.xlabel(r'$x$',fontsize=20)
plt.ylabel(r'$y$',fontsize=20)
plt.legend()
plt.show()
#calculating the relative % errors
yerr=np.zeros(N)
#due to relaxation method
yerr[0]=0
yerr[-1]=0
for k in range(N-2):
yerr[k+1]=(abs(y[k+1]-yexact[k+1])/yexact[k+1])*100
print('The relative % errors at each x step are \n',yerr)
| true |
10eeb83ede14cb92eab532560d99bf3906149c9b | Python | Niklesh99/Vehicle-Detection-and-tracking-count-using-OpenCV | /main2.py | UTF-8 | 3,000 | 3.03125 | 3 | [] | no_license | import cv2
import numpy as np
from time import sleep
width_min=80 #MIN WIDHT
height_min=80 #min height
offset=6
pos_line=550 #LINE POSITION
delay= 60 # VIDEO FPS
detect = []
cars= 0 # NO of CARS
def takes_center(x, y, w, h): # FRAME CENTER
x1 = int(w / 2)
y1 = int(h / 2)
cx = x + x1
cy = y + y1
return cx,cy
cap = cv2.VideoCapture('video.mp4') #Importing Video
subraction = cv2.bgsegm.createBackgroundSubtractorMOG() #Subraction Creation
while True:
ret , frame1 = cap.read() # read frames from video
temp = float(1/delay)
sleep(temp)
grey = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY) # converts frame to GREY Scale
blur = cv2.GaussianBlur(grey,(3,3),5) # converts gaussian blur
img_sub = subraction.apply(blur)
dilate = cv2.dilate(img_sub,np.ones((5,5))) #apply morphological filter to image
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) #Ellipse morphing image
detected = cv2.morphologyEx (dilate, cv2. MORPH_CLOSE , kernel)
detected = cv2.morphologyEx (detected, cv2. MORPH_CLOSE , kernel)
contour,h=cv2.findContours(detected,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #find Contours in frame
cv2.line(frame1, (25, pos_line), (1200, pos_line), (255,127,0), 3) #draw lines on the frames
for(i,c) in enumerate(contour):
(x,y,w,h) = cv2.boundingRect(c) #used to draw rect on the frame ROI
valid_contour = (w >= width_min) and (h >= height_min) #rect valid only if it is in the frame
if not valid_contour: #Not valid if it is outside
continue
cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) #drawing rectangle on ROI
centre = takes_center(x, y, w, h) #while crossing center
detect.append(centre) #Appending detect list
cv2.circle(frame1, centre, 4, (0, 0,255), -1)
for (x,y) in detect: #if cars crossing the line
if y<(pos_line+offset) and y>(pos_line-offset):
cars+=1 # add Count
cv2.line(frame1, (25, pos_line), (1200, pos_line), (0,127,255), 3) #draw line in frame
detect.remove((x,y)) # remove rect after crossing the line
print("car is detected : "+str(cars))
cv2.putText(frame1, "VEHICLE COUNT : "+str(cars), (450, 70), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),5)
cv2.imshow("Video Original" , frame1) #DIsplay Video and COUNT
cv2.imshow("Detected",detected)
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
cap.release() | true |
d0318b34c85c17585a4252bebfba21f81c3a005c | Python | masumrumi/Parser | /Parser.py | UTF-8 | 4,802 | 3.1875 | 3 | [] | no_license | # resources
# https://sly.readthedocs.io/en/latest/sly.html
# how to run:
# step one:
# pip install sly
# step two:
# python Parser.py
# step three:
# "language >" will show up.
# step 4:
# test the following programs.
# a = 7
# a = 3+4*8
# a = (4+7)*5
from sly import Lexer
from sly import Parser
class BasicLexer(Lexer):
def __init__(self):
self.nesting_level = 0
tokens = {ID, NUMBER, STRING}
ignore = '\t '
literals = {'=', '+', '-', '/', '{', '}',
'*', '(', ')', ',', ';'}
# Define tokens as regular expressions
# (stored as raw strings)
ID = r'[a-zA-Z_][a-zA-Z0-9_]*'
STRING = r'\".*?\"'
# LPAREN = r'\('
# RPAREN = r'\)'
# Number token
@_(r'\d+')
def NUMBER(self, t):
# convert it into a python integer
t.value = int(t.value)
return t
# Comment token
@_(r'//.*')
def COMMENT(self, t):
pass
# Newline token(used only for showing
# errors in new line)
@_(r'\n+')
def newline(self, t):
self.lineno = t.value.count('\n')
@_(r'\{')
def lbrace(self, t):
t.type = '{' # Set token type to the expected literal
self.nesting_level += 1
return t
@_(r'\}')
def rbrace(self, t):
t.type = '}' # Set token type to the expected literal
self.nesting_level -= 1
return t
# Error handling rule
def error(self, t):
print("Illegal character '%s'" % t.value[0])
self.index += 1
class BasicParser(Parser):
# tokens are passed from lexer to parser
tokens = BasicLexer.tokens
precedence = (
('left', '+', '-'),
('left', '*', '/'),
('right', 'UMINUS'),
)
def __init__(self):
self.env = {}
@_('')
def statement(self, p):
pass
@_('var_assign')
def statement(self, p):
return p.var_assign
@_('ID "=" expr')
def var_assign(self, p):
return ('var_assign', p.ID, p.expr)
@_('ID "=" STRING')
def var_assign(self, p):
return ('var_assign', p.ID, p.STRING)
@_('expr')
def statement(self, p):
return (p.expr)
@_('"-" expr %prec UMINUS')
def expr(self, p):
return p.expr
# Grammar rules and actions
@_('expr "+" term')
def expr(self, p):
return p.expr + p.term
@_('expr "-" term')
def expr(self, p):
return p.expr - p.term
@_('term')
def expr(self, p):
return p.term
@_('term "*" factor')
def term(self, p):
return p.term * p.factor
@_('term "/" factor')
def term(self, p):
return p.term / p.factor
@_('factor')
def term(self, p):
return p.factor
@_('ID')
def expr(self, p):
return ('var', p.ID)
@_('NUMBER')
def factor(self, p):
return p.NUMBER
@_('"(" expr ")"')
def factor(self, p):
return p.expr
class BasicExecute:
def __init__(self, tree, env):
self.env = env
result = self.walkTree(tree)
if result is not None and isinstance(result, int):
print(result)
if isinstance(result, str) and result[0] == '"':
print(result)
def walkTree(self, node):
if isinstance(node, int):
return node
if isinstance(node, str):
return node
if node is None:
return None
if node[0] == 'program':
if node[1] == None:
self.walkTree(node[2])
else:
self.walkTree(node[1])
self.walkTree(node[2])
if node[0] == 'num':
return node[1]
if node[0] == 'str':
return node[1]
if node[0] == 'add':
return self.walkTree(node[1]) + self.walkTree(node[2])
elif node[0] == 'sub':
return self.walkTree(node[1]) - self.walkTree(node[2])
elif node[0] == 'mul':
return self.walkTree(node[1]) * self.walkTree(node[2])
elif node[0] == 'div':
return self.walkTree(node[1]) / self.walkTree(node[2])
if node[0] == 'var_assign':
self.env[node[1]] = self.walkTree(node[2])
return node[1]
if node[0] == 'var':
try:
return self.env[node[1]]
except LookupError:
print("Undefined variable '"+node[1]+"' found!")
return 0
if __name__ == '__main__':
lexer = BasicLexer()
parser = BasicParser()
print('Start')
env = {}
while True:
try:
text = input('my_parser > ')
except EOFError:
break
if text:
tree = parser.parse(lexer.tokenize(text))
BasicExecute(tree, env)
| true |
b1befa1dc28e90bd65798aa04eb7c7e48ae89977 | Python | quigleyj97/COS125Project2 | /ControllerIntegration.py | UTF-8 | 1,781 | 3.3125 | 3 | [] | no_license | import pygame
import math
pygame.init()
gameDisplay = pygame.display.set_mode((800,600))
gameExit = False
x_coord = 300
y_coord = 300
joystick = pygame.joystick.Joystick(0)
joystick.init()
axes = joystick.get_numaxes()
## 0=Left_Stick X-axis, Left == Negative, Right == Positive
## 1=Left_Stick Y-axis, Up == Negative, Down == Positive
## 2=Triggers, Right == Negative, Left == Positive
## 3=Right_Stick Y-axis, Up == Negative, Down == Positive
## 4=Right_Stick X-axis, Left == Negative, Right == Positive
triangle = pygame.image.load("triangle.png")
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
def angle(x,y):
if y <0 and x >0:
y*=-1
answer = math.atan(y/x)
return 270+math.degrees(answer)
elif y<0 and x<0:
y*=-1
x*=-1
answer = 360 - math.atan(y/x)
return math.degrees(answer)
elif y>0 and x<0:
x*=-1
answer = 90+ math.atan(y/x)
return math.degrees(answer)
else:
answer = 180 - math.atan(y/x)
return math.degrees(answer)
x_coord += joystick.get_axis(0)
y_coord += joystick.get_axis(1)
def rot_center(image, angle):
loc = image.get_rect().center
rot_sprite = pygame.transform.rotate(image, angle)
rot_sprite.get_rect().center = loc
return rot_sprite
x_coordAngle = joystick.get_axis(4)+.0001
y_coordAngle = joystick.get_axis(3)+.0001
head = rot_center(triangle, angle(x_coordAngle, y_coordAngle))
gameDisplay.fill((255,255,255))
gameDisplay.blit(head,(x_coord,y_coord))
pygame.display.update()
pygame.quit()
quit
| true |
76cf9699e77955b893f57c6c7309f60b189eb60a | Python | stankevichea/daftacademy-python4beginners-autumn2018 | /Python_Funkcjonalny_Kod/praca_domowa/zadanie5.py | UTF-8 | 1,007 | 4.15625 | 4 | [] | no_license | # Zadanie 5
# Napisz 2 funkcje:
# Jedna o nazwie prime ma sprawdzić czy zadana liczba <n> jest liczbą pierwszą
# zwracając True/False
# Druga funkcja twins ma sprawdzić czy danae liczbay <n>, <k> są liczbami bliźniaczymi.
# Funkcja może przyjmować też jeden parametr
# Jeżeli podana liczba jest liczbą bliźniaczą zwróć jej bliźniaka,
# Jeżli nie jest bliźniacza to zwróć False
# Obie funkcje mają przyjmować liczby naturalne. Podanie innej liczby niż
# naturalna w wymaganym parametrze ma skutkować zwróceniem None
# Definicja 1: Liczba Pierwsza to liczba naturalna większa od 1,
# która ma dokładnie dwa dzielniki naturalne: jedynkę i siebie samą
# Definicja 2: Liczby bliźniacze to takie dwie liczby pierwsze, których różnica
# wynosi 2.
# Przydatne linki:
# https://stackoverflow.com/questions/18833759/python-prime-number-checker
assert prime(101) == True
assert prime("22") == None
assert twins(101) == 103
assert twins(79) == False
assert twins(5, 7) == True
| true |
06381128e7ca315951502a097c6e24ad8881caa1 | Python | jkjung-avt/tensorrt_demos | /utils/mtcnn.py | UTF-8 | 17,091 | 2.875 | 3 | [
"MIT",
"CC-BY-NC-SA-4.0",
"Apache-2.0"
] | permissive | """mtcnn_trt.py
"""
import numpy as np
import cv2
import pytrt
PIXEL_MEAN = 127.5
PIXEL_SCALE = 0.0078125
def convert_to_1x1(boxes):
"""Convert detection boxes to 1:1 sizes
# Arguments
boxes: numpy array, shape (n,5), dtype=float32
# Returns
boxes_1x1
"""
boxes_1x1 = boxes.copy()
hh = boxes[:, 3] - boxes[:, 1] + 1.
ww = boxes[:, 2] - boxes[:, 0] + 1.
mm = np.maximum(hh, ww)
boxes_1x1[:, 0] = boxes[:, 0] + ww * 0.5 - mm * 0.5
boxes_1x1[:, 1] = boxes[:, 1] + hh * 0.5 - mm * 0.5
boxes_1x1[:, 2] = boxes_1x1[:, 0] + mm - 1.
boxes_1x1[:, 3] = boxes_1x1[:, 1] + mm - 1.
boxes_1x1[:, 0:4] = np.fix(boxes_1x1[:, 0:4])
return boxes_1x1
def crop_img_with_padding(img, box, padding=0):
"""Crop a box from image, with out-of-boundary pixels padded
# Arguments
img: img as a numpy array, shape (H, W, 3)
box: numpy array, shape (5,) or (4,)
padding: integer value for padded pixels
# Returns
cropped_im: cropped image as a numpy array, shape (H, W, 3)
"""
img_h, img_w, _ = img.shape
if box.shape[0] == 5:
cx1, cy1, cx2, cy2, _ = box.astype(int)
elif box.shape[0] == 4:
cx1, cy1, cx2, cy2 = box.astype(int)
else:
raise ValueError
cw = cx2 - cx1 + 1
ch = cy2 - cy1 + 1
cropped_im = np.zeros((ch, cw, 3), dtype=np.uint8) + padding
ex1 = max(0, -cx1) # ex/ey's are the destination coordinates
ey1 = max(0, -cy1)
ex2 = min(cw, img_w - cx1)
ey2 = min(ch, img_h - cy1)
fx1 = max(cx1, 0) # fx/fy's are the source coordinates
fy1 = max(cy1, 0)
fx2 = min(cx2+1, img_w)
fy2 = min(cy2+1, img_h)
cropped_im[ey1:ey2, ex1:ex2, :] = img[fy1:fy2, fx1:fx2, :]
return cropped_im
def nms(boxes, threshold, type='Union'):
"""Non-Maximum Supression
# Arguments
boxes: numpy array [:, 0:5] of [x1, y1, x2, y2, score]'s
threshold: confidence/score threshold, e.g. 0.5
type: 'Union' or 'Min'
# Returns
A list of indices indicating the result of NMS
"""
if boxes.shape[0] == 0:
return []
xx1, yy1, xx2, yy2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
areas = np.multiply(xx2-xx1+1, yy2-yy1+1)
sorted_idx = boxes[:, 4].argsort()
pick = []
while len(sorted_idx) > 0:
# In each loop, pick the last box (highest score) and remove
# all other boxes with IoU over threshold
tx1 = np.maximum(xx1[sorted_idx[-1]], xx1[sorted_idx[0:-1]])
ty1 = np.maximum(yy1[sorted_idx[-1]], yy1[sorted_idx[0:-1]])
tx2 = np.minimum(xx2[sorted_idx[-1]], xx2[sorted_idx[0:-1]])
ty2 = np.minimum(yy2[sorted_idx[-1]], yy2[sorted_idx[0:-1]])
tw = np.maximum(0.0, tx2 - tx1 + 1)
th = np.maximum(0.0, ty2 - ty1 + 1)
inter = tw * th
if type == 'Min':
iou = inter / \
np.minimum(areas[sorted_idx[-1]], areas[sorted_idx[0:-1]])
else:
iou = inter / \
(areas[sorted_idx[-1]] + areas[sorted_idx[0:-1]] - inter)
pick.append(sorted_idx[-1])
sorted_idx = sorted_idx[np.where(iou <= threshold)[0]]
return pick
def generate_pnet_bboxes(conf, reg, scale, t):
"""
# Arguments
conf: softmax score (face or not) of each grid
reg: regression values of x1, y1, x2, y2 coordinates.
The values are normalized to grid width (12) and
height (12).
scale: scale-down factor with respect to original image
t: confidence threshold
# Returns
A numpy array of bounding box coordinates and the
cooresponding scores: [[x1, y1, x2, y2, score], ...]
# Notes
Top left corner coordinates of each grid is (x*2, y*2),
or (x*2/scale, y*2/scale) in the original image.
Bottom right corner coordinates is (x*2+12-1, y*2+12-1),
or ((x*2+12-1)/scale, (y*2+12-1)/scale) in the original
image.
"""
conf = conf.T # swap H and W dimensions
dx1 = reg[0, :, :].T
dy1 = reg[1, :, :].T
dx2 = reg[2, :, :].T
dy2 = reg[3, :, :].T
(x, y) = np.where(conf >= t)
if len(x) == 0:
return np.zeros((0, 5), np.float32)
score = np.array(conf[x, y]).reshape(-1, 1) # Nx1
reg = np.array([dx1[x, y], dy1[x, y],
dx2[x, y], dy2[x, y]]).T * 12. # Nx4
topleft = np.array([x, y], dtype=np.float32).T * 2. # Nx2
bottomright = topleft + np.array([11., 11.], dtype=np.float32) # Nx2
boxes = (np.concatenate((topleft, bottomright), axis=1) + reg) / scale
boxes = np.concatenate((boxes, score), axis=1) # Nx5
# filter bboxes which are too small
#boxes = boxes[boxes[:, 2]-boxes[:, 0] >= 12., :]
#boxes = boxes[boxes[:, 3]-boxes[:, 1] >= 12., :]
return boxes
def generate_rnet_bboxes(conf, reg, pboxes, t):
"""
# Arguments
conf: softmax score (face or not) of each box
reg: regression values of x1, y1, x2, y2 coordinates.
The values are normalized to box width and height.
pboxes: input boxes to RNet
t: confidence threshold
# Returns
boxes: a numpy array of box coordinates and cooresponding
scores: [[x1, y1, x2, y2, score], ...]
"""
boxes = pboxes.copy() # make a copy
assert boxes.shape[0] == conf.shape[0]
boxes[:, 4] = conf # update 'score' of all boxes
boxes = boxes[conf >= t, :]
reg = reg[conf >= t, :]
ww = (boxes[:, 2]-boxes[:, 0]+1).reshape(-1, 1) # x2 - x1 + 1
hh = (boxes[:, 3]-boxes[:, 1]+1).reshape(-1, 1) # y2 - y1 + 1
boxes[:, 0:4] += np.concatenate((ww, hh, ww, hh), axis=1) * reg
return boxes
def generate_onet_outputs(conf, reg_boxes, reg_marks, rboxes, t):
"""
# Arguments
conf: softmax score (face or not) of each box
reg_boxes: regression values of x1, y1, x2, y2
The values are normalized to box width and height.
reg_marks: regression values of the 5 facial landmark points
rboxes: input boxes to ONet (already converted to 2x1)
t: confidence threshold
# Returns
boxes: a numpy array of box coordinates and cooresponding
scores: [[x1, y1, x2, y2,... , score], ...]
landmarks: a numpy array of facial landmark coordinates:
[[x1, x2, ..., x5, y1, y2, ..., y5], ...]
"""
boxes = rboxes.copy() # make a copy
assert boxes.shape[0] == conf.shape[0]
boxes[:, 4] = conf
boxes = boxes[conf >= t, :]
reg_boxes = reg_boxes[conf >= t, :]
reg_marks = reg_marks[conf >= t, :]
xx = boxes[:, 0].reshape(-1, 1)
yy = boxes[:, 1].reshape(-1, 1)
ww = (boxes[:, 2]-boxes[:, 0]).reshape(-1, 1)
hh = (boxes[:, 3]-boxes[:, 1]).reshape(-1, 1)
marks = np.concatenate((xx, xx, xx, xx, xx, yy, yy, yy, yy, yy), axis=1)
marks += np.concatenate((ww, ww, ww, ww, ww, hh, hh, hh, hh, hh), axis=1) * reg_marks
ww = ww + 1
hh = hh + 1
boxes[:, 0:4] += np.concatenate((ww, hh, ww, hh), axis=1) * reg_boxes
return boxes, marks
def clip_dets(dets, img_w, img_h):
"""Round and clip detection (x1, y1, ...) values.
Note we exclude the last value of 'dets' in computation since
it is 'conf'.
"""
dets[:, 0:-1] = np.fix(dets[:, 0:-1])
evens = np.arange(0, dets.shape[1]-1, 2)
odds = np.arange(1, dets.shape[1]-1, 2)
dets[:, evens] = np.clip(dets[:, evens], 0., float(img_w-1))
dets[:, odds] = np.clip(dets[:, odds], 0., float(img_h-1))
return dets
class TrtPNet(object):
"""TrtPNet
Refer to mtcnn/det1_relu.prototxt for calculation of input/output
dimmensions of TrtPNet, as well as input H offsets (for all scales).
The output H offsets are merely input offsets divided by stride (2).
"""
input_h_offsets = (0, 216, 370, 478, 556, 610, 648, 676, 696)
output_h_offsets = (0, 108, 185, 239, 278, 305, 324, 338, 348)
max_n_scales = 9
def __init__(self, engine):
"""__init__
# Arguments
engine: path to the TensorRT engine file
"""
self.trtnet = pytrt.PyTrtMtcnn(engine,
(3, 710, 384),
(2, 350, 187),
(4, 350, 187))
self.trtnet.set_batchsize(1)
def detect(self, img, minsize=40, factor=0.709, threshold=0.7):
"""Detect faces using PNet
# Arguments
img: input image as a RGB numpy array
threshold: confidence threshold
# Returns
A numpy array of bounding box coordinates and the
cooresponding scores: [[x1, y1, x2, y2, score], ...]
"""
if minsize < 40:
raise ValueError("TrtPNet is currently designed with "
"'minsize' >= 40")
if factor > 0.709:
raise ValueError("TrtPNet is currently designed with "
"'factor' <= 0.709")
m = 12.0 / minsize
img_h, img_w, _ = img.shape
minl = min(img_h, img_w) * m
# create scale pyramid
scales = []
while minl >= 12:
scales.append(m)
m *= factor
minl *= factor
if len(scales) > self.max_n_scales: # probably won't happen...
raise ValueError('Too many scales, try increasing minsize '
'or decreasing factor.')
total_boxes = np.zeros((0, 5), dtype=np.float32)
img = (img.astype(np.float32) - PIXEL_MEAN) * PIXEL_SCALE
# stack all scales of the input image vertically into 1 big
# image, and only do inferencing once
im_data = np.zeros((1, 3, 710, 384), dtype=np.float32)
for i, scale in enumerate(scales):
h_offset = self.input_h_offsets[i]
h = int(img_h * scale)
w = int(img_w * scale)
im_data[0, :, h_offset:(h_offset+h), :w] = \
cv2.resize(img, (w, h)).transpose((2, 0, 1))
out = self.trtnet.forward(im_data)
# extract outputs of each scale from the big output blob
for i, scale in enumerate(scales):
h_offset = self.output_h_offsets[i]
h = (int(img_h * scale) - 12) // 2 + 1
w = (int(img_w * scale) - 12) // 2 + 1
pp = out['prob1'][0, 1, h_offset:(h_offset+h), :w]
cc = out['boxes'][0, :, h_offset:(h_offset+h), :w]
boxes = generate_pnet_bboxes(pp, cc, scale, threshold)
if boxes.shape[0] > 0:
pick = nms(boxes, 0.5, 'Union')
if len(pick) > 0:
boxes = boxes[pick, :]
if boxes.shape[0] > 0:
total_boxes = np.concatenate((total_boxes, boxes), axis=0)
if total_boxes.shape[0] == 0:
return total_boxes
pick = nms(total_boxes, 0.7, 'Union')
dets = clip_dets(total_boxes[pick, :], img_w, img_h)
return dets
def destroy(self):
self.trtnet.destroy()
self.trtnet = None
class TrtRNet(object):
"""TrtRNet
# Arguments
engine: path to the TensorRT engine (det2) file
"""
def __init__(self, engine):
self.trtnet = pytrt.PyTrtMtcnn(engine,
(3, 24, 24),
(2, 1, 1),
(4, 1, 1))
def detect(self, img, boxes, max_batch=256, threshold=0.6):
"""Detect faces using RNet
# Arguments
img: input image as a RGB numpy array
boxes: detection results by PNet, a numpy array [:, 0:5]
of [x1, y1, x2, y2, score]'s
max_batch: only process these many top boxes from PNet
threshold: confidence threshold
# Returns
A numpy array of bounding box coordinates and the
cooresponding scores: [[x1, y1, x2, y2, score], ...]
"""
if max_batch > 256:
raise ValueError('Bad max_batch: %d' % max_batch)
boxes = boxes[:max_batch] # assuming boxes are sorted by score
if boxes.shape[0] == 0:
return boxes
img_h, img_w, _ = img.shape
boxes = convert_to_1x1(boxes)
crops = np.zeros((boxes.shape[0], 24, 24, 3), dtype=np.uint8)
for i, det in enumerate(boxes):
cropped_im = crop_img_with_padding(img, det)
# NOTE: H and W dimensions need to be transposed for RNet!
crops[i, ...] = cv2.transpose(cv2.resize(cropped_im, (24, 24)))
crops = crops.transpose((0, 3, 1, 2)) # NHWC -> NCHW
crops = (crops.astype(np.float32) - PIXEL_MEAN) * PIXEL_SCALE
self.trtnet.set_batchsize(crops.shape[0])
out = self.trtnet.forward(crops)
pp = out['prob1'][:, 1, 0, 0]
cc = out['boxes'][:, :, 0, 0]
boxes = generate_rnet_bboxes(pp, cc, boxes, threshold)
if boxes.shape[0] == 0:
return boxes
pick = nms(boxes, 0.7, 'Union')
dets = clip_dets(boxes[pick, :], img_w, img_h)
return dets
def destroy(self):
self.trtnet.destroy()
self.trtnet = None
class TrtONet(object):
"""TrtONet
# Arguments
engine: path to the TensorRT engine (det3) file
"""
def __init__(self, engine):
self.trtnet = pytrt.PyTrtMtcnn(engine,
(3, 48, 48),
(2, 1, 1),
(4, 1, 1),
(10, 1, 1))
def detect(self, img, boxes, max_batch=64, threshold=0.7):
"""Detect faces using ONet
# Arguments
img: input image as a RGB numpy array
boxes: detection results by RNet, a numpy array [:, 0:5]
of [x1, y1, x2, y2, score]'s
max_batch: only process these many top boxes from RNet
threshold: confidence threshold
# Returns
dets: boxes and conf scores
landmarks
"""
if max_batch > 64:
raise ValueError('Bad max_batch: %d' % max_batch)
if boxes.shape[0] == 0:
return (np.zeros((0, 5), dtype=np.float32),
np.zeros((0, 10), dtype=np.float32))
boxes = boxes[:max_batch] # assuming boxes are sorted by score
img_h, img_w, _ = img.shape
boxes = convert_to_1x1(boxes)
crops = np.zeros((boxes.shape[0], 48, 48, 3), dtype=np.uint8)
for i, det in enumerate(boxes):
cropped_im = crop_img_with_padding(img, det)
# NOTE: H and W dimensions need to be transposed for RNet!
crops[i, ...] = cv2.transpose(cv2.resize(cropped_im, (48, 48)))
crops = crops.transpose((0, 3, 1, 2)) # NHWC -> NCHW
crops = (crops.astype(np.float32) - PIXEL_MEAN) * PIXEL_SCALE
self.trtnet.set_batchsize(crops.shape[0])
out = self.trtnet.forward(crops)
pp = out['prob1'][:, 1, 0, 0]
cc = out['boxes'][:, :, 0, 0]
mm = out['landmarks'][:, :, 0, 0]
boxes, landmarks = generate_onet_outputs(pp, cc, mm, boxes, threshold)
pick = nms(boxes, 0.7, 'Min')
return (clip_dets(boxes[pick, :], img_w, img_h),
np.fix(landmarks[pick, :]))
def destroy(self):
self.trtnet.destroy()
self.trtnet = None
class TrtMtcnn(object):
"""TrtMtcnn"""
def __init__(self):
self.pnet = TrtPNet('mtcnn/det1.engine')
self.rnet = TrtRNet('mtcnn/det2.engine')
self.onet = TrtONet('mtcnn/det3.engine')
def __del__(self):
self.onet.destroy()
self.rnet.destroy()
self.pnet.destroy()
def _detect_1280x720(self, img, minsize):
"""_detec_1280x720()
Assuming 'img' has been resized to less than 1280x720.
"""
# MTCNN model was trained with 'MATLAB' image so its channel
# order is RGB instead of BGR.
img = img[:, :, ::-1] # BGR -> RGB
dets = self.pnet.detect(img, minsize=minsize)
dets = self.rnet.detect(img, dets)
dets, landmarks = self.onet.detect(img, dets)
return dets, landmarks
def detect(self, img, minsize=40):
"""detect()
This function handles rescaling of the input image if it's
larger than 1280x720.
"""
if img is None:
raise ValueError
img_h, img_w, _ = img.shape
scale = min(720. / img_h, 1280. / img_w)
if scale < 1.0:
new_h = int(np.ceil(img_h * scale))
new_w = int(np.ceil(img_w * scale))
img = cv2.resize(img, (new_w, new_h))
minsize = max(int(np.ceil(minsize * scale)), 40)
dets, landmarks = self._detect_1280x720(img, minsize)
if scale < 1.0:
dets[:, :-1] = np.fix(dets[:, :-1] / scale)
landmarks = np.fix(landmarks / scale)
return dets, landmarks
| true |
a87f60624d25883e8928a43eef10660fc2b21b98 | Python | cesclee/intflowtest | /linktest01.py | UTF-8 | 327 | 2.53125 | 3 | [] | no_license | #mysqldb python으로 연동가능여부확인
import pymysql
conn=pymysql.connect
conn=pymysql.connect(host='localhost', user='root',password='rhtmxhq12@L', db="task01_intflowtest",charset='utf8')
curs=conn.cursor()
sql="select * from member"
curs.execute(sql)
rows = curs.fetchall()
print(rows)
conn.close()
| true |
081dd9751b014be0323a6a271f4436988f4556d7 | Python | bellyfat/Volunter_Scheduler | /Volunteer_Scheduler.py | UTF-8 | 6,315 | 2.828125 | 3 | [] | no_license | import xlwings as xw
from pandas import DataFrame
class Volunteer():
id = -1
consecutiveWorkday = 0
totalDaysOff = 0
schedule = []
def __init__(self, id, consecutiveWorkingDay,totalDaysOff,schedule):
self.id = id
self.consecutiveWorkday = consecutiveWorkingDay
self.totalDaysOff = totalDaysOff
self.schedule = schedule
def clone(self):
return Volunteer(self.id,self.consecutiveWorkday,self.totalDaysOff,self.schedule)
def addWorkday(volunteer, site):
volunteer.schedule.append(site)
volunteer.consecutiveWorkday = volunteer.consecutiveWorkday + 1
return volunteer
def createVolunteerList(numVolunteer):
volunteerList = []
for i in range(numVolunteer):
current = Volunteer(-1,0,0,[])
current.id = i
volunteerList.append(current)
return volunteerList
def removeWeekend(workingList,remainingDaysOffPerDay):
if len(workingList[0].schedule) != 0:
for volunteer in workingList:
if remainingDaysOffPerDay > 0:
if volunteer.schedule[-1] == 0:
if len(volunteer.schedule) == 1:
workingList.remove(volunteer)
remainingDaysOffPerDay = remainingDaysOffPerDay - 1
elif volunteer.schedule[-2] != 0:
workingList.remove(volunteer)
remainingDaysOffPerDay = remainingDaysOffPerDay - 1
def removeOverworked(workingList,remainingDaysOffPerDay, maxDaysWorking):
for volunteer in workingList:
if remainingDaysOffPerDay > 0 and volunteer.consecutiveWorkday >= maxDaysWorking:
workingList.remove(volunteer)
remainingDaysOffPerDay = remainingDaysOffPerDay - 1
def printVolunteerIds(volunteerList):
for volunteer in volunteerList: print(volunteer.id)
def sortByTotalDaysOff(volunteerList):
for i in range(len(volunteerList)):
for j in range(len(volunteerList)):
if volunteerList[i].totalDaysOff < volunteerList[j].totalDaysOff:
temp = volunteerList[i]
volunteerList[i] = volunteerList[j]
volunteerList[j] = temp
elif volunteerList[i].totalDaysOff == volunteerList[j].totalDaysOff and volunteerList[i].consecutiveWorkday < volunteerList[j].consecutiveWorkday:
temp = volunteerList[i]
volunteerList[i] = volunteerList[j]
volunteerList[j] = temp
def numTimesWorkedSite(volunteer,site):
numTimes = 0
for currentSite in volunteer.schedule:
if site == currentSite:
numTimes = numTimes + 1
return numTimes
def sortByTimesWorked(volunteerList,site):
site = site + 1
for i in range(len(volunteerList)):
for j in range(len(volunteerList)):
if numTimesWorkedSite(volunteerList[i],site) < numTimesWorkedSite(volunteerList[j],site):
temp = volunteerList[i]
volunteerList[i] = volunteerList[j]
volunteerList[j] = temp
def distributeRemainingDaysOff(workingList,remainingDaysOffPerDay,minDaysBetweenWeekends):
while(remainingDaysOffPerDay > 1):
for volunteer in workingList:
if volunteer.consecutiveWorkday >= minDaysBetweenWeekends and remainingDaysOffPerDay > 0:
workingList.remove(volunteer)
remainingDaysOffPerDay = remainingDaysOffPerDay - 1
minDaysBetweenWeekends = minDaysBetweenWeekends - 1
return workingList
def mergeVolunteerToList(volunteerList,volunteer):
for i in range(len(volunteerList)):
if volunteerList[i].id == volunteer.id:
volunteerList[i] = volunteer
return volunteerList
def getVolunteerById(volunteerList,id):
for volunteer in volunteerList:
if volunteer.id == id: return volunteer
def volunteerListToSchedule(volunteerList, numDays):
schedule = DataFrame()
for day in range(numDays):
row = 0
for volunteer in volunteerList:
schedule.set_value(row, day, volunteer.schedule[day])
row = row + 1
return schedule
def main():
#initialize inputs
sht = xw.Book.caller().sheets[0]
volunteer_schedule = sht.range("r_volunteer_schedule")
numVolunteer = int(sht.range("n_volunteers").value)
numDays = int(sht.range("n_days").value)
numSites = sht.range("n_num_sites").value
maxDaysWorking = sht.range("N_max_work_week").value
minDaysBetweenWeekends = sht.range("N_min_work_week").value
#create a list of empty volunteers
volunteerList = createVolunteerList(numVolunteer)
# Num of days off that can be assigned every day.
daysOffPerDay = numVolunteer - numSites
#Iterate through each day and assign sites and days off depending on volunteers past experience.
for day in range(numDays):
workingList = []
for volunteer in volunteerList: workingList.append(volunteer.clone())
remainingDaysOffPerDay = daysOffPerDay + len(workingList) - numVolunteer
removeOverworked(workingList,remainingDaysOffPerDay,maxDaysWorking)
remainingDaysOffPerDay = daysOffPerDay + len(workingList) - numVolunteer
removeWeekend(workingList,remainingDaysOffPerDay)
remainingDaysOffPerDay = daysOffPerDay + len(workingList) - numVolunteer
sortByTotalDaysOff(workingList)
distributeRemainingDaysOff(workingList,remainingDaysOffPerDay,minDaysBetweenWeekends)
for site in range(int(numSites)):
sortByTimesWorked(workingList,site)
workingList[0] = addWorkday(workingList[0],site+1)
volunteerList = mergeVolunteerToList(volunteerList,workingList[0])
del workingList[0]
for volunteer in volunteerList:
if len(volunteer.schedule) < day+1:
volunteer.schedule.append(0)
volunteer.totalDaysOff = volunteer.totalDaysOff + 1
volunteer.consecutiveWorkday = 0
sht.range("r_volunteer_schedule").options(index=False, header=False).value = volunteerListToSchedule(volunteerList,numDays)
| true |
596886fab76d4e3d1b319e6d223caaab5b07c08f | Python | fdm1/financier | /budget_builder/budget_builder/budget_event.py | UTF-8 | 2,809 | 3.484375 | 3 | [] | no_license | """Object to represent budget events"""
from datetime import date
class UnsupportedEventType(Exception):
"""Error for when unknown event types are given"""
pass
class BudgetEvent(object):
"""
An item used to define a recurring or one-time
budgeting event (e.g. payday, bills, bonuses, trips)
"""
VALID_EVENT_TYPES = ['one_time', 'monthly', 'biweekly', 'bimonthly']
def __init__(self, name, amount, kind, start_date=None,
example_date=date.today(), exact_date=date.today(),
end_date=None, day_of_month=None):
# pylint: disable=too-many-arguments
self.name = name
if kind not in self.VALID_EVENT_TYPES:
raise UnsupportedEventType("{} kind is not a supported budget event type".format(kind))
if amount >= 0:
self.debit_amount = amount
self.credit_amount = 0
else:
self.debit_amount = 0
self.credit_amount = amount
self.kind = kind
self.day_of_month = day_of_month
self.start_date = start_date
self.example_date = example_date
self.exact_date = exact_date
self.end_date = end_date
@property
def debit(self):
"""Return boolean True if this is a debit"""
return self.debit_amount > 0 and self.credit_amount == 0
def should_update(self, thedate):
"""Determine if the event has any effect on a given date"""
if self.kind == 'one_time':
return thedate == self.exact_date
elif ((self.start_date and thedate < self.start_date) or
(self.end_date and thedate > self.end_date)):
return False
# TODO: deal with end of month
elif self.kind == 'monthly':
return thedate.day == self.day_of_month
elif self.kind == 'biweekly':
return (thedate - self.example_date).days % 14 == 0
elif self.kind == 'bimonthly':
return thedate.day == 15 or thedate.day == 1
return False
def update_balance(self, orig_balance, thedate):
"""Update a balance with the event's amount if needed"""
balance = None
if self.should_update(thedate):
balance = orig_balance + self.debit_amount + self.credit_amount
return self, thedate, balance
def __repr__(self):
return ("{}(name={}, debit_amount={}, credit_amount = {}, "
"kind={}, start_date={}, end_date={}, day_of_month={})".format(
self.__class__.__name__,
self.name,
self.debit_amount,
self.credit_amount,
self.kind,
self.start_date,
self.end_date,
self.day_of_month))
| true |
dbb6f06d6e3c8c79c7b7ab19b52906c31194f46c | Python | AnaGVF/Programas-Procesamiento-Imagenes-OpenCV | /NumeroPrimo_Version2.py | UTF-8 | 288 | 4 | 4 | [] | no_license | # Nombre: Ana Graciela Vassallo Fedotkin
# Fecha: 13 de Enero 2021.
numero = 5
contador = 0
for i in range(1, numero+1):
if(numero%i == 0):
contador = contador + 1
if(contador == 2):
print("El número",{numero}, "es primo")
else:
print("El número",{numero}, "no es primo") | true |
49b5770870c9a26293a5fb8da249aa860c9ef2a5 | Python | tijgerkaars/AdventofCode2019 | /Day_9/Main.py | UTF-8 | 1,688 | 2.890625 | 3 | [] | no_license | import time
import math
from intComp import opComp
def get_input(name = '', test = False):
if not name:
if test:
name = r'/'.join(__file__.split(r'/')[-3:-1]) + r'/test_input.txt'
else:
name = r'/'.join(__file__.split(r'/')[-3:-1]) + r'/input.txt'
if name != '':
with open(name) as f:
lines = []
for line in f:
lines.append( list(map(int, line.split(','))))
if len(lines) == 1:
lines = lines[0]
return lines
def test():
program = get_input(test=True)
for each in program:
c1 = opComp(each, inp=2)
print( f"codes ran: { c1.opcodes_run}, l: {len(str(c1.output))} out: {c1.output}")
if __name__ == "__main__" or True:
t0 = time.time()
""" ------------------------------------------------------------------------------------------------------------------ """
debug = False
if debug:
test()
part1 = None
else:
program = get_input()
c1 = opComp(program, inp=1)
print( f"codes ran: { c1.opcodes_run}, l: {len(str(c1.output))} out: {c1.output}")
part1 = c1.output[0]
t1 = time.time()
""" ------------------------------------------------------------------------------------------------------------------ """
program = get_input()
c1 = opComp(program, inp=2)
print( f"codes ran: { c1.opcodes_run}, l: {len(str(c1.output))} out: {c1.output}")
part2 = c1.output[0]
t2 = time.time()
print(f"Part 1 -- {part1}, t: {t1-t0:0.4f}")
print(f"Part 2 -- {part2}, t: {t2-t1:0.4f}")
print(f"total, t: {t2-t0:0.4f}") | true |
a3117501938f1278da1dfa43de77a2193a0588ed | Python | benkiel/python_workshops | /2018_3_Cooper_Type/Samples/set_vertical_metrics.py | UTF-8 | 936 | 2.546875 | 3 | [
"MIT"
] | permissive | fonts = AllFonts()
min = 0
max = 0
maxGlyph = ''
minGlyph = ''
for font in fonts:
for glyph in font:
if glyph.box is not None:
if glyph.box[1] < min:
min = glyph.box[1]
minGlyph = glyph.name + ' ' + font.info.familyName + font.info.styleName
if glyph.box[3] > max:
max = glyph.box[3]
maxGlyph = glyph.name + ' ' + font.info.familyName + font.info.styleName
for font in fonts:
font.info.openTypeHheaAscender = max
font.info.openTypeHheaDescender = min
font.info.openTypeHheaLineGap = 0
font.info.openTypeOS2TypoAscender = font.info.ascender
font.info.openTypeOS2TypoDescender = font.info.descender
font.info.openTypeOS2TypoLineGap = (max + abs(min)) - font.info.unitsPerEm
font.info.openTypeOS2WinAscent = max
font.info.openTypeOS2WinDescent = abs(min)
print (max + abs(min)) - font.info.unitsPerEm | true |
ff7d69e7eb2802e00133c9f4718d65a012626f28 | Python | sandipsinha/python_bits | /pythonBST.py | UTF-8 | 798 | 3.640625 | 4 | [] | no_license | class Node:
def __init__(self, value):
self.value = value
self.leftChild = None
self.rightChild = None
def insert(self, data):
if self.value < data:
if self.rightChild is not None:
self.rightChild.insert(data)
else:
self.rightChild = Node(data)
elif self.value > data:
if self.leftChild is not None:
self.leftChild.insert(data)
else:
self.leftChild = Node(data)
def traverse(self, data):
if self.data == data:
if self.leftChild is not None:
self.leftChild.traverse(self.leftChild)
if self.rightChild is not None:
self.rightChild.traverse(self.rightChild)
| true |
a0b8547f79c3c867c5324da72ced7de37abe04dd | Python | vaidyaenc/vaidya | /201902-aruba-py-1/multi-threadinig-demos/demo03-count-down.py | UTF-8 | 430 | 3.03125 | 3 | [] | no_license | import threading as t
import sys
def count_down():
name=t.current_thread().name
max=100
while max>0:
print('{} counts {}'.format(name,max))
max-=1
print('{} ends'.format(name))
def main(name,args):
t1=t.Thread(target=count_down)
t2=t.Thread(target=count_down)
t1.start()
t2.start()
print('end of program')
if __name__=='__main__':
main(sys.argv[0],sys.argv[1:]) | true |
53447f28c36164416a25f5e5775033a5d8568ea5 | Python | stoddabr/research_robotics_arm | /ResearchRobotics/run_server.py | UTF-8 | 2,564 | 2.609375 | 3 | [] | no_license | import time
import os
from flask import Flask, send_file, request
from markupsafe import escape
import json
import random
import db_txt as db
def reset():
default_grasp_data = [0,0,False] # [angle, object_coords, is_grasp]
default_blobs_data = [ # TODO double check format
{'x': '50','y': '50', 'angle': '270', 'color': 'orange', 'type':'starfish'},
{'x': '200','y': '200', 'angle': '270', 'color': 'orange', 'type':'cube'},
]
db.updateGraspDB(default_grasp_data)
db.updateBlockDB(default_blobs_data)
# test code
def run_testing_thread():
""" will run thread that updates data every 5 seconds """
import threading # only used for testing
blobsA = [ # TODO double check format
{'x': '10','y': '10', 'angle': '270', 'color': 'orange', 'type':'cube'},
{'x': '200','y': '150', 'angle': '60', 'color': 'yellow', 'type':'cube'},
]
blobsB = [ # TODO double check format
{'x': '50','y': '50', 'angle': '270', 'color': 'orange', 'type':'starfish'},
{'x': '100','y': '100', 'angle': '60', 'color': 'yellow', 'type':'starfish'},
]
def loopWriteToDB():
fname = 'db_blobs.txt'
while True:
updateBlockDB(blobsA)
time.sleep(5)
updateBlockDB(blobsB)
time.sleep(5)
test_io_thread = threading.Thread(target = loopWriteToDB)
test_io_thread.start()
# setup flask server and routes
app = Flask(__name__)
@app.route('/grasp', methods=['GET', 'PUT'])
def grasp_request():
if request.method == 'PUT':
data = request.get_data(as_text=True)
print('!!!!! put grasp data', data)
db.updateGraspDB(data, as_text=True)
return 'Got'
else: # GET
return json.dumps(db.getGraspDB())
@app.route('/blobs', methods=['GET', 'PUT'])
def blobs_request():
if request.method == 'PUT':
data = request.get_json()
print('!!!!! put grasp data', data)
return db.updateBlockDB(data)
else: # GET
return json.dumps(db.getBlocksDB())
@app.route('/video_feed')
def video_feed():
fpath = '_scene.jpg'
return send_file(fpath, mimetype='image/jpg')
@app.route('/video_feed_test')
def video_feed_test():
test_img_paths = ['_testA.jpg', '_testB.jpg']
fpath = random.choice( test_img_paths )
return send_file(fpath, mimetype='image/jpg')
if __name__ == '__main__':
reset() # reset data in 'server'
#run_testing_thread() # comment this line during production
app.run(host='0.0.0.0')
| true |
9c804f6149ccd71cfbfd550ad465a0f6fc6f36d5 | Python | awaq96/ISS-Flyover-Time | /test/open_notify_service_test.py | UTF-8 | 3,967 | 2.578125 | 3 | [] | no_license | import unittest
from open_notify_service import *
from unittest.mock import patch, Mock
import open_notify_service
class open_notify_service_test(unittest.TestCase):
def test_canary(self):
self.assertTrue(True)
def test_get_raw_response(self):
location = (29.7216, -95.3436)
api_response = get_raw_response( location)
self.assertTrue(('passes' in api_response['request'].keys() and 'latitude' in api_response['request'].keys()
and 'longitude' in api_response['request'].keys()) or api_response == [])
def test_parse_json_first(self):
sample_data = {"message": "success",
"request": {
"altitude": 100,
"datetime": 1602736755,
"latitude": 29.72167,
"longitude": -95.343631,
"passes": 1
},
"response": [
{
"duration": 449,
"risetime": 1602764987
}
]
}
self.assertEqual(1602764987,
parse_json(sample_data))
def test_parse_json_second(self):
sample_data2 = {
"message": "success",
"request": {
"altitude": 100,
"datetime": 1602735194,
"latitude": 30.2672,
"longitude": -97.7431,
"passes": 1
},
"response": [
{
"duration": 368,
"risetime": 1602765016
}
]
}
self.assertEqual(1602765016,
parse_json(sample_data2))
def test_get_raw_response_mock(self):
fake_json = {
"message": "success",
"request": {
"altitude": 100,
"datetime": 1602875779,
"latitude": 29.72167,
"longitude": -95.343631,
"passes": 1
},
"response": [
{
"duration": 432,
"risetime": 1602877884
}
]
}
mock_get_patcher = patch('open_notify_service.requests.get')
mock_get = mock_get_patcher.start()
mock_get.return_value.json.return_value = fake_json
response = get_raw_response((29.7216, -95.3436))
mock_get_patcher.stop()
self.assertEqual(response, fake_json)
def test_parse_json_mock(self):
fake_json = 1602877884
json_request = {
"message": "success",
"request": {
"altitude": 100,
"datetime": 1602875779,
"latitude": 29.72167,
"longitude": -95.343631,
"passes": 1
},
"response": [
{
"duration": 432,
"risetime": 1602877884
}
]
}
mock_get_patcher = patch('open_notify_service.requests.get')
mock_get = mock_get_patcher.start()
mock_get.return_value.json.return_value = fake_json
response = parse_json(json_request)
mock_get_patcher.stop()
self.assertEqual(response, fake_json)
def test_get_flyover_pass_to_get_raw(self):
location = (29.7216, -95.3436)
open_notify_service.get_raw_response = Mock(return_value={
"message": "success",
"request": {
"altitude": 100,
"datetime": 1602875779,
"latitude": 29.72167,
"longitude": -95.343631,
"passes": 1
},
"response": [
{
"duration": 432,
"risetime": 1602877884
}
]
} )
open_notify_service.parse_json = Mock(return_value=1602877884)
self.assertEqual('02:51PM',
get_flyover_time_for_a_location(location))
def test_get_number_of_astronauts_on_iss(self):
self.assertEqual(6, get_number_of_astronauts_on_iss())
def test_get_names_of_astronauts_on_iss(self):
self.assertEqual(['Chris Cassidy', 'Anatoly Ivanishin', 'Ivan Vagner', 'Sergey Ryzhikov', 'Kate Rubins', 'Sergey Kud-Sverchkov'], get_names_of_astronauts_on_iss())
if __name__ == '__main__':
unittest.main()
| true |
046e21d7279f1299eeb09eedc79ff2803c41d603 | Python | Anmol406/Automation-code-sample | /working with frames.py | UTF-8 | 1,279 | 2.6875 | 3 | [] | no_license | #IN FRAME WORK XPATH DONT WORK TO FIND THE FRAME
# from selenium import webdriver
# from selenium.webdriver.common.by import By
# import time
# driver=webdriver.Chrome(executable_path="C:\driver\chromedriver.exe")
# driver.get("https://seleniumhq.github.io/selenium/docs/api/java/index.html")
# driver.switch_to.frame("packageListFrame")
# driver.find_element_by_link_text("org.openqa.selenium").click()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
driver=webdriver.Chrome(executable_path="C:\driver\chromedriver.exe")
driver.get("https://seleniumhq.github.io/selenium/docs/api/java/index.html")
driver.switch_to.frame("packageListFrame") #FIRST FRAME
driver.find_element_by_link_text("org.openqa.selenium").click()
time.sleep(5)
driver.switch_to.default_content()
driver.switch_to.frame("packageFrame") #SECOND FRAME
driver.find_element_by_link_text("WebDriver").click()
time.sleep(5)
driver.switch_to.default_content()
time.sleep(5)
driver.switch_to.frame("classFrame") #THIRD FRAME
driver.find_element(By.XPATH,"/html/body/div[1]/ul/li[5]/a").click()
| true |
b4c782a90afb1b9d5fe4ab1260893e55f91e597e | Python | talpallikar/ml-python-book | /adaline/plot.py | UTF-8 | 746 | 2.6875 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
import adaline
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
ada1 = adaline.AdalineGD(n_iter=10, eta=0.01).fit(X, y)
ax[0].plot(range(1, len(ada1.cost_) + 1), np.log10(ada1.cost_), marker='o')
ax[0].set_xlabel('Epochs')
ax[0].set_ylabel('log(Sum-squared-error)')
ax[0].set_title('Adaline - Learning rate 0.01')
ada2 = AdalineGD(n_iter=10, eta=0.0001).fit(X, y)
ax[1].plot(range(1, len(ada2.cost_) + 1), ada2.cost_, marker='o')
ax[1].set_xlabel('Epochs')
ax[1].set_ylabel('Sum-squared-error')
ax[1].set_title('Adaline - Learning rate 0.0001')
plt.tight_layout()
# plt.savefig('./adaline_1.png', dpi=300)
plt.show() | true |
1011e709107c55a2f6644173237bd71704dc67b8 | Python | mayerll/Via | /listExeFile.py | UTF-8 | 195 | 2.9375 | 3 | [] | no_license | # List all the execlusive files in a given dir (Python)
import os
path = '/home/data_analysis/tools/'
files = os.listdir(path)
for f in files:
if f.lower().endswith('*.exe'):
print(f)
| true |
3aca67637f893b39de474448926206c7f5745c34 | Python | ravisjoshi/python_snippets | /DataStructure/Trees/SymmetricTree.py | UTF-8 | 924 | 4.125 | 4 | [] | no_license | """
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def _check_lrt(self, left, right):
if not left and not right: return True
if not left or not right: return False
if left.val != right.val: return False
return self._check_lrt(left.left, right.right) and self._check_lrt(left.right, right.left)
def isSymmetric(self, root):
if not root:
return True
return self._check_lrt(root.left, root.right)
| true |
da384667920c21ccb9bae113a71f71efb33750cf | Python | DarkAlexWang/leetcode | /Huawei/sherlock_date.py | UTF-8 | 1,250 | 3.21875 | 3 | [] | no_license | import sys
#strings = []
#for i in range(4):
# line = sys.stdin.readline().strip()
# values = list(map(str, line.split()))
# for string in values:
# strings.append(string)
strings = ['3485djDkxh4hhGE',
'2984akDfkkkkggEdsb',
's&hgsfdk',
'd&Hyscvnm'
]
s1 = strings[0]
s2 = strings[1]
s3 = strings[2]
s4 = strings[3]
print(s1, s2)
week = ['MON', "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
flag = 0
length1 = len(s2) if len(s1) > len(s2) else len(s1)
for i in range(length1):
if s1[i] == s2[i] and (ord(s1[i]) >= 65 and ord(s1[i]) <= 71) and flag == 0:
flag = 1
print(week[ord(s1[i]) - 65] + ' ')
i += 1
if flag == 1 and s1[i] == s2[i]:
if s1[i] >= '0' and s1[i] <= '9':
print("0" + chr(a[i] - '0') + ':')
break
if s1[i] >= 'A' and s1[i] <= 'N':
print(chr(ord(s1[i]) - 65 + 10) + ":")
break
length2 = len(s4) if len(s3) > len(s4) else len(s3)
for i in range(length2):
if s3[i] == s4[i] and (ord(s3[i]) >= 65 and ord(s3[i]) <= 90) or (ord(s3[i]) >= 97 and ord(s3[i]) <= 122):
if i <= 9:
print("0" + chr(i))
break
else:
print(chr(i))
break
| true |
d19ad90d8c09e30ca54b535f02262aa8aef1faa0 | Python | BrunoPanizzi/sudoku | /sudoku.py | UTF-8 | 4,110 | 3.078125 | 3 | [] | no_license | import pygame
'''
TO DO:
solver algorithm
generator algorithm
'''
board = [[' ' for i in range(9)] for i in range(9)]
board = [
[ 6 , 2 ,' ', 9 ,' ',' ',' ',' ',' '],
[' ',' ', 9 ,' ',' ',' ',' ', 5 , 2 ],
[' ',' ',' ', 7 ,' ', 1 , 9 ,' ',' '],
[' ',' ',' ', 6 ,' ',' ',' ', 1 ,' '],
[ 4 ,' ', 6 ,' ', 1 ,' ',' ', 7 ,' '],
[' ',' ',' ',' ', 3 , 2 ,' ',' ',' '],
[ 1 , 7 ,' ',' ',' ', 8 ,' ',' ',' '],
[ 3 ,' ',' ',' ',' ',' ', 5 ,' ',' '],
[' ', 8 ,' ',' ',' ', 6 ,' ',' ', 1 ]]
numberInputs = {
pygame.K_1:1,
pygame.K_2:2,
pygame.K_3:3,
pygame.K_4:4,
pygame.K_5:5,
pygame.K_6:6,
pygame.K_7:7,
pygame.K_8:8,
pygame.K_9:9
}
def isValid(board):
for num in range(1,10):
# lines
for line in board:
if line.count(num) > 1:
return False
# columns
boardT = [[row[i] for row in board] for i in range(9)]
for line in boardT:
if line.count(num) > 1:
return False
# small squares
# i hate this thing
for i in range(3):
for j in range(3):
square = [board[r][c] for c in range(j*3, (j*3)+3) for r in range(i*3, (i*3)+3)]
if square.count(num) > 1:
return False
return True
class Game:
def __init__(self, res:tuple, fps:int) -> None:
pygame.init()
self.w, self.h = res
self.fps = fps
self.screen = pygame.display.set_mode(res)
self.font = pygame.font.Font(None, 36)
self.clock = pygame.time.Clock()
self.selected = None
self.run = True
self.margins = 50
self.squareSize = (self.w - (2*self.margins))/9
# secondary functions
def drawLines(self):
margins = self.margins
# vertical
for i in range(10):
start = (self.squareSize*i+margins, margins)
end = (self.squareSize*i+margins, self.h-margins)
pygame.draw.aaline(self.screen, (0,0,0), start, end)
# horizontal
for i in range(10):
start = (margins, self.squareSize*i+margins)
end = (self.w-margins, self.squareSize*i+margins)
pygame.draw.aaline(self.screen, (0,0,0), start, end)
def drawNumbers(self, sudoku):
start = self.margins*1.6
for i, line in enumerate(sudoku):
for j, num in enumerate(line):
number = self.font.render(str(num), True, (0,0,0))
rect = number.get_rect()
rect.center = (start+(j*self.squareSize), start+(i*self.squareSize))
self.screen.blit(number, rect)
def selectSquare(self, mousePos):
x, y = mousePos
if self.margins<x<self.squareSize*9+self.margins and self.margins<y<self.squareSize*9+self.margins:
xSquare = (x-self.margins)//self.squareSize
ySquare = (y-self.margins)//self.squareSize
self.selected = (int(xSquare), int(ySquare))
else:
self.selected = None
def highlight(self):
if self.selected:
pos = (self.selected[0] * self.squareSize + self.margins, self.selected[1] * self.squareSize + self.margins)
highlight = pygame.Rect(pos , (self.squareSize, self.squareSize))
pygame.draw.rect(self.screen, (0,200,0), highlight)
def placeNumber(self, number, sudoku):
if not self.selected:
return
column, row = self.selected
newSudoku = [list(line) for line in sudoku]
newSudoku[row][column] = number
if isValid(newSudoku):
sudoku[row][column] = number
self.selected = None
# main functions
def events(self):
mousePos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT: # closes the game
self.run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # closes the game too
self.run = False
elif event.key in numberInputs: # number input
self.placeNumber(numberInputs[event.key], board)
elif event.type == pygame.MOUSEBUTTONDOWN:
self.selectSquare(mousePos)
def updates(self):
self.screen.fill((255,255,255))
self.highlight()
self.drawLines()
self.drawNumbers(board)
pygame.display.update()
def main(self):
while self.run:
self.events()
self.updates()
self.clock.tick(self.fps)
if __name__ == '__main__':
game = Game((650, 650), 60)
game.main() | true |
ff86d332b2a6ce058bdcf63165255e9ab3c31b59 | Python | PaulienvandenNoort/Elliptische_krommen | /Backdoor.py | UTF-8 | 5,769 | 3.34375 | 3 | [] | no_license | import math
import copy
class ElliptischeKromme:
def __init__(self,a,b,p):
self.a = a
self.b = b
self.p = p
def __str__(self):
if -16*(4*self.a**3+27*self.b**2)!=0:
return 'E: y^2 = x^3 + ' + str(self.a) + 'x + ' + str(self.b)
else:
return 'Kan niet'
def __eq__(self,other):
return self.a == other.a and self.b == other.b and self.p == other.p
class Punt:
def __init__(self,x=[],y=[],c=ElliptischeKromme(0,0,2)):
self.x = x #voer het punt oneindig in als Punt()
self.y = y
self.E = c
self.a = c.a
self.b = c.b
self.p = c.p
def __str__(self):
if self.x==[] and self.y==[]:
return 'O'
return '(' + str(self.x) + ',' + str(self.y)+ ')'
def __add__(self,other):
return self.optellen(other)
def __sub__(self,other):
return self.optellen(other.negatie())
def __neg__(self):
return self.negatie()
def __mul__(self,n):
return self.vermenigvuldigen(n)
def __rmul__(self,n):
return self.vermenigvuldigen(n)
def __eq__(self,other):
return self.x==other.x and self.y==other.y and self.E==other.E
def optellen(self,other):
if self.x==[] and self.y==[]:
return other
elif other.x==[] and other.y==[]:
return self #punt bij oneindig optellen geeft punt zelf
elif self.E != other.E:
return 'Kan niet'
elif self.x == other.x and self.y != other.y:
return Punt() #twee punten die boven elkaar liggen (elkaars inverse) optellen geeft oneindig
elif self == other and self.y == 0:
return Punt() #raaklijn recht omhoog voor punt bij zichzelf optellen geeft oneindig
else:
if self == other:
s = (3*self.x**2+self.a)* inverse_of(2*self.y,self.p) #afgeleide van de elliptische kromme
else:
s = (self.y - other.y)* inverse_of((self.x - other.x),self.p) #rc van de lijn door de twee punten
xr = (s**2 - self.x - other.x) % self.p #afleiding in mn notities
yr = (self.y+s*(xr-self.x)) % self.p #rc*x-afstand tussen p en r+punt p
antwoord = -Punt(xr,yr,self.E)
return antwoord
def negatie(self):
new = copy.deepcopy(self)
new.y = -new.y % self.p
return new
def vermenigvuldigen(self,n):
antwoord = self
if n == 0:
return 0
if n == 1:
return antwoord
else:
for i in range(n-1):
antwoord += self
return antwoord
def binkeer(self,n): #bron https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add
if n == 0:
return 0
elif n == 1:
return self
elif n % 2 == 1:
return self.optellen(self.binkeer(n-1))
else:
return (2*self).binkeer(n // 2)
def extended_euclidean_algorithm(a, b):
"""
Returns a three-tuple (gcd, x, y) such that
a * x + b * y == gcd, where gcd is the greatest
common divisor of a and b.
This function implements the extended Euclidean
algorithm and runs in O(log b) in the worst case. """
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = b, a
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
return old_r, old_s, old_t
def inverse_of(n, p):
"""
Returns the multiplicative inverse of
n modulo p.
This function returns an integer m such that
(n * m) % p == 1.
"""
gcd, x, y = extended_euclidean_algorithm(n, p)
assert (n * x + p * y) % p == gcd
if gcd != 1:
# Either n is 0, or p is not a prime number.
raise ValueError(
'{} has no multiplicative inverse '
'modulo {}'.format(n, p))
else:
return x % p
import random
import os
# Normale werking van de generator Dual_EC_DRBG is als volgt
def PRNG(n,d):
Q = Punt(3,4,ElliptischeKromme(1,-1,104729))
P = Q.binkeer(d)
i0 = os.urandom(32)
lijstinput = n*[0] #lijst van i'tjes in bytes
lijstinput[0] = int.from_bytes(i0, byteorder='big')
lijstoutput = (n-1)*[0] #lijst van o'tjes in bytes
for i in range(1,n):
lijstinput[i] = (P.binkeer(lijstinput[i-1])).x
for i in range(n-1):
phi = (Q.binkeer(lijstinput[i+1])).x
#lijstoutput[i] = phi
lijstoutput[i]= phi.to_bytes((phi.bit_length() + 7) // 8, byteorder='big')[-30:]
print(lijstoutput)
return Q.binkeer(lijstinput[1])
def PRNG_backdoor(n=int(),d=int(),A=Punt()):
Q = Punt(3,4,ElliptischeKromme(1,-1,104729))
P = Q.binkeer(d)
lijstinput = n*[0] #lijst van itjes in bytes
lijstoutput = (n-1)*[0] #lijst van otjes in bytes
i1P=A.binkeer(d)
lijstinput[0] = 0
lijstinput[1] = 0
lijstinput[2] = i1P.x
#lijstoutput[0] = A.x
lijstoutput[0] = (A.x).to_bytes(((A.x).bit_length() + 7) // 8, byteorder='big')
for i in range(3,n):
lijstinput[i] = (P.binkeer(lijstinput[i-1])).x
for i in range(1,n-1):
#lijstoutput[i] = (Q.binkeer(lijstinput[i+1])).x
phi = (Q.binkeer(lijstinput[i+1])).x
lijstoutput[i] = phi.to_bytes((phi.bit_length() + 7) // 8, byteorder='big')
return lijstoutput
| true |
6b83df1846cd379c16d52559a3f8cf770528aa15 | Python | MariaIsabelLL/Python_NLTK | /ch03/ejercicios03.py | UTF-8 | 8,523 | 3.84375 | 4 | [] | no_license | ''' https://www.nltk.org/book/ch03.html
'''
import nltk
from urllib import request
from bs4 import BeautifulSoup
from nltk.corpus import names
from nltk import word_tokenize
from nltk.corpus import words
import re
# loads an list full of names
options = names.fileids()
name_options = [names.words(f) for f in options]
# flattens the list
name_options = [item for sublist in name_options for item in sublist]
'''
8. Write a utility function that takes a URL as its argument,
and returns the contents of the URL, with all HTML markup removed.
Use from urllib import request and then
request.urlopen('http://nltk.org/').read().decode('utf8')
to access the contents of the URL.
'''
def contentURL(url):
contenido = request.urlopen(url).read().decode('utf8')
soup = BeautifulSoup(contenido, "lxml")
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract() # rip it out
# get text
text = soup.get_text()
tokens = word_tokenize(text)
return tokens
print(contentURL('http://nltk.org/'))
'''
9. Save some text into a file corpus.txt. Define a function load(f)
that reads from the file named in its sole argument, and returns a
string containing the text of the file.
Use nltk.regexp_tokenize() to create a tokenizer that tokenizes
the various kinds of punctuation in this text. Use one multi-line
regular expression, with inline comments, using the verbose flag (?x).
Use nltk.regexp_tokenize() to create a tokenizer that tokenizes
the following kinds of expression: monetary amounts; dates;
names of people and organizations.
'''
def load(f):
doc = open(f,encoding='utf8')
#doc = open(f,encoding="ISO-8859-1")
raw = doc.read()
return raw
def regexp(raw):
#kinds of punctuation
pattern = r'''(?x) # set flag to allow verbose regexps
\W # searches for non-alphanumeric characters.
'''
tokPunc = nltk.regexp_tokenize(raw,pattern)
print('non-alphanumeric characters:',tokPunc)
#monetary amounts
pattern = r'''(?x) # set flag to allow verbose regexps
\$\d+\.\d+ # currency e.g. $12.40
'''
tokMon = nltk.regexp_tokenize(raw,pattern)
print('currency:',tokMon)
#dates
pattern = r'''(?x) # set flag to allow verbose regexps
\d\d\/\d\d\/\d\d\d\d # date formato dd/mm/yyyy
'''
tokMon = nltk.regexp_tokenize(raw,pattern)
print('data formato dd/mm/yyyy:',tokMon)
#names of people
pattern = r'''(?x) # set flag to allow verbose regexps
[A-Z][a-z]+ # names of people
'''
raw_matches = nltk.regexp_tokenize(raw, pattern)
name_matches = [match for match in raw_matches if match in name_options]
print('names of people',name_matches)
return raw
#print(load('textoEN2.txt'))
regexp(load('textoEN.txt'))
'''
13. What is the difference between calling split on a string with
no argument or with ' ' as the argument, e.g. sent.split() versus
sent.split(' ')? What happens when the string being split
contains tab characters, consecutive space characters, or a sequence
of tabs and spaces? (In IDLE you will need to use '\t' to enter a
tab character.)
'''
texto = load('textoEN.txt')
#print(texto.split())
print(texto.split(' '))
'''
14. Create a variable words containing a list of words.
Experiment with words.sort() and sorted(words).
What is the difference?'''
wordsPrueba = ['Maria','Rosa','ventana','mueble','termo','Ana','palabra','xenofobia','bobo']
print(sorted(wordsPrueba))
print(wordsPrueba)
wordsPrueba.sort()
print(wordsPrueba)
'''
18. Read in some text from a corpus, tokenize it, and print the
list of all wh-word types that occur. (wh-words in English are
used in questions, relative clauses and exclamations: who, which,
what, and so on.) Print them in order. Are any words duplicated
in this list, because of the presence of case distinctions or
punctuation?
'''
def allword(url,wordIni):
texto = load(url)
token = word_tokenize(texto)
#listWord = [w for w in token if re.search('^'+wordIni,w)]
listWord = []
for w in token:
if re.search('^'+wordIni,w.lower()) and w not in listWord:
listWord.append(w)
print(sorted(listWord))
return listWord
allword('textoEN.txt','wh')
'''
20. Write code to access a favorite webpage and extract some text
from it. For example, access a weather site and extract the forecast
top temperature for your town or city today.
'''
def has_title(tag):
return tag.has_attr('title')
def contentURL2(url,frase):
contenido = request.urlopen(url).read()#.decode('utf8')
#soup = BeautifulSoup(contenido, "lxml")
soup = BeautifulSoup(contenido, 'html.parser')
#texto1 = soup.find_all('title',string=re.compile(frase))
#texto1 = soup.find_all('img',attrs={'title':'WhatsApp'})
#listImg = soup.find_all('img')
listImg = soup.find_all(has_title)
listFrase = []
for w in listImg:
desc=w['title']
if frase.lower() in desc.lower() and desc not in listFrase:
listFrase.append(desc)
return listFrase
print('Noticias con la palabra Youtube',contentURL2('https://larepublica.pe/','Youtube'))
print('Noticias con la palabra Fujimorismo',contentURL2('https://larepublica.pe/','Fujimorismo'))
'''
21. Write a function unknown() that takes a URL as its argument,
and returns a list of unknown words that occur on that webpage.
In order to do this, extract all substrings consisting of lowercase
letters (using re.findall()) and remove any items from this set
that occur in the Words Corpus (nltk.corpus.words).
Try to categorize these words manually and discuss your findings.
'''
def unknown(url,wordsCorpus):
listTexto = contentURL(url)
texto = ' '.join(listTexto)
listLow = re.findall("[a-z]+", texto)
#print('solo minusculas',listLow)
#print('palabras de word corpus',wordsCorpus)
listWord = []
for w in listLow:
if w not in wordsCorpus and w not in listWord:
listWord.append(w)
return listWord
listWordsCorpus = words.words()
listUn= unknown('http://nltk.org/',listWordsCorpus)
print('palabras desconocidas',listUn)
'''
30. Use the Porter Stemmer to normalize some tokenized text,
calling the stemmer on each word. Do the same thing with the
Lancaster Stemmer and see if you observe any differences.
'''
porter = nltk.PorterStemmer()
lancaster = nltk.LancasterStemmer()
texto = load('textoEN2.txt')
tokTexto = word_tokenize(texto)
print([porter.stem(t) for t in tokTexto])
print([lancaster.stem(t) for t in tokTexto])
''' En espaol
'''
from nltk.stem import SnowballStemmer
stemmer = SnowballStemmer('spanish')
stemmer.stem('cuando')
text = load('textoES.txt')
stemmed_text = [stemmer.stem(i) for i in word_tokenize(text)]
print(stemmed_text)
''' En Portugues
'''
stemmer2 = SnowballStemmer('portuguese')
stemmer2.stem('quando')
text2 = load('textoPT.txt')
stemmed_text2 = [stemmer2.stem(i) for i in word_tokenize(text2)]
print(stemmed_text2)
'''
43. With the help of a multilingual corpus such as the
Universal Declaration of Human Rights Corpus (nltk.corpus.udhr),
and NLTK's frequency distribution and rank correlation
functionality (nltk.FreqDist, nltk.spearman_correlation),
develop a system that guesses the language of a previously
unseen text. For simplicity, work with a single character
encoding and just a few languages.
'''
from nltk.corpus import udhr
from nltk.metrics.spearman import *
def language(texto):
#fd = nltk.FreqDist(texto)
fd = nltk.FreqDist(word_tokenize(texto))
#print(list(fd))
#print(fd.most_common(50))
correlationMax = -10000
langFinal= '-Latin1'
for lang in udhr.fileids():
if lang[-7:]=='-Latin1':
fdu = nltk.FreqDist(word_tokenize(udhr.raw(lang)))
#fdu = nltk.FreqDist(udhr.raw(lang))
correlation = nltk.spearman_correlation(
list(ranks_from_sequence(fd)),
list(ranks_from_sequence(fdu)))
#print(fdu.most_common(50))
#print(lang,correlation)
if correlation > correlationMax:
langFinal = lang
correlationMax = correlation
return langFinal+',corr:'+str(correlationMax)
print(language(load('textoPT.txt')))
print(language(load('textoEN.txt')))
print(language(load('textoES.txt')))
| true |
dcf6a46087648db47ebe40b327c42941bf2f2957 | Python | JanKulbinski/Compression | /lab7/code.py | UTF-8 | 1,056 | 2.90625 | 3 | [] | no_license | from sys import argv
import sys
def readFile(name):
with open(name, "rb") as file:
byte = file.read()
bits = str(bin(int.from_bytes(byte,"big")))[2:]
front = '0'*((8 - (len(bits) % 8)) % 8)
return front + bits
def codeHamming(bits):
p1 = (int(bits[0]) + int(bits[1]) + int(bits[3])) % 2
p2 = (int(bits[0]) + int(bits[2]) + int(bits[3])) % 2
p3 = (int(bits[1]) + int(bits[2]) + int(bits[3])) % 2
p4 = (p1 + p2 + p3 + len([1 for i in bits if i == "1"])) % 2
return str(p1) + str(p2) + bits[0] + str(p3) + bits[1:] + str(p4)
if __name__ == "__main__":
if len(argv) != 3:
print("2 parameters required")
sys.exit()
source_file = argv[1]
output_file = argv[2]
bits = readFile(source_file)
result = ""
for index in range(0, len(bits), 4):
message = bits[index:(index+4)]
result += codeHamming(message)
result = int(result, 2).to_bytes(len(result) // 8, byteorder='big')
with open(output_file, "wb") as file:
file.write(result) | true |
7597ae68adc85c5d145985328503f54a9ff148f8 | Python | valen214/new-app | /code/multi.py | UTF-8 | 2,425 | 3.0625 | 3 | [] | no_license |
import hashlib
import multiprocessing as mp
X = "ManChingChiu"
Y = "17051909D"
hX = hashlib.sha256(bytes(X, "utf-8"))
hY = hashlib.sha256(bytes(Y, "utf-8"))
hX6 = hX.copy().digest()[:6]
def func(q):
"""
how to further optimize depends on which
operation takes the most time
"""
suffix = q.get()
if not suffix: return (False, None)
h = hY.copy()
h.update(suffix)
h = h.digest() # here?
if h[:6] == hX6: # or here
return (True, suffix)
else:
return (False, suffix)
def main():
manager = mp.Manager()
q = manager.Queue(256)
for b in [bytes([i]) for i in range(256)]:
q.put(b)
found = False
results = []
with mp.Pool(processes=8) as pool:
for i in range(256):
results.append(pool.apply_async(func, (q,)))
while not found:
success, suffix = results.pop(0).get()
if success:
found = suffix
elif suffix:
print(f"{suffix} failed, adding one more byte")
for b in [suffix + bytes([i]) for i in range(256)]:
q.put(b)
results.append(pool.apply_async(func, (q,)))
print(f"X = {X}")
print(f"Y' = {Y}{found.decode('utf-8')}")
if __name__ == "__main__":
main()
"""
import hashlib
def hashno(X, i):
return hashlib.sha256(bytes((X + str(i)), encoding= 'utf-8')).hexdigest()[:12]
def main():
X = "ManChingChiu"
Y = "17051909D"
hashtableX = [hashno(X, None)]
hashtableY = [hashno(Y,None)]
i = 0
print("plz wait a long long time")
while True:
tempX = hashno(X, i)
tempY = hashno(Y, i)
if tempX in hashtableY:
index = hashtableY.index(tempX)
break
elif tempY in hashtableX:
index = hashtableX.index(tempY)
break
else:
hashtableX.append(tempX)
hashtableY.append(tempY)
i += 1
if tempX in hashtableY:
print(tempX, hashtableY[index])
print(X+str(i), " ", Y+str(index-1))
elif tempY in hashtableX:
print(hashtableX[index], tempY)
print(X+str(index-1), " ", Y+str(i))
if __name__ == "__main__":
main()
#hashlib.sha256(bytes((X + str(i)), encoding= 'utf-8')).hexdigest()[:12]
#hashlib.sha256(bytes((Y + str(i)), encoding= 'utf-8')).hexdigest()[:12]
""" | true |
996c68d38abde8c209a86703bfb786e817b099c3 | Python | jenh/epub-ocr-and-translate | /eoat-printlang.py | UTF-8 | 724 | 3.4375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# Takes an input and prints only the language specified
# Usage: python print-lang.py [filename] [lang-code]
# i.e., python print-lang.py 04.md ru or python print-lang.py 04.md en
import sys
from langdetect import detect
input_file = sys.argv[1]
lang = sys.argv[2]
output_file = (input_file.rsplit(".", 1)[ 0 ]) + "_" + lang + ".md"
myfile = open(input_file,'r',encoding='utf-8')
output_file = open(output_file,'w',encoding='utf-8')
for line in myfile:
if line.isspace():
pass
else:
try:
if detect(line) == lang:
output_file.write(line + "\n")
else:
pass
except:
print("Cannot determine language for line: ",line)
output_file.write(line)
| true |
9060d147c3cc09cbbd5ac641508948306ca4a974 | Python | chinudev/hacker | /misc/geometric_trick.py | UTF-8 | 5,628 | 3.890625 | 4 | [] | no_license | #https://www.hackerrank.com/contests/w32/challenges/geometric-trick
import math
class FactorClass:
# we will be asked to factor a number <= maxN
def __init__(self, maxN):
"Create a prime store with primes <= sqrt(maxN)"
self.maxN = maxN
self.sqrtN = int(math.sqrt(maxN))
self.numList = [1 for i in range(0,maxN+1)]
self.numList[1] = 0
# mark all non-primes as 0
for i in range(2,self.sqrtN+1):
if self.numList[i] == 0: continue
for j in range(2*i,maxN+1,i): self.numList[j]=0
# convert prime into a linked list
prevPrime=2
for i in range(3,self.maxN+1):
if self.numList[i] != 0:
self.numList[prevPrime]=i
prevPrime=i
def isPrime(self, n):
if n > self.maxN:
raise Exception("range exceeded")
return self.numList[n] != 0
def getFactor(self,n):
"Return a list of prime factors and their powers for n"
" 18 => 2^1*3^2 => [2,1, 3,2] "
primeFactors = []
maxPrimeToTest = int(math.sqrt(n))
prime = 2
while (prime <= maxPrimeToTest):
if (n % prime == 0):
count = 0
while (n % prime == 0) :
n = int(n / prime)
count=count+1
primeFactors.append(prime)
primeFactors.append(count)
# follow linked list of prime to get next prime
prime = self.numList[prime]
if (n != 1) :
primeFactors.append(n)
primeFactors.append(1)
return primeFactors
def testFactor():
f = FactorClass(5*10**5)
print("20",f.getFactor(20))
print("200",f.getFactor(200))
print("93",f.getFactor(93))
print("31",f.getFactor(31))
def brute_force(s):
s="x"+s
count=0
for i in range(1,len(s)):
if (s[i] == 'b'): continue
if (s[i] == 'a'): rightChar='c'
else: rightChar='a'
for j in range(i+1,len(s)):
if (s[j] != 'b'): continue
k = int((j*j)/i)
if (k*i != j*j): continue
assert(k > i+1)
if (k >= len(s)): continue
if (s[k] == rightChar):
print(i,j,k,s[i],s[j],s[k])
count += 1
return count
def brute_force2(s):
s="x"+s
factorObj = FactorClass(5*10**5)
count=0
for k in range(len(s)-1,0,-1):
if (s[k] == 'b'): continue
if (s[k] == 'a'): leftChar='c'
else: leftChar='a'
factors = factorObj.getFactor(k)
delta = 1
for index in range(1,len(factors),2):
power=int((factors[index]+1)/2)
delta = delta * (factors[index-1] ** power)
#print(k,delta,factors)
for j in range(k-delta,0,-delta):
if (s[j] != 'b'): continue
i = int((j*j)/k)
if (k*i != j*j): continue # make sure these are even multiples
if (i >= j): continue # skip if i is too big
if (s[i] == leftChar):
#print(" match",i,j,k,s[i],s[j],s[k])
count += 1
return count
def geometricTrick(s):
factorObj = FactorClass(5*10**5)
s="X"+s
count=0
for i in range(1,len(s)):
if s[i] != 'b': continue
factors = factorObj.getFactor(i)
for index in range(1,len(factors),2):
factors[index] *= 2 # double since we square
#print("Found b at ",i,factors)
# iterate through all divisors
#
workingFactors=factors.copy() # make a copy that will change
workingNumber=i*i
while True:
# process this combination
#print("process",workingNumber, workingFactors)
if (workingNumber < len(s) and s[workingNumber] == 'a'):
secondNumber = int(i*i/workingNumber)
if secondNumber < len(s) and s[secondNumber] == 'c':
#print(" found match",workingNumber,i,secondNumber)
count += 1
if workingNumber == 1:
break
# pick next combination
for index in range(1,len(factors),2):
if workingFactors[index] == 0: continue
if workingFactors[index] != 0:
workingFactors[index] -= 1
workingNumber = int(workingNumber / workingFactors[index-1])
for revIndex in range(index-2,0,-2):
workingFactors[revIndex] = factors[revIndex]
workingNumber =workingNumber * (factors[revIndex-1]**factors[revIndex])
break
return count
#n = int(input().strip())
#s = input().strip()
s="cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca"
#print(brute_force(s))
#print(geometricTrick(s))
#print("expected 154")
s='ccaabbbcccbbaaccccbbbccaaabbabccccabbbbbbbbbbbbbbbb'
print(len(s))
print(brute_force2(s))
print(geometricTrick(s))
s='cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca' \
'cbaababaacccacabcbbabacccbaaccbacccaabaabbaacbbaabcaacabcabaababacbaabacbcccbbcccbcbaaacccccbaacbaacaabcabbaabcaabcababbccbbbabbbacacbcacbbbaabbbbcbabacbbbbaacbbabcacabbbccbbcbacccbcaaabacabccabaaabbcacbcaccbcbbbcabcacacacbccacaaacaccccaaabbaccbaccaccbbbbabbccaabcbaacaaccbccbabacbbaccabcaccbcabcabcbaaaacccaccbcacacbccabababbcaaaacbccaaababacaacabbabccccaabbbababbcbaaabaaaabbbabaaaacabacaacaaaaacaacccaacccbbbbaaabbcaaabccaccacbccbcbabbbbaabbbaacbabbabcaabbabcccabcacbabacccaaccacaacbbcbabbbbcbbcaccbabacbababbaaacbccccccbcabbbababbacacbcaccccacbcaabcbacabaccabccaccbbbacabaaccbaabcbbbcbbbcbccaacabbbcaaaaabbaacbbcabbccacacbaccbbacbbbaccababbbcbcbcbabcabacacaabbbcbaacccbbbaaccccabacabbaabacbccacbccbbacbaaabaccacabaaacaacbccaaaaaccabccbbacaacbccabacaabbbbccabcccbbcbbbacbbbacabcaccabbbaaababaaabbccaacaaaccacacccaacccbccaacabaaacbaacacbcacccabacbbaacaaccccabbaaacaaabbacaccaaccbababaabbccacbcbccaaccbcaabaccbbccacbccaabcbbbaabaababcaaabccbbbcaaccacbcccacaccaccaabbcbcbbbbacaabcbbbcbbbcbccabcbabaca'
#print("len=",len(s))
#print(brute_force(s))
print(geometricTrick(s))
print(brute_force2(s))
print("expected 2256")
| true |
d8f4140d2bb256c738ede90637c097b913bb3ffe | Python | fr33zik/servo_arm | /sources/rpi/rpi_gpio/demo_sw_rpigpio.py | UTF-8 | 391 | 2.921875 | 3 | [] | no_license | import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
sw_pwm = GPIO.PWM(21, 50)
sw_pwm.start(2.5)
try:
while 1: # Loop will run forever
sw_pwm.ChangeDutyCycle(10) # Move servo to 90 degrees
sleep(1)
sleep(1)
except KeyboardInterrupt:
pass
GPIO.cleanup()
| true |
6672eea595a242b4198316e0881e5c9d918954ae | Python | EugeneJenkins/pyschool | /Strings/21.py | UTF-8 | 195 | 3.296875 | 3 | [] | no_license | def isAllLettersUsed(word, required):
for c in required:
if c not in word:
return False
else:
return True
a=isAllLettersUsed('apple', 'google')
print (a) | true |
15d34333c9c01ffd072fdc024317140bb2a295c3 | Python | lsmoriginal/RPS_games | /players/Psychology.py | UTF-8 | 635 | 3.171875 | 3 | [] | no_license |
def win_action(action):
'''
return the action that would win the given action
'''
return (action + 1)%3
mymoves = [0]
oppmoves = []
def psycholoy_method(observation, configuration):
opp_last_act = observation.lastOpponentAction if observation.step != 0 else 0
oppmoves.append(opp_last_act)
if win_action(oppmoves[-1]) == mymoves[-1]:
# if you win the previous round
mymoves.append(win_action(mymoves[-1]))
# win yourself the next round
return win_action(mymoves[-1])
else:
mymoves.append(win_action(opp_last_act))
return win_action(opp_last_act)
| true |
6d613d8a84686ff284e9661636423258c5baa40a | Python | ryotosaito/sukkirisu | /src/sukkirisu.py | UTF-8 | 2,812 | 2.984375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import json
import urllib.parse
import urllib.request
import re
import sys
url = 'http://www.ntv.co.jp/sukkiri/sukkirisu/index.html'
def lambda_handler(event, context):
birth_month = int(urllib.parse.parse_qs(event['body'])['text'][0].rstrip())
result = get_sukkirisu(birth_month)
text = format_text(result)
return {
'isBase64Encoded': False,
'statusCode': 200,
'headers': {},
'body': json.dumps({
"response_type": "in_channel",
"text": text
})
}
def format_text(result):
return "{}月: {}\n{}\nラッキーカラー: {}\n(更新日: {})".format(
result["birth_month"],
result["type"] + (("(" + str(result["rank"]) + "位)") if 2 <= result["rank"] <= 11 else ''),
result["description"],
result["lucky_color"],
"/".join(result["modified_date"])
)
# argument:
# birth_month: month number you want to search sukkirisu result
# return:
# dict: {
# birth_month: int: argument
# modified_date: list: [month, date of month]
# rank: int: sukkirisu rank
# type: str: "超スッキリす" or "スッキリす" or "まぁまぁスッキリす" or "ガッカリす"
# description: str: fortune description
# lucky_color: str: lucky color
# }
def get_sukkirisu(birth_month):
if type(birth_month) != int:
raise TypeError("birth_month must be int.")
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as res:
body = res.read()
soup = BeautifulSoup(body, features="html.parser")
data = soup.find(id=("month"+str(birth_month)))
if 'type1' in data['class']:
rank = 1
type_ = "超スッキリす"
elif 'type4' in data['class']:
rank = 12
type_ = "ガッカリす"
else:
rank = int(data.find("p", class_="rankTxt").text.replace('位', ''))
type_ = ''
if 'type2' in data['class']:
type_ = "スッキリす"
elif 'type3' in data['class']:
type_ = "まぁまぁスッキリす"
return {
'birth_month': birth_month,
'modified_date': re.findall(r"\d+", soup.find("span", class_="date").text),
'rank': rank,
'type': type_,
'description': data.find("p", class_="").text,
'lucky_color': data.find("div", id="color").text
}
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.stderr.write("argument error: {} <month in int>\n".format(sys.argv[0]))
sys.exit(1)
result = get_sukkirisu(int(sys.argv[1]))
print(format_text(result))
| true |
b41f255751b756f4fb9ba589628d9406bbb4bb02 | Python | Yuudachi530/Assignment | /Programming Ex/s-2017-qp-23/q5_SearchFile.py | UTF-8 | 505 | 3.109375 | 3 | [] | no_license | LoginEvents = []
FileHolder = open('LoginFile.txt', 'r')
InfoHolder = FileHolder.readlines()
FileHolder.close()
def SearchFile():
UserIDInput = input('enter the user ID: ')
for i in InfoHolder:
if i[:5] == UserIDInput:
if i[-1:] == '\n':
s = i[:-1]
LoginInfo = [i[5:9], s]
else:
LoginInfo = [i[5:9], i[9:24]]
LoginEvents.append(LoginInfo)
SearchFile()
print(LoginEvents)
| true |
ac9c8d6dc1f6f1b2fae1c23fa54b3f2456895434 | Python | kvarada/constructiveness | /src/data/constructiveness_data_collector.py | UTF-8 | 11,480 | 2.90625 | 3 | [
"MIT"
] | permissive | #!/usr/local/bin/python3
__author__ = "Varada Kolhatkar"
import pandas as pd
import numpy as np
from normalize_comments import *
COMMENT_WORDS_THRESHOLD = 4
CONSTRUCTIVENESS_SCORE_THRESHOLD = 0.6
class ConstructivenessDataCollector:
'''
A class to collect training and test data for constructiveness
from different resources
'''
def __init__(self):
'''
'''
# initialize a dataframe for the training data
self.training_df = pd.DataFrame(columns=['comment_text', 'constructive', 'source'])
self.test_df = pd.DataFrame(columns=['comment_counter', 'comment_text', 'constructive'])
self.training_df_normalized = None
self.test_df_normalized = None
def get_positive_examples(self):
'''
:return:
'''
positive_df = self.training_df[self.training_df['constructive'] == 1]
return positive_df
def get_negative_examples(self):
'''
:return:
'''
negative_df = self.training_df[self.training_df['constructive'] == 0]
return negative_df
def normalize_comment_text(self, column = 'comment_text', mode = 'train'):
#start = timer()
#print('Start time: ', start)
if mode.startswith('train'):
df = self.training_df
else:
df = self.test_df
df_processed = parallelize(df, run_normalize)
#end = timer()
#print('Total time taken: ', end - start)
if mode.startswith('train'):
self.training_df_normalized = df_processed
else:
self.test_df_normalized = df_processed
def collect_training_data_from_CSV(self, data_csv, frac = 1.0, source = 'SOCC',
cols_dict={'constructive': 'constructive',
'comment_text': 'comment_text',
'comment_word_count': 'commentWordCount'}):
'''
:param data_csv:
:param frac:
:param cols_dict:
:return:
'''
df = pd.read_csv(data_csv, skipinitialspace=True)
df = df.sample(frac = frac)
if not cols_dict['comment_word_count'] in df:
df[cols_dict['comment_word_count']] = df[cols_dict['comment_text']].apply(lambda x: len(x.split()))
df.rename(columns={cols_dict['comment_text']: 'comment_text',
cols_dict['comment_word_count']:'comment_word_count',
cols_dict['constructive']: 'constructive'}, inplace = True)
df['source'] = source
# Select comments selected by NYT moderators as NYT pick and where the length
# of the comment is > COMMENT_WORDS_THRESHOLD
df['constructive'] = df['constructive'].apply(lambda x: 1 if x > CONSTRUCTIVENESS_SCORE_THRESHOLD else 0)
self.training_df = pd.concat([self.training_df, df[['comment_text', 'constructive', 'source',
'crowd_toxicity_level',
'constructive_characteristics',
'non_constructive_characteristics',
'toxicity_characteristics']]])
self.normalize_comment_text(mode='train')
#self.write_csv(output_csv)
def collect_positive_examples(self, positive_examples_csv, frac = 1.0, source = 'NYTPicks',
cols_dict = {'constructive':'editorsSelection',
'comment_text':'commentBody',
'comment_word_count': 'commentWordCount'}):
'''
:param positive_examples_csv:
:param frac:
:param cols_dict:
:return:
'''
df = pd.read_csv(positive_examples_csv, skipinitialspace=True)
df = df.sample(frac = frac)
if not cols_dict['comment_word_count'] in df:
df[cols_dict['comment_word_count']] = df[cols_dict['comment_text']].apply(lambda x: len(x.split()))
df.rename(columns={cols_dict['comment_text']: 'comment_text',
cols_dict['comment_word_count']:'comment_word_count',
cols_dict['constructive']: 'constructive'}, inplace = True)
df['source'] = source
df['crowd_toxicity_level'] = np.NaN
df['constructive_characteristics'] = np.NaN
df['non_constructive_characteristics'] = np.NaN
df['toxicity_characteristics'] = np.NaN
# Select comments selected by NYT moderators as NYT pick and where the length
# of the comment is > COMMENT_WORDS_THRESHOLD
positive_df = df[
(df['constructive'] == 1) & (df['comment_word_count'] > COMMENT_WORDS_THRESHOLD)]
self.training_df = pd.concat([self.training_df, positive_df[['comment_text', 'constructive', 'source',
'crowd_toxicity_level',
'constructive_characteristics',
'non_constructive_characteristics',
'toxicity_characteristics'
]]])
self.normalize_comment_text(mode='train')
return positive_df
def collect_negative_examples(self, negative_examples_csv, frac = 1.0, source = 'YNACC',
cols_dict = {'comment_text': 'text',
'constructive': 'constructiveclass'}):
'''
:param negative_examples_csv:
:param frac:
:param cols_dict:
:return:
'''
if negative_examples_csv.endswith('tsv'):
df = pd.read_csv(negative_examples_csv, sep='\t')
else:
df = pd.read_csv(negative_examples_csv)
df = df.sample(frac = frac)
df.rename(columns={cols_dict['comment_text']: 'comment_text'}, inplace=True)
df['comment_word_count'] = df['comment_text'].apply(lambda x: len(x.split()))
df['source'] = source
df['crowd_toxicity_level'] = np.NaN
df['constructive_characteristics'] = np.NaN
df['non_constructive_characteristics'] = np.NaN
df['toxicity_characteristics'] = np.NaN
df_subset = df[(df['comment_word_count'] > COMMENT_WORDS_THRESHOLD) & (
df[cols_dict['constructive']].str.startswith('Not'))]
negative_df = df_subset.copy()
negative_df['constructive'] = negative_df[cols_dict['constructive']].apply(lambda x: 0 if x.startswith('Not') else 1)
self.training_df = pd.concat([self.training_df, negative_df[['comment_text', 'constructive', 'source',
'crowd_toxicity_level',
'constructive_characteristics',
'non_constructive_characteristics',
'toxicity_characteristics'
]]])
return negative_df
def gather_test_data(self, test_data_file, frac = 1.0,
cols_dict={'comment_text': 'comment_text',
'constructive': 'is_constructive'}):
'''
:param test_data_file:
:param frac:
:param cols_dict:
:return:
'''
df = pd.read_csv(test_data_file)
df = df.sample(frac = frac)
df.rename(columns={cols_dict['comment_text']:'comment_text'}, inplace = True)
df['constructive'] = df[cols_dict['constructive']].apply(lambda x: 1 if x.startswith('yes') else 0)
df = df.sort_values(by=['constructive'], ascending = False)
self.test_df = pd.concat([self.test_df, df[['comment_counter', 'comment_text', 'constructive']]])
def collect_train_data(self,
positive_examples_csvs,
negative_examples_csvs):
'''
:param positive_examples_csvs:
:param negative_examples_csvs:
:return:
'''
## Collect Training data
# Collect non-constructive examples to the training data
for (source_csv, fraction) in negative_examples_csvs:
df = self.collect_negative_examples(source_csv, frac=fraction)
print('The number of negative examples collected from source: \n', source_csv, '\nFraction: ', fraction,
'\n is: ', df.shape[0])
print('---------------------------')
for (source_csv, fraction) in positive_examples_csvs:
df = self.collect_positive_examples(source_csv, frac = fraction)
print('The number of positive examples collected from source: \n', source_csv, '\nFraction: ', fraction,
'\n is: ', df.shape[0])
print('---------------------------')
# Normalize comment text
self.normalize_comment_text()
negative_df = self.get_negative_examples()
positive_df = self.get_positive_examples()
print('\n\n')
print('Total number of positive examples: ', positive_df.shape[0])
print('Total number of negative examples: ', negative_df.shape[0])
def collect_test_data(self, test_csvs, output_csv):
'''
:param test_csvs:
:param output_csv:
:return:
'''
# Collect test data
for (test_csv_file, fraction) in test_csvs:
self.gather_test_data(test_csv_file, frac=fraction)
# Normalize the comments
self.normalize_comment_text(mode='test')
# Write test data CSV
self.write_csv(output_csv, mode='test',
cols=['comment_counter', 'comment_text', 'pp_comment_text', 'constructive'])
def write_csv(self, output_csv, mode ='train', cols = ['comment_text', 'pp_comment_text',
'constructive', 'source',
'crowd_toxicity_level',
'constructive_characteristics',
'non_constructive_characteristics',
'toxicity_characteristics'], index = False):
'''
:param output_csv:
:param mode:
:param cols:
:param index:
:return:
'''
print('\n')
if mode.startswith('train'):
print('The number of training examples: ', self.training_df_normalized.shape[0])
self.training_df_normalized.to_csv(output_csv, columns=cols, index = index)
print('Training data written as a CSV: ', output_csv)
elif mode.startswith('test'):
print('The number of test examples: ', self.test_df_normalized.shape[0])
self.test_df_normalized.to_csv(output_csv, columns=cols, index = index)
print('Test data written as a CSV: ', output_csv)
else:
print('Invalid mode!!')
| true |
c7145352f7da20cca584a19a59bd8cf64a1cac64 | Python | satojkovic/algorithms | /problems/test_move_zeros.py | UTF-8 | 1,115 | 2.953125 | 3 | [] | no_license | import unittest
from move_zeros import move_zeros1, move_zeros2, move_zeros3, move_zeros4
from nose.tools import eq_
class TestMoveZeros(unittest.TestCase):
def setUp(self):
self.test_cases = []
self.test_cases.append([0, 1, 0, 3, 12])
self.test_cases.append([0])
self.test_cases.append([1])
self.results = []
self.results.append([1, 3, 12, 0, 0])
self.results.append([0])
self.results.append([1])
def test_move_zeros1(self):
for test_case, result in zip(self.test_cases, self.results):
eq_(move_zeros1(test_case), result)
def test_move_zeros2(self):
for test_case, result in zip(self.test_cases, self.results):
eq_(move_zeros2(test_case), result)
def test_move_zeros3(self):
for test_case, result in zip(self.test_cases, self.results):
eq_(move_zeros3(test_case), result)
def test_move_zeros4(self):
for test_case, result in zip(self.test_cases, self.results):
eq_(move_zeros4(test_case), result)
if __name__ == "__main__":
unittest.main() | true |
c8c6270292d42b41ea136e26c5ac4b7a75a6bc11 | Python | johnbrannstrom/zipato-extension | /src/error.py | UTF-8 | 402 | 2.703125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
.. moduleauthor:: John Brännström <john.brannstrom@gmail.com>
Error
******
This module contains exceptions.
"""
class ZipatoError(Exception):
def __init__(self, message):
"""
Constructor function.
:param str message:
"""
self._message = message
def __str__(self):
"""
String function.
"""
return self._message
| true |
6a99b44f633f35f38c788d2e123fa0d507c50cc9 | Python | exe1099/Backplane | /Debugging/curses_table.py | UTF-8 | 482 | 3.0625 | 3 | [] | no_license | import tableprint as tp
import numpy as np
import time
print(tp.header(["A", "B", "C"], width=20) )
for x in range(3):
data = np.random.randn(3)
print(tp.row(data, width=20), flush=True)
time.sleep(1)
data = np.random.randn(3)
print(tp.row(data, width=20), flush=True)
time.sleep(1)
data = np.random.randn(3)
print(tp.row(data, width=20), flush=True)
time.sleep(1)
print(tp.header(["A", "B", "C"], width=20) )
print(tp.bottom(3, width=20)) | true |
9839c36b84c2a0d43c22db8dcbc2664d0ea1a103 | Python | Buenz/python | /1/price.cost.py | UTF-8 | 423 | 3.046875 | 3 | [] | no_license | import os, pandas as pd, math
dirpath = os.getcwd()
print("Current directory is the following: " + dirpath)
g=input("Please insert path to file + file.txt: ")
print("Please see minimum price below:\n")
#g="/Users/harrisonbueno/Desktop/NMI/product_costs.txt"
file_txt=pd.read_csv(g, sep=" ", header=None)
for i in range(file_txt.shape[0]):
print(f"Line {i+1}: {int(math.ceil(file_txt[0][i]/(1-file_txt[1][i])))}")
| true |
ce673e16210e72b7cba0120dea899165bc5d7348 | Python | jakecoffman/euler-solutions | /5.py | UTF-8 | 231 | 3.5625 | 4 | [] | no_license | def is_divisible(number):
for i in xrange(21, 2, -1):
if number%i != 0:
return False
return True
i = 20
while True:
if is_divisible(i):
print i
break
i += 20
| true |
5b7ce5b356f9fbae6acb10ee6736e7e0075cd9a6 | Python | amoantony/python-codes-begginers- | /divisible by number.py | UTF-8 | 172 | 3.765625 | 4 | [] | no_license | print("Enter no of numbers ")
ra=int(input())
for i in range(ra):
mylist[i]=int(input("Enter number ",i))
for i in range(5):
print("Number 1 is :",mylist[i])
| true |
bfb888b4feeb501302b393155fab270d6322f110 | Python | AdvTop-ML-Team3/Project | /main.py | UTF-8 | 4,983 | 2.890625 | 3 | [] | no_license | import argparse
import numpy as np
import specifications
from wrapped import train, predict
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--num_train', "-train", type=int, default=100, help='Size of the training dataset, 1 to 1000')
# -4, -5 denotes extra tasks "shortest path" and "eulerian circuit" respectively
parser.add_argument('--task_id', "-task", type=int, default=18, help='Which bAbI task to perform. Valid values = 4,15,16,18,19,-4,-5')
parser.add_argument('--hidden_layer_dim', "-hidden", type=int, default=None, help='Dimension of the hidden layer')
parser.add_argument('--num_steps', "-step", type=int, default=5, help='Number of steps to unroll the propagation process') #Paper uses 5 steps (Ref: Section 5.1)
parser.add_argument('--epochs', "-e", type=int, default=10, help='Number of training epochs')
parser.add_argument('--batch_size', "-b", type=int, default=10, help='Mini batch size')
parser.add_argument('--model', '-m', type=str, default='ggnn', help='The neural network used to solve the task')
'''
For bAbI task 4, there are 4 types of questions: n,w,e,s - encoded as 0,1,2,3. (Ref: Weston, Jason, et al).
In the GGSNN paper (Ref: Li, Yujia, et al), the authors propose "training a separate GG-NN for each task".
Moreover, "When evaluating model performance, for all bAbI tasks that contain more than one questions in
one example [here, Task 4], the predictions for different questions were evaluated independently."
(section titled: More Training Details)
Hence, task 4's individual questions were evaluated separately.
Here, question id has default value 0 for other tasks.
'''
parser.add_argument('--question_id', "-q", type=int, default=0, help='Task 4 has 4 questions. Please enter the question id (0-3)')
'''
From the section titled "More training details" in the assigned paper,
"For all tasks in this section, we generate 1000 training examples and 1000 test examples,
50 of the training examples are used for validation. As there is randomness in the dataset
generation process, we generated 10 such datasets for each task, and report the mean and
standard deviation of the evaluation performance across the 10 datasets."
Here, the input can be any number from 1 to 10.
The default value is 0, indicating the calculation of average accuracy across all datasets.
'''
parser.add_argument('--dataset_id', "-data" , type=int, default=0, help='There are 10 datasets per task, 1-10. Enter 0 to calculate the average across all datasets')
args = parser.parse_args()
if not check_valid(args):
return
print_intro_message(args)
accuracy = []
data_ids = [args.dataset_id] if args.dataset_id else range(1, 11)
for i in data_ids:
args.dataset_id = i
train_output = train(args)
test_output = predict(args, train_output['net'])
accuracy.append(np.mean(test_output['accuracy']))
print("Results obtained for task ", specifications.TASK_NAMES[args.task_id],
(args.task_id == 4) * ("for question: " + str(args.question_id)),
"using the ",args.model, " architecture with", args.num_train, "training examples is", "{:.2f}%".format(np.mean(accuracy) * 100))
def check_valid(args):
args.model = args.model.lower()
args.hidden_layer_dim = args.hidden_layer_dim or (8 if args.model == 'ggnn' else 50)
checks = [
(args.question_id == 0 or (args.task_id == 4 and args.question_id in range(4)),
"Please enter a valid question id, tasks other than task 4 can only have question id 0"),
(args.dataset_id in range(11), "Please enter a valid dataset id (0-10)"),
(args.task_id in specifications.SUPPORTED_TASKS, "Task id is not supported."),
(args.model in specifications.SUPPORTED_NETS, "Model is not supported.")
]
print('\n'.join([msg for check, msg in checks if not check]))
return all([check for check, msg in checks])
def print_intro_message(options):
print_msg("An implementation of the paper \"Gated Graph Sequence Neural Networks\" by Yujia Li et al.")
print_msg("In this implementation, we deal with", len(specifications.TASK_NAMES), "tasks: " +
', '.join('Task ' + str(tid) + ':(' + name + ')' for tid, name in specifications.TASK_NAMES.items()) + '.')
print("\n")
print_msg("Task selected:", options.task_id, specifications.TASK_NAMES[options.task_id])
print_msg("Architecture selected:", options.model)
def print_msg(*args):
if specifications.VERBOSE:
print(*args)
if __name__ == "__main__":
main()
'''
Reference:
- Li, Yujia, et al. "Gated graph sequence neural networks." arXiv preprint arXiv:1511.05493 (2015).
- Weston, Jason, et al. "Towards ai-complete question answering: A set of prerequisite toy tasks." arXiv preprint arXiv:1502.05698 (2015).
'''
| true |
2f75992f55b740abf7374ff787c1837355d2e3ce | Python | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /completed Tutorials/Functions.py | UTF-8 | 367 | 4.5 | 4 | [] | no_license | #Functions have to be declared at first then later only the main program comes
def firstFunc():
print ('This is my first function')
def secondFunc(number,string):
print('This function takes in parameters of two types\n')
print('This is a number ' + str(number))
print('This is a string ' + string)
#main program
firstFunc()
secondFunc(7,'Nazhim')
| true |
49d52dff2dc39748b570e265aeb55e37c23262c9 | Python | D4r7h-V4d3R/Ornekler | /reduce().py | UTF-8 | 584 | 3.65625 | 4 | [] | no_license | from functools import reduce
#Bir Listenin en Büyük elemanını bulmak
#Birinci Yol
liste = [1,2,32,54,3,63,74,2,45,24,62,4]
print(max(liste))
#İkinci Yol
q = lambda a,b: a if (a>b) else b
print(reduce(q,liste))
#Bence bir yolu daha var X)
yenil = []
for i in liste:
if i >50:
yenil.append(i)
print(yenil)
#Ve daha niceleri...
#Biraz daha reduce() ornekliyelim.hmm faktoriyel..
calc = lambda x , y: x*y
print(reduce(calc,[1,2,3,4,5,6,7,8,9]))
#yazmaya usenenler ıcın --.
#print(reduce(calc ,[x for x in range(1,10)])) #1 dahil 10 haric
| true |
64649bd48473b3905b43103791f3deb4b018ef10 | Python | msullivancm/CursoEmVideoPython | /Mundo2-ExerciciosEstruturasDeRepeticao/ex068.py | UTF-8 | 695 | 4.03125 | 4 | [] | no_license | from random import randrange
print('=-'*20)
print('Vamos jogar Par ou Impar')
print('=-'*20)
while True:
n = int(input('Digite um valor: '))
pi = input('Par ou ímpar? [P/I]')
comp = randrange(0,10,1)
total = (n + comp)
if total % 2 == 0:
print(f'Você jogou {n} e o computador jogou {comp}. Total de {total} Deu PAR')
if pi == 'P':
print('Você venceu!')
else:
print('Você perdeu!')
break
else:
print(f'Você jogou {n} e o computador jogou {comp}. Total de {total} Deu IMPAR')
if pi == 'I':
print('Você venceu!')
else:
print('Você perdeu!')
break
| true |
e904e7da2d606ab03163f14398553d0f9f5a9685 | Python | kragebein/PythonFun | /pat/durr.py | UTF-8 | 1,847 | 3.1875 | 3 | [] | no_license | #!/usr/bin/python3.8
import requests
from bs4 import BeautifulSoup
search = 'https://mrplant.se/en/product-search/'
url = 'https://mrplant.se/'
input = ''
with open('input.txt', 'r') as brrt:
input = brrt.read().split('\n')
brrt.close()
print('parsing {} items\n'.format(len(input)))
def get(id):
x = requests.get(search + id)
if x.status_code == 200:
return x.text
else:
return False
def parse(i):
x = requests.get(url + i)
if x.status_code != 200:
return False
soup = BeautifulSoup(x.text, 'html.parser')
title = soup.find('title')
#print('Parsing {}'.format(title.string.strip()))
data = soup.find('div', {'id': 'productInfo'})
text = data.text.split('\n')
text = list(filter(None, text))
name = text[0].strip()
ind = 0
color = None
size = None
#Process data. To add more entries, add an elif, look for 'blah' in x:
# add the variable above this comment as blah = None, and blah = 'Whatever' + text[ind+1]
# also add it to the important output below
for x in text:
if 'Colour' in x:
color = text[ind+1].strip()
elif 'Height' in x:
size = 'Height' + text[ind+1]
elif 'Length' in x:
size = 'Length' + text[ind+1]
elif 'Diameter' in x:
size = 'Diameter' + text[ind+1]
ind += 1
output = '{};{};{}'.format(name, color, size) #important
print(output)
with open('output.txt', 'a') as brrt:
brrt.write(output + '\n')
brrt.close()
for item in input:
data = get(item)
soup = BeautifulSoup(data, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
if item in link.get('href') and 'item' in link.get('href'):
parse(link.get('href'))
| true |
d4364810822a927dd61b5cbc322d404e1801e8fd | Python | SudhirGhandikota/LeetCode | /Python_solutions/twoSum.py | UTF-8 | 418 | 3.21875 | 3 | [] | no_license | class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
visited = {}
for idx, num in enumerate(nums):
diff = target - num
if diff in visited:
return [visited[diff], idx]
visited[num] = idx
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
solution = Solution()
print(solution.twoSum(nums, target)) | true |
976957ba5ea0c557e39b76126b423b181c73a991 | Python | mrfourfour/tcp_to_http | /HTTP/Http.py | UTF-8 | 2,376 | 2.890625 | 3 | [] | no_license | import socket
# 서버키는거, 라우트 매핑, 반환< 이건 해야댐
class Http(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.routers = {}
def not_found(self):
return "404 Not Found"
def route(self, routerName, methods=["GET"]):
def wraps(f):
self.routers[routerName.lower()] = {
"func":f,
"methods":methods
}
return f
return wraps
def routerHandler(self, data):
try:
func, method = self.routers[data.lower()].values()
except :
func = self.not_found
method = True
return (func, method)
def httpDataParser(self,data):
method = data[0]
route = data[1].split('?')
if len(route) > 1:
route, query = route
querys = query.split("&")
query = {}
for q in querys:
q=q.split("=")
query[q[0]]=q[1]
print(route,"?")
return {"method":method, "route":route, "query":query}
else:
route = route.pop()
return {"method":method, "route":route, "query":None}
def request(self, f,data):
if data['query']:
try:
data = f(**data['query'])
return "HTTP/1.1 200 OK\n Content_Type: text/html\n\n"+str(data)
except:
return "HTTP/1.1 400 Bad Request\n Content_Type: text/html\n\n"+"Bad Request"
return "HTTP/1.1 400 Bad Request\n Content_Type: text/html\n\n"+str(f())
def runServer(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((self.host, self.port))
sock.listen(True)
print('RUNNING SERVER')
while True:
conn, addr = sock.accept()
req = str(conn.recv(1024))[2:-1].split()
# 여기에 뭔가 로직이 들어가는 함수를 하나 만들어 봅시다.
req = self.httpDataParser(req)
print(req)
print(req['route'])
func, method = self.routerHandler(req['route'])
req = self.request(func,req)
conn.sendall(req.encode())
conn.close()
| true |
1fc25fba92542c70729bb78fdd68a1f82aa7b3b0 | Python | Aasthaengg/IBMdataset | /Python_codes/p03074/s842788646.py | UTF-8 | 339 | 2.671875 | 3 | [] | no_license | n, k = map(int, input().split())
s = input()
l = [0]
for i in range(n - 1):
if s[i] != s[i + 1]:
l.append(i + 1)
l += [n]
le = len(l)
ans = 0
for i in range(le - 1):
if s[l[i]] == "0":
ans = max(ans, l[min(le - 1, k * 2 + i)] - l[i])
else:
ans = max(ans, l[min(le - 1, k * 2 + i + 1)] - l[i])
print(ans) | true |