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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8a601949c081b062055a27e792234bc455b070d9
|
Python
|
ijhajj/RabbitMQ
|
/consumer_ack.py
|
UTF-8
| 1,082
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
import pika
from ConnectLocal import do_connect
def consuming_callback(ch, method, body):
message = body.decode()
if "reject" in message:
#setting basic_nack: "Not acknowledged" : implies message was not consumed
# And needs to be requeued, this can be turned On/OFF
# Default : Requeue
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
print("N-acked the message & Requeued")
else:
ch.basic_ack(delivery_tag=method.delivery_tag)
print("Message {0} is received correctly & successfully".format(message))
with do_connect() as channel:
value =""
while(value!="q"):
#auto_ack: turns off auto acknowledgements and expect Explicit acks.
(method, props, body) = channel.basic_get("pika_queue", auto_ack=False)
if body:
#if body exists consume the message
consuming_callback(channel, method, body)
#ask user to enter option to continue or quit
value=raw_input("any key to continue, q to stop")
| true
|
ee7f19f5829f5e984b1a2c2e34ea2eee80a45ad6
|
Python
|
vishwatejn/30DayChallenge
|
/Integer to Roman.py
|
UTF-8
| 477
| 4
| 4
|
[] |
no_license
|
# Integer to Roman
a = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"]
b = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
a = a[::-1]
b = b[::-1]
def convertRoman(n):
op = ""
for i in range(len(a)):
while n >= b[i]:
n -= b[i]
op += a[i]
return op
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
print(convertRoman(n))
| true
|
e3875b49050cf06ba1fb7c0a4ff82601ecad3487
|
Python
|
oyasai8910/SourceCodes
|
/Recomendation.py
|
UTF-8
| 4,342
| 3.046875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from __future__ import print_function
from pyspark import SparkContext
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
from pyspark.mllib.evaluation import RegressionMetrics
import math
TRAIN = 8
VALIDATION = 0
TEST = 2
ADJUST = 10 - TRAIN - VALIDATION - TEST
SPLIT_LIST = TRAIN, VALIDATION, TEST, ADJUST
if __name__ == "__main__":
sc = SparkContext(appName="PythonCollaborativeFilteringExample")
# $example on$
# Load and parse the data
data = sc.textFile("data.csv")
# Splitting the data
ratings = data.map(lambda l: l.split(','))\
.map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))
train, validation, test, adjustment = ratings.randomSplit(SPLIT_LIST) # splitting data into testing data, validation data and training data
train.cache() # caching data for quick optimization
validation.cache()
test.cache()
validationForPredict = validation.map(lambda x: (x[0], x[1]))
actualReformatted = validation.map(lambda x: ((x[0], x[1]), x[2]))
# Build the recommendation model using Alternating Least Squares
#rank = 10
#numIterations = 10
#model = ALS.train(train, rank, numIterations)
iterations = [5, 7, 10]
regularizationParameter = 0.05
ranks = [10, 12, 15]
RMSEs = [0, 0, 0, 0, 0, 0, 0, 0, 0]
err = 0
tolerance = 0.03
minRMSE = float('inf')
bestIteration = -1
bestRank = -1
ptr1 = "output \n"
#validating hyper-parameters
#for rank in ranks:
# for iteration in iterations:
# model = ALS.trainImplicit(train, rank, iteration, lambda_=regularizationParameter)
# predictedRatings = model.predictAll(validationForPredict)
# predictedReformatted = predictedRatings.map(lambda x: ((x[0], x[1]), x[2]))
# predictionAndObservations = (predictedReformatted.join(actualReformatted).map(lambda x: x[1]))
#
# metrics = RegressionMetrics(predictionAndObservations)
# RMSE = metrics.rootMeanSquaredError
# RMSEs[err] = RMSE
# err += 1
#
# #print ("For rank %s and iteration %s, the RMSE is %s") % (rank, iteration, RMSE)
# ptr1 = ptr1 + "For rank " + str(rank) + " and iterations " + str(iteration) + " the RMSE is " + str(RMSE) + " \n"
# print(ptr1)
# if RMSE < minRMSE:
# minRMSE = RMSE
# bestIteration = iteration
# bestRank = rank
###print ("The best model was trained with rank %s and iteration %s") % (bestRank, bestIteration)
#ptr2 = "The best model was trained with rank " + str(bestRank) + " and iteration " + str(bestIteration) + " \n"
#print(ptr2)
bestRank = 25
bestIteration = 15
bestModel = ALS.trainImplicit(train, bestRank, iterations=bestIteration, lambda_=regularizationParameter)
testForPredicting = test.map(lambda x: (x[0], x[1]))
testReformatted = test.map(lambda x: ((x[0], x[1]), x[2]))
predictedTest = bestModel.predictAll(testForPredicting)
predictedTestReformatted = predictedTest.map(lambda x: ((x[0], x[1]), x[2]))
predictionAndObservationTest = (predictedTestReformatted.join(testReformatted). map(lambda x: x[1]))
metrics = RegressionMetrics(predictionAndObservationTest)
testRMSE = metrics.rootMeanSquaredError
print ("The Model had a RMSE on the test set of " + str(testRMSE))
ptr3 = "The Model had a RMSE on the test set of " + str(testRMSE)
with open("RMSE_vs_train" + ".csv", "a") as f:
f.write(','.join(map(str, SPLIT_LIST + (testRMSE,))) + '\n')
# Evaluate the model on training data
#testdata = test.map(lambda p: (p[0], p[1]))
#predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
# Keep the it if there is already a data, if not put in the data camputed by ALS
#ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
#RMSE = math.sqrt(ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean())
#print("Root Mean Squared Error = " + str(RMSE))
# Save and load model
bestModel.save(sc, "target/tmp/myCollaborativeFilter")
#sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")
# $example off$
| true
|
c48df1c45fc8c495759b37963cf6d20e4a9a239c
|
Python
|
tepharju/Code1--Harjoitusteht-v-t
|
/CODE1_5_6_Collatz.py
|
UTF-8
| 338
| 3.34375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 27 10:17:17 2021
@author: tepha
Collatzin konjektuuri
"""
luku = int(input("Anna luku:"))
while luku > 0 and luku != 1:
if luku % 2 == 0:
luku = luku // 2
print(luku)
else:
luku = luku *3 +1
print(luku)
| true
|
1b29d4b8a684ddcdc166aadc38051f323695e88c
|
Python
|
wangweifeng2018/pyBAC
|
/removesingleton.py
|
UTF-8
| 1,191
| 3
| 3
|
[] |
no_license
|
import pysam
bam=pysam.Samfile("filter4-3.sorted.bam",'rb') #Load input file
bam_out = pysam.Samfile("filter4-4.bam", 'wb', template=bam) #Create output file
names=[] #Keep list of names to match to mate
output=[]
for read in bam.fetch(): #Loop over all reads in file
if read.is_duplicate == False: #Filter out PCR duplicates
name=read.query_name
names.append(name) #Add read name to list
for nam in names: #Loop over each read name, reads with no mate will only have one read for each name, will pairs will have 2 (or more)
counter=0
for mate in bam.fetch(): #For each name check BAM-file
if mate.query_name==nam: #Match name from list to name from BAM-file
counter+=1
if counter!=1: #If more than one read is given for name, put it list output
output.append(nam)
for out in output: #Convert the raw names in output to the full read and app to new BAM-file
for item in bam.fetch():
if item.query_name==out:
bam_out.write(item)
print "Total number of reads: " + str(len(names))
print "Number of reads after filtering out single reads: " + str(len(output))
bam.close()
bam_out.close()
print "done"
| true
|
aab6ac585ef5b16979dc30330b48391347697751
|
Python
|
Im-Siyoun/algorithm-learning
|
/graph searching/BFS/2644.py
|
UTF-8
| 625
| 3.125
| 3
|
[] |
no_license
|
from collections import deque
n = int(input())
matrix = [[0]*(n+1) for _ in range(n+1)]
a, b = map(int,input().split())
for i in range(int(input())):
x, y = map(int,input().split())
matrix[x][y] = matrix[y][x] = 1
visit = [0]*(n+1)
queue = deque()
def BFS(start):
chone = 0
queue.append(start)
visit[start] = chone
while queue:
node = queue.popleft()
chone = visit[node] + 1
for i in range(n+1):
if matrix[node][i] and not visit[i]:
queue.append(i)
visit[i] = chone
BFS(a)
if not visit[b]:
print(-1)
else:
print(visit[b])
| true
|
3127354bbd290d3f3b1581e655ecb2bc431eb7c7
|
Python
|
jithinsarath/python3basics
|
/fibonacci_03_memoization.py
|
UTF-8
| 540
| 4.09375
| 4
|
[
"Unlicense"
] |
permissive
|
# Implementing Memoization in An recursive function to improve performance
# reference https://towardsdatascience.com/memoization-in-python-57c0a738179a
fibonacci_cache = {}
def fibonacci(num):
if num in fibonacci_cache:
return fibonacci_cache[num]
if num == 1:
value = 1
elif num == 2:
value = 1
elif num > 2:
value = fibonacci(num - 1) + fibonacci(num - 2)
fibonacci_cache[num] = value
return value
for i in range(1, 201):
print("fibonacci({}) = ".format(i), fibonacci(i))
| true
|
7c76229bb82ee09e23229ef789b560e687ee9423
|
Python
|
ghdus4185/SWEXPERT
|
/N2115-1.py
|
UTF-8
| 688
| 3.546875
| 4
|
[] |
no_license
|
# 수도코드
# M개의 원소에서 1개 이상 최대 M개를 고르는 방법
M = 3
arr = [6, 1, 9]
# 비트연산을 활용한 부분집합 만들기
maxV = 0
for i in range(1, 2 ** M): # 이진수 생성
for j in range(M): # 0, 1, 2번 비트
s = 0 # 부분집합의 합
ss = 0
if i & (1 << j) != 0 and s + arr[j] <= c: # i 의 j번 비트가 1이고, 제한량 이하면
s += arr[j]
ss += arr[i] * arr[j] # 채취한 벌꿀의 가치
if maxV < ss:
maxV = ss
print(maxV)
# 결국 부분집합 합의 최대 값을 구하는 것
#첫째줄을 한사람이 고르고 두번째 사람은 그 아후줄에서 구함
| true
|
ac9f882dc03bcbf725863f49e8a3078045da9d8f
|
Python
|
Solomonwisdom/BasicTask
|
/section_two/python/leetcode/hard/longestconsecutivesequence/Solution.py
|
UTF-8
| 594
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
"""
Solution class
problemId 128
@author wanghaogang
@date 2018/6/29
"""
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if not nums or length == 0:
return 0
s = set(nums)
ans = 0
cur = 0
for x in nums:
if not x - 1 in s:
cur = 1
i = 1
while x + i in s:
cur += 1
i += 1
ans = max(ans, cur)
return ans
| true
|
d151cda9176e7e77964d6597f603ec08d711f60e
|
Python
|
optirg-39/webflask
|
/1. mysqlconnector/DDL_Commands.py
|
UTF-8
| 945
| 3.03125
| 3
|
[] |
no_license
|
## import library
import mysql.connector
## first crete a mysql server on your system or in cloud
## creating connection with credentials
conn = mysql.connector.connect(host="localhost", user="root", passwd="password")
## create the cursor
mycursor = conn.cursor()
## creating the database
mycursor.execute("CREATE DATABASE IF NOT EXISTS test_db")
## show the list of databases
mycursor.execute("SHOW DATABASES")
for i in mycursor:
print(i)
## drop the database
# mycursor.execute("DROP TABLE table_name")
## use the database
mycursor.execute("USE test_db")
## create table if not exists
mycursor.execute('CREATE TABLE IF NOT EXISTS student_table(id INTEGER PRIMARY KEY AUTO_INCREMENT,\
name TEXT, marks INTEGER, group_id INTEGER)')
## DROP TABLE
#sql = "DROP TABLE table_name"
# show tables
mycursor.execute("SHOW TABLES")
# print the result
for x in mycursor:
print(x)
# close the connection
conn.close()
| true
|
e4ce0443f2eb99953ac599eec36fa92173ddbfa4
|
Python
|
JosephLevinthal/Research-projects
|
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1649_2711.py
|
UTF-8
| 499
| 3.375
| 3
|
[] |
no_license
|
# dinheiro total
v_disp = int(input("digite seu saldo: "))
# para o RU
quant_ru = int(input("digite quantos tickets de ru ce quer: "))
# valor dos tickets do RU
v_ru = float(input("digite o valor do ticket do ru: "))
# para os passes de onibus
quant_p = int(input("digite quantos passes ce quer: "))
# valor dos passes
v_p = float(input("digite o valor do passe: "))
#################################
if v_disp > (quant_ru * v_ru) + (quant_p * v_p):
print("SUFICIENTE")
else:
print("INSUFICIENTE")
| true
|
274fb7b3eab8d75ea265fea07bc96579c4b82fcf
|
Python
|
MarkHershey/SATSolver
|
/2-SAT-Problem/src/cnf_parser.py
|
UTF-8
| 1,573
| 3.15625
| 3
|
[] |
no_license
|
from pathlib import Path
from typing import List, Tuple
from dgraph import DirectedGraph
Literal = int
Clause = Tuple[Literal]
def construct_implication_graph(cnf: str) -> DirectedGraph:
cnf = Path(cnf)
assert cnf.is_file()
formula: List[Clause] = parse_cnf_to_list(cnf)
implication_graph = DirectedGraph()
for clause in formula:
vertex_a, vertex_b = clause
implication_graph.add_edge(-vertex_a, vertex_b)
implication_graph.add_edge(-vertex_b, vertex_a)
return implication_graph
def parse_cnf_to_list(cnf: str) -> List[Clause]:
cnf = Path(cnf)
assert cnf.is_file()
with cnf.open() as f:
content = f.readlines()
formula: List[Clause] = []
clause = []
for line in content:
line = line.strip()
if line.startswith("c"):
continue
if line.startswith("p"):
continue
tokens = line.split()
for token in tokens:
token = token.strip()
if token != "":
literal = int(token)
else:
continue
if literal == 0:
if len(clause) == 2:
formula.append(tuple(clause))
clause = []
else:
print(f"WARNING: caluse size != 2; Error clause: {clause}")
else:
clause.append(literal)
return formula
if __name__ == "__main__":
from pprint import pprint
g = construct_implication_graph("CNFs/sample_simple_SAT.cnf")
pprint(g.graph)
| true
|
9ae3f4b43764e689fa633b341b8bbcc2ba18d74b
|
Python
|
sucman/Python100
|
/21-30/21.py
|
UTF-8
| 514
| 3.890625
| 4
|
[] |
no_license
|
# -*- coding:utf-8 -*-
'''
猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,
又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,
见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
'''
x = 1
for day in range(9, 0, -1):
a = (x + 1) * 2
x = a
print x
| true
|
f0555a43a5f9832021a78819c4ca6e50f4a1eef0
|
Python
|
gouthamgopal/Twitter-Bot
|
/bots/config.py
|
UTF-8
| 811
| 2.5625
| 3
|
[] |
no_license
|
import tweepy
import logging
import os
from auth import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET
logger = logging.getLogger()
"""
To run the config file succesfully you need to generate the below 4 keys from the twitter developer account for the app.
Just reuse the variables, or replace them with the key generated for succesful authentication and use of twitter api.
"""
def create_api():
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error creating API", exc_info=True)
raise e
logger.info("API created")
return api
| true
|
b0bd918c1717b3cdbc887868171bc3268419d3d1
|
Python
|
yanx27/DeepLearning-Study
|
/Keras_learning/2.初识神经网络.py
|
UTF-8
| 1,850
| 3.6875
| 4
|
[] |
no_license
|
''' 第一个神经网络示例'''
'''加载 Keras 中的 MNIST 数据集'''
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
'''网络架构'''
from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
'''编译步骤'''
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
'''
准备图像数据:
在开始训练之前,我们将对数据进行预处理,将其变换为网络要求的形状,并缩放到所有值都在 [0, 1] 区间。
比如,之前训练图像保存在一个 uint8 类型的数组中,其形状为(60000, 28, 28) ,取值区间为 [0, 255] 。
我们需要将其变换为一个 float32 数组,其形状为 (60000, 28 * 28) ,取值范围为 0~1
'''
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
'''准备标签'''
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
'''在 Keras 中这一步是通过调用网络的 fit 方法来完成的我们在训练数据上拟合(fit)模型'''
network.fit(train_images, train_labels, epochs=5, batch_size=128)
'''我们很快就在训练数据上达到了 0.989(98.9%)的精度。现在我们来检查一下模型在测试集上的性能'''
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
'''显示第 4 个数字'''
digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit.reshape((28,28)), cmap=plt.cm.binary)
plt.show()
| true
|
469e81f2995eac651b91f92d65b3fd2e954bc43c
|
Python
|
lilharry/project_euler
|
/python/problem4.py
|
UTF-8
| 574
| 4.25
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def ispalindrome(n):
stringy = str(n)
stringybackwards = stringy[::-1]
if stringy == stringybackwards:
return True
else:
return False
a = 100
b = 100
palindromes = []
while a<1000:
while b<1000:
if ispalindrome(a*b):
palindromes.append(a*b)
b+=1
b=100
a+=1
print(max(palindromes))
| true
|
94f89d40e78d7e393ebc046f680a72cb8e90c3bb
|
Python
|
alok-upadhyay/BITS-mail-relay
|
/bits-mail.py
|
UTF-8
| 1,256
| 2.6875
| 3
|
[] |
no_license
|
#!C:\Python27\python.exe -u
#!/usr/bin/env python
import smtplib
print "You can send mail from any BITS Student ID to any other Student ID of the form f20XXYYY.\n"
sndr = raw_input("Enter the sender's email ID (f20XXYYY): ")
print
rcpt = raw_input("Enter the recepient's email ID (f20XXYYY): ")
sndr = sndr.__add__("@bits-goa.ac.in")
rcpt = rcpt.__add__("@bits-goa.ac.in")
recepients = []
recepients.append(rcpt)
op = raw_input("Do you want to add more recepients?(y/n)")
if op is "y":
rcpt = raw_input("Enter the recepient's email ID (f20XXYYY): ")
rcpt = rcpt.__add__("@bits-goa.ac.in")
recepients.append(rcpt)
#print recepients
sub = raw_input("Enter the subject line: ")
body = raw_input("Enter the body of the message: ")
try:
final_body = "From: "+sndr+"\nTo: "+recepients[0]+", "+recepients[1]+"\nSubject: "+sub+"\nBody: "+body
except:
final_body = "From: "+sndr+"\nTo: "+recepients[0]+", "+"\nSubject: "+sub+"\nBody: "+body
#print final_body
try:
smtpObj = smtplib.SMTP('warrior.bits-goa.ac.in')
smtpObj.helo('warrior.bits-goa.ac.in')
smtpObj.sendmail(sndr, recepients, final_body)
smtpObj.quit()
print "Message submitted successfully!"
except:
print "Could not send the message, there might be some problem with the server!"
| true
|
f623c00432e3de5df8a207f101230269c70ebfda
|
Python
|
freephys/blog_examples
|
/python_multiprocessing_zeromq_vs_queue/multiproc_with_queue.py
|
UTF-8
| 570
| 2.921875
| 3
|
[] |
no_license
|
import sys
import time
from multiprocessing import Process, Queue
def worker(q):
for task_nbr in range(10000000):
message = q.get()
sys.exit(1)
def main():
send_q = Queue()
Process(target=worker, args=(send_q,)).start()
for num in range(10000000):
send_q.put("MESSAGE")
if __name__ == "__main__":
start_time = time.time()
main()
end_time = time.time()
duration = end_time - start_time
msg_per_sec = 10000000 / duration
print "Duration: %s" % duration
print "Messages Per Second: %s" % msg_per_sec
| true
|
57936e2d62b0cea71572bee7719f36d95879a835
|
Python
|
susan025/myproj01
|
/day01/day1_strUpLow.py
|
UTF-8
| 316
| 3.9375
| 4
|
[] |
no_license
|
if __name__ == '__main__':
str = "Gud Lak"
#将准备好的字符串转换成大写字符串
upperStr = str.upper()
print(upperStr)
#将准备好的字符串转换成小写字符串
lowerStr = str.lower()
print(lowerStr)
#字符串大小写转换-首字母大写
print(str.title())
| true
|
eea5f5622694e053ba7341420a6be776b0c3a556
|
Python
|
mayankmikin/ds_algo_prep
|
/Python 2019/Basics/countOccurence.py
|
UTF-8
| 163
| 2.96875
| 3
|
[] |
no_license
|
if __name__ == '__main__':
a=input();
Out={}
for i in a:
if i in Out:
Out[i]+=1
else:
Out[i]=1
print(Out)
| true
|
d803d62da5614db7df1427977922fd2bb0000ef3
|
Python
|
AronZeng/Internet-Traffic
|
/Data-Mining/Minning.py
|
UTF-8
| 7,423
| 2.75
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.tree import export_graphviz
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix
import mysql.connector
import csv
from six import StringIO
from IPython.display import Image
import pydotplus
def main():
username = input("Enter your username\n")
password = input("Enter your password\n")
cnx = mysql.connector.connect(username=username,
password= password,
host='localhost',
database='internet_traffic')
cursor = cnx.cursor(dictionary=True)
print("Fetching data from database...")
#query the data we want from the database
queryString = "select iat_mean, fwd_packets, bwd_packets, duration, label, bytes_per_second, syn_flag_count, rst_flag_count, psh_flag_count, ack_flag_count, urg_flag_count, cwe_flag_count, ece_flag_count, active_time_mean, idle_time_mean from (((((flow inner join flowbytes on flow.id = flowbytes.flow_id) inner join flowflags on flow.id = flowflags.flow_id) inner join flowiat on flow.id = flowiat.flow_id) inner join flowinfo on flow.id = flowinfo.flow_id) inner join flowpackets on flow.id = flowpackets.flow_id) inner join protocol on flow.protocol_id = protocol.id"
cursor.execute(queryString)
rows = []
for i in cursor:
rows.append(i)
with open('mining.csv', 'w', newline='') as f:
fieldnames = []
for i in cursor.column_names:
fieldnames.append(i)
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
print("Data successfully fetched and recorded in csv file...")
#import the data
dataframe = pd.read_csv("mining.csv", header=0)
#used to check if the dataframe loaded the data properly
dataframe.columns = ['IATMean',
'ForwardPackets',
'BackwardPackets',
'Duration',
'Label',
'BytesPerSecond',
'SYNFlagCount',
'RSTFlagCount',
'PSHFlagCount',
'ACKFlagCount',
'URGFlagCount',
'CWEFlagCount',
'ECEFlagCount',
'ActiveTimeMean',
'IdleTimeMean']
#display the data types
print(dataframe.head())
print(dataframe.dtypes)
#print unique values for each column
for columnName in dataframe.columns:
print(columnName + ":")
print(dataframe[columnName].unique())
dataframe = dataframe.fillna({columnName: -1})
#split dataframe into independent and dependent
X = dataframe.drop('Label', axis=1).copy()
y = dataframe['Label'].copy()
#build the preliminary clasification tree
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
clf = DecisionTreeClassifier(random_state=42, max_depth=5)
clf = clf.fit(X_train, y_train)
# plot the preliminary tree
dot_data = StringIO()
export_graphviz(clf,
filled=True, rounded=True,
special_characters=True,feature_names = X.columns,class_names=['BENIGN','DDoS'],out_file=dot_data)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_png('preliminary.png')
Image(graph.create_png())
#create the confusion matrix for the preliminary decision tree
disp = plot_confusion_matrix(clf, X_test, y_test, display_labels=["BENIGN", "DDoS"])
plt.show()
#cost complexity pruning
#goal is to find the best pruning parameter alpha which controls how much pruning happens
path = clf.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas = path.ccp_alphas
ccp_alphas = ccp_alphas[:-1]
clfs = [] #we put decisions trees into here
print("Cost Complexity Pruning")
for ccp_alpha in ccp_alphas:
print("make tree for alpha")
clf = DecisionTreeClassifier(random_state=0, ccp_alpha=ccp_alpha, max_depth=5)
clf = clf.fit(X_train, y_train)
clfs.append(clf)
train_scores = [clf.score(X_train,y_train) for clf in clfs]
test_scores = [clf.score(X_test,y_test) for clf in clfs]
fig, ax = plt.subplots()
ax.set_xlabel("alpha")
ax.set_ylabel("Accuracy")
ax.set_title("Accuracy vs alpha for training and testing sets")
ax.plot(ccp_alphas, train_scores, marker='o', label="train", drawstyle="steps-post")
ax.plot(ccp_alphas, test_scores, marker='o', label="test", drawstyle="steps-post")
ax.legend()
plt.show()
#there could have been many ways we divide the training and testing dataset
#we use 10-fold cross validation to see if we used the best training and testing dataset
#i.e one set of data may have a different optimal alpha
#demonstrate using a single alpha with different data sets
#we see that this alpha is sensitive to the datasets
print("Cross validation")
clf = DecisionTreeClassifier(random_state=42, ccp_alpha=0.000005, max_depth=5)
scores = cross_val_score(clf, X_train, y_train, cv=10)
df = pd.DataFrame(data={'tree': range(10), 'accuracy': scores})
df.plot(x='tree', y='accuracy', marker='o', linestyle='--')
plt.show()
#use cross validation to find optimal value for ccp_alpha
alpha_loop_values = []
print("10-fold for more than one alpha")
#for each alpha candidate, we run a 10-fold cross validation
for ccp_alpha in ccp_alphas:
clf = DecisionTreeClassifier(random_state=0, ccp_alpha=ccp_alpha, max_depth=5)
scores = cross_val_score(clf, X_train, y_train, cv=10)
alpha_loop_values.append([ccp_alpha, np.mean(scores), np.std(scores)])
print("Finished one alpha candidate")
#graph the mean and standard deviation of the scores for each candidate alpha
alpha_results = pd.DataFrame(alpha_loop_values, columns=['alpha','mean_accuracy', 'std'])
alpha_results.plot(x='alpha', y='mean_accuracy', yerr='std', marker='o', linestyle='--')
plt.show()
#this part is used to find the exact optimal alpha value used to create the optimal pruned classification tree
print("optimal alpha value")
optimal_alpha = alpha_results[(alpha_results['alpha'] > 0) & (alpha_results['alpha'] < 0.0001)]
print(optimal_alpha)
#optimal pruned tree
clf = DecisionTreeClassifier(random_state=42, ccp_alpha=2.247936 * (10**(-10)), max_depth=5)
clf = clf.fit(X_train, y_train)
dot_data = StringIO()
export_graphviz(clf,
filled=True, rounded=True,
special_characters=True,feature_names = X.columns,class_names=['BENIGN','DDoS'],out_file=dot_data)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_png('best.png')
Image(graph.create_png())
#draw a confusion matrix for the optimal pruned tree
disp = plot_confusion_matrix(clf, X_test, y_test, display_labels=["BENIGN", "DDoS"])
print(disp)
plt.show()
main()
| true
|
3d33333fa636668a62bdf09661994cca1b6ab48e
|
Python
|
jag-prabhakaran/genetic-algorithm-for-stock-prediction
|
/.ipynb_checkpoints/nn-checkpoint.py
|
UTF-8
| 165
| 2.6875
| 3
|
[] |
no_license
|
import tensorflow as tf
mnist = tf.keras.datasets.mnist # (dataset of 28x28 images of handwritten digits 0-9)
(x_train, y_train), (x_test, y_test) = mnist.load_data
| true
|
cb153534555e62d1ad773ec541823d1fc519c7cd
|
Python
|
amoliu/gpplib
|
/GliderDataPython/ReadGliderLogfiles.py
|
UTF-8
| 5,237
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import gpplib
from gpplib.Utils import *
import re
class GliderConsoleLogFileReader(object):
def __init__(self,**kwargs):
self.LocPattern = re.compile("[ ]*(GPS|DR)[ ]*(TooFar|Location|Invalid)[ :]+([0-9\\.\\-]*) N ([0-9\\.\\-]*) E.*")
self.SensorPattern = re.compile("[ ]*sensor:[ ]*([a-z_]+)(?:\\(([a-zA-Z]+)\\))*[ ]*=[ ]*([0-9\\.-]+)[ ]*(lat|lon|enum)*.*")
self.MissionPattern = re.compile("MissionName:([a-zA-Z0-9\\.\\-\\_]*) MissionNum:([a-zA-Z0-9\\.\\-\\_]*) \\(([0-9\\.]*)\\)")
self.WaypointPattern = re.compile("[ ]*Waypoint: \\(([0-9\\.\\-]*),([0-9\\.\\-]*)\\) Range: ([0-9\\.]*)([a-zA-Z]*), Bearing: ([0-9\\.\\-]*)deg, Age: (.*)")
self.BecausePattern = re.compile("[ ]*Because:([a-zA-Z0-9 ]*) \\[(.*)\\]")
self.VehiclePattern = re.compile("[ ]*Curr Time: (.*) MT:[ ]*([0-9\\.]*)")
self.TimePattern = re.compile("[ ]*Curr Time: (.*) MT:[ ]*([0-9\\.]*)")
def getGpsDegree(self,webb_gps_str):
p=webb_gps_str.find(".")
d=float(webb_gps_str[0:p-2])
return d+cmp(d,0)*float(webb_gps_str[p-2:len(webb_gps_str)])/60
def GetGpsLocation(self,m,locType="Location"):
if(m and m.group(1) == "GPS" and m.group(2) == locType ):
#print m.groups()
lat = self.getGpsDegree(m.group(3))
lon = self.getGpsDegree(m.group(4))
return (lat,lon)
else:
return None
def GetSensorValue(self,m,sensorType="m_battery"):
if(m.group(1) == sensorType ):
return float(m.group(3))
else:
return None
def ParseData(self,msg):
''' ParseData = find useful information in the given data file '''
g = {}
if len(msg)>0:
for line in msg:
mL, mS, mM, mW, mB, mV, mT = \
self.LocPattern.match(line), self.SensorPattern.match(line), self.MissionPattern.match(line), \
self.WaypointPattern.match(line),self.BecausePattern.match(line),self.VehiclePattern.match(line), \
self.TimePattern.match(line)
if mL:
gliderLoc = self.GetGpsLocation(mL)
if gliderLoc != None:
g['lat'],g['lon']=gliderLoc
elif mS:
battery = self.GetSensorValue( mS,'m_battery' )
vacuum = self.GetSensorValue( mS, 'm_vacuum' )
if battery: g['battery']=battery
if vacuum: g['vacuum'] =vacuum
elif mW:
g['wp_lat'], g['wp_lon'], g['wp_range'], g['wp_bearing'], g['wp_time'] = \
self.getGpsDegree(mW.group(1)),self.getGpsDegree(mW.group(2)), \
float(mW.group(3)),float(mW.group(5)),0
elif mB:
g['because'] = mB.group(1)
elif mV:
g['name'] = mV.group(1)
elif mT:
g['time'] = time.strptime(m.group(1),'%a %b %d %H:%M:%S %Y')
else:
print 'Empty Message/File.'
return g
def GetLogFileListForGliderBetweenDates(self,glider_name,dt1,dt2):
''' Get a list of all log files after a particular date.
'''
self.gftp = GliderFTP('/var/opt/gmc/gliders/'+glider_name+'/logs/')
dir_list = self.gftp.GetSimpleDirList('')
filtered_list = []
for file in dir_list[0]:
m = re.match('%s_modem_([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2}).log'%(glider_name),file)
if m:
fyy,fmm,fdd,fhr,fmi,fse = \
int(m.group(1)),int(m.group(2)),int(m.group(3)),int(m.group(4)),int(m.group(5)),int(m.group(6))
file_dt = datetime.datetime(fyy,fmm,fdd,fhr,fmi,fse)
if file_dt>=dt1 and file_dt<=dt2:
filtered_list.append(file)
#print self.gftp.f.dir()
self.gftp.Close()
return filtered_list
def ReadLogFileContents(self,glider_name,remoteFileName,tmp_log_file_dir = 'logs/'):
self.gftp = GliderFTP('/var/opt/gmc/gliders/'+glider_name+'/logs/')
import os, sys
try:
os.mkdir(tmp_log_file_dir)
except OSError as (errno,strerror):
pass
lines_in_file = None
localFileName = tmp_log_file_dir+'%s'%(remoteFileName)
print 'Local file: %s'%(localFileName)
if self.gftp.DoesFileExist(remoteFileName)==True:
self.gftp.ReadFile(localFileName,remoteFileName)
f = open(localFileName,'r')
lines_in_file = f.readlines()
f.close()
self.gftp.Close()
return lines_in_file
gclfr = GliderConsoleLogFileReader()
f = open('rusalka_modem_20120719T154158.log','r')
msg = f.readlines()
f.close()
g = gclfr.ParseData(msg)
print g
download_dir = 'logs/'
dt1 = datetime.datetime(2012,7,18,0,0)
dt2 = datetime.datetime.utcnow()
fileList = gclfr.GetLogFileListForGliderBetweenDates('rusalka', dt1, dt2)
for file in fileList:
lines = gclfr.ReadLogFileContents('rusalka', file )
| true
|
d193c06ad6135d7989f4f3586d39db29734cb759
|
Python
|
SecondToGod/machine-learning
|
/CV/cvthreshold.py
|
UTF-8
| 1,674
| 2.78125
| 3
|
[] |
no_license
|
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('./test.jpg',0)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
imgs = [img,thresh1,thresh2,thresh3,thresh4,thresh5]
titles = ['origin','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
# for i in range(6):
# plt.subplot(2,3,i+1)
# plt.imshow(imgs[i],'gray')
# plt.title(titles[i])
# plt.show()
# 自适应二值化
# 加上中值滤波平滑图像
img2 = cv2.medianBlur(img,5)
# cv2.namedWindow('blur',cv2.WINDOW_NORMAL)
# cv2.imshow('blur',img2)
th1 = cv2.adaptiveThreshold(img2,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
th2 = cv2.adaptiveThreshold(img2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
# plt.subplot(1,3,1),plt.imshow(img2,'gray'),plt.title('medianBlur')
# plt.subplot(1,3,2),plt.imshow(th1,'gray'),plt.title('mean')
# plt.subplot(1,3,3),plt.imshow(th2,'gray'),plt.title('gaussian')
# plt.show()
# otsu 二值化
ret,th3 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
img3 = cv2.GaussianBlur(img,(5,5),0)
ret,th4 = cv2.threshold(img3,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
plt.figure()
plt.subplot(1,3,1),plt.imshow(img3,'gray'),plt.title('GaussianBlur')
plt.subplot(1,3,2),plt.imshow(th3,'gray'),plt.title('otsu')
plt.subplot(1,3,3),plt.imshow(th4,'gray'),plt.title('gaussian+otsu')
plt.show()
plt.figure()
plt.hist(th4.ravel(),256)
plt.show()
cv2.waitKey(0)
| true
|
d1f80ebc890605a60df958f1678ad176c603a632
|
Python
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_121/186.py
|
UTF-8
| 630
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
n=int(raw_input())
def solver(fulle,e,r,n,v):
max=0
if n==1:
return e*v[0]
else:
tempi=0
for i in xrange(0,e+1):
if e-i+r>=fulle:
temp = solver(fulle,fulle,r,n-1,v[1:])+i*v[0]
else:
temp = solver(fulle,e-i+r,r,n-1,v[1:])+i*v[0]
if temp>max:
max=temp
return max
for i in xrange(0,n):
s=raw_input()
(e,r,n)=[int(k) for k in s.split(' ')]
s=raw_input()
v=[int(k) for k in s.split(' ')]
print('Case #%d: %d' % (i+1, solver(e,e,r,n,v)))
| true
|
1670c52ac96e3693011daf8e49b9d0a3971cd9fb
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p02260/s739885042.py
|
UTF-8
| 407
| 3.265625
| 3
|
[] |
no_license
|
def selection_sort(A):
swap = 0
for i in range(len(A)):
minj = i
for j in range(i,len(A)):
if A[j] < A[minj]:
minj = j
if minj != i:
A[i],A[minj] = A[minj],A[i]
swap += 1
return swap
if __name__=='__main__':
N=int(input())
A=list(map(int,input().split()))
swap = selection_sort(A)
print(*A)
print(swap)
| true
|
e9c2222c8c584dabd6ce65202850ab91dbecd2a0
|
Python
|
geoxliu/Python_Crash_Course_all
|
/part_2/name_cases.py
|
UTF-8
| 841
| 3.515625
| 4
|
[] |
no_license
|
full_name = "eric"
message = "Hello " + full_name + "," + "would you like to learn some Python today?"
print(message)
full_name = "eric"
message = "Hello " + full_name.title() + "," + "would you like to learn some Python today?"
print(message)
full_name = "eric"
message = "Hello " + full_name.upper() + "," + "would you like to learn some Python today?"
print(message)
fmmous_person = "Albert Einstein "
message = fmmous_person + "once said," + " A person who never made a mistake never tried anything new."
print(message)
full_name = " Felix Zhang "
print(full_name)
print(full_name.lstrip())
print(full_name.rstrip())
print(full_name.strip())
message = 3 * 2
print(message)
message = 3 ** 2
print(message)
message = 3 / 2
print(message)
message = 3 + 2
print(message)
message = 3 + 2 * 4
print(message)
message = (3 + 2) * 4
print(message)
| true
|
b8b251cf13b8fda630910dd4a531d38831c2460e
|
Python
|
TamNguyenVanTam/ReinforcementLearning
|
/source/models/framework/actor_critic.py
|
UTF-8
| 2,712
| 2.75
| 3
|
[] |
no_license
|
"""
Defining Actor Critic Framework
Authors: TamNV
===============================
"""
import tensorflow as tf
import tensorflow.contrib.slim as slim
class ActorCritic:
"""
Actor Critic Framework
"""
def __init__(self,
num_obser_dim,
num_action_dim,
act_backbone,
cri_backbone):
"""
Initial Method
+ Params: num_obser_dim: Integer
+ Params: num_action_dim: Integer
+ act_backbone: Class Name
+ cri_backbone: Class Name
+ Returns: None
"""
self._num_obser_dim = num_obser_dim
self._num_action_dim = num_action_dim
self._act_backbone = act_backbone
self._cri_backbone = cri_backbone
self._states = tf.compat.v1.placeholder(dtype=tf.float32,
shape=(None, self._num_obser_dim))
self._next_states = tf.compat.v1.placeholder(dtype=tf.float32,
shape=(None, self._num_obser_dim))
self._actions = tf.compat.v1.placeholder(dtype=tf.float32,
shape=(None, self._num_action_dim)) # One-Hot-Vector Convention
self._rewards = tf.compat.v1.placeholder(dtype=tf.float32, shape=(None,))
self._gamma = tf.compat.v1.placeholder(dtype=tf.float32, shape=None)
self._cri_lr = tf.compat.v1.placeholder(dtype=tf.float32, shape=None)
self._act_lr = tf.compat.v1.placeholder(dtype=tf.float32, shape=None)
def init_actor_critic(self):
"""
Create An Actor and a Critic
"""
self._actor = self._act_backbone(in_dims=self._num_obser_dim,
out_dims=self._num_action_dim,
name="actor")
self._critic = self._cri_backbone(in_dims=self._num_obser_dim,
out_dims=1,
name="critic")
"""
Get Actor's trainable variables and Critic's trainable variables
"""
self._act_variables = self._actor._train_vars
self._cri_variables = self._critic._train_vars
print("The Number of Variables for Actor: {}".format(len(self._act_variables)))
print("The Number of Variables for Critic: {}".format(len(self._cri_variables)))
def inference(self):
# Perform Critic Phase
gt = self._critic(self._next_states) * self._gamma + self._rewards
td_error = (gt - self._critic(self._states)) ** 2
self._cri_loss = tf.reduce_mean(td_error)
# Perform Actor Phase
self._act_probs = self._actor(self._states)
log_action = tf.reduce_sum(tf.nn.log_softmax(self._act_probs, axis=-1) * self._actions, axis=-1)
self._act_loss = tf.reduce_mean(-td_error * log_action)
self._act_op = tf.compat.v1.train.AdamOptimizer(self._act_lr).minimize(self._act_loss, var_list=self._act_variables)
self._cri_op = tf.compat.v1.train.AdamOptimizer(self._cri_lr).minimize(self._cri_loss, var_list=self._cri_variables)
self._losses = [self._act_loss, self._cri_loss]
self._ops = [self._act_op, self._cri_op]
| true
|
855d11f7e9fd59425b0cb48dea2b53a859e40591
|
Python
|
quinkennedy/generative-zine-invite
|
/script_zine/mixed_test.py
|
UTF-8
| 647
| 2.875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from xml.parsers import expat
generative = []
elem_stack = []
def start_element(name, attributes):
if name == 'var' and elem_stack[-1] == 'command':
generative[-1] += attributes['key'].upper()
elif name == 'command':
generative.append('')
elem_stack.append(name)
def end_element(name):
elem_stack.pop()
def char_data(data):
if elem_stack[-1] == 'command':
generative[-1] += data
parser = expat.ParserCreate()
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.CharacterDataHandler = char_data
with open('zine.xml', 'rb') as f:
parser.ParseFile(f)
print(generative)
| true
|
dca53d7aef775786b56616b95e5747394f0dd738
|
Python
|
jakkularamesh/Innomatics_Internship_APR_21
|
/Day 2/Set .union() Operation.py
|
UTF-8
| 196
| 2.875
| 3
|
[] |
no_license
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
n1=set(input().split())
m=int(input())
m1=set(input().split())
u=n1.union(m1)
print(len(u))
| true
|
8a42eae59a7871d231b3735a35f442dc565d9291
|
Python
|
roadworrier/s_tools
|
/skyptool.py
|
UTF-8
| 5,034
| 2.640625
| 3
|
[] |
no_license
|
#!/usr/bin/python
#
# This started out as the code from
# https://pentesterscript.wordpress.com/2013/08/07/extract-contacts-call-log-message-from-skype-database/
# which required some indentation, and then some other snippets were added to make this do what I needed:
# List the date, time, duration of all skype calls, with the initator known.
#
# What does this do? Prints something like this:
#
#
#Timestamp: 2018-08-01 19:10:41 From live:someones_skypename :
# <name>Someone's Actual Name</name>
# <name>My Name</name>
#Timestamp: 2018-08-01 19:13:54 From my_skype_username :
# <name>Someone's Actual Name</name>
# <name>my_skype_username</name>
#Skype call duration: 0:03:13
import sqlite3
import optparse
import os
import datetime
import xml.etree.cElementTree as et
import re
from HTMLParser import HTMLParser
#https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup
from bs4 import BeautifulSoup
def printProfile(skypeDB):
conn = sqlite3.connect(skypeDB)
c = conn.cursor()
c.execute("SELECT fullname, skypename, city, country, \
datetime(profile_timestamp,'unixepoch') FROM Accounts;")
for row in c:
print '[*] - Found Account -'
print '[+] User : '+str(row[0])
print '[+] Skype Username : '+str(row[1])
print '[+] Location : '+str(row[2])+','+str(row[3])
print '[+] Profile Date : '+str(row[4])
def printContacts(skypeDB):
conn = sqlite3.connect(skypeDB)
c = conn.cursor()
c.execute("SELECT displayname, skypename, city, country,\
phone_mobile, birthday FROM Contacts;")
for row in c:
print '\n[*] - Found Contact -'
try:
print '[+] User : ' + str(row[0])
except:
pass
print '[+] Skype Username : ' + str(row[1])
if str(row[2]) !='' and str(row[2]) != 'None':
print '[+] Location : ' + str(row[2]) + ',' + str(row[3])
if str(row[4]) != 'None':
print '[+] Mobile Number : ' + str(row[4])
if str(row[5]) != 'None':
print '[+] Birthday : ' + str(row[5])
def printCallLog(skypeDB):
conn = sqlite3.connect(skypeDB)
c = conn.cursor()
c.execute("SELECT datetime(begin_timestamp,'unixepoch'), \
identity FROM calls, conversations WHERE \
calls.conv_dbid = conversations.id;"
)
print '\n[*] - Found Calls -'
for row in c:
print '[+] Time: '+str(row[0])+\
' | Partner: '+ str(row[1])
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag != 'duration':
return
#print "Encountered a start tag:", tag
#for name, value in attributes
def handle_endtag(self, tag):
print "Encountered an end tag :", tag
def handle_data(self, data):
print "Encountered some data :", data
def printMessages(skypeDB):
conn = sqlite3.connect(skypeDB)
c = conn.cursor()
c.execute("SELECT datetime(timestamp,'unixepoch'), \
dialog_partner, author, body_xml FROM Messages;")
print '\n[*] - Found Messages -'
time_text = "Timestamp: "
time_int = 0
prev_time_int = 0
for row in c:
try:
if 'partlist' not in str(row[3]):
if str(row[1]) != str(row[2]):
msgDirection = 'To ' + str(row[1]) + ': '
else:
msgDirection = 'From ' + str(row[2]) + ' : '
if str(row[3]).startswith('<partlist'):
soup = BeautifulSoup(str(row[3]))
call_length=soup.duration
time_int=int(call_length.string)
#print "call ln" + call_length.string
print time_text + str(row[0]) + ' ' + msgDirection
cleaner_string = str(row[3])
cleaner_string = re.sub('.*part.*\n', "", cleaner_string)
cleaner_string = re.sub('.*part.*', "", cleaner_string)
cleaner_string = re.sub('.*duration.*\n', "", cleaner_string)
print cleaner_string.rstrip('\n')
if prev_time_int == time_int:
print "Skype call duration: " + str(datetime.timedelta(seconds=time_int)) + "\n"
prev_time_int = time_int
except:
pass
def main():
parser = optparse.OptionParser("usage %prog "+\
"-p " + """\nSpecify skype profile path after -p\n
The locations of the Skype database in different operating systems are\n
In windows C:\\Users\user_name\AppData\Roaming\Skype\skype_user_name\n
In mac Users/user_name/Library//Application/Support/Skype/skype_user_name\n
In Linux /root/.Skype/skype_user_name """)
parser.add_option('-p', dest='pathName', type='string',\
help='Specify Skype profile path')
(options, args) = parser.parse_args()
pathName = options.pathName
if pathName == None:
print parser.usage
exit(0)
elif os.path.isdir(pathName) == False:
print '[!] Path Does Not Exist: ' + pathName
exit(0)
else:
print "Running skyptool.py found here: https://github.com/roadworrier/s_tools"
skypeDB = os.path.join(pathName, 'main.db')
if os.path.isfile(skypeDB):
printProfile(skypeDB)
#printContacts(skypeDB)
#printCallLog(skypeDB)
printMessages(skypeDB)
else:
print '[!] Skype Database '+\
'does not exist: ' + skpeDB
if __name__ == '__main__':
main()
| true
|
1bed2c4c594e17a90f3fe5153affd68aee7f34d5
|
Python
|
michael-lennox-wong/CS50W-Projects
|
/Project3/add_menu_items.py
|
UTF-8
| 3,251
| 2.625
| 3
|
[] |
no_license
|
from orders.models import Salad, Pasta, DinnerPlatter, Sub1, Sub2, Pizza
from orders.models import MenuItem
for x in Salad.SALAD_CHOICES:
f = Salad(salad_type=x[0])
f.save()
for x in Pasta.PASTA_CHOICES:
f = Pasta(pasta_type=x[0])
f.save()
for platter in DinnerPlatter.DINNER_PLATTER_CHOICES:
for s in DinnerPlatter.SIZES:
f = DinnerPlatter(size=s[0],platter_type=platter[0])
f.save()
# Sub1
def bin_str(n):
if n > 31:
return 'Input is too big'
else:
s = str(bin(n))[2:]
if len(s) < 5:
k = 5 - len(s)
for i in range(k):
s = '0'+s
return s
def bin_size(s):
if s[0]=='0':
return 'S'
else:
return 'L'
def bin_mushrooms(s):
return bool(int(s[1]))
def bin_green_peppers(s):
return bool(int(s[2]))
def bin_onions(s):
return bool(int(s[3]))
def bin_extra_cheese(s):
return bool(int(s[4]))
for n in range(32):
s = bin_str(n)
for st in Sub1.SUB1_CHOICES:
f = Sub1(sub_type=st[0])
f.size = bin_size(s)
f.mushrooms = bin_mushrooms(s)
f.green_peppers = bin_green_peppers(s)
f.onions = bin_onions(s)
f.extra_cheese = bin_extra_cheese(s)
f.save()
# Sub2
for st in ['H', 'C', 'FC', 'V']:
for size in ['S', 'L']:
for extra_cheese in [False, True]:
f = Sub2(sub_type=st)
f.size = size
f.extra_cheese = extra_cheese
f.save()
for extra_cheese in [False, True]:
f = Sub2(sub_type='SPO')
f.size = 'L'
f.extra_cheese = extra_cheese
f.save()
# Pizza
TWO_TOPPINGS = []
for i, top1 in enumerate(Pizza.TOPPING_CODES):
for j, top2 in enumerate(Pizza.TOPPING_CODES):
if j >= i:
TWO_TOPPINGS.append(top1 + top2)
THREE_TOPPINGS = []
for i, top1 in enumerate(Pizza.TOPPING_CODES):
for j, top2 in enumerate(Pizza.TOPPING_CODES):
if j >= i:
for k, top3 in enumerate(Pizza.TOPPING_CODES):
if k >= j:
THREE_TOPPINGS.append(top1 + top2 + top3)
ALL_TOPS = [''] + Pizza.TOPPING_CODES + TWO_TOPPINGS + THREE_TOPPINGS
for top in ALL_TOPS:
for size in ['S', 'L']:
for p_type in ['R', 'Si']:
f = Pizza(pizza_type=p_type,pizza_top=top)
f.size = size
f.save()
for size in ['S', 'L']:
for p_type in ['R', 'Si']:
f = Pizza(pizza_type=p_type,pizza_top='Spec')
f.size = size
f.save()
### Add everything to MenuItem
for class0 in [Salad, Pasta, DinnerPlatter, Sub1, Sub2, Pizza]:
for item in class0.objects.all():
f = MenuItem(name=item, price=item.price())
f.save()
### Forgot to put in type before (use Pizza as default)
for symb, class0 in [('Sa', Salad), ('S1', Sub1), ('S2', Sub2), \
('Pa', Pasta), ('DP', DinnerPlatter)]:
for item in class0.objects.all():
f = MenuItem(name=item, price=item.price(), type=symb)
f.save()
### Add MenuItem ids to other class instances
for class0 in [Pizza, DinnerPlatter, Sub1, Sub2]:
for item in class0.objects.all():
item.menu_item_id = MenuItem.objects.get(name=str(item))
| true
|
a78b94962b0930abb59efdfeeaf85ad21acc86f6
|
Python
|
doshmajhan/Xenoblast
|
/receiver.py
|
UTF-8
| 4,902
| 3.453125
| 3
|
[] |
no_license
|
import bitarray
import time
from unitcomp import unitcomp
THRESHOLD = 0.009
"""
Run unit comp 100 times to establish
the average amount of time it should take to run
returns the average time taken to run unitcomp
"""
def initialization():
count = 0
total_time = 0
while(count < 100):
total_time += unitcomp()
count += 1
print("Total time taken: {}".format(total_time))
avg_time = total_time / count
return avg_time
"""
Runs an indefinite operation to consistently run
unitcomp until it is over 0.03 secs of the usual run time.
If it is seen to running over the run time for at least 1.5 seconds
then it means the sender is about to transmit
:param avg_time: the average time unitcomp took to ran to compare against
"""
def synchronization(avg_time):
while(True):
start_time = time.time()
# Get time taken for unitcomp
time_taken = unitcomp()
# Check if the time taken is greater than average
if time_taken > (avg_time + THRESHOLD):
#print("Higher load noticed, checking if sync is in progress")
#print(time_taken - (avg_time + THRESHOLD))
# Time is greater than average so
# see if it stays that way for at least 1.5s
while time_taken > (avg_time + THRESHOLD):
time_taken = unitcomp()
end_time = time.time()
# check if the time it lasted was at least 1.5 seconds
if (end_time - start_time) >= 0.007:
print("Lasted atleast .007")
# time was at least 1.5 seconds so
# we can assume the sender is syncing with us
# so break out of this function
return
print("Not synced, only lasted: {}".format(end_time - start_time))
# time was not long enough for sync phase
# so keep looking
continue
"""
Confirms that the rise in CPU load occured from the sender.
Will determine how many times unitcomp can be run in 1 second.
If during this period, any of the execution times of unitcomp
is greater than the precalculated average (plus the threshold)
then it is determine that something else was causing the CPU load
on the system, not the sender.
:param avg_time: the average time unitcomp should execute for
:returns zero if it finds it was a false, sync otherwise
it runs the count of unitcomp execs
"""
def confirmation(avg_time):
count = 0
# Run for 1 second
end_time = time.time() + 1
while time.time() <= end_time:
time_taken = unitcomp()
count += 1
if time_taken > (avg_time + THRESHOLD):
print(time_taken)
# High CPU load is still occuring meaning
# it wasn't the sender creating it
return 0
return count
"""
Attempts to recieve 64 bits of data from sender.
Will measure number of unitcomp executions during 1 second.
If it is less than 90% of standard number, a 1 is recieved.
Otherwise a 0 is recieved. It will pause for 1 second between
bits to prevent VCPU state as being viewed as "over".
"""
def recieve_data(standard_number):
num_bits = 0
data = ""
while num_bits < 32:
# Run for 1 second
end_time = time.time() + 1
count = 0
while time.time() <= end_time:
unitcomp()
count += 1
if count < (standard_number * 0.95):
print("Recieved 1")
# It was less than 90% so it was a 1
data += "1"
else:
print("Recieved 0")
data += "0"
num_bits += 1
# pause for 1 second
time.sleep(1)
return data
if __name__ == '__main__':
# INIT
print("Starting initialization")
avg_time = initialization()
print("Average execution time: {}".format(avg_time))
confirmed = False
standard_number = 0
while not confirmed:
# SYNC
print("Listening for synchronization phase")
synchronization(avg_time)
print("Synchronization complete")
# Sleep after sync
time.sleep(1)
# CONFIRM
print("Confirming the higher load is from the sender")
standard_number = confirmation(avg_time)
print("Standard number: {}".format(standard_number))
if standard_number > 0:
confirmed = True
# Pause to reset state of vcpus
time.sleep(1)
print("Recieving data")
# RECIEVE DATA
data = recieve_data(standard_number)
# convert bit string to hex string then to regular string
print(data)
phrase = bitarray.bitarray(data).tobytes().decode('utf-8')
print("Recieved data: {}".format(phrase))
| true
|
3f74bb7d27bc9d1b89aa57792042ea8de9e6f542
|
Python
|
murali-kotakonda/PythonProgs
|
/PythonBasics1/exception1/TestEx22.py
|
UTF-8
| 182
| 2.875
| 3
|
[] |
no_license
|
a = False
try:
while not a:
f_n = input("Enter file name")
i_f = open(f_n, 'r')
except:
print("Input file not found")
print("Bye")
| true
|
0aca5d152a04dbacf92d3507594764130f330e63
|
Python
|
Chouffe/az
|
/services/data_handling.py
|
UTF-8
| 2,988
| 2.828125
| 3
|
[] |
no_license
|
import numpy as np
import utils
def api_preprocess_datapoint(data):
ddata = data.copy()
result = ddata.pop('result')
return result, ddata
# TODO: Test it
def dataset_to_matrix(schema, dataset):
"""Given a schema and a dataset, it returns the
training set and target set for the ml fitting
eg.
schema = {
'a': {'default': 0},
'b': {'default': 0},
'c': {'default': 0}}
dataset = [
{'a': 0, 'b': 1, '_obj': 3.3},
{'a': 1, 'b': 0, '_obj': 0.3},
{'a': 1, 'b': 0, 'c': 1, '_obj': 7.3}]
"""
keys = sorted(schema.keys())
defaults = [schema[k]['default'] for k in keys]
train = []
target = []
for point in dataset:
row = []
point_has_data = False
for key, default in zip(keys, defaults):
if key in point:
point_has_data = True
row.append(point[key])
else:
row.append(default)
# ignoring data for old experiments,
# should probably prune
if point_has_data:
train.append(row)
target.append(point["_obj"])
return np.array(train), np.array(target)
def datapoints_to_dataset(datapoints):
"""Given datapoints from the db, it returns the dataset
{feature1: value1, ..., featureN: valueN, _obj: mu}"""
point_dict = utils.process_datapoints(datapoints)
return [dict(d['features'].items() + {'_obj': d['mu']}.items())
for _, d in point_dict.items()]
def datapoints_to_graph_results(datapoints, features):
point_dict = utils.process_datapoints(datapoints)
tmp = [dict(m['features'].items() +
{'time': sorted(m['time'])[-1]}.items())
for _, m in point_dict.items()]
tmp = sorted(tmp, key=lambda d: d['time'])
results = {f: [] for f in features}
for e in tmp:
for f in features:
if f in e:
results[f].append(e[f])
else:
results[f].append(features[f]['default'])
return results
def datapoints_to_cost_function_result(datapoints, features, obj_function):
point_dict = utils.process_datapoints(datapoints)
tmp = [dict(m['features'].items() +
{'time': sorted(m['time'])[-1]}.items())
for _, m in point_dict.items()]
tmp = sorted(tmp, key=lambda d: d['time'])
return [obj_function(**p) for p in tmp]
def point_to_vector(point, features):
"""Given a point {feature1: value1, ..., featureN: valueN}
It returns [value1, ..., valueN] sorted by the keys"""
return [point[key] for key in sorted(features.keys())]
def points_to_vectors(points, features):
return map(lambda p: point_to_vector(p, features), points)
def vector_to_point(vector, features):
"""Given a vector [value1, ..., valueN]
It returns {feature1: value1, ..., featureN: valueN}"""
return {key: vector[i] for i, key
in enumerate(sorted(features.keys()))}
| true
|
d6e8c69afc073014ce0cc1854ebf9139e3ee82a9
|
Python
|
pighaddt/ITRI_BTconnect
|
/venv/TouchTaiwan_BT.py
|
UTF-8
| 878
| 2.734375
| 3
|
[] |
no_license
|
import bluetooth
###
target_name = "LAIRD BL654-CD8A74"
target_address = "f00f06cd8a74" # Touch Taiwan Device ()
nearby_devices = bluetooth.discover_devices()
print(nearby_devices)
print()
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name(bdaddr):
target_address = bdaddr
break
if target_address is not None:
print("Found target bluetooth device with address: ", target_address)
else:
print("Could not find target bluetooth device nearby")
##
import serial
portx = "COM4"
bps = 9600
A = []
ser = serial.Serial(portx, int(bps), timeout=1, parity=serial.PARITY_NONE, stopbits=1)
if (ser.isOpen()):
print("open success")
while (True):
line = ser.readline()
# if(line):
# a = str(line, 'utf-16')
# print(a)
# line = 0
else:
print("open failed")
ser.close()
| true
|
00cbc7ad4f8a3c547408b7dc50d8c069e3c4054d
|
Python
|
tmajest/project-euler
|
/python/p41/prime_tools.py
|
UTF-8
| 469
| 3.921875
| 4
|
[] |
no_license
|
# Contains prime generator functions
import math
def primes_up_to(num):
""" Prime sieve: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation """
primes = [True for i in xrange(num)]
primes[0] = False
primes[1] = False
for i in xrange(2, int(math.sqrt(num) + 1)):
if primes[i]:
for j in xrange(i * i, num, i):
primes[j] = False
return [pos for pos, is_prime in enumerate(primes) if is_prime]
| true
|
5538687b79e28796bbefa2671f70a872f23619b3
|
Python
|
alaadhami/spmblackjack
|
/blackjack_gui.py
|
UTF-8
| 18,989
| 2.8125
| 3
|
[] |
no_license
|
import tkinter as tk
from tkinter import *
from cards import *
from gameplay import *
from player import *
import random
TITLE_FONT = ("Arial", 30, "bold")
class BlackJackUI(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.minsize(self, 400, 400)
self.title("EngiMavs BlackJack App")
self.geometry("800x600")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
self.container = tk.Frame(self)
self.container.pack(side="top", fill="both", expand=True)
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (WelcomeUIPage, MenuPage):
page_name = F.__name__
frame = F(self.container, self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("WelcomeUIPage")
def gridContainerInit(self, *args, **kwargs):
self.container.pack_forget()
self.container.grid_rowconfigure(10, weight=1)
self.container.grid_columnconfigure(10, weight=1)
self.container.grid()
# Show a frame for the given page name
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
def closeApp(self):
self.destroy()
def okButton(self, controller, name, var, totalCashIn):
self.name = str(name.get())
self.option = str(var.get())
getTotalCashIn = totalCashIn.get()
param, splitTotalCashIn = getTotalCashIn.split("$", 1)
self.userMoney = int(splitTotalCashIn.strip())
self.gridContainerInit(controller)
self.once = "1"
self.showBetButtons = True
self.showGamePlayButtons = False
self.showFirstPlayButtons = True #this needs to be known
userName = self.name
option = self.option
self.game = gameplay()
game = self.game
# Add players to the game - depending on "Select Players" input
game.addPlayer("Dealer", "D")
self.dealer = game.playerDict["Dealer"]
self.dealer.money = 0
if option == "2":
game.addPlayer("Player2")
self.p2 = game.playerDict["Player2"]
self.p2.money = random.randrange(300, 500, 50)
elif option == "3":
game.addPlayer("Player2")
game.addPlayer("Player3")
self.p2 = game.playerDict["Player2"]
self.p3 = game.playerDict["Player3"]
self.p2.money = random.randrange(300, 500, 50)
self.p3.money = random.randrange(300, 500, 50)
game.addPlayer(userName, "NULL", True)
self.user = game.playerDict[userName]
self.user.money = controller.userMoney
self.refrehGamePage(controller)
def betButton(self, controller, bet):
self.user.bet += bet
self.refrehGamePage(controller)
def dealButton(self, controller):
self.showGamePlayButtons = True
self.showBetButtons = False
for i in controller.game.totalPlayers:
if (i.dealer != "dealer" and i.userRight == False):
i.bet = random.randrange(5, 200, 5)
self.refrehGamePage(controller)
def replayGame(self, controller):
controller.once = "1"
self.showBetButtons = True
self.showGamePlayButtons = False
self.user.bet = 0
controller.game.totalPlayersBet = 0
for i in controller.game.totalPlayers:
i.winner = "NULL"
self.refrehGamePage(controller)
def settingsGame(self, controller):
self.show_frame("MenuPage")
def hitMeButton(self, controller):
self.user.drawCard(controller.deck)
self.refrehGamePage(controller)
def doneButton(self, controller):
controller.game.checkMatch(controller.deck)
self.showCard = True
self.showBetButtons = False
self.showGamePlayButtons = True
self.refrehGamePage(controller)
def refrehGamePage(self, controller):
page_name = MainGamePage.__name__
frame = MainGamePage(self.container, controller)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
controller.show_frame("MainGamePage")
def passVal2controller(self, controller, deck, host):
self.deck = deck
self.host = host
class WelcomeUIPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg='orange2')
self.controller = controller
label = tk.Label(self, text="Welcome to EngiMavs BlackJack", font=TITLE_FONT, fg='blue2')
label.pack(side="top", fill="x", pady=30)
button1 = tk.Button(self, text="Start Game", bg="green3", fg='snow',
command=lambda: controller.show_frame("MenuPage"))
button2 = tk.Button(self, text="Quit", bg='red2', fg='snow',
command=lambda: controller.closeApp())
button1.pack(ipadx=50, ipady=40)
button2.pack(pady=30)
button1.config(font=('copper black', 20, 'bold'))
class MenuPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg='green3')
self.controller = controller
nameLabel = tk.Label(self, text="Enter your name", font=TITLE_FONT, fg='blue2')
name = tk.Entry(self, bd =5)
var1 = IntVar()#what does this do?
nameLabel.pack(side="top", fill="x", pady=10)
name.pack(ipadx=10, pady=5)
##-----------
#deckLabel = tk.Label(self, text="Enter number of decks", font=TITLE_FONT, fg='blue2')
#decks = tk.Entry(self, bd=5)
#deckLabel.insert(END,'3')
#deckLabel.pack(side="top", fill="x", pady =20)
##-----------###need a GUI input for number of decks on main page
label = tk.Label(self, text="How many players will be playing?", font=TITLE_FONT, fg='blue2')
var = tk.StringVar()
var.set("1") # initial value
option = tk.OptionMenu(self, var, "1", "2", "3")
label.pack(fill="x", pady=15)
option.pack()
totalCashLabel = tk.Label(self, text="Enter how much money you're\nbringing into the game:")
totalCashIn = tk.Entry(self, bd =5)
totalCashIn.insert(END, '$ ' + '500')
totalCashLabel.pack()
totalCashIn.pack()
button = tk.Button(self, text="OK",
command=lambda: controller.okButton(controller, name, var, totalCashIn))
button.pack(pady=40)
class MainGamePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg='green3')
self.controller = controller
# 'controller.once' determines if it's the first init.
# If it is (="1"), add players + generate card decks + draw cards,
# or else continue with the game with existing players and cards
if controller.once == "1":
self.gameInit(controller)
self.guiInit(controller)
### ====== Generate Cards, shuffle, and start game for the first init ====== ###
def gameInit(self, controller):#add argument decks
controller.once = "0"
controller.showCard = False
controller.user.bet = 0
# Get a deck of cards, shuffle them!
host = cards()
deck = host.generateDeck()#needs an int argument for copies
host.shuffleDeck(deck)
# game.startGame makes joined players draw 2 cards to begin with, including dealer
controller.game.startGame(deck)
controller.passVal2controller(controller, deck, host)
### ====== GUI display settings ====== ###
def guiInit(self, controller):
userName = controller.name
option = controller.option
game = controller.game
totalBet = abs(game.totalPlayersBet)
deck = controller.deck
dealer = controller.dealer
dealerName = dealer.name
dealerOnHand = dealer.onHand
dealerMoney = str(dealer.money)
user = controller.user
userOnHand = user.onHand
userMoney = str(user.money)
if option == "2":
p2 = controller.p2
p2name = p2.name
p2OnHand = p2.onHand
p2Money = str(p2.money)
p2Bet = p2.bet
elif option == "3":
p2 = controller.p2
p2name = p2.name
p2OnHand = p2.onHand
p2Money = str(p2.money)
p2Bet = p2.bet
p3 = controller.p3
p3name = p3.name
p3OnHand = p3.onHand
p3Money = str(p3.money)
p3Bet = p3.bet
# Default display - Dealer and User display
# ===== Dealer Display ===== #
if dealer.winner == False:
dealerLabel = tk.Label(self, text=dealerName, font=TITLE_FONT, fg="red")
elif dealer.winner == True:
dealerLabel = tk.Label(self, text=dealerName, font=TITLE_FONT, fg="green")
else:
dealerLabel = tk.Label(self, text=dealerName, font=TITLE_FONT)
dealerLabel.grid(row=2, column=0)
for i in range (0, len(dealerOnHand)):
if controller.showCard == True:
dealerCards = tk.Label(self, text=dealerOnHand[i], bg="white", fg="black")
else:
if i == 0 and controller.showGamePlayButtons:
dealerCards = tk.Label(self, text=dealerOnHand[i], bg="white", fg="black")##########################
dealerCards = tk.Label(self, text=dealerOnHand[i], bg="black", fg="black")
dealerCards.grid(row=3, column=1+i, padx=(0,5), ipadx=5, ipady=15)
dealerMoneyLabel = tk.Label(self, text="Total: $" + dealerMoney)
dealerMoneyLabel.grid(row=3, column=0)
if controller.showBetButtons == False:
if controller.dealer.winner == False:
totalBetLabel = tk.Label(self, text="-$" + str(totalBet), fg="red")
elif controller.dealer.winner == True:
totalBetLabel = tk.Label(self, text="+$" + str(totalBet), fg="green")
else:
totalBetLabel = tk.Label(self, text="$" + str(totalBet))
totalBetLabel.grid(row=2, column=3, columnspan=4)
# If user choose 2 players - add 1 more players (including himself)
if option == "2":
if p2.winner == False:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT, fg="red")
elif p2.winner == True:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT, fg="green")
else:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT)
p2.grid(row=5, column=0)
for i in range (0, len(p2OnHand)):
if controller.showCard == True:
p2Cards = tk.Label(self, text=p2OnHand[i], bg="black", fg="white")
else:
p2Cards = tk.Label(self, text=p2OnHand[i], bg="black", fg="black")
p2Cards.grid(row=6, column=1+i, padx=(0,5), ipadx=5, ipady=15)
p2MoneyLabel = tk.Label(self, text="Total: $" + p2Money)
p2MoneyLabel.grid(row=6, column=0)
if controller.showBetButtons == False:
if controller.p2.winner == False:
p2BetLabel = tk.Label(self, text="Bet: -$" + str(p2Bet), fg="red")
elif controller.p2.winner == True:
p2BetLabel = tk.Label(self, text="Bet: +$" + str(p2Bet), fg="green")
else:
p2BetLabel = tk.Label(self, text="Bet: $" + str(p2Bet))
p2BetLabel.grid(row=5, column=3, columnspan=4)
# If user choose 3 players - add 2 more players (including himself)
elif option == "3":
# ===== Player 2 Display ===== #
if p2.winner == False:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT, fg="red")
elif p2.winner == True:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT, fg="green")
else:
p2 = tk.Label(self, text=p2name, font=TITLE_FONT)
p2.grid(row=5, column=0)
for i in range (0, len(p2OnHand)):
if controller.showCard == True:
p2Cards = tk.Label(self, text=p2OnHand[i], bg="black", fg="white")
else:
p2Cards = tk.Label(self, text=p2OnHand[i], bg="black", fg="black")
p2Cards.grid(row=6, column=1+i, padx=(0,5), ipadx=5, ipady=15)
p2MoneyLabel = tk.Label(self, text="Total: $" + p2Money)
p2MoneyLabel.grid(row=6, column=0)
if controller.showBetButtons == False:
if controller.p2.winner == False:
p2BetLabel = tk.Label(self, text="Bet: -$" + str(p2Bet), fg="red")
elif controller.p2.winner == True:
p2BetLabel = tk.Label(self, text="Bet: +$" + str(p2Bet), fg="green")
else:
p2BetLabel = tk.Label(self, text="Bet: $" + str(p2Bet))
p2BetLabel.grid(row=5, column=3, columnspan=4)
# ===== Player 3 Display ===== #
if p3.winner == False:
p3 = tk.Label(self, text=p3name, font=TITLE_FONT, fg="red")
elif p3.winner == True:
p3 = tk.Label(self, text=p3name, font=TITLE_FONT, fg="green")
else:
p3 = tk.Label(self, text=p3name, font=TITLE_FONT)
p3.grid(row=7, column=0)
for i in range (0, len(p3OnHand)):
if controller.showCard == True:
p3Cards = tk.Label(self, text=p3OnHand[i], bg="black", fg="white")
else:
p3Cards = tk.Label(self, text=p3OnHand[i], bg="black", fg="black")
p3Cards.grid(row=8, column=1+i, padx=(0,5), ipadx=5, ipady=15)
p3MoneyLabel = tk.Label(self, text="Total: $" + p3Money)
p3MoneyLabel.grid(row=8, column=0)
if controller.showBetButtons == False:
if controller.p3.winner == False:
p3BetLabel = tk.Label(self, text="Bet: -$" + str(p3Bet), fg="red")
elif controller.p3.winner == True:
p3BetLabel = tk.Label(self, text="Bet: +$" + str(p3Bet), fg="green")
else:
p3BetLabel = tk.Label(self, text="Bet: $" + str(p3Bet))
p3BetLabel.grid(row=7, column=3, columnspan=4)
# ===== Line ===== #
line = tk.Label(self, text="_______________________________", font=TITLE_FONT)
line.grid(row=19, column=0, pady=(5), columnspan=10)
# ===== User Display ===== #
if user.winner == False:
userLabel = tk.Label(self, text=userName, font=TITLE_FONT, fg="red")
userBetLabel = tk.Label(self, text="Bet: -$" + str(controller.user.bet), fg="red")
elif user.winner == True:
userLabel = tk.Label(self, text=userName, font=TITLE_FONT, fg="green")
userBetLabel = tk.Label(self, text="Bet: +$" + str(controller.user.bet), fg="green")
else:
userLabel = tk.Label(self, text=userName, font=TITLE_FONT)
userBetLabel = tk.Label(self, text="Bet: $" + str(controller.user.bet))
userLabel.grid(row=20, column=0)
userBetLabel.grid(row=20, column=3, columnspan=4)
for i in range (0, len(userOnHand)):
if (controller.showGamePlayButtons == True):
userCards = tk.Label(self, text=userOnHand[i], bg="white", fg="black")
else:
userCards = tk.Label(self, text=userOnHand[i], bg="black", fg="black")
userCards.grid(row=21, column=1+i, padx=(0,5), ipadx=5, ipady=15)
if (controller.showBetButtons == True):
betButton5 = tk.Button(self, text="$5",
command=lambda: controller.betButton(controller, 5))
betButton10 = tk.Button(self, text="$10",
command=lambda: controller.betButton(controller, 10))
betButton25 = tk.Button(self, text="$25",
command=lambda: controller.betButton(controller, 25))
betButton50 = tk.Button(self, text="$50",
command=lambda: controller.betButton(controller, 50))
dealButton = tk.Button(self, text="Deal Cards",
command=lambda: controller.dealButton(controller))
betButton5.grid(row=21, column=3, pady=(5, 0))
betButton10.grid(row=21, column=4, pady=(5, 0))
betButton25.grid(row=21, column=5, pady=(5,0))
betButton50.grid(row=21, column=6, pady=(5,0))
dealButton.grid(row=22, column=3, columnspan=4, pady=(5,0))
userMoneyLabel = tk.Label(self, text="Total: $" + userMoney)
userMoneyLabel.grid(row=21, column=0)
# ===== Buttons Display ===== #
if (controller.showGamePlayButtons == True):
hitMe = tk.Button(self, text="Hit Me",
command=lambda: controller.hitMeButton(controller))
done = tk.Button(self, text="Stay",
command=lambda: controller.doneButton(controller))
replayButton = tk.Button(self, text="Replay?",
command=lambda: controller.replayGame(controller))
settingsButton = tk.Button(self, text="Settings",
command=lambda: controller.settingsGame(controller))
closeButton = tk.Button(self, text="Quit",
command=lambda: controller.closeApp())
hitMe.grid(row=22, column=1, pady=(25, 0))
done.grid(row=22, column=2, pady=(25, 0))
replayButton.grid(row=23, column=1, pady=(3,0))
settingsButton.grid(row=23, column=2, pady=(3,0))
closeButton.grid(row=24, column=1, columnspan=2, pady=(5,0))
if __name__ == "__main__":
app = BlackJackUI()
app.mainloop()
| true
|
e260d89de7f309ea34d9348e61acfce8cb6fc320
|
Python
|
Jawmo/Hope
|
/engine/admin.py
|
UTF-8
| 7,479
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
from engine.global_config import *
import psycopg2
from config import config
import json
class Admin_Commands():
def __init__(self, name):
self.name = name
def fill_db():
insert_item = """INSERT INTO items(uuid_id, name, item_desc, base_type, size, weight, capacity, can_attributes, room_target, combines_with, is_open, location, location_body, owner)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING uuid_id, name, item_desc, base_type, size, weight, capacity, can_attributes, combines_with, room_target, is_open, location, location_body, owner;"""
insert_room = """INSERT INTO rooms(uuid_id, room_type, name, description, exits, region, zone, effects, owner)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING uuid_id, room_type, name, description, exits, region, zone, effects, owner;"""
insert_player = """INSERT INTO players(uuid_id, name, gender, hp, core_attributes, player_state, conditions, credit, stow_loc, current_room)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING uuid_id, name, gender, hp, core_attributes, player_state, conditions, credit, stow_loc, current_room;"""
insert_npc = """INSERT INTO npcs(uuid_id, base_type, name, race, gender, npc_desc, core_attributes, npc_state, conditions, credit, supply, demand, home_loc, demeanor, current_room)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING uuid_id, base_type, name, race, gender npc_desc, core_attributes, npc_state, conditions, credit, supply, demand, home_loc, demeanor, current_room;"""
insert_org = """INSERT INTO orgs(uuid_id, name, org_desc, supply, demand, home)
VALUES(%s, %s, %s, %s, %s, %s)
RETURNING uuid_id, name, org_desc, supply, demand, home;"""
conn = None
try:
dbparams = config()
conn = psycopg2.connect(**dbparams)
cur = conn.cursor()
# insert a new part
# uuid, name, item_desc, base_type, size, weight, capacity, can_attributes, combines_with, is_open, location, location_body, owner
cur.execute(insert_item, ("70306652-fbda-479a-a06d-48b411911ed7", "9mm magazine", "It's a 9mm magazine.", "ammo_9mm", 1, 1, 10, None, "", "pistol_9mm", False, "65d56cbe-f276-4055-899c-3244c0c92003", None, "da",))
cur.execute(insert_item, ("035d0c23-fbda-479a-a06d-48b411911ed7", "9mm pistol", "Mmm, shiny.", "pistol_9mm", 2, 2, 10, "is_gun", "", "ammo_9mm", False, "65d56cbe-f276-4055-899c-3244c0c92003", None, "da",))
cur.execute(insert_item, ("6123e586-93c7-4fff-8787-3ca5706ad2a8", "rabbit toy", "Huh, looks real.", "toy", 1, 1, 0, None, "", None, False, "70306652-08cf-4c99-ac7d-c8bd1082220c", None, "da",))
cur.execute(insert_item, ("70306652-08cf-4c99-ac7d-c8bd1082220c", "backpack", "It's a backpack.", "storage_backpack", 2, 2, 0, "is_container", "", None, False, "c93e5db1-fabe-496f-a6a6-6769a1bf1404", "r_hand", "da",))
cur.execute(insert_item, ("e87c6768-0e3d-4f52-92b8-56ad69f63bea", "shuttle", "This shuttle belongs to the S.S. Hope.", "ship", 0, 5000, 0, "is_door", "ba0d6g25-ae3r-43n8-b25c-1f4342chyfd0", None, True, "65d56cbe-f276-4055-899c-3244c0c92003", "", "da",))
cur.execute(insert_room, ("65d56cbe-f276-4055-899c-3244c0c92003", None, "ship_capital_dock", "Shuttle Bay", "The room is simple.", json.dumps({"north": "aa0dd325-ae9e-43b0-b25c-1f4803ceefd0"}), "S.S. Hope", "space", None, "da",))
cur.execute(insert_room, ("aa0dd325-ae9e-43b0-b25c-1f4803ceefd0", None, "ship_capital_dock", "Shuttle Bay", "The room is simple.", json.dumps({"south": "65d56cbe-f276-4055-899c-3244c0c92003"}), "S.S. Hope", "space", None, "aa",))
cur.execute(insert_room, ("ba0d6g25-ae3r-43n8-b25c-1f4342chyfd0", "e87c6768-0e3d-4f52-92b8-56ad69f63bea", "ship_private_main", "Shuttle", "You see the inside of the shuttle.", json.dumps({"out": "65d56cbe-f276-4055-899c-3244c0c92003"}), "shuttle", "shuttle", None, "da",))
cur.execute(insert_room, ("ny0d6j56-ae3r-43n8-m28s-1f4342chyfd0", None, "planet_forest", "Forest", "There are lots of trees.", json.dumps({"south": "aa0dd234-ab72-32b6-c93c-1f4803ceefd0"}), "shuttle", "shuttle", None, "da",))
cur.execute(insert_room, ("34d66jru-f276-2144-384v-3244c0c92003", None, "space", "Space", "Like a back-lit canopy, the stars and galaxies shine across the black.", json.dumps({}), "shuttle", "shuttle", None, "da",))
cur.execute(insert_room, ("aa0dd234-ab72-32b6-c93c-1f4803ceefd0", None, "e87c6768-0e3d-4f52-92b8-56ad69f63bea", "planet_landing", "Open Field", "Tall, golden wheat grows wild here. You can see the edge of a dense forest to the north.", json.dumps({"north": "ny0d6j56-ae3r-43n8-m28s-1f4342chyfd0"}), "shuttle", "shuttle", None, "da",))
cur.execute(insert_room, ("pp2aa543-ab72-93n1-c93c-1f4803ceefd0", None, "e87c6768-0e3d-4f52-92b8-56ad69f63bea", "space_orbit", "Orbit around Oxine", "Green and blue hues decorate the planet of Oxine.", json.dumps({"entry": "aa0dd234-ab72-32b6-c93c-1f4803ceefd0"}), "shuttle", "shuttle", None, "da",))
cur.execute(insert_player, ("c93e5db1-fabe-496f-a6a6-6769a1bf1404", "da", "male", 100, json.dumps({"str": 12, "dex": 8, "con": 15, "ins": 6, "edu": 5, "soc": 6}), "standing", None, 100, None, "65d56cbe-f276-4055-899c-3244c0c92003",))
cur.execute(insert_player, ("3563874d-8646-487f-8beb-3c0278d2f292", "ry", "female", 100, json.dumps({"str": 8, "dex": 12, "con": 8, "ins": 12, "edu": 10, "soc": 10}), "standing", None, 100, None, "65d56cbe-f276-4055-899c-3244c0c92003",))
cur.execute(insert_player, ("06ce6e88-f666-4cac-9901-698f7464e1c5", "fa", "female", 100, json.dumps({"str": 8, "dex": 12, "con": 8, "ins": 12, "edu": 10, "soc": 10}), "standing", None, 100, None, "65d56cbe-f276-4055-899c-3244c0c92003",))
cur.execute(insert_npc, ("c93e5db1-08cf-4cac-a06d-c8bd1082220c", "npc_human", "Lt. Dan", "human", "male", "He looks like he's busy.", json.dumps({"str": 5, "dex": 5, "con": 5, "ins": 5, "edu": 5, "soc": 5}), "standing", None, 100, json.dumps({}), json.dumps({}), "S.S. Hope", "friendly", "65d56cbe-f276-4055-899c-3244c0c92003"))
cur.execute(insert_npc, ("c93e5db1-08cf-4cac-a06d-c8bd1082220c", "npc_predator", "Predator", "onxine", "male", "He looks mean.", json.dumps({"str": 5, "dex": 5, "con": 5, "ins": 5, "edu": 5, "soc": 5}), "standing", None, 100, json.dumps({}), json.dumps({}), "Oxine", "Hostile", "ny0d6j56-ae3r-43n8-m28s-1f4342chyfd0"))
cur.execute(insert_org, ("6123e586-f276-4c99-a06d-48b411911ed7", "Heiss", "A humanoid race focused heavily on cybernetics and augments.", json.dumps({}), json.dumps({}), "Eroli"))
# commit changes
conn.commit()
print("Done adding objects to DB.")
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def create_instance(self, user, user_input, input_kwargs):
print("ADMIN | Creating Instance:", user_input)
Room_Procgen(user_input[1])
| true
|
6aebe609a6acb0535a41418d3a1ba43cc937f1d9
|
Python
|
fursovia/chatbot_game
|
/chatgame/classifiers/classifier.py
|
UTF-8
| 2,346
| 2.578125
| 3
|
[] |
no_license
|
from typing import Union, Optional, Tuple
import torch
DISCRIMINATOR_MODELS_PARAMS = {
"clickbait": {
"path": "models/clickbait_classifier_head.pt",
"class_size": 2,
"embed_size": 1024,
"class_vocab": {"non_clickbait": 0, "clickbait": 1},
"default_class": 1,
"pretrained_model": "gpt2-medium",
},
"sentiment": {
"path": "models/SST_classifier_head.pt",
"class_size": 5,
"embed_size": 1024,
"class_vocab": {"very_positive": 2, "very_negative": 3},
"default_class": 3,
"pretrained_model": "gpt2-medium",
},
}
class ClassificationHead(torch.nn.Module):
"""Classification Head for transformer encoders"""
def __init__(self,
class_size: int,
embed_size: int):
"""
:param class_size: number of labels
:param embed_size: embeddings vector size
"""
super(ClassificationHead, self).__init__()
self.class_size = class_size
self.embed_size = embed_size
self.mlp = torch.nn.Linear(embed_size, class_size)
def forward(self,
hidden_state: torch.Tensor):
logits = self.mlp(hidden_state)
return logits
def get_classifier(
name: Optional[str],
class_label: Union[str, int],
device: str,
classifiers_dir: str) -> Tuple[Optional[ClassificationHead], Optional[int]]:
if name is None:
return None, None
params = DISCRIMINATOR_MODELS_PARAMS[name]
classifier = ClassificationHead(class_size=params['class_size'],
embed_size=params['embed_size']).to(device)
resolved_archive_file = classifiers_dir + params["path"]
classifier.load_state_dict(torch.load(resolved_archive_file, map_location=device))
classifier.eval()
if isinstance(class_label, str):
if class_label in params["class_vocab"]:
label_id = params["class_vocab"][class_label]
else:
label_id = params["default_class"]
elif isinstance(class_label, int):
if class_label in set(params["class_vocab"].values()):
label_id = class_label
else:
label_id = params["default_class"]
else:
label_id = params["default_class"]
return classifier, label_id
| true
|
98454d99e0284ae1c26a72e4d95e93bda4fb8298
|
Python
|
fnsisdabast/nuc_bot_remote
|
/nuc_bot_remote/laser_scan_printer3.py
|
UTF-8
| 2,069
| 2.65625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
import rospy
import numpy as np
from std_msgs.msg import Float32MultiArray
from sensor_msgs.msg import LaserScan
def laser_callback(scan):
depths = []
for dist in scan.ranges: #get all of the depths from laser scanner
depths.append(dist)
depth_octants=[]
depth_octants.append(depths[90:112]) #divide them into 16 bins
depth_octants.append(depths[112:135])
depth_octants.append(depths[135:157])
depth_octants.append(depths[157:180])
depth_octants.append(depths[180:203])
depth_octants.append(depths[203:225])
depth_octants.append(depths[225:248])
depth_octants.append(depths[248:270])
depth_octants.append(depths[270:293])
depth_octants.append(depths[293:315])
depth_octants.append(depths[315:338])
depth_octants.append(depths[338:360])
depth_octants.append(depths[0:23])
depth_octants.append(depths[23:45])
depth_octants.append(depths[45:68])
depth_octants.append(depths[68:90])
octant_avg=[]
for octants in depth_octants: #average each bin
if len(octants)>0:
depth_running=0
num_depths=0
for depth_vals in octants:
if not np.isnan(depth_vals): #if it is a number
if not np.isinf(depth_vals): #and is not infinity, add it to the sum
depth_running=depth_running+depth_vals
else: #otherwise just skip it
num_depths=num_depths-1
num_depths=num_depths+1
octant_avg.append(depth_running/num_depths) #append to array of averages
array_to_pub=Float32MultiArray(data=octant_avg) #publish array of averages
pub.publish(array_to_pub)
def laser_subscriber():
rospy.init_node('laser_subscriber')
sub=rospy.Subscriber('scan', LaserScan, laser_callback)
pub=rospy.Publisher('octant_dist',Float32MultiArray, queue_size=1)
rospy.spin()
if __name__ == '__main__':
laser_subscriber()
| true
|
7353b111bfa7b8510638b639d455a283669eeb04
|
Python
|
1224667889/ML_Task
|
/lesson_5/session_3.py
|
UTF-8
| 2,336
| 2.765625
| 3
|
[] |
no_license
|
import matplotlib.pyplot as plt
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
import utils
import time
from sklearn.neighbors import KNeighborsClassifier as KNN
if __name__ == '__main__':
X, labels, to_image = utils.createDatabase("17flowers")
X = X.reshape(X.shape[0], 200 * 180)
X_train, X_test, labels_train, labels_test = train_test_split(X, labels, test_size=0.2, random_state=22)
plt.figure()
plt.imshow(to_image)
plt.show()
# from lesson_2.session_3 import KNN
PCA_ACCs = []
LDA_ACCs = []
for K in range(1, 10):
t0 = time.time()
pca = PCA(n_components=K).fit(X_train)
x_train_pca = pca.transform(X_train)
x_test_pca = pca.transform(X_test)
print("|", time.time() - t0, "|")
knn = KNN()
t1 = time.time()
knn.fit(x_train_pca, labels_train)
t2 = time.time()
PCA_pred = knn.predict(x_test_pca)
t3 = time.time()
ACC_PCA = np.sum(np.array(PCA_pred) == np.array(labels_test)) / len(PCA_pred)
# print(f'PCA K={K} 训练消耗:{t2-t1}s\t预测消耗:{t3-t2}s\t准确率:{ACC_PCA*100}%')
# print(f'|K={K}|{t2-t1}s|{t3-t2}s|{ACC_PCA*100}%|')
PCA_ACCs.append(ACC_PCA)
print("------------------")
for K in range(1, 10):
t0 = time.time()
lda = LDA(n_components=K).fit(X_train, labels_train)
x_train_lda = lda.transform(X_train)
x_test_lda = lda.transform(X_test)
print("|", time.time() - t0, "|")
knn = KNN()
t1 = time.time()
knn.fit(x_train_lda, labels_train)
t2 = time.time()
LDA_pred = knn.predict(x_test_lda)
t3 = time.time()
ACC_LDA = np.sum(np.array(LDA_pred) == np.array(labels_test)) / len(LDA_pred)
# print(f'LDA K={K} 训练消耗:{t2-t1}s\t预测消耗:{t3-t2}s\t准确率:{ACC_LDA*100}%')
# print(f'|K={K}|{t2-t1}s|{t3-t2}s|{ACC_LDA*100}%|')
LDA_ACCs.append(ACC_LDA)
_, ax = plt.subplots()
bar_width = 0.3
index = np.arange(9)
ax.bar(index, PCA_ACCs, bar_width, label='PCA')
ax.bar(index + bar_width, LDA_ACCs, bar_width, label='LCD')
ax.legend()
plt.show()
| true
|
1d69c7c59c769d8d8fde5375cc574fbbfdc39eb3
|
Python
|
zjhmale/bfx-hf-indicators-py
|
/bfxhfindicators/stochastic.py
|
UTF-8
| 1,966
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
from bfxhfindicators.indicator import Indicator
from bfxhfindicators.sma import SMA
class Stochastic(Indicator):
def __init__(self, period, smoothK, smoothD, cache_size=None):
self._p = period
self._buffer = []
self._kSMA = SMA(smoothK, cache_size)
self._dSMA = SMA(smoothD, cache_size)
super().__init__({
'args': [period, smoothK, smoothD, cache_size],
'id': 'stoch',
'name': 'Stoch(%f)' % (period),
'seed_period': period,
'data_type': 'candle',
'data_key': '*'
})
def reset(self):
super().reset()
self._buffer = []
self._kSMA.reset()
self._dSMA.reset()
def update(self, candle):
if len(self._buffer) == 0:
self._buffer.append(candle)
else:
self._buffer[-1] = candle
if len(self._buffer) < self._p:
return self.v()
close = candle['close']
lowestLow = min(map(lambda c: c['low'], self._buffer))
highestHigh = max(map(lambda c: c['high'], self._buffer))
k = 100 * ((close - lowestLow) / (highestHigh - lowestLow))
self._kSMA.update(k)
self._dSMA.update(self._kSMA.v())
return super().update({
'k': self._kSMA.v(),
'd': self._dSMA.v()
})
def add(self, candle):
self._buffer.append(candle)
if len(self._buffer) > self._p:
del self._buffer[0]
elif len(self._buffer) < self._p:
return self.v()
close = candle['close']
lowestLow = min(map(lambda c: c['low'], self._buffer))
highestHigh = max(map(lambda c: c['high'], self._buffer))
k = 100 * ((close - lowestLow) / (highestHigh - lowestLow))
self._kSMA.add(k)
self._dSMA.add(self._kSMA.v())
return super().add({
'k': self._kSMA.v(),
'd': self._dSMA.v()
})
| true
|
354af68311dc73f144ad529417f3d7db48b1fd61
|
Python
|
kyrilkhaletsky/CA117-Programming
|
/Exercises/test.py
|
UTF-8
| 64
| 2.953125
| 3
|
[] |
no_license
|
n = list(range(15))
q = [c for c in n if c % 3 == 0]
print(q)
| true
|
61e0608c9d518dfe4439e63901857a127fc59e70
|
Python
|
smeets/thesis
|
/scripts/mdrparser.py
|
UTF-8
| 1,950
| 2.953125
| 3
|
[] |
no_license
|
from xml.dom import minidom
from datetime import datetime
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# 2019-01-17T14:33:21.738
# yyyy-mm-dd HH:MM:SS.N
class MdrParser:
""""""
def __init__(self, file):
self.xmldoc = minidom.parse(file)
self.read_head = 0
def FREQUENCIES(self, frequencies):
vals = getText(frequencies.childNodes).split('; ')
vals.pop()
return list(map(lambda k: str(int(int(k)/1e6)), vals))
def VALUES(self, values):
vals = getText(values.childNodes).split('; ')
vals.pop()
return vals
def DATE(self, date):
return datetime.strptime(getText(date.childNodes), "%Y-%m-%dT%H:%M:%S.%f")
def SWEEP(self, sweep):
return {
'time' : self.DATE(sweep.getElementsByTagName('StartDate')[0]),
'values': self.VALUES(sweep.getElementsByTagName('Values')[0])
}
def SWEEPS(self, sweeps):
return [self.SWEEP(sweep) for sweep in sweeps]
def all(self):
mcs = self.xmldoc
sweeps = mcs.getElementsByTagName('Sweep')
freqs = sweeps[0].getElementsByTagName('Frequencies')[0]
return {
"freqs": self.FREQUENCIES(freqs),
"sweeps": self.SWEEPS(sweeps)
}
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print("usage: {} datasets/raw/measure.mdr".format(sys.argv[0]))
sys.exit(1)
a = MdrParser(sys.argv[1]).all()
# x1 y1 z1
# x2 y2 z2
# x = time
# y = freq
# z = value
print(len(a["freqs"]))
print(len(a["sweeps"]))
# print("time," + ','.join(a["freqs"]))
# incr = 0
# for s in a["sweeps"]:
# vals = [str(incr*4)]
# vals.extend(s["values"])
# print(",".join(vals))
# incr = incr + 1
| true
|
3c45ff268112943fcefaf31bf191bdd90eb2f2ea
|
Python
|
lidongyin0212/be-atp
|
/public/database/mysql_api.py
|
UTF-8
| 3,475
| 2.8125
| 3
|
[] |
no_license
|
# -*- coding:utf-8 -*-
# 导入mysql库
import pymysql
import os
class MySQLObj(object):
def __init__(self, host, port, user, password, db):
self.host = host
self.port = port
self.user = user
self.password = password
self.db = db
self.conn, self.cursor = None, None
def connect(self):
# 打开数据库连接
try:
self.conn = pymysql.Connect(
host=self.host,
port=self.port,
user=self.user,
passwd=self.password,
db=self.db,
charset='utf8'
)
self.cursor = self.conn.cursor()
except:
# 获取一个游标(数据库操作的对象)
return {"msg": "error"}
# 关闭数据库连接
def close(self):
self.cursor.close()
self.conn.close()
# 增加
# INSERT INTO course(c_name, c_weight) VALUES(%s, %d)
def insert(self, sql, param=()):
return self.__edit(sql, param)
# 删除
def delete(self, sql, param=()):
return self.__edit(sql, param)
# 修改
def update(self, sql, param=()):
return self.__edit(sql, param)
# 增删改通用的代码
def __edit(self, sql, param=()):
count = 0
try:
# 连接数据库
self.connect()
# 执行SQL语句
count = self.cursor.execute(sql, param)
# 提交数据库事务处理
self.conn.commit()
return count, ''
except Exception as e:
# 如果出现错误就回滚
print(e)
self.conn.rollback()
return -1, e
# 查询所有
def get_all(self, sql, param=()):
result = () # 返回的结果是一个元组
try:
# 连接数据库
self.connect()
# 执行SQL语句
if param:
self.cursor.execute(sql, param)
else:
self.cursor.execute(sql)
# 获取查询的内容
result = self.cursor.fetchall()
fields = self.cursor.description
column_list = [] # 定义字段名的列表
for i in fields:
column_list.append(i[0])
# 提交数据库事务处理
self.conn.commit()
return result, column_list, ""
except Exception as e:
# 如果出现错误就回滚
print(e)
self.conn.rollback()
return -1, None, e
# 查询一个
def get_one(self, sql, param=()):
result = () # 返回的结果是一个元组
try:
# 连接数据库
self.connect()
# 执行SQL语句
if param:
self.cursor.execute(sql, param)
else:
self.cursor.execute(sql)
# 获取查询的内容
result = self.cursor.fetchone()
# 提交数据库事务处理
self.conn.commit()
except Exception as e:
# 如果出现错误就回滚
print(e)
self.conn.rollback()
return result
def __del__(self):
# 关闭数据库连接
self.close()
if __name__ == "__main__":
print(MySQLObj(host='10.8.214.191', port=3306, user='root', password='123456', db='interface_v03').get_all("select * from userinfo"))
| true
|
aa390b2e521d804333f94ea41b95fb5d02c8ce5a
|
Python
|
juantor16/Python
|
/Calculate_kinetic_energy.py
|
UTF-8
| 576
| 3.859375
| 4
|
[] |
no_license
|
# Calculate Kinetic Energy
print "this program calculates the kinetic energy of a moving object."
m_string = input ("Enter the object's mass in Kilograms: ")
m=float(m_string)
# m_string = input ("Enter the object's mass in Kilograms: ")
# m=float(m_string)
# is equal to:
#m_string = float(input ("Enter the object's mass in Kilograms: "))
v_string = input ("enter the object's speed in meters per second: ")
v=float (v_string)
e=0.5*m*v*v
print ("The object has "+str(e)+ " Joules of energy.")
raw_input ("press enter to exit ")
Andrew is friends with a ninja turtle.
| true
|
b47eee704efddac2a0d6deb05a1273850b4bbe7c
|
Python
|
ryosuke0825/atcoder_python
|
/ABC_C/ABC172_C.py
|
UTF-8
| 611
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import itertools
import bisect
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
aa = [0] + list(itertools.accumulate(A))
bb = [0] + list(itertools.accumulate(B))
ans = bisect.bisect_left(aa, K)-1
ans = max(ans, bisect.bisect_left(bb, K)-1)
for i in reversed(range(N+1)):
tmp_K = K-aa[i]
if tmp_K == 0:
ans = max(ans, i)
elif tmp_K < 0:
continue
if i + M <= ans:
continue
if tmp_K >= bb[-1]:
ans = max(ans, i+M)
continue
ans = max(ans, bisect.bisect_left(bb, tmp_K)-1+i)
print(ans)
| true
|
f2e99d8b270e434aeb3cb242b37f511bb75a55bc
|
Python
|
madhavambati/Convolutional-Neural-Network-with-Numpy
|
/model/functions.py
|
UTF-8
| 9,440
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
import gzip
'''
This file contains all the essential functions that are used in the network '''
''' Getting data '''
#Extract images by reading the file bytestream.
#Reshape the read values into a 2D matrix of dimensions [n, h*w]
def extract_data(filename, num_images, IMAGE_WIDTH):
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(16)
buf = bytestream.read(IMAGE_WIDTH * IMAGE_WIDTH * num_images)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data.reshape(num_images, IMAGE_WIDTH*IMAGE_WIDTH)
return data
#Extract labels by reading the file bytestream.
#Reshape the read values into a row matrix of dimensions [n, 1]
def extract_labels(filename, num_images):
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(8)
buf = bytestream.read(1 * num_images)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
return labels
''' Initialising weights and biases for all the layers'''
#random values for filters in convolution layers
def Filter_weights(size):
#Initialize filter using a normal distribution with and a
#standard deviation inversely proportional the square root of the number of units
stddev = 1/np.sqrt(np.prod(size))
return np.random.normal(loc = 0.0, scale = stddev, size = size)
#random values for weights in deep layers
def deep_weights(size):
#Initialize weights with a random normal distribution
return np.random.standard_normal(size = size)*0.01
'''convolution function'''
def convolution(image, Filter, bias, stride=1):
# convolution of input image with a filter of dimensions(n_f,n_c,f,f)
# n_f is no.of filters
# n_c is no.of channels
# f,f are height & width
# image dimensions(n_c, image_h, image_w)
# n_c is no.of channels in image
# img_h is height of image
# img_w is width of image
(n_c, img_h, img_w) = image.shape
(n_f, n_c, f, f) = Filter.shape
# output dimensions after convolution
out_h = int((img_h - f) / stride) + 1 # height of output matrix
out_w = int((img_h - f) / stride) + 1 # width of output matrix
# n_f will be the depth of the matrix
out = np.zeros((n_f, out_h, out_w))
# convolution of image_array with filter yeilds out_array
# for i in range of no.of filters
# define a row , out_y variabless to hover along rows of image, out_matrix respectively
# define a column , out_x variables to hover along columns of image, out_matrix respectively
# convolution is done in the ranges of image_height to image_width
for i in range(n_f):
row = out_row = 0
while row + f <= img_h:
column = out_column = 0
while column + f <= img_w:
out[i, out_row, out_column] = np.sum(Filter[i] * image[:, row: row + f, column: column + f]) + bias[i]
column += stride
out_column += 1
row += stride
out_row += 1
return out
'''Maxpooling function'''
def maxpool(image, f=5, stride=2):
(n_c, img_h, img_w) = image.shape # input image dimension
out_h = int((img_h - f) / stride) + 1 # output image height
out_w = int((img_w - f) / stride) + 1 # output image width
max_out = np.zeros((n_c, out_h, out_w)) # matrix to hold maxpooled image(or)array
# maxpool of image_array with filter yeilds max_out array
# for i in range of no.of channels
# define a row , out_y variables to hover along rows of image, out_matrix respectively
# define a column , out_x variables to hover along columns of image, out_matrix respectively
for i in range(n_c):
row = out_row = 0
while row + f <= img_h: # slide the max pooling window vertically(along rows) across the image
column = out_column = 0
while column + f <= img_w: # slide the max pooling window vertically(along columns) across the image
# choose the maximum value within the window at each step and store it to the output matrix
max_out[i, out_row, out_column] = np.max(image[i, row: row + f, column: column + f])
column += stride
out_column += 1
row += stride
out_row += 1
return max_out
'''Softmax function'''
def softmax(activations):
# activations raised to the power of 'e'
activations_raised_exp = np.exp(activations)
# divide by sum of all exponentiated activations to get the required probability (0,1)
probabilities = activations_raised_exp / np.sum(activations_raised_exp)
return probabilities
'''Loss function'''
def loss_function(pred, label):
# loss function for softmaxlayer will be -Σylogŷ
# where- y is given label and ŷ is pred output
net_loss = -np.sum(label * np.log(pred))
return net_loss
'''Convolution during backpropagation'''
# back-propagation operations in convolution layers
# for convolution_backward we need derivative of convolution in the previous layer
# 'dconv_prev' is the derivative of convolution in the previous layer
# 'image' is referred to as the input for the current conv layer with which the convolution operation is applied
# 'Filter' is the filter used in the current layer
# The obtained convoluted matrix will be the 'conv_prev' for the current layer in backpropagation
# Backpropagation of the convolution layers is explained in the link below
# https://medium.com/@2017csm1006/forward-and-backpropagation-in-convolutional-neural-network-4dfa96d7b37e
def convolution_backprop(dconv_prev, image, Filter, stride):
(n_f, n_c, f, f) = Filter.shape
(n_c, img_h, img_w) = image.shape
dimage = np.zeros(image.shape)
dFilter = np.zeros(Filter.shape)
dbias = np.zeros((n_f, 1))
for i in range(n_f):
row = dimage_y = 0
while row + f <= img_h:
column = dimage_x = 0
while column + f <= img_w:
dFilter[i] += dconv_prev[i, dimage_y, dimage_x] * image[:, row:row + f, column:column + f]
dimage[:, row:row + f, column:column + f] += dconv_prev[i, dimage_y, dimage_x] * Filter[i]
column += stride
dimage_x += 1
row += stride
dimage_y += 1
dbias[i] = np.sum(dconv_prev[i])
return dimage, dFilter, dbias
'''Maxpooling during backpropagation'''
# back-propagation in maxpool layer
# 'dpooled' is the derivative of previous layer i.e pooled layer
# 'maxpooled' is the maxpool layer's output
# 'Filter' will be 2*2 with 'stride' = 2
# save the index of the input image at which the max values are captured in the maxpool layer
# use the index to iterate across the output matrix while equating the corresponding higher values in pooledlayer
# back propagation in maxpool layers are explained in the link below
# https://leonardoaraujosantos.gitbooks.io/artificial-inteligence/content/pooling_layer.html
def maxpool_backprop(dpooled, maxpooled, Filter, stride):
(n_c, maxpooled_dim, _) = maxpooled.shape # maxpooled_height = maxpooled_width=maxpooled_dim
dmaxpooled = np.zeros(maxpooled.shape)
for i in range(n_c):
row = dmaxpooled_y = 0
while row + Filter <= maxpooled_dim:
column = dmaxpooled_x = 0
while column + Filter <= maxpooled_dim:
# obtain index of largest value in input for current window
index = np.nanargmax(maxpooled[i, row:row + Filter, column:column + Filter])
(a, b) = np.unravel_index(index, maxpooled[i, row:row + Filter, column:column + Filter].shape)
dmaxpooled[i, row + a, column + b] = dpooled[i, dmaxpooled_y, dmaxpooled_x]
column += stride
dmaxpooled_x += 1
row += stride
dmaxpooled_y += 1
return dmaxpooled
'''predict function'''
# after training the neural net just do the Forward-feed
def predict(image, params, conv_stride = 1, pooling_filter = 2, pooling_stride = 2 ):
[f1, f2, w3, w4, b1, b2, b3, b4] = params
print('done')
convolution_1 = convolution(image, f1, b1, conv_stride) # first covolution
convolution_1[convolution_1 <= 0] = 0 # pass through ReLU non-linearity
convolution_2 = convolution(convolution_1, f2, b2, conv_stride) # second convolution
convolution_2[convolution_2 <= 0] = 0 # pass through ReLU non-linearity
maxpool_layer = maxpool(convolution_2, pooling_filter, pooling_stride) # maxpooling
(nf, dim, _) = maxpool_layer.shape
print('done')
fc = maxpool_layer.reshape((nf * dim * dim, 1)) # flattened layer
print(fc.shape)
z1 = w3.dot(fc) + b3 # dense layer_1
z1[z1 <= 0] = 0 # ReLU non-linearity
out = w4.dot(z1) + b4 # dense layer_2
probabilities = softmax(out) # pass through softmax function
pred = np.argmax(probabilities)
prob = np.max(probabilities)
#prob = max(probabilities)
#for i in range(10):
# if(probabilities[i] == max(probabilities)):
# pred = i
return pred, prob
| true
|
9b413b2d5b2d809e3f548ed780af84eaa831396e
|
Python
|
madhu74/deconst-openapi-preparer
|
/tests/test_tocbuilder.py
|
UTF-8
| 7,632
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python3
'''
test_tocbuilder
----------------------------------
Tests for `tocbuilder` module.
'''
import unittest
import subprocess
import sys
import os
import re
from os import path
from bs4 import BeautifulSoup
sys.path.append(path.join(path.dirname(__file__), '..'))
from openapipreparer.builders.tocbuilder import tag_it
from openapipreparer.builders.tocbuilder import sibs_it
from openapipreparer.builders.tocbuilder import parse_it
from openapipreparer.builders.tocbuilder import htmlify
class TocBuilderTestCase(unittest.TestCase):
'''
Tests for the tocbuilder methods
'''
def setUp(self):
pass
def tearDown(self):
soup = None
tag = None
html_sample = None
the_method = None
the_result = None
def test_tag_it_if_id_present(self):
'''
Does tag_it provide a string when given good input?
'''
soup = BeautifulSoup('<h2 id="yep">heading</h2>', 'html.parser')
tag = soup.h2
self.assertEqual('yep', tag_it(tag))
def test_tag_it_if_id_not_present(self):
'''
Does tag_it provide a string when given good input without an id field?
'''
soup = BeautifulSoup('<h2>yep that is it</h2>', 'html.parser')
tag = soup.h2
self.assertEqual('yepthatisit', tag_it(tag))
def test_sibs_it_has_sib(self):
'''
If the tag is followed by a sibling, does it provide the right output?
'''
soup = BeautifulSoup('<h4>test</h4><h4>test</h4>', 'html.parser')
the_method = sibs_it(
soup.h4, 'h4', ['current_heading_list'], re.compile(
'h[2,3,4]'), ['toc_builder'])
self.assertEqual(
(['toc_builder'], ['current_heading_list'], None, '4'), the_method)
def test_sibs_h4_followed_by_h3(self):
'''
If the h4 tag is followed by an h3 tag, does it provide the right
output?
'''
soup = BeautifulSoup('<h4>test</h4><h3>test</h3>', 'html.parser')
the_method = sibs_it(
soup.h4, 'h4', ['current_heading_list'], re.compile(
'h[2,3,4]'), ['toc_builder'], ['h3 list'])
self.assertEqual(
(['toc_builder'], [], ['h3 list', ['current_heading_list']], '3'),
the_method)
def test_sibs_h4_followed_by_h2(self):
'''
If the h4 tag is followed by an h2 tag, does it provide the right
output?
'''
soup = BeautifulSoup('<h4>test</h4><h2>test</h2>', 'html.parser')
the_method = sibs_it(
soup.h4, 'h4', ['current_heading_list'], re.compile(
'h[2,3,4]'), ['toc_builder'])
self.assertEqual(
(['toc_builder', ['current_heading_list']],
[], None, '2'), the_method)
def test_parse_it_h2_only(self):
'''
Does parse_it work for h2 tags only?
'''
self.maxDiff = None
html_sample = '<body><h2>Heading 1 h2</h2><h2>Heading 2 h2</h2></body>'
the_result = ['<li><a href="#Heading1h2">Heading 1 h2</a></li>',
'<li><a href="#Heading2h2">Heading 2 h2</a></li>']
the_method = parse_it(html_sample)
self.assertEqual(the_method, the_result)
# FIXED: These next two tests make the test_parse_it_h2_only test break.
def test_parse_it_h2_and_h3(self):
'''
Does parse_it work for h2 and h3 tags?
'''
self.maxDiff = None
html_sample = (
'<body><h2>Heading 1 h3</h2><h3>Heading 1.1 h3</h3>'
'<h3>Heading 1.2 h3</h3><h2>Heading 2 h3</h2>'
'<h3>Heading 2.1 h3</h3><h3>Heading 2.2 h3</h3></body>')
# BUG: Need to figure out why the double square bracket appears on the
# first 2nd level here.
the_result = ['<li><a href="#Heading1h3">Heading 1 h3</a></li>', [
['<li><a href="#Heading1.1h3">Heading 1.1 h3</a></li>',
'<li><a href="#Heading1.2h3">Heading 1.2 h3</a></li>']],
'<li><a href="#Heading2h3">Heading 2 h3</a></li>', [
'<li><a href="#Heading2.1h3">Heading 2.1 h3</a></li>',
'<li><a href="#Heading2.2h3">Heading 2.2 h3</a></li>']]
the_method = parse_it(html_sample)
self.assertEqual(the_method, the_result)
def test_parse_it_pass(self):
'''
Does parse_it work for h2, h3, and h4 tags?
'''
self.maxDiff = None
html_sample = (
'<body><h2>Heading 1 h4</h2><h3>Heading 1.1 h4</h3>'
'<h4>Heading 1.1.1 h4</h4><h4>Heading 1.1.2 h4</h4>'
'<h3>Heading 1.2 h4</h3><h4>Heading 1.2.1 h4</h4>'
'<h2>Heading 2 h4</h2><h3>Heading 2.1 h4</h3>'
'<h3>Heading 2.2 h4</h3></body>')
the_result = ['<li><a href="#Heading1h4">Heading 1 h4</a></li>', [
'<li><a href="#Heading1.1h4">Heading 1.1 h4</a></li>', [
'<li><a href="#Heading1.1.1h4">Heading 1.1.1 h4</a></li>',
'<li><a href="#Heading1.1.2h4">Heading 1.1.2 h4</a></li>'],
'<li><a href="#Heading1.2h4">Heading 1.2 h4</a></li>', [
'<li><a href="#Heading1.2.1h4">Heading 1.2.1 h4</a></li>']],
'<li><a href="#Heading2h4">Heading 2 h4</a></li>', [
'<li><a href="#Heading2.1h4">Heading 2.1 h4</a></li>',
'<li><a href="#Heading2.2h4">Heading 2.2 h4</a></li>']]
the_method = parse_it(html_sample)
self.assertEqual(the_method, the_result)
def test_parse_it_full_pass(self):
'''
Does parse_it work for a full sample?
'''
self.maxDiff = None
html_sample = (
'<body><h2>Heading 1 h4</h2><p>Random text</p>'
'<h3>Heading 1.1 h4</h3><p>Random text</p><p>Random text</p>'
'<h4>Heading 1.1.1 h4</h4><p>Random text</p><p>Random text</p>'
'<h4>Heading 1.1.2 h4</h4><p>Random text</p>'
'<h3>Heading 1.2 h4</h3><p>Random text</p><p>Random text</p>'
'<h4>Heading 1.2.1 h4</h4><p>Random text</p>'
'<h2>Heading 2 h4</h2><p>Random text</p><p>Random text</p>'
'<h3>Heading 2.1 h4</h3><p>Random text</p>'
'<h3>Heading 2.2 h4</h3><p>Random text</p><p>Random text</p>'
'<p>Random text</p></body>')
the_result = ['<li><a href="#Heading1h4">Heading 1 h4</a></li>', [
'<li><a href="#Heading1.1h4">Heading 1.1 h4</a></li>', [
'<li><a href="#Heading1.1.1h4">Heading 1.1.1 h4</a></li>',
'<li><a href="#Heading1.1.2h4">Heading 1.1.2 h4</a></li>'],
'<li><a href="#Heading1.2h4">Heading 1.2 h4</a></li>', [
'<li><a href="#Heading1.2.1h4">Heading 1.2.1 h4</a></li>']],
'<li><a href="#Heading2h4">Heading 2 h4</a></li>', [
'<li><a href="#Heading2.1h4">Heading 2.1 h4</a></li>',
'<li><a href="#Heading2.2h4">Heading 2.2 h4</a></li>']]
the_method = parse_it(html_sample)
self.assertEqual(the_method, the_result)
def test_htmlify_pass(self):
'''
Does htmlify return a list wrapped in <ul></ul>?
'''
the_list = ['<li>item1</li>', [
'<li>sub1</li>', '<li>sub2</li>',
['<li>subsub1</li>', '<li>subsub2</li>']],
'<li>item2</li>']
the_result = '<ul><li>item1</li><ul><li>sub1</li><li>sub2</li><ul><li>subsub1</li><li>subsub2</li></ul></ul><li>item2</li></ul>'
the_method = htmlify(the_list)
self.assertEqual(the_method, the_result)
if __name__ == '__main__':
unittest.main()
| true
|
577a9945956cbc1e29c668adbb1981d87afda2c5
|
Python
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2445/60595/238455.py
|
UTF-8
| 777
| 3.171875
| 3
|
[] |
no_license
|
def Test():
s=input()
s=s.replace("s"," ")
s=s.replace("t"," ")
s=s.replace("\""," ")
s=s.replace("="," ")
s=s.replace(" ","")
q=s.split(",")
word1=q[0]
word2=q[1]
maps1=[]
maps2=[]
if(len(word1)!=len(word2)):
print("false")
else:
for i in range(0,128):
maps1.append(0)
maps2.append(0)
for i in range(0,len(word1)):
maps1[ord(word1[i])]=maps1[ord(word1[i])]+1
maps2[ord(word2[i])]=maps2[ord(word2[i])]+1
if(check(maps1,maps2)):
print("true")
else:
print("false")
def check(a,b):
for i in range(0,len(a)):
if(a[i]!=b[i]):
return False
return True
if __name__ == "__main__":
Test()
| true
|
fea97795460b620cb401ec167efeaa90090bfff9
|
Python
|
agentnova/LuminarPython
|
/Luminaarpython/Multitasking/pgm3.py
|
UTF-8
| 524
| 2.90625
| 3
|
[] |
no_license
|
from threading import *
class Mythread(Thread):
def run(self):
for i in range(1,10):
print(i)
print(current_thread().getName())
t=Mythread()
t.start()
for i in range(1,10):
print(i)
print(current_thread().getName())
# after connecting print connect:[clnt name]
# then message send message:[msg] each of the client
# print disconnect:[clnt name]
# client
# input login name
# send connct msg to servr
# loop message input
# send msg to server
# send disconnect message through exit
| true
|
fe0715726349b293c3053026901ba530b7ebfa6b
|
Python
|
HenryBalthier/digger
|
/MY_digger/riskctl.py
|
UTF-8
| 785
| 2.765625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import csv
class Riskctl(object):
def __init__(self):
self.cts = {
'code': 0,
'exchange': 1,
'name': 2,
'spell': 3,
'long_margin_ratio': 4,
'short_margin_ratio': 5,
'price_tick': 6,
'volume_multiple': 7
}
#@classmethod
def csv_test(self, code=None):
n = []
with open('./data/contracts.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
if row[self.cts['code']] == code:
n.append(row)
return n
if __name__ == '__main__':
s = 'I.SHFE-1.Day'
r = Riskctl()
m = r.csv_test(s.split('.')[0])
print m
#assert (len(m) == 1)
| true
|
734024bf4aca1ace692402d5968508fa39e5faba
|
Python
|
NatashaMiyaguti/Projeto5_Blue
|
/classes/personagemCao.py
|
UTF-8
| 3,227
| 3.46875
| 3
|
[] |
no_license
|
from sys import exit
from fases.fases import fase1
from auxiliar.funcoes_auxiliares import final
from classes.relogio import Relogio
from classes.carrocinha import Carrocinha
def gameOver():
print('Game Over!')
final()
reiniciar = input('Gostaria de jogar novamente (s/n)? ')
if reiniciar == 's':
relogio = Relogio()
nome = input('Digite o nome do seu cãozinho: ').title()
personagem = Personagem(nome)
fase1(relogio, personagem)
else:
print('Obrigado por jogar!')
exit()
class Personagem:
def __init__(self, nome):
self.__nome = nome
self.__humor = 50
self.__fome = 50
self.__frio = 50
self.__energia = 50
self.__lugar = 'terreno baldio'
def __str__(self): # Altera os atributos confome necessidade, sendo valores positivos ou negativos#
return f'''
Status {self.__nome}:
==============================
|{("Humor - " + str(self.__humor) + "%").center(28)}|
|{("Fome - " + str(self.__fome) + "%").center(28)}|
|{("Frio - " + str(self.__frio) + "%").center(28)}|
|{("Energia - " + str(self.__energia) + "%").center(28)}|
==============================
'''
def muda_humor(self,humor_novo):
humnov = humor_novo
if humnov >= 0:
print(f'''Humor +{humnov}%''')
else:
print(f'''Humor -{abs(humnov)}%''')
self.__humor += humnov
if self.__humor >= 100:
self.__humor = 100
elif self.__humor <= 0:
print('Humor chegou a Zero.')
gameOver()
def muda_fome(self,fome_nova):
fomnov = fome_nova
if fomnov >= 0:
print(f'''Fome +{fomnov}%''')
else:
print(f'''Fome -{abs(fomnov)}%''')
self.__fome += fomnov
if self.__fome >= 100:
self.__fome = 100
elif self.__fome <= 0:
print('Fome chegou a Zero.')
gameOver()
def muda_frio(self,frio_novo):
frinov = frio_novo
if frinov >= 0:
print(f'''Frio +{frinov}%''')
else:
print(f'''Frio -{abs(frinov)}%''')
self.__frio += frinov
if self.__frio >= 100:
self.__frio = 100
elif self.__frio <= 0:
print('Frio chegou a Zero.')
gameOver()
def muda_energia(self,nova_energia):
enenov = nova_energia
if enenov >= 0:
print(f'''Energia +{enenov}%''')
else:
print(f'''Energia -{abs(enenov)}%''')
self.__energia += enenov
if self.__energia >= 100:
self.__energia = 100
elif self.__energia <= 0:
print('Energia chegou a Zero.')
gameOver()
def muda_lugar(self,novo_lugar):
self.__lugar = novo_lugar
@property
def nome(self):
return self.__nome
@property
def lugar(self):
return self.__lugar
def atualizacao_frio(self,relogio,frio = -5):
if relogio.noite_fria():
self.muda_frio (frio)
else:
self.muda_frio(frio * -1)
| true
|
8fa77f4f3b4e6600a278839002f71355bbaa13c2
|
Python
|
q-riku/algorithm
|
/19-3-1 Problem03-1.py
|
UTF-8
| 1,882
| 3.71875
| 4
|
[] |
no_license
|
"""
#1 from LeetCode
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
===============================================================================
===============================================================================
"""
class Solution(object):
# A2
def binary_search(self, li, left, right, val):
while left <= right:
mid = (left + right) // 2
if li[mid][0] == val:
return mid
elif li[mid][0] > val:
right = mid - 1
else:
left = mid + 1
else:
return None
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# A1
n = len(nums)
for i in range(n):
for j in range(i):
if nums[i] + nums[j] == target:
return sorted([i, j])
# A2
new_nums = [[num, i] for i, num in enumerate(nums)]
new_nums.sort(key=lambda x: x[0])
m = len(new_nums)
for i in range(m):
a = new_nums[i][0]
b = target - a
if b >= a:
j = self.binary_search(new_nums, i + 1, m - 1, b)
else:
j = self.binary_search(new_nums, 0, i - 1, b)
if j:
break
return sorted([new_nums[i][1], new_nums[j][1]])
| true
|
0d09c4aaf3a2e4d633e891e21f329bfdcf74c4bd
|
Python
|
irissooa/Algorithm-with-Python
|
/Baekjoon/스택큐/BOJ_10828_스택.py
|
UTF-8
| 1,021
| 4.15625
| 4
|
[] |
no_license
|
'''
정수를 저장하는 스택,
스택은 LIFO(마지막에 들어간것이 먼저나감)
push X : X를 스택에 넣는 연산
pop : 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력, 만약 스택에 들어있는 정수가 없는 경우 -1 출력
size : 스택에 들어있는 정수의 개수 출력
empty : 스택이 비어있으면 1, 아니면 0 출력
top : 스택의 가장 위에 있는 정수 출력, 만약 없으면 -1
'''
import sys
input = sys.stdin.readline
N = int(input())
stack = []
for _ in range(N):
order = input()
if "push" in order:
stack.append(int(order[5:]))
elif "pop" in order:
if stack:
print(stack.pop())
else:
print(-1)
elif "size" in order:
print(len(stack))
elif "empty" in order:
if stack:
print(0)
else:
print(1)
elif "top" in order:
if stack:
print(stack[-1])
else:
print(-1)
#print(order,stack)
| true
|
c09f6a251f15f790fab19bfb5184baccc7e69d62
|
Python
|
sunsun1001/NASA_Weibull
|
/weibullDist.py
|
UTF-8
| 1,167
| 3.15625
| 3
|
[] |
no_license
|
import numpy as np
import pylab as pl
import scipy.special as ss
import matplotlib.pyplot as plt
# a=scale parameter b=shape parameter mew=x(variable)
def weib(a,b,mew):
e1 = (b/a)
e2 = ((mew/a)**(b-1))
e3 = np.exp((-(mew/a)**b))
return e1*e2*e3
def plot_weib(a,b,xmin,xmax):
Ly = []
Lx = []
mews = np.mgrid[xmin:xmax:100j]
for apple in mews:
Lx.append(apple)
Ly.append(weib(a, b, apple))
pl.plot(Lx, Ly, label="a=%f, b=%f" %(a,b))
def main():
xmin=0.0
xmax=5.0
a,b = np.loadtxt('data.txt', unpack=True, usecols=[0,1] )
if type(a)==np.ndarray:
for k in range(len(a)):
plot_weib(a[k],b[k])
elif type(a)==np.float64:
plot_weib (a,b,xmin,xmax)
#scale=input('Please enter the scale parameter: ')
#shape=input('Please enter the shape parameter: ')
#plot_weib(scale,shape)
plt.title("This is a PDF Graph")
plt.xlabel("X")
plt.ylabel("Probability Density Function")
pl.xlim(xmin, xmax)
pl.ylim(0.0, 3)
pl.legend()
pl.show()
if __name__ == "__main__":
main()
| true
|
ae6f01ca2a94da6d1c2038c0e7f6263bf6c7a04b
|
Python
|
pythrick/drf-cli
|
/cookiecutters/project/{{cookiecutter.module_name}}/{{cookiecutter.module_name}}/apps/user/managers/user.py
|
UTF-8
| 652
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
from django.contrib.auth.base_user import BaseUserManager
from django.db import transaction
class UserManager(BaseUserManager):
@transaction.atomic
def create_user(self, name: str, email: str, password: str, **kwargs):
user = self.model(name=name, email=email, **kwargs)
user.set_password(password)
user.save()
return user
@transaction.atomic
def create_superuser(self, name, email, password, **kwargs):
user = self.create_user(name, email, password, **kwargs)
user.is_active = True
user.is_staff = True
user.is_superuser = True
user.save()
return user
| true
|
b1e70af0bca989832f5ca113ca214cd18f2f9803
|
Python
|
gshreve01/covid19-flask
|
/covid19/models.py
|
UTF-8
| 5,147
| 2.65625
| 3
|
[] |
no_license
|
from django.db import models
# Create your models here.
class State(models.Model):
geocodeid = models.IntegerField("Geographic Code Identifier",primary_key=True)
name = models.CharField("State Name", null=False, max_length=100, unique=True)
abbreviation = models.CharField("State Abbreviation", null=False, max_length=2)
def __str__(self):
return self.name
class CensusData(models.Model):
state = models.ForeignKey(State, on_delete=models.CASCADE, primary_key=True, unique=True, db_column="geocodeid")
population = models.IntegerField("Population", null=False)
density = models.FloatField("Population Density", null=True)
def __str__(self):
return f"{self.name}:{str(self.geocodeid)}"
class CoronaVirusTesting(models.Model):
state = models.ForeignKey(State, on_delete=models.CASCADE, primary_key=True, unique=True, db_column="geocodeid")
percentageoftestingtarget = models.IntegerField("Percentage Of Testing Target", null=True)
positivitytestrate = models.IntegerField("Positivity Test Rage", null=True)
dailytestsper100k = models.IntegerField("Daily Tests Per 100,000", null=True)
hospitalizedper100k = models.IntegerField("Hospitalized Per 100,000", null=True)
def __str__(self):
return f"{self.name}:{str(self.state.geocodeid)}"
class DailyData(models.Model):
state = models.ForeignKey(State, on_delete=models.CASCADE, db_column="geocodeid")
date = models.DateField("Date Pulled From Feed")
positive = models.IntegerField("Positive Test Rate Percentage", null=True)
negative = models.IntegerField("Negative Test Rate Percentage", null=True)
hospitalizedcurrently = models.IntegerField("Number of People Currently Hospitalized", null=True)
hospitalizedcumulative = models.IntegerField("Number of People Hospitalized Cumulative", null=True)
inicucurrently = models.IntegerField("Number of People Currently in ICU", null=True)
inicucumulative = models.IntegerField("Number of People in ICU Cumulative", null=True)
onventilatorcurrently = models.IntegerField("Number of People on Ventilator Currently", null=True)
onventilatorcumulative = models.IntegerField("Number of People on Ventilator Cumulative", null=True)
recovered = models.IntegerField("Number of People Who Recovered", null=True)
death = models.IntegerField("Number of People Who have Died", null=True)
deathconfirmed = models.IntegerField("Number of People Who have Confirmed to have Died from COVID-19", null=True)
deathprobable = models.IntegerField("Number of People Who have Probably Died from COVID-19", null=True)
positiveincrease = models.IntegerField("Number of Positive Test Increases", null=True)
negativeincrease = models.IntegerField("Number of Negative Test Increases", null=True)
totaltests = models.IntegerField("Number of Total Tests", null=True)
newtests = models.IntegerField("Number of New Tests", null=True)
newdeaths = models.IntegerField("Number of New Deaths", null=True)
newhospitalizations = models.IntegerField("Number of New Hospitalizations", null=True)
def __str__(self):
return f"{self.name}:{str(self.state.geocodeid)}"
class Meta:
unique_together=(("state", "date"),)
class EconomyState(models.Model):
id = models.IntegerField("ID", primary_key=True)
state = models.CharField("State", max_length=25, null=False)
def __str__(self):
return self.state
class Event(models.Model):
id = models.IntegerField("ID", primary_key=True)
eventname = models.CharField("Name of Event", max_length=50, null=False)
def __str__(self):
return self.eventname
class EventDate(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE, db_column="eventid")
eventdate = models.DateField("Date of Event")
def __str__(self):
return f"{self.event.eventname}:{self.eventdate.strftime('%Y-%m-%d')}"
class Meta:
unique_together=(("event", "eventdate"),)
class GredeEffDt(models.Model):
state = models.ForeignKey(State, to_field='name', db_column='state', primary_key=True, on_delete=models.CASCADE)
grade = models.CharField("State Grade", max_length=3, null=False)
stayathomedeclaredate = models.DateField("Date Stay At Home was Declared", null=True)
stayathomestartdate = models.DateField("Date Stay At Home Started", null=True)
def __str__(self):
return f"{self.name}:{self.state.name}"
class StateReopening(models.Model):
state = models.ForeignKey(State, on_delete=models.CASCADE, primary_key=True, unique=True, db_column="geocodeid")
economystate = models.ForeignKey(EconomyState, on_delete=models.CASCADE, null=False, db_column="economystateid")
stayathomeexpiredate = models.DateField("Date Stay At Home Order Expired", null=True)
openbusinesses = models.CharField("Open Businesses Description", null=True, max_length=3000)
closedbusinesses = models.CharField("Closed Businesses Description", null=True, max_length=3000)
hasstayathomeorder = models.BooleanField("Has Stay At Home Order", null=True)
| true
|
5b4eb891a56836c7ed5187d4b8b3b0847519acc2
|
Python
|
AlexKotl/stepik-python-lessons
|
/3/books_advanced.py
|
UTF-8
| 1,233
| 3.21875
| 3
|
[] |
no_license
|
from books import *
class AdvancedPerson(Person):
def __init__(self, name):
super().__init__(name)
def search(self, book, name_page):
return book.search(name_page)
def read(self, book, page):
if isinstance(page, int):
return super().read(book, page)
else:
return super().read(book, self.search(book, page))
def write(self, book, page, text):
if isinstance(page, int):
return super().write(book, page, text)
else:
return super().write(book, self.search(book, page), text)
class NovelWithTable(Novel):
"""класс - книга с оглавлением"""
def __init__(self, author, year, title, content=None, table=None):
super().__init__(author, year, title, content)
self.table = table or {}
def search(self, name_page):
if name_page not in self.table:
raise PageNotFoundError
return self.table[name_page]
def add_chapter(self, chapter, page):
return self.table.update({ chapter: page })
def remove_chapter(self, chapter):
if chapter not in self.table:
raise PageNotFoundError
del self.table[chapter]
| true
|
d77f13de00222d02eb4e53f873dc73e02b01f0e6
|
Python
|
josemscnogueira/disparitypy
|
/disparitypy/__main__.py
|
UTF-8
| 592
| 2.796875
| 3
|
[] |
no_license
|
import argparse
import sys
from .comparators.comparator import UComparator
"""
Definition of the main function body
"""
def main():
"""
Argument parsing and initial test
"""
parser = argparse.ArgumentParser('disparity')
parser.add_argument('folder1')
parser.add_argument('folder2')
arguments = parser.parse_args()
ccc = UComparator.from_paths(arguments.folder1,
arguments.folder2)
print(ccc.compare())
return 0
"""
Python binding for main script
"""
if __name__ == "__main__":
sys.exit(main())
| true
|
8916213d2ad46dbb262c6ae1c921e60040c69d78
|
Python
|
rajivs15/set_6
|
/countKinlist.py
|
UTF-8
| 154
| 2.71875
| 3
|
[] |
no_license
|
N,K=map(int,(input().split()))
m=list(map(int,input().split()))
count=0
if len(m)==N:
for i in range (0,N):
if m[i]==K:
count=count+1
print (count)
| true
|
19b3bf62ba0d7133bb8fc73838f360bd4bffb750
|
Python
|
Kaitlyn0712/CS106A-Stanford
|
/lectures/21-Practice/raw/process.py
|
UTF-8
| 1,377
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
import csv
NUM_YEARS = 216
IGNORE = set([
'Dominica',
'Monaco',
'Andorra',
'Turks and Caicos Islands',
'San Marino',
'Bermuda',
'Nauru',
'Cayman Islands',
'Palau',
'Tuvalu',
'St. Kitts and Nevis',
'Marshall Islands',
'Martinique',
'Guam',
'French Polynesia',
'Western Sahara',
'Virgin Islands (U.S.)',
'Croatia',
'Reunion',
'Netherlands Antilles',
'Mayotte',
'New Caledonia',
'Guadeloupe',
'French Guiana'
])
def main():
gdpMap = load('gdpRaw.csv')
lifeMap = load('lifeRaw.csv')
print len(gdpMap)
print len(lifeMap)
for key in gdpMap:
if not key in lifeMap:
print "'" + key + "',"
for key in lifeMap:
if not key in gdpMap:
print "'" +key + "',"
saveMap('gdp.csv', gdpMap)
saveMap('life.csv', lifeMap)
def saveMap(fileName, countryMap):
writer = csv.writer(open(fileName, 'wb'))
for key in countryMap:
row = [key]
row += countryMap[key]
writer.writerow(row)
def load(fileName):
reader = csv.reader(open(fileName))
header = reader.next()
data = {}
for row in reader:
countryName = row[0]
if countryName in IGNORE: continue
if countryName:
values = numberize(row[1:])
if len(values) == NUM_YEARS:
data[countryName] = values
return data
def numberize(values):
nums = []
for v in values:
try:
intV = float(v)
nums.append(intV)
except:
pass
return nums
if __name__ == '__main__':
main()
| true
|
c7dc0d5cf67878bcdd281f91b248c0341265dff5
|
Python
|
ThomasWilshaw/edlReader
|
/edl_reader.py
|
UTF-8
| 3,694
| 2.890625
| 3
|
[] |
no_license
|
#TODO:
#Clean EDL
#Recognise EDL features
#
import helper, os, sys, getopt
import edl as edlImp
def isInt(s):
#suppresses vlue errors
try:
int(s)
return int(s)
except ValueError:
pass
def getPaths(path):
#gets path to all mov's in folder
paths = []
extensions = tuple(['.mov', '.MOV'])
for root, subFolder, files in os.walk(path):
for item in files:
if item.endswith(extensions):
paths.append(str(os.path.join(root,item)))
return paths
class Shot(object):
def __init__(self, shotData):
self.shotData = shotData
def getAllData(self):
return self.shotData
def getGlobalStart(self):
return self.shotData[0]
def getClipStart(self):
return self.shotData[1]
def getDuration(self):
return self.shotData[2]
def getName(self):
return self.shotData[3]
class EDL(object):
data = []
lastShot = 0
def __init__(self, data):
self.data = data[0] #main data
self.path = data[1]
self.title = data[1]
print ("\n\n\n", data, "\n\n\n")
self.lastShot = len(self.data)
def getTitle(self):
return self.title
def getShotInfo(self, number):
if (number > self.lastShot or number < 1): #check requested shot is within bounds
raise ValueError('Shot %s out of bounds, max = %s, min = 1' % (number, self.lastShot))
return Shot(self.data[number-1])
def createBlenderEDL(self):
path = str(input("\nFile path of footage: "))
paths = getPaths(path)
clips = []
shotPaths = {}
for i in range(1, self.lastShot+1):
clip = self.getShotInfo(i).getClipName().strip("\n")
if clip not in clips:
clips.append(clip)
for clip in clips:
for path in paths:
if path.split('\\')[-1].split('.')[0] == clip.split(".")[0]:
shotPaths.update({clip:path})
continue
edlPath = str(self.path).strip('.edl') + '_blender.edl'
blenderEDL = open(edlPath, 'w')
blenderEDL.write("%-150s %8s %8s %8s %8s\n" %("PathToFile", "FileIn", "FileOut", "EditIn", "Shot"))
for i in range(1, self.lastShot+1):
shot = self.getShotInfo(i)
shotPath = shotPaths[shot.getClipName()]
blenderEDL.write("%-150s %8s %8s %8s %8d\n" %(str(shotPath)+":", str(shot.getSourceIn()['Frames'])+":", str(shot.getSourceOut()['Frames'])+":", str(shot.getEditIn()['Frames'])+":", i))
blenderEDL.close()
return 0
def main(argv):
try:
opts, args = getopt.getopt(argv,"hi:",["blender"])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print("EDL Tool: Does useful stuff with EDL's")
print("Author: Tom Wilshaw")
print("Version: 0.1")
print('\nUsage:\tpython3 edl_reader_2.py -i <input_edl> <options>\n')
print('Options:\n\n\t -blender: Create Blender EDL')
elif opt == '-i':
input_edl = str(arg)
a = edlImp.importEDL(input_edl)
edl = EDL(a)
elif opt == '--blender':
edl.createBlenderEDL()
if __name__ == "__main__":
a = edlImp.importEDL("C:/Users/Tom/Documents/EDL_reader/testEDL.edl")
a = edlImp.createEDLData(a)
edl = EDL(a)
print(edl.getTitle())
print(edl.getShotInfo(3).getAllData())
print(edl.getShotInfo(3).getName())
#print(edl.createBlenderEDL())
| true
|
868f372e93cac47c257c7bf3fe809aba29a0a107
|
Python
|
tlestang/PyBaMM
|
/pybamm/models/submodels/electrolyte_diffusion/leading_order_diffusion.py
|
UTF-8
| 3,698
| 2.5625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
#
# Class for leading-order electrolyte diffusion employing stefan-maxwell
#
import pybamm
from .base_electrolyte_diffusion import BaseElectrolyteDiffusion
class LeadingOrder(BaseElectrolyteDiffusion):
"""Class for conservation of mass in the electrolyte employing the
Stefan-Maxwell constitutive equations. (Leading refers to leading order
of asymptotic reduction)
Parameters
----------
param : parameter class
The parameters to use for this submodel
reactions : dict
Dictionary of reaction terms
**Extends:** :class:`pybamm.electrolyte_diffusion.BaseElectrolyteDiffusion`
"""
def __init__(self, param):
super().__init__(param)
def get_fundamental_variables(self):
c_e_av = pybamm.standard_variables.c_e_av
c_e_n = pybamm.PrimaryBroadcast(c_e_av, ["negative electrode"])
c_e_s = pybamm.PrimaryBroadcast(c_e_av, ["separator"])
c_e_p = pybamm.PrimaryBroadcast(c_e_av, ["positive electrode"])
return self._get_standard_concentration_variables(c_e_n, c_e_s, c_e_p)
def get_coupled_variables(self, variables):
N_e = pybamm.FullBroadcastToEdges(
0,
["negative electrode", "separator", "positive electrode"],
"current collector",
)
variables.update(self._get_standard_flux_variables(N_e))
c_e_av = pybamm.standard_variables.c_e_av
c_e = pybamm.Concatenation(
pybamm.PrimaryBroadcast(c_e_av, ["negative electrode"]),
pybamm.PrimaryBroadcast(c_e_av, ["separator"]),
pybamm.PrimaryBroadcast(c_e_av, ["positive electrode"]),
)
eps = variables["Porosity"]
variables.update(self._get_total_concentration_electrolyte(c_e, eps))
return variables
def set_rhs(self, variables):
param = self.param
c_e_av = variables["X-averaged electrolyte concentration"]
T_av = variables["X-averaged cell temperature"]
eps_n_av = variables["X-averaged negative electrode porosity"]
eps_s_av = variables["X-averaged separator porosity"]
eps_p_av = variables["X-averaged positive electrode porosity"]
deps_n_dt_av = variables["X-averaged negative electrode porosity change"]
deps_p_dt_av = variables["X-averaged positive electrode porosity change"]
div_Vbox_s_av = variables[
"X-averaged separator transverse volume-averaged acceleration"
]
sum_j_n_0 = variables[
"Sum of x-averaged negative electrode interfacial current densities"
]
sum_j_p_0 = variables[
"Sum of x-averaged positive electrode interfacial current densities"
]
sum_s_j_n_0 = variables[
"Sum of x-averaged negative electrode electrolyte reaction source terms"
]
sum_s_j_p_0 = variables[
"Sum of x-averaged positive electrode electrolyte reaction source terms"
]
source_terms = (
param.l_n * (sum_s_j_n_0 - param.t_plus(c_e_av, T_av) * sum_j_n_0)
+ param.l_p * (sum_s_j_p_0 - param.t_plus(c_e_av, T_av) * sum_j_p_0)
) / param.gamma_e
self.rhs = {
c_e_av: 1
/ (param.l_n * eps_n_av + param.l_s * eps_s_av + param.l_p * eps_p_av)
* (
source_terms
- c_e_av * (param.l_n * deps_n_dt_av + param.l_p * deps_p_dt_av)
- c_e_av * param.l_s * div_Vbox_s_av
)
}
def set_initial_conditions(self, variables):
c_e = variables["X-averaged electrolyte concentration"]
self.initial_conditions = {c_e: self.param.c_e_init}
| true
|
dc69e45bae0c7e9cddd03aecaeebf76bc604296f
|
Python
|
mcsheehan/RobotChallenge
|
/test/robot/command_parser_tests.py
|
UTF-8
| 2,239
| 2.828125
| 3
|
[] |
no_license
|
import unittest
from robot_challenge import CommandParser
from robot_challenge.robot_direction import RobotDirection
class CommandParserTests(unittest.TestCase):
def test_empty_string_returns_nothing(self):
test_input = ""
expected_output = []
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_north_string_returns_north(self):
test_input = "N"
expected_output = [RobotDirection.NORTH]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_south_string_returns_south(self):
test_input = "S"
expected_output = [RobotDirection.SOUTH]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_east_string_returns_west(self):
test_input = "E"
expected_output = [RobotDirection.EAST]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_west_string_returns_west(self):
test_input = "W"
expected_output = [RobotDirection.WEST]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_sequence_N_S_E_W_W(self):
test_input = "N S E W W"
expected_output = [RobotDirection.NORTH, RobotDirection.SOUTH, RobotDirection.EAST, RobotDirection.WEST, RobotDirection.WEST]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
def test_sequence_N_G_D_E_W(self):
test_input = "N G D E W"
expected_output = [RobotDirection.NORTH, RobotDirection.GRAB, RobotDirection.DROP, RobotDirection.EAST, RobotDirection.WEST]
result = CommandParser.process_string(test_input)
self.assertEqual(expected_output, result)
# def test_sequence_N_E_returns_N_E_Command(self):
# test_input = "N E"
# expected_output = [RobotCommand.NORTH_EAST]
# result = CommandParser.process_string(test_input)
#
# self.assertEqual(expected_output, result)
if __name__ == '__main__':
unittest.main()
| true
|
28d6ae9b1bbdc8d1e16bc761db280ea0a88689e7
|
Python
|
Rurril/IT-DA-3rd
|
/study/Ace/VCWeek4/BOJ_17144_권순규.py
|
UTF-8
| 2,448
| 2.65625
| 3
|
[] |
no_license
|
def spread():
global dust
tmp_dust = [[0] * C for _ in range(R)]
for y in range(R):
for x in range(C):
if dust[y][x] > 0:
n = 4
for i in range(4):
ny = y + dy1[i]
nx = x + dx1[i]
if ny < 0 or nx < 0 or ny == R or nx == C or dust[ny][nx] == -1:
n -= 1
continue
tmp_dust[ny][nx] += dust[y][x] // 5
tmp_dust[y][x] += dust[y][x] - (dust[y][x]//5)*n
dust = tmp_dust
def cycle():
global dust
tmp_dust = deepcopy(dust)
top_y = AirCleaner[0][0]
top_x = AirCleaner[0][1]
bot_y = AirCleaner[1][0]
bot_x = AirCleaner[1][1]
# 반시계 회전
y = top_y
x = top_x
for i in range(4):
while True:
ny = y + dy1[i]
nx = x + dx1[i]
if ny < 0 or nx < 0 or ny == R or nx == C or (ny,nx) == AirCleaner[0]:
break
if dust[ny][nx] != -1:
if dust[y][x] == -1:
tmp_dust[ny][nx] = 0
else:
tmp_dust[ny][nx] = dust[y][x]
y = ny
x = nx
# 시계 회전
y = bot_y
x = bot_x
for i in range(4):
while True:
ny = y + dy2[i]
nx = x + dx2[i]
if ny < 0 or nx < 0 or ny == R or nx == C or (ny,nx) == AirCleaner[1]:
break
if dust[ny][nx] != -1:
if dust[y][x] == -1:
tmp_dust[ny][nx] = 0
else:
tmp_dust[ny][nx] = dust[y][x]
y = ny
x = nx
tmp_dust[AirCleaner[0][0]][AirCleaner[0][1]] = -1
tmp_dust[AirCleaner[1][0]][AirCleaner[1][1]] = -1
dust = tmp_dust
dx1, dy1 = (1,0,-1,0),(0,-1,0,1) # 반시계
dx2, dy2 = (1,0,-1,0),(0,1,0,-1) # 시계
from copy import deepcopy
if __name__ == "__main__":
R,C,T = map(int,input().split())
dust = []
AirCleaner = []
for y in range(R):
tmp = list(map(int,input().split()))
for x, n in enumerate(tmp):
if n == -1:
AirCleaner.append((y,x))
dust.append(tmp)
for _ in range(T):
spread()
cycle()
answer = 2
for i in range(R):
answer += sum(dust[i])
print(answer)
| true
|
46c3c682a75a384dca193eb949901ed789814cb9
|
Python
|
saurabhsood91/advent-of-code
|
/one.py
|
UTF-8
| 356
| 3.734375
| 4
|
[] |
no_license
|
from math import floor
def get_fuel_required(mass: int):
fuel = floor(mass / 3) - 2
if fuel <= 0:
return 0
return fuel + get_fuel_required(fuel)
if __name__ == '__main__':
total_fuel = 0
file = open('fuel.txt')
for line in file:
mass = int(line)
total_fuel += get_fuel_required(mass)
print("Total Fuel: {}".format(total_fuel))
| true
|
dfb31c58548c3e6345d260d8e10090b63033361d
|
Python
|
ShwethaDeepak/Text_Summarization
|
/TEXt Summarization.py
|
UTF-8
| 2,075
| 3.25
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 15:43:49 2019
@author: swetu
"""
#creating an article summarization
import bs4 as bs
import urllib.request
import re
import nltk
nltk.download('stopwords')
import heapq
#Getting data
Source =urllib.request.urlopen('https://en.wikipedia.org/wiki/Global_warming').read()
soup = bs.BeautifulSoup(Source,'lxml')
text = ""
for paragraph in soup.find_all('p'):
text += paragraph.text
#preprocessing the text
text = re.sub(r'\[[0-9]*\]',' ',text)
text = re.sub(r'\s+',' ',text)
# clean_text is for hostogram(bag of words) text is for summary
clean_text = text.lower()
clean_text = re.sub(r'\W',' ',clean_text)
clean_text = re.sub(r'\d',' ',clean_text)
clean_text = re.sub(r'\s+',' ',clean_text)
#Tokenize article into different sentences
sentences = nltk.sent_tokenize(text)
stop_words = nltk.corpus.stopwords.words('english')
# Building the histogram(Basic histogram)
word2count = {}
for word in nltk.word_tokenize(clean_text):
if word not in stop_words:
if word not in word2count.keys():
word2count[word] = 1
else:
word2count[word] +=1
#weighted histogram
for key in word2count.keys():
word2count[key] = word2count[key]/max(word2count.values())
#Calculating sentence scores
sent2score = {}
for sentence in sentences:
for word in nltk.word_tokenize(sentence.lower()):
if word in word2count.keys():
if len(sentence.split(' ')) < 25:# less than 30 words are in our summary others are exculded
if sentence not in sent2score.keys():
sent2score[sentence] = word2count[word]
else:
sent2score[sentence] += word2count[word]
#finding out the summary (top n sentence from dictory using heapq library)
best_sentences = heapq.nlargest(5,sent2score,key = sent2score.get)
print('-------------------------------------------------------------')
for sentence in best_sentences:
print(sentence)
| true
|
cf2a9f2a00518cdf39ed90b0a725a97bf72c8bbd
|
Python
|
Ragul-SV/Data-Structures-and-Algorithms
|
/Array/Easy II/Maximum No. of 1s (Sliding Window).py
|
UTF-8
| 483
| 2.828125
| 3
|
[] |
no_license
|
t = int(input())
for cases in range(t):
n = int(input())
arr = list(map(int,input().strip().split()))
m = int(input())
wL,wR = 0,0
res = 0
zero_count = 0
while wR<n:
if zero_count<=m:
if arr[wR]==0:
zero_count+=1
wR+=1
if zero_count>m:
if arr[wL]==0:
zero_count-=1
wL+=1
if wR-wL>res and zero_count<=m:
res = wR-wL
print(res)
| true
|
08c6a9d9701723c2e7a3a7af8bab76a33ffea630
|
Python
|
1allan/tower-of-bullets
|
/TowerofBullets/scenery/room.py
|
UTF-8
| 6,292
| 2.703125
| 3
|
[] |
no_license
|
import os
import pygame
from random import randint, choice
from util.functions import load_image
from .tile import Tile
from character.enemy import Enemy
from items.item import Item
class Room(pygame.sprite.Sprite):
def __init__(self, surface: pygame.Surface, position: tuple, size: tuple,
args):
pygame.sprite.Sprite.__init__(self)
self.width, self.height = size
self.surface = surface
self.rect = pygame.Rect(position[0], position[1], size[0], size[1])
self.player = None
self.spawn_point = args['SPAWN_POINT']
self.portal = None
layer1, layer2 = self.__load_layout(args['STRUCTURE']['LAYOUT'])
self.overlay = self.__generate_layout(layer2, overlay=True,
offset=(0, -15))
self.floors, self.walls = self.__generate_layout(layer1)
self.wave_now = 0
self.last_wave = pygame.time.get_ticks()
self.waves = args['WAVES']
self.started = False
self.rewarded = False
self.coins = pygame.sprite.Group()
self.energy_orbs = pygame.sprite.Group()
self.hearts = pygame.sprite.Group()
self.enemies = pygame.sprite.Group()
self.enemies_bullets = pygame.sprite.Group()
self.start_wave()
def __load_layout(self, path):
file_ = open(os.path.join(os.path.dirname(__file__),
'../assets/scenery/layouts/' + path), 'r')
layout = file_.read()
file_.close()
output = []
for i, matrix in enumerate(layout.split('\n\n')):
output.append([])
for line in matrix.split('\n'):
output[i].append(line.split(' '))
return output
def __generate_layout(self, matrix, overlay=False, offset=None):
walls = pygame.sprite.Group()
floors = pygame.sprite.Group()
offset = (0, 0) if offset is None else offset
w = round(self.width/len(matrix[0]))
h = round(self.height/len(matrix))
for i in range(len(matrix)):
for j in range(len(matrix[i])):
group = walls
collidable = False
convert = not overlay
image = ''
if matrix[i][j].startswith('wall'):
collidable = True
image = 'walls/' + matrix[i][j]
else:
group = floors
image = 'floors/' + matrix[i][j]
group.add(Tile(self.surface,
(w * i + offset[0], h * j + offset[1]), (w, h),
collidable, image_file=image, convert=convert))
if overlay:
group = pygame.sprite.Group()
group.add(floors)
group.add(walls)
return group
else:
return floors, walls
def start_wave(self):
for i in range(self.waves[self.wave_now]['ENEMY_QUANTITY']):
enemy_type = choice(self.waves[self.wave_now]['ENEMIES'])
chosen = choice(list(self.floors))
position = (chosen.rect.left, chosen.rect.top)
self.enemies.add(Enemy(self.surface, position, (70, 70),
self.walls, enemy_type, animated=True))
self.wave_now += 1
def spawn_portal(self):
image_file = 'misc/portal.png'
self.portal = Item(self.surface, self.spawn_point,
(32, 64), image_file, 0)
def spawn_coins(self, quantity: int):
image_file = "misc/coin.png"
for _ in range(quantity):
chosen = choice(list(self.floors))
position = (chosen.rect.left, chosen.rect.top)
self.coins.add(Item(self.surface, position, (20, 20), image_file,
0))
def spawn_energy_orbs(self, quantity: int):
image_file = "misc/energy_orb.png"
for _ in range(quantity):
chosen = choice(list(self.floors))
position = (chosen.rect.left, chosen.rect.top)
self.energy_orbs.add(Item(self.surface, position, (20, 20), image_file,
0))
def spawn_hearts(self, quantity: int):
image_file = "misc/heart.png"
for _ in range(quantity):
chosen = choice(list(self.floors))
position = (chosen.rect.left, chosen.rect.top)
self.hearts.add(Item(self.surface, position, (30, 30), image_file,
0))
def spawn_player(self, player):
player.rect.left, player.rect.top = self.spawn_point
self.player = player
def update(self):
tick = pygame.time.get_ticks()
if tick - self.last_wave < 3000 and not self.started:
return
else:
self.started = True
self.enemies_bullets.update()
if len(self.enemies) == 0:
if not self.rewarded:
self.spawn_hearts(2)
self.spawn_coins(5)
self.spawn_energy_orbs(3)
self.rewarded = True
if self.wave_now < len(self.waves) and tick - self.last_wave > 3000:
self.last_wave = tick
self.rewarded = False
self.start_wave()
elif self.wave_now >= len(self.waves) and tick - self.last_wave > 2000:
self.last_wave = tick
self.spawn_portal()
else:
self.last_wave = pygame.time.get_ticks()
for enemy in self.enemies:
bullet = enemy.attack((self.player.x, self.player.y))
if bullet is not None:
self.enemies_bullets.add(bullet)
enemy.chase((self.player.x, self.player.y))
enemy.weapon.update((self.player.x, self.player.y))
enemy.draw()
def draw(self):
self.floors.draw(self.surface)
self.hearts.draw(self.surface)
self.energy_orbs.draw(self.surface)
self.coins.draw(self.surface)
if self.portal is not None:
self.portal.draw()
self.enemies_bullets.draw(self.surface)
self.walls.draw(self.surface)
self.player.draw()
self.update()
| true
|
9fea0bf00091806a8e2fe15da0008c1f95fa1421
|
Python
|
Altison/code_1021
|
/main.py
|
UTF-8
| 1,146
| 2.703125
| 3
|
[] |
no_license
|
k = 0
value = False
def on_button_pressed_a():
global k
for I in range(19):
k = min(18 - I, I)
for j in range(5):
if I == 9:
basic.pause(1000)
break
elif I < 9:
led.plot(4 - j, 4 - (k - j))
else:
led.unplot(4 - j, 4 - (k - j))
basic.pause(100)
input.on_button_pressed(Button.A, on_button_pressed_a)
def on_button_pressed_ab():
for I2 in range(5):
for l in range(5):
if I2 % 2 == l % 2:
led.plot(I2, l)
input.on_button_pressed(Button.AB, on_button_pressed_ab)
def on_button_pressed_b():
global value
value = True
for index in range(2):
for x in range(9):
for I3 in range(5):
for m in range(5):
if I3 + m == x:
if value:
led.plot(4 - I3, 4 - m)
else:
led.unplot(I3, m)
basic.pause(100)
value = False
basic.pause(1000)
input.on_button_pressed(Button.B, on_button_pressed_b)
| true
|
a88f0f9b1ca1566cdd45a7e3636c34f6f9e3d9e3
|
Python
|
abandonsea/RandPerson
|
/generateCode/cc1_createCorlor.py
|
UTF-8
| 1,193
| 3.21875
| 3
|
[
"Apache-2.0"
] |
permissive
|
# *********************
# Generate 625 colors
# *********************
from PIL import Image
import math
def hsv2rgb(h, s, v):
h = float(h)
s = float(s)
v = float(v)
h60 = h / 60.0
h60f = math.floor(h60)
hi = int(h60f) % 6
f = h60 - h60f
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
r, g, b = 0, 0, 0
if hi == 0: r, g, b = v, t, p
elif hi == 1: r, g, b = q, v, p
elif hi == 2: r, g, b = p, v, t
elif hi == 3: r, g, b = p, q, v
elif hi == 4: r, g, b = t, p, v
elif hi == 5: r, g, b = v, p, q
r, g, b = int(r * 255), int(g * 255), int(b * 255)
return r, g, b
for i in range(0,24):
h, s, v = 0, 0, 0
h = i*15
for j in range(2,11,2):
s = j*0.1
for k in range(2,11,2):
v = k*0.1
color = hsv2rgb(h, s, v)
img = Image.new("RGBA", (500, 500), color)
img.save("color/" + str(int(h))+"_"+str(int(s*10))+"_"+str(int(v*10))+".png")
# black, white, gray
for i in range(0,25):
color = hsv2rgb(0, 0, i/24)
img = Image.new("RGBA", (500, 500), color)
img.save("color/" + str(0) + "_" + str(0) + "_" + str(int(i * 10)) + ".png")
| true
|
4d1c6dbfede5d835f47f80b8c28bb76e31d7cf53
|
Python
|
dsteinmo/AdventOfCode-2020
|
/day4/num_valid_passports.py
|
UTF-8
| 6,425
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
class Passport:
# Props:
# byr (Birth Year)
# iyr (Issue Year)
# eyr (Expiration Year)
# hgt (Height)
# hcl (Hair Color)
# ecl (Eye Color)
# pid (Passport ID)
# cid (Country ID, optional)
def __init__(self, byr, iyr, eyr, hgt, hcl, ecl, pid, cid):
self.byr = byr
self.iyr = iyr
self.eyr = eyr
self.hgt = hgt
self.hcl = hcl
self.ecl = ecl
self.pid = pid
self.cid = cid
def print(self):
print(f"byr: {self.byr}, iyr: {self.iyr}, eyr: {self.eyr}, \
hgt: {self.hgt}, hcl: {self.hcl}, ecl: {self.ecl}, pid: {self.pid}, cid: {self.cid}")
def is_valid(self, version=1) -> bool:
if version < 2:
# version 1 rules:
return (self.byr is not None and
self.iyr is not None and
self.eyr is not None and
self.hgt is not None and
self.hcl is not None and
self.ecl is not None and
self.pid is not None)
return (self.byr_is_valid() and
self.iyr_is_valid() and
self.eyr_is_valid() and
self.hgt_is_valid() and
self.hcl_is_valid() and
self.ecl_is_valid() and
self.pid_is_valid()) # cid ignored.
# version 2 rules:
# 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.
def byr_is_valid(self):
if self.byr is None:
return False
byr_num = int(self.byr)
if (byr_num >= 1920 and byr_num <= 2002):
return True
print("bad byr")
return False
def iyr_is_valid(self):
if self.iyr is None:
return False
iyr_num = int(self.iyr)
if (iyr_num >= 2010 and iyr_num <= 2020):
return True
print("bad iyr")
return False
def eyr_is_valid(self):
if self.eyr is None:
return False
eyr_num = int(self.eyr)
if (eyr_num >= 2020 and eyr_num <= 2030):
return True
print("bad eyr")
return False
def hgt_is_valid(self):
if self.hgt is None:
return False
if len(self.hgt) < 3:
return False
meas = self.hgt[-2:]
if meas != "in" and meas != "cm":
print("height bad units")
return False
hgt_num = int(self.hgt[:-2])
if meas == "in":
if hgt_num >= 59 and hgt_num <= 76:
return True
else:
print("bad inches height")
return False
# must be "cm":
if hgt_num >= 150 and hgt_num <= 193:
return True
print("bad cm height")
return False
def hcl_is_valid(self):
if self.hcl is None:
return False
if self.hcl[0] != "#":
return False
color = self.hcl[1:]
if (len(color) != 6):
return False
valid_chars = set(['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'])
for char in color:
if char not in valid_chars:
print("bad color string")
return False
return True
def ecl_is_valid(self):
if self.ecl is None:
return False
valid_ecls = set(["amb", "blu", "brn", "gry", "grn", "hzl", "oth"])
if self.ecl not in valid_ecls:
print("invalid ecl")
return False
return True
def pid_is_valid(self):
if self.pid is None:
return False
if len(self.pid) != 9:
return False
valid_chars = set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
for char in self.pid:
if char not in valid_chars:
return False
return True
passports = []
with open("day4_input.txt", mode="r") as f:
eof_reached = False
eor_reached = False
passport_fields = {
"byr": None, "iyr": None, "eyr": None, "hgt": None,
"hcl": None, "ecl": None, "pid": None, "cid": None
}
while(eof_reached == False):
line = f.readline().strip()
if len(line) == 0 and eor_reached == True:
eof_reached = True
elif len(line) == 0:
# Blank line -- end of record, so add to list of passports.
passports.append(Passport(passport_fields["byr"], passport_fields["iyr"], passport_fields["eyr"],
passport_fields["hgt"], passport_fields["hcl"], passport_fields["ecl"],
passport_fields["pid"], passport_fields["cid"]))
# Reset fields for next record.
passport_fields = {
"byr": None, "iyr": None, "eyr": None, "hgt": None,
"hcl": None, "ecl": None, "pid": None, "cid": None
}
eor_reached = True
else:
# Data line -- parse what we can, and wait until end-of-record (empty line).
eor_reached = False
fields = line.split(" ")
for field in fields:
kv_pair = field.split(":")
key = kv_pair[0]
val = kv_pair[1]
passport_fields[key] = val
if __name__ == "__main__":
print("Day 4")
print("=====")
num_valid = 0
for passport in passports:
if passport.is_valid():
num_valid += 1
print(f"Part 1: Number of valid passports: {num_valid}")
num_valid = 0
for passport in passports:
passport.print()
if passport.is_valid(version=2):
num_valid += 1
print("passport is valid")
else:
print("not valid")
print(f"Part 2: Number of valid passports: {num_valid}")
| true
|
65e9e434fb9c44e542e3cf7eb6bb3dcf6340437a
|
Python
|
kevinjycui/Competitive-Programming
|
/Python/DMOJ/art0.py
|
UTF-8
| 325
| 3.90625
| 4
|
[] |
no_license
|
n = int(input())
vowels = ['a', 'e', 'i', 'o', 'u']
words = ['Hi! ', 'Bye! ', 'How are you? ', 'Follow me! ', 'Help! ']
for i in range(n):
s = input().lower()
ans = ''
for c in s:
if c in vowels:
ans += words[vowels.index(c)]
elif c.isdigit():
ans += 'Yes! '
print(ans)
| true
|
c6b9826a3907261e0f92935c0e9081405e6a250a
|
Python
|
Stefanh18/python_projects
|
/test/q3.py
|
UTF-8
| 256
| 3.6875
| 4
|
[] |
no_license
|
first = int(input("Initial value: "))
steps = int(input("Steps: "))
sum_of_series = 0
count2 = first
while count2 <= 100:
print(count2, end= ' ')
sum_of_series += count2
count2 += steps
print(" ")
print("Sum of series: ", sum_of_series)
| true
|
8f7c4c7279a7c1b7293fe5a15ceaab07d93d35ae
|
Python
|
tea1013/google_brain_ventilator_pressure_prediction
|
/teads/util/params.py
|
UTF-8
| 291
| 2.78125
| 3
|
[] |
no_license
|
import pickle
from typing import Dict
class Params:
def dump_dict(d: Dict, path: str) -> None:
with open(path, "wb") as f:
pickle.dump(d, f)
def load_dict(path: str) -> Dict:
with open(path, "rb") as f:
d = pickle.load(f)
return d
| true
|
8eb19b369146fb5ddefe563e5ff70985095fbbfb
|
Python
|
GavinAlison/python-learning
|
/requestss/fetch_qsbk2.py
|
UTF-8
| 6,210
| 3.296875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-01-03 22:46:00
# @Author : alison
# @File : fetch_qsbk2.py
# 备注: urllib2在python3.x版本里面,与urllib合并,以后导入urllib2,=import urllib.request
# 环境: python3.7.0
# 工具: pycharm2018.3
import urllib
import urllib.request
import re
## 设计面向对象模式
# page = 1
# url = 'https://www.qiushibaike.com/text/page/' + str(page) + '/'
# user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/71.0.3578.98 Safari/537.36'
# headers = {'User-Agent': user_agent}
# 抓取一下糗事百科的热门段子吧
# 抓取的内容为, 用户名, 用户内容,好笑数, 评论数
# regex2 = r'<a href="/users/\d+/".*?<h2>(.*?)</h2>.*?<a href="/article/\d+".*?<span>(.*?)</span>.*?<span class="stats-vote">.*?<i class="number">(.*?)</i>.*?<a href="/article/\d+.*?<i class="number">(.*?)</i>'
# try:
# request = urllib.request.Request(url, headers=headers)
# response = urllib.request.urlopen(request)
# content = response.read().decode('utf-8')
# # print(content)
# pattern = re.compile(regex2, re.S)
# items = re.findall(pattern, content)
# print(items) # '''items的值为[(,,),(,,),(,,)], []匹配到list, ()为匹配到的元祖,()里面的值为匹配到的(.*?)匹配到的值'''
# for item in items:
# print('用户名: ', str(item[0]).replace('\n', ''))
# print('内容: ', str(item[1]).replace('\n', '').replace('<br/>', '\n'))
# print('好笑: ', str(item[2]))
# print('评论: ', str(item[3]))
# print()
# except Exception as e:
# print(e)
# 糗事百科的爬虫
class QSBK:
# 初始化方法,定义一些变量
def __init__(self):
self.pageIndex = 1
self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/71.0.3578.98 Safari/537.36'
# 初始化headers
self.headers = {'User-Agent': self.user_agent}
# 抓取一下糗事百科的热门段子
# 抓取的内容为, 用户名, 用户内容,好笑数, 评论数
self.regex = r'<a href="/users/\d+/".*?<h2>(.*?)</h2>.*?<a href="/article/\d+".*?<span>(.*?)</span>.*?<span class="stats-vote">.*?<i class="number">(.*?)</i>.*?<a href="/article/\d+.*?<i class="number">(.*?)</i>'
# 存放段子的变量,每一个元素是每一页的段子们
self.stories = []
# 存放程序是否继续运行的变量
self.enable = False
# 传入某一页的索引获得页面代码
def getPage(self, pageIndex):
try:
url = 'https://www.qiushibaike.com/text/page/' + str(pageIndex) + '/'
request = urllib.request.Request(url, headers=self.headers)
response = urllib.request.urlopen(request)
pageContext = response.read().decode('utf-8')
return pageContext
except urllib.request.URLError as e:
print('connect fail ', e.reason)
return None
# 传入某一页代码
def getPageItems(self, pageIndex):
pageContext = self.getPage(pageIndex)
if not pageContext:
print('页面加载失败......')
return None
regex = self.regex
pattern = re.compile(regex, re.S)
items = re.findall(pattern, pageContext)
# 用来存储每页的段子
pageStories = []
for item in items:
# item存储的是用户名, 用户内容,好笑数, 评论数
text1 = re.sub(r'\n', '', item[0])
text2 = re.sub(r'\n', '', item[1])
text3 = re.sub(r'\n', '', item[2])
text4 = re.sub(r'\n', '', item[3])
text2 = re.sub(r'<br/>', '\n', text2)
t_tuple = (text1, text2, text3, text4)
pageStories.append(t_tuple)
return pageStories
# 加载并提取页面的内容,加入到列表中
def loadPage(self):
# 如果当前未看的页数少于2页,则加载新一页
if self.enable == True:
if len(self.stories) < 2:
# 获取新一页
pageStories = self.getPageItems(self.pageIndex)
# 将该页的段子存放到全局list中
if pageStories:
self.stories.append(pageStories)
# 获取完之后页码索引加一,表示下次读取下一页
self.pageIndex += 1
# 调用该方法,每次敲回车打印输出一个段子
def getOneStory(self, pageStories, page):
# 遍历一页的段子
# print(pageStories)
for story in pageStories:
# print('story===',story)
# 等待用户输入
i = input()
# 每当输入回车一次,判断一下是否要加载新页面
self.loadPage()
# 如果输入1则程序结束
if i == "q":
self.enable = False
return
print("第%d页\n\t发布人:\n\t\t%s\n\t内容:\n\t\t%s\n\t好笑数:\n\t\t%s\n\t评论数:\n\t\t%s\n" % (
page, story[0], story[1], story[2], story[3]))
# print("第%d页\t发布人:%s\t内容:%s\t好笑数:%s\t评论数:%s\n" % (page, story[0], story[1], story[2], story[3]))
# IndexError: string index out of range
def start(self):
print(u"正在读取糗事百科,按回车查看新段子,Q退出")
# 使变量为True,程序可以正常运行
self.enable = True
# 先加载一页内容
self.loadPage()
# 局部变量,控制当前读到了第几页
nowPage = 0
while self.enable:
if len(self.stories) > 0:
# 从全局list中获取一页的段子
pageStories = self.stories[0]
# 当前读到的页数加一
nowPage += 1
# 将全局list中第一个元素删除,因为已经取出
del self.stories[0]
# 输出该页的段子
self.getOneStory(pageStories, nowPage)
spider = QSBK()
spider.start()
| true
|
a9cb1f45b1a82647b65fcf04e0d07fb4870a7227
|
Python
|
loerac/crypto-hodl
|
/hodl.py
|
UTF-8
| 5,153
| 2.6875
| 3
|
[] |
no_license
|
import config
import gspread
import json
import pandas as pd
import pickle
import redis
import streamlit as st
import validationNormalization as vnorm
import zlib
from crypto_api import IEX
from oauth2client.service_account import ServiceAccountCredentials
# Google Spreadsheets
scope =['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_name("cred.json", scope)
client = gspread.authorize(creds)
sheet = client.open('crypto-hodl').sheet1
# Set up IEX
iex = IEX(config.IEX_TOKEN)
# Redis cache
cache = redis.Redis(host='localhost', port=6379, db=0)
def getHodl():
"""
@brief: Either get complete order history from
Google Spreadsheets or from cache.
If getting from Google Spreadsheets, save JSON
to cache and set it to expire in 10 hours
@return: Dataframe of order history
"""
hodl = cache.get('hodl')
if hodl:
# Decompress dataframe from cache
df = pickle.loads(zlib.decompress(hodl))
else:
# Compress data to cache
data = sheet.get_all_records()
df = pd.read_json(json.dumps(data))
cache.setex('hodl', 36000, zlib.compress(pickle.dumps(df)))
return df
@st.cache
def portfolio(df):
"""
@brief: Calculate the profit/loss (P/L) of each cryptocurrency.
@param: df - complete order history dataframe
@return: Dataframe of cryptocurrency portfolio
"""
coins = df.Coin.unique()
stat = []
for coin in coins:
coin_df = df[df.Coin == coin]
total = coin_df.Total.iloc[-1]
avg = coin_df.Average.iloc[-1]
if total == 0.0:
continue
ret_price = 'N/A'
ret_precent = 'N/A'
curr_price = cache.get(f'{coin}')
if curr_price:
curr_price = float(curr_price)
else:
curr_price = iex.getCryptoPrice(str.lower(coin))
if curr_price:
curr_price = float(curr_price['price'])
cache.setex(f'{coin}', 86400, curr_price)
if curr_price:
avg_num = float(str(avg).replace('$', '').replace(',', ''))
total_num = float(str(total).replace(',', ''))
ret_price = total_num * (curr_price - avg_num)
ret_price = '$' + str(round(ret_price, 5))
ret_precent = ((curr_price / avg_num) - 1 ) * 100
ret_precent = str(round(ret_precent, 5)) + '%'
avg_num = round(avg_num, 5)
total_num = round(total_num, 5)
avg_num = '${:,}'.format(avg_num)
total_num = '{:,}'.format(total_num)
stat.append([coin, total_num, avg_num, ret_price, ret_precent])
hodl_df = pd.DataFrame(stat, columns=['Coin', 'Total', 'Average', '$ P/L', '% P/L'])
return hodl_df.set_index('Coin')
@st.cache
def orderHistory(df):
"""
@brief: Extract the columns for the order history.
@param: df - complete order history dataframe
@return: Dataframe of cryptocurrency order history.
"""
hist_df = df[['Date', 'Direction', 'Amount', 'Coin', 'Price', 'Exchange']]
return hist_df.set_index('Date')
@st.cache
def newOrder(df, new_order):
"""
@brief: Check if new submitted order was filled out properly.
If value are invalid, send message back to user on error.
On success, send new order to Google Spreadsheet.
@param: df - complete order history dataframe
@param: new_order - new order that was submitted
@return: message on submittion, and boolean value
True on success, else False
"""
complete_order = all(value != '' for value in new_order.values())
if not complete_order:
return 'All fields need to be filled', False
order, msg = vnorm.validateNormalizeOrder(new_order)
if order is None:
return msg, False
order_df = df[df['Coin'] == order['Coin']]
order_df = order_df.append(order, ignore_index=True)
order_df.Amount = order_df.Amount.astype(str)
order_df.iloc[-1, order_df.columns.get_loc('Total')] = \
order_df.Amount.apply(lambda x: x.replace(',', '')).astype(float).sum()
_sum = 0
for i in range(order_df.shape[0]):
_amount = float(str(order_df.iloc[i]['Amount']).replace(',', ''))
_price = float(order_df.iloc[i]['Price'].replace('$', '').replace(',', ''))
_sum += (_amount * _price)
order_df.iloc[-1, order_df.columns.get_loc('Average')] = \
_sum / order_df.iloc[-1]['Total']
order_df.iloc[-1, order_df.columns.get_loc('Average')] = '$' + \
str(order_df.iloc[-1, order_df.columns.get_loc('Average')])
sheet.insert_row(list(order_df.iloc[-1]), df.shape[0] + 2)
df = df.append(order_df.iloc[-1])
cache.setex('hodl', 36000, zlib.compress(pickle.dumps(df)))
return f"Order #{df.shape[0] + 2}: {order['Direction']} {order['Amount']} {order['Coin']} has been added", True
| true
|
313eae700ef2d87f9d2bef4b8be3af5280b89787
|
Python
|
gelizondomora/python_basico_2_2019
|
/Semana 1/practica_2.py
|
UTF-8
| 298
| 3.546875
| 4
|
[] |
no_license
|
# Esta es al practica para escribir dos lineas
# en consola
"""
Comentario de multiples lineas
util para explicar mas detalles
"""
print("Hola a todos!")
print("buenos dias")
#Varias lineas en un solo print
print("mi primera linea \nmi segunda linea")
print("hola de nuevo")
| true
|
a866a5fa90c3a5a59abac228ca8e19a45f091af0
|
Python
|
liupy525/Pythontip-OJ
|
/16_renminbi_example_ck.py
|
UTF-8
| 6,095
| 3.625
| 4
|
[] |
no_license
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
注明:数据已于2013-11-19日加强,原来通过的代码可能不能再次通过。
注意:由于中文乱码问题,输出时请先decode("utf8"),例如你要输出ans = "零圆", print ans.decode("utf8").
银行在打印票据的时候,常常需要将阿拉伯数字表示的人民币金额转换为大写表示,现在请你来完成这样一个程序。
在中文大写方式中,0到10以及100、1000、10000被依次表示为:
零壹贰叁肆伍陆柒捌玖拾佰仟万
以下的例子示范了阿拉伯数字到人民币大写的转换规则:
1 壹圆
11 壹拾壹圆
111 壹佰壹拾壹圆
101 壹佰零壹圆
-1000 负壹仟圆
1234567 壹佰贰拾叁万肆仟伍佰陆拾柒圆
现在给你一个整数a(|a|<100000000), 打印出人民币大写表示
'''
import warnings
from decimal import Decimal
def cncapital(value, capital=True, prefix=False, classical=None):
'''
人民币数字转汉字表示 Ver 0.03
作者: qianjin(AT)ustc.edu
版权声明:
只要保留本代码最初作者的电子邮件即可,随便用。用得爽的话,不反对请
作者吃一顿。
参数:
capital: True 大写汉字金额
False 一般汉字金额
classical: True 圆
False 元
prefix: True 以'人民币'开头
False, 无开头
'''
# 转换为Decimal
if isinstance(value, float):
msg = '''
由于浮点数精度问题,请使用考虑使用字符串,或者 decimal.Decimal 类。
因使用浮点数造成误差而带来的可能风险和损失作者概不负责。
'''
warnings.warn(msg, UserWarning)
value = Decimal(str(value))
elif isinstance(value, int):
value = Decimal(value)
elif not isinstance(value, Decimal):
try:
value = Decimal(str(value))
except:
raise TypeError('无法转换为Decimal:%s' % value.__repr__())
# 截断多余小数
value = Decimal(value).quantize(Decimal('0.01'))
# 默认大写金额用圆,一般汉字金额用元
if classical is None:
classical = True if capital else False
# 汉字金额前缀
if prefix is True:
prefix = '人民币'
else:
prefix = ''
# 汉字金额字符定义
dunit = ('角', '分')
if capital:
num = ('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
iunit = [None, '拾', '佰', '仟', '万', '拾', '佰', '仟',
'亿', '拾', '佰', '仟', '万', '拾', '佰', '仟']
else:
num = ('〇', '一', '二', '三', '四', '五', '六', '七', '八', '九')
iunit = [None, '十', '百', '千', '万', '十', '百', '千',
'亿', '十', '百', '千', '万', '十', '百', '千']
if classical:
iunit[0] = '圆' if classical else '元'
# 处理负数
if value < 0:
prefix += '负' # 输出前缀,加负
value = - value # 取正数部分,无须过多考虑正负数舍入
# assert - value + value == 0
# 转化为字符串
s = str(value)
if len(s) > 19:
raise ValueError('金额太大了,不知道该怎么表达。')
istr, dstr = s.split('.') # 小数部分和整数部分分别处理
istr = istr[::-1] # 翻转整数部分字符串
so = [] # 用于记录转换结果
# 零
if value == 0:
return prefix + unm[0] + iunit[0]
haszero = False # 用于标记零的使用
if dstr == '00':
haszero = True # 如果无小数部分,则标记加过零,避免出现“圆零整”
# 处理小数部分
# 分
if dstr[1] != '0':
so.append(dunit[1])
so.append(num[int(dstr[1])])
else:
so.append('整') # 无分,则加“整”
# 角
if dstr[0] != '0':
so.append(dunit[0])
so.append(num[int(dstr[0])])
elif dstr[1] != '0':
so.append(num[0]) # 无角有分,添加“零”
haszero = True # 标记加过零了
# 无整数部分
if istr == '0':
if haszero: # 既然无整数部分,那么去掉角位置上的零
so.pop()
so.append(prefix) # 加前缀
so.reverse() # 翻转
return ''.join(so)
# 处理整数部分
for i, n in enumerate(istr):
n = int(n)
if i % 4 == 0: # 在圆、万、亿等位上,即使是零,也必须有单位
if i == 8 and so[-1] == iunit[4]: # 亿和万之间全部为零的情况
so.pop() # 去掉万
so.append(iunit[i])
if n == 0: # 处理这些位上为零的情况
if not haszero: # 如果以前没有加过零
so.insert(-1, num[0]) # 则在单位后面加零
haszero = True # 标记加过零了
else: # 处理不为零的情况
so.append(num[n])
haszero = False # 重新开始标记加零的情况
else: # 在其他位置上
if n != 0: # 不为零的情况
so.append(iunit[i])
so.append(num[n])
haszero = False # 重新开始标记加零的情况
else: # 处理为零的情况
if not haszero: # 如果以前没有加过零
so.append(num[0])
haszero = True
# 最终结果
so.append(prefix)
so.reverse()
return ''.join(so)
print cncapital(100000000)
| true
|
cd7e3582f308d417b98d7b49a427c9011a8f2b42
|
Python
|
ccnmtl/django-oembed
|
/oembed/tests.py
|
UTF-8
| 1,324
| 2.78125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
from __future__ import unicode_literals
from django.test import TestCase
from oembed.core import replace
class OEmbedTests(TestCase):
fixtures = ['initial_data.json']
noembed = r"This is text that should not match any regex."
end = r"There is this great photo at %s"
start = r"%s is a photo that I like."
middle = r"There is a movie here: %s and I really like it."
trailing_comma = r"This is great %s, but it might not work."
trailing_period = r"I like this photo, located at %s."
loc = 'https://www.flickr.com/photos/ian_ruotsala/39088280250/'
embed = '<img src="https://farm5.staticflickr.com/4776/39088280250_01461fee94_n.jpg" alt="living space is shared with this furry little ambush predator"></img>'
def testNoEmbed(self):
self.assertEquals(
replace(self.noembed),
self.noembed
)
def testEnd(self):
for text in (self.end, self.start, self.middle, self.trailing_comma, self.trailing_period):
self.assertEqual(
replace(text % self.loc),
text % self.embed
)
def testManySameEmbeds(self):
pass
text = " ".join([self.middle % self.loc] * 100)
resp = " ".join([self.middle % self.embed] * 100)
self.assertEqual(replace(text), resp)
| true
|
a0658a310b2b5dd3159a9edc75e71171ea9275e2
|
Python
|
in-toto/apt-transport-in-toto
|
/tests/measure_coverage.py
|
UTF-8
| 1,049
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python3
"""
<Program Name>
measure_coverage.py
<Author>
Lukas Puehringer <lukas.puehringer@nyu.edu>
<Started>
December 21, 2018.
<Purpose
Shim to setup code coverage measurement for a Python script executed
in a subprocess.
Requires an environment variable COVERAGE_PROCESS_START that points to the
.coveragerc file that should be used.
This is an alternative to performing coverage setup using`sitecustomize.py`
or `.pth` file as suggested in:
https://coverage.readthedocs.io/en/coverage-4.2/subprocess.html
Usage:
python measure_coverage.py <path/to/python/script>
"""
import sys
import coverage
# Setup code coverage measurement (will look for COVERAGE_PROCESS_START envvar)
coverage.process_startup()
# The first argument must be the actual executable
exectuable = sys.argv[1]
# Patch sys.argv so that the executable thinks it was called directly
sys.argv = [exectuable]
# Execute executable in this process measuring code coverage
with open(exectuable) as f:
code = compile(f.read(), exectuable, "exec")
exec(code)
| true
|
88f2c7b3c1191c9f23ff3865a4423692cb23eaeb
|
Python
|
mad3310/galera-manager
|
/galera-manager/utils/randbytes.py
|
UTF-8
| 284
| 2.875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import os
import binascii
from base64 import b64encode
def randbytes(bytes):
"""Return bits of random data as a hex string."""
return binascii.hexlify(os.urandom(bytes))
def randbytes2(bytes=16):
return b64encode(randbytes(bytes)).rstrip('=')
| true
|
057c3a81241835dfc3feca40e5b30001a9638af8
|
Python
|
muondu/Hotel-sytem
|
/tryal.py
|
UTF-8
| 312
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
from everything_db import *
def insert():
pass
# c.execute('INSERT INTO hotel_rooms VALUES(30)')
def delete():
num = 15
with conn:
c.execute('DELETE FROM hotel_rooms WHERE hotelnumber = ?',(num,))
c.execute('SELECT * FROM hotel_rooms')
print(c.fetchall())
delete()
| true
|
1aa6991bd1bc6b65215583e3b88a0fe46889649a
|
Python
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_117/1412.py
|
UTF-8
| 1,920
| 2.578125
| 3
|
[] |
no_license
|
filename = "B-large.in" # change later
f = open(filename)
T = int(f.readline())
for case in range(1,T+1):
s = f.readline()
tmp = s.split()
N = int(tmp[0])
M = int(tmp[1])
lawn = {}
for i in range(N):
s = f.readline()
s = map(int, s.split())
for j in range(M):
lawn[M*i+j] = s[j]
lawnlist = lawn.items()
lawnlist.sort(key = lambda a: a[1])
lawnlist.reverse()
lawn_index = 0
forbidden_x = set()
forbidden_y = set()
impossible_flag = 0
unchecked_flag = 0
while True:
ind, biggest = lawnlist[lawn_index]
tmp_fob_x = set()
tmp_fob_y = set()
x = ind / M
y = ind % M
if (x in forbidden_x) and (y in forbidden_y):
impossible_flag = 1
break
elif unchecked_flag == 1 and lawn_index == N*M-1:
impossible_flag = 0
break
else:
tmp_fob_x.add(x)
tmp_fob_y.add(y)
unchecked_flag = 0
while lawn_index < N*M-1:
lawn_index += 1
ind, value = lawnlist[lawn_index]
if value != biggest:
unchecked_flag = 1
break
else:
x = ind / M
y = ind % M
if (x in forbidden_x) and (y in forbidden_y):
impossible_flag = 1
break
else:
tmp_fob_x.add(x)
tmp_fob_y.add(y)
if impossible_flag == 1:
break
elif lawn_index == N*M-1 and unchecked_flag != 1:
break
else:
forbidden_x |= tmp_fob_x
forbidden_y |= tmp_fob_y
print "Case #" + str(case) + ": ",
if impossible_flag == 1:
print "NO"
else:
print "YES"
| true
|
4d471084b71d4d07d9b1bc6f11a4e5ba65cf7d9b
|
Python
|
youfeng243/hackerearth
|
/Xsquare And Two Arrays/Xsquare And Two Arrays.py
|
GB18030
| 2,414
| 2.984375
| 3
|
[] |
no_license
|
#coding=utf-8
def SumA( startA, endA ):
if startA == endA:
return A[startA]
if startA > endA:
return 0
#ż
if startA % 2 == 0:
if startA == 0:
return eveA[endA]
return eveA[endA] - eveA[startA - 2]
if startA == 1:
return oddA[endA]
return oddA[endA] - oddA[startA - 2]
def SumB( startB, endB ):
if startB == endB:
return B[startB]
if startB > endB:
return 0
#ż
if startB % 2 == 0:
if startB == 0:
return eveB[endB]
return eveB[endB] - eveB[startB - 2]
if startB == 1:
return oddB[endB]
return oddB[endB] - oddB[startB - 2]
def main():
global eveA
global oddA
global eveB
global oddB
global A
global B
N,Q = map(int, raw_input().strip().split())
A = map(int, raw_input().strip().split())
B = map(int, raw_input().strip().split())
eveA = [0] * N
oddA = [0] * N
eveB = [0] * N
oddB = [0] * N
#żк
eveA[0] = A[0]
for i in xrange( 2, N, 2 ):
eveA[i] += eveA[i - 2] + A[i]
if N >= 1:
oddA[1] = A[1]
for i in xrange( 3, N, 2 ):
oddA[i] += oddA[i - 2] + A[i]
eveB[0] = B[0]
for i in xrange( 2, N, 2 ):
eveB[i] += eveB[i - 2] + B[i]
if N >= 1:
oddB[1] = B[1]
for i in xrange( 3, N, 2 ):
oddB[i] += oddB[i - 2] + B[i]
for _ in xrange( Q ):
turn, start, end = map(int, raw_input().strip().split())
start -= 1
end -= 1
Astart = 0
Aend = 0
Bstart = 0
Bend = 0
if turn == 1: #Aͷ
Astart = start
Bstart = start + 1
if start % 2 == end % 2:
Aend = end
Bend = end - 1
else:
Bend = end
Aend = end - 1
if turn == 2: #Bͷ
Bstart = start
Astart = start + 1
if start % 2 == end % 2:
Bend = end
Aend = end - 1
else:
Aend = end
Bend = end - 1
print SumA(Astart, Aend) + SumB( Bstart, Bend )
if __name__ == "__main__":
main()
| true
|
659038b1a71205ec2dae7e7f2487e9fc81edcef1
|
Python
|
Kraming-linux/arnor
|
/com vison/class two.py
|
UTF-8
| 1,559
| 3.359375
| 3
|
[] |
no_license
|
import cv2
import numpy as np
def assess_pictutre(iamge): # 遍历数组的每个像素点
print(iamge.shape)
heigh = iamge.shape[0] # 形状的第一维度(高度)
width = iamge.shape[1] # 第二维度(宽度)
channel = iamge.shape[2] # 通道数
print("heigh", heigh)
print("width", width)
print("channel", channel)
def inverse(img): # 像素取反
dst = cv2.bitwise_not(img)
cv2.imshow("img", dst)
def create_Image():
img = np.zeros([400, 400, 3], np.uint8) # 生成一张全0三通道的400*400大小的图(全黑)
img[:, :, 0] = np.ones([400, 400])*255 # 修改原图生成全蓝色的新图 0 1 2 (三通道顺序)
cv2.imshow("newpicture", img)
# img = np.ones([400,400,1],np.uint8)
# img = img * 127
# cv2.imshow("new2", img) 这些是单通道生成灰色图像的代码
# 早期黑白电视的值是0到255(0是黑色,255是白色)
src = cv2.imread("D:/pictures/sunny.jpg") # 引用一下class one的图
cv2.imshow('src', src) # blue,green,red 三通道的顺序(0,1,2)
assess_pictutre(src)
create_Image()
t1 = cv2.getTickCount() # 计算上面所需时间
inverse(src)
t2 = cv2.getTickCount() # 同上
time = (t2-t1)/cv2.getTickFrequency() # 两时间差就是inverse所用的时间
print("time is ", time*1000) # 乘以1000转化为毫秒的计数单位
cv2.waitKey(0) # 等待下一个按键触发
cv2.destroyAllWindows() # 关闭窗口
| true
|
d8dfca241d4e289253da036500492b8d41900bf1
|
Python
|
lk-greenbird/costar_plan
|
/costar_task_plan/tests/sampler_test.py
|
UTF-8
| 2,138
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python
import unittest
import keras.losses as l
import keras.backend as K
import numpy as np
from costar_models import SamplerLoss
class SamplerLossTest(unittest.TestCase):
def test1(self):
A = np.array([[0,1,0],[1,0.7,0.5]]).T
B = np.array([[0.001, 1.002, 0.01],[0.001, 0.002, 2.01]]).T
print "==========="
correct = np.zeros((3,3))
print "A 1\t\t2\t\t3"
for i in xrange(3):
for j in xrange(3):
correct[i,j] = np.sum((B[i] - A[j])**2)
print correct
print "==========="
loss = SamplerLoss()
x = K.variable(value=A)
y = K.variable(value=B)
x2 = K.variable(value=np.array([A]))
from keras.layers import Lambda
import tensorflow as tf
print "---"
print x2
print x2.shape
print B
print K.eval(Lambda(lambda x: tf.gather_nd(tf.transpose(x),[[i] for i in range(2)]))(x2))
print K.eval(Lambda(lambda x: tf.gather_nd(x,[[0,1]]))(x2))
print "---"
# Distances from A to B
res = K.eval(loss._dists(x,y))
print res
self.assertTrue(np.all(np.abs(correct - res) < 1e-5))
# Distances from B to itself
res = K.eval(loss._dists(y,y))
print res
print "==========="
print "Loss"
print "==========="
# Loss
res2 = K.eval(loss(x,y))
print res2
#z = K.dot(x,y)
#res = K.eval(z)
#print res
def test2(self):
A = np.array([[0,0,1,0,0]])
B = np.array([[2]])
C = np.array([[3]])
A = K.variable(value=A)
B = K.variable(value=B)
C = K.variable(value=C)
cc = l.get("categorical_crossentropy")
print K.eval(cc(A,B))
print K.eval(cc(A,C))
print K.eval(cc(A,A))
if __name__ == '__main__':
import tensorflow as tf
with tf.device('/cpu:0'):
config = tf.ConfigProto(
device_count={'GPU': 0}
)
sess = tf.Session(config=config)
K.set_session(sess)
unittest.main()
| true
|
a365db39d07fd7ba358d74ba59e9d21df8ff88f9
|
Python
|
minrivertea/laowailai
|
/questions/split_search.py
|
UTF-8
| 1,208
| 3.203125
| 3
|
[] |
no_license
|
#-*- coding: iso-8859-1 -*
##
## Split search string - Useful when building advanced search application
## By: Peter Bengtsson, mail@peterbe.com
## May 2008
## ZPL
##
__version__='1.0'
"""
split_search(searchstring [str or unicode],
keywords [list or tuple])
Splits the search string into a free text part and a dictionary of keyword
pairs. For example, if you search for 'Something from: Peter to: Lukasz'
this function will return
'Something', {'from':'Peter', 'to':'Lukasz'}
It works equally well with unicode strings.
Any keywords in the search string that isn't recognized is considered text.
"""
import re
def split_search(q, keywords):
params = {}
s = []
regex = re.compile(r'\b(%s):' % '|'.join(keywords), re.I)
bits = regex.split(q)
skip_next = False
for i, bit in enumerate(bits):
if skip_next:
skip_next = False
else:
if bit in keywords and params:
params[bit.lower()] = bits[i+1].strip()
skip_next = True
elif bit.strip():
s.append(bit.strip())
return ' '.join(s), params
| true
|
0f00c3ee7216ea806a61d16a9f77f481f8035c6e
|
Python
|
honzabilek4/artificial-intelligence-examples
|
/2.5.1_10.py
|
UTF-8
| 830
| 3.203125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
from linked_lists import LinkedList, Cons, Nil
def append(xs, ys):
if xs == Nil:
return ys
else:
return Cons(xs.head, append(xs.tail, ys))
def qsort(xs):
if xs == Nil:
return Nil
if xs.tail == Nil:
return xs
ms, vs = divide(xs.head, xs.tail)
return append(qsort(ms), Cons(xs.head, qsort(vs)))
def divide(h, xs):
if xs == Nil:
return (Nil, Nil)
ms, vs = divide(h, xs.tail)
if xs.head <= h:
return (Cons(xs.head, ms), vs)
else:
return (ms, Cons(xs.head, vs))
# demonstracni vypis
if __name__ == "__main__":
print("Radici algoritmus QuickSort\n")
print("qsort(LinkedList([5, 2, 8, 2, 654, 8, 3, 4])): \n\t%s\n" % \
qsort(LinkedList([5, 2, 8, 2, 654, 8, 3, 4])))
| true
|
d62d06b3205eafb58563670844cafe3bf9441a2f
|
Python
|
saurabh11308/aws-team3
|
/lambda.py
|
UTF-8
| 1,225
| 4.5
| 4
|
[] |
no_license
|
#!/usr/bin/python
# Lambda function example
print("\nExample Program 1 - Anonymous Function Lambda\n")
total = lambda s1,s2,s3,s4,s5:s1+s2+s3+s4+s5
#Now call total as a function
print("Student1 total marks : ",total(90,70,85,80,67))
print("Student2 total marks : ",total(10,30,45,50,78))
def func_ref(list):
print("List values before append are : ",list)
list.append([90,75,68,54])
print("List values after append are : ",list)
return
list = [60,70,80]
print("Example Program 2: Passby assignment\n")
print("List values before function call are : ",list)
func_ref(list)
print("List values after function call are : ",list)
# Pass by value
def func_value(obj):
# To change passed parameter into function
obj = 90
print("Values inside the function: ", obj)
return
obj = 80
print("Example Program 3: Passby value\n")
print("obj values before function call are : ",obj)
func_value(obj)
print("obj values after function call are : ",obj)
#Global and local variables
print("Example Program 4 - Global Values\n")
sum = 500
def total(s1,s2,s3,s4,s5):
sum = s1+s2+s3+s4+s5
print("Inside the function :",sum)
return sum
total(90,85,95,85,70)
print("Outside the function : ",sum)
| true
|
f13544dda3edb0ff7b44d2c294444f14df1be341
|
Python
|
womogenes/AoC-2020-solutions
|
/01/1.2.py
|
UTF-8
| 711
| 3.53125
| 4
|
[] |
no_license
|
with open("1-input.txt") as fin:
data = fin.read()
numbers = [int(i) for i in data.split("\n")[:-1]]
print(len(numbers))
def naive():
for i in numbers:
for j in numbers:
for k in numbers:
if i + j + k == 2020:
print(i * j * k)
break
def smarter():
for i in range(len(numbers)):
rem = 2020 - numbers[i]
seen = set()
for j in range(i, len(numbers)):
seen.add(numbers[j])
if rem - numbers[j] in seen:
product = numbers[i] * numbers[j] * (rem - numbers[j])
print(product)
smarter()
| true
|
d9fe5e628635a98692685beddc48544b6b95cfb0
|
Python
|
Enokisan/WeatherDatabase
|
/tendl.py
|
UTF-8
| 317
| 2.671875
| 3
|
[] |
no_license
|
import urllib.request as req
def download():
# URLや保存ファイル名を指定
url = 'https://www.jma.go.jp/bosai/forecast/data/forecast/010000.json'
filename = 'tenki.json'
# ダウンロード
req.urlretrieve(url, filename)
print("[Weather Database] tenki.json has been downloaded!\n")
| true
|
b5b1faf0565fa75e5d01d03001180e3d51f23472
|
Python
|
NeerajK23/WeatherForecast
|
/application.py
|
UTF-8
| 2,344
| 2.78125
| 3
|
[] |
no_license
|
from flask import Flask,render_template, request,url_for
import pywapi
import requests
from bs4 import BeautifulSoup
app=Flask(__name__)
def get_city_name_list(city_name):
#this will give you a dictionary of all cities in the world with this city's name Be specific (city, country)!
lookup = pywapi.get_location_ids(city_name)
return lookup
def fetch_data(city_id,forecaste_type):
country_code=city_id[0:2]
url="https://weather.com/en-IN/weather/{}/l/{}:1:{}".format(forecaste_type,city_id,country_code)
page=requests.get(url)
soup=BeautifulSoup(page.content,"html.parser")
if forecaste_type=="tenday":
div_class_name="locations-title ten-day-page-title"
elif forecaste_type=="5day":
div_class_name="locations-title five-day-page-title"
all=soup.find("div",{"class":div_class_name}).find("h1").text
table=soup.find_all("table",{"class":"twc-table"})
list_of_data=[]
for items in table:
for i in range(len(items.find_all("tr"))-1):
d = {}
d["day"]=items.find_all("span",{"class":"date-time"})[i].text
d["date"]=items.find_all("span",{"class":"day-detail"})[i].text
d["desc"]=items.find_all("td",{"class":"description"})[i].text
d["temp"]=items.find_all("td",{"class":"temp"})[i].text
d["precip"]=items.find_all("td",{"class":"precip"})[i].text
d["wind"]=items.find_all("td",{"class":"wind"})[i].text
d["humidity"]=items.find_all("td",{"class":"humidity"})[i].text
list_of_data.append(d)
return list_of_data
@app.route('/')
def name():
return render_template('enterplace.html')
@app.route('/place',methods = ['POST', 'GET'])
def place():
if request.method == 'POST':
city_name = request.form['Name']
list_of_cities=get_city_name_list(city_name)
return render_template("list_of_cities.html",list_of_cities = list_of_cities)
@app.route('/finalcode',methods = ['POST', 'GET'])
def citykey():
forecaste_type=request.form['forecaste_type']
final_city_code = request.form['final_city']
forecasted_data=fetch_data(final_city_code,forecaste_type)
return render_template("show_data.html",forecasted_data = forecasted_data)
if __name__== '__main__':
app.run(debug=True,host='0.0.0.0',port=5002, threaded=True)
| true
|
446992f31bab0c0666d87944c995b2e73386d377
|
Python
|
cermegno/Ansible-test
|
/web.py
|
UTF-8
| 400
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def mainmenu():
return """
<html>
<body>
<center>
<h1>Hi there</h1>
<h2>You brought me here with <u>Ansible<u>!</h2><br>
</center>
</body>
</html>"""
if __name__ == "__main__":
app.run(debug=False,host='0.0.0.0', port=int(os.getenv('PORT', '5000')))
| true
|
8f1ee243aec87332ae296ffe99ee08e231cebca2
|
Python
|
fuksi/pyalgorithm
|
/merge_sort/tests.py
|
UTF-8
| 420
| 3.3125
| 3
|
[] |
no_license
|
import unittest
from main import merge_sort
class MainTest(unittest.TestCase):
def test_unordered_list(self):
result = merge_sort([1,5,3,4,1])
self.assertEqual([1,1,3,4,5], result)
def test_empty_list(self):
result = merge_sort([])
self.assertEqual([], result)
def test_short_list(self):
result = merge_sort([10,1])
self.assertEqual([1,10], result)
| true
|
8d6b47b73adb2b7e22e7a75fc81266a77cefe4e0
|
Python
|
kimjane7/numerical_linalg
|
/homework5/test.py
|
UTF-8
| 790
| 3.25
| 3
|
[] |
no_license
|
import os
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.family'] = "serif"
# 3
plt.figure(figsize=(8,6))
x = np.arange(1.920,2.081,0.001)
p = (x-2)**9
plt.plot(x,p,c='b',label=r'factorized $p(x)=(x-2)^9$')
p = x**9-18*x**8+144*x**7-672*x**6+2016*x**5-4032*x**4+5376*x**3-4608*x**2+2304*x-512
plt.plot(x,p,c='r',label=r'expanded $p(x)$')
plt.xlabel(r'$x$',fontsize=12)
plt.legend(loc='upper left', shadow=True, fontsize=12)
plt.title(r'Stability of a polynomial')
# save and open
figname = 'polynomial.png'
plt.savefig(figname, format='png')
os.system('okular '+figname)
plt.clf()
# 4
b = np.float32(1.0)
c = np.float32(0.004004)
a = 1000*(c/(np.sqrt(b**2+c)-b)-2*b)
print(a)
a = 1000*c/(np.sqrt(b**2+c)+b)
print(a)
| true
|
476b7cd985dffacaa302adb8f7f609fab057a3cd
|
Python
|
naorton/Advent-of-Code
|
/2015/Day 10/day10.py
|
UTF-8
| 814
| 3.421875
| 3
|
[] |
no_license
|
#data = [1113222113]
#1 = 11
#11 = 21
#21 = 1211
#1211 = 111221
#111221 = 312211
data = [1,1]
count = 0
temp = len(data) + 1
final = []
final.append(temp)
final += data
print(final)
def num_count(num_list):
temp_list = []
count = 1
temp_num = num_list[0]
i = 1
if len(num_list) == 1:
temp_list.append(count)
temp_list.append(temp_num)
return temp_list
while i < len(num_list):
if num_list[i-1] == num_list[i]:
count += 1
elif num_list[i-1] != num_list[i]:
temp_list.append(count)
temp_list.append(temp_num)
temp_num = num_list[i]
count = 1
if i+1 == len(num_list):
temp_list.append(count)
temp_list.append(temp_num)
i += 1
return temp_list
data = [1,1,1,3,2,2,2,1,1,3]
i = 0
new_list = data
while i < 50:
new_list = num_count(new_list)
i +=1
print(len(new_list))
| true
|
efa11152d0055ad60ed85c9132111c28994aed81
|
Python
|
Nardri/trisixty-buys-API
|
/api/utilities/helpers/errors.py
|
UTF-8
| 377
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
"""Errors"""
# utilities
from api.utilities.validations.custom_validations_error import ValidationError
def raises(message, status_code):
"""A helper method for raising exceptions.
Args:
message (str): Message
status_code (int): Status code
Raises:
ValidationError
"""
raise ValidationError(dict(message=message), status_code)
| true
|