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 |
---|---|---|---|---|---|---|---|---|---|---|---|
f15db92bf048ac1c0becd6b118825be852b63774
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p03760/s958997741.py
|
UTF-8
| 117 | 2.765625 | 3 |
[] |
no_license
|
O=input()
E=input()
P = ""
for i in range(len(E)):
P += O[i]
P += E[i]
if len(O)-len(E)==1:
P += O[-1]
print(P)
| true |
612e503009acde2eaee4df4f0d1b28db14a71338
|
Python
|
rkdr055/BOJ
|
/2997.py
|
UTF-8
| 280 | 3.09375 | 3 |
[] |
no_license
|
a,b,c=map(int,input().split())
list1=[a,b,c]
list1=sorted(list1)
if list1[1]-list1[0] == list1[2]-list1[1]:
print(list1[2]+list1[2]-list1[1])
elif (list1[2]-list1[1])//(list1[1]-list1[0])==2:
print(list1[1]+list1[1]-list1[0])
else:
print(list1[1]-(list1[2]-list1[1]))
| true |
7f8d4793eefa9f0d8fd3499113ca788e249ce41a
|
Python
|
lyqscmy/iredis
|
/tests/unittests/test_utils.py
|
UTF-8
| 2,659 | 2.609375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
import re
import time
import pytest
from unittest.mock import patch
from iredis.utils import timer, _strip_quote_args, split_command_args
from iredis.commands_csv_loader import all_commands
from iredis.utils import command_syntax
from iredis.style import STYLE
from iredis.commands_csv_loader import commands_summary
from prompt_toolkit import print_formatted_text
def test_timer():
with patch("iredis.utils.logger") as mock_logger:
timer("foo")
time.sleep(0.1)
timer("bar")
mock_logger.debug.assert_called()
args, kwargs = mock_logger.debug.call_args
matched = re.match(r"\[timer (\d)\] (0\.\d+) -> bar", args[0])
assert matched.group(1) == str(3)
assert 0.1 <= float(matched.group(2)) <= 0.2
# --- test again ---
timer("foo")
time.sleep(0.2)
timer("bar")
mock_logger.debug.assert_called()
args, kwargs = mock_logger.debug.call_args
matched = re.match(r"\[timer (\d)\] (0\.\d+) -> bar", args[0])
assert matched.group(1) == str(5)
assert 0.2 <= float(matched.group(2)) <= 0.3
@pytest.mark.parametrize(
"test_input,expected",
[
("hello world", ["hello", "world"]),
("'hello world'", ["hello world"]),
('''hello"world"''', ["helloworld"]),
(r'''hello\"world"''', [r"hello\world"]),
(r'"\\"', [r"\\"]),
(r"\\", [r"\\"]),
(r"\abcd ef", [r"\abcd", "ef"]),
# quotes in quotes
(r""" 'hello"world' """, ['hello"world']),
(r""" "hello'world" """, ["hello'world"]),
(r""" 'hello\'world'""", ["hello'world"]),
(r""" "hello\"world" """, ['hello"world']),
(r"''", [""]), # set foo "" is a legal command
(r'""', [""]), # set foo "" is a legal command
(r"\\", ["\\\\"]), # blackslash are legal
("\\hello\\", ["\\hello\\"]), # blackslash are legal
],
)
def test_stipe_quote_escaple_in_quote(test_input, expected):
assert list(_strip_quote_args(test_input)) == expected
@pytest.mark.parametrize(
"command,expected",
[
("GET a", "GET"),
("cluster info", "cluster info"),
("getbit foo 17", "getbit"),
("command ", "command"),
(" command count ", "command count"),
(" command count ", "command count"), # command with multi space
],
)
def test_split_commands(command, expected):
assert split_command_args(command, all_commands)[0] == expected
def test_render_bottom_with_command_json():
for command, info in commands_summary.items():
print_formatted_text(command_syntax(command, info), style=STYLE)
| true |
322632c0c7c915cc150934a19cf7bc6502125190
|
Python
|
sachinchauhan10497/Hack_gseb
|
/filter.py
|
UTF-8
| 1,296 | 2.8125 | 3 |
[] |
no_license
|
import sys
from processes import make_url
import webbrowser
import configs
filters = []
for i in range(1,len(sys.argv)):
filters.append(sys.argv[i])
def process_file():
output = {}
f = open(configs.FILE_TO_SAVE_SEAT_NAME_PAIR)
for line in f:
values = line.split("-")
if len(values) > 1:
name = str(values[0]).strip()
seat = str(values[1]).strip()
output[name] = seat
f.close()
return output
def do_filter(input, token):
output = {}
for name,seat in input.items():
if token.upper() in name:
output[name] = seat
return output
if __name__ == "__main__":
output = process_file()
for token in filters:
output = do_filter(output, token)
print("\n\n-----------------------------------------\n\n")
print("Filter string - " + token + " - " + str(len(output)) + " Results")
print("\n\n-----------------------------------------\n\n")
for k in output.keys():
print(k + " - " + output[k])
print("\n\n------------------Final-----------------------\n\n")
url = ""
for k in output.keys():
url = make_url(output[k])
print(k + " - " + output[k] + " - " + url)
if len(output) == 1:
webbrowser.open(url)
| true |
36ee61b891bac431f323459bd7fa6c7c8cbb5576
|
Python
|
EnotionZ/FoodListing
|
/RestaurantStore.py
|
UTF-8
| 1,812 | 3.015625 | 3 |
[] |
no_license
|
"""
UserInfo.py -- Grabs user info from the database.
by Sean.
"""
from Config import Config
from pymongo import Connection
from datetime import datetime
import time
from base64 import b64encode
from hashlib import sha256
import logging
class RestaurantStore:
def __init__( self, config ):
self.config = Config( config )
self.address = self.config['mongo']['address']
self.port = self.config['mongo']['port']
self.database = "foodlisting"
self.logger = logging.getLogger( "FoodListing.DB.UserInfo" )
try:
self.database = self.config['mongo']['database']
except:
pass
self.collection = "restaurants"
self.con = Connection( self.address, self.port )
self.db = self.con[self.database]
self.collection = self.db[self.collection]
self.collection.ensure_index( "id", unique=True )
def addRestaurant( self, name, location ):
restaurant = {}
restaurant['name'] = name #Name of the place
restaurant['id'] = b64encode( sha256( name ).digest() )[:5].replace( "/", "1" )
restaurant['menu'] = [] #menu of food items
restaurant['loc'] = location #location
if self.collection.save( restaurant ) != None:
return restaurant['id']
else:
return None
def getByID( self, id ):
restaurant = self.collection.find_one( { "id": id } )
return restaurant
def addMenuItem( self, id, fid ):
return self.collection.update( { "id": id }, { "$addToSet": { "menu": fid } } )
def getMenu( self, id ):
ret = self.collection.find_one( { "id": id } )
return ret['menu']
if __name__ == "__main__":
u = RestaurantStore( "config.json" )
a = u.addRestaurant( "Out Back Steak House", ( 73.1, 73.1 ) )
a = u.getByID( a )
print a
| true |
b08ec101695ebebe2a0d205ec85ab68a49360894
|
Python
|
hwheelen/state_senate_results
|
/process_2016.py
|
UTF-8
| 956 | 2.921875 | 3 |
[] |
no_license
|
import pandas as pd
import geopandas as gpd
import numpy as np
#input start path
start_path = ''
#load in raw election data
raw_elec = gpd.read_file(start_path + 'GitHub/MEDSL/stateoffices2016.csv')
#select states and print offices for this state in 2016
states = ['Florida']
for st in states:
st_df = raw_elec.loc[raw_elec.state == st]
offices = st_df.office.unique()
print(offices)
#input name of state senate election to aggregate
sen = 'State Senator'
st_sen = st_df.loc[st_df.office == sen]
st_sen['votes'] = st_sen['candidatevotes'].astype(int)
st_sen_tots = pd.pivot_table(st_sen, index = ['district'], columns = ['party'], values = ['votes'], aggfunc = np.sum)
st_sen_tots.columns = st_sen_tots.columns.to_series().str.join(' ')
st_sen_tots['state'] = st
st_sen_tots['year'] = '2016'
st_sen_tots.to_csv(start_path + 'GitHub/projects/state_senate_results/2016_results/' + st + '_st_sen_tots.csv')
| true |
9b30f1bab9f67cbec2556916f6fae8542997b5a2
|
Python
|
RoboticsClubatUCF/Laki2
|
/catkin_ws/src/laki2_mechanical/ugv/winchCalc.py
|
UTF-8
| 19,478 | 2.921875 | 3 |
[] |
no_license
|
from __future__ import division
import numpy as np
from scipy import integrate
from scipy.optimize import minimize
import matplotlib.pyplot as plt
#----------------------------------------------------------------------------------#
# BE WARNED: currently does not work for spool sizes other than what is listed as a
# constant here
# Define Constants:
# Mass in kg
mass = 1.36078
# Drop Height in m
dropHeight = 30.48
# Gravity in m/s^2
g = 9.81
# Landing speed in m/s
landingSpeed = 5.5
# Max motor hub radius
maxHub = 3 * 0.0254
#----------------------------------------------------------------------------------#
def newDrop(brakeHeight, maxSpeed, Kv, hub, spoolWidth, gear = 1):
# Calculates the voltage, current, power, and force from the motors
# Inputs speed in m/s
# Outputs [voltage, current, power, force]
def motorVals(speed, height):
if (speed == 0):
return [0, 0, 0]
if ((height > brakeHeight) and (abs(speed) < maxSpeed)) or (abs(speed) < 3):
return [0, 0, 0]
# Motor speed in rad/s: gear-ratio * linear-velocity / hub-radius
omega = gear * abs(speed) / effHub(hub, height, spoolWidth)
# Voltage produced by the motor
voltage = omega / Kv
# Power produced by the motor: V^2 / R
power = 3 * (20.88 * voltage - 42.1)
# Max power the motor can handle
if (power > 113.4*0.9):
power = 113.4*0.9
# Force from motor: power = force * linear-velocity
force = power / abs(speed)
return [voltage, power, force]
# Update function for IVP solver
# my" = Fm - Fg
# Ground is 0, up is +
# Inputs:
# U = [y, y']
# t is unused
# Outputs:
# [y', y"]
def dU_dt(t, U):
# Force of gravity
Fg = mass * g
# Pull force from the motor from the helper function
motorForce = motorVals(U[1], U[0])[2]
print U[1], motorForce
# Net Force acting on the motor
netForce = motorForce - Fg
# Net acceleration on the UGV (y double prime)
yDub = netForce / mass
# Return [y', y"]
return [U[1], yDub]
# Dropped from the drop height with 0 initial velocity
U = [dropHeight, 0]
ts = [0, 0]
# Make a list to populate with (t, y)
tVals = []
yVals = []
yPrimeVals = []
motorVolt = []
power = []
tensionVals = []
# While the vehicle is not on the ground, continue to iterate
while (U[0] > 0):
# Take another time step
ts = [ts[1], ts[1] + 1e-2]
# Solve for the next time step
intermediate = integrate.solve_ivp(dU_dt, ts, U)
volt, powerVal, force = motorVals(U[1], U[0])
print "power: ", powerVal
tensionVals.append((dU_dt(0, U)[1] + g) / mass)
U = [intermediate.y[0][-1], intermediate.y[1][-1]]
tVals.append(ts[1])
yVals.append(U[0])
yPrimeVals.append(-U[1])
motorVolt.append(volt)
power.append(powerVal)
return (tVals, yVals, yPrimeVals, motorVolt, power, tensionVals)
# Estimates the size of a given hub at a given height due to the wrapping of the
# tether
def effHub(hub, height, spoolWidth):
# The fishing line can be thought of as cylinders wrapped around a circle
# It can be modeled ad cylinders with some packing efficiency
# cross sectional area is assumed to be that of 30lb fishing line (Dia = 0.022")
tetherCrossArea = np.pi * (0.022 * 0.0254 / 2)**2
# Height is the length of wire remaining
# Volume (with 100% packing efficiency) is height * cross sectional area
volume = height * tetherCrossArea
# Assume it has 90% of the theoretical cylinder packing efficiency of 91%:
volume /= 0.91 / 0.9
# Find the cross sectional area of the spool
spoolCrossArea = volume / spoolWidth
# Area of an annulus is pi(R^2 -r^2)
effHub = np.sqrt((spoolCrossArea / np.pi) + hub**2)
return effHub
#----------------------------------------------------------------------------------#
# Returns lists for time, y, y', and tension in the tether
# of a vehicle dropping in 0 air friction from the drop height to the ground
# Solve numerically
def drop(brakeHeight, maxSpeed, Kv, hub, spoolWidth, res):
# Calculates the voltage, current, power, and force from the motors
# Inputs speed in m/s
# Outputs [voltage, current, power, force]
def motorVals(speed, height):
if (speed == 0):
return [0, 0, 0, 0]
if ((height > brakeHeight) and (abs(speed) < maxSpeed)):
return [0, 0, 0, 0]
# Motor speed in rad/s: gear-ratio * linear-velocity / hub-radius
omega = gear * abs(speed) / effHub(hub, height, spoolWidth)
# Voltage produced by the motor
voltage = omega / Kv
# Total resistance of the system
totalRes = Ra + res
# Current throught the motor and resistor: V = IR
current = voltage / totalRes
# Power produced by the motor: V^2 / R
power = voltage**2 / totalRes
# Force from motor: power = force * linear-velocity
force = power / abs(speed)
return [voltage, current, power, force]
# Update function for IVP solver
# my" = Fm - Fg
# Ground is 0, up is +
# Inputs:
# U = [y, y']
# t is unused
# Outputs:
# [y', y"]
def dU_dt(t, U):
# Force of gravity
Fg = mass * g
# Pull force from the motor from the helper function
motorForce = motorVals(U[1], U[0])[3]
# Net Force acting on the motor
netForce = motorForce - Fg
# Net acceleration on the UGV (y double prime)
yDub = netForce / mass
# Return [y', y"]
return [U[1], yDub]
# Dropped from the drop height with 0 initial velocity
U = [dropHeight, 0]
ts = [0, 0]
# Make a list to populate with (t, y)
tVals = []
yVals = []
yPrimeVals = []
tensionVals = []
resVolt = []
motorVolt = []
sysCurr = []
rmsPower = []
resPower = []
motorPower = []
# While the vehicle is not on the ground, continue to iterate
while (U[0] > 0):
# Take another time step
ts = [ts[1], ts[1] + 1e-2]
# Solve for the next time step
intermediate = integrate.solve_ivp(dU_dt, ts, U)
tensionVals.append((dU_dt(0, U)[1] + g) / mass)
U = [intermediate.y[0][-1], intermediate.y[1][-1]]
tVals.append(ts[1])
yVals.append(U[0])
yPrimeVals.append(-U[1])
volts, curr, powers = brakeElecProps(Kv, Ra, gear,
effHub(hub, U[0], spoolWidth), res, U[1])
motorVolt.append(-volts[0])
resVolt.append(-volts[1])
sysCurr.append(-curr)
resPower.append(powers[1])
motorPower.append(powers[0])
power = motorVals(U[1], U[0])[2]
rmsPower.append(power)
return (tVals, yVals, yPrimeVals, resVolt, motorVolt, sysCurr, rmsPower,
resPower, motorPower, tensionVals)
#----------------------------------------------------------------------------------#
# Returns lists for time, and y
# of a vehicle dropping in 0 air friction from the drop height to the ground
# Solve analytically (at least mostly analytically)
def analyticalDrop(brakeHeight, maxSpeed, Kv, gear, hub, totalRes, flag = None):
# Returns the height of the UGV for a given time after the brakeHeight
def decayedDescentPos(t):
# Height as a function of time (solved by wolfram symbolic diff eq solver):
# y(t) = brakeHeight + (g * m^2 / c^2) * (exp(r) - 1) + (g * m / c) * t
# + (maxSpeed * m / c) * (1 - exp(r))
# Where:
# g = -abs(gravity)
# m = mass
# c = (gear * hub / Kv)^2 / (totRes)
# r = -c * t / m
c = (gear /(hub * Kv))**2 / (totalRes)
r = -c * t / mass
gravity = -g
speed = -maxSpeed
height = (brakeHeight + (gravity * mass**2 / c**2) * (np.exp(r) - 1)
+ (gravity * mass / c) * t - (maxSpeed * mass / c) * (1 - np.exp(r)))
return height
# Returns the speed of the UGV for a given time after the brakeHeight
def decayedDescentVel(t):
# Velocity as a function of time (solved by wolfram symbolic diff eq solver):
# y'(t) = (g * m / c) * exp(r) + (g * m / c) + maxSpeed * exp(r)
# Where:
# g = -abs(gravity)
# m = mass
# c = (gear * hub / Kv)^2 / (totRes)
# r = -c * t / m
c = (gear /(hub * Kv))**2 / (totalRes)
r = -c * t / mass
gravity = -g
speed = -maxSpeed
speed = ((-gravity * mass / c) * np.exp(r) + (gravity * mass / c)
+ speed * np.exp(r))
return speed
# Height at which the max speed is achieved
speedHeight = speedHeightCalc(maxSpeed)
# If the brakeHeight is less than the speedHeight, the system follows 3 phases:
# Phase 1: Free Fall
# Phase 2: Perfect PWM to maintain max speed
# Phase 3: Full Braked Descent to Ground
if (brakeHeight < speedHeight):
# Phase 1: Free Fall:
# y = y0 - 0.5*g*t^2
tSpeed = np.sqrt(2*(dropHeight - speedHeight) / g)
# Phase 2: Perfect PWM to maintain the maxSpeed
# y = y0 + maxSpeed * (t - tSpeed)
tBrake = tSpeed + (speedHeight - brakeHeight) / maxSpeed
# Otherwise, the vehicle skips combines phases 1 and 2 to reach the brake height
# before it reaches max speed:
else:
# Phase 1 & 2: Free Fall to BrakeHeight:
# y = y0 - g*t^2
tBrake = np.sqrt(2*(dropHeight - brakeHeight) / g)
# For plotter to plot correctly
tSpeed = tBrake
# In this case, the speed that starts the exponential decay is no the max
# speed of the vehicle but rather the speed achieved at the drop height
maxSpeed = g * tBrake
# Phase 3: Full Braked Descent to Ground (Exponential Decay of Speed)
# See decayedDescent for eqn
# Quick helper function to return error of the decayed descent
def evalTime(t):
return abs(decayedDescentPos(t))
bnds = ((0, None),)
opt = minimize(evalTime, 1e-6, method = 'SLSQP', bounds = bnds, tol = 1e-8)
tLand = tBrake + opt.x[0]
# If the input didn't ask for anything, output the time to hit the ground
if (flag == None):
return tLand
# The input requested the landing speed
if (flag == 'landingSpeed'):
return decayedDescentVel(opt.x[0])
# The input requested the piecewise time values
if (flag == 'times'):
return (tSpeed, tBrake, tLand[0])
else:
tVals = np.linspace(0, tLand, 1000)
yVals = []
yPrimeVals = []
for t in tVals:
# Phase 1:
if (t < tSpeed):
yVals.append(dropHeight - 0.5*g*t**2)
yPrimeVals.append(-g*t)
# Phase 2:
elif (t < tBrake):
yVals.append(speedHeight - maxSpeed * (t-tSpeed))
yPrimeVals.append(-maxSpeed)
# Phase 3:
else:
yVals.append(decayedDescentPos(t - tBrake))
yPrimeVals.append(decayedDescentVel(t - tBrake))
return (tVals, yVals, yPrimeVals)
#----------------------------------------------------------------------------------#
# Calculates peak to peak electric properties of the motor and resistor
def brakeElecProps(Kv, Ra, gear, hub, res, speed):
# Resistance of motor and external resistor act in series
totalRes = Ra + res
# Motor rotational speed at the given linear speed
omega = gear * speed / hub
# Total voltage generated at the motor rotational speed
volt = omega / Kv
# volts is [motor voltage, resistor voltage]
volts = [volt * (Ra / (Ra + res)) * np.sqrt(2),
volt * (res / (Ra+res)) * np.sqrt(2)]
# Current generated at the control height
curr = volt / totalRes * np.sqrt(2)
# Power generated at the control height
powers = [volts[0] * curr * 0.8, volts[1] * curr / 3]
return [volts, curr, powers]
#----------------------------------------------------------------------------------#
# Calculates the fastest speed allowable and the lowest height to deploy the brake
# TO DO: Make this work with the new variable hub model
def brakeVals(Kv, Ra, gear, hub, res, maxElec):
speed = 0
minSpeed = 0
# Twice the max speed achievable during the fall
maxSpeed = 2 * np.sqrt(2 * dropHeight * g)
convError = 1
lastValid = -1
# Calculate the min height that the brake can be applied in order to not
# exceed the elctrical limits
while (convError > 1e-6):
speed_old = speed
speed = (minSpeed + maxSpeed)/2
convError = abs(speed_old - speed)
[volts, curr, powers] = brakeElecProps(Kv, Ra, gear, hub, res, speed)
# If it is over the motor electrical limits, the speed is too fast
# Voltage multiplied by sqrt(2) for peak to peak voltage
# Current multiplied by sqrt(2) for peak to peak current
# Power Multiplied by 2 for peak to peak power
if (volts[0] > maxElec[0][0] or curr > maxElec[0][1]
or powers[0] > maxElec[0][2]):
maxSpeed = speed
# If it is over the MOSFET electrical limits, the speed is too fast
# Voltage multiplied by sqrt(2) for peak to peak voltage
# Current multiplied by sqrt(2) for peak to peak current
# Power Multiplied by 2 for peak to peak power
elif (volts[1] > maxElec[1][0] or curr > maxElec[1][1]
or powers[1] > maxElec[1][2]):
lastValid = speed
maxSpeed = speed
else:
minSpeed = speed
speed = lastValid
if (speed < landingSpeed):
return [speed, -1]
height = 0
minHeight = 0
maxHeight = dropHeight
convError = 1
lastValid = -1
totalRes = Ra + res
# Calculate the min height that the brake can be applied to reach the desired
# speed
while (convError > 1e-6):
# Improve the hub guess
height_old = height
height = (minHeight + maxHeight)/2
convError = abs(height_old - height)
finalSpeed = -analyticalDrop(height, speed, Kv, gear, hub, totalRes,
flag = 'landingSpeed')
finalSpeed = drop(height, speed, Kv, Ra, gear, hub, spoolWidth, res)[2][-1]
# If the drop height slows down the UGV to within 0.5% of the desired speed by
# the end, the height can be raised
if (abs(finalSpeed - landingSpeed) < (0.005 * landingSpeed)):
lastValid = height
maxHeight = height
# Otherwise it is not enough braking distance
else:
minHeight = height
finalSpeed = -analyticalDrop(lastValid, speed, Kv, gear, hub, totalRes,
flag = 'landingSpeed')
finalSpeed = drop(lastValid, speed, Kv, Ra, gear, hub, spoolWidth, res)[2][-1]
if (abs(finalSpeed - landingSpeed) > (0.005 * landingSpeed)):
return [speed, -1]
else:
return [speed, lastValid]
#----------------------------------------------------------------------------------#
# Returns the height that the given speed with be achieved
# Will return a negative number
def speedHeightCalc(speed):
dropDist = (speed**2) / (2*g)
speedHeight = dropHeight - dropDist
return speedHeight
#----------------------------------------------------------------------------------#
# Returns the largest hub possible with the given configuration
# TO DO: make this work with the variable hub model
def largestHub(Kv, gear, totalRes, maxElec):
def evalHub(hub):
# Force of gravity
Fg = mass * g
# Power of gravity
Pg = Fg * landingSpeed
# Motor speed at the given linear speed
omega = gear * landingSpeed / hub
# Voltage produced by the motor
voltage = omega / Kv
# Power across equivalent resistance
Pr = voltage**2 / totalRes
return abs(Pr - Pg)
bnds = ((1e-6, None),)
opt = minimize(evalHub, maxHub/2, method = 'L-BFGS-B', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
opt = minimize(evalHub, maxHub/2, method = 'TNC', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
opt = minimize(evalHub, maxHub/2, method = 'SLSQP', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
# At this point all of the methods that allow for boundaries have been used.
# The solution was not found
return -1
#----------------------------------------------------------------------------------#
# Returns the hub radius that minimizes the descent time within the given constraints
# This assumes that the hub is sized approriately such that at steady state with
# full break the speed equals the max allowable landing speed. This does not
# have to be the case as the system could be PWM'ed into disapating less power
# TO DO: at the very least helper functions are broken due to the new variable hub
# model. Fix those first
def minimizeTime(Kv, Ra, gear, res, maxElec):
maxHub = largestHub(Kv, gear, Ra + res, maxElec)
# TO DO: Calculate a minimum hub size to stay within bounds
# A spool with a 0.125" radius is the minimum we can tolerate
if (maxHub < 0.125 * 0.0254):
return -1
bnds = ((0.125 * 0.0254, maxHub),)
def evalHub(hub):
maxSpeed, brakeHeight = brakeVals(Kv, Ra, gear, hub, res, maxElec)
t = analyticalDrop(brakeHeight, maxSpeed, Kv, gear, hub, Ra + res)
return t
opt = minimize(evalHub, maxHub/2, method = 'L-BFGS-B', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
opt = minimize(evalHub, maxHub/2, method = 'TNC', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
opt = minimize(evalHub, maxHub/2, method = 'SLSQP', bounds = bnds, tol = 1e-6)
# If converged, return the result
if (opt.success):
return opt.x[0]
# At this point all of the methods that allow for boundaries have been used.
# The solution was not found
return -1
#----------------------------------------------------------------------------------#
# Returns the minimum time to descent for the given motor
# This is basically useless
def motorEvaluator(Kv, Ra, gear, res, maxElec):
hub = minimizeTime(Kv, Ra, gear, res, maxElec)
if (hub == -1):
print 'hub error'
return (-1, -1, np.inf)
maxSpeed, brakeHeight = brakeVals(Kv, Ra, gear, hub, res, maxElec)
print maxSpeed, brakeHeight
if (maxSpeed == -1 or brakeHeight == -1):
print 'brakeVal error'
return (-1, -1, np.inf)
t = analyticalDrop(brakeHeight, maxSpeed, Kv, gear, hub, Ra + res)
if (t == -1):
print 'drop error'
return (-1, -1, np.inf)
else:
return (hub, t)
| true |
258e1c878555c9cf6d9b52e8c7001a650e0eeb8e
|
Python
|
youknowbaron/LearnPythonTheHardWay
|
/ex18.py
|
UTF-8
| 382 | 3.765625 | 4 |
[] |
no_license
|
def print_three(*args):
arg1, arg2, arg3 = args
print(f"arg1: {arg1}, arg2: {arg2}, arg3: {arg3}")
def print_two(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
def print_one(arg1):
print(f"arg1: {arg1}")
def print_none():
print("I got nothin'.")
print_three("i", "am", "baron!")
print_two("just", "4fun")
print_one("haha")
print_none()
print_three(1,2,3)
| true |
246eec142e2cdb9c9c0f735df23e28f851c2e98c
|
Python
|
R4f4Lc/Programacion1Daw
|
/Segundo Trimestre/1- Primeros Ejercicios POO/Python/TestFraccion.py
|
UTF-8
| 2,312 | 4.59375 | 5 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Crea una clase Fraccion (en Java yPython) de forma que podamos hacer las siguientes operaciones:
Contruir un objeto Fraccion pasándole al constructor el numerador y el denominador.
Obtener la fracción.
Obtener y modificar numerador y denominador. No se puede dividir por cero.
Obtener resultado de la fracción (número real).
Multiplicar la fracción por un número.
Multiplicar, sumar y restar fracciones.
Simplificar la fracción.
__author__ = Rafael López | RafaLpeC
"""
from Fraccion import *
salir = True
nu1 = float(input("Introduce el numerador de la primera fracción: "))
de1 = float(input("Introduce el denominador de la primera fracción: "))
frac1 = Fraccion(nu1, de1)
while salir:
print("1. Obtener la fracción.")
print("2. Modificar numerador y denominador.")
print("3. Resultado de la fracción. ")
print("4. Multiplicar un número a la fracción. ")
print("5. Multiplicar, sumar y restar dos fracciones.")
print("6. Salir.")
opcion = float(input("Elige una opción: (1-6)"))
if opcion == 1:
print("La fracción es " + str(frac1.getNum()) + "/" + str(frac1.getDen()))
if (opcion == 2):
nu1 = float(input("Introduce el numerador de la primera fracción: "))
de1 = float(input("Introduce el denominador de la primera fracción: "))
frac1.numerador = nu1
frac1.denominador = de1
if (opcion == 3):
if(frac1.getFraccion() == 0):
print("La fracción tiene que tener un denominador mayor que 0")
else:
print("La fracción es " + str(frac1.getFraccion()))
if (opcion == 4):
num = float(input("Introduce el número a multiplicar: "))
print("El resultado es " + str(frac1.MultiplicaNum(num)))
if (opcion == 5):
nu2 = float(input("Introduce el numerador de la segunda fracción: "))
de2 = float(input("Introduce el denominador de la segunda fracción: "))
frac2 = Fraccion(nu2, de2)
print("La multiplicación de las dos fracciones es igual a " + str(frac1.MultiplicaFrac(frac2)))
print("La suma de las dos fracciones es igual a " + str(frac1.SumaFrac(frac2)))
print("La resta de las dos fracciones es igual a " + str(frac1.RestarFrac(frac2)))
if (opcion == 6):
salir = False
| true |
d8efef2976f32b6f34472d21a735827d763f9f34
|
Python
|
dimitymiller/cac-openset
|
/networks/openSetClassifier.py
|
UTF-8
| 5,065 | 2.796875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""
Network definition for our proposed CAC open set classifier.
Dimity Miller, 2020
"""
import torch
import torchvision
import torch.nn as nn
class openSetClassifier(nn.Module):
def __init__(self, num_classes = 20, num_channels = 3, im_size = 64, init_weights = False, dropout = 0.3, **kwargs):
super(openSetClassifier, self).__init__()
self.num_classes = num_classes
self.encoder = BaseEncoder(num_channels, init_weights, dropout)
if im_size == 32:
self.classify = nn.Linear(128*4*4, num_classes)
elif im_size == 64:
self.classify = nn.Linear(128*8*8, num_classes)
else:
print('That image size has not been implemented, sorry.')
exit()
self.anchors = nn.Parameter(torch.zeros(self.num_classes, self.num_classes).double(), requires_grad = False)
if init_weights:
self._initialize_weights()
self.cuda()
def forward(self, x, skip_distance = False):
batch_size = len(x)
x = self.encoder(x)
x = x.view(batch_size, -1)
outLinear = self.classify(x)
if skip_distance:
return outLinear, None
outDistance = self.distance_classifier(outLinear)
return outLinear, outDistance
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode = 'fan_out', nonlinearity = 'relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def set_anchors(self, means):
self.anchors = nn.Parameter(means.double(), requires_grad = False)
self.cuda()
def distance_classifier(self, x):
''' Calculates euclidean distance from x to each class anchor
Returns n x m array of distance from input of batch_size n to anchors of size m
'''
n = x.size(0)
m = self.num_classes
d = self.num_classes
x = x.unsqueeze(1).expand(n, m, d).double()
anchors = self.anchors.unsqueeze(0).expand(n, m, d)
dists = torch.norm(x-anchors, 2, 2)
return dists
class BaseEncoder(nn.Module):
def __init__(self, num_channels, init_weights, dropout = 0.3, **kwargs):
super().__init__()
self.dropout = nn.Dropout2d(dropout)
self.relu = nn.LeakyReLU(0.2)
self.bn1 = nn.BatchNorm2d(64)
self.bn2 = nn.BatchNorm2d(64)
self.bn3 = nn.BatchNorm2d(128)
self.bn4 = nn.BatchNorm2d(128)
self.bn5 = nn.BatchNorm2d(128)
self.bn6 = nn.BatchNorm2d(128)
self.bn7 = nn.BatchNorm2d(128)
self.bn8 = nn.BatchNorm2d(128)
self.bn9 = nn.BatchNorm2d(128)
self.conv1 = nn.Conv2d(num_channels, 64, 3, 1, 1, bias=False)
self.conv2 = nn.Conv2d(64, 64, 3, 1, 1, bias=False)
self.conv3 = nn.Conv2d(64, 128, 3, 2, 1, bias=False)
self.conv4 = nn.Conv2d(128, 128, 3, 1, 1, bias=False)
self.conv5 = nn.Conv2d(128, 128, 3, 1, 1, bias=False)
self.conv6 = nn.Conv2d(128, 128, 3, 2, 1, bias=False)
self.conv7 = nn.Conv2d(128, 128, 3, 1, 1, bias=False)
self.conv8 = nn.Conv2d(128, 128, 3, 1, 1, bias=False)
self.conv9 = nn.Conv2d(128, 128, 3, 2, 1, bias=False)
self.encoder1 = nn.Sequential(
self.conv1,
self.bn1,
self.relu,
self.conv2,
self.bn2,
self.relu,
self.conv3,
self.bn3,
self.relu,
self.dropout,
)
self.encoder2 = nn.Sequential(
self.conv4,
self.bn4,
self.relu,
self.conv5,
self.bn5,
self.relu,
self.conv6,
self.bn6,
self.relu,
self.dropout,
)
self.encoder3 = nn.Sequential(
self.conv7,
self.bn7,
self.relu,
self.conv8,
self.bn8,
self.relu,
self.conv9,
self.bn9,
self.relu,
self.dropout,
)
if init_weights:
self._initialize_weights()
self.cuda()
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode = 'fan_out', nonlinearity = 'relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def forward(self, x):
x1 = self.encoder1(x)
x2 = self.encoder2(x1)
x3 = self.encoder3(x2)
return x3
| true |
dc44fb896ceb55a200c7967e9bcd913ca5d76275
|
Python
|
bhyun/daily-algorithm
|
/2022/2022.06/Programmers_추석트래픽.py
|
UTF-8
| 1,194 | 3.109375 | 3 |
[] |
no_license
|
def solution(lines):
answer = 0
responses = []
for line in lines:
date, time, t = line.split()
t = float(t[:-1]) * 1000
hour, minute, second = time.split(":")
endtime = (int(hour) * 3600 + int(minute) * 60 + float(second)) * 1000
responses.append((endtime - t + 1, endtime))
for standard_s, standard_e in responses:
answer = max(answer, count(responses, standard_s, standard_s + 1000), count(responses, standard_e, standard_e + 1000))
return answer
def count(responses, start, end):
cnt = 0
for s, e in responses:
if e >= start and s < end:
cnt += 1
return cnt
print(solution( [
"2016-09-15 01:00:04.001 2.0s",
"2016-09-15 01:00:07.000 2s"
]))
print(solution([
"2016-09-15 01:00:04.002 2.0s",
"2016-09-15 01:00:07.000 2s"
]))
print(solution( [
"2016-09-15 20:59:57.421 0.351s",
"2016-09-15 20:59:58.233 1.181s",
"2016-09-15 20:59:58.299 0.8s",
"2016-09-15 20:59:58.688 1.041s",
"2016-09-15 20:59:59.591 1.412s",
"2016-09-15 21:00:00.464 1.466s",
"2016-09-15 21:00:00.741 1.581s",
"2016-09-15 21:00:00.748 2.31s",
"2016-09-15 21:00:00.966 0.381s",
"2016-09-15 21:00:02.066 2.62s"
]))
| true |
6a2442189f3934c7f79113a7b8b997d8328d22e3
|
Python
|
kathrynzav/DukeTIP2018Projects
|
/hangmangame.py
|
UTF-8
| 7,947 | 2.75 | 3 |
[] |
no_license
|
import random
##big hangman
print(" _ _ _ _ _____ __ __ _ _ ")
print(" | | | | /\ | \ | |/ ____| | \/ | /\ | \ | |")
print(" | |__| | / \ | \| | | __ | \ / | / \ | \| |")
print(" | __ | / /\ \ | . ` | | |_ | | |\/| | / /\ \ | . ` |")
print(" | | | |/ ____ \| |\ | |__| | | | | |/ ____ \| |\ |")
print(" |_| |_/_/ \_\_| \_|\_____| |_| |_/_/ \_\_| \_|")
print("Taylor Farley, Kathryn Zavadil, Myles Crockem, Colby DuHamel")
print("")
easyWords = ["shadowofthecolossus","leagueoflegends","grandtheftauto","supersmashbros","legendofzelda","supermarioodyssey","sonicthehedgehog","streetfighter","residentevil","undertale"]
hardWords = ["fortnite","minecraft","pubg","cuphead","octodad","godofwar","titanfall","fallout","overwatch","darksouls","skyrim","splatoon","callofduty","pokemon","thesims","pacman","tetris","doom"]
def isAlpha(char):
if(char == "a" or char == "b" or char == "c" or char == "d" or char == "e" or char == "f" or char == "g" or char == "h" or char == "i" or char == "j" or char == "k" or char == "l" or char == "m" or char == "n" or char == "o" or char == "p" or char == "q" or char == "r" or char == "s" or char == "t" or char == "u" or char == "v" or char == "w" or char == "x" or char == "y" or char == "z"):
return True
uwuMode = False
cheatMode = False
difficulty = 0
selectedDifficulty = False
lives = 6
victory = False
def drawMan():
boiNum = 0
boiNum = random.randint(0,3)
if(lives > 6 and boiNum <= 1):
print("____. ")
print("|_(._.)_ ")
print("| \_|_/ ")
print("| | ")
print("| / \ ")
print("| ")
print("|_______ ")
if(lives > 6 and boiNum == 2):
print("____. ")
print("| (._.) ")
print("|___|___ ")
print("| | ")
print("| / \ ")
print("| ")
print("|_______ ")
if(lives == 6):
print("____. ")
print("| ")
print("| ")
print("| ")
print("| ")
print("| ")
print("|_______ ")
if(lives == 5):
print("____. ")
print("| ( ) ")
print("| ")
print("| ")
print("| ")
print("| ")
print("|_______ ")
if(lives == 4):
print("____. ")
print("| ( ) ")
print("| | ")
print("| | ")
print("| ")
print("| ")
print("|_______ ")
if(lives == 3):
print("____. ")
print("| ( ) ")
print("| /| ")
print("| | ")
print("| ")
print("| ")
print("|_______ ")
if(lives == 2):
print("____. ")
print("| ( ) ")
print("| /|\ ")
print("| | ")
print("| ")
print("| ")
print("|_______ ")
if(lives == 1):
print("____. ")
print("| ( ) ")
print("| /|\ ")
print("| | ")
print("| / ")
print("| ")
print("|_______ ")
if(lives == 0):
print("____. ")
print("| ( ) ")
print("| /|\ ")
print("| | ")
print("| / \ ")
print("|_______ ")
while(selectedDifficulty != True):
press = input("Choose a difficulty. Type '0' for easy or '1' for hard ")
if(press == "0"):
difficulty = 0
print("Easy Mode Selected!")
selectedDifficulty = True
if(press == "1"):
difficulty = 1
print("Hard Mode Selected!")
selectedDifficulty = True
if(press == "uwu"):
print("what's this?")
uwuMode = True
if(press == "i am a cheater"):
print("If it makes you happy, I guess.")
difficulty = 0
cheatMode = True
selectedDifficulty = True
if(press == "upupdowndownleftrightleftrightba"):
print("cool cool fam")
difficulty = 1
lives = 999
selectedDifficulty = True
item = 0
if(press == "lootbox"):
print("oh boy what are ya goona get?")
item = random.randint(0,22)
if(item == 1):
print("you got an apple")
if(item == 2):
print("you got a voice line for winston")
if(item == 3):
print("you got a broken game of tic tac toe")
if(item == 4):
print("you got a single macaroni noodle")
if(item == 5):
print("you got a nice shirt. Lookin good!")
if(item == 6):
print("you got a 100$ sharky's gift card")
if(item == 7):
print("you got a body pillow of your waifu")
if(item == 8):
print("you got a sense of pride and accomplishment")
if(item == 9):
print("you got a badly translated copy of a dating simulator")
if(item == 10):
print("you got a career of a master fortnite player")
if(item == 11):
print("you got a new and improved sense of humor")
if(item == 12):
print("you got too many bagels")
if(item == 13):
print("you got a duplicate (+5 coins tho)")
if(item ==14):
print("you got a wrinkled up pokemon card")
if(item == 15):
print("you got a hefty donation from the NRA")
if(item == 16):
print("you got burned. You feel incredibly insulted and your self confidence is down the drain")
if(item == 17):
print("you got a new understanding of the furry fandom")
if(item == 18):
print("you got a bag of various girlscout cookies but none of the flavor you like")
if(item == 19):
print("you got in trouble. Go to jaaiiiillll")
if(item == 20):
print("you got Todd Howard on your doorstep coming to take away your computer")
if(item == 21):
print("You got dead")
currentWord = ""
if(difficulty == 0):
currentWord = easyWords[random.randint(0,9)]
if(difficulty == 1):
currentWord = hardWords[random.randint(0,17)]
letters = list(currentWord)
length = len(currentWord)
usedLetters = []
wordBlank = []
for a in range(length):
wordBlank.append("_")
lettersguessed = 0
guessCorrect = False
blanks = "_ "
while(lives == 0 or victory != True):
drawMan()
if(cheatMode == True):
print(currentWord)
guessCorrect = False
print("The word is " + str(length) + " letters long. [" + str(lives) + " lives left]")
print(*wordBlank)
text = input("Guess a letter!")
text = text.lower()
usedAgain = False
#check if the letter is valid
if(isAlpha(text) and len(text) == 1):
for e in range(len(usedLetters)):
if(text == usedLetters[e]):
usedAgain = True
for b in range(length): #correct guess
if(text == letters[b-1]):
wordBlank[b-1] = (str(text))
guessCorrect = True
if(usedAgain != True):
lettersguessed += 1
for c in range(length): #testing for a win
if(lettersguessed == length):
victory = True
if(usedAgain != True):
usedLetters.append(text)
else:
print('\033[1m' + "Invalid Response. Be sure your input is a letter and only one character long")
guessCorrect = True
if(victory == True):
print("Victory!!! The word was \'" + currentWord + "\'!!")
break
print("Already used:" + str(list(usedLetters)))
if(guessCorrect == False):
if(usedAgain != True):
lives -= 1
print('\033[1m' + "There are no " + text + "\'s in the word. Try again [-1 life]")
if(lives == 0):
print('\033[1m' + "Game Over. The word was \'" + currentWord + "\'")
print("| ||")
print("|||_")
break
if(usedAgain == True):
print("already used that letter!")
if(victory == True):
if(uwuMode == False):
print(" (:D)/ ")
print(" /| ")
print(" | ")
print(" / \ ")
if(uwuMode == True):
print(" (uwu)/ ")
print(" /| ")
print(" | ")
print(" / \ ")
print("Thanks for playing!")
pressedExit = False
while(pressedExit == False):
bloop = input("press any key to exit")
if(len(bloop) > -1):
pressedExit = True
| true |
97fa939fdfb592a3fd1d58392a25b01d71070319
|
Python
|
secpanel/rogue-ips-api-actionkit
|
/python/sample-python.py
|
UTF-8
| 1,339 | 2.984375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
#Importing modules for HTTPS Connection
import urllib
import httplib
#Importing modules for parsing JSON
import json
def getTheData(key,limit=10,offset=0):
h = httplib.HTTPSConnection('apis.secpanel.com');
h.request('GET', '/rouge-ips-json.php?key='+str(key)
+'&limit='+str(limit)+'&offest='+str(offset))
response = h.getresponse()
return response.read()
#Get the JSON Data
json_response=getTheData("your-key")
#Parse JSON String
parsed_json = json.loads(json_response)
#Create a blank Dictionary to store ip and respective
#Geolocation attributes
ips={}
#Read the parsed JSON
for keys in parsed_json:
if keys=='limit':
limit_used=parsed_json[keys]
elif keys=='offset':
offset_used=parsed_json[keys]
elif keys=='total':
total_records=parsed_json[keys]
elif keys=='status':
status=parsed_json[keys]
elif keys=='status_code':
status_code=parsed_json[keys]
else:
#Store the IPs
ips[keys]=parsed_json[keys]
#Process as per application logic
if status_code==200:
#data is good for and useful
if total_records < 1:
print "No records returned"
else:
for ip in ips:
print ip,":",ips[ip],"\n"
else:
print "Something went bad : [",status_code,"] ",status,"\n"
| true |
104a5cb3a05e08a5c6711cbe1cb016390eda0337
|
Python
|
christopherjmedlin/discord-auto-responder
|
/autoresponder.py
|
UTF-8
| 1,495 | 2.546875 | 3 |
[] |
no_license
|
#!/usr/bin/env python3.6
from discord import Client
from discord.errors import LoginFailure
import asyncio
import configparser
from getpass import getpass
import os
import json
client = Client()
message_map = {}
default_message = "¯\_(ツ)_/¯"
@client.event
async def on_ready():
print('\033[92m\nLogged in as\033[92m\n\033[95m------\033[0m')
print(client.user.name)
print(client.user.id)
print('\033[95m------\033[0m')
@client.event
async def on_message(message):
mentioned = client.user.mention in message.content
if (message.channel.is_private and message.author.id != client.user.id) or mentioned:
response = message_map.get(str(message.author.id), default_message)
await client.send_message(message.channel, response)
if __name__ == "__main__":
config = {"config": {}}
if os.path.isfile('config.json'):
config = json.load(open('config.json'))
groups = config.get("groups", [])
for group in groups:
for num in group["ids"]:
message_map[str(num)] = group["message"]
email = config.get("email")
if not email:
email = input("Email: ")
password = config.get("password")
if not password:
password = getpass()
default_message = config.get("default_message")
if not default_message:
default_message = input("Default Message: ")
try:
client.run(email, password)
except LoginFailure:
print("\033[91mInvalid login.\033[0m")
| true |
036b6c1937c2ed7fcfbdd130ff5ca534de4bfea5
|
Python
|
mikkolaj/wdi
|
/zestaw2/elo.py
|
UTF-8
| 130 | 3.671875 | 4 |
[] |
no_license
|
def pow(a, n):
c=1
for i in range(1,n+1):
c*=a
return c
tab = [1, 2, 3, 4]
for i in tab:
print(pow(i, 2))
| true |
d60bb5ca6f525b09635ce23c691fce60a0a0616d
|
Python
|
jumpjumpdog/CrawlAmazon
|
/learnRe.py
|
UTF-8
| 255 | 2.6875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import re
def reFunc(str):
matchObj = re.search(r'(.*?) *:(.*)' ,testStr)
if matchObj:
print matchObj.group(2)
else:
print "no match"+matchObj.group(0)
if __name__ == "__main__":
reFunc(testStr)
| true |
9f5755332f61e5252fb802631072cf5aebc0f25d
|
Python
|
ojhaanshu87/LeetCode
|
/139_word_break.py
|
UTF-8
| 3,540 | 3.875 | 4 |
[
"Unlicense"
] |
permissive
|
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
"""
#METHOD1 -> DFS with Memorization TC (O(n) with memoization, O(2^n) without)
"""
The basic idea is to use DFS to remove any possible word from the word dictionary that exists in the begining of the string,
and then the remainder of each resultant string will have the same procedure recursively applied to it.
At the end of the day, if there's one recusrion that returns True, when a input string "" is found, then there exists a possible wordBreak.
Used a memo table to store previously seen postfix strings, so we don't have to go down the route of calculating already tabulated words.
"""
class Solution(object):
def dfs(self, string, wordDict, found):
if string == "":
return True
if string in found:
return found[string]
found_split = False
for word in wordDict:
if string .startswith(word):
found_split = found_split or self.dfs(string[len(word):], wordDict, found)
if found_split == True:
return True
found[string] = found_split
return found_split
def wordBreak(self, s, wordDict):
found = {}
return self.dfs(s, wordDict, found)
#METHOD2 -> Trie With Memorization
class Solution:
def __init__(self):
self.trie = [{}]
# memoization cache
self.found = {}
def get_prefixes(self, word):
prefixes = []
current_word = []
current = self.trie[0]
for c in word:
if "$" in current:
prefixes.append(''.join(current_word))
if c in current:
current_word.append(c)
current = self.trie[current[c]]
else:
break
if "$" in current:
prefixes.append(''.join(current_word))
return prefixes
def make_trie(self, wordDict):
for word in wordDict:
current = self.trie[0]
for c in word + "$":
if c in current:
current = self.trie[current[c]]
else:
# make new node
self.trie.append({})
current[c] = len(self.trie) - 1
current = self.trie[current[c]]
def dfs(self, suffix):
if suffix in self.found:
return False
if not suffix:
return True
for p in self.get_prefixes(suffix):
if self.dfs(suffix[len(p):]):
return True
self.found[suffix] = False
return False
def wordBreak(self, s, wordDict):
self.make_trie(wordDict)
return self.dfs(s)
| true |
be1c504d5a8af1abda460520aea597d4a1221b08
|
Python
|
sam95/python-simple-tasks
|
/NewForms/app.py
|
UTF-8
| 1,809 | 2.828125 | 3 |
[] |
no_license
|
from flask import Flask
from flask import request
from flask import render_template
import re
app = Flask(__name__)
my_dict = {}
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/handle_data', methods=['POST'])
def handle_data():
name = request.form['usrName']
email = request.form['email']
phone = request.form['phone']
print name, email, phone
if name.isalpha():
if re.match("[^@]+@[^@]+\.[^@]+", email):
if len(phone) == 10 and phone.isdigit():
my_dict["name"] = name
my_dict["email"] = email
my_dict["phone"] = phone
return render_template('directions.html', name=name)
return "Data not valid, Please enter again"
@app.route('/quote_process', methods=['POST'])
def quote_process():
my_from = request.form['myfrom']
my_to = request.form['myto']
birthday = request.form['bday']
print my_from, my_to, birthday
if my_from and my_to and birthday:
my_dict["from"] = my_from
my_dict["to"] = my_to
my_dict["birthday"] = birthday
return render_template("laststep.html")
return "Invalid data, Please enter again"
@app.route('/last_process', methods=['POST'])
def last_process():
min = request.form['minvalue']
max = request.form['maxvalue']
time = request.form['timeslot']
if float(min) < float(max):
my_dict["min"] = min
my_dict["max"] = max
my_dict["time"] = time
return render_template("data.html", **my_dict)
print min, max, time, min.isdigit() and max.isdigit(), float(min) < float(max)
return "Wrong data, Please enter again"
if __name__ == '__main__':
app.run(debug=True)
| true |
0c194ab3ebba4c6f3df6820712c7d67b523f663c
|
Python
|
worry1613/dongni-recommendation
|
/rec-engine/mining/nlp/word2v.py
|
UTF-8
| 1,833 | 2.859375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @创建时间 : 19/2/2018
# @作者 : worry1613(549145583@qq.com)
# GitHub : https://github.com/worry1613
# CSDN : http://blog.csdn.net/worryabout/
from optparse import OptionParser
from gensim.models import word2vec
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# 使用gensim库中的word2vec类
class W2v(object):
def __init__(self, fin=None):
self.model = None
self.file = fin
def load(self, fmodel):
self.model = word2vec.Word2Vec.load(fmodel)
def process(self, size=300, window=5, min_count=5):
import multiprocessing
cpu_count = multiprocessing.cpu_count()
workers = cpu_count
sentences = word2vec.LineSentence(self.file)
self.model = word2vec.Word2Vec(sentences, size=size, window=window, min_count=min_count, workers=workers)
def save(self, fout):
try:
self.model.save(fout)
except IOError:
print(fout, "写文件取错误请检查!")
exit(0)
if __name__ == '__main__':
'''
python word2v.py -f ../../../data/新闻min_cw.txt -m ../../../model/w2v.300.新闻min.model
'''
parser = OptionParser()
parser.add_option('-f', '--file', type=str, help='已经分了词的语料库文件', dest='wordsfile')
parser.add_option('-m', '--model', type=str, help='训练完成了w2v模型文件', dest='modelfile')
parser.add_option('-s', '--size', type=int, default=300, help='w2v向量维度')
options, args = parser.parse_args()
if not (options.wordsfile or options.modelfile):
parser.print_help()
exit()
w = W2v(options.wordsfile)
logging.info('<<<<<<<<<<<<<<<<')
w.process()
logging.info('>>>>>>>>>>>>>>>>')
w.save(options.modelfile)
| true |
9ca6a66d91cc3f90549ecc4e94cf831c0d2a0932
|
Python
|
etmorefish/leetcode
|
/剑指offer/52_两个链表的第一个公共节点.py
|
UTF-8
| 967 | 3.71875 | 4 |
[] |
no_license
|
"""
解题思路:
我们使用两个指针 node1,node2 分别指向两个链表 headA,headB 的头结点,
然后同时分别逐结点遍历,当 node1 到达链表 headA 的末尾时,
重新定位到链表 headB 的头结点;当 node2 到达链表 headB 的末尾时,
重新定位到链表 headA 的头结点。
这样,当它们相遇时,所指向的结点就是第一个公共结点。
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA, headB):
ha, hb = headA, headB
while ha != hb:
# if ha:
# ha = ha.next
# else:
# ha = headB
# if hb:
# hb = hb.next
# else:
# hb = headA
ha = ha.next if ha else headB
hb = hb.next if hb else headA
return ha
| true |
fd38551e4c98de8cf7702aaaa3397d93f2cf3bee
|
Python
|
abulkairhamitov/TrainingInDataScience
|
/workWithData/oneDimensionalData.py
|
UTF-8
| 2,438 | 3.71875 | 4 |
[] |
no_license
|
from typing import List, Dict
from collections import Counter
import math
import matplotlib.pyplot as plt
import random
def bucketize(point: float, bucket_size: float) -> float:
"""Округлить точку до следующего наименьшего кратного размера интервала bucket_size"""
return bucket_size * math.floor(point / bucket_size)
def make_histogram(points: List[float], bucket_size: float) -> Dict[float, int]:
"""Разбивает точки на интервалы и подсчитывает их количество в каждом интервале"""
return Counter(bucketize(point, bucket_size) for point in points)
def plot_histogram(points: List[float], bucket_size: float, title: str = ""):
histogram = make_histogram(points, bucket_size)
plt.bar(list(histogram.keys()), list(histogram.values()), width=bucket_size)
plt.title(title)
plt.show()
# Нормальное распределение
def normal_cdf(x, mu=0, sigma=1):
return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2
# Обратная ИФР нормального распределения
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.00001):
# Используем двоичный поиск
if mu !=0 or sigma != 1:
return mu + sigma*inverse_normal_cdf(p, tolerance=tolerance)
hi_z, low_z = 10, -10
while hi_z - low_z > tolerance:
mid_z = (hi_z + low_z) / 2
mid_p = normal_cdf(mid_z)
if mid_p < p:
low_z = mid_z
elif mid_p > p:
hi_z = mid_z
else:
break
return mid_z
# Рассмотрим пример
random.seed(0)
# Рассмотрим два набора данных с одним и тем же среднеквадратичным отклонением и средним
# но гистограммы показывают насколько они разные
# Равномерное распределение между -100 и 100
uniform = [200 * random.random() - 100 for _ in range(10000)]
# Нормальное со средним 0 и стандартным отклонением 57
normal = [57 * inverse_normal_cdf(random.random()) for _ in range(10000)]
plot_histogram(uniform, 10, "Равномерная гистрограмма")
plot_histogram(normal, 10, "Нормальная гистограмма")
| true |
c55c9171dda8e44ca6ef6fe6ff903b085c817658
|
Python
|
souhardya1/Single-LinkedList-in-python
|
/MergeSoort on LinkedList.py
|
UTF-8
| 1,594 | 3.640625 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 19:47:35 2020
@author: Souhardya
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(new_data)
new_node.next=self.head
self.head=new_node
def printList(self):
curr=self.head
while curr!=None:
print(curr.data,end='->')
curr=curr.next
print('None')
def merge(self,a,b):
r=None
if a==None:
return b
if b==None:
return a
if a.data<=b.data:
r=a
r.next=self.merge(a.next,b)
else:
r=b
r.next=self.merge(a,b.next)
return r
def sort(self,h):
if h==None or h.next==None:
return h
mid=self.getMiddle(h)
midN=mid.next
mid.next=None
l=self.sort(h)
r=self.sort(midN)
new=self.merge(l,r)
return new
def getMiddle(self,h):
if h==None:
return
slow=h
fast=h
while fast.next!=None and fast.next.next!=None:
slow=slow.next
fast=fast.next.next
return slow
ll=LinkedList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)
print('Given List:')
ll.printList()
ll.head=ll.sort(ll.head)
print('After Sorting')
ll.printList()
| true |
693fa52ac2f688324e5f645886d28f4b56761e69
|
Python
|
ajinkyapuar/loonycorn-zero-to-one
|
/FizzBuzz.py
|
UTF-8
| 306 | 3.609375 | 4 |
[] |
no_license
|
# % by 3 Fizz
# % by 5 Buzz
# % by 3 & 5 FizzBuzz
# For instance, the result will look something like this for 1 to 20.
# 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19
['Fizz' * (i % 3 == 0) + 'Buzz' * (i % 5 == 0) or i for i in range(1, 20)]
| true |
0e5d83bef70536fadaa679a85c45e5ee489856b1
|
Python
|
ucsd-cse-spis-2020/SPIS-Final-Project-Theodore-Nikunj
|
/python/card.py
|
UTF-8
| 411 | 3.140625 | 3 |
[] |
no_license
|
import os
import pygame
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
self.face = pygame.image.load(os.path.join("assets", str(self.value) + self.suit + ".png"))
self.back = pygame.image.load(os.path.join("assets", "Gray_back.jpg"))
def __str__(self):
return "Card value: " + str(self.value) + " suit: " + str(self.suit) + "\n"
| true |
d23e7dd1643136cea5688e69ac931443b446d4ba
|
Python
|
adison330/testdemo
|
/test013.py
|
UTF-8
| 177 | 3.5625 | 4 |
[] |
no_license
|
#! /usr/bin/env python
num_str = "1234567890"
print(num_str[2:6])
print(num_str[2:])
print(num_str[:6])
print(num_str[ : ])
print(num_str[ : : 2])
print(num_str[1: : 2])
| true |
f3041393fc436eaa8369623c92d35454bec4ea12
|
Python
|
lanzo-siega/FooDD-classification
|
/preparation.py
|
UTF-8
| 2,456 | 2.890625 | 3 |
[] |
no_license
|
import numpy as np
import os
from matplotlib import pyplot as plt
import cv2
import random
import pickle
file_list = []
class_list = []
direct = '/path/to/dataset'
cat = os.listdir('/path/to/dataset')
# identifies the subfolders that contain the images we will use
for category in cat:
path = os.path.join(direct, category)
for subdir, dirs, files in os.walk(path):
for file in files:
filepath = subdir
if filepath.endswith('Environment'):
end = filepath
elif filepath.endswith('Net'):
end = filepath
elif filepath.endswith('images'):
end = filepath
else:
pass
for img in os.listdir(end):
img_array = cv2.imread(os.path.join(end, img), cv2.IMREAD_GRAYSCALE)
train_data = []
#setting the parameters in which the images will be resized to
img_size = 50
# a function to convert image files into data that can be fed into the CNN model
def create_train_data():
for category in cat:
path = os.path.join(direct, category)
class_num = cat.index(category)
for subdir, dirs, files in os.walk(path):
for file in files:
filepath = subdir
if filepath.endswith('Environment'):
end = filepath
elif filepath.endswith('Net'):
end = filepath
else:
pass
# each image in a folder are converted to grayscale and resized to a dimension of img_size by img_size. This image is then appended to the
# train_data array with their encoded class
for img in os.listdir(end):
try:
img_array = cv2.imread(os.path.join(end, img), cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (img_size, img_size))
train_data.append([new_array, class_num])
except Exception as e:
pass
create_train_data()
#randomizes the order of the training data
random.shuffle(train_data)
X = []
y = []
# identifies the image array as the feature and the encoded class as the label
for features, label in train_data:
X.append(features)
y.append(label)
# converts X from a list to an array
X = np.array(X).reshape(-1,img_size, img_size, 1)
# serializes the X and y arrays so that they can be stored for later use by the CNN model
pickle_out = open("X.pickle", "wb")
pickle.dump(X, pickle_out)
pickle_out.close()
pickle_out = open("y.pickle", "wb")
pickle.dump(y, pickle_out)
pickle_out.close()
pickle_in = open("X.pickle", "rb")
X = pickle.load(pickle_in)
| true |
4415ccb6e30df451774e71035ac00e2b0c500d0f
|
Python
|
mh-rahman/Programming-Practice
|
/78. Subsets.py
|
UTF-8
| 594 | 2.78125 | 3 |
[] |
no_license
|
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
if not nums:
return res
res+=[[c] for c in nums]
for _ in range(2**len(nums)):
res+=[s+[c] for s in res for c in nums if s and c not in s and c>s[-1] and s+[c] not in res]
# print(res)
return res
def fastersubsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
nums.sort()
res+=[[c] for c in nums]
for c in nums:
res+=[s+[c] for s in res if s and c>s[-1] ]
return res
| true |
3237fd9296bda93a3196eeecf039920b8a16a93c
|
Python
|
zggl/wax-ml
|
/wax/modules/gym_feedback.py
|
UTF-8
| 3,205 | 2.734375 | 3 |
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
# Copyright 2021 The WAX-ML Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Gym feedback between an agent and a Gym environment."""
from collections import namedtuple
from dataclasses import dataclass, field
from typing import Any
import haiku as hk
@dataclass
class GymOutput:
"""Dynamically define GymOutput namedtuple structure.
Args:
return_obs: if true, add 'obs' field to output structure.
return_action: if true, action 'obs' field to output structure.
"""
return_obs: bool = False
return_action: bool = False
gym_output_struct: Any = field(init=False)
def __post_init__(self):
outputs = ["reward"]
if self.return_obs:
outputs += ["obs"]
if self.return_action:
outputs += ["action"]
self.gym_output_struct = namedtuple("GymOutput", outputs)
def format(self, reward, obs=None, action=None):
outputs = [reward]
if self.return_obs:
outputs += [obs]
if self.return_action:
outputs += [action]
return self.gym_output_struct(*outputs)
class GymFeedback(hk.Module):
"""Gym feedback between an agent and a Gym environment."""
GymState = namedtuple("GymState", "action")
def __init__(
self,
agent,
env,
return_obs=False,
return_action=False,
name=None,
):
"""Initialize module.
Args:
agent : Gym environment used to unroll the data and feed the agent.
env : Gym environment used to unroll the data and feed the agent.
return_obs : if true return environment observation
return_action : if true return agent action
name : name of the module
"""
super().__init__(name=name)
self.agent = agent
self.env = env
self.return_obs = return_obs
self.return_action = return_action
self.GymOutput = GymOutput(self.return_obs, self.return_action)
def __call__(self, raw_obs):
"""Compute Gym feedback loop.
Args:
raw_obs: raw observations.
Returns:
gym_output : reward.
Use return_obs=True to also return env observations.
Use return_action=True to aslo return agent actions.
"""
action = hk.get_state(
"action", shape=[], init=lambda *_: self.GymState(self.agent(raw_obs))
)
rw, obs = self.env(action.action, raw_obs)
action = self.agent(obs)
outputs = self.GymOutput.format(rw, obs, action)
state = self.GymState(action)
hk.set_state("action", state)
return outputs
| true |
baaeb53954f9968aa717c8bd46f1a735bed89b8e
|
Python
|
valar-m0rghulis/Python
|
/Infosys-Foundation-Program/MODULES/Module_3_Python_DB_Integration/Assignment_9.py
|
UTF-8
| 897 | 2.75 | 3 |
[] |
no_license
|
import cx_Oracle
# 3)Invalid Username
#con = cx_Oracle.connect('infosysdb/admin@localhost/xe')
#OUTPUT :
#cx_Oracle.DatabaseError: ORA-01017: invalid username/password; logon denied
con = cx_Oracle.connect('infosys/admin@localhost/xe')
cur = con.cursor()
# 1) Invalid Column Name
#cur.execute("DELETE FROM users WHERE user_id = 2")
#con.commit()
# OUTPUT :
# cx_Oracle.DatabaseError: ORA-00904: "USER_ID": invalid identifier
# 2) Exception Handeling
try:
cur.execute("DELETE FROM users WHERE user_id = 2")
con.commit()
except cx_Oracle.DatabaseError as e:
print("Error Details :: ",e)
finally:
print("Done.")
# OUTPUT :
# Error Details :: ORA-00904: "USER_ID": invalid identifier
# Done.
# 4) Wrong Table Name
cur.execute("DELETE FROM user WHERE userid = 2")
con.commit()
# OUTPUT :
# cx_Oracle.DatabaseError: ORA-00903: invalid table name
con.close()
| true |
c6e9710a737653961fc1e9e46c1759b0a1a05198
|
Python
|
SabiKov/OpenCvPython
|
/chapter4_getting_and_setting/getting_and_setting.py
|
UTF-8
| 899 | 3.171875 | 3 |
[] |
no_license
|
# import necessary packages
from __future__ import print_function
import argparse
import cv2
# Read in CLI argument
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image",
required=True,
help="Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
cv2.imshow("Original", image)
# Access the first pixel of the image
(b, g, r) = image[0, 0]
print ("Default -> pixel at 0, 0 - Red: {}, Green: {}, Blue: {}"
. format(r, g, b))
image[0:10, 0:10] = (0, 0, 255)
(b, g, r) = image[0, 0]
print ("Updated -> Pixel at 0, 0 - Red: {}, Green: {}, Blue: {}"
. format(r, g, b))
# Manipulate and display 100 x 100 pixel region of the image
corner = image[0:100, 0:100]
cv2.imshow("Corner", corner)
# replace the 100 x 100 region with green colour
image[0:100, 0:100] = (0, 255, 0)
cv2.imshow("Updated", image)
cv2.waitKey(0)
| true |
a173d0e7723830d47161dc44165c340f37afe9be
|
Python
|
developyoun/AlgorithmSolve
|
/programmers/가장큰수.py
|
UTF-8
| 149 | 3.0625 | 3 |
[] |
no_license
|
def solution(numbers):
answer = ''.join(sorted(map(str, numbers), key=lambda x:x*3, reverse=True))
return '0' if answer[0] == '0' else answer
| true |
a914abb498757a720dd3ff0d04b4b790e1871a52
|
Python
|
loisks317/TitanicBlogCode
|
/LoisTitanic.py
|
UTF-8
| 1,688 | 3.21875 | 3 |
[] |
no_license
|
# LoisTitanic.py
#
#
# LKS, December 2016
#
#
# imports
import pandas as pd
import numpy as np
# load in file into a pandas dataframe
df=pd.read_csv('Titanic.csv')
#
# first, let's clean up our data set
df=df.dropna()
# then let's put the solution off to the side
# and drop the labeled 'male/female' column in favor of the
# sex code one (female = 1, male = 0)
SolutionCol = df['Survived']
df=df.drop(['Survived', 'Sex', 'Name', 'Unnamed: 0'], axis=1)
#
# then we have to fix PClass from 1st, 2nd, etc. to just 1, 2, 3
# once again, we need numerical values
df['PClass'] = df['PClass'].map(lambda x: str(x)[0])
#
# now split up train-test data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
df, SolutionCol, test_size=0.25, random_state=2)
# setup the model
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
predictions=clf.predict(X_test)
# score the model
# how accurate was the model overall
from sklearn.metrics import accuracy_score
acc=accuracy_score(y_test, predictions)
# what was it's precision
from sklearn.metrics import precision_score
precision=precision_score(y_test, predictions)
# what is the TP, FP, FN, TN rate? (true positive, false positive, etc.)
from sklearn.metrics import confusion_matrix
confusionMatrix=confusion_matrix(y_test, predictions)
# print out the values
print('accuracy is: ' + str(int(acc*100)) + '%')
print('precision is: ' + str(precision))
print ('confusion matrix: '+ str(confusion_matrix(y_test, predictions)))
# what were the most important features?
list(zip(df.columns.values, clf.feature_importances_))
| true |
790bb70db4d56db1a08e677b5be6b4a6977974ec
|
Python
|
pablodarius/mod02_pyhton_course
|
/Python Exercises/ejercicios varios.py
|
UTF-8
| 655 | 3.921875 | 4 |
[] |
no_license
|
# Ejercicio 6.1. Escribir un ciclo que permita mostrar los caracteres de una cadena del final al principio.
word = "cagadutaz"
wordRev = ""
for l in range(len(word)-1, -1, -1):
wordRev += word[l]
print(wordRev)
#########################################################
counterA = 0
counterE = 0
counterI = 0
counterO = 0
counterU = 0
for l in word:
if l.upper() == 'A':
counterA += 1
elif l.upper() == 'E':
counterE += 1
elif l.upper() == 'I':
counterI += 1
elif l.upper() == 'O':
counterO += 1
elif l.upper() == 'U':
counterU += 1
print([counterA, counterE, counterI, counterO, counterU])
| true |
9f89672c06c0abdda9fd420e187be2552e4360d4
|
Python
|
MICROBAO/cs61a
|
/disussion3.py
|
UTF-8
| 107 | 2.953125 | 3 |
[] |
no_license
|
# # Discussion 2
# 1.1
def multiply(m, n):
if m == 0 or n == 0:
return 0
return m + multiply(m, n - 1)
| true |
cbcf116e84f1c58e411a2727a83cb7ca64ce247f
|
Python
|
chaocharliehuang/FlaskMySQLRESTfulUsers
|
/server.py
|
UTF-8
| 3,030 | 2.640625 | 3 |
[] |
no_license
|
from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = 'secret'
mysql = MySQLConnector(app, 'semirestfulusersdb')
@app.route('/users')
def index():
query = "SELECT id, CONCAT_WS(' ', first_name, last_name) AS full_name, email, DATE_FORMAT(created_at, '%M %D, %Y') AS created_at FROM users"
users = mysql.query_db(query)
return render_template('users.html', users=users)
@app.route('/users/<id>')
def show(id):
data = {'id': int(id)}
query = "SELECT id, CONCAT_WS(' ', first_name, last_name) AS full_name, email, DATE_FORMAT(created_at, '%M %D, %Y') AS created_at FROM users WHERE id = :id LIMIT 1"
user = mysql.query_db(query, data)
return render_template('show.html', user=user[0])
@app.route('/users/<id>', methods=['POST'])
def update(id):
update_data = {
'id': int(id),
'first_name': request.form['first_name'],
'last_name': request.form['last_name'],
'email': request.form['email']
}
update_query = "UPDATE users SET first_name = :first_name, last_name = :last_name, email = :email, updated_at = NOW() WHERE id = :id"
mysql.query_db(update_query, update_data)
return redirect('/users/' + id)
@app.route('/users/<id>/edit')
def edit(id):
data = {'id': int(id)}
query = "SELECT id, first_name, last_name, email FROM users WHERE id = :id LIMIT 1"
user = mysql.query_db(query, data)
return render_template('edit.html', user=user[0])
@app.route('/users/new')
def new():
return render_template('new.html')
@app.route('/users/create', methods=['POST'])
def create():
first_name = request.form['first_name']
last_name = request.form['last_name']
email = request.form['email']
# FORM VALIDATION
if len(first_name) < 2 or len(last_name) < 2 or not first_name.isalpha() or not last_name.isalpha():
flash('First and last names must be at least 2 characters and only contain letters!')
return redirect('/users/new')
if len(email) < 1:
flash('Email cannot be blank!')
return redirect('/users/new')
elif not EMAIL_REGEX.match(email):
flash('Invalid email address!')
return redirect('/users/new')
# INSERT NEW USER INTO DATABASE
insert_data = {
'first_name': first_name,
'last_name': last_name,
'email': email
}
insert_query = "INSERT INTO users (first_name, last_name, email, created_at, updated_at) VALUES (:first_name, :last_name, :email, NOW(), NOW())"
new_user_id = mysql.query_db(insert_query, insert_data)
return redirect('/users/' + str(new_user_id))
@app.route('/users/<id>/destroy', methods=['POST'])
def destroy(id):
delete_data = {'id': int(id)}
delete_query = "DELETE FROM users WHERE id = :id"
mysql.query_db(delete_query, delete_data)
return redirect('/users')
app.run(debug=True)
| true |
f3c3896904ce6bf0ccb6e310afe9280978af1c30
|
Python
|
DongHuaLu/mdcom
|
/mdcom/MHLogin/analytics/forms.py
|
UTF-8
| 343 | 2.671875 | 3 |
[] |
no_license
|
from django import forms
months = (
(1, 1), (2, 2), (3, 3), (4, 4), (5, 5),
(6, 6), (7, 7), (8, 8), (9, 9), (10, 10),
(11, 11), (12, 12),
)
years = (
(2009, 2009),
(2010, 2010),
(2011, 2011),
)
class MonthForm(forms.Form):
"""MonthForm class
"""
month = forms.ChoiceField(months)
year = forms.ChoiceField(years)
| true |
b971f72dd3a9890ce91c1fb533b3b8ad6bbeb687
|
Python
|
chenxiang97/study_base
|
/python_study/study_mooc/study_4.2.1.py
|
UTF-8
| 240 | 3.28125 | 3 |
[] |
no_license
|
s = "PYTHON"
while s != "":
for c in s :
if c == "T" :
break
print(c, end="")
#去除最后一个字符串
s = s[:-1]
"""
for c in "PYTHON":
if c == "T":
break
print(c, end="")
"""
| true |
27a7317d238d29d240d1dfabc7ebf6e6b3bb89a2
|
Python
|
wdudek82/sqlite_importer
|
/sqllite_importer.py
|
UTF-8
| 734 | 2.875 | 3 |
[] |
no_license
|
from collections import Counter
import sqlite3
import re
import requests
conn = sqlite3.connect('../../sql1.sqlite')
cur = conn.cursor()
trunkate_table = cur.execute('''DELETE FROM Counts;''')
req = (requests.get('http://www.pythonlearn.com/code/mbox.txt').content).decode('utf8')
emails = Counter(re.findall(r'From: \S.+@(\S.+)', req))
for email, count in emails.items():
cur.execute('''INSERT INTO Counts(org, count) VALUES ('{0}', {1})'''
.format(email, int(count)))
conn.commit()
query = 'SELECT * FROM Counts ORDER BY count DESC LIMIT 10'
# Pretty printed top 10 results
rows = ['{:<20} {}'.format(row[0], row[1]) for row in cur.execute(query)]
print('Counts:\n{}'.format('\n'.join(rows)))
cur.close()
| true |
5670ed8dfcc50f803bd4283b2c654eb2092e92ce
|
Python
|
lin-zone/scrapyu
|
/scrapyu/utils.py
|
UTF-8
| 1,439 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
import re
from urllib.parse import urlparse
from selenium import webdriver
def get_base_url(url):
result = urlparse(url)
base_url = '{}://{}'.format(result.scheme, result.netloc)
return base_url
def get_domain(url):
result = urlparse(url)
return result.netloc
_cookies = dict()
def _get_firefox_cookies(url, **kwargs):
options = webdriver.FirefoxOptions()
options.add_argument('--headless')
browser = webdriver.Firefox(options=options, **kwargs)
browser.set_page_load_timeout(60)
browser.get(url)
cookies = browser.get_cookies()
browser.quit()
return cookies
def _raw_cookies_to_scrapy_cookies(cookies):
return {c['name']: c['value'] for c in cookies}
def get_firefox_cookies(url, convert_scrapy_cookies=True, **kwargs):
base_url = get_base_url(url)
key = (base_url, convert_scrapy_cookies)
if key not in _cookies:
cookies = _get_firefox_cookies(base_url, **kwargs)
if convert_scrapy_cookies:
cookies = _raw_cookies_to_scrapy_cookies(cookies)
_cookies[key] = cookies
return _cookies[key]
def re_match(pattern, string):
if not isinstance(pattern, str):
return False
bound = r'\b'
if not pattern.startswith(bound):
pattern = bound + pattern
if not pattern.endswith(bound):
pattern += bound
compile_pattern = re.compile(pattern)
return bool(compile_pattern.match(string))
| true |
c984f7b15c5df08a0f85e6e56187b90fb81d4871
|
Python
|
dombrno/irbasis
|
/test/python/ref/make_unl_safe.py
|
UTF-8
| 3,262 | 2.546875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
from __future__ import print_function
import os
import argparse
import numpy
import h5py
import irlib
import scipy.integrate as integrate
from mpmath import *
class BasisSet(object):
def __init__(self, h5file, prefix_name):
self._h5file = h5file
self._prefix_name = prefix_name
def _write_data(self, path, data):
if path in self._h5file:
del self._h5file[path]
self._h5file[path] = data
def set_info(self, Lambda, dim, statistics):
self._write_data(self._prefix_name + "/info/Lambda", Lambda)
self._write_data(self._prefix_name + "/info/dim", dim)
self._write_data(self._prefix_name + "/info/statistics", \
0 if statistics == "B" else 1)
self._dim = dim
self._Lambda = Lambda
def set_unl(self, unl, l):
dir = self._prefix_name
str_dir = "leven" if l%2 == 0 else "lodd"
self._write_data(dir + "/data/"+str_dir+"/unl", unl)
self._write_data(dir + "/data/"+str_dir+"/l", l)
self._write_data(dir + "/data/"+str_dir+"/unlmax", numpy.amax(abs(unl[:,1])))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog='save.py',
description='Output results to hdf5 file.',
epilog='end',
add_help=True,
)
parser.add_argument('-o', '--output', action='store', dest='outputfile',
default='irbasis.h5',
type=str, choices=None,
help=('Path to output hdf5 file.'),
metavar=None)
parser.add_argument('-i', '--input', action='store', dest='inputfile',
type=str, choices=None,
required=True,
help=('Path to input file.'),
metavar=None)
parser.add_argument('-l', '--lambda', action='store', dest='lambda',
required=True,
type=float, choices=None,
help=('Value of lambda.'),
metavar=None)
parser.add_argument('-p', '--prefix', action='store', dest='prefix',
type=str, choices=None,
default='/',
help=('Data will be stored in this HF5 group.'),
metavar=None)
args = parser.parse_args()
if os.path.exists(args.inputfile):
b = irlib.loadtxt(args.inputfile)
else:
print("Input file does not exist.")
exit(-1)
h5file = h5py.File(args.outputfile, "a")
irset = BasisSet(h5file, args.prefix)
nl = b.dim()
# set info
irset.set_info(b.Lambda(), nl, b.get_statistics_str())
nvec_short = numpy.arange(100)
nvec_long = numpy.array([10**3, 10**4, 10**5, 10**6, 10**7, 10**8])
nvec = numpy.append(nvec_short, nvec_long)
Nodd_max = b.dim()-1 if b.dim()%2==0 else b.dim()-2
unl_odd = numpy.array([ (int(n), b.compute_unl_safe(int(n), Nodd_max)) for n in nvec])
irset.set_unl(unl_odd, Nodd_max)
Neven_max = b.dim()-1 if b.dim()%2==1 else b.dim()-2
unl_even = numpy.array([ (int(n), b.compute_unl_safe(int(n), Neven_max)) for n in nvec])
irset.set_unl(unl_even, Neven_max)
| true |
64514ee6172616461fbc71ab5b05e29987b314f0
|
Python
|
alyssa1996/CodingExercise
|
/Algorithm/이진탐색/[이코테2021] 떡볶이 떡 만들기.py
|
UTF-8
| 346 | 3.140625 | 3 |
[] |
no_license
|
import sys
n,m=map(int,input().split())
rice=list(map(int,sys.stdin.readline().split()))
rice.sort()
start,end=0,rice[-1]
result=0
while start<=end:
mid=(start+end)//2
total=0
for i in rice:
if i>mid:
total+=i-mid
if m<=total:
result=mid
start=mid+1
else:
end=mid-1
print(result)
| true |
81d77d9ed24954a3cf75bed722c57fd1d2062983
|
Python
|
ishikalamba222/tathastu_week_of_code
|
/string.py
|
UTF-8
| 79 | 3.046875 | 3 |
[] |
no_license
|
a=set([1,2,3,4])
b=set([6,7,8,3,1])
print(a.union(b))
print(a.intersection(b))
| true |
e717f32213e058c59888bd7d5e871e8669379d97
|
Python
|
TTheof/potential-winner-nome-randown-dado-pelo-site
|
/aaaaf.py
|
UTF-8
| 377 | 3.390625 | 3 |
[] |
no_license
|
import random
aa = [0,1]
a= random.choice(aa)
# de manha a tarde
almoço= [['só arroz','miojo','carne','ovo cozido','ovo frito'],['maça','café','chá','bolo']]
if a>0:
print ('a tarde eu vou comer/beber')
else:
print ('de manha eu vou comer/beber')
kk = random.choice(almoço[a])
print ('um/uma', kk)
| true |
096817ecc08b129bba7a6c972418d2739dfe137d
|
Python
|
dsmrt/web-crawler
|
/src/utils/test_parse.py
|
UTF-8
| 457 | 3.046875 | 3 |
[] |
no_license
|
from parse import parse_html
def test_parse_html():
html = '''
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="/blog">Blog</a>
<a href="/about">Here is my real website</a>
<a href="https://dsmrt.com">Here is my real website</a>
<a href="https://github.com/dsmrt">@dsmrt on github</a>
</nav>
<h1>Welcome</h1>
<p>My awesome website.</p>
</body>
</html>
'''
# there should only be 2 valid anchor tags
assert len(parse_html(html)) == 2
| true |
296116a909bd45d76ec8a1d09c31290a5a30671a
|
Python
|
tiffanyposs/pythonNotes
|
/programs/listModifiers.py
|
UTF-8
| 137 | 3.375 | 3 |
[] |
no_license
|
x = [1, 2, 3]
print x.pop(1)
#2
print x
#[1,3]
y = [1, 2, 3]
print y.remove(1)
#1
print y
#[2,3]
z = [1, 2, 3]
del(z[1])
print z
#[1,3]
| true |
27e47e409a8018f222157cacb16e39230821ded8
|
Python
|
theNicelander/advent-of-code-2020
|
/day03/day03.py
|
UTF-8
| 1,293 | 3.78125 | 4 |
[] |
no_license
|
import numpy as np
from utils.files import read_data_into_list
class Slope:
def __init__(self, input_path):
self.slope = read_data_into_list(input_path)
self.slope_length = len(self.slope)
self.slope_width = len(self.slope[0])
def broaden_slope(self):
self.slope = [line + line for line in self.slope]
self.slope_width = len(self.slope[0])
def is_tree(self, x, y) -> bool:
if self.slope[y][x] == "#":
return True
return False
def count_trees(self, move_right=3, move_down=1):
count = 0
x = move_right
y = move_down
while self.slope_length > y:
if x >= self.slope_width:
self.broaden_slope()
if self.is_tree(x, y):
count += 1
x += move_right
y += move_down
return count
def count_trees_multiple(self, to_traverse):
return [self.count_trees(right, down) for right, down in to_traverse]
if __name__ == "__main__":
slope = Slope("input.txt")
print(f"Solution 1: {slope.count_trees()}")
to_traverse = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]
multiple_paths = slope.count_trees_multiple(to_traverse)
print(f"Solution 2: {np.product(multiple_paths)}")
| true |
d3d9b6d22491850605907553895dc0396221843e
|
Python
|
roooooon/HW3_ABC
|
/code/complex_numbers.py
|
UTF-8
| 717 | 3.015625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import import_ipynb
from Random import Rand
import math
# In[2]:
class ComplexNumber:
def __init__(self):
self.real = Rand()
self.imaginary = Rand()
def c_In(self, file):
with open(f"{file}.txt", "a+") as f:
f.write(f"Real: {self.real} Imaginary: {self.imaginary} Complex: {self.complex_calculation()} \n")
def complex_calculation(self):
return math.sqrt(self.real * self.real + self.imaginary * self.imaginary)
def c_Out(self, file):
with open(f"{file}.txt", "r") as f:
print(f.read())
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
ac7c2f43db21a9989f0d1d8b09fa0ce6368b8e50
|
Python
|
wysocki-lukasz/CODEME-homework
|
/02_Zmienne i typy/0_Zadanie_1.py
|
UTF-8
| 382 | 3.984375 | 4 |
[] |
no_license
|
#Oblicz koszt wyprawy znając dystans, spalanie na 100km i cenę litra benzyny.
# Załóżmy, że spalanie na 100km wynosi 6,4 l, trasa to 120km, litr benzyny kosztuje 5,04 zł.
fuel_consumption = 6.4
distance = 120
price_per_litr = 5.04
travel_cost = round(float(distance/100 * fuel_consumption * price_per_litr),2)
print(f'Koszt zaplanowanej trasy wyniesie: {travel_cost} ZL')
| true |
7371a4f2fb203dc923dc5fdeef7d84c3870f9678
|
Python
|
anujdutt9/Machine-Learning
|
/Linear Regression/LinearRegressionGradientDescent.py
|
UTF-8
| 3,273 | 4.1875 | 4 |
[] |
no_license
|
# Linear Regression using Gradient Descent
# In this tutorial, we will be writing the code from scratch for Linear Regression using the Second Approach that we studied i.e. using Gradient Descent and then we will move on to plotting the "Best Fit Line".
# So, let's get started.
# Import Dependencies
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
# Load the data using Pandas
df = pd.read_csv('dataset/Insurance-dataset.csv')
# Let's have a look at the data, what it looks like, how many data points are there in the data.
print(df.head())
# Data is in the form of two columns, X and Y. X is the total number of claims and Y represents the claims in thousands of Swedish Kronor.
# Now, let's describe our data.
# Describe the Data
df.describe()
# Load the data in the form to be input to the function for Best Fit Line
X = np.array(df['X'], dtype=np.float64)
y = np.array(df['Y'], dtype=np.float64)
# Cost Function
def cost_Function(m,b,X,y):
return sum(((m*X + b) - y)**2)/(2*float(len(X)))
# Gradient Descent
# X,y: Input Data Points
# m,b: Initial Slope and Bias
# alpha: Learning Rate
# iters: Number of Iterations for which we need to run Gradient Descent.
def gradientDescent(X,y,m,b,alpha,iters):
# Initialize Values of Gradients
gradient_m = 0
gradient_b = 0
# n: Number of items in a row
n = float(len(X))
a = 0
# Array to store values of error for analysis
hist = []
# Perform Gradient Descent for iters
for _ in range(iters):
# Perform Gradient Descent
for i in range(len(X)):
gradient_m = (1/n) * X[i] * ((m*X[i] + b) - y[i])
gradient_b = (1/n) * ((m*X[i] + b) - y[i])
m = m - (alpha*gradient_m)
b = b - (alpha*gradient_b)
# Calculate the change in error with new values of "m" and "b"
a = cost_Function(m,b,X,y)
hist.append(a)
return [m,b,hist]
# Main Function
if __name__ == '__main__':
# Learning Rate
lr = 0.0001
# Initial Values of "m" and "b"
initial_m = 0
initial_b = 0
# Number of Iterations
iterations = 900
print("Starting gradient descent...")
# Check error with initial Values of m and b
print("Initial Error at m = {0} and b = {1} is error = {2}".format(initial_m, initial_b, cost_Function(initial_m, initial_b, X, y)))
# Run Gradient Descent to get new values for "m" and "b"
[m,b,hist] = gradientDescent(X, y, initial_m, initial_b, lr, iterations)
# New Values of "m" and "b" after Gradient Descent
print('Values obtained after {0} iterations are m = {1} and b = {2}'.format(iterations,m,b))
# Calculating y_hat
y_hat = (m*X + b)
print('y_hat: ',y_hat)
# Testing using arbitrary Input Value
predict_X = 76
predict_y = (m*predict_X + b)
print('predict_y: ',predict_y)
# Plot the final Outptu
fig,ax = plt.subplots(nrows=1,ncols=2)
ax[1].scatter(X,y,c='r')
ax[1].plot(X,y_hat,c='y')
ax[1].scatter(predict_X,predict_y,c='r',s=100)
ax[0].plot(hist)
ax[1].set_xlabel('X')
ax[1].set_ylabel('y')
ax[1].set_title('Best Fit Line Plot')
ax[0].set_title('Cost Function Over Time')
plt.show()
| true |
07b6e6d27d4dd0ff29f0f7a2035da654165c6334
|
Python
|
CasCard/FlappyBird
|
/flappybird.py
|
UTF-8
| 4,733 | 2.8125 | 3 |
[] |
no_license
|
import pygame
import os
import time
import neat
import random
WIN_WIDTH = 500
WIN_HEIGHT = 800
pygame.display.set_caption("Flappy Bird")
BIRD_IMGS = [pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))),
pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird2.png"))),
pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird3.png")))]
PIPE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "pipe.png")))
BASE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "base.png")))
BG_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bg.png")))
class Bird:
IMGS = BIRD_IMGS
MAX_ROTATION = 25
ROT_VEL = 20
ANIMATION_TIME = 5
def __init__(self, x, y):
self.x = x
self.y = y
self.tilt = 0
self.tick_count = 0
self.img_count=0
self.vel = 0
self.height = self.y
self.img = self.IMGS[0]
def jump(self):
self.vel = -10.5
self.tick_count = 0
self.height = self.y
def move(self):
self.tick_count += 1
# s=ut+1.5t**2
d = self.vel * self.tick_count + 1.5 * self.tick_count ** 2
if d >= 16:
d = 16
if d < 0:
d -= 2
self.y = self.y + d
if d < 0 or self.y < self.height + 50:
if self.tilt < self.MAX_ROTATION:
self.tilt = self.MAX_ROTATION
else:
if self.tilt > -90:
self.tilt -= self.ROT_VEL
def draw(self, win):
self.img_count += 1
if self.img_count < self.ANIMATION_TIME:
self.img = self.IMGS[0]
elif self.img_count < self.ANIMATION_TIME * 2:
self.img = self.IMGS[1]
elif self.img_count < self.ANIMATION_TIME * 3:
self.img = self.IMGS[2]
elif self.img_count < self.ANIMATION_TIME * 4:
self.img = self.IMGS[1]
elif self.img_count == self.ANIMATION_TIME * 4 + 1:
self.img = self.IMGS[0]
self.img_count = 0
if self.tilt <= -80:
self.img = self.IMGS[1]
self.img_count = self.ANIMATION_TIME * 2
rotated_image = pygame.transform.rotate(self.img, self.tilt)
new_rect = rotated_image.get_rect(center=self.img.get_rect(topleft=(self.x, self.y)).center)
win.blit(rotated_image, new_rect.topleft)
def get_mask(self):
return pygame.mask.from_surface(self.img)
class Pipe:
GAP=200
VEL=5
# the heigth will be random
def __init__(self,x):
self.x=x
self.height=0
self.gap=100
self.top=0
self.bottom=0
self.PIPE_TOP=pygame.transform.flip(PIPE_IMG,False,True)
self.PIPE_BOTTOM=PIPE_IMG
self.passed=False
self.set_heigth()
def set_heigth(self):
self.height=random.randrange(50,450)
self.top=self.height-self.PIPE_TOP.get_height()
self.bottom=self.height+self.GAP
def move(self):
self.x -= self.VEL
def draw(self,win):
win.blit(self.PIPE_TOP,(self.x,self.top))
win.blit(self.PIPE_BOTTOM,(self.x,self.bottom))
def collide(self,bird):
bird_mask=bird.get_mask()
top_mask=pygame.mask.from_surface(self.PIPE_TOP)
bottom_mask=pygame.mask.from_surface(self.PIPE_BOTTOM)
top_offset=(self.x-bird.x,self.top-round(bird.y))
bottom_offset=(self.x-bird.x,self.bottom-round(bird.y))
b_point=bird_mask.overlap(bottom_mask,bottom_offset)
t_point=bird_mask.overlap(top_mask,top_offset)
if t_point or b_point:
return True
return False
class Base:
VEL=5
WIDTH=BASE_IMG.get_width()
IMG=BASE_IMG
def __init__(self,y):
self.y=y
self.x1=0
self.x2=self.WIDTH
def move(self):
self.x1-=self.VEL
self.x2-=self.VEL
if self.x1 + self.WIDTH<0:
self.x1=self.x2+self.WIDTH
if self.x2 + self.WIDTH<0:
self.x2=self.x1+self.WIDTH
def draw(self,win):
win.blit(self.IMG,(self.x1,self.y))
win.blit(self.IMG,(self.x2,self.y))
def draw_window(win, bird):
win.blit(BG_IMG, (0, 0))
bird.draw(win)
pygame.display.update()
def main():
bird = Bird(200, 200)
win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
clock=pygame.time.Clock()
run = True
while run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# bird.move()
draw_window(win, bird)
pygame.quit()
quit()
main()
| true |
bf67e37c0a817c689b63d8e1beb3e794a6aa7ed0
|
Python
|
Antiger2005/mst
|
/tools/check_with_diff.py
|
UTF-8
| 2,473 | 2.9375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
from check_output import extract_answer
from mstutil import get_path_to_checker_binary, get_path_to_mst_binary, get_path_to_project_root
from mstutil import die, quiet_remove, random_tmp_filename
import os, sys
def main(argv=sys.argv):
if len(argv) != 2:
die("""usage: check_with_diff.py INPUT_GRAPH
Checks the current mst for a given input file and reports the diff, if any. It
does not do anything smart in terms of caching the correctness checker's output,
so it will be recomputed every time this is run.
""")
else:
input_graph = argv[1]
if not os.path.exists(input_graph):
die("%s not found" % input_graph)
# get our mst output
mst = get_path_to_mst_binary(make_sure_it_exists=False)
mst_out = random_tmp_filename(10)
if os.system('%s %s > %s' % (mst, input_graph, mst_out)) != 0:
quiet_remove(mst_out)
die("failed to run mst (or exited with an error code)")
# get the checker's output
checker = get_path_to_checker_binary(make_sure_it_exists=True)
checker_out = random_tmp_filename(10)
if os.system('%s %s true > %s' % (checker, input_graph, checker_out)) != 0:
quiet_remove(mst_out)
quiet_remove(checker_out)
die("failed to run checker (or exited with an error code)")
# check just the MST weight first
mst_w = extract_answer(mst_out)
checker_w = extract_answer(checker_out)
fmt = '%.1f' # tolerance to 1 decimal place
str_mst_w = fmt % mst_w
str_checker_w = fmt % checker_w
if str_mst_w == str_checker_w:
print 'Weights match! %s %s' % (str_mst_w, str_checker_w)
quiet_remove(mst_out)
quiet_remove(checker_out)
return 0
else:
print 'Weight mistmatch, comparing vertices!! (checker_mst (%s) - our_mst (%s) = %s)' % (str(checker_w), str(mst_w), str(checker_w - mst_w))
# sort them
mst_out2 = random_tmp_filename(10)
checker_out2 = random_tmp_filename(10)
sort_and_order = get_path_to_project_root() + 'src/input/sort_and_order.py '
os.system(sort_and_order + mst_out + ' 1 > ' + mst_out2)
os.system(sort_and_order + checker_out + ' 1 > ' + checker_out2)
# compare them
os.system('diff %s %s && echo Edges are the same!' % (checker_out2, mst_out2))
quiet_remove(mst_out)
quiet_remove(mst_out2)
quiet_remove(checker_out)
quiet_remove(checker_out2)
return 0
if __name__ == "__main__":
sys.exit(main())
| true |
86d28f536aa7cba0f006c0d5912924a25c2e1ef4
|
Python
|
dixonaws/PowerCo
|
/PowerCoAPITest.py
|
UTF-8
| 2,581 | 2.875 | 3 |
[] |
no_license
|
__author__ = 'dixonaws@amazon.com'
# import statements
from sys import argv
import urllib2
import urllib
import time
import sys
import json
def getInvoice(invoiceNumber):
invoiceUrl="http://localhost:8080/RESTTest/api/invoices/" + str(invoiceNumber)
startTime=int(round(time.time() * 1000))
endTime=0;
sys.stdout.write("GETting invoice... ")
opener=urllib2.build_opener()
# ask the API to return JSON
opener.addheaders=[('Accept', 'application/json')]
try:
# our response string should result in a JSON object
response = opener.open(invoiceUrl).read()
endTime=int(round(time.time() * 1000))
print "done (" + str(endTime-startTime) + " ms)."
except urllib2.HTTPError:
print "Error in GET..."
# decode the returned JSON response into JSONIaccount (a Python dict object)
JSONinvoice = json.loads(str(response))
return(JSONinvoice)
### end getInvoice()
def getAccount(accountNumber):
accountUrl="http://localhost:8080/RESTTest/api/accounts/"
startTime=int(round(time.time() * 1000))
endTime=0;
sys.stdout.write(url + ": GETting account... ")
opener=urllib2.build_opener()
# ask the API to return JSON
opener.addheaders=[('Accept', 'application/json')]
response=""
try:
# our response string should result in a JSON object
response=opener.open(url).read()
endTime=int(round(time.time() * 1000))
print "done (" + str(endTime-startTime) + " ms)."
except urllib2.HTTPError:
print "Error in GET..."
# decode the returned JSON response into JSONIaccount (a Python dict object)
JSONaccount = json.loads(str(response))
return(JSONaccount)
### end getAccount()
## Main
script, args0 = argv
# take the fileName as the first argument, and the endpoint URL as the second argument
baseurl=args0
print "PowerCo API Test, v1.1"
url=baseurl
# retrieve account ID 1
JSONaccount=getAccount(1)
print JSONaccount
# decode the invoices from the account
JSONinvoices=JSONaccount['invoices']
# get the number of invoices associated with this account
intNumberOfInvoices=len(JSONinvoices)
# count the number of invoices in this account
print("I found " + str(intNumberOfInvoices) + " invoices associated with this account")
# loop through the invoices asspociated with this account and print out the amount due
for invoices in JSONinvoices:
invoice=getInvoice(invoices['id'])
print("Invoice id " + str(invoice['id']) + ": " + "$" + str(invoice['amountDollars']) + "." + str(invoice['amountCents']))
| true |
ba9e0506e21dd573e17525591ee6e2a318392973
|
Python
|
ahmad307/NearestPlace
|
/NearestPlace/locations/views.py
|
UTF-8
| 3,375 | 2.625 | 3 |
[] |
no_license
|
from django.shortcuts import render, HttpResponse
from locations.gmaps import LocationFinder
from locations.models import Session, Location
from django.core.exceptions import ValidationError
from django.core.exceptions import ObjectDoesNotExist
import json
import secrets
import string
from decimal import *
def home(request):
api_key = open('D:/Projects/secretkey/gmaps_key.txt', 'r').read()
return render(request,'home/index.html', {'api_key': api_key})
def get_location(request):
# TODO: Return 'Nothing found' if there is no returned data
"""Receives POST request and returns the 'Nearest Place'."""
if request.method == 'POST':
code = request.POST.get('code')
meeting = None
try:
meeting = Session.objects.get(code=code)
except ObjectDoesNotExist:
return HttpResponse(json.dumps({'message': 'Incorrect Code'}),
content_type='application/json')
location_finder = LocationFinder(meeting)
result_place = location_finder.get_nearest_place()
return HttpResponse(json.dumps({
'name': result_place['name'],
'address': result_place['formatted_address'],
'rating': result_place['rating']
}), content_type='application/json')
def create_session(request):
"""Creates a session for saving locations in the database."""
if request.method == 'POST':
# Create pseudo-unique random string of numbers and capital letters
code = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(6))
session = Session(
name=request.POST.get('meeting_name'),
code=code,
place_type=request.POST.get('place_type'),
city=request.POST.get('city')
)
# Validate data before saving to Database
try:
session.full_clean()
session.save()
except ValidationError:
return HttpResponse(json.dumps({'message': 'ValidationError'}),
content_type='application/json')
return HttpResponse(json.dumps({'message': 'success','code': code}),
content_type='application/json')
def add_location(request):
"""Adds a new location to the given meeting and saves it in DB."""
if request.POST:
# Get request data
code = request.POST.get('code')
lat = round(Decimal(request.POST.get('lat')), 6)
lng = round(Decimal(request.POST.get('lng')), 6)
# Create object of location with the given session's code
try:
session = Session.objects.get(code=code)
except ObjectDoesNotExist:
return HttpResponse(json.dumps({'message': 'Incorrect Code'}),
content_type='application/json')
location = Location(
longitude=lng,
latitude=lat,
session=session
)
# Validate data before saving to Database
try:
location.full_clean()
location.save()
result = {'message': 'Success'}
except ValidationError as e:
result = {'message': 'Validation Error'}
finally:
return HttpResponse(json.dumps(result),
content_type='application/json')
| true |
b4a5092ecafcd6304fd15774cf9369eef07b4ecb
|
Python
|
DenisPitsul/SoftServe_PythonCore
|
/video2/Task1.py
|
UTF-8
| 178 | 4.125 | 4 |
[] |
no_license
|
fuelCapacity = float(input("Input fuel capacity: "))
fuelAmount = float(input("Input fuel amount: "))
if fuelCapacity*0.1 > fuelAmount:
print("Red")
else:
print("Green")
| true |
9fb879e762bd95c6c858afc627988f3ad95643fd
|
Python
|
dlemvigh/GoogleCodeJam
|
/PythonCodeJam/PythonApplication1/rev_word.py
|
UTF-8
| 141 | 2.96875 | 3 |
[] |
no_license
|
def solve(file):
line = file.readline()[:-1]
words = line.split(" ")
words.reverse()
line = ' '.join(words)
return line
| true |
30a1a5cfad2832e3deaa83403f7c18ed47a677e8
|
Python
|
domtom1126/bail_flask
|
/app.py
|
UTF-8
| 1,886 | 2.625 | 3 |
[] |
no_license
|
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, RadioField, SubmitField
from wtforms.validators import InputRequired
from bail import X_test, y_test, plea_list
import joblib
# SECTION Class for input form
class BailForm(FlaskForm):
class Meta:
def render_field(self, field, render_kw):
render_kw.setdefault('required', True)
return super().render_field(field, render_kw)
input_plea_orc = SelectField(choices=plea_list)
input_race = RadioField('Race', choices=['White', 'Black', 'Hispanic', 'Asian', 'Other'], validators=[InputRequired()])
input_priors = StringField('Prior Cases', validators=[InputRequired()])
# !SECTION End form class
# NOTE This is where the model for the bail should be loaded
model = joblib.load('bail_model')
app = Flask(__name__)
# NOTE This needs to be here for FlaskForms
app.config['SECRET_KEY'] = '_+aro@(rjwcan9*=l%&(l=cs7mzbh-&5w1g%7)c3*i3ms(vzvf'
@app.route('/', methods=['GET', 'POST'])
def home():
form = BailForm()
plea_orc_list = plea_list
return render_template('index.html', form=form, plea_orc_list=plea_list)
@app.route('/predict', methods=['GET', 'POST'])
def predict():
form = BailForm()
# TODO Import unique plea list
plea_orc_list = plea_list
# SECTION Race transform
# TODO Find out what races are transformed as (ex if White: white = 4)
# !SECTION
user_input = [[form.input_plea_orc.data, form.input_race.data, form.input_priors.data]]
# SECTION predict output and show accuracy score
output = model.predict(user_input)
score = model.score(X_test, y_test)
# !SECTION
return render_template('index.html', prediction_text ='Bail: {}'.format(output), accuracy='Algorithm accuracy: {:.0%}'.format(score), form=form, plea_orc_list=plea_list)
app.run(debug=True)
| true |
fe2c90c5adaf7286499a451e83292fcbd08355e5
|
Python
|
srisaimacha13/rg_assignments
|
/Assign_2/avg_of_positive_int_instring.py
|
UTF-8
| 886 | 3.796875 | 4 |
[] |
no_license
|
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
import re
try:
input_string = raw_input('Enter a String:\n')
if not input_string:
raise MyError('String is empty.')
list_of_integers = re.findall('-?\d+',input_string)
if not list_of_integers:
raise MyError('String contains all characters or special characters.')
list_of_integers = list(map(float,list_of_integers))
def avg(list_of_integers):
count=0
sum=0
for x in list_of_integers:
if x>0:
count=count+1
sum=sum+x
if count == 0:
raise MyError('No positive integers in string')
return sum/count
print avg(list_of_integers)
except MyError as e:
print e
| true |
137d289a6de9926bf66ba5775034d2fb18a1e7f6
|
Python
|
shine914/mutual_fund_network
|
/3.3-stock_status_summary.py
|
UTF-8
| 3,213 | 2.5625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
#avoid chinese mess
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import glob,os
import xlrd
import networkx as nx
from networkx.algorithms import bipartite
import numpy as np
import pandas as pd
import pandas as pd
import numpy as np
import glob,os
import math
from math import log10
import collections
from collections import Counter
import matplotlib.pyplot as plt
import scipy
from scipy import stats, integrate #draw density line
import seaborn as sns
"""
delete rows that contain n NaN values
"""
def drop_emptycell(df):
print 'original data row number', df.shape[0] #Count_Row
df.replace('', np.nan, inplace=True)#删除原始数据中的空白单元格,不是NaN
df.dropna(axis=0, inplace=True)
print 'after delete missing data, row number is', df.shape[0] #Count_Row
return df
def drop_duplicate(df): #after drop empty cells
df = df.drop_duplicates() #df.drop_duplicates(subset[])
print 'after delete duplicate data, row number is', df.shape[0] #Count_Row
#print df
return df
"""
label stock status
"""
def stock_status(df, col_name1, col_name2):
if df[col_name1] == 1:
return 'upper_limit'
if df[col_name1] == -1:
return 'lower_limit'
if df[col_name1] == 0:
if df[col_name2] == u'停牌一天':
return 'suspension'
else:
return 'other'
"""
run
"""
os.chdir('/Users/shine/work_hard/financial_network/data/status_wind_612_710')
FileList = glob.glob('*.xlsx') #for workingfile in filelist
print FileList
print "FileList length is", len(FileList) #共20个文件
df_len = pd.DataFrame()
summary_lower = pd.DataFrame()
summary_sus = pd.DataFrame()
summary_lower_sus = pd.DataFrame()
labels = list() #boxplot的横轴,即交易日
length = pd.DataFrame()
for workingfile in FileList:
print workingfile,'is working now'
filename = workingfile.split('0150')[1]
filename = filename .split('.')[0]#只保留日期,不然plot出来的图都重叠了
print 'filename is', filename
os.chdir('/Users/shine/work_hard/financial_network/data/status_wind_612_710')
status = pd.ExcelFile(workingfile)
status = pd.read_excel(status, 'Wind资讯'.decode('utf-8'))
status = pd.DataFrame(status)
status.columns = ['source', 'stock_name', 'limit_ori', 'sus_reason', 'sus_days', 'sus_ori']
status['limit'] = status.apply (lambda df: stock_status(df, 'limit_ori', 'sus_ori'), axis=1)
#print len(status) ##经过drop_emptycell和drop_duplicate验证,status中有很多missing data, 如果只提取分析用的几列数可能会改善
status = status[['source', 'stock_name','limit']]
#print '------------'
df = drop_emptycell(status)
df = drop_duplicate(df)
df_lower = df[df.limit == 'lower_limit']
#print df_lower.iloc[1:20,:]
df_sus = df[df.limit == 'suspension']
#print df_sus.iloc[1:20,:]
df_lower_sus = df[df.limit == 'lower_limit'].append(df[df.limit == 'suspension'])
#print df_lower_sus.iloc[1:20,:]
length1 = pd.DataFrame(data={'date': [filename],
'total': [len(df)],
'lower': [len(df_lower)],
'sus': [len(df_sus)],
'lower_sus': [len(df_lower_sus)]
})
length = length.append(length1)
length.to_excel('status_ratio.xlsx', sheet_name='Sheet1')
| true |
fdf86d8b3c982927ca16c6684f4711034e5d4261
|
Python
|
autasi/tensorflow_examples
|
/tools/mnist_dump.py
|
UTF-8
| 1,341 | 2.53125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import pickle
import os
from config import mnist_data_folder
def convert(imgs, img_size, data_format="channels_first"):
if data_format == "channels_first":
data = np.reshape(imgs, [imgs.shape[0], 1, img_size, img_size])
else:
data = np.reshape(imgs, [imgs.shape[0], img_size, img_size, 1])
return data
def main(out_folder = "/home/ucu/Work/git/mnist/data/",
data_format = "channels_first"):
mnist = input_data.read_data_sets(out_folder, one_hot=True)
img_size = 28
tr_x = convert(mnist.train.images, img_size, data_format=data_format)
tr_y = mnist.train.labels
te_x = convert(mnist.test.images, img_size, data_format=data_format)
te_y = mnist.test.labels
val_x = convert(mnist.validation.images, img_size, data_format=data_format)
val_y = mnist.validation.labels
data = {'train': (tr_x, tr_y), 'test': (te_x, te_y), 'validation': (val_x, val_y)}
if data_format == "channels_first":
suf = "nchw"
else:
suf = "nhwc"
fname = os.path.join(out_folder, "data_" + suf + ".pkl")
with open(fname, "wb") as f:
pickle.dump(data, f)
if __name__ == "__main__":
main(out_folder=mnist_data_folder, data_format="channels_last")
| true |
642aedb66a4aaac409a40e5ae1a3c85b4b84fe7a
|
Python
|
Anthonymcqueen21/Algorithms-in-Python
|
/Python Interview Questions/Reverse_string.py
|
UTF-8
| 558 | 3.9375 | 4 |
[] |
no_license
|
# Here you are given a string as an input and you have to return the input and make sures its reversed
# Python Implementation
class Solutiion(object):
def reverseString(self,s):
string = list(s)
i, j = 0, len(string) - 1
while i - j:
string[i], string[j] = string[j] = string[i]
i += 1
j -= 1
return "".join(string)
# Time: O(n)
# Space 0(n)
class Solution2(object):
def reverseString(self, s):
return s[::-1]
| true |
7bf704c5f68aa33cc56c80004fb92bb1bccfb09d
|
Python
|
Jenkins-manager/Jenkins
|
/Server/q_and_a_script.py
|
UTF-8
| 4,660 | 2.8125 | 3 |
[] |
no_license
|
"""
run this file to create and implmenet a new question /
answer pair. enter the following details to create a
complete pair:
- question body
- answer body (should be a function ideally)
- question keywords (at least one)
"""
import sys
import ast
import django
django.setup()
from model.file_processor import FileProcessor
from questions.models import Question
from answers.models import Answer
HELP_STRING = ("run this file to create and implmenet a new question" +
"answer pair.\n enter the following details to create a" +
"complete pair:\n" +
" - question body\n" +
" - answer body (should be a function ideally)\n" +
" - question keywords (at least one)\n")
ORG_TRAIN_SET = FileProcessor.read_file('machine_learning/data/value_set.jenk')
ORG_IN_SET = FileProcessor.read_file('machine_learning/data/output_set.jenk')
ORG_KEY_SET = ast.literal_eval(FileProcessor.read_file('./key_words/keywords.jenk'))
ORG_Q_LIST = FileProcessor.read_file('db/question_list.jenk').split('|')
ORG_Q_LIST = map(lambda w: ast.literal_eval(w), ORG_Q_LIST)
ORG_A_LIST = FileProcessor.read_file('db/answer_list.jenk').split('|')
ORG_A_LIST = map(lambda w: ast.literal_eval(w), ORG_A_LIST)
def revert_data_to_reset():
FileProcessor.write_file('key_words/keywords.jenk', str(ORG_KEY_SET), 'w')
FileProcessor.write_file('machine_learning/data/value_set.jenk', str(ORG_TRAIN_SET), 'w')
FileProcessor.write_file('machine_learning/data/output_set.jenk', str(ORG_IN_SET), 'w')
FileProcessor.write_file('db/question_list.jenk', str(ORG_Q_LIST), 'w')
FileProcessor.write_file('db/answer_list.jenk', str(ORG_A_LIST), 'w')
def write_keyword_data(q_keyword, q_address):
key_arr = q_keyword.split(" ")
key_arr = map(lambda w: w.replace('_', ' '), key_arr)
new_keywords = ORG_KEY_SET
try:
for word in key_arr:
new_keywords[word] = q_address
except Exception, e:
raise e
finally:
FileProcessor.write_file('key_words/keywords.jenk', str(keywords), 'w')
def add_new_data_to_db_files(q_new, a_new):
q_new_list = ORG_Q_LIST
a_new_list = ORG_A_LIST
q_new_list.append({'body': q_new.body, 'address': q_new.address})
a_new_list.append({'body': a_new.body, 'address': a_new.address})
FileProcessor.write_file('db/question_list.jenk', "|".join(str(x) for x in q_new_list), 'w')
FileProcessor.write_file('db/answer_list.jenk', "|".join(str(x) for x in a_new_list), 'w')
def add_to_training_set(q_address, a_address):
training_set = ORG_TRAIN_SET.split(",")
input_set = ORG_IN_SET.split(",")
training_set.append(float(q_address))
input_set.append(float(a_address))
input_set = ",".join(str(x) for x in input_set)
training_set = ",".join(str(x) for x in training_set)
FileProcessor.write_file('machine_learning/data/value_set.jenk', str(training_set), 'w')
FileProcessor.write_file('machine_learning/data/output_set.jenk', str(input_set), 'w')
def q_and_a_creation(q_body, a_body):
length = len(Question.objects.all())
q_new = Question(body=q_body, address=(length + 1))
a_new = Answer(body=a_body, address=(length + 1))
add_new_data_to_db_files(q_new, a_new)
q_new.save()
a_new.save()
return [q_new.address, a_new.address]
print("This is the runner for adding questions and answers to the application\n" +
"Please read the included instructions for more infomation, this can be done"+
"by entering HELP! at any time, press QQQ to close the script at any time\n"+
"Enter a question to begin:")
while True:
try:
command = sys.stdin.readline().rstrip()
if command == "QQQ":
break
elif command == "HELP!":
print(HELP_STRING)
next
q_body = command
print("Now enter an answer please:")
command = sys.stdin.readline().rstrip()
a_body = command
print("now enter your keywords:")
command = sys.stdin.readline().rstrip()
keywords = command
if q_body == "" or a_body == "" or keywords == "":
raise Exception("you must enter all three fields to continue")
address_pair = q_and_a_creation(q_body, a_body)
write_keyword_data(keywords, address_pair[0])
add_to_training_set(address_pair[0], address_pair[1])
print("saved sucessfully")
break
except Exception, e:
print("an error occured, resetting files..")
revert_data_to_reset()
print("your error message is:")
raise e
| true |
bb1ac084fd16c1c817496113db8820741c65205c
|
Python
|
Chris-Quant/TeamCo
|
/7. Machine Learning Prediction/main_ml.py
|
UTF-8
| 6,539 | 3.015625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 7 16:07:34 2016
@author: ZFang
"""
from datetime import datetime
import pandas_datareader.data as wb
import pandas as pd
import numpy as np
from sklearn import svm
def cal_return(p):
daily_return = (p['Adj Close'] - p['Adj Close'].shift(1))/p['Adj Close']
return daily_return
def get_etf(stocklist, start):
'''
Pull the data using Yahoo Fiannce API, given ticker(could be a list) and start date
'''
start = datetime.strptime(start, '%m/%d/%Y')
# end = datetime.strptime(end, '%m/%d/%Y')
end = datetime.today()
p = wb.DataReader(stocklist,'yahoo',start,end)
p['Return'] = cal_return(p)
return p
def gen_ind(dataframe, n=10):
'''
Generate the technical indicator from price
'''
dataframe['SMA_10'] = dataframe['Adj Close'].rolling(window=n).mean()
mo_arr = dataframe['Adj Close'][9:].values - dataframe['Adj Close'][:-9].values
dataframe['Momentum'] = np.zeros(len(dataframe.index))
dataframe.ix[9:,'Momentum'] = mo_arr
dataframe['LL'] = dataframe['Adj Close'].rolling(window=n).min()
dataframe['HH'] = dataframe['Adj Close'].rolling(window=n).max()
dataframe['stoch_K'] = 100 * (dataframe['Adj Close']- dataframe['LL'])/(dataframe['HH']- dataframe['LL'])
for i in range(9,len(dataframe.index)):
dataframe.ix[i,'WMA_10'] = (10*dataframe.ix[i,'Adj Close']+9*dataframe.ix[i-1,'Adj Close']+
8*dataframe.ix[i-2,'Adj Close']+7*dataframe.ix[i-3,'Adj Close']+
6*dataframe.ix[i-4,'Adj Close']+5*dataframe.ix[i-5,'Adj Close']+
4*dataframe.ix[i-6,'Adj Close']+3*dataframe.ix[i-7,'Adj Close']+
2*dataframe.ix[i-8,'Adj Close']+dataframe.ix[i-9,'Adj Close'])/sum(range(1,11,1))
dataframe['EMA_12'] = dataframe['Adj Close'].ewm(span=12).mean()
dataframe['EMA_26'] = dataframe['Adj Close'].ewm(span=26).mean()
dataframe['DIFF'] = dataframe['EMA_12'] - dataframe['EMA_26']
dataframe['MACD'] = np.zeros(len(dataframe.index))
dataframe['A/D'] = np.zeros(len(dataframe.index))
for i in range(1,len(dataframe.index)):
dataframe.ix[i,'MACD'] = dataframe.ix[i-1,'MACD'] + 2/(n+1)*(dataframe.ix[i,'DIFF']-dataframe.ix[i-1,'MACD'])
dataframe.ix[i,'A/D'] = (dataframe.ix[i,'High']-dataframe.ix[i-1,'Adj Close'])/(dataframe.ix[i,'High']-dataframe.ix[i,'Low'])
return dataframe
def gen_op_df(dataframe):
'''
Generate binary indicator based on technical indicator value
'''
op_df = pd.DataFrame(np.zeros((len(dataframe),10)), columns=['SMA_10', 'Momentum',
'stoch_K', 'WMA_10', 'MACD', 'A/D', 'Volume', 'Adj Close', 'Adj Close Value', 'Return'])
op_df.index = dataframe.index
op_df['Adj Close Value'] = dataframe['Adj Close']
op_df['Return'] = dataframe['Return']
op_df['Year'] = dataframe.index.year
for i in range(10,len(dataframe.index)-1):
op_df.ix[i,'SMA_10']=1 if (dataframe.ix[i,'Adj Close']>dataframe.ix[i,'SMA_10']) else -1
op_df.ix[i,'WMA_10']=1 if (dataframe.ix[i,'Adj Close']>dataframe.ix[i,'WMA_10']) else -1
op_df.ix[i,'MACD']=1 if (dataframe.ix[i,'MACD']>dataframe.ix[i-1,'MACD']) else -1
op_df.ix[i,'stoch_K']=1 if (dataframe.ix[i,'stoch_K']>dataframe.ix[i-1,'stoch_K']) else -1
op_df.ix[i,'Momentum']=1 if (dataframe.ix[i,'Momentum']>0) else -1
op_df.ix[i,'A/D']=1 if (dataframe.ix[i,'A/D']>dataframe.ix[i-1,'A/D']) else -1
op_df.ix[i,'Volume']=1 if (dataframe.ix[i,'Volume']>dataframe.ix[i-1,'Volume']) else -1
op_df.ix[i,'Adj Close']=1 if (dataframe.ix[i+1,'Adj Close']/dataframe.ix[i,'Adj Close']>1) else -1
# drop first 10 columns due to nan
op_df = op_df[10:]
return op_df
def tune_para(dataframe, i):
# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
columns = ['SMA_10','Momentum','stoch_K','WMA_10','MACD','A/D','Volume']
X = dataframe[columns].as_matrix()
y = dataframe['Adj Close'].as_matrix()
X_train = X[i-200:i]
y_train = y[i-200:i]
X_test = X[i:i+1]
y_test = y[i:i+1]
### Train four kinds of SVM model
C = 1 # SVM regularization parameter
svc = svm.SVC(cache_size = 1000, kernel='linear', C=C).fit(X_train, y_train)
rbf_svc = svm.SVC(cache_size = 1000, kernel='rbf', gamma=0.7, C=C).fit(X_train, y_train)
poly_svc = svm.SVC(cache_size = 1000, kernel='poly', degree=3, C=C).fit(X_train, y_train)
lin_svc = svm.LinearSVC(loss='squared_hinge', penalty='l1', dual=False, C=C).fit(X_train, y_train)
Y_result = y_test
### Make the prediction
for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):
pred = clf.predict(X_test)
Y_result = np.vstack((Y_result, np.array(pred))) # append prediction on Y_result
return Y_result.T
def svm_result(op_df):
result_arr = np.zeros((1,5))
for i in range(200, len(op_df.index)):
Y_result = tune_para(op_df, i)
result_arr = np.append(result_arr, Y_result, axis=0)
Y_result_df = pd.DataFrame(result_arr, columns = ['True value', 'SVC with linear kernel','LinearSVC (linear kernel)', 'SVC with RBF kernel','SVC with polynomial'])
Y_result_df['Return'] = op_df.ix[199:,'Return'].values
return Y_result_df
if __name__ == '__main__':
new_file_name = 'appl_op.csv'
price_df = get_etf('AMZN','12/05/2010')
indicator_df = gen_ind(price_df, n=10)
op_df = gen_op_df(indicator_df)
# Save the file and read it next time
op_df.to_csv(new_file_name, index=True, header=True, index_label='index')
op_df = pd.read_csv(new_file_name, index_col='index')
Y_result_df = svm_result(op_df)
### Calculate the return based on the strategy
Accuracy = pd.DataFrame(np.zeros((2,5)), columns = ['True value','SVC with linear kernel','LinearSVC (linear kernel)',
'SVC with RBF kernel','SVC with polynomial'])
for i in range(5):
Accuracy.iloc[0,i] = sum(Y_result_df.iloc[:,0]==Y_result_df.iloc[:,i])/len(Y_result_df.iloc[:,0])
if i==0:
Accuracy.iloc[1,i] = np.prod(1+ Y_result_df['Return'][2:].values)
else:
Accuracy.iloc[1,i] = np.prod(1+ Y_result_df.iloc[1:-1,i].values*Y_result_df['Return'][2:].values)
# bol = 1+ Y_result_df.iloc[1:-1,i] * Y_result_df['Return'].shift(1)[2:]
# bol.prod()
| true |
867f3dae4e7945b3f3613e6ac51a6fec665ce5cf
|
Python
|
elenarangelova/Phyton-course-in-Softuni
|
/lesson2/5task.py
|
UTF-8
| 3,686 | 3.4375 | 3 |
[] |
no_license
|
#Да си направим програмка за запознанства.
#В едно list-че сме си съчинили малко информация за момиченца и момченца.
# От данните, програмата трябва да изведе резултати кои хора биха си паснали,
# съгласно следните правила:
#момиченце с момченце; ако сте по-свободомислещи, можете да комбинирате
# и момченце с момченце, но все пак да има някакво правило :о);
#трябва да имат поне един общ интерес;
#Примерен резултат:
#Мария и Георги - общ интерес: плуване
people = [
{
'name': "Мария",
'interests': ['пътуване', 'танци', 'плуване', 'кино'],
'gender': "female",
},
{
'name': "Диана",
'interests': ['мода', 'спортна стрелба', 'четене', 'скандинавска поезия'],
'gender': "female",
},
{
'name': "Дарина",
'interests': ['танци', 'покер', 'история', 'софтуер'],
'gender': "female",
},
{
'name': "Лилия",
'interests': ['покер', 'автомобили', 'танци', 'кино'],
'gender': "female",
},
{
'name': "Галя",
'interests': ['пътуване', 'автомобили', 'плуване', 'баскетбол'],
'gender': "female",
},
{
'name': "Валерия",
'interests': ['плуване', 'покер', 'наука', 'скандинавска поезия'],
'gender': "female",
},
{
'name': "Ина",
'interests': ['кино', 'лов със соколи', 'пътуване', 'мода'],
'gender': "female",
},
{
'name': "Кирил",
'interests': ['баскетбол', 'автомобили', 'кино', 'наука'],
'gender': "male",
},
{
'name': "Георги",
'interests': ['автомобили', 'футбол', 'плуване', 'танци'],
'gender': "male",
},
{
'name': "Андрей",
'interests': ['футбол', 'скандинавска поезия', 'история', 'танци'],
'gender': "male",
},
{
'name': "Емил",
'interests': ['летене', 'баскетбол', 'софтуер', 'наука'],
'gender': "male",
},
{
'name': "Димитър",
'interests': ['футбол', 'лов със соколи', 'автомобили', 'баскетбол'],
'gender': "male",
},
{
'name': "Петър",
'interests': ['пътуване', 'покер', 'баскетбол', 'лов със соколи'],
'gender': "male",
},
{
'name': "Калоян",
'interests': ['история', 'покер', 'пътуване', 'автомобили'],
'gender': "male",
},
]
girls = []
boys = []
for person in people:
if person.get('gender', None) == 'male' :
boys.append(person)
else:
girls.append(person)
for boy in boys:
for girl in girls:
boy_interests = set(boy['interests'])
girl_interests = set(girl['interests'])
if boy_interests & girl_interests:
print("{} и {} - интереси: {}".format(boy['name'], girl['name'], boy_interests & girl_interests))
break
| true |
1267d97b762caaa0bbebbfe53d5452cbb07d19e3
|
Python
|
tecWang/knowledges-for-cv
|
/剑指offer/Codes/31_把数组排成最小的数_贪心.py
|
UTF-8
| 331 | 3.515625 | 4 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
arr = [num for num in numbers]
arr.sort()
print(arr)
return "".join([str(a) for a in arr])
print(Solution().PrintMinNumber([1, 12, 123]))
print(Solution().PrintMinNumber([3, 32, 321]))
| true |
391ecaf2c5a2c6cb7d0bdfbedd386c7c3f624daa
|
Python
|
BishuPoonia/coding
|
/Python/diagonal_difference.py
|
UTF-8
| 506 | 3.84375 | 4 |
[] |
no_license
|
def diagonal_difference(arr):
r1, r2 = 0, 0
for i in range(n):
T = list(map(int, arr[i]))
r1 += T[i]
r2 += T[-i -1]
return abs(r1-r2)
n = 3
arr = [[11, 2, 4],
[4, 5, 6],
[10, 8, -12]]
result = diagonal_difference(arr)
print(result)
''''
a = []
result = 0
for i in range(int(input("value of n: "))):
a = list(map(int, input().split()))
result += a[i] - a[-1 -i]
print("diagonal difference is", abs(result))
'''
| true |
b9fbb46514e0cfe298833e764053b5812239a883
|
Python
|
tarcisioLima/learnpython
|
/oo/class-attributes.py
|
UTF-8
| 544 | 3.96875 | 4 |
[] |
no_license
|
class A:
vc = 123
# Inicializa logo quando instancia, caso não seja instanciado, não altera a variavel da classe.
def __init__(self):
self.vc = 111
a1 = A()
a2 = A()
# Muda para todas as instancias
A.vc = 321
# Muda apenas para a instancia
a1.vc = 9090
# R: {'vc': 9090}
print(a1.__dict__)
# R: {'vc': 111}
print(a2.__dict__)
'''
Primeiro o compilador do python vai procurar na instancia,
se ele n encontra na instancia, ele procura na classe.
'''
print(A.__dict__)
print()
print(a1.vc)
print(a2.vc)
print(A.vc)
| true |
b7d804c2e51e897e67ceaa18a3dd085979fac964
|
Python
|
Binny-bansal/PYTHON
|
/day1.py
|
UTF-8
| 1,085 | 3.6875 | 4 |
[] |
no_license
|
# print("Binny!", end=" ")
# print("Riya")
# # num = int(input("Enter a number: "))
# # print(num)
# # print(2**5)
# money = 100
# item = 90
# chocolate = 20
# if(money-item >= chocolate):
# print("Yes! We can buy chocolate.")
# elif(money-item < 20):
# print("You're low on money!")
# n = int(input("Enter a Number: "))
# if (n%2==0):
# if (n>2 and n<5):
# print("Not Weird")
# if(n>6 and n<20):
# print("Weird")
# if (n>20):
# print("Not Weird")
# else:
# print("Not Success!")
# n = int(input("Enter a Number: "))
# for i in range(n):
# print(i**2)
# sum = 0
# n = int(input("Enter a Number: "))
# i=0
# while i<=n:
# sum+=i
# i+=1
# print(sum)
# n=7
# print(n**3)
# i=1
# while i<10:
# if i==5:
# continue
# print(i)10
# i+=1
n = int(input("Enter any Number: "))
sum=0
for i in range(1,n+1):
sum+=i*i
print(sum)
| true |
5196a37332132bd2147c4f43a4ac0f59bd27e37d
|
Python
|
josehuillca/Analise_de_Imagens
|
/help_functions/canny.py
|
UTF-8
| 4,611 | 2.875 | 3 |
[] |
no_license
|
import numpy as np
import sys
sys.path.append('/usr/local/lib/python3.6/site-packages')
import cv2
def create_image(shape, dtype, nchanels):
img = np.zeros([shape[0], shape[1], nchanels], dtype=dtype)
r, g, b = cv2.split(img)
img_bgr = cv2.merge([b, g, r])
return img_bgr
def single_band_representation(img):
img_r = create_image(img.shape, img.dtype, 3)
w = img.shape[1]
h = img.shape[0]
color_titles = ('Banda Vermelha(Red)')
for x in range(0, w):
for y in range(0, h):
cor = img[y, x]
img_r[y, x] = [cor[0], cor[0], cor[0]]
#imshow(img_r)
#show()
return img_r
# imagen a escala de grises
def get_canny(path, image, low=71):
src = cv2.imread(path + image)
img_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
lowThreshold = low # 66/45
max_lowThreshold = lowThreshold*3 # 198/135
kernel_size = 3
# Reduce noise with a kernel 3x3
detected_edges = cv2.blur(img_gray, (3, 3))
# Canny detector
detected_edges = cv2.Canny(detected_edges, lowThreshold, max_lowThreshold, kernel_size)
return detected_edges
def my_get_canny(image, low=71, max_=71*3):
img_gray = image #cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
lowThreshold = low # 66/45
max_lowThreshold = max_ # 198/135
kernel_size = 3
# Reduce noise with a kernel 3x3
detected_edges = cv2.bilateralFilter(img_gray, 5, 7, 7)
detected_edges = cv2.blur(detected_edges, (3, 3))
# Canny detector
detected_edges = cv2.Canny(detected_edges, lowThreshold, max_lowThreshold, kernel_size)
return detected_edges
# -------------------------------------------
def empty(x):
pass
def main_canny(path, image, l_limiar=0):
src, src_gray = [], []
dst, detected_edges = [], []
edgeThresh = 1
lowThreshold = l_limiar
max_lowThreshold = 100
ratio = 3
kernel_size = 3
window_name = "Edge Map"
# ----------
src = cv2.imread(path + image)
if not src.data:
return -1
# src = single_band_representation(src)
# cv2.imshow("Original", src)
# Create a matrix of the same type and size as src(for dst)
# dst = create_image(src.shape, src.dtype, 3)
# Convert the image to grayscale
src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
# Create a Trackbar for user to enter threshold
cv2.createTrackbar("Min Threshold:", window_name, lowThreshold, max_lowThreshold, empty)
#CannyThreshold()
while True:
# Reduce noise with a kernel 3x3
detected_edges = cv2.blur(src_gray, (3, 3))
# Canny detector
detected_edges = cv2.Canny(detected_edges, lowThreshold, lowThreshold * ratio, kernel_size)
lowThreshold = cv2.getTrackbarPos("Min Threshold:", window_name)
cv2.setTrackbarPos("Min Threshold:", window_name, lowThreshold)
dst = detected_edges
cv2.imshow(window_name, dst)
if cv2.waitKey(1) == 27: # 27 is the key 'esc'
break
cv2.destroyAllWindows()
print("lowThreshold:", lowThreshold)
print("lowThreshold * ratio:", lowThreshold * ratio)
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
# return the edged image
return edged
def auto_canny_(path, image):
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread(path + image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
# apply Canny edge detection using a wide threshold, tight
# threshold, and automatically determined threshold
wide = cv2.Canny(blurred, 10, 200)
tight = cv2.Canny(blurred, 225, 250)
auto = auto_canny(blurred)
# show the images
#cv2.imshow("Original", image)
cv2.imshow("Edges", np.hstack([wide, tight, auto]))
cv2.waitKey(0)
cv2.destroyAllWindows()
#imshow(tight, cmap="gray")
#show()
def my_auto_canny(image):
if len(image.shape)==2:
gray = image
else:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Bilateral filtering has the nice property of removing noise
# in the image while still preserving the actual edges.
gray = cv2.bilateralFilter(gray, 5, 7, 7)
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
return auto_canny(blurred)
| true |
2e81257ce1118b2c93aa128e8f9c17d042176eb6
|
Python
|
tiagodrehmer/TCC
|
/util.py
|
UTF-8
| 28,635 | 2.515625 | 3 |
[] |
no_license
|
import cv2
import numpy as np
import math
from sklearn.cluster import KMeans
import operator
w = 1280
h = 720
amarelo = (0,255,255)
vermelho = (0,0,255)
azul = (255,0,0)
branco = (255,255,255)
preto = (0, 0, 0)
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (640,360)
fontScale = 1
fontColor = (255,255,255)
lineType = 2
globalErro = 0
acerto = 0
globalJogadores = 0
erroBola = 0
#cv2.putText(img, str(total) + " " + str(len(self.listaJAux)), bottomLeftCornerOfText, font, fontScale, fontColor, lineType)
class Jogador:
def __init__(self, x1, x2, y1, y2, time, ide):
self.y1 = y1
self.y2 = y2
self.cont=1
if time >= 0:
self.mediaTime = time
self.contTime = 6
self.time = time + 1
else:
self.mediaTime = 0
self.contTime = 0
self.time = 0
self.vel = 0
self.histVel = []
self.histAltura = []
self.flagAlt = True
self.flagVel = True
self.colisao = 0
self.x2 = x2
self.x1 = x1
self.altura = x2 - x1
self.id = ide
self.pred = 0
self.lastTime = 0
self.colisor = None
def atualiza(self, x1, x2, y1, y2, time, flag):
self.atualiza_vel(y2)
self.y1 = y1
self.y2 = y2
self.cont+=1
self.atualiza_altura(x2, x1)
if flag:
self.time = time + 1
self.lastTime = time + 1
self.colisor = None
else:
if self.time == 0 and time >= 0 and self.colisao == 0:
if self.contTime <= 7:
self.mediaTime += time
self.contTime += 1
else:
self.time = math.ceil(self.mediaTime/self.contTime) + 1
print(str(self.id), str(self.time))
#x = input()
# if x == "1":
# self.time = (self.time%2) + 1
# global globalErro
# globalErro += 1
# elif x == "2":
# self.time = (self.time%2) + 1
# elif x != "3":
# global acerto
# acerto += 1
# if self.colisor:
# self.colisor.time = (self.time%2) + 1
# self.colisor.lastTime = (self.time%2) + 1
# self.colisor = None
global acerto
acerto += 1
self.lastTime = self.time
if self.contTime == 7 and not self.lasTime:
global globalJogadores
globalJogadores += 1
self.pred = 0
self.colisao = 0
def atualiza_altura(self, x2, x1):
altura = x2-x1
if self.flagAlt:
self.histAltura.append(altura)
qtd_alt = len(self.histAltura)
if qtd_alt == 10:
self.flagAlt = False
self.altura = math.ceil(sum(self.histAltura)/qtd_alt)
else:
del self.histAltura[9]
self.histAltura.insert(0, altura)
self.altura = math.ceil(sum(self.histAltura)/10)
if (abs(self.x2 - x2) > 15) != (abs(self.x1 - x1) > 15):
if abs(self.x2 - x2) > 15:
self.x2 = self.x1 + (self.altura - 15)
elif abs(self.x1 - x1) > 15:
self.x1 = self.x2 - (self.altura - 15)
else:
self.x1 = x1
self.x2 = x2
self.altura = x2 - x1
def quebra(self, colisor, time):
#self.x1 = self.x2 - self.altura
self.colisao += colisor.colisao
if colisor.time != self.time and self.colisao >= 2:
self.time = 0
self.contTime = 0
self.mediaTime = 0
if time != 0:
self.colisor = colisor
def atualiza_vel(self, y2):
if self.flagVel:
self.histVel.append(y2 - self.y2)
qtd_vel = len(self.histVel)
if qtd_vel == 10:
self.flagVel = False
self.vel = math.ceil(sum(self.histVel)/qtd_vel)
else:
del self.histVel[9]
self.histVel.insert(0, y2 - self.y2)
self.vel = math.ceil(sum(self.histVel)/10)
def ajusta(self, colisor):
#self.atualiza_vel(y2)
#self.atualiza_vel(y2)
#self.x1 = x1
self.colisao += 1
if self.colisao >= 2:
self.y1 = colisor.y1
self.y2 = colisor.y2
if colisor.time != self.time:
self.time = 0
self.contTime = 0
self.mediaTime = 0
if colisor.time != 0:
self.colisor = colisor
#else:
#self.predict()
def testa_borda(self):
if (self.y2 < 40) or (self.y1 > w - 40):
return True
else:
return False
def predict(self):
# if flag:
# self.x1 = self.x1+self.vel[0]
# self.x2 = self.x2+self.vel[0]
self.y1 = self.y1+self.vel
self.y2 = self.y2+self.vel
self.pred+=1
#self.time = 2
#return self.testa_borda()
def getTuple1(self):
return(self.y1, self.x1)
def getTuple2(self):
return(self.y2, self.x2)
class Goleira:
def __init__(self):
self.dist = [0, 0]
self.x1 = [0, 0]
self.x2 = [0, 0]
self.y1 = [0, 0]
self.y2 = [0, 0]
self.mantem = False
self.numTrave = 0
def atualiza(self, x1, x2, y1, y2):
self.mantem = True
self.x1[self.numTrave] = x1
self.x2[self.numTrave] = x2
self.y1[self.numTrave] = y1
self.y2[self.numTrave] = y2
self.numTrave = (self.numTrave+1)%2
def resetTraves(self):
self.numTrave = 0
self.mantem = False
self.x1 = [0, 0]
self.x2 = [0, 0]
self.y1 = [0, 0]
self.y2 = [0, 0]
def getTuple1T1(self):
return(self.y1[0], self.x1[0])
def getTuple2T1(self):
return(self.y2[0], self.x2[0])
def getTuple1T2(self):
return(self.y1[1], self.x1[1])
def getTuple2T2(self):
return(self.y2[1], self.x2[1])
class Bola:
def __init__(self):
self.dist = 0
self.vel = [0, 0]
self.mantem = False
self.pred = 0
self.x1 = 0
self.x2 = 0
self.y1 = 0
self.y2 = 0
self.dominio = False
self.ok = 0
self.predTotal = 0
#self.detect = True
def reset(self):
self.dist = 0
self.vel = [0, 0]
self.mantem = False
self.pred = 0
self.x1 = 0
self.x2 = 0
self.y1 = 0
self.y2 = 0
self.dominio = False
def atualiza(self, x1, x2, y1, y2):
if self.x1:
disx1, disx2, disy2, disy1 = abs(x1 - self.x1), abs(x2 - self.x2), abs(y2 - self.y2), abs(y1 - self.y1)
if not (disx1 < 100 and disx2 < 100 and disy2 < 100 and disy1 < 100) and self.pred < 6:
self.predict()
return
self.mantem = True
self.vel = [x2 - self.x2, y2 - self.y2]
# if self.detect:
self.pred = 0
#self.detec = True
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.ok += 1
def predict(self):
self.predTotal += 1
if self.dominio < 4:
if self.pred == 0:
self.lastPosition = [self.x2, self.y2]
else:
self.x1 += self.vel[0]
self.x2 += self.vel[0]
self.y1 += self.vel[1]
self.y2 += self.vel[1]
if self.x1 < 0 or self.y1 < 0 or self.x2 > h or self.y2 > w:
global erroBola
erroBola += 1
self.pred += 1
self.mantem = True
def getTuple1(self):
return(self.y1, self.x1)
def getTuple2(self):
return(self.y2, self.x2)
class Objects:
def __init__(self):
self.listaJogadores = []
self.listaJAux = []
self.vago = 0
self.bola = Bola()
self.goleira = Goleira()
self.CLUSTERS = 2
self.listColors = []
self.colorTimes = [np.array(3)]*2
self.totalJogadores = 0
#video 3
#self.colorTimes = [[54, 49, 43], [165, 158, 134]]
#video 1
#self.colorTimes = [[79, 61, 46], [230, 220, 193]]
self.contFrame = 0
#self.colorTimes = [[191, 162, 138], [97, 49, 26]]
self.ids = 0
self.nReconhecidos = 0
self.aglu = 0
def kmeansColors(self, x1, x2, y1, y2, img):
distY = y2 - y1
distX = x2 - x1
#tuple1 = (y1 + math.ceil(0/6 * distY), x1 + math.ceil(1/5 * distX))
#tuple2 = (y1 + math.ceil(2/6 * distY), x1 + math.ceil(1/2 * distX))
#tuple3 = (y1 + math.ceil(3/6 * distY), x1 + math.ceil(1/5 * distX))
#tuple4 = (y1 + math.ceil(4/6 * distY), x1 + math.ceil(1/2 * distX))
#tuple5 = (y1 + math.ceil(5/6 * distY), x1 + math.ceil(1/5 * distX))
#tuple6 = (y1 + math.ceil(6/6 * distY), x1 + math.ceil(1/2 * distX))
tuplet1 = (y1 + math.ceil(3/9 * distY), x1 + math.ceil(1/2 * distX))
tuplet2 = (y1 + math.ceil(6/9 * distY), x1 + math.ceil(4/7 * distX))
kmeans = KMeans(n_clusters = self.CLUSTERS)
img2 = img[tuplet1[1]:tuplet2[1], tuplet1[0]:tuplet2[0]]
img2 = img2.reshape((img2.shape[0] * img2.shape[1], 3))
kmeans.fit(img2)
COLORS = kmeans.cluster_centers_
COLORS.astype(int)
cv2.rectangle(img, tuplet1, tuplet2, amarelo, 2)
#cv2.rectangle(img, tuple3, tuple4, np.ceil(COLORS[0]), 2)
#cv2.rectangle(img, tuple4, tuple5, np.ceil(COLORS[1]), 2)
#COLORS.sort(key = operator.itemgetter(0, 1, 2))
return sorted(COLORS, key = operator.itemgetter(0, 1, 2))
def update_list(self, COLORS):
aux_best = -1
for j, resultColor in enumerate(COLORS):
best = -1
aux = 80
for i, color in enumerate(self.listColors):
b = math.ceil(color[0][0]/color[1])
g = math.ceil(color[0][1]/color[1])
r = math.ceil(color[0][2]/color[1])
b, g, r = abs(b - resultColor[0]), abs(g- resultColor[1]), abs(r - resultColor[2])
if b < 40 and g < 40 and r < 40 and i != aux_best:
result = b + g + r
if aux > result:
aux = result
best = i
if best != -1:
b = math.ceil(self.listColors[best][0][0]/self.listColors[best][1])
g = math.ceil(self.listColors[best][0][1]/self.listColors[best][1])
r = math.ceil(self.listColors[best][0][2]/self.listColors[best][1])
self.listColors[best][1] += 1
self.listColors[best][0][0] += resultColor[0]
self.listColors[best][0][1] += resultColor[1]
self.listColors[best][0][2] += resultColor[2]
aux_best = best
else:
self.listColors.append([resultColor, 1])
def escolhe_time(self, COLORS):
aux = 80
valueT = 0
testeBg = False
#print("jogador:")
for resultColor in COLORS:
b1 = abs(self.colorTimes[0][0] - resultColor[0])
g1 = abs(self.colorTimes[0][1] - resultColor[1])
r1 = abs(self.colorTimes[0][2] - resultColor[2])
b2 = abs(self.colorTimes[1][0] - resultColor[0])
g2 = abs(self.colorTimes[1][1] - resultColor[1])
r2 = abs(self.colorTimes[1][2] - resultColor[2])
if b1 < 30 and g1 < 30 and r1 < 30:
result1 = b1 + g1 + r1
else:
result1 = 100
if b2 < 30 and g2 < 30 and r2 < 30:
result2 = b2 + g2 + r2
else:
result2 = 100
if result2 < result1:
if result2 < aux:
aux = result2
valueT = 0
break
elif result1 < result2:
if result1 < aux:
aux = result1
valueT = 1
#print(valueT)
#print("\n\n\n")
#if testeBg:
return valueT
#else:
# return -1
def testa_time(self, x1, x2, y1, y2, img):
COLORS = np.ceil(self.kmeansColors(x1, x2, y1, y2, img))
if self.contFrame <= 20:
self.update_list(COLORS)
if self.contFrame == 20 or self.contFrame == 15:
self.listColors.sort(key = lambda x: x[1], reverse=True)
for color, qtd in self.listColors:
print(np.ceil(color/qtd), qtd)
#self.bg = np.ceil(self.listColors[0][0]/self.listColors[0][1])
self.colorTimes[0] = np.ceil(self.listColors[0][0]/self.listColors[0][1])
self.colorTimes[1] = np.ceil(self.listColors[1][0]/self.listColors[1][1])
else:
return self.escolhe_time(COLORS)
return -1
def reset(self):
self.listaJogadores = []
self.bola.reset()
self.goleira = Goleira()
self.research = True
def ajusta_objects(self):
# for jogador in self.listaJAux:
# print(jogador.x2)
for jogador in self.listaJogadores:
if not jogador.testa_borda():
if jogador.cont >= 5:
if jogador.pred < 10: # and jogador.colisao < 10:
colisor = False
#jogador.predict()
for i, jogadorTest in enumerate(self.listaJAux):
if jogadorTest.x1 - jogador.x1 < 20:
if jogador.x1 < jogadorTest.x2 and jogador.x2 > jogadorTest.x1 and jogador.y1 < jogadorTest.y2 and jogador.y2 > jogadorTest.y1:
if not colisor or jogadorTest.x2 > colisor.x2:
colisor = jogadorTest
self.aglu += 1
if colisor:
time = jogador.time
jogador.ajusta(colisor)
colisor.quebra(jogador, time)
colisor.predict()
else:
jogador.colisao = 0
self.nReconhecidos += 1
self.listaJAux.append(jogador)
jogador.predict()
else:
self.nReconhecidos += 1
self.listaJogadores = self.listaJAux
self.listaJAux = []
if not self.bola.mantem:
self.bola.predict()
# for jogador in self.listaJogadores:
# print(jogador.x2)
def draw_objects(self, img, frame_count):
cv2.putText(img, str(frame_count), bottomLeftCornerOfText, font, fontScale, fontColor, lineType)
self.contFrame+=1
if self.listaJAux:
self.ajusta_objects()
for jogador in self.listaJogadores:
if jogador.time == 1:
cv2.rectangle(img, jogador.getTuple1(), jogador.getTuple2(), vermelho, 2)
cv2.putText(img, str(jogador.id), jogador.getTuple1(), font, fontScale/2, fontColor, lineType)
elif jogador.time == 2:
cv2.rectangle(img, jogador.getTuple1(), jogador.getTuple2(), azul, 2)
cv2.putText(img, str(jogador.id), jogador.getTuple1(), font, fontScale/2, fontColor, lineType)
else:
cv2.rectangle(img, jogador.getTuple1(), jogador.getTuple2(), branco, 2)
cv2.putText(img, str(jogador.id), jogador.getTuple1(), font, fontScale/2, fontColor, lineType)
if self.bola.mantem:
cv2.rectangle(img, self.bola.getTuple1(), self.bola.getTuple2(), amarelo, 2)
self.bola.mantem = False
if self.goleira.mantem:
cv2.rectangle(img, self.goleira.getTuple1T1(), self.goleira.getTuple2T1(), preto, 2)
if self.goleira.numTrave == 0:
cv2.rectangle(img, self.goleira.getTuple1T2(), self.goleira.getTuple2T2(), preto, 2)
self.goleira.mantem = False
self.contJog = len(self.listaJogadores)
def testa_borda(self, y1, y2):
#print(y1, y2)
if (y1 < 50) or (y2 > w - 50):
return True
else:
return False
def atualizaJogador(self, x1, x2, y1, y2, i, cont, img):
jogador = self.listaJogadores[i-cont]
if self.contFrame <= 20 or jogador.time or self.testa_borda(y1, y2):
jogador.atualiza(x1, x2, y1, y2, -1, False)
else:
time = self.testa_time(x1, x2, y1, y2, img)
jogador.atualiza(x1, x2, y1, y2, time, False)
self.totalJogadores += 1
self.listaJAux.append(self.listaJogadores.pop(i-cont))
def atualiza_list(self, lista_atualiza, img, research):
#print(lista_atualiza)
total = len(self.listaJogadores)
#print(len(lista_atualiza), len(lista_classe))
#lista_atualiza.sort(key = operator.itemgetter(1), reverse = True)
#print(total)
if research:
self.reset()
l_possiveis1 = [[[-1, 1000], [-1, 1000]] for i in range(total)]
l_possiveis2 = [[-1, 1000] for i in range(len(lista_atualiza))]
for j, detect in enumerate(lista_atualiza):
x1, x2, y1, y2, classe = detect
#cv2.imwrite('frames/img_j3_'+str(x1) +".png",img[x1: x2, y1:y2])
#print(x1, x2, y1, y2)
melhor = -1
if classe == 1.:
if x2 - x1 > 50:
if self.contFrame <= 20:
time = self.testa_time(x1, x2, y1, y2, img)
flag = True
for i, jogador in enumerate(self.listaJogadores):
disx1, disx2, disy2, disy1 = abs(x1 - jogador.x1), abs(x2 - jogador.x2), abs(y2 - jogador.y2), abs(y1 - jogador.y1)
#disP1 = abs(x1 - jogador.x1) + abs(y1 - jogador.y1)
erro = 10 * jogador.colisao
erroAlt = 10 * jogador.colisao
if (disx1 < 50 or disx2 < 50 + erroAlt) and disy2 < 50 + erro and disy1 < 50 +erro :
dist = 2*disx2+disy2+disx1+disy1
if l_possiveis1[i][0][1] > dist:
l_possiveis1[i][1] = l_possiveis1[i][0].copy()
l_possiveis1[i][0] = [j, dist]
elif l_possiveis1[i][1][1] > dist:
l_possiveis1[i][1] = [j, dist]
if l_possiveis2[j][1] > dist:
l_possiveis2[j] = [i, dist]
flag = False
if flag:
self.listaJAux.append(Jogador(x1, x2, y1, y2, -1, self.ids))
self.totalJogadores += 1
self.ids += 1
elif classe == 2.:
#if abs(x1 - self.bola.x1) < 20 or abs(x2 - self.bola.x2) < 20 or abs(y2 - self.bola.y2) < 20 or abs(y1 - self.bola.y1) < 20 or :
self.bola.atualiza(x1, x2, y1, y2)
else:
if x2 - x1 > 50:
self.goleira.atualiza(x1, x2, y1, y2)
cont = 0
for i, possiveis in enumerate(l_possiveis1):
testIndex, testDist = possiveis[0]
pIndex, pDist = possiveis[1]
if testIndex != -1 and i == l_possiveis2[testIndex][0]:
x1, x2, y1, y2, _ = lista_atualiza[testIndex]
self.atualizaJogador(x1, x2, y1, y2, i, cont, img)
cont+=1
elif pIndex != -1 and testIndex == l_possiveis1[l_possiveis2[pIndex][0]][0][0]:
x1, x2, y1, y2, _ = lista_atualiza[pIndex]
self.atualizaJogador(x1, x2, y1, y2, i, cont, img)
cont+=1
# if total - len(self.listaJogadores) < 4:
# return False
# else:
# self.ajusta_objects()
# return True
class Event_detect(Objects):
def __init__(self):
#eventos
Objects.__init__(self)
self.posses = [0, 0]
self.passesCE = [[0,0], [0,0]]
self.passesInt = [0, 0]
self.roubadas = [0, 0]
self.dribles = [0, 0]
self.jDominio = [None, 1]
self.jDisputa = [None, 1]
self.listaIndefinidos = []
self.listPassesCorrige = []
self.corrigeDisputaPR = []
self.corrigeDisputaDR = []
self.lastDominio = [0, None]
self.lastDisputaID = -1
self.lastEstado = 0
self.listLancesA = []
self.estado = 0
self.flagDisputa = True
# 0 = Bola livre
# 1 = dominio
# 2 = Disputa
# 3 = Disputa Intensa
self.totalDominios = 0
#with open("checkPoint.txt", "r") as auxFile:
#self.ids, self.posses[0], self.posses[1] = list(map(int, auxFile.read().split("\n")))
def resetDetect(self, frame_count):
self.jDominio = [None, 1]
self.jDisputa = [None, 1]
self.listaIndefinidos = []
self.listPassesCorrige = []
self.corrigeDisputaPR = []
self.corrigeDisputaDR = []
self.lastDominio = [0, None]
self.lastDisputaID = -1
self.lastEstado = 0
self.estado = -1
self.flagDisputa = True
def detect(self, img, frame_count, research):
if research:
self.resetDetect(frame_count)
aux = 60
aux2 = 80
jogadorDominio = None
jogadorDisputa = None
for i, jogador in enumerate(self.listaJogadores):
distBolax2 = abs(self.bola.x2 - jogador.x2)
distBolay1 = distBolax2 + abs(self.bola.y1 - jogador.y1)
distBolay2 = distBolax2 + abs(self.bola.y2 - jogador.y2)
if distBolay2 < distBolay1:
if distBolay2 < aux:
jogadorDisputa = jogadorDominio
aux2 = aux
jogadorDominio = jogador
aux = distBolay2
elif distBolay2 <= aux2:
aux2 = distBolay2
jogadorDisputa = jogador
else:
if distBolay1 < aux:
jogadorDisputa = jogadorDominio
aux2 = aux
jogadorDominio = jogador
aux = distBolay1
elif distBolay1 <= aux2:
aux2 = distBolay1
jogadorDisputa = jogador
if jogadorDisputa and not jogadorDominio:
jogadorDisputa = None
elif jogadorDisputa and jogadorDominio and jogadorDisputa.time == jogadorDominio.time:
jogadorDisputa = None
self.defineEstado(jogadorDominio, jogadorDisputa, frame_count)
self.defineEvento(frame_count)
self.bolaBaseJogador()
self.draw_Dominios(img)
#self.printResult(frame_count)
def defineEstado(self, jogadorDominio, jogadorDisputa, frame_count):
if self.jDominio[0] and jogadorDominio:
if jogadorDominio.id == self.jDominio[0].id:
self.bola.dominio += 1
self.jDominio[1] += 1
if self.jDominio[1] >= 6:
self.estado = 1
else:
if self.jDisputa[0] and jogadorDisputa:
if self.jDisputa[0].id == jogadorDominio.id and self.jDominio[0].id == jogadorDisputa.id:
aux = self.jDominio.copy()
self.jDominio = self.jDisputa
self.jDisputa = aux
self.jDisputa[1] += 1
self.jDominio[1] += 1
self.estado = 2
else:
if self.jDominio[1] >= 5:
self.jDisputa = self.jDominio.copy()
self.estado = 2
else:
self.jDisputa = self.jDominio.copy()
self.estado = 0
self.jDominio[0] = jogadorDominio
self.jDominio[1] = 1
self.bola.dominio = 1
elif jogadorDominio:
if self.lastDominio[1] and jogadorDominio.id == self.lastDominio[1].id:
self.jDominio[1] = 3
else:
self.jDominio[1] = 1
self.jDominio[0] = jogadorDominio
self.ajustaJogadorDisputa(jogadorDisputa)
self.bola.dominio = 1
elif self.jDominio[0]:
self.jDominio = [None, 1]
self.bola.dominio = 0
self.estado = 0
else:
self.jDominio[1] += 1
self.estado = 0
if self.estado != 2:
self.ajustaJogadorDisputa(jogadorDisputa)
if self.jDominio[0] and self.jDisputa[0]:
if self.jDominio[0].colisao >= 2:
self.listLancesA.append(frame_count)
def defineEvento(self, frame_count):
if self.jDominio[0]:
print(self.lastDominio[0], self.jDominio[0].time, self.estado, self.lastEstado)
else:
print(self.lastDominio[0], -1, self.estado, self.lastEstado)
self.corrigeLances()
self.checkLastDominio()
if self.estado == 1:
if self.lastEstado == 0:
if self.lastDominio[1]:
self.checkPasse(frame_count)
elif self.lastEstado == 5:
if self.lastDominio[1] and self.jDominio[0].id != self.lastDominio[1].id:
self.checkRoubada(frame_count)
elif self.lastEstado == 2:
if self.lastDominio[1]:
if self.jDominio[0].id == self.lastDominio[1].id or self.jDominio[0].id == self.lastDisputaID:
self.checkDribleRoubada(frame_count)
else:
self.checkPasseRoubada(frame_count)
elif self.lastEstado == 4:
if self.aux < 3:
self.checkPasse(frame_count)
else:
self.checkPasseRoubada(frame_count)
if self.lastDominio != self.jDominio:
self.totalDominios += 1
if self.lastDisputaID:
self.lastDisputaID = 0
self.checkPosse()
self.lastDominio = [self.jDominio[0].time, self.jDominio[0]]
elif self.estado == 2:
if self.lastEstado == 0 or self.lastEstado == 5:
self.estado = 4
self.aux = 1
elif self.lastEstado == 4:
self.estado = 4
self.aux += 1
if self.jDisputa[0] and not self.lastDisputaID:
self.lastDisputaID = self.jDisputa[0].id
elif self.estado == 0:
if self.lastEstado == 1:
self.lastEstado = self.estado
return
else:
return
self.lastEstado = self.estado
def ajustaJogadorDisputa(self, jogadorDisputa):
if self.jDisputa[0] and jogadorDisputa:
if self.jDisputa[0].id == jogadorDisputa.id:
self.jDisputa[1] += 1
if self.jDisputa[1] >= 2:
self.estado = 2
else:
self.jDisputa[0] = jogadorDisputa
self.jDisputa[1] = 1
self.flagDisputa = True
elif jogadorDisputa:
self.jDisputa[0] = jogadorDisputa
self.jDisputa[1] = 1
elif self.jDisputa[0] and self.flagDisputa:
self.flagDisputa = False
if self.jDisputa[1] >= 5:
self.estado = 2
else:
self.jDisputa = [None, 1]
def corrigeLances(self):
self.corrigePasseRoubada()
self.corrigeDribleRoubada()
self.corrigePasse()
self.corrigePosse()
def checkRoubada(self, frame_count):
if self.lastDominio[0] != 0 and self.jDominio[0].time != 0:
if self.lastDominio[0] == self.jDominio[0].time:
print(str(frame_count) + ": Passe certo")
self.passesCE[self.jDominio[0].time - 1][0] += 1
elif self.lastDominio[0] != self.jDominio[0].time:
print(str(frame_count) + ": Roubada")
self.roubadas[self.jDominio[0].time - 1] += 1
elif self.lastDominio[0] != 0:
self.corrigeDisputaDR.append([self.lastDominio[0], self.jDominio[0], frame_count])
def corrigePasseRoubada(self):
aux = []
for time1, jogador, frame_count in self.corrigeDisputaPR:
if jogador.time != 0:
if time1 == jogador.time:
self.passesCE[time1 - 1][0] += 1
self.dribles[time1 - 1] += 1
print(str(frame_count) + ": Passe certo e drible [Correcao]")
elif time1 != jogador.time:
self.roubadas[jogador.time - 1] += 1
self.passesCE[jogador.time - 1][0] += 1
print(str(frame_count) + ": Roubada e passe certo [Correcao]")
else:
aux.append([time1, jogador, frame_count])
self.corrigeDisputaPR = aux
def checkPasseRoubada(self, frame_count):
if self.lastDominio[0] != 0 and self.jDominio[0].time != 0:
if self.lastDominio[0] == self.jDominio[0].time:
self.passesCE[self.jDominio[0].time - 1][0] += 1
self.dribles[self.jDominio[0].time - 1] += 1
print(str(frame_count) + ": Passe certo e individual")
elif self.lastDominio[0] != self.jDominio[0].time:
self.roubadas[self.jDominio[0].time - 1] += 1
self.passesCE[self.jDominio[0].time - 1][0] += 1
print(str(frame_count) + ": Roubada e passe certo")
elif self.lastDominio[0] != 0:
self.corrigeDisputaPR.append([self.lastDominio[0], self.jDominio[0], frame_count])
def corrigeDribleRoubada(self):
aux = []
for time1, jogador, frame_count in self.corrigeDisputaDR:
if jogador.time != 0:
print(jogador.time, time1)
if time1 == jogador.time:
self.dribles[time1 - 1] += 1
print(str(frame_count) + ": Drible [Correcao]")
elif time1 != jogador.time:
self.roubadas[jogador.time - 1] += 1
print(str(frame_count) + ": Roubada [Correcao] ")
else:
aux.append([time1, jogador, frame_count])
self.corrigeDisputaDR = aux
def checkDribleRoubada(self, frame_count):
if self.lastDominio[0] != 0 and self.jDominio[0].time != 0:
if self.lastDominio[0] == self.jDominio[0].time:
self.dribles[self.jDominio[0].time - 1] += 1
print(str(frame_count) + ": Drible")
elif self.lastDominio[0] != self.jDominio[0].time:
self.roubadas[self.jDominio[0].time - 1] += 1
print(str(frame_count) + ": Roubada")
elif self.lastDominio[0] != 0:
self.corrigeDisputaDR.append([self.lastDominio[0], self.jDominio[0], frame_count])
def checkLastDominio(self):
if not self.lastDominio[0]:
if self.lastDominio[1] and self.lastDominio[1].time:
self.lastDominio[0] = self.lastDominio[1].time
def corrigePasse(self):
aux = []
for jogador, lastJogador, frame_count in self.listPassesCorrige:
if jogador and lastJogador and jogador.time and lastJogador.time:
if jogador.time == lastJogador.time:
self.passesCE[lastJogador.time - 1][0] += 1
print(str(frame_count) + ": Passe certo [Correcao]")
else:
self.passesCE[lastJogador.time - 1][1] += 1
self.passesInt[lastJogador.time %2] += 1
print(str(frame_count) + ": Passse errado [Correcao]")
else:
aux.append([jogador, lastJogador, frame_count])
self.listPassesCorrige = aux
def checkPasse(self, frame_count):
if self.lastDominio[0] != 0 and self.jDominio[0].time != 0:
if self.lastDominio[1].id != self.jDominio[0].id:
if self.lastDominio[0] == self.jDominio[0].time:
self.passesCE[self.lastDominio[0] - 1][0] += 1
print(str(frame_count) + ": Passe certo")
else:
self.passesCE[self.lastDominio[0] - 1][1] += 1
self.passesInt[self.lastDominio[0] %2] += 1
print(str(frame_count) + ": Passse errado")
else:
self.posses[self.jDominio[0].time - 1] += 2
else:
self.listPassesCorrige.append([self.jDominio[0], self.lastDominio[1], frame_count])
def corrigePosse(self):
aux = []
for jogador, qtd in self.listaIndefinidos:
if jogador.time != 0:
self.posses[jogador.time - 1] += qtd
else:
aux.append([jogador, qtd])
self.listaIndefinidos = aux
def checkPosse(self):
if self.jDominio[0].time != 0:
self.posses[self.jDominio[0 ].time - 1] += 1
else:
self.somaDominioIndef()
def draw_Dominios(self, img):
if self.jDominio[0]:
cv2.rectangle(img, self.jDominio[0].getTuple1(), self.jDominio[0].getTuple2(), preto, 2)
if self.jDisputa[0]:
cv2.rectangle(img, self.jDisputa[0].getTuple1(), self.jDisputa[0].getTuple2(), amarelo, 2)
def printResult(self, frame_count):
totalPosse = sum(self.posses)
if totalPosse:
print ("Time 1:")
print ("Passes Certos: " + str(self.passesCE[0][0]))
print ("Passes Errados: " + str(self.passesCE[0][1]))
print ("Posse de bola: " + str(self.posses[0]/totalPosse*100))
print ("Interceptacoes: " + str(self.passesInt[0]))
print ("Roubo de bola: " + str (self.roubadas[0]))
print ("Lance Individual: " + str(self.dribles[0]))
print ("Time 2:")
print ("Passes Certos: " + str(self.passesCE[1][0]))
print ("Passes Errados: " + str(self.passesCE[1][1]))
print ("Posse de bola: " + str(self.posses[1]/totalPosse*100))
print ("Interceptacoes: " + str(self.passesInt[1]))
print ("Roubo de bola: " + str (self.roubadas[1]))
print ("Lance Individual: " + str(self.dribles[1]))
print ("-----------------------------")
print ("Lances para serem avaliados: ")
for frame_count in self.listLancesA:
print(str(frame_count))
def bolaBaseJogador(self):
if self.jDominio[0] and self.bola.pred > 3:
self.bola.x2 = self.jDominio[0].x2
self.bola.x1 = self.jDominio[0].x2 - math.ceil(1/5*(self.jDominio[0].altura))
self.bola.y1 = self.jDominio[0].y1 + math.ceil(2/5*(self.jDominio[0].y2 - self.jDominio[0].y1))
self.bola.y2 = self.jDominio[0].y1 + math.ceil(4/5*(self.jDominio[0].y2 - self.jDominio[0].y1))
self.bola.domino = True
def somaDominioIndef(self):
for i, jogador in enumerate(self.listaIndefinidos):
if self.jDominio[0].id == jogador[0].id:
self.listaIndefinidos[i][1] += 1
return
self.listaIndefinidos.append([self.jDominio[0], 1])
| true |
99fd77bb00149b104ff5d79d0ce09d66a8c25348
|
Python
|
Sneha-singh-pal/simple-linear-regression-ML-model
|
/model.py
|
UTF-8
| 310 | 2.890625 | 3 |
[] |
no_license
|
import pandas
import sklearn.linear_model from LinearRegression
db = pandas.read_csv("dataset.csv")
X= db["hrs"].values.reshape(-1,1)
Y= db["marks"]
mind = LinearRegression()
mind.fit(X,Y)
hours= int(input("enter the no of hours you study :" ))
print("your marks wil be approx :" ,mind.predict([[hours]]))
| true |
bc94346808f3594db3765b392e5e70638399d2a5
|
Python
|
TheAlgorithms/Python
|
/project_euler/problem_107/sol1.py
|
UTF-8
| 4,211 | 4.15625 | 4 |
[
"CC-BY-NC-4.0",
"CC-BY-NC-SA-4.0",
"MIT"
] |
permissive
|
"""
The following undirected network consists of seven vertices and twelve edges
with a total weight of 243.

The same network can be represented by the matrix below.
A B C D E F G
A - 16 12 21 - - -
B 16 - - 17 20 - -
C 12 - - 28 - 31 -
D 21 17 28 - 18 19 23
E - 20 - 18 - - 11
F - - 31 19 - - 27
G - - - 23 11 27 -
However, it is possible to optimise the network by removing some edges and still
ensure that all points on the network remain connected. The network which achieves
the maximum saving is shown below. It has a weight of 93, representing a saving of
243 - 93 = 150 from the original network.
Using network.txt (right click and 'Save Link/Target As...'), a 6K text file
containing a network with forty vertices, and given in matrix form, find the maximum
saving which can be achieved by removing redundant edges whilst ensuring that the
network remains connected.
Solution:
We use Prim's algorithm to find a Minimum Spanning Tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
"""
from __future__ import annotations
import os
from collections.abc import Mapping
EdgeT = tuple[int, int]
class Graph:
"""
A class representing an undirected weighted graph.
"""
def __init__(self, vertices: set[int], edges: Mapping[EdgeT, int]) -> None:
self.vertices: set[int] = vertices
self.edges: dict[EdgeT, int] = {
(min(edge), max(edge)): weight for edge, weight in edges.items()
}
def add_edge(self, edge: EdgeT, weight: int) -> None:
"""
Add a new edge to the graph.
>>> graph = Graph({1, 2}, {(2, 1): 4})
>>> graph.add_edge((3, 1), 5)
>>> sorted(graph.vertices)
[1, 2, 3]
>>> sorted([(v,k) for k,v in graph.edges.items()])
[(4, (1, 2)), (5, (1, 3))]
"""
self.vertices.add(edge[0])
self.vertices.add(edge[1])
self.edges[(min(edge), max(edge))] = weight
def prims_algorithm(self) -> Graph:
"""
Run Prim's algorithm to find the minimum spanning tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
>>> graph = Graph({1,2,3,4},{(1,2):5, (1,3):10, (1,4):20, (2,4):30, (3,4):1})
>>> mst = graph.prims_algorithm()
>>> sorted(mst.vertices)
[1, 2, 3, 4]
>>> sorted(mst.edges)
[(1, 2), (1, 3), (3, 4)]
"""
subgraph: Graph = Graph({min(self.vertices)}, {})
min_edge: EdgeT
min_weight: int
edge: EdgeT
weight: int
while len(subgraph.vertices) < len(self.vertices):
min_weight = max(self.edges.values()) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
min_edge = edge
min_weight = weight
subgraph.add_edge(min_edge, min_weight)
return subgraph
def solution(filename: str = "p107_network.txt") -> int:
"""
Find the maximum saving which can be achieved by removing redundant edges
whilst ensuring that the network remains connected.
>>> solution("test_network.txt")
150
"""
script_dir: str = os.path.abspath(os.path.dirname(__file__))
network_file: str = os.path.join(script_dir, filename)
edges: dict[EdgeT, int] = {}
data: list[str]
edge1: int
edge2: int
with open(network_file) as f:
data = f.read().strip().split("\n")
adjaceny_matrix = [line.split(",") for line in data]
for edge1 in range(1, len(adjaceny_matrix)):
for edge2 in range(edge1):
if adjaceny_matrix[edge1][edge2] != "-":
edges[(edge2, edge1)] = int(adjaceny_matrix[edge1][edge2])
graph: Graph = Graph(set(range(len(adjaceny_matrix))), edges)
subgraph: Graph = graph.prims_algorithm()
initial_total: int = sum(graph.edges.values())
optimal_total: int = sum(subgraph.edges.values())
return initial_total - optimal_total
if __name__ == "__main__":
print(f"{solution() = }")
| true |
f20273465bac34792f2557e7d1d541c3cddba586
|
Python
|
harshsd/NUS-Intern
|
/Codes/Final_Codes_Folder/svm.py
|
UTF-8
| 4,971 | 3.09375 | 3 |
[] |
no_license
|
from sklearn import svm
import os
import numpy as np
import matplotlib.pyplot as plt
def accuracy_svm (data_set1 , data_set2 , cc , gg):
'''Returns average accuracy of a svm after doing 5 fold validation on the given datasets.Uses rbf kernel. To edit change on line 53
Args:
data_set1 : The first data_set. All the inputs should have same number of features. Also each of them should belong to the same class.
data_set2 : The second data_set. All inputs should have same number of features. Each should belong to same class other than that of data_set1. Also, lenght of the dataset must be same as the previous data_set.
cc: C for kernal
gg: gamma for kernel
More datasets can be easily added for multiclass svm. See next function (commented) for an example.
Returns:
Tuple containing mean accuracy of selected svm and standard deviation of the included accuracies.'''
accuracy = []
l = len(data_set1)
if l != len (data_set2):
print ("error")
print (l)
print (len(data_set2))
for i in range (0,5):
fatigue_train1 = []
fatigue_train2 = []
fatigue_test1 = []
fatigue_test2 = []
test1 = data_set1[int(i*l/5):int((i+1)*l/5)]
test2 = data_set2[int(i*l/5):int((i+1)*l/5)]
#print(type(test1))
if i == 0:
train1 = data_set1[int(l/5):l]
train2 = data_set2[l//5:l]
elif i == 4 :
train1 = data_set1[0:4*l//5]
train2 = data_set2[0:4*l//5]
else:
train1 = data_set1[0:i*l//5]
train1 = np.concatenate((train1,data_set1[(i+1)*l//5:l]),axis = 0)
train2 = data_set2[0:i*l//5]
train2 = np.concatenate((train2 ,data_set2[(i+1)*l//5:l]) , axis =0)
test1 = np.concatenate((test1,test2),axis=0)
train1 = np.concatenate((train1,train2), axis=0)
#print (test1.shape)
#print (len(test1[0]))
for k in range (0,int(4*l//5)):
fatigue_train1.append(0)
fatigue_train2.append(1)
if(k<int(l//5)):
fatigue_test1.append(0)
fatigue_test2.append(1)
#print (len(fatigue_train1))
fatigue_train1 += fatigue_train2
fatigue_train = np.array(fatigue_train1)
#print (len(fatigue_train))
fatigue_test1 += fatigue_test2
fatigue_test = np.array(fatigue_test1)
#print (len(fatigue_test))
clf = svm.SVC(kernel='rbf', C=cc, gamma = gg )
clf.fit (train1 , fatigue_train1)
fatigue_result = clf.predict(test1)
y = 0
n = 0
for i in range (0,len(fatigue_result)):
if (fatigue_result[i] == fatigue_test1[i]):
y=y+1
else:
n=n+1
accuracy_curr = y/(y+n)
accuracy.append (float(100*accuracy_curr))
accuracy = np.array(accuracy)
#print (accuracy)
mean = accuracy.mean()
std = accuracy.std()
return (mean , std)
'''
def accuracy_svm (data_set1 , data_set2 , data_set3 , cc , gg):
accuracy = []
l = len(data_set1)
if l != len (data_set2):
print ("error")
print (l)
print (len(data_set2))
elif l != len(data_set3):
print ("error")
print (l)
print (len(data_set3))
for i in range (0,5):
fatigue_train1 = []
fatigue_train2 = []
fatigue_train3 = []
fatigue_test1 = []
fatigue_test2 = []
fatigue_test3 = []
test1 = data_set1[int(i*l/5):int((i+1)*l/5)]
test2 = data_set2[int(i*l/5):int((i+1)*l/5)]
test3 = data_set3[int(i*l/5):int((i+1)*l/5)]
if i == 0:
train1 = data_set1[int(l/5):l]
train2 = data_set2[l//5:l]
train3 = data_set3[l//5:l]
elif i == 4 :
train1 = data_set1[0:4*l//5]
train2 = data_set2[0:4*l//5]
train3 = data_set3[0:4*l//5]
else:
train1 = data_set1[0:i*l//5]
train1 = np.concatenate((train1,data_set1[(i+1)*l//5:l]),axis = 0)
train2 = data_set2[0:i*l//5]
train2 = np.concatenate((train2 ,data_set2[(i+1)*l//5:l]) , axis =0)
train3 = data_set3[0:i*l//5]
train3 = np.concatenate((train3 ,data_set3[(i+1)*l//5:l]) , axis =0)
test_final = np.concatenate((test1,test2,test3),axis=0)
train_final = np.concatenate((train1,train2,train3), axis=0)
# print (len(train1))
# print (len(train2))
# print (len(train3))
# print (len(train_final))
for k in range (0,int(4*l//5)):
fatigue_train1.append(0)
fatigue_train2.append(1)
fatigue_train3.append(2)
if(k<int(l//5)):
fatigue_test1.append(0)
fatigue_test2.append(1)
fatigue_test3.append(2)
fatigue_train1 += fatigue_train2
fatigue_train1 += fatigue_train3
fatigue_train = np.array(fatigue_train1)
fatigue_test1 += fatigue_test2
fatigue_test1 += fatigue_test3
fatigue_test = np.array(fatigue_test1)
# print(l)
# print (np.array(train_final).shape)
# print(fatigue_train.shape)
clf = svm.SVC(kernel='rbf', C=cc, gamma = gg ,decision_function_shape='ovo')
clf.fit (train_final , fatigue_train)
fatigue_result = clf.predict(test_final)
y = 0
n = 0
for i in range (0,len(fatigue_result)):
if (fatigue_result[i] == fatigue_test1[i]):
y=y+1
else:
n=n+1
accuracy_curr = y/(y+n)
accuracy.append (float(100*accuracy_curr))
accuracy = np.array(accuracy)
#print (accuracy)
mean = accuracy.mean()
std = accuracy.std()
return (mean , std)
'''
| true |
43b894b28b62f5eafaadb23ce4a531dfeb9bec70
|
Python
|
zeeking786/BSCIT_PYTHON_PRACTICAL
|
/PRACTICAL-6/Pract_3.py
|
UTF-8
| 206 | 3.609375 | 4 |
[] |
no_license
|
"""
Write a Python program to read last n lines of a file.
"""
def read_lastnlines(fname,n):
with open('file.txt') as f:
for line in (f.readlines() [-n:]):
print(line)
read_lastnlines('file.txt',2)
| true |
16137fd90e2e3200aced5322f2ca4e2fa43195d9
|
Python
|
simonecampisi97/Voiced-Unvoiced_Speech_Detection
|
/frontend/GUI.py
|
UTF-8
| 4,714 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import font as tkfont
from frontend.HomePage import HomePage
from frontend.GraphicPage import GraphicPage
from frontend.NeuralNetworkPage import NeuralNetworkPage
from frontend.Settings import *
from frontend.Tooltip import ToolTip
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title('VUV SPEECH DETECTION')
self.resizable(RESIZABLE, RESIZABLE)
self.geometry(str(WIDTH_WINDOW) + 'x' + str(HEIGHT_WINDOW))
self.configure(bg=BACK_GROUND_COLOR)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
self.iconbitmap(default='frontend/icons/speech1.ico')
# self.iconwindow(pathName=tk.PhotoImage('frontend/icons/speech1.ico'))
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self, bg=BACK_GROUND_COLOR, borderwidth=0, highlightbackground="black",
highlightcolor="black", highlightthickness=1)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# --------------MENU BAR---------------------------
self.menu_frame = tk.LabelFrame(master=self, height=HEIGHT_WINDOW, width=50,
borderwidth=2, relief='flat', highlightbackground="black",
highlightcolor="black", highlightthickness=1,
bg=SIDE_BAR_COLOR).place(x=0, y=0)
# Home Button
self.home_img = tk.PhotoImage(file='frontend/icons/home.png')
self.home_button = tk.Button(master=self.menu_frame, image=self.home_img, height=25, width=25,
bg=SIDE_BAR_COLOR, command=self.go_home, activebackground=SIDE_BAR_COLOR,
relief='flat')
self.tooltip_home = ToolTip(self.home_button, 'Home Page')
self.home_button.place(x=10, y=15)
# Back Button
self.back_img = tk.PhotoImage(file='frontend/icons/back.png')
self.back_button = tk.Button(master=self.menu_frame, image=self.back_img, height=25, width=25,
bg=SIDE_BAR_COLOR, relief='flat',
command=lambda: self.show_frame("HomePage"), activebackground=SIDE_BAR_COLOR)
self.tooltip_back = ToolTip(self.back_button, 'Back')
self.back_button.place(x=10, y=56)
s = ttk.Style()
s.configure('TSeparator', foreground='black', background='black')
self.separator = ttk.Separator(master=self.menu_frame, orient=tk.HORIZONTAL).place(x=0.3, y=100, relwidth=0.05)
self.button_graphics_img = tk.PhotoImage(file='frontend/icons/graphic.png')
self.button_graphic = tk.Button(master=self.menu_frame, relief='flat', activebackground=SIDE_BAR_COLOR,
image=self.button_graphics_img, height=25, width=25, bg=MENU_COLOR,
command=lambda: self.show_frame("GraphicPage"))
self.tooltip_graphic = ToolTip(self.button_graphic, 'Plot Results and\nModel Evaluation')
self.button_graphic.place(x=10, y=127)
self.neural_img = tk.PhotoImage(file='frontend/icons/neural.png')
self.button_neural = tk.Button(master=self.menu_frame, relief='flat', activebackground=SIDE_BAR_COLOR,
image=self.neural_img, height=25, width=25, bg=MENU_COLOR,
command=lambda: self.show_frame("NeuralNetworkPage"))
self.tooltip_neural = ToolTip(self.button_neural, 'Neural Network Architecture')
self.button_neural.place(x=10, y=180)
self.frames = {}
for F in (HomePage, GraphicPage, NeuralNetworkPage):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
frame.configure(bg=BACK_GROUND_COLOR)
self.show_frame("HomePage")
def show_frame(self, page_name):
"""Show a frame for the given page name"""
frame = self.frames[page_name]
frame.tkraise()
def go_home(self):
self.show_frame('HomePage')
| true |
cc6e6d007b5795082fb99b378b4cb3e60380cb68
|
Python
|
Xg2Acte1Train/01.dl_nithya
|
/14_softmax_classifier.py
|
UTF-8
| 1,848 | 2.6875 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from random import randint
mnist = input_data.read_data_sets("MNIST_data/data", one_hot=True)
print (mnist.train.images.shape)
print (mnist.train.labels.shape)
print (mnist.test.images.shape)
print (mnist.test.labels.shape)
X = tf.placeholder(dtype = tf.float32, shape = (None,784), name='input')
Y = tf.placeholder(dtype = tf.float32, shape = ([None,10]))
W = tf.Variable(initial_value=tf.zeros([784, 10]), dtype = tf.float32)
b = tf.Variable(initial_value=tf.zeros([10], dtype=tf.float32))
XX = tf.reshape(X, [-1, 784])
Z = tf.nn.softmax(tf.matmul(XX, W) + b, name="output")
cost = -tf.reduce_mean(Y * tf.log(Z)) * 1000.0
GD = tf.train.GradientDescentOptimizer(0.005).minimize(cost)
correct_prediction = tf.equal(tf.argmax(Z, 1),tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('log_mnist_softmax',graph=tf.get_default_graph())
for epoch in range(10):
batch_count = int(mnist.train.num_examples/100)
for i in range(batch_count):
batch_x, batch_y = mnist.train.next_batch(100)
c = sess.run([GD, cost], feed_dict={X: batch_x, Y: batch_y})[1]
print ("Epoch: ", epoch)
print ("Accuracy: ", accuracy.eval(feed_dict={X: mnist.test.images,Y: mnist.test.labels}))
print ("done")
num = randint(1, mnist.test.images.shape[1])
img = mnist.test.images[num]
classification = sess.run(tf.argmax(Z, 1), feed_dict={X: [img]})
print('Neural Network predicted', classification[0])
print('Real label is:', np.argmax(mnist.test.labels[num]))
| true |
25c569ad8eefe42a118ce61812f1a34f40af6ca0
|
Python
|
sowrd299/AccountantsFriend
|
/taped_adding_machine.py
|
UTF-8
| 1,547 | 3.234375 | 3 |
[] |
no_license
|
from adding_machine import AddingMachine, CharOp
'''
A class to represent an entry on the tape
'''
class TapeEntry():
fstr = "{0} {1}\n"
def __init__(self, number, op):
self.number = number
self.op = op
def __str__(self):
return self.fstr.format(self.number, self.op)
class TextTapeEntry(TapeEntry):
def __init__(self, text):
self.fstr = "{0}\n".format(text)
super().__init__(0, CharOp("+"))
BLANK_TAPE_ENTRY = TextTapeEntry("")
'''
A class to represent the tape output of an adding machine
'''
class AddingMachineTape():
def __init__(self):
self.entries = []
def append(self, *args, **kwargs):
self.entries.append(TapeEntry(*args, **kwargs))
def new_line(self):
self.entries.append(BLANK_TAPE_ENTRY)
def __str__(self):
r = "".join(map(str, self.entries))
if len(r) > 0 and r[-1] == "\n":
r = r[:-1]
return r
'''
An adding machine that records all its operations to a tape
'''
class TapedAddingMachine(AddingMachine):
def __init__(self):
super().__init__()
self.tape = AddingMachineTape()
def get_tape(self):
return self.tape
def do_op(self, op):
self.tape.append(self.get_number(), op)
return super().do_op(op)
def cache_op(self, op):
self.tape.new_line()
self.tape.append(op.a, op)
return super().cache_op(op)
def do_cached_op(self):
self.tape.new_line()
return super().do_cached_op()
| true |
5f53b8b4507a3c51d2e608ed7098ad749428b27e
|
Python
|
Danbrose/CV_in_Squash
|
/code/centroid_tracker_video.py
|
UTF-8
| 2,671 | 2.765625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
from centroidtracker import CentroidTracker
import json
import itertools
import numpy as np
import cv2
import time
import glob
import os
import sys
from frame_draw import frame_draw
ct = CentroidTracker()
# collects key point files files and puts them in to an ordered list
files = []
for filepath in glob.glob('results/mamatch_1_rally_2_1080_60fps_BODY_25_MaxPeople.json/*.json'):
files.append(filepath)
files = sorted(files)
# enumerates throught the key points calculating metrics related to bounding
# boxes and keypoint centroids returns a list of dicts in the form
# [{0:[box_origin, width, height, centroid, box_colour]}, {1: [...]}] where dict
# entries '0' and '1' are players 1 and 2 repectively
clip_data = []
for i, key_points in enumerate(files):
with open(key_points) as json_file:
data = json.load(json_file)
frame_data = frame_draw(data)
clip_data.append(frame_data)
start = time.time()
pathOut = "center-point_tracking_2.avi"
# Read video
video = cv2.VideoCapture("match_1_rally_2_1080_60fps.mp4")
# Exit if video not opened.
if not video.isOpened():
print( "Could not open video" )
sys.exit()
frame_array = []
n = 0
while True:
# Read a new frame
ok, frame = video.read()
if not ok:
break
rects = []
centroids = []
# loop over both players
for x in clip_data[n][0].values():
# Ploting bounding box from XY start and ends
# p1 = (x[0][0], x[0][1])
# p2 = (x[0][0]+x[1] , x[0][1]+x[2])
# cv2.rectangle(frame, p1, p2, (0, 255, 0), 2, 1)
# box = (x[0][0], x[0][1], x[0][0]+x[1] , x[0][1]+x[2])
# rects.append(box)
# returning centroid coordinates
centroid = x[3]
centroids.append(centroid)
objects = ct.update(centroids)
# loop over the tracked objects
for (objectID, centroid) in objects.items():
# draw both the ID of the object and the centroid of the
# object on the output frame
text = "ID {}".format(objectID)
cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.circle(frame, (centroid[0], centroid[1]), 8, (0, 255, 0), -1)
#inserting the frames into an image array
frame_array.append(frame)
n += 1
height, width, layers = frame.shape
size = (width,height)
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), 60, size)
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
# Release everything if job is finished
out.release()
end = time.time()
duration = end - start
| true |
f5d1ea38dd1cdd4402fde9a4a1406f11f063f600
|
Python
|
PyLamGR/PyLam-Edu
|
/Workshops/11.03.2018 - Python. The Basics - Volume 2 -/Python Codes/8. Αντικειμενοστρεφής Προγραμματισμός/3_another_hierarchy_example.py
|
UTF-8
| 250 | 3.515625 | 4 |
[
"MIT"
] |
permissive
|
class Wolf:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("Grr...")
class Dog(Wolf):
def bark(self):
print("Woof!")
husky = Dog("Max", "grey")
husky.bark()
| true |
2f5c47cfb175172e04550310d99cbeea8e18c483
|
Python
|
montoyamoraga/ai-rapper
|
/script.py
|
UTF-8
| 2,183 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# import libraries
# time for delays
import time
# os for sending commands to bash terminal
import os
# midi library
# pip3 install mido
import mido
# midi library
# pip3 install python-rtmidi
import rtmidi
# read .txt files and strip new line characters
textLil = [line.rstrip("\n") for line in open('lil-wayne.txt')]
textKendrick = [line.rstrip("\n") for line in open('kendrick-lamar.txt')]
# pick voices and rate for terminal
voiceLil = " -v Alex -r 200 "
voiceKendrick = " -v Fred -r 200 "
# calculate the length of shortest
lengthShortest = min(len(textKendrick), len(textLil))
# init counter
counter = 0
# create midi outputs
midiProcessing = rtmidi.MidiOut()
midiVocoder = rtmidi.MidiOut()
# check available ports to pick vocoder
available_ports = midiProcessing.get_ports()
print(available_ports)
vocoderIndex = 0
outProcessing = midiProcessing.open_virtual_port("python-midi")
outVocoder = midiVocoder.open_port(vocoderIndex)
# create messages for showing different
# 0x90 means 144 in decimal
# 144 is note on channel 1
midiLil = [0x90, 60, 112];
midiKendrick = [0x90, 61, 112];
# midi cc control of tune in roland vp-03 vocoder
tuneCC = 79
tuneLil = 0
tuneKendrick = 127
ccLil = [0xb0, 79, 0]
ccKendrick = [0xb0, 79, 127]
os.system("clear")
# infinite loop
while True:
# get next lyrics
lineLil = textLil[counter]
lineKendrick = textKendrick[counter]
# change tune via midi cc
midiVocoder.send_message(ccLil)
time.sleep(0.1)
# send lil wayne midi message
midiProcessing.send_message(midiLil);
# say lil wayne lyric
os.system("clear")
print("[Lil Wayne]: " + lineLil)
os.system("say " + voiceLil + "\"" + str(lineLil) + "\"")
# wait
time.sleep(1.0)
# change tune via midi cc
midiVocoder.send_message(ccKendrick)
time.sleep(0.1)
# send kendrick lamar midi message
midiProcessing.send_message(midiKendrick);
# say kendrick lamar lyric
os.system("clear")
print("[Kendrick Lamar]: " + lineKendrick)
os.system("say " + voiceKendrick + "\"" + str(lineKendrick) + "\"")
# wait
time.sleep(1.0)
# update counter
counter = counter + 1
counter = counter % lengthShortest
| true |
d390c40f7ba739fc393d514ba8b37961548f720a
|
Python
|
pktangyue/LeetCode
|
/python/1535_FindTheWinnerOfAnArrayGame_test.py
|
UTF-8
| 649 | 3.421875 | 3 |
[] |
no_license
|
import unittest
class TestSolution(unittest.TestCase):
def test_getWinner(self):
Solution = __import__('1535_FindTheWinnerOfAnArrayGame').Solution
self.assertEqual(
5,
Solution().getWinner(arr=[2, 1, 3, 5, 4, 6, 7], k=2)
)
self.assertEqual(
3,
Solution().getWinner(arr=[3, 2, 1], k=10)
)
self.assertEqual(
9,
Solution().getWinner(arr=[1, 9, 8, 2, 3, 7, 6, 4, 5], k=7)
)
self.assertEqual(
99,
Solution().getWinner(arr=[1, 11, 22, 33, 44, 55, 66, 77, 88, 99], k=1000000000)
)
| true |
f26751d82b370db73e16e73402391096c3454446
|
Python
|
eclubiitk/Li-Fi-E-Club
|
/Old Codes/FTP v1.0/pyLi-Fi.py
|
UTF-8
| 5,297 | 2.703125 | 3 |
[] |
no_license
|
import serial
import time
import os
recport=input('{:<25}'.format("Input Receiver Port : "))
traport=input('{:<25}'.format("Input Transmitter Port : "))
ser = serial.Serial()
ser.baudrate=230400
ser.port=recport #Receiver-(Slave/Master)
ser.open()
serftr = serial.Serial()
serftr.baudrate=9600
serftr.port=traport #Transmitter-(Master-Slave)
serftr.open()
queue = [0,0,0,0,0,0,0,0,0,0]
start_seq = [1,1,0,0,0,1,0,0,0,1]
end_seq=[0,1,1,0,1,0,0,1,1,1]
x2={'11110':0,
'01001':1,
'10100':2,
'10101':3,
'01010':4,
'01011':5,
'01110':6,
'01111':7,
'10010':8,
'10011':9,
'10110':10,
'10111':11,
'11010':12,
'11011':13,
'11100':14,
'11101':15}
def queuecomp(queue1, queue2) :
if(queue1!=queue2):
return False
return True
ch=input("(T)ransmitter or (R)eceiver : ")
if(ch[0]=='T' or ch[0]=='t'):
print("Initialising Transmitter. Please Wait ...")
time.sleep(5)
fl=input("Text File Path (Leave it empty for text transfer) : ")
lines = []
if(fl!=''):
if(os.path.exists(fl) and os.path.isfile(fl)):
if(os.name=='nt'):
fname=fl.split('\\')
else:
fname=fl.split('/')
fname=fname[-1]
lines.append('file')
lines.append(fname)
fl=open(fl, 'r')
for x in fl:
lines.append(x)
fl.close()
print("File Loaded Successfully.")
else:
print("File Specified doesn't exist.")
else:
lines.append('gentext')
print("Start Entering Input")
while True:
line = input()
if line:
lines.append(line)
else:
break
lines.append('endtrans')
print("Sending ...")
response=""
flag=0
trans=''
ind=0
t1=0
t2=0
while (ind<len(lines)):
trans=lines[ind]+'\n'
serftr.write(trans.encode())
t1=time.time()
while True :
t2=time.time()
if(t2-t1>1):
serftr.write(trans.encode())
t1=t2
while queuecomp(queue, start_seq) == False :
val = int(ser.readline().decode('ascii')[0])
queue.pop(0)
queue.append(val)
t2=time.time()
if(t2-t1>0.5):
serftr.write(trans.encode())
t1=t2
while True:
q=[]
for i in range(10):
queue.pop(0)
val = (ser.readline().decode('ascii')[0])
queue.append(int(val))
q.append(val)
if(queuecomp(queue, end_seq)==True):
flag=1
break
queuex=''.join(q)
q1=x2[queuex[0:5]]
q2=x2[queuex[5:]]
num=q1*16+q2
response=response+chr(num)
if(flag==1):
if(response[0]=='N'):
response=''
break
elif(response[0]=='Y'):
response=''
ind+=1
break
else:
flag=0
print("Sending Successful.")
elif(ch[0]=='R' or ch[0]=='r'):
print("Waiting to Receive ...")
st1=''
st2=''
flag=0
typef=0
fname=''
lnx=0
fobj=open('none','w')
while True :
while queuecomp(queue, start_seq) == False :
val = int(ser.readline().decode('ascii')[0])
queue.pop(0)
queue.append(val)
while True:
q=[]
for i in range(10):
queue.pop(0)
val = (ser.readline().decode('ascii')[0])
queue.append(int(val))
q.append(val)
if(queuecomp(queue, end_seq)==True):
if(st1!=st2):
flag=1
st1=st2
break
else:
flag=2
break
queuex=''.join(q)
q1=x2[queuex[0:5]]
q2=x2[queuex[5:]]
num=q1*16+q2
st2=st2+chr(num)
if(flag==1):
st1=st2
if(st2[:len(st2)-1]=='endtrans'):
if(fname!=''):
fobj.close()
serftr.write('Y\n'.encode())
break
if(typef==2):
print(st2[:len(st2)-1])
if(typef==1):
if(fname==''):
fname=st2[:len(st2)-1]
fobj=open(fname,'w')
else:
if(lnx==0):
lnx+=1
fobj.write(st2[:len(st2)-1])
fobj.write('\r')
else:
fobj.write(st2[1:])
# print(st2[:len(st2)-1])
if(typef==0):
if(st2=='file\n'):
typef=1
else:
typef=2
st2=''
serftr.write('Y\n'.encode())
if(flag==2):
st2=''
serftr.write('Y\n'.encode())
print("Reception Complete!")
else:
print("Wrong Choice. Start pyLi-Fi again.")
| true |
a591f1679b7cf70f4b7b759cd7f7beec999bee3b
|
Python
|
garbhitjain/problem-statement
|
/date to day converter.py
|
UTF-8
| 1,712 | 3.3125 | 3 |
[] |
no_license
|
import calendar
import datetime as dt
import pandas as pd
start = dt.datetime(1970,1,1)
End = dt.datetime(2100,1,1)
dates = pd.date_range(start,End)
def solution(D):
out={'Mon':0,'Tue':0,'Wed':0,'Thu':0,'Fri':0,'Sat':0,'Sun':0}
lis = []
for i,j in D.items():
a,b,c=i.split('-')
y,m,d=int(a),int(b),int(c)
dayNumber = calendar.weekday(y,m,d)
days =["Mon", "Tue", "Wed", "Thu","Fri", "Sat", "Sun"]
day = days[dayNumber]
if day in lis:
a = out[day]
a+=j
out[day] = a
else:
out[day] = j
lis.append(day)
days =["Mon", "Tue", "Wed", "Thu","Fri", "Sat", "Sun"]
for i in range(len(days)):
if days[i] in lis:
pass
else:
out[days[i]]=int((out[days[i-1]]+out[days[(i+1)%7]])/2)
if days[i <= 100000] in lis :
return out
else:
return "Enter Integer value between given range (range = 1 to 100000)"
inp={}
print('How many keys you want to Enter : ')
n = int(input())
for i in range(n):
print('Enter the date: ')
date=input()
if date in inp:
print('Do you want to overwrite previous value (y for yes) : ')
answer=(input())
if(answer == 'y'):
print('Enter the integer value of date : ')
inp[date]=int(input())
else:
i-=1
else:
print('Enter the integer value of date : ')
inp[date]=int(input())
for d in date==dates :
if d:
print(inp)
out=solution(inp)
print(out)
break
else :
print("Enter the date between the given range(range = 1970-01-01 to 2100-01-01)")
| true |
e2e4b619de107749b5761b6a78a3473002de7169
|
Python
|
wjdrkfka3/Valorant_Team_Maker_Python
|
/main.py
|
UTF-8
| 11,092 | 3.015625 | 3 |
[] |
no_license
|
# PyQT 5.0 버전과, 아나콘다 Python 3.6 버전을 사용했습니다.
# PyCharm을 사용하는 경우 File->Settings->Project Interpreter 를 아나콘다 Python 3.6으로 설정해줘야 코드가 올바르게 동작합니다.
import sys
import random
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyApp(QWidget):
def __init__(self):
super().__init__()
# ----- 위젯 생성 시작 -----
self.player_list = []
global listWidget
listWidget = QListWidget() # 리스트박스
listWidget.setFixedSize(150, 250) # 사이즈조절
global nickNameBox
nickNameBox = QLineEdit() # 닉네임박스
nickNameBox.setFixedSize(130, 20) # 사이즈조절
nickNameBox.returnPressed.connect(self.moveToListWidget) # 엔터 칠때 함수 moveToListWidget에 연결
global btn_add
btn_add = QPushButton('추 가') # 추가 버튼
btn_add.clicked.connect(self.moveToListWidget) # 버튼 누를 때 함수 btn_add_Function에 연결
global btn_delete
btn_delete = QPushButton('삭 제') # 삭제 버튼
btn_delete.clicked.connect(self.btn_delete_Function) # 버튼 누를 때 함수 btn_delete_Function에 연결
global txt_setNum
txt_setNum = QLabel('참여 인원 :') # 참여 인원 선택 텍스트
global txt_memberCount
txt_memberCount = QLabel(str(listWidget.count())+' 명') # 참여 인원 텍스트
global btn_makeTeam
btn_makeTeam = QPushButton('팀 생성하기') # 팀 생성하기 버튼
btn_makeTeam.clicked.connect(self.makeTeamOK) # 버튼 기능 함수로 연결
btn_makeTeam.setFixedSize(120, 50) # 사이즈 조절
btn_makeTeam.setCheckable(True) # 선택 가능하게 하기
btn_makeTeam.setChecked(True) # 선택 되어있게 하기
global btn_exit
btn_exit = QPushButton('종료') # 종료 버튼
btn_exit.clicked.connect(QCoreApplication.instance().quit) # 종료 기능 동작
global items
items = [] # 팀 리스트를 섞기 위한 임시 배열
global m_items
m_items = [0, 1, 2, 3] # 맵 리스트륵 섞기 위한 임시 배열
global lbl_maps
lbl_maps = [QLabel('1경기 : 스플릿'), QLabel('2경기 : 바인드'), QLabel('3경기 : 헤이븐'), QLabel('4경기 : 어센트')]
global num
num = []
for i in range(40):
num.append(QLabel())
self.player_list = list(range(1, 41))
global lbl_imgmaps
lbl_imgmaps = [QLabel(), QLabel(), QLabel(), QLabel()]
global img_split
img_split = QPixmap('split.jpg') # 스플릿 이미지 경로 설정
global img_haven
img_haven = QPixmap('haven.jpg') # 헤이븐 이미지 경로 설정
global img_ascent
img_ascent = QPixmap('ascent.jpg') # 어센트 이미지 경로 설정
global img_bind
img_bind = QPixmap('bind.jpg') # 바인드 이미지 경로 설정
lbl_imgmaps[0].setPixmap(QPixmap(img_split.scaledToWidth(150)))
lbl_imgmaps[1].setPixmap(QPixmap(img_haven.scaledToWidth(150)))
lbl_imgmaps[2].setPixmap(QPixmap(img_bind.scaledToWidth(150)))
lbl_imgmaps[3].setPixmap(QPixmap(img_ascent.scaledToWidth(150)))
pixmap = QPixmap('logo_civil_war.png') # 상단 로고 설정
lbl_logo = QLabel() # 레이블 활용하여 로고 설정
lbl_logo.setPixmap(QPixmap(pixmap.scaledToWidth(600))) # 사이즈 조절 (비율에 맞춰서)
# ----- 위젯 생성 끝 -----
# ----- 레이아웃 세부 설정 -----
layout_top_right_high = QHBoxLayout()
layout_top_right_high.addWidget(self.mapBox1())
layout_top_right_high.addWidget(self.mapBox2())
layout_top_right_low = QHBoxLayout()
layout_top_right_low.addWidget(self.mapBox3())
layout_top_right_low.addWidget(self.mapBox4())
layout_top_right = QVBoxLayout()
layout_top_right.addLayout(layout_top_right_high)
layout_top_right.addLayout(layout_top_right_low)
layout_top_left = QVBoxLayout()
layout_top_left.addWidget(self.executeBox())
layout_top_left.addWidget(self.modifyBox())
# layout_top
layout_top = QHBoxLayout()
layout_top.addWidget(listWidget) # 리스트박스 추가
layout_top.addLayout(layout_top_left)
layout_top.addLayout(layout_top_right)
# layout_mid
layout_mid = QHBoxLayout()
layout_mid.addStretch(1)
for i in range(4):
layout_mid.addWidget(self.team_groupbox(i+1))
if (i+1) % 2 == 0:
layout_mid.addStretch(1)
# layout_bottom
layout_bottom = QHBoxLayout()
layout_bottom.addStretch(1)
for i in range(4):
layout_bottom.addWidget(self.team_groupbox(i+5))
if (i+5) % 2 == 0:
layout_bottom.addStretch(1)
# layout_main
layout_main = QVBoxLayout()
layout_main.addWidget(lbl_logo) # 세로 첫줄 로고 추가
layout_main.addLayout(layout_top)
layout_main.addStretch(1)
layout_main.addLayout(layout_mid)
layout_main.addLayout(layout_bottom)
layout_main.addStretch(1)
# ----- 레이아웃 세부 설정 끝 -----
# 기본 설정들
self.setLayout(layout_main) # 레이아웃 설정
self.setWindowTitle('sVeT clan 발로란트 내전 팀 생성기') # 프로그램 제목 설정
self.setWindowIcon(QIcon('icon_svet.ico')) # sVeT 클랜 아이콘 설정
self.setFixedSize(600, 900) # 창 사이즈 조절
self.center() # 창 가운데 함수 실행
self.show()
def center(self): # 창 가운데 함수
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def btn_delete_Function(self): # 삭제 버튼 함수
removeItemText = listWidget.currentRow()
listWidget.takeItem(removeItemText)
txt_memberCount.setText(str(listWidget.count()) + ' 명')
def moveToListWidget(self): # 엔터 버튼 함수
if not nickNameBox.text():
reply = QMessageBox.warning(self, '경고', '닉네임을 네모칸에 입력 후<br>추가버튼을 눌러 추가해주세요.')
elif (listWidget.count()>39):
reply = QMessageBox.warning(self, '경고', '최대 인원인 40명을 초과할 수 없습니다.')
else:
addItemText = nickNameBox.text()
listWidget.addItem(addItemText)
nickNameBox.clear()
txt_memberCount.setText(str(listWidget.count()) + ' 명')
def makeTeamOK(self):
if (listWidget.count()==0):
reply = QMessageBox.warning(self, '경고', '추가된 인원이 없어 팀을 생성할 수 없습니다.')
else:
reply = QMessageBox.warning(self, '팀 생성 완료', '팀 생성이 완료되었습니다.')
self.suffleTeam()
self.insertTeam()
self.suffleMap()
def suffleTeam(self):
items.clear()
for index in range(listWidget.count()):
items.append(listWidget.item(index).text())
random.shuffle(items)
def suffleMap(self):
random.shuffle(m_items)
for i in range(0, 4):
if (m_items[i] == 0):
# 스플릿
lbl_maps[i].setText(str(i + 1) + '경기 : 스플릿')
lbl_imgmaps[i].setPixmap(QPixmap(img_split.scaledToWidth(150)))
elif (m_items[i] == 1):
# 바인드
lbl_maps[i].setText(str(i + 1) + '경기 : 바인드')
lbl_imgmaps[i].setPixmap(QPixmap(img_bind.scaledToWidth(150)))
elif (m_items[i] == 2):
# 헤이븐
lbl_maps[i].setText(str(i + 1) + '경기 : 헤이븐')
lbl_imgmaps[i].setPixmap(QPixmap(img_haven.scaledToWidth(150)))
elif (m_items[i] == 3):
# 어센트
lbl_maps[i].setText(str(i + 1) + '경기 : 어센트')
lbl_imgmaps[i].setPixmap(QPixmap(img_ascent.scaledToWidth(150)))
def insertTeam(self):
for i in range(len(items)):
self.player_list[i] = items[i]
num[i].setText(self.player_list[i])
for i in range(len(items), 40):
num[i].clear()
def team_groupbox(self, team_num):
end_idx = team_num * 5
start_idx = end_idx - 5
groupbox = QGroupBox('Team #'+str(team_num))
vbox = QVBoxLayout()
for i in range (start_idx, end_idx):
vbox.addWidget(num[i])
groupbox.setLayout(vbox)
groupbox.setFixedSize(130, 180)
return groupbox
def modifyBox(self):
groupbox = QGroupBox()
grid = QGridLayout()
grid.addWidget(txt_setNum, 0, 0) # 현재 참여 인원 텍스트 추가
grid.addWidget(txt_memberCount, 0, 1) # 현재 참여 인원 카운트 추가
grid.addWidget(nickNameBox, 1, 0) # 닉네임박스 추가
grid.addWidget(btn_add, 2, 0) # 추가 버튼 추가
grid.addWidget(btn_delete, 2, 1) # 삭제 버튼 추가
groupbox.setLayout(grid)
groupbox.setFixedSize(150, 120) # 사이즈 조절
return groupbox
def executeBox(self):
groupbox = QGroupBox()
grid = QGridLayout()
version = QLabel('Ver 2.0')
grid.addWidget(btn_makeTeam, 0, 0)
grid.addWidget(version, 1, 0)
grid.addWidget(btn_exit, 1, 3)
groupbox.setLayout(grid)
groupbox.setFixedSize(150, 120) # 사이즈 조절
return groupbox
def mapBox1(self):
groupbox = QGroupBox()
grid = QGridLayout()
grid.addWidget(lbl_imgmaps[0], 0, 0)
grid.addWidget(lbl_maps[0], 1, 0)
groupbox.setLayout(grid)
groupbox.setFixedSize(120, 120)
return groupbox
def mapBox2(self):
groupbox = QGroupBox()
grid = QGridLayout()
grid.addWidget(lbl_imgmaps[1], 0, 0)
grid.addWidget(lbl_maps[1], 1, 0)
groupbox.setLayout(grid)
groupbox.setFixedSize(120, 120)
return groupbox
def mapBox3(self):
groupbox = QGroupBox()
grid = QGridLayout()
grid.addWidget(lbl_imgmaps[2], 0, 0)
grid.addWidget(lbl_maps[2], 1, 0)
groupbox.setLayout(grid)
groupbox.setFixedSize(120, 120)
return groupbox
def mapBox4(self):
groupbox = QGroupBox()
grid = QGridLayout()
grid.addWidget(lbl_imgmaps[3], 0, 0)
grid.addWidget(lbl_maps[3], 1, 0)
groupbox.setLayout(grid)
groupbox.setFixedSize(120, 120)
return groupbox
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
| true |
1d2ea1012518151e6549e8b681270fda57f14804
|
Python
|
1205-Sebas/TALLERCV-GOMEZ-DIAZ
|
/Ejercicio6.py
|
UTF-8
| 926 | 3.90625 | 4 |
[] |
no_license
|
"""
6. Elaborar un algoritmo que permita realizar el inventario de una tienda, es decir cuántas unidades de
cada tipo de producto existen actualmente en la tienda. Se debe imprimir una lista ordenada de
productos de menor a mayor cantidad.
"""
import operator
a=int(input("Cantidad Aceite:"))
b=int(input("Cantidad Arroz:"))
c=int(input("Cantidad Cerveza:"))
d=int(input("Cantidad Gaseosa:"))
e=int(input("Cantidad Panela:"))
f=int(input("Cantidad Azucar:"))
g=int(input("Cantidad Cafe:"))
nombres={"Aceite:":a,"Arroz:":b,"Cerveza:":c,"Gaseosa:":d,"Panela:":e,"Azucar:":f,"Cafe:":g}
clients_sort = sorted(nombres)
clients_sort
clients_sort = sorted(nombres.items())
clients_sort
clients_sort = sorted(nombres.items(), key=operator.itemgetter(1), reverse=False)
print("INVENTARIO")
for name in enumerate(clients_sort):
print(name[1][0],nombres[name[1][0]])
t=int(input("Ingrese el promedio: ",i))
| true |
65b6944385052d0871663a9f4e1a28e6b5331e10
|
Python
|
tmu-nlp/NLPtutorial2017
|
/bambi/tutorial13/beam.py
|
UTF-8
| 3,019 | 2.640625 | 3 |
[] |
no_license
|
from collections import defaultdict
import math
file = "../../data/wiki-en-test.norm"
emission = defaultdict(int)
transition = defaultdict(lambda: 1) # 1 to prevent log(0) raise math domain error and the log(1) == 0
possible_tags = defaultdict(int)
def key(*names):
return " ".join(map(str,names))
def cal_score(best_score,transition,score_key,trans_key,emis_key):
'''
PT(yi|yi-1) = PML(yi|yi-1)
PE(xi|yi) = λ PML(xi|yi) + (1-λ) 1/N
'''
lamb_ = 0.95
V = 1000000
P_emit = math.log(lamb_ * emission[emis_key] + ((1.0-lamb_)/V),2)
return float(best_score[score_key]) - float(math.log(transition[trans_key],2)) - float(P_emit)
for line in open("model_hmm.txt"):
word_type, context, word, prob = line.strip("\n").split(" ")
possible_tags[context] = 1
# enumerate all tags
if word_type == "T":
transition["{} {}".format(context,word)] = float(prob)
else:
emission["{} {}".format(context,word)] = float(prob)
B = 10
def beam(line):
words = line.strip("\n").split()
l = len(words)
best_score = {}
best_edge = {}
active_tags = []
active_tags.append(["<s>"])
best_score["0 <s>"] = 0 # Start with <s>
best_edge["0 <s>"] = None
for i in range(0, len(words)):
my_best = {}#add from previous hmm
for prev in active_tags[i]: #add from previous hmm
for next_tag in possible_tags.keys():
if key(i,prev) in best_score and key(prev,next_tag) in transition:
score = cal_score(best_score,transition,key(i,prev),key(prev,next_tag),key(next_tag, words[i]))
if key(i+1,next_tag) not in best_score or best_score[key(i+1,next_tag)] > score:
best_score[key(i+1,next_tag)] = score
best_edge[key(i+1,next_tag)] = key(i,prev)
my_best[next_tag] = score #add from previous hmm
my_best_B_elements = [k for k, v in sorted(my_best.items(), key = lambda x:x[1])[:B]]# small v is better
active_tags.append(my_best_B_elements)
for prev in active_tags[i]:#add from previous hmm
score_key = "{} {}".format(l, prev)
trans_key = "{} </s>".format(prev)
emis_key = trans_key
last_score_key = "{} </s>".format(l+1)
if score_key in best_score:
score = cal_score(best_score,transition,score_key,trans_key,emis_key)
if last_score_key not in best_score or best_score[last_score_key] > score:
best_score[last_score_key] = score
best_edge[last_score_key] = score_key
tags = []
next_edge = best_edge["{} </s>".format(l+1)]
while next_edge != "0 <s>":
position, tag = next_edge.split()
tags.append(tag)
next_edge = best_edge[next_edge]
tags.reverse()
answer = " ".join(tags)
print(answer)
return answer
with open("beam.pos","w") as output:
for line in open(file):
print(beam(line), file=output)
print("finished")
| true |
9d260d8f40d3fc5766021687182d98bffa53be91
|
Python
|
alisonflint/urban-data-challenge-sf
|
/sf-urban-transit/extract_d3_graph.py
|
UTF-8
| 1,193 | 2.671875 | 3 |
[] |
no_license
|
import csv
import json
import gzip
import sys
STOPID = 1
ON = 3
OFF = 4
LOAD = 5
MONTH = 6
DAY = 7
YEAR = 8
TIMESTOP = 15
TIMEDOORCLOSE = 16
TIMEPULLOUT = 17
TRIPID = 18
DATE_FMT = "%H:%M:%S"
def getGraphJson(passenger_count_file):
csv_file = csv.reader(gzip.open(passenger_count_file, 'rb'))
csv_lines = list(csv_file)
node_map = {}
link_set = set()
node_index = 0
for i in xrange(1, len(csv_lines)-1):
if (csv_lines[i][TRIPID] != csv_lines[i+1][TRIPID]):
continue;
base_stopid = int(csv_lines[i][STOPID])
next_stopid = int(csv_lines[i+1][STOPID])
if base_stopid not in node_map:
node_map[base_stopid] = node_index;
node_index += 1;
if next_stopid not in node_map:
node_map[next_stopid] = node_index;
node_index += 1;
link_set.add((node_map[base_stopid], node_map[next_stopid]))
links = []
for source, target in link_set:
links.append({"source": source, "target": target, "value": 1.0})
nodes = []
for node in node_map:
nodes.append({"name": node})
return {"nodes": list(nodes), "links": links}
if __name__ == "__main__":
graph = getGraphJson(sys.argv[1])
print json.dumps(graph, indent=2)
| true |
631121e112aa5e21fa8052c693dbe555c3632c53
|
Python
|
jonathan-carvalho/Modelagem-ARIMA
|
/code/main.py
|
UTF-8
| 2,231 | 2.5625 | 3 |
[] |
no_license
|
from identificacao import *
from estimacao import *
from diagnostico import *
from graficos_resultado import *
import sys
from pandas import Series
from itertools import product
class Modelo:
p = 0
d = 0
q = 0
pesos_autoregressivos = []
pesos_medias_moveis = []
ruidos_estimados = []
autocorrelacoes_ruidos = []
Q_valor_portmanteau = 0
p_valor_portmanteau = 0
arquivo_serie = sys.argv[1]
caminho = '..\Datasets\\' + arquivo_serie + '.csv'
serie_temporal = Series.from_csv(caminho, index_col=None)
serie_temporal.index = range(1, serie_temporal.size+1)
d, serie_diferenciada = diffs_estacionariedade(serie_temporal.values)
print('Estimação dos parâmetros:')
modelos_ajustados = []
for quantidades_pesos in product(range(5), repeat=2):
p = quantidades_pesos[0]
q = quantidades_pesos[1]
print('Modelo ARIMA(' + str(p) + ',' + str(d) + ',' + str(q) + ')')
modelo = Modelo()
modelo.p = p
modelo.d = d
modelo.q = q
modelo = estimacao_parametros(modelo, serie_diferenciada, d)
modelos_ajustados.append(modelo)
print('\nDiagnosticando os modelos ...')
maximo_p = 0
for modelo in modelos_ajustados:
resultado_portmanteau = portmanteau_teste(modelo)
modelo.Q_valor_portmanteau = round(resultado_portmanteau.estatistica_Q, 2)
modelo.p_valor_portmanteau = round(resultado_portmanteau.valor_p, 2)
modelo.autocorrelacoes_ruidos = resultado_portmanteau.autocorrelacoes
if modelo.p_valor_portmanteau > maximo_p:
maximo_p = modelo.p_valor_portmanteau
modelo_selecionado = modelo
print('\nModelo Selecionado: ARIMA(' + str(modelo_selecionado.p) +
',' + str(modelo_selecionado.d) +
',' + str(modelo_selecionado.q) + ')')
print('Pesos AR:')
print(modelo_selecionado.pesos_autoregressivos)
print('Pesos MA:')
print(modelo_selecionado.pesos_medias_moveis)
print('Estatística Q: ' + str(modelo_selecionado.Q_valor_portmanteau))
print('Valor p: ' + str(modelo_selecionado.p_valor_portmanteau))
exibir_fac_ruido(modelo_selecionado.autocorrelacoes_ruidos, modelo_selecionado.ruidos_estimados.size)
comparacao_esperado_obtido(serie_temporal, modelo_selecionado)
| true |
d9990cf65a3159d27605298d48406ec611699755
|
Python
|
anastasiia-l/rateskill-backend
|
/api/utils/twitter_manager.py
|
UTF-8
| 1,131 | 2.765625 | 3 |
[] |
no_license
|
import os
import re
import tweepy
class TwitterManager(object):
def __init__(self):
self.consumer_key = os.environ.get('CONSUMER_KEY', '')
self.consumer_key_secret = os.environ.get('CONSUMER_KEY_SECRET', '')
self.access_token = os.environ.get('ACCESS_TOKEN', '')
self.access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET', '')
self.auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_key_secret)
self.auth.set_access_token(self.access_token, self.access_token_secret)
self.api = tweepy.API(self.auth)
def get_user_tweets(self, screen_name, count=20):
return self.api.user_timeline(screen_name=screen_name, count=count, tweet_mode='extended')
def get_tweet_content(self, tweet):
return tweet.retweeted_status.full_text if 'retweeted_status' in tweet._json else tweet.full_text
def clean_tweet(self, tweet):
'''
Cleans tweet text by removing links,
special characters - using regex statements.
'''
return ' '.join(re.sub("([^0-9A-Za-z.,!:%’ \t])|(\w+:\/\/\S+)", " ", tweet).split())
| true |
f6f2f6fe96d8848c3d975c68dddca68d9698a9c1
|
Python
|
ArtemKurchakov/git_home_project
|
/artem_boxer.py
|
UTF-8
| 218 | 3.40625 | 3 |
[] |
no_license
|
class Boxer():
def __init__(self, age, weight, height):
self.age = age
self.weight = weight
self.height = height
artem = Boxer(34, 100, 187)
print(artem.age, artem.weight, artem.height)
| true |
c77e50903a278db96db61c4ebcea3c2e8ed7ca9e
|
Python
|
Aakash-kaushik/machine-learning
|
/multivariate_linear_regression_normal_equation/multivariate_linear_regression_normal_equation.py
|
UTF-8
| 855 | 3.015625 | 3 |
[
"Unlicense"
] |
permissive
|
import pandas as pd
import numpy as np
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
data=pd.read_csv("data2.txt")
nor_data=data#(data-data.mean())/data.std()
nor_data=np.array(nor_data)
x=np.array(nor_data[:,0:2])
y=np.array(nor_data[:,2])
x_one=np.append(np.ones([np.size(x,0),1]),x,axis=1)
#plotting the data
fig=plt.figure()
ax=plt.axes(projection='3d')
ax.scatter3D(x[:,0],x[:,1],y)
plt.show()
#solving with normal equation
y=y.reshape(-1,1)
theta=np.zeros([np.size(x,1)+1,1])
theta=np.matmul(np.matmul(np.linalg.inv(np.matmul(x_one.transpose(),x_one)),x_one.transpose()),y)
print("the values of theta are "+str(theta))
y_pred=np.inner(theta.transpose(),x_one).transpose()
fig=plt.figure()
ax=plt.axes(projection='3d')
ax.scatter3D(x[:,0],x[:,1],y,color='green')
ax.scatter3D(x[:,0],x[:,1],y_pred,color='red')
plt.show()
| true |
d277d7e51cb7a846811b1a4d9b1a3516e206aa55
|
Python
|
jonathantsang/CompetitiveProgramming
|
/binarysearchio/contest10/2.py
|
UTF-8
| 930 | 3.15625 | 3 |
[] |
no_license
|
from collections import defaultdict, deque
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
leaves = defaultdict(int) # node # -> depth for leaves
q = deque([(root, 0, "")])
while q:
node, d, part = q.popleft()
if node.left:
q.append((node.left, d+1, part + str(node.val)))
if node.right:
q.append((node.right, d+1, part + str(node.val)))
if node.left == None and node.right == None:
leaves[part] = d
# get second highest value
m1 = -1
m2 = -1
for l in leaves:
if leaves[l] > m1:
m2 = m1
m1 = leaves[l]
elif leaves[l] > m2:
m2 = leaves[l]
return m2
| true |
0182597bbef24e7ae027802d3a768517b5c24cac
|
Python
|
AreebsUddinSiddiqui/OOADActivities
|
/Vehicle.py
|
UTF-8
| 360 | 2.53125 | 3 |
[] |
no_license
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
class Vehicle:
def __init__(self):
self.regNo = None
self.Year = None
self.LicenseNo = None
def Forward(self, ):
pass
def Backward(self, ):
pass
def Stop(self, ):
pass
def TurnRight(self, ):
pass
def Turn Left(self, ):
pass
| true |
cb460913396929324a2ced58b7a29bc4d9459da5
|
Python
|
sibowi/equivariant-spherical-deconvolution
|
/generate_data/5_nii_to_mif.py
|
UTF-8
| 2,436 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file convert a nii file into a mif file.
If you find bugs and/or limitations, please email axel DOT elaldi AT nyu DOT edu.
"""
import argparse
import os
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--path',
default='data',
help='The root path to the gradients directory (default: data)',
type=str
)
parser.add_argument(
'--path_bvals_bvecs',
help='The root path to the bvals and bvecs directory (default: None)',
type=str
)
parser.add_argument(
'--mask',
action='store_true',
help='Transform the max (default: False)'
)
# Parse the arguments
args = parser.parse_args()
path = args.path
path_bvals_bvecs = args.path_bvals_bvecs
mask = args.mask
if not os.path.exists(path):
print("Path doesn't exist: {0}".format(path))
raise NotADirectoryError
# Check if directory exist
if mask:
gradient_nii_path = os.path.join(path, 'mask.nii')
gradient_mif_path = os.path.join(path, 'mask.mif')
cmd = "mrconvert {0} {1}".format(gradient_nii_path, gradient_mif_path)
else:
gradient_nii_path = os.path.join(path, 'features.nii')
gradient_mif_path = os.path.join(path, 'features.mif')
bvecs_path = os.path.join(path_bvals_bvecs, 'bvecs.bvecs')
bvals_path = os.path.join(path_bvals_bvecs, 'bvals.bvals')
cmd = "mrconvert {0} {1} -fslgrad {2} {3}".format(gradient_nii_path, gradient_mif_path, bvecs_path, bvals_path)
if not os.path.exists(bvecs_path):
print("Path doesn't exist: {0}".format(bvecs_path))
raise NotADirectoryError
if not os.path.exists(bvals_path):
print("Path doesn't exist: {0}".format(bvals_path))
raise NotADirectoryError
print('Load bvals file from: {0}'.format(bvals_path))
print('Load bvecs file from: {0}'.format(bvecs_path))
if not os.path.exists(gradient_nii_path):
print("Path doesn't exist: {0}".format(gradient_nii_path))
raise NotADirectoryError
print('Load nii file from: {0}'.format(gradient_nii_path))
print('Write mif file to: {0}'.format(gradient_mif_path))
print('Run command: {0}'.format(cmd))
os.system(cmd)
| true |
23b07f6c6945667965fdcce7fbc129766448679a
|
Python
|
veronicarose27/plaaaa
|
/aaac.py
|
UTF-8
| 153 | 3.34375 | 3 |
[] |
no_license
|
p=input()
count=0
for i in p:
if(i!='a' and i!='b'):
count=count+1
if(count==1 or count==0):
print('yes')
else:
print('no')
| true |
556c5e31acd4927d9f586c42907cb37a2c760474
|
Python
|
louay-075/CyberBlindTech-python-lessons
|
/lesson-2.py
|
UTF-8
| 107 | 3.203125 | 3 |
[] |
no_license
|
name = "louay"
last_name = "eloudi"
age = "26"
print "I am " + name + last_name + "and I am" + age
| true |
11765e8f0974e8976174b81f0638699d4912e5ed
|
Python
|
hegangmas/MySourceLib
|
/CppCallPy/mymod.py
|
UTF-8
| 217 | 2.875 | 3 |
[] |
no_license
|
import random
def a():
print "func a"
def square(a):
return a**2
def add(a,b):
return a+b
def addString(a,b):
return a*b
def normal(a,b):
return random.normalvariate(a,b);
| true |
887f6cd9b5d3e9b78c77de00e6d2c5009a8d8d70
|
Python
|
juarezpaulino/coderemite
|
/problemsets/Codeforces/Python/B227.py
|
UTF-8
| 232 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
a=[0]*(n+1)
for i,x in enumerate(map(int,input().split())):
a[x]=i
x=y=0
input()
for u in map(int,input().split()):
x+=a[u]+1
y+=n-a[u]
print(x,y)
| true |
3c46dc823b79445c287858cfc2f64f238e5b3e3e
|
Python
|
chenzw93/python
|
/python/python_demo/first/typeOfData.py
|
UTF-8
| 1,806 | 4.28125 | 4 |
[] |
no_license
|
'''
数据类型
整数
浮点数
字符串
list
tuple
dict
set
1. set、dict 只能是不可变类型数据,{}
2. tuple 即为数组,元素个数确定 ()
3. list 可变集合 []
条件判断:
if 条件:执行语句
if 条件: 执行语句 elif 条件: 执行语句 else:执行语句
循环:
while
for xxx in xxx
continue
break
'''
# name = 10
# print(name)
#
# name = 1.1
# print(name)
#
# name = 'dd'
# print(name)
#
# print('''ffff
# ...dddd
# ...aaa''')
#
# print('fff\\')
# print(r'fff\\')
#
# print('%2d-%02d' % (3, 1))
# print('%.2f' % 3.1415926)
#
# s1 = 72
# s2 = 85
# r = (s2 -s1) / s1 * 100
# print(r)
# print('%.1f%%' % r)
'''
list features:
1. 元素类型可以不一致,可以嵌套list
2.
'''
# lists = [111, 222, 333]
# len(lists)
# print(lists[0])
# print(lists[-1])
# print(lists)
# lists.pop(0);
# print(lists)
#
# names = ['Bart', 'Lisa', 'Adam']
# for name in names:
# print('hello, %s!' % name)
'''
tuple
元素的指向永不变,同时元素类型可以多种,嵌套list等,
'''
# tuples = ()
'''
dict(dictionary): 字典,即map,键值对
'''
# dicts = {'name':"xiaobei","age": 1,"address":"baoji",10:'age'}
# print(dicts.get('names') is None)
# print(dicts.get(10) is None)
# print(dicts['name'])
# # print(dicts['names'])
# print(dicts[10])
'''
set
'''
# sets = set((1, 2, 3))
# print(sets)
# print(type(sets))
'''
if : xxx elif: xxx
'''
# age = 10
# if age == 10 :
# print("age > 10")
# print("age <= 10")
#
# birth = int(input('birth: '))
# if birth > 2000 :
# print("age <= 20")
# else:
# print("age > 20")
| true |
612a74f5a62ff67027bf82a27dc183a4163b886f
|
Python
|
tomboxfan/PythonExample
|
/exercise/001/P001V3.py
|
UTF-8
| 125 | 3.09375 | 3 |
[] |
no_license
|
# 之前的输出结果不好看
for i in range(1, 5):
for j in range(1, 5):
num = i * 10 + j
print(num)
| true |
0eb2cd02f917d217cbe173235b53491a3f7b8905
|
Python
|
fatihyasar/grower-firmware
|
/relay.py
|
UTF-8
| 712 | 3.078125 | 3 |
[] |
no_license
|
import time
import grovepi
# Connect the Grove Relay to digital port D4
# SIG,NC,VCC,GND
grovepi.pinMode(2,"OUTPUT")
grovepi.pinMode(3,"OUTPUT")
grovepi.pinMode(4,"OUTPUT")
grovepi.pinMode(5,"OUTPUT")
grovepi.pinMode(6,"OUTPUT")
grovepi.pinMode(7,"OUTPUT")
def open(relayNumber):
grovepi.digitalWrite(relayNumber,1)
time.sleep(2)
print (relayNumber, ".relay turned on " )
def close(relayNumber):
grovepi.digitalWrite(relayNumber,0)
time.sleep(2)
print (relayNumber, ".relay turned off " )
########################
# Main
########################
if "__main__" == __name__:
print "running console mode"
for x in range(2, 8):
open(x)
close(x)
quit()
| true |