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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c558f72d7fad0e834ae7fb4ace391bf26e32d018 | Python | varnar217/lesson2 | /ana.py | UTF-8 | 461 | 2.921875 | 3 | [] | no_license | doing={"Как дела ?": "Хорошо!", "Что делаешь?": "Программирую"}
def ask_user():
while True:
bufer_string=input('пользователь\n')
#print(doing[bufer_string])
try :
doing[bufer_string]
print(doing[bufer_string])
break
#pass
except KeyError:
print ('нет вопрсса')
#pass
ask_user()
| true |
0b44063b8709f7f10a66acf22e36c97fa0a33acf | Python | VinACE/producer_shield | /ihealthdata/utils/configmanager.py | UTF-8 | 1,171 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | import configparser as configParser
import os
class ConfigManager:
def __init__(self):
self.config_parser = configParser.ConfigParser()
file_name = os.path.join(os.getcwd(), 'config.ini')
print(file_name)
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
self.config_parser.read(os.path.realpath(file_name))
def config_sectionmap(self, section):
contents = {}
self.config_parser.sections()
options = self.config_parser.options(section)
for option in options:
try:
contents[option] = self.config_parser.get(section, option)
if contents[option] == -1:
print('skip: %s ' % option)
except Exception:
print('exception on %s!' % option)
contents[option] = None
return contents
def config_item(self, section, key):
content = self.config_sectionmap(section)
try:
ret_val = content[key.lower()]
return ret_val
except Exception:
print('No value found for key %s under section %s' % (key, section))
return None
| true |
d08a4abdd7297beddb3baea6c13c8d519a2b31f8 | Python | PhraxayaM/amazon_practice_problems | /Batch #1/Medium/sum of nodes with even valued grandparents.py | UTF-8 | 1,161 | 3.65625 | 4 | [] | no_license | """
Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
If there are no nodes with an even-valued grandparent, return 0.
Example 1:
6
/ \
7 8
/ \ / \
2 7 1 3
/ / \ \
9 1 4 5
"""
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
if not root:
return 0
stack = []
stack.append((root,[root.val]))
sums = 0
while stack:
node, fam = stack.pop()
# check fam length and if grandparens are even
if len(fam) > 2 and fam[-3]%2 == 0:
sums+=node.val
# DFS while tracking granparents
if node.left:
stack.append((node.left,fam+[node.left.val]))
if node.right:
stack.append((node.right,fam+[node.right.val]))
return sums | true |
d73a8134ed8c4b477d2567b8ca74566a25e3b271 | Python | shangpf1/python-homework | /2018-12/test6.py | UTF-8 | 941 | 4.46875 | 4 | [] | no_license | # 总结 filter reduce map函数的用法
# 处理序列中的每个元素,得到的结果是一个“列表”,该列表元素个数及位置与原来一样
# map()
# filter 遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
people = [
{'name':'alex','age':1000},
{'name':'lucy','age':10000},
{'name':'jack','age':9000},
{'name':'rose','age':18}
]
# 过滤掉people中年龄大于18的人 -- filter函数
res = filter(lambda p:p['age']<=18,people)
print(list(res))
# reduce 函数的用法
from functools import reduce
print(reduce(lambda x,y:x+y,range(5),1))
print(reduce(lambda x,y:x+y,range(1,5)))
# map函数的用法
num = [1,3,5,7]
def map_test(func,array):
resp = []
for i in array:
yt = func(i)
resp.append(yt)
return resp
print(map_test(lambda x:x**2,num))
print(map_test(lambda x:x+1,num))
print(map_test(lambda y:y-1,num))
| true |
70b28f5d2698f122d136fd81f91db79828079cfc | Python | senoa95/agbot_deploy | /src/agbot_nav/src/pp_controller.py | UTF-8 | 5,749 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
import rospy
import math
from geometry_msgs.msg import Point32,Pose
import transforms3d as tf
import numpy as np
pi = 3.141592653589793238
#class to define vehicle position on a coordinate system at a certain heading
class Point:
def __init__(self,inputX = 0,inputY = 0,inputHeading = 0):
self.x = inputX
self.y = inputY
self.heading = inputHeading
# Define a global variable to keep track of the current position of Vehicle
global currentPoint
currentPoint = Point()
reachedGoal = False
# class to define vehicle parameters
class AckermannVehicle:
def __init__(self,inputLength = 1,inputMaximumSteeringAngle = 1,inputMaximumVelocity = 48*pi/180):
self.length = inputLength
self.maximumSteeringAngle = inputMaximumSteeringAngle
self.maximumVelocity = inputMaximumVelocity
self.minTurningRadius = self.length / math.tan(self.maximumSteeringAngle)
# class to define Pure pursuite controller parameters
class PPController:
def __init__(self,inputLeadDistance,inputLength):
self.leadDistance = inputLeadDistance
self.length = inputLength #set the length for ppcontroller as the length of maximumSteeringAngle
self.turningRadius = 1
# compute the steering radius of ackerman vehicle of given parameters
def compute_turning_radius(self, inputCurrent = Point(0,0,0) , inputGoal = Point(0,0,0)):
current = inputCurrent
goal = inputGoal
beta = math.atan2((goal.y - current.y),(goal.x-current.y)) # angle between line joining start-end and x axis
temp = ((current.heading + 3.14))
temp = (math.fmod(temp , 2*3.14)) - 3.14
alpha = temp - beta #angle between current heading and the line joining start-end
L_a = math.sqrt(math.pow((goal.x - current.x),2) + math.pow((goal.y-current.y),2))
self.turningRadius = L_a / (2*math.sin(alpha)) #this outputs the turning radius
# compute the steering angle of ackermann vehicle of given paramters
def compute_steering_angle(self):
# Steering angle command from Pure pursuit paper:
# Steering angle = atan(L/R)
steeringAngle = math.atan(self.length / self.turningRadius)
# @senoa95: I'm commenting out this steering angle command. I did not understand this one.
#steeringAngle = 0.7*math.sin(alpha)*self.length
return steeringAngle
# compute forward velocity relative to steering angle
def compute_forward_velocity(self): #added a variable velocity based on Bijo's suggestion
#forwardVelocity = mule.maximumVelocity * (1 - atan(abs(steeringAngle))/(pi/2)); //this specifies the forward velocity at a given steering angle
forwardVelocity = 0.4
return forwardVelocity
# this is a test line...
def XYZcallback(data):
global currentPoint
currentPoint.x = data.position.x
currentPoint.y = data.position.y
euler = tf.euler.quat2euler([data.orientation.x,data.orientation.y,data.orientation.z,data.orientation.w])
euler[1] = euler[1] - 1.57
euler[2] = euler[2] + 3.14
currentPoint.heading = euler[2]
def command():
global currentPoint
global goalPoint
# Create objects for AckermannVehicle and Pure Pursuit controller:
mule = AckermannVehicle(2.5772,60*pi/180,1)
senaPurePursuit = PPController(0,mule.length)
rospy.Subscriber("/agBOT/local/Pose", Pose, XYZcallback)
rospy.init_node('ppcontroller', anonymous=True)
pub = rospy.Publisher('/agBOT/ackermann_cmd', Point32, queue_size =10)
rate = rospy.Rate(10)
# Initialize:
# 1. Parameters:
threshold = 0.5
euclideanError = 0
# 2. Points:
goalPoint = Point()
currentPoint = Point()
# 3. Commands:
command = Point32()
stationaryCommand = Point32()
stationaryCommand.x = 0
stationaryCommand.y = 0
# Loop through as long as the node is not shutdown:
while not rospy.is_shutdown():
# Update the current Point:
# Case #1:Vehicle is in the vicinity of current goal point (waypoint):
if (euclideanError < threshold):
reachedGoal = True
goalPoint = Point()
currentPoint = Point()
while (euclideanError < threshold):
# Acquire the new goal point from the user:
goalPoint.x = int(input('Enter goX:'))
goalPoint.y = int(input('Enter goY:'))
goalPoint.heading = int(input('Enter goHeading:'))
# Recompute the new Euclidean error:
euclideanError = math.sqrt((math.pow((goalPoint.x-currentPoint.x),2) + math.pow((goalPoint.y-currentPoint.y),2)))
# # Recompute Euclidean error if euclideanErro !< threshold:
# euclideanError = math.sqrt((math.pow((goalPoint.x-currentPoint.x),2) + math.pow((goalPoint.y-currentPoint.y),2)))
print (" Euclidean Error = ", euclideanError)
# Case #2:
if (euclideanError > threshold):
if reachedGoal:
# Compute turningRadius , steeringAngle and velocity for current start and goal point:
senaPurePursuit.compute_turning_radius(currentPoint, goalPoint)
command = Point32()
command.x = senaPurePursuit.compute_steering_angle()
command.y = senaPurePursuit.compute_forward_velocity()
reachedGoal = False
# Publish the computed command:
pub.publish(command)
# Recompute the Euclidean error to see if its reducing:
euclideanError = math.sqrt((math.pow((goalPoint.x-currentPoint.x),2) + math.pow((goalPoint.y-currentPoint.y),2)))
rate.sleep()
rospy.spin()
if __name__ == '__main__':
command()
| true |
26c9efd8c141da03e02fe38882bfc32fc3235cf9 | Python | MareboinaRavi/python | /ds_problem.py | UTF-8 | 242 | 3.015625 | 3 | [] | no_license | class A(object):
def method(self):
print('I am from class A')
class B(A):
def method(self):
print('I am from class B')
class C(A):
def method(self):
print('I am from class C')
class D(C,B):
pass
d = D()
d.method()
print(D.mro()) | true |
8646bc886ecb534ffb03bf13ebaad0ebc03db246 | Python | aklys/Black_Jack | /Card_Deck.py | UTF-8 | 1,663 | 3.8125 | 4 | [] | no_license | import random
class Deck:
def __init__(self):
self.deck = []
def generate_std_deck(self):
std_cards = {"Suits": ["S", "C", "H", "D"],
"Value": ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K"]}
for i in std_cards["Suits"]:
for j in std_cards["Value"]:
self.deck.append(StdCard(i + j))
def add_jokers(self, num):
for i in range(num):
self.deck.append(StdCard("JJ"))
def shuffle(self, num_shuffles = 1):
for i in range(num_shuffles):
random.shuffle(self.deck)
def deal_card(self, hand):
dealt_card = random.choice(self.deck)
print("{} has been dealt a card.".format(hand.owner))
hand.add_card(dealt_card)
self.deck.remove(dealt_card)
class StdCard:
def __init__(self, ref):
self.ref = ref
def __repr__(self):
names = {"A": "Ace", "2": "Two", "3": "Three", "4": "Four",
"5": "Five", "6": "Six", "7": "Seven", "8": "Eight",
"9": "Nine", "10": "Ten", "J": "Jack", "Q": "Queen", "K": "King",
"JJ": "Joker", "S": "Spades", "C": "Clubs", "H": "Hearts", "D": "Diamonds"}
if self.ref == "JJ":
return "Joker"
else:
return names[self.ref[1:]] + " of " + names[self.ref[0]]
class Hand:
def __init__(self, owner):
self.hand = []
self.owner = owner
def add_card(self, card):
self.hand.append(card)
def __repr__(self):
return "Currently {} is holding:\n {}".format(self.owner, self.hand)
| true |
9e281e072c7da292fc16de4928efa8362c5e7b6e | Python | JiaoZexin/PyDemo | /kaike/first/3Demo1.py | UTF-8 | 789 | 4.28125 | 4 | [] | no_license | height = 0;
while height < 170:
height = int(input('继续输入身高:'))
print('已经找到人去搬水了~')
print('''课外题一:for 循环能确定循环次数while 不能确定循环次数 需要有跳出while循环的条件 break等''')
print('课外题二')
sum1 = 0;
for i in range(1, 101):
sum1 += i;
print('使用for循环打印1-100之间的和:', sum1)
sum2 = 0;
i = 1;
while i < 101:
sum2 += i;
i+=1;
print('使用while循环打印1-100之间的和:', sum2)
print('课外题三 使用for 和while打印100以内的偶数')
for i in range(1, 101):
if i % 2 == 0:
print('使用for循环打印1-100之间偶数:', i)
i = 1;
while i < 101:
if i % 2 == 0:
print('使用while循环打印1-100之间的偶数:', i)
i += 1; | true |
a25da94f8d1616a2e12fe90111b9dffba4df10ea | Python | matib99/DWave | /CVRPTW/cvrptw_problem.py | UTF-8 | 11,731 | 2.8125 | 3 | [] | no_license | from qubo_helper import Qubo
from itertools import combinations, permutations
class CVRPTWProblem:
def __init__(self, sources, costs, time_costs, capacities, dests, weights, time_windows, vehicles_num, time_blocks_num):
self.costs = costs
self.time_costs = time_costs
self.capacities = capacities
self.dests = dests
self.weights = weights
self.time_windows = time_windows
self.time_blocks_num = time_blocks_num
self.dests_num = len(dests)
self.vehicles_num = vehicles_num
self.max_cost = max(costs[a][b] for (a, b) in combinations(dests + sources, 2)) * 1.25
self.min_cost = min(costs[a][b] for (a, b) in combinations(dests + sources, 2))
self.zero_edges = []
# Merging all sources into one source.
source = 0
weights[source] = 0
self.source = source
in_nearest_sources = dict()
out_nearest_sources = dict()
# Finding nearest source for all destinations.
for dest in dests:
in_nearest = sources[0]
out_nearest = sources[0]
for s in sources:
costs[source][s] = 0
costs[s][source] = 0
if costs[s][dest] < costs[in_nearest][dest]:
in_nearest = s
if costs[dest][s] < costs[dest][out_nearest]:
out_nearest = s
costs[source][dest] = costs[in_nearest][dest]
costs[dest][source] = costs[dest][out_nearest]
time_costs[source][dest] = time_costs[in_nearest][dest]
time_costs[dest][source] = time_costs[dest][out_nearest]
in_nearest_sources[dest] = in_nearest
out_nearest_sources[dest] = out_nearest
time_costs[source][source] = 0
self.in_nearest_sources = in_nearest_sources
self.out_nearest_sources = out_nearest_sources
# edges to 'delete later'
for (a, b, c) in permutations(dests, 3):
if time_costs[a][b] + time_costs[b][c] == time_costs[a][c]:
self.zero_edges.append((a, c))
def get_capacity_qubo(self, capacity_const):
tw = self.time_windows
dests = self.dests
weights = self.weights
cap_qubo = Qubo()
for vehicle in range(self.vehicles_num):
capacity = self.capacities[vehicle]
for (d1, d2) in combinations(dests, 2):
for (t1, t2) in combinations(range(self.time_blocks_num), 2):
if (tw[d1][0] < t1 < tw[d1][1]) and (tw[d2][0] < t2 < tw[d2][1]):
index = ((vehicle, d1, t1), (vehicle, d2, t2))
cost = capacity_const * weights[d1] * weights[d2] / capacity**2
cap_qubo.add(index, cost)
return cap_qubo
def get_time_windows_qubo(self, time_windows_const, penalty_const):
tw_qubo = Qubo()
for d in self.dests:
tw = self.time_windows[d]
for (t1, t2) in combinations(range(self.time_blocks_num), 2):
for v in range(self.vehicles_num):
index = ((v, d, t1), (v, d, t2))
index_m = ((v, d, t2), (v, d, t1))
index1 = ((v, d, t1), (v, d, t1))
index2 = ((v, d, t2), (v, d, t2))
# we don't want vehicles to be late
if t1 > tw[1]:
tw_qubo.add(index1, penalty_const)
if t2 > tw[1]:
tw_qubo.add(index2, penalty_const)
# vehicle can 'visit' certain destination only once. But it can wait for the time window to start
# waiting is represented by 2 visits: one before the time window and one at the beginning of it
# (because there is no point in waiting any longer)
# this should be the only exception in which vehicle can visit twice the same destination
if t1 < t2:
if t2 != tw[0]:
tw_qubo.add(index, penalty_const)
tw_qubo.add(index_m, penalty_const)
for t in range(self.time_blocks_num):
if tw[0] <= t <= tw[1]:
for v in range(self.vehicles_num):
index = ((v, d, t), (v, d, t))
# reward for being on time
tw_qubo.add(index, time_windows_const)
if t < tw[0]:
for t2 in range(t, tw[0]):
for d2 in self.dests:
if d2 != d:
for v in range(self.vehicles_num):
index = ((v, d, t), (v, d2, t2))
index_m = ((v, d2, t2), (v, d, t))
# if vehicle is at the destination before time window it should wait
tw_qubo.add(index, penalty_const)
tw_qubo.add(index_m, penalty_const)
return tw_qubo
def get_sources_qubo(self, cost_const, penalty_const, reward_const, time_windows_const):
src_qubo = Qubo()
dests = self.dests
source = self.source
costs = self.costs
time_blocks_num = self.time_blocks_num
for dest in dests:
in_time = self.time_costs[source][dest] # [0]
for t in range(time_blocks_num):
out_time = self.time_costs[dest][source] # [t]
for v in range(self.vehicles_num):
in_index = ((v, source, 0), (v, dest, t))
out_index = ((v, dest, t), (v, source, t + out_time))
dest_index = ((v, dest, t), (v, dest, t))
# too early to arrive from source
if t < in_time:
src_qubo.add(dest_index, penalty_const)
else:
if t == in_time:
cost = (costs[source][dest] - self.min_cost) * cost_const # [0]
src_qubo.add(in_index, (reward_const * 0.5 + cost) * 0.75)
else:
src_qubo.add(in_index, 0)
# to late to go back to the source
if time_blocks_num - t - 1 < out_time:
src_qubo.add(out_index, penalty_const)
else:
cost = (costs[dest][source] - self.min_cost) * cost_const # [0]
src_qubo.add(out_index, (reward_const * 0.5 + cost) * 0.75)
for t2 in range(t, min(t + out_time, time_blocks_num - 1)):
# too fast
pnl_index = ((v, dest, t), (v, source, t2))
src_qubo.add(pnl_index, penalty_const)
for v in range(self.vehicles_num):
for t in range(time_blocks_num):
src_index = ((v, source, t), (v, source, t))
src_qubo.add(src_index, time_windows_const)
for (t1, t2) in combinations(range(1, time_blocks_num), 2):
for v in range(self.vehicles_num):
index = ((v, source, t1), (v, source, t2))
src_qubo.add(index, penalty_const)
# vehicle must start and end at source
for t in range(1, time_blocks_num):
for d in dests:
for v in range(self.vehicles_num):
for t2 in range(t, time_blocks_num):
index = ((v, source, t), (v, d, t2))
src_qubo.add(index, penalty_const)
return src_qubo
def get_cvrptw_qubo(self,
penalty_const, reward_const, capacity_const, time_windows_const):
dests_num = self.dests_num
cost_const = (-0.5 * reward_const / ((self.max_cost - self.min_cost) * dests_num))
dests = self.dests
costs = self.costs
time_costs = self.time_costs
vehicles_num = self.vehicles_num
time_blocks_num = self.time_blocks_num
vrp_qubo = Qubo()
for (d1, d2) in permutations(dests, 2):
for (t1, t2) in combinations(range(time_blocks_num), 2):
if t1 + time_costs[d1][d2] == t2:
for i in range(vehicles_num):
# going from (d1) to (d2) at the time (t1) with vehicle (i)
cost = (costs[d1][d2] - self.min_cost) * cost_const # [t]
var2 = (i, d2, t2) # [t]
var1 = (i, d1, t1)
vrp_qubo.add((var1, var2), (reward_const / dests_num + cost))
# reward for visiting destination + cost of travel
# parameters on edges are positive if t2 - t2 = time_cost[d1][d2]
# zero if t2 - t2 > time_cost[d1][d2] and (penalty const) if t2 - t2 < time_cost[d1][d2]
else:
if d1 != d2:
if t1 + time_costs[d1][d2] > t2:
for i in range(vehicles_num):
# cannot go from (b) to (a) at the time (t1) in (dt)
var1 = (i, d1, t1)
var3 = (i, d2, t2)
vrp_qubo.add((var1, var3), penalty_const)
else:
for i in range(vehicles_num):
# waiting
var1 = (i, d1, t1)
var3 = (i, d2, t2)
vrp_qubo.add((var1, var3), 0)
# cannot be in 2 places at the same time
for (d1, d2) in combinations(dests, 2):
for t in range(time_blocks_num):
for i in range(vehicles_num):
var1 = (i, d1, t)
var2 = (i, d2, t)
vrp_qubo.add((var1, var2), penalty_const)
# customer cannot be visited twice in different times
for d in dests:
for (t1, t2) in permutations(range(time_blocks_num), 2):
for (i1, i2) in combinations(range(vehicles_num), 2):
var1 = (i1, d, t1)
var2 = (i2, d, t2)
vrp_qubo.add((var1, var2), penalty_const)
# customer cannot be visited twice in the same time by 2 different vehicles
for d in dests:
for t in range(time_blocks_num):
for (i1, i2) in combinations(range(vehicles_num), 2):
var1 = (i1, d, t)
var2 = (i2, d, t)
vrp_qubo.add((var1, var2), penalty_const)
print("src")
src_qubo = self.get_sources_qubo(cost_const, penalty_const, reward_const / dests_num,
time_windows_const / dests_num)
print("cap")
cap_qubo = self.get_capacity_qubo(capacity_const)
print("tw")
tw_qubo = self.get_time_windows_qubo(time_windows_const / dests_num, penalty_const)
print("merge")
vrp_qubo.merge_with(src_qubo, 1, 1)
vrp_qubo.merge_with(cap_qubo, 1, 1)
vrp_qubo.merge_with(tw_qubo, 1, 1)
print("bound")
vrp_qubo.bound(-penalty_const, penalty_const)
return vrp_qubo
| true |
ac7fbcd1e9769eed2c78fb322966e4f338107b17 | Python | prajaktaaD/Basic-Python1 | /Loop_control_statements.py | UTF-8 | 215 | 3.59375 | 4 | [] | no_license | x=int(input("enter the num of items:"))
i=1
stock=7
while(i<=x):
if(i<=stock):
print("issue product=",i)
i+=1
continue
else:
print("out of stock")
i=i+1
break
| true |
b1f9f2485b8629fe5e6c66ad4148ec2653e403c3 | Python | moriken0921/python_study | /応用編/14.ファイル読み書き/sample01.py | UTF-8 | 259 | 2.671875 | 3 | [] | no_license | import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
f = open('/Users/kentomori/Documents/GitHub/python_study/応用編/14.ファイル読み書き/read.txt', 'r', encoding='utf-8')
for row in f:
print(row)
f.close()
| true |
f1f9f5c4a4bf5a5925354d2d2d496fe803e611eb | Python | iliankostadinov/thinkpython | /Chapter17/Exercise_17_2.py | UTF-8 | 1,317 | 4.3125 | 4 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python3
"""
Write a definition for a class named Kangaroo with the following methods:
1. An __init__ method that initializes an attribute named pouch_contents to an
empty list.
2. A method named put_in_pouch that takes an object of any type and adds it to
pouch_contents .
3. A __str__ method that returns a string representation of the Kangaroo object
and the contents of the pouch.
Test your code by creating two Kangaroo objects, assigning them to variables
named kanga and roo , and then adding roo to the contents of kangas pouch.
"""
class Kangaroo(object):
"""Define Kangaroo class """
def __init__(self, name, pouch_contents=None):
self.name = name
if pouch_contents is None:
pouch_contents = []
self.pouch_contents = pouch_contents
def __str__(self):
t = ["Object " + self.name]
for obj in self.pouch_contents:
s = ' ' + object.__str__(obj)
t.append(s)
return '\n'.join(t)
def put_in_pouch(self, item):
"""Adds new ittem to the pouch_contents
item: object to be added
"""
self.pouch_contents.append(item)
kanga = Kangaroo('Kanga')
roo = Kangaroo('Roo')
kanga.put_in_pouch('wallet')
kanga.put_in_pouch('car keys')
kanga.put_in_pouch(roo)
print(kanga)
| true |
6e0c368df092c622b3142de56e274d79d7d5b2b5 | Python | AnhQuann/nguyenanhquan-fundameltal-c4e14 | /Fundamentals/session04/homework/serious_4.py | UTF-8 | 282 | 3.75 | 4 | [] | no_license | bacteriaB = int(input('How many B bacteria are there? '))
minute = int(input('How much time in minute will we wait? '))
looptime = int(minute/2)
for i in range(looptime):
bacteriaB=bacteriaB*2
print('After {0} minutes, we would have {1} bacterias'.format(minute, bacteriaB))
| true |
6a98bac5d88bd86227178b30a590a05484929bc1 | Python | adamtorok96/GitSpider | /GitSpider.py | UTF-8 | 2,281 | 2.609375 | 3 | [] | no_license | from urllib.parse import urlparse
import requests
import scrapy
def has_directory(url, directory='.git'):
return has_file(url, directory + '/')
def has_file(url, file):
full_url = '%s/%s' % (url, file)
r = requests.get('%s' % full_url, allow_redirects=False, timeout=2)
valid_codes = [
200
]
if r.status_code not in valid_codes:
return False, full_url
return r.text.startswith('ref:'), full_url
def get_ext(path):
if not '.' in path:
return None
path = path.split('.')
return path[len(path) - 1]
class GitSpider(scrapy.Spider):
name = 'gitspider'
counter = 0
excluded_extensions = [
'png',
'jpg',
'jpeg',
'bmp',
'zip',
'rar',
'exe',
'pdf',
'txt',
'doc',
'docx'
'docx'
]
allowed_schemes = [
'http',
'https'
]
def __init__(self, **kwargs):
super().__init__(self.name, **kwargs)
starting_url = self.url
if not starting_url.startswith('http://') and not starting_url.startswith('https://'):
starting_url = 'https://' + starting_url
print('Starting url: %s' % starting_url)
self.start_urls = ['%s' % starting_url]
def parse(self, response):
#print('Response URL: %s' % response.url)
self.counter += 1
if self.counter % 10 == 0:
print('[%d]: %s' % (self.counter, response.url))
resp_urlp = urlparse(response.url)
hd, git_path = has_file('%s://%s' % (resp_urlp.scheme, resp_urlp.netloc), file='.git/HEAD')
if hd:
print('Has .git directory: %s' % git_path)
for url in response.xpath('//a/@href').extract():
urlp = urlparse(url)
if len(urlp.scheme) == 0 or len(urlp.netloc) == 0:
continue
url = '%s://%s' % (urlp.scheme, urlp.netloc)
if resp_urlp.netloc is urlp.netloc:
continue
if urlp.scheme not in self.allowed_schemes:
continue
# if len(urlp.path) != 0 and get_ext(urlp.path) in self.excluded_extensions:
# continue
yield scrapy.Request(url, callback=self.parse)
| true |
7236b15a549a3d089335f590d202bf652f243374 | Python | vqpv/stepik-course-58852 | /7 Циклы for и while/7.3 Частые сценарии/4.py | UTF-8 | 156 | 3.34375 | 3 | [] | no_license | n = int(input())
summa = 0
for i in range(n + 1):
if (i ** 2) % 10 == 2 or (i ** 2) % 10 == 5 or (i ** 2) % 10 == 8:
summa += i
print(summa)
| true |
9b27b5880b9536253d2c152c13e51d39924726bd | Python | njokuifeanyigerald/corona-tracker-with-python-speech | /app.py | UTF-8 | 4,372 | 2.640625 | 3 | [] | no_license | import requests
import json
import pyttsx3
import speech_recognition as sr
import re
import threading
import time
APIKEY= 't_Hc1GB4FOkj'
PROJECTTOKEN = 'tN9U7jFUG2JB'
RUNTOKEN = 'tPFHv-guQC-5'
class Data:
def __init__(self, api_key, project_token):
self.api_key = api_key
self.project_token = project_token
self.params = {
'api_key': api_key
}
self.data = self.get_data()
def get_data(self):
response = requests.get(f'https://www.parsehub.com/api/v2/projects/{self.project_token}/last_ready_run/data', params=self.params)
data = json.loads(response.text)
return data
def get_total_cases(self):
data = self.data['total']
for content in data:
if content['name'] == 'Coronavirus Cases:':
return content['value']
return 'network breakdown'
def get_total_deaths(self):
data = self.data['total']
for content in data:
if content['name'] == 'Deaths:':
return content['value']
return 'network breakdown'
def get_total_recovered(self):
data = self.data['total']
for content in data:
if content['name'] == 'Recovered:':
return content['value']
return 'network breakdown'
def get_country_data(self, country):
data = self.data['country']
for content in data:
if content['name'].lower() == country.lower():
return content
return 'network breakdown'
def get_country_list(self):
countries = []
for country in self.data['country']:
countries.append(country['name'])
return countries
def update_data(self):
response = requests.post(f'https://www.parsehub.com/api/v2/projects/{self.project_token}/run', params=self.params)
def poll():
time.sleep(0.1)
oldData = self.data
while True:
new_data = self.get_data()
if new_data != oldData:
self.data = new_data
print('updating data...')
break
time.sleep(5)
t = threading.Thread(target=poll)
t.start()
data = Data(APIKEY,PROJECTTOKEN)
print(data.get_total_cases())
print(data.get_total_deaths())
print(data.get_total_recovered())
print(data.get_country_data('nigeria')['total_cases'])
print(data.update_data())
def speak(self,text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def get_audio(self):
r= sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
except Exception as e:
print('exception', str(e))
return said.lower()
def main(self):
print('start program')
end_word = 'end'
exist_word = 'exit'
stop_word = 'stop'
country_list = data.get_country_list()
Patterns = {
re.compile('[\w\s] + total [\w\s] + cases'):data.get_total_cases,
re.compile('[\w\s] + total cases'):data.get_total_cases,
re.compile('[\w\s] + total [\w\s] + deaths'):data.get_total_cases,
re.compile('[\w\s] + total deaths'):data.get_total_cases
}
countryPatterns = {
re.compile('[\w\s] + cases [\w\s]+'):data.get_country_data['total_cases'],
re.compile('[\w\s] + death [\w\s]+'):data.get_country_data['total_deaths']
}
updateCommand = 'update'
while True:
print('i de hear you!!!...')
text = get_audio()
result = None
for pattern, func in countryPatterns.items():
if pattern.match(text):
words = set(text.split(' '))
for country in country_list:
if country in words:
result = func(country)
break
break
for pattern, func in Patterns.items():
if pattern.match(text):
result = func()
break
if text == updateCommand:
result = 'data is been updated'
data.update_data()
if result:
speak(result)
if text.find(end_word or exist_word or stop_word) != -1:
print("exit")
break
| true |
5e88ce42705287e37b5d0a0d9ef2583c9dd837b5 | Python | meelement/Chatette | /chatette/units/slot/rule_content.py | UTF-8 | 6,115 | 2.828125 | 3 | [
"MIT"
] | permissive | from __future__ import print_function
from random import randint
from chatette.parsing.parser_utils import UnitType, remove_escapement, \
add_escapement_back_in_unit_ref
from chatette.units import Example, RuleContent, may_get_leading_space, \
may_change_leading_case, randomly_change_case, \
with_leading_lower, with_leading_upper
class SlotRuleContent(RuleContent):
"""
This class represents a slot as it can be contained in a rule,
with its modifiers.
Accepted modifiers:
- leading-space: bool
- casegen: bool
- randgen: str
- percentgen: int
- arg: str
- variation-name: str
- slot-val: str (to define later)
"""
def __init__(self, name, leading_space=False, variation_name=None, arg_value=None,
casegen=False, randgen=None, percentage_gen=50, parser=None):
super(SlotRuleContent, self).__init__(name, leading_space=leading_space,
variation_name=variation_name,
arg_value=arg_value, casegen=casegen,
randgen=randgen, percentage_gen=percentage_gen,
parser=parser)
self.casegen_checked = False
def can_have_casegen(self):
return self.parser.get_definition(self.name, UnitType.slot) \
.can_have_casegen()
def check_casegen(self):
"""Checks that casegen is applicable (at generation time)."""
if not self.casegen_checked and self.casegen:
if not self.can_have_casegen():
self.casegen = False
self.casegen_checked = True
def get_max_nb_generated_examples(self):
nb_possible_ex = self.parser.get_definition(self.name, UnitType.slot) \
.get_max_nb_generated_examples(self.variation_name)
if self.casegen:
nb_possible_ex *= 2
if self.randgen is not None:
nb_possible_ex += 1
return nb_possible_ex
def generate_random(self, generated_randgens=None):
if generated_randgens is None:
generated_randgens = dict()
self.check_casegen()
# Manage randgen
if self.randgen is not None and self.randgen in generated_randgens:
if generated_randgens[self.randgen]:
pass # Must be generated
else:
return Example() # Cannot be generated
elif self.randgen is not None:
if randint(0, 99) >= self.percentgen:
# Don't generated this randgen
if self.randgen != "":
generated_randgens[self.randgen] = False
return Example()
elif self.randgen != "":
# Generate this randgen
generated_randgens[self.randgen] = True
generated_example = self.parser.get_definition(self.name, UnitType.slot) \
.generate_random(self.variation_name, self.arg_value)
if self.casegen:
generated_example.text = randomly_change_case(generated_example.text)
if self.leading_space and may_get_leading_space(generated_example.text):
generated_example.text = ' ' + generated_example.text
return generated_example
def generate_all(self):
self.check_casegen()
generated_examples = []
if self.randgen is not None:
generated_examples.append(Example())
slots = self.parser.get_definition(self.name, UnitType.slot) \
.generate_all(self.variation_name, self.arg_value)
generated_examples.extend(slots)
if self.leading_space:
for (i, ex) in enumerate(generated_examples):
if may_get_leading_space(ex.text):
generated_examples[i].text = ' ' + ex.text
if self.casegen:
tmp_buffer = []
for ex in generated_examples:
if may_change_leading_case(ex.text):
tmp_buffer.append(Example(with_leading_lower(ex.text), ex.entities))
tmp_buffer.append(Example(with_leading_upper(ex.text), ex.entities))
else:
tmp_buffer.append(ex)
generated_examples = tmp_buffer
return generated_examples
def as_string(self):
"""
Returns the representation of the rule
as it would be written in a template file.
"""
result = add_escapement_back_in_unit_ref(self.name)
if self.casegen:
result = '&'+result
if self.variation_name is not None:
result += '#'+self.variation_name
if self.randgen is not None:
result += '?'+str(self.randgen)
if self.percentgen != 50:
result += '/'+str(self.percentgen)
if self.arg_value is not None:
result += '$'+self.arg_value
result = "@[" + result + ']'
if self.leading_space:
result = ' '+result
return result
class DummySlotValRuleContent(RuleContent):
"""
This class is supposed to be the first rule inside a list of rules that has
a slot value. It won't generate anything ever.
`self.name` and `self.slot_value` map to the slot value it represents.
"""
def __init__(self, name, next_token):
# (str, RuleContent) -> ()
super(DummySlotValRuleContent, self).__init__(name)
self.name = remove_escapement(name)
self.slot_value = self.name
self.real_first_token = next_token
def can_have_casegen(self):
return self.real_first_token.can_have_casegen()
def generate_random(self, generated_randgens=None):
return Example()
def generate_all(self):
return [Example()]
def print_DBG(self, nb_indent=0):
indentation = nb_indent * '\t'
print(indentation + "Slot val: " + self.name)
def as_string(self):
return ""
| true |
00545c1b131034dcece76ce13e9d8f7ed4b59e63 | Python | tom-frantz/chesslet | /chesslet/player.py | UTF-8 | 1,554 | 3.34375 | 3 | [] | no_license | # chesslet/player.py
class InvalidPasswordException(Exception):
pass
class AlreadyLoggedInException(Exception):
pass
class PlayerNotLoggedIn(Exception):
pass
class Player:
def __init__(
self,
uuid,
password,
account_name,
highscore=0,
score=0,
logged_in=False
):
self.uuid = uuid # (Universally Unique Identifier)
self.password = password # NOTE: THIS WILL BE INSECURE. DO NOT USE A PROPER PASSWORD.
self.account_name = account_name
self.score = score
self.highscore = highscore
self.logged_in = logged_in
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return str(self.__dict__)
# Logs a user in
# Checks that the password inputed is the same as what is saved in the object.
# If it is the same, set logged in true and return.
# otherwise, raise invalid password exception.
def login(self, password):
self.logged_in = self.password == password
if not self.logged_in:
raise InvalidPasswordException("Invalid Password")
return self.logged_in # True
# Logs a user outside
# If a user is logged in, set self.logged_in to false, and return.
# Else, raise PlayerNotLoggedIn exception.
def logout(self):
if self.logged_in:
self.logged_in = False
return True
if not self.logged_in:
raise PlayerNotLoggedIn
| true |
5ff040107357dbb848198d127eb6af7f1dc7c77a | Python | text-master/textmaster | /clf/model_saver.py | UTF-8 | 1,383 | 2.640625 | 3 | [] | no_license | import random
import time
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import csv
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
def get_topic_list(topic_name):
with open('validated_csv/' + topic_name + '.csv', 'rb') as f:
reader = csv.reader(f)
return [tuple(row) for row in reader]
def get_full_list(topics):
full_list = []
for topic in topics:
topic_list = get_topic_list(topic)
full_list += topic_list
return full_list
def split_train_test(full_list, ratio):
sample = random.sample(full_list, len(full_list))
X = [sent[0] for sent in sample]
y = [sent[1] for sent in sample]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ratio)
return X_train, y_train, X_test, y_test
topics = ['business', 'culture', 'society', 'sport', 'tech']
full_list = get_full_list(topics)
list_len = len(full_list)
(X_train, y_train, X_test, y_test) = split_train_test(full_list, 0.3)
vectorizer = TfidfVectorizer(max_df=0.3, stop_words='english')
X_train = vectorizer.fit_transform(X_train)
X_test = vectorizer.transform(X_test)
joblib.dump(vectorizer, 'model_dump/vectorizer.pk')
clf = MultinomialNB(alpha=.01)
clf.fit(X_train, y_train)
joblib.dump(clf, 'model_dump/finalized_model.sav')
| true |
bcbb0d0b29cceb830ffa0b5ebea159f083a4af7a | Python | l-iberty/machine_learning | /VAE-PyTorch/main.py | UTF-8 | 4,512 | 2.59375 | 3 | [] | no_license | import os
import torch
import torchvision
from torch.utils.data import DataLoader
from model import VAE
import numpy as np
import matplotlib.pyplot as plt
np.set_printoptions(threshold=np.inf)
train_data = torchvision.datasets.MNIST(
"mnist", train=True, transform=torchvision.transforms.ToTensor(), download=False)
test_data = torchvision.datasets.MNIST(
"mnist", train=False, transform=torchvision.transforms.ToTensor(), download=False)
print("size of train_data: ", train_data.train_data.size())
print("size of test_data: ", test_data.test_data.size())
net_arch = {
"n_hidden_encoder1": 500,
"n_hidden_encoder2": 500,
"n_hidden_decoder1": 500,
"n_hidden_decoder2": 500,
"n_z": 20,
"n_input": 784, # 28 * 28
}
lr = 0.001
batch_size = 100
device = "cpu"
model_save_path = "model_cpu.pt"
model_2d_save_path = "model_2d_cpu.pt"
gen_images_path="gen_images.pt"
vae_model = VAE(net_arch, lr, batch_size, device)
print(vae_model)
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True)
if not os.path.exists(model_save_path):
vae_model.train()
n_epoch = 50
for epoch in range(n_epoch):
total_loss = 0.0
count = 0
for imgs, labels in train_loader:
imgs = imgs.squeeze() # [100,28,28]
imgs = imgs.reshape(imgs.shape[0], -1) # [100, 784]
loss = vae_model.train_step(imgs.to(device))
count += 1
total_loss += loss
print(f"epoch {epoch + 1} loss {total_loss / count}")
torch.save(vae_model.state_dict(), model_save_path)
print(f"vae_model saved in {model_save_path}")
else:
print(f"load vae_model {model_save_path}")
vae_model.load_state_dict(torch.load(model_save_path))
x, test_labels = next(iter(test_loader))
x = x.squeeze()
x = x.reshape(x.shape[0], -1)
x_reconstr = vae_model.reconstruct(x.to(device))
x = x.numpy()
x_reconstr = x_reconstr.cpu().detach().numpy()
""" check reconstruction
"""
plt.figure(figsize=(6, 10))
rows, cols = 5, 2
for i in range(rows):
plt.subplot(rows, cols, 2 * i + 1)
plt.imshow(x[i].reshape(28, 28), vmin=0, vmax=1, cmap="Greys_r")
plt.title("test input")
plt.colorbar()
plt.subplot(rows, cols, 2 * i + 2)
plt.imshow(x_reconstr[i].reshape(28, 28), vmin=0, vmax=1, cmap="Greys_r")
plt.title("reconstruct")
plt.colorbar()
plt.tight_layout()
plt.show()
""" check generation
"""
vae_model.eval()
noise = torch.randn(batch_size, net_arch["n_z"], device=device)
images = vae_model.generate(noise).cpu().detach()
torch.save(images, gen_images_path)
print(f"{gen_images_path} saved")
""" check latent space, in order to do that, we need to train another VAE model with n_z=2
"""
net_arch["n_z"] = 2
vae_model_2d = VAE(net_arch, lr, batch_size, device)
print(vae_model_2d)
if not os.path.exists(model_2d_save_path):
vae_model_2d.train()
n_epoch = 50
for epoch in range(n_epoch):
total_loss = 0.0
count = 0
for imgs, labels in train_loader:
imgs = imgs.squeeze() # [100,28,28]
imgs = imgs.reshape(imgs.shape[0], -1) # [100, 784]
loss = vae_model_2d.train_step(imgs.to(device))
count += 1
total_loss += loss
print(f"epoch {epoch + 1} loss {total_loss / count}")
torch.save(vae_model_2d.state_dict(), model_2d_save_path)
print(f"vae_model saved in {model_2d_save_path}")
else:
print(f"load vae_model {model_2d_save_path}")
vae_model_2d.load_state_dict(torch.load(model_2d_save_path))
nx = ny = 20
x_values = np.linspace(-3, 3, nx)
y_values = np.linspace(-3, 3, nx)
plt.figure(figsize=(8, 10))
canvas = np.zeros(shape=(28 * nx, 28 * ny))
for i, xi in enumerate(x_values):
for j, yj in enumerate(y_values):
z_mu = np.array([[xi, yj]] * batch_size, dtype=np.float32)
x_mean = vae_model_2d.generate(torch.from_numpy(z_mu).to(device)).cpu().detach().numpy()
canvas[i * 28:(i + 1) * 28, j * 28:(j + 1) * 28] = x_mean[0].reshape(28, 28)
plt.imshow(canvas, origin="upper", cmap="Greys_r")
plt.tight_layout()
plt.show()
test_loader = DataLoader(test_data, batch_size=5000, shuffle=True)
x, test_labels = next(iter(test_loader))
x = x.squeeze()
x = x.reshape(x.shape[0], -1)
z_mu = vae_model_2d.transform(x.to(device))
z_mu = z_mu.cpu().detach().numpy()
plt.scatter(x=z_mu[:, 0], y=z_mu[:, 1], c=test_labels.numpy())
plt.colorbar()
plt.grid()
plt.show()
| true |
7bcfee0f33d2ce389920ebeb6b8e3c507e9bc9c5 | Python | olekstomek/mcod-backend-dane.gov.pl | /mcod/lib/validators.py | UTF-8 | 1,893 | 2.65625 | 3 | [] | no_license | import json
import falcon
class RequestValidator(object):
__parsers__ = {
'json': 'parse_json',
'querystring': 'parse_querystring',
'query': 'parse_querystring',
'form': 'parse_form',
'headers': 'parse_headers',
'cookies': 'parse_cookies',
'files': 'parse_files',
}
def __init__(self, form_class, locations, request, **kwargs):
data = self.prepare_data(locations, request)
self.form = form_class(data=data, **kwargs)
def prepare_data(self, locations, req):
data = {}
for location in locations:
func = getattr(self, self.__parsers__.get(location))
data.update(func(req))
return data
def validate(self):
self.form.is_valid()
return self.form.cleaned_data, self.form.errors
def parse_json(self, req):
if req.content_length in (None, 0):
return {}
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
data = json.loads(body.decode('utf-8'))
return data
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')
def parse_querystring(self, req):
return req.params
def parse_form(self, req):
raise NotImplementedError()
def parse_headers(self, req):
return req.headers
def parse_cookies(self, req):
return req.cookies
def parse_files(self, req):
raise NotImplementedError()
| true |
b6010b150a77287b2a7983609b87006f010a1b3b | Python | jiafulow/emtf-nnet | /emtf_nnet/sparse/indexed_slices_value.py | UTF-8 | 4,250 | 2.828125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # The following source code was originally obtained from:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/indexed_slices.py
# ==============================================================================
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Value for IndexedSlices."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
class IndexedSlicesValue(object):
"""Represents the value of an `IndexedSlices`.
See `tf.IndexedSlices` API for descriptions.
Example:
>>> IndexedSlicesValue(indices=np.array([0, 2, 4]),
... values=np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]]),
... dense_shape=np.array([6, 4]))
IndexedSlicesValue(indices=array([0, 2, 4]), values=array([[ 1, 2, 3, 4],
[-1, -2, -3, -4],
[ 5, 6, 7, 8]]), dense_shape=array([6, 4]))
"""
def __init__(self, indices, values, dense_shape):
"""Creates an `IndexedSlices`.
Args:
indices: A 1-D integer Tensor with shape [D0].
values: A Tensor of any dtype with shape [D0, D1, ..., Dn].
dense_shape: A 1-D int64 tensor of shape [ndims], e.g. [LARGE0, D1, .. , DN] where LARGE0 >> D0
"""
if not (isinstance(indices, (np.ndarray, np.generic)) and
indices.dtype in (np.int64, np.int32) and indices.ndim == 1):
raise TypeError("indices must be a 1D int32 or int64 numpy array")
if not (isinstance(values, (np.ndarray, np.generic)) and values.ndim >= 1):
raise TypeError("values must be a n-D numpy array")
if not (isinstance(dense_shape, (np.ndarray, np.generic)) and
dense_shape.dtype in (np.int64, np.int32) and dense_shape.ndim == 1):
raise TypeError("dense_shape must be a 1D int32 or int64 numpy array")
self._indices = indices
self._values = values
self._dense_shape = dense_shape
indices = property(
lambda self: self._indices,
doc="""The indices of the tensor slices.""")
values = property(
lambda self: self._values,
doc="""The values of the tensor slices.""")
dtype = property(
lambda self: self._values.dtype,
doc="""The numpy dtype of values in this tensor.""")
dense_shape = property(
lambda self: tuple(self._dense_shape),
doc="""A tuple representing the shape of the dense tensor.""")
shape = property(
lambda self: tuple(self._dense_shape),
doc="""A tuple representing the shape of the dense tensor.""")
def __str__(self):
return "IndexedSlicesValue(indices=%s, values=%s, dense_shape=%s)" % (
self._indices, self._values, self._dense_shape)
def __repr__(self):
return "IndexedSlicesValue(indices=%r, values=%r, dense_shape=%r)" % (
self._indices, self._values, self._dense_shape)
def with_values(self, new_values):
"""Returns a copy of `self` with `values` replaced by `new_values`."""
return IndexedSlicesValue(self._indices, new_values, self._dense_shape)
IndexedSlicesNamedTuple = collections.namedtuple(
'IndexedSlicesNamedTuple', ['indices', 'values', 'dense_shape'])
def dense_to_indexed_slices(dense, indices):
dense = np.asarray(dense)
indices = np.asarray(indices)
values = dense[indices]
dense_shape = np.asarray(dense.shape)
return IndexedSlicesValue(indices=indices, values=values, dense_shape=dense_shape)
def indexed_slices_to_dense(indexed):
dense = np.zeros(indexed.dense_shape, dtype=indexed.dtype)
dense[indexed.indices] = indexed.values
return dense
| true |
b3d98203d15b30a2bda8338765a29fce1e00b9b6 | Python | gabriellaec/desoft-analise-exercicios | /backup/user_148/ch127_2020_04_01_16_38_55_817376.py | UTF-8 | 90 | 2.65625 | 3 | [] | no_license | import math
def calcula_elongacao(A, k0, w, t):
x = A*(math.cos(k0+w*t))
return x | true |
9c241670b30c669c6c75323d6f3a4fa10be39a41 | Python | JulyKikuAkita/PythonPrac | /cs15211/EscapeTheGhosts.py | UTF-8 | 2,795 | 3.796875 | 4 | [
"Apache-2.0"
] | permissive | __source__ = 'https://leetcode.com/problems/escape-the-ghosts/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 789. Escape The Ghosts
#
# You are playing a simplified Pacman game. You start at the point (0, 0),
# and your destination is (target[0], target[1]). There are several ghosts on the map,
# the i-th ghost starts at (ghosts[i][0], ghosts[i][1]).
#
# Each turn, you and all ghosts simultaneously *may* move in one of 4 cardinal directions:
# north, east, west, or south, going from the previous point to a new point 1 unit of distance away.
#
# You escape if and only if you can reach the target before any ghost reaches you
# (for any given moves the ghosts may take.)
# If you reach any square (including the target) at the same time as a ghost,
# it doesn't count as an escape.
#
# Return True if and only if it is possible to escape.
#
# Example 1:
# Input:
# ghosts = [[1, 0], [0, 3]]
# target = [0, 1]
# Output: true
# Explanation:
# You can directly reach the destination (0, 1) at time 1,
# while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you.
# Example 2:
# Input:
# ghosts = [[1, 0]]
# target = [2, 0]
# Output: false
# Explanation:
# You need to reach the destination (2, 0),
# but the ghost at (1, 0) lies between you and the destination.
# Example 3:
# Input:
# ghosts = [[2, 0]]
# target = [1, 0]
# Output: false
# Explanation:
# The ghost can reach the target at the same time as you.
# Note:
#
# All points have coordinates with absolute value <= 10000.
# The number of ghosts will not exceed 100.
#
import unittest
# 24ms 65.55%
class Solution(object):
def escapeGhosts(self, ghosts, target):
"""
:type ghosts: List[List[int]]
:type target: List[int]
:rtype: bool
"""
def taxi(P, Q):
return abs(P[0] - Q[0]) + abs(P[1] - Q[1])
return all(taxi([0, 0], target) < taxi(ghost, target)
for ghost in ghosts)
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought: https://leetcode.com/problems/escape-the-ghosts/solution/
Approach #1: Taxicab Distance [Accepted]
Complexity Analysis
Time Complexity: O(ghosts.length).
Space Complexity: O(1)
Triangle inequality : all parties just go directly to the target in the shortest time possible
# 3ms 99.22%
class Solution {
public boolean escapeGhosts(int[][] ghosts, int[] target) {
int[] source = new int[]{0, 0};
for (int[] ghost: ghosts)
if (taxi(ghost, target) <= taxi(source, target))
return false;
return true;
}
public int taxi(int[] P, int[] Q) {
return Math.abs(P[0] - Q[0]) + Math.abs(P[1] - Q[1]);
}
}
''' | true |
de2f36c719af40f30acd0766a95de21701fc03d0 | Python | AGarrow/blank_anthropod | /anthropod/scripts/contacts_migrate_to_object.py | UTF-8 | 570 | 2.53125 | 3 | [] | no_license | '''Migrate contact info from a list of 3-tuples to objects.
'''
from anthropod.core import db
def migrate_contacts(thing):
contacts = thing['contact_details']
fieldnames = ('type', 'value', 'note')
contacts = [dict(zip(fieldnames, tpl)) for tpl in contacts]
thing['contact_details'] = contacts
return thing
for obj in db.people.find():
db.people.save(migrate_contacts(obj))
for obj in db.organizations.find():
db.organizations.save(migrate_contacts(obj))
for obj in db.memberships.find():
db.memberships.save(migrate_contacts(obj))
| true |
8d445b5c2c9416d9fe9f934bd266344ed3ce24f1 | Python | ncollins/lis.py | /test_eval.py | UTF-8 | 2,737 | 2.984375 | 3 | [] | no_license |
from lex import tokenize
from parse import parse_tokens
from evaluate import eval_in_env, Environment
def test_eval_add_const():
exp = ['+', 3, 4]
res = eval_in_env(exp, Environment([]))
assert res == 7
def test_eval_if():
exp = ['if', True, 3, 4]
assert eval_in_env(exp, Environment([])) == 3
def test_eval_cond_true():
exp = ['cond', [['>', 4, 3], 1], ['else', 0]]
assert eval_in_env(exp, Environment([])) == 1
def test_eval_cond_false():
exp = ['cond', [['>', 4, 4], 1], ['else', 0]]
assert eval_in_env(exp, Environment([])) == 0
def test_eval_let():
exp = ['let', [['x', 3], ['y', 10]], ['+', 'x', 'y']]
assert eval_in_env(exp, Environment([])) == 13
def test_eval_define():
env = Environment([])
exp = ['define', 'a', 3]
eval_in_env(exp, env)
#assert env._env == [['a', 3]]
assert env.lookup('a') == 3
def test_eval_closure():
env = Environment([['add3', ['closure', ['lambda', ['x'], ['+', 'x', 3]], []]]])
exp = ['add3', 10]
assert eval_in_env(exp, env) == 13
def test_eval_closure_2():
env = Environment([['ifthen', ['closure', ['lambda', ['x'], ['if', True, 'x', 3]], []]]])
exp = ['ifthen', 10]
assert eval_in_env(exp, env) == 10
def test_eval_recursion():
env = Environment([['sumto', ['closure', ['lambda', ['n'],
['if', ['<', 'n', 1],
0,
['+', 'n', ['sumto', ['-', 'n', 1]]]]],
[]]]])
exp = ['sumto', 3]
assert eval_in_env(exp, env) == 6
def test_eval_recursion_2():
env = Environment([['factorial', ['closure', ['lambda', ['n'],
['if', ['<', 'n', 1], 1, ['*', 'n', ['factorial', ['-', 'n', 1]]]]], []]]])
exp = ['factorial', 5]
assert eval_in_env(exp, env) == 120
def test_eval_anon():
exp = [['lambda', ['x'], ['+', 'x', 'x']], 7]
assert eval_in_env(exp, Environment([])) == 14
def test_eval_set():
env = Environment([['a', 0]])
exp = ['set!', 'a', 10]
eval_in_env(exp, env)
assert env.lookup('a') == 10
def test_eval_begin():
exp = ['begin', ['define', 'a', 0], ['set!', 'a', 10], 'a']
assert eval_in_env(exp, Environment([])) == 10
def test_eval_modulo():
assert 0 == eval_in_env(['modulo', 9, 3], Environment([]))
assert 1 == eval_in_env(['modulo', 10, 3], Environment([]))
assert 2 == eval_in_env(['modulo', 11, 3], Environment([]))
def test_eval_not():
assert True == eval_in_env(['not', False], Environment([]))
assert False == eval_in_env(['not', True], Environment([]))
assert False == eval_in_env(['not', 'null'], Environment([]))
| true |
7257775d1582f5e39d4db78a0f446f728d9a5da7 | Python | bkrive19/cl-starter | /Tera.py | UTF-8 | 8,570 | 3.78125 | 4 | [] | no_license | def clear():
from os import system, name
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
clear()
print("In this story- you can't choose where you were born. You can't choose how you were born.")
print("Here... you are a Teragate. A race that is in a far, unreachable location.")
print ("In a dimension filled with organic materials that your race can eat. You being born from a mother tree just like everyone else. Your race has been living in boredom for centuries.")
print('But then one day...')
print("A rip was revealed in your world. This rip is something that'll change your race's way of living FOREVER.")
print("You see Teragates gathering around this dimensional rip...")
killpoint= 0
def badend():
print(" ")
print("You've killed everyone in your way...")
print("You're very stong now. Everyone fears you...no one was able to stop you...")
print("From now on, the world will never be the same.")
from pyfiglet import Figlet
fig = Figlet(font='graffiti')
banner = fig.renderText("Fear The New Me")
print(banner)
def mixend():
print(" ")
print("You've spared and killed...")
print("Managing to survive and become stong. To you, some people need to be killed in order for you to be alive...")
from pyfiglet import Figlet
fig = Figlet(font='graffiti')
banner = fig.renderText("MIX end")
print(banner)
def goodend():
print(" ")
print("You've spared the life of those with feelings for others. Even if it means killing your kind, you still saved others for doing so...")
print("You will be the one who will bring peace towards this dimension...")
from pyfiglet import Figlet
fig = Figlet(font='graffiti')
banner = fig.renderText("GOOD end")
print(banner)
def end():
global killpoint
if killpoint == 7:
badend()
else:
pass
if killpoint > 7:
mixend()
else:
pass
if killpoint == 0:
goodend()
else:
pass
def k4():
global killpoint
print(" ")
print("The Teragate looks really mad that you took the child, so he runs off- but you hear more screaming, so you followed the screaming")
print("You manage to reach the Teragates prey. They are all little kids. You and the Teragate are staring at eachothers eyes- he looks as strong as you.")
answer =input ("Will you kill and eat the kids for yourself, or will you save them and kill the Teragate? Who will you kill- the kids or the teragate? ")
if answer =="kids":
print("You consumed all of them- very quick. Your body reinforeces its self. You've grown stronger. You decide to kill the Teragate as well")
print("His shock and fear taste just as good as the kids!")
killpoint+=4
print(killpoint)
end()
pass
elif answer =="teragate":
print("You have a brawl with him. You took three blows- you returned the punches. You're leaking red liquid- so is the Teragate...")
print("Finally- your so close to dying, but you killed one of your kind to save the kids. You realized that they all ran off while you were fighting...")
end()
pass
else:
print("teragate, or the kids?!")
k4()
def k3():
global killpoint
print(" ")
print("You hear a child's voice screaming for help- you start to run towards it while avoiding the main public path.")
print("There is a little boy running from another Teragate- He's running towards your direction.")
answer = input (" Will you kill him or will you help him? kill, or help?")
if answer =="kill":
print("You killed the little thing- his screams and fear taste so good! You feel very strong.")
killpoint+=1
print(killpoint)
k4()
elif answer == "help":
print ("You grabbed him- he is scared, so you pet him. The Tearagate looks really mad, so you ran off to bring the child to a safe publical place.")
k4()
else:
print("kill or help? What are you going to do to him?")
k3()
def k2():
global killpoint
print(" ")
print("You move on. You're now exploring in the forest. You see another person, but they see you! They are scared- will you eat her, or spare her?")
answer = input ("Kill, or spare?")
if answer =="kill":
print("You killed her. She's screaming in fear. It tastes so good- you gained some short claws. Later you hear a child calling for help")
killpoint+=1
print(killpoint)
k3()
elif answer == "spare":
print ("You show a gesture of mercy. She is very suprised that you have some emotion. She takes a picture and some notes, but she heard someone calling her name for help- she runs off.")
k3()
else:
print("kill or spare!")
k2()
def k1():
global killpoint
print(" ")
print ("You see an animal, but it looks smart- if not maybe as smart as you.")
print ("You realize eating from a new dimension makes you stronger. The person doesn't see you...")
answer = input ("Do you want to kill him??? Kill or don't kill? ")
if answer =="kill":
print("You killed the person. You can see it's pain and fear- it taste good. You gained some teeth.")
killpoint+=1
print(killpoint)
k2()
elif answer == "don't kill":
print ("You spared the being. You just spectated it- he's picking up a little girl from a cabin. You feel like you made a right choice.")
k2()
else:
print("kill or don't kill!")
k1()
def firstbite():
print(" ")
print("Finally after years of boredom- your free! Your in a black place..")
print ("You see light. You walk towards it, but for some reason you feel lighter in mass.")
print("Your out! There's a lot of organic material- like in your world, but green and delicate, more alive. You realize that your're a ghost..")
print(" ")
answer = input ("You see a slow animal and a berry bush. Will you perfer a plant, or an easy meat meal?")
if answer == "meat":
print ("You ate the animal alive. You start to gain mass- your ghost forms a skeleton and fresh flesh for your new body!")
k1()
elif answer == "plant":
print("You ate the berries. Your ghost forms a skeleton and some fresh flesh around your hip and head.")
k1()
else:
print("plant, or meat. Eat, so you can materialize!")
firstbite()
def rip():
print(" ")
print("Every one is just celebrating! You see some Teragates fall in the rip, and some jump in and out, but they seem tranparent now...")
answer = input ("You really want to see what's beyond the rip. go, or stay?")
if answer == "stay":
end1()
elif answer == "go":
firstbite()
else:
print("go or stay?")
rip()
def birthplace():
print(" ")
print("You went back to the tree. The tree that gives birth to your race. You're the fruit of the tree. The only one now...")
print("You waited there for an hour. Waiting for something to happen. Then....")
print(" ")
print("The tree speaks! Saying in a soft accent,- YOU ARE THE ONLY CHILD I HAVE WHO CARED TO COME AND VISIT ME BEFORE LEAVING.")
print("I'M GLAD YOU KNOW WHO GAVE BIRTH TO YOU. SEAL THE RIP AND COME AND EAT WITH ME...")
from pyfiglet import Figlet
fig = Figlet(font='graffiti')
banner = fig.renderText("SECRET end")
print(banner)
def end1():
print(" ")
print("You went back to go eat. After a couple of hours you noticed that everyone was gone... You realize your alone.")
wait()
def wait():
answer = input ("Will you wait for them, or do you want to check out your mother tree? Check, or wait?")
if answer == "check":
print("You went to go check the tree that gae birth to you.")
birthplace()
elif answer == "wait":
print("You waited a day later. No one came.")
wait()
else:
print ("check or wait?")
wait()
def gotorip():
answer=input("Will you follow them? yes or no?")
if answer == "yes":
print("You Went to see what's up.")
rip()
elif answer =="no":
print("You ignored the excitement.")
end1()
else:
print("yes or no?")
gotorip()
gotorip()
| true |
409ba4b750be06250235bf656b68eb27a1d6d80a | Python | u2386/leet | /6-ZigZag Conversion/solution.py | UTF-8 | 565 | 3.453125 | 3 | [] | no_license | # coding: utf-8
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) < numRows or numRows == 1:
return s
pat = ['' for _ in range(len(s))]
x, d = 0, 1
for c in s:
pat[x] += c
x += d
if x == numRows - 1 or x == 0:
d *= -1
return ''.join(pat)
def main():
print(Solution().convert('LEETCODEISHIRING', 3))
if __name__ == '__main__':
main()
| true |
6f521329035b9dff09b1ed425d1a0919108acba3 | Python | moonrollersoft/subtitles | /src/series_parser.py | UTF-8 | 546 | 3.1875 | 3 | [
"MIT"
] | permissive | import re
SERIES_SEPARATOR_GROUP_REGEX = '( ?[eE]| ?[xX])'
SERIES_GROUPS_REGEX = r'([0-9]+){}([0-9]+)'.format(SERIES_SEPARATOR_GROUP_REGEX)
class SeriesFilenameParser:
def __init__(self, filename):
pattern = re.compile(SERIES_GROUPS_REGEX)
matched_pattern = pattern.search(filename)
self._season = matched_pattern.group(1)
self._episode = matched_pattern.group(3)
@property
def season(self):
return int(self._season)
@property
def episode(self):
return int(self._episode)
| true |
8a583f173cbd0fef0e7b56218608702f2f7f0172 | Python | mvilchis/aprendizaje_proyecto | /adaBoostClassifier.py | UTF-8 | 310 | 2.5625 | 3 | [] | no_license | from sklearn.ensemble import *
from sklearn.metrics import accuracy_score
# Ensemble algorithms used
model_adaBoost = AdaBoostClassifier(n_estimators=100)
model_adaBoost.fit(x_train, y_train)
predictions_ada = model_adaBoost.predict(x_test)
print(accuracy_score(y_test, predictions_ada))
# 30% de accuracy
| true |
b876de9f50db039afa9a8c0cd3e57c189d6280c0 | Python | rubenglezant/ORDENADOS | /FINAL2/GetInfoCRM/getDataWeb.py | UTF-8 | 2,606 | 2.96875 | 3 | [] | no_license | #!/usr/bin/python
# Obtiene los datos de la Web
import urllib2
import base64
import json
def GetAtributoEspecial(idOportunidad, nombreAtributo):
# Obtenemos los atributos especiales
username = '2d486e42771eee18125b8aef3afe216d'
password = '4c2TNRdi'
req = urllib2.Request('https://infeci.capsulecrm.com/api/opportunity/'+idOportunidad+'/customfields')
base64string = base64.b64encode('%s:%s' % (username, password))
req.add_header("Authorization", "Basic %s" % base64string)
req.add_header("Accept", "application/json")
response = urllib2.urlopen(req)
data = json.load(response)
try:
for value in data['customFields']['customField']:
if (value['label']==nombreAtributo):
s = value['number']
break
else:
s = ""
except:
s = ""
return s
# Construimos el Array de Clientes
username = '2d486e42771eee18125b8aef3afe216d'
password = '4c2TNRdi'
req = urllib2.Request('https://infeci.capsulecrm.com/api/party')
base64string = base64.b64encode('%s:%s' % (username, password))
req.add_header("Authorization", "Basic %s" % base64string)
req.add_header("Accept", "application/json")
response = urllib2.urlopen(req)
data = json.load(response)
clientes = {}
for op in data['parties']['organisation']:
clientes[op['id']] = op['name']
# Recogemos el conjunto de oportunidades
username = '2d486e42771eee18125b8aef3afe216d'
password = '4c2TNRdi'
req = urllib2.Request('https://infeci.capsulecrm.com/api/opportunity')
base64string = base64.b64encode('%s:%s' % (username, password))
req.add_header("Authorization", "Basic %s" % base64string)
req.add_header("Accept", "application/json")
response = urllib2.urlopen(req)
data = json.load(response)
# Creamos el CSV con las oportunidades
atributos = ['name','probability','expectedCloseDate','createdOn','updatedOn','value','currency','partyId','milestoneId','milestone','owner','id','durationBasis']
s = ""
s = s + "Cliente" + ","
for atr in atributos:
s = s + atr + ","
s = s + "Margen" + ","
s = s + "Grafo" + ","
s = s + "\n"
for op in data['opportunities']['opportunity']:
s = s + clientes[str(op['partyId'])] + ","
for atr in atributos:
try:
s = s + op[atr] + ","
except:
s = s + "" + ","
s = s + (GetAtributoEspecial(op['id'],'Margen')) + ","
s = s + (GetAtributoEspecial(op['id'],'Grafo')) + ","
s = s + "\n"
# Ajustamos para crear el CSV
s = s.replace(",","|")
s = s.replace(".",",")
print (s.encode("utf8"))
text_file = open("oportunidades.csv", "w")
text_file.write(s.encode("utf8"))
text_file.close()
| true |
2fc35c39c629ba365fd15b2eb3a3fa19e169f708 | Python | carodewig/advent-of-code | /advent-py/2015/day_14.py | UTF-8 | 1,350 | 3.4375 | 3 | [] | no_license | """ day 14: reindeer olympics """
import re
from collections import defaultdict
import attr
@attr.s
class Reindeer:
name = attr.ib()
speed = attr.ib()
fly_duration = attr.ib()
rest_duration = attr.ib()
distance = attr.ib(init=False, default=0)
seconds_flown = attr.ib(init=False, default=0)
seconds_rested = attr.ib(init=False, default=0)
def fly(self):
distance = 0
while True:
for _ in range(self.fly_duration):
distance += self.speed
yield (self.name, distance)
for _ in range(self.rest_duration):
yield (self.name, distance)
PATTERN = r"([A-z]+) can fly ([0-9]+) km/s for ([0-9]+) seconds, but then must rest for ([0-9]+) seconds."
stable = []
with open("data/14.txt") as fh:
for line in fh:
if match := re.match(PATTERN, line):
name, speed, fly, rest = match.groups()
stable.append(Reindeer(name, int(speed), int(fly), int(rest)))
scores = defaultdict(int)
for seconds, distances in enumerate(zip(*[reindeer.fly() for reindeer in stable]), 1):
max_distance = max([x[1] for x in distances])
for (name, distance) in distances:
if distance == max_distance:
scores[name] += 1
if seconds == 2503:
print(max(scores.values()))
break
| true |
f0c8ab54dd61c02bf6d0027ff472e730b34475d0 | Python | mittagessen/kraken | /kraken/contrib/generate_scripts.py | UTF-8 | 1,125 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python3
"""
Script fetching the latest unicode Scripts.txt and dumping it as json.
"""
from urllib import request
import json
import regex
uri = 'http://www.unicode.org/Public/UNIDATA/Scripts.txt'
re = regex.compile(r'^(?P<start>[0-9A-F]{4,6})(..(?P<end>[0-9A-F]{4,6}))?\s+; (?P<name>[A-Za-z]+)')
with open('scripts.json', 'w') as fp, request.urlopen(uri) as req:
d = []
for line in req:
line = line.decode('utf-8')
if line.startswith('#') or line.strip() == '':
continue
m = re.match(line)
if m:
print(line)
start = int(m.group('start'), base=16)
end = start
if m.group('end'):
end = int(m.group('end'), base=16)
name = m.group('name')
if len(d) > 0 and d[-1][2] == name and (start - 1 == d[-1][1] or start - 1 == d[-1][0]):
print('merging {} and ({}, {}, {})'.format(d[-1], start, end, name))
d[-1] = (d[-1][0], end, name)
else:
d.append((start, end if end != start else None, name))
json.dump(d, fp)
| true |
ee99f365816dcaaed2fd14038874b72fa39e58f1 | Python | kinow/mint | /scripts/compute_trapezoidal_bilinear_flux.py | UTF-8 | 2,215 | 2.65625 | 3 | [
"0BSD"
] | permissive | import vtk
import argparse
import numpy
parser = argparse.ArgumentParser(description='Write line point data to file')
parser.add_argument('-p', type=str, default="(0., 0.),(1., 0.)",
help='Interlaced xy points')
parser.add_argument('-o', type=str, default="line.vtk",
help='Output file')
args = parser.parse_args()
xy = numpy.array(eval('[' + args.p + ']'))
npts = xy.shape[0]
ncells = npts - 1
xyz = numpy.zeros((npts, 3), numpy.float64)
xyz[:, 0] = xy[:, 0]
xyz[:, 1] = xy[:, 1]
pointData = vtk.vtkDoubleArray()
pointData.SetNumberOfComponents(3)
pointData.SetNumberOfTuples(npts)
pointData.SetVoidArray(xyz, 3*npts, 1)
points = vtk.vtkPoints()
points.SetNumberOfPoints(npts)
points.SetData(pointData)
grid = vtk.vtkUnstructuredGrid()
grid.SetPoints(points)
grid.Allocate(ncells, 1)
ptIds = vtk.vtkIdList()
ptIds.SetNumberOfIds(2)
for i in range(ncells):
ptIds.SetId(0, i)
ptIds.SetId(1, i + 1)
grid.InsertNextCell(vtk.VTK_LINE, ptIds)
cellLocator = vtk.vtkCellLocator()
cellLocator.SetDataSet(grid)
cellLocator.BuildLocator()
cell = vtk.vtkGenericCell()
subId = vtk.mutable(0)
pcoords = numpy.zeros((3,), numpy.float64)
weights = numpy.zeros((4,), numpy.float64)
tol2 = 1.e-12
twopi = 2*numpy.pi
ptIds = vtk.vtkIdList()
def vectorField(xy):
# find the cell and the pcoords
xyz = numpy.array([xy[0], xy[1], 0.])
cellId = cellLocator.FindCell(xyz, tol2, cell, pcoords, weights)
if cellId < 0: print 'ERROR cellId = ', cellId
grid.GetCellPoints(cellId, ptIds)
# interpolate the vector field at that position
vec = numpy.zeros((3,), numpy.float64)
vertex = numpy.zeros((3,), numpy.float64)
# iterate over the cell vertices
for i in range(ptIds.GetNumberOfIds()):
ptId = ptIds.GetId(i)
grid.GetPoint(ptId, vertex)
x, y, z = vertex
r2 = x**2 + y**2
v = numpy.array([x, y, 0.])/(twopi*r2)
vec += weights[i] * v
return vec
def integratedFlux(xy0, xy1):
xyMid = 0.5*(xy0 + xy1)
vec = vectorField(xyMid)
ds = numpy.array([xy1[1] - xy0[1], -(xy1[0] - xy0[0]), 0.0])
return numpy.dot(vec, ds)
flux = 0.0
for i in range(ncells):
xy0 = xy[i + 0, :]
xy1 = xy[i + 1, :]
flux += integratedFlux(xy0, xy1)
print 'flux = {:16.12f}'.format(flux)
| true |
9a8cc7686318e3e7e120bd3a51030b720c6bb418 | Python | aarontinn13/MPCS-52011 | /project9/commentstripper.py | UTF-8 | 2,855 | 2.875 | 3 | [] | no_license | def stripcomments(path):
with open(path, 'r') as r:
with open('nocomments.out', 'a+') as w:
flag = False
for i in r.readlines():
found = False
#remove all blank lines
if i == '\n' or i == '\t\n':
continue
#remove all white space from the line
new = ' '.join(i.split())
#initial parse to find comments
for j in range(0,len(new)-1):
#if we are still looking for the ending multiline comment
if flag:
if new[j] + new[j+1] == '*/':
flag = False
found = True
end = new.partition('*/')
if end[2] == '':
break
else:
w.write(end[2]+'\n')
break
#if we find multiline starter
elif new[j] + new[j+1] == '/*':
found = True
left = new.partition('/*')
#find if ending comment in the same line
if '*/' in left[2]:
#partition around the ending comment
right = left[2].partition('*/')
#combine the two none comments
combined = left[0]+right[2]
#if the whole line was a comment we skip to next line
if combined == '':
break
#write the non comment and skip to next line
else:
w.write(combined+'\n')
break
#if the ending comment is not on the same line, we need to keep a flag to indicate multiline comment
else:
flag = True
if left[0] == '':
break
else:
w.write(left[0]+'\n')
break
#if we find singleline starter
elif new[j] + new[j+1] == '//':
found = True
single = new.partition('//')
if single[0] == '':
break
else:
w.write(single[0]+'\n')
break
#if we find no comments in the string
if not found and not flag:
w.write(new+'\n') | true |
5be6a12a0a9d8575cf6324c1c31c026707f41933 | Python | chefe996/chatbot | /ruchatbot/bot/unittest_dummy_answering_machine.py | UTF-8 | 472 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import unittest
from dummy_answering_machine import DummyAnsweringMachine
class TestDummyAnsweringMachine(unittest.TestCase):
def setUp(self):
self.bot = DummyAnsweringMachine()
def test_echo(self):
input_phrase = u'входная фраза'
self.bot.push_phrase('test', input_phrase)
answer = self.bot.pop_phrase('test')
self.assertEqual(input_phrase, answer)
if __name__ == '__main__':
unittest.main()
| true |
0afa60580c1406cc9ca89cf696efa54002dcea9c | Python | zongdaoming/MDN | /Machine_Learning_Models/hmm.py | UTF-8 | 2,622 | 3.15625 | 3 | [] | no_license | import numpy as np
states = ('Healthy', 'Fever')
observations = ('normal', 'cold', 'dizzy')
start_probability = {'Healthy': 0.6, 'Fever': 0.4}
transition_probability = {
'Healthy': {'Healthy': 0.7, 'Fever': 0.3},
'Fever': {'Healthy': 0.4, 'Fever': 0.6},
}
emission_probability = {
'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},
'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6},
}
class HMM:
"""
Order 1 Hidden Markov Model
Attributes
----------
A : numpy.ndarray
State transition probability matrix
B: numpy.ndarray
Output emission probability matrix with shape(N, number of output types)
pi: numpy.ndarray
Initial state probablity vector
"""
def __init__(self, A, B, pi):
self.A = A
self.B = B
self.pi = pi
def generate_index_map(lables):
index_label = {}
label_index = {}
i = 0
for l in lables:
index_label[i] = l
label_index[l] = i
i += 1
return label_index, index_label
states_label_index, states_index_label = generate_index_map(states)
observations_label_index, observations_index_label = generate_index_map(observations)
def convert_observations_to_index(observations, label_index):
list = []
for o in observations:
list.append(label_index[o])
return list
def convert_map_to_vector(map, label_index):
v = np.empty(len(map), dtype=float)
for e in map:
v[label_index[e]] = map[e]
return v
def convert_map_to_matrix(map, label_index1, label_index2):
m = np.empty((len(label_index1), len(label_index2)), dtype=float)
for line in map:
for col in map[line]:
m[label_index1[line]][label_index2[col]] = map[line][col]
return m
A = convert_map_to_matrix(transition_probability, states_label_index, states_label_index)
print (A)
B = convert_map_to_matrix(emission_probability, states_label_index, observations_label_index)
print(B)
observations_index = convert_observations_to_index(observations, observations_label_index)
pi = convert_map_to_vector(start_probability, states_label_index)
print(pi)
hmm = HMM(A, B, pi)
def simulate(self, T):
def draw_from(probs):
return np.where(np.random.multinomial(1, probs) == 1)[0][0]
observations = np.zeros(T, dtype=int)
states = np.zeros(T, dtype=int)
states[0] = draw_from(self.pi)
observations[0] = draw_from(self.B[states[0], :])
for t in range(1, T):
states[t] = draw_from(self.A[states[t - 1], :])
observations[t] = draw_from(self.B[states[t], :])
return observations, states | true |
4f9e819867ae5b1d8d144f41ee0e978a1eadc19f | Python | JunaidRana/MLStuff | /Boruta/KNN_Boruta.py | UTF-8 | 701 | 2.828125 | 3 | [] | no_license | import pandas as pd
import numpy as np
#This dataset is organised by feature importance.
df = pd.read_csv('normcleve_knn.csv')
df1 = df
array = df1.values
#We already know the feature importance and ranking through Boruta files.
#Here we are taking only two columns and our accuracy rate is still 96.7 %
X = array[:,0:2]
y = array[:,14]
y = y.astype(int)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=21)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print (y_pred)
print (knn.score(X_test, y_test))
| true |
e090229ec5ac01f07fece9baa2789a77b578dc9e | Python | lizuyao2010/summer_ttic | /binary_words_withdic.py | UTF-8 | 2,733 | 2.640625 | 3 | [] | no_license | #!/usr/bin/python
import json
from nltk.tokenize import word_tokenize
word2ind={}
relation2ind={}
flag=1
# count number of questions
count=0
def encode_word(text,dic,fw):
codes=[]
for word in text:
if word in dic:
codes.append(str(dic[word]))
print >> fw, ' '.join(codes)
def encode_relation(text,dic,fw):
codes=[]
for word in text:
if word not in dic:
dic[word]=len(dic)+1
codes.append(str(dic[word]))
print >> fw, ' '.join(codes)
# with open('../data/train_ws_soft.txt','r') as fr, open('../data/train_ws_soft_code.txt','w') as fw, open('../data/state.train_ws_soft.txt','r') as state:
# for line in fr:
# line=line.strip()
# # new question
# if line=="":
# flag=1
# print >> fw
# continue
# # question and answer
# if flag==1:
# q,a=line.split(' # ')
# q=word_tokenize(q.lower().strip().rstrip('?'))
# encode(q,word2ind,fw)
# count+=1
# flag+=1
# continue
# # my answer and relation
# elif flag==2:
# line=line.split(' # ')
# if len(line)==2:
# mya,r=line
# r=r.split(' ')
# assert len(r)<3
# encode(r,relation2ind,fw)
# continue
with open('../data/train_web_soft_0.8.txt','r') as fr, open('../data/train_web_soft_0.8_code_glove.txt','w') as fw, open('../data/state.train_web_soft_0.8.txt','r') as state, open('../data/word2ind_web_soft_0.8.glove.json','r') as dic:
vocab,num_answered,total=state.readline().strip().split()
word2ind=json.load(dic)
print(len(word2ind))
for i in xrange(int(num_answered)):
# new question
line=fr.readline().strip()
q,a=line.split(' # ')
# print q
q=word_tokenize(q.lower().strip().rstrip('?').decode('utf-8'))
encode_word(q,word2ind,fw)
count+=1
while True:
line=fr.readline().strip()
# next question
if line=="":
print >> fw
break
# my answer and relation
line=line.split(' # ')
if len(line)==2:
mya,r=line
r=r.split(' ')
assert len(r)<3
encode_relation(r,relation2ind,fw)
print "finish",count
with open('../data/word2ind_web_soft_0.8.glove.json','w') as fw1, open('../data/relation2ind_web_soft_0.8.glove.json','w') as fw2, open('../data/state_web_soft_0.8.glove.txt','w') as fw3:
json.dump(word2ind,fw1)
json.dump(relation2ind,fw2)
print >> fw3, len(word2ind), len(relation2ind), count | true |
0a22bd2be69aac2818d324f8ac61245e276a023a | Python | jimmykimani/andela-14- | /Day_0/prime/test_prime_numbers.py | UTF-8 | 1,601 | 3.59375 | 4 | [] | no_license | import prime_numbers
import unittest
class PrimeNumbersTest(unittest.TestCase):
"""prime number test for Integer, """
def test_if_value_is_integer(self):
self.assertEqual(prime_numbers.prime_numbers("three"), "only Integers alowed")
def test_zero_is_not_prime(self):
self.assertEqual(prime_numbers.prime_numbers(0), "Prime numbers start from 2")
def test_prime_numbers_are_returned_in_a_list(self):
self.assertEqual(type(prime_numbers.prime_numbers(3)), list)
def test_input_value_is_included_in_range_if_input_value_is_prime_number(self):
self.assertEqual(prime_numbers.prime_numbers(101)[-1], 101)
def test_one_is_not_prime(self):
self.assertEqual(prime_numbers.prime_numbers(1), "Prime numbers start from 2")
def test_two_is_prime(self):
self.assertEqual(prime_numbers.prime_numbers(2), [2])
def test_negative_value_inputs(self):
self.assertEqual(prime_numbers.prime_numbers(-2), "negative numbers are not allowed")
def test_two_is_the_first_value_returned_by_inputs_equal_to_and_greater_than_two(self):
self.assertEqual(prime_numbers.prime_numbers(500)[0], 2)
def test_even_numbers_are_absent_in_the_returned_result(self):
self.assertNotEqual((i for i in prime_numbers.prime_numbers(10) if i % 2 == 0), [2, 3, 4, 5, 6, 7, 8])
def test_if_function_validity(self):
self.assertEqual(prime_numbers.prime_numbers(100), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
if __name__ == '__main__':
unittest.main()
| true |
9feaa100a5150d6f4512d59d88acd6f094f9a8b3 | Python | michaelfisher/python | /ex4.py | UTF-8 | 942 | 4.21875 | 4 | [] | no_license | #How many cars are available in total?
cars = 100
#How many seats are available in each car
space_in_a_car = 4.0
#How many people will be driving a car
drivers = 30
#How many people will not be driving, but still need a ride
passengers = 90
#How many cars will not be driven?
cars_not_driven = cars - drivers
#How many cars will be driven?
cars_driven = drivers
#Including drivers, how many people can our system accomodate
carpool_capacity = cars_driven * space_in_a_car
#On average, how many passengers need to ride in each car?
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars."
print "We can transport", carpool_capacity, "total people today."
print "We have", passengers, "passengers to carpool."
print "We need to put about", average_passengers_per_car, "passengers in each car." | true |
2ef92a85dd1366079d8533f694ca12e5d85d794a | Python | samantha-jian/learn-python-in-hacker-way | /courses/novice/exercises/week1/1-student.py | UTF-8 | 210 | 3.296875 | 3 | [] | no_license | #! /usr/bin/env python
# -*- coding: utf8 -*-
str1 = ' 《五音集韻》說:「人死為鬼,人見懼之;鬼死為魙,鬼見怕之。」 '
str2 = '我愛紅娘'
msg = str1.strip()
print msg + str2
| true |
8f0a1394e5998457f3fd84b45421927175e1d035 | Python | hmvege/LatViz | /latviz/latviz.py | UTF-8 | 6,474 | 2.953125 | 3 | [
"MIT"
] | permissive | import subprocess
from pathlib import Path
from typing import Optional
import numpy as np
import pyvista as pv
from loguru import logger
from tqdm import tqdm
def create_animation(
frame_folder: Path,
animation_folder: Path,
observable: str,
animation_type: str,
time_slice: Optional[int] = None,
frame_rate: Optional[int] = 10,
) -> None:
"""
Method for creating animations from generated volumetric figures.
Args:
frame_folder: folder path to figures that will be be stitched together.
animation_folder: folder path to place animations in.
observable: observable we are creating an animation..
animation_type: format of animation. Available: 'gif', 'avi' or 'mp4'
time_slice: optional, eucl time slice.
frame_rate: frames per second of animation.
Raises:
NameError: if animation_type is not recognized.
"""
# Removes spaces
observable = observable.replace(" ", "_")
input_paths = frame_folder / "frame_t%02d.png"
if time_slice:
animation_path = animation_folder / (
f"{observable.lower()}_{time_slice}.{animation_type}"
)
else:
animation_path = animation_folder / (
f"{observable.lower()}.{animation_type}"
)
if animation_type == "gif":
cmd = [
"convert",
"-delay",
"1",
"-loop",
"0",
str(frame_folder / "*.png"),
str(animation_path),
]
elif animation_type == "mp4":
cmd = [
"ffmpeg",
"-r",
str(frame_rate),
"-start_number",
"0",
"-i",
str(input_paths),
"-c:v",
"libx264",
"-crf",
"0",
"-preset",
"veryslow",
"-c:a",
"libmp3lame",
"-b:a",
"320k",
"-y",
str(animation_path),
]
elif animation_type == "avi":
cmd = [
"ffmpeg",
"-r",
str(frame_rate),
"-i",
str(input_paths),
"-y",
"-qscale:v",
"0",
str(animation_path),
]
else:
raise NameError(
f"{animation_type} is not a recognized animation type."
)
logger.info(f"Running command: {' '.join(cmd)}")
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
_ = proc.stdout.read() # type: ignore[union-attr]
logger.success(f"Animation {animation_path} created.")
def plot_iso_surface(
field: np.ndarray,
observable_name: str,
frame_folder: Path,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
n_contours: Optional[int] = 20,
camera_distance: Optional[float] = 1.0,
xlabel: Optional[str] = "x",
ylabel: Optional[str] = "y",
zlabel: Optional[str] = "z",
title: Optional["str"] = None,
figsize: Optional[tuple[int, int]] = (1280, 1280),
) -> None:
"""
Function for creating figures of volumetric surfaces.
Args:
field: field array of size (N,N,N,NT) to plot. The number of
points to animate over is always the last dimension.
observable_name: str of observable_name we are plotting.
frame_folder: location of where to temporary store frames.
vmin: float lower cutoff value of the field.
vmax: float upper cutoff value of the field.
n_contours: optional integer argument for number of contours.
camera_distance: scalar to multiple camera position by.
xlabel: x label.
ylabel: y label.
zlabel: z label.
title: title of figure.
figsize: shape of figure.
"""
frame_folder.mkdir(exist_ok=True)
logger.info(f"Folder created at {str(frame_folder)}")
n_frames, n, _, _ = field.shape
if vmin is None:
vmin = np.min(field)
if vmax is None:
vmax = np.max(field)
if title is None and observable_name != "Observable":
title = observable_name
# Sets up the contours
contour_list = np.linspace(vmin, vmax, n_contours)
contour_list = contour_list.tolist()
for it in tqdm(range(n_frames), desc=f"Rendering {observable_name}"):
p = pv.Plotter(window_size=figsize, off_screen=True)
p.enable_anti_aliasing()
p.set_background(color="#AFAFAF")
volume = field[it]
grid = pv.UniformGrid()
grid.dimensions = volume.shape
grid.point_data["values"] = volume.flatten(order="F")
contour = grid.contour(contour_list)
outline = grid.outline()
# Viable color maps:
# - viridis
# - plasma
# - Spectral
# - coolwarm
#
# More color maps seen at:
# https://matplotlib.org/stable/tutorials/colors/colormaps.html
p.add_mesh(outline, color="k")
p.add_mesh(
contour,
clim=[vmin, vmax],
cmap="plasma",
show_scalar_bar=True,
opacity=0.65,
scalar_bar_args={
"vertical": True,
"label_font_size": 20,
"title_font_size": 26,
"title": "",
"font_family": "times",
"fmt": "%.2e",
"position_y": 0.0125,
},
)
p.show_grid(
font_size=26,
font_family="times",
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
)
pos = list(map(lambda f: f * camera_distance, p.camera.position))
p.set_position(pos)
p.camera.elevation = -2.5
p.add_text(
f"Frame: {it:-02d}",
font="times",
font_size=14,
position="upper_right",
)
p.add_text(
(
f"Avg={volume.mean():8.2e}\n"
f"Std={volume.std():8.2e}\n"
f"Min={volume.min():8.2e}\n"
f"Max={volume.max():8.2e}"
),
font="times",
position="lower_left",
font_size=12,
)
if title:
p.add_title(title, font="times")
fpath = frame_folder / f"frame_t{it:02d}.png"
p.screenshot(fpath, return_img=False)
tqdm.write(f"file created at {fpath}")
logger.info("Figures created.")
| true |
d15fdf75281dca89838b55220537518e7790e556 | Python | boratw/metalearn-gym | /metalearn/test2.py | UTF-8 | 3,545 | 2.515625 | 3 | [
"MIT"
] | permissive | import gym
import numpy as np
import tensorflow as tf
import random
input_state = tf.placeholder(tf.float32, [None, 4])
input_action = tf.placeholder(tf.float32, [None, 5])
input_qvalue = tf.placeholder(tf.float32, [None, 1])
global_step = tf.placeholder(tf.int64)
w1 = tf.Variable(tf.truncated_normal([4, 40], stddev=0.1), trainable=True, name="w1")
b1 = tf.Variable(tf.zeros([40]), trainable=True, name="b1")
fc1 = tf.matmul(input_state, w1) + b1
fc1 = tf.layers.dropout(fc1, rate=0.05)
fc1_relu = tf.nn.leaky_relu(fc1, alpha=0.05)
w2 = tf.Variable(tf.truncated_normal([40, 40], stddev=0.1), trainable=True, name="w2")
b2 = tf.Variable(tf.zeros([40]), trainable=True, name="b2")
fc2 = tf.matmul(fc1_relu, w2) + b2
fc2 = tf.layers.dropout(fc2, rate=0.05)
fc2_relu = tf.nn.leaky_relu(fc2, alpha=0.05)
w3 = tf.Variable(tf.truncated_normal([40, 5], stddev=0.1), trainable=True, name="w3")
output = tf.matmul(fc2_relu, w3)
cost = tf.reduce_sum(tf.square(tf.reduce_sum(tf.multiply(input_action, output), axis=1, keepdims=True) - input_qvalue)) * 0.01
learning_rate = tf.train.exponential_decay(0.001, global_step, 20, 0.9)
operation = tf.train.AdamOptimizer(learning_rate).minimize(cost)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
saver = tf.train.Saver(max_to_keep=0)
env = gym.make('CartPoleGoal-v0')
log_file = open("data/test2_8/log1.txt", "wt")
for epoch in range(1000):
states = []
actions = []
qvalues = []
steps = 0
costs = 0
scores = 0
for play in range(16):
rewards = []
maxvalues = []
state = env.reset()
env.set_goal(2.0)
step = 0
for _ in range(500):
states.append(state)
if play == 0:
env.render()
o_output = sess.run(output, {input_state:[state]})
action = np.argmax(o_output[0])
maxvalues.append(o_output[0][action])
r = random.randrange(20)
if r <= 4:
action = r
action_onehot = [0., 0., 0., 0., 0.]
action_onehot[action] = 1.
actions.append(action_onehot)
step += 1
state, reward, done, info = env.step(action)
rewards.append(reward)
scores += reward
if done:
break
print("Episode " + str(epoch) + " Step " + str(step))
steps += step
if(step == 500):
survivescore = reward * reward * 0.2 - abs(state[1]) - abs(state[3])
if survivescore < 0:
survivescore = 0
else:
survivescore = 0
for i in range(1, step) :
qvalues.append([rewards[i-1] + maxvalues[i] * 0.96 + survivescore])
qvalues.append([rewards[step-1] + survivescore])
for _ in range(64):
dic = random.sample(range(len(states)), 32)
dic_states = [states[i] for i in dic]
dic_actions = [actions[i] for i in dic]
dic_qvalues = [qvalues[i] for i in dic]
_, o_cost = sess.run((operation, cost), {input_state:dic_states, input_action:dic_actions, input_qvalue:dic_qvalues, global_step:epoch })
print("Episode " + str(epoch) + " Loss " + str(o_cost))
costs += o_cost
log_file.write("Episode\t" + str(epoch) + "\tStep\t" + str(steps / 16) + "\tScore\t" + str(scores / 16) + "\tCost\t" + str(costs / 32) + "\n")
if epoch % 50 == 0:
saver.save(sess, "data/test2_8/log1_" + str(epoch) + ".ckpt")
env.close() | true |
1a52adcaabb5a781a9298e4fe221892cfbbbb012 | Python | jinzaizhichi/akshare | /akshare/datasets.py | UTF-8 | 1,631 | 2.84375 | 3 | [
"MIT"
] | permissive | # -*- coding:utf-8 -*-
# !/usr/bin/env python
"""
Date: 2022/5/9 18:08
Desc: 导入文件工具,可以正确处理路径问题
"""
from importlib import resources
import pathlib
def get_ths_js(file: str = "ths.js") -> pathlib.Path:
"""Get path to data "ths.js" text file.
Returns
-------
pathlib.PosixPath
Path to file.
References
----------
.. [1] E.A.Abbott, ”Flatland”, Seeley & Co., 1884.
"""
with resources.path("akshare.data", file) as f:
data_file_path = f
return data_file_path
def get_crypto_info_csv(file: str = "crypto_info.zip") -> pathlib.Path:
"""Get path to data "ths.js" text file.
Returns
-------
pathlib.PosixPath
Path to file.
References
----------
.. [1] E.A.Abbott, ”Flatland”, Seeley & Co., 1884.
"""
with resources.path("akshare.data", file) as f:
data_file_path = f
return data_file_path
def get_covid_js(file: str = "covid.js") -> pathlib.Path:
"""Get path to data "ths.js" text file.
Returns
-------
pathlib.PosixPath
Path to file.
References
----------
.. [1] E.A.Abbott, ”Flatland”, Seeley & Co., 1884.
"""
with resources.path("akshare.data", file) as f:
data_file_path = f
return data_file_path
if __name__ == "__main__":
get_ths_js_path = get_ths_js(file="ths.js")
print(get_ths_js_path)
get_crypto_info_csv_path = get_crypto_info_csv(file="crypto_info.zip")
print(get_crypto_info_csv_path)
get_covid_js_path = get_covid_js(file="covid.js")
print(get_covid_js_path)
| true |
99803194f6b7415a5cb2d1f3bd3859d1ffd294de | Python | GIA-USB/LARC-2017 | /MOTORS/ServoPWM.py | UTF-8 | 1,269 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python
import pigpio
import time
ORDENHA = 4
APRIETA = 3
pi = pigpio.pi()
pi.set_mode(ORDENHA, pigpio.OUTPUT)
pi.set_mode(APRIETA, pigpio.OUTPUT)
#print("setting to: ",pi.set_servo_pulsewidth(APRIETA, 1000)) # Mover servo
#print("set to: ",pi.get_servo_pulsewidth(APRIETA))
#time.sleep(1)
veces = 4
for i in range(veces):
print("setting to: ",pi.set_servo_pulsewidth(APRIETA, 1625))
print("set to: ",pi.get_servo_pulsewidth(APRIETA))
#for i in range(8):
# pi.set_servo_pulsewidth(APRIETA,1450)
# time.sleep(0.5)
# pi.set_servo_pulsewidth(APRIETA,1550)
#print("setting to: ",pi.set_servo_pulsewidth(ORDENHA, 1000))
# time.sleep(1.5)
time.sleep(4)
pi.set_servo_pulsewidth(ORDENHA,1700)
time.sleep(2)
print("setting to: ",pi.set_servo_pulsewidth(ORDENHA, 0))
time.sleep(3)
print("setting to: ",pi.set_servo_pulsewidth(APRIETA, 1420)) # Detener servo (Hace torque)
time.sleep(3)
print("setting to: ",pi.set_servo_pulsewidth(ORDENHA, 0)) # Detener servo (Sin torque)
print("set to: ",pi.get_servo_pulsewidth(ORDENHA))
print("setting to: ",pi.set_servo_pulsewidth(APRIETA, 0)) # Detener servo (Sin torque)
print("set to: ",pi.get_servo_pulsewidth(APRIETA))
pi.stop()
| true |
195d51c2342b895c0cd185d873ce50f8c269a057 | Python | yiyscut/drumExtractor | /features.py | UTF-8 | 3,903 | 2.9375 | 3 | [] | no_license | #functions for extracting features from audio signals
from scipy import *
import numpy as np
from rect import halfWave
from stft import *
#dexters
def hfc(X):
hfcs = np.zeros(X.shape[0])
for k in range(X.shape[0]):
print("K = ", k)
hfcs[k] = np.sum(np.abs((X[k, :])*k))
return hfcs
def RMS(x):
total = 0
for i in range(len(x) - 1):
total = x[i] + total
return (total/len(x))**(0.5)
#returns 9 RMS data points
def threeBandRMS(x):
"""
Variables :
-----------------------
x : input list or array of data
-----------------------
Outputs :
-----------------------
low : the amount of energy observed in the lower third
mid :
high :
LV :
MV :
HV :
LVM :
LVH :
MVH :
-----------------------
"""
X = myFFT(x)
low = RMS(X[:len(X)//3])
mid = RMS(X[len(X)//3:(len(X)//3)*2])
high = RMS(X[(len(X)//3)*2:])
#one band vs energy of other two bands
LV = low / ((mid + high)/2)
MV = mid / ((low + high)/2)
HV = high / ((mid + low)/2)
#one band vs energy of other specific band
LVM = low / mid
LVH = low / high
MVH = mid / high
#return the nine features from three band RMS
return low, mid, high, LV, MV, HV, LVM, LVH, MVH
def crestFactor(x):
raise NotImplementedError()
def temporalCentroid():
raise NotImplementedError()
def spectralTemproid():
raise NotImplementedError()
def spectralKurtosis():
raise NotImplementedError()
def spectralSkewness():
raise NotImplementedError()
def spectralRolloff():
raise NotImplementedError()
def spectralFlux(x, hop=None):
"""
A function for detecting the amount of relitive energy change in a signal
-------------------
Variables :
----------------------
x : the input array of data
hop : the number of samples to analyze at once
----------------------
Returns
----------------------
flux : the spectral flux of the signal
----------------------
"""
if (hop == None):
hop = 100
flux = envelope(x, hop)
x = halfWave(x)
aver = flux[0]
for i in range (hop, len(x) - hop, hop):
flux[i:i+hop] = np.abs(flux[i] - flux[i+hop])
for i in range (len(flux)):
aver = aver + flux[i]
return (aver/(len(flux)))
def complexNovelty(x):
raise NotImplementedError()
def zeroCrossingRate(x, srate = 44100):
crossingCount = 0
crossings = np.zeros(len(x))
for i in range (1, len(x)):
if ((x[i] > 0) & (x[i-1] <= 0)):
crossings[i] = 1
crossingCount = crossingCount + 1
if ((x[i] < 0) & (x[i-1] > 0)):
crossings[i] = 1
crossingCount = crossingCount + 1
print(crossingCount*len(x)/srate/2)
return crossings
def envelope(x, binSize=None):
"""
function for determining the overall amplitude envelope of a signal
-------------------
Variables :
----------------------
x : incoming array of audio data (or data in general
binSize : the amount of samples processed at a time
----------------------
Returns
----------------------
x : an array containing the envelope data
"""
if (binSize == None):
binSize = 2200
for i in range(0,len(x)-binSize,binSize):
maxi = 0.0
for j in range (i,i+binSize):
if (x[j] > maxi):
maxi = x[j]
for i in range(i,i+binSize):
x[i] = maxi
return x
"""
def flatness(x):
256, 128, 64, 32, 16, 8, 4, 2
X1 = x[:128,:]
X2 = x[128:256,:]
X3 = x[256:,:]
K1 = X1.shape[0]
GeoMean = np.prod(np.abs(X1), axis=0)**(1/K1)
arithMean = np.sum(np.abs(X1), axis=0)/K1
flat1 = geoMean/arithMean#the flatness for the first bin
"""
| true |
1a34da58fc77170054d3895ecaef9e7752d0c462 | Python | dekasthiti/pythonic | /yoga/bit_manipulation/hamming_dist.py | UTF-8 | 600 | 3.796875 | 4 | [] | no_license | from argparse import ArgumentParser
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
tmp = x ^ y # Find bits that are different
return bin(tmp).count('1')
#461. Hamming Distance
if __name__ == '__main__':
sol = Solution()
parser = ArgumentParser()
parser.add_argument('--first_num', help = 'First number', type = int, default=20000)
parser.add_argument('--second_num', help = 'Second number', type = int, default=247483647)
args = parser.parse_args()
print(f"Hamming distance: {sol.hammingDistance(args.first_num, args.second_num)}") | true |
864258ba5b2653f2e89ac51a424cfbcc2c2953ab | Python | lalitkapoor112000/Python | /List Comprehension.py | UTF-8 | 53 | 2.609375 | 3 | [] | no_license | squares=[i**2 for i in range(1,11)]
print(squares)
| true |
1979bd3ba191453f760c4f78a3cd0fcff44b0a83 | Python | sukritsangvong/Hearts | /heartCard.py | UTF-8 | 2,177 | 3.5 | 4 | [] | no_license | import random
from heartCard import *
from playable import *
from takeCardFromBoard import *
def generatePlayers():
'''Makes a list containing the 4 player objects.'''
players = []
for i in range(4):
players.append(player())
return players
class player:
'''An object that has a hand, a score, and a graveyard. Can be controlled
by either a human or by code.'''
def __init__(self):
self.hand = []
self.graveyard = []
self.score = 0
self.swaps = []
def setHand(self, hand):
self.hand = hand
def getHand(self):
return self.hand
def appendHand(self,card):
self.hand.append(card)
def setSwaps(self,swapList):
for swap in swapList:
self.swaps.append(swap)
def getSwaps(self):
return self.swaps
def addScore(self, score):
self.score += score
def setScore(self, score):
self.score = score
def getScore(self):
return self.score
def getGraveyard(self):
return self.graveyard
def addGraveyard(self, listOfCollecetedCards):
self.graveyard += listOfCollecetedCards
return self.graveyard
def clearGraveyard(self):
self.graveyard = []
def removeHand2Clubs(self):
self.getHand()[1].remove(['2', 'clubs'])
def createDeck():
'''Creates a standard deck of 52 cards. Aces are high.'''
deck = []
for suits in ["clubs", "diamonds", "hearts", "spades"]:
for num in ['2', '3','4', '5', '6', '7', '8', '9','10',\
'J', 'Q', 'K', 'A']:
cardAdded = [num, suits]
deck.append(cardAdded)
return deck
def assignHand(player, deck, numberofCards):
'''Deals a random hand of cards to the player.'''
currentHand = player.getHand()
for cards in range(numberofCards):
#random one card at a time
card = random.choice(deck)
#remove chosen card from the deck
deck.remove(card)
#add card to hand
currentHand.append(card)
#return currentHand
player.setHand(currentHand)
return player
| true |
7bc623835e7991b1db0893422c4c025d4cd0a271 | Python | zhengguorong/pomes_lstm | /utils/helper.py | UTF-8 | 2,936 | 3.3125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import collections
import os
import sys
import numpy as np
# 将数据转换为字词向量
def data_process(file_name):
datas = []
# 提取每行诗的标题和内容,去除长度小于5和大于79的数据,并按诗的字数排序
with open(file_name, "r") as f:
for line in f.readlines():
try:
line = line.decode('UTF-8') #如果是python3 把这句注释即可
line = line.strip(u'\n')
title, content = line.strip(u' ').split(u':')
content = content.replace(u' ',u'')
if u'_' in content or u'(' in content or u'(' in content or u'《' in content or u'[' in content:
continue
if len(content) < 5 or len(content) > 79:
continue
content = u'[' + content + u']'
datas.append(content)
except ValueError as e:
pass
# 按字数从小到多排序
datas = sorted(datas, key=lambda l: len(line))
all_words = []
for data in datas:
# 将所有字拆分到数组里
all_words += [word for word in data]
# 统计每个字出现的次数。counter输出格式 {'不': 13507, '人': 12003, '山': 10162, '风': 9675}
counter = collections.Counter(all_words)
# 对数据做格式转换,变为[('不', 13507), ('人', 12003), ('山', 10162), ('风', 9675)]
count_pairs = sorted(counter.items(), key=lambda x: -x[1])
words, _ = zip(*count_pairs)
words = words[:len(words)] + (' ',)
# 每个字映射为一个数字ID , {'不': 4, '人': 5, '山': 6, '风': 7}
word_num_map = dict(zip(words, range(len(words))))
# 把原始数据诗词转换成词向量的形式
to_num = lambda word: word_num_map.get(word, len(words))
datas_vector = [ list(map(to_num, data)) for data in datas]
return datas_vector, word_num_map, words
def generate_batch(batch_size, poems_vec, word_to_int):
# 将所有诗词分成n_chunk组,每组大小为batch_size
n_chunk = len(poems_vec) // batch_size
x_batches = []
y_batches = []
for i in range(n_chunk):
start_index = i * batch_size
end_index = start_index + batch_size
batches = poems_vec[start_index:end_index]
length = max(map(len, batches))
# 使用空字符填充长度
x_data = np.full((batch_size, length), word_to_int[' '], np.int32)
for row in range(batch_size):
x_data[row, :len(batches[row])] = batches[row]
# label数据为x数据+1位
y_data = np.copy(x_data)
y_data[:, :-1] = x_data[:, 1:]
x_batches.append(x_data)
y_batches.append(y_data)
return x_batches, y_batches
if __name__ == '__main__':
data_vector, word_num_map, words = data_process('../data/poetry.txt')
x, y = generate_batch(64, data_vector, word_num_map) | true |
6b21fc15855b6ff9c307277fe543a70b5f621e33 | Python | helloira-al/Classic-CS-in-Python-Notes | /fibonacci_sequence1/main.py | UTF-8 | 788 | 4.59375 | 5 | [] | no_license | #the code below implements explicit memoization to calculate the nth Fibonacci value
fibonacci_cache = {}
def fibonacci(n):
# check if n is aleady stored in the cached values
if n in fibonacci_cache:
return fibonacci_cache[n]
# otherwise calculate the nth term
# check if n is an integer
if type(n) != int:
raise TypeError("n must be a positive integer")
# check if n is a positive integer
if n < 1:
raise ValueError("n must be a positive integer")
if (n == 1):
value = 1
elif (n == 2):
value = 1
elif (n > 2):
value = fibonacci(n - 1) + fibonacci(n - 2)
# store the value in cache and return it
fibonacci_cache[n] = value
return value
# call the function
print(fibonacci(100))
| true |
d835bc2dcf4e0eae753f65be219fdeeb78e51e40 | Python | Nashluffy/49er-sense-edge | /serverSocket.py | UTF-8 | 967 | 3.234375 | 3 | [] | no_license | import socket
from gpiozero import LED
from time import sleep
led = LED(17)
port = 12345
try:
s = socket.socket()
print 'Socket successfully created!'
except:
print 'Socket creation failed'
try:
s.bind(('', port))
print 'Socket binded to %s' %(port)
except:
print 'Failed to bind to port! Is something already listening?'
#Socket needs to listen now
s.listen(5)
print 'Socket is listening'
while True:
# Establish connection with client.
c, addr = s.accept()
print 'Got connection from', addr
# send a thank you message to the client.
command = c.recv(1024)
if command == 'TurnOn':
print 'Turning LED on!'
led.on()
sleep(10)
led.off()
print 'Turning LED off!'
c.send('Thank you for connecting')
# Close the connection with the client
c.close()
| true |
3c33e6654e4ea6933fbb88f34fff739f9c9019f8 | Python | ec-geolink/d1lod | /d1lod/d1lod/people/documents.py | UTF-8 | 3,264 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | """
file: documents.py
author: Bryce Meucm
Gets n scimeta documents off the D1 Solr index and saves them in a
subdirectory.
"""
def getDocuments(n=100, start=0):
"""Get `n`, staring at `start` documents off the CN's Solr index."""
base_url = "https://cn.dataone.org/cn/v1/query/solr/"
fields = ",".join(["identifier"])
query_params = "formatType:METADATA+AND+(datasource:*LTER+OR+datasource:*"\
"KNB+OR+datasource:*PISCO+OR+datasource:*GOA)+AND+-"\
"obsoletedBy:*"
rows = n
start = start
query_string = "%s?fl=%s&q=%s&rows=%s&start=%s" % (base_url,
fields,
query_params,
rows,
start)
print(query_string)
xmldoc = getXML(query_string)
return(xmldoc)
def getSysMeta(identifier):
"""Get the system metadata for document `identifier`"""
getDocumentAtEndpoint("meta", identifier)
def getSciMeta(identifier):
"""Get the scientific metadata for document `identifier`"""
getDocumentAtEndpoint("resolve", identifier)
def getDocumentAtEndpoint(endpoint, identifier):
"""Helper function to get a document at an arbitrary REST endpoint"""
base_url = "https://cn.dataone.org/cn/v1"
query_string = "%s/%s/%s" % (base_url,
endpoint,
urllib.quote_plus(identifier))
print("\t" + query_string)
xmldoc = getXML(query_string)
return(xmldoc)
def getXML(url):
"""Get XML document at the given url `url`"""
try:
res = urllib2.urlopen(url)
except:
print "\tgetXML failed for %s" % url
return None
content = res.read()
xmldoc = ET.fromstring(content)
return(xmldoc)
def saveXML(filename, xmldoc):
"""Save a pretty-printed version of an XML document"""
xmlstr = minidom.parseString(ET.tostring(xmldoc)).toprettyxml(indent="\t")
filename_with_path = "./documents/%s" % filename
with codecs.open(filename_with_path, "w", encoding="utf-8") as f:
f.write(xmlstr)
def main(n, start):
results = getDocuments(n)
documents = results.findall(".//str[@name='identifier']")
identifiers = []
for document in documents:
identifiers.append(document.text)
for identifier in identifiers:
filename = identifier.translate(None, "/:")
print "%s" % (identifier)
scimeta = getSciMeta(identifier)
# Bail if we can't get scimeta
if scimeta is None:
print "\tCoudln't get scimeta for %s." % (identifier)
continue
sysmeta = getSysMeta(identifier)
if sysmeta is not None:
saveXML("%s-sysmeta.xml" % filename, sysmeta)
saveXML("%s-scimeta.xml" % filename, scimeta)
if __name__ == "__main__":
import urllib2
import urllib
import xml.etree.ElementTree as ET
from xml.dom import minidom
import os
import codecs
if not os.path.exists("./documents"):
os.makedirs("./documents")
n = 100
start = 30000
main(n, start)
| true |
a6e57ddfac99abf9f9c5a8e38de1333917fb38f6 | Python | zhanghao-esrichina/bigdata-project | /basic_grammar/进程线程/多线程同步.py | UTF-8 | 1,119 | 3.484375 | 3 | [] | no_license | '''
共享数据
如果多个线程对某个数据进行修改,则可能出现不可预料对结果,为了保证数据的正确性,需要对多个线程进行同步,一个一个的完成。
使用thread对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire方法和release方法
对于那些需要每次只允许一个线程操作的数据,可以将其操作放到acquire和release方法之间
'''
import threading
import random
import time
lock = threading.Lock()
list1 = [0]*10
def set_list_value():
# 获取线程锁,如果已经上锁则等待释放
lock.acquire()
for i in range(len(list1)):
list1[i] = 1
time.sleep(0.5)
lock.release()
def get_list_value():
lock.acquire()
for i in range(len(list1)):
print("===== ", list1[i])
time.sleep(0.5)
lock.release()
if __name__ == "__main__":
get_task = threading.Thread(target=get_list_value)
set_task = threading.Thread(target=set_list_value)
get_task.start()
set_task.start()
get_task.join()
set_task.join()
print(list1)
| true |
60d38ee0cf31c1ae303a16b4f3e76dbf3d0b3625 | Python | mla96/Paired-Autoencoder-Image-Fusion | /Registration/registration.py | UTF-8 | 3,919 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python3
"""
This file contains functions to register a moving image to a fixed image.
"""
import numpy as np
import SimpleITK as sitk
from PIL import Image
# Print registration metrics
def command_iteration(method):
print("{0:3} = {1:10.5f} : {2}".format(method.GetOptimizerIteration(),
method.GetMetricValue(),
method.GetOptimizerPosition()))
# Register moving image to fixed image
def my_registration(fixed_im, moving_im):
initial_transform = sitk.CenteredTransformInitializer(fixed_im,
moving_im,
sitk.AffineTransform(2),
sitk.CenteredTransformInitializerFilter.GEOMETRY)
moving_resampled = sitk.Resample(moving_im, fixed_im, initial_transform, sitk.sitkLinear, 0.0,
moving_im.GetPixelID())
R = sitk.ImageRegistrationMethod()
R.SetMetricAsANTSNeighborhoodCorrelation(50) # sampling?
R.SetMetricSamplingStrategy(R.RANDOM)
R.SetMetricSamplingPercentage(0.4)
# R.SetShrinkFactorsPerLevel(shrinkFactors = [4,2,1])
# R.SetSmoothingSigmasPerLevel(smoothingSigmas=[2,1,0])
# R.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()
# R.SetOptimizerAsRegularStepGradientDescent(1.0, 0.0001, 500, estimateLearningRate=R.Once)
R.SetOptimizerAsGradientDescent(1.0, numberOfIterations=900, convergenceMinimumValue=1e-14)
# R.SetOptimizerAsGradientDescentLineSearch(1.0, numberOfIterations=300, convergenceMinimumValue=1e-12)
R.SetOptimizerScalesFromPhysicalShift()
R.SetInitialTransform(initial_transform, inPlace=False)
R.SetInterpolator(sitk.sitkLinear)
R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
final_transform = R.Execute(fixed_im, moving_resampled)
print("-------")
print(final_transform)
print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
print(" Iteration: {0}".format(R.GetOptimizerIteration()))
print(" Metric value: {0}".format(R.GetMetricValue()))
moving_final = sitk.Resample(moving_resampled, fixed_im, final_transform, sitk.sitkLinear, 0.0,
moving_im.GetPixelID())
# sitk.Show(moving_final)
return moving_final, initial_transform, final_transform
# Compares two images; useful for comparing un-registered and registered moving images with fixed images
def checkerboard(image1, image2, filename, writer):
checker = sitk.CheckerBoard(image1, image2)
# sitk.Show(checker)
writer.SetFileName(filename + '.tiff')
writer.Execute(checker)
# Register raw time series using a pre-calculated transform from flattened series
def transform_slices(fixed_im, final_transform, voxel_array, w, h):
# transformed_voxel_array = np.zeros(shape=(h, w, 1024)) # Matches larger size
transformed_movie_array = np.zeros(shape=(256, 256, 1024))
for i in range(len(voxel_array[0][0])):
slice = voxel_array[:, :, i]
slice_im = Image.fromarray(slice)
slice_im = sitk.GetImageFromArray(np.array(slice_im.resize((w, h), Image.LANCZOS), dtype=np.float32),
isVector=False)
transformed_slice = sitk.Resample(slice_im, fixed_im, final_transform, sitk.sitkLinear, 0.0,
slice_im.GetPixelID())
# transformed_voxel_array[:, :, i] = sitk.GetArrayFromImage(transformed_slice)
transformed_movie_slice = Image.fromarray(sitk.GetArrayFromImage(transformed_slice))
transformed_movie_slice = np.array(transformed_movie_slice.resize((256, 256), Image.LANCZOS), dtype=np.float32)
transformed_movie_array[:, :, i] = transformed_movie_slice
return transformed_movie_array
| true |
393be373e6fe3c2f5de36b37bc3cc8f3bbd5117c | Python | shiqing881215/Python | /object&database/constructorDestructor.py | UTF-8 | 742 | 4.1875 | 4 | [] | no_license | class PartyAnimal :
x = 0
name = ""
# This is the constructor
def __init__(self, name) :
self.name = name
print "I'm constructing", self.name
# method, each python class at least has one variable called self
def party(self):
self.x = self.x+1
print self.name, " says ", self.x
# This is the destructor
def __del__(self):
print "I'm destructed", self.name
# Attention - there is no "new" keyword
jack = PartyAnimal("Jack")
rose = PartyAnimal("Rose")
jack.party()
jack.party()
jack.party()
rose.party()
jack.party()
rose.party()
'''
The result is
I'm constructing Jack
I'm constructing Rose
Jack says 1
Jack says 2
Jack says 3
Rose says 1
Jack says 4
Rose says 2
I'm destructed Rose
I'm destructed Jack
'''
| true |
616091877321a52df078b3140aab37938e9cad19 | Python | JHadley1406/udemy_coursework | /threading/extending_thread_class.py | UTF-8 | 378 | 3.46875 | 3 | [] | no_license | import threading
class MyThread(threading.Thread):
# MUST override run method
def run(self):
print(threading.current_thread().getName())
print("Egyptian Pyramid")
for x in range(0, 5):
for j in range(0,x+1):
print("*", end=" ")
print("\n")
pyramid = MyThread(name="Pyramid Thread")
pyramid.start()
| true |
3e5ca0ec28ce534fac4adf576bbe9ece1770e0d6 | Python | GiaKhangLuu/BasicOpenCV | /chapter06.py | UTF-8 | 628 | 2.546875 | 3 | [] | no_license | # JOINING IMAGE
import cv2
import numpy as np
img1 = cv2.resize(cv2.imread('imgs/khang.jpeg'), (200, 200))
img2 = cv2.resize(cv2.imread('imgs/drinking.jpeg'), (200, 200))
#imgHor = np.hstack([img1, img2])
#imgVer = np.vstack([img1, img2])
#mix = np.vstack([imgHor, imgHor])
imgGray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
imgGray = np.expand_dims(imgGray, axis=2)
imgGray = np.insert(imgGray, imgGray.shape[2], 0 , axis=2)
imgGray = np.insert(imgGray, imgGray.shape[2], 0 , axis=2)
mix = np.hstack([imgGray, img2])
#cv2.imshow("Horizontal", imgHor)
#cv2.imshow("Vertical", imgVer)
cv2.imshow("Mix", mix)
cv2.waitKey(5000)
| true |
f02b85c56ff40f547428a52f0f74d7823f2c40b1 | Python | idmakers/python | /2scompement.py | UTF-8 | 489 | 4.125 | 4 | [] | no_license |
def twos_comp(val, bits):
"""compute the 2's compliment of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
#Going from a binary string is particularly easy...
while(1):
x = input('二進位')
binary_string = x # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
print(out)
| true |
660a38ea2a39a10c0f1f792157109a1c80f0b7d0 | Python | garrettBJohnson/cautious_cauliflower | /stats_quiz.py | UTF-8 | 714 | 3.609375 | 4 | [] | no_license | def question(prompt, hint, answer):
'''
prompt - string
hint - string
answer - string
'''
while True:
response = input(prompt)
if response is "?":
print(hint)
elif response is not None:
print(answer)
break
##### Quiz: Stats edition #####
print("For each question, type your response, then press ENTER to proceed; this triggers the answer to each open-ended quesiton. Type '?' to trigger a hint.\n\n")
q1 = question("Question", "Hint", "Answer")
q2 = question("Question", "Hint", "Answer")
q3 = question("Question", "Hint", "Answer")
q4 = question("Question", "Hint", "Answer")
q5 = question("Question", "Hint", "Answer")
| true |
aa1e7e58712e55155657d5eb8b58e592cb671ab3 | Python | bopopescu/clearglass-test | /utility/utility.py | UTF-8 | 1,457 | 2.765625 | 3 | [] | no_license | import time
import json
from datetime import datetime,date
def json_date_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime) or isinstance(obj, date):
serial = obj.isoformat()
return serial
else:
jsonEncoder = json.JSONEncoder()
return jsonEncoder.default(obj)
class Utility(object):
module_name = "Utility"
def safe_int(self, a):
try:
return int(a)
except:
return -1
def get_current_time(self):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
def checkForSQLInjectionCharacters(self, input):
if not input:
return 0
invalid_characters = [';','=','"',"'",'or 1', 'delete ','drop ', '\\','like', '%','select ','update ','insert ', '(',')']
for invalid_character in invalid_characters:
if input.lower().find(invalid_character) != -1 :
return 1
return 0
def print_json(self, log_message, log_object):
if log_message:
print log_message
print json.dumps(log_object, indent=4, default=json_date_serial)
def print_str(self, log_message, log_object=""):
print "%s %s" % (log_message, log_object)
def print_log_msg(self, log_message, log_object=None):
if self.print_log:
if log_object:
if isinstance(log_object, dict) or isinstance(log_object, list):
self.print_json(log_message, log_object)
else:
self.print_str(log_message, log_object)
else:
print log_message
else:
pass
| true |
6b1d94bc13e54664ada6c6b414f5ebfd72c725b7 | Python | yflfly/learn_pytorch | /2D函数优化实例.py | UTF-8 | 1,803 | 3.25 | 3 | [] | no_license | import numpy as np
import torch
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def himmelblau(x):
return (x[0] ** 2 + x[1] - 11) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2
x = np.arange(-6, 6, 0.1) # x.shape=(120,)
y = np.arange(-6, 6, 0.1) # y.shape=(120,)
X, Y = np.meshgrid(x, y) # X.shape=(120, 120), Y.shape=(120,120)
Z = himmelblau([X, Y])
fig = plt.figure("himmeblau")
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z)
ax.view_init(60, -30)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
'''
学习网址:
https://www.bilibili.com/video/BV1ht4y1C7GA?p=36
https://www.cnblogs.com/douzujun/p/13300437.html
'''
# 先对x[0],x[1]进行初始化,不同的初始值可能会得到不同的结果
x = torch.tensor([0., 0.], requires_grad=True)
# 定义Adam优化器,指明优化目标是x,学习率是1e-3
optimizer = torch.optim.Adam([x], lr=1e-3)
for step in range(20000):
pred = himmelblau(x)
optimizer.zero_grad() # 将梯度设置为0
pred.backward() # 生成当前所在点函数值相关的梯度信息,这里即优化目标的梯度信息
optimizer.step() # 使用梯度信息更新优化目标的值,即更新x[0]和x[1]
if step % 2000 == 0:
print("step={},x={},f(x)={}".format(step, x.tolist(), pred.item()))
''''
Tip:
使用 optimizer的流程就是三行代码:
optimizer.zero_grad()
loss.backward()
optimizer.step()
首先,循环里每个变量都拥有一个优化器
需要在循环里逐个zero_grad(),清理掉上一步的残余值。
之后,对loss调用backward()的时候
它们的梯度信息会被保存在自身的两个属性(grad 和 requires_grad)当中。
最后,调用optimizer.step(),就是一个apply gradients的过程
将更新值 重新赋给parameters。
''' | true |
4ff5763256f6fda6c0322aefd5256fe05057299f | Python | gregtuck/Greco-Roman | /train_model.py | UTF-8 | 3,073 | 2.9375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import keras
import cv2 as cv
from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
# get the dataset that was created on convert_to_csv.py
data_set = pd.read_csv(r'/home/greg/Documents/uni/AI/course_files/shuffledCK.csv', dtype='a')
# create two numpy arrays that will contain the data for emotion labels and image pixels separately
emotion_labels = np.array(data_set['emotion'])
image_pixels = np.array(data_set['imgPixels'])
# convert numpy array to list
image_pixels = image_pixels.tolist()
# convert image_pixels array to 2D array, each array index can be displayed as an image using matplotlib
faces = []
for pixels in image_pixels:
face = [int(pixel) for pixel in pixels.split(' ')]
face = np.asarray(face).reshape(48, 48)
face = cv.resize(face.astype('uint8'), (48, 48))
faces.append(face.astype('float32'))
faces = np.asarray(faces)
# normalise the data to values between 0 and 1
faces /=255
# convert label array to one hot vector ie 4:'Sad' will become [0. 0. 0. 0. 1. 0. 0.]
emotion = keras.utils.to_categorical(emotion_labels, 7)
# split emotion data and appropriate labels to a train and test set equal to the number of images
train_size = 500
test_size = 108
# prepare the image and label data to be used for the training phase
train_X = faces[0:train_size]
train_Y = emotion[0:train_size]
train_X = train_X.reshape(-1, 48, 48, 1)
# prepare the image and label data to be used for the testing phase from index 500 to the rest
test_X = faces[train_size:608]
test_Y = emotion[train_size:608]
test_X = test_X.reshape(-1, 48, 48, 1)
# define the type of model as sequence of layers
model = Sequential()
##############################FEATURE_LEARNING##################################
# first layer
model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(48,48,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
# second layer
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# third layer
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
##############################FEATURE_LEARNING##################################
###############################CLASSIFICATION###################################
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))
###############################CLASSIFICATION###################################
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
model.fit(train_X, train_Y, batch_size=10, epochs=20)
train_score = model.evaluate(train_X, train_Y, batch_size=10)
print('Train Loss', train_score[0])
print('Train accuracy', 100*train_score[1])
test_score = model.evaluate(test_X, test_Y, batch_size=10)
print('Test Score', test_score[0])
print('Test accuracy', 100*test_score[1])
model.save('modelA.h5')
model.summary()
| true |
8bfddfb38c922dd4fab1b87dd4744afaf3606b12 | Python | vprogramer/Zephyr | /task_three.py | UTF-8 | 175 | 3.40625 | 3 | [] | no_license |
number_of_sides = [4, 6, 8, 12, 20]
# Looking for probabilities.
for i in number_of_sides:
p = ((int(i >= 5) * 1/i) * 0.2)/(0.2 * (0 + 1/6 + 1/8 + 1/12 + 1/20))
print(p)
| true |
b45d6d4f0326c560145af9214f2b80f5992b8f24 | Python | MayankMaheshwar/DS-and-Algo-solving | /2022-convert-1d-array-into-2d-array/2022-convert-1d-array-into-2d-array.py | UTF-8 | 268 | 3.140625 | 3 | [] | no_license | class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
ans = []
if len(original) == m*n:
for i in range(0, len(original), n):
ans.append(original[i:i+n])
return ans | true |
457de3c25dbc217a237ed2e1a9d9641c9920c132 | Python | Akhilesh09/MS_Projects | /Deep Learning - Individual Projects/DL_HW1/code/main.py | UTF-8 | 6,960 | 3.25 | 3 | [] | no_license | import os
import matplotlib.pyplot as plt
from LogisticRegression import logistic_regression
from LRM import logistic_regression_multiclass
from DataReader import *
data_dir = "../data/"
train_filename = "training.npz"
test_filename = "test.npz"
def visualize_features(X, y):
'''This function is used to plot a 2-D scatter plot of training features.
Args:
X: An array of shape [n_samples, 2].
y: An array of shape [n_samples,]. Only contains 1 or -1.
Returns:
No return. Save the plot to 'train_features.*' and include it
in submission.
'''
### YOUR CODE HERE
### END YOUR CODE
def visualize_result(X, y, W):
'''This function is used to plot the sigmoid model after training.
Args:
X: An array of shape [n_samples, 2].
y: An array of shape [n_samples,]. Only contains 1 or -1.
W: An array of shape [n_features,].
Returns:
No return. Save the plot to 'train_result_sigmoid.*' and include it
in submission.
'''
### YOUR CODE HERE
### END YOUR CODE
def visualize_result_multi(X, y, W):
'''This function is used to plot the softmax model after training.
Args:
X: An array of shape [n_samples, 2].
y: An array of shape [n_samples,]. Only contains 0,1,2.
W: An array of shape [n_features, 3].
Returns:
No return. Save the plot to 'train_result_softmax.*' and include it
in submission.
'''
### YOUR CODE HERE
### END YOUR CODE
def main():
# ------------Data Preprocessing------------
# Read data for training.
raw_data, labels = load_data(os.path.join(data_dir, train_filename))
raw_train, raw_valid, label_train, label_valid = train_valid_split(raw_data, labels, 2300)
##### Preprocess raw data to extract features
train_X_all = prepare_X(raw_train)
valid_X_all = prepare_X(raw_valid)
##### Preprocess labels for all data to 0,1,2 and return the idx for data from '1' and '2' class.
train_y_all, train_idx = prepare_y(label_train)
valid_y_all, val_idx = prepare_y(label_valid)
####### For binary case, only use data from '1' and '2'
train_X = train_X_all[train_idx]
train_y = train_y_all[train_idx]
####### Only use the first 1350 data examples for binary training.
train_X = train_X[0:1350]
train_y = train_y[0:1350]
valid_X = valid_X_all[val_idx]
valid_y = valid_y_all[val_idx]
####### set lables to 1 and -1. Here convert label '2' to '-1' which means we treat data '1' as postitive class.
train_y[np.where(train_y==2)] = -1
valid_y[np.where(valid_y==2)] = -1
data_shape= train_y.shape[0]
# # Visualize training data.
visualize_features(train_X[:, 1:3], train_y)
# ------------Logistic Regression Sigmoid Case------------
##### Check GD, SGD, BGD
logisticR_classifier = logistic_regression(learning_rate=0.5, max_iter=100)
logisticR_classifier.fit_GD(train_X, train_y)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
logisticR_classifier.fit_BGD(train_X, train_y, data_shape)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
logisticR_classifier.fit_SGD(train_X, train_y)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
logisticR_classifier.fit_BGD(train_X, train_y, 1)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
logisticR_classifier.fit_BGD(train_X, train_y, 10)
print(logisticR_classifier.get_params())
print(logisticR_classifier.score(train_X, train_y))
# Explore different hyper-parameters.
### YOUR CODE HERE
### END YOUR CODE
# Visualize the your 'best' model after training.
# visualize_result(train_X[:, 1:3], train_y, best_logisticR.get_params())
### YOUR CODE HERE
### END YOUR CODE
# Use the 'best' model above to do testing. Note that the test data should be loaded and processed in the same way as the training data.
### YOUR CODE HERE
### END YOUR CODE
# ------------Logistic Regression Multiple-class case, let k= 3------------
###### Use all data from '0' '1' '2' for training
train_X = train_X_all
train_y = train_y_all
valid_X = valid_X_all
valid_y = valid_y_all
######### BGD for multiclass Logistic Regression
logisticR_classifier_multiclass = logistic_regression_multiclass(learning_rate=0.5, max_iter=100, k= 3)
logisticR_classifier_multiclass.fit_BGD(train_X, train_y, 10)
print(logisticR_classifier_multiclass.get_params())
print(logisticR_classifier_multiclass.score(train_X, train_y))
# Explore different hyper-parameters.
### YOUR CODE HERE
### END YOUR CODE
# Visualize the your 'best' model after training.
# visualize_result_multi(train_X[:, 1:3], train_y, best_logistic_multi_R.get_params())
# Use the 'best' model above to do testing.
### YOUR CODE HERE
### END YOUR CODE
# ------------Connection between sigmoid and softmax------------
############ Now set k=2, only use data from '1' and '2'
##### set labels to 0,1 for softmax classifer
train_X = train_X_all[train_idx]
train_y = train_y_all[train_idx]
train_X = train_X[0:1350]
train_y = train_y[0:1350]
valid_X = valid_X_all[val_idx]
valid_y = valid_y_all[val_idx]
train_y[np.where(train_y==2)] = 0
valid_y[np.where(valid_y==2)] = 0
###### First, fit softmax classifer until convergence, and evaluate
##### Hint: we suggest to set the convergence condition as "np.linalg.norm(gradients*1./batch_size) < 0.0005" or max_iter=10000:
### YOUR CODE HERE
### END YOUR CODE
train_X = train_X_all[train_idx]
train_y = train_y_all[train_idx]
train_X = train_X[0:1350]
train_y = train_y[0:1350]
valid_X = valid_X_all[val_idx]
valid_y = valid_y_all[val_idx]
##### set lables to -1 and 1 for sigmoid classifer
train_y[np.where(train_y==2)] = -1
valid_y[np.where(valid_y==2)] = -1
###### Next, fit sigmoid classifer until convergence, and evaluate
##### Hint: we suggest to set the convergence condition as "np.linalg.norm(gradients*1./batch_size) < 0.0005" or max_iter=10000:
### YOUR CODE HERE
### END YOUR CODE
################Compare and report the observations/prediction accuracy
'''
Explore the training of these two classifiers and monitor the graidents/weights for each step.
Hint: First, set two learning rates the same, check the graidents/weights for the first batch in the first epoch. What are the relationships between these two models?
Then, for what leaning rates, we can obtain w_1-w_2= w for all training steps so that these two models are equivalent for each training step.
'''
### YOUR CODE HERE
### END YOUR CODE
# ------------End------------
if __name__ == '__main__':
main()
| true |
103fe5b2624efb525cbfe836e7ae8c14ba0c9b67 | Python | GregoireHENRY/python-template-quick | /{{cookiecutter.repo_name}}/ssot.py | UTF-8 | 1,480 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #!/usr/bin/env python3
"""
Update single sources of truth (name, version) in all listed files according to
their respective rules.
"""
import re
import sys
from pathlib import Path
from typing import Optional # noqa: F401
from pudb import set_trace as bp # noqa: F401
from {{cookiecutter.repo_name}} import VERSION
# Define for each file the pattern to match and the value to replace.
REGEX_VERSION = {
Path("pyproject.toml"): [
(r'(version\ =\ )("[\d.]+")', rf'\g<1>"{VERSION}"'),
],
Path("README.md"): [
(r"(\[version badge\]\:\ .+\/version)(-[\d.]+-)", rf"\g<1>-{VERSION}-"),
],
}
def main() -> None:
# Loop over the files to change.
for PATH, OPERATIONS in REGEX_VERSION.items():
# Read contents of file.
TEXT = PATH.read_text()
for (PATTERN, REPLACEMENT) in OPERATIONS:
# Check that we have exactly one match.
RESULT = re.findall(PATTERN, TEXT)
if not len(RESULT):
print(f"no match for the pattern {PATTERN} of {PATH.name}")
sys.exit(1)
elif len(RESULT) > 1:
print(f"more than one match for the pattern {PATTERN} of {PATH.name}")
sys.exit(1)
# Apply match replacement.
else:
TEXT = re.sub(PATTERN, REPLACEMENT, TEXT)
# Save TEXT into file.
with PATH.open("w") as F:
F.write(TEXT)
if __name__ == "__main__":
main()
| true |
85a2115df5804eb1c88e496df58fbded00f832c3 | Python | civodlu/trw | /tests/test_callback_learning_rate_finder.py | UTF-8 | 2,114 | 2.765625 | 3 | [
"MIT"
] | permissive | import unittest
import collections
import trw
import torch.nn as nn
import torch
import numpy as np
import functools
def create_simple_regression(factor, nb_samples=100):
i = np.random.randn(nb_samples, 1).astype(np.float32)
o = i * np.float32(factor)
datasets = collections.OrderedDict()
sampler = trw.train.SamplerRandom(batch_size=256)
datasets['simple'] = {
'train': trw.train.SequenceArray({
'input': i,
'output': o}, sampler=sampler)
}
return datasets
class ModelSimpleRegression(nn.Module):
def __init__(self):
super().__init__()
with torch.no_grad():
p = torch.ones(1, dtype=torch.float32) * 0.0001
self.w = nn.Parameter(p, requires_grad=True)
def forward(self, batch):
x = self.w * batch['input']
o = trw.train.OutputRegression(output=x, output_truth=batch['output'])
return {'regression': o}
optimizer_fn = functools.partial(trw.train.create_sgd_optimizers_fn, learning_rate=10.0, momentum=0)
class TestCallbackLearningRateFinder(unittest.TestCase):
def test_always_find_good_LR(self):
"""
Here we always try to find a good LR for random models. Make sure we also plot the LR search
Initial learning rate is too high and wont converge. Use the LR finder to set this automatically
"""
torch.manual_seed(0)
np.random.seed(0)
options = trw.train.Options(device=torch.device('cpu'), num_epochs=200)
trainer = trw.train.TrainerV2(
callbacks_post_training=None,
callbacks_pre_training=[trw.callbacks.CallbackLearningRateFinder(set_new_learning_rate=True)]
)
results = trainer.fit(
options,
datasets=create_simple_regression(factor=10.0),
model=ModelSimpleRegression(),
optimizers_fn=optimizer_fn,
log_path='LR_finder',
eval_every_X_epoch=2)
assert float(results.history[-1]['simple']['train']['overall_loss']['loss']) < 1e-4
if __name__ == '__main__':
unittest.main()
| true |
497627f2add34c2befb15acd0c11f2c0a3bff5fc | Python | kagnew-j/Algorithm | /chapter 3_search and sort problem_09_insertion_sort.py | UTF-8 | 2,743 | 4.25 | 4 | [] | no_license | #chapter 3_search and sort
#problem_09_insertion_sort
# 삽입 정렬 for easy explanation
def find_ins_idx(r,v):
"""
for문 활용한 삽입 위치 반환 함수
입력 : 리스트 r, 삽입될 숫자값 v
출력 : 삽입해야할 index
"""
for i in range(len(r)): # 이미 정렬된 리스트를 앞에서부터 확인
if v < r[i]: # v값보다 i번 위치 값이 크면
return i # i 위치 반환, v값이 현 i 위치 앞에 놓이려면 i 번째 삽입해야함.
return len(r) # 적절한 위치 반환 없을시 제일 큰 수 이므로 맨 뒤에 삽입
def ins_sort(a):
"""
for문 활용한 삽입 리스트 정렬
입력 : 리스트 a
출력 : 정렬된 리스트 a
"""
result = [] # 정렬된 값을 저장할 새 리스트
while a: # 기존 리스트에 값이 남아 있는 동안 반복
value = a.pop(0) # 기존 리스트에서 제일 첫번째 값 꺼냄
ins_idx = find_ins_idx(result,value) # 꺼낸 값이 들어갈 위치 찾기
result.insert(ins_idx, value) # 찾은 위치에 값 삽입
return result # 결과 리스트 반환
# Generalized Insertion Sort
def ins_sort_gen(a):
"""
for문 활용한 삽입 리스트 정렬
입력 : 리스트 a
출력 : 정렬된 리스트 a
"""
n = len(a)
for i in range(1,n): # 1부터 n-1까지
key = a[i] # key에 i번 위치 값 저장
j = i-1 # j에 바로 i번 왼쪽 위치 값 저장
while j >= 0 and a[j] > key: # j가 0보다 크거나 같고, 값이 key 보다 큰 경우
a[j+1] = a[j] # 삽입할 공간이 생기도록 값을 오른쪽으로 한 칸 이동
j -= 1
a[j+1] = key # 찾은 삽입 위치에 key 값 삽입
# exercise 9-1
# Done by hands
# exercise 9-2
# reverse insertion sort
def ins_sort_rev(a):
"""
for문 활용한 삽입 리스트 정렬
입력 : 리스트 a
출력 : 정렬된 리스트 a
"""
n = len(a)
for i in range(1,n): # 1부터 n-1까지
key = a[i] # key에 i번 위치 값 저장
j = i-1 # j에 바로 i번 왼쪽 위치 값 저장
while j >= 0 and a[j] < key: # j가 0보다 크거나 같고, 값이 key 보다 작은 경우
a[j+1] = a[j] # 삽입할 공간이 생기도록 값을 오른쪽으로 한 칸 이동
j -= 1
a[j+1] = key # 찾은 삽입 위치에 key 값 삽입 | true |
0ec52c24e9e1b4cff727ebe0fb25e638ecaf3376 | Python | grant-ward/BotNet | /linux/generate.py | UTF-8 | 2,212 | 3.078125 | 3 | [] | no_license | import os
import ipaddress,time
print("Welcome! this script will configurate the agent with your configurations!")
if os.path.isfile("settings.py"):
while True:
delete = input("\nDo you wanna clean your old configuration? for a new configuration?\n [Y/n] ")
if delete in ("Y","y","Yes","yes","YES"):
os.system("echo '' > settings.py")
break
if delete in ("N","n","no","No","NO"):
print("closing...")
exit()
else:
print("Invalid answer!")
else:
print("\n\nCreating a configurantion file..")
time.sleep(.5)
os.system("touch settings.py")
print("File created! going to configuration phase!")
script = open("settings.py","w")
while True:
ip = input("Wich IP?\n :")
try:
validate_ip = ipaddress.ip_network(ip, strict=False)
script.write("host="+"'"+str(ip)+"'"+"\n")
break
except:
print("INVALID IP!")
while True:
try:
port = int(input("Wich port?\n :"))
script.write("port="+str(port)+"\n")
break
except:
print("INVALID PORT!")
while True:
while True:
tkinter = input("Do you wanna a message in execution of agent?\n[Y/N] :")
if tkinter in ("y","Y","yes","YES","Yes"):
script.write("tkinter=True\n")
while True:
type_message = input("What type?\nALERT[A] INFO[I] ERROR[E]\n: ")
if type_message in ("e","E","A","a","i","I"):
if type_message in ("e","E"):
script.write("type=ERROR")
break
if type_message in ("A","a"):
script.write("type=ALERT")
break
if type_message in ("I","i"):
script.write("type=INFO")
break
else:
print("Invalid type!")
if tkinter in ("n","N","no","NO","No") or type_message != None:
break
else:
print("Invalid answer!")
break
print("Configuration fineshed!\nUse Compile.py to make a .exe or compile yourself with Pyinstaller!")
| true |
2ff660bb8b9e8c36ed778a2200ee054e748db8b8 | Python | kanokanoka/pytest | /library/re_test/test.py | UTF-8 | 187 | 3.015625 | 3 | [] | no_license | # re is the regular expression library
import re
pattern = r"test"
words = "aaatestcomand"
match = re.match(pattern,words)
print(match)
search = re.search(pattern,words)
print(search)
| true |
d2f675e265034581b1775b8a4ea18a5994a1c0f7 | Python | albertosanfer/MOOC_python_UPV | /Módulo 3/Práctica3_1.py | UTF-8 | 462 | 4.375 | 4 | [
"Apache-2.0"
] | permissive | # A continuación tenemos un input en el que le pediremos un número al usuario y
# lo guardaremos en la variable entrada. Después, deberemos guardar en la
# variable mayorQueTres el valor True si ese número es mayor que tres y False
# en caso contrario.
# Nota, acordaros de realizar la conversión de tipos en el input
entrada = int(input('Introduce un número:'))
if entrada > 3:
mayorQueTres = True
else:
mayorQueTres = False
print(mayorQueTres)
| true |
8c77ee59994fae2170c76870aa54c90d16714571 | Python | furious-luke/polecat | /tests/test_model.py | UTF-8 | 1,897 | 2.5625 | 3 | [
"MIT"
] | permissive | from polecat.db.schema import Role
from .models import Actor, Address, schema
def test_construct_related():
actor = Actor(
first_name='Johnny',
last_name='Depp',
address={
'country': 'USA'
}
)
assert isinstance(actor.address, Address)
assert actor.address.country == 'USA'
def test_construct_reverse():
address = Address(
country='USA',
actors_by_address=[
{
'first_name': 'Johnny',
'last_name': 'Depp'
},
{
'first_name': 'Bill',
'last_name': 'Murray'
}
]
)
assert isinstance(address.actors_by_address, list)
assert len(address.actors_by_address) == 2
for actor in address.actors_by_address:
assert isinstance(actor, Actor)
assert actor.first_name is not None
assert actor.last_name is not None
assert actor.address == address
def test_create_schema():
address_table = schema.get_table_by_name('address')
actor_table = schema.get_table_by_name('actor')
admin_role = schema.get_role_by_name('admin')
address_access = schema.get_access_by_entity(address_table)
assert actor_table.C.id is not None
assert actor_table.C.first_name is not None
assert actor_table.C.last_name is not None
assert actor_table.C.age is not None
assert actor_table.C.address is not None
assert actor_table.C.user is not None
assert address_table.C.id is not None
assert address_table.C.country is not None
assert address_table.C.actors_by_address is not None
assert admin_role.name == 'admin'
assert address_access.entity == address_table
def test_role_to_dbrole_converts_parents():
user_role = schema.get_role_by_name('user')
parent = list(user_role.parents)[0]
assert parent.__class__ == Role
| true |
0b967a39f036a24a61092216645b523d6c896bb8 | Python | linheimx/python_master | /oop_design_pattern/factory_method/elevator_schedule_example_improve_v2.py | UTF-8 | 2,991 | 3.015625 | 3 | [] | no_license | import datetime
from constant import *
class Singleton(type):
_instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class ScheduleFactory(object):
@staticmethod
def get_scheduler(strategy_id):
if strategy_id == SCHEDULE_STRATEGY_ID.RESPONSE_TIME:
return ResponseTimeSchedule()
elif strategy_id == SCHEDULE_STRATEGY_ID.THROUGH_PUT:
return ThroughtputScheduler()
elif strategy_id == SCHEDULE_STRATEGY_ID.DYNAMIC:
if datetime.datetime.now().hour < 12:
return ResponseTimeSchedule()
else:
return ThroughtputScheduler()
class ElevatorManager(object):
def __init__(self, controller_count, strategy_id):
self._controllers = [ElevatorController(i) for i in range(controller_count)]
self._strategy_id = strategy_id
@property
def strategy_id(self):
return self._strategy_id
@strategy_id.setter
def strategy_id(self, strategy_id):
self._strategy_id = strategy_id
def request_elevator(self, destination, direction):
scheduler = ScheduleFactory.get_scheduler(self._strategy_id)
print(scheduler)
selected_elevator = scheduler.select_elevator(self, destination, direction)
self._controllers[selected_elevator].goto_floor(destination)
class ElevatorController(object):
def __init__(self, elevator_id):
self._elevator_id = elevator_id
self._cur_floor = 1
def goto_floor(self, destination):
print("Elevator [{}] Floor {} => {}".format(self._elevator_id, self._cur_floor, destination))
self._cur_floor = destination
class ThroughtputScheduler(object, metaclass=Singleton):
"""
스케줄링 기능을 제공하는 클래스는 오직 하나의 객체만 생성해서 사용해도 충분하다.
그러므로 싱글턴(Singleton) 패턴으로 설계하면 좋다.
"""
def select_elevator(self, manager, destination, direction):
return 0 #임의로 선택함
class ResponseTimeSchedule(object, metaclass=Singleton):
"""
스케줄링 기능을 제공하는 클래스는 오직 하나의 객체만 생성해서 사용해도 충분하다.
그러므로 싱글턴(Singleton) 패턴으로 설계하면 좋다.
"""
def select_elevator(self, manager, destination, direction):
return 1 #임의로 선택함
if __name__ == "__main__":
response_time_scheduler = ElevatorManager(2, SCHEDULE_STRATEGY_ID.RESPONSE_TIME)
response_time_scheduler.request_elevator(10, DIRECTION.UP)
through_put_scheduler = ElevatorManager(2, SCHEDULE_STRATEGY_ID.THROUGH_PUT)
through_put_scheduler.request_elevator(10, DIRECTION.UP)
dynamic_scheduler = ElevatorManager(2, SCHEDULE_STRATEGY_ID.DYNAMIC)
dynamic_scheduler.request_elevator(10, DIRECTION.UP) | true |
cbbadc112f3c78627ec6b673825a965f9ed07a85 | Python | baton96/Intelligent-Systems | /fuzzy/fuzzy.py | UTF-8 | 3,023 | 2.953125 | 3 | [] | no_license | import math
import numpy as np
def trapezoid(val, bottomLeft, upperLeft, upperRight, bottomRight):
if val < bottomLeft:
return 0
elif val < upperLeft:
return (val - bottomLeft) / (upperLeft - bottomLeft)
elif val < upperRight:
return 1.0
elif val < bottomRight:
return (bottomRight - val) / (bottomRight - upperRight)
else:
return 0
def pi(val, bottomLeft, upperLeft, upperRight, bottomRight):
if val < (upperLeft + upperRight) / 2:
return 1 / (1 + math.exp(k * ((bottomLeft + upperLeft) / 2 - val)))
else:
return 1 / (1 + math.exp(k * (val - (upperRight + bottomRight) / 2)))
def fuzzySet(bottomLeft, upperLeft, upperRight, bottomRight, stop, start=0):
return [fun(i, bottomLeft, upperLeft, upperRight, bottomRight) for i in np.arange(start, stop, step)]
def tNorm(a, b):
try:
_ = iter(a)
except TypeError:
return min(a, b) # Gödel–Dummett t-norm
# return a*b # product t-conorm
# return max(a+b-1,0) # Łukasiewicz t-norm
# return min(a,b) if max(a,b)==1 else 0 # drastic t-norm
# return (a*b)/(2-(a+b-a*b)) # Einstein t-norm
# return (a*b)/(a+b-a*b) # Hamacher t-norm
else:
try:
_ = iter(b)
except TypeError:
b = np.array([b] * len(a))
return np.fmin(a, b)
def sNorm(a, b):
try:
_ = iter(a)
except TypeError:
return max(a, b) # Gödel–Dummett t-norm
# return a+b-a*b # product t-conorm
# return min(a+b,1) # Łukasiewicz t-conorm
# return max(a,b) if min(a,b)==0 else 1 # drastic t-conorm
# return (a+b)/(1+a*b) # Einstein t-conorm
# return (a+b-2*a*b)/(1-a*b) # Hamacher t-conorm
else:
try:
_ = iter(b)
except TypeError:
b = np.array([b] * len(a))
return np.fmax(a, b)
# defuzz = lambda agg: len(agg)-np.argmax(agg[::-1])-1 # max of maximum
# defuzz = np.argmax # min of maximum
defuzz = lambda agg: np.mean(np.where(agg == max(agg))) # mean of maximum
step = 0.1
k = 2.5
fun = trapezoid
tSolid = fuzzySet(0, 0, 4, 8, 12)
tSolidVal = fun(5, 0, 0, 4, 8)
tSolidClipped = tNorm(tSolid, tSolidVal)
tSoft = fuzzySet(4, 8, 12, 12, 12)
tSoftVal = fun(5, 4, 8, 12, 12)
tSoftClipped = tNorm(tSoft, tSoftVal)
wHeavy = fuzzySet(3, 6, 9, 9, 9)
wHeavyVal = fun(4.5, 3, 6, 9, 9)
wHeavyClipped = tNorm(wHeavy, wHeavyVal)
wLight = fuzzySet(0, 0, 0, 6, 9)
wLightVal = fun(4.5, 0, 0, 0, 6)
wLightClipped = tNorm(wLight, wLightVal)
gFirm = fuzzySet(2, 3, 4, 4, 4)
gMedium = fuzzySet(1, 2, 2, 3, 4)
gGentle = fuzzySet(0, 0, 1, 2, 4)
rule = tNorm(tSolidVal, wHeavyVal)
gFirmClipped = tNorm(gFirm, rule)
rule = sNorm(tNorm(tSolidVal, wLightVal), tNorm(tSoftVal, wHeavyVal))
gMediumClipped = tNorm(gMedium, rule)
rule = tNorm(tSoftVal, wLightVal)
gGentleClipped = tNorm(gGentle, rule)
aggregated = sNorm(sNorm(gFirmClipped, gMediumClipped), gGentleClipped)
print(defuzz(aggregated) * step)
| true |
0ef181fc65ef4d9507291281727156896440e8d7 | Python | antaramunshi/GUIwithTkinter | /script1.py | UTF-8 | 764 | 3.078125 | 3 | [] | no_license | from tkinter import *
window = Tk()
def km_to_miles():
miles = float(e1_value.get())*.6
t1.insert(END, miles)
def kg_conversion():
grams = float(e1_value.get())*1000
t1.insert(END, grams)
pounds = float(e1_value.get())*2.20462
t2.insert(END,pounds)
ounces = float(e1_value.get())*35.274
t3.insert(END, ounces)
b1 = Button(window, text='Execute',command=kg_conversion)
b1.grid(row=0,column=3)
label = Label(window, text='Kg')
label.grid(row=0,column=1)
e1_value=StringVar()
e1=Entry(window,textvariable=e1_value)
e1.grid(row=0,column=2)
t1=Text(window,height=1,width=20)
t1.grid(row=1,column=1)
t2=Text(window,height=1,width=20)
t2.grid(row=1,column=2)
t3=Text(window,height=1,width=20)
t3.grid(row=1,column=3)
window.mainloop()
() | true |
5675d37cbe0584ddb9af838910bef90b3066e133 | Python | wogusqkr0515/python | /06/selfStudy06-01.py | UTF-8 | 150 | 3.390625 | 3 | [] | no_license | i, hap = 0, 0
for i in range(0, 101, 1) :
if i % 7 == 0 :
hap = hap + i
print("0과 100 사이에 있는 7의 배수 합계 : %d" % hap) | true |
69d96e181d13b8bcde631c4c63180c974399c39a | Python | andreas-harmuth/registreringstidende-api | /temp.py | UTF-8 | 47 | 2.578125 | 3 | [] | no_license | s = "%s jhej %s" % ("hej med dig","f")
print(s) | true |
63c7ff66d30610c85fe4c646615fd4ff1e8c9323 | Python | metapy/metapy | /demos/twitter-test.py | UTF-8 | 599 | 2.546875 | 3 | [] | no_license | import twitter, getpass
import pickle
try:
auth = pickle.load(open("../auth.p"))
data = auth['twitter']
except Exception:
print "ERROR: Run 'authorize.py twitter' first!"
exit()
# API stuff
api = twitter.Api(
consumer_key=data['CONSUMER_KEY'],
consumer_secret=data['CONSUMER_SECRET'],
access_token_key=data['OAUTH_TOKEN'],
access_token_secret=data['OAUTH_TOKEN_SECRET']
)
print "People who have recently posted statuses:"
statuses = api.GetPublicTimeline()
print [s.user.name for s in statuses]
print ""
print "Your friends:"
friends = api.GetFriends()
print [u.name for u in friends]
| true |
f860b8ffea3340bbeed346ce2c0f3f7044b8c730 | Python | lqs4188980/CodingPractice | /Python/same_tree/same_tree.py | UTF-8 | 362 | 2.9375 | 3 | [] | no_license | class Solution(object):
def isSameTree(self, p, q):
if q is None or p is None:
if q is None and p is None:
return True
else:
return False
if q.val != p. val:
return False
return self.isSameTree(q.left, p.left) and \
self.isSameTree(q.right, p.right)
| true |
f09298e5cdd1a3840e726c93353428dab9008315 | Python | dilya123/pythoMonth1 | /lesson3/lesson3.py | UTF-8 | 754 | 3.8125 | 4 | [] | no_license | posuda = "not ok"
if posuda == "ok":
print("Пойдешь гулять")
print("Купим мороженное")
else:
print("минус Карманные деньги")
print("Махач, Мясо, Рубилово, Жестокость")
name = input("Введите ваше имя хозяин ")
if name == "Султанмурат":
age = int(input("Введите ваш возраст! "))
if age > 16:
hobby = input("Введите ваше хобии ")
if hobby == "книги":
print("Приветсвую хозяин!")
else:
print("Султанмурат любит книги, вы точно не хозяин!")
else:
print("Султанмурату 17!")
else:
print("Вы не хозяин!")
| true |
0225f639ff71094da33fbbd0d0621e5b4830bedd | Python | skibold/cs6364 | /ABGame.py | UTF-8 | 1,011 | 3.046875 | 3 | [] | no_license | '''Same output as MiniMaxGame, just fewer nodes evaluated'''
from MorrisBoard import Board
from Algorithms import *
def static_est(board, pos):
return board.mid_end_estimate_white(pos)
def successor(board, pos, d):
if d % 2 == 0:
if board.num_white(pos) == 3:
return board.gen_hop_4_white(pos)
else:
return board.gen_move_4_white(pos)
else:
if board.num_black(pos) == 3:
return board.gen_hop_4_black(pos)
else:
return board.gen_move_4_black(pos)
def move(startpos, depth):
reset_count()
board = Board()
finalpos, score = maxmin_ab(board, startpos, 0, depth, static_est, successor, -100000, 100000, False)
print("Input position: {}, Output position: {}, Positions evaluated by static: {}, AlphaBeta estimate: {}".format(startpos, finalpos, get_count(), score))
return finalpos
if __name__ == "__main__":
startpos, outp, depth = optargs(argv)
write_output(move(startpos, depth), outp) | true |
ac4ade34ddd4ca7c334c4b2266255cb1befe1027 | Python | jghibiki/Byte-le-Royale-2018 | /game/server/server_control.py | UTF-8 | 3,944 | 2.8125 | 3 | [] | no_license | import random
import os
import json
import platform
import shutil
import sys
from datetime import datetime, timedelta
class ServerControl:
def __init__(self, wait_on_client, verbose):
self._loop = None
self._socket_client = None
self.verbose = verbose
self.wait_on_client = wait_on_client
self._clients_connected = 0
self._client_ids = []
self._quit = False
# Game Configuration options
system = platform.system()
if system == "Windows":
self.turn_time = 0.025
else:
self.turn_time = 0.01
self.game_tick_no = 0
self.max_game_tick = 1e4
self.turn_data = None
def initialize(self):
if self.verbose:
print("Initializing Server Logic")
# clear game log
if os.path.exists("game_log"):
shutil.rmtree("game_log")
self.send({ "type": "game_starting"})
self.schedule(self.pre_tick, delay=0.1)
def wait_for_clients(self):
if self.verbose:
print("Waiting for clients...")
if self._clients_connected < 1:
self.schedule(self.wait_for_clients, 2)
else:
self.schedule(self.initialize, delay=0.1)
def notify_client_connect(self, client_id):
self._clients_connected += 1
self._client_ids.append(client_id)
self.turn_data = None
def notify_client_turn(self, turn_data):
self.turn_data = turn_data
def pre_tick(self):
if self.verbose: print("SERVER TICK: {}".format(self.game_tick_no))
self.game_tick_no += 1
self.turn_data = None
self.pre_turn()
self.send_turn_data()
self.schedule(self.post_tick)
def post_tick(self):
# wait for turn data before handling post tick
if self.turn_data is None and self.wait_on_client:
self.schedule(self.post_tick)
return
self.post_turn()
log_data = self.log()
self.dump_log(log_data)
if self.game_tick_no < self.max_game_tick:
if not self._quit:
self.schedule(self.pre_tick)
else:
# Exit Cleanly
# Dump Game log manifest
with open("game_log/manifest.json", "w") as f:
json.dump({"ticks": self.game_tick_no}, f)
self._socket_client.close()
self.schedule(lambda : sys.exit(0), 3)
else:
print("Exiting - MAX Tickes: {0} exceeded".format(self.max_game_tick))
# Dump Game log manifest
with open("game_log/manifest.json", "w") as f:
json.dump({"ticks": self.game_tick_no}, f)
self._socket_client.close()
self.schedule(lambda : sys.exit(1), 3)
def send_turn_data(self):
pass
def set_loop(self, loop):
self._loop = loop
def set_socket_client(self, socket_client):
self._socket_client = socket_client
def send(self, data):
self._socket_client.sendAll( data )
def schedule(self, callback, delay=None):
self._loop.call_later(
delay if delay != None else self.turn_time,
callback)
def pre_turn(self):
""" Override. Logic to be executed before the players are allowed to take a turn """
pass
def post_turn(self):
"""Override. Logic to be executed after the players have sent turn actions"""
pass
def log(self):
"""Override. Dumps state to a file """
return {}
def dump_log(self, data):
if not os.path.exists("game_log"):
os.makedirs("game_log")
with open("game_log/{0:05d}.json".format(self.game_tick_no), "w") as f:
json.dump(data, f)
def notify_game_over(self):
self.send({
"type": "game_over"
})
| true |
3783146adc74640381a0da5575f5789d73f0f429 | Python | FattestCat/dt-manager | /tournament.py | UTF-8 | 884 | 3 | 3 | [] | no_license | from __future__ import annotations
from team import Team
from bracket import Bracket, OlimpicBracket
class Tournament:
def __init__(self, teams: list[Team], bracket: Bracket):
self.teams: list[Team] = teams
self.bracket: Bracket = bracket
@classmethod
def generate_blank_tournament(cls):
trn_teams = [Team.gerenate_blank_team() for _ in range(4)]
brk = OlimpicBracket([t.team_id for t in trn_teams])
return cls(trn_teams, brk)
def __repr__(self):
res = ""
res += "\n".join(str(team) for team in self.teams)
res += self.bracket.get_history()
return res
def main():
trn = Tournament.generate_blank_tournament()
trn.bracket.generate_initial_team_pairs()
while trn.bracket.get_winner() < 0:
trn.bracket.play_round()
print(trn)
if __name__ == "__main__":
main()
| true |
7317af033e842d7ff45ee11aa49706a8531eb0ff | Python | Aasthaengg/IBMdataset | /Python_codes/p02415/s341896845.py | UTF-8 | 37 | 3.171875 | 3 | [] | no_license | x=input()
x=str.swapcase(x)
print(x)
| true |
1b9799c0d1fefc7a3c163b8f7fc2bea829420f34 | Python | tomkowz/python-fav-memes-rest-api | /api/helpers/meme_dto.py | UTF-8 | 455 | 2.546875 | 3 | [
"MIT"
] | permissive | from api.model.meme import Meme
class MemeDTO:
@staticmethod
def to_json(meme):
json = dict()
json['keywords'] = meme.keywords
json['filename'] = meme.filename
return json
@staticmethod
def from_json(json):
meme = Meme()
if 'keywords' in json:
meme.keywords = json['keywords']
if 'filename' in json:
meme.filename = json['filename']
return meme
| true |
a8f205318e28e4a77e1073f9a3af65c4d4ae811d | Python | JohnyXXX/Telephone-DB | /module.py | UTF-8 | 4,159 | 3.46875 | 3 | [] | no_license | from json import dump, load
from sys import stderr
class TelephoneExist(Exception):
"""Класс исключения если тнлефон уже имеется в БД"""
pass
class TelephoneDB(dict):
"""
Класс БД на основе списка. Должен добавлять,
искать, изменять и удалять из БД.
"""
def __init__(self):
try:
self.db = load(open('db.json'))
except FileNotFoundError:
self.db = {}
def __person_exist_check(self, person):
for i in self.db.keys():
if person.key == i:
return True
def add(self, person):
if self.__person_exist_check(person) is True:
raise TelephoneExist('Запись с таким номером уже существует!')
else:
self.db.update({person.key: person.value})
def find(self, request):
result = {}
for key, value in self.db.items():
if (
request.lower() in key.lower()) or (
request.lower() in value[0].lower() or (
request.lower() in value[1].lower())
):
result.update({key: value})
return result
def edit(self, data):
for key in self.db.keys():
if data.key in key:
self.db.update({data.key: data.value})
def remove(self, request):
for key, value in self.db.items():
if (
request.lower() in key.lower()) or (request.lower() in value[0].lower()) or (
request.lower() in value[1].lower()
):
return self.db.pop(key)
def save(self):
dump(self.db, open('db.json', 'w'), ensure_ascii=False)
class Person(TelephoneDB):
"""
Конструктор для "Персоны" и представление для печати.
"""
def __init__(self, telephone, fullname, address):
self.value = (fullname, address)
self.key = telephone
def __repr__(self):
return f'Телефон: {self.key}, ФИО: {self.value[0]}, Адрес: {self.value[1]}'
if __name__ == '__main__':
db = TelephoneDB()
for add_person in (
Person('+70000000001', 'Иванов Иван Иванович', 'Ленина, 45, 23'),
Person('+70000000002', 'Прекрасная Елена Павловна', 'Кутузова, 6, 123'),
Person('+70000000003', 'Вольная Ольга Александровна', 'Парковая, 50, 82'),
Person('+70000000004', 'Гордый Михаил Львович', 'Центральный, 142, 73'),
):
try:
db.add(add_person)
print('Add success:', add_person)
except Exception as e:
print(type(e), add_person, file=stderr)
for exist_person in (
Person('+70000000002', 'Прекрасная Елена Павловна', 'Кутузова, 6, 123'),
Person('+70000000004', 'Гордый Михаил Львович', 'Центральный, 142, 73'),
):
try:
db.add(exist_person)
print('Add exist:', exist_person)
except Exception as e:
print(e, exist_person, file=stderr)
for find_person in (
'Ольга',
'Ивано',
'Центральный',
'+70000000002',
'вна',
):
try:
p = db.find(find_person)
print(f'{find_person} find in:', p)
except Exception as e:
print(type(e), find_person, file=stderr)
for edit_person in (
Person('+70000000003', 'Невольная Мария Викторовна', 'Лесная, 12, 5'),
Person('+70000000003', 'ГыГыГыГЫ', 'Луговая, 26, 20'),
):
try:
db.edit(edit_person)
print(len(db.db), db.db)
except Exception as e:
print(type(e), edit_person, file=stderr)
for remove_person in (
'+70000000001',
'ГыГы',
):
try:
db.remove(remove_person)
print(len(db.db), db.db)
except Exception as e:
print(type(e), remove_person, file=stderr)
db.save()
| true |
38d4aa078ff32ea4bdf7ee454daf5316532b56f3 | Python | gentry-atkinson/pip_test | /segmentation_visuals.py | UTF-8 | 2,042 | 3.5625 | 4 | [] | no_license | #Author: Gentry Atkinson
#Organization: Texas University
#Data: 7 April, 2021
#Visualize the segmentation of a signal with 3 methods
#Method 1: regular breaks every 150 samples
#Method 2: 150 samples centered on a PIP
#Method 3: Divide segments at PIPs, resample each segment to 150
from scipy.signal import resample
from fastpip import pip
from matplotlib import pyplot as plt
import pandas
import random
if __name__ == "__main__":
instances = pandas.read_csv('pip_test_data.csv')
print('Keys: ', instances.keys())
print('D types: ', instances.dtypes)
print('Number of instances: ', len(instances['samples']))
lucky_winner = random.randint(0,5000)
s = instances['samples'][lucky_winner]
s = s[1:-2]
s = s.replace('\n', '')
s = s.replace('[', '')
s = s.replace(']', '')
s = [float(x) for x in s.split(' ') if x]
#Plot the segment with divisions every 150 samples
reg_divisions = list(range(150, len(s), 150))
plt.plot(range(len(s)), s)
for x in reg_divisions:
plt.axvline(x=x, color='red')
plt.savefig('imgs/plot_marked_every_150.pdf')
#Plot the segment with PIPs shown as red lines
plt.figure()
NUM_SEGMENTS = len(s)//150
pips = pip([(i, j) for i,j in enumerate(s)], NUM_SEGMENTS+1, distance='vertical') #n+1 pips create n segments
trim_pips = pip([(i, j) for i,j in enumerate(s)], NUM_SEGMENTS+2, distance='vertical')
trim_pips = trim_pips[1:-1] #remove start and end points
plt.plot(range(len(s)), s)
for (x, y) in trim_pips:
plt.axvline(x=x, color='red')
plt.savefig('imgs/plot_marked_with_pips.pdf')
#Plot segments produced by 3 methods
plt.figure()
plt.plot(range(150,300, 1), s[150:300])
plt.savefig('imgs/one_seg_by_m1.pdf')
plt.figure()
plt.plot(range(150), s[trim_pips[1][0]-75:trim_pips[1][0]+75])
plt.savefig('imgs/one_seg_by_m2.pdf')
plt.figure()
plt.plot(range(150), resample(s[pips[1][0]:pips[2][0]], 150))
plt.savefig('imgs/one_seg_by_m3.pdf')
#plt.show()
| true |
21f999112a80a9df9255b6b828a36ad35cb5c9c9 | Python | vishakha2907/Assignments | /Palindrome/Palindrome.py | UTF-8 | 342 | 3.890625 | 4 | [] | no_license | def rev(temp):
remainder = 0
reverse = 0
while(temp != 0):
remainder = temp % 10
reverse = reverse * 10 + remainder
temp = int(temp / 10)
return reverse
#main() function
n = int(input("Enter a number: "))
temp = n
res = rev(temp)
if (res == n):
print(" Number is Palindrome")
else:
print("Number is not Palindrome")
| true |
92cfa90e905543b414d503fa44d065835deb9154 | Python | JuanchoVoltio/python-2021-III | /Taller04/ejemplo-while_break_continue.py | UTF-8 | 369 | 3.671875 | 4 | [] | no_license |
first_question = '¿Qué edad tiene? '
second_question = '¿En qué ciudad vive? '
age = 0
city = ''
while not ( age > 18 and city == 'Medellín' ):
age = int ( input ( first_question ))
if( age < 18 ):
continue
city = input ( second_question )
#pregunta 3
#pregunta 4
else :
print ( '¡Encontré a la persona!' )
| true |
9166b5ffbf21cd941a06a7c3f4219ae5ee15af25 | Python | Jeonseoghyeon/APR | /백준/삼성A형 대비/1260(BFS,DFS).py | UTF-8 | 746 | 2.875 | 3 | [] | no_license | def dfs (start,visit):
visit.append(start)
for i in range(N+1):
if arr[start][i] == 1 and i not in visit:
visit = dfs(i,visit)
return visit
def bfs (start):
queue = [start]
visit = [start]
while queue:
c = queue.pop(0)
for i in range(N+1):
if arr[c][i] and i not in visit:
visit.append(i)
queue.append(i)
return visit
N,M,V = list(map(int,input().split()))
arr = [[0]*(N+1) for ar in range(N+1)]
# visit = [[0]*(N+1) for ar in range(N+1)]
for i in range(M):
x,y = list(map(int,input().split()))
arr[x][y] = 1
arr[y][x] = 1
# for arrr in range(N+1):
# print(arr[arrr])
start =[V]
print(*dfs(V,[]))
print(*bfs(V))
| true |
d6fdcf359f60ad2d07ecd46409eb96a99ee47f7f | Python | alenthomas/days_between_dates | /dBd.py | UTF-8 | 920 | 3.5625 | 4 | [
"MIT"
] | permissive | import calendar
import time
_months = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31,
9:30, 10:31, 11:30, 12:31}
def days_in_month(month, year, leap=False):
if month == 2:
if calendar.isleap(year):
return 29
return _months[month]
def find(d1, m1, y1, d2, m2, y2, count=0):
if (y1 == y2 and m1 == m2):
return count + d2 - d1
count += days_in_month(m1, y1) - d1 + 1
if (m1 == 12):
y1 += 1
m1 = 1
else:
m1 += 1
return find(1, m1, y1, d2, m2, y2, count)
if __name__ == "__main__":
start_time = time.time()
print("days:", find(5, 5, 2017, 14, 6, 2017))
print("days:", find(23, 4, 2017, 24, 8, 2017))
print("days:", find(26, 8, 1993, 11, 1, 2021))
print("days:", find(26, 8, 1993, 15, 6, 2017))
print("days:", find(24, 11, 1986, 21, 9, 2017))
print("avg time: {:.6f}".format(time.time() - start_time))
| true |
4a90c00464a7e9874457b10742e45c51374eb7ad | Python | TEC-2014092195/IC1802-introduccion-a-la-programacion | /Proyectos/Bracket v2/Clases.py | UTF-8 | 10,054 | 2.921875 | 3 | [
"MIT"
] | permissive | from tkinter import *
class Boton_Grupos(Button):
Grupo_Seleccionado=None
Entrada=None
lst_Otro1=None
lst_Otro2=None
lst_Otro3=None
lst_Otro4=None
lst_Otro5=None
lst_Otro6=None
lst_Otro7=None
def __init__(self,lista_grupo,entrada,otra1,otra2,otra3,otra4,otra5,otra6,otra7,parent,**kw):
Button.__init__(self,parent,kw)
self.Grupo_Seleccionado=lista_grupo
self.Entrada=entrada
self.lst_Otro0=lista_grupo
self.lst_Otro1=otra1
self.lst_Otro2=otra2
self.lst_Otro3=otra3
self.lst_Otro4=otra4
self.lst_Otro5=otra5
self.lst_Otro6=otra6
self.lst_Otro7=otra7
#-----AgregarEquipo-----
def AgregarEquipo(self):
if self.VerDuplicados() == True:
messagebox.showwarning("Bracket Mundial","Equipo Duplicado\nIngrese otro nombre diferente")
self.Entrada.set("")
else:
lista_seleccionada = list(self.Grupo_Seleccionado.get(0,END))
if self.Entrada.get() != "":
if len(lista_seleccionada) <= 3:
self.Grupo_Seleccionado.insert( END , self.Entrada.get() )
self.Entrada.set("")
else:
messagebox.showwarning("Bracket Mundial","El grupo esta lleno.\nSi no le complace el orden del grupo puede presionar en el boton limpiar")
print("El grupo esta lleno")
self.Entrada.set("")
else:
messagebox.showinfo("Bracket Mundial","Debe ingresar al menos un carácter que lo identifique")
#-----ValidarLista-----
def ValidarLista(self,lista):
if len(lista) != 0:
for i in range( len(lista) ):
if self.Entrada.get() == lista[i]:
return(True)
if len(lista) == 0:
return(False)
#------------------------------
def VerDuplicados(self):
bandera=False
listaOtro0=list( self.lst_Otro0.get(0,END) )
listaOtro1=list( self.lst_Otro1.get(0,END) )
listaOtro2=list( self.lst_Otro2.get(0,END) )
listaOtro3=list( self.lst_Otro3.get(0,END) )
listaOtro4=list( self.lst_Otro4.get(0,END) )
listaOtro5=list( self.lst_Otro5.get(0,END) )
listaOtro6=list( self.lst_Otro6.get(0,END) )
listaOtro7=list( self.lst_Otro7.get(0,END) )
if self.ValidarLista(listaOtro0)==True:
bandera=True
if self.ValidarLista(listaOtro1)==True:
bandera=True
if self.ValidarLista(listaOtro2)==True:
bandera=True
if self.ValidarLista(listaOtro3)==True:
bandera=True
if self.ValidarLista(listaOtro4)==True:
bandera=True
if self.ValidarLista(listaOtro5)==True:
bandera=True
if self.ValidarLista(listaOtro6)==True:
bandera=True
if self.ValidarLista(listaOtro7)==True:
bandera=True
#------If bandera-----
if bandera==True:
return (True)
else:
return (False)
#print("Ya esta el quipo")
##########################################
##########################################
##########################################
class Limpiar():
def LimpiarLista(lista):
lista.delete(0,END)
##########################################
##########################################
##########################################
class Boton_Confirmacion(Button):
lst_GrupoA=None
lst_GrupoB=None
lst_GrupoC=None
lst_GrupoD=None
lst_GrupoE=None
lst_GrupoF=None
lst_GrupoG=None
lst_GrupoH=None
Mensaje=""
def __init__(self,lstgrupoA,lstgrupoB,lstgrupoC,lstgrupoD,lstgrupoE,lstgrupoF,lstgrupoG,lstgrupoH,parent,**kw):
Button.__init__(self,parent,kw)
self.lst_GrupoA=lstgrupoA
self.lst_GrupoB=lstgrupoB
self.lst_GrupoC=lstgrupoC
self.lst_GrupoD=lstgrupoD
self.lst_GrupoE=lstgrupoE
self.lst_GrupoF=lstgrupoF
self.lst_GrupoG=lstgrupoG
self.lst_GrupoH=lstgrupoH
#-------------VALIDAR LISTAS-----------------------------------
def ValidarListas(self,v_main):
lista_valores_A = list( self.lst_GrupoA.get(0,END) )
lista_valores_B = list( self.lst_GrupoB.get(0,END) )
lista_valores_C = list( self.lst_GrupoC.get(0,END) )
lista_valores_D = list( self.lst_GrupoD.get(0,END) )
lista_valores_E = list( self.lst_GrupoE.get(0,END) )
lista_valores_F = list( self.lst_GrupoF.get(0,END) )
lista_valores_G = list( self.lst_GrupoG.get(0,END) )
lista_valores_H = list( self.lst_GrupoH.get(0,END) )
bandera=False
self.Mensaje=""
if self.RevisarFaltantes(lista_valores_A,"Grupo A") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_B,"Grupo B") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_C,"Grupo C") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_D,"Grupo D") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_E,"Grupo E") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_F,"Grupo F") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_G,"Grupo G") == True:
bandera=True
else:
bandera=False
if self.RevisarFaltantes(lista_valores_H,"Grupo H") == True:
bandera=True
else:
bandera=False
if bandera==True:
messagebox.showinfo("Bracket Mundial",self.Mensaje) #True es completo // False es faltan
file = open("Template.txt", 'w')
#-----Grupo A-----
file.write("Grupo A")
file.write(",")
for i in range(4):
file.write(lista_valores_A[i])
file.write(",")
file.write("\n")
#-----Grupo B-----
file.write("Grupo B")
file.write(",")
for i in range(4):
file.write(lista_valores_B[i])
file.write(",")
file.write("\n")
#-----Grupo C-----
file.write("Grupo C")
file.write(",")
for i in range(4):
file.write(lista_valores_C[i])
file.write(",")
file.write("\n")
#-----Grupo D-----
file.write("Grupo D")
file.write(",")
for i in range(4):
file.write(lista_valores_D[i])
file.write(",")
file.write("\n")
#-----Grupo E-----
file.write("Grupo E")
file.write(",")
for i in range(4):
file.write(lista_valores_E[i])
file.write(",")
file.write("\n")
#-----Grupo F-----
file.write("Grupo F")
file.write(",")
for i in range(4):
file.write(lista_valores_F[i])
file.write(",")
file.write("\n")
#-----Grupo G-----
file.write("Grupo G")
file.write(",")
for i in range(4):
file.write(lista_valores_G[i])
file.write(",")
file.write("\n")
#-----Grupo H-----
file.write("Grupo H")
file.write(",")
for i in range(4):
file.write(lista_valores_H[i])
file.write(",")
file.write("\n")
file.close()
#-----Leer Archivo-----
file = open("Template.txt", 'r')
lista_archivo=file.readlines()
for i in range(len(lista_archivo)):
lista_linea=lista_archivo[i].split(",")
print(len(lista_linea))
print(lista_linea)
print("GRUPO: ",lista_linea[0])
file.close()
#ventana.withdraw()
import Admin_Bracket_Ganador
Admin_Bracket_Ganador.ClaseBracketGanador.VentanaBracketGanador(v_main)
else:
messagebox.showwarning("Bracket Mundial",self.Mensaje)
def RevisarFaltantes(self,lista,nom_grupo):
#---------------------------
if len(lista) == 4:
print("La longitud de lista del ",nom_grupo," esta buena")
self.Mensaje+="El "
self.Mensaje+=nom_grupo
self.Mensaje+=" esta completo"
self.Mensaje+="\n"
return(True)
else:
faltante=4-len(lista)
print("Hacen falta ",faltante,"Equipos en la lista del ",nom_grupo)
self.Mensaje+="Hacen falta "
self.Mensaje+=str(faltante)
self.Mensaje+=" Equipos en la lista del "
self.Mensaje+=nom_grupo
self.Mensaje+="\n"
return(False)
| true |
9214b4111f945e548eb4d5736ef618692aa2f7f4 | Python | Edyta2801/Python-kurs-infoshareacademy | /code/Day_15/kod zajecia/hello.py | UTF-8 | 846 | 3.40625 | 3 | [] | no_license | import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
# wiadomosc wyswietlana
message = "Welcome"
# handler - funkcja wywołana na skutek jakiegos zdarzenia (eventu)
def click():
"""Handler for mouse click"""
global message
message = "Good job!"
def draw(canvas):
"""Handler przerysowujący okno"""
# wypisujemy wiadomosc na ekranie
canvas.draw_text(message, [50,112], 48, "Red")
# tworzymy okno
frame = simplegui.create_frame("Home", 300, 200)
# dodajemy przycisk do naszego okna, podajemy:
# napis na przycisku, oraz handler, który będzie uruchomiony po naci-
# snieciu przycisku
frame.add_button("Click me", click)
# ustawiamy handler, ktory bedzie wykonywany podczas każdego
# odświeżenia okna (w zalezności od sprzętu od 60 do 120 MHz)
frame.set_draw_handler(draw)
# uruchamiamy okno
frame.start()
| true |
94c6a0e4186158d20b2d68add6ec564b07bee40d | Python | Gleysson/RNA | /neural/search_grid.py | UTF-8 | 996 | 2.828125 | 3 | [] | no_license | class SearchGrid:
def __init__(self, type="classifier"):
self.etas = []
self.epochs = []
self.neurons = []
self.setValues(type)
def setValues(self, type):
if(type=='classifier'):
self.etas = [0.06, 0.08, 0.1 , 0.12]
self.epochs = [500, 500, 700, 1000, 1500, 2000]
self.neurons = [2,4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,28 ,30 ]
else:
self.etas = [0.001 , 0.005 , 0.008 , 0.01, 0.05, 0.08, 0.01]
self.epochs = [200, 500, 700, 1000, 1200, 1500, 2000, 3000]
self.neurons = [4, 6, 8, 10, 12, 14, 16, 20, 22, 25, 28, 30 ]
self.neuronsElm = [4, 6, 8, 10, 12, 14, 16, 20, 22, 25, 28, 30, 32, 34 ,36, 38, 40, 42, 44, 46, 48, 50 ]
def getEtas(self):
return self.etas
def getEpochs(self):
return self.epochs
def getNeurons(self):
return self.neurons
def getNeuronsELM(self):
return self.neuronsElm
| true |
881101b7b98c840fce6151810ee94833b43b2d64 | Python | huangxi2000/tpshop2 | /scripts/test_login.py | UTF-8 | 1,103 | 2.59375 | 3 | [] | no_license | import os
import sys
sys.path.append(os.getcwd())
import pytest
import time
from base.read_yaml import ReadYaml
from base.get_driver import get_driver
from page.page_in import PageIn
def get_data():
res = ReadYaml("data_login.yaml").read_yaml()
list1 = []
for data in res.values():
list1.append((data.get("username"), data.get("password"), data.get("code")))
return list1
# 登录测试
class TestLogin():
def setup(self):
self.driver = get_driver()
self.page = PageIn(self.driver)
def teardown(self):
self.driver.quit()
@pytest.mark.parametrize("username, password, code", get_data())
def test_login(self, username, password, code):
main = self.page.page_in_pagemain()
main.open_url()
login = self.page.page_in_pagelogin()
# 点击首页登录
main.page_main_login_click()
# 登录页面输入
login.page_login_username(username)
login.page_login_password(password)
login.page_login_code(code)
login.page_login_btn()
time sleep(5)
| true |
47967c2e227aabd087a0b5bdbcfd79c8d46a3835 | Python | cr0cK/algorithms | /quicksort/list_comprehensions.py | UTF-8 | 445 | 3.578125 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*
from random import randint
def qsort1(list):
"""Quicksort using list comprehensions"""
if list == []:
return []
else:
pivot = list[0]
lesser = qsort1([x for x in list[1:] if x < pivot])
greater = qsort1([x for x in list[1:] if x >= pivot])
return lesser + [pivot] + greater
l = [randint(0, 100) for i in range(0, 10)]
r = qsort1(l)
print(r)
| true |
ccde62c0e25c12b0e05be9d4ce19580b46cf15ba | Python | noahadelstein/mathemagic | /sample_python/cardDeck (2013).py | UTF-8 | 2,706 | 4.28125 | 4 | [] | no_license | #-------------------------------------------------------------------------------
# Name: cardDeck.py
# Purpose: class Deck representing a deck of cards
# constructor - creates a new deck of 52 cards in standard order
# getCardList - returns list of cards in deck
# shuffle - randomizes the order of the cards
# dealCard - returns a single card from the top of the deck,
# removes it from the deck
# cardsLeft - returns the number of cards in the deck
#
# Author: Adrienne Sands
#
# Created: 21/05/2013
# Copyright: (c) Adrienne Sands 2013
#-------------------------------------------------------------------------------
from card import Card
from cardSort import orderCardStringList, createCardList
import random
class Deck:
def __init__(self):
deckStringList = []
for i in ['s','h','c','d']:
for j in range(1,14):
deckStringList.append((j,i))
#newDeckStringList = orderCardStringList(deckStringList)
#print(newDeckStringList)
self.deckStringList = deckStringList
self.deckList = createCardList(deckStringList)
def getCardStringList(self):
return self.deckStringList
def getCardList(self):
return self.deckList
def shuffle(self):
deckStringList = self.deckStringList
shuffledList = []
randList = list(range(self.cardsLeft()))
random.shuffle(randList)
for i in randList:
shuffledList.append(deckStringList[i])
self.deckStringList = shuffledList
self.deckList = createCardList(shuffledList)
def dealCard(self):
self.deckStringList = self.deckStringList[1:] #remove element from string list
return self.deckList.pop(0)
#uses deckStringList vs deckList for performance
def cardsLeft(self):
return len(self.deckStringList)
def test():
#tests deck creation
testDeck = Deck()
print("Current cards in deck:\n",testDeck.getCardList())
print("Cards left: ",testDeck.cardsLeft())
#tests dealing
print(testDeck.dealCard())
print(testDeck.getCardList())
print("Cards left: ",testDeck.cardsLeft())
#tests shuffling
testDeck.shuffle()
print(testDeck.dealCard())
print('Should be shuffled: ',testDeck.getCardList())
def main():
print("This program deals out a sequence of n cards from a shuffled deck")
n = int(input("How many cards do you want? "))
deck = Deck()
deck.shuffle()
hand = []
for i in range(n):
hand.append(deck.dealCard())
print("Here are your cards: ",hand)
if __name__ == '__main__':
main()
| true |
8246f286ecb2ca85f2b347fe109ea1e197542d76 | Python | chantigit/pythonbatch1_june2021data | /Python_9to10_June21Apps/project1/listapps/app3.py | UTF-8 | 298 | 3.875 | 4 | [] | no_license | #Iterable & Iterator (next() & iter() functions)
#Preparing iterable using list
setA={10,2,30,4,50}
#Preparing iterator
elements=iter(setA)
print(next(elements)) #10
print(next(elements)) #2
print(next(elements)) #30
print(next(elements)) #4
print(next(elements)) #50
print(next(elements)) # | true |