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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0ebc2cb90676e41b1ffdcbf898847452dfca09f0 | Python | Shawley-Codes/Incrementor | /increment+2.py | UTF-8 | 7,403 | 4 | 4 | [] | no_license | #6/5/2019
#Scott Hawley
#imports
import time
#Incrementor
#Class holds 2 functions
class incrementor:
#Score
#increment score based on current increment amount over time, then print
def scoreInc(score, increment):
score += increment
print("Score: ", score)
#Money
#increment money based on current increment amount over time, then print
def moneyInc(money, increment):
money += increment
print("Money: ", money)
#Money Management
#class holds 3 functions
class manageMoney:
#Use data structures to return multiple values to program
#experiment 1: arrays
#Buy
#takes in target name and current money
#decreases money if successful purchase, changes increment amounts
#print on unsuccessful purchase
#def buy(target, money, incrementMoney, incrementScore):
def buy(target, tracker):
targetPrice = tracker[0]
if target == "Score":
targetPrice = 30
elif target == "Money":
targetPrice = 50
if tracker[0] >= targetPrice:
tracker[0] -= targetPrice
print("\nSuccessful purchase")
if targetPrice == 50:
tracker[3] += 5
tracker[4] += 10
return tracker
#incrementScore += 10
#incrementMoney += 5
elif targetPrice == 30:
tracker[3] += 1
tracker[4] += 20
return tracker
#incrementScore += 20
#incrementMoney += 1
else:
print("\nYou did not have enough money")
return tracker
#Save
#takes in amount to store, current money, currently stored
#decreases money if successful store, increase amount stored
#print on unsuccessuful storage
#print amount in bank
#use tracker instead
def save(store, tracker):
if tracker[0] >= store:
tracker[0] -= store
tracker[2] += store
else:
print("You tried to store more money than you have!")
print("\nYou currently have $", tracker[2], " stored in the bank.")
return tracker
#Withdraw
#takes in amount to withdraw, current money, currently stored
#increase money on successful withdraw, decrease amount stored
#print on unsuccessful withdraw
#print amount in bank
def withdraw(draw, tracker):
if draw <= tracker[2]:
tracker[0] += draw
tracker[2] -= draw
else:
print("You tried to withdraw more money thank you have stored.")
print("You currently have $", tracker[2], " stored in the bank.")
return tracker
#Play Loop
playAgain = "yes"
#Reset Game variables
while playAgain == "yes":
#experiment 1: arrays
#add all values to array "tracker"
tracker = [100,0,0,1,0,.1]
#money = 100
#score = 0
#bank = 0
#incrementMoney = 1
#incrementScore = 0
#incrementBank = .1
roundNum = 1
#Main Game Loop
#Commands: Buy, Withdraw, Save, Wait
#Get input on number of rounds
print("Welcome to the incrementor game!\n")
rounds = input("Please enter the amount of rounds(recommended 30): ")
#input validation
correctRounds = False
while correctRounds == False:
try:
val = int(rounds)
if val < 0:
rounds = input("Invalid. Please enter a positive number: ")
else:
correctRounds = True
except ValueError:
rounds = input("Invalid. Please enter the amount of rounds: ")
for num in range(0, int(rounds)):
#Print round number, then get user input/validate
print("\nRound ", roundNum)
command = input("Please enter a command(Buy, Save, Withdraw, Wait): ")
while command != "Buy" and command != "Save" and command != "Withdraw" and command != "Wait":
command = input("Invalid! Please enter a command(Buy, Save, Withdraw, Wait): ")
#run commands
#buy command, print available options for purchase, get input, validate
#call class function, Buy
if command == "Buy":
print("\nCurrently available to purchase:\nScore Earner: $30\nMoney Earner: $50")
target = input("\nPlease enter which to purchase(Score or Money): ")
while target != "Score" and target != "Money":
target = input("Please enter which to purchase(Score or Money): ")
#manageMoney.buy(target, money, incrementMoney, incrementScore)
#give in target, and tracker values
tracker = manageMoney.buy(target, tracker)
#validate by try except
elif command == "Withdraw":
print("Welcome to the bank! Your savings is: $", tracker[2])
draw = input("Please enter the amound you wish to withdraw: $")
correctDraw = False
#input validation
while correctDraw == False:
try:
val = int(draw)
if val < 0:
draw = input("Invalid. Please enter a positive number: $")
else:
correctDraw = True
except ValueError:
draw = input("Invalid. Please enter the amount you wish to withdraw: $")
tracker = manageMoney.withdraw(int(draw), tracker)
elif command == "Save":
print("Welcome to the bank! Your savings is: $", tracker[2])
print("Your are currently holding: $", tracker[0])
store = input("Please enter the amount you wish to save: $")
#Validation for input of int
#create loop for continous check
#check wether value causes Value error or is negative, let out if neither
correctStore = False
while correctStore == False:
try:
val = int(store)
if val < 0:
store = input("Invalid. Please enter a positive number: $")
else:
correctStore = True
except ValueError:
store = input("Invalid. Please enter the amount you wish to save: $")
#officially cast as int then send into function
tracker = manageMoney.save(int(store), tracker)
else:
print("You decided to wait!")
#increment numbers and print data
#use array to print data
tracker[0] += tracker[3]
tracker[1] += tracker[4]
tracker[2] = (tracker[2]*tracker[5]) + tracker[2]
print("\nScore: ", tracker[1])
print("Money: ", tracker[0])
print("Stored: ", tracker[2])
#money += incrementMoney
#score += incrementScore
#bank = (bank*incrementBank) + bank
#print("\nMoney: $", money)
#print("Score: ", score)
#print("Stored: $", bank)
roundNum = roundNum + 1
playAgain = input("\n\nDo you want to play again (yes or no): ")
| true |
3cbff2900f2f273eae26d8e66a6adfd8e2124c84 | Python | icantnotfindaname/smi_project | /main.py | UTF-8 | 1,638 | 2.734375 | 3 | [] | no_license | """
@Constant:
learning_rate = 0.1
batch_size = 64
epoch = 5 # 测试阶段 真正训练需要百代以上
model_save_path = ''
"""
def train_pathnet(cpu = True,):
# 一些常量
learning_rate = 0.1
batch_size = 64
epochs = 1 # 将整体数据迭代多少代
# TODO: 改造主程序 封装pathnet训练函数和 overlapnet训练函数
if __name__ == '__main__':
# 先制作 DataLoader
trainset = dataset_module.PN_dataset('train_pathnet',
transform=transforms.ToTensor())
train_loader = DataLoader(trainset,batch_size=batch_size,shuffle=True,num_workers=2)
# 定义 网络
net = net_modules.PathNet()
# 定义学习相关的一系列参数 , 优化器 等
loss = nn.MSELoss() # 损失函数 (1/n)*|x-y|^2
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
scheduler = optim.lr_scheduler.StepLR(optimizer,step_size=5, gamma=0.05) # 每5个epoch 调整一下学习率
for epoch in range(epochs):
print('Epoch {}/{}'.format(epoch+1,epochs))
print('--'*10)
net.train()
lossss = 0 # 用来计算loss
for batch_id, sample in enumerate(train_loader):
input_batch = sample['input']
labels = sample['label']
outputs = net(input_batch)
losses = loss(outputs, labels)
losses.backward()
optimizer.zero_grad()
optimizer.step()
lossss += losses.item()
print('平均loss = {}'.format(lossss / batch_size))
scheduler.step()
| true |
0ab1b68f17bd6f88cfae7dcd5e19756b9d34f58f | Python | sadatusa/PCC | /8_11.py | UTF-8 | 698 | 4.53125 | 5 | [] | no_license | # 8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the
# function make_great() with a copy of the list of magicians’ names. Because the
# original list will be unchanged, return the new list and store it in a separate list.
# Call show_magicians() with each list to show that you have one list of the original
# names and one list with the Great added to each magician’s name.
magicians_list=['kareem','jhons','michale']
great_magicians=[]
def make_great(magicians,greatmagician):
for x in range (0,len(magicians)):
greatmagician.append('The great '+magicians[x])
make_great(magicians_list,great_magicians)
print(magicians_list)
print(great_magicians) | true |
d4db69920278bff4f18034436df06ce79d6090f7 | Python | laobadao/Python_Learn | /PythonNote/ml/knn/knn.py | UTF-8 | 5,189 | 3.609375 | 4 | [
"Apache-2.0"
] | permissive | # -*- coding: UTF-8 -*-
"""
k-近邻算法步骤如下:
计算已知类别数据集中的点与当前点之间的距离;
按照距离递增次序排序;
选取与当前点距离最小的k个点;
确定前k个点所在类别的出现频率;
返回前k个点所出现频率最高的类别作为当前点的预测分类。
"""
import numpy as np
import operator
"""
函数说明:创建数据集
:parameter 无
:returns
group - 数据集
labels -分类标签
:date
2017-9-29
"""
def createDataSet():
# 四组二维特征, [ 打头镜头, 接吻镜头 ]
group = np.array([[1, 101], [5, 89], [108, 5], [115, 8]])
labels = ['爱情片', '爱情片', '武侠片', '武侠片']
return group, labels
if __name__ == '__main__':
group, labels = createDataSet()
print(group)
print(labels)
"""
函数说明:KNN 算法,分类器
:parameter
testX - 用于分类的数据 (测试集)
trainSet - 用于训练的数据 (训练集)
labels - 用于分类的标签
k - kNN 算法参数,选择距离最小的 k 个点
:return
sortedClassCount[0][0] 分类结果
:date
2017-09-29
"""
"""
note:
补充 numpy 函数
1. 创建二维数组
2. 求数组行数
3. 求数组列数
"""
# if __name__ == '__main__':
# testArray = np.array([[1., 2.], [2., 3.], [3., 4.], [4., 5.], [5., 6.]])
# row = testArray.shape[0]
# column = testArray.shape[1]
# print("行:", row, " 列:", column)
def classify0(testX, trainSet, labels, k):
# numpy函数 shape[0] 返回 trainSet 的行数
trainSetSize = trainSet.shape[0]
# 在列向量方向上重复 testX 共1次(横向),行向量方向上重复 testX 共dataSetSize次(纵向)
# np.tile(testX, (trainSetSize, 1)) 是为了 将测试数据 test = [101, 20] 构造成 和 训练集相同的数据形式
# 这样可以使用 欧式距离公式 多个维度之间的距离公式
# 在欧几里得空间中,点x = (x1, ..., xn)和 y = (y1, ..., yn)之间的欧氏距离为
diffMat = np.tile(testX, (trainSetSize, 1)) - trainSet
print("testX:", testX)
print("trainSet:", trainSet)
print("diffMat:", diffMat)
# 二维特征相减后平方
sqDiffMat = diffMat ** 2
print("sqDiffMat:", sqDiffMat)
# sum()所有元素相加,sum(0)列相加,sum(1)行相加 axis=0表示按列相加,axis=1表示按照行的方向相加
sqDistances = sqDiffMat.sum(axis=1)
print("sqDistances:", sqDistances)
# 开方,计算出距离
distances = sqDistances ** 0.5
print("distances:", distances)
# distances: [ 128.68954892 118.22436297 16.55294536 18.43908891]
# 返回distances中元素从小到大排序后的索引值 因为函数返回的排序后元素在原array中的下标
# 上面四个数 在array中的下标 索引是 128.68954892 - 0 ,118.22436297- 1 ,16.55294536 - 2 ,18.43908891- 3
# 排序后是 16.55294536 18.43908891 118.22436297 128.68954892 所以 索引 下标的排序就是 2 3 1 0
sortedDistIndices = distances.argsort()
print("sortedDistIndices", sortedDistIndices)
# sortedDistIndices [2 3 1 0]
# 定一个记录类别次数的字典 字典 类似于 map 存储 键值对
classCount = {}
for i in range(k):
# 取出前k个元素的类别
print("sortedDistIndices[i]:", sortedDistIndices[i])
print("labels:", labels)
voteIlabel = labels[sortedDistIndices[i]]
print("voteIlabel:", voteIlabel)
print("classCount:", classCount)
# dict.get(key,default=None),字典的get()方法,返回指定键的值,如果值不在字典中返回默认值。
# 计算类别次数 比如 第一次 加入 武侠片时 先取之前存过的 武侠片的值 没有则默认 0 classCount.get(voteIlabel, 0)
# 也就是 2 对应的 武侠片 先存到 classCount 字典中 然后 累加次数
# 爱情片 同理 第一次 字典中没有 因为是空的 或者 只有武侠 或只有爱情 然后默认0 再加1
# 循环到 i =1 取出 索引 3 的值 对应的 labels 是武侠 再取字典之前的1 累加 2
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
# python3中用items()替换python2中的iteritems()
# key=operator.itemgetter(1)根据字典的值进行排序 在这个字典中,爱情片是键,1 是值
# key=operator.itemgetter(0)根据字典的键进行排序
# reverse降序排序字典 从大到小排序
print("classCount:", classCount)
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
# 返回次数最多的类别,即所要分类的类别 前三个值里面 武侠片出现两次 分类为 武侠片
return sortedClassCount[0][0]
if __name__ == '__main__':
# 创建数据集
group, labels = createDataSet()
# 测试集
test = [101, 20]
# kNN分类
test_class = classify0(test, group, labels, 3)
# 打印分类结果
print(test_class)
| true |
cfc94fb0c0b59724342c45bbcf89f8a440742d06 | Python | gw1770df/python-test | /get-filetype/t.py | UTF-8 | 962 | 2.921875 | 3 | [] | no_license | #! /usr/bin/python
# -*- coding: utf-8 -*-
# pythontab提醒您注意中文编码问题,指定编码为utf-8
# import struct
# import IPython
# 支持文件类型
# 用16进制字符串的目的是可以知道文件头是多少字节
# 各种文件头的长度不一样,少则2字符,长则8字符
FILE_TYPE_MAP = {"FFD8FF": "JPEG",
"89504E47": "PNG"}
# 获取文件类型
def filetype(filename):
binfile = open(filename, 'rb') # 必需二制字读取
ftype = 'unknown'
for hcode in FILE_TYPE_MAP:
numOfBytes = len(hcode) / 2 # 需要读多少字节
binfile.seek(0) # 每次读取都要回到文件头,不然会一直往后读取
code = binfile.read(numOfBytes)
# IPython.embed()
if code.encode('hex') == hcode.lower():
ftype = FILE_TYPE_MAP[hcode]
break
binfile.close()
return ftype
if __name__ == '__main__':
print filetype('./logo.png')
| true |
b6adaa9e398428caa3cbde567e5684177457fcf3 | Python | kharrigian/covid-mental-health | /scripts/acquire/twitter/retrieve_timelines_api.py | UTF-8 | 4,479 | 2.625 | 3 | [] | no_license |
#######################
### Imports
#######################
## Standard Library
import os
import sys
import json
import gzip
import argparse
from time import sleep
## External Libraries
import tweepy
import pandas as pd
from mhlib.util.logging import initialize_logger
#######################
### Configuration
#######################
## API Requests
MAX_RETRIES = 3
SLEEP_TIME = 1
## Load Twitter Credentials
ROOT_DIR =os.path.dirname(os.path.abspath(__file__)) + "/../../../"
with open(f"{ROOT_DIR}config.json","r") as the_file:
CREDENTIALS = json.load(the_file)
## Initialize Twitter API
TWITTER_AUTH = tweepy.OAuthHandler(CREDENTIALS.get("twitter").get("api_key"),
CREDENTIALS.get("twitter").get("api_secret_key"))
TWITTER_AUTH.set_access_token(CREDENTIALS.get("twitter").get("access_token"),
CREDENTIALS.get("twitter").get("access_secret_token"))
TWITTER_API = tweepy.API(TWITTER_AUTH,
wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
## Logger
LOGGER = initialize_logger()
#######################
### Functions
#######################
def parse_arguments():
"""
Parse command-line to identify configuration filepath.
Args:
None
Returns:
args (argparse Object): Command-line argument holder.
"""
## Initialize Parser Object
parser = argparse.ArgumentParser(description="Pull all available tweets on a User's Timeline")
## Generic Arguments
parser.add_argument("user_list",
type=str,
help="Path to list of user IDs (.txt file, newline delimited")
parser.add_argument("output_dir",
type=str,
help="Where to store tweets")
## Parse Arguments
args = parser.parse_args()
## Check Arguments
if not os.path.exists(args.user_list):
raise ValueError(f"Could not find user list file {args.user_list}")
return args
def _pull_timeline(user_id,
include_rts=False,
exclude_replies=True):
"""
"""
## Initialize Cursor
cursor = tweepy.Cursor(TWITTER_API.user_timeline,
user_id=user_id,
include_rts=include_rts,
exclude_replies=exclude_replies,
tweet_mode="extended",
trim_user=False,
count=200)
## Cycle Through Pages
response_jsons = []
for page in cursor.pages():
response_jsons.extend([r._json for r in page])
dates = pd.to_datetime([r["created_at"] for r in response_jsons])
LOGGER.info("Found {} Tweets (Start: {}, End: {})".format(
len(response_jsons),
dates.min().date(),
dates.max().date()
))
## Return
return response_jsons
def pull_timeline(user_id,
max_retries=MAX_RETRIES,
sleep_time=SLEEP_TIME):
"""
"""
response = []
for r in range(max_retries):
try:
response = _pull_timeline(user_id)
break
except Exception as e:
if e.response.reason in ['Not Found',"Forbidden"]:
return []
else:
LOGGER.info(e.response)
sleep_time = (sleep_time + 1) ** 2
sleep(sleep_time * r)
return response
def main():
"""
"""
## Parse Command Line
args = parse_arguments()
## Create Output Directory
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
## Load User List
users = [i.strip() for i in open(args.user_list,"r").readlines()]
## Pull Data
for u, user_id in enumerate(users):
## Check For User File
outfile = f"{args.output_dir}{user_id}.json.gz"
if os.path.exists(outfile):
LOGGER.info(f"Skipping User {user_id} (Already Downloaded)")
continue
else:
LOGGER.info(f"Pulling Tweets for User {u+1}/{len(users)}: {user_id}")
## Query
response = pull_timeline(user_id)
## Cache
with gzip.open(outfile, "wt", encoding="utf-8") as the_file:
json.dump(response, the_file)
## Done
LOGGER.info("Script Complete!")
#####################
### Run
#####################
if __name__ == "__main__":
_ = main() | true |
0aa2272fd5db353f938d6604ba80388fa66cb042 | Python | walyncia/ConvertString | /StringConversion.py | UTF-8 | 1,234 | 4.3125 | 4 | [] | no_license | import time
def StringToInt ():
"""
This program prompts the user for a string and converts
it to a integer if applicable.
"""
string = input('Desired Number:')
print('The current state:\nString:',string,' ->', type(string))
if string == '': #handle no input
raise Exception ('Invalid input!') #throws exception
elif '-' in string: #handle non-positive inputs
raise Exception('No negative numbers') # throws exception
else:
num=0 #initialize int value of string
string =string[::-1] #reverse the string
var = 1 #placeholder
#print (isinstance(string,str)) #precaution to check if the string is a string
for x in range (len(string)): # determine the number of places
if x is 0:
num += int(string[x])
else:
num += int(string[x]) * var
var = var * 10 #concatenate placeholder
#print (isinstance(num,int)) #precaution to check if the string is converted to is a integer
print('\nConverting your string.....')
time.sleep(len(string)/2)
print('\nConverted State: \nNum:', num,'->', type(num))
StringToInt()
| true |
711a1e26fcbdd043d48b3ca748713b5b33827ecd | Python | TKSanthosh/tutorial-programme | /ExampleProgramme/pythagorasnumbers.py | UTF-8 | 215 | 3.6875 | 4 | [] | no_license | from math import sqrt
n= int(input("Maximum number?"))
for a in range(1,n+1):
for b in range(a,n):
c_square=a**2+b**2
c=int(sqrt(c_square))
if (c_square==c**2):
print(a,b,c)
| true |
7e4c26355987fbae5b250afa1311a7a90b80d263 | Python | MattWellie/refparse | /refparse/GBParser.py | UTF-8 | 13,157 | 2.75 | 3 | [
"MIT"
] | permissive | from Bio import SeqIO
__author__ = "mwelland"
__version__ = 2.0
__version_date__ = "06/08/2020"
class GBParser:
"""
Notes:
Isolated class to deal exclusively with GBK/GB files
Should return dictionary, not write full output
Parses the input file to find all the useful values
This will populate a dictionary to be returned at completion
Dict { pad
genename
refseqname
transcripts { transcript { protein_seq
cds_offset
exons { exon_number { genomic_start
genomic_stop
transcript_start
transcript_stop
sequence (with pad)
"""
def __init__(self, cli_args, app_settings):
"""
This class is created by instantiating with a file name and a padding value.
These are used to locate the appropriate target file, and to select the
amount of flanking sequence to be appended to exons.
:param cli_args: all arguments provded from command line, inc. defaults
:param padding: the required amount of intronic padding
"""
padding = int(app_settings["FILE_PARSER"]["padding"])
self.cli_args = cli_args
self.exons = []
self.cds = []
self.mrna = []
# Read in the specified input file into a variable
try:
self.transcriptdict = dict(
transcripts={},
input=SeqIO.to_dict(SeqIO.parse(self.cli_args.input_file, "genbank")),
pad=int(padding),
pad_offset=int(padding) % 5,
)
self.transcriptdict["refseqname"] = list(
self.transcriptdict["input"].keys()
)[0]
self.is_matt_awesome = True
except IOError as fileNotPresent:
raise Exception(
"The specified file cannot be located: {}".format(
fileNotPresent.filename
)
)
assert self.transcriptdict["pad"] <= int(
app_settings["FILE_PARSER"]["max_padding"]
), "Padding too large, please use a value below {} bases".format(
int(app_settings["FILE_PARSER"]["padding"])
)
@property
def get_version(self):
"""
Quick function to grab version details for final printing
:return:
"""
return "Version: {0}, Version Date: {1}".format(
str(__version__), __version_date__
)
def find_cds_delay(self):
""" Method to find the actual start of the translated sequence
introduced to sort out non-coding exon problems """
"""
:param transcript: currently a relic of the LRG process (29-01-2015), designed to separate the
dictionary population process into distinct sections for each transcript
"""
for transcript in self.transcriptdict["transcripts"].keys():
offset_total = 0
offset = self.transcriptdict["transcripts"][transcript]["cds_offset"]
exon_list = self.transcriptdict["transcripts"][transcript]["list_of_exons"]
for exon in exon_list:
g_start, g_stop = self.get_genomic_start_end(transcript, exon)
if offset > g_stop:
offset_total = offset_total + (g_stop - g_start)
elif g_stop > offset >= g_start:
self.transcriptdict["transcripts"][transcript][
"cds_offset"
] = offset_total + (offset - g_start)
break
def get_protein(self):
"""
This method takes the CDS tagged block from the GenBank features section and parses the
contents to retrieve the protein sequence. This is added to the appropriate section of
dictionary used to hold all required details of the file.
"""
"""
:param cds: a list containing the cds element(s) of the genbank features
"""
for alternative in self.transcriptdict["Alt transcripts"]:
selected_cds = self.cds[alternative - 1]
self.transcriptdict["transcripts"][alternative].update(
{
"protein_seq": "{}*".format(
selected_cds.qualifiers["translation"][0]
),
"NP_number": selected_cds.qualifiers["protein_id"][0],
"cds_offset": selected_cds.location.start,
}
)
def get_mrna_exons(self):
""" This uses the list of exon start and stop positions to populate
the exon positions in the dictionary"""
for alt in self.transcriptdict["Alt transcripts"]:
self.transcriptdict["transcripts"][alt] = {"list_of_exons": [], "exons": {}}
selected_mrna = self.mrna[alt - 1]
try:
self.transcriptdict["transcripts"][alt][
"NM_number"
] = selected_mrna.qualifiers["transcript_id"][0]
except KeyError:
self.transcriptdict["transcripts"][alt][
"NM_number"
] = self.transcriptdict["genename"]
self.transcriptdict["refseqname"] = self.transcriptdict["genename"]
self.transcriptdict["genename"] = self.cds[0].qualifiers["gene"][0]
exon = 1
subfeatures = selected_mrna.location.parts
for coords in subfeatures:
self.transcriptdict["transcripts"][alt]["list_of_exons"].append(exon)
self.transcriptdict["transcripts"][alt]["exons"][exon] = {
"genomic_start": coords.start,
"genomic_end": coords.end,
}
exon += 1
def get_exon_contents(self):
"""
This function is supplied with the list of exon tagged blocks from the features section
and populates the exons region of the dictionary with the exon number, coordinates, and
sequence segments which define the exon
"""
"""
:param exons: a list of the exon objects from the GenBank features list
"""
for alternative in self.transcriptdict["Alt transcripts"]:
sequence = self.transcriptdict["full genomic sequence"]
for exon_number in self.transcriptdict["transcripts"][alternative][
"exons"
].keys():
start, end = self.get_genomic_start_end(alternative, exon_number)
seq = sequence[start:end]
pad = self.transcriptdict["pad"]
exon_list = self.transcriptdict["transcripts"][alternative][
"list_of_exons"
]
if pad != 0:
if self.cli_args.trim_flanking:
if exon_number < len(exon_list) - 1:
next_exon = exon_list[exon_number]
next_start, _end = self.get_genomic_start_end(
alternative, next_exon
)
if end > next_start - (self.transcriptdict["pad"] * 2):
half_way_point = int(
round((next_start - (end + 1)) / 2)
)
if half_way_point % 2 == 1:
half_way_point -= 1
pad3 = sequence[end : end + half_way_point]
else:
assert end + pad <= len(
sequence
), "Exon index out of bounds"
pad3 = sequence[end : end + pad]
else:
assert end + pad <= len(
sequence
), "Exon index out of bounds"
pad3 = sequence[end : end + pad]
if exon_number != exon_list[0]:
previous_exon = exon_list[exon_number - 2]
_start, previous_end = self.get_genomic_start_end(
alternative, previous_exon
)
if start < previous_end + (self.transcriptdict["pad"] * 2):
half_way_point = int(
round((start - (previous_end + 1)) / 2)
)
if half_way_point % 2 == 1:
half_way_point -= 1
pad5 = sequence[
previous_end + half_way_point + 1 : start
]
else:
assert start - pad >= 0, "Exon index out of bounds"
pad5 = sequence[start - (pad) : start]
else:
assert start - pad >= 0, "Exon index out of bounds"
pad5 = sequence[start - (pad) : start]
else:
assert start - pad >= 0, "Exon index out of bounds"
assert end + pad <= len(sequence), "Exon index out of bounds"
pad3 = sequence[end : end + pad]
pad5 = sequence[start - (pad + 1) : start - 1]
seq = pad5.lower() + seq + pad3.lower()
seq = pad5.lower() + seq + pad3.lower()
self.transcriptdict["transcripts"][alternative]["exons"][exon_number][
"sequence"
] = seq
def fill_and_find_features(self):
dictionary = self.transcriptdict["input"][self.transcriptdict["refseqname"]]
self.transcriptdict["full genomic sequence"] = dictionary.seq
features = dictionary.features
for feature in features:
# Multiple exons are expected, not explicitly used
if feature.type == "exon":
self.exons.append(feature)
"""
This section works on the assumption that each exon in the file will use the appropriate gene name
and that the only relevant CDS and mRNA sections will also contain the same accession
"""
try:
self.transcriptdict["genename"] = self.exons[0].qualifiers["gene"][0]
for feature in features:
if feature.type == "CDS":
if feature.qualifiers["gene"][0] == self.transcriptdict["genename"]:
self.cds.append(feature)
elif feature.type == "mRNA":
if feature.qualifiers["gene"][0] == self.transcriptdict["genename"]:
self.mrna.append(feature)
except KeyError:
for feature in features:
if feature.type == "CDS":
self.cds.append(feature)
elif feature.type == "mRNA":
self.mrna.append(feature)
note = self.mrna[0].qualifiers["note"][0]
self.transcriptdict["genename"] = note.split("=")[1]
assert len(self.cds) == len(
self.mrna
), "There are a different number of CDS and mRNA"
def get_genomic_start_end(self, transcript, exon_number):
"""
this should minimise overall lines in this module
Args:
transcript:
exon_number:
Returns: start and end values
"""
start = self.transcriptdict["transcripts"][transcript]["exons"][exon_number][
"genomic_start"
]
stop = self.transcriptdict["transcripts"][transcript]["exons"][exon_number][
"genomic_end"
]
return start, stop
def run(self):
"""
This is the main method of the GBK Parser. This method is called after class instantiation
and handles the operation of all the other functions to complete the dictionary which will
hold all of the sequence and exon details of the gene file being parsed
"""
"""
:return transcriptdict: This function fills and returns the dictionary, contents explained in docstring above
"""
# initial sequence grabbing and populating dictionaries
self.fill_and_find_features()
self.transcriptdict["Alt transcripts"] = range(1, len(self.cds) + 1)
self.get_mrna_exons()
self.get_protein()
self.get_exon_contents()
self.find_cds_delay()
return self.transcriptdict
| true |
1a7f5b560febcb92aa0fc3c287aace99773d17dc | Python | Crazy-Jack/VisualConceptRouting | /data_process/to_100k.py | UTF-8 | 2,221 | 2.875 | 3 | [] | no_license | """Extract 100k img from .mdb into byte img in folder"""
import io
import os
import argparse
from shutil import copyfile
import lmdb
import pandas as pd
from PIL import Image
import numpy as np
from tqdm import tqdm
def set_args():
parser = argparse.ArgumentParser("Export from .mdb file to flat folder")
parser.add_argument("--db_path", type=str, default="../data_unzip/bedroom_train_lmdb/",
help="database folder")
parser.add_argument("--df_path", type=str, default="lsun_100k.csv",
help="100k dataframe list path")
parser.add_argument("--out_dir", type=str, default="../data_unzip/bedroom_train_lmdb/lsun_bed100k/imgs")
parser.add_argument("--meta_file_name", type=str, default="meta_lsun_100k.csv")
args = parser.parse_args()
args.meta_folder = "/".join(args.out_dir.split("/")[:-1])
args.meta_file_path = os.path.join(args.meta_folder, args.meta_file_name)
return args
def export_images(df, db_path, out_dir):
os.makedirs(out_dir, exist_ok=True)
print('Exporting', db_path, 'to', out_dir)
env = lmdb.open(db_path, map_size=1099511627776,
max_readers=100, readonly=True)
count = 0
name_list = list(df.iloc[:,0])
for name in tqdm(name_list, total=len(name_list)):
key = name.split(".")[0]
byte_key = bytes(key, 'utf-8')
with env.begin(write=False) as txn:
byte_img = txn.get(byte_key)
out_img_path = os.path.join(out_dir, key + '.webp')
with open(out_img_path, 'wb') as f:
f.write(byte_img)
return out_img_path
def main():
args = set_args()
df = pd.read_csv(args.df_path, index_col=0)
# export imgs
last_img_path = export_images(df, args.db_path, args.out_dir)
# transfer meta data
copyfile(args.df_path, args.meta_file_path)
# test
print("Testing results")
img = Image.open(last_img_path)
img = np.array(img)
print("Last img shape: {} ---- OK!".format(img.shape))
if __name__ == "__main__":
"""Command
$ python to_100k.py --db_path xxxx/bedroom_train_lmdb --df_path lsun_100k.csv --out_dir /path/to/save/dir
"""
main()
| true |
da578ccc2dba857a579c4c2b0be4a2f17cec127e | Python | PrincessGrouchy/na-rocky-mountain-2020-public | /problems/forcedchoice/submissions/accepted/forcedchoice-zf.py | UTF-8 | 148 | 2.71875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
n, p, s = map(int, input().split())
for _ in range(s): print ("KEEP" if p in list(map(int, input().split()))[1:] else "REMOVE")
| true |
553f47bb8b0320997878d555d3afe65c830c8c9d | Python | BLSQ/geohealthaccess | /geohealthaccess/worldpop.py | UTF-8 | 1,847 | 2.921875 | 3 | [
"MIT"
] | permissive | """Download WorldPop population count datasets.
Notes
-----
See `<https://www.worldpop.org/>`_ for more information about the WorldPop project.
"""
from loguru import logger
import requests
from geohealthaccess.utils import download_from_url
logger.disable("__name__")
BASE_URL = "https://data.worldpop.org/GIS/Population/Global_2000_2020"
def build_url(country, year=2020, un_adj=False):
"""Build download URL.
Parameters
----------
country : str
Country ISO A3 code.
year : int, optional
Year of interest (2000--2020). Default=2020.
un_adj : bool, optional
Use UN adjusted population counts. Default=False.
Returns
-------
url : str
Download URL.
"""
return (
f"{BASE_URL}/{year}/{country.upper()}/"
f"{country.lower()}_ppp_{year}{'_UNadj' if un_adj else ''}.tif"
)
def download(
country, output_dir, year=2020, un_adj=False, show_progress=True, overwrite=False
):
"""Download a WorldPop population dataset.
Parameters
----------
country : str
Country ISO A3 code.
output_dir : str
Path to output directory.
year : int, optional
Year of interest (2000--2020). Default=2020.
un_adj : bool, optional
Use UN adjusted population counts. Default=False.
show_progress : bool, optional
Show progress bar. Default=False.
overwrite : bool, optional
Overwrite existing files. Default=True.
Returns
-------
str
Path to output GeoTIFF file.
"""
url = build_url(country, year=year, un_adj=un_adj)
logger.info(f"Downloading population counts from {url}.")
with requests.Session() as s:
fp = download_from_url(
s, url, output_dir, show_progress=show_progress, overwrite=overwrite
)
return fp
| true |
8b61c776da78efc8d75cf5a4c8a7dc0ab3b63078 | Python | callmeliuchu/LeetCode | /Problems/39CombinationSum.py | UTF-8 | 593 | 3.171875 | 3 | [] | no_license | class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
ans = []
self.f(candidates,target,[],ans)
return ans
def f(self,arr,target,res,ans):
if target < 0:
return
if target == 0:
new_arr = sorted(res)
if new_arr not in ans:
ans.append(new_arr)
for val in arr:
res.append(val)
self.f(arr,target-val,res,ans)
res.pop() | true |
49b1fcd845b076366212d6406117d9b6c285d3e0 | Python | GRSEB9S/linconfig | /qgis/qgis2/python/plugins/qProf/geosurf/surfaces.py | UTF-8 | 3,112 | 2.953125 | 3 | [] | no_license |
from numpy import * # general import for compatibility with formula input
from .deformations import calculate_geographic_scale_matrix, calculate_geographic_rotation_matrix, calculate_geographic_offset
from .deformations import define_deformation_matrices
from .errors import AnaliticSurfaceCalcException
def calculate_abz_lists( array_range, array_size, formula ):
a_min, a_max, b_max, b_min = array_range
array_rows, array_cols = array_size
a_array = linspace( a_min, a_max, num=array_cols )
b_array = linspace( b_max, b_min, num=array_rows ) # note: reversed for conventional j order in arrays
try:
a_list, b_list = [ a for a in a_array for b in b_array ], [ b for a in a_array for b in b_array ]
except:
raise AnaliticSurfaceCalcException, "Error in a-b values"
try:
z_list = [ eval( formula ) for a in a_array for b in b_array ]
except:
raise AnaliticSurfaceCalcException, "Error in formula application to array"
return a_list, b_list, z_list
def calculate_geosurface( analytical_params, geogr_params, deform_params ):
array_range, array_size, formula = analytical_params
(geog_x_min, geog_y_min), (area_length, area_width), area_rot_ang_deg = geogr_params
a_min, a_max, b_min, b_max = array_range
a_range, b_range = a_max-a_min, b_max-b_min
# calculate array from formula
try:
X, Y, Z = calculate_abz_lists( array_range, array_size, formula )
except AnaliticSurfaceCalcException, msg:
raise AnaliticSurfaceCalcException, msg
# calculate geographic transformations to surface
geographic_scale_matrix = calculate_geographic_scale_matrix( a_range, b_range, area_length, area_width )
geographic_rotation_matrix = calculate_geographic_rotation_matrix( area_rot_ang_deg )
geographic_transformation_matrix = dot( geographic_rotation_matrix, geographic_scale_matrix )
geographic_offset_matrix = calculate_geographic_offset( geographic_transformation_matrix,
array( [a_min, b_min, 0.0] ),
array( [geog_x_min, geog_y_min, 0.0] ) )
# apply total transformations to grid points
deformations = define_deformation_matrices( deform_params )
geosurface_X = []; geosurface_Y = []; geosurface_Z = []
for x, y, z in zip( X, Y, Z ):
pt = dot( geographic_transformation_matrix, array([x,y,z]) ) + geographic_offset_matrix
for deformation in deformations:
if deformation['increment'] == 'additive':
pt = pt + deformation['matrix']
elif deformation['increment'] == 'multiplicative':
pt = dot( deformation['matrix'], pt )
geosurface_X.append( pt[0] )
geosurface_Y.append( pt[1] )
geosurface_Z.append( pt[2] )
return geosurface_X, geosurface_Y, geosurface_Z
| true |
d93c12198e8eab80213b0d6fcaf15596a9fbd005 | Python | zuzanna-f/pp1 | /03-FileHandling/03.21.py | UTF-8 | 392 | 3.59375 | 4 | [] | no_license | with open('numbersinrows.txt', 'r') as file:
ile = 0
suma = 0
for line in file:
temp = []
temp = line.split(',')
for i in range(len(temp)):
temp[i] = int(temp[i])
suma = suma + temp[i]
ile = ile + 1
print("Suma liczb: ", suma)
print("Ilość licz: ", ile)
| true |
f4c369eddeca257d9ea6b1e21e5700848b836263 | Python | WIEQLI/performance-testing | /ptdockertest/prepare_benchmark.py | UTF-8 | 871 | 2.5625 | 3 | [] | no_license | """
Created on 22/09/2015
@author: Aitor Gomez Goiri <aitor.gomez-goiri@open.ac.uk>
Script to create database.
"""
from argparse import ArgumentParser
from models import PerformanceTestDAO, Test
def main(database_file):
dao = PerformanceTestDAO(database_file)
session = dao.get_session()
for num_containers in (1, 5, 10, 20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600):
test = Test(image_id='packettracer_xvfb_mount', volumes_from='ptdata', number_of_containers=num_containers, repetitions=1)
session.add(test)
session.commit()
def entry_point():
parser = ArgumentParser(description='Create database and create data for the benchmark.')
parser.add_argument('-db', default='/tmp/benchmark.db', dest='database', help='Database file.')
args = parser.parse_args()
main(args.database)
if __name__ == "__main__":
entry_point()
| true |
f2fa722e9343dfd5667190fba69e5be2fecbb2f6 | Python | pantlavanya/tic_tac_toe_game | /src/game_pattern_based.py | UTF-8 | 3,788 | 3.015625 | 3 | [] | no_license | import copy, random
from game_common_feature import GameCommonFeature
from template import WON_MESSAGE, CONTINUE_MESSAGE
class GamePatternBased(GameCommonFeature):
@staticmethod
def get_all_keys_for_x_and_o(board_dict):
"""
get all keys for both players
:param board_dict:
:return:
"""
x_keys = list(key for key in board_dict if 'X' == board_dict[key])
y_keys = list(key for key in board_dict if 'O' == board_dict[key])
return x_keys, y_keys
@staticmethod
def win_condition_check(x_keys):
"""
:param x_keys:
:return:
"""
# check
# get point with same x point
for i in range(0, 3):
# row combination
row_comb = list(True for _x, _y in x_keys if _x == i)
# col combination
col_comb = list(True for _x, _y in x_keys if _y == i)
if len(row_comb) == 3 or len(col_comb) == 3:
return True
if (0, 0) in x_keys and (1, 1) in x_keys and (2, 2) in x_keys:
return True
if (0, 2) in x_keys and (1, 1) in x_keys and (2, 0) in x_keys:
return True
return False
def based_win_condition(self):
"""
:param board_dict:
:return:
"""
x_keys, y_keys = GamePatternBased.get_all_keys_for_x_and_o(self.board_dict)
if len(x_keys) > 2 or len(y_keys) > 2:
x_point_check = GamePatternBased.win_condition_check(x_keys)
if x_point_check:
return WON_MESSAGE, False
y_point_check = GamePatternBased.win_condition_check(y_keys)
if y_point_check:
return WON_MESSAGE, False
return CONTINUE_MESSAGE, True
def get_computer_move(self):
"""
:param board:
:param computerLetter:
:return:
"""
# check if computer can win in the next move
for i in range(0, 3):
for j in range(0, 3):
board_copy = copy.deepcopy(self.board_dict)
if not board_copy[(i, j)]:
board_copy, update_flag = GamePatternBased.update_board_dict(i, j, 'O', board_copy)
x_keys, y_keys = GamePatternBased.get_all_keys_for_x_and_o(board_copy)
y_point_check = GamePatternBased.win_condition_check(y_keys)
if y_point_check:
return i, j
# Check if the player could win on his next move, and block them.
for i in range(0, 3):
for j in range(0, 3):
board_copy = copy.deepcopy(self.board_dict)
if not board_copy[(i, j)]:
board_copy, update_flag = GamePatternBased.update_board_dict(i, j, 'X', board_copy)
x_keys, y_keys = GamePatternBased.get_all_keys_for_x_and_o(board_copy)
x_point_check = GamePatternBased.win_condition_check(x_keys)
if x_point_check:
return i, j
# take one of the corners
move = self.computer_next_move([(0, 0), (0, 2), (2, 0), (2, 2)])
if move:
return move
# take the center
if not self.board_dict[(1, 1)]:
return 1, 1
# any remaining position
return self.computer_next_move([(0,1), (1,0), (1, 2), (2, 1)])
def computer_next_move(self, move_list):
"""
:param move_list:
:return:
"""
available_moves = []
for i, j in move_list:
if not self.board_dict[(i, j)]:
available_moves.append((i, j))
if len(available_moves) > 0:
return random.choice(available_moves)
return None
| true |
6917a1842582a23e84bae6783f6df190387ac22d | Python | SJLMax/NLP | /最大匹配/segword.py | UTF-8 | 4,309 | 2.9375 | 3 | [] | no_license | import xlrd
import datetime
import re
# 读取文献
def readtxt(path):
data=[]
with open(path,'r',encoding='utf8') as f:
line = f.readlines()
for i in line:
i = i.strip(' ')
i = i.replace('\n','').replace('\u3000','').replace('\xa0','').replace(' ','')
if i!='':
data.append(i)
#print(data)
return data
# 清洗文本
def remove_sentence(data):
sentences=[]
for line in data:
print(line)
pattern = re.findall(r'/(.*)/', line)
if len(pattern)>=1:
line = line.replace('/' + pattern[0] + '/', '')
sentences.append(line)
return list(filter(None, sentences))
# 获取底表
def readxls(path):
word=[]
rbook = xlrd.open_workbook(path)
table = rbook.sheets()[0]
nrows = table.nrows # 获取行号
ncols = table.ncols # 获取列号
for i in range(1, nrows): # 第0行为表头
alldata = table.row_values(i) # 循环输出excel表中每一行,即所有数据
result = alldata[0] # 取出表中第一列数据
word.append(result)
#print(word)
return word
# 逆向最大匹配分词
def segword(data):
wordlis= sorted(wordlexicon, key=lambda i: len(i), reverse=True) # 按长度大小排序
#print(wordlis)
re=[]
for i in range(len(data)):
s1 = data[i]
#print(s1)
s2 = ''
maxlen = 5
w = s1[-maxlen:] # 逆向
while (w):
if len(w) != 1:
if w in wordlis:
s2 = w + ' ' + s2
n=len(s1)-len(w)
s1 = s1[0:n]
w = s1[-maxlen:]
#print(s2,s1)
else:
w = w[1:len(w)]
#print(w)
else:
s2 = w + ' ' + s2
n = len(s1) - len(w)
s1 = s1[0:n]
w = s1[-maxlen:]
#print(s2, s1)
re.append(s2)
print(re)
return re
# 正向最大匹配分词
def segword_2(data):
wordlis= sorted(wordlexicon, key=lambda i: len(i), reverse=True) # 按长度大小排序
# print(wordlis)
re=[]
for i in range(len(data)):
s1 = data[i]
#print(s1)
s2 = ''
maxlen = 5
w = s1[:maxlen] # 逆向
#print(w)
while (w):
if len(w) != 1:
if w in wordlis:
s2 = s2 + w+ ' '
s1 = s1[len(w):]
w = s1[:maxlen]
#print(s2,s1)
else:
w = w[:len(w)-1]
#print(w)
else:
s2 = s2 + w + ' '
s1 = s1[len(w):]
w = s1[:maxlen]
#print(s2, s1)
re.append(s2)
print(re)
return re
# 去停用词(没有采用该函数)
def remove(data,stopwords):
corpus=[]
for line in data:
l=''
for word in line.split(' '):
# print(word)
if word not in stopwords:
l=l+word+' '
corpus.append(l)
corpus=[i.strip(' ') for i in corpus]
final = list(filter(None, corpus))
print(final)
return final
def writetxt(path,data):
with open(path,'w',encoding='utf8') as f:
for i in data:
f.write(i+'\n')
if __name__ == '__main__':
data1 = readtxt('./新闻1.txt')
#data2 = readtxt('./新闻2.txt')
#data3 = readtxt('./待分词文本0519.txt')
wordlexicon=readxls('./人民日报词汇频次表.xlsx')
# 逆向最大匹配
start = datetime.datetime.now() #开始时间
re = segword(data1)
# re2 = segword(data)
end = datetime.datetime.now() #结束时间
print((end - start).seconds)
# 正向最大匹配
start = datetime.datetime.now() # 开始时间
new1=segword_2(data1)
end = datetime.datetime.now() # 结束时间
print((end - start).seconds)
writetxt('./结果_逆向.txt', re)
writetxt('./结果_正向.txt',new1)
#writetxt('./实践分词结果.txt', re)
| true |
a5f41d97a4315dce63c1f3a7d5bbbfbf535686e2 | Python | cpe202spring2019/lab1-pietrok29 | /lab1_test_cases.py | UTF-8 | 2,887 | 3.234375 | 3 | [] | no_license | import unittest
from lab1 import *
# A few test cases. Add more!!!
class TestLab1(unittest.TestCase):
def test_max_list_iter(self):
"""This test checks for the value Error in the max_list_iter functinon"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
max_list_iter(tlist)
def test_max_list_iter_none(self): #used for checking None statement in max_list_iter
self.assertEqual(max_list_iter([]), None)
def test_max_list_iter_num(self): #used for checking regular max_list_iter inputs
self.assertEqual(max_list_iter([1, 2, 3, 4]), 4)
self.assertEqual(max_list_iter([5, 3, 2, 1, 0]), 5)
self.assertEqual(max_list_iter([4, 3, 5, 1]), 5)
self.assertEqual(max_list_iter([7]), 7)
self.assertEqual(max_list_iter([2, 2]), 2)
def test_reverse_rec(self): #used for checking regular reverse_rec inputs
self.assertEqual(reverse_rec([1, 2, 3]), [3, 2, 1])
self.assertEqual(reverse_rec([1]), [1])
self.assertEqual(reverse_rec([5, 7, 3, 9]), [9, 3, 7, 5])
self.assertEqual(reverse_rec([1, 1]), [1, 1])
self.assertEqual(reverse_rec([1, 2, 1]), [1, 2, 1])
def test_reverse_rec_none(self): #used for testing empty reverse_rec list
self.assertEqual(reverse_rec([]), [])
def test_reverse_rec_error(self):
tlist = None
with self.assertRaises(ValueError): # used to check for exception
reverse_rec(tlist)
def test_bin_search(self): #given test function
list_val =[0,1,2,3,4,7,8,9,10]
low = 0
high = len(list_val) - 1
self.assertEqual(bin_search(4, 0, len(list_val)-1, list_val), 4)
def test_bin_search_case(self): #used for checking regular bin_searches
self.assertEqual(bin_search(5, 0, 8, [1, 3, 5, 6, 8, 10, 12, 14, 16]), 2)
self.assertEqual(bin_search(1, 0, 6, [1, 3, 5, 6, 8, 10, 12]), 0)
self.assertEqual(bin_search(12, 0, 6, [1, 3, 5, 6, 8, 10, 12]), 6)
self.assertEqual(bin_search(3, 0, 1, [1, 3]), 1)
self.assertEqual(bin_search(1, 0, 1, [1, 3]), 0)
self.assertEqual(bin_search(2, 0, 0, [2]), 0)
def test_bin_search_none(self): #used for checking the None statement in bin_search
self.assertEqual(bin_search(10, 0, 5, [1, 2, 3, 4, 5, 6]), None)
self.assertEqual(bin_search(2, 0, 0, [1]), None)
self.assertEqual(bin_search(2, 0, 1, [1, 6]), None)
self.assertEqual(bin_search(2, 0, 0, []), None)
def test_bin_search_error(self): #used for checking the raise valueerror in bin_search
tlist = None
with self.assertRaises(ValueError): # used to check for exception
bin_search(1, 0, 0, tlist)
if __name__ == "__main__":
unittest.main()
| true |
2ee00fd5f59bbfd816e72314a27a7672bdeec82a | Python | sumrdev/Code-Portfolio | /PYTHON BASIS/calcpy.py | UTF-8 | 533 | 2.765625 | 3 | [] | no_license | import math
from decimal import *
getcontext().prec = 300
def calculatePi(k):
calculations = 12
a = (426880*math.sqrt(10005))
pi = 0
for i in range(calculations):
currentK = math.factorial(6*k)*(545140134*k+13591409)/(math.factorial(3*k)*math.pow(math.factorial(k),3)*math.pow(-262537412640768000,k))
pi = pi + currentK
k =+ 1
return a/pi
print(calculatePi(0, 100))
print("3,1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679") | true |
9340f5ccfd8f5ef594ce56728a031435b62aabf8 | Python | hh1802/hh | /flask02/App/models.py | UTF-8 | 1,689 | 2.6875 | 3 | [] | no_license | from _datetime import datetime
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
s_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
s_name = db.Column(db.String(16), unique=True)
s_age = db.Column(db.Integer, default=18)
grades = db.Column(db.Integer,db.ForeignKey('grade.g_id'), nullable=True)
__tablename__ = 'student'
def to_dict(self):
return {
's_id': self.s_id,
's_name': self.s_name,
's_age':self.s_age,
'grade':self.grades,
}
class Grade(db.Model):
g_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
g_name = db.Column(db.String(16), unique=True, nullable=False)
g_desc = db.Column(db.String(30), nullable=True)
g_create_time = db.Column(db.DATE, default=datetime.now())
students = db.relationship('Student', backref ='grade', lazy=True)
__tablename__ = 'grade'
sc = db.Table('sc',
db.Column('s_id', db.Integer, db.ForeignKey('student.s_id'), primary_key=True),
db.Column('c_id', db.Integer, db.ForeignKey('courses.c_id'), primary_key=True))
class Course(db.Model):
c_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
c_name = db.Column(db.String(16), unique=True)
students = db.relationship('Student', secondary=sc, backref='course')
__tablename__ = 'courses'
# def __init__(self, id, name):
# self.id = id
# self.name = name
def to_dict(self):
return {
'c_id':self.c_id,
'c_name':self.c_name,
'students':[stu.to_dict() for stu in self.students],
}
| true |
58fa7972275ed20f57b3383c4c70ab3c5c498681 | Python | anhtm/python-data-structures-clrs | /implementation/linked_list/node.py | UTF-8 | 208 | 3.09375 | 3 | [] | no_license | class Node:
def __init__(self, key = None):
self.key = key
self.next = None
class DoublyNode(Node):
def __init__(self, key = None):
Node.__init__(self)
self.prev = None
self.key = key | true |
1f6bbd9477f9cc86d079d41b0a57c610bd5206fd | Python | AhmedWael205/MI-Go-Game | /ServerConfig.py | UTF-8 | 2,870 | 2.6875 | 3 | [] | no_license | import json
import numpy as np
from game import Game
from Stones import Turn
import asyncio
def server_config(GameConfig,FileName=None,mode=1,GuiObject=None):
if(FileName is None):
GameConfig = GameConfig
else:
with open(FileName, 'r') as f:
GameConfig = json.load(f)
#print("1")
#print(GameConfig)
# TODO DO we need reamining time of anything at the initalization state(begining of the game from a certain stage)
GameState = GameConfig["initialState"]
moveLogJsonArr = GameConfig["moveLog"]
wloc = list(zip(*np.where((np.array(GameState["board"])) == "W")))
bloc = list(zip(*np.where((np.array(GameState["board"])) == "B")))
bCaptured = GameState["players"]["W"]["prisoners"]
wCaptured = GameState["players"]["B"]["prisoners"]
gameArgs = {"wloc": wloc, "bloc": bloc,
"wCapturedStones": wCaptured,
"bCapturedStones": bCaptured}
# TODO Check for any misplaced argument and if initialization of any argument can affect other class members
"""
instance of backend game supposed to be only one instance
"""
if mode == 1:
backEndGame = Game(**gameArgs)
else:
backEndGame = Game(**gameArgs,GuiObject=GuiObject, mode=mode)
turn = Turn.black if GameState["turn"] == "B" else Turn.white
#print("1.1")
#print(turn)
"""
logically speaking Yahia should not send resign move at the beginning
"""
"""
Taking the move log and adding stones till we reach final state to begin with
"""
for move in moveLogJsonArr:
if move["move"]["type"] == "place":
print("location", (move["move"]["point"]["row"], move["move"]["point"]["column"]), turn)
x = backEndGame.play(
(move["move"]["point"]["row"], move["move"]["point"]["column"], turn))
# gameBoard = backEndGame.getBoard()
# print(gameBoard)
if (not x):
print("Error in location", (move["move"]["point"]["row"], move["move"]["point"]["column"]), turn)
backEndGame.Drawboard()
# input('Press any key ...')
elif (move["move"]["type"] == "pass"):
backEndGame.play(1, turn)
elif (move["move"]["type"] == "resign"):
# TODO handle resign at game config(illogical)
print("Error in parsing JSON FILE AT GAME INIT CONFIG")
else:
# TODO handle error at game config
pass
print("Error in parsing JSON FILE AT GAME INIT CONFIG")
turn = 1 - turn
# backEndGame.Drawboard()
# input('Press any key ...')
# score, TerrBoard = backEndGame.getScoreAndTerrBoard()
# print(score)
""""
NOW instance backEnd stage is initialized with the data parsed
"""
#print("2")
return backEndGame
| true |
d2b3bce79feaa1effde9414b7b64d9f8cb83f74c | Python | icaros7/python_study | /lab6_my_1.py | UTF-8 | 4,823 | 4.125 | 4 | [] | no_license | """
챕터 : Day 6
주제 : Class
문제 : Fraction 메서드의 4칙 연산을 완성하라
작성자 : 이호민
작성일 : 2018.10.24
"""
# 최대공략수를 찾아주는 math.gcd 를 쓰기위해 math 모듈 중 gcd import
from math import gcd
# 분수 클래스 정의
class Fraction:
def __init__(self, n, d):
"""
초기화 함수
:param n: 분자
:param d: 분모
"""
self.numer = n
self.denom = d
def print(self, inp: object, o: object, calc):
print("%d/%d %s %d/%d = %d/%d" % (inp.numer, inp.denom, calc, o.numer, o.denom, self.numer, self.denom)) # 보기 좋게 출력
def getNumer(self):
return self.numer
def getDenom(self):
return self.denom
def setNumer(self, n):
self.numer = n
def setDenom(self, d):
self.denom = d
def add(self, o: object):
"""
덧셈
:param o: self에 더할 분수
:return: 더한 결과 값을 반환
"""
tong = gcd(self.denom, o.denom) # 최대공약수 값을 구해 저장
# 결과의 분모 계산
d = self.denom * o.denom
# 결과의 분자 계산
n = self.numer * o.denom + self.denom * o.numer
if (n % tong == 0) and (d % tong == 0): # 통분해야할 것이 있다면
r = Fraction(int(n / tong), int(d / tong)) # 결과값을 통분 한 뒤 해당 값으로 Fraction 분수 생성
else:
r = Fraction(n, d) # 결과 값을 포함하는 Fraction 분수 생성
return r
def minus(self, o: object):
"""
뺄셈
:param o: self에 뺄 분수
:return: 뺄 결과 값을 반환
"""
tong = gcd(self.denom, o.denom) # 최대공약수 값을 구해 저장
# 결과의 분모 계산
d = self.denom * o.denom
# 결과의 분자 계산
n = self.numer * o.denom - self.denom * o.numer
if (n % tong == 0) and (d % tong == 0): # 통분해야할 것이 있다면
r = Fraction(int(n / tong), int(d / tong)) # 결과값을 통분 한 뒤 해당 값으로 Fraction 분수 생성
else:
r = Fraction(n, d) # 결과 값을 포함하는 Fraction 분수 생성
return r
def times(self, o: object):
"""
곱셈
:param o: self에 곱할 분수
:return: 곱한 결과 값을 반환
"""
tong = gcd(self.denom, o.denom) # 최대공약수 값을 구해 저장
# 결과의 분모 계산
d = self.denom * o.denom
# 결과의 분자 계산
n = self.numer * o.numer
if (n % tong == 0) and (d % tong == 0): # 통분해야할 것이 있다면
r = Fraction(int(n / tong), int(d / tong)) # 결과값을 통분 한 뒤 해당 값으로 Fraction 분수 생성
else:
r = Fraction(n, d) # 결과 값을 포함하는 Fraction 분수 생성
return r
def div(self, o: object):
"""
나눗셈
:param o: self에 나눌 분수
:return: 나눈 결과 값을 반환
"""
tong = gcd(self.denom, o.denom) # 최대공약수 값을 구해 저장
# 결과의 분모 계산
d = self.denom * o.numer
# 결과의 분자 계산
n = self.numer * o.denom
if (n % tong == 0) and (d % tong == 0): # 통분해야할 것이 있다면
r = Fraction(int(n / tong), int(d / tong)) # 결과값을 통분 한 뒤 해당 값으로 Fraction 분수 생성
else:
r = Fraction(n, d) # 결과 값을 포함하는 Fraction 분수 생성
return r
def __add__(self, o):
r = Fraction(5, 3)
return r
def __str__(self):
return str(self.numer) + "/" + str(self.denom)
def __eq__(self, other):
"""
통분 해야하는가?
"""
g1 = gcd(self.numer, self,denom)
g2 = gcd(other.numer, other, denom)
if (self.numer//g1 == other.numer//g2) and (self.denom//g1 == other.denom//g2):
return True
else:
return False
def __ne__(self, other):
"""
두 분수가 같으면 참, 다르면 거짓
"""
if self == other:
return True
else:
return False
f1 = Fraction(1, 2) # Fraction 인스턴스 생성
f2 = Fraction(5, 4) # Fraction 인스턴스 생성
"""
print 매서드가 아닌 __str__ 매직 매서드를 쓰기 위해 주석처리
f1.add(f2).print(f1, f2, "+")
f1.minus(f2).print(f1, f2, "-")
f1.times(f2).print(f1, f2, "*")
f1.div(f2).print(f1, f2, "/")
"""
print(f1, "+", f2, "=", f1.add(f2))
print(f1, "-", f2, "=", f1.minus(f2))
print(f1, "*", f2, "=", f1.times(f2))
print(f1, "/", f2, "=", f1.div(f2)) | true |
54ff2beed3e651a0481c733dc8af39a14e2a647c | Python | Vicky1-bot/barcode-detection | /detect_barcode.py | UTF-8 | 1,569 | 2.828125 | 3 | [] | no_license | # import the necessary packages
import simple_barcode_detection
from imutils.video import VideoStream
import argparse
import time
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video",
help="path to the (optional) video file")
args = vars(ap.parse_args())
# if the video path was not supplied, grab the reference to the
# camera
if not args.get("video", False):
vs = VideoStream(src=0).start()
time.sleep(2.0)
# otherwise, load the video
else:
vs = cv2.VideoCapture(args["video"])
# keep looping over the frames
while True:
# grab the current frame and then handle if the frame is returned
# from either the 'VideoCapture' or 'VideoStream' object,
# respectively
frame = vs.read()
frame = frame[1] if args.get("video", False) else frame
# check to see if we have reached the end of the
# video
if frame is None:
break
# detect the barcode in the image
box = simple_barcode_detection.detect(frame)
# if a barcode was found, draw a bounding box on the frame
if box is not None:
cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)
# show the frame and record if the user presses a key
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break
# if we are not using a video file, stop the video file stream
if not args.get("video", False):
vs.stop()
# otherwise, release the camera pointer
else:
vs.release()
# close all windows
cv2.destroyAllWindows()
| true |
be2aa7552b3a330fc1b8028d2ae0e5c131703dbd | Python | TrellixVulnTeam/InterfaceTest_94CO | /ConferenceSignSystem2.0/ConferenceSignSystemTestFramework2.0/interface/md5_get_event_list.py | UTF-8 | 2,924 | 2.515625 | 3 | [] | no_license | # 增加签名+时间戳
# 对Event接口进行测试
# 发布会查询接口
import unittest
import requests
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
from db_fixture import test_data
import time
import hashlib
class GetEventListTest(unittest.TestCase):
"""查询发布会信息"""
def setUp(self):
self.base_url = "http://127.0.0.1:8000/api/get_event_list_with_md5/"
self.secret_key = '&cfssystem'
now_time = time.time()
self.client_time = str(now_time).split('.')[0]
md5 = hashlib.md5()
sign_str = self.client_time + self.secret_key
sign_bytes_utf8 = sign_str.encode(encoding='utf-8')
md5.update(sign_bytes_utf8)
self.sign_md5 = md5.hexdigest()
def tearDown(self):
print(self.result)
# 请求超时
def test_time_out(self):
r = requests.get(self.base_url, params={'eid': 1,'sign':self.sign_md5, 'time':'915123661'})
self.result = r.json()
self.assertEqual(self.result['status'], 10032)
self.assertEqual(self.result['message'], 'time out')
# 认证失败
def test_sign_error(self):
r = requests.get(self.base_url, params={'eid': 1,'sign':'1111', 'time':self.client_time})
self.result = r.json()
self.assertEqual(self.result['status'], 10034)
self.assertEqual(self.result['message'], 'sign error')
# eid查询不存在
def test_get_event_list_eid_error(self):
r = requests.get(self.base_url, params={'eid': 100,'sign':self.sign_md5, 'time':self.client_time})
self.result = r.json()
self.assertEqual(self.result['status'], 10005)
self.assertEqual(self.result['message'], 'query result is empty')
# eid查询成功
def test_get_event_list_eid_success(self):
r = requests.get(self.base_url, params={'eid': 1,'sign':self.sign_md5, 'time':self.client_time})
self.result = r.json()
self.assertEqual(self.result['status'], 200)
self.assertEqual(self.result['message'], 'success')
self.assertEqual(self.result['data']['name'], '魅蓝 S6发布会')
self.assertEqual(self.result['data']['address'], '北京会展中心')
# 关键字模糊查询成功
def test_get_event_list_name_find(self):
r = requests.get(self.base_url, params={'name': '发布会','sign':self.sign_md5, 'time':self.client_time})
self.result = r.json()
self.assertEqual(self.result['status'], 200)
self.assertEqual(self.result['message'], 'success')
self.assertEqual(self.result['data'][0]['name'], '魅蓝 S6发布会')
self.assertEqual(self.result['data'][0]['address'], '北京会展中心')
if __name__ == '__main__':
test_data.init_data()
unittest.main() | true |
f84e158fe6042f1e71544fe192fb60a552d47d1a | Python | Isaias301/Questions-URI | /1178.py | UTF-8 | 372 | 3.484375 | 3 | [] | no_license | def main():
valor = input()
teste(valor)
def teste(valor):
vetor = [None]*100
for i in range(len(vetor)):
if i == 0:
vetor[i] = float(valor)
print("N[%i] = %.4f" % (i, vetor[i]))
else:
vetor[i] = vetor[i-1]/2
print("N[%i] = %.4f" % (i, vetor[i]))
if __name__ == '__main__':
main()
| true |
9072d4d060539348a2ceddf56de6089f06914f60 | Python | EDA2021-1-SEC02-G02/Reto4---G02 | /App/model.py | UTF-8 | 4,816 | 2.71875 | 3 | [] | no_license | """
* Copyright 2020, Departamento de sistemas y Computación,
* Universidad de Los Andes
*
*
* Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along withthis program. If not, see <http://www.gnu.org/licenses/>.
*
* Contribuciones:
*
* Dario Correal - Version inicial
"""
import config as cf
from DISClib.ADT import list as lt
from DISClib.ADT import map as mp
from DISClib.DataStructures import mapentry as me
from DISClib.Algorithms.Sorting import shellsort as sa
from haversine import haversine as hs
assert cf
from DISClib.ADT.graph import gr
#TODO revisar si se puede eliminar la informacion en el mapLP
"""
Se define la estructura de un catálogo de videos. El catálogo tendrá dos listas, una para los videos, otra para las categorias de
los mismos.
"""
# Construccion de modelos
def newdatabase():
database = {'maplpoints':None,
'maplpcountries':None,
'mapcountinents':None,
'mapconnections':None,
'ltvertex': None,
'graph':None}
database['maplpoints'] = createmap(3400)
database['maplpcountries'] =createmap(600)
database['mapcountinents'] = createmap(20)
database['mapconnections'] = createmap(3000)
database['ltvertex'] = lt.newList('ARRAY_LIST')
database['graph'] = gr.newGraph(datastructure='ADJ_LIST',
directed=True,
size=1700,
comparefunction=None)
return database
#_______________________________________________________________
# Funciones para agregar informacion al catalogo
def loadlpoints(database, vertex):
ltvertex = database['ltvertex']
graph = database['graph']
maplpoints = database['maplpoints']
lp = vertex['landing_point_id']
maplpcountries = database['maplpcountries']
lt.addLast(ltvertex, vertex)
addvertexgraph(graph, lp)
addvertexmaplp(maplpoints, lp, vertex)
addvertexmapct(maplpcountries, lp, vertex)
return database
def loadconnections(database, connection):
mapconnections = database['mapconnections']+
destination = connection['destination']
origin = connection['origin']
cablename = connection['cable_name']
relation = (origin, cablename)
completemap(mapconnections, destination, relation)
#esta funcion identifica cuantos cables llegaran a un vertice
def loadcountries(database, countries):
pass
def createvertex(database):
mapconnections = database['mapconnections']
pass
#_______________________________________________________________
# Funciones para creacion de datos
def addvertexgraph(graph, lp):
# agrega los vertices al grafo
if not gr.containsVertex(graph, lp):
gr.insertVertex(graph, lp)
return graph
def addvertexmaplp(maplpoints, lp, vertex):
#guarda todo los vertices en un map
entry = mp.get(maplpoints, lp)
if entry is None:
mp.put(maplpoints, lp, vertex)
return maplpoints
def addvertexmapct(maplpcountries, lp, vertex):
#cladifica los vertices por paises
countrie = vertex['name']
countrie = countrie.replace(' ','').lower().replace(',',' ')
countrie = countrie.split()
if len(countrie) == 1:
completemap(maplpcountries, countrie[0], lp)
else:
completemap(maplpcountries, countrie[1], lp)
def completemap(map, key, value):
entry = mp.get(map,key)
if entry is None:
datentry = completelist('ARRAY_LIST', value)
mp.put(map,key,datentry)
else:
datentry = me.getValue(entry)
lt.addLast(datentry, value)
return map
def completelist(type, data):
list = lt.newList(type)
lt.addLast(list, data)
return list
def createmap(size):
map = mp.newMap(size,
maptype='PROBING',
loadfactor=0.5,
comparefunction=None)
return map
#_______________________________________________________________
# Funciones de consulta
#_______________________________________________________________
# Funciones utilizadas para comparar elementos dentro de una lista
#_______________________________________________________________
# Funciones de ordenamiento
| true |
e6a89b0b16d9f447a4bef16ead9e0a96fdc0b4d2 | Python | wickman/rainman | /rainman/torrent.py | UTF-8 | 1,680 | 2.5625 | 3 | [] | no_license | import hashlib
from .codec import BDecoder, BEncoder
from .metainfo import MetaInfo
from .handshake import PeerHandshake
class Torrent(dict):
@classmethod
def from_file(cls, filename):
with open(filename, 'rb') as fp:
torrent, _ = BDecoder.decode(fp.read())
if 'info' not in torrent or 'announce' not in torrent:
raise ValueError('Invalid .torrent file!')
return cls.from_metainfo(torrent['info'], torrent['announce'])
@classmethod
def from_metainfo(cls, metainfo, announce):
return cls(info=MetaInfo(metainfo), announce=announce)
def __init__(self, *args, **kw):
super(Torrent, self).__init__(*args, **kw)
self._invalidate()
def to_file(self, filename):
assert 'announce' in self and 'info' in self
with open(filename, 'wb') as fp:
fp.write(BEncoder.encode(self))
def _invalidate(self):
self._hash = hashlib.sha1(BEncoder.encode(self.get('info', {}))).digest()
self._prefix = PeerHandshake.make(self._hash)
def raw(self):
return BEncoder.encode(self)
@property
def hash(self):
return self._hash
@property
def handshake_prefix(self):
return self._prefix
def handshake(self, peer_id=None):
return PeerHandshake.make(self._hash, peer_id)
@property
def announce(self):
return self.get('announce')
@announce.setter
def announce(self, value):
assert isinstance(value, str)
self['announce'] = value
@property
def info(self):
return self['info']
@info.setter
def info(self, value):
if not isinstance(value, dict):
raise TypeError('Info must be a dictionary or MetaInfo.')
self['info'] = MetaInfo(value)
self._invalidate()
| true |
2f903d1af0966c3dda82ad9f2e7ca4c3e1c1ad5b | Python | toticavalcanti/HackerHank | /Diagonal_Difference.py | UTF-8 | 709 | 3.390625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 12:07:33 2018
@author: toti.cavalcanti
"""
#!/bin/python3
import sys
def diagonalDifference(a):
# Complete this function
diagonal_left_to_right = 0
diagonal_right_to_left = 0
for i in range(n):
diagonal_left_to_right += a[i][i]
for i in range(n):
diagonal_right_to_left += list(reversed(a[i]))[i]
return(abs(diagonal_left_to_right - diagonal_right_to_left))
if __name__ == "__main__":
n = int(input().strip())
a = []
for a_i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
a.append(a_t)
result = diagonalDifference(a)
print(result)
| true |
290b16ffc555cb3f6f763644ab10d3c277b7b489 | Python | whyadiwhy/Awesome_Python_Scripts | /GUIScripts/Contact Management System/contact_management_system.py | UTF-8 | 14,521 | 2.90625 | 3 | [
"MIT"
] | permissive | # Import Required Modules
from tkinter import *
import sqlite3
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
root = Tk() # Setting an Window
root.title("Contact List") # Applicaion Name
width = 700
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # Application Size
root.resizable(0, 0)
root.config(bg="magenta")
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Variable Names
FIRSTNAME = StringVar()
LASTNAME = StringVar()
GENDER = StringVar()
AGE = StringVar()
ADDRESS = StringVar()
CONTACT = StringVar()
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def Database(): # Function to Create Database
conn = sqlite3.connect("pythontut.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT, gender TEXT, age TEXT, address TEXT, contact TEXT)")
cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def SubmitData(): # Function to Submit the data
if FIRSTNAME.get() == "" or LASTNAME.get() == "" or GENDER.get() == "" or AGE.get() == "" or ADDRESS.get() == "" or CONTACT.get() == "":
result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
else:
tree.delete(*tree.get_children())
conn = sqlite3.connect("pythontut.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO `member` (firstname, lastname, gender, age, address, contact) VALUES(?, ?, ?, ?, ?, ?)", (str(FIRSTNAME.get()), str(LASTNAME.get()), str(GENDER.get()), int(AGE.get()), str(ADDRESS.get()), str(CONTACT.get())))
conn.commit()
cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
FIRSTNAME.set("")
LASTNAME.set("")
GENDER.set("")
AGE.set("")
ADDRESS.set("")
CONTACT.set("")
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def UpdateData(): # Function to Update the Data in Contact List
if GENDER.get() == "":
result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
else:
tree.delete(*tree.get_children())
conn = sqlite3.connect("pythontut.db")
cursor = conn.cursor()
cursor.execute("UPDATE `member` SET `firstname` = ?, `lastname` = ?, `gender` =?, `age` = ?, `address` = ?, `contact` = ? WHERE `mem_id` = ?", (str(FIRSTNAME.get()), str(LASTNAME.get()), str(GENDER.get()), str(AGE.get()), str(ADDRESS.get()), str(CONTACT.get()), int(mem_id)))
conn.commit()
cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
FIRSTNAME.set("")
LASTNAME.set("")
GENDER.set("")
AGE.set("")
ADDRESS.set("")
CONTACT.set("")
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def OnSelected(event): # Function for labels, entry and button functions...
global mem_id, UpdateWindow
curItem = tree.focus()
contents =(tree.item(curItem))
selecteditem = contents['values']
mem_id = selecteditem[0]
FIRSTNAME.set("")
LASTNAME.set("")
GENDER.set("")
AGE.set("")
ADDRESS.set("")
CONTACT.set("")
FIRSTNAME.set(selecteditem[1])
LASTNAME.set(selecteditem[2])
AGE.set(selecteditem[4])
ADDRESS.set(selecteditem[5])
CONTACT.set(selecteditem[6])
UpdateWindow = Toplevel() # Update the existing window
UpdateWindow.title("Contact List")
width = 400
height = 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = ((screen_width/2) + 450) - (width/2)
y = ((screen_height/2) + 20) - (height/2)
UpdateWindow.resizable(0, 0)
UpdateWindow.geometry("%dx%d+%d+%d" % (width, height, x, y)) # Size of the window
if 'NewWindow' in globals():
NewWindow.destroy()
#FRAMES
FormTitle = Frame(UpdateWindow)
FormTitle.pack(side=TOP)
ContactForm = Frame(UpdateWindow)
ContactForm.pack(side=TOP, pady=10)
RadioGroup = Frame(ContactForm)
Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
#LABELS
lbl_title = Label(FormTitle, text="Updating Contacts", font=('arial', 16), bg="green", width = 300) #Title
lbl_title.pack(fill=X)
lbl_firstname = Label(ContactForm, text="Firstname", font=('arial', 14), bd=5) # First Name
lbl_firstname.grid(row=0, sticky=W)
lbl_lastname = Label(ContactForm, text="Lastname", font=('arial', 14), bd=5) # Last Name
lbl_lastname.grid(row=1, sticky=W)
lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5) #Gender
lbl_gender.grid(row=2, sticky=W)
lbl_age = Label(ContactForm, text="Age", font=('arial', 14), bd=5) # Age
lbl_age.grid(row=3, sticky=W)
lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5) # Address
lbl_address.grid(row=4, sticky=W)
lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5) # Contact number
lbl_contact.grid(row=5, sticky=W)
#ENTRY
firstname = Entry(ContactForm, textvariable=FIRSTNAME, font=('arial', 14)) # First Name
firstname.grid(row=0, column=1)
lastname = Entry(ContactForm, textvariable=LASTNAME, font=('arial', 14)) # Last Name
lastname.grid(row=1, column=1)
RadioGroup.grid(row=2, column=1) # Gender
age = Entry(ContactForm, textvariable=AGE, font=('arial', 14)) # Age
age.grid(row=3, column=1)
address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14)) # Address
address.grid(row=4, column=1)
contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14)) # Contact number
contact.grid(row=5, column=1)
#BUTTONS
btn_updatecon = Button(ContactForm, text="Update", width=50, command=UpdateData) # To Update COntact Page
btn_updatecon.grid(row=6, columnspan=2, pady=10)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def DeleteData(): # Function to Delete the data
if not tree.selection():
result = tkMessageBox.showwarning('', 'Please Select Something First!', icon="warning")
else:
result = tkMessageBox.askquestion('', 'Are you sure you want to delete this record?', icon="warning")
if result == 'yes':
curItem = tree.focus()
contents =(tree.item(curItem))
selecteditem = contents['values']
tree.delete(curItem)
conn = sqlite3.connect("pythontut.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM `member` WHERE `mem_id` = %d" % selecteditem[0])
conn.commit()
cursor.close()
conn.close()
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def AddNewWindow(): # New Window function for add contact
global NewWindow
FIRSTNAME.set("")
LASTNAME.set("")
GENDER.set("")
AGE.set("")
ADDRESS.set("")
CONTACT.set("")
NewWindow = Toplevel()
NewWindow.title("Contact List")
width = 400
height = 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = ((screen_width/2) - 455) - (width/2)
y = ((screen_height/2) + 20) - (height/2)
NewWindow.resizable(0, 0)
NewWindow.geometry("%dx%d+%d+%d" % (width, height, x, y))
if 'UpdateWindow' in globals():
UpdateWindow.destroy()
#FRAMES
FormTitle = Frame(NewWindow)
FormTitle.pack(side=TOP)
ContactForm = Frame(NewWindow)
ContactForm.pack(side=TOP, pady=10)
RadioGroup = Frame(ContactForm)
Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
#LABELS
lbl_title = Label(FormTitle, text="Adding New Contacts", font=('arial', 16), bg="cyan", width = 300)
lbl_title.pack(fill=X)
lbl_firstname = Label(ContactForm, text="Firstname", font=('arial', 14), bd=5)
lbl_firstname.grid(row=0, sticky=W)
lbl_lastname = Label(ContactForm, text="Lastname", font=('arial', 14), bd=5)
lbl_lastname.grid(row=1, sticky=W)
lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5)
lbl_gender.grid(row=2, sticky=W)
lbl_age = Label(ContactForm, text="Age", font=('arial', 14), bd=5)
lbl_age.grid(row=3, sticky=W)
lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5)
lbl_address.grid(row=4, sticky=W)
lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5)
lbl_contact.grid(row=5, sticky=W)
#ENTRY
firstname = Entry(ContactForm, textvariable=FIRSTNAME, font=('arial', 14))
firstname.grid(row=0, column=1)
lastname = Entry(ContactForm, textvariable=LASTNAME, font=('arial', 14))
lastname.grid(row=1, column=1)
RadioGroup.grid(row=2, column=1)
age = Entry(ContactForm, textvariable=AGE, font=('arial', 14))
age.grid(row=3, column=1)
address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14))
address.grid(row=4, column=1)
contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14))
contact.grid(row=5, column=1)
#BUTTONS
btn_addcon = Button(ContactForm, text="Save", bg = "aqua", width=50, command=SubmitData)
btn_addcon.grid(row=6, columnspan=2, pady=10)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
#FRAMES
Top = Frame(root, width=500, bd=1, relief=SOLID) # Setting up a frame
Top.pack(side=TOP)
Mid = Frame(root, width=500, bg="magenta")
Mid.pack(side=TOP)
MidLeft = Frame(Mid, width=100)
MidLeft.pack(side=LEFT, pady=10)
MidLeftPadding = Frame(Mid, width=370, bg="magenta")
MidLeftPadding.pack(side=LEFT)
MidRight = Frame(Mid, width=100)
MidRight.pack(side=RIGHT, pady=10)
TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
#LABELS
lbl_title = Label(Top, text="Contact Management System", font=('arial', 16), bg = "pink", width=500)
lbl_title.pack(fill=X)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
#BUTTONS
btn_add = Button(MidLeft, text="ADD NEW", bg="lemonchiffon", command=AddNewWindow)
btn_add.pack()
btn_delete = Button(MidRight, text="DELETE", bg="lemonchiffon", command=DeleteData)
btn_delete.pack(side=RIGHT)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
#TABLES
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("MemberID", "Firstname", "Lastname", "Gender", "Age", "Address", "Contact"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('MemberID', text="MemberID", anchor=W)
tree.heading('Firstname', text="Firstname", anchor=W)
tree.heading('Lastname', text="Lastname", anchor=W)
tree.heading('Gender', text="Gender", anchor=W)
tree.heading('Age', text="Age", anchor=W)
tree.heading('Address', text="Address", anchor=W)
tree.heading('Contact', text="Contact", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=0)
tree.column('#2', stretch=NO, minwidth=0, width=80)
tree.column('#3', stretch=NO, minwidth=0, width=120)
tree.column('#4', stretch=NO, minwidth=0, width=90)
tree.column('#5', stretch=NO, minwidth=0, width=80)
tree.column('#6', stretch=NO, minwidth=0, width=120)
tree.column('#7', stretch=NO, minwidth=0, width=120)
tree.pack()
tree.bind('<Double-Button-1>', OnSelected)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__': # Main Loop
Database()
root.mainloop()
| true |
a249811235c4403d7727c5bee1e9db347d7afee6 | Python | haeunnam/Algorithm | /SWEA/1970.쉬운거스름돈.py | UTF-8 | 435 | 3.421875 | 3 | [] | no_license |
def calculate_change(money, idx):
if money < 10:
return
while money >= unit[idx]:
money -= unit[idx]
change[idx] += 1
calculate_change(money, idx+1)
return
for tc in range(1, int(input())+1):
money = int(input())
change = [0] * 8
unit = [50000, 10000, 5000, 1000, 500, 100, 50, 10]
calculate_change(money, 0)
print('#{}'.format(tc))
print(" ".join(map(str, change)))
| true |
f9f73da8838422c97b2b52aa9c3a513ee891c2fd | Python | christinecoco/python_test | /test46.py | UTF-8 | 353 | 4.21875 | 4 | [] | no_license | #求输入数字的平方,如果平方运算后小于 50 则退出
print('如果输入数字的平方小于50,程序则会退出')
while True:
i=int(input('请输入一个数:'))
sum=i*i
if sum<50:
print('%d的平方是%d'%(i,sum))
break
else:
print('%d的平方是%d'%(i,sum))
| true |
c779401142435481b8693942c74eee26705760e7 | Python | mayank888k/Python | /tupleeee.py | UTF-8 | 313 | 3.515625 | 4 | [] | no_license | lst=[5,6,7,8,9] #tuple is Immutable like strings
tple=(1,2,3,4) #you cant append or remove like list
tple2=tuple(lst)
tple3=tple + tple2
print(tple3)
print(tple3[5:10]) #you can access it by index
print(tple3[::-1])
print(max(tple3))
del tple3 #You can delete whole tuple | true |
e23288915cb0c0ee790cf393fd5a5ced4d6f3d2d | Python | piter104/dices | /dice_counter.py | UTF-8 | 4,240 | 2.671875 | 3 | [] | no_license | import cv2 as cv
import numpy as np
import random as rng
import copy
import matplotlib.pyplot as plt
def remove_everything_below_std_and_mean(image):
treshold = round(np.std(image) + np.mean(image))
return np.array((image > treshold) * 255, dtype=np.uint8)
def __draw_contours(image):
copy_image = copy.deepcopy(image)
contours, hierarchy = cv.findContours(copy_image, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
color = (rng.randint(120,130), rng.randint(120,130), rng.randint(120,130))
cv.drawContours(copy_image, contours, -1, color, 5, cv.LINE_8, hierarchy, 2)
return copy_image
def process_image_and_draw_fragments(filtered_image):
min_width = 30
max_width = 400
color = (rng.randint(120,130), rng.randint(120,130), rng.randint(120,130))
minimum_distance_between_circles_centers = 80
contoursss, hierarchy = cv.findContours(filtered_image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
images = []
for j, con in enumerate(contoursss):
x,y,w,h = cv.boundingRect(contoursss[j])
perimeter = cv.arcLength(con, True)
approx = cv.approxPolyDP(con, 0.03 * perimeter , True)
if len(approx) != 4 or w < min_width or w > max_width or h < min_width or h > max_width:
continue
cropped = filtered_image[y:y+h,x:x+w]
rezised = cv.resize(cropped, (400, 400))
circles = cv.HoughCircles(rezised, cv.HOUGH_GRADIENT, 1,
minimum_distance_between_circles_centers,
param1=100, param2=14,
minRadius=15, maxRadius=80)
if circles is None:
continue
circles = np.uint16(np.around(circles))
for i, circle in enumerate(circles[0, :6]):
center = (circle[0],circle[1])
radius = circle[2]
cv.circle(rezised,center,radius,color,3)
images.append(rezised)
fig = plt.figure()
for i, img in enumerate(images):
fig.add_subplot(len(images), 1, i+1)
plt.imshow(img)
plt.show()
def __process(base_image, filtered_image):
base_image = np.array(base_image, dtype=np.uint8)
min_width = 30
max_width = 400
rectangle_thickness = 4
color = (rng.randint(120,130), rng.randint(120,130), rng.randint(120,130))
minimum_distance_between_circles_centers = 80
contoursss, hierarchy = cv.findContours(filtered_image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
all_circles = 0
for j, con in enumerate(contoursss):
x,y,w,h = cv.boundingRect(contoursss[j])
perimeter = cv.arcLength(con, True)
approx = cv.approxPolyDP(con, 0.03 * perimeter , True)
if len(approx) != 4 or w < min_width or w > max_width or h < min_width or h > max_width:
continue
cropped = filtered_image[y:y+h,x:x+w]
rezised = cv.resize(cropped, (400, 400))
circles = cv.HoughCircles(rezised, cv.HOUGH_GRADIENT, 1,
minimum_distance_between_circles_centers,
param1=100, param2=14,
minRadius=15, maxRadius=80)
if circles is None:
continue
circles = np.uint16(np.around(circles))
circles_count = len(circles[0, :6])
if circles_count > 6:
circles_count = 6 # 🙃
all_circles += circles_count
cv.rectangle(base_image, (x, y), (x+w, y+h), color, rectangle_thickness)
cv.putText(base_image, str(circles_count), (x+w+10, y+h+10), cv.FONT_HERSHEY_SIMPLEX, 2, color, 3, cv.LINE_AA)
cv.putText(base_image, f'Wszystkich kropek: {all_circles}', (60, 60), cv.FONT_HERSHEY_SIMPLEX, 2, (100, 100, 100), 4, cv.LINE_AA)
plt.imshow(cv.cvtColor(base_image, cv.COLOR_BGR2RGB))
plt.show()
def process_image(file_name):
image = cv.imread(file_name)
image = cv.resize(image, (1280, 720))
bw_image = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
filtered = remove_everything_below_std_and_mean(bw_image)
kernel = np.ones((3,3), np.uint8)
eroded = cv.erode(filtered, kernel, iterations=2)
__process(image, eroded)
if __name__ == "__main__" :
process_image("1.jpg") | true |
32b40baa290a3bb56dadcaff0ea4436b7da6877b | Python | ellynhan/challenge100-codingtest-study | /suyeonsu/Implement_23290.py | UTF-8 | 3,411 | 3.484375 | 3 | [] | no_license | from collections import deque
def moveFish():
moved = [[[] for _ in range(5)] for _ in range(5)]
dx = [0, 0, -1, -1, -1, 0, 1, 1, 1]
dy = [0, -1, -1, 0, 1, 1, 1, 0, -1]
for x in range(1, 5):
for y in range(1, 5):
for direction in origin[x][y]:
d = direction
for _ in range(8):
nx, ny = x + dx[d], y + dy[d]
sm = sum(smell, [])
if 1 <= nx <= 4 and 1 <= ny <= 4 and (nx, ny) != (sx, sy) and (nx, ny) not in sm:
moved[nx][ny].append(d)
break
else:
d = d - 1 if d > 1 else 8
else:
moved[x][y].append(direction)
return moved
def product(arr, r):
for i in range(len(arr)):
if r == 1:
yield [arr[i]]
else:
for nxt in product(arr, r - 1):
yield [arr[i]] + nxt
def moveShark():
global sx, sy
dx = [0, -1, 0, 1, 0]
dy = [0, 0, -1, 0, 1]
def getRoute(sx, sy):
max_val = -1, -1
for case in list(product([1, 2, 3, 4], 3)):
cnt = 0
visited = [[0] * 5 for _ in range(5)]
x, y = sx, sy
for direction in case:
nx, ny = x + dx[direction], y + dy[direction]
if 1 <= nx <= 4 and 1 <= ny <= 4:
if not visited[nx][ny]:
visited[nx][ny] = 1
cnt += len(board[nx][ny])
x, y = nx, ny
else:
break
else:
if max_val[0] < cnt:
max_val = cnt, case
return max_val[1]
smell.append([])
route = getRoute(sx, sy)
for direction in route:
sx += dx[direction]
sy += dy[direction]
if 1 <= sx <= 4 and 1 <= sy <= 4 and len(board[sx][sy]):
board[sx][sy] = []
smell[-1].append((sx, sy))
def replicateFish():
for x in range(1, 5):
for y in range(1, 5):
for fish in board[x][y]:
origin[x][y].append(fish)
def countFish():
cnt = 0
for row in origin:
for fish in row:
cnt += len(fish)
return cnt
m, s = map(int, input().split())
origin = [[[] for _ in range(5)] for _ in range(5)]
smell = deque()
for _ in range(m):
fx, fy, d = map(int, input().split())
origin[fx][fy].append(d)
sx, sy = map(int, input().split())
for practice in range(s):
board = moveFish()
moveShark()
if practice >= 2: smell.popleft()
replicateFish()
print(countFish())
"""
[조합, 순열, 중복조합, 중복순열 itertools없이 구현하기]
기본 틀은 똑같고, else의 for문에서 재귀호출 할 때 전달하는 리스트가 다른데,
def ___func___(arr, r):
for i in range(len(arr)):
if r == 1:
yield [arr[i]]
else:
for nxt in ___func___(_____, r-1):
yield [arr[i]] + nxt
- 조합 (중복 x, 순서 상관 x): combinations(arr[i+1:], r-1)
- 순열 (중복 x, 순서 상관 o): permutations(arr[:i] + arr[i+1:], r-1)
- 중복조합 (중복 o, 순서 상관 x): combinations_with_replacement(arr[i:], r-1)
- 중복순열 (중복 o, 순서 상관 o): product(arr, r-1)
[2차원 리스트 1차원으로 만들기]
sum(arr, [])
"""
| true |
3f0f873185d7b3162380a9f82abe16399db37adb | Python | arlinnshimimana/python-basis | /py6.3.py | UTF-8 | 175 | 3.015625 | 3 | [] | no_license | def lang_genoeg(lengte):
if lengte > 120 or lengte == 120:
print('je bent lang genoeg')
else:
print('Sorry,je bent te klein')
print(lang_genoeg(177)) | true |
70b76d695d6142c83c76733e5789f7355defe0e8 | Python | chosaihim/jungle_codingTest_study | /JAN/20th/sh_체육복.py | UTF-8 | 594 | 2.890625 | 3 | [] | no_license | def solution(n, lost, reserve):
lost.sort()
reserve.sort()
tmp=[]
for student in lost:
tmp.append(student)
for student in tmp:
if student in reserve:
reserve.remove(student)
lost.remove(student)
borrow = 0
for student in lost:
if student-1 in reserve:
reserve.remove(student-1)
borrow += 1
elif student+1 in reserve:
reserve.remove(student+1)
borrow += 1
answer = n - len(lost) + borrow
return answer | true |
8bbbc37e3c684f0fc31e44ea3e78d8a65fc5dc7c | Python | meechaguep/MCOC-Intensivo-de-Nivelacion | /21082019/000226.py | UTF-8 | 696 | 4.15625 | 4 | [] | no_license | print "Este dia estudiaremos listas"
#intento 1
lista1= [14,21,3,-14,-21,-3]
print "la lista es:"
print lista1
#intento 2
print "agreguemos un numero a la lista"
lista1= [14,21,3,-14,-21,-3]
lista1.append(1313)
print lista1
#intento 3
print "ahora agreguemos una frase a esta lista de numeros"
lista1= [14,21,3,-14,-21,-3,1313] #las defino denuevo simplemente para hacer como codigos nuevos
lista1.append("hola numeros, soy un texto")
print lista1
#intento 4
print "ahora agreguemos una lista nueva dentro de la actual"
lista1= [14, 21, 3, -14, -21, -3, 1313, 'hola numeros, soy un texto']
lista1.append(["yo tambien soy texto",44,55,22])
print lista1 | true |
fa47727a25426c905e72ceb4dd8d3aed8896aeda | Python | juliaheisler/CSE-231 | /proj07.py | UTF-8 | 7,280 | 4.375 | 4 | [] | no_license | ##############################################################################
# Computer Project 7
#
# Algorithm
#
# Project uses 7 functions to take a network provided and suggests a friend\
# to inputed user that has the most friends in common (not already friends).
#
# open_file: attempts opening .txt file if file exists
#
# read_file: uses file pointer as an argument and creates list of lists -\
# each user and their friends.
#
# num_in_common_between_lists: takes two lists as arguments. Finds greatest\
# number of friends in common between the two lists.
#
# init_matrix: creates empty matrix that is n x n in size
#
# calc_similarity_scores: takes network as an argument. Creates similarity\
# matrix of network's size.
#
# recommend: uses network, user_id, and similarity_matrix as arguments.
# Finds friend in common with most mutual friends (not already friends).
#
# main: main function of program, uses user's inputed file and user_id,\
# to determine recommended friend (with most mutual friends)
##############################################################################
#import sys
#def input( prompt=None ):
#if prompt != None:
#print( prompt, end="" )
#aaa_str = sys.stdin.readline()
#aaa_str = aaa_str.rstrip( "\n" )
#print( aaa_str )
#return aaa_str
def open_file():
'''
Using user's input, attempts to open .txt file (try/except)
Returns txt file
'''
# driver loop for user's file input #
while True:
file_input = input("Enter a filename: ")
try:
# while file exists, attempt opening #
fp = open(file_input)
# return file pointer #
return fp
# if file does not exist, prints error statement #
except FileNotFoundError:
print("\nError: File does not exist!")
def read_file(fp):
'''
Using inputed file, creates a list of lists - each user's friends
Returns network
'''
# Read n and initialize the network to have n empty lists --
# one empty list for each member of the network
# saves first line of file (network size) to n #
n = fp.readline()
# converts n to integer #
n = int(n)
# initializes network to an empty list #
network = []
# for loop creating list of lists, depending on number of users #
for i in range(n):
network.append([])
# for loop iterating through lines of txt file #
for line in fp:
# assigns stripped/split string to a and b #
a,b=line.strip().split()
# converts a and b to integers #
a,b = int(a),int(b)
# adds b to the network of a #
network[a].append(b)
# adds a to the network of b #
network[b].append(a)
# returns network - list of lists #
return network
def num_in_common_between_lists(list1, list2):
'''
Using two lists of user friends, finds greatest value of friends in common
Returns common_friends (integer)
'''
# initializes friends in common to 0 #
common_friends = 0
# for loop iterating through first list #
for i in list1:
# if user in list1 also appears in list2 #
if i in list2:
# increment common friends by 1 #
common_friends += 1
# returns greatest number of friends in common between lists #
return common_friends
def init_matrix(n):
'''Create an nxn matrix, initialize with zeros, and return the matrix.'''
matrix = []
for row in range(n): # for each of the n rows
matrix.append([]) # create the row and initialize as empty
for column in range(n):
matrix[row].append(0) # append a 0 for each of the n columns
return matrix
def calc_similarity_scores(network):
'''
Creates matrix of friends in common between each user
Returns similarity_matrix
'''
# similarity matrix created n x n - numbers of users in network #
similarity_matrix = init_matrix(len(network))
for a in range(len(network)):
for b in range (len(network)):
# defines common_friends as number of friends in common between 2\
# indexes of network #
common_friends = num_in_common_between_lists(network[a],network[b])
# creates similarity matrix #
similarity_matrix[a][b] = similarity_matrix[b][a] = common_friends
return similarity_matrix
def recommend(user_id,network,similarity_matrix):
'''
Uses user, network, and similarity matrix to find user with most\
friends in common that the user is not already friends with.
Returns recommendation.
'''
# creates similarity matrix from network provided #
similarity_matrix = calc_similarity_scores(network)
# initializes maximum value to 0 to begin counter #
maximum = 0
# enumerate loop through index that is provided user id #
for i, value in enumerate(similarity_matrix[user_id]):
# if statement picking largest value that is not the user id and\
# not in its network #
if value > maximum and i != user_id and i not in network[user_id]:
maximum = value
recommendation = i
# returns friend recommendation #
return recommendation
def main():
print("\nFacebook friend recommendation.\n")
# prompts user for file and attempts to open #
fp = open_file()
# creates list of lists (user's and their friends) from file provided #
network = read_file(fp)
# creates similarity matrix from network #
similarity_matrix = calc_similarity_scores(network)
# acceptable range assigned to net_range #
net_range = len(network)-1
# driver loop for inputed user_id #
while True:
# while integer is entered, try #
try:
# prompts user for integer in network range #
user_input = input("Enter an integer in the range 0 to "\
+str(net_range)+": ")
# converts user_input to integer #
user_id = int(user_input)
# if non-integer entered, error message printed and loop restarted #
except ValueError:
print("Error: non-integer entered!")
continue
# if the user_id falls into the range of the network #
if user_id in range (net_range):
# recommendation found using recommend function #
recommendation = recommend(user_id,network,similarity_matrix)
# prints recommended friend #
print("The suggested friend for", user_id, "is", recommendation)
# continuation prompt #
cont_loop = input("\nDo you want to continue? ")
# if user inputs any form of 'yes', restart loop #
if cont_loop.lower() == 'yes':
continue
# if user inputs any form of 'no', quit program #
if cont_loop.lower() == 'no':
break
# if integer entered is out of range, error message printed #
else:
print("Error: input must be an int between 0 and ", net_range)
if __name__ == "__main__":
main()
# Questions
# Q1: 7
# Q2: 4
# Q3: 6
# Q4: 6
# Q5: 7
| true |
cd50ad882f10f716ad13a97faad52b87ef87b972 | Python | jackwallace180/python24-9 | /while loops.py | UTF-8 | 574 | 3.734375 | 4 | [] | no_license |
# keeps looping an iterating until a condition is met
# OR it comes into a break statement
#while<condition>:
#block
# if <condition>:
#break
#import time
#counter = 0
#while counter <10:
#print(counter)
#print('hello')
#counter += 1
#time.sleep(1)
#counter = 0
#while True:
#print(counter)
#print('WAAAAHHHHHH')
#if counter > 10:
#break
#counter+=1
cars = ['volvo', 'skoda', 'ferrari', 'lambo']
counter = 0
max_length = len(cars)
while max_length > counter:
print(counter +1, '-',cars[counter])
counter += 1
| true |
f2939b80968fe76ccbcf64474f70f16da45b2b1c | Python | abhigupta4/Competitive-Coding | /SPOJ/AKVQLD03.py | UTF-8 | 553 | 2.96875 | 3 | [] | no_license | def getsum(index):
sum1 = 0
while index > 0:
sum1 += BIT[index]
index -= index & (-index)
return sum1
def updateBIT(n,index,val):
while(index <= n):
BIT[index] += val
index += index & (-index)
def cons(n):
for i in xrange(n):
updateBIT(n,i,list1[i])
BIT = [0] * (10**6 + 2)
list1 = [0] * (10**6 + 2)
n,q = map(int,raw_input().split())
for i in xrange(q):
arr = raw_input().split()
if arr[0] == 'find':
print (getsum(int(arr[2]))-getsum(int(arr[1])-1))
else:
updateBIT(n,int(arr[1]),int(arr[2]))
#AC | true |
2aee592c660987143f5ed54cfd9ccf86a0c98ef0 | Python | TTWen/test | /test9.py | UTF-8 | 634 | 2.703125 | 3 | [] | no_license | #cs231n:批量归一化
import numpy as np
#定义一个双层网络随机初始化
def init_two_layer_model(input_size,hidden_size,output_size):
model = {}
model['W1'] = 0.0001 * np.random.randn(input_size,hidden_size)
model['b1'] = np.zeros(hidden_size)
model['W2'] = 0.0001 * np.random.randn(hidden_size,output_size)
model['b2'] = np.zeros(output_size)
return model
model = init_two_layer_model(32*32*3,50,10)
loss,grade = two_layer_net(X_train,model,y_train,0.0) #这里的0是零正则化项,loss大约是2.3,启动正则化赋值为1e3时,loss大约是3.06
print("loss:",loss)
| true |
61d3ae63d80ac578f48424b53446228536e94e76 | Python | nekapoor7/Python-and-Django | /PRACTICE_CODE/fibo_series_sum.py | UTF-8 | 539 | 3.671875 | 4 | [] | no_license | class Fibonacci:
def __init__(self):
self.cache = {}
def __call__(self,n):
if n not in self.cache:
if n == 0 :
self.cache[0] = 0
elif n == 1:
self.cache[1] = 1
else:
self.cache[n] = self.__call__(n-1) + self.__call__(n-2)
return self.cache[n]
start = int(input())
end = int(input())
list1 = []
sum = 0
fib = Fibonacci()
for i in range(start,end + 1):
list1.append(fib(i))
sum += fib(i)
print(list1)
print(sum)
| true |
71b5311e66bc2c7da973e2855e1fbd48bdf04b40 | Python | jhson989/algorithm | /Grammar/Array/cal_avg.py | UTF-8 | 240 | 2.78125 | 3 | [] | no_license | import sys
C = int(sys.stdin.readline())
for _ in range(C):
num, *L = [int(e) for e in sys.stdin.readline().split()]
avg = sum(L)/len(L)
chk = [1 if e>avg else 0 for e in L]
print( "%.3f" % (100.0*sum(chk)/len(chk)) + "%" ) | true |
c40aeef764c90edaf477c20165885829108e2bc5 | Python | inkysigma/ACM-UCI-Website | /src/data/long_distance_social_distance_i.py | UTF-8 | 87 | 3.46875 | 3 | [
"MIT"
] | permissive | T = int(input())
for _ in range(T):
n = int(input())
print((n//2)*6 + 4*(n%2))
| true |
fb562df2d405d3368276acd17bb450584ac7caf8 | Python | StRobertCHSCS/fabroa-PHRZORO | /Working/PracticeQuestions/1_1_4_Variables.py | UTF-8 | 62 | 3.046875 | 3 | [] | no_license | name = ("Keisha")
my_number = 10
print(name)
print(my_number)
| true |
a9cae2987a11b5ca46129473866fb2e67332763e | Python | MartinMxn/NailTheLeetcode | /Python/Hard/Review_OK_84_H_Largest Rectangle in Histogram.py | UTF-8 | 2,719 | 3.359375 | 3 | [] | no_license | class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
# brute force TLE
# find the min height for every height
# if len(heights) == 0:
# return 0
# res = heights[0]
# pt = 0
# def check(heights, end_idx):
# res = min_v = heights[pt]
# for i in range(end_idx, -1, -1):
# min_v = min(heights[i], min_v)
# res = max(res, min_v * (end_idx - i + 1))
# return res
# while pt < len(heights) - 1:
# if heights[pt + 1] < heights[pt]:
# max_v = check(heights, pt)
# res = max(max_v, res)
# elif heights[pt + 1] == heights[pt]:
# max_v = check(heights, pt + 1)
# res = max(max_v, res)
# pt += 1
# res = max(res, check(heights, pt)) # check at then end, prevent all increasing case
# return res
# stack
"""
maintain a monolithic stack to store index
the height of the index we store in stack is always increasing
because:
6
5
3
2 2
1
0 1 2 3 4 5
from the period 1 5 6, if we calculate the height from 6 to 5 to 1 the height after 5 and 1
are always height than themself, so we just care about width
if we meet decrease, we could just pop and calculate the higher height,
the left stack are all increase, and calculate them at the end
"""
def largestRectangleArea(self, heights: List[int]) -> int:
# monolithic stack
# always remember the increase heights before idx
# stack store the idx, not the value
stack = [-1]
res = 0
for i, h in enumerate(heights):
while stack[-1] != -1 and h < heights[stack[-1]]:
prev_i = stack.pop()
prev_h = heights[prev_i] # prev_h is always smaller than previous pop heights, so could use prev_h as max height
# like 5,6,2 when at 2, calculate 6, then 5, then 2 outside of for loop
width = i - 1 - stack[-1]
res = max(res, width * prev_h)
stack.append(i)
print(stack)
while stack[-1] != -1:
prev_i = stack.pop()
prev_h = heights[prev_i]
width = len(heights) - stack[-1] - 1 # dif with for loop, stack[-1] is the prev idx after pop
res = max(res, width * prev_h)
return res
| true |
9dc8f3873b4f25a976f75a06291c302ba2eed72c | Python | eckiss/diplomovka | /csvsave.py | UTF-8 | 1,581 | 2.8125 | 3 | [] | no_license |
import tweepy
import csv
import datetime
from operator import add
from authentication import authentication
auth = authentication()
# Twitter API credentials
consumer_key = auth.getconsumer_key()
consumer_secret = auth.getconsumer_secret()
access_key = auth.getaccess_token()
access_secret = auth.getaccess_token_secret()
def get_all_tweets():
# overenie
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
# pole tweetov
alltweets = []
# pocet tweetov na ziskanie
new_tweets = api.home_timeline(count=200)
# ulozene
alltweets.extend(new_tweets)
# id koniec
oldest = alltweets[-1].id - 1
#
while len(new_tweets) > 0:
print "od %s" % (oldest)
new_tweets = api.home_timeline(count=200, max_id=oldest)
#ulozenie dalsich tweetov
alltweets.extend(new_tweets)
oldest = alltweets[-1].id - 1
print "...%s po" % (len(alltweets))
# ulozenie tweetov do pola
outtweets = [
[
tweet.created_at,
tweet.text.encode("utf-8"),
]
for tweet in alltweets
]
# for i in range(outtweets):
# for j in range(outtweets):
# print '{:2}'.format(outtweets[i][j]),
# print
# ulozenie
with open('doprava_tweets.csv' , 'wb') as f:
writer = csv.writer(f)
writer.writerow(["Datum", "text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
get_all_tweets() | true |
19b876ac128c4271627f92ca2b31e8c4af3105f0 | Python | RobotronicsClubIITMandi/syncUAVs | /testing/gps_basic.py | UTF-8 | 628 | 2.75 | 3 | [] | no_license | # requires sudo
# RX -> Pin 8
# TX -> Pin 10
import serial
from serial.serialutil import SerialException
from gps_decoder import decodeGPGGA, NotGPGGAError, FixNotAcquiredError
port = "/dev/serial0"
ser = serial.Serial(port, baudrate=9600, timeout=1.0)
while True:
try:
line = ser.readline()
try:
print(decodeGPGGA(line))
except NotGPGGAError:
pass
except FixNotAcquiredError:
print("GPS fix not acquired")
except SerialException:
print("Exception Raised!!")
ser.close()
ser = serial.Serial(port, baudrate=9600, timeout=1.0)
| true |
cfef923e352ba13d0dbb4ff467bff5e963a2e627 | Python | outlander85/python_courses | /HomeWorks/main.py | UTF-8 | 18,129 | 3.59375 | 4 | [] | no_license | print('Hello, \nWorld!')
#
a = 1
b = 2
c = a + b
print(c)
#
a = 56
print(a%10)
#
a = 56
b = 78
print(a > b)
#
a = 56
b = 78
print(a, b)
#
userName = 'Petr'
print('Name:', userName)
#
a = 10
b = 20
c = 0
print(a < b and b > c)
#
a = 10
b = 20
c = 0
print(a < b and b < c or not c)
#a = input()
#print(a)
#a = input()
#print(type(a))
#
# a = input('enter y name: ')
# print(a)
'''
test
'''
try:
x = int(input('Введите первое число:'))
y = int(input('Введите второе число:'))
z = int(input('Введите предполагаемый ответ: '))
otvet = x * y
if otvet == z:
print('Верно!')
elif otvet != z:
print('Ответ не верный, правильный ответ:' + str(otvet))
##
from math import pi, sqrt
print(sqrt(pi))
#################################################################################
from math import sqrt
# print(sqrt(pi))
## Просим ввести числа у пользователя
a = int(input('Введите число a:'))
b = int(input('Введите число b:'))
c = int(input('Введите число c: '))
##вычисляем дискриминант
d = b ** 2 - 4 * a * c
if d > 0:
x1 = (-b + sqrt(d)) / 2 * a
x2 = (-b - sqrt(d)) / 2 * a
print('x1=', str(x1), 'x2=', str(x2))
elif d == 0:
x = -b / 2 * a
print('x=', x)
# elif d < 0:
else:
print('Действительных корней нет')
#################################################################################
a = int(input('Введите число a:'))
b = int(input('Введите число b:'))
res = 0
# x = 1
while a <= b:
if a % 2 != 0:
res += a ##
a += 1
print(res)
#################################################################################
a = int(input('Введите число a:'))
b = int(input('Введите число b:'))
res = 0
if a % 2 == 0:
a += 1
while a <= b:
res += a
a += 2
print(res)
#################################################################################
for i in 'hello world':
print (i, end = '')
#################################################################################
a = 1
b = 5
res = 0
for i in range(a, b+1):
if i % 2 != 0:
res += i
print(res)
#################################################################################
pA = 10
pB = 5
pC = 2
summ = 100
count = 30
for a in range(int(summ / pA)):
for b in range(int(summ / pB)):
for c in range(int(summ / pC)):
if (pA * a + pB * b + pC * c == summ) and a + b + c == count:
print(a, ',', b, ',', c)
#################################################################################
S = 'Hello'
print(S[0] + S[1] + S[2] + S[3])
print (S[-len(S)])
#################################################################################
s = 'abcdefghijklm'
print(s[0:10:2])
for i in range(0, 10, 2):
print (i, s[i])
#################################################################################
s = 'abcdefghijklm'
print(type(s))
#################################################################################
s = 'Python'
i = 0
while i < len(s):
print(s[i], end=' ')
i+=1
print(
for j in s:
print(j, end=' ')
print()
)
#################################################################################
s = 'Python'
i = 0
while i < len(s):
print(s[i], end=' ')
i += 1
print()
for j in s:
print(j, end=' ')
print()
stroka = 'Hello'
for symbol in stroka:
if symbol in stroka:
if symbol == 'y':
break
#################################################################################
import re
res = re.findall('\d','05 Analytics Vidnya 28')
res1 = re.findall('\d+','05 Analytics Vidnya 28')
print(res)
print(res1)
#################################################################################
import re
res = re.split('W', 'Hello World')
print(res)
#################################################################################
f = str(input('Введите фразу:'))
f1 = f.replace(' ', '')
i = 0
while i < (len(f1) // 2):
if f1[i] != f1[-1-i]:
print('-')
break
i += 1
else:
print('+')
# for i in range(i, cnt-1):
#################################################################################
s = 'abc cde def'
res = ''
for i in s:
if res.find(i) == -1 and i != ' ':
res += i
print(res)
#################################################################################
f = input('Введите последовательность букв латинского алфавита нижним и верхним регистром:')
k = 0
j = 0
for i in f:
if 'a' <= i <= 'z':
k += 1
if 'A' <= i <= 'Z':
j += 1
print('lower:' + str(k), 'upper:' + str(j))
#################################################################################
s = 'dfgmdflkbmh09_'
for i in range(len(s)):
if not ('a' <= s[0] <= 'z' or s[0] == '_'):
print('no')
quit()
if not (('a' <= s[i].lower() <= 'z') or ('0' <= s[i] <= '9') or (s[i] == '_')):
print('no')
quit()
print('yes')
#################################################################################
import random
se = random.randint(1, 5)
print(se)
#################################################################################
# def printToConsole()
# print('Hello World')
#
# printToConsole()
def dellSpace(s):
res = ''
for i in s:
if i != ' ':
res += i
return res
s = 'Hello World'
print(dellSpace(s))
def addAndDiff(x, y):
return x+y, x-y
print(addAndDiff(5,9))
#################################################################################
from HomeWorks import temp
typp = input('Введите К, П, или Т').lower()
if typp == 'к':
print(temp.sqr_circle())
elif typp == 'п':
print(temp.sqr_pr())
elif typp == 'т':
print(temp.sqr_triangle())
else:
print('Error')
# 2d part
import math
def sqr_circle():
r = float(input('Введите радиус:'))
pl = math.pi * (r ** 2)
return pl
def sqr_pr():
a = float(input('Введите сторону a:'))
b = float(input('Введите сторону b:'))
pl = a * b
return pl
def sqr_triangle():
a = float(input('Введите сторону a:'))
b = float(input('Введите сторону b:'))
c = float(input('Введите сторону c:'))
p = (a + b + c) /2
pl = math.sqrt(p * (p - a) * (p - b) * (p - c))
return pl
#################################################################################
x = int(input('Введите число:'))
print(len(str(abs(x))))
#################################################################################
s = [12, 12.22, '12', [1, 3, 4]]
print(type(s[0]))
#################################################################################
s = 'Hello world'
print(list(s))
#################################################################################
from random import randint
n = randint(10, 15)
arr = []
for i in range(n):
arr.append(randint(-100, 100))
print(arr)
num = 0
for i in range(1, len(arr)):
if abs(arr[i]) < abs(arr[num]):
num = i
print(num + 1)
#################################################################################
from random import randint
n = 10
arr = []
for i in range(n):
arr.append(randint(-100, 100))
print(arr)
res = 0
j = 0
while j < len(arr):
if arr[j] < 0:
del(arr[j])
else:
j += 1
print(arr)
#################################################################################
from random import randint
n = 5
arr = []
for i in range(n):
arr.append(randint(-100, 100))
print(arr)
min_x = 0
max_x = 0
res = 0
for i in range(1, len(arr)):
if arr[i] < arr[min_x]:
min_x = i
print(arr[min_x])
for j in range(1, len(arr)):
if arr[i] > arr[max_x]:
max_x = j
print(arr[max_x])
if max_x < min:
max_x, min_x = min_x, max_x
for k in range(min_x + 1, max_x):
res += arr[k]
print(res)
#################################################################################
from random import randint
n = 5
arr = []
for i in range(n):
arr.append(randint(-100, 100))
print(arr)
min_x = 0
max_x = 0
res = 0
for i in range(1, len(arr)):
if arr[i] < arr[min_x]:
min_x = i
print(arr[min_x])
for j in range(1, len(arr)):
if arr[i] > arr[max_x]:
max_x = j
print(arr[max_x])
if max_x < min:
max_x, min_x = min_x, max_x
for k in range(min_x + 1, max_x):
res += arr[k]
print(res)
#################################################################################
from random import randint
n = 10
arr = []
for i in range(n):
arr.append(randint(-100, 100))
print(arr)
res = 0
j = 0
while j < len(arr):
if arr[j] < 0:
del(arr[j])
else:
j += 1
print(arr)
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'a')
file.close()
print(file.closed)
print(file.mode)
print(file.name)
#################################################################################file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
data = file.read()
file.close()
print(data)
print (len(data))
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
data = file.readlines()
# data = file.readline()
file.close()
print(data)
print (len(data))
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
for line in file:
print(line, end = '')
file.close()
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
while True:
data = file.readline()
print(data, end = '')
if not data:
break
file.close()
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
while True:
data = file.read(2)
print(data)
if not data:
break
file.close()
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
data = file.read(4)
print(data)
print(file.tell())
data = file.read(2)
print(data)
print(file.tell())
file.close()
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'rb')
data = file.read(2)
print(data)
# print(file.tell())
file.seek(1, 2)
data = file.read(2)
print(data)
file.close()
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'a')
data = 'qwerty\n', 'qwerty2\n'
file.writelines(data)
file.close()
#################################################################################
with open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r') as file_handler:
for line in file_handler:
print(line, end='')
print('File Closed:' + ' ' + str(file_handler.closed))
#################################################################################
file = open(r'C:\Users\ihor.ivchenko\PycharmProjects\python_courses\file_1.txt', 'r')
# rus = ''
# eng = ''
N = file.readline()
d = {}
for line in file:
# print(line, end = '')
words = line.strip().split('-')
ru = words[0].strip()
en = words[1].strip().split(',')
# print(words)
# print(ru)
# print(en)
for en_word in en:
d[en_word.strip()] = ru
file.close()
file_output = open('file_output.txt', 'w')
file_output.write(str(len(d)) + '\n')
for key in sorted(d):
file_output.write(key + ' - ' + d[key] + '\n')
print(d)
#################################################################################
def readMass(path):
file = open(path)
N = 0
mass = []
for line in file:
row = line.strip().split(' ')
mass.append(row)
N += 1
file.close()
return mass, N
def printMass(mass):
for i in range(len(mass)):
for j in range(len(mass[i])):
print('%4s'%mass[i][j], end='')
print()
mass, N = readMass('file_2.txt')
printMass(mass)
def change (mass):
for i in range(len(mass)):
for j in range(len(mass[i])):
if i == j:
mass[i][j], mass[i][len(mass)-1-j] = mass[i][len(mass)-1-j], mass[i][j]
return mass
res = change(mass)
print()
printMass(res)
#################################################################################
def fun1(a):
x = a * 3
def fun2(b):
# nonlocal x
return b + x
return fun2
test_fun = fun1(4)
print(test_fun(7))
#################################################################################
def readMass(path):
file = open(path)
N = 0
mass = []
for line in file:
row = line.strip().split(' ')
mass.append(row)
N += 1
file.close()
return mass, N
def printMass(mass):
for i in range(len(mass)):
for j in range(len(mass[i])):
print('%4s'%mass[i][j], end='')
print()
mass, N = readMass('file_2.txt')
printMass(mass)
def change (mass):
for i in range(len(mass)):
for j in range(len(mass[i])):
if i == j:
mass[i][j], mass[i][len(mass)-1-j] = mass[i][len(mass)-1-j], mass[i][j]
return mass
res = change(mass)
print()
printMass(res)
#################################################################################################
name = 0
surname = 1
cclass = 2
DOB = 3
day = 0
month = 1
year = 2
users = []
def readDB(path):
users = []
for line in open(path):
tUser = []
for i in line.split(' '):
tUser.append(i.split('=')[1])
users.append(tUser)
return users
def printDB(dbName):
for users in dbName:
print('name=%-12s surname=%-12s class=%-5s birthday=%-10s' % (users[name], users[surname], users[cclass], users[DOB]), end = '')
def older(arg1, arg2):
if (int(arg1[2]) < int(arg2[2])):
return True
elif (int(arg1[2]) == int(arg2[2]) and int(arg1[1]) < int(arg2[1])):
return True
elif (int(arg1[2]) == int(arg2[2]) and int(arg1[1]) == int(arg2[1]) and int(arg1[0]) < int(arg2[0])):
return True
return False
def getIOlder(dbName):
iOlderUser = 0
for i in range(1, len(dbName)):
date = dbName[i][DOB].split('.')
dateOlder = dbName[iOlderUser][DOB].split('.')
if older (date, dateOlder):
iOlderUser = i
return iOlderUser
def younger(arg1, arg2):
if (int(arg1[2]) > int(arg2[2])):
return True
elif (int(arg1[2]) == int(arg2[2]) and int(arg1[1]) > int(arg2[1])):
return True
elif (int(arg1[2]) == int(arg2[2]) and int(arg1[1]) == int(arg2[1]) and int(arg1[0]) > int(arg2[0])):
return True
return False
def getIYounger(dbName):
iYoungerUser = 0
for i in range(1, len(dbName)):
date = dbName[i][DOB].split('.')
dateOlder = dbName[iYoungerUser][DOB].split('.')
if older (date, dateOlder):
iOlderUser = i
return iYoungerUser
file = readDB('input.txt')
printDB(file)
print()
print('Самый старший:')
print(file[getIOlder(file)])
print()
print('Самый младший:')
print(file[getIYounger(file)])
#################################################################################
def test():
pass
if __name__ == "__main__":
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
#################################################################################
| true |
6b6859595ed93abec7bf4e3142bff5b411becebe | Python | hse-labs/PY111-template | /Tasks/c2_recursive_binary_search.py | UTF-8 | 401 | 4.21875 | 4 | [] | no_license | from typing import Sequence, Optional
def binary_search(elem: int, arr: Sequence) -> Optional[int]:
"""
Performs binary search of given element inside of array (using recursive way)
:param elem: element to be found
:param arr: array where element is to be found
:return: Index of element if it's presented in the arr, None otherwise
"""
print(elem, arr)
return None
| true |
a3f7934509af756e3795dc74e48ad548c3353a79 | Python | ohandyya/ml-app | /others/first_app.py | UTF-8 | 4,852 | 3.421875 | 3 | [] | no_license | import streamlit as st
import base64
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import datetime
import numpy as np
import pandas as pd
import time
import logging
logger = logging.getLogger(__name__)
VALID_PASSWORD = ["password"]
password = st.sidebar.text_input("Enter a password", value="", type="password")
def my_long_func():
time.sleep(5)
return 10
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
csv = df.to_csv(index=False)
# some strings <-> bytes conversions necessary here
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}">Download csv file</a>'
return href
@st.cache(suppress_st_warning=True) # 👈 Changed this
def expensive_computation(a, b):
# 👇 Added this
st.write("Cache miss: expensive_computation(", a, ",", b, ") ran")
time.sleep(2) # This makes the function take 2s to run
return a * b
def main():
st.title('My first app')
st.header("This is a header")
st.subheader("this is a subheader")
st.text("this is my test")
code = '''
def myf(variable):
return variable
'''
st.code(code, language="python")
st.header("This section is about data frame")
st.write("Here's our first attempt at using data to create a table:")
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}, index=['a', 'b', 'c', 'd'])
df.index.name = "my shortcut"
st.write(df)
st.dataframe(df)
st.table(df)
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
map_data = pd.DataFrame(
0.1 * np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.dataframe(map_data)
st.map(map_data)
if st.checkbox('Show dataframe'):
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
option = st.selectbox("What sports doe you link?", [
'Basketball', "Baseball"])
st.write("You like ", option)
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.sidebar.line_chart(chart_data)
left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
if pressed:
right_column.write("Woohoo!")
expander = st.beta_expander("FAQ")
expander.write(
"Here you could put in some really, really long explanations...")
st.write('Starting a long computation...')
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.001)
st.write('...and now we\'re done!')
if st.button("Run my function"):
st.write("Running.....")
val = my_long_func()
st.write("Value = ", val)
genre = st.radio("What's your favorite movie genre",
('Comedy', 'Drama', 'Documentary'))
if genre == "Comedy":
st.write("You select Comedy")
else:
st.write("You did not like Comedy???")
options = st.multiselect('What are your favorite colors', [
'Green', 'Yellow', 'Red', 'Blue'])
st.write("You select: ", options)
age = st.slider('How old are you?', 0, 130, 25)
st.write("I'm ", age, 'years old')
title = st.text_input('Movie title', 'Life of Brian')
st.write('The current movie title is', title)
txt = st.text_area('Text to analyze')
st.write(txt)
bd = st.date_input("When is your birthday?")
st.write("Your birthday is :", bd)
t = st.time_input('Set an alarm for', datetime.time(8, 42))
st.write('Alarm is set for', t)
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file:
dataframe = pd.read_csv(uploaded_file)
st.write(dataframe)
color = st.color_picker('Pick A Color', '#00f900')
st.write('The current color is', color)
st.markdown(get_table_download_link(df), unsafe_allow_html=True)
num1 = st.number_input("Insert number 1", value=0.0)
num2 = st.number_input("Insert number 2", value=0.0)
res = expensive_computation(num1, num2)
st.write(f"{num1} x {num2} equals ", res)
if __name__ == "__main__":
if password in VALID_PASSWORD:
logger.info("User put correct password")
main()
else:
st.title("Wrong password entered")
logger.info("User put wrong password")
# st.stop()
| true |
4fe5d5a067919d1faef41020ad4b6bbd63f1f0fd | Python | shoriwe-upb/PreInformeFunciones | /a-potencia-b.py | UTF-8 | 524 | 4.125 | 4 | [
"MIT"
] | permissive | def pow(a, b):
result = 1
for i in range(b):
result *= a
return result
def main():
results = []
for i in range(2):
a = int(input(f"numero a{i + 1}: "))
b = int(input(f"numero b{i + 1}: "))
results.append(pow(a, b))
if results[0] > results[1]:
print(f"{results[0]} > {results[1]}")
elif results[0] < results[1]:
print(f"{results[0]} < {results[1]}")
else:
print(f"{results[0]} == {results[1]}")
if __name__ == "__main__":
main()
| true |
dec27506e9777c8109608d0d11d46a5f24a91d35 | Python | Aasthaengg/IBMdataset | /Python_codes/p02842/s109159848.py | UTF-8 | 160 | 3.03125 | 3 | [] | no_license | import math
N=int(input())
if (N/1.08).is_integer()==True:
S=int(N/1.08)
else:
S=math.ceil(N/1.08)
if (S*1.08)//1==N:
print(S)
else:
print(':(') | true |
c82e785aa1ed2684a9298576f5d6196800736d5e | Python | narendraaa/Python_learning | /memory.py | UTF-8 | 170 | 2.765625 | 3 | [] | no_license | a= [1,2,[4,5],3]
b= a
print('b:',b ,end =' ')
print('a:',a)
print('after chcGING VALUES')
a[2][0]=23
a[2][1]='naren'
print('b:',b ,end =' ')
print('a:',a)
| true |
ad5ec9d9004b2f2ea5a6e221bf6864805277efb7 | Python | Hypha5/twitter_bot | /search.py | UTF-8 | 591 | 2.765625 | 3 | [] | no_license | import tweepy
import time
consumer_key = 'QWsvG3JxGUQRtSHWmUXc2jMpY'
consumer_secret = 'HEgF2toVbkS8gduVI26Y98VMN1TiwPxx0Jx2ZI3zAp5apsUq9w'
key = '767967551305297920-NBKUDZAKMZoNXD8qTd2biG5LeWoL5pI'
secret = 'csQ4J8heCG37EzOL5hW1yW8GrkMXHPp9pkdc5mygsvikz'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
api = tweepy.API(auth)
hashtag = "100daysofcode"
tweetnumber = 3
tweets = tweepy.Cursor(api.search, hashtag).items(tweetnumber)
def search():
for tweet in tweets:
try:
tweet.retweet()
print("Retwet done")
time.sleep(5)
except tweepy.TweepError as e:
print(e.reason)
search()
| true |
d64256e63cbebc41e33dd54580fe422b2a49e86c | Python | CurtisThompson/spotify-history | /src/statistics.py | UTF-8 | 8,287 | 2.796875 | 3 | [] | no_license | import os
import numpy as np
import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
def read_data(path='../data/ExampleData/', year=2021):
"""Import JSON streaming data."""
data_dfs = []
# Get list of streaming history files
directory_files = os.listdir(path)
directory_files = [x for x in directory_files if x[:16] == 'StreamingHistory' and x[-5:] == '.json']
for file in directory_files:
# Read in the JSON data
data = pd.read_json(path + file)
# Filter by year
if year != None:
data = data[(data.endTime >= str(year)+'-01-01')
& (data.endTime <= str(year)+'-12-31')]
# Add to list
data_dfs.append(data)
return pd.concat(data_dfs)
def get_all_songs(data):
"""Get a DataFrame of songs in the data."""
all_songs = data.groupby(['artistName', 'trackName'])
return all_songs.msPlayed.sum().reset_index()
def get_dev_keys(path='../data/api_keys/api_dev_keys.txt'):
"""Gets the Spotify development keys from file."""
with open(path, 'r') as f:
keys = f.read().split('\n')
return keys[0], keys[1]
#SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET = get_dev_keys()
#client_credentials_manager = SpotifyClientCredentials(client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET)
#sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
def get_song_artists_through_api(artist, track, sp):
"""Get all song artist details for a song using the Spotify API."""
search_query = artist + ' ' + track
song_details = sp.search(search_query, limit=1)
song_artists = song_details['tracks']['items'][0]['artists']
return song_artists
def get_songs_artists_frame(songs_df, sp):
"""Gets all possible artists for all possible songs in a DataFrame."""
all_songs_with_artists = []
for index, row in songs_df.iterrows():
try:
# Get song artists
song_artists = get_song_artists_through_api(row.artistName,
row.trackName,
sp=sp)
# Store artists for song
uris = [artist['uri'] for artist in song_artists]
for uri in uris:
all_songs_with_artists.append([row.artistName,
row.trackName,
uri])
except:
if ' - ' in row.trackName:
try:
# Get song artists
new_track_name = ' - '.join(row.trackName.split(' - ')[:-1])
song_artists = get_song_artists_through_api(row.artistName,
new_track_name,
sp=sp)
# Store artists for song
uris = [artist['uri'] for artist in song_artists]
for uri in uris:
all_songs_with_artists.append([row.artistName,
row.trackName,
uri])
except:
print(index, row.artistName, row.trackName)
else:
print(index, row.artistName, row.trackName)
# Convert results to dataframe
all_songs_with_artists = pd.DataFrame(all_songs_with_artists,
columns=['artistName',
'trackName',
'artistURI'])
# Get a list of URIs
artist_uris = list(all_songs_with_artists.artistURI.unique())
return all_songs_with_artists, artist_uris
def get_artists_from_uris(artist_uris, sp):
"""Convert a list of artist URIs to data dicts with the Spotify API."""
artist_search = {}
for i in range(0, len(artist_uris), 50):
search_results = sp.artists(artist_uris[i:i + 50])
for result in search_results['artists']:
artist_search[result['uri']] = result
return artist_search
def check_uri_for_song(song_artists, uri, trackName, artistName):
"""Does an artist URI feature in a given song."""
song_filter = (song_artists.artistName==artistName) & (song_artists.trackName==trackName)
return uri in song_artists[song_filter].artistURI.unique()
def get_artists_by_play_time(data, artist_search, all_songs_with_artists):
"""Count play time for each artist."""
# Get play time for each artist
df_artists = data[['trackName', 'artistName', 'msPlayed']]
artist_play_times = []
for uri in list(artist_search.keys()):
artist_play_time = df_artists[df_artists.apply(lambda x: check_uri_for_song(all_songs_with_artists, uri, x.trackName, x.artistName), axis=1)].msPlayed.sum()
artist_play_times.append((uri, artist_play_time))
# Get artist names and time
top_artists = pd.DataFrame(artist_play_times, columns=['URI', 'Ms'])
top_artists['Name'] = top_artists.URI.apply(lambda x: artist_search[x]['name'])
top_artists['Minutes'] = top_artists.Ms / 60000
return top_artists
def get_genres_by_play_time(data, artist_search, all_songs_with_artists):
"""Count play time for each genre."""
# Get a list of genres
genres = []
for artist in artist_search:
genres.extend(artist_search[artist]['genres'])
genres = list(set(genres))
# Set up genre time dict
genre_times = {}
for genre in genres:
genre_times[genre] = 0
# Get genre for each song
for index, row in data.iterrows():
# Get main artist
song_data = all_songs_with_artists[(all_songs_with_artists.trackName==row.trackName) & (all_songs_with_artists.artistName==row.artistName)]
song_data = song_data.copy().reset_index()
try:
main_artist = song_data.iloc[0].artistURI
except:
main_artist = None
# Add genres of main artist to counter
if main_artist != None:
artist_genres = artist_search[main_artist]['genres']
for genre in artist_genres:
genre_times[genre] += row.msPlayed
# Return as DataFrame
df_genre = pd.DataFrame(list(genre_times.items()), columns=['Genre', 'Ms'])
df_genre['Minutes'] = df_genre.Ms / 60000
return df_genre
def get_songs_by_listens(data):
"""Returns a count for each song, ordered by most listens."""
song_counts = data.groupby(['artistName', 'trackName']).size().to_frame()
song_counts = song_counts.reset_index().rename({0 : 'count'}, axis=1)
return song_counts.sort_values(by='count', ascending=False)
def get_total_song_count(data):
"""Returns the total number of songs listened to."""
return data.shape[0]
def get_unique_song_count(data):
"""Returns the unique number of songs listened to."""
return len(list(data.groupby(['artistName', 'trackName']).groups.keys()))
def get_play_time_string(data):
"""Returns a string explaining total listening time on Spotify."""
total_ms = data.msPlayed.sum()
total_s = total_ms // 1000
total_ms -= total_s * 1000
total_m = total_s // 60
total_s -= total_m * 60
total_h = total_m // 60
total_m -= total_h * 60
total_d = total_h // 24
total_h -= total_d * 24
time_string = ''
if total_d > 0:
time_string += str(total_d) + ' Days, '
if total_h > 0:
time_string += str(total_h) + ' Hours, '
if total_m > 0:
time_string += str(total_m) + ' Minutes, '
if total_s > 0:
time_string += str(total_s) + ' Seconds, '
time_string = time_string[:-2]
return time_string
def get_days_by_play_time(data):
"""Gets the listening time for each day, and returns in a DataFrame."""
data_days = data.copy()
data_days['day'] = data_days.endTime.apply(lambda x: x[:10])
data_days = data_days.groupby('day').msPlayed.sum().to_frame()
return data_days.reset_index().sort_values('msPlayed', ascending=False) | true |
368a284af4a989846288b5edb18ea6744d83b9ad | Python | ModifiedClass/hisx | /note-django rest framework/07drf解析器.py | UTF-8 | 1,201 | 2.984375 | 3 | [] | no_license | #django rest fromework解析器
#1请求头要求
Content-Type:application/x-www-form-urlencoded,
request.POST中才有值(去request.body中解析数据)
#2数据格式要求:
para1=value1¶2=value2
$.ajax({
data:{para1:value1,para2,value2}
})
#内部转化para1=value1¶2=value2
$.ajax({
data:JSON.stringfy({para1:value1,para2,value2})
})
#json.loads(request.body)
#rest_framework解析器,对请求体进行解析
from rest_framework.parsers import JSONParser,FormParser
class ExampleView(APIView):
paraser_classes=[JSONParser,FormParser]
'''
JSONParser:只能解析Content-Type:application/json头
FormParser:只能解析Content-Type:application/x-www-form-urlencoded头
'''
def post(self,request,*args,**kwargs):
'''允许发json格式数据
a.content-type:application/json
b.{'para1':'value1','para2','value2'}
'''
'''
1.获取用户请求
2.获取用户请求体
3.根据用户请求头和paraser_classes=[JSONParser,FormParser]中支持的请求头进行比较
4.JSONParser对象去请求体
5.request.data
'''
#解析后的结果
request.data | true |
2e2e96fb68f700289b8fb5a32c090292fdcdf2fe | Python | sumit2303/sustcitymgmt | /data_collector/data_collector.py | UTF-8 | 1,720 | 2.671875 | 3 | [] | no_license | import db
import data_fetching as df
import data_processor as dp
import time
import datetime
def create_tables(db_file, tables_data):
for table in tables:
print(table, tables_data[table])
db.create_db_tables(db_file, table, tables_data[table])
bike_data = db.get_bike_data()
pollution_data = db.get_pollution_data()
event_data = db.get_event_data()
traffic_data = db.get_traffic_data()
database_file = "../citymgmt/mobility_db"
tables = ['bike_availability', 'pollution_level', 'traffic_info','event_info']
tables_data = {tables[0]:bike_data, tables[1]:pollution_data, tables[2]:traffic_data, tables[3]:event_data}
#create_tables(database_file, tables_data)
bike_db_file = '../citymgmt/rt_bike_db'
lat = db.read_column_from_db(bike_db_file,'lat','bike_availability')
lon = db.read_column_from_db(bike_db_file,'lng','bike_availability')
bid = db.read_column_from_db(bike_db_file, 'number', 'bike_availability')
coord = (bid, lat, lon)
latlonid = dp.clean_lat_lon_id(coord)
start_time = time.time()
max_date = datetime.datetime.utcfromtimestamp(start_time).date()
lat = str(53.344352)
lon = str(-6.258456)
key_itr = 0
while True:
current_time = time.time()
current_date = datetime.datetime.utcfromtimestamp(current_time).date()
df.fetch_bike_api_data(database_file, tables[0])
df.fetch_pollution_api_data(database_file, tables[1], latlonid[0], latlonid[1], latlonid[2], key_itr)
key_itr += 1
df.fetch_traffic_api_data(database_file, tables[2], latlonid[0], lat, lon, latlonid[1], latlonid[2])
if current_date == max_date:
max_date = current_date
df.fetch_events_api_data(database_file, tables[3], lat, lon)
print('Completed', key_itr)
time.sleep(60) | true |
6d2a34fdc989ca0d60530945dd9a0d8153646be4 | Python | TamuYokomori/hangman | /challenge10.py | UTF-8 | 162 | 3.46875 | 3 | [] | no_license | # find words having 'oo' after some characters.
import re
docs = "The ghost that says boo haunts the loo."
m = re.findall(".oo", docs, re.IGNORECASE)
print(m)
| true |
7bc40c4c2b3e5becaed25ffd7d88133a197a6dbb | Python | 2575614015/python_test | /ihome/ihome06/ihome/web_html.py | UTF-8 | 2,319 | 3 | 3 | [] | no_license | # -*- coding:utf-8 -*-
# 此文件,专门处理静态文件的访问. 不做模板的渲染, 只是转发文件路径
from flask import Blueprint, current_app, make_response
from flask_wtf.csrf import generate_csrf
html = Blueprint('html', __name__)
# (.*)
# 我们只需要1个路由来搞定静态文件的访问
@html.route('/<re(r".*"):file_name>')
def web_html(file_name):
'''
127.0.0.1:5000/ index.html
127.0.0.1:5000/login.html login.html
/favicon.ico 固定访问的名字, 我们还需要处理浏览器发出的访问网站小图标的请求
'''
# 1. 处理没有文件名, 自行拼接首页
if not file_name:
file_name = 'index.html'
# 2. 如果发现文件名不叫"favicon.ico", 再拼接html/路径
# favicon.ico: 浏览器为了显示图标, 会自动向地址发出一个请求
# favicon.ico: 会有缓存,打开浏览器第一次访问该网址时会发出请求.然后缓存起来
if file_name != 'favicon.ico':
file_name = 'html/' + file_name
# 将html当做静态文件返回
# 3. 如果文件名是'favicon.ico', 就直接返回
print file_name
# 创建response
response = make_response(current_app.send_static_file(file_name))
# 这里还需要设置csrf_token
csrf_token = generate_csrf()
# 设置cookie
response.set_cookie('csrf_token', csrf_token)
# Flask-WTF的generate_csrf, 会将cookie中的csrf_token信息, 会同步到session中
# Flask-Session又会讲session中的csrf_token, 同步到redis中
# generate_csrf不会每次调用都生成. 会先判断浏览器的cookie中的session里是否有csrf_token信息.没有才重新生成
# 常规的CSRF保护机制, 是从浏览器的cookie中获取. 而Flask-WTF的扩展机制不一样, 是从session信息中获取csrf_token保护机制
return response
# @html.route('/')
# def web_html():
# # 发送静态资源, 而不是渲染模板
#
# # send_static_file: 会自动指向static文件
# return current_app.send_static_file('html/index.html')
#
#
# @html.route('/<file_name>')
# def web_html_demo(file_name):
# # 发送静态资源, 而不是渲染模板
#
# # send_static_file: 会自动指向static文件
# return current_app.send_static_file('html/' + file_name) | true |
0fec0913690a753efbc2bba05583b038afbe6ec9 | Python | haakensonb/advent_of_code_2018 | /day_2/day_2_part_2.py | UTF-8 | 1,456 | 4.125 | 4 | [] | no_license | """
Advent of Code Day 2
Part 2:
Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.
The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs:
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij
differ by exactly one character, the third (h and u). Those must be the correct boxes.
What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing
character from either ID, producing fgij.)
"""
data = [line.strip() for line in open("input.txt")]
# test data
# data = ['abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz']
def find_common():
for i in range(len(data)):
for j in range(i+1, len(data)):
answer = check_diff(data[i], data[j])
if answer != '':
return answer
def check_diff(str1, str2):
off_count = 0
common_letters = ''
for x in range(len(str1)):
if off_count > 1:
return ''
elif str1[x] == str2[x]:
common_letters += str1[x]
else:
off_count += 1
return common_letters
# print(check_diff('fghij', 'fguij'))
print(find_common()) | true |
d173b5cb3d3d2b3be8f9ac7abf7561a9f2b1eec2 | Python | ichbinhandsome/sword-to-offer | /查找/旋转数组中的查找.py | UTF-8 | 1,440 | 4.03125 | 4 | [] | no_license | '''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return -1
i, j = 0, len(nums)-1
#中间元素将数组分为左右两部分,无论数组怎么旋转,左右两部分必有一方是有序的
# 当 nums[mid] > nums[right] 时, 左侧元素是有序的
# 当nums[mid] < nums[right] 时, 右侧元素是有序的
while i <= j :
mid = (i+j)//2
if nums[mid] == target:
return mid
if nums[mid] < nums[j]: # 右侧有序
if nums[mid] < target <= nums[j]:
i = mid + 1
else:
j = mid -1
else: # 左侧有序
if nums[i]<= target < nums[mid]:
j = mid - 1
else:
i = mid + 1
return -1 | true |
67c7ad9c73e922dce0dffa272cb420c92116d5a3 | Python | reeddunkle/MSP7 | /parse_DAT.py | UTF-8 | 1,060 | 2.84375 | 3 | [] | no_license | import struct
class ParseMPS7(object):
def __init__(self, file_path):
with open(file_path, 'rb') as f:
self.file = f.read()
@property
def header(self):
magic_string = self.file[:4]
return {
"magic_string": magic_string,
"version": self.version,
"num_records": self.num_records
}
@property
def version(self):
return self.file[4]
@property
def num_records(self):
return struct.unpack(">I", self.file[5:9])[0]
def records(self):
# Returns dict of records by ID
pass
def total_debit(self):
# Return total amount in dollars of debits
pass
def total_credit(self):
# Return total amount in dollars of credits
pass
def autopay_started(self):
# Returns number of autopays started
pass
def autopay_ended(self):
# Returns number of autopays ended
pass
def balance(self, id):
# Returns balance of user ID
pass
| true |
5db524ef2bebfeaefee81be0f190060e6290252d | Python | mx1001/animation_nodes | /nodes/interpolation/evaluate.py | UTF-8 | 619 | 2.515625 | 3 | [] | no_license | import bpy
from ... base_types.node import AnimationNode
class EvaluateInterpolationNode(bpy.types.Node, AnimationNode):
bl_idname = "an_EvaluateInterpolationNode"
bl_label = "Evaluate Interpolation"
def create(self):
self.width = 150
self.inputs.new("an_FloatSocket", "Position", "position").setRange(0, 1)
self.inputs.new("an_InterpolationSocket", "Interpolation", "interpolation").defaultDrawType = "PROPERTY_ONLY"
self.outputs.new("an_FloatSocket", "Value", "value")
def getExecutionCode(self):
return "value = interpolation(max(min(position, 1.0), 0.0))"
| true |
54c83f6465e5668aa0584fd1e8b28d59b919a23c | Python | Alsant205/StartOfPython | /Lesson_2/Lesson_2_Task_1.py | UTF-8 | 941 | 3.5 | 4 | [] | no_license | """Создать список и заполнить его элементами различных типов данных.
Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
Элементы списка можно не запрашивать у пользователя, а указать явно, в программе."""
# Список типов из методички
data_types = [
4, 4.4, 5+6j, 'some string', ['l', 'i', 's', 't'],
('t', 'u', 'p', 'l', 'e'), {'s', 'e', 't'},
{'1': 'd', '2': 'i', '3': 'c', '4': 't'},
True, b'text', None
]
print(f' № | ВЫРАЖЕНИЕ{" " * 35} | ТИП ПЕРЕМЕННОЙ\n {"-" * 70}')
for num, types in enumerate(data_types, 1):
print(f' {num:02.0f}.| "{types}" {" " * (41 - len(str(types)))} | {type(types)}\n {"-" * 70}')
| true |
d0a2865cb37358a54fa712d2dff27fee03203e68 | Python | aiedward/CCIR | /code/SVM/feature2.py | UTF-8 | 3,512 | 2.765625 | 3 | [] | no_license | # -*-coding: utf-8 -*-
from get_words_for_CCIR import *
import numpy as np
import gensim
import sys
import os
from feature import *
reload(sys)
sys.setdefaultencoding("utf-8")
def get_feature_vector(word, model):
try:
vector = model[word]
except KeyError:
vector = np.array([0 for k in range(128)])
return vector
def get_feature_word_vector(start, end, q, item, word):
question_matrix = []
answer_matrix = []
gensim_model = "wiki.zh.text.model"
model = gensim.models.Word2Vec.load(gensim_model)
# 在这里读入数据,如果word2vec查找不到或者出现的是高频的词的话,就跳过
for i in range(start, end, 1):
question_matrix.append([])
for j in range(len(q[i])):
temp = get_feature_vector(q[i][j], model)
if q[i][j] in word:
continue
if np.all(temp == 0):
continue
question_matrix[i - start].append(temp)
for i in range(start, end, 1):
answer_matrix.append([])
for j in range(len(item[i])):
answer_matrix[i - start].append([])
for k in range(len(item[i][j])):
temp = get_feature_vector(item[i][j][k], model)
if item[i][j][k] in word:
continue
if np.all(temp == 0):
continue
answer_matrix[i - start][j].append(temp)
return question_matrix, answer_matrix
def get_feature_data(start, end, q, item, word):
train_file_dir = './'
train_file_name = 'CCIR_train_3_word_num.txt'
word2 = frequency_statistical(train_file_dir, train_file_name)
question, answer = get_feature_word_vector(start, end, q, item, word)
question_data = []
answer_data = []
for i in range(len(question)):
for j in range(len(answer[i])):
question_data.append(question[i])
for i in range(len(answer)):
for j in range(len(answer[i])):
answer_data.append(answer[i][j])
# 在这里的形式是,[ [], [], []],其中的都是问题或者答案的经过word2vec的矩阵
feature = similarity_feature(question_data, answer_data)
# feature是用来衡量问题与答案之间相似度的特征,有16个特征
# feature2 = metadata_feature(question, answer)
# feature2有4个特征
feature3 = frequency_feature(start, end, q, item, word2)
# feature3有4个特征
feature4 = same_word_feature(question_data, answer_data)
# feature4有4个特征
del answer_data, question_data
del answer, question
# 在这里将其进行问题和答案的拼接,形成最后的q-a对的词频特征向量
for i in range(len(feature)):
#for j in range(len(feature2[i])):
# feature[i].append(feature2[i][j])
for n in range(len(feature3[i])):
feature[i].append(feature3[i][n])
for mm in range(len(feature4[i])):
feature[i].append(feature4[i][mm])
for i in range(len(feature)):
for j in range(len(feature[i])):
if np.isnan(feature[i][j]):
feature[i][j] = 0
max_item = max(feature[i])
min_item = min(feature[i])
if max_item == min_item:
continue
for k in range(len(feature[i])):
feature[i][k] = (feature[i][k] - min_item) / (max_item - min_item)
#feature = np.array(feature)
#feature = feature.reshape((len(feature), len(feature[0]), 1))
return feature | true |
33cd71e9f25c27c8a32d3bebec636df77f307d24 | Python | pawelpiatekProjects/pythonWebscraping | /models/Flat.py | UTF-8 | 676 | 3.09375 | 3 | [] | no_license | class Flat:
def __init__(self, title, location, website, buildingType, rooms, price, area, description, link):
self.title = title
self.location = location
self.website = website
self.buildingType = buildingType
self.rooms = rooms
self.price = price
self.area = area
self.description = description
self.link = link
def print_values(self):
print(self.title + '; ' + self.location + '; ' + self.website + '; ' + self.buildingType + '; ' + self.rooms + '; ' + self.price + '; ' + self.area + '; ' + self.description + '; ' + self.link)
def get_link(self):
return f'{self.link}'
| true |
28ff0d6496615199ca25ed56cbd8b64455130645 | Python | RoccoFortuna/advent_of_code_2020 | /d4_passport_processing/problem4.py | UTF-8 | 6,681 | 3.359375 | 3 | [] | no_license | from typing import List, Dict
def parse_input_file() -> List[Dict[str, str]]:
input_path = "./d4_passport_processing/input.txt"
with open(input_path, "r") as file:
passports_str = file.read().strip().split("\n\n")
passports = []
for passport_str in passports_str:
passport_str = passport_str.replace('\n', ' ') # remove newlines and replace with space for split
new_passport = {field.split(':')[0]:field.split(':')[1] for field in passport_str.split()}
passports.append(new_passport)
return passports
def validate_passports1(passports: List[Dict[str, str]]) -> int:
"""Count number of valid passports
Valid passports have all required fields:
'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'.
'cid' is optional.
Args:
passports (List[Dict[str: str]]): contains dict where key is
a passport field and value its str value.
Returns:
int: number of valid passports
"""
valid_passports_count = 0
for passport in passports:
if is_valid_passport1(passport):
valid_passports_count += 1
return valid_passports_count
def is_valid_passport1(passport: Dict[str, str]) -> bool:
"""Check if given passport is valid
Valid passports have all required fields:
'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'.
'cid' is optional.
Args:
passports (Dict[str: str]): key is a passport field
and value its str value.
Returns:
bool: if given passport is valid
"""
required_fields = {'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'}
for f in required_fields:
if passport.get(f, None) is None:
return False
return True
def validate_passports2(passports: List[Dict[str, str]]) -> int:
"""Count number of valid passports
Valid passports have all required fields:
'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'.
'cid' is optional.
Moreover,
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
Args:
passports (List[Dict[str: str]]): contains dict where key is
a passport field and value its str value.
Returns:
int: number of valid passports
"""
valid_passports_count = 0
for passport in passports:
if is_valid_passport2(passport):
valid_passports_count += 1
return valid_passports_count
def is_valid_passport2(passport: Dict[str, str]) -> bool:
"""Check if given passport is valid
Valid passports have all required fields:
'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'.
'cid' is optional.
Moreover,
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
Args:
passports (Dict[str: str]): key is a passport field
and value its str value.
Returns:
bool: if given passport is valid
"""
required_fields = ['ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt']
for field in required_fields:
value = passport.get(field, None)
if value is None or not is_valid_field(field, value):
return False
return True
def is_valid_field(field: str, value: str) -> bool:
"""Checks whether a value is valid for a given field
Simple case distinction. Rather long, given the number
of cases and specific way to handle each.
Args:
field (str): given field to check validity of value against
value (str): value associated to given field
Returns:
bool: whether value is valid for given field
"""
if field == 'byr': # (Birth Year) - four digits; at least 1920 and at most 2002.
return len(value) == 4 and int(value) >= 1920 and int(value) <= 2002
elif field == 'iyr': # (Issue Year) - four digits; at least 2010 and at most 2020.
return len(value) == 4 and int(value) >= 2010 and int(value) <= 2020
elif field == 'eyr': # (Expiration Year) - four digits; at least 2020 and at most 2030.
return len(value) == 4 and int(value) >= 2020 and int(value) <= 2030
elif field == 'hgt': # (Height) - a number followed by either cm or in:
value, unit = value[:-2], value[-2:]
if unit == 'cm': #If cm, the number must be at least 150 and at most 193.
return int(value) >= 150 and int(value) <= 193
if unit == 'in': # If in, the number must be at least 59 and at most 76.
return int(value) >= 59 and int(value) <= 76
else:
return False
elif field == 'hcl': # hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
return value[0] == '#' and len(value[1:]) == 6 and (value[1:].isnumeric() or (value[1:].islower() and value[1:].isalnum()))
elif field == 'ecl': # ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
return value in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
elif field == 'pid': # pid (Passport ID) - a nine-digit number, including leading zeroes.
return len(value) == 9 and value.isnumeric()
elif field == 'cid': # cid (Country ID) - ignored, missing or not.
return True
else:
print(f"Unknown field: {field}\twith value: {value}")
if __name__ == "__main__":
passports = parse_input_file()
ans1 = validate_passports1(passports)
print(ans1)
ans2 = validate_passports2(passports)
print(ans2) | true |
4cfa1416572cbb555eadf0bb27b2fdcb0d2a2050 | Python | KJThoma/arista-automation | /arista-version.py | UTF-8 | 763 | 2.515625 | 3 | [
"MIT"
] | permissive | from netmiko import ConnectHandler
# our devices info to connect and session log files to save output
arista_1 = {
'device_type': 'arista_eos',
'ip': 'your_ip',
'username': 'your_username',
'password': 'your_password',
'session_log': 'sw1.txt'
}
arista_2 = {
'device_type': 'arista_eos',
'ip': 'your_ip',
'username': 'your_username',
'password': 'your_password',
'session_log': 'sw2.txt'
}
# command to run on switches
command = "show version"
# for loop to connect to devices, run on both switches, and print output
for device in (arista_1, arista_2):
net_connect = ConnectHandler(**device)
output = net_connect.send_command(command)
print()
print('#' * 70)
print(output)
print('#' * 70)
print()
| true |
97eac8e89d7cdfcf9e06c820621eb8102252ccac | Python | Sona1414/luminarpython | /collections/LIST/DEMO.py | UTF-8 | 536 | 3.828125 | 4 | [] | no_license | #list
lst=[]
#first method using square bracket
print(type(lst))
#2nd method usint list function
sa=list()
print(type(lst))
#supports hetrogenous data
lst=[1,10.6,"sona",True,False]
print(lst)
#whether inseryion order is preserved
lst=[10,15,6,7,3,3,2,1,1,"sona","neena"]
print(lst)
#duplicate value supported or not
lst=[10,10,10,"sona","sona"]
print(lst)
#to access each element we can use index values.. which starts from 0 to n-1
print(lst[0])
print(lst[3])
#to change an element in the list#is mutable
lst[2]=100
print(lst)
| true |
3c4b80ff80add96f029d8b8dc870e4308fe9e04d | Python | albigel/RK_ode_ivp | /RK.py | UTF-8 | 3,992 | 2.796875 | 3 | [] | no_license | from numpy.linalg import norm as np_norm
import numpy as np
def c_(x):
return np.array(x)
norm_1 = lambda x: np.sum(abs(x))
RK_METHODS = {
'FE': [c_([[0]]), c_([1]), c_([0]), False], #Explicit Euler
'BE': [c_([[1]]), c_([1]), c_([1]), True], #Implicit Euler
'IMP': [c_([[.5]]), c_([1]), c_([.5]), True], #Implicit Midpoint
'ETrapz': [c_([[0,0],[1,0]]), c_([.5,.5]), c_([0,1]), False], # Explicit Trapezoidal
'ITrapz': [c_([[0,0],[.5,.5]]), c_([.5,.5]), c_([0,1]), True], # Implicit Trapezoidal
'RK4': [c_([[0,0,0,0],[.5,0,0,0],[0,.5,0,0],[0,0,1,0]]), c_([1./6.,1./3.,1./3.,1./6.]), c_([0,.5,.5,1]),False], #Classical RK 4
'RK4(3)I': [c_([[.5,0,0,0],[1./6.,.5,0,0],[-.5,.5,.5,0],[1.5,-1.5,0.5,0.5]]), c_([1.5,-1.5,0.5,0.5]), c_([.5,2./3.,.5,1]), True], # Implicit stable RK 4 with 3 order of approx
'3/8': [c_([[0,0,0,0],[1./3.,0,0,0],[-1./3.,1,0,0],[1,-1,1,0]]), c_([.125, .475, .475, .125]), c_([0,1./3.,2./3.,1]) ,False], # Classical #/8 rule of R-K
'SSPRK3': [c_([[0,0,0],[1,0,0],[.25, .25, 0]]), c_([1./6., 1./6., 2./3.]), c_([0,1.,1./2.]), False] # Third-order Strong Stability Preserving Runge-Kutta
}
RK_NAMES = {
'FE': 'Explicit Euler',
'BE': 'Implicit Euler',
'IMP': 'Implicit Midpoint',
'ETrapz': 'Explicit Trapezoidal',
'ITrapz': 'Implicit Trapezoidal',
'RK4': 'Classical RK 4',
'RK4(3)I': 'Implicit stable RK 4 with 3 order of approximation',
'3/8': 'Classical #/8 rule of R-K',
'SSPRK3': 'Third-order Strong Stability Preserving Runge-Kutta'
}
def fixedp(f,x0,tol=10e-7, max_iter=100, log=True, nrm=norm_1):
"""
Fixed point algorithm
x0 and f(x0) must be scalars or numpy arrays-like
"""
err=0
x = 0
for itr in range(max_iter):
x = f(x0)
err = nrm(x-x0)
if err < tol:
return x
x0 = x
if log:
print("warning! didn't converge, err: ",err)
return x
def implicit_RK(f,a,b,c,x,N,s,h, y0, nrm=norm_1):
number_of_systems = y0.shape[0]
y = np.zeros((N,number_of_systems))
y[0] = y0
for n in range(0,N-1):
def k_eq(k):
_arr_2 = lambda i : y[n]+ h*np.sum([k[j]*a[i][j] for j in range(s)], axis=0)
return np.array([f(x[n]+c[i]*h, _arr_2(i)) for i in range(s)])
k = fixedp(k_eq, np.ones((s,number_of_systems)))
y[n+1] = y[n] + h*np.sum([b[i]*k[i] for i in range(s)], axis = 0)
return x,y
def explicit_RK(f,a,b,c,x,N,s,h, y0,):
number_of_systems = y0.shape[0]
y = np.zeros((N,number_of_systems))
y[0] = y0
k = np.zeros((s,number_of_systems))
for n in range(0,N-1):
y[n+1] = y[n]
for i in range(s):
k[i] = f(x[n]+c[i]*h, y[n]+h*np.sum([a[i][j]*k[j] for j in range(i)] , axis=0) )
y[n+1]+=h*b[i]*k[i]
return x,y
def RK(f, y0, t0, T, N=1000, h=None, method = 'RK4', butcher = None, implicit = None, nrm=norm_1):
N=N+1
if butcher is None:
a,b,c,implicit = RK_METHODS[method]
else:
if implicit is None:
implicit = True
a,b,c, = butcher
if h is None:
h = (T-t0)/N
t = np.linspace(t0,T,N)
else:
N = np.floor((T-t0)/h)
t = np.arange(t0,t,h)
s = a.shape[0]
if implicit:
return implicit_RK(f,a,b,c,t,N,s,h, y0, nrm=nrm)
else:
return explicit_RK(f,a,b,c,t,N,s,h, y0)
from functools import partial
class solver:
def __init__(self,name, method = None,butcher = None, implicit = None):
if butcher is None:
self.method = partial(RK, method = method)
else:
self.method = partial(RK, butcher = butcher, implicit = implicit)
self.name = name
def __call__(self, f, y0, t0, T, N=1000, h=None):
return self.method(f, y0, t0, T, N=1000, h=None)
| true |
5e32c952ef3e4197e2f0e83d2a3a923788814f15 | Python | umutku94/blog | /blog.py | UTF-8 | 11,180 | 2.65625 | 3 | [] | no_license | #------------------------MODULES--------------------------------------
from flask import abort,Flask, render_template, flash, redirect, url_for, request, session, logging
from flask_mysqldb import MySQL
from wtforms import Form,TextAreaField,StringField,PasswordField, validators
from passlib.hash import sha256_crypt
from functools import wraps
from time import sleep
#------------------------FORM CLASSES---------------------------------------
class RegisterForm(Form):
name = StringField("İsminiz :",validators=[validators.Length(min=3, max=15,
message="İsminiz 3-15 karakter uzunluğunda olmalıdır !")])
username = StringField("Kullanıcı Adınız :",
validators=[validators.Length(min=4, max=15,
message="Kullanıcı adınız 4-15 karakter uzunluğunda olmalıdır !"),
validators.DataRequired(message="Zorunlu alan")])
email = StringField("E-mail :",
validators=[validators.Email(message="Lütfen geçerli bir E-Mail giriniz !"),
validators.DataRequired(message="Zorunlu alan")])
password = PasswordField("Şifreniz :",
validators=[validators.Length(min=8,max=20,message="Şifreniz 8-20 karakter uzunluğunda olmalı !"),
validators.data_required(message="Şifre alanı boş bırakılamaz !"),
validators.EqualTo(fieldname="passconfirm",
message="Tekrar girilen şifre ile farklı bir şifre girdiniz !")])
passconfirm = PasswordField("Şifrenizi Tekrar Girin :")
class LoginForm(Form):
username = StringField("Kullanıcı Adı :")
password = PasswordField("Şifre :")
class AddArticle(Form):
title = StringField("Makale Başlığı :",
validators=[validators.Length(min=5,max=35,message="Başlık 3-35 karakter arası olmalıdır.")])
content = TextAreaField("Makale Konusu :",
validators=[validators.Length(min=10,message="Makale en az 10 karakter içermelidir.")],
render_kw={"rows":10})
#------------------------APP AND DB CONFIG---------------------------------------
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = ""
app.config["MYSQL_DB"] = "umut_blog"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
mysql = MySQL(app)
app.secret_key = "umut_blog"
#------------------------DECORATORS---------------------------------------
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "login" in session:
return f(*args, **kwargs)
else:
sleep(2)
flash("Öncelikle giriş yapmanız gerek !","danger")
return redirect(url_for("login"))
return decorated_function
def logout_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "login" in session:
return redirect("",304)
else:
return f(*args, **kwargs)
return decorated_function
#------------------------REQUESTS---------------------------------------
#Main
@app.route("/")
def index():
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles"
result = cur.execute(sorgu)
cur.close()
return render_template("index.html",switch="on",result=result)
#About
@app.route("/about")
def about():
cont=["Umut","Utku","Yasin","Çağatay"]
return render_template("about.html",cont = cont)
#View Articles
@app.route("/article/<string:id>")
def article(id):
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles WHERE id = %s"
result = cur.execute(sorgu,(id,))
if result > 0:
article = cur.fetchone()
cur.close()
return render_template("viewarticle.html",article = article,id = id)
else:
return render_template("viewarticle.html")
#Articles
@app.route("/articles")
def articles():
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles ORDER BY created_date DESC"
result = cur.execute(sorgu)
if result > 0:
articles = cur.fetchall()
cur.close()
return render_template("articles.html",articles = articles)
else:
cur.close()
return render_template("articles.html")
#Add Article
@app.route("/addarticle",methods=["GET","POST"])
@login_required
def addarticle():
form = AddArticle(request.form)
if request.method == "POST" and form.validate():
try:
title = form.title.data
content = form.content.data
cur = mysql.connection.cursor()
sorgu = "INSERT INTO articles(title,author,content) VALUES(%s,%s,%s)"
cur.execute(sorgu,(title,session["username"],content))
mysql.connection.commit()
cur.close()
flash("Makaleniz başarıyla eklenmiştir !","success")
except:
flash("Makale başlığı veya içeriği zaten eklenmiş !","danger")
return render_template("addarticle.html",form = form)
#Delete Article
@app.route("/delete/<string:id>",methods=["GET","POST"])
@login_required
def delete(id):
#Get Request
if request.method == "GET":
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles WHERE id = %s AND author = %s"
result = cur.execute(sorgu,(id,session["username"]))
#Create 'delete.html' template
if result > 0:
article = cur.fetchone()
cur.close()
return render_template("delete.html",article = article)
else:
cur.close()
return render_template("delete.html")
#Post Request
else:
cur = mysql.connection.cursor()
sorgu = "DELETE FROM articles WHERE id = %s and author = %s"
result = cur.execute(sorgu,(id,session["username"]))
mysql.connection.commit()
cur.close()
#Deleting Article
if result > 0:
flash("Makale başarıyla silindi.","success")
return redirect("/dashboard")
else:
flash("Bir hata oluştu","danger")
return redirect("/dashboard")
#Update Article
@app.route("/edit/<string:id>",methods=["GET","POST"])
@login_required
def update(id):
#Get Request
if request.method == "GET":
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles WHERE id = %s AND author = %s"
result = cur.execute(sorgu,(id,session["username"]))
#Create 'update.html' template
if result > 0:
article = cur.fetchone()
cur.close()
form = AddArticle()
form.title.data = article["title"]
form.content.data = article["content"]
return render_template("update.html",form = form)
else:
cur.close()
return render_template("update.html")
#Post Request
else:
form = AddArticle(request.form)
newTitle = form.title.data
newContent = form.content.data
try:
cur = mysql.connection.cursor()
sorgu = "REPLACE INTO articles(id,title,author,content) VALUES(%s,%s,%s,%s)"
cur.execute(sorgu,(id,newTitle,session["username"],newContent))
mysql.connection.commit()
cur.close()
except:
flash("Aynı başlık veya içerik zaten var.","danger")
return redirect("/edit/"+id)
flash("Makaleniz Güncellenmiştir","success")
return redirect("/dashboard")
#Search Article
@app.route("/search",methods=["GET","POST"])
def search():
#Get Request
if request.method == "GET":
return redirect("/articles")
#Post Request
else:
keyword = request.form.get("keyword")
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles WHERE title LIKE '%"+keyword+"%'"
result = cur.execute(sorgu)
if result > 0:
articles = cur.fetchall()
cur.close()
return render_template("articles.html",articles = articles)
else:
cur.close()
sleep(2)
flash("Makale bulunamadı","danger")
return redirect("/articles")
#Register
@app.route("/register",methods = ["GET","POST"])
@logout_required
def register():
form = RegisterForm(request.form)
name = form.name.data
username = form.username.data
email = form.email.data
password = sha256_crypt.hash(form.password.data)
if request.method == "POST" and form.validate():
cur = mysql.connection.cursor()
try:
sorgu = "INSERT INTO users(name,email,username,password) VALUES(%s,%s,%s,%s)"
cur.execute(sorgu,(name,email,username,password))
mysql.connection.commit()
cur.close()
flash("Başarıyla kayıt oldunuz !","success")
return redirect("/login")
except:
flash("Bu kullanıcı adı veya E-mail adresi zaten kayıtlı !","danger")
cur.close()
return redirect("/register")
else:
return render_template("register.html",form=form)
#Login
@app.route("/login",methods=["GET","POST"])
@logout_required
def login():
form = LoginForm(request.form)
if request.method == "POST":
username = form.username.data
password = form.password.data
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM users WHERE username = %s"
db_request = cur.execute(sorgu,(username,))
if db_request > 0 :
data = cur.fetchone()
encrypted_pass = data["password"]
cur.close()
if sha256_crypt.verify(password,encrypted_pass):
flash("Başarıyla giriş yaptınız !","success")
session["login"] = True
session["username"] = username
return redirect("/")
else:
sleep(2)
flash("Şifrenizi yanlış girdiniz !","danger")
return redirect("/login")
else:
sleep(2)
flash("Böyle bir kullanıcı adı bulunamadı !","danger")
cur.close()
return redirect("/login")
return render_template("login.html",form=form)
#Logout
@app.route("/logout")
@login_required
def logout():
session.clear()
flash("Başarıyla çıkış yaptınız !","success")
return redirect("/")
#Dashboard
@app.route("/dashboard")
@login_required
def dashboard():
cur = mysql.connection.cursor()
sorgu = "SELECT * FROM articles WHERE author = %s ORDER BY created_date DESC"
result = cur.execute(sorgu,(session["username"],))
if result > 0:
articles = cur.fetchall()
cur.close()
return render_template("dashboard.html",articles = articles)
else:
cur.close()
return render_template("dashboard.html")
#To run the .py
if __name__ == "__main__":
app.run()
| true |
cc56477c09a3e3bc8a4e90cfffba30f4818592c4 | Python | bhusain/GenPair | /preprocess.py | UTF-8 | 2,037 | 3.015625 | 3 | [] | no_license | # Preprocessing Script
# Rachel Eimen
# 2/16/18
# Description: Program reads in GEM, deletes points <= 0, and populates
# an array of size 361 with a condensed version of the data
import pandas as pd
import matplotlib.pyplot as plt
import math
data = pd.read_csv('Hsapiens-9606-201603-2016-RNASeq-Quantile-CancerGenomeAtlas-v1.GEM.txt',sep='\t')
#data = data[data.columns.values[:-1]]
data = data.transpose()
global_max = data.max().max()
global_min = data.min().min()
print(global_max)
print(global_min)
print(data.shape)
import numpy as np
import json
d = dict()
with open('output_new.txt', 'w') as file:
for i in range (0, 100): #(0,73599): # g1 options
if data.ix[:, i].max() > 0:
for j in range(i + 1, 100): # 73599): # g2 options
if data.ix[:, j].max() > 0:
gName = 'g' + str(i + 1) + '_g' + str(j + 1)
array = np.zeros(361, dtype = int)
for k in range(0, 2016): # run through each sample for every gene
if (data.ix[k, i] != 'nan'): # verify that entry is not equal to 'nan'
if (data.ix[k, i] > 0 and data.ix[k, j] > 0): # if value is greater than 0
g1_coord = math.ceil(data.ix[k, i]) # round up
g2_coord = math.ceil(data.ix[k, j])
array[int(g1_coord - 1 + (18*g2_coord))] += 1 # add 1 to the array at index = g1 - 1 + (18*g2)
d[gName] = array
# write array to file
for key in d:
file.write(key)
for i in d[key]:
o = ' '.join(str(i) for i in d[key])
file.write(o)
file.close()
| true |
cde8c85f28d6e6e4e1cde25da152eef3c0e639b6 | Python | IDP-L211/controllers | /driver/modules/motion.py | UTF-8 | 4,995 | 3.21875 | 3 | [
"MIT"
] | permissive | # Copyright (C) 2021 Jason Brown
#
# SPDX-License-Identifier: MIT
"""Class file for the motion controller"""
import numpy as np
tau = np.pi * 2
class MotionCS:
"""
All MotionCS methods will return an array of left and right motor velocities
To be used via robot.motors.velocities = MotionControlStrategies.some_method(*args)
"""
# Overwritten in robot.py
max_f_speed = None
@staticmethod
def combine_and_scale(forward, rotation, angle=None):
# Reverse rotation if angle is negative for symmetric strategies
if angle is not None:
rotation *= np.sign(angle)
# Combine velocities
left_speed = forward + rotation
right_speed = forward - rotation
# Scale so max is +-1
if abs(left_speed) >= 1:
left_speed = left_speed / abs(left_speed)
right_speed = right_speed / abs(left_speed)
if abs(right_speed) >= 1:
right_speed = right_speed / abs(right_speed)
left_speed = left_speed / abs(right_speed)
return np.array([left_speed, right_speed])
@staticmethod
def dual_pid(prime_quantity=None, deriv_quantity=None, prime_pid=None, derivative_pid=None,
req_prime_quantity=None, req_deriv_quantity=None) -> float:
"""This method uses 2 PID's to control a quantity based on a threshold. If only one of the required measurements
is given it just uses a single PID.
The PID takes a quantity and its derivative (i.e. distance and velocity). When close to closing the error it
uses the prime quantity but when it's far it uses the derivative quantity
With derivative control it acts as a feed-forward PID (open loop + closed loop) as this is a powerful and
responsive control method for situations such as these.
It switches quantity when the output of the prime quantity controller is equal to the output of the derivative
quantity controller, this is found using pid.query which gets output without affecting pid state.
Args:
prime_quantity (float): Our current prime quantity. E.g. distance, m or angle, rad
deriv_quantity (float): Our current derivative quantity. E.g. forward speed, m/s or
rotational speed, rad/s
prime_pid (PID): Prime quantity PID controller
derivative_pid (PID): Derivative quantity PID controller
req_prime_quantity (float): Required prime quantity
req_deriv_quantity (float): Required derivative quantity
Returns:
float: The drive fraction for the given inputs
"""
if prime_quantity is None and deriv_quantity is None:
drive = 0
else:
if deriv_quantity is not None:
derivative_based_drive = derivative_pid.query(req_deriv_quantity - deriv_quantity) + req_deriv_quantity
if prime_quantity is not None:
if np.sign(derivative_based_drive) * prime_pid.query(prime_quantity - req_prime_quantity) <= abs(derivative_based_drive):
drive = prime_pid.step(prime_quantity - req_prime_quantity)
else:
drive = derivative_pid.step(req_deriv_quantity - deriv_quantity) + req_deriv_quantity
else:
drive = derivative_pid.step(req_deriv_quantity - deriv_quantity) + req_deriv_quantity
else:
drive = prime_pid.step(prime_quantity - req_prime_quantity)
return drive
@staticmethod
def linear_dual_pid(distance=None, forward_speed=None, distance_pid=None, forward_speed_pid=None,
required_distance=0, required_forward_speed=None, angle_attenuation=True, angle=None):
"""Wrapper for dual_pid to make linear control simpler"""
# If required_forward_speed is not specified use max
req_forward_speed = MotionCS.max_f_speed if required_forward_speed is None else required_forward_speed
# Attenuate speeds and distance based on angle so robot doesn't zoom off when not facing target
if angle_attenuation and angle is not None:
attenuation_factor = (np.cos(angle) ** 5) if abs(angle) <= tau / 4 else 0
distance *= attenuation_factor
required_distance *= attenuation_factor
req_forward_speed *= attenuation_factor
# Convert from actual robot velocities to drive fraction equivalent
required_forward_drive = req_forward_speed / MotionCS.max_f_speed
forward_speed_drive_eq = None if forward_speed is None else forward_speed / MotionCS.max_f_speed
return MotionCS.dual_pid(prime_quantity=distance, deriv_quantity=forward_speed_drive_eq,
prime_pid=distance_pid, derivative_pid=forward_speed_pid,
req_prime_quantity=required_distance, req_deriv_quantity=required_forward_drive)
| true |
e386b844226c72dbf52040769ed2518875a937d3 | Python | avim2809/CameraSiteBlocker | /venv/Lib/site-packages/docs/likegeeks_tutorial/md_to_html.py | UTF-8 | 699 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | import markdown
import codecs
def md_to_html(md_filename):
html_filename = u"{fn}.html".format(fn=u'.'.join(md_filename.split(u'.')[:-1]))
with codecs.open(html_filename, mode='w') as html_file:
html_file.write("""<!DOCTYPE html>
<html>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
""")
markdown.markdownFromFile(input=md_filename)
markdown.markdownFromFile(input=md_filename,
output=html_file,
encoding=u'utf-8')
html_file.write(u'</body>'
u'</html>'
)
md_to_html(u'tutorial.md') | true |
71d41cb3b5e2955d0e3cf74cc37f1f8308cefddc | Python | yanone/dancingshoes | /Sample files/myFP/features.py | UTF-8 | 2,329 | 2.78125 | 3 | [] | permissive | from dancingshoes import DancingShoes
from dancingshoes.helpers import SubstitutionsFromCSV
import string
def MakeDancingShoes(glyphnames):
# Your features, in the order you want them in the font
features = ('aalt', 'locl', 'numr', 'dnom', 'frac', 'tnum', 'smcp', 'case', 'calt', 'liga', 'ss01', 'ss02', 'ss03')
# Initialize DancingShoes object, hand over glyph names and default features
shoes = DancingShoes(glyphnames, features)
# Stylistic Sets
for i in range(20):
shoes.AddSimpleSubstitutionFeature('ss' + str(string.zfill(i, 2)), '.ss' + str(string.zfill(i, 2)))
# Add direct substitutions
directsubstitutions = (
('smcp', '.sc'),
('case', '.case'),
('tnum', '.tf'),
('ss01', '.ss01'),
('ss02', '.ss02'),
('ss03', '.ss03'),
)
for feature, ending in directsubstitutions:
shoes.AddSimpleSubstitutionFeature(feature, ending)
# Arabic
if shoes.HasGroups(['.init']):
shoes.AddEndingToBothClasses('init', '.init')
shoes.AddSubstitution('init', "@init_source", "@init_target", 'arab', '', 'RightToLeft')
# You can write contextual code for your script fonts using your own glyph name endings
if shoes.HasGroups(['.initial', '.final']):
# Add contextual substitution magic here
for target in shoes.GlyphsInGroup('.initial'):
shoes.AddGlyphsToClass('@initialcontext', ('a', 'b', 'c'))
shoes.AddSubstitution('calt', "@initialcontext %s'" % (shoes.SourceGlyphFromTarget(target)), target)
# You can theoretically write your own kern feature (which FontLab can also do for you upon font generation):
shoes.AddPairPositioning('kern', 'T A', -30)
shoes.AddPairPositioning('kern', 'uniFEAD uniFEEB', (-30, 0, -60, 0), 'arab', '', 'RightToLeft')
# From CSV file
csvfile = "../substitutions.csv"
for feature, source, target, script, language, lookupflag, comment in SubstitutionsFromCSV(csvfile):
shoes.AddSubstitution(feature, source, target, script, language, lookupflag, comment)
# Uppercase Spacing
uppercaseletters = ['A', 'B', 'C', 'D', 'E']
for uppercaseletter in uppercaseletters:
if shoes.HasGlyphs(uppercaseletter):
shoes.AddGlyphsToClass('@uppercaseLetters', uppercaseletter)
if shoes.HasClasses('@uppercaseLetters'):
shoes.AddSinglePositioning('cpsp', '@uppercaseLetters', (5, 0, 10, 0))
shoes.DuplicateFeature('hist', 'ss20')
return shoes | true |
5ce2bd4677f02edc7f66b28ec43731ee0e2488ff | Python | gavingavinchan/lusca | /computerVision/thresholdIMG.py | UTF-8 | 998 | 2.625 | 3 | [
"MIT"
] | permissive | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('checkerboardIMG.jpg',cv.IMREAD_GRAYSCALE)
imgHeight = img.shape[0]
imgWidth = img.shape[1]
#print(img.shape)
#ret,thresh = cv.threshold(img,)
#cv.imshow('image',img)
resizeIMG = cv.resize(img,(int(imgWidth/10),int(imgHeight/10)))
cv.imshow('resizedIMG',resizeIMG)
blurIMG = cv.blur(resizeIMG,(5,5))
cv.imshow('blurIMG',blurIMG)
ret, thresholdIMG = cv.threshold(blurIMG,127,255,cv.THRESH_BINARY)
cv.imshow('thresholdIMG',thresholdIMG)
edgeIMG = cv.Canny(thresholdIMG,100,200,apertureSize = 3)
cv.imshow('edgeIMG',edgeIMG)
'''
lines = cv.HoughLines(edgeIMG,1,np.pi/180,200)
for rho,theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv.imshow('lineIMG',img)
'''
cv.waitKey(0)
cv.destroyAllWindows()
| true |
b02d18cb4ab423b1f535ad8e8da23ead2c36f289 | Python | TorpidCoder/Algorithm-in-Flow | /Sorting/reeverse.py | UTF-8 | 271 | 3.46875 | 3 | [] | no_license | def reverse_only_string(list):
if(len(list)<=1):
return list
return reverse_only_string(list[1:]) + list[0]
print(reverse_only_string('abc'))
def rev_1(lst):
if not lst:
return lst
else:
return lst[-1:] + rev_1(lst[:-1])
| true |
703a51161c69b23baffc9dc0c0734315da733b99 | Python | HarshaniSomarathne/ExtractEXIF | /EXIF.py | UTF-8 | 938 | 2.984375 | 3 | [
"MIT"
] | permissive | import exifread
import optparse
import sys
def openImage(path_name):
"""Open image file for reading (binary mode)"""
image = open(path_name, 'rb')
return image
def getData(tags, key):
"""get EXIF info according to the tag key"""
for tag in tags.keys():
if key in tag:
print "Key: %s, value: %s" % (tag, tags[tag])
def main():
"""get EXIF info from images according to the key value"""
optparser = optparse.OptionParser()
optparser.add_option("-f", "--filename", dest="filename", default="", help="the location of input image")
optparser.add_option("-k", "--key", dest="key", default="GPS", help="the EXIF key")
(opts, _) = optparser.parse_args()
#open image
image = openImage(opts.filename)
#get image tags
tags = exifread.process_file(image)
#print EXIF info according to the key
getData(tags, opts.key)
if __name__ == '__main__':
main() | true |
c0b4920abe13f9e9534962ca1b2ef166caa66835 | Python | UMass-Rescue/OakContentScraper | /content_scraper/scrapers/utils.py | UTF-8 | 490 | 3.03125 | 3 | [] | no_license | from abc import ABC, abstractmethod
class Scrape(ABC):
@abstractmethod
def collect_batch(self):
"""Collect batch of text contents"""
pass
@abstractmethod
def batch_monitor(self):
pass
@abstractmethod
def continuous_monitor(self):
pass
def vdir(obj):
"""Short summary.
:param any obj: Any object
:return: List of object attributes
:rtype: list
"""
return [x for x in dir(obj) if not x.startswith("__")]
| true |
94d48fd81e73763daf1f1b672ca3a4b15103014f | Python | JeroenVanGelder/citadels-machiavelli | /tests/test_character_card_draft.py | UTF-8 | 5,502 | 2.984375 | 3 | [] | no_license | import unittest, random
from machiavalli_game import MachiavelliGame
from player.playerDescriptions import PlayerDescription
from test_machiavelli_game import TestMachiavelliGame
class CharacterCardDraftTest(TestMachiavelliGame):
def setUp(self):
self.game = MachiavelliGame()
self.game.registerPlayer(PlayerDescription('jeroen'))
self.game.registerPlayer(PlayerDescription('robin'))
self.game.registerPlayer(PlayerDescription('sander'))
self.game.registerPlayer(PlayerDescription('martijn'))
self.game.registerPlayer(PlayerDescription('casper'))
self.game.startGame()
def getRandomCardName(self):
allAvailableCards = self.game.getAvailableCharacterCards()
randomCardPosition = random.randint(0, len(allAvailableCards))-1
card = allAvailableCards[randomCardPosition].name
return card
def test_draft_first_random_character_card(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen", jeroenCard)
def test_get_drafting_player(self):
draftingPlayer = self.game.getDraftingPlayer()
self.assertEqual('jeroen',draftingPlayer.name)
def test_get_drafting_player_after_one_pick(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen", jeroenCard)
draftingPlayer = self.game.getDraftingPlayer()
self.assertEqual('robin',draftingPlayer.name)
def test_draft_when_not_active_player(self):
robinCard = self.getRandomCardName()
with self.assertRaises(Exception):
self.game.draftCharacterCard("robin",robinCard)
def test_draft_when_not_active_player_after_pick(self):
randomDraftPick = self.getRandomCardName()
self.game.draftCharacterCard("jeroen",randomDraftPick)
randomDraftPick = self.getRandomCardName()
with self.assertRaises(Exception):
self.game.draftCharacterCard("jeroen",randomDraftPick)
def test_player_is_character_after_draft_pick(self):
randomDraftPick = self.getRandomCardName()
self.game.draftCharacterCard("jeroen",randomDraftPick)
self.assertEqual(randomDraftPick,self.game.getPlayer("jeroen").character)
def test_game_contains_all_character_cards(self):
cardInGame = self.game.getAllCharacterCards()
self.assertEqual(8, len(cardInGame))
def test_draft_starts_with_correct_open_cards(self):
cardsInGame = self.game.getAllCharacterCards()
openCards = 0
for card in cardsInGame:
if card.open is True:
self.assertNotEqual("koning",card.name)
openCards = openCards + 1
self.assertEqual(1, openCards)
def test_available_cards_not_available_after_draft_pick(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen",jeroenCard)
self.assertEqual(False, self.game.getCharacterCard(jeroenCard).available)
def test_available_cards_not_available_after_three_draft_picks(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen", jeroenCard)
robinCard = self.getRandomCardName()
self.game.draftCharacterCard("robin", robinCard)
sanderCard = self.getRandomCardName()
self.game.draftCharacterCard("sander", sanderCard)
koningCard = self.game.getCharacterCard(jeroenCard)
magierCard = self.game.getCharacterCard(robinCard)
bouwmeesterCard = self.game.getCharacterCard(sanderCard)
self.assertEqual(False, koningCard.available)
self.assertEqual(False, magierCard.available)
self.assertEqual(False, bouwmeesterCard.available)
def test_draft_unavailable_card(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen", jeroenCard)
with self.assertRaises(Exception):
self.game.draftCharacterCard("robin", jeroenCard)
def test_available_cards_available_after_wrong_draft_pick(self):
jeroenCard = self.getRandomCardName()
self.game.draftCharacterCard("jeroen", jeroenCard)
sanderCard = self.getRandomCardName()
with self.assertRaises(Exception):
self.game.draftCharacterCard("sander", sanderCard)
unavailableCard = self.game.getCharacterCard(jeroenCard)
availableCard = self.game.getCharacterCard(sanderCard)
self.assertEqual(False, unavailableCard.available)
self.assertEqual(True, availableCard.available)
#test if the game continues correctly when done drafter
def test_everyone_is_the_correct_character_after_full_draft(self):
draftedCards = self.runFullRandomDraft()
self.assertEqual(draftedCards["jeroen"], self.game.getPlayer("jeroen").character)
self.assertEqual(draftedCards["robin"], self.game.getPlayer("robin").character)
self.assertEqual(draftedCards["sander"], self.game.getPlayer("sander").character)
self.assertEqual(draftedCards["martijn"], self.game.getPlayer("martijn").character)
self.assertEqual(draftedCards["casper"], self.game.getPlayer("casper").character)
def test_game_goes_to_turns_after_draft(self):
draftedCards = self.runFullRandomDraft()
gamestate = self.game.getState()
turnGameState = "RunCharacterTurnsGameState"
self.assertEqual(turnGameState, gamestate)
if __name__ == '__main__':
unittest.main() | true |
15839166485a645e5dc3e8bb080ef91fab05d9e4 | Python | ptucker9/PythonClass-2015 | /ordinal_test.py | UTF-8 | 723 | 3.390625 | 3 | [] | no_license | import unittest #You need this module
import ordinal #This is the script you want to test
class mytest(unittest.TestCase):
def test_ord(self):
self.assertEqual("11th", ordinal.ordinal_type(11))
def test_ord1(self):
self.assertEqual("Put in an integer.", ordinal.ordinal_type(23.4))
def test_ord2(self):
self.assertEqual("13th", ordinal.ordinal_type(13))
def test_ord3(self):
self.assertEqual("2nd", ordinal.ordinal_type(2))
def test_two(self):
thing1=ordinal.ordinal_type(22)
thing2=ordinal.ordinal_type(23)
self.assertNotEqual(thing1, thing2)
if __name__ == '__main__': #Add this if you want to run the test with this script.
unittest.main()
| true |
b94e0dadbc4c54c1273dcf3583d305d114d5fc13 | Python | tszdanger/phd | /learn/ctci/1804-number-of-2s_test.py | UTF-8 | 523 | 2.984375 | 3 | [] | no_license | from labm8.py import app
from labm8.py import test
FLAGS = app.FLAGS
MODULE_UNDER_TEST = None # No coverage.
# Write a method to count the number of 2s that appear in all the numbers
# between 0 and n (inclusive).
#
# EXAMPLE
# Input: 25
# Output: 9 (2, 12, 20, 21, 22, 23, 24, 25)
#
def count_2s(n):
count = 0
for i in range(2, n + 1):
while i:
if i % 10 == 2:
count += 1
i = i // 10
return count
def test_main():
assert 9 == count_2s(25)
if __name__ == "__main__":
test.Main()
| true |
74dd7079091d4847c998f1e0edb9ac61ea05a896 | Python | oyorooms/hue | /desktop/core/ext-py/josepy-1.1.0/src/josepy/b64_test.py | UTF-8 | 2,326 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | """Tests for josepy.b64."""
import unittest
import six
# https://en.wikipedia.org/wiki/Base64#Examples
B64_PADDING_EXAMPLES = {
b'any carnal pleasure.': (b'YW55IGNhcm5hbCBwbGVhc3VyZS4', b'='),
b'any carnal pleasure': (b'YW55IGNhcm5hbCBwbGVhc3VyZQ', b'=='),
b'any carnal pleasur': (b'YW55IGNhcm5hbCBwbGVhc3Vy', b''),
b'any carnal pleasu': (b'YW55IGNhcm5hbCBwbGVhc3U', b'='),
b'any carnal pleas': (b'YW55IGNhcm5hbCBwbGVhcw', b'=='),
}
B64_URL_UNSAFE_EXAMPLES = {
six.int2byte(251) + six.int2byte(239): b'--8',
six.int2byte(255) * 2: b'__8',
}
class B64EncodeTest(unittest.TestCase):
"""Tests for josepy.b64.b64encode."""
@classmethod
def _call(cls, data):
from josepy.b64 import b64encode
return b64encode(data)
def test_empty(self):
self.assertEqual(self._call(b''), b'')
def test_unsafe_url(self):
for text, b64 in six.iteritems(B64_URL_UNSAFE_EXAMPLES):
self.assertEqual(self._call(text), b64)
def test_different_paddings(self):
for text, (b64, _) in six.iteritems(B64_PADDING_EXAMPLES):
self.assertEqual(self._call(text), b64)
def test_unicode_fails_with_type_error(self):
self.assertRaises(TypeError, self._call, u'some unicode')
class B64DecodeTest(unittest.TestCase):
"""Tests for josepy.b64.b64decode."""
@classmethod
def _call(cls, data):
from josepy.b64 import b64decode
return b64decode(data)
def test_unsafe_url(self):
for text, b64 in six.iteritems(B64_URL_UNSAFE_EXAMPLES):
self.assertEqual(self._call(b64), text)
def test_input_without_padding(self):
for text, (b64, _) in six.iteritems(B64_PADDING_EXAMPLES):
self.assertEqual(self._call(b64), text)
def test_input_with_padding(self):
for text, (b64, pad) in six.iteritems(B64_PADDING_EXAMPLES):
self.assertEqual(self._call(b64 + pad), text)
def test_unicode_with_ascii(self):
self.assertEqual(self._call(u'YQ'), b'a')
def test_non_ascii_unicode_fails(self):
self.assertRaises(ValueError, self._call, u'\u0105')
def test_type_error_no_unicode_or_bytes(self):
self.assertRaises(TypeError, self._call, object())
if __name__ == '__main__':
unittest.main() # pragma: no cover
| true |
9a40a167d334c6cbaa6ef82ca561546e1addf41b | Python | zk1013/mobileTestToolkit | /utils/adbkit.py | UTF-8 | 21,360 | 2.53125 | 3 | [] | no_license | """
@Time : 2021/3/1 11:15 上午
@Author : lan
@Mail : lanzy.nice@gmail.com
@Desc :
TODO: 提交 pr, wlan_ip() 里面没有做无权限设备获取IP的处理,可以添加上
"""
import re
import os
import logging
import platform
import datetime
import subprocess
from random import random
import adbutils
import functools
from MyQR import myqr
from time import sleep
from adbutils import adb
from utils import systemer
def check_device(func):
"""设备检测,判断仅有设备时继续执行"""
@functools.wraps(func)
def wrapper(*args, **kw):
device_list = AdbKit.device_list()
logging.debug(f"设备连接列表:{device_list}")
if len(device_list) == 0:
logging.error("没有设备")
raise RuntimeError("Can't find any android device/emulator")
return func(*args, **kw)
return wrapper
class AdbKit:
"""
https://github.com/openatx/adbutils
https://developer.android.com/studio/command-line/adb
"""
def __init__(self, serial=None):
self.serial = serial
self.adb = adb
self.adb_path = adbutils.adb_path()
self.adb_device = adb.device(self.serial)
self.shell = systemer.shell
logging.debug(f"AdbKit(serial={serial})")
def __adb_client(self):
"""AdbClient() API,这个函数不供调用,仅做演示"""
adb.server_version() # adb 版本
adb.server_kill() # adb kill-server
adb.connect("192.168.190.101:5555")
def __adb_device(self):
"""AdbDevice() API,这个函数不供调用,仅做演示"""
device = self.adb_device
print(device.serial) # 获取设备串号
print(device.prop.model)
print(device.prop.device)
print(device.prop.name)
print(device.prop.get("ro.product.manufacturer"))
# 获取当前应用包名和 activity
# {'package': 'com.android.settings', 'activity': 'com.android.settings.MainSettings'}
print(device.current_app())
# 安装
device.install("apk_path...")
# 卸载
device.uninstall("com.esbook.reader")
# 拉起应用
device.app_start("com.android.settings") # 通过 monkey 拉起
device.app_start("com.android.settings", "com.android.settings.MainSettings") # 通过 am start 拉起
# 清空APP
device.app_clear("com.esbook.reader")
# 杀掉应用
device.app_stop("com.esbook.reader")
# 获取屏幕分辨率 1080*1920
x, y = device.window_size()
print(f"{x}*{y}")
# 获取当前屏幕状态 亮/熄
print(device.is_screen_on()) # bool
device.switch_wifi(True) # 需要开启 root 权限
device.switch_airplane(False) # 切换飞行模式
device.switch_screen(True) # 亮/熄屏
# 获取 IP 地址
print(device.wlan_ip())
# 打开浏览器并跳转网页
device.open_browser("http://www.baidu.com")
device.swipe(500, 800, 500, 200, 0.5)
device.click(500, 500)
device.keyevent("HOME") # 发送事件
device.send_keys("hello world$%^&*") # simulate: adb shell input text "hello%sworld\%\^\&\*"
print(device.package_info("com.esbook.reader")) # dict
print(device.rotation()) # 屏幕是否转向 0, 1, 2, 3
device.screenrecord().close_and_pull() # 录屏
device.list_packages() # 包名列表 ["com.example.hello"]
@staticmethod
def device_list():
try:
return [d.serial for d in adb.device_list()]
except RuntimeError:
return []
def state(self):
"""获取设备状态
Returns:
Iterator[DeviceEvent], DeviceEvent.status can be one of
['device', 'offline', 'unauthorized', 'absent']
"""
return adb.track_devices().__next__()[-1]
def model(self) -> str:
"""获取设备型号: ELE-AL00"""
return self.adb_device.prop.model
def manufacturer(self) -> str:
"""获取设备制造商: HUAWEI"""
return self.adb_device.prop.get("ro.product.manufacturer")
def device_version(self) -> str:
"""获取设备 Android 版本号,如 4.2.2"""
return self.adb_device.prop.get("ro.build.version.release")
def sdk_version(self) -> str:
"""获取设备 SDK 版本号,如 26"""
return self.adb_device.prop.get("ro.build.version.sdk")
def cpu_version(self):
"""获取cpu基带版本: arm64-v8a"""
return self.adb_device.prop.get("ro.product.cpu.abi")
def wifi_state(self):
"""获取WiFi连接状态"""
return 'enabled' in self.shell('dumpsys wifi | grep ^Wi-Fi')
def wifi(self) -> str:
"""获取设备当前连接的 Wi-Fi 名称"""
# output: mWifiInfo SSID: wifi_name, BSSID: 70:f9:6d:b6:a4:81, ...
output = self.adb_device.shell("dumpsys wifi | grep mWifiInfo")
name = output.strip().split(",")[0].split()[-1]
return name
def ip(self) -> str:
"""Get device IP
正常情况:inet addr:192.168.123.49 Bcast:192.168.123.255 Mask:255.255.255.0
无权限情况:ifconfig: ioctl 8927: Permission denied (Android 10)
"""
output = self.adb_device.shell("ifconfig wlan0")
ip = re.findall(r'inet\s*addr:(.*?)\s', output, re.DOTALL)
if not ip:
return ""
return ip[0]
def connect(self, ip=None, port=5555) -> str:
"""基于 WI-FI 连接设备"""
# TODO:判断手机与PC是否为同一网段,如果不是给出提示
if not ip:
ip = self.ip()
if not ip:
return '无线连接失败,请输入 IP 地址后重试!'
# 设置端口
dev = f"{ip.strip()}:{str(port).strip()}"
logging.info(f"进行无线连接 ==> {dev}")
self.shell(f'adb tcpip {port}')
self.shell(f'adb connect {dev}')
try:
assert dev in self.device_list()
return 'Successful wireless connection.'
except AssertionError:
return '无线连接失败,请确保手机和PC网络一致;或检查IP地址是否正确。'
def device_info_complete(self):
try:
ip = self.ip()
except RuntimeError as e:
ip = str(e).split(":")[-1]
device_info_dict = {
"【设备型号】": f"{self.manufacturer()} | {self.model()}",
"【设备串号】": self.adb_device.serial,
"【系统版本】": f"Android {self.device_version()} (API {self.sdk_version()})",
"【电池状态】": self.battery_info(),
"【CPU版本】": self.cpu_version(),
"【屏幕尺寸】": f"{self.window_size()[0]}x{self.window_size()[-1]}",
"【IP地址】": ip,
}
output = ''
for k, v in device_info_dict.items():
output += f"{k}: {v}\n"
return output
def get_pid(self, pkg_name) -> str:
"""根据包名获取对应的 gid
args:
pkg_name -> 应用包名
usage:
get_pid("com.android.commands.monkey") # monkey
"""
pid_info = self.shell(f"adb -s {self.serial} shell ps | grep -w {pkg_name}")[0]
if not pid_info:
return "The process doesn't exist."
pid = pid_info.split()[1]
return pid
def kill_pid(self, pid):
"""TODO:还没测试,杀死应用进程 monkey 进程
usage:
kill_pid(154)
注:杀死系统应用进程需要root权限
"""
print(self.adb_device.shell(f"kill {pid}"))
# if self.shell("kill %s" % str(pid)).stdout.read().split(": ")[-1] == "":
# return "kill success"
# else:
# return self.shell("kill %s" % str(pid)).stdout.read().split(": ")[-1]
def pm_list_package(self, options="-3"):
"""输出所有软件包,可根据 options 进行过滤显示
options:
-s:进行过滤以仅显示系统软件包。
-3:进行过滤以仅显示第三方软件包。
-i:查看软件包的安装程序。
"""
return self.adb_device.shell(f"pm list packages {options}")
def pm_path_package(self, package):
"""输出给定 package 的 APK 的路径"""
return self.adb_device.shell(f"pm path {package}")
def install(self, apk):
"""安装应用,支持本地路径安装和URL安装"""
self.shell(f"python3 -m adbutils -s {self.serial} -i {apk}")
def uninstall(self, package):
"""卸载应用"""
self.adb_device.uninstall(package)
def delete_folder(self, folder):
"""删除 sdcard 上的文件夹"""
self.adb_device.shell(f"rm -rf /sdcard/{folder}")
def battery_info(self) -> str:
"""获取电池信息
returns:
100% (已充满, 29°)
"""
output = (self.adb_device.shell("dumpsys battery"))
m = re.compile(r'level: (?P<level>[\d.]+)').search(output)
level = m.group("level")
m = re.compile(r'status: (?P<status>[\d.]+)').search(output)
status = int(m.group("status"))
m = re.compile(r'temperature: (?P<temperature>[\d.]+)').search(output)
temperature = int(m.group("temperature")) // 10
# BATTERY_STATUS_UNKNOWN:未知状态
# BATTERY_STATUS_CHARGING: 充电状态
# BATTERY_STATUS_DISCHARGING: 放电状态
# BATTERY_STATUS_NOT_CHARGING:未充电
# BATTERY_STATUS_FULL: 充电已满
status_dict = {
1: "未知状态",
2: "充电中",
3: "放电中",
4: "未充电",
5: "已充满"
}
battery_info = f"{level}% ({status_dict[status]}, {temperature}°)"
return battery_info
def window_size(self):
"""获取设备屏幕分辨率"""
x, y = self.adb_device.window_size()
return x, y
def qr_code(self, text):
"""生成二维码, pip3 install MyQR"""
# TODO:支持本地路径可以内网访问 ,地址为:http://192.168.125.81:8000/path
qr_path = systemer.get_abs_path("log", "qr_code.jpg")
logging.info(f"二维码路径:{qr_path}")
myqr.run(
words=text, # 不支持中文
# pictures='2.jpg', # 生成带图的二维码
# colorized=True,
save_name=qr_path,
)
return qr_path
def reboot(self):
"""重启设备"""
self.shell("adb reboot")
def fast_boot(self):
"""进入fastboot模式"""
self.shell("adb reboot bootloader")
def current_app(self):
"""获取当前顶层应用的包名和activity,未命中系统应用,才返回值"""
package_black_list = [
"com.miui.home", # 小米桌面
"com.huawei.android.launcher" # 华为桌面
]
current_app = self.adb_device.current_app()
logging.debug(current_app)
package = current_app["package"]
activity = current_app["activity"]
if package in package_black_list:
logging.info(f"Current package is System APP ==> {package}")
return
return package, activity
def current_app_reset(self):
"""重置当前应用"""
pkg_act = self.current_app()
if not pkg_act:
return "当前为系统应用,请启动应用后重试"
package, activity = pkg_act
self.adb_device.app_clear(package)
logging.info(f"Reset APP ==> {package}")
self.adb_device.app_start(package_name=package)
logging.info(f"Restart APP ==> {package}")
def app_info(self, pkg_name):
return self.adb_device.package_info(pkg_name)
def current_app_info(self):
"""
return -> dict:
version_name,
version_code(去掉了最高和最低支持的 SDK 版本),
flags,
first_install_time,
last_update_time,
signature
"""
package, activity = self.current_app()
package_info = self.adb_device.package_info(package)
return package_info
def call_phone(self, number: int):
"""启动拨号器拨打电话"""
self.adb_device.shell(f"am start -a android.intent.action.CALL -d tel:{number}")
def get_focused_package_xml(self, save_path):
file_name = random.randint(10, 99)
self.shell(f'uiautomator dump /data/local/tmp/{file_name}.xml').communicate()
self.adb_device(f'pull /data/local/tmp/{file_name}.xml {save_path}').communicate()
def click_by_percent(self, x, y):
"""通过比例发送触摸事件"""
if 0.0 < x+y < 2.0:
wx, wy = self.window_size()
x *= wx
y *= wy
logging.debug(f"点击坐标 ==> ({x}, {y})")
return self.adb_device.click(x, y)
else:
logging.error("click_by_percent(x, y) 预期为小于等于1.0的值,请检查参数")
def swipe_by_percent(self, sx, sy, ex, ey, duration: float = 1.0):
"""通过比例发送滑动事件,Android 4.4以上可选 duration(ms)"""
wx, wy = self.window_size()
sx *= wx
sy *= wy
ex *= wx
ey *= wy
logging.debug(f"滑动事件 ==> ({sx}, {sy}, {ex}, {ey}, duration={duration})")
return self.adb_device.swipe(sx, sy, ex, ey, duration=duration)
def swipe_to_left(self):
"""左滑屏幕"""
self.swipe_by_percent(0.8, 0.5, 0.2, 0.5)
def swipe_to_right(self):
"""右滑屏幕"""
self.swipe_by_percent(0.2, 0.5, 0.8, 0.5)
def swipe_to_up(self):
"""上滑屏幕"""
self.swipe_by_percent(0.5, 0.8, 0.5, 0.2)
def swipe_to_down(self):
"""下滑屏幕"""
self.swipe_by_percent(0.5, 0.2, 0.5, 0.8)
def gen_file_name(self, suffix=None):
"""生成文件名称,用于给截图、日志命名"""
now = datetime.datetime.now()
str_time = now.strftime('%y%m%d_%H%M%S')
device = self.manufacturer().lower()
if not suffix:
return f"{device}_{str_time}"
return f"{device}_{str_time}.{suffix}"
def screenshot(self, pc_path):
"""获取当前设备的截图,导出到指定目录
usage:
screenshot("/Users/lan/Downloads/")
"""
try:
self.adb_device.shell("mkdir sdcard/screenshot")
except FileExistsError:
logging.debug("截图保存位置 ==> sdcard/screenshot/")
filename = self.gen_file_name("png")
file = f"/sdcard/screenshot/{filename}"
self.adb_device.shell(f"/system/bin/screencap -p {file}")
self.adb_device.sync.pull(file, f"{pc_path}/{filename}")
def screen_record(self):
pass
def app_usage(self, package):
"""获取当前应用 cpu、内存使用占比
"""
# 安卓top命令仅显示16位包名,这里处理下方便 grep
pkg = package[:15] + (package[15:] and "+")
# -n 显示n次top的结果后命令就会退出
# -d 更新间隔秒数
# 各参数含义:https://blog.csdn.net/q1183345443/article/details/89920632
output = self.adb_device.shell(f'top -n 1 -d 1 | grep {pkg}').split()
logging.debug(f"返回数据 ==> {output}")
cup, mem = output[8], output[9]
return cup, mem
def bigfile(self):
"""填充手机磁盘,直到满"""
self.adb_device.shell('dd if=/dev/zero of=/mnt/sdcard/bigfile')
def delete_bigfile(self):
"""删除填满磁盘的大文件"""
self.adb_device.shell('rm -r /mnt/sdcard/bigfile')
def backup_apk(self, package, path):
"""备份应用与数据(未测试)
- all 备份所有 | -f 指定路径 | -system|-nosystem | -shared 备份sd卡
"""
self.adb_device.adb_output(f'backup -apk {package} -f {path}/mybackup.ab')
def restore_apk(self, path):
"""恢复应用与数据(未测试)"""
self.adb_device.adb_output('restore %s' % path)
def logcat_c(self):
self.adb_device.shell("logcat --clear")
logging.info("logcat clear...")
def logcat(self, filepath, timeout=5, flag=""):
"""获取 adb 日志
Example:
flag: '*:E';过滤错误级别日志
"""
command = f"{self.adb_path} -s {self.serial} logcat -v time {flag} > {filepath}"
logging.info(f"==> {command}")
output = subprocess.Popen(command, shell=True)
pid = str(output.pid)
sleep(timeout)
logging.info(f"adb logcat finished... (PID: {pid}; time: {timeout}s)")
system = platform.system()
if system == "Darwin" or "Linux":
output = subprocess.Popen(f"kill -9 {pid}", shell=True)
else:
# Windows 不知道能否生效,没有机器测试
output = subprocess.Popen(f"taskkill /F /T /PID {pid}", shell=True)
logging.info(f"Kill adb logcat process! ({system}:{output})")
def dump_crash_log(self, filepath):
"""转储带有 crash pid 的日志
filepath:
日志存储的目录路径
"""
# log 存储路径
filename = self.gen_file_name()
log_filename = f"{filename}.log"
crash_filename = f"{filename}_crash.log"
log_filepath = os.path.join(filepath, log_filename)
crash_filepath = os.path.join(filepath, crash_filename)
self.logcat(log_filepath, flag='*:E')
logging.info(f"adb logcat *:E filepath ==> {log_filepath}")
# 获取设备基础信息
model = self.model()
manufacturer = self.manufacturer()
version = self.device_version()
sdk_version = self.sdk_version()
device_info = f"DeviceInfo: {manufacturer} {model} | Android {version} (API {sdk_version})"
# 根据关键字找到出现 FATAL 错误的 pid
keyword = "FATAL EXCEPTION: main"
crash_pid_list = []
with open(log_filepath, encoding="utf-8") as fr:
for line in fr.readlines():
if keyword in line:
data = re.findall(r"\d+", line) # 提取出日志行内所有数字(日期 + PID)
pid = data[-1]
crash_pid_list.append(pid)
logging.info(f"Crash PID list >>> {crash_pid_list}")
# 根据 pid 过滤出错误日志,转储到新的文件内
if crash_pid_list:
with open(crash_filepath, "w+", encoding="utf-8") as f: # 创建转储日志并写入
f.write(f"{'-' * 50}\n")
f.write(f"{device_info}\n共出现 {len(crash_pid_list)} 次闪退\n")
f.write(f"{'-' * 50}\n")
with open(log_filepath, encoding="utf-8") as f1: # 读取原始日志
for line in f1.readlines():
for pid in crash_pid_list:
if pid in line:
if "FATAL" in line:
f.write("\n# begging of crash --- >>>\n")
f.write(line)
logging.info(f"Crash log path: {crash_filepath}")
return crash_filename
else:
logging.info(f"Not found 'FATAL EXCEPTION: main' in {log_filepath}")
return log_filename
def find_process_id(self, pkg_name):
"""根据包名查询进程 PID
:param pkg_name: Package Name
:return: USER | PID | NAME
"""
output = self.adb_device.shell("ps | grep %s" % pkg_name)
process_list = str(output[1]).split('\n')
for process in process_list:
if process.count(pkg_name):
while process.count(' ') > 0:
process = process.replace(' ', ' ')
process_info = process.split(' ')
user = process_info[0]
pid = process_info[1]
name = process_info[-1]
return user, pid, name
return None, None, None
def find_and_kill_process(self, pkg_name):
"""查找并结束指定进程"""
user, pid, process_name = self.find_process_id(pkg_name)
if pid is None:
return "None such process [ %s ]" % pkg_name
if user == 'shell':
kill_cmd = 'kill -9 %s' % pid
else:
kill_cmd = 'am force-stop %s' % pkg_name
return self.shell(kill_cmd)
if __name__ == '__main__':
pass
| true |
b35a9f8c291c4c0546ad5e33cc305bbdec33e16b | Python | catherinetmoyo/CEBD1100_Work | /WEEK4/exercise2.py | UTF-8 | 96 | 2.53125 | 3 | [] | no_license | my_list = ["A", "B", "C"]
copied_list_1 == my_list
copied_list_2 = my_list.copy()
origina
| true |
f34d67638bb225d98d6bf141753d5fbdacd60d25 | Python | jbayardo/metnum-tp2 | /generadores/contador.py | UTF-8 | 467 | 3.3125 | 3 | [] | no_license | file = open('train.csv', 'r')
cantidades = [0,0,0,0,0,0,0,0,0,0]
c = 0
for line in file:
if c == 0:
c = 1 # el primero es un label.
continue
partes = line.split(",")
cantidades[int(partes[0])] = cantidades[int(partes[0])] +1
file.close()
print cantidades
sum = 0
for i in cantidades:
sum = i + sum
porcentajes = [0,0,0,0,0,0,0,0,0,0]
for i in range(0, 10):
porcentajes[i] = 100*(float(cantidades[i])/sum)
print porcentajes
| true |
82d46021c3d28606d8bea61dbfb29209b6c1dda3 | Python | RubyPatil/7_Class | /Webtable.py | UTF-8 | 415 | 2.84375 | 3 | [] | no_license | from selenium import webdriver
driver=webdriver.Chrome()
driver.get("file:///C:/Users/Dell/Desktop/webtable2.html")
driver.maximize_window()
driver.implicitly_wait(30)
#ele=driver.find_elements_by_xpath("//*[@id='emp']/thead/tr/th")
ele=driver.find_elements_by_xpath("//*[@id='emp']/tbody/tr[1]/td") # For first row length
print(len(ele))
first_part="//*[@id='emp']/thead/tr/th["
second_part="]"
driver.close()
| true |
5a20b912540ac601ae98a350833f0d5d1bb1f265 | Python | beeven/pyZenWheels | /microcar.py | UTF-8 | 1,578 | 2.640625 | 3 | [] | no_license | from bluetooth import *
ADDR = '00:06:66:61:A3:EA'
STEER = [b'\x81' + x.to_bytes(1, byteorder='big') for x in range(128)]
SPEED = [b'\x82' + x.to_bytes(1, byteorder='big') for x in range(128)]
SIDELIGHT_LEFT = [b'\x83\x00', b'\x83\x01', b'\x83\x02', b'\x83\x03', b'\x83\x04' ]
SIDELIGHT_RIGHT = [b'\x84\x00', b'\x84\x01', b'\x84\x02', b'\x84\x03', b'\x84\x04' ]
LIGHTS = [b'\x85\x00', b'\x85\x01', b'\x85\x02']
HORN = [b'\x86\x00', b'\x86\x01']
class Car(object):
def __init__(self, address):
self.address = address
self.sock = BluetoothSocket(RFCOMM)
self.light = 0
self.left_sidelight = 0
self.right_sidelight = 0
def init(self):
self.sock.connect((self.address, 1))
def steer(self, value):
self.sock.send(STEER[int(value*63)])
def drive(self, value):
self.sock.send(SPEED[int(value*63)])
def toggle_light(self):
self.light += 1
self.sock.send(LIGHTS[self.light % len(LIGHTS)])
def toggle_horn(self, horn=True):
if horn:
self.sock.send(HORN[1])
else:
self.sock.send(HORN[0])
def toggle_left_sidelight(self):
self.left_sidelight += 1
self.sock.send(SIDELIGHT_LEFT[self.left_sidelight % len(SIDELIGHT_LEFT)])
def toggle_right_sidelight(self):
self.right_sidelight += 1
self.sock.send(SIDELIGHT_RIGHT[self.right_sidelight % len(SIDELIGHT_RIGHT)])
def __del__(self):
self.sock.close() | true |
c0083a17147e345e0cc2c37f83517682e47ba173 | Python | caique-santana/CursoEmVideo-Curso_Python3 | /PythonExercicios/ex030 - Par ou Ímpar.py | UTF-8 | 508 | 4.5 | 4 | [
"MIT"
] | permissive | # Crie um programa que leia um número inteiro e mostre na tela se ela o PAR ou IMPAR
# Meu
num = int(input('Digite um número: '))
if num % 2 == 0:
print('O número {} é \033[7;30m\033[1mPAR\033[m.'.format(num))
else:
print('O número {} é \033[7;30m\033[1mIMPAR\033[m.'.format(num))
# Gustavo Guanabara
número = int(input('Me diga um número qualquer: '))
resultado = número % 2
if resultado == 0:
print('O número {} é PAR'.format(número))
else:
print('O número {} é IMPAR'.format(número))
| true |
61a3ced71324f20ead873381dfe4363cb879b030 | Python | jeklen/todolist | /toDoList-3/first.py | UTF-8 | 446 | 2.71875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-20 16:32:25
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
from Tkinter import *
root = Tk()
v = StringVar()
def addItem(event):
content = v.get()
label = Label(root, text=content)
label.grid()
print type(label)
e.delete(0, END)
e = Entry(root, textvariable=v)
e.bind("<Return>", addItem)
e.grid(row=1, column=0)
root.mainloop()
| true |
6d3632a82dea4ba8ea26707fa30ab8082f872286 | Python | xiaole0310/leetcode | /659. Split Array into Consecutive Subsequences/Python/Solution.py | UTF-8 | 953 | 2.953125 | 3 | [] | no_license | class Solution:
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
counts = {}
for num in nums:
if num not in counts:
counts[num] = 0
counts[num] += 1
needs = {}
for num in nums:
if counts[num] == 0:
continue
if num in needs and needs[num] > 0:
needs[num] -= 1
if num + 1 not in needs:
needs[num + 1] = 0
needs[num + 1] += 1
elif num + 1 in counts and counts[num + 1] > 0 and num + 2 in counts and counts[num + 2] > 0:
counts[num + 1] -= 1
counts[num + 2] -= 1
if num + 3 not in needs:
needs[num + 3] = 0
needs[num + 3] += 1
else:
return False
counts[num] -= 1
return True
| true |
5d544b01497453888a275ac0b07129e7e7c3769d | Python | Vidhu-Chaudhary/Art_Of_Turtle_Programming | /Assembler/pass1.py | UTF-8 | 2,871 | 2.875 | 3 | [] | no_license | from Opcode import *
from SymbolTable import *
labels = list()
def pass1():
locptr = 0
arr = list()
error = False
stp = False
with open("input.txt","r") as f:
for x in f:
x = x.strip("\n")
arr = x.split(' ')
# print(arr)
st = ""
if len(arr) == 1 and arr[0] == st:
print("Error: Line is Blank"+"( at: "+str(locptr)+")")
error = True
continue
if (st in arr) and len(arr)>1 and arr[-1] != "":
print("Error: Extra white space between Opcodes/Variables"+"( at: "+str(locptr)+")")
error = True
continue
if len(arr) == 1 and ifLabel(arr[0]):
print("Error: Label defined does not point to any instruction"+"( at: "+str(locptr)+")")
if len(arr) == 1 and ifOpcode(arr[0]):
if check(arr[0]):
if arr[0] == "STP":
stp = True
break
else:
print("Error: Arguments Missing for the given Opcode"+"( at: "+str(locptr)+")")
error = True
elif len(arr) >= 2 and ifOpcode(arr[0]):
if len(arr) > 2:
print("Error: Too many arguments"+"( at: "+str(locptr)+")")
error = True
elif ifVariable(arr[1]):
addSym1(arr[1])
if(arr[0] == "INP"):
error = addSym(f'{locptr:08b}',arr[1])
else:
print("Error: Argument cannot be Opcode"+"( at: "+str(locptr)+")")
error = True
elif len(arr) >= 2 and ifVariable(arr[0]):
if len(arr) == 2:
if check(arr[1]):
if ifLabel(arr[0]):
labels.append(arr[0][:-1])
#print(labels)
error = addSym(f'{locptr:08b}',arr[0])
if arr[1] == "STP":
stp = True
break
else:
print("Error: Opcode Missing for the given Label"+"( at: "+str(locptr)+")")
error = True
elif len(arr) > 2:
if len(arr) > 3:
print("Error: Too many arguments"+"( at: "+str(locptr)+")")
error = True
elif ifOpcode(arr[1]) and ifVariable(arr[2]):
if ifLabel(arr[0]):
labels.append(arr[0][:-1])
if arr[2] in labels:
print("Error: Attribute should be Variable, Label given"+"( at: "+str(locptr)+")")
error = addSym(f'{locptr:08b}',arr[0])
addSym1(arr[2])
if(arr[1] == "INP"):
error = addSym(f'{locptr:08b}',arr[2])
else:
if not ifOpcode(arr[1]):
print("Error: No valid Opcode given"+"( at: "+str(locptr)+")")
error = True
elif ifOpcode(arr[2]):
print("Error: Opcode cannot be given as Arguments"+"( at: "+str(locptr)+")")
error = True
else:
print("Error: Line must have an Opcode as instruction"+"( at: "+str(locptr)+")")
error = True
locptr += 1
if not stp:
print("Error: No STP Opcode for stopping the program"+"( at: "+str(locptr)+")")
error = True
if (not error) and stp:
error = writeTbl()
if locptr == 255:
print("Error: Memory overflow, cannot exceed more than 255 variable and labels")
#print(labels)
return error | true |
4f360016f50a34fd9c906b70c4610f557c630523 | Python | mahajanrahul24/demo_cba | /inc.py | UTF-8 | 58 | 2.96875 | 3 | [] | no_license | def inc(input_user):
return input_user+1
print(inc(10)) | true |
5d5505f9a93cb5bf30054304a2d6e86fda9017d7 | Python | IkerSedanoSanchez/TIC-II-20_21 | /7_letra_funcion2_IkerSedano.py | UTF-8 | 1,176 | 4.25 | 4 | [] | no_license | def letra_funcion():
print """
***MENU***
S de suma
R de resta
M de multiplicacion
D de division"""
interruptora=1
while(interruptora==1):
numero=input ("Introcuzca el primer numero: ")
numero2=input ("Introduzca el segundo numero: ")
funcion=raw_input ("Introduzca una letra para definir la operacion: ")
if funcion=="S":
operacion=numero+numero2
interruptora=0
print numero,"+",numero2,"=",operacion
if funcion=="R":
operacion=numero-numero2
interruptora=0
print numero,"-",numero2,"=",operacion
if funcion=="M":
operacion=numero*numero2
interruptora=0
print numero,"*",numero2,"=",operacion
if funcion=="D":
if (numero2!=0):
interruptora=0
operacion=numero/numero2
print numero,"/",numero2,"=",operacion
else:
print "0 en el divisor no computa, brrr,introduce otra operacion, brrr"
interruptora=1
letra_funcion()
| true |
67b8041add0e2a75689411d94fc7848d61c0ca54 | Python | pozdnyakovx/AlfaBattle2.0 | /Alfa.py | UTF-8 | 8,915 | 2.515625 | 3 | [] | no_license |
# Alfa Battle 2.0 baseline
# Task 2 (default prediction)
# Features:
# * app_id - Идентификатор заявки. заявки пронумерованы так, что более поздним заявкам соответствует # более поздняя дата
# * amnt - Нормированная сумма транзакции. 0.0 - соответствует пропускам
# * currency - Идентификатор валюты транзакции
# * operation_kind - Идентификатор типа транзакции
# * card_type - Уникальный идентификатор типа карты
# * operation_type - Идентификатор типа операции по пластиковой карте
# * operation_type_group - Идентификатор группы карточных операций, например, дебетовая карта или кредитная карта
# * ecommerce_flag - Признак электронной коммерции
# * payment_system - Идентификатор типа платежной системы
# * income_flag - Признак списания/внесения денежных средств на карту
# * mcc - Уникальный идентификатор типа торговой точки
# * country - Идентификатор страны транзакции
# * city - Идентификатор города транзакции
# * mcc_category - Идентификатор категории магазина транзакции
# * day_of_week - День недели, когда транзакция была совершена
# * hour - Час, когда транзакция была совершена
# * days_before - Количество дней до даты выдачи кредита
# * weekofyear - Номер недели в году, когда транзакция была совершена
# * hour_diff - Количество часов с момента прошлой транзакции для данного клиента
# * transaction_number - Порядковый номер транзакции клиента
# Target:
# * flag - Целевая переменная, 1 - факт ухода в дефолт.
# URL: https://boosters.pro/championship/alfabattle2_sand/overview
# This is an open-source notebook and can be used accordingly.
# 1. Импорт данных через Spark
from pyspark.sql.types import DoubleType, StringType, StructField, IntegerType, LongType, StructType
schema = StructType([
StructField("app_id", IntegerType(), True),
StructField("amnt", DoubleType(), True),
StructField("currency", IntegerType(), True),
StructField("operation_kind", IntegerType(), True),
StructField("operation_type", IntegerType(), True),
StructField("operation_type_group", IntegerType(), True),
StructField("ecommerce_flag", IntegerType(), True),
StructField("payment_system", IntegerType(), True),
StructField("income_flag", IntegerType(), True),
StructField("mcc", IntegerType(), True),
StructField("country", IntegerType(), True),
StructField("city", IntegerType(), True),
StructField("mcc_category", IntegerType(), True),
StructField("day_of_week", IntegerType(), True),
StructField("hour", IntegerType(), True),
StructField("days_before", IntegerType(), True),
StructField("weekofyear", IntegerType(), True),
StructField("hour_diff", LongType(), True),
StructField("transaction_number", IntegerType(), True),
StructField("__index_level_0__", LongType(), True)
])
df = spark.read.format("parquet").schema(schema).load("/FileStore/tables/alfa")
cols = df.columns
df = df.dropna()
df = df.drop_duplicates()
print('Размер датасета: %d x %d' % (df.count(), len(cols)))
display(df)
# 2. Feature engineering
df.select('hour_diff').summary().show()
import pyspark.sql.functions as sf
display(df.groupBy(['payment_system']).agg(sf.count('app_id')))
order_sum_features = df.groupBy(['app_id']).agg(sf.mean('amnt').alias('order_sum_mean'), # средняя сумма транзакции
sf.max('amnt').alias('order_sum_max'), # макс. сумма транзакции
sf.min('amnt').alias('order_sum_min'), # мин. сумма транзакции
sf.expr('percentile_approx(amnt, 0.5)').alias('order_sum_median'), # медиана транзакции
)
display(order_sum_features)
# Credits to @aizakharov94 for heads-up
hour_diff_features = df.select(['app_id', 'hour_diff'])
hour_diff_features = hour_diff_features.withColumn('is_0',
(sf.col('hour_diff') == sf.lit(0)).cast(IntegerType())) # нулевая разница в транзакциях
# далее последовательно инжинирим фичи для разниц 1-3, 1-10, 5-10, 11-100, 100+
hour_diff_features = hour_diff_features.withColumn('is_1_3',
((sf.col('hour_diff') >= sf.lit(1)) & (sf.col('hour_diff') <= sf.lit(3))).cast(IntegerType()))
hour_diff_features = hour_diff_features.withColumn('is_5_10',
((sf.col('hour_diff') >= sf.lit(5)) & (sf.col('hour_diff') <= sf.lit(10))).cast(IntegerType()))
hour_diff_features = hour_diff_features.withColumn('is_1_10',
((sf.col('hour_diff') >= sf.lit(1)) & (sf.col('hour_diff') <= sf.lit(10))).cast(IntegerType()))
hour_diff_features = hour_diff_features.withColumn('is_11_100',
((sf.col('hour_diff') >= sf.lit(11)) & (sf.col('hour_diff') <= sf.lit(100))).cast(IntegerType()))
hour_diff_features = hour_diff_features.withColumn('is_100_plus',
(sf.col('hour_diff') > sf.lit(100)).cast(IntegerType()))
hour_diff_features = hour_diff_features.groupBy(['app_id']).agg(
sf.mean('is_0').alias('hour_diff_0_mean'),
sf.mean('is_1_3').alias('hour_diff_1_3_mean'),
sf.mean('is_1_10').alias('hour_diff_1_10_mean'),
sf.mean('is_5_10').alias('hour_diff_5_10_mean'),
sf.mean('is_11_100').alias('hour_diff_11_100_mean'),
sf.mean('is_100_plus').alias('hour_diff_100_plus_mean'))
df = df.withColumn('is_night_trans', sf.col('hour').isin({0, 1, 2, 3, 23}).cast(IntegerType()))
target = spark.read.format("csv").load("/FileStore/tables/alfabattle2_sand_alfabattle2_train_target.csv")
cols = df.columns
target = target.withColumnRenamed('_c0','app_id')
target = target.withColumnRenamed('_c1','product')
target = target.withColumnRenamed('_c2','flag')
target = target.filter(target.app_id != 'app_id')
target = target.withColumn('app_id', sf.col('app_id').cast(IntegerType()))
target = target.withColumn('product', sf.col('product').cast(IntegerType()))
target = target.withColumn('flag', sf.col('flag').cast(IntegerType()))
target = target.join(order_sum_features, on=['app_id'], how='left')
target = target.join(hour_diff_features, on=['app_id'], how='left')
# 3. Построение бейзлайна
train_df, test_df = target.randomSplit([0.8, 0.2])
cols = train_df.columns
cols = [i for i in cols if i != 'flag']
# Decision Tree model
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml import Pipeline
vector = VectorAssembler(inputCols=cols, outputCol='features')
tree = DecisionTreeClassifier(featuresCol='features', labelCol='flag')
pipe = Pipeline(stages=[vector, tree])
# Define the pipeline model
pipeModel = pipe.fit(train_df)
# Apply to train data
pred_df = pipeModel.transform(train_df)
# Evaluate the model
display(pred_df.select("features", "label", "prediction", "probability"))
display(pipelineModel.stages[-1], pred_df.drop("prediction", "rawPrediction", "probability"), "ROC")
# LGBM model
# %pip install lightgbm
from lightgbm import LGBMClassifier
lgbm = LGBMClassifier(objective='binary', num_leaves=10, learning_rate=0.05,
max_depth=1, n_estimators=50, boosting_type='goss')
lgbm.fit(train_df.drop('flag', axis=1), train_df['flag'])
y_true = test_df['flag'].values
y_pred = lgbm.predict(test_df.drop('flag', axis=1))
from sklearn.metrics import accuracy_score
accuracy_score(y_true, y_pred)
from sklearn.metrics import f1_score
import numpy as np
def lgb_f1_score(y_hat, y_true):
y_hat = np.round(y_hat
return 'f1', f1_score(y_true, y_hat)
lgb_f1_score(y_pred,y_true)
| true |
338d0aa406d19fed370cb160f679ce45f29a31c4 | Python | francescozanini/RPG | /story.py | UTF-8 | 1,871 | 3.484375 | 3 | [] | no_license | from fight import *
from tools import *
import random
class Story:
def __init__(self, name, difficulty_level):
self.name = name
self.location = 'Home'
self.is_alive = True
self.difficulty_level = difficulty_level
def get_diffuculty_level(self):
return 'novice' if self.difficulty_level==0 else 'skilled'
def update_story(self, player, inventory):
flag_quit = False
locations = ['Castle', 'Cave', 'Shore', 'Mountains', 'Fortress']
while (not (player.is_dead()) and not (flag_quit)):
options = ['Quit the game', 'Explore the neighborhood', 'Rest and restore health']
user_input = get_user_input(options)
if (user_input == 1): # Quit
flag_quit = True
print('Your adventure is terminated')
print('')
elif (user_input == 2): # Esplora
probability = 0.5
go_into_battle = random.random() < probability
if go_into_battle:
print('!!! You''ve found an opponent !!!')
fight(player, inventory, self)
print('')
else:
random_location = random.choice(locations)
if (random_location == self.location):
random_location = random.choice(locations)
self.location = random_location
print('No one''s around. You''re moving to ' + self.location)
print('')
elif (user_input == 3): # Return
player.rest()
self.location = 'Home'
print('')
else: # comando sbagliato
print('Wrong command, retry')
print('')
if player.is_dead():
print('Wasted') | true |
77636afb1335b88128604070fed28463af6cc08e | Python | bignatezzz/LMSClub | /calender3/calender3.py | UTF-8 | 1,338 | 4.46875 | 4 | [] | no_license | #
# Program: This is an example program that shows how to use str functions.
# 1. We are printing captilize Schedule
# 2. find if the schedule has a day of your intrest
# Author: Aashrith
# Date : 10/03/20
def capitalizeMySchedule(str):
print(str.upper())
def isMyDayPresent(str, findStr):
#for i in range(len(str)):
# print(i,str[i])
strLower = str.lower()
findStrLower = findStr.lower()
#print( "strLower ",strLower)
#print( "findStrLower ",findStrLower)
result = strLower.find(findStrLower)
if result > -1:
print( findStr, " is in the schedule at ", result)
else:
print( findStr, " is not in the schedule.")
#The main code starts here
strSchedule = """Day Time. Subject
Monday 10:00 - 11:00 AM Period 1
11:30-12:30 AM. Math
Tuesday 9:00-11:00 AM PE
10:00-11:00 AM. Science
Wednesday 9:00-11:00 AM Period 3
10:00-11:00 AM. Science"""
print("Get my schedule from function and print in uppercase.")
capitalizeMySchedule(strSchedule)
print("Check if the character is in schedule")
isMyDayPresent(str=strSchedule, findStr = "Wednesday" )
isMyDayPresent(strSchedule, "Monday" )
isMyDayPresent(strSchedule, "tuesdaY")
| true |