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 |
---|---|---|---|---|---|---|---|---|---|---|---|
d3e90712532f223c731261ae02a9cc44e99a4012
|
Python
|
StBogdan/PythonWork
|
/Leetcode/1396.py
|
UTF-8
| 1,598 | 3.578125 | 4 |
[] |
no_license
|
from collections import defaultdict
from typing import Dict, Tuple
# Name: Design Underground System
# Link: https://leetcode.com/problems/design-underground-system/
# Method: 2 dictionaries, started journeys and a dict of pairwise of averages
# Time: O(1)
# Space: O(n)
# Difficulty: Medium
Id = int
Station = str
Time = int
Journey = Tuple[Station, Station]
class UndergroundSystem:
def __init__(self):
self.completed_journeys: Dict[Journey, Tuple[int, int]] = defaultdict(
lambda: (0, 0)
)
self.started_journey: Dict[Id, Tuple[Station, Time]] = {}
def checkIn(self, id: Id, station_name: Station, start_time: Time) -> None:
self.started_journey[id] = (station_name, start_time)
def checkOut(self, id: int, station_name: str, end_time: int) -> None:
end_station = station_name
start_station, start_time = self.started_journey[id]
del self.started_journey[id]
self._update_travel_time((start_station, end_station), end_time - start_time)
def _update_travel_time(
self, journey: Tuple[Station, Station], new_journey_time: int
):
start_s, end_s = journey
avg_now, journeys = self.completed_journeys[(start_s, end_s)]
new_avg = (avg_now * journeys + new_journey_time) / (journeys + 1)
self.completed_journeys[(start_s, end_s)] = (new_avg, journeys + 1)
def getAverageTime(self, start_station: str, end_station: str) -> float:
average_travel_time, _ = self.completed_journeys[(start_station, end_station)]
return average_travel_time
| true |
bc4316cb46b2daf90827c1b1e08849ab14a3c94c
|
Python
|
DonaldButters/Pytho134
|
/module3/strings1.py
|
UTF-8
| 108 | 3.203125 | 3 |
[] |
no_license
|
x = 'Peter Parker in Spiderman'
x = str.capitalize('Peter Parker in Spiderman')
print (x)
word= 'Peter Parker in Spiderman'
print(word.find('er',1))
| true |
8ad18853fd5d0332a544a45fdf8afa9e89caddf1
|
Python
|
WikimediaOIT/wikiosk
|
/osx-hide-mouse.py
|
UTF-8
| 802 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python
"""
Move mouse to edge of screen
"""
# osx libraries for mouse control and display sizes
# mouse control
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGHIDEventTap
# display size
from Quartz import CGDisplayBounds
from Quartz import CGMainDisplayID
def movemouse(x, y):
theEvent = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x,y), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
mainMonitor = CGDisplayBounds(CGMainDisplayID())
x=mainMonitor.size.width
y=mainMonitor.size.height
# Move mouse (must be an onscreen pixel thus, -1s)
movemouse(x-2,y-10)
| true |
b8ac538a5eb31d6e0118b7b77c67762641a9f0f8
|
Python
|
feng1510/self_driving_car_nd
|
/term1/P4-Advanced-Lane-Lines/tools/find_perspective_transform.py
|
UTF-8
| 6,435 | 2.96875 | 3 |
[] |
no_license
|
"""Helper tool to find perspective transform for birds-eye-view.
Let the user select perspective source points in an image with lanes lines,
and then measure lines dash length and lane width, which provides for
calculation of perspective transformation matrix. The calculation assumes
lane properties as in the USA, see constants section below.
The output from this tool is a pickle file with the transformation matrix
together with the x and y pixel resolution in meters.
"""
import numpy as np
import cv2
from moviepy.editor import VideoFileClip
import pickle
import sys
sys.path.append("../src/")
# Constants
dash_length_in_meters = 3.048 # 10 feet
lane_width_in_meters = 3.6576 # 12 feet
expected_visual_length_in_meters = 30.0 # Defines the transformed view length.
expected_visual_width_in_meters = 10.0 # Defines the transformed view width.
# mouse callback function
def get_coord(event, x, y, flags, param):
global coords
global done
global output_image
global temp_image
if event == cv2.EVENT_LBUTTONUP:
coords.append((x, y))
if len(coords) > 1:
cv2.line(output_image, coords[-2], coords[-1], color=(0, 0, 255), thickness=1)
temp_image = np.copy(output_image)
if event == cv2.EVENT_MOUSEMOVE:
if len(coords) > 0:
cv2.line(temp_image, coords[-1], (x, y), color=(0, 0, 255), thickness=1)
def load_camera_calibration():
with open("../src/calibration.p", 'rb') as fid:
return pickle.load(fid)
calibration = load_camera_calibration()
# Get a frame 17 seconds into the sequence, where the road is fairly straight.
input_image = VideoFileClip('../input/project_video.mp4').get_frame(17)
input_image = calibration.undistort(input_image)
input_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR)
h, w, _ = input_image.shape
# Show image and let user select four coordinates for perspective transform.
draw_win = 'Select source points for perspective transform'
cv2.namedWindow(draw_win)
cv2.setMouseCallback(draw_win, get_coord)
output_image = np.copy(input_image)
temp_image = np.copy(output_image)
coords = []
while 1:
cv2.imshow(draw_win, temp_image)
cv2.waitKey(20)
if len(coords) >= 4:
break
cv2.line(output_image, coords[-1], coords[0], color=(0, 0, 255), thickness=1)
cv2.imshow(draw_win, output_image)
cv2.imwrite('../output/perspective_source.png', output_image)
src = np.array([list(coord) for coord in coords]).astype(np.float32)
dst_width = 500
dst_height = h
dst = np.float32([[(w - dst_width) // 2, h],
[(w - dst_width) // 2, h - dst_height],
[(w + dst_width) // 2, h - dst_height],
[(w + dst_width) // 2, h]])
# Temporary transform used for measurements.
transformation_matrix = cv2.getPerspectiveTransform(src, dst)
transformed_image = cv2.warpPerspective(input_image, transformation_matrix, (w, h), flags=cv2.INTER_LINEAR)
coords = []
output_image = np.copy(transformed_image)
temp_image = np.copy(transformed_image)
measure_win = 'Measure dash length and lane width'
cv2.namedWindow(measure_win)
cv2.setMouseCallback(measure_win, get_coord)
while 1:
cv2.imshow(measure_win, temp_image)
cv2.waitKey(20)
if len(coords) >= 2:
break
cv2.imshow(measure_win, output_image)
assert(len(coords) == 2)
assert(abs(coords[1][0] - coords[0][0]) <= 2) # The lane line should be vertical after transformation.
dash_length_in_pixels = ((coords[1][0] - coords[0][0])**2 + (coords[1][1] - coords[0][1])**2) ** (1 / 2)
print(f"dash length {dash_length_in_pixels:.03f} pixels")
coords = []
temp_image = np.copy(output_image)
while 1:
cv2.imshow(measure_win, temp_image)
cv2.waitKey(20)
if len(coords) >= 2:
break
cv2.imshow(measure_win, output_image)
cv2.imwrite('../output/perspective_measurments.png', output_image)
assert(len(coords) == 2)
assert(abs(coords[1][1] - coords[0][1]) <= 2) # The shortest distance between lanes should be horizontal.
lane_width_in_pixels = ((coords[1][0] - coords[0][0])**2 + (coords[1][1] - coords[0][1])**2) ** (1 / 2)
print(f"lane width {lane_width_in_pixels:.03f} pixels")
x_meter_per_pixel = lane_width_in_meters / lane_width_in_pixels
y_meter_per_pixel = dash_length_in_meters / dash_length_in_pixels
visual_length_in_meters = h * y_meter_per_pixel
visual_width_in_meters = w * x_meter_per_pixel
print(f"visual length {visual_length_in_meters:.03f} meters")
print(f"visual width {visual_width_in_meters:.03f} meters")
# Adjust transform according to expected visual range.
dst_width *= visual_width_in_meters / expected_visual_width_in_meters
dst_height *= visual_length_in_meters / expected_visual_length_in_meters
dst = np.float32([[(w - dst_width) // 2, h],
[(w - dst_width) // 2, h - dst_height],
[(w + dst_width) // 2, h - dst_height],
[(w + dst_width) // 2, h]])
transformation_matrix = cv2.getPerspectiveTransform(src, dst)
inv_transformation_matrix = cv2.getPerspectiveTransform(dst, src)
final_transformed_image = cv2.warpPerspective(input_image, transformation_matrix, (w, h), flags=cv2.INTER_LINEAR)
result_win = 'Final perspective'
cv2.namedWindow(result_win)
cv2.imshow(result_win, final_transformed_image)
cv2.imwrite('../output/perspective_result.png', final_transformed_image)
y_meter_per_pixel *= expected_visual_length_in_meters / visual_length_in_meters
x_meter_per_pixel *= expected_visual_width_in_meters / visual_width_in_meters
visual_length_in_meters = h * y_meter_per_pixel
visual_width_in_meters = w * x_meter_per_pixel
print("transformation matrix", transformation_matrix)
print("inv_transformation_matrix", inv_transformation_matrix)
print(f"x resolution {x_meter_per_pixel:.03f} meters/pixel")
print(f"y resolution {y_meter_per_pixel:.03f} meters/pixel")
print(f"adjusted visual length {visual_length_in_meters:.03f} meters")
print(f"adjusted visual width {visual_width_in_meters:.03f} meters")
with open('../output/perspective_transform.p', 'wb') as fid:
output = {
"transformation_matrix": transformation_matrix,
"inv_transformation_matrix": inv_transformation_matrix,
"x_meter_per_pixel": x_meter_per_pixel,
"y_meter_per_pixel": y_meter_per_pixel,
"visual_length_in_meters": visual_length_in_meters,
"visual_width_in_meters": visual_width_in_meters
}
pickle.dump(output, fid)
cv2.waitKey()
cv2.destroyAllWindows()
| true |
906946854561c55fe142abd380f478263edd32b8
|
Python
|
ali-jozaghi/app
|
/src/common/validators.py
|
UTF-8
| 381 | 3.09375 | 3 |
[] |
no_license
|
import re
def is_none(value) -> bool:
return value is None
def empty_or_none_string(value) -> bool:
return is_none(value) or (str(value).strip() == "")
def not_int(value) -> bool:
return is_none(value) or not isinstance(value, int)
def not_valid_email(value) -> bool:
return is_none(value) or not bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", value))
| true |
0af790dbed8a3d175a01ea7e9601db36d5d73554
|
Python
|
ZeroPage/algorithm_study2013
|
/hashing/yeongjuncho.py
|
UTF-8
| 100 | 2.53125 | 3 |
[] |
no_license
|
#Skywave
data = raw_input().split('$')
print int(data[0][::-1]) + int(data[2][::-1]) + int(data[1])
| true |
5dffaabdc1f6369217dbe604d441a9f0b6083a8f
|
Python
|
josueibecerra/Hippotherapy-Simulator-Code
|
/feedbackloop.py
|
UTF-8
| 1,744 | 3.15625 | 3 |
[] |
no_license
|
import RPi.GPIO as GPIO
import time
rpm = 0
power_output=0
sensor = 40 # define the GPIO pin our sensor is attached to
sample = 20 # how many half revolutions to time
count = 0
start = 0
end = 0
desired_rpm = 1500
GPIO.setmode(GPIO.BOARD) # set GPIO numbering system to BOARD
GPIO.setup(sensor, GPIO.IN) # set our sensor pin to an input
GPIO.setup(7, GPIO.OUT)
p= GPIO.PWM(7, 207)
p.start(0)
def set_start():
global start
start = time.time()
def set_end():
global end
end = time.time()
def get_rpm(c):
global count # delcear the count variable global so we can edit it
if not count:
set_start() # create start time
count = count + 1 # increase counter by 1
else:
count = count + 1
if count == sample:
global rpm
set_end() # create end time
delta = end - start # time taken to do a half rotation in seconds
delta = delta / 60 # converted to minutes
rpm = (sample / delta) / 2 # converted to time for a full single rotation
print(rpm)
count = 0 # reset the count to 0
GPIO.add_event_detect(sensor, GPIO.RISING,
callback=get_rpm) # execute the get_rpm function when a HIGH signal is detected
try:
while True: # create an infinite loop to keep the script running
if desired_rpm >= rpm and power_output<100:
power_output=power_output+1
p.ChangeDutyCycle(power_output)
time.sleep(0.5)
if desired_rpm <= rpm and power_output>0:
power_output=power_output-1
p.ChangeDutyCycle(power_output)
time.sleep(0.5)
except KeyboardInterrupt:
print('Quit')
GPIO.cleanup()
pass
p.stop()
| true |
b37ce7dccb6d42e6b23d4633b700db583c3d967c
|
Python
|
lkreidberg/WASP33_HST12495
|
/multiply_sines_bad/vis_1/fit_funcs/models/sine2.py
|
UTF-8
| 349 | 2.515625 | 3 |
[] |
no_license
|
import sys
sys.path.insert(0,'..')
from read_data import Data
import numpy as np
def sine2(t, data, params):
a1, omega1, phi1, a2, omega2, phi2 = params
#FIXME data.t_vis won't work if there are multiple visits
return ( 1. + a1*np.sin(omega1*data.t_vis + phi1) ) * \
( 1. + a2*np.sin(omega2*data.t_vis + phi2) )
| true |
c1225dc7d69d1134ad94a7d79b07bb8a912f0a9d
|
Python
|
HodaeSsi/Algorithm
|
/패스트캠퍼스_유형별문제풀이(인강)/백준1920_수찾기_PY.py
|
UTF-8
| 193 | 2.890625 | 3 |
[] |
no_license
|
N = int(input())
n = set(map(int, input().split(' ')))
M = int(input())
m = list(map(int, input().split(' ')))
for i in m:
if i in n:
print(1)
elif i not in n:
print(0)
| true |
71d3d2c465f04f2580bdeb82143a76fdd995bd0d
|
Python
|
XuYan/u_programming_language
|
/fundamental/fsm_simulator.py
|
UTF-8
| 469 | 3.203125 | 3 |
[] |
no_license
|
# FSM Simulation
edges = {(1, 'a') : 2,
(2, 'a') : 2,
(2, '1') : 3,
(3, '1') : 3}
accepting = [3]
def fsmsim(string, current, edges, accepting):
if string == "":
return current in accepting
else:
letter = string[0]
if (current, letter) not in edges:
return False
return fsmsim(string[1:], edges[(current, letter)], edges, accepting)
#print fsmsim("aaa111",1,edges,accepting)
# >>> True
| true |
9aec7c84f7c6e5535bb64ffdbbc97c7059143c97
|
Python
|
BurntBrunch/pydiskmonitor
|
/src/parse.py
|
UTF-8
| 1,839 | 3.359375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
from pyparsing import Word, Optional, ZeroOrMore, alphanums, Literal, StringEnd
def parse_rule(rule):
""" Given a rule string, return a key-value pair """
result = []
def got_pair(tokens):
result.append(tuple(tokens[-2:]))
possibleChars = alphanums+"_-/^&*'"
keyOrValue = Optional(Literal('"').suppress()) + Word(possibleChars) + Optional(Literal('"').suppress())
keyValuePair = keyOrValue + Literal("=").suppress() + keyOrValue
keyValuePair.setParseAction(got_pair)
line = keyValuePair + ZeroOrMore(Literal(',').suppress() + keyValuePair) + StringEnd()
try:
line.parseString(rule)
return result
except:
return None
def check_rule(rule, obj):
""" Rule is a list of key-value tuples,
obj is the object to check against """
if rule is None:
return False
def key_check((k, v)):
if k in obj:
return obj[k] == v
elif hasattr(obj, k):
return getattr(obj,k) == v
else:
return False
return all(map(key_check, rule))
def check_rules(rules, obj):
""" Rules is a list of strings,
obj is the object to check against """
return any(map(lambda rule: check_rule(parse_rule(rule), obj), rules))
if __name__ == "__main__":
t = ['a = b, c = d',
'a=b,c=d,e=f',
'a = c,',
'a = d, b =']
for test in t:
try:
print test,
print parse_rule(test)
except:
print "failed"
obj = { 'a': 'b', 'e': 'f' }
print obj
t = ['a=b',
'a=b,c=d',
'a=b,c=d,e=f',
'a=b,e=f']
for test in t:
try:
print test,
print check_rules((test,), obj)
except:
print "failed"
| true |
8c14175fcf6f2e8e8ae6cae79fa94a34b5677870
|
Python
|
MengyingGIRL/python-100-days-learning
|
/Day04/for3.py
|
UTF-8
| 243 | 3.65625 | 4 |
[] |
no_license
|
'''
输入非负整数n计算n!
@Time : 2020/1/8 9:21
@Author : wangmengying
@File : for3.py
'''
n = int(input('请输入非负整数:'))
if n <= 0:
print('输入错误!')
result = 1
for i in range(1,n+1):
result *= i
print(result)
| true |
592a0700088b081b926c51d00b59e23f8b726cfd
|
Python
|
shamanu4/biltv
|
/src/app/tv/roll.py
|
UTF-8
| 1,721 | 3.359375 | 3 |
[] |
no_license
|
# To change this template, choose Tools | Templates
# and open the template in the editor.
class Roll():
def __init__(self):
self.cash = 100
self.bid = [None,None]
self.black = (1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36)
self.red = (2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35)
self.odd = (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35)
self.even = (2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36)
def s(self,bid,sum):
self.bid=[bid,sum]
self.cash -= sum
print "Bid placed: %s sum %s. cash: %s" % (self.bid[0],self.bid[1],self.cash)
def win(self,multiplier):
self.cash += self.bid[1]*multiplier
print "You WIN! %s. cash: %s" % (self.bid[1]*multiplier,self.cash)
def roll(self):
import random
rand = random.randrange(0, 37)
color= "ZERO"
parity = "ZERO"
if rand in self.red:
color="RED"
if self.bid[0] == 'r':
self.win(2)
if rand in self.black:
color="BLACk"
if self.bid[0] == 'b':
self.win(2)
if rand in self.odd:
parity="ODD"
if self.bid[0] == 'o':
self.win(2)
if rand in self.even:
parity="EVEN"
if self.bid[0] == 'e':
self.win(2)
if color == 'ZERO':
if self.bid[0] == 'z' or self.bid == 0:
self.win(36)
if self.bid[0] == rand:
self.win(36)
print "%s [%s] [%s]" % (rand,color,parity)
self.bid = [None,None]
| true |
a8c500d66b3d9699d6acb16648a2cedbf539c326
|
Python
|
spsrathor/Data-Structures-By-Python
|
/Array/Minimum distance between two numbers.py
|
UTF-8
| 412 | 2.90625 | 3 |
[] |
no_license
|
def minDist(arr, n, x, y):
# Code here
r=-1
if (x in arr) and (y in arr):
xl = []
diff = []
for i in range(len(arr)):
if x==arr[i]:
xl.append(i)
for i in range(len(arr)):
if y==arr[i]:
temp = xl
temp = [abs(i-yi) for yi in temp]
diff.extend(temp)
r=min(diff)
return r
| true |
d982e4da7ea96f2c134b9ae6373c372eff2ba920
|
Python
|
nmala001/restaurant_menu_project
|
/app.py
|
UTF-8
| 230 | 2.9375 | 3 |
[] |
no_license
|
import sqlite3
connection = sqlite3.connect("restaurantmenu.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM restaurant")
results = cursor.fetchall()
for r in results:
print(r)
cursor.close()
connection.close()
| true |
adbe1698891adb232526a84be03ecdc0be400d56
|
Python
|
kjappelbaum/oximachine_featurizer
|
/run/run_featurization.py
|
UTF-8
| 536 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
"""Run the featurization on one structure"""
import click
import numpy as np
from pymatgen import Structure
from oximachine_featurizer import featurize
@click.command("cli")
@click.argument("structure")
@click.argument("outname")
def main(structure: str, outname: str):
"""CLI function"""
structure = Structure.from_file(structure)
feature_matrix, _, _ = featurize(structure)
np.save(outname, feature_matrix)
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter
| true |
6beaa6b424fdafd9a9911cb291f0d039bd58a1a9
|
Python
|
tejaskannan/block-sparse-dnn
|
/blocksparsednn/analysis/energy_comparison.py
|
UTF-8
| 2,107 | 2.875 | 3 |
[] |
no_license
|
import csv
import os.path
import numpy as np
from argparse import ArgumentParser
from collections import defaultdict
from blocksparsednn.utils.file_utils import iterate_dir
NUM_SAMPLES = 15
BLOCK_DIAG = 'block_diag'
SPARSE = 'sparse'
DENSE = 'dense'
def get_energy(input_path: str) -> float:
energy = 0.0
with open(input_path, 'r') as fin:
reader = csv.reader(fin, delimiter=',')
for idx, line in enumerate(reader):
if idx > 0:
energy = float(line[-1]) # Energy in uJ
return energy / 1000.0
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--input-folder', type=str, required=True)
args = parser.parse_args()
# Get the results from bluetooth alone
bt_energy = get_energy(os.path.join(args.input_folder, 'bluetooth_alone.csv'))
energy_results = defaultdict(list)
for path in iterate_dir(args.input_folder, pattern='.*csv'):
energy = get_energy(path) # Energy in mJ
processing_energy = (energy - bt_energy) / NUM_SAMPLES
file_name = os.path.basename(path)
if file_name.startswith(BLOCK_DIAG):
energy_results[BLOCK_DIAG].append(processing_energy)
elif file_name.startswith(SPARSE):
energy_results[SPARSE].append(processing_energy)
elif file_name.startswith(DENSE):
energy_results[DENSE].append(processing_energy)
# Aggregate the results
sparse_avg = np.average(energy_results[SPARSE])
sparse_std = np.std(energy_results[SPARSE])
dense_avg = np.average(energy_results[DENSE])
dense_std = np.std(energy_results[DENSE])
block_avg = np.average(energy_results[BLOCK_DIAG])
block_std = np.std(energy_results[BLOCK_DIAG])
# Format the results in a table
print('Model & Energy (mJ) / Inference \\\\')
print('\\midrule')
print('Sparse & {0:.4f} (\\pm {1:.4f}) \\\\'.format(sparse_avg, sparse_std))
print('Dense & {0:.4f} (\\pm {1:.4f}) \\\\'.format(dense_avg, dense_std))
print('Block Diagonal & {0:.4f} (\\pm {1:.4f}) \\\\'.format(block_avg, block_std))
| true |
d3be0da2d59cf788a8e2a4a0ef22faaa9eca5a08
|
Python
|
mashbes/lesson27
|
/habrparse.py
|
UTF-8
| 1,261 | 2.625 | 3 |
[] |
no_license
|
import lxml.html as html
from urllib.request import urlopen
import requests
import json
main_domain_stat = 'https://habr.com/'
data = []
main_page = html.parse(urlopen(main_domain_stat)).getroot()
article_links = main_page.xpath(
'//li/article[contains(@class, "post")]/h2[@class="post__title"]/a[@class="post__title_link"]/@href')
for link in article_links:
article_page = html.parse(urlopen(link))
title = article_page.xpath('//article[contains(@class, "post")]/div[@class="post__wrapper"]/h1[contains(@class, "post__title")]/span/text()')
text = article_page.xpath('//article[contains(@class, "post")]/div[@class="post__wrapper"]/div[contains(@class, "post__body")]/'
'div[contains(@class, "post__text")]/text()')
images = article_page.xpath('//article[contains(@class, "post")]/div[@class="post__wrapper"]/div[contains(@class, "post__body")]/'
'div[contains(@class, "post__text")]/img/@src')
data.append({
'title': title[0],
'text' : text,
'images' : images
})
with open('article.json', 'w', encoding='utf-8') as jdata:
json.dump(data, jdata, sort_keys=True, indent=4, ensure_ascii=False)
| true |
80b8c5f119b6e60ad73fe0380aacc20e05ecf08d
|
Python
|
FrancescoPenasa/UNITN-CS-2018-Intro2MachineLearning
|
/exercise/exercise9.py
|
UTF-8
| 5,505 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 17:50:04 2019
@author: francesco
Given the iris dataset CSV file,
apply the k-nearest neighbors algorithm to all the elements of the dataset
using k ∈ {3, 5, 10, 20} and build the confusion matrix.
Using the confusion matrix, compute total precision, total accuracy and total recall.
TIPS:
total metrics correspond to the average of the relative metric computed on the elements of each class
when evaluating, do not include the point you are predicting in the neighbors (this would be cheating)
"""
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import sys
def euclidean_distance(s1,s2):
"""
Compute the Euclidean distance between two n-dimensional objects.
"""
tmpsum = 0
for index,value in enumerate(s1):
tmpsum += (s1[index]-s2[index])**2
return math.sqrt(tmpsum)
def find_distances(frame, newPoint):
"""
Find the distance between a point and all the points in a dataframe, and
sort the elements in ascending order.
"""
distances = []
# iterate over all rows in the dataframe
for index in range(frame.shape[0]):
# get all columns of a row (except the label)
point = frame.iloc[index,:-1]
# compute the distance, then save distance and label
# (use distance as first value)
distance = euclidean_distance(point, newPoint)
if distance != 0:
distances.append((distance, frame.iloc[index,-1]))
else:
distances.append((sys.maxsize, frame.iloc[index,-1]))
distances.sort()
return distances
def k_nn(frame, newPoint, colClass, k):
"""
Predict the class of a point by using the k-nearest neighbor algorithm on
the points of a dataframe.
"""
counts = []
# find all distances wrt the newPoint
dist = find_distances(frame, newPoint)
# find the nearest k points, extract their labels and save them in a list
labels = [label for distance,label in dist[:k]]
# for each class label, count how many occurrencies have been found
for label in frame[colClass].unique():
# save the number of occurrencies in a list of tuples (number, label)
counts.append((labels.count(label), label))
# sort the list in descending order, and use the first label of the tuples'
# list to make the prediction
counts.sort(reverse=True)
prediction = counts[0][1]
return prediction
def compute_accuracy(confusionMatrix):
"""
Compute accuracy based on a Confusion Matrix
with prediction on rows
and truth on columns.
"""
correct = 0
for elem in range(confusionMatrix.shape[0]):
correct += confusionMatrix[elem, elem]
tot = confusionMatrix.sum()
return correct / tot
def compute_precision(confusionMatrix):
"""
Compute precision based on a Confusion Matrix
with prediction on rows
and truth on columns.
precision = true positive / (true positive + false positive)
"""
precision = []
for i in range(confusionMatrix.shape[0]):
tot = 0
for j in range(confusionMatrix.shape[0]):
tot += confusionMatrix[i, j]
correct = confusionMatrix[i, i]
precision.append(correct/tot)
return precision
def compute_recall(confusionMatrix):
"""
Compute recall based on a Confusion Matrix
with prediction on rows
and truth on columns.
recall = true positive / (true positive + false negative)
"""
recall = []
for elem in range(confusionMatrix.shape[0]):
tot = 0
for j in range(confusionMatrix.shape[0]):
tot += confusionMatrix[j, elem]
correct = confusionMatrix[elem, elem]
recall.append(correct/tot)
return recall
def init_confusionMatrix(df, spec):
"""
Init confusion matrix with rows and columns based on the df[spec].unique()
"""
rows = 0
names = []
for name in df[spec].unique():
rows += 1
names.append(name)
confusionMatrix = [[0] * rows for x in range(rows)]
confusionMatrix = np.matrix(confusionMatrix)
return confusionMatrix,names
def k_nn_all(df, k, spec):
"""
k_nn on all the rows of the frame excluding the one tested
"""
confusionMatrix,names = init_confusionMatrix(df, spec)
for tested in range(df.shape[0]):
prediction = k_nn(df, df.iloc[tested], spec, k)
if prediction == df.iloc[tested,-1]:
i = names.index(prediction)
confusionMatrix[i,i] += 1
elif prediction != df.iloc[tested,-1]:
i = names.index(prediction)
j = names.index(df.iloc[tested,-1])
confusionMatrix[i,j] += 1
print(confusionMatrix)
print("k:" , k)
print("accuracy: ", compute_accuracy(confusionMatrix))
print("precision: ", compute_precision(confusionMatrix))
print("recall: ", compute_recall(confusionMatrix))
print("")
# --------------------------------------------------------------------------- #
df = pd.read_csv("iris.data", names = ["SepalLength","SepalWidth","PetalLength","PetalWidth","Class"])
#
#k_nn_all(df, 3, "Class")
#k_nn_all(df, 5, "Class")
#k_nn_all(df, 10, "Class")
k_nn_all(df, 20, "Class")
| true |
b2918b72727e3014e681b6e0b35fe840af6b439f
|
Python
|
cqlouis/MyoPS20-HNU
|
/stage_2/network_architectures.py
|
UTF-8
| 9,917 | 2.59375 | 3 |
[] |
no_license
|
''' Neural net architectures '''
from tensorflow.python.keras.layers import Input, LeakyReLU, BatchNormalization, \
Conv2D, concatenate, Activation, SpatialDropout2D, AveragePooling2D, Conv2DTranspose, Flatten, Dense, Conv2D, Lambda, Reshape, add, SeparableConv2D, MaxPooling2D, UpSampling2D, GlobalAveragePooling2D, GlobalMaxPooling2D, multiply
from tensorflow_addons.layers import GroupNormalization
from tensorflow.python.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import layers as KL
from tensorflow.python.keras.losses import binary_crossentropy, mean_absolute_error, huber_loss
from tensorflow.keras.regularizers import l2, l1 # l2:5e-4
import tensorflow as tf
import numpy as np
from skimage.filters import laplace
from tensorflow.nn import softmax_cross_entropy_with_logits
class DefineMnet:
"""This class defines the architecture for a U-NET and must be inherited by a child class that
executes various functions like training or predicting"""
def generator_convolution(self, x, number_of_filters, strides, use_batch_norm=False, use_group_norm=False, skip_x=None, use_seperate=False, use_dropout=True):
"""Convolution block used for generator"""
if skip_x is not None:
skip_x.append(x)
x = concatenate(skip_x)
if use_seperate == True:
x = SeparableConv2D(number_of_filters, self.filter_size, padding="same", kernel_initializer='he_normal', use_bias=False, depthwise_initializer='glorot_normal', pointwise_initializer='glorot_normal', depthwise_regularizer=l1(1e-6), pointwise_regularizer=l1(1e-6))(x)
else:
x = Conv2D(number_of_filters, self.filter_size, strides, padding="same", kernel_initializer='he_normal', use_bias=False, kernel_regularizer=l1(1e-6))(x)
if use_batch_norm:
x = GroupNormalization(groups=8, axis=3, trainable=False)(x)
if use_group_norm:
x = BatchNormalization()(x)
#x = self.channel_attention(x, number_of_filters) * x
#x = self.spatial_attention(x, number_of_filters) * x
x = LeakyReLU(alpha=0.2)(x)
if use_dropout:
x = SpatialDropout2D(0.2)(x)
return x
def channel_attention(self, x, number_of_filters, ratio=16):
gap = GlobalAveragePooling2D()(x)
gmp = GlobalMaxPooling2D()(x)
gap_fc1 = Dense(number_of_filters//ratio, kernel_initializer='he_normal', activation='relu')(gap)
gap_fc2 = Dense(number_of_filters, kernel_initializer='he_normal', activation='sigmoid')(gap_fc1)
gmp_fc1 = Dense(number_of_filters//ratio, kernel_initializer='he_normal', activation='relu')(gmp)
gmp_fc2 = Dense(number_of_filters, kernel_initializer='he_normal', activation='sigmoid')(gmp_fc1)
out = gap_fc2 + gmp_fc2
out = tf.nn.sigmoid(out)
out = Reshape((1, 1, number_of_filters))(out)
return out
def spatial_attention(self, x, number_of_filters):
gap = tf.reduce_mean(x, axis=3)
gmp = tf.reduce_max(x, axis=3)
out = tf.stack([gap, gmp], axis=-1)
out = Conv2D(1, self.filter_size, strides=self.stride_size, padding="same", use_bias=False)(out)
return out
def residual_blocks(self, x, number_of_filters, use_batch_norm=False, use_group_norm=True):
y = Conv2D(number_of_filters, self.filter_size, strides=self.stride_size, padding="same", use_bias=False)(x)
y = BatchNormalization(momentum=0.99, epsilon=0.001, trainable=False)(y)
y = LeakyReLU(alpha=0.2)(y)
y = Conv2D(number_of_filters, self.filter_size, strides=self.stride_size, padding="same", use_bias=False)(y)
y = self.channel_attention(y, number_of_filters) * y
y = self.spatial_attention(y, number_of_filters) * y
out = add([x,y])
out = LeakyReLU(alpha=0.2)(out)
return out
def concat_up_blocks(self, x, number_of_filters, strides, skip_x=None, use_dilate=False, use_batch_norm=False, use_group_norm=False):
if skip_x is not None:
skip_x.append(x)
x = concatenate(skip_x)
y = self.generator_convolution(x, number_of_filters, strides, use_seperate=True, use_batch_norm=use_batch_norm, use_group_norm=use_group_norm)
z = self.generator_convolution(y, number_of_filters, strides, use_seperate=True, use_batch_norm=use_batch_norm, use_group_norm=use_group_norm)
z = self.channel_attention(z, number_of_filters) * z
if use_dilate==False:
return z
z = add([y,z])
out = self.generator_convolution(z, number_of_filters, strides*2, use_batch_norm=use_batch_norm, use_group_norm=use_group_norm)
return out
def concat_down_blocks(self, x, number_of_filters, strides, skip_x=None, use_batch_norm=False, use_group_norm=True):
if skip_x is not None:
skip_x.append(x)
x = concatenate(skip_x)
y = self.generator_convolution(x, number_of_filters, strides, use_seperate=False, use_batch_norm=use_batch_norm, use_group_norm=use_group_norm)
#y = concatenate([x,y])
z = self.generator_convolution(y, number_of_filters, strides, use_seperate=False, use_batch_norm=use_batch_norm, use_group_norm=use_group_norm)
z = self.spatial_attention(z, number_of_filters) * z
z = add([y,z])
out = UpSampling2D(size=2)(z)
return out
def define_unet(self):
# Define inputs
input = Input((128,128,3))
pooling1 = MaxPooling2D((2, 2))(input)
pooling2 = MaxPooling2D((2, 2))(pooling1)
pooling3 = MaxPooling2D((2, 2))(pooling2)
x1 = self.concat_up_blocks(input, self.initial_number_of_filters, strides=1, use_dilate=True, use_batch_norm=False, use_group_norm=False)
x2 = self.concat_up_blocks(x1, 2 * self.initial_number_of_filters, strides=1, use_dilate=True, skip_x=[pooling1], use_batch_norm=False, use_group_norm=False)
x3 = self.concat_up_blocks(x2, 4 * self.initial_number_of_filters, strides=1, use_dilate=True, skip_x=[pooling2], use_batch_norm=False, use_group_norm=False)
x4 = self.concat_up_blocks(x3, 8 * self.initial_number_of_filters, strides=1, use_dilate=True, skip_x=[pooling3], use_batch_norm=False, use_group_norm=False)
res_1 = self.residual_blocks(x4, 8 * self.initial_number_of_filters)
res_2 = self.residual_blocks(res_1, 8 * self.initial_number_of_filters)
res_3 = self.residual_blocks(res_2, 8 * self.initial_number_of_filters)
x4b = self.concat_down_blocks(res_3, 8 * self.initial_number_of_filters, strides=1, skip_x=[x4], use_batch_norm=False, use_group_norm=False)
x3b = self.concat_down_blocks(x4b, 4 * self.initial_number_of_filters, strides=1, skip_x=[x3], use_batch_norm=False, use_group_norm=False)
x2b = self.concat_down_blocks(x3b, 2 * self.initial_number_of_filters, strides=1, skip_x=[x2], use_batch_norm=False, use_group_norm=False)
x1b = self.concat_down_blocks(x2b, 1 * self.initial_number_of_filters, strides=1, skip_x=[x1], use_batch_norm=False, use_group_norm=False)
up4 = UpSampling2D((16,16))(res_3)
up3 = UpSampling2D((8,8))(x4b)
up2 = UpSampling2D((4,4))(x3b)
up1 = UpSampling2D((2,2))(x2b)
concat = concatenate([up4, up3, up2, up1, x1b])
concat = self.generator_convolution(concat, self.initial_number_of_filters, strides=1, use_seperate=False, use_batch_norm=False, use_group_norm=False)
x0b = Conv2D(4, (1,1), strides=self.stride_size, padding="same")(concat)
output_label = Activation("softmax")(x0b)
self.unet = Model(inputs=input, outputs=output_label, name="generator")
self.unet.compile(loss=[dice_loss], optimizer=Adam(3e-4, 0.5), metrics=[dice_coff_edema, dice_coff_scar, dice_coff])
self.unet.summary()
def dice_loss(y_true, y_pred):
intersection = tf.reduce_sum(y_true[:,:,:,0] * y_pred[:,:,:,0])
union = tf.reduce_sum(y_pred[:,:,:,0]) + tf.reduce_sum(y_true[:,:,:,0])
dice1 = 1 - tf.math.pow(((2. * intersection + 1) / (union + 1)), 1/2)
intersection = tf.reduce_sum(y_true[:,:,:,1] * y_pred[:,:,:,1])
union = tf.reduce_sum(y_pred[:,:,:,1]) + tf.reduce_sum(y_true[:,:,:,1])
dice2 = 1 - tf.math.pow(((2. * intersection + 1) / (union + 1)), 1/2)
intersection = tf.reduce_sum(y_true[:,:,:,2] * y_pred[:,:,:,2])
union = tf.reduce_sum(y_pred[:,:,:,2]) + tf.reduce_sum(y_true[:,:,:,2])
dice3 = 1 - tf.math.pow(((2. * intersection + 1) / (union + 1)), 1/2)
intersection = tf.reduce_sum(y_true[:,:,:,3] * y_pred[:,:,:,3])
union = tf.reduce_sum(y_pred[:,:,:,3]) + tf.reduce_sum(y_true[:,:,:,3])
dice4 = 1 - tf.math.pow(((2. * intersection + 1) / (union + 1)), 1/2)
dice = 100 * huber_loss(y_pred, y_true) + dice1+dice2+dice3+0.5*dice4
return dice
def dice_coff_edema(y_true, y_pred):
y_pred = tf.where(y_pred >= 0.5, tf.ones_like(y_pred), tf.zeros_like(y_pred))
intersection = tf.reduce_sum(y_true[:,:,:,0] * y_pred[:,:,:,0])
union = tf.reduce_sum(y_true[:,:,:,0]) + tf.reduce_sum(y_pred[:,:,:,0])
dice = ((2. * intersection) / (union))
return dice
def dice_coff_scar(y_true, y_pred):
y_pred = tf.where(y_pred >= 0.5, tf.ones_like(y_pred), tf.zeros_like(y_pred))
intersection = tf.reduce_sum(y_true[:,:,:,1] * y_pred[:,:,:,1])
union = tf.reduce_sum(y_true[:,:,:,1]) + tf.reduce_sum(y_pred[:,:,:,1])
dice = ((2. * intersection) / (union))
return dice
def dice_coff(y_true, y_pred):
y_pred = tf.where(y_pred >= 0.5, tf.ones_like(y_pred), tf.zeros_like(y_pred))
intersection = tf.reduce_sum(y_true * y_pred)
union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
dice = ((2. * intersection) / (union))
return dice
| true |
7cfb81ba1b087ec5d01e1c705ebcebf46317ae13
|
Python
|
pablocelis/K-means-algorithm
|
/k-means.py
|
UTF-8
| 2,882 | 3.265625 | 3 |
[
"Unlicense"
] |
permissive
|
from numpy import matrix
import numpy as np
import random
import collections
# findClosestCentroids(X, centroids) returns the index of the closest
# centroids for a dataset X where each row is a single example.
# idx = m x 1 is a vector of centroid assignments
# (i.e., each entry in range [0..k-1])
def findClosestCentroids(X, centroids):
# Set k, the number of centroids
k = np.size(centroids,0)
# You need to return the following variables correctly.
idx = np.mat(np.zeros((np.size(X,0),1)), dtype=int)
distance = np.mat(np.zeros((k,1)))
for i, vect in enumerate(X):
for p, pnt in enumerate(centroids):
distance[p] = np.linalg.norm(vect-pnt)
idx[i] = np.argmin(distance)
return idx
# computeCentroids(X, idx, k) returns the new centroids by
# computing the means of the data points assigned to each centroid. It is
# given a dataset X where each row is a single data point, a vector
# idx of centroid assignments (i.e., each entry in range [0..k-1]) for each
# example, and k, the number of centroids. You should return a matrix of
# centroids, where each row of centroids is the mean of the data points
# assigned to it.
def computeCentroids(X, idx, k):
m,n = np.shape(X)
centroids = np.mat(np.zeros((k,n)))
num_points = np.mat(np.zeros((k,1))) # Get the number of vectors in each centroid
for i, vect in enumerate(X):
c = idx[i] # Return the centroid assigned to this vector
num_points[c] += 1
centroids[c] += vect # Sum the group of vectors of each centroid
for i in range(k):
centroids[i] = centroids[i]/num_points[i]
return centroids
# runkMeans(X, initial_centroids, max_iters) runs the k-Means algorithm
# on data matrix X, where each row of X is a single example. It uses
# initial_centroids used as the initial centroids. max_iters specifies
# the total number of interactions of k-Means to execute. runkMeans returns
# centroids, a k x n matrix of the computed centroids and idx, a m x 1
# vector of centroid assignments (i.e., each entry in range [0..k-1])
#
def runkMeans(X, initial_centroids, max_iters):
m,n = np.shape(X)
k = np.size(initial_centroids,0)
centroids = initial_centroids
idx = np.mat(np.zeros((m,1)))
for i in range(max_iters):
idx = findClosestCentroids(X, centroids)
centroids = computeCentroids(X, idx, k)
kMeansInitCentroids(X, k)
return [centroids, idx]
# kMeansInitCentroids(X, k) returns k initial centroids to be
# used with the k-Means on the dataset X
def kMeansInitCentroids(X, k):
centroids = np.mat(np.zeros((k,np.size(X,1))))
centroids = random.sample(X, k)
return centroids
| true |
f3c91097059d2ec16eb7b2dd5fdbf5f9d3334517
|
Python
|
rongyafeng0410/test0001
|
/hello.py
|
UTF-8
| 328 | 2.921875 | 3 |
[] |
no_license
|
import unittest
def divid(num1, num2):
return num1 / num2
class MyTest(unittest.TestCase):
def test1(self):
assert (divid(1, 1) == 1)
def test2(self):
assert (divid(0, 1) == 0)
def test3(self):
assert (divid(2, 3) == 0)
print("hello")
if __name__ == "__main__":
unittest.main()
| true |
3a79cad17cbb1747e197cb52a6f46345f5b06924
|
Python
|
johanvandegriff/quest
|
/tmp.py
|
UTF-8
| 452 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python
def memoize(f):
m = {}
def h(*x):
if x not in m:
m[x] = f(*x)
print m
return m[x]
h.__name__ = f.__name__
return h
def plus1(f):
def h(x):
return x *2
return h
def strings(f):
def h(x):
return str(x) + "hi"
return h
@memoize
def fib2(a, b):
if a == 0:
return 0
if a == 1:
return 1
return fib2(a-1, b) + fib2(a-2, b) + b
print fib2(4,5)
print fib2(2,2)
print fib2.__name__
| true |
e7a8400633574bc5a073afbf7eb5bed01fda63e9
|
Python
|
caoxp930/MyPythonCode
|
/类/code/单例模式new.py
|
UTF-8
| 760 | 3.625 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# __new__
class Earth:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'): # 如果我的类没有实例对象,那我就去new一个实例对象
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
self.name = 'earth'
e = Earth()
print(e)
a = Earth()
print(a)
# 类每次实例化时都会新建一个对象,并在内存里划出一块存放对象
# 通过__new__可以实现不管实例多少次,始终都是同一个对象
# __new__方法是在__init__之前执行的
# 单例模式
# 1.适用情装的数据都相况:当所有实例中封同时(可视为同一个实例),此时可以考虑单例模式
# 2.案例:数据库连接池
| true |
c75386693a933c2a33ad01a143d2cf74579ccec7
|
Python
|
alexaugustobr/impacta-desenvolvimento-aplicacoes-distribuidas
|
/Client.py
|
UTF-8
| 3,007 | 2.75 | 3 |
[] |
no_license
|
import requests as req
url = "http://localhost:5000/alunos"
print("Cadastrando alunos")
aluno = {"ra":"1700072", "nome":"Alex Augusto"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1700693", "nome":"Cinthia Queiroz"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1700381", "nome":"Michael da Silva de Souza"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1700603", "nome":"Fabio Aurelio Abe Nogueira"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1601606", "nome":"Gabriel Bueno"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1700054", "nome":"Henrique Borges da Silva"}
print(req.api.post(url, json=aluno).json())
aluno = {"ra":"1700677", "nome":"Diego santos"}
print(req.api.post(url, json=aluno).json())
print("Lista alunos")
print(req.api.get(url).json())
print("Cria forum")
Forum = {"ForumId":"1", "OwnerId":"1700072", "Title": "Title", "Description":"Description", "CreateDate":"10/10/2017", "LastPostDate":"10/10/2017", "Active":True}
url = "http://localhost:5000/forum"
print(req.api.post(url, json=Forum).json())
print("Lista forum")
print(req.api.get(url).json())
print("Registrar aluno no forum")
url = "http://localhost:5000/forum/register"
print(req.api.post(url, json={"ForumId":"1", "ra":"1700693"}).json())
print(req.api.post(url, json={"ForumId":"1", "ra":"1700603"}).json())
print("Tirar registro do aluno no forum")
url = "http://localhost:5000/forum/unregister"
print(req.api.post(url, json={"ForumId":"1", "ra":"1700603"}).json())
print("Criar post no forum")
Postagem = {"PostId":"1", "ForumId": "1", "OwnerId":"1700693", "CreateDate":"10/10/2017", "Message": "Teste", "Visible":True}
url = "http://localhost:5000/forum/post"
print(req.api.post(url, json=Postagem).json())
print("Posts do forum")
url = "http://localhost:5000/forum/1/post?ra=1700693"
print(req.api.get(url).json())
print("Ler post")
url = "http://localhost:5000/forum/post/1?ra=1700693"
print(req.api.get(url).json())
print("Criar notificacao para Aluno, de trabalho")
Notificacao = {"id":"1", "data":"10/10/2018", "assunto":"Atividades","mensagem":"Atividades disponiveis","status":"Nao visualizado","aluno":"1700072"}
url = "http://localhost:5000/notificacoes"
print(req.api.post(url, json=Notificacao).json())
url = "http://localhost:5000/notificacoes"
print("Criar notificacao para Aluno, de comunitacao")
Notificacao = {"id":"2", "data":"10/10/2018", "assunto":"Nao vizualizado","mensagem":"Ola voce recebeu uma mensagem do professor","status":"Nao visualizado","aluno":"1700072"}
print(req.api.post(url, json=Notificacao).json())
print("Busca notificacao recebidas por ra")
url = "http://localhost:5000/alunos/1700072/notificacoes/recebidas"
print(req.api.get(url).json())
print("Busca notificacao por id")
url = "http://localhost:5000/notificacoes/1"
print(req.api.get(url).json())
print("Busca notificacao por ra")
url = "http://localhost:5000/alunos/1700072/notificacoes"
print(req.api.get(url).json())
url = "http://localhost:5000/notificacoes/1/arquivar?ra=1700072"
print(req.api.get(url).json())
| true |
2c80e9e195d3eb832159f05deff175060fab1b73
|
Python
|
heping945/pythonbackend
|
/python3基础/6 生成器与协程.py
|
UTF-8
| 818 | 3.625 | 4 |
[] |
no_license
|
__author__ = 'pinge'
# 1 什么是生成器
def xx():
yield 'hello'
yield 'world'
x=xx()
print(next(x))
print(next(x))
# 2 基于生成器的协程(python2)
def coro():
hello = yield 'hello' #yield 在右作为表达式,可以被send值
yield hello
c = coro()
print(next(c)) #输出hello ,这里调用next产出第一个值hello 之后函数暂停
print(c.send('world')) #调用send发送值,此时hello变量赋值为'world',然后yeild产出hello的值'world'
#之后协程结束,后续在send值会抛出异常StopIteration
# 3 协程装饰器
from functools import wraps
def outer(func):
@wraps(func)
def inner(*args,**kwargs):
gen = func(*args,**kwargs)
next(gen)
return gen
return inner
# 4 py3.5引入原生协程(async/await)
| true |
4d7a6bc69daf7c5fd097b4949e43d3534f3024a2
|
Python
|
jawad5311/100-Days-Python
|
/intermediate-Day15-to-Day32/Day_28-Pomodoro_app/main.py
|
UTF-8
| 3,844 | 3.59375 | 4 |
[
"Apache-2.0"
] |
permissive
|
import math
import tkinter
# CONSTANTS
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
reps = 0
timer = None
# ---------------------------- TIMER RESET ------------------------------- #
def reset_timer():
""" Reset the App when reset button is clicked """
global reps
window.after_cancel(timer) # Tkinter builtin func to stop after() func
label.config(text="Timer", fg=GREEN, font=(FONT_NAME, 32, "bold")) # Updates Timer label
reps = 0
canvas.itemconfigure(timer_text, text=f"00:00") # Reset the displaying time
tick_label.config(text="") # Reset the tick marks
# ---------------------------- TIMER MECHANISM ------------------------------- #
def start_timer():
""" Start the timer when start button is clicked """
global reps
reps += 1 # Increase the reps everytime timer starts
# Converts working and break minutes into seconds
work_sec = WORK_MIN * 60
short_break_sec = SHORT_BREAK_MIN * 60
long_break_sec = LONG_BREAK_MIN * 60
# Check for the reps and display work and break text accordingly
if reps % 8 == 0:
count_down(long_break_sec)
label.config(text="Break", fg=RED)
elif reps % 2 == 0:
count_down(short_break_sec)
label.config(text="Break", fg=PINK)
else:
count_down(work_sec)
label.config(text="Work", fg=GREEN)
# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #
def count_down(count):
""" Holds all the functionality of counting """
count_min = math.floor(count / 60) # Converts the counting sec to min to make them display on the screen like clock
count_sec = count % 60 # Holds the remaining sec to make them display on the screen0
# Use to display two digits on screen instead of 1 if the remaining seconds are less then 10
if count_sec < 10:
count_sec = f"0{count_sec}"
canvas.itemconfigure(timer_text, text=f"{count_min}:{count_sec}") # Display the updated time every 1 sec
# Decrease the count by 1 after each second
if count > 0:
global timer
timer = window.after(1000, count_down, count - 1)
else: # If the count get to the zero then trigger the start_timer() again
start_timer()
# Display the tick mark for each work session completed
mark = ""
work_session = math.floor(reps/2)
for _ in range(work_session):
mark += "✔"
tick_label.config(text=mark)
# ---------------------------- UI SETUP ------------------------------- #
# Create and setup display screen
window = tkinter.Tk()
window.title("PomoDoro App")
window.config(padx=100, pady=50, bg=YELLOW)
"""
Following are Button and Text properties that are displaying on the screen
"""
# "Timer" Text
label = tkinter.Label(text="Timer", fg=GREEN, bg=YELLOW, font=(FONT_NAME, 32, "bold"))
label.grid(column=1, row=0)
# Background image of Tomato
tomato_img = tkinter.PhotoImage(file="tomato.png")
canvas = tkinter.Canvas(width=204, height=224, bg=YELLOW, highlightthickness=0)
canvas.create_image(102, 112, image=tomato_img)
# Clock time 00:00
timer_text = canvas.create_text(102, 130, text=f"00:00", fill="white", font=(FONT_NAME, 28, "bold"))
canvas.grid(column=1, row=1)
# Start Button
start_btn = tkinter.Button(text="Start", command=start_timer, highlightthickness=0)
start_btn.grid(column=0, row=3)
# Reset Button
reset_btn = tkinter.Button(text="Reset", command=reset_timer, highlightthickness=0)
reset_btn.grid(column=2, row=3)
# Tick mark properties
tick_label = tkinter.Label(fg=GREEN, bg=YELLOW, font=(FONT_NAME, 18))
tick_label.grid(column=1, row=4)
window.mainloop() # tkinter built-in func(), Keep the display open until closed
| true |
4c67e48babab4d8cb6a2f57d4d97841449ab1f19
|
Python
|
Marou-Hub/myfirstproject
|
/learnPython/text1.py
|
UTF-8
| 381 | 4.21875 | 4 |
[] |
no_license
|
def main():
# creation d'une variable 'username' ayant pour valeur le mot Graven
username = "Graven"
username = "YouTube"
# creation d'une variable 'age' ayant pour valeur 19
age = 19
# change la valeur par 25
age = 25
# afficher la nouvelle valeur
age = age * age
print("Salut " + username + ", vous avez " + str(age) + " ans !")
main()
| true |
b9aa02d3746aea0ece53063baada75e3ea378cf8
|
Python
|
MicrohexHQ/opencoin-historic
|
/sandbox/mathew/fraction/protocols.py
|
UTF-8
| 48,857 | 3 | 3 |
[] |
no_license
|
"""
Protocol have states, which are basically methods that consume messages, do
something and return messages. The states are just methods, and one state
might change the state of its protocol to another state.
A protocol writes to a transport, using Transport.write. It receives messages
from the transport with Protocol.newMessage.
A state (a protocol method) returns messages, it does not write directly back
to a transport (XXX not sure about this, what if a state needs to communicate
with another enity). Instead newMessage by default writes back to the transport.
(XXX maybe the transport could take the returned message, and write it up its own,
ah write method?)
Before returning the message, the state should set the protocols state to the next
state (sounds a bit ackward, its easy, check the states code)
"""
from messages import Message
import containers
import types
class Protocol:
"""A protocol ties messages and actions togehter, it is basically one side
of an interaction. E.g. when A exchanges a coin with B, A would use the
walletSenderProtocol, and B the walletRecipientProtocol."""
def __init__(self):
'Set the initial state'
self.state = self.start
self.result = None
def setTransport(self,transport):
'get the transport we are working with'
self.transport = transport
def start(self,message):
'this should be the initial state of the protocol'
pass
def goodbye(self,message):
self.state = self.finish
return Message('GOODBYE')
def finish(self,message):
'always the last state. There can be other final states'
return Message('finished')
def newMessage(self,message):
'this is used by a transport to pass on new messages to the protocol'
out = self.state(message)
self.transport.write(out)
return out
def newState(self,method):
self.state = method
def initiateHandshake(self,message):
self.newState(self.firstStep)
return Message('HANDSHAKE',{'protocol': 'opencoin 1.0'})
#ProtocolErrorMessage = lambda x: Message('PROTOCOL_ERROR', 'send again %s' % x)
ProtocolErrorMessage = lambda x: Message('PROTOCOL_ERROR', 'send again')
class answerHandshakeProtocol(Protocol):
def __init__(self,**mapping):
Protocol.__init__(self)
self.mapping = mapping
def start(self,message):
if message.type == 'HANDSHAKE':
if message.data['protocol'] == 'opencoin 1.0':
self.newState(self.dispatch)
return Message('HANDSHAKE_ACCEPT')
else:
self.newState(self.goodbye)
return Message('HANDSHAKE_REJECT','did not like the protocol version')
else:
return Message('PROTOCOL_ERROR','please do a handshake')
def dispatch(self,message):
self.result = message
nextprotocol = self.mapping[message.type]
self.transport.setProtocol(nextprotocol)
m = nextprotocol.newMessage(message)
#print 'here ', m
#return m
############################### Spending coins (w2w) ##########################
# Spoken bewteen two wallets to transfer coins / tokens #
###############################################################################
class TokenSpendSender(Protocol):
"""
>>> from tests import coins
>>> coin1 = coins[0][0]
>>> coin2 = coins[1][0]
>>> css = TokenSpendSender([coin1,coin2],'foobar')
>>> css.state(Message(None))
<Message('HANDSHAKE',{'protocol': 'opencoin 1.0'})>
>>> css.state(Message('HANDSHAKE_ACCEPT'))
<Message('SUM_ANNOUNCE',['...', '3', 'foobar'])>
>>> css.state(Message('SUM_ACCEPT'))
<Message('TOKEN_SPEND',['...', [[(...)], [(...)]], 'foobar'])>
>>> css.state(Message('TOKEN_ACCEPT'))
<Message('GOODBYE',None)>
>>> css.state(Message('Really?'))
<Message('finished',None)>
"""
def __init__(self,coins,target):
from containers import sumCurrencies
self.coins = coins
self.amount = sumCurrencies(coins)
self.target = target
import base64
from crypto import _r as Random
self.transaction_id = Random.getRandomString(128)
self.encoded_transaction_id = base64.b64encode(self.transaction_id)
Protocol.__init__(self)
self.state = self.initiateHandshake
def firstStep(self,message):
self.state = self.spendCoin
standard_identifier = self.coins[0].standard_identifier # All the coins are
currency_identifier = self.coins[0].currency_identifier # same currency & CDD
return Message('SUM_ANNOUNCE',[self.encoded_transaction_id,
standard_identifier,
currency_identifier,
str(self.amount),
self.target])
def spendCoin(self,message):
if message.type == 'SUM_ACCEPT':
self.state = self.goodbye
jsonCoins = [c.toPython() for c in self.coins]
return Message('TOKEN_SPEND',[self.encoded_transaction_id,
jsonCoins,
self.target])
elif message.type == 'PROTOCOL_ERROR':
pass
else:
return ProtocolErrorMessage('TokenSpendSender')
def goodbye(self,message):
if message.type == 'TOKEN_ACCEPT':
self.state = self.finish
return Message('GOODBYE')
elif message.type == 'PROTOCOL_ERROR':
pass
else:
return ProtocolErrorMessage('TokenSpendSender')
class TokenSpendRecipient(Protocol):
"""
>>> import entities
>>> from tests import coins
>>> coin1 = coins[0][0].toPython() # Denomination of 1
>>> coin2 = coins[1][0].toPython() # Denomination of 2
>>> w = entities.Wallet()
>>> csr = TokenSpendRecipient(w)
>>> csr.state(Message('SUM_ANNOUNCE',['1234','standard', 'currency', '3','a book']))
<Message('SUM_ACCEPT',None)>
>>> csr.state(Message('TOKEN_SPEND',['1234', [coin1, coin2], 'a book']))
<Message('TOKEN_ACCEPT',None)>
>>> csr.state(Message('Goodbye',None))
<Message('GOODBYE',None)>
>>> csr.state(Message('foobar'))
<Message('finished',None)>
TODO: Add PROTOCOL_ERROR checking
"""
def __init__(self,wallet,issuer_transport = None):
self.wallet = wallet
self.issuer_transport = issuer_transport
Protocol.__init__(self)
def start(self,message):
import base64
from fraction import Fraction
if message.type == 'SUM_ANNOUNCE':
try:
encoded_transaction_id, standard_identifier, currency_identifier, encoded_amount, self.target = message.data
except ValueError:
return ProtocolErrorMessage('SA')
if not isinstance(encoded_transaction_id, types.StringType):
return ProtocolErrorMessage('SA')
if not isinstance(standard_identifier, types.StringType):
return ProtocolErrorMessage('SA')
if not isinstance(currency_identifier, types.StringType):
return ProtocolErrorMessage('SA')
if not isinstance(encoded_amount, types.StringType):
return ProtocolErrorMessage('SA')
if not isinstance(self.target, types.StringType):
return ProtocolErrorMessage('SA')
# Decode the transaction_id
try:
self.transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('SA')
# Setup sum
self.sum = Fraction(encoded_amount)
# And do stuff
#get some feedback from interface somehow
action = self.wallet.confirmReceiveCoins('the other wallet id',self.sum,self.target)
if action == 'reject':
self.state = self.goodbye
return Message('SUM_REJECT')
else:
self.action = action
self.state = self.handleCoins
return Message('SUM_ACCEPT')
elif message.type == 'PROTOCOL_ERROR':
pass
else:
return ProtocolErrorMessage('TokenSpendRecipient')
def handleCoins(self,message):
import base64
if message.type == 'TOKEN_SPEND':
try:
encoded_transaction_id, tokens, target = message.data
except ValueError:
return ProtocolErrorMessage('TS')
if not isinstance(encoded_transaction_id, types.StringType):
return ProtocolErrorMessage('TS')
if not isinstance(tokens, types.ListType):
return ProtocolErrorMessage('TS')
if not tokens: # We require tokens
return ProtocolErrorMessage('TS')
for token in tokens:
if not isinstance(token, types.ListType):
return ProtocolErrorMessage('TS')
# Convert transaction_id
try:
transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TS')
# Convert the tokens
try:
tokens = [containers.CurrencyCoin().fromPython(c) for c in tokens]
except AttributeError: #FIXME: this is the wrong error, I'm pretty sure
return ProtocolErrorMessage('TS')
# And now do things
from containers import sumCurrencies
#be conservative
result = Message('TOKEN_REJECT','default')
if transaction_id != self.transaction_id:
#FIXME: is the a PROTOCOL_ERROR?
result = Message('TOKEN_REJECT','Rejected')
elif sumCurrencies(tokens) != self.sum:
result = Message('TOKEN_REJECT','Rejected')
elif target != self.target:
result = Message('TOKEN_REJECT','Rejected')
elif self.action in ['redeem','exchange','trust']:
out = self.wallet.handleIncomingCoins(tokens,self.action,target)
if out:
result = Message('TOKEN_ACCEPT')
self.state = self.goodbye
return result
elif message.type == 'PROTOCOL_ERROR':
pass
else:
return ProtocolErrorMessage('TokenSendRecipient')
############################### Transfer tokens ##############################
# This is spoken between a wallet (sender) and the issuer, for minting, #
# exchange and redemption #
###############################################################################
class TransferTokenSender(Protocol):
"""
>>> from tests import coins
>>> coin1 = coins[0][0] # denomination of 1
>>> coin2 = coins[1][0] # denomination of 2
>>> tts = TransferTokenSender('my account',[],[coin1, coin2],type='redeem')
>>> tts.state(Message(None))
<Message('HANDSHAKE',{'protocol': 'opencoin 1.0'})>
>>> tts.state(Message('HANDSHAKE_ACCEPT'))
<Message('TRANSFER_TOKEN_REQUEST',['...', 'my account', [], [[(...)], [(...)]], [['type', 'redeem']]])>
>>> tts.state(Message('TRANSFER_TOKEN_ACCEPT',[tts.encoded_transaction_id, []]))
<Message('GOODBYE',None)>
"""
def __init__(self, target, blinds, coins, **kwargs):
import base64
from crypto import _r as Random
self.transaction_id = Random.getRandomString(128)
self.encoded_transaction_id = base64.b64encode(self.transaction_id)
self.target = target
self.blinds = blinds
self.coins = [c.toPython() for c in coins]
self.kwargs = kwargs
Protocol.__init__(self)
self.state = self.initiateHandshake
def firstStep(self,message):
data = [self.encoded_transaction_id,
self.target,
self.blinds,
self.coins]
if self.kwargs:
data.append([list(i) for i in self.kwargs.items()])
self.state = self.goodbye
return Message('TRANSFER_TOKEN_REQUEST',data)
def goodbye(self,message):
import base64
if message.type == 'TRANSFER_TOKEN_ACCEPT':
try:
encoded_transaction_id, blinds = message.data
except ValueError:
return ProtocolErrorMessage('TTA')
if not isinstance(blinds, types.ListType):
return ProtocolErrorMessage('TTA')
for blind in blinds:
if not isinstance(blind, types.StringType):
return ProtocolErrorMessage('TTA')
# decode the blinds
try:
self.blinds = [base64.b64decode(blind) for blind in blinds]
except TypeError:
return ProtocolErrorMessage('TTA')
#decode transaction_id
try:
transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TTA')
# Start checking things
if transaction_id != self.transaction_id:
#FIXME: Wrong message, I think. We don't really have a way to handle this.
return Message('PROTOCOL_ERROR', 'incorrect transaction_id')
if self.kwargs['type'] == 'exchange' or self.kwargs['type'] == 'mint':
if not blinds:
return ProtocolErrorMessage('TTA')
else:
if len(blinds) != 0:
raise Exception('c')
return ProtocolErrorMessage('TTA')
self.result = 1
elif message.type == 'TRANSFER_TOKEN_DELAY':
try:
encoded_transaction_id, reason = message.data
except ValueError:
return ProtocolErrorMessage('TTD')
if not isinstance(reason, types.StringType):
return ProtocolErrorMessage('TTD')
# Decode the transaction_id
try:
transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TTD')
# Start checking things
if transaction_id != self.transaction_id:
#FIXME: This seems like a wrong message....
return ProtocolErrorMessage('TTD')
# FIXME Do some things here, after we work out how delays work
self.result = 1
elif message.type == 'TRANSFER_TOKEN_REJECT':
try:
encoded_transaction_id, type, reason, reason_detail = message.data
except ValueError:
return ProtocolErrorMessage('TTRj')
if not isinstance(encoded_transaction_id, types.StringType):
return ProtocolErrorMessage('TTRj')
if not isinstance(type, types.StringType):
return ProtocolErrorMessage('TTRj')
if not type:
return ProtocolErrorMessage('TTRj')
if not isinstance(reason, types.StringType):
return ProtocolErrorMessage('TTRj')
if not reason:
return ProtocolErrorMessage('TTRj')
if not isinstance(reason_detail, types.ListType):
return ProtocolErrorMessage('TTRj')
# Decode the transaction_id
try:
transcation_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TTRj')
# Do checking of reason_detail
# If reason is see dtail, reason_detail is a list with
# entries, otherwise, reason_detail is an empty list
if reason == 'See detail':
if not reason_detail:
return ProtocolErrorMessage('TTRj')
else:
if reason_detail:
return ProtocolErrorMessage('TTRj')
# Any checking of specific reasons for validity should be also
# be done, but reason_detail is always empty
# Start checking things
if transaction_id != self.transaction_id:
#FIXME: I don't like using this message for this..
return ProtocolErrorMessage('TTRj')
# FIXME: Do something here?
self.result = 0
elif message.type == 'PROTOCOL_ERROR':
#FIXME: self.state=self.finish is hackish. Does it do what we want?
self.state = self.finish
return Message('GOODBYE')
else:
return ProtocolErrorMessage('TransferTokenSender')
self.state = self.finish
return Message('GOODBYE')
class TransferTokenRecipient(Protocol):
"""
>>> import entities, tests, containers, base64, copy, calendar
>>> issuer = tests.makeIssuer()
>>> issuer.getTime = lambda: calendar.timegm((2008,01,31,0,0,0))
>>> issuer.mint.getTime = issuer.getTime
>>> ttr = TransferTokenRecipient(issuer)
>>> coin1 = tests.coins[0][0].toPython() # denomination of 1
>>> coin2 = tests.coins[1][0].toPython() # denomination of 2
>>> coin3 = tests.coins[0][0].toPython() # denomination of 1
This should not be accepted
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', [], ['foobar'], [['type', 'redeem']]]))
<Message('PROTOCOL_ERROR','send again')>
The malformed coin should be rejected
>>> malformed = copy.deepcopy(tests.coins[0][0])
>>> malformed.signature = 'Not a valid signature'
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', [], [malformed.toPython()], [['type', 'redeem']]]))
<Message('TRANSFER_TOKEN_REJECT',['1234', 'Token', 'See detail', ['Rejected']])>
The unknown key_identifier should be rejected
>>> malformed = copy.deepcopy(tests.coins[0][0])
>>> malformed.key_identifier = 'Not a valid key identifier'
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', [], [malformed.toPython()], [['type', 'redeem']]]))
<Message('TRANSFER_TOKEN_REJECT',['1234', 'Token', 'See detail', ['Rejected']])>
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', [], [coin1, coin2], [['type', 'redeem']]]))
<Message('TRANSFER_TOKEN_ACCEPT',['1234', []])>
Try to double spend. Should not work.
>>> ttr.state = ttr.start
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', [], [coin1, coin2], [['type', 'redeem']]]))
<Message('TRANSFER_TOKEN_REJECT',['1234', 'Token', 'Invalid token', []])>
>>> blank1 = containers.CurrencyBlank().fromPython(tests.coinA.toPython(nosig=1))
>>> blank2 = containers.CurrencyBlank().fromPython(tests.coinB.toPython(nosig=1))
>>> blind1 = base64.b64encode(blank1.blind_blank(tests.CDD,tests.mint_key1, blind_factor='a'*26))
>>> blind2 = base64.b64encode(blank2.blind_blank(tests.CDD,tests.mint_key2, blind_factor='a'*26))
>>> blindslist = [[tests.mint_key1.encodeField('key_identifier'),[blind1]],
... [tests.mint_key2.encodeField('key_identifier'),[blind2]]]
>>> ttr.state = ttr.start
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', 'my account', blindslist, [], [['type', 'mint']]]))
<Message('TRANSFER_TOKEN_ACCEPT',['1234', ['Do0el3uxdyFMF8NdXtowBLBOxXM0r7xR9hXkaZWEhPUBQCe8yaYGO09wnxrWEVFlt0r9M6bCZxKtzNGDGw3/XQ==', 'dTnL8yTkdelG9fW//ZoKzUl7LTjBXiElaHkfyMLgVetEM7pmEzfcdfRWhm2PP3IhnkZ8CmAR1uOJ99rJ+XBASA==']])>
Now, check to make sure the implementation is good
>>> ttr.state = ttr.start
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST'))
<Message('PROTOCOL_ERROR','send again')>
Okay. Have to reset DSDB to do this next trick
>>> issuer = tests.makeIssuer()
>>> issuer.getTime = lambda: calendar.timegm((2008,01,31,0,0,0))
>>> issuer.mint.getTime = issuer.getTime
>>> blank = tests.makeBlank(tests.mintKeys[0], 'a'*26, 'a'*26)
>>> blind = [[tests.mintKeys[0].encodeField('key_identifier'), [base64.b64encode(blank.blind_blank(tests.CDD, tests.mintKeys[0]))]]]
>>> ttr = TransferTokenRecipient(issuer)
>>> ttr.state = ttr.start
>>> ttr.state(Message('TRANSFER_TOKEN_REQUEST',['1234', '', blind, [coin1], [['type', 'exchange']]]))
<Message('TRANSFER_TOKEN_ACCEPT',['1234', ['UIo2KtqK/6JqSWbtFFVR14fOjnzwr4tDiY/6kOnQ0h92EewY2vJBV2XaS43wK3RsNFg0sHzNh3v2BVDFV8cDvQ==']])>
"""
def __init__(self,issuer):
self.issuer = issuer
Protocol.__init__(self)
def start(self,message):
from entities import LockingError
import base64
if message.type == 'TRANSFER_TOKEN_REQUEST':
try:
encoded_transaction_id, target, blindslist, coins, options_list = message.data
except TypeError:
return ProtocolErrorMessage('TTRq17')
if not isinstance(target, types.StringType):
return ProtocolErrorMessage('TTRq1')
if not isinstance(blindslist, types.ListType):
return ProtocolErrorMessage('TTRq2')
for blind in blindslist:
if not isinstance(blind, types.ListType):
return ProtocolErrorMessage('TTRq3')
try:
key, b = blind
except ValueError:
return ProtocolErrorMessage('TTRq4')
if not isinstance(key, types.StringType):
return ProtocolErrorMessage('TTRq5')
if not isinstance(b, types.ListType):
return ProtocolErrorMessage('TTRq6')
for blindstring in b:
if not isinstance(blindstring, types.StringType):
return ProtocolErrorMessage('TTRq7')
if len(b) == 0:
return ProtocolErrorMessage('TTRq14')
# Decode transaction_id
try:
transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TTRq18')
# Convert blindslist
try:
blindslist = [[base64.b64decode(key), [base64.b64decode(bl) for bl in blinds]] for key, blinds in blindslist]
except TypeError:
return ProtocolErrorMessage('TTRq15')
if not isinstance(coins, types.ListType):
return ProtocolErrorMessage('TTRq8')
for coin in coins:
if not isinstance(coin, types.ListType):
return ProtocolErrorMessage('TTRq9')
#convert coins
try:
coins = [containers.CurrencyCoin().fromPython(c) for c in coins]
except AttributeError: #FIXME: Right error?
return ProtocolErrorMessage('TTRq16')
if not isinstance(options_list, types.ListType):
return ProtocolErrorMessage('TTRq10')
for options in options_list:
try:
key, val = options
except ValueError:
return ProtocolErrorMessage('TTRq11')
if not isinstance(key, types.StringType):
return ProtocolErrorMessage('TTRq12')
if not isinstance(val, types.StringType):
return ProtocolErrorMessage('TTRq13')
# Decipher options
options = {}
options.update(options_list)
if not options.has_key('type'):
return Message('TRANSFER_TOKEN_REJECT', 'Options', 'Reject', [])
# Start doing things
if options['type'] == 'redeem':
failures = []
#check if coins are valid
for coin in coins:
mintKey = self.issuer.keyids.get(coin.key_identifier, None)
if not mintKey or not coin.validate_with_CDD_and_MintKey(self.issuer.cdd, mintKey):
failures.append(coin)
if failures: # We don't know exactly how, so give coin by coin information
details = []
for coin in coins:
if coin not in failures:
details.append('None')
else:
details.append('Rejected')
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Token',
'See detail', details])
#and not double spent
try:
#XXX have adjustable time for lock
self.issuer.dsdb.lock(transaction_id,coins,86400)
except LockingError, e:
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Token', 'Invalid token', []])
# XXX transmit funds
if not self.issuer.transferToTarget(target,coins):
self.issuer.dsdb.unlock(transaction_id)
return ProtocolErrorMessage('TTRq19')
#register them as spent
try:
self.issuer.dsdb.spend(transaction_id,coins)
except LockingError, e:
#Note: if we fail here, that means we have large problems, since the coins are locked
return ProtocolErrorMessage('TTRq20')
self.state = self.goodbye
return Message('TRANSFER_TOKEN_ACCEPT',[encoded_transaction_id, []])
# exchange uses basically mint and redeem (or a modified form thereof)
# XXX refactor to not have duplicate code
elif options['type'] == 'mint':
#check that we have the keys
blinds = [[self.issuer.keyids[keyid], blinds] for keyid, blinds in blindslist]
#check the MintKeys for validity
timeNow = self.issuer.getTime()
failures = []
for mintKey, blindlist in blinds:
can_mint, can_redeem = mintKey.verify_time(timeNow)
if not can_mint:
# TODO: We need more logic here. can_mint only specifies if we are
# between not_before and key_not_after. We may also need to do the
# checking of the period of time the mint can mint but the IS cannot
# send the key to the mint.
failures.append(mintKey.encodeField('key_identifier'))
if failures:
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Blind', 'Invalid key_identifier', []])
#check target
if not self.issuer.debitTarget(target,blindslist):
return ProtocolErrorMessage('TTRq20')
#mint them immediately (the only thing we can do right now with the mint)
minted = []
for key, blindlist in blinds:
this_set = []
for blind in blindlist:
signature = self.issuer.mint.signNow(key.key_identifier, blind)
this_set.append(base64.b64encode(signature))
minted.extend(this_set)
return Message('TRANSFER_TOKEN_ACCEPT', [encoded_transaction_id, minted])
elif options['type'] == 'exchange':
import base64
failures = []
#check if coins are valid
for coin in coins:
mintKey = self.issuer.keyids.get(coin.key_identifier, None)
try:
if not mintKey or not coin.validate_with_CDD_and_MintKey(self.issuer.cdd, mintKey):
failures.append(coin)
except AttributeError:
failures.append(coin)
if failures: # We don't know exactly how, so give coin by coin information
details = []
for coin in coins:
if coin not in failures:
details.append('None')
else:
details.append('Rejected')
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Token',
'See detail', details])
#and not double spent
try:
self.issuer.dsdb.lock(transaction_id,coins,86400)
except LockingError, e:
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Token', 'Invalid token', []])
# And onto the blinds
#check that we have the keys
import base64
blinds = [[self.issuer.keyids[keyid], blinds] for keyid, blinds in blindslist]
#check target
if not self.issuer.debitTarget(target,blindslist):
self.issuer.dsdb.unlock(transaction_id)
return Message('PROTOCOL_ERROR', 'send again')
#check the MintKeys for validity
timeNow = self.issuer.getTime()
failures = []
for mintKey, blindlist in blinds:
can_mint, can_redeem = mintKey.verify_time(timeNow)
if not can_mint:
# TODO: We need more logic here. can_mint only specifies if we are
# between not_before and key_not_after. We may also need to do the
# checking of the period of time the mint can mint but the IS cannot
# send the key to the mint.
failures.append(mintKey.encodeField('key_identifier'))
if failures:
self.issuer.dsdb.unlock(transaction_id)
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Blind', 'Invalid key_identifier', []])
# Make sure that we have the same amount of coins as mintings
from fraction import Fraction
from containers import sumCurrencies
total = Fraction('0')
for b in blinds:
total += b[0].denomination * len(b[1])
if total != sumCurrencies(coins):
self.issuer.dsdb.unlock(transaction_id)
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Generic', 'Rejected', []])
# mint them immediately (the only thing we can do right now with the mint)
minted = []
from entities import MintError
for key, blindlist in blinds:
this_set = []
for blind in blindlist:
try:
signature = self.issuer.mint.signNow(key.key_identifier, blind)
except MintError:
self.issuer.dsdb.unlock(transaction_id)
return Message('TRANSFER_TOKEN_REJECT', [encoded_transaction_id, 'Blind', 'Unable to sign', []])
this_set.append(base64.b64encode(signature))
minted.extend(this_set)
# And now, we have verified the coins are valid, they aren't double spent, and we've minted.
# Register the tokens as spent
try:
self.issuer.dsdb.spend(transaction_id,coins)
except LockingError, e:
#Note: if we fail here, that means we have large problems, since the coins are locked
return Message('PROTOCOL_ERROR', 'send again')
self.state = self.goodbye
return Message('TRANSFER_TOKEN_ACCEPT', [encoded_transaction_id, minted])
else:
#FIXME: This could rightfully be a PROTOCOL_ERROR, since we don't have a 'type' that we like.
# -or- maybe we should check to see if we set it, and if we didn't then do a PROTOCOL_ERROR
return Message('TRANSFER_TOKEN_REJECT', ['Option', 'Rejected', []])
elif message.type == 'TRANSFER_TOKEN_RESUME':
encoded_transaction_id = message.data
if not isinstance(encoded_transaction_id, types.StringType):
return ProtocolErrorMessage('TTRs')
# Decode transaction_id
try:
transaction_id = base64.b64decode(encoded_transaction_id)
except TypeError:
return ProtocolErrorMessage('TTRs')
# FIXME: actually handle TRANSFER_TOKEN_RESUMES
elif message.type == 'PROTOCOL_ERROR':
#FIXME: actually do something for a PROTOCOL_ERROR
pass
else:
return ProtocolErrorMessage('TransferTokenRecipient')
############################### Mint key exchange #############################
#Between a wallet and the IS, to get the mint key #
###############################################################################
class fetchMintingKeyProtocol(Protocol):
"""
Used by a wallet to fetch the mints keys, needed when
creating blanks
Lets fetch by denomination
>>> fmp = fetchMintingKeyProtocol(denominations=['1'])
>>> fmp.state(Message(None))
<Message('HANDSHAKE',{'protocol': 'opencoin 1.0'})>
>>> fmp.state(Message('HANDSHAKE_ACCEPT'))
<Message('MINTING_KEY_FETCH_DENOMINATION',[['1'], '0'])>
>>> from tests import mintKeys
>>> mintKey = mintKeys[0]
>>> fmp.state(Message('MINTING_KEY_PASS',[mintKey.toPython()]))
<Message('GOODBYE',None)>
And now by keyid
>>> fmp = fetchMintingKeyProtocol(keyids=['sj17RxE1hfO06+oTgBs9Z7xLut/3NN+nHJbXSJYTks0='])
>>> fmp.state(Message(None))
<Message('HANDSHAKE',{'protocol': 'opencoin 1.0'})>
>>> fmp.state(Message('HANDSHAKE_ACCEPT'))
<Message('MINTING_KEY_FETCH_KEYID',['sj17RxE1hfO06+oTgBs9Z7xLut/3NN+nHJbXSJYTks0='])>
>>> fmp.state(Message('MINTING_KEY_PASS',[mintKey.toPython()]))
<Message('GOODBYE',None)>
Lets have some problems a failures (we set the state
to getKey to reuse the fmp object and save a couple
of lines)
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_FAILURE',[['RxE1', 'Unknown key_identifier']]))
<Message('GOODBYE',None)>
Now lets break something
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('FOOBAR'))
<Message('PROTOCOL_ERROR','send again')>
Okay. Now we'll test every possible MINTING_KEY_PASS.
The correct argument is a list of coins. Try things to
break it.
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_PASS', [['foo']]))
<Message('PROTOCOL_ERROR','send again')>
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_PASS', ['foo']))
<Message('PROTOCOL_ERROR','send again')>
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_PASS', 'foo'))
<Message('PROTOCOL_ERROR','send again')>
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_PASS', []))
<Message('PROTOCOL_ERROR','send again')>
Now try every possible bad MINTING_KEY_FAILURE.
Note: it may make sense to verify we have tood reasons
as well.
We need to make sure we are setup as handling keyids
>>> fmp.keyids and not fmp.denominations
True
Check base64 decoding causes failure
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_FAILURE', [[1, '']]))
<Message('PROTOCOL_ERROR','send again')>
And the normal tests
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_FAILURE', [[]]))
<Message('PROTOCOL_ERROR','send again')>
Okay. Check the denomination branch now
>>> fmp.denominations = ['1']
>>> fmp.keyids = None
Make sure we are in the denomination branch
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_FAILURE', [['1', '']]))
<Message('GOODBYE',None)>
Do a check
>>> fmp.newState(fmp.getKey)
>>> fmp.state(Message('MINTING_KEY_FAILURE', [[]]))
<Message('PROTOCOL_ERROR','send again')>
"""
def __init__(self,denominations=None,keyids=None,time=None):
self.denominations = denominations
self.keyids = keyids
self.keycerts = []
if not time: # The encoded value of time
self.encoded_time = '0'
else:
self.encoded_time = containers.encodeTime(time)
Protocol.__init__(self)
def start(self,message):
self.newState(self.requestKey)
return Message('HANDSHAKE',{'protocol':'opencoin 1.0'})
def requestKey(self,message):
"""Completes handshake, asks for the minting keys """
if message.type == 'HANDSHAKE_ACCEPT':
if self.denominations:
self.newState(self.getKey)
return Message('MINTING_KEY_FETCH_DENOMINATION',[self.denominations, self.encoded_time])
elif self.keyids:
self.newState(self.getKey)
return Message('MINTING_KEY_FETCH_KEYID',self.keyids)
elif message.type == 'HANDSHAKE_REJECT':
self.newState(self.finish)
return Message('GOODBYE')
else:
return Message('PROTOCOL ERROR','send again')
def getKey(self,message):
"""Gets the actual key"""
if message.type == 'MINTING_KEY_PASS':
if not isinstance(message.data, types.ListType):
return ProtocolErrorMessage('MKP1')
if len(message.data) == 0: # Nothing in the message
return ProtocolErrorMessage('MKP2')
try:
keys = [containers.MintKey().fromPython(key) for key in message.data]
except AttributeError: #FIXME: Correct error?
return ProtocolErrorMessage('MKP3')
except TypeError:
return ProtocolErrorMessage('MKP4')
except IndexError:
return ProtocolErrorMessage('MKP5')
#TODO: Check to make sure we got the keys we asked for, probably?
# Note: keycerts stores the value of the MintKeys. They get checked by the
# wallet explicitly
self.keycerts.extend(keys)
self.newState(self.finish)
return Message('GOODBYE')
elif message.type == 'MINTING_KEY_FAILURE':
reasons = message.data
if not isinstance(reasons, types.ListType):
return ProtocolErrorMessage('MKF1')
if not reasons:
return ProtocolErrorMessage('MKF2')
for reasonlist in reasons:
if not isinstance(reasonlist, types.ListType):
return ProtocolErrormessage('MKF3')
try:
key, rea = reasonlist
except ValueError:
return ProtocolErrorMessage('MKF4')
if not isinstance(key, types.StringType):
return ProtocolErrorMessage('MKF5')
if not isinstance(rea, types.StringType):
return ProtocolErrorMessage('MKF6')
# Do not do any conversions of keyid/denomination at this time. Have
# to wait to do it after we know which set we have
self.reasons = []
if self.denominations: # Was a denomination search
for reasonlist in message.data:
denomination, reason = reasonlist
#FIXME: Should we make sure valid reason?
#FIXME: Did we even ask for this denomination?
self.reasons.append((denomination, reason))
else: # Was a key_identifier search
import base64
for reasonlist in message.data:
key, reason = reasonlist
#FIXME: Should we make sure valid reason?
#FIXME: Did we even ask for this denomination
# Note: Explicit b64decode here
try:
self.reasons.append((base64.b64decode(key), reason))
except TypeError:
return ProtocolErrorMessage('MKF9')
self.newState(self.finish)
return Message('GOODBYE')
elif message.type == 'PROTOCOL_ERROR':
pass
else:
return ProtocolErrorMessage('fetchMintingKeyProtocol')
class giveMintingKeyProtocol(Protocol):
"""An issuer hands out a key. The other side of fetchMintingKeyProtocol.
>>> from entities import Issuer
>>> issuer = Issuer()
>>> issuer.createMasterKey(keylength=512)
>>> issuer.makeCDD(currency_identifier='http://opencent.net/OpenCent2', denominations=['1', '2'],
... short_currency_identifier='OC', options=[], issuer_service_location='here')
>>> now = 0; later = 1; much_later = 2
>>> pub1 = issuer.createSignedMintKey('1', now, later, much_later)
>>> gmp = giveMintingKeyProtocol(issuer)
>>> gmp.state(Message('HANDSHAKE',{'protocol': 'opencoin 1.0'}))
<Message('HANDSHAKE_ACCEPT',None)>
>>> gmp.state(Message('MINTING_KEY_FETCH_DENOMINATION',[['1'], '0']))
<Message('MINTING_KEY_PASS',[[('key_identifier', '...'), ('currency_identifier', 'http://opencent.net/OpenCent2'), ('denomination', '1'), ('not_before', '...T...Z'), ('key_not_after', '...T...Z'), ('token_not_after', '...T...Z'), ('public_key', '...,...'), ['signature', [('keyprint', '...'), ('signature', '...')]]]])>
>>> gmp.newState(gmp.giveKey)
>>> m = gmp.state(Message('MINTING_KEY_FETCH_KEYID',[pub1.encodeField('key_identifier')]))
>>> m
<Message('MINTING_KEY_PASS',[...])>
>>> gmp.newState(gmp.giveKey)
>>> gmp.state(Message('MINTING_KEY_FETCH_DENOMINATION',[['2'], '0']))
<Message('MINTING_KEY_FAILURE',[['2', 'Unknown denomination']])>
>>> gmp.newState(gmp.giveKey)
>>> gmp.state(Message('MINTING_KEY_FETCH_KEYID',['NonExistantIDxxx']))
<Message('MINTING_KEY_FAILURE',[['NonExistantIDxxx', 'Unknown key_identifier']])>
>>> gmp.newState(gmp.giveKey)
>>> gmp.state(Message('bla','blub'))
<Message('PROTOCOL_ERROR','send again')>
"""
def __init__(self,issuer):
self.issuer = issuer
Protocol.__init__(self)
def start(self,message):
if message.type == 'HANDSHAKE':
if message.data['protocol'] == 'opencoin 1.0':
self.newState(self.giveKey)
return Message('HANDSHAKE_ACCEPT')
else:
self.newState(self.goodbye)
return Message('HANDSHAKE_REJECT','did not like the protocol version')
else:
return Message('PROTOCOL_ERROR','please do a handshake')
def giveKey(self,message):
self.newState(self.goodbye)
errors = []
keys = []
if message.type == 'MINTING_KEY_FETCH_DENOMINATION':
try:
denominations, time = message.data
except ValueError: # catch tuple unpack errors
return Message('PROTOCOL_ERROR', 'send again')
if not isinstance(denominations, types.ListType):
return ProtocolErrorMessage('MKFD')
if not denominations: # no denominations sent
return ProtocolErrorMessage('MKFD')
for denomination in denominations:
if not isinstance(denomination, types.StringType):
return ProtocolErrorMessage('MKFD')
if not isinstance(time, types.StringType):
return ProtocolErrorMessage('MKFD')
if time == '0':
time = self.issuer.getTime()
else:
try:
time = containers.decodeTime(time)
except ValueError:
return ProtocolErrorMessage('MKFD')
for denomination in denominations:
try:
key = self.issuer.getKeyByDenomination(denomination, time)
keys.append(key)
except 'KeyFetchError':
errors.append([denomination, 'Unknown denomination'])
elif message.type == 'MINTING_KEY_FETCH_KEYID':
import base64
encoded_keyids = message.data
if not isinstance(encoded_keyids, types.ListType):
return ProtocolErrorMessage('MKFK1')
if not encoded_keyids:
return ProtocolErrorMessage('MKFK2')
for encoded_keyid in encoded_keyids:
if not isinstance(encoded_keyid, types.StringType):
return ProtocolErrorMessage('MKFK3')
# Decode keyids
try:
keyids = [base64.b64decode(keyid) for keyid in encoded_keyids]
except TypeError:
return ProtocolErrorMessage('MKFK4')
for keyid in keyids:
try:
key = self.issuer.getKeyById(keyid)
keys.append(key)
except 'KeyFetchError':
errors.append([base64.b64encode(keyid), 'Unknown key_identifier'])
else:
return Message('PROTOCOL_ERROR', 'send again')
if not errors:
return Message('MINTING_KEY_PASS',[key.toPython() for key in keys])
else:
return Message('MINTING_KEY_FAILURE',errors)
############################### For testing ########################################
class WalletSenderProtocol(Protocol):
"""
This is just a fake protocol, just showing how it works
>>> sp = WalletSenderProtocol(None)
It starts with sending some money
>>> sp.state(Message(None))
<Message('sendMoney',[1, 2])>
>>> sp.state(Message('Foo'))
<Message('Please send a receipt',None)>
Lets give it a receipt
>>> sp.state(Message('Receipt'))
<Message('Goodbye',None)>
>>> sp.state(Message('Bla'))
<Message('finished',None)>
>>> sp.state(Message('Bla'))
<Message('finished',None)>
"""
def __init__(self,wallet):
'we would need a wallet for this to work'
self.wallet = wallet
Protocol.__init__(self)
def start(self,message):
'always set the new state before returning'
self.state = self.waitForReceipt
return Message('sendMoney',[1,2])
def waitForReceipt(self,message):
'after sending we need a receipt'
if message.type == 'Receipt':
self.state=self.finish
return Message('Goodbye')
else:
return Message('Please send a receipt')
class WalletRecipientProtocol(Protocol):
def __init__(self,wallet=None):
self.wallet = wallet
Protocol.__init__(self)
def start(self,message):
if message.type == 'sendMoney':
if self.wallet:
self.wallet.coins.extend(message.data)
self.state=self.Goodbye
return Message('Receipt')
else:
return Message('Please send me money, mama')
def Goodbye(self,message):
self.state = self.finish
return Message('Goodbye')
if __name__ == "__main__":
import doctest,sys
if len(sys.argv) > 1 and sys.argv[-1] != '-v':
name = sys.argv[-1]
gb = globals()
verbose = '-v' in sys.argv
doctest.run_docstring_examples(gb[name],gb,verbose,name)
else:
doctest.testmod(optionflags=doctest.ELLIPSIS)
| true |
404fd6560db9679e71c08e56cb590b79070a852a
|
Python
|
hazardland/train.py
|
/poloniex/public.py
|
UTF-8
| 780 | 2.8125 | 3 |
[] |
no_license
|
from urllib import request
from datetime import datetime
class InvalidPeriond(Exception):
pass
def returnChartData(currencyPair, start, end, period=300):
if period not in (300, 900, 1800, 7200, 14400, 86400):
raise InvalidPeriond
if isinstance(start, str):
start = int(datetime.strptime(start, '%Y-%m-%d %H:%M:%S').timestamp())
if isinstance(end, str):
end = int(datetime.strptime(end, '%Y-%m-%d %H:%M:%S').timestamp())
url = ('https://poloniex.com/public?command=returnChartData'
'¤cyPair=%s'
'&start=%s'
'&end=%s'
'&period=%s'
%
(currencyPair, start, end, period))
print(url)
result = request.urlopen(url)
print(result.peek())
return result
| true |
67377118c0977f4313aa98963d457804a7373435
|
Python
|
CormacMOB/UnixCommands
|
/head.py
|
UTF-8
| 2,773 | 3.09375 | 3 |
[] |
no_license
|
from docopt import docopt
import fileinput
import sys
# Docopt configuration string. See Docopt.org.
doc ="""
Usage:
head1.py [-c <N>| -n <N>] [-q | -v] [FILENAME...]
head1.py [FILENAME...]
Options:
-c <N>, --bytes=N print the first N bytes of each file
-n <N>, --lines=N
-q, --quiet
-v, --verbose
"""
args = docopt(doc, argv=sys.argv[1:], help=True, version=None)
class LineObject(object):
def __init__(self,N,filename):
self.length = abs(int(N))
self.filename = filename
self.data_to_print = ""
self.source = open(filename, 'r')
if int(N) > 0:
for line in range(0,self.length):
self.data_to_print = self.data_to_print + self.source.readline()
else:
data = self.source.read().split('\n') # create a list of the lines in the file
for element in data[:(len(data)-self.length)]:
self.data_to_print = self.data_to_print + element + '\n'
class ByteObject(object):
def __init__(self,N,filename):
self.length = abs(int(N))
self.filename = filename
self.data_to_print = ""
self.source = open(filename, 'r')
if int(N) > 0:
self.data_to_print = self.source.read(self.length)
else:
data = self.source.read()
self.data_to_print = data[:(len(data)-self.length)]
def decorate_verbose(data, filename):
header = "==>%s<==\n" % filename
modified_data_to_print = "" + header + data
return modified_data_to_print
def main():
if args['--bytes'] == None and args['--lines'] == None and not args['FILENAME']:
for i in range(0,10):
data = raw_input()
print data
elif args['--bytes'] != None and not args['FILENAME']:
data = sys.stdin.read(int(args['--bytes']))
print data
elif args['--lines'] != None and not args['FILENAME']:
for i in range(1,int(args['--lines'])):
data = raw_input()
print data
else:
outputs = []
for File in args['FILENAME']:
if args['--bytes']:
outputs.append(ByteObject(args['--bytes'],File))
elif args['--lines']:
outputs.append(LineObject(args['--lines'],File))
else:
outputs.append(LineObject('10',File))
if args['--verbose']:
for item in outputs:
print decorate_verbose(item.data_to_print, item.filename)
else:
for item in outputs:
print item.data_to_print
if __name__ == "__main__":
main()
| true |
e4c1c1f57c88c01a4d2399530646a94564572021
|
Python
|
maxotar/algorithms
|
/algorithms/insertionSort.py
|
UTF-8
| 255 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
def insertionSort(alist):
for endpoint in range(len(alist) - 1):
for i in range(endpoint, -1, -1):
if alist[i] > alist[i + 1]:
alist[i + 1], alist[i] = alist[i], alist[i + 1]
else:
break
| true |
f193f642845923b49550b594d2f28c10248c8924
|
Python
|
emanoelmlsilva/Lista-IP
|
/exercicio03/uri1018.py
|
UTF-8
| 590 | 3.1875 | 3 |
[] |
no_license
|
n = int(input())
c = 100
l = 50
t = 20
x = 10
v = 5
d = 2
u = 1
if((n>0) and (n<1000000)):
resc = n // c
n = n%c
resl = n // l
n = n%l
rest = n // t
n = n%t
resx = n // x
n = n%x
resv = n // v
n = n%v
resd = n // d
n = n%d
resu = n
print('{} nota(s) de R$100,00'.format(resc))
print('{} nota(s) de R$50,00'.format(resl))
print('{} nota(s) de R$20,00'.format(rest))
print('{} nota(s) de R$10,00'.format(resx))
print('{} nota(s) de R$5,00'.format(resv))
print('{} nota(s) de R$2,00'.format(resd))
print('{} nota(s) de R$1,00'.format(resu))
| true |
70d049b3fa8384fc527c4f5458af458d9d0a248d
|
Python
|
AP-MI-2021/lab-4-AdrianSK75
|
/assignment_4.py
|
UTF-8
| 2,360 | 3.96875 | 4 |
[] |
no_license
|
def hiding_repeted_chars(lst):
result = []
for i in lst:
if i not in result:
result.append(i)
print(result)
def find_the_str(string, lst):
if any(string in word for word in lst):
print("Yes")
else:
print("No")
def find_repeated_string(lst):
frq = {}
max_frq = 0
max_str_frq = ""
for string in lst:
if string not in frq:
frq[string] = 1
else:
if max_frq < frq[string]:
max_frq = frq[string]
max_str_frq = string
frq[string] += 1
print(max_str_frq)
def display_the_palindroms(lst):
palindromes = []
for word in lst:
length = len(word) - 1
index = 0
is_palindrome = 0
while index < length:
if word[index] == word[length]:
is_palindrome = 1
else:
is_palindrome = 0
index+=1
length-=1
if is_palindrome:
palindromes.append(word)
print(palindromes)
def display_the_frq_array(lst):
frq = {}
max_char = ""
max_frq_char = 0
for word in lst:
for char in word:
if char not in frq:
frq[char] = 1
else:
if frq[char] > max_frq_char:
max_char = char
max_frq_char = frq[char]
frq[char] += 1
for word in lst:
if any(max_char in c for c in word):
print(max_frq_char + 1)
else:
print(word)
def main():
problem = input("Choose a problem: ")
if problem == "1":
n = int(input("Read the length: "))
lst = []
print("Read the array elements: ")
for i in range(n):
lst.append(input())
hiding_repeted_chars(lst)
elif problem == "2":
string = input("Read a string: ")
lst = ['aaa', 'bbb', 'cmtc', 'drd', 'aaa']
find_the_str(string, lst)
elif problem == "3":
lst = ['aaa', 'bbb', 'cmtc', 'drd', 'aaa']
find_repeated_string(lst)
elif problem == "4":
lst = ['ada', 'abc', 'cmtc', 'drd', 'aaa']
display_the_palindroms(lst)
elif problem == "5":
lst = ['aaa', 'bbab', 'caamtc', 'drd', 'aaa']
display_the_frq_array(lst)
if __name__ == '__main__':
main()
| true |
ab65127c8dad0c6f36b9ffc847450b48b07bfacc
|
Python
|
engrborhanbd/Frequent-Itemset-Mining
|
/association_rules/frequent_itemset_mining.py
|
UTF-8
| 16,470 | 2.78125 | 3 |
[] |
no_license
|
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
import numpy as np
class FrequentItemsetAlgorithm():
"""Base class"""
def __init__(self):
self.support_dict = {} # records all frequent itemset
self.TXs_amount = 0
self.TXs_sets = []
self.item_sets = set()
def proccess_input_data(self, filename):
pass
def save_output(self, filename):
print("Saving output to file:", filename)
# supportList = sorted(self.support_dict.items(), key=lambda t: len(t[0]))
with open(filename, 'w') as fp:
for k, v in self.support_dict.items():
items = ' '.join([str(item) for item in sorted(k)])
fp.write('{} ({})\n'.format(items, v))
def calculate_one_item_support(self):
pass
def refresh_support(self, dict_to_check=None):
pass
def check_minimum_support(self, min_support_ratio, dict_to_check=None):
to_be_pruned = []
if dict_to_check is None:
dict_to_check = self.support_dict
for k, v in dict_to_check.items():
if v / float(self.TXs_amount) < min_support_ratio:
to_be_pruned.append(k)
for k in to_be_pruned:
dict_to_check.pop(k)
def find_supersets_k(self, min_support_ratio):
pass
class Apriori(FrequentItemsetAlgorithm):
def __init__(self):
super().__init__()
def proccess_input_data(self, filename):
print('Processing data input...')
with open(filename, 'r') as fp:
for line in fp:
tx = [int(item) for item in line.split()]
self.TXs_sets.append(frozenset(tx))
for item in tx:
self.item_sets.add(frozenset([item]))
self.TXs_amount = len(self.TXs_sets)
def calculate_one_item_support(self):
self.support_dict = {}
for tx in self.TXs_sets:
for item in self.item_sets:
if item.issubset(tx):
try:
self.support_dict[item] += 1
except KeyError:
self.support_dict[item] = 1
def refresh_support(self, dict_to_check=None):
if not dict_to_check or type(dict_to_check) != dict:
return
for tx in self.TXs_sets:
for k in dict_to_check.keys():
if k.issubset(tx):
dict_to_check[k] += 1
def find_supersets_k(self, min_support_ratio):
# Start from Level 1 (One item)
self.calculate_one_item_support()
self.check_minimum_support(min_support_ratio)
# Iterates to higher k+1 level, till None
previous_level_dict = self.support_dict
while True:
print("> Finding next level superset from", len(
previous_level_dict.items()), "k-1 items..")
# New dict for this new level
current_level_dict = dict()
items = list(previous_level_dict.items())
item_sets = set()
for item in previous_level_dict.keys():
item_sets.add(item)
for i in range(len(items)):
for j in range(i+1, len(items)):
k1, v1 = items[i]
k2, v2 = items[j]
new_key = k1 | k2
# Below checks if the new_key's length matches with the current level
continue_flag = 0
for k in new_key:
temp_set = frozenset(new_key - set({k}))
test_set = frozenset([temp_set])
if not test_set.issubset(item_sets):
continue_flag = 1
break
if new_key not in self.support_dict and continue_flag == 0:
current_level_dict[new_key] = 0
self.refresh_support(current_level_dict)
self.check_minimum_support(min_support_ratio, current_level_dict)
if len(current_level_dict.items()) == 0:
print("Frequent Itemsets generation finished !!!")
return
# Take this k level output to generate k+1 level
previous_level_dict = current_level_dict
# Update into support_dict, records all frequent itemset
self.support_dict.update(current_level_dict)
class Eclat(FrequentItemsetAlgorithm):
DATA_STRUCT_AVAILABLE = {
'TIDSET': 1,
# 'naive_bit': 2,
# 'compressed_bit': 3,
'np_bit_array': 4
}
GPU_MOD = SourceModule("""
__device__ void warpReduce(volatile int* sdata, int tid) {
sdata[tid] += sdata[tid + 32];
sdata[tid] += sdata[tid + 16];
sdata[tid] += sdata[tid + 8];
sdata[tid] += sdata[tid + 4];
sdata[tid] += sdata[tid + 2];
sdata[tid] += sdata[tid + 1];
}
__global__ void count_support(char *g_idata, int *g_odata, int *DATA_SIZE) {//(char *bit_array, int *itemset_id, int *ITEM_SIZE, int *g_odata, int *DATA_SIZE) {
extern __shared__ int sdata[];
unsigned int tid = threadIdx.x;
unsigned int bid = blockIdx.x;
sdata[tid] = 0;
for (unsigned int i = bid * (blockDim.x) + tid; i< (*DATA_SIZE); i+=gridDim.x*blockDim.x){
sdata[tid] += g_idata[i];
__syncthreads();
}
__syncthreads();
for (unsigned int s=blockDim.x/2; s>32; s>>=1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid < 32) warpReduce(sdata, tid);
// write result for this block to global mem
if (tid == 0) {
g_odata[blockIdx.x] = sdata[0];
}
}
__global__ void op_and(char *bit_array, char *op_and_odata, int *itemset_id, int *ITEM_SIZE, int *DATA_SIZE)
{
/*
bit_array
01000...1100.. [1st]
10010...0111.. [2nd]
11011...1101.. [3nd]
..
..
*/
int index = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
int offset0 = itemset_id[0]*(*DATA_SIZE);
for (int i = index; i < *DATA_SIZE; i += stride){
op_and_odata[i] = bit_array[i + offset0];
if(!op_and_odata[i]) continue;
for (int j = 1; j < *ITEM_SIZE; j+=1) {
op_and_odata[i] = op_and_odata[i] & bit_array[i + itemset_id[j]*(*DATA_SIZE)];
if(!op_and_odata[i]) break;
}
}
}
""")
def __init__(self, use_data_struc='np_bit_array', use_gpu=False, block_param_opAND=(512,1,1), grid_param_opAND=(128,1), block_param_sum=(512,1,1), grid_param_sum=(128,1)):
"""
Arg:
use_data_struc = ['TIDSET', 'np_bit_array']
"""
super().__init__()
self.tidset_data = dict()
self.bitvector_data_with_numpy = dict()
self.use_gpu = use_gpu
if use_gpu:
# block, grid param for two gpu functions
self.block_param_opAND = block_param_opAND
self.grid_param_opAND = grid_param_opAND
self.block_param_sum = block_param_sum
self.grid_param_sum = grid_param_sum
self.data_gpu = None
self.shared_mem = None
self.result = None
self.result_gpu = None
self.num_of_TXs_gpu = None
self.op_and_func = self.GPU_MOD.get_function("op_and")
self.count_support = self.GPU_MOD.get_function("count_support")
self.bit_2DArray_index = None
self.bit_2DArray_gpu = None
self.bit_vec_keys_gpu = None
self.itemset_size_gpu = None
if use_data_struc not in self.DATA_STRUCT_AVAILABLE.keys():
raise ValueError(
"Data struc not available! Only ['TIDSET', 'np_bit_array'] ")
self.data_struc = self.DATA_STRUCT_AVAILABLE[use_data_struc]
def proccess_input_data(self, filename):
print('Processing data input...')
with open(filename, 'r') as fp:
txCnt = 0
for idx, line in enumerate(fp):
tx = [int(item) for item in line.split()]
self.TXs_sets.append(frozenset(tx))
for item in tx:
self.item_sets.add(frozenset([item]))
key = frozenset([item])
if key in self.tidset_data.keys():
self.tidset_data[key].update({txCnt})
else:
self.tidset_data[key] = set({txCnt})
txCnt += 1
# Create numpy bit array
print('Creating bit vector from TIDSET...')
for item in self.tidset_data.keys():
bit_array = np.zeros(txCnt, dtype=np.int8)
for tid in self.tidset_data[item]:
bit_array[tid] = np.int8(1)
self.bitvector_data_with_numpy[item] = bit_array
self.TXs_amount = txCnt
# Initialize data for GPU processing
# memcpy is timeconsuming, do it first here
if self.use_gpu:
print('Initializing GPU MEM')
# Store output of the first func op_and and use as input to count_support
intermediate_data = np.zeros([txCnt], dtype=np.int8)
self.intermediate_data_gpu = cuda.mem_alloc(intermediate_data.nbytes)
# Final output
self.result = np.zeros([self.block_param_sum[0]], dtype=np.int32)
self.result_gpu = cuda.mem_alloc(self.result.nbytes)
cuda.memcpy_htod(self.result_gpu, self.result)
# Store Bit vector length = TX amount
num_of_TXs = np.int32(txCnt)
self.num_of_TXs_gpu = cuda.mem_alloc(num_of_TXs.nbytes)
cuda.memcpy_htod(self.num_of_TXs_gpu, num_of_TXs)
# GPU func count_support needs shared mem (4 * thread_size)
self.shared_mem = 4* self.block_param_sum[0]
# Store the keys of bit vector to do intersection func on GPU
bit_vec_keys = np.arange(2603, dtype=np.int32)
self.bit_vec_keys_gpu = cuda.mem_alloc(bit_vec_keys.nbytes)
bit_vec_keys_size = np.int32(2603)
self.bit_vec_keys_size_gpu = cuda.mem_alloc(bit_vec_keys_size.nbytes)
# Copy All Bit vector into gpu
bit_2DArray_key_val = sorted(self.bitvector_data_with_numpy.items(), key=lambda x: tuple(x[0]))
bit_2DArray = []
self.bit_2DArray_index = {}
for idx, item in enumerate(bit_2DArray_key_val):
self.bit_2DArray_index[list(item[0])[0]] = idx
bit_2DArray.append(item[1])
bit_2DArray = np.array(bit_2DArray, dtype=np.uint8)
self.bit_2DArray_gpu = cuda.mem_alloc(bit_2DArray.nbytes)
cuda.memcpy_htod(self.bit_2DArray_gpu, bit_2DArray)
print("Whole bit vector copied to GPU Mem! shape:",bit_2DArray.shape, "size:", bit_2DArray.nbytes, "bytes")
def calculate_one_item_support(self):
self.support_dict = dict()
if self.data_struc == self.DATA_STRUCT_AVAILABLE['TIDSET']:
# Operation with Tidset data
for key, tidset in self.tidset_data.items():
self.support_dict[key] = len(tidset)
elif self.data_struc == self.DATA_STRUCT_AVAILABLE['np_bit_array']:
# Operation with numpy bit array
for key, bit_array in self.bitvector_data_with_numpy.items():
self.support_dict[key] = np.sum(bit_array)
def refresh_support(self, dict_to_check=None):
if self.data_struc == self.DATA_STRUCT_AVAILABLE['TIDSET']:
# Operation with Tidset data
for key in dict_to_check.keys():
tidsets = [self.tidset_data[frozenset([item])] for item in key]
intersect = set.intersection(*tidsets)
dict_to_check[key] = len(intersect)
elif self.data_struc == self.DATA_STRUCT_AVAILABLE['np_bit_array']:
# Operation with numpy bit array
if self.use_gpu is True:
# Use gpu to do intersection & count support
for key in dict_to_check.keys():
# Find what keys to do intersections on their bitvectors
bit_vec_keys = np.array([self.bit_2DArray_index[item] for item in key], dtype=np.int32)
cuda.memcpy_htod(self.bit_vec_keys_gpu, bit_vec_keys)
bit_vec_keys_size = np.int32(len(bit_vec_keys))
cuda.memcpy_htod(self.bit_vec_keys_size_gpu, bit_vec_keys_size)
# Do Intersection first
self.op_and_func(self.bit_2DArray_gpu, self.intermediate_data_gpu, self.bit_vec_keys_gpu, self.bit_vec_keys_size_gpu, self.num_of_TXs_gpu, block=self.block_param_opAND, grid=self.grid_param_opAND)
# Then Count support
self.count_support(self.intermediate_data_gpu, self.result_gpu, self.num_of_TXs_gpu, block=self.block_param_sum, grid=self.grid_param_sum, shared=self.shared_mem)
cuda.memcpy_dtoh(self.result, self.result_gpu)
dict_to_check[key] = np.sum(self.result)
else:
for key in dict_to_check.keys():
bitvec_sets = [
self.bitvector_data_with_numpy[frozenset([item])] for item in key]
res = bitvec_sets[0]
for i in range(1, len(bitvec_sets)):
res = res*bitvec_sets[i]
dict_to_check[key] = np.sum(res)
def find_supersets_k(self, min_support_ratio):
# Start from Level 1 (One item)
self.calculate_one_item_support()
self.check_minimum_support(min_support_ratio)
# Iterates to higher k+1 level, till None
previous_itemsets_of_prefix = {0: self.support_dict}
while True:
print("> Finding next level superset from", len(
previous_itemsets_of_prefix.items()), "same prefix itemsets")
# New dict for this new level
current_itemsets_of_prefix = dict()
num_of_super_k_sets_found_in_all_tree = 0
for _, prev_prefix_dict in previous_itemsets_of_prefix.items():
items = list(prev_prefix_dict.items())
for i in range(len(items)):
k1, v1 = items[i]
current_prefix_dict = dict()
for j in range(i+1, len(items)):
k2, v2 = items[j]
new_key = k1 | k2
if new_key not in self.support_dict:
current_prefix_dict[new_key] = 0
self.refresh_support(current_prefix_dict)
self.check_minimum_support(
min_support_ratio, current_prefix_dict)
current_itemsets_of_prefix[k1] = current_prefix_dict
num_of_super_k_sets_found_in_all_tree += len(
current_prefix_dict.items())
if num_of_super_k_sets_found_in_all_tree == 0:
print("Frequent Itemsets generation finished !!!")
return
# Take this k level output to generate k+1 level
previous_itemsets_of_prefix = current_itemsets_of_prefix
# Update into support_dict, records all frequent itemset
for _, current_prefix_dict in current_itemsets_of_prefix.items():
self.support_dict.update(current_prefix_dict)
| true |
9c6b0d3e888e73e7f85c1dfe4245c75d953577d0
|
Python
|
asmodeii/Bomberman
|
/framework/core.py
|
UTF-8
| 1,380 | 3.234375 | 3 |
[] |
no_license
|
import pygame
class GameHandler:
def handle_input(self, event):
pass
def handle_draw(self, canvas):
pass
def handle_update(self, dt):
pass
# noinspection PyMethodMayBeStatic
def running(self) -> bool:
return True
class Game:
def __init__(self, handler: GameHandler, fps=60, scr_width=960,
scr_height=600):
self._handler = handler
self._fps = fps
self._running = False
pygame.init()
self._clock = pygame.time.Clock()
self._screen = pygame.display.set_mode((scr_width, scr_height))
def start(self):
self.run()
def run(self):
while self._handler.running():
dt = self._clock.tick(self._fps)
self.step(dt)
pygame.quit()
def step(self, dt):
for event in pygame.event.get():
if event.type == pygame.QUIT:
import sys
sys.exit()
self._handler.handle_input(event)
self._handler.handle_update(dt)
self._handler.handle_draw(self._screen)
pygame.display.flip()
if __name__ == '__main__':
class SimpleGameHandler(GameHandler):
def running(self):
return True
def handle_draw(self, canvas):
canvas.fill((0, 0, 0xff))
Game(handler=SimpleGameHandler()).start()
| true |
1516fab2e15c37b44911d3522f8135f0a453b37a
|
Python
|
peterwinter/boxcluster
|
/boxlist.py
|
UTF-8
| 7,536 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
from collections import abc
from itertools import permutations
from .mixins import FitnessEqualitiesMixin
import random
import numpy as np
class BaseBoxList(abc.MutableSequence, FitnessEqualitiesMixin):
""" basic class functionality """
def __init__(self, boxes=[], fitness=np.inf):
self.boxes = boxes
self.fitness = fitness
def copy(self):
return self.__class__(boxes=self.boxes.copy(), fitness=self.fitness)
def __getitem__(self, key):
return self.boxes[key]
def __setitem__(self, key, value):
self.boxes[key] = value
def __delitem__(self, key):
del self.boxes[key]
def __len__(self):
return len(self.boxes)
def __repr__(self):
f = round(self.fitness, ndigits=2)
return 'Fit:{f} Boxes: {b}'.format(f=f, b=self.boxes)
def insert(self, key, value):
self.boxes.insert(key, value)
def items(self):
boxes = self.boxes
yield 0, boxes[0]
for begin, end in zip(boxes, boxes[1:]):
yield begin, end
class BoxList(BaseBoxList):
def _random_bounded_pareto(self, limit):
d = np.inf
while d > limit:
d = int(np.ceil((np.random.pareto(0.5))))
return d
def _determine_takeover_size(self, limit):
takeover_size = 1
if limit > 1:
takeover_size = self._random_bounded_pareto(limit=limit)
return takeover_size
def right_join(self, box_pos, size=None):
"""
take some items from box on right.
amount of items taken is _random_bounded_pareto()
None is returned if no box to right.
(ie. box_pos at limit)
"""
# join with the one to the right
candidate = self.copy()
if box_pos == len(self.boxes) - 1:
return
current_edge = candidate[box_pos]
upper_bound = candidate[box_pos + 1]
takeover_limit = (upper_bound - current_edge)
if size is None:
takeover_size = self._determine_takeover_size(limit=takeover_limit)
else:
takeover_size = size
assert takeover_size <= takeover_limit
assert takeover_size >= 0
new_edge = current_edge + takeover_size
# if cut_location is the next box, remove current box
if new_edge == upper_bound:
candidate.pop(box_pos)
# if cut location is smaller than next box, move to next spot
else:
candidate[box_pos] = new_edge
return candidate
def left_join(self, box_pos, size=None):
"""
take some items from box on left.
amount of items taken is _random_bounded_pareto()
this moves the index of the box at box_pos - 1.
None is returned if no box to left.
(ie. box_pos = 0)
"""
candidate = self.copy()
if box_pos == 0:
return
lower_bound = 0 # seems like it should be one?
if box_pos > 1:
lower_bound = candidate[box_pos - 2]
current_edge = candidate[box_pos - 1]
takeover_limit = current_edge - lower_bound
if size is None:
takeover_size = self._determine_takeover_size(limit=takeover_limit)
else:
takeover_size = size
if takeover_size > takeover_limit:
print('takeover:', takeover_size, 'limit:', takeover_limit)
assert takeover_size <= takeover_limit
assert takeover_size >= 0
new_edge = current_edge - takeover_size
if new_edge == lower_bound:
candidate.pop(box_pos - 1)
else:
candidate[box_pos - 1] = new_edge
return candidate
def split(self, box_pos, size=None):
""" return a split list or None if box_pos doesn't work
new item gets inserted at box_pos and existing item
is shifted right.
ie. new item inserted left of existing item
all box_pos are possible
limitations, if the box in a given position is too small... no luck
"""
candidate = self.copy()
upper = candidate[box_pos]
lower = 1
if box_pos > 0:
lower = candidate[box_pos - 1]
r = upper - lower
if r <= 1:
return
if size is None:
cut_location = random.randrange(lower + 1, upper)
else:
assert size > 0
cut_location = upper - size
assert cut_location >= lower + 1
candidate.insert(box_pos, cut_location)
return candidate
def propose_move(self):
"""
1. pick a random position in box list
2. randomly pick if doing a split or join on position
"""
candidate = self.copy()
# split
if random.random() < 0.5 or len(self) == 1:
box_pos = random.randrange(len(self.boxes))
candidate = candidate.split(box_pos)
# join
else:
if random.random() < 0.5:
# join with the one to the left
box_pos = random.randrange(len(self.boxes) - 1)
candidate = candidate.right_join(box_pos)
else:
# join with the one to the right
box_pos = random.randrange(1, len(self.boxes))
candidate = candidate.left_join(box_pos)
return candidate
def to_matrix(self):
"""create coocurance matrix from boxlist"""
print(self)
N = self.boxes[-1]
matrix = np.zeros(shape=(N, N))
# diagonal always true
for i in range(N):
matrix[i, i] = 1
for begin, end in self.items():
a = range(begin, end)
for i, j in permutations(a, 2):
matrix[i, j] = 1
return matrix
@classmethod
def from_matrix(cls, matrix):
"""create boxlist from coocurance matrix"""
# TODO: clean this up. make it readable
row = 0
b = []
N = len(matrix)
for i in range(N):
diff = np.diff(matrix[row])
if -1 in diff:
p0 = np.argmin(diff) + 1
b.append(p0)
row = p0
else:
break
b.append(N)
return BoxList(boxes=b)
def calculate_fitness(self, matrix):
"""least squares
sum of squared error from mean within every box
+ the squared error from mean of every cell outside of a box
"""
fitness = 0.
n = len(matrix)
non_box_mask = np.ones(shape=(n, n), dtype=bool)
# evaluate the least-squares fitness for each box
for begin, end in self.items():
# print(begin, end)
non_box_mask[begin:end, begin:end] = False
if end - begin <= 1:
continue
box_nodes = matrix[begin:end, begin:end].copy()
# print(box_nodes)
np.fill_diagonal(box_nodes, np.nan)
# print(box_nodes)
m = np.nanmean(box_nodes)
# print(m)
sq = (box_nodes - m)**2
fitness += np.nansum(sq)
# print(fitness)
if non_box_mask.any():
# now do it for the non-box nodes
non_box_nodes = matrix[non_box_mask]
# print(non_box_nodes)
m = non_box_nodes.mean()
sq = (non_box_nodes - m)**2
fitness += sq.sum()
# print(fitness)
self.fitness = fitness
return fitness
| true |
4db1b17608f72de3cae19c9e5a4799b399ae6e5c
|
Python
|
Rpratik13/HackerRank
|
/pangram.py
|
UTF-8
| 252 | 3.484375 | 3 |
[] |
no_license
|
def checkPangram(s):
check = [False] * 26
for i in range(len(s)):
if s[i].isalpha():
check[ord(s[i]) - 97] = True
if all(check):
return "pangram"
else:
return "not pangram"
s = input();
print(checkPangram(s.lower()));
| true |
6da8d45397e5e7b60dab534486a6a71c588ba76c
|
Python
|
safoyeth/basher
|
/source/basher.py
|
UTF-8
| 6,061 | 2.71875 | 3 |
[] |
no_license
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
############################################################################
# basher - easy parser of bash.im runet quoter #
# Copyright (C) 2014 Sergey Baravicov aka Safoyeth #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see http://www.gnu.org/licenses/ #
############################################################################
import re
import sys
import random
import requests
try:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
except:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Main(QMainWindow):
'''
Main inherits QMainWindow. Main WIndows of the application
'''
def __init__(self):
'''
initialization
'''
super(Main, self).__init__()
self.index = 0
self.statuz = None
self.text = QTextEdit(self)
self.text.setReadOnly(True)
self.text.setStyleSheet("font-size: 14px; "
"text-align: left;"
"font-family: Verdana;")
self.toolbar = QToolBar(u"Действия", self)
self.getRandomButton = QPushButton(u"Случайная [F5]", self)
self.getNewButton = QPushButton(u"Свежачок! [F4]", self)
self.getNewButton.clicked.connect(self.getNew)
self.getRandomButton.clicked.connect(self.getRandom)
self.status = QStatusBar(self)
self.progress = QProgressBar(self)
self.progress.setRange(0, 10)
self.countLabel = QLabel(u"", self)
self.toolbar.addWidget(self.getNewButton)
self.toolbar.addWidget(self.getRandomButton)
self.toolbar.addWidget(self.countLabel)
self.status.addPermanentWidget(self.progress)
self.addToolBar(self.toolbar)
self.setStatusBar(self.status)
self.setCentralWidget(self.text)
def getRandom(self):
'''
getRandom() - gets random quote from bash.in using requests to get, regular
expression to find the text and random.randint to randomize quotes
'''
self.progress.setValue(2)
self.text.append("<span style='color:green';>BASH.IM {RANDOM}</span></br>")
self.progress.setValue(4)
self.text.append(re.findall('<div class="text">.*</div>',
requests.get("http://bash.im/random").text)[random.randint(0, 10)])
self.progress.setValue(6)
self.text.append("<br/>")
self.progress.setValue(8)
self.index += 1
self.countLabel.setText(u" Цитат получено: %s"%str(self.index))
self.progress.setValue(10)
def getNew(self):
'''
getNew() - gets new quotes. Using requests and regular expression.
Every time when the user runs the script getNew() may be called and
the quotes may be retrieved.
'''
if not self.statuz:
self.progress.setValue(1)
dates = re.findall('<span class="date">.*</span>', requests.get("http://bash.im").text)
for each, date in enumerate(dates):
self.progress.setValue(2)
if dates[each][19:29] == QDate().currentDate().toString("yyyy-MM-dd"):
self.progress.setValue(3)
self.text.append(u"<span style='color:green';>BASH.IM {Свежачок!}</span></br>")
self.progress.setValue(4)
self.text.append(re.findall('<div class="text">.*</div>',
requests.get("http://bash.im").text)[each])
self.progress.setValue(5)
self.text.append("<br/>")
self.progress.setValue(6)
self.index += 1
self.progress.setValue(7)
self.countLabel.setText(u" Цитат получено: %s"%str(self.index))
self.progress.setValue(8)
else:
QMessageBox.information(self, u"Цитатник рунета", u"Свежачка больше пока нет...")
self.progress.setValue(10)
self.statuz = True
self.progress.setValue(10)
else:
QMessageBox.information(self, u"Цитатник рунета", u"Свежачок уже был получен!", QMessageBox.Ok)
self.progress.setValue(10)
def keyPressEvent(self, event):
'''
keyPressEvent() - bind F4 to getNew() and F5 to getRandom().
'''
if event.key() == Qt.Key_F5:
self.getRandom()
if event.key() == Qt.Key_F4:
self.getNew()
def main():
'''
main() - classic routine
'''
application = QApplication(sys.argv)
window = Main()
window.setWindowIcon(QIcon("net.ico"))
application.setStyle("plastique")
window.setWindowTitle(u"Цитатник рунета")
window.showMaximized()
sys.exit(application.exec_())
if __name__ == "__main__":
main()
| true |
be103af19de69f49f264195c6f8d96065766b77e
|
Python
|
zhangguol/Udacity-FullStack-Project1
|
/entertainment_center.py
|
UTF-8
| 578 | 2.65625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# encoding: utf-8
from media import Movie
from fresh_tomatoes import open_movies_page
idenity = Movie(
"Identity",
"http://goo.gl/K4HIeh",
"https://www.youtube.com/watch?v=S8fjyxM7DgU",
"2003"
)
the_prestige = Movie(
"The Prestige",
"http://goo.gl/Bj06fy",
"https://www.youtube.com/watch?v=o4gHCmTQDVI",
"2006"
)
ratatouille = Movie(
"Ratatouille",
"http://goo.gl/r5yOz6",
"https://www.youtube.com/watch?v=c3sBBRxDAqk",
"2007"
)
movies = [idenity, the_prestige, ratatouille]
open_movies_page(movies)
| true |
4ea5bd645194e8952c214603a5a2b71292accb3b
|
Python
|
ilanguev/mongodb
|
/test.py
|
UTF-8
| 455 | 2.734375 | 3 |
[] |
no_license
|
#!/usr/bin/python
from pymongo import MongoClient
import uuid
client = MongoClient('mongodb://10.244.41.118:27017')
db = client.myDB
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
for i in xrange(1,1000000):
post_data['_id'] = uuid.uuid1()
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))
| true |
1c575a7b4e17b3c5f9a23f13302f07b3348e48c3
|
Python
|
natakhatina/file
|
/file_script.py
|
UTF-8
| 345 | 3.453125 | 3 |
[] |
no_license
|
import math,random
def fooCos(x):
yield math.cos(x)
def fooSin(x):
yield math.sin(x)
def foo(n):
x=random.randint(0,180)
x=x* math.pi/180
for i in range(n):
if x%2==0:
a=fooSin(x)
yield next(a)
else:
a=fooCos(x)
yield next(a)
L=[x for x in foo(50)]
print(L)
| true |
c85baa0eb0205f25354733518d4d4e0446bdeb19
|
Python
|
taddeus/advent-of-code
|
/2019/20_donutmaze.py
|
UTF-8
| 2,131 | 3.265625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
import sys
from collections import deque
from itertools import chain
def read_grid(f):
rows = [line.replace('\n', '') for line in f]
return list(chain.from_iterable(rows)), len(rows[0])
def find_labels(grid, w):
def get(i):
return grid[i] if 0 <= i < len(grid) else ' '
def try_label(i, spacediff, outer):
if get(i + spacediff) == '.':
labels.setdefault(label, []).append((i, i + spacediff, outer))
labels = {}
h = len(grid) // w
for i, cell in enumerate(grid):
if cell.isalpha():
y, x = divmod(i, w)
label = get(i) + get(i + 1)
if label.isalpha():
try_label(i, -1, x > w // 2)
try_label(i + 1, 1, x < w // 2)
label = get(i) + get(i + w)
if label.isalpha():
try_label(i, -w, y > h // 2)
try_label(i + w, w, y < h // 2)
return labels
def find_portals(labels):
assert all(len(v) == 2 for v in labels.values())
inner = {}
outer = {}
for (l1, s1, o1), (l2, s2, o2) in labels.values():
assert o1 ^ o2
(outer if o1 else inner)[l1] = s2
(outer if o2 else inner)[l2] = s1
return inner, outer
def shortest_path(grid, w, leveldiff):
labels = find_labels(grid, w)
src = labels.pop('AA')[0][1]
dst = labels.pop('ZZ')[0][1]
inner, outer = find_portals(labels)
work = deque([(src, 0, 0)])
visited = set()
while work:
i, dist, level = work.popleft()
if i == dst and level == 0:
return dist
if (i, level) in visited:
continue
visited.add((i, level))
for nb in (i - 1, i + 1, i - w, i + w):
if grid[nb] == '.':
work.append((nb, dist + 1, level))
elif nb in inner:
work.append((inner[nb], dist + 1, level + leveldiff))
elif nb in outer and level > 0:
work.append((outer[nb], dist + 1, level - leveldiff))
grid, w = read_grid(sys.stdin)
print(shortest_path(grid, w, 0))
print(shortest_path(grid, w, 1))
| true |
04862d762b56e17f8beb8e84fe345162b61bf825
|
Python
|
ouuzannn/BlackAs---Game-Ular
|
/main.py
|
UTF-8
| 8,521 | 2.796875 | 3 |
[] |
no_license
|
import pygame
import sys
import random
import TombolMenu,MenuGame
from konstanta import *
class Ular():
def __init__(self):
self.PanjangUlar = 1
self.letakUlar = [((lebar_layar/2), (tinggi_layar/2))]
self.arahUlar = random.choice([atas, bawah, kiri, kanan])
self.nilai = 0
self.kecepatan = 5
self.hitungmakanan = 0
def PosisiKepalaUlar(self) :
return self.letakUlar[0]
def turn(self, point):
if self.PanjangUlar > 1 and (point[0]*-1, point[1]*-1) == self.arahUlar:
return
else :
self.arahUlar = point
def PergerakanUlar(self) :
cur = self.PosisiKepalaUlar()
x,y = self.arahUlar
new = (((cur[0]+(x*gridsize))%lebar_layar), (cur[1]+(y*gridsize))%tinggi_layar)
if (len(self.letakUlar) > 2 and new in self.letakUlar[2:]) :
#akhir()
cek=0
self.reset()
Menu(cek)
elif cur[0] >= (lebar_layar-20) or cur[0] <= 0 or cur[1] >= (tinggi_layar-20) or cur[1] <= 0:
#akhir()
cek=0
self.reset()
Menu(cek)
else :
self.letakUlar.insert(0,new)
if len(self.letakUlar) > self.PanjangUlar :
self.letakUlar.pop()
def reset(self) :
self.PanjangUlar = 1
self.letakUlar = [((lebar_layar/2), (tinggi_layar/2))]
self.arahUlar = random.choice([atas, bawah, kiri, kanan])
self.nilai = 0
self.kecepatan = 5
self.hitungmakanan = 0
def GambarUlar(self, surface):
PenandaKepala = 0
for p in self.letakUlar:
bagianular = pygame.Rect((p[0], p[1]), (gridsize,gridsize))
if PenandaKepala == 0 :#penanda kepala
self.warna = (25, 24, 47)
pygame.draw.rect(surface, self.warna, bagianular)
else :
self.warna = (255, 24, 47)
pygame.draw.rect(surface, self.warna, bagianular)
pygame.draw.rect(surface, (25,24,228), bagianular, 1)
PenandaKepala +=1
def KontrolUlar(self):
for event in pygame.event.get():
if event.type == pygame.QUIT :
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN :
if event.key == pygame.K_UP:
self.turn(atas)
elif event.key == pygame.K_DOWN :
self.turn(bawah)
elif event.key == pygame.K_LEFT :
self.turn(kiri)
elif event.key == pygame.K_RIGHT :
self.turn(kanan)
class Makanan() :
def __init__(self):
self.letakmakanan = (0,0)
self.warna = (223, 163, 49)
self.PosisiAcakMakanan()
def PosisiAcakMakanan(self):
self.letakmakanan = (random.randint(1, grid_width-2)*gridsize, random.randint(1, grid_height-2)*gridsize)
def gambarObjek(self, surface) :
gambarmakanan = pygame.Rect((self.letakmakanan[0], self.letakmakanan[1]), (gridsize, gridsize))
pygame.draw.rect(surface, self.warna, gambarmakanan)
pygame.draw.rect(surface, (93, 216, 228), gambarmakanan, 1)
class MakananBonus() :
def __init__(self):
self.LetakMakananBonus = (0,0)
#self.warna = [(25, 163, 49), (0,0,0)]
self.PosisiAcakMakanan()
self.timer = 0
self.waktubonus = 25
self.tanda = 0
def PosisiAcakMakanan(self):
self.LetakMakananBonus = (random.randint(1, grid_width-2)*gridsize, random.randint(1, grid_height-2)*gridsize)
def gambarObjek(self, surface, pilihwarna) :
gambarmakananbonus = pygame.Rect(((self.LetakMakananBonus[0]-5), (self.LetakMakananBonus[1]-5)), (30, 30))
pygame.draw.rect(surface, pilihwarna, gambarmakananbonus)
pygame.draw.rect(surface, (93, 216, 228), gambarmakananbonus, 1)
class kotak :
def GambarKotak(self,surface) :
for y in range(0, int(grid_height)) :
for x in range(0, int(grid_width)) :
if (x+y) %2 == 0:
gridgenap = pygame.Rect((x*gridsize, y*gridsize), (gridsize,gridsize))
pygame.draw.rect(surface,(93,216,228), gridgenap)
else :
gridganjil = pygame.Rect((x*gridsize, y*gridsize), (gridsize, gridsize))
pygame.draw.rect(surface, (84,194,205), gridganjil)
#gambarborder
for y in range(0, int(grid_height)) :
for x in range(0, int(grid_width)) :
if (x<1 or y<1 or x>22 or y>22):
xxx = pygame.Rect((x*gridsize, y*gridsize), (gridsize,gridsize))
pygame.draw.rect(surface,(0,0,0), xxx)
#GLOBAL VARIABEL
clock = pygame.time.Clock()
lebar_layar = 480
tinggi_layar = 480
latar = (0, 0, 0)
win = pygame.display.set_mode((lebar_layar, tinggi_layar))
pygame.init()
bonus=bool(0)
waktubatas = 5
gridsize = 20
grid_width = lebar_layar/gridsize
grid_height = tinggi_layar/gridsize
atas = (0, -1)
bawah = (0, 1)
kiri = (-1, 0)
kanan = (1,0)
hitung = 0
def mainin(indeks) :
clock = pygame.time.Clock()
screen = pygame.display.set_mode((lebar_layar, tinggi_layar), 0, 32)
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
#deklarasi objek
papan = kotak()
ular = Ular()
makanan = Makanan()
makananbonus = MakananBonus()
putih=(255, 255, 255)
hijau=(25, 163, 49)
warnaa=[putih,hijau]
hitungwaktu=0
hitung=0
#Setting ukuran dan jenis font dari tulisan score
myfont = pygame.font.SysFont("monospace",18)
while True :
if indeks == 1:
pygame.quit()
sys.exit()
clock.tick(ular.kecepatan) #kecepatan ular
ular.KontrolUlar()
papan.GambarKotak(surface)
ular.PergerakanUlar()
hitung += 1
if ular.PosisiKepalaUlar() == makanan.letakmakanan :
ular.PanjangUlar += 1
ular.nilai += 1
ular.hitungmakanan += 1
makananbonus.timer=0
print("k", ular.kecepatan)
makanan.PosisiAcakMakanan()
if ular.nilai%10==0:
ular.kecepatan = ular.kecepatan * 1.5
makananbonus.waktubonus = makananbonus.waktubonus * 1.5
if(ular.hitungmakanan !=0 and ular.hitungmakanan % 5 == 0):
makananbonus.tanda=1
if ( makananbonus.tanda==1 and makananbonus.timer<makananbonus.waktubonus) :
if hitung%2==0:
pilihwarna=warnaa[0]
else:
pilihwarna=warnaa[1]
makananbonus.gambarObjek(surface, pilihwarna)
makananbonus.timer+=1
if ular.PosisiKepalaUlar() == makananbonus.LetakMakananBonus :
ular.PanjangUlar += 1
ular.nilai += 5
ular.hitungmakanan = 0
makananbonus.tanda=0
makananbonus.timer=0
if ular.nilai%10==0:
ular.kecepatan = ular.kecepatan * 1.5
makananbonus.waktubonus = makananbonus.waktubonus * 1.5
#tampilbonus = 0
makananbonus.PosisiAcakMakanan()
print("t", makananbonus.timer)
print("w", makananbonus.waktubonus)
elif makananbonus.timer>=makananbonus.waktubonus:
makananbonus.tanda=0
ular.GambarUlar(surface)
makanan.gambarObjek(surface)
screen.blit(surface, (0,0)) #menampilkan gambar pada window game
text = myfont.render("Score : {0}".format(ular.nilai), 1, (putih))
screen.blit(text, (20,0))
pygame.display.update()
cek=bool(1)
def Menu(cek):
window = pygame.display.set_mode((lebar_layar, tinggi_layar), 0, 32)
if cek == 1 :
menu = MenuGame.PyMenu(BLACK, lebar_layar/2, 45, "GAME ULAR BLACK AS")
else :
menu = MenuGame.PyMenu(RED, lebar_layar/2, 45, "PERMAINAN BERAKHIR")
# create the buttons
TombolNewGame = TombolMenu.PyButton(lebar_layar/2, 130, "New Game")
TombolQuit = TombolMenu.PyButton(tinggi_layar/2, 220, "Quit")
menu.tambahkanTombol(TombolNewGame, mainin)
menu.tambahkanTombol(TombolQuit, mainin)
# draw the menu
menu.tampilan(window)
if __name__ == '__main__':
Menu(cek)
Menu(cek)
| true |
5c7b10c4e91819adfa2f7fb194f6a0c2983dc68f
|
Python
|
amitarvindpatil/DjangoFrameworkStuff
|
/ORM.py
|
UTF-8
| 2,041 | 3.625 | 4 |
[] |
no_license
|
# ORM - Object Relational Mapper
# Defin Data Modules Entirely in Python.You get Dynamic database-access API for Free
# A Model is the single,definative source of information about your data.
# It contains the required field to store your data Generally each maodel map to a single database table
# The Basic
# -Each Module in python class that subclasses django.db.Models.Model
# -Each Attribute of models represent a database field
# -with all if this ,Django gives you automatically generated database-access
# Example
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Person(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=20)
def __str__(self):
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=100)
pub_date = models.DateField()
rating = models.IntegerField()
def __str__(self):
return self.headline
# Retriving All objects
all_entries = Entry.objects.all()
# Retriving Perticuler Object
pert_entries = Entry.objects.filter(pub_date__year=2006)
pert_entries = Entry.objects.all().filter(pub_date__year=2006)
# Retrieving a single object with get()
one_entry = Entry.objects.get(pk=1)
# Limiting QuerySets¶
# For example, this returns the first 5 objects (LIMIT 5)
first_five = Entry.objects.all()[:5]
# This returns the sixth through tenth objects (OFFSET 5 LIMIT 5):
five_ten = Entry.objects.all()[5:10]
# (e.g. SELECT foo FROM bar LIMIT 1), use an index instead of a slice. For example,
# this returns the first Entry in the database, after ordering entries alphabetically by headline:
op = Entry.objects.order_by('headline')[0]
# Exact Match
op = Entry.objects.get(headline__exact="Cat bites dog")
# Case insensative
Blog.objects.get(name__iexact="beatles blog")
# Like statements
Entry.objects.filter(headline__contains='%')
| true |
100a4dc28a007372c673c30e1079e3c6291e2488
|
Python
|
hishark/Algorithm
|
/LEETCODE/7_整数反转.py
|
UTF-8
| 446 | 2.765625 | 3 |
[] |
no_license
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
temp = ''
if x < 0:
temp += '-'
x = -x
s = str(x)[::-1]
if s[0] == '0':
s = s[1:]
temp += s
result = int(temp)
if -2**31<=result<=2**31-1:
return result
else:
return 0
| true |
9c85960955bfb54175b9b8d841154ca6676f6c78
|
Python
|
nepomnyashchii/TestGit
|
/old/final1/03/put.py
|
UTF-8
| 725 | 2.671875 | 3 |
[] |
no_license
|
import mysql.connector
import time
import uuid
print("Please wait...")
msg = "time3"
exp = 600
pin = 1234
sid = str(uuid.uuid4())
mytime=time.strftime('%Y-%m-%d %H:%M:%S')
return_value = ''
try:
mydb = mysql.connector.connect(
host="db4free.net",
user="coolspammail",
passwd="coolspammail-pass",
database="coolspammail"
)
mycursor = mydb.cursor()
sql = "INSERT INTO secret (id, msg, pin, exp, created) VALUES (%s, %s, %s, %s, %s)"
val = (sid, msg, pin, exp, mytime)
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
return_value = sid
except:
print("Something went wrong")
print('return_value:' + return_value)
| true |
c347c5315c616d6b4251a83474e7989179854579
|
Python
|
sravankr96/kaggle-fisheries-monitoring
|
/src/model_archs/localizer_as_regr.py
|
UTF-8
| 2,914 | 2.875 | 3 |
[] |
no_license
|
"""
Copyright © Sr@1 2017, All rights reserved.
*The module contains the architecture of a localization network
*Network is built analogous to VGG network
*The Hyper parameters of the network are passed from the /tasks/localizer.py module
"""
from keras.models import Sequential
from keras.layers import Activation, Convolution2D, MaxPooling2D, Dropout, Dense, Flatten
import keras.backend as K
class LocalizerAsRegrModel(Sequential):
def __init__(self, hyper_params):
self.optimizer = hyper_params['optimizer']
self.objective = hyper_params['objective']
self.shape = hyper_params['input_shape']
self.activation = hyper_params['activation']
# Building the model
def center_normalize(x):
return (x - K.mean(x)) / K.std(x)
super(LocalizerAsRegrModel, self).__init__()
self.add(Activation(activation=center_normalize, input_shape=self.shape))
# 256
self.add(Convolution2D(16, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='tf'))
# 128
self.add(Convolution2D(32, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(Convolution2D(32, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(Convolution2D(32, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
# 64
self.add(Convolution2D(64, 3, 3, border_mode='same', activation=self.activation, subsample=(2, 2),
dim_ordering='tf'))
self.add(Convolution2D(64, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(Convolution2D(64, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
# 32
self.add(Convolution2D(128, 3, 3, border_mode='same', activation=self.activation, subsample=(2, 2),
dim_ordering='tf'))
self.add(Convolution2D(128, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(Convolution2D(128, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
# 16
self.add(Convolution2D(256, 3, 3, border_mode='same', activation=self.activation, subsample=(2, 2),
dim_ordering='tf'))
self.add(Convolution2D(256, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
self.add(Convolution2D(256, 3, 3, border_mode='same', activation=self.activation, dim_ordering='tf'))
# 8
self.add(MaxPooling2D(pool_size=(4, 4), dim_ordering='tf'))
self.add(Dropout(0.5))
self.add(Flatten())
self.add(Dense(4))
self.compile(loss=self.objective, optimizer=self.optimizer, metrics=['accuracy'])
| true |
54d001367dcdf7d330245ff52d80c86c9f4e89e6
|
Python
|
littleironical/HackerRank_Solutions
|
/Python/Set .discard(), .remove() & .pop().py
|
UTF-8
| 320 | 3 | 3 |
[] |
no_license
|
n = int(input())
a = set(map(int, input().split()))
m = int(input())
for _ in range(m):
command = list(input().split())
if command[0] == "pop":
a.pop()
elif command[0] == "remove":
a.remove(int(command[1]))
elif command[0] == "discard":
a.discard(int(command[1]))
print(sum(a))
| true |
1ff17395be20229cfe6b5216f61b7c2e7d63b774
|
Python
|
miguel-pessoa/VI
|
/scripts/lineData.py
|
UTF-8
| 798 | 3.1875 | 3 |
[] |
no_license
|
import pandas as pd
years = [2016, 2017, 2018, 2019, 2020]
dfs = []
def dfYear(start_df, year):
col = f'happiness_score_{year}'
df = happy_df[['country', col]]
df = df.rename(columns={col: "happy"})
df['year'] = year
print(df.head())
return df
# Read data
happy_df = pd.read_csv('data/final/happy_gov_continent.csv', delimiter=',')
for i in range(0,len(years)):
dfs.append(dfYear(happy_df, years[i]))
output = pd.concat(dfs)
output.to_csv('data/final/lineData.csv', index=False, header=True)
# happy2016 = dfYear(happy_df, 2016)
# happy2017 = dfYear(happy_df, 2017)
# happy2018 = dfYear(happy_df, 2018)
# happy2019 = dfYear(happy_df, 2019)
# happy2020 = dfYear(happy_df, 2020)
# out_df.to_csv('data/final/happy_gov_continent.csv', index=False, header=True)
| true |
a172a02092cb7359ad15112513131a346b3f5f28
|
Python
|
march-saber/UI-
|
/PO_v1/TestCases/test_login.py
|
UTF-8
| 3,058 | 2.65625 | 3 |
[] |
no_license
|
import unittest
from selenium import webdriver
import ddt
from PO_v1.PageObjects.longin_page import LoginPage
from PO_v1.PageObjects.index_page import IndexPage
from PO_v1.TestDatas import login_datas as id
from PO_v1.TestDatas import Comm_Datas as cd
#用例三部曲:前置、步骤、断言
@ddt.ddt
class TestLogin(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 前置 -打开网页。启动浏览器
cls.driver = webdriver.Chrome()
cls.driver.maximize_window()
cls.driver.get("{}/Index/login.html".format(cd.base_url))
#正常用例 - 登陆+首页
def test_login_2_success(self):
#步骤 - 登录操作 - 登录页面
LoginPage(self.driver).login(id.success_data["user"],id.success_data["passwd"]) #测试对象+测试数据
#断言1. - 页面是否存在 我的账户 元素
self.assertTrue(IndexPage(self.driver).check_nick_name_exists())
#断言2.url是否跳转
self.assertEqual(self.driver.current_url,id.success_data["check"]) #current_url获取当前页面的url
#异常用例 -密码为空、用户名为空、用户名不正确、
@ddt.data(*id.wrong_datas) # ddt循环数据,#装饰测试方法,接收可迭代数据,
def test_login_1_failed_by_no_passwd(self,data):
# 步骤 - 登录操作 - 登录页面 - 密码为空 18684720553
LoginPage(self.driver).login(data["user"], data["passwd"])
# 断言 - 面页的提示内容为:请输入密码
self.assertTrue(data["check"],LoginPage(self.driver).get_error_msg_from_loginFrom())
@ddt.data(*id.fail_datas)
def test_login_0_failed_by_fail_datas(self,data):
# 步骤 - 登录操作 - 登录页面 - 未注册的号码 18600000000
LoginPage(self.driver).login(data["user"], data["passwd"])
# 断言 - 面页的提示内容为:此账号没有经过授权,请联系管理员!
self.assertTrue(data["check"], LoginPage(self.driver).get_error_msg_from_pageCenter())
# 异常用例 -无用户名
# def test_login_failed_by_no_user(self):
# # 步骤 - 登录操作 - 登录页面 - 手机号错误 18684720553
# LoginPage(self.driver).login("186847205", "python")
# # 断言 - 面页的提示内容为:请输入密码
# self.assertTrue("请输入手机号", LoginPage(self.driver).get_error_msg_from_loginFrom())
# # 异常用例 - 错误的手机号
# def test_login_failed_by_wrong_user_formater(self):
# # 步骤 - 登录操作 - 登录页面 - 用户名错误 15717481995
# LoginPage(self.driver).login("1868472", "python")
# # 断言 - 面页的提示内容为:请输入密码
# self.assertTrue("请输入正确的手机号", LoginPage(self.driver).get_error_msg_from_loginFrom())
@classmethod
def tearDownClass(cls):
#关闭浏览器,
cls.driver.quit() #关闭所有
def tearDown(self):
#刷新当前页面
self.driver.refresh()
| true |
6329d2e7d01a5392545cd0e8d5cd4a7e849c81ff
|
Python
|
Susaposa/Homwork_game-
|
/solutions/5_methods.py
|
UTF-8
| 5,410 | 4.59375 | 5 |
[] |
no_license
|
# REMINDER: Only do one challenge at a time! Save and test after every one.
print('Challenge 1 -------------')
# Challenge 1:
# Uncomment the following code and fix the typos to practice using the list
# methods. If correct, we should see Shrek, Frozen, Titanic in that order.
my_fave_movies = []
my_fave_movies.append("Titanic")
my_fave_movies.append("Frozen")
my_fave_movies.append("Shrek")
my_fave_movies.reverse()
print(my_fave_movies)
print('Challenge 2 -------------')
# Challenge 2:
# Uncomment the following code and fix the typos to practice using dictionary
# methods. It should print out the dictionary keys, the phrase 'No manners!',
# the dictionary values, and then the word SHREK centered in the screen.
# methods. If correct, we should see Shrek, Frozen, Titanic in that order.
user_info = {
'username': 'shrek',
'location': 'swamp',
'friend': 'donkey',
}
print(user_info.keys())
print(user_info.get('manners', 'No manners!'))
print(user_info.values())
print(user_info.get('manners', 'No manners!'))
print(user_info['username'].upper().center(80))
print('Challenge 3 -------------')
# Challenge 3:
# Uncomment the following code. Modify it using string methods to "sanitize"
# the input. That is to say, make it so that the user can type in weird
# spellings of yes, such as "YeS", " yes " or "YES" to cause the program
# to continue.
answer = 'yes'
while answer == 'yes':
answer = input('Stay in swamp? ')
answer = answer.strip().lower()
print('Leaving swamp...')
print('Challenge 4 -------------')
# Challenge 4:
# The follow is code to create our own class with our own methods. Uncomment
# the code and fix the typos to get it working.
class Ogre:
def say_name(self):
print('My name is Shrek')
def get_friend_name(self):
return 'Donkey'
def get_enemy_name(self):
return 'Lord Farquaad'
shrek = Ogre()
shrek.say_name()
print(shrek.get_friend_name())
print(shrek.get_enemy_name())
print('Challenge 5 -------------')
# Challenge 5:
# Time to get classy! To get more practice with class syntax, create 3 classes:
# One called LordFarquaad, one called PrincessFiona, one called PrinceCharming.
# Each should have 3 methods, each method returning different values.
# --------------------- --------------------- ----------------------
# | LordFarquaad | PrincessFiona | PrinceCharming |
# --------------------- --------------------- ----------------------
# get_title | "Lord" | "Princess" | "Prince" |
# get_name | "Lord Farquaad" | "Princess Fiona" | "Prince Charming" |
# is_villain | True | False | True |
class LordFarquaad:
def get_title(self):
return "Lord"
def get_name(self):
return "Lord Farquaad"
def is_villain(self):
return True
class PrincessFiona:
def get_title(self):
return "Princess"
def get_name(self):
return "Princess Fiona"
def is_villain(self):
return False
class PrinceCharming:
def get_title(self):
return "Prince"
def get_name(self):
return "Prince Charming"
def is_villain(self):
return True
print('----- Farquaad')
farquaad = LordFarquaad()
print(farquaad.get_name())
print(farquaad.get_title())
print(farquaad.is_villain())
print('----- Fiona')
fiona = PrincessFiona()
print(fiona.get_name())
print(fiona.get_title())
print(fiona.is_villain())
print('----- Charming')
charming = PrinceCharming()
print(charming.get_name())
print(charming.get_title())
print(charming.is_villain())
print('-------------')
# Bonus Challenge 1:
# We'll get more into classes more next week. But until then, uncomment and
# examine the following code. See if you understand what is going on. See if
# you can refactor the 3 classes you defined in Challenge 5 to be a single
# class that takes different inputs to the `__init__` method. Once you have
# done that, see if you can create 3 instances of the class, one for each
# character that you made above.
class Ogre:
def __init__(self, name, location):
self.name = name
self.location = location
def get_name(self):
return self.name
def get_location(self):
return self.location
print('----- Shrek')
shrek = Ogre('Shrek', 'swamp')
print(shrek.get_name())
print(shrek.name)
print(shrek.get_location())
print(shrek.location)
class Noble:
def __init__(self, name, title, villain):
self.name = name
self.title = title
self.villain = villain
def get_name(self):
return self.name
def get_title(self):
return self.title
def is_villain(self):
return self.villain
print('----- Farquaad')
farquaad = Noble('Lord Farquaad', 'Lord', True)
print(farquaad.get_name())
print(farquaad.get_title())
print(farquaad.is_villain())
print('----- Fiona')
fiona = Noble('Princess Fiona', 'Princess', False)
print(fiona.get_name())
print(fiona.get_title())
print(fiona.is_villain())
print('----- Charming')
charming = Noble('Prince Charming', 'Prince', True)
print(charming.get_name())
print(charming.get_title())
print(charming.is_villain())
# Advanced Bonus Challenge: See if you can rewrite the bonus challenge from
# 2_functions.py using a class. Hint: Use a single class for "Location", then
# create many instances of that class for each location you can go.
# Separate file!
| true |
168188f6b996f858f1b68b3b5fc3d83f7532f4f2
|
Python
|
xys234/coding-problems
|
/algo/array/find_resolved_interval.py
|
UTF-8
| 1,276 | 3.609375 | 4 |
[] |
no_license
|
"""
Find "resolved" interval, resolved marked as 1. input [0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1] output [(2,4), (7,7), (9,10)]
Find the start and ending indices of consecutive resolved interval
Facebook Infra DS phone interview
"""
class Solution:
def find_resolved_interval(self, intervals):
i = 0
ans = []
while i < len(intervals):
if intervals[i] == 0:
i += 1
else:
j = i
while j < len(intervals):
if intervals[j] == 1:
j += 1
else:
break
ans.append((i, j-1))
i = j
return ans
if __name__ == '__main__':
sol = Solution()
cases = [
(sol.find_resolved_interval, ([0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1],), [(2,4), (7,7), (9,10)]),
(sol.find_resolved_interval, ([0, 0],), []),
(sol.find_resolved_interval, ([1],), [(0, 0)]),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i+1, str(expected), str(ans)))
| true |
a19f44c08eeb59110576eae0a500e1e348386b3d
|
Python
|
IvanVuytsik/RunnerGame_pygame
|
/Game.py
|
UTF-8
| 9,034 | 2.734375 | 3 |
[] |
no_license
|
import pygame
from sys import exit
from random import randint
def display_score():
current_time = int(pygame.time.get_ticks()/1000) - start_time
score_surface = test_font.render(f'Score{current_time}',False,(64,64,64)) #f string conversion
score_rect = score_surface.get_rect(center=(400,50))
screen.blit(score_surface,score_rect)
return current_time
def obstacle_movement (obstacle_list):
if obstacle_list:
for obstacle_rect in obstacle_list:
obstacle_rect.x -= 10
if obstacle_rect.bottom == 385: screen.blit(knight, obstacle_rect)
else: screen.blit(witch, obstacle_rect)
obstacle_list = [obstacle for obstacle in obstacle_list if obstacle.x > -100]
return obstacle_list
else: return []
def collision (hero, obstacles):
if obstacles:
for obstacle_rect in obstacles:
if hero.colliderect(obstacle_rect): return False
return True
def hero_animation():
global hero, hero_index
if hero_rect.bottom < 380:
hero = hero_jump
else:
hero_index += 0.1
if hero_index >= len(hero_walk): hero_index = 0
hero = hero_walk[int(hero_index)]
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption("Currier Knight")
clock = pygame.time.Clock()
test_font = pygame.font.Font('ARCADECLASSIC.TTF', 40)
game_active = False
start_time = 0
score = 0
ground_surface = pygame.image.load('venv/ground0.png').convert_alpha()
#ground_surface = pygame.transform.scale(ground_surface, (800, 400))
sky_surface = pygame.image.load('venv/sky0.png').convert_alpha()
sky_surface = pygame.transform.scale(sky_surface, (800, 400))
#bg = pygame.image.load('venv/castle.jpg').convert_alpha()
#bg = pygame.transform.scale(bg, (800, 400))
#bg_rect = bg.get_rect(bg,(800,400))
#score_surface = test_font.render('My Game', False, (64,64,64)) #text,anti-aliasing,color
#score_rect = score_surface.get_rect(center=(400, 60))
#------------------------hero----------------------------------
hero_walk1 = pygame.image.load('venv/knight0.png').convert_alpha()
hero_walk1 = pygame.transform.scale(hero_walk1, (150, 150))
hero_walk2 = pygame.image.load('venv/knightwalk2.png').convert_alpha()
hero_walk2 = pygame.transform.scale(hero_walk2, (150, 150))
hero_walk = [hero_walk1,hero_walk2]
hero_index = 0
hero_jump = pygame.image.load('venv/knightwalk2.png').convert_alpha()
hero_jump = pygame.transform.scale(hero_jump, (150, 150))
hero = hero_walk[hero_index]
hero_rect = hero.get_rect(midbottom=(100, 200))
hero_rect.inflate_ip(-75,0)
# hero_rect = pygame.Rect (left,top, width, height)
hero_gravity = 0
#------------------------obstacles----------------------------------
knight_stand = pygame.image.load('venv/knight1_stand.png').convert_alpha()
knight_stand = pygame.transform.scale(knight_stand, (150, 150))
knight_move = pygame.image.load('venv/knight1_move.png').convert_alpha()
knight_move = pygame.transform.scale(knight_move, (150, 150))
knight_animation = [knight_stand, knight_move]
knight_index = 0
knight = knight_animation [knight_index]
###knight = pygame.transform.scale(knight, (150, 150))
###knight_rect = knight.get_rect(midbottom=((650, 350)))
###knight_rect.inflate_ip(-50,-75)
witch_stand = pygame.image.load('venv/witch.png').convert_alpha()
witch_move = pygame.image.load('venv/witch_move.png').convert_alpha()
witch_animation = [witch_stand, witch_move]
witch_index = 0
witch = witch_animation[witch_index]
obstacle_rect_list = []
####knight_surface.set_colorkey((0,0,0))
#------------------intro screen----------------------------------
hero_intro = pygame.image.load('venv/knight_front.png').convert_alpha()
hero_intro_scaled = pygame.transform.scale(hero_intro, (250, 230))
### pygame.transform.scale2x (hero_intro)
### pygame.transform.rotozoom (hero_intro,0,2) /angle, scalling
hero_intro_rect = hero_intro.get_rect(center=(400,150))
#------------------intro screen----------------------------------
game_name = test_font.render("Currier " + " Knight", False, 'blue')
game_name_rect = game_name.get_rect(center = (400,290))
game_message = test_font.render("Press Space to Start", False, 'blue')
game_message_rect = game_message.get_rect(center = (400,340))
#------------Timer-------------------------------------------------
obstacle_timer = pygame.USEREVENT + 1 # +1 to separate from events reserved for pygame
pygame.time.set_timer(obstacle_timer, 1500)
knight_animation_timer = pygame.USEREVENT + 2
pygame.time.set_timer(knight_animation_timer, 500)
witch_animation_timer = pygame.USEREVENT + 3
pygame.time.set_timer(witch_animation_timer, 500)
#-----------------------Game Body----------------------------------
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # and hero_rect.bottom >= 380:
pygame.quit()
exit()
if game_active:
if event.type == pygame.MOUSEBUTTONDOWN and hero_rect.bottom >= 380:
if hero_rect.collidepoint(event.pos):
hero_gravity = -25
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and hero_rect.bottom >= 380:
hero_gravity = -25
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game_active = True
start_time = int(pygame.time.get_ticks()/1000)
if game_active:
if event.type == obstacle_timer:
if randint(0,2):
obstacle_rect_list.append(knight.get_rect(midbottom=(randint(900,1100), 385)))
else:
obstacle_rect_list.append(witch.get_rect(midbottom=(randint(900,1100), 210)))
#-----------------------Game Body-Knight and Witch Animation--------
if event.type == knight_animation_timer:
if knight_index ==0: knight_index = 1
else: knight_index =0
knight = knight_animation[knight_index]
if event.type == witch_animation_timer:
if witch_index ==0: witch_index = 1
else: witch_index =0
witch = witch_animation[witch_index]
#--------------------------Mouse------------------------------------
#if event.type == pygame.MOUSEMOTION:
#if hero_rect.collidepoint(event.pos): print('collision')
#--------------------------Background images and objects------------
if game_active:
screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(0,100))
pygame.draw.ellipse(screen, "Yellow", pygame.Rect (550,50,100,100)) # create rect in a figure
score = display_score()
#pygame.draw.rect(screen, "red", knight_rect)
#pygame.draw.rect(screen, "blue", hero_rect)
#pygame.draw.line(screen, "Gold", (0,0),(800,400), 10)
#screen.blit(score_surface, score_rect)
#---------------------Knight movement---------------
#screen.blit(knight, knight_rect)
#knight_rect.right -=10
#if knight_rect.right <= 0: knight_rect.left = 800
#--------------------gravity and surface-------------
hero_gravity +=1
hero_rect.y += hero_gravity
if hero_rect.bottom >= 380: hero_rect.bottom = 380
hero_animation()
screen.blit(hero, hero_rect)
#hero_rect.left += 1
#---------------------Obstacle movement-------------
obstacle_rect_list = obstacle_movement(obstacle_rect_list)
#---------------------Keyboard-----------------------------
# keys = pygame.key.get_pressed()
# if keys[pygame.K_SPACE]:
#----------------------------------------------------------
#mouse_pos = pygame.mouse.get_pos()
#hero_rect.colliderect(knight_rect)
#if hero_rect.collidepoint(mouse_pos):
#print("collision")
#print(pygame.mouse.get_pressed())
#----------------------collision-------------------------------
game_active = collision(hero_rect,obstacle_rect_list)
#if knight_rect.colliderect(hero_rect):
# knight_rect = knight.get_rect(midbottom=((650, 350)))
# knight_rect.inflate_ip(-50,-75)
# game_active = False
#----------------------Game Start / End -----------------------
else:
screen.fill("light blue")
#screen.blit(bg,(0,0))
screen.blit(hero_intro_scaled,hero_intro_rect)
hero_rect.midbottom = (100, 400)
hero_gravity =0
score_message = test_font.render(f'Your score is {score}', False, 'blue')
score_message_rect= score_message.get_rect(center = (400,340))
screen.blit(game_name,game_name_rect)
if score == 0: screen.blit(game_message,game_message_rect)
else: screen.blit(score_message,score_message_rect)
obstacle_rect_list = []
#pygame.quit()
#exit()
#------------------------------------------------------------------
pygame.display.update()
clock.tick(60)
| true |
3306e33874fac796ef1cb4899b129275ff836fd6
|
Python
|
samhofman/AirlinePlanning
|
/NetworkScheduling/Assignment 1/Functions_P1.py
|
UTF-8
| 2,026 | 3.21875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 15:09:28 2019
@author: hofma
"""
import xlsxwriter
from Data import *
### Make cost matrix ###
cost = np.zeros(shape=(16,16))
for i in range(len(arcs)):
a = arcs[i,1]
b = arcs[i,2]
cost[a,b] = arcs[i,3]
cost = np.maximum( cost, cost.transpose() ) #Make matrix symmetric to work in both directions
workbook = xlsxwriter.Workbook('Cost_P1.xlsx') #Write to Excel to check
worksheet = workbook.add_worksheet('Cost')
array = cost
row = 0
for col, data in enumerate(array):
worksheet.write_column(row, col, data)
workbook.close()
### Determine number of airports ###
airports = len(cost)
### Make capacity matrix ###
capacity = np.zeros(shape=(16,16))
for i in range(len(arcs)):
a = arcs[i,1]
b = arcs[i,2]
capacity[a,b] = arcs[i,4]
capacity = np.maximum( capacity, capacity.transpose() ) #Make matrix symmetric to work in both directions
workbook = xlsxwriter.Workbook('Capacity_P1.xlsx') #Write to Excel to check
worksheet = workbook.add_worksheet('Capacity')
array = capacity
row = 0
for col, data in enumerate(array):
worksheet.write_column(row, col, data)
workbook.close()
### Make quantity matrix ###
quantity = np.zeros(shape=(16,16))
for i in range(len(commodities)):
a = commodities[i,1]
b = commodities[i,2]
quantity[a,b] = commodities[i,3]
workbook = xlsxwriter.Workbook('Quantity_P1.xlsx') #Write to Excel to check
worksheet = workbook.add_worksheet('Capacity')
array = quantity
row = 0
for col, data in enumerate(array):
worksheet.write_column(row, col, data)
workbook.close()
### Demand function ###
def d(i,k):
if i == commodities[k,1]:
d = float(commodities[k,3])
elif i == commodities[k,2]:
d = -float(commodities[k,3])
else:
d = 0.0
return d
### Cost function ###
def c(i,j):
c = cost[i,j]
return c
### Capacity function ###
def u(i,j):
u = capacity[i,j]
return u
| true |
66b5b07ea81457631926c51545b3ad86614e7894
|
Python
|
rendy026/reverse-enginnering
|
/Instatools/install.py
|
UTF-8
| 503 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import os
print("[!] Running configuration ")
print("[!] Please don't interrupt this process")
os.system('python -m pip install cython ')
os.system('gcc `python-config --cflags --ldflags` run.c -o run /dev/null 2>&1')
os.system('cythonize -i instagram/* /dev/null 2>&1 ')
print("\n\n\n[!] removing files C extensions")
try:
os.system("rm instagram/*.c")
except:
pass
try:
os.system("rm run.c")
except:
pass
print("[!] Compiled done")
print("[!] Now you can run with command ./run")
| true |
d89647abd7c1d9e3c0c9dcdaa750ad0a9945a07f
|
Python
|
aandyberg/school-projects
|
/Chalmers python/lab2/test.py
|
UTF-8
| 8,266 | 3.25 | 3 |
[] |
no_license
|
import io
import sys
import importlib.util
import graphics
def test(res,msg):
global pass_tests, fail_tests
if res:
pass_tests = pass_tests + 1
else:
print(msg)
fail_tests = fail_tests + 1
def runTests(game):
players = game.getPlayers()
test(len(players) == 2, "there should be two players")
test(players[0].getColor() == "blue", "player 0 should be blue!")
test(players[1].getColor() == "red", "player 1 should be red!")
test(players[0].getX() == -90, "player 0 should stand at x=-90!")
test(players[1].getX() == 90, "player 1 should stand at x=90!")
test(game.getCurrentPlayerNumber() == 0, "player 0 should start!")
test(game.getCurrentPlayer() == players[0], "player 0 should start! (2)")
test(game.getOtherPlayer() == players[1], "getOtherPlayer() doesn't work")
test(-10 <= game.getCurrentWind() <= 10, "wind should be a random value in [-10,10]")
# Testing manually swapping player
game.nextPlayer()
test(game.getCurrentPlayerNumber() == 1, "player 1 should go second!")
test(game.getCurrentPlayer() == players[1], "player 1 should go second! (2)")
test(game.getOtherPlayer() == players[0], "getOtherPlayer() doesn't work")
# Switch back to player 0
game.nextPlayer()
test(game.getCurrentPlayer() == players[0], "player 0 should go after player 1!")
test(game.getOtherPlayer() == players[1], "getOtherPlayer() doesn't work")
# Turn off wind
game.setCurrentWind(0)
test(game.getCurrentWind() == 0, "wind should be 0")
#Testing "Manual fire" for player 0
proj = game.getCurrentPlayer().fire(30,31)
test(proj.getX() == game.getCurrentPlayer().getX(), "Fired projectile should start at player X-position")
test(abs(proj.getY() - 10/2) < 0.01, "Fired projectile Y-position should start half the cannon size")
test(proj.isMoving() == True, "projectile should be moving")
test(game.getCurrentPlayer().getAim() == (30,31), "After firing, getAim() should give the latest (angle,velocity)-values")
proj.update(1.0)
test(abs(proj.getX() + 63.1532124826824) < 0.01, "Projectile X-Position is {0:f}, should be -63.153212".format(proj.getX()))
test(abs(proj.getY() - 15.6) < 0.01, "Projectile X-Position is {0:f}, should be 15.6".format(proj.getY()))
test(proj.isMoving(), "projectile should be moving")
ticks = 0
while proj.isMoving():
proj.update(0.1)
ticks += 1
test(ticks <= 25, "projectile should have stopped now...")
test(ticks == 25, "Incorrect tick-count")
test(proj.getY() == 0.0, "projectile should stop at y=0")
test(abs(proj.getX() - 3.9637563106115907) < 0.01, "Projectile X-Position is {0:f}, should be -3.9637563106115907".format(proj.getX()))
test(abs(players[1].projectileDistance(proj) - -78.03624368938841) < 0.01, "Projectile X-distance to player is {0:f}, should be -78.03624368938841".format(players[1].projectileDistance(proj)))
test(abs(players[0].projectileDistance(proj) - 85.96375631061159) < 0.01, "Projectile X-distance to player is {0:f}, should be 85.96375631061159".format(players[0].projectileDistance(proj)))
#Switching to player 1
game.nextPlayer()
test(game.getCurrentPlayerNumber() == 1, "player 1 should go after player 0")
test(game.getCurrentPlayer() == players[1], "player 1 should go after player 0")
test(game.getOtherPlayer() == players[0], "getOtherPlayer() doesn't work")
#Testing "Manual fire" for player 1
proj = game.getCurrentPlayer().fire(45,41)
test(proj.getX() == game.getCurrentPlayer().getX(), "Fired projectile should start at player X-position")
test(proj.getY() == 10/2, "Fired projectile Y-position should start half the cannon size")
test(proj.isMoving(), "projectile should be moving")
ticks = 0
while proj.isMoving():
proj.update(0.1)
ticks += 1
assert ticks <= 61, "projectile should have stopped now..."
test(ticks == 61, "Incorrect tick-count")
test(proj.getY()==0.0, "projectile should always stop at y=0")
test(abs(proj.getX() - -86.84740597475547) < 0.01, "Projectile X-Position is {0:f}, should be -86.84740597475547".format(proj.getX()))
test(abs(players[1].projectileDistance(proj) - -168.84740597475547) < 0.01, "Projectile X-distance to player is {0:f}, should be 168.84740597475547".format(players[1].projectileDistance(proj)))
test(players[0].projectileDistance(proj) == 0, "Projectile X-distance to player is {0:f}, should be 0".format(players[1].projectileDistance(proj)))
# Test scoring
test(players[0].getScore()==0, "Initial score should be 0")
players[0].increaseScore()
test(players[1].getScore()==0, "Score should be 0")
test(players[0].getScore()==1, "Score should be 1")
# Test new round
game.setCurrentWind(1000)
test(game.getCurrentWind()==1000, "Failed to set wind speed")
game.newRound()
test(game.getCurrentWind()!=1000, "Wind should be randomized each round")
# Test firing with wind
game.setCurrentWind(-1)
proj = players[0].fire(45,41)
test(proj.getX() == players[0].getX(), "Fired projectile should start at player X-position")
test(proj.getY() == 10/2, "Fired projectile Y-position should start half the cannon size")
test(proj.isMoving(), "projectile should be moving")
ticks = 0
while proj.isMoving():
proj.update(0.1)
ticks += 1
assert ticks <= 61, "projectile should have stopped now..."
test(ticks == 61, "Incorrect tick-count")
test(abs(proj.getX() - 68.2424059747553) < 0.01, "Projectile X-Position is {0:f}, should be 68.2424059747553".format(proj.getX()))
# A few additional hints
gameAtts = len(game.__dict__.items())
if (gameAtts > 5):
print("Your Game object has {} attributes. This isn't necessarily wrong, but 5 seems like a nice number.".format(gameAtts))
print("Make sure you are not representing the same information in multiple attributes.")
playerAtts = len(game.getCurrentPlayer().__dict__.items())
if (playerAtts > 8):
print("Your Player object has {} attributes. This isn't necessarily wrong, but it seems a bit high.".format(playerAtts))
def runTestsGraphics(ggame):
# First run the standard tests (same as for the model)
runTests(ggame)
# For these tests to work, you need to have a getWindow-method in GraphicGame
w = ggame.getWindow()
circ_type = type(graphics.Circle(graphics.Point(0,0), 10))
rect_type = type(graphics.Rectangle(graphics.Point(0,0), graphics.Point(1,1)))
everything = w.items
circles = [x for x in w.items if type(x) == circ_type]
rectangles = [x for x in w.items if type(x) == rect_type]
test(len(circles) == 2, "there should be two circles drawn after running tests")
test(len(rectangles) == 2, "there should be two rectangles initially")
rect_pos = [x.getCenter().getX() for x in rectangles]
test(-90 in rect_pos and 90 in rect_pos, "rectangles should be at x=-90 and x=90")
# Fire a red projectile and move it a bit
ggame.setCurrentWind(0)
ggame.getCurrentPlayer().fire(30, 30).update(2)
circles = [x for x in w.items if type(x) == circ_type]
test(len(circles) <= 2, "there should never be more than two circles! You need to undraw old cannonballs")
def run(src_path=None):
global pass_tests, fail_tests
if src_path == None:
import gamemodel
import gamegraphics
else:
spec = importlib.util.spec_from_file_location("gamemodel", src_path+"/gamemodel.py")
gamemodel = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gamemodel)
spec = importlib.util.spec_from_file_location("gamegraphics", src_path+"/gamegraphics.py")
gamegraphics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gamegraphics)
pass_tests = 0
fail_tests = 0
fun_count = 0
game = gamemodel.Game(10,3)
runTests(game)
ggame = gamegraphics.GraphicGame(gamemodel.Game(10, 3))
runTestsGraphics(ggame)
print(str(pass_tests)+" out of "+str(pass_tests+fail_tests)+" passed.")
return (fun_count == 0 and fail_tests == 0)
if __name__ == "__main__":
run()
| true |
99d86b3a91e44b36593cc45471d35482dcad7c3d
|
Python
|
jspeis/pebble-mac-powerpoint-remote
|
/presenter_controller.py
|
UTF-8
| 2,123 | 2.71875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import argparse, os, sys, time
import pebble as libpebble
# -- based off the smarthomewatch example by makrco https://github.com/makrco/smarthomewatch
FORWARD = chr(29)
BACK = chr(28)
def music_control_handler(endpoint, resp):
print "Button pressed", resp
key = BACK
if resp == 'NEXT':
key = FORWARD
cmd = """osascript -e 'tell application "System Events" to keystroke "%s"'""" % (key,)
os.system(cmd)
def cmd_remote(pebble):
pebble.register_endpoint("MUSIC_CONTROL", music_control_handler)
print 'Waiting for control events...'
try:
while True:
if pebble._ser.is_alive():
time.sleep(2)
else:
print "Lost connection"
break
except KeyboardInterrupt:
pass
def main():
parser = argparse.ArgumentParser(description='a utility belt for pebble development')
parser.add_argument('--pebble_id', type=str, help='the last 4 digits of the target Pebble\'s MAC address. \nNOTE: if \
--lightblue is set, providing a full MAC address (ex: "A0:1B:C0:D3:DC:93") won\'t require the pebble \
to be discoverable and will be faster')
parser.add_argument('--lightblue', action="store_true", help='use LightBlue bluetooth API')
parser.add_argument('--pair', action="store_true", help='pair to the pebble from LightBlue bluetooth API before connecting.')
args = parser.parse_args()
while True:
try:
pebble_id = args.pebble_id
if pebble_id is None and "PEBBLE_ID" in os.environ:
pebble_id = os.environ["PEBBLE_ID"]
pebble = libpebble.Pebble(pebble_id, args.lightblue, args.pair)
try:
cmd_remote(pebble)
except Exception as e:
print 'error', e
pebble.disconnect()
raise e
return
pebble.disconnect()
time.sleep(5)
except:
print 'error (2)'
time.sleep(2)
if __name__ == '__main__':
main()
| true |
11245772a96bec79e002ef5d69e88363deef74f6
|
Python
|
cotsog/pathways-backend
|
/search/save_similarities.py
|
UTF-8
| 1,908 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
from search.models import TaskSimilarityScore, TaskServiceSimilarityScore
def save_task_similarities(ids, similarities, count):
TaskSimilarityScore.objects.all().delete()
for i in range(len(ids)):
similarities_for_task = [similarities[i, j] for j in range(len(ids)) if i != j]
cutoff = compute_cutoff(similarities_for_task, count)
for j in range(len(ids)):
score = similarities[i, j]
if i != j and score >= cutoff:
record = TaskSimilarityScore(first_task_id=ids[i],
second_task_id=ids[j],
similarity_score=score)
record.save()
def compute_cutoff(scores, count):
scores.sort(reverse=True)
return scores[min(count, len(scores)) - 1]
def save_task_service_similarity_scores(task_ids, service_ids, similarities, count):
TaskServiceSimilarityScore.objects.all().delete()
task_count = len(task_ids)
service_count = len(service_ids)
# Assuming that the similarities are computed from a document vector
# containing task descriptions *followed by* service descriptions
def to_service_similarity_offset(service_index):
return task_count + service_index
for i in range(task_count):
similarities_for_task = [similarities[i, to_service_similarity_offset(j)]
for j in range(service_count)]
cutoff = compute_cutoff(similarities_for_task, count)
for j in range(service_count):
score = similarities[i, to_service_similarity_offset(j)]
if score >= cutoff:
record = TaskServiceSimilarityScore(task_id=task_ids[i],
service_id=service_ids[j],
similarity_score=score)
record.save()
| true |
24a750e1f78cc1a52929302a43175586a5f77753
|
Python
|
HLNN/leetcode
|
/src/1765-merge-in-between-linked-lists/merge-in-between-linked-lists.py
|
UTF-8
| 1,597 | 3.953125 | 4 |
[] |
no_license
|
# You are given two linked lists: list1 and list2 of sizes n and m respectively.
#
# Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
#
# The blue edges and nodes in the following figure indicate the result:
#
# Build the result list and return its head.
#
#
# Example 1:
#
#
# Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
# Output: [0,1,2,1000000,1000001,1000002,5]
# Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
#
#
# Example 2:
#
#
# Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
# Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
# Explanation: The blue edges and nodes in the above figure indicate the result.
#
#
#
# Constraints:
#
#
# 3 <= list1.length <= 104
# 1 <= a <= b < list1.length - 1
# 1 <= list2.length <= 104
#
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
tail2 = list2
while tail2 and tail2.next:
tail2 = tail2.next
start = list1
for _ in range(a - 1):
start = start.next
end = start
for _ in range(b - a + 1):
end = end.next
end = end.next
start.next = list2
tail2.next = end
return list1
| true |
f6d448ed85580d7d612d5e07b9bd16af7226db62
|
Python
|
albertoamo/BerkleyPacman
|
/Project1/test.py
|
UTF-8
| 140 | 2.703125 | 3 |
[] |
no_license
|
import fclass
def function(var1):
aux = s
print aux
# Main Function
if __name__ == '__main__':
s = ['20','30']
function(s)
| true |
02d7e43379b453022c22da484ef2f7642be3bbfc
|
Python
|
kcct-fujimotolab/chainer-image-gen-nets
|
/gennet/dcgan/net.py
|
UTF-8
| 6,006 | 2.59375 | 3 |
[] |
no_license
|
import json
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
def conved_image_size(image_size, max_n_ch=512):
n_conv = 4
conved_size = image_size
for i in range(n_conv):
kwargs = get_conv2d_kwargs(i, image_size=image_size, max_n_ch=max_n_ch)
conved_size = check_conved_size(conved_size, kwargs['ksize'], kwargs[
'stride'], kwargs['pad'])
return conved_size
def check_conved_size(image_size, ksize, stride=1, pad=0):
return int((image_size - ksize + 2 * pad) / stride) + 1
def get_conv2d_kwargs(i, image_size=64, n_color=3, max_n_ch=512, deconv=False):
n_conv = 4
channels = [n_color] + [max_n_ch // (2 ** x)
for x in range(0, n_conv)][::-1]
if image_size == 64:
kernel = [
{'ksize': 4, 'stride': 2, 'pad': 1}, # 64 -> 32
{'ksize': 4, 'stride': 2, 'pad': 1}, # 32 -> 16
{'ksize': 4, 'stride': 2, 'pad': 1}, # 16 -> 8
{'ksize': 4, 'stride': 2, 'pad': 1}, # 8 -> 4
]
elif image_size == 32:
kernel = [
{'ksize': 3, 'stride': 1, 'pad': 1}, # 32 -> 32
{'ksize': 4, 'stride': 2, 'pad': 1}, # 32 -> 16
{'ksize': 4, 'stride': 2, 'pad': 1}, # 16 -> 8
{'ksize': 4, 'stride': 2, 'pad': 1}, # 8 -> 4
]
elif image_size == 28:
kernel = [
{'ksize': 3, 'stride': 3, 'pad': 1}, # 28 -> 10
{'ksize': 2, 'stride': 2, 'pad': 1}, # 10 -> 6
{'ksize': 2, 'stride': 2, 'pad': 1}, # 6 -> 4
{'ksize': 2, 'stride': 2, 'pad': 1}, # 4 -> 3
]
else:
raise NotImplementedError(
'(image_size == {}) is not implemented'.format(image_size))
if deconv:
kwargs = {
'in_channels': channels[n_conv - i],
'out_channels': channels[n_conv - i - 1],
}
kwargs.update(kernel[n_conv - i - 1])
else:
kwargs = {
'in_channels': channels[i],
'out_channels': channels[i + 1],
}
kwargs.update(kernel[i])
return kwargs
class Generator(chainer.Chain):
def __init__(self, image_size, n_z, n_color, wscale=0.02):
self.image_size = image_size
self.n_z = n_z
self.n_color = n_color
self.wscale = wscale
self.conved_size = conved_image_size(image_size)
super(Generator, self).__init__(
l0=L.Linear(self.n_z, self.conved_size ** 2 * 512, wscale=wscale),
dc1=L.Deconvolution2D(
**get_conv2d_kwargs(0, image_size, n_color, 512, deconv=True), wscale=wscale),
dc2=L.Deconvolution2D(
**get_conv2d_kwargs(1, image_size, n_color, 512, deconv=True), wscale=wscale),
dc3=L.Deconvolution2D(
**get_conv2d_kwargs(2, image_size, n_color, 512, deconv=True), wscale=wscale),
dc4=L.Deconvolution2D(
**get_conv2d_kwargs(3, image_size, n_color, 512, deconv=True), wscale=wscale),
bn0l=L.BatchNormalization(self.conved_size ** 2 * 512),
bn0=L.BatchNormalization(512),
bn1=L.BatchNormalization(256),
bn2=L.BatchNormalization(128),
bn3=L.BatchNormalization(64),
)
def __call__(self, z, test=False):
h = self.l0(z)
h = self.bn0l(h, test=test)
h = F.relu(h)
h = F.reshape(h, (z.data.shape[0], 512,
self.conved_size, self.conved_size))
h = self.dc1(h)
h = self.bn1(h, test=test)
h = F.relu(h)
h = self.dc2(h)
h = self.bn2(h, test=test)
h = F.relu(h)
h = self.dc3(h)
h = self.bn3(h, test=test)
h = F.relu(h)
x = self.dc4(h)
return x
def make_hidden(self, batchsize):
return np.random.uniform(-1, 1, (batchsize, self.n_z, 1, 1)).astype(np.float32)
def to_json(self):
d = {
'class_name': self.__class__.__name__,
'kwargs': {
'image_size': self.image_size,
'n_z': self.n_z,
'n_color': self.n_color,
'wscale': self.wscale,
}
}
return json.dumps(d)
class Discriminator(chainer.Chain):
def __init__(self, image_size, n_color, wscale=0.02):
self.image_size = image_size
self.n_color = n_color
self.wscale = wscale
self.conved_size = conved_image_size(image_size)
super(Discriminator, self).__init__(
c0=L.Convolution2D(
**get_conv2d_kwargs(0, image_size, n_color, 512), wscale=wscale),
c1=L.Convolution2D(
**get_conv2d_kwargs(1, image_size, n_color, 512), wscale=wscale),
c2=L.Convolution2D(
**get_conv2d_kwargs(2, image_size, n_color, 512), wscale=wscale),
c3=L.Convolution2D(
**get_conv2d_kwargs(3, image_size, n_color, 512), wscale=wscale),
l4=L.Linear(self.conved_size ** 2 * 512, 2, wscale=wscale),
bn0=L.BatchNormalization(64),
bn1=L.BatchNormalization(128),
bn2=L.BatchNormalization(256),
bn3=L.BatchNormalization(512),
)
def __call__(self, x, test=False):
h = self.c0(x)
h = F.leaky_relu(h)
h = self.c1(h)
h = self.bn1(h, test=test)
h = F.leaky_relu(h)
h = self.c2(h)
h = self.bn2(h, test=test)
h = F.leaky_relu(h)
h = self.c3(h)
h = self.bn3(h, test=test)
h = F.leaky_relu(h)
l = self.l4(h)
return l
def to_json(self):
d = {
'class_name': self.__class__.__name__,
'kwargs': {
'image_size': self.image_size,
'n_color': self.n_color,
'wscale': self.wscale,
}
}
return json.dumps(d)
| true |
ca1154c8339b4114cd4e254aed8a953be99368b8
|
Python
|
shayan-taheri/RazorNet_AdversarialExample_Detection
|
/test_inference.py
|
UTF-8
| 3,999 | 2.625 | 3 |
[] |
no_license
|
"""Test ImageNet pretrained DenseNet"""
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
import cv2
import numpy as np
from keras.optimizers import SGD
import keras.backend as K
# We only test DenseNet-121 in this script for demo purpose
from densenet169 import DenseNet
im = cv2.resize(cv2.imread('resources/cat.jpg'), (224, 224)).astype(np.float32)
#im = cv2.resize(cv2.imread('resources/shark.jpg'), (224, 224)).astype(np.float32)
# Subtract mean pixel and multiple by scaling constant
# Reference: https://github.com/shicai/DenseNet-Caffe
im[:,:,0] = (im[:,:,0] - 103.94) * 0.017
im[:,:,1] = (im[:,:,1] - 116.78) * 0.017
im[:,:,2] = (im[:,:,2] - 123.68) * 0.017
if K.image_dim_ordering() == 'th':
# Transpose image dimensions (Theano uses the channels as the 1st dimension)
im = im.transpose((2,0,1))
# Use pre-trained weights for Theano backend
weights_path = 'imagenet_models/densenet169_weights_th.h5'
else:
# Use pre-trained weights for Tensorflow backend
weights_path = 'imagenet_models/densenet169_weights_tf.h5'
# Insert a new dimension for the batch_size
im = np.expand_dims(im, axis=0)
# Test pretrained model
model = DenseNet(reduction=0.5, classes=10, weights_path=weights_path)
# Learning rate is changed to 1e-3
sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
out = model.predict(im)
# Load ImageNet classes file
classes = []
with open('resources/classes.txt', 'r') as list_:
for line in list_:
classes.append(line.rstrip('\n'))
print 'Prediction: '+str(classes[np.argmax(out)])
from keras.datasets import cifar10
(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()
img_size = 32
img_chan = 3
n_classes = 10
X_train = np.reshape(X_train, [-1, img_size, img_size, img_chan])
X_train = X_train.astype(np.float32) / 255
X_test = np.reshape(X_test, [-1, img_size, img_size, img_chan])
X_test = X_test.astype(np.float32) / 255
from keras.utils import to_categorical
Y_train = to_categorical(Y_train)
Y_test = to_categorical(Y_test)
print('\nSpliting data')
ind = np.random.permutation(X_train.shape[0])
X_train, Y_train = X_train[ind], Y_train[ind]
VALIDATION_SPLIT = 0.1
n = int(X_train.shape[0] * (1-VALIDATION_SPLIT))
X_valid = X_train[n:]
X_train = X_train[:n]
Y_valid = Y_train[n:]
Y_train = Y_train[:n]
X_Train = np.empty([500, 224, 224, 3])
for i1 in range(500):
X_Train[i1] = cv2.resize(X_train[i1], (224, 224)).astype(np.float32)
# Subtract mean pixel and multiple by scaling constant
# Reference: https://github.com/shicai/DenseNet-Caffe
X_Train[i1][:,:,0] = (X_Train[i1][:,:,0] - 103.94) * 0.017
X_Train[i1][:,:,1] = (X_Train[i1][:,:,1] - 116.78) * 0.017
X_Train[i1][:,:,2] = (X_Train[i1][:,:,2] - 123.68) * 0.017
# Insert a new dimension for the batch_size
X_Train = np.expand_dims(X_Train, axis=0)
X_Valid = np.empty([500, 224, 224, 3])
for i2 in range(500):
X_Valid[i2] = cv2.resize(X_valid[i2], (224, 224)).astype(np.float32)
# Subtract mean pixel and multiple by scaling constant
# Reference: https://github.com/shicai/DenseNet-Caffe
X_Valid[i2][:, :, 0] = (X_Valid[i2][:, :, 0] - 103.94) * 0.017
X_Valid[i2][:, :, 1] = (X_Valid[i2][:, :, 1] - 116.78) * 0.017
X_Valid[i2][:, :, 2] = (X_Valid[i2][:, :, 2] - 123.68) * 0.017
# Insert a new dimension for the batch_size
X_Valid[i2] = np.expand_dims(X_Valid[i2], axis=0)
batch_size = 16
epochs = 10
print(X_Train.shape)
print(X_Valid.shape)
print(Y_train[0:500,:].shape)
print(Y_valid[0:500,:].shape)
# Start Fine-tuning
model.fit(X_Train, Y_train[0:500,:],
batch_size=batch_size,
epochs=epochs,
shuffle=True,
verbose=1,
validation_data=(X_valid, Y_valid[0:500,:])
)
# Make predictions
predictions_valid = model.predict(X_Valid[0])
# Cross-entropy loss score
score = log_loss(Y_valid[0], predictions_valid)
| true |
13c942d5f815f575d086b14966b8c00fb0127b96
|
Python
|
zahranorozzadeh/tamarin4
|
/tamrin4-2.py
|
UTF-8
| 332 | 3.5 | 4 |
[] |
no_license
|
def ab(m,n):
for i in range(1,m+1):
if i % 2 == 0:
for j in range(1,n+1):
if j % 2 == 0:
print('*', end=' ')
else:
print('#', end=' ')
print()
rows = int(input())
clumns =int(input())
ab(rows,clumns)
| true |
f69bb3bec1d8336ccf709cb6b0054a0218fff49d
|
Python
|
somaproject/backplane
|
/network/sim/data/dumpparse.py
|
UTF-8
| 1,789 | 2.78125 | 3 |
[] |
no_license
|
#!/usr/bin/python
import numpy as n
def computeIPHeader(octetlist):
header = octetlist[14:14+20]
x = 0
for i in range(10):
s = "%2.2X%2.2X" % (header[i*2], header[i*2+1])
a = int(s, 16)
if i != 5:
x += a
#print hex(a), hex(x)
y = ((x & 0xFFFF) + (x >> 16))
return ( ~ y) & 0xFFFF
def updateIPHeader(octetlist):
iphdr = hex(computeIPHeader(octetlist))
if octetlist[12] == 8 and octetlist[13] == 0:
csum = computeIPHeader(octetlist)
octetlist[24] =(csum >> 8)
octetlist[25] =(csum & 0xFF)
else:
pass
fid = file('data.tcpdump')
l = fid.readline()
inpkt = False
pktstr = ""
pktstrs = []
while l != "":
# blah
l = fid.readline()
if l[:2] == "IP":
if len(pktstr) > 0:
pktstrs.append( pktstr)
pktstr = ""
else:
pktstr += l[10:-1]
ofile = file('data.txt', 'w')
# segment packet strings into lists of bytes
for s in pktstrs:
bytestr = ''.join(s.split(' '))
N = len(bytestr)
da = n.zeros(N/2, n.uint8)
for i in range(N/2):
wordstr = bytestr[i*2:(i+1)*2]
#print wordstr, len(wordstr), i, N, N/4
da[i] = int(wordstr, 16)
# now we have the output packets in numerical form; perform the update
# of the ip sequence and then the relevant header checksum update
da[19] = 0
da[20] = 0
# zero udp chksum
da[40] = 0
da[41] = 0
updateIPHeader(da)
# now we print our normal format
ofile.write("%d " % (len(da)/2 + 1))
ofile.write("%4.4X " % (len(da)))
for i in range(len(da) / 2):
ofile.write("%2.2X%2.2X " % (da[i*2], da[i*2+1]))
ofile.write('\n')
| true |
64eb49b727d0bcca8dc6d4f945d888da6a8b9610
|
Python
|
thekma/DS2000
|
/pr05_python/pi(1).py
|
UTF-8
| 1,628 | 4.34375 | 4 |
[] |
no_license
|
# Problem 1: Pi Approximations
# Name: Ken Ma
# Introduction: In this program, we will be using three different ways to approximate pi
# Method 1: pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 -.....
# Method 2: pi = sqrt( 6/1^2 + 6/2^2 + 6/3^2 + 6/4^2 + 6/5^2 +....) = sqrt(6/1 + 6/4 + 6/9 + 6/16 + 6/25 + 6/36 + ...)
# Method 3: pi = 2 *(2/1 * 2/3 * 4/3 * 4/5 * 6/5 * 6/7 * 8/7 * 8/9 * 10/9 * 10/11 *....)
# However, instead of computing n terms, we will instead compute until we are within some
# epsilon of pi. That is to say, we want to do this until the difference our approximation
# and pi is less than epsilon
# e.g. abs(piApprox - pi) < epsilon
# Instructions: For each of the three pi approximations above, you should build a function that
# inputs some epsilon, and returns the number of iterations we needed until our approximation
# was within epsilon of pi
# Specifically, abs(pi-piApprox)<epsilon
# Hint: You can find pi in the math module. Specifically, "from math import pi"
# Example: pi1(0.00001) = 100001
# Example: pi2(0.00001) = 95493
# Example pi3(0.00001) = 157079
# Example: pi1(0.0000123) = 81301
# Example: pi2(0.0000123) = 77637
# Example pi3(0.0000123) = 127706
from math import pi
from math import sqrt
def pi1(epsilon):
piapprox = 0
k = 0
while abs(piapprox-pi)>epsilon:
piapprox += (-1)**(k)*(4/(2*k+1))
k += 1
return (k)
def pi2(epsilon):
sum = 0
piapproxim = 0
ii = 0
while abs(piapproxim-pi)>epsilon:
sum += 6/((ii+1)**2)
ii += 1
piapproxim = sqrt(sum)
return (ii)
def pi3(epsilon):
return 0 #skipped
| true |
9f9ad29e7e700b575fc8f53acbbe64eb4ba150a8
|
Python
|
guyonthat/Carnac
|
/Hobocode-import and modify.py
|
UTF-8
| 8,303 | 3.59375 | 4 |
[
"Unlicense"
] |
permissive
|
# This is real python code! This will actually read in a file from disk
# and return to you its contents.
def read_file(file_path):
with open(file_path, 'r') as f:
data = f.read()
return data
# This is real python code! This will actually write data to a file on disk.
def write_file(file_path, content, mode="w"):
with open(file_path, mode) as stream:
stream.write(content)
# This will get populated by the load-in function
# which is triggered by the user
raw_csv_data = None
# This will be filled with the processed data from the
# spreadsheet. The structure of this object is faked below.
# The key here is the title of the user from the csv.
# The value are what rows from the raw data contain this type of user.
proc_csv_data = {
# "grouping_bucket_from_csv": [1, 2, 3, 4],
}
# This object contains prettyfying labels for our "in memory" bucket names
pretty_names = {
"ceo": "Chief Executive Officer",
"grunt": "Valued Employee",
"unknown": "UNKNOWN"
}
def load_csv_file(path):
global raw_csv_data
# @DEBUG
# If this were for real you'd use something like:
# raw_csv_data = csv.parse(read_file(path))
raw_csv_data = [
["Richie", "Bigshot", "CEO"],
["Joel", "Schmuckberg", "Grunt"]
]
# The arguments to this function correspond to which columns
# in the csv contain the salient data we want to extract.
# If you need more data to be extracted from the csv, simply add more args
# in the style of foo_col=index.
#
# The varname=value struct in python is how you define "default values" for args.
#
# This is saying unless you pass in something, use the second column for the title
# field, the first for the first name, and the second for the last name.
#
# You can in your little GUI render something to let the user specify what columns
# contain what data.
def process_csv_data(src_file, title_col=2, fname_col=0, lname_col=1):
global proc_csv_data
# Go get our CSV data
load_csv_file(src_file)
print "Starting data processing..."
# set up an index counter to keep track of where we are in the list.
index = 0
for row in raw_csv_data:
# This extract title function defined below is where all the magic happens
title = extractTitle(row[title_col])
# This little line of code checks to see if the title we returned is already
# in our processed data. If it's not, we want to create an empty array to store
# our data keys in.
if title not in proc_csv_data:
proc_csv_data[title] = []
# Now we will definitely have proc_csv_data be a list (even if it's empty)
# the first time, so we can now append our indicies to it!
proc_csv_data[title].append(index)
# Now we increment the index counter to keep everything working
index += 1
# At this point, all of our data is processed!
print "Data processing complete!"
# Create the headers for our CSV.
# I always like to do this newline thing to indicate that it's a list of lists. Otherwise
# I find having the two brackets next to each other [[ is hard to read at a glance.
csv_output = [
["First Name", "Last Name", "Employee Bucket"]
]
# This is a list we are going to use to prevent duplicate entries in the output CSV.
# just incase something really crazy happens during processing, which it will.
# Doing this is called "defensive programming". We are going to force the program
# logic to guarantee that we never have duplicate data in the program output.
has_already_displayed = []
# Remember that our proc_csv_data only contains indices to the raw data array!
for raw_title in proc_csv_data:
# The raw title here is what type of user we think it is based on the
# rules we applied in extractTitle. The way we've structured our data,
# we group users by their title and then display them.
# Because we're grouping by the type of user on it's title, we can get the display
# name for all users of this type before we go through every user. This is just
# more efficient than resetting this variable to the same value every time in the list.
display_title = pretty_names[raw_title]
# When you iterate through an object, you get it's keys. To get the values, you
# need to request the value of the object at the key, which is what the
# proc_csv_data[raw_title] line does. The "for ... in ..." construct here will iterate
# through the value at proc_csv_data, which is a list of the indices in raw data that
# we want.
for user_index in proc_csv_data[raw_title]:
# Before we process the row, we need to ensure that we have not already
# processed this user. Fundamentally, we can assume that the index of the
# row in the raw data array is a unique identifier (there can only be one first row).
# Knowing that, the first time we see a new array, we pop
# it into our `has_already_displayed' list. If the list doesn't contain the index,
# then it's new data and should be processed.
if user_index in has_already_displayed:
# This is a keyword that tells the loop to stop here and go to the next item.
continue
# If we're here in the code, it means that we are processing a new item. First,
# add that item index to the displayed list so we don't ever get a dupe.
has_already_displayed.append(user_index)
# Next, because this identifier is only the index of the data and not the data itself
# we need to go grab the actual raw data.
raw_data = raw_csv_data[user_index]
first_name = raw_data[fname_col]
last_name = raw_data[lname_col]
# Finally, simply add this to the output list.
csv_output.append(first_name, last_name, display_title)
# We're almost done! All we need to do now is format the data.
# Because we're saving to a CSV, we need to actually join our lists into strings
# which are separated by commas. To do this is pretty simple. First, we create
# one final list to contain the output:
out = []
# Then, for each row in our csv_output
for row in csv_output:
# We join the row data with a comma
row = ",".join(row) # ["foo", "bar"] -becomes-> "foo,bar"
# And then add this to the output list
out.append(row)
# Finally, we need to turn out list of strings into a string with line breaks so
# we can write it into a file.
# Right now we have this: ["foo,bar", "baz,gaz"]
# And we need: "foo,bar\nbaz,gaz".
# The "\n" is how you say "make a newline" in a string. When you hit enter, you are
# inserting this special "escaped n" character, which renders as a linebreak. Neat, eh?
out = "\n".join(out)
# Our out variable is now in the "foo,bar\nbaz,gaz" format, so we can write it back to
# disk!
write_file(OUTPUT_FILE, out)
print "Program completed!"
print "File located at: {0}.format(OUTPUT_FILE)
# This is your rules engine. It needs to take in the title field from the CSV
# and output one of the expected "in progress" titles for a user. In this
# example, the acceptable values for inprogress titles are CEO and grunt.
# In the event no bucketing title can be computed, "unknown" is returned.
def extractTitle(csv_title_string):
# This is the "do rules" (p)art of your program. You can do literally whatever
# makes sense here, all that needs to happen is your output the string
# identifier for the type of user.
# Python lets you search strings for substrings using "in".
# Example:
# "CEO" in "CEO, Dog, Person"; // True
# "CEO" in "C E O"; // False
# "CEO" in "CEORPHAN"; // True
if "CEO" in user_title:
return "ceo"
# You can also do explicit string matching against a "set" of possible values:
if user_title.lower() in ["grunt", "engineer", "manager", "accountant"]:
return "grunt"
# If we get to the last case, we don't know what the user is, so return our
# fallback value to keep everything happy.
return "unknown"
| true |
4fa6d07d1eb0c987521e86a52214e443980e57b3
|
Python
|
samantabueno/python
|
/CursoEmVideo/CursoEmVideo_ex089.py
|
UTF-8
| 1,004 | 3.8125 | 4 |
[] |
no_license
|
# Exercise for training lists
# Program that you can put the students and your grades
grade = []
repository = []
student = []
while True:
student.append(input('Type the student name: '))
grade.append(int(input('Type first grade: ')))
grade.append(int(input('Type de second grade: ')))
student.append(grade[:])
grade.clear()
repository.append(student[:])
student.clear()
print(repository)
cont = input('Type "N" to stop typing new students: ').upper()
if cont == 'N':
break
print('--'*30)
print(f'{"Id":<3} {"Name":<20} Average')
for pos, value in enumerate(repository):
average = (repository[pos][1][0] + repository[pos][1][1])/2
print(f'{pos:<3} {repository[pos][0]:.<20} {average}')
print('--'*30)
while True:
d = int(input('Which student do you want to see the grade detail?'))
print(f'Grades of {repository[d][0]}: {repository[d][1]}')
cont = input('Type "N" to stop seeing grades: ').upper()
if cont == 'N':
break
| true |
c6be9c203766880062b74effaee3b76bae7b82c2
|
Python
|
GeorgeVasiliadis/Scrap11888
|
/Scrap11888/lib/DataManagement/Filter.py
|
UTF-8
| 516 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
from .Utils import purify
def filter(data, key):
"""
This function is used to filter out all records that don't match to given
key. In current implementation filter is applied on address field.
- data: The formatted data to be filtered.
- key: The srting that should be contained in a record's address.
"""
filtered_data = []
key = purify(key)
for record in data:
if key in purify(record["street"]):
filtered_data.append(record)
return filtered_data
| true |
032798ff7cdfd7d37901db0987b80627f702b886
|
Python
|
cryptogroup123/Trader
|
/core/exchange.py
|
UTF-8
| 1,316 | 3.109375 | 3 |
[] |
no_license
|
"""
Generic exchange class
All info and methods for each exchange is done through this module
"""
import calendar
import datetime
import json
import time
import requests
class Exchange(object):
id = None
def __init__(self,config={}):
settings = self.deep_extend(self.describe(),config)
for key in settings:
setattr(self,key,settings[key])
self.symbols = []
self.load_symbols()
def describe(self):
return {}
def deep_extend(*args):
result = None
for arg in args:
if isinstance(arg,dict):
if not isinstance(result,dict):
result = {}
for key in arg:
result[key] = Exchange.deep_extend(result[key] if key in result else None,arg[key])
else:
result = arg
return result
def load_symbols(self):
symbols = self.fetch_symbols()
for sym in symbols:
if sym not in self.symbols:
self.symbols.append(sym)
def get_symbol_price(self,symbol):
return self.fetch_symbol_price(symbol)
#looping json request until we get a 200/successful response
def loop_json(self,url):
result = None
print(url)
while result == None:
try:
print('trying')
response = requests.get(url)
print(response)
print(response.text)
final = response.json()
result = 1
except:
time.sleep(3)
pass
return final
| true |
2f7acb049a56c3f5091e894907fff9ba04128b64
|
Python
|
ganwy2016/Vehicle_Detection_and_Tracking
|
/vehicle_detection.py
|
UTF-8
| 26,606 | 2.984375 | 3 |
[] |
no_license
|
# coding: utf-8
# In[141]:
#!/usr/bin/env python
import glob
import time
import math
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import scipy.misc
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from skimage.feature import hog
# Import everything needed to edit/save/watch video clips
# from IPython.display import HTML
from moviepy.editor import VideoFileClip
# In[142]:
class CarDetector(object):
"""Detect vehicles in images.
Contains all the attributes and methods to perform detection
of vehicles in an image. Includes feature extraction methods
and training a Linear SVC classifier.
Attributes:
cspace: Color space in which feature extraction should be done
spatial_size: size of the image required for feature extraction
hist_bins: integer number of bins in the histogram
hist_range: tupple of integer defining the range of pixel values (e.g. (0, 255))
orient: integer defining the number of orientations in the HOG method (6 to 12)
pix_per_cell: integer number of pixels per cell for the HOG method
cell_per_block: integer number of cells per block for HOG method
hog_channel: integer number of the image channel for HOG method
vis: boolean flag indicating if the HOG method should return an image representation
feature_vec: boolean flag indication if a feature vecture is required as output
spatial: boolean flag indicating whether spatial feature extraction should be used
histogram: boolean flag indicating whether histogram feature extraction should be used
hog: boolean flag indicating whether HOG feature extraction should be used
classifier: holds the classifier object
scaler: holds the scaler object
"""
def __init__(self, cspace='HSV', spatial_size=(32, 32),
hist_bins=32, hist_range=(0, 256), orient=9,
pix_per_cell=8, cell_per_block=2, hog_channel=2,
spatial=True, histogram=True, hog_method=True):
'''Initializes the object with given params'''
self.cspace = cspace
self.spatial_size = spatial_size
self.hist_bins = hist_bins
self.hist_range = hist_range
self.orient = orient
self.pix_per_cell = pix_per_cell
self.cell_per_block = cell_per_block
self.hog_channel = hog_channel
self.vis = False
self.feature_vec = True
self.spatial = spatial
self.histogram = histogram
self.hog = hog_method
self.classifier = []
self.scaler = []
def get_classifier(self):
'''returns the classifier'''
return self.classifier
def get_scaler(self):
'''returns the scaler'''
return self.scaler
def train_classifier(self, cars, notcars):
'''trains the classifier given the positive (cars) and negative (notcars) datasets'''
classifier_file = 'classifier.pkl'
scaler_file = 'scaler.pkl'
# extract features from dataset
car_features = car_detector.extract_features(cars)
print("Car features extracted")
notcar_features = car_detector.extract_features(notcars)
print("Other features extracted")# Create an array stack of feature vectors
x_data = np.vstack((car_features, notcar_features)).astype(np.float64)
# Fit a per-column scaler
x_scaler = StandardScaler().fit(x_data)
print("X_scaler ready")
#save the model
joblib.dump(x_scaler, scaler_file)
# Apply the scaler to X - normalise data
scaled_x = x_scaler.transform(x_data)
print("Data normalised")
# Define the labels vector
y_data = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))
# Split up data into randomized training and test sets
rand_state = np.random.randint(0, 100)
x_train, x_test, y_train, y_test = train_test_split(scaled_x, y_data, test_size=0.2,
random_state=rand_state)
# Use a linear SVC
svc = LinearSVC()
# Check the training time for the SVC
tstamp1 = time.time()
svc.fit(x_train, y_train)
tstamp2 = time.time()
print(tstamp2-tstamp1, 'Seconds to train SVC...')
# Check the score of the SVC
print('Train Accuracy of SVC = ', svc.score(x_train, y_train))
print('Test Accuracy of SVC = ', svc.score(x_test, y_test))
# Check the prediction time for a single sample
tstamp1 = time.time()
prediction = svc.predict(x_test[0].reshape(1, -1))
print("prediction", prediction)
tstamp2 = time.time()
print(tstamp2-tstamp1, 'Seconds to predict with SVC')
print(svc)
# save the model
joblib.dump(svc, classifier_file)
self.classifier = svc
self.scaler = x_scaler
print("Model saved as:", classifier_file, " and ", scaler_file)
def load_classifier(self, classifier_file, scaler_file):
'''loads the classifier and scaler from files'''
self.classifier = joblib.load(classifier_file)
self.scaler = joblib.load(scaler_file)
print("Model loaded: \n\n", self.classifier)
def bin_spatial(self, img):
'''computes binned color features'''
# Use cv2.resize().ravel() to create the feature vector
features = cv2.resize(img, self.spatial_size).ravel()
# Return the feature vector
return features
def color_hist(self, img):
'''computes color histogram features'''
# Compute the histogram of the color channels separately
channel1_hist = np.histogram(img[:, :, 0], bins=self.hist_bins, range=self.hist_range)
channel2_hist = np.histogram(img[:, :, 1], bins=self.hist_bins, range=self.hist_range)
channel3_hist = np.histogram(img[:, :, 2], bins=self.hist_bins, range=self.hist_range)
# Concatenate the histograms into a single feature vector
hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))
# Return the individual histograms, bin_centers and feature vector
return hist_features
def get_hog_features(self, img_channel):
'''extracts hog features from the given image channel'''
# Call with two outputs if vis==True
if self.vis:
features, hog_image = hog(img_channel, orientations=self.orient,
pixels_per_cell=(self.pix_per_cell, self.pix_per_cell),
cells_per_block=(self.cell_per_block, self.cell_per_block),
transform_sqrt=True, visualise=self.vis,
feature_vector=self.feature_vec)
return features, hog_image
# Otherwise call with one output
else:
features = hog(img_channel, orientations=self.orient,
pixels_per_cell=(self.pix_per_cell, self.pix_per_cell),
cells_per_block=(self.cell_per_block, self.cell_per_block),
transform_sqrt=True, visualise=self.vis, feature_vector=self.feature_vec)
return features
def extract_features_img(self, rgb_image):
'''extracts features from the given rgb image'''
# apply color conversion if other than 'RGB'
features = []
if self.cspace != 'RGB':
if self.cspace == 'HSV':
feature_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)
elif self.cspace == 'LUV':
feature_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2LUV)
elif self.cspace == 'HLS':
feature_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HLS)
elif self.cspace == 'YUV':
feature_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2YUV)
elif self.cspace == 'YCrCb':
feature_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2YCrCb)
else:
feature_image = np.copy(rgb_image)
# Apply bin_spatial() to get spatial color features
if self.spatial:
# features.append(self.bin_spatial(rgb_image)) # extract spatial only in RGB
features.append(self.bin_spatial(feature_image))
# Apply color_hist() also with a color space option now
if self.histogram:
features.append(self.color_hist(feature_image))
if self.hog:
if self.hog_channel == 'ALL':
features.append(self.get_hog_features(feature_image[:, :, 0]))
features.append(self.get_hog_features(feature_image[:, :, 1]))
features.append(self.get_hog_features(feature_image[:, :, 2]))
else:
features.append(self.get_hog_features(feature_image[:, :, self.hog_channel]))
features = np.concatenate((features))
return features
# Define a function to extract features from a list of images
# Have this function call bin_spatial() and color_hist()
# this function combines color, histogram and hog features extraction
def extract_features(self, img_files):
'''extracts features from all the images in the given list of files (img_files)'''
# Create a list to append feature vectors to
features = []
# Iterate through the list of images
for afile in img_files:
# Read in each one by one
# rgb_image = mpimg.imread(afile)
rgb_image = scipy.misc.imread(afile)
# image = cv2.imread(afile) # reads a file into bgr values 0-255
features.append(self.extract_features_img(rgb_image))
# Return list of feature vectors
return features
# In[143]:
def load_dataset():
'''load data from the dataset'''
cars = []
notcars = []
# load vehicle images
images = glob.iglob('vehicles/*/*.png', recursive=True)
for image in images:
cars.append(image)
# load non vehicle images
images = glob.iglob('non-vehicles/*/*.png', recursive=True)
for image in images:
notcars.append(image)
print('cars = ', len(cars))
print('notcars = ', len(notcars))
return cars, notcars
def peak_data(cars, notcars):
'''plot one random example of each from the dataset'''
data_info = data_look(cars, notcars)
print('Your function returned a count of',
data_info["n_cars"], ' cars and',
data_info["n_notcars"], ' non-cars')
print('of size: ', data_info["image_shape"], ' and data type:',
data_info["data_type"])
# choose random car / not-car indices and plot example images
car_ind = np.random.randint(0, len(cars))
notcar_ind = np.random.randint(0, len(notcars))
# Read in car / not-car images
car_image = mpimg.imread(cars[car_ind])
notcar_image = mpimg.imread(notcars[notcar_ind])
# Plot the examples
fig = plt.figure()
plt.subplot(121)
plt.imshow(car_image)
plt.title('Example Car Image')
plt.subplot(122)
plt.imshow(notcar_image)
plt.title('Example Not-car Image')
plt.show()
def data_look(car_list, notcar_list):
'''return some characteristics of the dataset'''
data_dict = {}
# Define a key in data_dict "n_cars" and store the number of car images
data_dict["n_cars"] = len(car_list)
# Define a key "n_notcars" and store the number of notcar images
data_dict["n_notcars"] = len(notcar_list)
# Read in a test image, either car or notcar
example_img = mpimg.imread(car_list[0])
# Define a key "image_shape" and store the test image shape 3-tuple
data_dict["image_shape"] = example_img.shape
# Define a key "data_type" and store the data type of the test image.
data_dict["data_type"] = example_img.dtype
# Return data_dict
return data_dict
# # Sliding Window Implementation
# In[146]:
# Define a function that takes an image,
# start and stop positions in both x and y,
# window size (x and y dimensions),
# and overlap fraction (for both x and y)
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5), max_y=780):
'''returns a list of rectangles of a specific size spanning the image at relevant locations'''
height, width, channels = img.shape
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] is None:
x_start_stop[0] = 0
if x_start_stop[1] is None:
x_start_stop[1] = img.shape[1]
if y_start_stop[0] is None:
y_start_stop[0] = 0
if y_start_stop[1] is None:
y_start_stop[1] = img.shape[0]
# Compute the span of the region to be searched
xspan = x_start_stop[1] - x_start_stop[0]
yspan = y_start_stop[1] - y_start_stop[0]
# Compute the number of pixels per step in x/y
nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0]))
ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1]))
# Compute the number of windows in x/y
nx_windows = np.int(xspan/nx_pix_per_step) - 1
ny_windows = np.int(yspan/ny_pix_per_step) - 1
# Initialize a list to append window positions to
window_list = []
# Loop through finding x and y window positions
# Note: you could vectorize this step, but in practice
# you'll be considering windows one by one with your
# classifier, so looping makes sense
for ys in range(ny_windows):
for xs in range(nx_windows):
# Calculate window position
startx = int(xs*nx_pix_per_step + x_start_stop[0])
endx = int(startx + xy_window[0])
starty = int(ys*ny_pix_per_step + y_start_stop[0])
endy = int(starty + xy_window[1])
# Append window position to list
if endy < height and endx < width and endy < max_y:
window_list.append(((startx, starty), (endx, endy)))
# Return the list of windows
return window_list
# create a list of rectangles with different sizes across the
# lower part of the image for searching cars
def create_list_rectangles(img):
'''creates a list of rectangles of different sizes across relevant section of the image'''
height, width, channels = img.shape
window_list = ()
rectangles = []
step_h = 32
start_h = step_h#int(height/4)
stop_h = height
# size_of_sq = int(256 * (1/height))
y_val = int(9*height/16)
size_vec = [100, 140]
overlap_vec = [0.5, 0.5]
for i, _ in enumerate(size_vec):
size = size_vec[i]
overlap = overlap_vec[i]
window_list = slide_window(img, x_start_stop=[0, width+size],
y_start_stop=[y_val, y_val+4*size],
xy_window=(size, size),
xy_overlap=(overlap, overlap),
max_y=height*0.9)
rectangles.extend(window_list)
return rectangles
# In[130]:
def draw_rectangles(img, window_list, color=(255, 255, 255)):
'''draw the list of rectangles in the image'''
labeled_img = img.copy()
for window in window_list:
pt1 = window[0]
pt2 = window[1]
thickness = 4
cv2.rectangle(labeled_img, pt1, pt2, color, thickness)
return labeled_img
# In[131]:
def get_heat_map(img, rectangles, car_detector_obj, heat_increment=25, debug=0):
'''creates a heat map'''
cv_filled = -1
heat_map = np.zeros_like(img)
if debug:
positive_cars = np.copy(img)
for rectangle in rectangles:
heat_img = np.zeros_like(img)
pt1 = rectangle[0]
pt2 = rectangle[1]
crop_img = img[pt1[1]:pt2[1], pt1[0]:pt2[0]]
size = (64, 64)
crop_img = cv2.resize(crop_img, size)#.astype(np.float64)
img_features = car_detector_obj.extract_features_img(crop_img)
features = np.vstack((img_features)).astype(np.float64)
features = np.array(features).reshape(1, -1)
feature_scaler = car_detector_obj.get_scaler()
classifier = car_detector_obj.get_classifier()
scaled_features = feature_scaler.transform(features)
prediction = classifier.predict(scaled_features.reshape(1, -1))
if prediction == 1:
if debug:
cv2.rectangle(positive_cars, pt1, pt2, color=(255, 255, 255), thickness=4)
cv2.rectangle(heat_img, pt1, pt2,
color=(heat_increment, heat_increment, heat_increment),
thickness=cv_filled)
heat_map = cv2.add(heat_map, heat_img)
if debug:
plt.imshow(positive_cars)
plt.show()
return heat_map
# In[132]:
# apply filter to the heat_map
# Note: th_ratio should be a ratio (0-1)
# It will be used with respect to the maximum pixel value in the image
def filter_heat_map(heat_map, th_ratio=0.5):
'''filter the heat map given the threshold (th_ratio)'''
red_channel = np.copy(heat_map[:, :, 0])
threshold = np.amax(red_channel)*th_ratio # define threshold
filt_heat_map = np.zeros_like(heat_map)
if np.amax(red_channel) > 0:
red_channel[red_channel >= threshold] = 255
red_channel[red_channel < threshold] = 0
filt_heat_map[:, :, 0] = red_channel
return filt_heat_map
# In[133]:
def get_detected(heat_map, area_th=20, heat_th=80):
'''computes positions and bounding rectangles identifying the location of detected vehicles'''
# define a threshold for minimum area required to be a positive detection
imgray = heat_map[:, :, 0]#cv2.cvtColor(heat_map,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray.astype(np.uint8), heat_th, 255, cv2.THRESH_BINARY) #60
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
data = []
for contour in contours:
area = cv2.contourArea(contour)
if area > area_th:
x_pos, y_pos, width, height = cv2.boundingRect(contour)
M = cv2.moments(contour)
# calculate image centroid
centroid_x = int(M['m10']/M['m00'])
centroid_y = int(M['m01']/M['m00'])
pt1 = (x_pos, y_pos)
pt2 = (x_pos+width, y_pos+height)
coord = [centroid_x, centroid_y]
rect = [pt1, pt2]
data.append((coord, rect, area))
return data
# In[134]:
def get_distance(pt1, pt2):
'''computes the euclidean distance between two points'''
return math.sqrt((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2)
# In[135]:
def filter_by_location(data, valid_data, threshold=50):
'''filters valid data based on the threshold distance'''
# for each element of data, chech if there is one in filter data that is close enough
# if so, then it is a valid element
posit_data = []
for elem in data:
for valid_el in valid_data:
#compute distance
distance = get_distance(elem[0], valid_el[0])
if distance < threshold:
posit_data.append(elem)
return posit_data
# In[136]:
def create_map_from_data(img, posit_data, heat_increment=25):
'''convert the data (as rectangles) in a heat map'''
new_heat_map = np.zeros_like(img) # 1 channel is enough
for elem in posit_data:
cv2.rectangle(new_heat_map, elem[1][0], elem[1][1],
(heat_increment, heat_increment, heat_increment),
thickness=-1) #filled rect
return new_heat_map
# In[137]:
def process_image(img, debug=0):
'''pipeline to process a single image (e.g. from camera or video stream)'''
heat_increment = 25 #25
heat_thres = 80
if not hasattr(process_image, "heat_map_old"):
process_image.heat_map_old = np.zeros_like(img)
if not process_image.heat_map_old.size:
process_image.heat_map_old = np.zeros_like(img)
decay = 0.05
# apply decay to the heat_map
process_image.heat_map_old = process_image.heat_map_old*(1-decay)
#get heat_map
heat_map = get_heat_map(img, process_image.rectangles,
process_image.car_detector, heat_increment)
#filter the heat map to get rid of false positives
filtered_heat_map = filter_heat_map(heat_map, th_ratio=0.5)
valid_data = get_detected(filtered_heat_map, area_th=1000, heat_th=heat_thres)
# now that we know the location of valid positives
# we can use the original heat map to get the complete area and filter out false positives
filtered_heat_map = filter_heat_map(heat_map, th_ratio=0.05)
data = get_detected(filtered_heat_map, area_th=1000, heat_th=heat_thres)
posit_data = filter_by_location(data, valid_data)
# now we create a new filtered_heat_map with the posit_data only
filtered_heat_map = create_map_from_data(img, posit_data, heat_increment=255)
process_image.heat_map_old = (filtered_heat_map*0.2 + process_image.heat_map_old*0.8)
final_data = get_detected(process_image.heat_map_old, area_th=1000, heat_th=100)
detected_car_rectangles = []
for elem in final_data:
detected_car_rectangles.append(elem[1])
detected_cars_img = draw_rectangles(img, detected_car_rectangles, color=(255, 255, 255))
if debug:
# Ploting images
labeled_img = draw_rectangles(img, process_image.rectangles)
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(24, 9))
fig.tight_layout()
ax1.imshow(heat_map)
ax1.set_title('Heat map')
ax2.imshow(filtered_heat_map.astype(np.uint8))
ax2.set_title('Filtered heat_map')
ax3.imshow(process_image.heat_map_old.astype(np.uint8))
ax3.set_title('Used heat_map')
ax4.imshow(img)
ax4.set_title('Source image')
ax5.imshow(labeled_img)
ax5.set_title('Sliding Window')
ax6.imshow(detected_cars_img)
ax6.set_title('Confirmed cars')
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
ax4.axis('off')
ax5.axis('off')
ax6.axis('off')
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()
return detected_cars_img
# In[156]:
def process_video(input_video_file, output_video_file, pipeline_func):
'''process a video file'''
video_output = output_video_file
clip1 = VideoFileClip(input_video_file)
video_clip = clip1.fl_image(pipeline_func) #NOTE: this function expects color images!!
get_ipython().magic('time video_clip.write_videofile(video_output, audio=False)')
print('Finished processing video file')
# # Method
# * Perform a Histogram of Oriented Gradients (HOG) feature extraction on a labeled training set of images and train a classifier Linear SVM classifier
# * Optionally, you can also apply a color transform and append binned color features, as well as histograms of color, to your HOG feature vector.
# * Note: for those first two steps don't forget to normalize your features and randomize a selection for training and testing.
# * Implement a sliding-window technique and use your trained classifier to search for vehicles in images.
# * Run your pipeline on a video stream and create a heat map of recurring detections frame by frame to reject outliers and follow detected vehicles.
# * Estimate a bounding box for vehicles detected.
#
# # Train or Load existing Model
# # ========================
# In[160]:
def main():
# my code here
new_model = False
# new_model = True
# create a CarDetector object
# cspace='RGB', spatial_size=(16, 16),hist_bins=16,hog_channel=0) #cspace='YUV',hog_channel=1)
# Options: RGB, HSV, LUV, HLS, YUV
car_detector = CarDetector(cspace='HSV', hog_channel=2, spatial=True,
histogram=True, hog_method=True)
if new_model:
# load the dataset
cars, notcars = load_dataset()
peak_data(cars, notcars)
#train the classifier
car_detector.train_classifier(cars, notcars)
else:
# load existing model
car_detector = CarDetector(cspace='HSV', hog_channel=2, spatial=True,
histogram=True, hog_method=True)
car_detector.load_classifier('classifier.pkl', 'scaler.pkl')
# Test pipeline in an test image
im_filename = 'test_images/test_01.jpg' # two cars, black and white
rgb_image = scipy.misc.imread(im_filename)
#reset heat_map_old
process_image.heat_map_old = np.zeros_like(rgb_image)
process_image.car_detector = car_detector
process_image.rectangles = create_list_rectangles(rgb_image)
# im_filename = 'test_images/test_14.png' # two cars, black and white
# im_filename = 'test_images/test_13.png' # two cars, black and white
# im_filename = 'test_images/test_12.png' # two cars, black and white
# im_filename = 'test_images/test_11.png' # two cars, black and white
# im_filename = 'test_images/test_10.png' # two cars, black and white
# im_filename = 'test_images/test_09.png' # two cars, black and white
# im_filename = 'test_images/test_08.png' # two cars, black and white
# im_filename = 'test_images/test_07.png' # two cars, black and white
# im_filename = 'test_images/test_06.jpg' # two cars, black and white
# im_filename = 'test_images/test_05.jpg' # two cars, black and white
# im_filename = 'test_images/test_04.jpg' # two cars, black and white
# im_filename = 'test_images/test_03.jpg' # white car
# im_filename = 'test_images/test_02.jpg' # no cars
im_filename = 'test_images/test_01.jpg' # two cars, black and white
result = process_image(rgb_image, debug=1)
#process a video file
process_image.heat_map_old = np.zeros_like(rgb_image)
process_image.car_detector = car_detector
process_image.rectangles = create_list_rectangles(rgb_image)
# process_video('test_video.mp4', 'output_images/test_output.mp4', process_image)
# process_video('small_video_2.mp4', 'output_images/small_output_2.mp4', process_image)
# process_video('small_video_3.mp4', 'output_images/small_output_3.mp4', process_image)
# process_video('project_video.mp4', 'output_images/project_output.mp4', process_image)
if __name__ == "__main__":
main()
# In[ ]:
| true |
75574e95bfb78cc895f9c8663a4d8ff31fb04c6c
|
Python
|
rehnuma777/Bot_detection_keyboard
|
/classifiers.py
|
UTF-8
| 4,993 | 2.71875 | 3 |
[] |
no_license
|
import os
from sklearn import metrics
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score
import scipy
import numpy as np
import sklearn
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
from sklearn import neighbors
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score
from sklearn import svm
from sklearn.model_selection import cross_validate,KFold
import pandas as pd
global files
features_directory = r'D:\BotDetection-master\BotDetection-master\data\features'
def get_data_from_folders(data_folders):
data = None
classifications = []
for folder in data_folders:
# Retrieve key and mouse features for a single user
key_data = pd.read_csv(os.path.join(features_directory, folder, 'key.csv'))
mouse_data = pd.read_csv(os.path.join(features_directory, folder, 'mouse.csv'))
# Combine key and mouse features from the user into one row
merged_data = pd.concat([key_data, mouse_data], axis=1)
# Determine classification of user from folder name and add to classifications
classification = 'human' if 'human' in folder else 'bot'
classifications.append(classification)
# Merge feature row with existing data set
data = merged_data if data is None else pd.concat([data, merged_data], ignore_index=True)
return data, classifications
def get_data_for_advanced_bot():
global files
# Retrieve all folders from features directory. Each user's data is in a separate folder.
folders = [f for f in os.listdir(features_directory) if os.path.isdir(os.path.join(features_directory, f))]
human_folders = [f for f in folders if 'human' in f]
advanced_bot_folders = [f for f in folders if 'advanced' in f]
data_folders = human_folders + advanced_bot_folders
return get_data_from_folders(data_folders)
def get_data_for_simple_bot():
global files
# Retrieve all folders from features directory. Each user's data is in a separate folder.
folders = [f for f in os.listdir(features_directory) if os.path.isdir(os.path.join(features_directory, f))]
human_folders = [f for f in folders if 'human' in f]
simple_bot_folders = [f for f in folders if 'simple' in f]
data_folders = human_folders + simple_bot_folders
return get_data_from_folders(data_folders)
#get_data_for_simple_bot()
def print_results(results):
# Print accuracy, precision, recall, and F1 score results from a classifier
# The mean() is there because cross validation evaluates on each 'split' of data, so the
# number of results is the same as the number of splits.
print('Accuracy: {:0.2f}%'.format(results['test_accuracy'].mean() * 100))
print('Precision: {:0.2f}%'.format(results['test_precision'].mean() * 100))
print('Recall: {:0.2f}%'.format(results['test_recall'].mean() * 100))
print('F1 score: {:0.2f}%'.format(results['test_f1_score'].mean() * 100))
print('\n')
def main():
# This contains the human and simple bot data
X_simple, y_simple = get_data_for_simple_bot()
# This contains the human and advanced bot data
X_advanced, y_advanced = get_data_for_advanced_bot()
classifiers = []
cv = KFold(n_splits=2, shuffle=True)
rfc = RandomForestClassifier()
dt = DecisionTreeClassifier()
SVM = svm.SVC(kernel = 'linear')
knn = neighbors.KNeighborsClassifier(n_neighbors=3, weights = 'uniform')
classifiers.append(knn)
classifiers.append(rfc)
classifiers.append(dt)
classifiers.append(SVM)
#knn.fit(X_simple, y_simple)
#knn.fit(X_advanced,y_simple)
#prediction = knn.predict()
scoring = {'accuracy': make_scorer(accuracy_score),
'precision': make_scorer(precision_score, pos_label='bot'),
'recall': make_scorer(recall_score, pos_label='bot'),
'f1_score': make_scorer(f1_score, pos_label='bot')}
for clf in classifiers:
print('Results for classifier: {}'.format(str(clf)))
print('=================================================\n')
# Simple bot results (human + simple data)
print('Simple Bot Results')
print('------------------')
results = cross_validate(clf, X_simple, y_simple, cv=cv, scoring=scoring)
print_results(results)
# This is commented out for now because there's not enough advanced bot data for this data.
# Advanced bot results (human + advanced data)
# print('Advanced Bot Results')
# print('--------------------')
# results = cross_validate(rfc, X_advanced, y_advanced, cv=cv, scoring=scoring)
# print(results)
if __name__ == '__main__':
main()
| true |
adc0e45f9bdde3acc071e9709a0487724abf9fe7
|
Python
|
Axect/PL2020
|
/05_number/04_complex_4.py
|
UTF-8
| 769 | 3.734375 | 4 |
[] |
no_license
|
class Complex:
def __init__(self, a, b):
self.real = a
self.imag = b
def __str__(self):
if self.imag >= 0:
return str(self.real) + " + " + str(self.imag) + "i"
else:
return str(self.real) + " - " + str(-self.imag) + "i"
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
return Complex(
self.real * other.real - self.imag * other.imag,
self.real * other.imag + self.imag * other.real
)
z1 = Complex(1, 2)
z2 = Complex(2, -3)
print(z1 + z2)
print(z1 - z2)
print(z1 * z2)
| true |
9b7e00f489f76673c0f9ac982224fd31d01abd89
|
Python
|
Nauman3S/MQ3VendingMachine
|
/Firmware/tempFW.py
|
UTF-8
| 761 | 2.984375 | 3 |
[] |
no_license
|
# import time
# import smbus
# import time
# # Get I2C bus
# bus = smbus.SMBus(1)
# BAC= 10000#1BAC(g/dL) is 10000ppm
# PPM=1/BAC
# mgL=0.1#mg/dL
# def getAlcoholValue():
# global bus,PPM,mgL
# data = bus.read_i2c_block_data(0x50, 0x00, 2)
# # Convert the data to 12-bits
# raw_adc = (data[0] & 0x0F) * 256 + data[1]
# concentration = (9.95 / 4096.0) * raw_adc + 0.05
# print ("Alcohol Concentration : %.2f mg/l" %concentration)
# concentration=concentration*mgL#conversion to mg/dL
# concentration=concentration*0.001#conversion to g/dL
# BACValue=concentration
# print('ALCOHOL BAC=',BACValue)
# return BACValue
# while 1:
# time.sleep(1)
# getAlcoholValue()
a=[1.1,2,3,4]
print(sum(a))
| true |
bcf165f69ae9c611c464cff1f441c0db00e43b97
|
Python
|
leodbrito/helpredirect
|
/models.py
|
UTF-8
| 8,106 | 2.96875 | 3 |
[] |
no_license
|
import re
import requests
class HelpRedirect:
def __init__(self, source_url=None, dest_url=None):
self.source_url = source_url
self.dest_url = dest_url
def clear_validations(self):
validations = {
"match_values_error": False,
"match_values_error_msg": "[ Falha ] Para que a construção das regras seja correto é necessário o mesmo número de URLs de origem e destino!",
"have_duplicates": False,
"duplicates_msg": "[ Falha ] Na lista de URLs de origem NÃO podem haver duplicatas!",
"source_urls_duplicates_list": [],
"have_path_duplicates": False,
"path_duplicates_msg": "[ Falha ] Na lista de URLs de origem NÃO podem haver duplicatas de 'PATH'!",
"source_urls_path_duplicates_list": [],
"have_invalid_source_url": False,
"invalid_source_url_msg": "[ Falha ] URL(s) de origem inválida(s)! Verifique se em sua composição é seguido o modelo protocol://domain/path",
"invalid_source_url_list": [],
"have_invalid_dest_url": False,
"invalid_dest_url_msg": "[ Falha ] URL(s) de destino inválida(s)! Verifique se em sua composição é seguido o modelo protocol://domain/path",
"invalid_dest_list": []
}
return validations
def input_validate(self):
source_url = str(self.source_url).strip().split()
dest_url = str(self.dest_url).strip().split()
invalid_source_url_list = []
invalid_dest_url_list = []
source_urls_duplicates_list = []
source_urls_path_list = []
source_urls_path_duplicates_list = []
validations = self.clear_validations()
# Verificando se na lista de URLs de destino, caso seja > 1, tem a mesma quantidade de URLs de origem
if len(dest_url) > 1 and len(dest_url) != len(source_url):
validations["match_values_error"] = True
# Verificando se na lista de URLs de origem tem duplicatas ou URLs inválidas
for url in source_url:
if re.search('\.(com|br|globo)/.', url.lower()):
if source_url.count(url) > 1 and source_urls_duplicates_list.count(url) == 0:
source_urls_duplicates_list.append(url)
else:
# Criando uma lista de paths
path = re.sub("^.+\.(com|globo|br)/", "/", url)
if not re.search("/$", path):
path = path.replace(path, path+"/",1)
source_urls_path_list.append(path)
else:
invalid_source_url_list.append(url)
for path in source_urls_path_list:
if source_urls_path_list.count(path) > 1 and source_urls_path_duplicates_list.count(path) == 0:
source_urls_path_duplicates_list.append(path)
# Preenchendo as listas com os erros encontrados
if len(source_urls_duplicates_list) > 0:
validations["have_duplicates"] = True
validations["source_urls_duplicates_list"] = source_urls_duplicates_list
if len(source_urls_path_duplicates_list) > 0:
validations["have_path_duplicates"] = True
validations["source_urls_path_duplicates_list"] = source_urls_path_duplicates_list
if len(invalid_source_url_list) > 0:
validations["have_invalid_source_url"] = True
validations["invalid_source_url_list"] = invalid_source_url_list
for url in dest_url:
if not re.search('^(http|https)://.+\.(com|br|globo|info|net|org|biz|name|pro|aero|asia|cat|coop|edu|eu|gal|gov|int|jobs|mil|mobi|museum|news|tel|travel|xxx)/?', url.lower()):
invalid_dest_url_list.append(url)
if len(invalid_dest_url_list) > 0:
validations["have_invalid_dest_url"] = True
validations["invalid_dest_url_list"] = invalid_dest_url_list
return validations
def create_rule_list(self):
source_url = str(self.source_url).strip().split()
dest_url = str(self.dest_url).strip().split()
validations = self.input_validate()
rule_list = []
compile1 = re.compile(r'^.+\.(com|globo|br)/', flags=re.IGNORECASE)
if validations["match_values_error"] == False and validations["have_duplicates"] == False and validations["have_invalid_source_url"] == False:
for url in source_url:
if len(dest_url) == 1:
compiled = str(compile1.sub(r'rewrite ^/',url))
if url.rfind('.',-6) != -1:
rule_list.append(compiled+f'$ {dest_url[0]} permanent;')
elif url.rfind('/',-1) != -1:
rule_list.append(compiled+f'?$ {dest_url[0]} permanent;')
else:
rule_list.append(compiled+f'/?$ {dest_url[0]} permanent;')
elif len(dest_url) == len(source_url):
compiled = str(compile1.sub(r'rewrite ^/',url))
if url.rfind('.',-6) != -1:
rule_list.append(compiled+f'$ {dest_url[source_url.index(url)]} permanent;')
elif url.rfind('/',-1) != -1:
rule_list.append(compiled+f'?$ {dest_url[source_url.index(url)]} permanent;')
else:
rule_list.append(compiled+f'/?$ {dest_url[source_url.index(url)]} permanent;')
return rule_list
def check_url_status(self, is_source=True):
if is_source:
url_list = str(self.source_url).strip().split()
else:
url_list = str(self.dest_url).strip().split()
url_status_list = []
request_error = False
for url in url_list:
url_status = {
"URL": url,
"history_list": [],
"Server": "",
"X-Sered-from": "",
"Cache-Control": "",
"Via": ""
}
if not re.search('^(http://|https://)', url.lower()):
url = f'http://{url}'
try:
request = requests.get(url, timeout = 1)
request.raise_for_status()
except requests.exceptions.HTTPError as errh:
url_status["Http Error"] = errh
except requests.exceptions.ConnectionError as errc:
url_status["Error Connecting"] = errc
except requests.exceptions.Timeout as errt:
url_status["Timeout Error"] = errt
except requests.exceptions.RequestException as err:
url_status["Ops, Something Else"] = err
try:
request
except:
request_error = True
url_status["history_list"] = []
if request_error == False:
for location in request.history:
url_status["history_list"].append({"Location": location.url, "HTTP Status Code": location.status_code})
url_status["history_list"].append({"Location": request.url, "HTTP Status Code": request.status_code})
try:
headers = request.headers
except:
headers = None
if headers != None:
for k, v in headers.items():
if "server" in k.lower():
url_status["Server"] = v
if "x-served-from" in k.lower():
url_status["X-Sered-from"] = v
if "cache-control" in k.lower():
url_status["Cache-Control"] = v
if "via" in k.lower():
url_status["Via"] = v
url_status_list.append(url_status)
return url_status_list
| true |
ec32feff60117b022e7b0fdc5283acef57c6b17f
|
Python
|
mullen25312/aoc2019
|
/d10/d10.py
|
UTF-8
| 5,460 | 3.328125 | 3 |
[] |
no_license
|
import math
from collections import OrderedDict
def in_line_of_sight(vec1, vec2):
# only vectors in the same quadrant can be in line of sight
if ((vec1[0] >= 0) == (vec2[0] >= 0)) and ((vec1[1] >= 0) == (vec2[1] >= 0)):
# check for linear dependency
if vec1[0] != 0 and vec2[0] != 0:
if vec1[1] / vec1[0] == vec2[1] / vec2[0]:
return True
if vec1[0] == 0 and vec2[0] == 0:
return True
else:
return False
else:
return False
class DailyPuzzle10:
def __init__(self):
self.astroid_map_dict = {}
def read_data(self):
# read input data
with open("./d10/input.txt") as f:
lines = f.readlines()
# and save as dictionary with astroid positions as keys
for y, line in enumerate(lines):
for x, pos in enumerate(line):
if pos == "#":
self.astroid_map_dict[(x, y)] = []
def solve_part_one(self):
# look through all astroids
for astroid in self.astroid_map_dict:
# order other astroids by distance w.r.t. considered astroid
other_astroids = OrderedDict(
sorted(
self.astroid_map_dict.items(),
key=lambda item: (item[0][0] - astroid[0]) ** 2
+ (item[0][1] - astroid[1]) ** 2,
)
)
# delete first astroid with distance zero because it is itself
other_astroids.popitem(last=False)
# go through all other astroids ordered by distance
for other_astroid in other_astroids:
# assume it is not blocked
self.astroid_map_dict[astroid].append(other_astroid)
# and check against all other already in line of sight
vec1 = (other_astroid[0] - astroid[0], other_astroid[1] - astroid[1])
for los_astroid in self.astroid_map_dict[astroid][:-1]:
vec2 = (los_astroid[0] - astroid[0], los_astroid[1] - astroid[1])
if in_line_of_sight(vec1, vec2):
# if in line of sight dismiss
self.astroid_map_dict[astroid].pop()
break
# find astroid position with most line of sight astroids for monitoring station
monitoring_station = max(
self.astroid_map_dict.keys(),
key=(lambda astroid: len(self.astroid_map_dict[astroid])),
)
# return number of most line of sight astroids
return len(self.astroid_map_dict[monitoring_station])
def solve_part_two(self):
# what is the astroid position with most line of sight astroids again
monitoring_station = max(
self.astroid_map_dict.keys(),
key=(lambda astroid: len(self.astroid_map_dict[astroid])),
)
# lets vaporize them all
vaporized = []
while len(self.astroid_map_dict) != 1: # until monitoring station is left
# arrange astroid in line of sight in clockwise (reverse mathematical) order
# rotate coordinate frame by 90 deg because laser fires along y-axis first
self.astroid_map_dict[monitoring_station].sort(
key=lambda item: math.atan2(
-(item[0] - monitoring_station[0]) - 0.0000001, # corr: above first
+(item[1] - monitoring_station[1]),
),
)
# vaporize each astroid in that order
for astroid in self.astroid_map_dict[monitoring_station]:
vaporized.append(astroid)
self.astroid_map_dict.pop(astroid)
self.astroid_map_dict[monitoring_station] = []
# determine new astroids in line of sight
# order other astroids by distance w.r.t. considered astroid
other_astroids = OrderedDict(
sorted(
self.astroid_map_dict.items(),
key=lambda item: (item[0][0] - monitoring_station[0]) ** 2
+ (item[0][1] - monitoring_station[1]) ** 2,
)
)
# delete first astroid with distance zero because it is itself
other_astroids.popitem(last=False)
# go through all other astroids ordered by distance
for other_astroid in other_astroids:
# assume it is not blocked
self.astroid_map_dict[monitoring_station].append(other_astroid)
# and check against all other already in line of sight
vec1 = (
other_astroid[0] - monitoring_station[0],
other_astroid[1] - monitoring_station[1],
)
for los_astroid in self.astroid_map_dict[monitoring_station][:-1]:
vec2 = (
los_astroid[0] - monitoring_station[0],
los_astroid[1] - monitoring_station[1],
)
if in_line_of_sight(vec1, vec2):
# if in line of sight dismiss
self.astroid_map_dict[monitoring_station].pop()
break
# return result: multiply its X coordinate by 100 and then add its Y coordinate
print(vaporized[200 - 1][0] * 100 + vaporized[200 - 1][1])
| true |
113f33d670cf52d6c34fd52b796dfb3bf3386073
|
Python
|
wfondrie/mokapot
|
/mokapot/writers/txt.py
|
UTF-8
| 2,945 | 3.390625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""Writer to save results in a tab-delmited format"""
from pathlib import Path
from collections import defaultdict
import pandas as pd
def to_txt(conf, dest_dir=None, file_root=None, sep="\t", decoys=False):
"""Save confidence estimates to delimited text files.
Write the confidence estimates for each of the available levels
(i.e. PSMs, peptides, proteins) to separate flat text files using the
specified delimiter. If more than one collection of confidence estimates
is provided, they will be combined, yielding a single file for each level
specified by either dataset.
Parameters
----------
conf : Confidence object or tuple of Confidence objects
One or more :py:class:`~mokapot.confidence.LinearConfidence` objects.
dest_dir : str or None, optional
The directory in which to save the files. :code:`None` will use the
current working directory.
file_root : str or None, optional
An optional prefix for the confidence estimate files. The suffix will
always be "mokapot.{level}.txt" where "{level}" indicates the level at
which confidence estimation was performed (i.e. PSMs, peptides,
proteins).
sep : str, optional
The delimiter to use.
decoys : bool, optional
Save decoys confidence estimates as well?
Returns
-------
list of str
The paths to the saved files.
"""
try:
assert not isinstance(conf, str)
iter(conf)
except TypeError:
conf = [conf]
except AssertionError:
raise ValueError("'conf' should be a Confidence object, not a string.")
file_base = "mokapot"
if file_root is not None:
file_base = file_root + "." + file_base
if dest_dir is not None:
file_base = Path(dest_dir, file_base)
results = defaultdict(list)
for res in conf:
for level, qval_list in _get_level_data(res, decoys).items():
results[level] += qval_list
out_files = []
for level, qval_list in results.items():
out_file = str(file_base) + f".{level}.txt"
pd.concat(qval_list).to_csv(out_file, sep=sep, index=False)
out_files.append(out_file)
return out_files
def _get_level_data(conf, decoys):
"""Return the dataframes for each level.
Parameters
----------
conf : a Confidence object
A LinearConfidence object.
decoys : bool
Should decoys be included?
Returns
-------
Dict
Each entry contains a level, dataframe pair.
"""
results = defaultdict(list)
for level, qvals in conf.confidence_estimates.items():
if qvals is None:
continue
results[level].append(qvals)
if decoys:
for level, qvals in conf.decoy_confidence_estimates.items():
if qvals is None:
continue
results[f"decoy.{level}"].append(qvals)
return results
| true |
25f381b4e53c6e525e7a6a869e5bc0b524d381c2
|
Python
|
adelriscom/Python
|
/Python/AP-Python/Curso Tutorizado Python/Python-Mintic/moduloGenerarContraseñas.py
|
UTF-8
| 999 | 3.671875 | 4 |
[] |
no_license
|
import random
def generarContrasegna():
mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#print(mayusculas)
minusculas = mayusculas.lower()
#print(minusculas)
mayusculas = list(mayusculas)
#print(mayusculas)
minusculas = list(minusculas)
#print(minusculas)
numeros = list("1234567890")
#print(numeros)
simbolos = list("!@#$%^&*()/-.,")
#print(simbolos)
caracterUtilizar = mayusculas + minusculas + numeros + simbolos
#print(caracterUtilizar)
# CONTINUAR GENERAR CONTRASEÑA SEGURA
contrasegna = list()
#print(contrasegna)
rango = random.randint(10, 20)
for i in range(rango):
caractAleat = random.choice(caracterUtilizar)
#print(caractAleat)
contrasegna.append(caractAleat)
#print(contrasegna)
#print(contrasegna)
#contrasegna = "".join(contrasegna)
contrasegna = str().join(contrasegna)
#print(contrasegna)
return contrasegna
| true |
7ed67483d8d3be33602062515a5ae2e53468e226
|
Python
|
shukaiz/movie-scraper-api
|
/graph.py
|
UTF-8
| 3,524 | 3.140625 | 3 |
[] |
no_license
|
import numpy as np
import pandas as pd
import networkx as nx
from networkx.readwrite import json_graph
import matplotlib.pyplot as plt
import json
import logging
def top_actors(x):
"""
List the top X actors with most movie productions
With most movie productions means more connections.
"""
logging.debug("top_actors function called.")
df = df_actor.nlargest(x, 'num_movies')
return str(df['name'].values.tolist())
def print_edges(g):
"""
Print all edges in the graph
For testing.
"""
logging.debug("print_edges function called.")
for line in nx.generate_adjlist(g):
print(line)
def data_analysis():
"""
Plot relationship between age and total gross.
Also conducts data analysis as required.
"""
logging.debug("data_analysis function called.")
plt.scatter(df_actor['age'], df_actor['total_gross'], s=df_actor['num_movies'], alpha=0.5)
plt.title("Actor/Actresses' Age vs. Total Gross")
plt.xlabel("Age")
plt.ylabel("Total Gross")
plt.show()
print(top_actors(2)) # List out two actors with most connections.
print("Correlation between actor/actress' age and total gross:")
print(np.corrcoef(df_actor['age'], df_actor['total_gross']))
data = json.load(open("json/data.json")) # Read new JSON
logging.debug("data.json Read.")
graph = nx.Graph() # Initialize graph
# Create new lists for actors to be added to data frame.
name = []
age = []
total_gross = []
movies = []
# To generate JSON for later visualization.
id = []
group = []
source = []
target = []
value = []
# Read actor data and add to graph
for i in data[0]:
name.append(i)
id.append(i)
group.append(1)
age.append(data[0][i]['age'])
total_gross.append(data[0][i]['total_gross'])
movies.append(len(data[0][i]['movies']))
graph.add_node(i)
for movie in data[0][i]['movies']:
graph.add_node(movie)
graph.add_edge(i, movie)
id.append(movie)
group.append(2)
source.append(i)
target.append(movie)
value.append(5)
logging.info("Actor data read and added to graph.")
# Create a data frame for actors
df_actor = pd.DataFrame()
df_actor['name'] = name
df_actor['age'] = age
df_actor['total_gross'] = total_gross
df_actor['num_movies'] = movies
# Create new lists for films to be added to data frame.
film = []
year = []
box_office = []
actors = []
# Read film data
for i in data[1]:
film.append(i)
id.append(i)
group.append(2)
year.append(data[1][i]['year'])
box_office.append(data[1][i]['box_office'])
actors.append(len(data[1][i]['actors']))
graph.add_node(i)
for actor in data[1][i]['actors']:
graph.add_node(actor)
graph.add_edge(i, actor)
id.append(actor)
group.append(1)
source.append(i)
target.append(actor)
value.append(5)
logging.info("Movie data read and added to graph.")
# Create a data frame for films
df_movie = pd.DataFrame()
df_movie['name'] = film
df_movie['year'] = year
df_movie['box_office'] = box_office
df_movie['num_actors'] = actors
# Generate node JSON for visualization
df_nodes = pd.DataFrame()
df_nodes['id'] = id
df_nodes['group'] = group
df_nodes.to_json('json/nodes.json', orient='records')
# Generate links JSON for visualization
df_links = pd.DataFrame()
df_links['source'] = source
df_links['target'] = target
df_links['value'] = value
df_links.to_json('json/links.json', orient='records')
# Run for data analysis
data_analysis()
| true |
92b2cd7902e9980c382ea20ae42d9f60267604f4
|
Python
|
Nosskirneh/SmartRemoteControl
|
/util.py
|
UTF-8
| 622 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
import datetime
from typing import Tuple, Union
import json
import os
def get_hour_minute(time: str) -> Tuple[str, str]:
return [int(x) for x in time.split(":")]
def time_in_range(start: datetime.time, end: datetime.time, time: datetime.time) -> bool:
"""Returns true if time is in the range [start, end]"""
if start <= end:
return start <= time <= end
else:
return start <= time or time <= end
def load_json_file(filename: str) -> Union[dict, list]:
with open(filename) as file:
return json.load(file)
def is_debug() -> bool:
return os.environ.get("DEBUG") is not None
| true |
b93176d884bfe91a49a1b36adf27de89401365cb
|
Python
|
liuzhipeng17/python-common
|
/python基础/第三方模块/argparser/test_argparse.py
|
UTF-8
| 1,800 | 3.6875 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import argparse
parser = argparse.ArgumentParser(description='Ftp client')
# 添加位置参数(不用带-)
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
# integers: 说明这个参数名字是integers,可以通过解析后获取
# metavar
# ype=int 默认参数类型为string,可以通过type设置类型,参数类型不一样会报类型错误
# help 是对这个参数的说明
# nargs
# 添加可选参数
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
# dest通过解析后,其值保存在args.accumulate(有dest),没有dest保存在integers
# action
args = parser.parse_args()
#parse_args()返回一个对象,该对象拥有两个属性:integers,accumulate
#integers是列表,元素为整形
#accumulate为函数名,如果命令行指明--sum,则为sum(),否则为max()
print(args.integers)
print(args.accumulate)
print(args.accumulate(args.integers))
# F:\oldboy\network_programming\ftp_task\tests
# λ python test_argparse.py 1 2 3
# [1, 2, 3]
# <built-in function max>
# 3
#
# F:\oldboy\network_programming\ftp_task\tests
# λ python test_argparse.py --sum 1 2 3 4
# [1, 2, 3, 4]
# <built-in function sum>
# 10
# ArgumentParser通过parse_args()方法解析参数。
# 这将检查命令行,将每个参数转换为适当的类型,然后调用适当的操作。
# 在大多数情况下,这意味着一个简单的名称空间对象将从命令行解析属性中建立起来:
# parser.parse_args(['--sum', '7', '-1', '42']) # 列表传递参数
# Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
| true |
d41e6662e05bbb1cf8bbe1a99d1324eb2ff460c0
|
Python
|
SumanMarahatha7/python
|
/python solve/004_question.py
|
UTF-8
| 290 | 4.0625 | 4 |
[] |
no_license
|
"""values inside a tuple cannot be changed i.e. they are constant
values inside a array can be changed i.e. they are variables
tuples are denoted are small bracket()
array are denoted by big brackets[] """
a=[1,2,3,4,5,6,7,8,9]
print(a[-4:]) #it gives last four values as output
| true |
e1eaf657e709a0ddb6a29b126fdf9dd717173935
|
Python
|
vmalj/workfiles
|
/python/envlab.py
|
UTF-8
| 334 | 3.28125 | 3 |
[] |
no_license
|
#! /usr/bin/env python3.6
import os
stage = os.getenv("STAGE", default="test").upper()
output = f"You are in {stage}"
if stage.startswith("PROD"):
output = "Hey" + output
print(output)
#Note: Here I learnt how to use the OS module, and use its getenv function. I ran through some errors due to syntax but now understood it.
| true |
21d5db0e1bdf33a3ce3a58e80f13edce2398bd15
|
Python
|
cs480-projects/cs480-projects.github.io
|
/teams-fall2022/Code9/A6-Dylan/CalorieRequirement.py
|
UTF-8
| 1,110 | 3.25 | 3 |
[] |
no_license
|
import UserProfile as User
class UsersCalorieRequirement:
users = []
userBMR = []
def addUser(user):
users.append(user)
if(user.getSex()):
BMR = 66 + ((13.7*0.453592) * user.getWeight()) + (5 * ((user.getHeight[0] * 30.48) + (user.getHeight[1] * 2.54))) - (6.8 * user.getAge())
else:
BMR = 655 + ((9.6*0.453592) * user.getWeight()) + (1.8 * ((user.getHeight[0] * 30.48) + (user.getHeight[1] * 2.54))) - (4.7 * user.getAge())
userBMR.append(BMR)
return 1
def getUserBMR(self, user):
for i in range(len(users)):
if(users[i].getAccountNum() == user.getAccountNum()):
return userBMR[i]
return "User does not exist in the database"
if __name__ == '__main__':
usersRegistry = UsersCalorieRequirement()
user1 = User(Bob, 123, '000001')
user1.setAge(69)
user1.setHeight([5,9])
user1.setSex(True)
user1.setWeight(189)
print("Adding Bob into registry: ", usersRegistry.addUser(user1))
print("Retrieving Bob's BMR: ", usersRegistry.getUserBMR(user1))
| true |
edc047a9fa9316f55d29a4db34c0f9611a4bd9fc
|
Python
|
RickGroeneweg/UvAAxelrod
|
/country.py
|
UTF-8
| 1,859 | 2.953125 | 3 |
[] |
no_license
|
from .enums import random_action
import numpy as np
class Country:
"""
stores country hypterparamters, but also state from the simulation
"""
def __init__(self, name, m, location, e, i, sqrt_area):
# Variables that stay the same during simulations
self.name = name
self.m = m
self.e = e
self.i = i
self.location = location
self.sqrt_area = sqrt_area
self.self_reward = None
# State variables, not yet initialized since that will be done in the tournament
self.fitness = None
self.fitness_history = []
# private attributes, they should only be changed with `change_strategy`
self._strategy = None
self._evolution = []
def __str__(self):
return f'<{self.name}>'
def __repr__(self):
return f'<{self.name}>'
def change_strategy(self, round_num, strategy):
"""
parameters:
- round_num: int, round number when the change occured
- strategy: new strategy that the country adopts
side effects:
- set self._strategy to the new strategy
- appends self.evolution
"""
self._strategy = strategy
self._evolution.append((round_num, strategy))
def select_action(self, selfmoves, othermoves, noise_threshold):
r = np.random.uniform()
if r < noise_threshold:
# there is a chance of {noise_threshold} that this action will
# be randomly selected
return random_action()
else:
return self._strategy(selfmoves, othermoves)
def get_current_strategy(self):
"""
returns:
- current strategy
"""
return self._strategy
| true |
90ab946746e9cfa445f7fa0e2dd81f66a2b39e14
|
Python
|
CaioPenhalver/naive-bayes-detect-spam
|
/naive_bayes.py
|
UTF-8
| 1,539 | 3.109375 | 3 |
[] |
no_license
|
import pandas as pd
df = pd.read_table('SMSSpamCollection',
sep='\t',
header=None,
names=['label', 'sms_message'])
df['label'] = df.label.map({'ham':0, 'spam':1})
print df.shape
print df.head()
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(df['sms_message'], df['label'], random_state=1)
print('number of rows in the total set: {}'.format(df.shape[0]))
print('number of rows in the traning set: {}'.format(x_train.shape[0]))
print('number of rows in the test set: {}'.format(x_test.shape[0]))
from sklearn.feature_extraction.text import CountVectorizer
# Instantiate the CountVectorizer method
count_vector = CountVectorizer()
# Fit the training data and then return the matrix
training_data = count_vector.fit_transform(x_train)
# Transform testing data and return the matrix. Note we are not fitting the testing data into the CountVectorizer()
testing_data = count_vector.transform(x_test)
from sklearn.naive_bayes import MultinomialNB
naive_bayes = MultinomialNB()
naive_bayes.fit(training_data, y_train)
predictions = naive_bayes.predict(testing_data)
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy score: ', format(accuracy_score(y_test, predictions)))
print('Precision score: ', format(precision_score(y_test, predictions)))
print('Recall score: ', format(recall_score(y_test, predictions)))
print('F1 score: ', format(f1_score(y_test, predictions)))
| true |
1057499e42d6433e466ecf917f775919a2275935
|
Python
|
wanxinxie/pdf_rename
|
/pdf_rename.py
|
UTF-8
| 1,492 | 2.859375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from pdfrw import PdfReader
import os
import glob
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
Filename = os.path.join(THIS_FOLDER, 'target.zip')
renamedfilename =os.path.join(THIS_FOLDER, 'renamed.zip')
"""**Step 2:**
Determine new names
Change Filename to the zip file name you are working with
"""
# Change Filename below to the zip file name you are working with
# Determine new name
from os import walk
mypath = THIS_FOLDER + '/target'
f = []
d = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
f.remove('.DS_Store')
for file in f:
d.append(THIS_FOLDER + '/target/'+file)
print(f)
print(d)
newnames = []
for i in range(len(f)):
reader = PdfReader(d[i])
title=''
author=''
date=''
if str(type(reader.Info.Title)) != "<class 'NoneType'>":
title= reader.Info.Title[1:len(reader.Info.Title)-1]
print(title)
if str(type(reader.Info.Author)) != "<class 'NoneType'>":
author = reader.Info.Author[1:len(reader.Info.Author)-1]
words = author. split()
lastname = words[-1]
print(lastname)
if str(type(reader.Info.CreationDate)) != "<class 'NoneType'>":
date = reader.Info.CreationDate[3:7]
print(date)
new_name = title +'|' + author + '|' + date +'.pdf'
print(new_name)
newnames.append(THIS_FOLDER + '/target/'+new_name)
count=0
"""Rename files"""
print(newnames)
for i in range(len(f)):
os.rename(d[i],newnames[i])
"""Create new zip file with renamed pdf"""
| true |
6a577a89112634795f1202a3636e552a5d2a3499
|
Python
|
yeomkyeorae/algorithm
|
/BJ/Comb Perm/15686_chicken_delivery.py
|
UTF-8
| 1,549 | 3.21875 | 3 |
[] |
no_license
|
def comb(k, start):
global store_comb
if k == R:
store_comb.append(choose.copy())
return
for i in range(start, N):
choose.append(chicken[i])
comb(k + 1, i + 1)
choose.pop()
n, m = map(int, input().split())
house = []
chicken = []
for i in range(n):
tmp = list(map(int, input().split()))
for j, value in enumerate(tmp):
if value == 2:
chicken.append((i, j))
elif value == 1:
house.append((i, j))
all_dist = []
for c in chicken:
for h in house:
all_dist.append([(c[0], c[1]), (h[0], h[1]), abs(c[0] - h[0]) + abs(c[1] - h[1])])
N = len(chicken)
R = m
choose = []
store_comb = []
if R == N:
store_comb = [chicken]
else:
comb(0, 0)
MIN_VALUE = 100000
for one_comb in store_comb: # 고를 수 있는 치킨가게 조합 하나씩
house_dict = {}
for one_dist in all_dist: # 집과 치킨가게 사이의 모든 조합 하나씩
if one_dist[0] in one_comb: # 거리를 구한 치킨가게가 조합 중에 있으면
if not one_dist[1] in house_dict.keys(): # 아직 dict에 해당 집이 없으면
house_dict[one_dist[1]] = one_dist[2]
else: # 더 가까운 가게로 갱신
if house_dict[one_dist[1]] > one_dist[2]:
house_dict[one_dist[1]] = one_dist[2]
tmp = 0
for value in house_dict.values():
tmp += value
if tmp < MIN_VALUE:
MIN_VALUE = tmp
print(MIN_VALUE)
| true |
c04f4221c378152d3c0413d9b631e700685f989e
|
Python
|
ali3nnn/MasterArtificialIntelligence
|
/PracticalMachineLearning/Proiect/CNN/stuff/predictor.py
|
UTF-8
| 907 | 2.59375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import matplotlib.pyplot as plt
from keras.models import Sequential, load_model
from keras.layers import Dense, Conv2D, Flatten
from keras import optimizers
import cv2 #resize image
import numpy as np
from random import shuffle
from tqdm import tqdm #progress bar
import sys
model = load_model('./dogness25000pic4ep.h5')
img = cv2.resize(cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE),(50, 50))
img = np.array(img)
img2 = img.reshape(-1, 50, 50, 1)
magic = model.predict(img2)
# print(str(round(magic[0][0]*100,1))+"% a cat and "+str(round(magic[0][1]*100,1))+"% dog")
plt.imshow(img, interpolation='nearest', cmap="gray")
plt.title(str(round(magic[0][0]*100,1))+"% a cat and "+str(round(magic[0][1]*100,1))+"% dog")
plt.show()
| true |
914c89ed251aca2ba1b10ae416c7737229fee0a7
|
Python
|
lalitsshejao/Python_PractiseCode
|
/scripts/numpy_SinCurve.py
|
UTF-8
| 178 | 2.890625 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
# from matplotlib import pyplot
x=np.arange(0, 3*np.pi, 0.1)
# y=np.sin(x)
# y=np.cos(x)
y=np.tan(x)
plt.plot(x,y)
plt.show()
| true |
4f951cc854298e33f886c2d62ee40936cae7f8c8
|
Python
|
Ritika10/Bash-Linux
|
/Python/Programs/prettyprinting.py
|
UTF-8
| 3,284 | 4.25 | 4 |
[] |
no_license
|
# given a dictionary of the form {string1: float1, string2: float2 ... }
# print contents of the dictionary one per line, with the string
# right aligned in 20 characters, followed by a colon and a space, followed by
# the floating point number printed with two decimal precision
def precise_printing(dictionary):
for key in dictionary:
print('%20s:%0.2f' % (key, dictionary[key]))
pass
# given a list of tuples of two integers each, print
# num1 multiplied by num2 is num1*num2
# with the appropriate integers in place of a, b, and a*b
def multiply_printing(tuples):
pass
# given a string, return a string with every number in the input
# 1) converted to float
# 2) divided by divisor
# 3) printed with four decimal precision
# for simplicity, you can assume there is no punctuation in the sentence
def divide_numbers(sentence, divisor):
pass
# given two positive integers, x and y,
# generate a times table with x as the column, y as the row
# and x*y as the value
# compute the narrowest field width you can use to display the largest number
# and display all numbers in that field width, right aligned
# e.g. a times_table(5,4) looks like this:
# 1 2 3 4 5
# 1 1 2 3 4 5
# 2 2 4 6 8 10
# 3 3 6 9 12 15
# 4 4 8 12 16 20
def times_table(x,y):
pass
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
def main():
test_d = {'height': 6.54, 'weight': 124.6547, 'wingspan': 0.3645}
print ('your precise_printing')
precise_printing(test_d)
print ("\n")
print ('expected precise_printing')
print (' wingspan: 0.36')
print (' weight: 124.65')
print (' height: 6.54')
print("\n")
print ('your multiply printing')
multiply_printing([(1,1), (2,4), (3,3), (4,6)])
print("\n")
print ('expected multiply printing')
print ('1 multiplied by 1 is 1')
print ('2 multiplied by 4 is 8')
print ('3 multiplied by 3 is 9')
print ('4 multiplied by 6 is 24')
print("\n")
print ('divide_numbers')
test(divide_numbers('the 2000 year old statue was worth 4 million dollars', 3), 'the 666.6667 year old statue was worth 1.3333 million dollars')
test(divide_numbers('58 engineers worked for 3 months on the project', 4), '14.5000 engineers worked for 0.7500 months on the project')
print("\n")
print ('your times_table')
times_table(10,12)
print("\n")
print ('expected times_table')
print (' 1 2 3 4 5 6 7 8 9 10')
print (' 1 1 2 3 4 5 6 7 8 9 10')
print (' 2 2 4 6 8 10 12 14 16 18 20')
print (' 3 3 6 9 12 15 18 21 24 27 30')
print (' 4 4 8 12 16 20 24 28 32 36 40')
print (' 5 5 10 15 20 25 30 35 40 45 50')
print (' 6 6 12 18 24 30 36 42 48 54 60')
print (' 7 7 14 21 28 35 42 49 56 63 70')
print (' 8 8 16 24 32 40 48 56 64 72 80')
print (' 9 9 18 27 36 45 54 63 72 81 90')
print (' 10 10 20 30 40 50 60 70 80 90 100')
print (' 11 11 22 33 44 55 66 77 88 99 110')
print (' 12 12 24 36 48 60 72 84 96 108 120')
if __name__ == '__main__':
main()
| true |
79056fa1ab1481c2c4566ca7b20d58013914b7b0
|
Python
|
lukereed/PythonTraining
|
/Class/Class_05/ex40a_IntroOOP.py
|
UTF-8
| 1,042 | 4.6875 | 5 |
[] |
no_license
|
#!/usr/bin/python
# Luke Reed
# ex40a.py
# 02/10/2016
# an introduction to OOP
mystuff = {'apple':"I AM APPLES!"}
print mystuff['apple']
# we can also reference mystuff.py:
import mystuff
mystuff.apple()
# we can also access variables in mystuff.py
print mystuff.tangerine
'''
# this is similar to using a dictionary
mystuff['apple'] # get apple from dictionary
mystuff.apple() # get apple from the module
mystuff.tangerine # same thing, it's just a variable this time
'''
# next we can create a class just like the mystuff module
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
# now we instantiate (create) a class by calling the class like it's a function
thing = MyStuff()
thing.apple()
print thing.tangerine
'''
# we now have three ways to get things from things
# dictionary style
mystuff['apple']
# module style
mystuff.apples()
print mystuff.tangerine
# class styles
thing = MyStuff()
thing.apples()
print thing.tangerine
'''
| true |
e4d2bd9697bdc8f23d61b8371fe99e18c765943c
|
Python
|
AnirudhaRamesh/Mario-
|
/main.py
|
UTF-8
| 3,767 | 2.6875 | 3 |
[] |
no_license
|
""" Main game loop program """
import os, sys, time
from board import Board, Boss_Board
from bricks import Brick, Ground_Brick, Special_Brick, UnderGround_Brick, EmptyCoin
from characters import *
from input import *
from collision import *
from config import *
import random
from colorama import Fore
sun = Sun(sun_x,sun_y)
hills = Hills(hill_x,hill_y)
gBrick = Ground_Brick(26,20)
ugBrick = UnderGround_Brick(26,20)
aBrick = Air_Brick(10,10)
bigMap = Board(board_length,board_width,start_lives, gBrick)
frameCount = 0
for i in Map :
frameCount = frameCount + 1
tempCount = 1
for i in Map:
if tempCount == frameCount - 2:
break
tempCount = tempCount + 1
tempFrame = Board(board_length,board_width,start_lives, gBrick)
for j in i :
tempFrame.UpdatePartOfMatrix(j)
bigMap.ExtendMap(tempFrame)
tempFrame = Boss_Board(board_length,board_width,start_lives, ugBrick)
for i in range(frameCount-3, frameCount) :
for j in Map[i] :
tempFrame.UpdatePartOfMatrix(j)
bigMap.ExtendMap(tempFrame)
screenBoard = Board(board_length,board_width,start_lives, gBrick)
mario = Mario(mario_init_x,mario_init_y)
sGround = ""
framePointer = 0
BrickMat = gBrick.return_matrix()
flagToCheckIfLineHasASomething = False
GameRuns = True
getch = Get()
jump_timer = 10 # number of frames for jump to last
os.system('aplay -q main_theme.wav&')
os.system('sleep 2 &aplay -q Its_a_me_mario.wav&')
os.system('sleep 7 && aplay -q Mamma_mia.wav&')
while GameRuns!=False:
input = input_to(getch)
os.system('clear')
""" Mario movement """
screenBoard.ClearingPartOfMatrix(mario)
moveType = mario.move(input, jump_timer, screenBoard)
if jump_timer != 10 or (input == 'w' and jump_timer == 10) :
os.system('aplay -q jump.wav&')
jump_timer = jump_timer - 1
mario.move('w',jump_timer, screenBoard)
if jump_timer == 0 :
jump_timer = 10
framePointer = screenBoard.UpdateFrame(mario, bigMap)
screenBoard.UpdatePartOfMatrix(mario)
if moveType == 2 :
""" Move screen, and not mario """
framePointer = screenBoard.UpdateFrame(mario, bigMap)
""" Mario movement ends """
""" Enemies Updation """
DistFromStart = mario.return_distance()
for i in enemies :
empty = EmptyEnemy(i)
if empty.return_matrix() == i.return_matrix() :
enemies.remove(i)
continue
if i.return_initial_y() >= framePointer and i.return_initial_y() < framePointer + 80 :
screenBoard.UpdatingEnemiesOnFrame(empty, framePointer)
i.move(screenBoard, mario)
screenBoard.UpdatingEnemiesOnFrame(i, framePointer)
""" Enemies done """
""" Coins """
for i in coins :
empty = EmptyCoin(i)
if empty.return_matrix() == i.return_matrix() :
coins.remove(i)
continue
if i.return_ypos() >= framePointer and i.return_ypos() < framePointer + 80 :
screenBoard.UpdatingEnemiesOnFrame(empty, framePointer)
i.test(screenBoard, mario)
screenBoard.UpdatingEnemiesOnFrame(i, framePointer)
if input == 'q':
os.system('clear')
sys.exit()
screenBoard.UpdatePartOfMatrixForBakcgroundElements(sun)
if framePointer <= 700 :
screenBoard.UpdatePartOfMatrixForBakcgroundElements(hills)
screenBoard.UpdatePartOfMatrix(mario)
screenBoard.UpdateMatrix(screenBoard)
print(screenBoard.ReturnStringBoard()+'\n'+"Distance covered :"+str(mario.return_distance()) + '\n' + "Score :" + str(mario.ret_score()+mario.return_distance()))
if mario.return_distance() >= 960 :
print("Game over, you win!")
break
time.sleep(0.025)
| true |
9e6127f1868f963af896ae2c4ea935520d67dc38
|
Python
|
fnaos/StochOPy
|
/stochopy/tests/test_evolutionary_algorithm.py
|
UTF-8
| 4,782 | 2.859375 | 3 |
[
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
Author: Keurfon Luu <keurfon.luu@mines-paristech.fr>
License: MIT
"""
import numpy as np
import unittest
if __name__ == "__main__":
import sys
sys.path.append("../")
from evolutionary_algorithm import Evolutionary
else:
from stochopy import Evolutionary
class EvolutionaryTest(unittest.TestCase):
"""
Evolutionary algorithms unit tests.
"""
def setUp(self):
"""
Initialize evolutionary algorithm tests.
"""
func = lambda x: 100*np.sum((x[1:]-x[:-1]**2)**2)+np.sum((1-x[:-1])**2)
n_dim = 2
lower = np.full(n_dim, -5.12)
upper = np.full(n_dim, 5.12)
popsize = int(4 + np.floor(3.*np.log(n_dim)))
max_iter = 50
random_state = 42
self.optimizer = Evolutionary(func, lower = lower, upper = upper,
popsize = popsize, max_iter = max_iter,
snap = True, random_state = random_state)
self.n_dim = n_dim
self.popsize = popsize
def tearDown(self):
"""
Cleaning after each test.
"""
del self.optimizer
def test_pso(self):
"""
Particle Swarm Optimization test.
"""
w = 0.42
c1 = 1.409
c2 = 1.991
xopt, gfit = self.optimizer.optimize(solver = "pso", w = w, c1 = c1, c2 = c2)
xopt_true = np.array([ 0.70242052, 0.49260076 ])
for i, val in enumerate(xopt):
self.assertAlmostEqual(val, xopt_true[i])
def test_pso_param_zero(self):
"""
Checking PSO behaviour when all the parameters are set to 0.
"""
xstart = np.random.rand(self.popsize, self.n_dim)
w = 0.
c1 = 0.
c2 = 0.
self.optimizer.optimize(solver = "pso", w = w, c1 = c1, c2 = c2,
xstart = xstart)
for i, val in enumerate(self.optimizer.models[:,:,-1].ravel()):
self.assertAlmostEqual(val, xstart.ravel()[i])
def test_cpso(self):
"""
Competitive Particle Swarm Optimization test.
"""
w = 0.42
c1 = 1.409
c2 = 1.991
gamma = 0.8
xopt, gfit = self.optimizer.optimize(solver = "cpso", w = w, c1 = c1,
c2 = c2, gamma = gamma)
xopt_true = np.array([ 0.55554141, 0.30918171 ])
for i, val in enumerate(xopt):
self.assertAlmostEqual(val, xopt_true[i])
def test_cpso_param_zero(self):
"""
Checking CPSO behaviour when all the parameters are set to 0.
"""
xstart = np.random.rand(self.popsize, self.n_dim)
w = 0.
c1 = 0.
c2 = 0.
gamma = 0.
self.optimizer.optimize(solver = "pso", w = w, c1 = c1, c2 = c2,
xstart = xstart)
pso_models = self.optimizer.models[:,:,-1]
self.optimizer.optimize(solver = "cpso", w = w, c1 = c1, c2 = c2,
xstart = xstart, gamma = gamma)
cpso_models = self.optimizer.models[:,:,-1]
for i, val in enumerate(cpso_models.ravel()):
self.assertAlmostEqual(val, pso_models.ravel()[i])
def test_de(self):
"""
Differential Evolution test.
"""
CR = 0.42
F = 1.491
xopt, gfit = self.optimizer.optimize(solver = "de", CR = CR, F = F)
xopt_true = np.array([ 1.35183858, 1.81825907 ])
for i, val in enumerate(xopt):
self.assertAlmostEqual(val, xopt_true[i])
def test_cmaes(self):
"""
Covariance Matrix Adaptation - Evolution Strategy test.
"""
sigma = 0.1
mu_perc = 0.2
xstart = np.array([ -3., -3. ])
xopt, gfit = self.optimizer.optimize(solver = "cmaes", sigma = sigma,
mu_perc = mu_perc, xstart = xstart)
xopt_true = np.array([ 0.80575841, 0.649243 ])
for i, val in enumerate(xopt):
self.assertAlmostEqual(val, xopt_true[i])
def test_vdcma(self):
"""
VD-CMA test.
"""
sigma = 0.1
mu_perc = 0.2
xstart = np.array([ -3., -3. ])
xopt, gfit = self.optimizer.optimize(solver = "vdcma", sigma = sigma,
mu_perc = mu_perc, xstart = xstart)
xopt_true = np.array([ 1.38032658, 1.89976049 ])
for i, val in enumerate(xopt):
self.assertAlmostEqual(val, xopt_true[i])
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(EvolutionaryTest)
unittest.TextTestRunner().run(suite)
| true |
9218a63193227f62db3ee3bfa9c8926debe77b40
|
Python
|
ChenghaoZHU/LeetCode
|
/41.缺失的第一个正数.py
|
UTF-8
| 1,082 | 3.1875 | 3 |
[] |
no_license
|
#
# @lc app=leetcode.cn id=41 lang=python
#
# [41] 缺失的第一个正数
#
# @lc code=start
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 最小缺失正整数肯定小于等于size + 1
found = False
size = len(nums)
for i, n in enumerate(nums):
if n == 1:
found = True
elif n <= 0 or n > size:
nums[i] = 1
if not found:
return 1
# 利用数组做hash效果
# index是key,value是负数表示出现过
# size用0表示
for i, n in enumerate(nums):
n = abs(n)
if n == size and nums[0] > 0:
nums[0] = -nums[0]
elif n < size and nums[n] > 0:
nums[n] = -nums[n]
# element 0 for n, which equals to size
for i, n in enumerate(nums[1:], 1):
if n > 0:
return i
return size if nums[0] > 0 else size + 1
# @lc code=end
| true |
1c93c12658284d2334a21a4ec76412b70b178699
|
Python
|
sandyjmacdonald/Leeds_footfall
|
/leeds_footfall.py
|
UTF-8
| 1,155 | 3.8125 | 4 |
[] |
no_license
|
#!/usr/bin/env python
import pandas as pd
## Reads in our cleaned up and merged footfall data.
all_data = pd.read_csv('cleaned_data.csv')
## This function takes a dataframe and two years and then calculates the
## percentage difference in footfall between those two years.
def year_delta(df, year1, year2):
gp = df.groupby(['BRCYear', 'LocationName'])['InCount'].mean().reset_index()
df_yr1 = gp.copy()[gp['BRCYear'] == year1]
df_yr1.rename(columns={'InCount': str(year1) + '_Mean'}, inplace=True)
del df_yr1['BRCYear']
df_yr2 = gp.copy()[gp['BRCYear'] == year2]
df_yr2.rename(columns={'InCount': str(year2) + '_Mean'}, inplace=True)
del df_yr2['BRCYear']
df_delta = pd.merge(df_yr1, df_yr2, on='LocationName')
df_delta[str(year2) + '_' + str(year1) + '_Delta'] = ((df_delta[str(year2) + '_Mean'] - df_delta[str(year1) + '_Mean']) / df_delta[str(year1) + '_Mean']) * 100
return df_delta
## An example of how the year_delta function works.
print ''
print 'Annual footfall percentage change, 2013 vs. 2012'
print ''
delta_2013_2012 = year_delta(all_data, 2012, 2013)
print delta_2013_2012.sort(columns='2013_2012_Delta', ascending=False)
| true |
5fc35ba7fbefc73c2951eb31b6f50eb96c7345ef
|
Python
|
Vichoko/pytorch-wavenet
|
/audio_data.py
|
UTF-8
| 5,935 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import os
import os.path
import math
import threading
import torch
import torch.utils.data
import numpy as np
import librosa as lr
import bisect
class WavenetDataset(torch.utils.data.Dataset):
def __init__(self,
dataset_file,
item_length,
target_length,
file_location=None,
classes=256,
sampling_rate=16000,
mono=True,
normalize=False,
dtype=np.uint8,
train=True,
test_stride=100):
# |----receptive_field----|
# |--output_length--|
# example: | | | | | | | | | | | | | | | | | | | | |
# target: | | | | | | | | | |
self.dataset_file = dataset_file
self._item_length = item_length
self._test_stride = test_stride
self.target_length = target_length
self.classes = classes
if not os.path.isfile(dataset_file):
assert file_location is not None, "no location for dataset files specified"
self.mono = mono
self.normalize = normalize
self.sampling_rate = sampling_rate
self.dtype = dtype
self.create_dataset(file_location, dataset_file)
else:
# Unknown parameters of the stored dataset
# TODO Can these parameters be stored, too?
self.mono = None
self.normalize = None
self.sampling_rate = None
self.dtype = None
self.data = np.load(self.dataset_file, mmap_mode='r')
self.start_samples = [0]
self._length = 0
self.calculate_length()
self.train = train
print("one hot input")
# assign every *test_stride*th item to the test set
def create_dataset(self, location, out_file):
print("create dataset from audio files at", location)
self.dataset_file = out_file
files = list_all_audio_files(location)
processed_files = []
for i, file in enumerate(files):
print(" processed " + str(i) + " of " + str(len(files)) + " files")
file_data, _ = lr.load(path=file,
sr=self.sampling_rate,
mono=self.mono)
if self.normalize:
file_data = lr.util.normalize(file_data)
quantized_data = quantize_data(file_data, self.classes).astype(self.dtype)
processed_files.append(quantized_data)
np.savez(self.dataset_file, *processed_files)
def calculate_length(self):
start_samples = [0]
for i in range(len(self.data.keys())):
start_samples.append(start_samples[-1] + len(self.data['arr_' + str(i)]))
available_length = start_samples[-1] - (self._item_length - (self.target_length - 1)) - 1
self._length = math.floor(available_length / self.target_length)
self.start_samples = start_samples
def set_item_length(self, l):
self._item_length = l
self.calculate_length()
def __getitem__(self, idx):
if self._test_stride < 2:
sample_index = idx * self.target_length
elif self.train:
sample_index = idx * self.target_length + math.floor(idx / (self._test_stride-1))
else:
sample_index = self._test_stride * (idx+1) - 1
file_index = bisect.bisect_left(self.start_samples, sample_index) - 1
if file_index < 0:
file_index = 0
if file_index + 1 >= len(self.start_samples):
print("error: sample index " + str(sample_index) + " is to high. Results in file_index " + str(file_index))
position_in_file = sample_index - self.start_samples[file_index]
end_position_in_next_file = sample_index + self._item_length + 1 - self.start_samples[file_index + 1]
if end_position_in_next_file < 0:
file_name = 'arr_' + str(file_index)
this_file = np.load(self.dataset_file, mmap_mode='r')[file_name]
sample = this_file[position_in_file:position_in_file + self._item_length + 1]
else:
# load from two files
file1 = np.load(self.dataset_file, mmap_mode='r')['arr_' + str(file_index)]
file2 = np.load(self.dataset_file, mmap_mode='r')['arr_' + str(file_index + 1)]
sample1 = file1[position_in_file:]
sample2 = file2[:end_position_in_next_file]
sample = np.concatenate((sample1, sample2))
example = torch.from_numpy(sample).type(torch.LongTensor)
one_hot = torch.FloatTensor(self.classes, self._item_length).zero_()
one_hot.scatter_(0, example[:self._item_length].unsqueeze(0), 1.)
target = example[-self.target_length:].unsqueeze(0)
return one_hot, target
def __len__(self):
test_length = math.floor(self._length / self._test_stride)
if self.train:
return self._length - test_length
else:
return test_length
def quantize_data(data, classes):
mu_x = mu_law_encoding(data, classes)
bins = np.linspace(-1, 1, classes)
quantized = np.digitize(mu_x, bins) - 1
return quantized
def list_all_audio_files(location):
audio_files = []
for dirpath, dirnames, filenames in os.walk(location):
for filename in [f for f in filenames if f.endswith((".mp3", ".wav", ".aif", "aiff"))]:
audio_files.append(os.path.join(dirpath, filename))
if len(audio_files) == 0:
print("found no audio files in " + location)
return audio_files
def mu_law_encoding(data, mu):
mu_x = np.sign(data) * np.log(1 + mu * np.abs(data)) / np.log(mu + 1)
return mu_x
def mu_law_expansion(data, mu):
s = np.sign(data) * (np.exp(np.abs(data) * np.log(mu + 1)) - 1) / mu
return s
| true |
2dee0eb3946eabf9c42af9ccaaf223153dbeddbc
|
Python
|
Mud-Phud/my-python-scripts
|
/Project Euler/PE-002.py
|
UTF-8
| 575 | 3.9375 | 4 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler 2
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values
do not exceed four million, find the sum of the even-valued terms.
"""
a_2 = 1
a_1 = 1
a_3 = a_2 + a_1
sum = 0
while a_3 < 4000000:
# print(a_3,sum)
if a_3 % 2 == 0: sum = sum + a_3
a_2 = a_1
a_1 = a_3
a_3 = a_1 + a_2
print(sum)
| true |
70fcaa31ac0441cbc9d29957e933234a54eb4714
|
Python
|
Matico40/pdsnd_github
|
/bikeshare.py
|
UTF-8
| 13,295 | 3.875 | 4 |
[] |
no_license
|
import pandas as pd
import numpy as np
import time
# Those are my imports
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hellow! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city_valid = False
while city_valid == False:
city_valid = True
city = input('\nWhere would you like to see data for: Chicago, New York City, or Washington?\n').lower()
if city.lower() == 'chicago':
print('\nLet\'s see data for Chicago.')
elif city.lower() == 'washington':
print('\nLet\'s see data for Washington.')
elif city.lower() == 'new york city':
print('\nLet\'s see data for New York City.')
else:
print('\nYou provided an invalid input. Please try again\n')
city_valid = False
# TO DO: get user input for month (all, january, february, ... , june)
time_valid = False
while time_valid == False:
time_valid = True
time_filter = input("\nWhat would you like to filter data for: Month, Day, or None?\n")
if time_filter.lower() == 'month':
month = input("\nPlease select a month: January, February, March, April, May, or June.\n").lower()
day = "all"
while (month=='january' or month=='february' or month=='march' or month=='april' or month=='may' or month=='june') == False:
print("\nInvalid month. Please try again.\n")
month = input("\nPlease select a month: January, February, March, April, May, or June.\n").lower()
elif time_filter.lower() == 'day':
day = input("\nPlease select a day: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.\n").lower()
month = "all"
while (day=='monday' or day=='tuesday' or day=='wednesday' or day=='thursday' or day=='friday' or day=='saturday' or day=='sunday') == False:
print('\nInvalid day. Please try again\n')
day = input("\nPlease select a day: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.\n").lower()
elif (time_filter.lower() == 'none'):
month = 'all'
day = 'all'
print("\nData will not be filtered.\n")
else:
print("\nYou provided an invalid input. Please try again\n")
time_valid = False
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
return df
def time_stats(df, month, day):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day'] = df['Start Time'].dt.weekday
df['hour'] = df['Start Time'].dt.hour
months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
month_index = months.index(month) + 1
month_data = df[df['month'] == month_index]
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
day_index = days.index(day)#+1
day_data = df[df['day'] == day_index]
if month != 'all':
print('Filtering by month, {}.'.format(month.title()))
popular_day = month_data['day'].mode()[0]
print('\nMost popular day of the week:\n', popular_day)
popular_hour = month_data['hour'].mode()[0]
print('\nMost popular start hour:\n', popular_hour)
if day != 'all':
print('Filtering by day of the week, {}.'.format(day.title()))
popular_day = day_data['hour'].mode()[0]
print('\nMost popular start hour:', popular_day)
if month == 'all' and day == 'all':
print('Applying no filters')
popular_month = df['month'].mode()[0]
print('\nMost popular month:', popular_month)
popular_day = df['day'].mode()[0]
print('\nMost popular day of the week:', popular_day)
# TO DO: display the most common month
# TO DO: display the most common day of week
# TO DO: display the most common start hour
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df,month, day):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
month_index = months.index(month) + 1
month_data = df[df['month'] == month_index]
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
day_index = days.index(day)#+1
day_data = df[df['day'] == day_index]
if month != 'all':
print('Filtering by month, {}.'.format(month.title()))
popular_start_station = month_data['Start Station'].mode()[0]
print('\nMost popular start station:\n', popular_start_station)
popular_end_station = month_data['End Station'].mode()[0]
print('\nMost popular end station:\n', popular_end_station)
popular_trip = (month_data['Start Station'] + 'to' + month_data['End Station']).mode()[0]
print('\nMost populart trip:\n', popular_trip)
if day != 'all':
print('Filtering by day of the week, {}.'.format(day.title()))
popular_start_station = day_data['Start Station'].mode()[0]
print('\nMost popular start station:\n', popular_start_station)
popular_end_station = day_data['End Station'].mode()[0]
print('\nMost popular end station:\n', popular_end_station)
popular_trip = (day_data['Start Station'] + 'to' + day_data['End Station']). mode()[0]
print('\nMost populart trip:\n', popular_trip)
if month == 'all' and day == 'all':
print('Applying no filters')
popular_start_station = df['Start Station'].mode()[0]
print('\nMost popular start station:\n', popular_start_station)
popular_end_station = df['End Station'].mode()[0]
print('\nMost popular end station:\n', popular_end_station)
popular_trip = (df['Start Station'] + 'to' + df['End Station']).mode()[0]
print('\nMost popular trip:\n', popular_trip)
# TO DO: display most commonly used start station
# TO DO: display most commonly used end station
# TO DO: display most frequent combination of start station and end station trip
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df, month, day):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
month_index = months.index(month) + 1
month_data = df[df['month'] == month_index]
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
day_index = days.index(day) #+ 1
day_data = df[df['day'] == day_index]
if month != 'all':
print('Filtering by month, {}.'.format(month.title()))
total_travel = month_data['Trip Duration'].count()
print('\nTotal trip duration:\n', total_travel)
mean_travel = month_data['Trip Duration'].mean()
print('\nThe mean travel time:\n', mean_travel)
if day != 'all':
print('Filtering by day of the week, {}.'.format(day.title()))
total_travel = day_data['Trip Duration'].count()
print('\nTotal trip duration:\n', total_travel)
mean_travel = day_data['Trip Duration'].mean()
print('\nThe mean travel time:\n', mean_travel)
if month == 'all' and day == 'all':
print('Applying no filters')
total_travel = df['Trip Duration'].count()
print('\nTotal trip duration:\n', total_travel)
mean_travel = df['Trip Duration'].mean()
print('\nThe mean travel time:\n', mean_travel)
# TO DO: display total travel time
# TO DO: display mean travel time
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df, month, city, day):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
month_index = months.index(month) + 1
month_data = df[df['month'] == month_index]
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
day_index = days.index(day) #+ 1
day_data = df[df['day'] == day_index]
if city == 'washington':
if month != 'all':
print('Filtering by month, {}.'.format(month.title()))
user_types = month_data['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
if day != 'all':
print('Filtering by day of the week, {}.'.format(day.title()))
user_types = day_data['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
if month == 'all' and day == 'all':
print('Applying no filters')
user_types = df['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
if city != 'washington':
if month != 'all':
print('Filtering by month, {}.'.format(month.title()))
user_types = month_data['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
genders = month_data['Gender'].value_counts()
print('\nGender counts:\n', genders)
min_birthyear = month_data['Birth Year'].min()
print('\nThe earliest birth year:\n', min_birthyear)
max_birthyear = month_data['Birth Year'].max()
print('\nThe most recent birth year:\n', max_birthyear)
common_birthyear = month_data['Birth Year'].mode()[0]
print('\nThe most common birth year:\n', common_birthyear)
if day != 'all':
print('Filtering by day of the week, {}.'.format(day.title()))
user_types = day_data['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
genders = day_data['Gender'].value_counts()
print('\nGender counts:\n', genders)
min_birthyear = day_data['Birth Year'].min()
print('\nThe earliest birth year:\n', min_birthyear)
max_birthyear = day_data['Birth Year'].max()
print('\nThe most recent birth year:\n', max_birthyear)
common_birthyear = day_data['Birth Year'].mode()[0]
print('\nThe most common birth year:\n', common_birthyear)
if month == 'all' and day == 'all':
print('Applying no filters')
user_types = df['User Type'].value_counts()
print('\nNumber of user types:\n', user_types)
genders = df['Gender'].value_counts()
print('\nGender counts:\n', genders)
min_birthyear = df['Birth Year'].min()
print('\nThe earliest birth year:\n', min_birthyear)
max_birthyear = df['Birth Year'].max()
print('\nThe most recent birth year:\n', max_birthyear)
common_birthyear = df['Birth Year'].mode()[0]
print('\nThe most common birth year:\n', common_birthyear)
# TO DO: Display counts of user types
# TO DO: Display counts of gender
# TO DO: Display earliest, most recent, and most common year of birth
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def get_raw(dtf):
raw_valid = False
raw_yn = input('Would you like to see raw data first?\n').lower()
n = 0
while raw_valid == False:
raw_valid = True
if raw_yn.lower() == 'yes':
print('\nLet\'s see the raw data.')
print(dtf[n:n+5])
raw_yn = input('Would you like to see more raw data?\n').lower()
raw_valid = False
n = n + 5
elif raw_yn.lower() == 'no':
return()
else:
raw_yn = input('\nYou provided an invalid input.\nPlease try again: ').lower()
raw_valid = False
def main():
while True:
city, month, day = get_filters()
# city = 'chicago'
# month = 'all'
# day = 'monday'
# day = 'tuesday'
# day = 'wednesday'
# day = 'thursday'
# day = 'friday'
# day = 'saturday'
# day = 'sunday'
df = load_data(city, month, day)
get_raw(df)
time_stats(df, month, day)
station_stats(df, month, day)
trip_duration_stats(df, month, day)
user_stats(df, month, city, day)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
| true |
413d38ba4f961b3dcc8b9c035895a023e81ca10c
|
Python
|
ramiabukhader/graphsearchalgorithms_geneticalgorithm_hillclimbing
|
/Utils/Node.py
|
UTF-8
| 664 | 2.96875 | 3 |
[] |
no_license
|
class Node:
def __init__(self, name, heuristic=0, is_goal=False):
self.name = name
self.children = {} # this will be a list of nodes with their corresponding distance
self.heuristic = heuristic # this will be used in greedy best first and A*
self.visited = False
self.depth = 0 # this will be used in Limited Depth First Search And Iterative Deepening DFS
self.parent = None # this will be used to find the path
self.costFromOrigin = 0 # will be used for uniform cost & A*
class Node2:
def __init__(self, name):
self.name = name
self.neighbours = set()
self.colour = 0
| true |