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 |
---|---|---|---|---|---|---|---|---|---|---|---|
f2ee8a91493fc943872ab6c503c1edf2f7e73ea6
|
Python
|
GarrettMooney/moonpy
|
/tests/conftest.py
|
UTF-8
| 325 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
import pytest
@pytest.fixture(scope="module")
def data():
return {
"data": {"a": 1, "c": 3, "b": 2},
"file_contents": '{\n "hello": "world"\n}',
"invalid_file_contents": '{\n "hello": world\n}',
"file_name": "tmp.json",
"sorted_file_contents": '{"a":1,"b":2,"c":3}',
}
| true |
f152fa1ecf8d134c9da19aabc612e8427caffd9f
|
Python
|
Sarastro72/Advent-of-Code
|
/2019/16/puzzle2.py
|
UTF-8
| 586 | 3.09375 | 3 |
[] |
no_license
|
#!/usr/local/bin/python3
with open("input") as fp:
string = fp.readline().strip()
input = list(map(int, list(string)))
input = input * 10000
skip = int("".join([str(i) for i in input[:7]]))
length = len(input)
count = 1
for i in range(100):
output = [0] * length
for p in range(length-1, skip-1, -1):
if (p == length-1):
output[p] = input[p]
else:
output[p] = (input[p] + output[p + 1]) % 10
input = output
print(f"{count}\r", end="")
count += 1
ostr = "".join([str(d) for d in output[skip:skip+8]])
print(ostr)
| true |
98d5ed72f32044d030a84b51e1be48657e190fdd
|
Python
|
Paryaxify/450dsa
|
/Practice/LeetCode/97_interleaving_strings.py
|
UTF-8
| 1,395 | 3.953125 | 4 |
[] |
no_license
|
def isInterleaving(s1: str, s2: str, s3: str) -> bool:
l1 = len(s1)
l2 = len(s2)
l3 = len(s3)
# check whether the length of s3 is comparable to s1 and s2 or not
if l1 + l2 != l3:
return False
# set starting pointer to 0 for the strings
queue = [(0, 0)]
# add to visited set if the index has been visited
visited = set((0, 0))
while queue:
# starting from front of queue
s1_index, s2_index = queue.pop(0)
if s1_index + s2_index == l3:
return True
# check whether current index is less than the length of list
# check if current index is the current index of the interleaved string
# check whether the current queue exists in visited
if s1_index + 1 <= l1 and s1[s1_index] == s3[s1_index + s2_index] and (s1_index + 1, s2_index) not in visited:
# add the index to queue and mark it as visited
queue.append((s1_index + 1, s2_index))
visited.add((s1_index + 1, s2_index))
if s2_index + 1 <= l2 and s2[s2_index] == s3[s1_index + s2_index] and (s1_index, s2_index + 1) not in visited:
queue.append((s1_index, s2_index + 1))
visited.add((s1_index, s2_index + 1))
# loop continues until the queue isnt empty
return False
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac"
print(isInterleaving(s1, s2, s3))
| true |
9792aaf92212eddfc97e299cd331fc73b29a6f8c
|
Python
|
jainharshit27/P7_T
|
/P7_T.py
|
UTF-8
| 600 | 3.078125 | 3 |
[] |
no_license
|
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
countdown = 10
font = pygame.font.Font("freesansbold.ttf", 32)
# Add while condition such that the countdown will run until it is greater than 0
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# render the number
# paste the rendered number
# decrease countdown by 1
pygame.display.update()
# Delay the program by 1
if countdown == 0:
pygame.quit()
sys.exit()
| true |
46ed010784b55a81bde3a397700150a9f7d2c3c9
|
Python
|
vanyaeccles/Android-HumanActivityRecognition
|
/Networking/basicUDPSocket.py
|
UTF-8
| 1,126 | 3 | 3 |
[] |
no_license
|
import socket, traceback
import time, os
from datetime import datetime
import keyboard
#simple script that streams data from port 5555 to the terminal
host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
print("Socket has been set up")
#naming the file
#activity_label = input("Please enter a label for the activity: \n")
#get the time as a name
timestr = time.strftime("%d,%m,%Y--%H,%M,%S")
##script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
##filename = "Data/" + activity_label + ',' + timestr +".csv"
##filename = os.path.join(script_dir, filename)
while 1:
if keyboard.is_pressed('q'):#if key 'q' is pressed
print('You Pressed A Key!')
break#finishing the loop
#get the message as utf text
message, address = s.recvfrom(8192)
messageString = message.decode("utf-8")
#print to console
print(messageString)
print()
print("Done streaming")
| true |
0d960d2896624690a3c6de42e2e87016fb9db46b
|
Python
|
laurenah/image-downloader
|
/download_images.py
|
UTF-8
| 1,988 | 3.84375 | 4 |
[] |
no_license
|
# imports
import urllib.request
import argparse
# parser
parser = argparse.ArgumentParser(description="Download multiple images from a URL into the folder where this file is located. For example: " +
"using 'https://acnhapi.com/v1/icons/fish/' as the base URL, where every fish has an id from 1 to 80, " +
"you would input the URL, maybe 'fish' as the image category, the starting id and the ending id. " +
"This will save images named 'fish1.jpg', 'fish2.jpg' etc. into the folder where this file is executed")
# add arguments
parser.add_argument('-url', metavar='url', type=str, help='the base URL - should follow this format: https://site/image_category/')
parser.add_argument('-img', metavar='img', type=str, help='the main image name/category - for example: animal, or person. This assumes the site hosts an image for each item given the item id')
parser.add_argument('-start', metavar='start', type=int, help='the starting id of the images to download, must be a positive integer, and less than the end argument')
parser.add_argument('-end', metavar='end', type=int, help='the ending id of the images to download, must be a positive integer, and greater than the start argument')
# execute parse_args() method
args = parser.parse_args()
# collect args into variables
base_url = args.url
image_name = args.img
start = args.start
end = args.end
if (start <= 0 or start > end):
print('start must not be negative or greater than end argument')
exit()
if (end <= 0 or end < start):
print('end must not be negative, or less than start argument')
exit()
# for each id in the range supplied, fetch the image
for i in range(start, end+1):
urllib.request.urlretrieve(base_url + str(i), image_name + str(i) + ".jpg")
print("Downloaded " + image_name + str(i) + ".jpg")
print("-- Finished! --")
| true |
294e88c3aea81842e5a0ad76ef6e63b1f8a2bc5e
|
Python
|
dongyifeng/algorithm
|
/python/interview/matrix/transposition.py
|
UTF-8
| 364 | 3.453125 | 3 |
[] |
no_license
|
#coding:utf-8
# 矩阵倒置
# 将倒置矩阵
def transposition(matrix):
if matrix is None and len(matrix) > 0:return
n = len(matrix)
m = len(matrix[0])
if m <= 0 :return
r = [[0 for j in range(n)] for i in range(m)]
for i in range(n):
for j in range(m):
r[j][i] = matrix[i][j]
return r
m = [[1,2,3],[4,5,6]]
print m
t = transposition(m)
print t
| true |
e8cea498bf64d7ac16d4b2b8c218885b0d3a9c10
|
Python
|
gsi-upm/soba
|
/projects/GreenSOBA/agents/light.py
|
UTF-8
| 1,814 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
from transitions import Machine
from mesa import Agent, Model
from transitions import State
import configuration.settings
class Light(Agent):
states = [
State(name='off', on_enter=['set_off']),
State(name='on', on_enter=['set_on'])
]
def __init__(self, unique_id, model, room):
super().__init__(unique_id, model)
self.room = room
self.consume = configuration.settings.consume_light_byroom_medium
self.wait_off = int(configuration.settings.time_to_off_light * 60 * 100 /configuration.settings.time_by_step)
self.machine = Machine(model=self, states=Light.states, initial='off')
self.machine.add_transition('switch_on', '*', 'on')
self.machine.add_transition('switch_off', '*', 'off')
def sensorCheck(self):
userInRoom = self.model.ThereIsSomeOccupantInRoom(self.room)
if userInRoom == True:
if self.state == 'on':
pass
else:
self.switch_on()
else:
if self.state == 'on':
if self.wait_off > 0:
self.wait_off = self.wait_off - 1
else:
self.switch_off()
self.wait_off = int(configuration.settings.time_to_off_light * 60 * 100 /configuration.settings.time_by_step)
else:
pass
def regularBehaviour(self):
pass
def step(self):
#print('light: ', self.unique_id, self.state, self.room.name)
self.model.consumeEnergy(self)
if (self.model.modelWay != 0):
self.sensorCheck()
else:
self.regularBehaviour()
def set_off(self):
self.model.lightsOn.remove(self)
def set_on(self):
self.model.lightsOn.append(self)
| true |
20ef51f2dbb8e3f48f4b3dd0baebb73d8834500f
|
Python
|
3dankateers/nitrogenspider
|
/pro_match.py
|
UTF-8
| 9,504 | 2.65625 | 3 |
[] |
no_license
|
## Model for match
## matches: id, team1_name, team2_name, map_number, match_day, champs1, champs2, win, match_date, is_test, tournament_id, first_blood, kills_5, status
##odds (is embedded inside ProMatch)
## status possibilities: "nitrogen" or "csv or "both" or None
from nitrogen_db_client import NitrogenDbClient
from odd import Odd
from tournament import Tournament
PATCH = "6.13"
class ProMatch:
##Required on creation: team1_name, team2_name, map_number, match_day
##Possibly populated later by csv file: champs1, champs2, win, first_blood, kills_5, red_side
##Possibly populated later by nitrogen scraper: tournament_id, match_date, odds
## set programmatically: id, is_test, status
def __init__(self, team1_name, team2_name, map_number, match_day, red_side = None, champs1 = None, champs2 = None, win = None, match_date = None, odds = [], is_test = None, tournament_id = None, first_blood = None, kills_5 = None, status = None, id = None, patch = PATCH):
self.id = id
self.team1_name = team1_name
self.team2_name = team2_name
self.map_number = map_number
self.match_day = match_day
self.red_side = red_side
self.champs1 = champs1
self.champs2 = champs2
self.win = win
self.match_date = match_date
self.odds = odds
self.is_test = is_test
self.tournament_id = tournament_id
self.first_blood = first_blood
self.kills_5 = kills_5
self.status = status
self.to_invert = False
self.patch = patch
##constructor from Cursor
@classmethod
def from_dict(cls, c):
id = c["_id"]
team1_name = c["team1_name"]
team2_name = c["team2_name"]
map_number = c["map_number"]
match_day = c["match_day"]
red_side = c["red_side"]
champs1 = c["champs1"]
champs2 = c["champs2"]
win = c["win"]
match_date = c["match_date"]
odds = c["odds"]
is_test = c["is_test"]
tournament_id = c["tournament_id"]
first_blood = c["first_blood"]
kills_5 = c["kills_5"]
status = c["status"]
patch = c["patch"]
return cls(team1_name, team2_name, map_number, match_day, red_side, champs1, champs2, win, match_date, odds, is_test, tournament_id, first_blood, kills_5, status, id, patch)
## Uniquely defined by: team1_name, team2_name, map_number, match_day
## if match already exists in db return it, else create new match using required information
@classmethod
def find_match(cls, team1_name, team2_name, map_number, match_day, caller):
cursor1 = cls.lookup_match(team1_name, team2_name, map_number, match_day)
cursor2 = cls.lookup_match(team2_name, team1_name, map_number, match_day)
## pretty sure nitrogen lists teams alphabetically so need to check both since csv find_match uses red_side/blue_side order
if cursor1.count() != 0:
##no inversion neccesary
match = cls.from_dict(cursor1[0])
match.to_invert = False
return match
elif cursor2.count() != 0:
##inversion might be neccesary
match = cls.from_dict(cursor2[0])
match.set_should_invert(caller)
return match
else:
return cls(team1_name, team2_name, map_number, match_day)
@classmethod
def find_corrupted_match(cls, team1_name, team2_name, map_number, match_day, champs1):
print team1_name, team2_name, map_number, match_day
cursor1 = cls.lookup_corrupted_match(team1_name, team2_name, map_number, match_day, champs1)
if cursor1.count() == 0:
print "corrupted"
return True
else:
print "corrupted"
return False
@staticmethod
def lookup_corrupted_match(team1_name, team2_name, map_number, match_day, champs1):
cursor = NitrogenDbClient.get_db().matches.find({"team1_name" : team1_name, "team2_name" : team2_name, "map_number" : map_number, "match_day" : match_day, "champs1" : champs1})
return cursor
## check if inversion neccesary(same match but team1 and team2 are swapped)
def set_should_invert(self, caller):
## if both means inversion was done already
if self.status == "both":
self.to_invert = False
elif self.status == caller:
print "wtf should not be possible"
self.to_invert = False
else:
self.to_invert = True
## create new match based on model, returns match_id
def create_match(self):
record = NitrogenDbClient.get_db().matches.insert_one({
"team1_name" : self.team1_name,
"team2_name" : self.team2_name,
"map_number" : self.map_number,
"match_day" : self.match_day,
"red_side" : self.red_side,
"champs1" : self.champs1,
"champs2" : self.champs2,
"win" : self.win,
"match_date" : self.match_date,
"odds" : self.odds,
"is_test" : self.is_test,
"tournament_id" : self.tournament_id,
"first_blood" : self.first_blood,
"kills_5" : self.kills_5,
"status" : self.status,
"patch" : self.patch
})
return record.inserted_id
## update existing match with new values in model
def update_match(self):
NitrogenDbClient.get_db().matches.update_one(
{"_id" : self.id},{
"$set": {
"team1_name" : self.team1_name,
"team2_name" : self.team2_name,
"map_number" : self.map_number,
"match_day" : self.match_day,
"red_side" : self.red_side,
"champs1" : self.champs1,
"champs2" : self.champs2,
"win" : self.win,
"match_date" : self.match_date,
"odds" : self.odds,
"is_test" : self.is_test,
"tournament_id" : self.tournament_id,
"first_blood" : self.first_blood,
"kills_5" : self.kills_5,
"status" : self.status,
"patch" : self.patch
}
})
## set is_test to whatever is_test value is passed in, for all pro matches that have csv data
@staticmethod
def reset_all_tests(is_test = True):
NitrogenDbClient.get_db().matches.update_many(
{"status" : "csv", "patch" : PATCH},{
"$set": {
"is_test" : is_test
}
})
NitrogenDbClient.get_db().matches.update_many(
{"status" : "both", "patch" : PATCH},{
"$set": {
"is_test" : is_test
}
})
## return cursor to match found based on id
@staticmethod
def get_match(id):
cursor = NitrogenDbClient.get_db().matches.find({"_id" : id})
return cursor
## find match that has same teams and date
@staticmethod
def lookup_match(team1_name, team2_name, map_number, match_day):
cursor = NitrogenDbClient.get_db().matches.find({"team1_name" : team1_name, "team2_name" : team2_name, "map_number" : map_number, "match_day" : match_day})
return cursor
## return all matches not marked as is_test
@staticmethod
def get_training_set():
cursor = NitrogenDbClient.get_db().matches.find({"is_test" : False, "patch" : PATCH})
return cursor
## return all matches that are labeled is_test
@staticmethod
def get_test_set():
cursor = NitrogenDbClient.get_db().matches.find({"is_test" : True, "patch" : PATCH})
return cursor
##returns all matches that have csv data
@staticmethod
def get_csv_set():
cursor = NitrogenDbClient.get_db().matches.find({"$or":[ {"status" : "both"}, {"status" : "csv", "patch" : PATCH}]})
return cursor
@staticmethod
def get_testable_set():
cursor = NitrogenDbClient.get_db().matches.find({"$or":[ {"status" : "both"}, {"status" : "csv", "patch" : PATCH}]})
return cursor
##should always be passed in either status == "both_old" or "both"
@staticmethod
def get_bettable_set():
cursor = NitrogenDbClient.get_db().matches.find({"status" : "both", "patch" : PATCH})
return cursor
@staticmethod
def get_by_status(status):
cursor = NitrogenDbClient.get_db().matches.find({"status" : status, "patch" : PATCH})
return cursor
## passed in status, prints basic informatin about pro matches
@staticmethod
def print_by_status(status):
cursor = ProMatch.get_by_status(status)
for d in cursor:
match = ProMatch.from_dict(d)
match.pprint()
##passed in status and a string from tourny required
@staticmethod
def print_by_status_tournament(status, tournament_string):
cursor = Tournament.get_all()
t_id_requested = 0
for d in cursor:
tournament = Tournament.from_dict(d)
if tournament_string in tournament.name:
t_id_requested = tournament.id
break
cursor = NitrogenDbClient.get_db().matches.find({"status" : status, "tournament_id" : t_id_requested, "patch" : PATCH})
for d in cursor:
match = ProMatch.from_dict(d)
match.pprint()
def pprint(self):
print self.team1_name, self.team2_name, self.match_day, self.map_number, self.status
## return all matches
@staticmethod
def get_all_matches():
cursor = NitrogenDbClient.get_db().matches.find({"patch" : PATCH})
return cursor
def get_latest_ML_T1(self):
##sorted by date when returned
latest_odd = self.odds[-1]
return latest_odd["ML_T1"]
def get_latest_ML_T2(self):
##sorted by date when returned
latest_odd = self.odds[-1]
return latest_odd["ML_T2"]
def save(self):
##if found already in db
if self.id != None:
##should only ever run once per match(sometimes 0 times)
if self.to_invert == True:
self.invert()
self.update_match()
## else it's a new match that needs to be created
else:
##print "new"
self.id = self.create_match()
##invert team names and MLS when nitrogen.team1_name = csv.team2_name and vice versa
def invert(self):
assert (self.status == "both")
print "inverting"
temp = self.team1_name
self.team1_name = self.team2_name
self.team2_name = temp
for o in self.odds:
temp = o["ML_T1"]
o["ML_T1"] = o["ML_T2"]
o["ML_T2"] = temp
@staticmethod
def print_statuses():
cursor = ProMatch.get_all_matches()
for d in cursor:
match = ProMatch.from_dict(d)
print match.status
| true |
9bb934b9a72bcfcd9f27be0857bae2003881f11e
|
Python
|
Piropoo/dashboard
|
/dashboard/blueprints/views.py
|
UTF-8
| 2,847 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
from flask import Blueprint, session, redirect, render_template, url_for, request, flash
from dashboard.ext.database import Usuario
bp = Blueprint('views', __name__)
@bp.route('/')
def index():
if 'usuario_logado' not in session:
session['usuario_logado'] = False
if not session['usuario_logado']:
return redirect(url_for('views.login'))
else:
return redirect(url_for('views.dashboard'))
@bp.route('/login')
def login():
if not session['usuario_logado']:
return render_template('login.html', titulo_da_pagina='Dashboard - Login',
usuario_logado=session['usuario_logado'] or False,
stylesheets=['login.css'],
scripts=['validar_campos_form.js'])
def autenticar_login(login_digitado, password_digitado):
users = Usuario.query.all()
usuario = None
usuario_existe = False
if '@' in login_digitado:
campo = 'email'
for user in users:
if login_digitado == user.email:
usuario = user
usuario_existe = True
else:
campo = 'username'
for user in users:
if login_digitado == user.username:
usuario = user
usuario_existe = True
if usuario_existe:
if password_digitado == usuario.password:
senha_correta = True
else:
senha_correta = False
if senha_correta:
dados = {'nome': usuario.nome, 'logado': True}
return dados
else:
dados = {'erro': 'A senha está incorreta.', 'logado': False}
return dados
else:
if campo == 'email':
dados = {'erro': 'Este email não está cadastrado.', 'logado': False}
return dados
elif campo == 'username':
dados = {'erro': 'Este usuário não está cadastrado.', 'logado': False}
return dados
@bp.route('/autenticar', methods=['POST'])
def autenticar():
login_digitado = request.form['login'].strip().lower()
password_digitado = request.form['senha']
dados = autenticar_login(login_digitado, password_digitado)
logado = dados['logado']
if logado:
session['usuario_logado'] = True
session['nome'] = dados['nome']
else:
flash(dados['erro'])
return redirect(url_for('views.index'))
@bp.route('/dashboard')
def dashboard():
primeiro_nome = session['nome'].split()[0]
return render_template('dashboard.html', nome=primeiro_nome, usuario_logado=session['usuario_logado'],
stylesheets=['dashboard.css'])
@bp.route('/logout')
def logout():
session['usuario_logado'] = False
return redirect(url_for('views.index'))
def init_app(app):
app.register_blueprint(bp)
| true |
000e8412ebef8e7ac02231097df7b325babda5f1
|
Python
|
liuwang1/tefla
|
/tefla/core/losses.py
|
UTF-8
| 13,373 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
# -------------------------------------------------------------------#
# Written by Mrinal Haloi
# Contact: mrinal.haloi11@gmail.com
# Copyright 2016, Mrinal Haloi
# -------------------------------------------------------------------#
import tensorflow as tf
import numpy as np
log_loss = tf.contrib.losses.log_loss
def log_loss_custom(predictions, labels, eps=1e-7, name='log'):
"""Define a log loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D or array tensor, [batch_size, num_classes] ground truth labels or target labels.
eps: a constant to set upper or lower limit for labels, smoothening factor
name: Optional scope/name for op_scope.
Returns:
A tensor with the log loss.
"""
with tf.name_scope(name):
predictions = tf.to_float(predictions)
labels = tf.to_float(labels)
predictions = tf.clip_by_value(predictions, eps, 1 - eps)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
loss = -tf.reduce_mean(labels * tf.log(predictions))
return loss
def kappa_loss(predictions, labels, y_pow=1, eps=1e-15, num_ratings=5, batch_size=32, name='kappa'):
"""Define a kappa loss, Its a continuous differentiable approximation of discrete kappa loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels.
y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2
num_ratings: numbers of rater to used, typically num_classes of the model
batch_size: batch_size of the training or validation ops
eps: a float, prevents divide by zero
name: Optional scope/name for op_scope.
Returns:
A tensor with the kappa loss.
"""
with tf.name_scope(name):
labels = tf.to_float(labels)
repeat_op = tf.to_float(tf.tile(tf.reshape(
tf.range(0, num_ratings), [num_ratings, 1]), [1, num_ratings]))
repeat_op_sq = tf.square((repeat_op - tf.transpose(repeat_op)))
weights = repeat_op_sq / tf.to_float((num_ratings - 1) ** 2)
pred_ = predictions ** y_pow
try:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [-1, 1]))
except Exception:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [batch_size, 1]))
hist_rater_a = tf.reduce_sum(pred_norm, 0)
hist_rater_b = tf.reduce_sum(labels, 0)
conf_mat = tf.matmul(tf.transpose(pred_norm), labels)
nom = tf.reduce_sum(weights * conf_mat)
denom = tf.reduce_sum(weights * tf.matmul(tf.reshape(hist_rater_a, [
num_ratings, 1]), tf.reshape(hist_rater_b, [1, num_ratings])) / tf.to_float(batch_size))
try:
return -(1 - nom / denom)
except Exception:
return -(1 - nom / (denom + eps))
def kappa_log_loss(predictions, labels, label_smoothing=0.0, y_pow=1, batch_size=32, log_scale=0.5, log_offset=0.50, name='kappa_log'):
"""Define a joint kappa and log loss, Kappa is a continuous differentiable approximation of discrete kappa loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels.
label_smoothing: a float, used to smooth the labels for better generalization
if greater than 0 then smooth the labels.
y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2
num_ratings: numbers of rater to used, typically num_classes of the model
batch_size: batch_size of the training or validation ops
log_scale: a float, used to multiply the clipped log loss, e.g: 0.5
log_offset:a float minimum log loss offset to substract from original log loss; e.g. 0.50
name: Optional scope/name for op_scope.
Returns:
A tensor with the kappa log loss.
"""
with tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.cast(labels, predictions.dtype)
if label_smoothing > 0:
smooth_positives = 1.0 - label_smoothing
smooth_negatives = label_smoothing / num_classes
labels = labels * smooth_positives + smooth_negatives
log_loss_res = log_loss(predictions, labels)
kappa_loss_res = kappa_loss(
predictions, labels, y_pow=y_pow, batch_size=batch_size)
return kappa_loss_res + log_scale * (log_loss_res - log_offset)
def kappa_log_loss_clipped(predictions, labels, label_smoothing=0.0, y_pow=1, batch_size=32, log_scale=0.5, log_cutoff=0.80, name='kappa_log_clipped'):
"""Define a joint kappa and log loss; log loss is clipped by a defined min value; Kappa is a continuous differentiable approximation of discrete kappa loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels.
label_smoothing: a float, used to smooth the labels for better generalization
if greater than 0 then smooth the labels.
y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2
num_ratings: numbers of rater to used, typically num_classes of the model
batch_size: batch_size of the training or validation ops
log_scale: a float, used to multiply the clipped log loss, e.g: 0.5
log_cutoff:a float, minimum log loss value; e.g. 0.50
name: Optional scope/name for op_scope.
Returns:
A tensor with the clipped kappa log loss.
"""
with tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.cast(labels, predictions.dtype)
if label_smoothing > 0:
smooth_positives = 1.0 - label_smoothing
smooth_negatives = label_smoothing / num_classes
labels = labels * smooth_positives + smooth_negatives
log_loss_res = log_loss(predictions, labels)
kappa_loss_res = kappa_loss(
predictions, labels, y_pow=y_pow, batch_size=batch_size)
return kappa_loss_res + log_scale * tf.clip_by_value(log_loss_res, log_cutoff, 10 ** 3)
def cross_entropy_loss(logits, labels, label_smoothing=0.0, weight=1.0, name='cross_entropy_loss'):
"""Define a cross entropy loss with label smoothing.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels.
label_smoothing: a float, used to smooth the labels for better generalization
if greater than 0 then smooth the labels.
weight: scale the loss by this factor.
name: Optional scope/name for op_scope.
Returns:
A tensor with the cross entropy loss.
"""
logits.get_shape().assert_is_compatible_with(labels.get_shape())
with tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.cast(labels, logits.dtype)
if label_smoothing > 0:
smooth_positives = 1.0 - label_smoothing
smooth_negatives = label_smoothing / num_classes
labels = labels * smooth_positives + smooth_negatives
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits, labels, name='xentropy')
weight = tf.convert_to_tensor(
weight, dtype=logits.dtype.base_dtype, name='loss_weight')
loss = tf.mul(weight, tf.reduce_mean(cross_entropy), name='value')
return loss
def l1_l2_regularizer(var, weight_l1=1.0, weight_l2=1.0, name='l1_l2_regularizer'):
"""Define a L2Loss, useful for regularize, i.e. weight decay.
Args:
var: tensor to regularize.
weight_l1: an optional weight to modulate the l1 loss.
weight_l2: an optional weight to modulate the l2 loss.
name: Optional scope/name for op_scope.
Returns:
the l1+L2 loss op.
"""
with tf.name_scope(name):
weight_l1_t = tf.convert_to_tensor(
weight_l1, dtype=var.dtype.base_dtype, name='weight_l1')
weight_l2_t = tf.convert_to_tensor(
weight_l2, dtype=var.dtype.base_dtype, name='weight_l2')
reg_l1 = tf.mul(weight_l1_t, tf.reduce_sum(
tf.abs(var)), name='value_l1')
reg_l2 = tf.mul(weight_l2_t, tf.nn.l2_loss(var), name='value_l2')
return tf.add(reg_l1, reg_l2, name='value')
def discretized_mix_logistic_loss(inputs, predictions, sum_all=True, name='disretized_mix_logistic_loss'):
""" log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval
Args:
predictions: 4D tensor or array, [batch_size, width, height, out_channels] predictions of the network .
inputs: 4D tensor or array, [batch_size, width, height, num_classes] ground truth labels or target labels.
name: Optional scope/name for op_scope.
Returns:
A tensor with the discretized mix logistic loss.
"""
with tf.name_scope(name):
inputs_shape = list(map(int, inputs.get_shape()))
predictions_shape = list(map(int, predictions.get_shape()))
nr_mix = int(predictions_shape[-1] / 10)
logit_probs = predictions[:, :, :, :nr_mix]
predictions = tf.reshape(
predictions[:, :, :, nr_mix:], inputs_shape + [nr_mix * 3])
means = predictions[:, :, :, :, :nr_mix]
log_scales = tf.maximum(
predictions[:, :, :, :, nr_mix:2 * nr_mix], -7.)
coeffs = tf.nn.tanh(predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix])
inputs = tf.reshape(inputs, inputs_shape +
[1]) + tf.zeros(inputs_shape + [nr_mix])
m2 = tf.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :]
* inputs[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix])
m3 = tf.reshape(means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * inputs[:, :, :, 0, :] +
coeffs[:, :, :, 2, :] * inputs[:, :, :, 1, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix])
means = tf.concat(3, [tf.reshape(means[:, :, :, 0, :], [
inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]), m2, m3])
centered_inputs = inputs - means
inv_stdv = tf.exp(-log_scales)
plus_in = inv_stdv * (centered_inputs + 1. / 255.)
cdf_plus = tf.nn.sigmoid(plus_in)
min_in = inv_stdv * (centered_inputs - 1. / 255.)
cdf_min = tf.nn.sigmoid(min_in)
log_cdf_plus = plus_in - tf.nn.softplus(plus_in)
log_one_minus_cdf_min = -tf.nn.softplus(min_in)
cdf_delta = cdf_plus - cdf_min
mid_in = inv_stdv * centered_inputs
log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in)
log_probs = tf.select(inputs < -0.999, log_cdf_plus, tf.select(inputs > 0.999, log_one_minus_cdf_min, tf.select(
cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)), log_pdf_mid - np.log(127.5))))
log_probs = tf.reduce_sum(log_probs, 3) + \
log_prob_from_logits(logit_probs)
if sum_all:
return -tf.reduce_sum(log_sum_exp(log_probs))
else:
return -tf.reduce_sum(log_sum_exp(log_probs), [1, 2])
def mse_loss(pred, labels):
try:
batch_size = tf.cast(pred.shape[0], tf.float32)
except Exception as e:
print('Pred is a tf tensor %s' % str(e.message))
batch_size = tf.cast(tf.shape(pred)[0], tf.float32)
loss_val = tf.sqrt(2 * tf.nn.l2_loss(pred - labels)) / batch_size
return loss_val
def pullaway_loss(embeddings, name='pullaway_loss'):
"""Pull Away loss calculation
Args:
embeddings: The embeddings to be orthogonalized for varied faces. Shape [batch_size, embeddings_dim]
Return: pull away term loss
"""
with tf.name_scope(name):
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
similarity = tf.matmul(normalized_embeddings,
normalized_embeddings, transpose_b=True)
batch_size = tf.cast(tf.shape(embeddings)[0], tf.float32)
pt_loss = (tf.reduce_sum(similarity) - batch_size) / \
(batch_size * (batch_size - 1))
return pt_loss
def log_sum_exp(x):
""" numerically stable log_sum_exp implementation that prevents overflow """
axis = len(x.get_shape()) - 1
m = tf.reduce_max(x, axis)
m2 = tf.reduce_max(x, axis, keep_dims=True)
return m + tf.log(tf.reduce_sum(tf.exp(x - m2), axis))
def log_prob_from_logits(x):
""" numerically stable log_softmax implementation that prevents overflow """
axis = len(x.get_shape()) - 1
m = tf.reduce_max(x, axis, keep_dims=True)
return x - m - tf.log(tf.reduce_sum(tf.exp(x - m), axis, keep_dims=True))
| true |
c6911b3ab0a8451f81b9c4ce9d92104da3aee688
|
Python
|
ymsk-sky/atcoder
|
/abc217/a.py
|
UTF-8
| 59 | 2.921875 | 3 |
[] |
no_license
|
s,t=map(str,input().split())
print('Yes' if s<t else 'No')
| true |
9df23fbde85f293e598e5e644550e6f837b7c845
|
Python
|
mjdroz/StatisticsCalculator
|
/UnitTests/test_random_generator.py
|
UTF-8
| 3,966 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
import unittest
from pprint import pprint
from RandomGenerator.random_generator import random
class MyTestCase(unittest.TestCase):
def setUp( self ) -> None:
self.random = random()
self.start = 1
self.end = 100
self.length = 6
self.seed = 8
self.num_val = 3
self.list = self.random.randomIntList(self.start, self.end, self.length, self.seed)
def test_instantiate_calculator(self):
self.assertIsInstance(self.random, random)
def test_randomInt_method( self ):
int_rand = str(self.random.randomInt(self.start, self.end))
pprint("Random Int: " + int_rand)
self.assertEqual(isinstance(self.random.randomInt(self.start, self.end), int),True)
def test_randomDec_method(self):
dec_rand = str(self.random.randomDec(self.start, self.end))
pprint("Random Decimal: " + dec_rand)
self.assertEqual(isinstance(self.random.randomDec(self.start, self.end), float), True)
def test_randomIntSeed_method( self ):
int_seed = str(self.random.randomIntSeed(self.start, self.end, self.seed))
pprint("Seeded Int: " + int_seed)
self.assertEqual(int_seed, str(self.random.randomIntSeed(self.start, self.end, self.seed)))
def test_randomDecSeed_method( self ):
dec_seed = str(self.random.randomDecSeed(self.start, self.end, self.seed))
pprint("Seeded Decimal: " + dec_seed)
self.assertEqual(dec_seed, str(self.random.randomDecSeed(self.start, self.end, self.seed)))
def test_randomIntList_method(self):
int_array = str(self.random.randomIntList(self.start, self.end, self.length, self.seed))
val_list = (self.random.randomIntList(self.start, self.end, self.length, self.seed))
pprint("Integer Array with a Seed: " + int_array)
for val in val_list:
test_val = int(val)
self.assertEqual(isinstance(test_val, int), True)
def test_randomDecList_method(self):
dec_array = str(self.random.randomDecList(self.start, self.end, self.length, self.seed))
dec_list = (self.random.randomDecList(self.start, self.end, self.length, self.seed))
pprint("Decimal Array with a Seed: " + dec_array)
for val in dec_list:
test_val = float(val)
self.assertEqual(isinstance(test_val, float), True)
def test_randomListSelection_method(self):
selection = str(self.random.randomListSelection(self.list))
non_str_selection = self.random.randomListSelection(self.list)
pprint("Selection from the List: " + selection)
if non_str_selection in self.list:
in_list = True
else:
in_list = False
self.assertEqual(in_list, True)
def test_randomListSelectionSeed_method(self):
selection = str(self.random.randomListSelectionSeed(self.list, self.seed))
pprint("Seeded Selection from the List: " + selection)
self.assertEqual(selection, str(self.random.randomListSelectionSeed(self.list, self.seed)))
def test_randomAmountSelection_method(self):
selection = str(self.random.randomAmountSelection(self.list, self.num_val))
non_str_selection = self.random.randomAmountSelection(self.list, self.num_val)
pprint("N Number of Values Selected from the List: " + selection)
in_list = False
for val in non_str_selection:
if val in self.list:
in_list = True
else:
in_list = False
self.assertEqual(in_list, True)
def test_randomAmountSelectionSeed_method(self):
selection = str(self.random.randomAmountSelectionSeed(self.list, self.num_val, self.seed))
pprint("N Number of Values Selected from the List with a Seed: " + selection)
self.assertEqual(selection, str(self.random.randomAmountSelectionSeed(self.list, self.num_val, self.seed)))
if __name__ == '__main__':
unittest.main()
| true |
95b55ca47783f34a639950f1941e312ddd4a8e24
|
Python
|
tobyhsu73/lidar
|
/draw.py
|
UTF-8
| 691 | 3.171875 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
import math
theta=np.arange(0,2*np.pi,0.02)
#for i in range (315):
#print(math.degrees(theta[i]))
x=[math.radians(45),math.radians(46),math.radians(47),math.radians(48),math.radians(49)]
print(x)
y=[1.3,1.4,1.5,1.4,1.6]
plt.subplot(polar=True)
plt.plot(theta,2*np.ones_like(theta),lw=2)
plt.plot(theta,theta/6,'--',lw=2)
plt.plot(0.7853,1.3,lw=2)
plt.plot(0.802,1.4,lw=2)
plt.plot(0.820,1.5,lw=2)
plt.scatter(x,y,s=10)
plt.plot(0.837,1.4,lw=2)
plt.plot(0.855,1.6,lw=2)
plt.plot(theta,np.cos(5*theta),'--',lw=2)
plt.plot(theta,2*np.cos(4*theta),lw=2)
plt.rgrids(np.arange(0.5,2,0.5),angle=45)
plt.thetagrids([0,45,90])
print()
plt.show()
| true |
c74c3234a56b4c7ce4ae0c9930ecf8700d14bcf8
|
Python
|
dastronmighty/literate-guacamole
|
/Data/GenData.py
|
UTF-8
| 1,664 | 3.0625 | 3 |
[] |
no_license
|
import numpy as np
import os
def add_xor_data(X):
return X[:, 0] + X[:, 1]
def gen_XOr_data():
x = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
y = np.array([[0], [1], [1], [0]])
return x, y
def add_sub_sin_helper(x):
return x[:, 0] - x[:, 1] + x[:, 2] - x[:, 3]
def gen_sin_data(seed=42, size=500, train_size=400):
np.random.seed(seed)
x = np.random.uniform(-1.0, 1.0, size=(size, 4))
y = np.sin(add_sub_sin_helper(x))
y = y.reshape(-1, 1)
tr_x, tr_y, te_x, te_y = x[0:train_size], y[0:train_size], x[train_size:], y[train_size:]
return (tr_x, tr_y), (te_x, te_y)
ALPHAB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def array_to_letter(t):
if len(t.shape) == 1:
idx = [t.argmax()]
else:
idx = t.argmax(axis=1)
return np.array([ALPHAB[i] for i in idx])
def one_hot_letter(letter):
y = list(np.zeros(26))
y[ALPHAB.index(letter)] = 1.0
return y
def process_line(line):
y = one_hot_letter(line[0])
x = line[2:]
x = [float(_) for _ in x.split(",")]
return x, y
def gen_letter_data(test_percent=0.2):
full_path = os.path.dirname(os.path.realpath(__file__))
with open(f"{full_path}/letter-recognition.data") as data_file:
lines = data_file.readlines()
x_a, y_a = [], []
for l in lines:
x, y = process_line(l)
x_a.append(x),
y_a.append(y)
x, y = np.array(x_a), np.array(y_a)
train_amt = int(len(x) - int(len(x) * test_percent))
tr_x, te_x = x[0:train_amt], x[train_amt:]
tr_y, te_y = y[0:train_amt], y[train_amt:]
return (tr_x, tr_y), (te_x, te_y)
| true |
146fe53beb4c0676119671a7204bb1385d03d5af
|
Python
|
Taxiozaurus/GeometricRunner
|
/scoreBoard.py
|
UTF-8
| 2,164 | 3.015625 | 3 |
[] |
no_license
|
import MySQLdb
# for this class to work you will need a MySQL database that presumably has 2 tables
# t1:
# users
# id int primary auto_inc
# nick
# password
#
# t2
# hiscore
# u_id int FK_users_id
# level varchar
# score
class Score :
def __init__(self) :
self.db_con = MySQLdb.connect(host='', user='', passwd='', db='')
self.c = self.db_con.cursor()
def login(self, nick, password) :
my_query = "SELECT * FROM users WHERE nick = '" + nick + "';"
self.c.execute(my_query)
ans = self.c.fetchone()
if ans :
if ans[2] == password :
return ans[0]
else :
return ""
else :
return ""
def register(self, nick, password):
data = self.login(nick, password)
if data > -1 :
my_query = "INSERT INTO users (nick, password) VALUES ('" + nick + "','" + password + "')"
self.c.execute(my_query)
self.db_con.commit()
return self.login(nick, password)
def send_score(self, u_id, level, score) :
my_query = "SELECT score FROM hiscore WHERE u_id = " + str(u_id) + " AND level = '" + level + "' ;"
self.c.execute(my_query)
ans = self.c.fetchone()
if ans :
if ans[0] < score :
my_query = "UPDATE hiscore SET score = " + str(score) + " WHERE u_id = " + str(u_id) + " AND level = '" + level + "';"
self.c.execute(my_query)
else :
my_query = "INSERT INTO hiscore VALUES (" + str(u_id) + ",'" + level + "'," + str(score) + ");"
self.c.execute(my_query)
self.db_con.commit()
def get_scores(self, level) :
my_query = "SELECT nick, score FROM users JOIN hiscore ON id = u_id WHERE level = '" + level + "' ORDER BY score LIMIT 0,10 ;"
self.c.execute(my_query)
ans = self.c.fetchall()
self.db_con.commit()
if len(ans) > 0 :
return ans
else :
return []
def finish(self):
self.db_con.commit()
self.c.close()
self.db_con.close()
| true |
060656cb9d176d2d95a7e477a3bc78c7f4fee4fd
|
Python
|
sreshthakashyap/OralScreen
|
/OralCellDataPreparation/predict_patch.py
|
UTF-8
| 2,033 | 2.796875 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
# -*- coding: utf-8 -*-
import cv2
from tqdm import tqdm
import csv
from glob import glob
import os
#%%
z_offsets = ['z0', 'z400', 'z-400', 'z800', 'z-800', 'z1200', 'z-1200', 'z1600', 'z-1600', 'z2000', 'z-2000']
#%%
def generate_patch(w=80):
"""
Arguments:
w -- window size for patches
Returns:
total_num -- total number of predicted nucleus patches
"""
total_num = 0
# generate patches only for the sub-images with nuclei detected
for csv_path in tqdm(glob('./CSVResults/*.csv')):
# extract image name without extension, and separate without z value
img_name = os.path.basename(csv_path)[:-len('.csv')]
img_name_l = img_name[:img_name.rindex('z0')]
img_name_r = img_name[img_name.rindex('z0') + len('z0'):]
for z_offset in z_offsets:
img_z_name = img_name_l + z_offset + img_name_r + '.jpg'
img = cv2.imread('./JPEGImages/' + img_z_name)
with open(csv_path) as f:
f_csv = csv.reader(f)
headers = next(f_csv)
i = 0
for row in f_csv:
center = [round(float(row[-2])), round(float(row[-1]))]
box = [center[0] - int(w/2), center[1] - int(w/2),
center[0] + int(w/2), center[1] + int(w/2)]
cropped = img[box[1]:box[1]+w, box[0]:box[0]+w] # [Ymin:Ymax , Xmin:Xmax]
cv2.imwrite("./Patches/Z_expanded/{}_{}_{}.jpg"
.format(img_name, '0'*(4 - len(str(i))) + str(i), z_offset),
cropped, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
i += 1
total_num += (f_csv.line_num - 1)
return total_num
#%%
if __name__ == '__main__':
print('#'*30)
print('Generating predicted patches at all Z level.')
print('#'*30)
total_num = generate_patch()
| true |
6cf0fe329e96e57cded2e19b8c392fccb1484cc4
|
Python
|
sinhlt58/mc_functions
|
/aniblock/blocks.py
|
UTF-8
| 1,162 | 2.53125 | 3 |
[] |
no_license
|
from aniblock.constants import *
from aniblock.utils import *
class Block:
pass
class CommandBlock(Block):
def __init__(self, command, type="command_block"):
self.command = command
self.type = type
def to_mc_commands(self, pos, facing, relative=POS_RELATIVE_W):
pos_str = pos_to_str(pos, relative)
return [
f"setblock {pos_str} minecraft:{self.type}[facing={facing}]",
f"data modify block {pos_str} Command set value \"{self.command}\""
]
class CommandBlockDelay(CommandBlock):
def __init__(self, delay_ticks):
super().__init__("")
self.delay_ticks = delay_ticks
def to_mc_commands(self, pos, facing, relative=POS_RELATIVE_W):
delay_pos = facing_to_vec(facing)
pos_str = pos_to_str(pos, relative)
delay_pos_str = pos_to_str(delay_pos, relative)
return [
f"setblock {pos_str} minecraft:chain_command_block[facing={facing}]",
f"data modify block {pos_str} Command set value \"summon minecraft:area_effect_cloud {delay_pos_str} {{Tags:[\\\"TickCounter\\\"],Age:{-self.delay_ticks}}}\""
]
| true |
b40ea948373cf881045e59ea34ab94018e2d7a23
|
Python
|
dylanjorgensen/modules
|
/(custom)/single-script/mod.py
|
UTF-8
| 263 | 3.21875 | 3 |
[] |
no_license
|
# Import
print 'this line printed just because you imported me'
# Function
def func():
return 'you called a function inside a module script'
# Class
class Classy(object):
def meth(self):
return 'you called a function with a class in it'
| true |
a27f23f0419598bdcd5f952e605d22ba904fdf8d
|
Python
|
tommylees112/esowc_notes
|
/analysis_scripts/spatial_r2.py
|
UTF-8
| 1,327 | 2.515625 | 3 |
[] |
no_license
|
#
true_da_shape = (true_da.lat.shape[0], true_da.lon.shape[0])
pred_da_shape = (pred_da.lat.shape[0], pred_da.lon.shape[0])
assert true_da_shape == pred_da_shape
vals = np.sqrt(
np.nansum((true_da.values - pred_da.values) ** 2, axis=0) / pred_da.shape[0]
)
da = xr.ones_like(pred_da).isel(time=0)
da.values = vals
# reapply the mask
da = da.where(~get_ds_mask(pred_da))
#
from sklearn.metrics import r2_score
# fit values, and mean
pred = p(x) # or [p(z) for z in x]
true_mean = numpy.sum(y) / len(y) # or sum(y)/len(y)
ssreg = numpy.sum(
(pred - true_mean) ** 2
) # or sum([ (yihat - true_mean)**2 for yihat in pred])
sstot = numpy.sum((y - true_mean) ** 2) # or sum([ (yi - true_mean)**2 for yi in y])
results["determination"] = ssreg / sstot
def spatial_r2(true_da: xr.DataArray, pred_da: xr.DataArray) -> xr.DataArray:
true_da_shape = (true_da.lat.shape[0], true_da.lon.shape[0])
pred_da_shape = (pred_da.lat.shape[0], pred_da.lon.shape[0])
assert true_da_shape == pred_da_shape
r2_vals = 1 - (np.nansum((true_da.values - pred_da.values) ** 2, axis=0)) / (
np.nansum((true_da.values - np.nanmean(pred_da.values)) ** 2, axis=0)
)
da = xr.ones_like(pred_da).isel(time=0)
da.values = r2_vals
# reapply the mask
da = da.where(~get_ds_mask(pred_da))
return da
| true |
f4ffd341dcb2c6989f5c0ed37752f895a2abab12
|
Python
|
constantine77/python
|
/basics/test.py
|
UTF-8
| 616 | 4.25 | 4 |
[] |
no_license
|
#Data Structures in Python
def simple_list_iteration():
'''
List iteration
:return:
'''
A = [1,2,3,4,5]
for x in A:
print(x,type(x))
x += 1
print(x)
def list_index_iteration():
'''
List iteration with index
:return:
'''
A = [1,2,3,4,5]
for k in range(5): #from o to 4, k is index
print(A[k])
def create_list():
'''
create List A with 10 elements
:return:
'''
A =[ 0]*10
B = [1,2,3,4,5,6,7,8]
C = list(B) #create copy of list B
D = []
for k in range(len(C)):
D[k].append
create_list()
| true |
3e7741822e712c83e70c6bb8d2b3a602e2526e20
|
Python
|
Dunkash/GroupTask3
|
/helpers.py
|
UTF-8
| 2,800 | 3.015625 | 3 |
[] |
no_license
|
import numpy as np
def hex_to_rgb(hex_str):
return int(hex_str[1:3], 16), int(hex_str[3:5], 16), int(hex_str[5:7], 16)
class Point:
def __init__(self, x=0, y=0):
self.X = x
self.Y = y
def line(x1, y1, x2, y2, img, line_color):
beg = Point(x1, y1)
end = Point(x2, y2)
line_color = np.array(line_color)
deltX = end.X - beg.X
deltY = end.Y - beg.Y
sX = np.sign(deltX)
sY = np.sign(deltY)
deltX = abs(deltX)
deltY = abs(deltY)
if deltX > deltY:
pDelX, pDelY = sX, 0
es, el = deltY, deltX
else:
pDelX, pDelY = 0, sY
es, el = deltX, deltY
err, t = round(el / 2), 0
img[beg.X][beg.Y] = line_color
while (t < el):
err -= es
if err < 0:
err += el
beg.X += sX
beg.Y += sY
else:
beg.X += pDelX
beg.Y += pDelY
t += 1
img[beg.X][beg.Y] = line_color
def lineVu(x1, y1, x2, y2, img):
beg = Point(x1, y1)
end = Point(x2, y2)
if (beg.X > end.X):
beg.X, end.X = end.X, beg.X
beg.Y, end.Y = end.Y, beg.Y
delX = end.X - beg.X
delY = end.Y - beg.Y
grad = delY / delX
yend = beg.Y + grad * (round(beg.X) - beg.X)
xgagp = 1 - ((beg.X + 0.5) - int(beg.X + 0.5))
xpxl1 = round(beg.X)
ypxl1 = int(yend)
img.putpixel((xpxl1, ypxl1), (100, 100, 100, round(255 * (1 - (yend - int(yend))) * xgagp)))
img.putpixel((xpxl1, ypxl1 + 1), (100, 100, 100, round(255 * (yend - int(yend)) * xgagp)))
intery = yend + grad
yend = end.Y + grad * (round(end.X) - end.X)
xgap = (end.X + 0.5) - int(end.X + 0.5)
xpxl2 = round(end.X)
ypxl2 = int(yend)
img.putpixel((xpxl2, ypxl2), (100, 100, 100, round(255 * (1 - (yend - int(yend))) * xgap)))
img.putpixel((xpxl2, ypxl2 + 1), (100, 100, 100, round(255 * (yend - int(yend)) * xgap)))
for i in range(xpxl1 + 1, xpxl2):
img.putpixel((i, int(intery)), (100, 100, 100, round(255 * (1 - (intery - int(intery))))))
img.putpixel((i, int(intery) + 1), (100, 100, 100, round(255 * (intery - int(intery)))))
intery = intery + grad
def draw_line(line_cord, img_arr, line_color):
if line_cord[0] == line_cord[2]:
for x in range(min(line_cord[1], line_cord[3]), max(line_cord[1], line_cord[3]) + 1):
img_arr[x, line_cord[0]] = np.array(line_color)
else:
for y in range(min(line_cord[0], line_cord[2]), max(line_cord[0], line_cord[2]) + 1):
img_arr[line_cord[1], y] = np.array(line_color)
assert hex_to_rgb("#ff0000"), (255, 0, 0)
assert hex_to_rgb("#0a040b"), (10, 4, 11)
assert hex_to_rgb("#fe1000"), (254, 16, 0)
| true |
f9f3f3bd4bfdb379b7c200c23701cd9501157c8d
|
Python
|
jhgdike/leetCode
|
/medium/different_ways_to_add_parenthese.py
|
UTF-8
| 1,809 | 3.3125 | 3 |
[] |
no_license
|
# coding: utf-8
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
res = []
length = len(input)
for i in range(0, length):
if input[i] in '+-*':
res1 = self.diffWaysToCompute(input[:i])
res2 = self.diffWaysToCompute(input[i+1:])
for m in res1:
for n in res2:
if input[i] == '+':
res.append(m + n)
elif input[i] == '-':
res.append(m - n)
else:
res.append(m * n)
if not res:
res.append(int(input))
return res
def diffWaysToCompute_recursion(self, input):
map_res = {}
return self._recursion(input, map_res)
def _recursion(self, input, map_res):
res = []
length = len(input)
for i in range(0, length):
if input[i] in '+-*':
left, right = input[:i], input[i+1:]
if not map_res.get(left):
map_res[left] = self._recursion(left, map_res)
res1 = map_res[left]
if not map_res.get(right):
map_res[right] = self._recursion(right, map_res)
res2 = map_res[right]
for m in res1:
for n in res2:
if input[i] == '+':
res.append(m + n)
elif input[i] == '-':
res.append(m - n)
else:
res.append(m * n)
if not res:
res.append(int(input))
return res
| true |
5280f4bf7e2aafa4a478a2c15884fc6e93f2c68f
|
Python
|
SVwrite/Web_Scrapers
|
/Book_scraper/book_scrapper.py
|
UTF-8
| 2,844 | 2.96875 | 3 |
[] |
no_license
|
import requests
from bs4 import BeautifulSoup
# import re
import os
import time
class Book:
def __init__(self, title= None, author = None, publisher = None, year =None, url = None, formats = None):
self.title = title
self.author = author
self.publisher = publisher
self.year = year
self.url = url
self.formats = formats
def PrintDetails(self) -> None:
print(f"\n\tTitle : {self.title}\n\tAuthor : {self.author}\n\tYear : {self.year}")
print(f"\tPublisher : {self.publisher}\n\tAvailable format: {self.formats}")
def geturl(self) -> str:
return self.url
def ProductName()-> str:
product = input("\n\tWhat's the title of the book ? : ")
z_lib_books = 'https://1lib.in/s/'
url = z_lib_books + product
return url
def HtmlFetch(url :str) -> BeautifulSoup:
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
return soup
def ZlibBookDetailsExtracter(soup : BeautifulSoup) -> Book:
book ={}
all_searches = soup.find('div', id='searchResultBox')
all_searches = all_searches.find_all('table', class_='resItemTable')
# print(all_searches)
# searches = all_searches[0]
for i in range(4):
search = all_searches[i]
title = search.h3.a.text
url = 'https://1lib.in/' + search.h3.a['href']
author = search.find('div', class_='authors')
if author:
author = author.text
publisher = search.find('div', title = "Publisher")
if publisher:
publisher = publisher.text
year = search.tr.find('div', class_='bookProperty property_year')
if year:
year = year.find('div', class_='property_value')
if year:
year = year.text
format = search.find('div', class_='bookProperty property__file')
format = format.find('div', class_='property_value').text
b = Book(title, author, publisher, year, url, format)
yield b
def ZlibDownloadExtractor(url :str) :
#Returns avail book formats and download urls
soup = HtmlFetch(url)
formats = soup.find('div', class_='btn-group')
formats = formats.find('button', id='btnCheckOtherFormats')
print(formats.prettify())
def download(url):
r = requests.get(url, allow_redirects=False)
print(r.headers.get('content-type'))
open('Book_name.pdf', 'wb').write(r.content)
# print(r.text)
def main():
soup = HtmlFetch(ProductName())
books = list(ZlibBookDetailsExtracter(soup))
books[0].PrintDetails()
# for book in books:
# book.PrintDetails()
# url = books[0].geturl()
# ZlibDownloadExtractor(url)
# download('https://1lib.in/dl/3485511/701625')
if __name__=="__main__":
main()
| true |
3766aa7435651b8dbe2c3931d3e66e19c3c6fae1
|
Python
|
JustLonggg/NLP_notes
|
/分词、词性标注以及命名实体识别/词性标注及信息提取/extract_data.py
|
UTF-8
| 293 | 2.515625 | 3 |
[] |
no_license
|
#encoding=utf8
import jieba
import re
from tokenizer import seg_sentences
fp = open('text.txt','r',encoding='utf-8')
fout = open('out.txt','w',encoding='utf-8')
for line in fp:
line = line.strip()
if len(line) > 0:
fout.write(' '.join(seg_sentences(line)) + '\n')
fout.close()
| true |
99791b4c95d975c1d60413cce833a5930408a4ca
|
Python
|
flilyday/upgrade
|
/vervreqests/29._slots_ effect.py
|
UTF-8
| 3,011 | 3.90625 | 4 |
[] |
no_license
|
# 29._slots_ effect.py
# __dict__의 단점과 해결책
# 단점 : 객체의 값을 관리할 때 '키'를 이용해서 '값'을 얻게 하므로 리스트나 튜플보다 메모리 사용량이 많아진다.
# 그러므로 많은 수의 객체를 생성하려고 할 때는 메모리에 부담이 된다.
# 해결책 -> __slots__의 사용
# 0.일반적인 경우 : __dict__에 값이 할당
class Point3D :
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '{0}, {1}, {2}'.format(self.x, self.y, self.z) #좌표 정보 출력
def main():
p1 = Point3D(1, 1, 1)
p2 = Point3D(24, 17, 31)
print(p1)
print(p2)
main()
print('-')
# 1. __slots__를 쓰는 경우
class Point3D :
__slots__ = ('x', 'y', 'z') #속성을 x, y, z로 제한한다.
#이 클래스로 생성한 변수는 x, y, z로 제한한다.
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '{0}, {1}, {2}'.format(self.x, self.y, self.z)
def main():
p1 = Point3D(1, 1, 1)
# p1.w = 30 #w는 slots에 명시하지 않은 이름이므로 오류 발생
main()
print('-')
# 2. __slots__를 썼을 때의 성능 향상 테스트
# 2.1.__dict__만 있을 때 내부적으로 일어나는 과정
class Point3D :
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '{0}, {1}, {2}'.format(self.x, self.y, self.z) #좌표 정보 출력
def main():
p = Point3D(24, 17, 31)
print(p.x, p.y, p.z)
print(p.__dict__['x'], p.__dict__['y'], p.__dict__['z']) #내부적으로는 이렇게 __dict__의 값을 참조하여 출력하게 된다.
main()
print('-')
# 2.2.속도 테스트
# 2.2.1.slots를 안 쓸 경우 : 3.78초 정도
import timeit
class Point3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '({0},{1},{2})'.format(self.x, self.y, self.z)
def main():
start = timeit.default_timer()
p = Point3D(1, 1, 1)
for i in range(3000):
for i in range(3000):
p.x += 1
p.y += 1
p.z += 1
print(p)
stop = timeit.default_timer()
print(stop - start)
main()
# 2.2.2.slots를 안 쓸 경우 : 3.78초 정도
import timeit
class Point3D:
__slots__ = ('x', 'y', 'z') #이 부분을 추가
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '({0},{1},{2})'.format(self.x, self.y, self.z)
# 2.2.3.slots를 쓸 경우 : 2.98정도
def main():
start = timeit.default_timer()
p = Point3D(1, 1, 1)
for i in range(3000):
for i in range(3000):
p.x += 1
p.y += 1
p.z += 1
print(p)
stop = timeit.default_timer()
print(stop - start)
main()
| true |
6eeb769f77025bfe2f71669630bfb8c68321b794
|
Python
|
bit-meddler/skunkWorks
|
/toys/viconFiles.py
|
UTF-8
| 7,817 | 2.796875 | 3 |
[] |
no_license
|
"""
collection of functions to read vicon data, staring simple with the XML stuff
XCP
VSK
VSS
Then on to the hard one, x2d
X2D
"""
import numpy as np
from xml.dom import minidom
from quaternions import Quaternion
# In case we run out of precision
FLOAT_T = np.float32
INT_T = np.int32
class ViconCamera( object ):
def __init__( self, input_dict=None ):
# camera data
self.hw_id = -1 # uniue id. data is in id order in the x2d
self.type = ""
self.vicon_name = ""
self.px_aspect = -1 #
self.sensor_type = ""
self.sensor_wh = [0, 0] # px
self.user_id = -1
# raw calibration data
self._pp = [0., 0.] # px
self._radial= [0., 0.] # k1, k2
self._pos = [0., 0., 0.] # tx, ty, tz
self._rotQ = [0., 0., 0., 0.] # uartonions [x,y,z,w]
self._err = 0. # rms reprojection error
self._skew = 0. # ??
self._focal = 0. # f in sensor px?
# computed matrixs
self.K = np.eye( 3, dtype=FLOAT_T )
self.R = np.eye( 3, dtype=FLOAT_T )
self.Q = Quaternion()
self.T = np.zeros( (3,), dtype=FLOAT_T )
self.RT = np.zeros( (3,4), dtype=FLOAT_T )
self.P = np.zeros( (3,4), dtype=FLOAT_T )
if( input_dict is not None ):
self.setFromDict( input_dict )
def setFromDict( self, dict ):
self.hw_id = dict["DEVICEID"]
self.type = dict["TYPE"]
self.vicon_name = dict["NAME"]
self.px_aspect = dict["PIXEL_ASPECT_RATIO"]
self.sensor_type = dict["SENSOR"]
self.sensor_wh = dict["SENSOR_SIZE"]
self.user_id = dict["USERID"]
self._pp = dict["PRINCIPAL_POINT"]
self._radial = dict["VICON_RADIAL"]
self._skew = dict["SKEW"]
self._focal = dict["FOCAL_LENGTH"]
self._pos = dict["POSITION"]
self._rotQ = dict["ORIENTATION"]
self._err = dict["IMAGE_ERROR"]
self.computeMatrix()
def computeMatrix( self ):
# see also: http://run.usc.edu/cs420-s15/lec05-viewing/05-viewing-6up.pdf
# compose RT
self.T = self._pos
x, y, z, w = self._rotQ
self.Q.setQ( x, y, z, w )
# These transposed RotMats are driving me mad!
self.R = self.Q.toRotMat2().T
self.R = self.Q.toRotMat()
# from Vicon's "Cara Reference" pdf (/Fileformats/XCP)
# Assuming (!) XCPs are the same between products
# P = [ R | -RT ]
self.RT[ :3, :3 ] = self.R
self.RT[ :, 3 ] = -np.matmul( self.R, self.T )
# compose K
# fiddle with PP, focal length, aspect ratio and skew (which in all encountered files is zero0
a = self.px_aspect
x_pp, y_pp = self._pp
f = self._focal
k = self._skew
self.K = np.array(
[ [ f, k, x_pp ],
[ 0., (f/a), y_pp ],
[ 0., 0., 1. ] ] , dtype=FLOAT_T )
# compute P = K.RT
self.P = np.matmul( self.K, self.RT )
def undistort( self, point ):
# As Vicon doesn't use NDCs the undistort is computed per det - dumb!
a = self.px_aspect
w1, w2 = self._radial
x_pp, y_pp = self._pp
# Again from the CaraPost Refference pdf
x_r, y_r = point
dp = [ x_r - x_pp, a * ( y_r - y_pp ) ]
print dp
r = np.linalg.norm( dp )
print r
s = 1 + w1 * r**1 + w2 * r**2
print s
ud = [ s * dp[0] + x_pp, (s * dp[1] + y_pp)/a ]
print ud
def projectPoints( self, points3D ):
ret = np.zeros( ( points3D.shape[0], 3 ), dtype=FLOAT_T )
# ret = self.P * points3D
return ret
class CalReader( object ):
CASTS = {
# Intrinsics
"PRINCIPAL_POINT" : lambda x: map( float, x.split() ),
"VICON_RADIAL" : lambda x: map( float, x.split() ),
"SKEW" : float,
"FOCAL_LENGTH" : float,
# extrinsics
"ORIENTATION" : lambda x: np.array( x.split(), dtype=FLOAT_T),
"POSITION" : lambda x: np.array( x.split(), dtype=FLOAT_T),
# Meta Data
"SENSOR_SIZE" : lambda x: map( int, x.split() ),
"PIXEL_ASPECT_RATIO" : float,
"DEVICEID" : int,
"USERID" : int,
"NAME" : lambda x: x, # passthru
"SENSOR" : lambda x: x, # passthru
"TYPE" : lambda x: x, # passthru
"IMAGE_ERROR" : float,
}
CAMERA_ID_KEY = "DEVICEID"
CAMERA_ATTERS_HARDWARE = ( "DEVICEID", "NAME", "PIXEL_ASPECT_RATIO", "SENSOR", "SENSOR_SIZE", "SKEW", "TYPE", "USERID" )
CAMERA_ATTERS_CALIBRATION = ( "FOCAL_LENGTH", "IMAGE_ERROR", "ORIENTATION", "POSITION", "PRINCIPAL_POINT", "VICON_RADIAL" )
def __init__( self ):
self.reset()
def reset( self ) :
self.data = {}
self.cameras = {}
self.camera_order = []
self.source_file = ""
def read( self, file_path=None ):
if( file_path is None ):
print( "Error: no file supplied" )
return -1
mode = "XCP"
self.source_file = file_path
if( file_path.lower().endswith( ".xcp" ) ):
mode = "XCP"
elif( file_path.lower().endswith( ".cp" ) ):
print( "Error: .cp not yet supported" )
return -1
if( mode == "XCP" ):
XD = minidom.parse( file_path )
cameras = XD.getElementsByTagName( "Camera" )
for camera in cameras:
# create dict
cid = camera.attributes[ CalReader.CAMERA_ID_KEY ].value.encode( "ascii" )
self.data[ cid ] = {}
# load camera data
for entry in CalReader.CAMERA_ATTERS_HARDWARE:
self.data[ cid ][ entry ] = camera.attributes[ entry ].value.encode( "ascii" )
# load calibration data
kf_list = camera.getElementsByTagName( "KeyFrame" )
if( len( kf_list ) > 0 ):
for entry in CalReader.CAMERA_ATTERS_CALIBRATION:
self.data[ cid ][ entry ] = kf_list[0].attributes[ entry ].value.encode( "ascii" )
# cast
for atter, cast in self.CASTS.iteritems():
self.data[ cid ][ atter ] = cast( self.data[ cid ][ atter ] )
for cam_id, cam_data in self.data.iteritems():
camera = ViconCamera( cam_data )
self.cameras[ int( cam_id ) ] = camera
self.camera_order = sorted( self.cameras.keys() )
if( __name__ == "__main__" ):
# testing reading an xml
file_path = r"170202_WictorK_Body_ROM_01.xcp"
cal_reader = CalReader()
cal_reader.read( file_path )
for cid in cal_reader.camera_order:
cam = cal_reader.cameras[ cid ]
print( "Camera '{}' is at T:{} R:{}".format(
cid, cam.T, np.degrees( cam.Q.toAngles2() ) ) )
# examining this in blade, the rot should be [166.497, -84.23, -119.151]
cam = cal_reader.cameras[ 2107343 ]
print np.degrees( cam.Q.toAngles() )
print np.degrees( cam.Q.toAngles2() )
print np.degrees( cam.Q.toAngles3() )
# 178, 408, 142 is about the center of 2107343
x, y, z = np.matmul( cam.P, np.array( [-178.20, -408.21, 142.86, 1.] ) )
print x/z, y/z
# not bad :)
| true |
c01c5d78f3321bb3ee41216c7a8ba0ae70995123
|
Python
|
shiftsayan/python-2048
|
/play.py
|
UTF-8
| 5,691 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
####################################
# Imports
####################################
from tkinter import *
from helper import *
from ai import *
####################################
# Draw Functions
####################################
def draw_win(canvas, data):
# Background
canvas.create_rectangle(0, 0, data.width, data.height, fill=data.end_bg_color, width=0)
# Text
canvas.create_text(data.width/2, data.height/2, text="YOU WON :)", font=("Open Sans", "80", "bold"), fill=data.light_text_color)
def draw_lost(canvas, data):
# Background
canvas.create_rectangle(0, 0, data.width, data.height, fill=data.end_bg_color, width=0)
# Text
canvas.create_text(data.width/2, data.height/2, text="YOU LOST :(", font=("Open Sans", "80", "bold"), fill=data.light_text_color)
def draw_board(canvas, data):
# Background
canvas.create_rectangle(0, 0, data.width, data.height, fill=data.game_bg_color, width=0)
# Tiles
for i in range(data.grid):
for j in range(data.grid):
# Coordinates
x1 = data.thick * (j+1) + data.size * j
y1 = data.thick * (i+1) + data.size * i
x2 = x1 + data.size
y2 = y1 + data.size
# Label
tile_color = data.tile_color[data.board[i][j]]
text_color = data.dark_text_color if data.board[i][j] < 3 else data.light_text_color
text = "" if data.board[i][j] == 0 else str(2 ** data.board[i][j])
# Draw
canvas.create_rectangle(x1, y1, x2, y2, fill=tile_color, width=0)
canvas.create_text((x1+x2)/2, (y1+y2)/2, text=text, font=("Open Sans", "55", "bold"), fill=text_color)
####################################
# Move Function
####################################
def move(data, vector):
if not (data.is_won or data.is_lost):
if data.is_ai:
data.board, result, _ = move_sim(data.board, data.grid, ai(data.board, data.grid, data.target), data.target)
elif vector in [ "Left", "Right", "Up", "Down" ]:
data.board, result, _ = move_sim(data.board, data.grid, vector, data.target)
if result not in [ True, False ]:
pass
else:
data.is_won, data.is_lost = (True, False) if result else (False, True)
data.timerDelay = 1000
####################################
# Animation Functions
####################################
def init(data):
# Settings
data.start_tiles = 2
data.target = 11 # 2 ** 11 = 2048
# Board
data.grid = 4
data.board = [ [ 0 for i in range(data.grid) ] for i in range(data.grid) ]
# Sizes
data.size = data.width / 4.5
data.thick = data.size / 10
# Colors
data.game_bg_color = rgb2hex(187, 173, 161)
data.end_bg_color = rgb2hex(241, 196, 15)
data.dark_text_color = rgb2hex(118, 110, 101)
data.light_text_color = rgb2hex(249, 246, 242)
data.tile_color = [
rgb2hex(205, 192, 181), # None
rgb2hex(238, 228, 218), # 2
rgb2hex(237, 224, 200), # 4
rgb2hex(242, 177, 121), # 8
rgb2hex(245, 149, 99), # 16
rgb2hex(246, 124, 95), # 32
rgb2hex(246, 94, 59), # 64
rgb2hex(237, 207, 114), # 128
rgb2hex(237, 204, 97), # 256
rgb2hex(237, 200, 80), # 512
rgb2hex(237, 197, 63), # 1024
rgb2hex(237, 194, 46) # 2048
]
# Win States
data.is_lost = False
data.is_won = False
# Randomly Insert Two 2-tiles
for i in range(data.start_tiles):
data.board = random_insert(data.board, data.grid)
def mousePressed(event, data):
pass
def keyPressed(event, data):
if not data.is_ai: move(data, event.keysym)
def timerFired(data):
if data.is_ai: move(data, "")
def redrawAll(canvas, data):
if data.is_won: draw_win(canvas, data)
elif data.is_lost: draw_lost(canvas, data)
else: draw_board(canvas, data)
####################################
# Run Function
# Source: www.cs.cmu.edu/~112
####################################
def run(mode, width=600, height=600):
def redrawAllWrapper(canvas, data):
canvas.delete(ALL)
canvas.create_rectangle(0, 0, data.width, data.height,
fill='white', width=0)
redrawAll(canvas, data)
canvas.update()
def mousePressedWrapper(event, canvas, data):
mousePressed(event, data)
redrawAllWrapper(canvas, data)
def keyPressedWrapper(event, canvas, data):
keyPressed(event, data)
redrawAllWrapper(canvas, data)
def timerFiredWrapper(canvas, data):
timerFired(data)
redrawAllWrapper(canvas, data)
canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)
class Struct(object): pass
data = Struct()
data.is_ai = True if mode[0].upper() == 'S' else False # Simulate
data.width = width
data.height = height
data.timerDelay = 200 # milliseconds
root = Tk()
init(data)
canvas = Canvas(root, width=data.width, height=data.height)
canvas.pack()
root.title("2048")
root.bind("<Button-1>", lambda event:
mousePressedWrapper(event, canvas, data))
root.bind("<Key>", lambda event:
keyPressedWrapper(event, canvas, data))
timerFiredWrapper(canvas, data)
root.mainloop()
if __name__ == '__main__':
mode = raw_input("Play or Simulate: ")
run(mode)
| true |
dcc8303f2f2c9683080515a40ce2af10afa0c328
|
Python
|
Stihotvor/python3_magic_method_examples
|
/representation_and_validations.py
|
UTF-8
| 1,046 | 3.609375 | 4 |
[
"MIT"
] |
permissive
|
class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
# list of dicts with passenger attributes
self.passengers = []
def __lt__(self, other):
"""
Less than other
:param other:
:return:
"""
return len(self.passengers) < len(other)
# __le__ - less or equal, __eq__ - equal, __ne__ - not equal, __gt__ - greater than, __ge__ - greater or equal
# Vessel methods
def pump_in_fuel(self, quantity: float):
self.fuel += quantity
def pump_out_fuel(self):
self.fuel = 0.0
def discharge_passengers(self):
self.passengers = []
if __name__ == '__main__':
# Runtime tests will be here
vsl = Vessel('Casandra')
vsl.pump_in_fuel(10.5)
vsl.passengers = [
{
'name': 'Peter'
},
{
'name': 'Jessika'
}
]
print(vsl < [1, ])
| true |
1691fe8b8e5d967ed7b2c37820974ccac4cf4b35
|
Python
|
davendiy/forpythonanywhere
|
/hackatons/materials/algo/source/T7_Graphs/P2/__test_ways.py
|
UTF-8
| 1,222 | 3.578125 | 4 |
[] |
no_license
|
from source.T7_Graphs.P1.GraphForAlgorithms import GraphForAlgorithms
from source.T7_Graphs.P2.BFS import BFS
from source.T7_Graphs.P2.DFS import DFS
from source.T7_Graphs.P2.Ways import waySearch, waySearchByWave
def show_way(vertices: list, weight, tag):
if vertices is None: # шляху не існує
print(tag, "Шляху не існує! ")
return
# виводимо шлях way на екран
print(tag, "(%d): " % weight, end="")
for i in range(len(vertices) - 1):
print(vertices[i], end=" -> ")
print(vertices[-1])
if __name__ == "__main__":
g = GraphForAlgorithms(False) # Створюємо орієнтований граф
g.add_edge(0, 1)
g.add_edge(0, 5)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)
g.add_edge(3, 5)
g.add_edge(4, 0)
g.add_edge(5, 4)
g.add_edge(5, 2)
g.add_edge(6, 7)
BFS(g, 0)
DFS(g, 0) # запускаємо DFS з вершини 0
way, way_weight = waySearch(g, 0, 7)
show_way(way, way_weight, "Wave algorithm1 ")
way, way_weight = waySearchByWave(g, 0, 3)
show_way(way, way_weight, "Wave algorithm2 ")
| true |
97c779d7fc7cd527675e6a63fd70d8cef29d9d4e
|
Python
|
W-KE/Leetcode-Solutions
|
/challenge/30-day-leetcoding-challenge/week1/maximum-subarray.py
|
UTF-8
| 440 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maximum = nums[0]
subarray = []
for num in nums:
if num > maximum:
maximum = num
if num > 0:
subarray.append(num)
if subarray:
return sum(subarray)
return maximum
s = Solution()
print(s.maxSubArray(nums=[-2, 1, -3, 4, -1, 2, 1, -5, 4]))
| true |
9df4c6c22dd5f1a6617e7d9785b27930315c61e8
|
Python
|
gdcohan/deepmedic-preprocess
|
/qtim_tools/qtim_pipelines/deep_learning.py
|
UTF-8
| 13,014 | 2.53125 | 3 |
[] |
no_license
|
import numpy as np
import glob
import os
import yaml
from shutil import copy, rmtree
from ..qtim_preprocessing.motion_correction import motion_correction
from ..qtim_preprocessing.threshold import crop_with_mask
from ..qtim_preprocessing.resample import resample
from ..qtim_preprocessing.normalization import zero_mean_unit_variance
from ..qtim_preprocessing.bias_correction import bias_correction
from ..qtim_preprocessing.skull_strip import skull_strip
from ..qtim_utilities.file_util import nifti_splitext
def deep_learning_preprocess(study_name, base_directory, skull_strip_label='T2SPACE', skip_modalities=[]):
""" This script is meant for members of the QTIM lab at MGH. It takes in one of our study names, finds the
COREGISTRATION folder, presumed to have been created in an earlier part of the pipeline, and applies
the following pre-processing steps to our data to make it ready for input into deep-learning algorithms:
1) N4 Bias Correction
2) Isotropic Resampling
3) Skull-Stripping
4) Zero Mean Normalization
This is a work in progress, and may not be appropriate for every deep-learning task. For example, data
completion tasks may not benefit from zero-mean normalization.
Parameters
----------
study_name: str
A QTIM study name code, usually three letters.
base_directory: str
The full path to the directory from which to search for studies. The study directory
should be contained in this directory.
skull_strip_label: str
An text identifier (e.g. "FLAIR") for which volume should be skull-stripped. All other volumes will be stripped according to this identifier.
skip_modalities: str or list of str
Any modalities that should not be processed.
"""
# NiPype is not very necessary here, but I want to get used to it. DataGrabber is a utility for
# for recursively getting files that match a pattern.
study_files = nio.DataGrabber()
study_files.inputs.base_directory = base_directory
study_files.inputs.template = os.path.join(study_name, 'ANALYSIS', 'COREGISTRATION', study_name + '*', 'VISIT_*', '*.nii.gz')
study_files.inputs.sort_filelist = True
results = study_files.run().outputs.outfiles
bias_correct_vols = ['FLAIR', 'MPRAGE', 'T1', 'T2SPACE']
# Remove modality codes that will not be processed for deep-learning.
dl_volumes = []
for output in results:
if any(modality in output for modality in skip_modalities):
continue
dl_volumes += [output]
# We prefer the same skull-stripping in each case. Thus, we first iterate through skull-strip volumes.
skull_strip_volumes = [volume for volume in dl_volumes if skull_strip_label in volume]
# Strip the chosen volume..
for skull_strip_volume in skull_strip_volumes:
# Find the output folder
# TODO: Do this with nipype DataSink instead.
# Also TODO: Make this easier to change in case directory structure changes.
split_path = os.path.normpath(skull_strip_volume).split(os.sep)
output_folder = os.path.join(base_directory, study_name, 'ANALYSIS', 'DEEPLEARNING', split_path[-3], split_path[-2])
# Make the output directory if it does not exist.
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# If skull-stripping has not yet been performed, perform it.
skull_strip_mask = os.path.join(output_folder, split_path[-3] + '-' + split_path[-2] + '-' + 'SKULL_STRIP_MASK.nii.gz')
skull_strip_output = os.path.join(output_folder, nifti_splitext(os.path.basename(skull_strip_volume))[0] + '_ss' + nifti_splitext(skull_strip_volume)[-1])
if not os.path.exists(skull_strip_mask):
skull_strip(skull_strip_volume, skull_strip_output, skull_strip_mask)
# Skull-Strip, Resample, and Normalize the rest.
for dl_volume in dl_volumes:
try:
split_path = os.path.normpath(dl_volume).split(os.sep)
output_folder = os.path.join(base_directory, study_name, 'ANALYSIS', 'DEEPLEARNING', split_path[-3], split_path[-2])
deep_learning_output = os.path.join(output_folder, nifti_splitext(os.path.basename(dl_volume))[0] + '_DL' + nifti_splitext(dl_volume)[-1])
if os.path.exists(deep_learning_output):
continue
print(output_folder)
# Make sure a mask was created in the previous step.
skull_strip_mask = os.path.join(output_folder, split_path[-3] + '-' + split_path[-2] + '-' + 'SKULL_STRIP_MASK.nii.gz')
if not os.path.exists(skull_strip_mask):
print('No skull-stripping mask created, skipping volume ', dl_volume)
continue
# Use existing mask to skull-strip if necessary.
n4_bias_output = os.path.join(output_folder, nifti_splitext(os.path.basename(dl_volume))[0] + '_n4' + nifti_splitext(dl_volume)[-1])
if any(bias_vol in n4_bias_output for bias_vol in bias_correct_vols):
if not os.path.exists(n4_bias_output):
bias_correction(dl_volume, output_filename=n4_bias_output, mask_filename=skull_strip_mask)
else:
copy(dl_volume, n4_bias_output)
# Use existing mask to skull-strip if necessary.
skull_strip_output = os.path.join(output_folder, nifti_splitext(n4_bias_output)[0] + '_ss' + nifti_splitext(n4_bias_output)[-1])
if not os.path.exists(skull_strip_output):
crop_with_mask(n4_bias_output, skull_strip_mask, output_filename=skull_strip_output)
os.remove(n4_bias_output)
# Resample and remove previous file.
# resample_output = os.path.join(output_folder, nifti_splitext(skull_strip_output)[0] + '_iso' + nifti_splitext(skull_strip_output)[-1])
# print resample_output
# if not os.path.exists(resample_output):
# resample(skull_strip_output, output_filename=resample_output)
# os.remove(skull_strip_output)
# Mean normalize and remove previous file.
if not os.path.exists(deep_learning_output):
zero_mean_unit_variance(skull_strip_output, input_mask=skull_strip_mask, output_filename=deep_learning_output)
os.remove(skull_strip_output)
except:
print('Error encountered on', os.path.basename(dl_volume))
return
def deep_learning_experiment(base_directory, output_directory, config_file):
""" This script creates a deep learning "experiment" from our available studies. This means
sorting patient visits into testing and training folders with certain pre-specified modalities.
Parameters
----------
base_directory: str
The full path to the directory from which to search for studies. The study directory
should be contained in this directory.
config_file: str
A configuration file that dictates how studies should be split and which modalities.
"""
if config_file is None:
config_file = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', 'default_configs', 'deep_learning_experiment.yaml'))
else:
config_file = os.path.asbpath(config_file)
with open(config_file, 'r') as stream:
config = yaml.load(stream)
if not os.path.exists(output_directory):
os.mkdir(output_directory)
for train_test in ['Train', 'Test', 'Validation']:
output_folder = os.path.join(os.path.abspath(output_directory), train_test)
# Make output folder
rmtree(output_folder)
# if not os.path.exists(output_folder):
os.mkdir(output_folder)
if train_test == 'Train':
for study in ['FMS']:
for patient in ['01']:
for visit in ['01','02','03', '04', '05']:
for modality in ['MPRAGE_POST', 'FLAIR_r_T2', 'T2SPACE_DL', 'T1Pre']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
for modality in ['SUV']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
if train_test == 'Validation':
for study in ['FMS']:
for patient in ['02']:
for visit in ['01','02','03', '04', '05']:
for modality in ['MPRAGE_POST', 'FLAIR_r_T2', 'T2SPACE_DL', 'T1Pre']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
for modality in ['SUV']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
if train_test == 'Test':
for study in ['FMS']:
for patient in ['05']:
for visit in ['01','02','03','04','05']:
for modality in ['MPRAGE_POST', 'FLAIR_r_T2', 'T2SPACE_DL', 'T1Pre']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
for modality in ['SUV']:
try:
target_file = glob.glob(os.path.join(base_directory, study, 'ANALYSIS', 'DEEPLEARNING', '_'.join([study, patient]), '_'.join(['VISIT', visit]), '*' + modality + '*'))[0]
target_folder = os.path.join(output_folder, '_'.join([study, patient, visit]))
if not os.path.exists(target_folder):
os.mkdir(target_folder)
copy(target_file, os.path.join(target_folder, os.path.basename(target_file)))
except:
pass
# print config[train_test]
# for study in config[train_test]['Study']:
# study_dir = study
return
def run_test():
pass
if __name__ == '__main__':
run_test()
| true |
d1ec62316dd6eeb0af2e2c6e7002d36de8f02ded
|
Python
|
akulikova64/cgm_3d_cnn
|
/src/rotations.py
|
UTF-8
| 2,205 | 3.796875 | 4 |
[
"MIT"
] |
permissive
|
# this module contains rotation functions for a 9 x 9 x 9 cube.
import math
import random
# axis is the axis across which the rotation occurs
# rot_num is the number of 90 degree rotations needed (0, 1, 2 or 3)
def rotate_box(pre_box, axis, rot_num = 0, box_size = 9): #box size is the number of bins
""" rotates box along one axis rot_num times """
box_size -= 1 # with 9 bins, indices are 0-8
dict = {"x":[1, 2], "y":[0, 2], "z":[0, 1]} # lists the axes to be changed if rotated around key
new_pre_box = []
for ind_set in pre_box:
a_1, a_2 = dict[axis][0], dict[axis][1]
ind_1, ind_2 = ind_set[a_1], ind_set[a_2]
new_set = ind_set.copy()
if rot_num == 1:
new_set[a_1] = box_size - ind_2
new_set[a_2] = ind_1
if rot_num == 2:
new_set[a_1] = box_size - ind_1
new_set[a_2] = box_size - ind_2
if rot_num == 3:
new_set[a_1] = ind_2
new_set[a_2] = box_size - ind_1
new_pre_box.append(new_set)
return new_pre_box
def multiple_rotations(i, pre_box, box_size = 9): # i is a value from 0-23 (encodes the 24 possible rotations)
""" rotates box into one of 24 possible cube orientations """
prebox_1 = rotate_box(pre_box, "z", i%4, box_size) # remainder conveniently assignes i to one of 4 z-axis rotations.
# rotate along x or y
rot_num = math.floor(i/4) # 0-5 (gives one of 6 remaining rotation possibilities)
if rot_num < 4:
prebox_2 = rotate_box(prebox_1, "y", rot_num, box_size) # 3 possible rotations around y
elif rot_num == 4:
prebox_2 = rotate_box(prebox_1, "x", 1, box_size) # get one of the remaining two conformations by rotating around x
elif rot_num == 5:
prebox_2 = rotate_box(prebox_1, "x", 3, box_size)
return prebox_2
# chooses one of 24 conformations
def rotation_combo(pre_box, rotations, box_size = 9):
""" randomly selects one of the 24 orientations of a cube """
final_preboxes = []
rot_list = random.sample(range(0, 24), rotations) # get random cube conformations "rotations" number of times.
for i in rot_list:
rotated_prebox = multiple_rotations(i, pre_box, box_size)
final_preboxes.append(rotated_prebox)
return final_preboxes
| true |
4615786737b604251596ce66e01461ab48f5881f
|
Python
|
joseluisgarciad/Hacking
|
/hacking.py
|
UTF-8
| 3,169 | 3.59375 | 4 |
[] |
no_license
|
# Versión 2
# Este es un juego basado en adivinar una password de una lista de potenciales paswords
# generados por la computadora.
# Se muestra la lista de passwords posibles
# El jugador tiene permitido 1 intento para adivinar la password.
# El juego indica que el jugador falla al adivinar la password correcta.
# Independientemente de lo que el usuario introduzca;
# Se borra la pantalla
# Con mensajes centrados se muestra; la password introducida y tres mensajes de error.
# Espera a que el usuario pulse enter
# La ventana se cierra
from uagame import Window
from time import sleep
import os
# Creamos una ventana
ventana = Window('Hacking', 600, 500)
ventana.set_font_name('couriernew')
ventana.set_font_size(18)
ventana.set_font_color('green')
ventana.set_bg_color('black')
# Se inicializan variables
tiempo_espera = 0.5
x_coord = 0
nlineafin = 7
y_coord = 0
altura_texto = ventana.get_font_height()
def linea_inicio(linea):
primera = linea * altura_texto
return primera
def centrar_texto(linea, texto):
primera = linea_inicio(linea)
c_x = (ventana.get_width() - ventana.get_string_width(texto)) // 2
c_y = (ventana.get_height() - primera) // 2
if texto == "": c_x = 0 # "" para que funcione la verificacion
ventana.draw_string(texto, c_x, c_y)
ventana.update()
print(sleep(tiempo_espera))
linea -= 2
return linea
def vt(texto: str, ycoord):
if texto != 'DEBUG MODE':
ycoord = ycoord + ventana.get_font_height()
ventana.draw_string(texto, x_coord, ycoord)
ventana.update()
sleep(tiempo_espera)
return ycoord
# display header
y_coord = vt('DEBUG MODE', 0)
# display intentos
y_coord = vt('1 ATTEMPT(S) LEFT', y_coord)
# display password
y_coord = vt("", y_coord) # "" para que funcione la verificacion
y_coord = vt('PROVIDE', y_coord); y_coord = vt('SETTING', y_coord); y_coord = vt('CANTINA', y_coord); y_coord = vt('CUTTING', y_coord);
y_coord = vt('HUNTERS', y_coord); y_coord = vt('SURVIVE', y_coord); y_coord = vt('HEARING', y_coord); y_coord = vt('HUNTING', y_coord);
y_coord = vt('REALIZE', y_coord); y_coord = vt('NOTHING', y_coord); y_coord = vt('OVERLAP', y_coord); y_coord = vt('FINDING', y_coord);
y_coord = vt('PUTTING', y_coord)
# pedir contraseña
y_coord = vt("", y_coord) # "" para que funcione la verificacion
y_coord = y_coord + ventana.get_font_height()
contrasena = ventana.input_string("ENTER PASSWORD >", 0, y_coord)
# end game
ventana.clear()
nlineafin = centrar_texto(nlineafin, contrasena)
nlineafin = centrar_texto(nlineafin, "") # "" para que funcione la verificacion
nlineafin = centrar_texto(nlineafin, 'LOGIN FAILURE - TERMINAL LOCKED')
nlineafin = centrar_texto(nlineafin, "") # "" para que funcione la verificacion
nlineafin = centrar_texto(nlineafin, 'PLEASE CONTACT AN ADMINISTRATOR')
nlineafin = centrar_texto(nlineafin, "") # "" para que funcione la verificacion
centrar_x = (ventana.get_width() - ventana.get_string_width("PRESS ENTER TO EXIT")) // 2
centrar_y = (ventana.get_height() - linea_inicio(nlineafin)) // 2
ventana.input_string("PRESS ENTER TO EXIT", centrar_x, centrar_y)
ventana.close()
# prompt for end
| true |
c7ff2893e0220f4269525b06a4e71faeb2faeec7
|
Python
|
Sirisha111102/Python
|
/lowercaseinrange.py
|
UTF-8
| 191 | 3.8125 | 4 |
[] |
no_license
|
#print lowercaseletters up to a range n
"""import string
s=int(input())
print(string.ascii_lowercase[:s])"""
s=int(input())
a=97
for i in range(s):
print(chr(a),end="")
a+=1
| true |
4d28ca24e2d70be3c51a46c93af62a7b8a650e88
|
Python
|
ToniCaimari/Codewars
|
/Python/kyu8/Is_he_gonna_survive.py
|
UTF-8
| 125 | 2.703125 | 3 |
[] |
no_license
|
def hero(bullets, dragons):
ammo = dragons*2
if bullets-ammo < 0:
return False
else:
return True
| true |
ab77864ea6682256d5f28a7733db451bcb891617
|
Python
|
panosadamop/pythonCourses
|
/trionymo.py
|
UTF-8
| 501 | 3.875 | 4 |
[] |
no_license
|
import math as m
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
d = b**2-4*a*c
if d > 0:
x1 = (-b + m.sqrt((b ** 2) - (4 * (a * c)))) / (2 * a)
x2 = (-b - m.sqrt((b ** 2) - (4 * (a * c)))) / (2 * a)
print("This equation has two solutions: ", x1, " or", x2)
elif d == 0:
x = (-b+m.sqrt(b**2-4*a*c))/2*a
print ("This equation has one solutions: "), x
else:
print("This equation has no real solution")
| true |
a2d4b452f1d4b0d25d142e698d49893133a9f23b
|
Python
|
gselva28/100_days_of_code
|
/DAY 14/game_code.py
|
UTF-8
| 2,081 | 3.78125 | 4 |
[] |
no_license
|
#Higher Lower Game Code
import random
import os
clear = lambda: os.system('cls')
from game_art import logo, vs
from game_data import data
def format_data(account):
""" Format the account data into printable format """
account_name = account["name"]
account_descr = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_descr}, from {account_country}"
def check_answer(guess, a_followers, b_followers):
"""Take the user guess and follower counts and returns if they got it right"""
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b"
# Display game_art
clear()
print(logo)
score = 0
continue_game = True
# Make the game repeatable [till lose]
# Shift the position of B account to A account
"""In this the first choice of b will be created outside the while loop then the uncoming b will the value of a and b will create a new one."""
account_b = random.choice(data)
while continue_game:
# Generate a random account from the game data [dict values]
account_a = account_b
account_b = random.choice(data)
if account_a == account_b:
account_b = random.choice(data)
print(f"Compare A: {format_data(account_a)}")
print(vs)
print(f"Compare B: {format_data(account_b)}")
# Ask user for a guess [which one has more insta follower account]
guess = input("Who has more followers? Type 'A' or 'B': ").lower()
# Check if user is correct
## Get follwer count of each account
a_follower_account = account_a["follower_count"]
b_follower_account = account_b["follower_count"]
is_correct = check_answer(guess, a_follower_account, b_follower_account)
# Clear the screen between rounds.
clear()
print(logo)
# Give user feedback on their game [win or loss each round]
# Track the score
if is_correct:
score += 1
print(f"You're right! Current score: {score}.")
else:
continue_game = False
print(f"Sorry, that's wrong. Final score: {score}")
| true |
e6d2fe7aa9805e56d388186ee972545859ea06d7
|
Python
|
zhanglongliu/Crawl
|
/movie/spiders/awesome_movie.py
|
UTF-8
| 1,093 | 2.734375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
from movie.items import MovieItem
class AwesomeMovieSpider(CrawlSpider):
name = 'awesome_movie'
start_urls = ['https://movie.douban.com/subject/3011091/']
rules= (
Rule(LinkExtractor(allow='https://movie.douban.com/subject/\d+/\?from=subject-page'),callback='parse_movie_item',follow=True),
)
def parse_movie_item(self,response):
item=MovieItem()
item['url']=response.url
item['name']=response.xpath('//span[@property="v:itemreviewed"]/text()').extract_first()
item['summary']=response.xpath('//span[@property="v:summary"]/text()').extract_first()
item['score']=response.xpath('//strong[@property="v:average"]/text()').extract_first()
print('------------------', item)
yield item
'''
def parse_start_url(self,response):
yield self.parse_movie_item(response)
def parse_page(self, response):
yield self.parse_movie_item(response)
'''
| true |
721cff03035b65eab07ffbd2d33f1f21381cca67
|
Python
|
lvoegtlin/crnn.pytorch
|
/datasets/dataset.py
|
UTF-8
| 3,045 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import os
import torch
import torch.utils.data as data
from datasets.datahelpers import default_loader
class DigitsDataset(data.Dataset):
"""Digits dataset."""
def __init__(self, mode, data_root, transform=None, loader=default_loader):
if not (mode == 'train' or mode == 'dev'):
raise(RuntimeError("MODE should be either train or dev, passed as string"))
self.mode = mode
self.transform = transform
self.loader = loader
self.img_root = os.path.join(data_root, 'images')
self.img_names = []
self.targets = []
label_path = os.path.join(data_root, '{}.txt'.format(mode))
with open(label_path, 'r') as f:
for line in f.readlines():
line = line.strip().split()
self.img_names.append(line[0])
self.targets.append(line[1:])
def __len__(self):
return len(self.img_names)
def __getitem__(self, idx):
img_name = os.path.join(self.img_root, self.img_names[idx])
image = self.loader(img_name)
if self.transform is not None:
image = self.transform(image)
target = self.targets[idx]
target = torch.IntTensor([int(i) for i in target])
return image, target
class DigitsBatchTrain:
"""Collate function for train mode."""
def __init__(self, batch, keep_ratio=False):
transposed_data = list(zip(*batch))
if keep_ratio:
self.images = transposed_data[0]
else:
self.images = torch.stack(transposed_data[0], 0)
self.targets = torch.cat(transposed_data[1], 0)
# length of the each target string
self.targets_single = transposed_data[1]
self.target_lengths = torch.IntTensor([len(i) for i in transposed_data[1]])
def pin_memory(self):
self.images = self.images.pin_memory()
self.targets = self.targets.pin_memory()
self.target_lengths = self.target_lengths.pin_memory()
return self
class DigitsBatchDev:
"""Collate function for dev mode."""
def __init__(self, batch, keep_ratio=False):
transposed_data = list(zip(*batch))
if keep_ratio:
self.images = transposed_data[0]
else:
self.images = torch.stack(transposed_data[0], 0)
self.targets = [i.tolist() for i in transposed_data[1]]
self.target_lengths = torch.IntTensor([len(i) for i in transposed_data[1]])
def pin_memory(self):
self.images = self.images.pin_memory()
return self
class DigitsCollater:
"""Digits Collater."""
def __init__(self, mode, keep_ratio=False):
self.mode = mode
self.keep_ratio = keep_ratio
def __call__(self, batch):
if self.mode == 'train':
return DigitsBatchTrain(batch, self.keep_ratio)
elif self.mode == 'dev':
return DigitsBatchDev(batch, self.keep_ratio)
else:
raise(RuntimeError("MODE should be either train or dev, passed as string"))
| true |
7511692c16fcd2d811f71b5e043953af34a5d1d7
|
Python
|
rodriguezmatirp/Lab-Main
|
/Sem 4/CN_Lab/PS_5/2/server.py
|
UTF-8
| 709 | 2.828125 | 3 |
[] |
no_license
|
import socket
import crc
LOCALHOST = '127.0.0.1'
PORT = 65432
if __name__ == '__main__':
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((LOCALHOST, PORT))
sock.listen()
while True:
conn, addr = sock.accept()
print('Connection address : ', addr)
received_data = conn.recv(100).decode('utf-8').split(' ')
codeword = received_data[0]
key = received_data[1]
if codeword and key:
remainder = crc.decode(codeword,key)
if '1' in remainder:
print('Error Detected')
else:
print('No error Detected')
| true |
acbaacc8032d1a5f420b2d5cf39435da1bc6b525
|
Python
|
DaiMaDaiMa/PythonStudy
|
/面向对象class/classdemo6.py
|
UTF-8
| 444 | 3.78125 | 4 |
[] |
no_license
|
"""
通过对象和类分别访问私有方法
但类无法访问对象的属性,无论是公有还是私有
"""
class Person():
def __init__(self, name):
self.name = name
self.__age = 18
def __secret(self):
print("%s 的年龄是 %d" % (self.name, self.__age))
if __name__ == "__main__":
p = Person("xiaofang")
print(p._Person__age)
p._Person__secret()
Person._Person__secret(p)
| true |
18ee506b695076f8b61c9742295d47bb66da9b00
|
Python
|
nberrehouma/Developpement-systeme-sous-Linux
|
/chapitre-21/exemple-buffers.py
|
UTF-8
| 459 | 3.171875 | 3 |
[] |
no_license
|
#! /usr/bin/python
from __future__ import print_function
import sys
print("1 stdout : ligne + \\n")
print("2 stdout : ligne seule", end='')
print("\n3 stderr : avant flush()", file=sys.stderr)
sys.stdout.flush()
print("\n4 stderr : apres flush ()", file=sys.stderr)
print("5 stdout : ligne seule ", end='')
print("\n6 stderr : avant sys.stdin.read()", file=sys.stderr)
sys.stdin.readline()
print("\n7 stderr : apres sys.stdin.read(stdin)", file=sys.stderr)
| true |
c79e44a4b427c0d7f1235cf8fae5cf0dc1811541
|
Python
|
jonjanelle/ChaosGame
|
/ChaosGame.py
|
UTF-8
| 1,653 | 3.71875 | 4 |
[] |
no_license
|
'''
Chaos game
1) place three starting posts
2) stamp turtle at random position
3) choose starting post at random, move to midpoint of current position and post, and stamp
4) repeat step 3 a few thousand times
Note: Stamp by moving forward 1 unit.
'''
import turtle, random
def main():
window = turtle.Screen()
pen = turtle.Turtle()
pen.tracer(-1,delay=None)
pen.color("black")
pen.hideturtle()
pen.shape("circle")
pen.pensize(1)
pen.speed(0)
pen.penup()
p1 = (-150,0)
pen.setpos(p1[0],p1[1])
pen.stamp()
p2 = (150,0)
pen.setpos(p2[0],p2[1])
pen.stamp()
p3 = (0, 150)
pen.setpos(p3[0],p3[1])
pen.stamp()
newX = 0
newY = 0
for i in range(10000):
pen.penup()
#get current pen position
px = pen.position()[0]
py = pen.position()[1]
#pick one of the three random points
point = random.randint(1,3)
#calculate new destination to place a point
if point == 1:
newX = (px + p1[0])/2
newY = (py + p1[1])/2
elif point == 2:
newX = (px + p2[0])/2
newY = (py + p2[1])/2
elif point == 3:
newX = (px + p3[0])/2
newY = (py + p3[1])/2
pen.setpos(newX,newY)
pen.pendown()
pen.forward(1)
window.exitonclick()
window.mainloop()
if __name__ == "__main__":
main()
| true |
4af0d61b4c756f0b190b22fdb36b1c96a1e5a4d9
|
Python
|
3ngthrust/Fast-Switching-Webradio
|
/webradio_parallel.py
|
UTF-8
| 5,608 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: 3ngthrust
"""
import os
import gpiozero
import functools
import time
from MCP3002 import MCP3002
def split_into_equal_sublists(a_list, number_of_parts):
""" Splits a list into a list of sublists
Arguments
----------
a_list : list object
List wich will be split into Sublists
number_of_parts : int
Number of sublists which should be created
Returns
-------
seperated_lists : list of lists
List of Sublists of the given list which are as equal sized as possible
"""
start = 0
seperated_lists = []
for i in range(number_of_parts):
end = round((len(a_list) / number_of_parts) * (i + 1))
seperated_lists.append(list(range(start,end)))
start = end
return seperated_lists
def update_station_faktory(num_of_stations, adc):
""" Creates a function to update the station of the player
Arguments
----------
num_of_stations : int
Number of different stations selectable on the player
adc : gpiozero MCO3xxx object
Analog to Digital Converter wich reads the raw slider position
Returns
-------
update_station : function
Function wich will take the current station number and update the
station on the player if necessary
"""
# Create sublists of equal sized percentage ranges for each station
percentage_sublists = split_into_equal_sublists(list(range(0,101)), num_of_stations)
def update_station(current_station, current_volume):
slider_value = int(adc.value * 100)
for i, l in enumerate(percentage_sublists):
if slider_value in l:
new_station_number = percentage_sublists.index(l)
break
if i == (len(percentage_sublists) - 1):
raise Exception("slider_value {} is not between 0 and 100".format(slider_value))
# First element in mpc is 1 not 0
new_station_number += 1
if current_station == new_station_number:
return current_station
else:
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(current_station) + ' volume 0')
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(new_station_number) + ' volume ' + str(current_volume))
return new_station_number
return update_station
def update_volume(adc, current_station, current_volume):
""" Updates the volume of the player
Arguments
----------
adc : gpiozero MCO3xxx object
Analog to Digital Converter wich reads the raw volume knob position
"""
new_volume = 100 - int(adc.value * 100)
if current_volume == new_volume:
return current_volume
else:
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(current_station) + ' volume ' + str(new_volume))
return new_volume
def toggle_mute_factory(led_0):
mute_list = [] # Small Hack: Empty List = False
def toggle_mute():
if not mute_list:
mute_list.append(1)
led_0.toggle()
else:
mute_list.pop()
led_0.toggle()
def mute():
return bool(mute_list)
return toggle_mute, mute
def reload_factory(led_1, num_of_stations):
def reload():
led_1.toggle()
for i in range(1, num_of_stations + 1):
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(i) + ' play ' + str(i))
led_1.toggle()
return reload
if __name__ == "__main__":
#time.sleep(25) # Wait for wifi connction to be established on startup
num_of_stations = 10
# Start mpd server
for i in range(1, num_of_stations + 1):
os.system('mpd /home/pi/.config/mpd/mpd_' + str(i) + '.conf')
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(i) + ' clear')
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(i) + ' load webradio_stations')
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(i) + ' volume 0')
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(i) + ' play ' + str(i))
print('All mpd servers started')
# Setup frontend
adc_0 = MCP3002(channel=0)
adc_1 = MCP3002(channel=1)
led_0 = gpiozero.LED(23)
led_1 = gpiozero.LED(22)
button_0 = gpiozero.Button(17)
button_1 = gpiozero.Button(18)
# Init
current_station = 0
current_volume = 0
# Create Functions
update_station = update_station_faktory(num_of_stations, adc_0)
update_volume = functools.partial(update_volume, adc_1)
toggle_mute, mute = toggle_mute_factory(led_0)
reload = reload_factory(led_1, num_of_stations)
# Assign functions
button_0.when_pressed = toggle_mute
button_1.when_pressed = reload
try:
while True:
if mute():
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(current_station) + ' volume 0')
current_volume = 0
while mute():
time.sleep(0.05)
current_station = update_station(current_station, current_volume)
current_volume = update_volume(current_station, current_volume)
time.sleep(0.05)
except KeyboardInterrupt:
os.system('mpc --host=/home/pi/.config/mpd/socket_' + str(current_station) + ' volume 0')
| true |
ae6111c9cfe3e44bb9f9272c47bc94a1e8d9a636
|
Python
|
adithya-tp/leet_code
|
/0112_path_sum/solution.py
|
UTF-8
| 668 | 3.1875 | 3 |
[] |
no_license
|
class Solution:
def __init__(self):
self.fs = 0
def hasPathSum(self, r: TreeNode, s: int) -> bool:
if r is None:
return False
if (r.left is not None):
self.fs += r.val
if(self.hasPathSum(r.left, s)):
return True
self.fs -= r.val
if (r.right is not None):
self.fs += r.val
if(self.hasPathSum(r.right, s)):
return True
self.fs -= r.val
if (r.left is None) and (r.right is None):
self.fs += r.val
if(self.fs == s):
return True
self.fs -= r.val
| true |
b42ed761d108c1995beeb653da3ffe848e8a3b74
|
Python
|
DaveIndeed/Pumpvakt
|
/core/InternetKommunikation.py
|
UTF-8
| 733 | 3.65625 | 4 |
[] |
no_license
|
import socket
class InternetKommunikation:
"""
Hanterar kommunikation med internet
"""
def isAnslutenTillInternet(self, host="8.8.8.8", port=53, timeout=3):
"""Undersök om man är ansluten till internet"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except Exception as ex:
#errno, strerror = ex.args
print(ex.args)
return False
if __name__ == '__main__':
i = InternetKommunikation();
if i.isAnslutenTillInternet():
print("Ansluten till internet")
else:
print("Inte ansluten till internet")
| true |
a33b871c85b25019049f392fa5ed4db1cffbca3f
|
Python
|
x-coode/WIFI_H
|
/Wifi_H.py
|
UTF-8
| 2,487 | 2.515625 | 3 |
[] |
no_license
|
# by x-c0de
# instagram x.c0de
import os
import os.path
import time,sys
try:
import pywifi
from pywifi import PyWiFi
from pywifi import const
from pywifi import Profile
except:
print("\033[1;34mInstalling pywifi\n\n")
time.sleep(0.5)
os.system("pip install pywifi")
print("run script agan")
sys.exit()
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
try:
# wlan
wifi = PyWiFi()
ifaces = wifi.interfaces()[0]
ifaces.scan() #check the card
results = ifaces.scan_results()
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
except:
print("[-] Error system")
def get_location():
print(__file__)
l = len(__file__)
f = __file__.split("\\")
l = len(f)
output =""
for i in range(l):
if i != l-1:
output += f[i] +"\\"
return output
def main(ssid, password, number):
profile = Profile()
profile.ssid = ssid
profile.auth = const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
profile.key = password
iface.remove_all_network_profiles()
tmp_profile = iface.add_network_profile(profile)
time.sleep(0.2) # if script not working change time to 1 !!!!!!
iface.connect(tmp_profile) # trying to Connect
time.sleep(0.35) # 1s
if ifaces.status() == const.IFACE_CONNECTED: # checker
time.sleep(1)
print(BOLD, GREEN,'[*] Crack success!',RESET)
print(BOLD, GREEN,'[*] password is ' + password, RESET)
p=open("passwords.txt","a+")
p.writelines(ssid+" : "+password + "\n")
time.sleep(1)
exit()
else:
print(RED, '[{}] Crack Failed using {}'.format(number, password))
def pwd(ssid, file):
number = 0
with open(file, 'r') as words:
for line in words:
number += 1
line = line.split("\n")
pwd = line[0]
main(ssid, pwd, number)
def menu():
print(BLUE)
ssid = input("[*] SSID: ")
filee = get_location()+input("[*] password list : ")
if os.path.exists(filee):
print(BLUE,"[~] Cracking...")
pwd(ssid, filee)
else:
print(RED,"[-] No Such File.",BLUE)
if __name__ == "__main__":
menu()
| true |
386d8254a0d8de0dfcd959dd55971f031b4211fc
|
Python
|
daviddwlee84/LeetCode
|
/Contest/LeetCodeWeeklyContest/WeeklyContest243/3_fail4.py
|
UTF-8
| 1,187 | 2.59375 | 3 |
[] |
no_license
|
from typing import List
import heapq
from collections import defaultdict, deque
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
server_heap = [(weight, i) for i, weight in enumerate(servers)]
heapq.heapify(server_heap)
server_free = defaultdict(list)
pending = deque()
ans = [None] * len(tasks)
time = 0
while time < len(tasks) or pending:
duration = None
if time < len(tasks):
# release new tasks
task_i = time
duration = tasks[time]
pending.append((duration, task_i))
if server_free[time]:
for i in server_free[time]:
weight = servers[i]
heapq.heappush(server_heap, (weight, i))
del server_free[time]
while server_heap and pending:
duration, task_i = pending.popleft()
_, server_i = heapq.heappop(server_heap)
ans[task_i] = server_i
server_free[time + duration].append(server_i)
time += 1
return ans
# TLE
| true |
08aa4a5dd9710886715f420caecf840fc0466267
|
Python
|
curtiskoo/miscellaneous_scripts
|
/data_parsing_poc/xlstuff.py
|
UTF-8
| 1,429 | 3.015625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 21:22:54 2018
@author: curtiskoo
"""
import openpyxl
from openpyxl import load_workbook
wb = load_workbook('testcolor.xlsx',data_only=True)
sh = wb['Sheet1']
cell = 'B3'
rgb = sh[cell].fill.start_color.rgb
#print(rgb)
for x in range(1,5):
for l in "ABCDEFG":
cell = "{}{}".format(l,x)
rgb = sh[cell].fill.start_color.index
print(rgb,l,x)
if rgb == 2:
print(l,x)
def white_cell(c,l=None,x=None):
if l == None or x == None:
cell = c
else:
cell = "{}{}".format(l,x)
rgb = sh[cell].fill.start_color.rgb
if rgb == '00000000':
return True
else:
return False
white_cell('B1','C',1)
ws = wb.worksheets[0]
ws['A1'] = 'hellosir123'
wb.save('testcolor.xlsx')
ws['A1'].value
rows = ws.max_row
columns = ws.max_column
print(rows,columns)
def get_alpha(n):
key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lst = []
if n == 0:
return
tn = n
while n > 26:
tn = n // 26
tr = n % 26
if tr == 0 and tn == 27:
#print(tn,tr)
tn = 26
tr = 26
elif tr == 0 and tn != 27:
#print(tn,tr)
tn = tn - 1
tr = 26
lst = [tr] + lst
n = tn
lst = [tn] + lst
s = ""
for x in lst:
s = s + key[x-1]
return s, lst
get_alpha(53)
| true |
9907ee276f378748947bfc7c5cd7eeca669589c3
|
Python
|
Hangyuge/scrapy
|
/coser/coser/spiders/douban.py
|
UTF-8
| 559 | 2.65625 | 3 |
[] |
no_license
|
import scrapy
from coser.items import DoubanspiderItem
class DOubanSpider(scrapy.Spider):
name = 'douban'
allowed_domains = ['movie.douban.com']
start = 0
url = 'https://movie.douban.com/top250?start='
ends = '&filter='
start_urls = [url + str(start) + ends]
def parse(self,response):
item = DoubanspiderItem()
movies = response.xpath('//*[@id="content"]/div/div[1]/ol').extract_first()
print(movies)
for movie in movies:
print(movie)
# item['title'] = movie.xpath('./li')
| true |
f98d5291d0f11dfae13b5213e62b0332dae0174b
|
Python
|
monir06/Algorithms-1
|
/Machine Learning/Regression/data.py
|
UTF-8
| 573 | 2.984375 | 3 |
[] |
no_license
|
# Setup data into two arrays
import scipy as sp
import matplotlib.pyplot as plt
from error import error
data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")
x = data[:, 0]
y = data[:, 1]
x = x[~sp.isnan(y)]
y = y[~sp.isnan(y)]
# Setup graph for plotting
plt.scatter(x, y, s=2)
plt.title("Web traffic over last month")
plt.xlabel("Time")
plt.ylabel("Hits/hour")
plt.xticks([w * 7 * 24 for w in range(10)], ['week %i'%w for w in range(10)])
plt.autoscale(tight=True)
x1,x2,y1,y2 = plt.axis()
plt.axis((x1, x2, 0, 10000))
if __name__ == "__main__":
plt.grid()
plt.show()
| true |
6d5975ff52b258c5e4304dc41e37a973b9177332
|
Python
|
diegoamorin/APIDropbox_v2
|
/download_files_apidropbox.py
|
UTF-8
| 393 | 2.921875 | 3 |
[] |
no_license
|
"""
EJEMPLOS:
TOKEN = Token de la aplicación
ARCHIVO_LOCAL = Poner la ruta y nombredel archivo
en el que se va almacenar.
RUTA_REMOTA = LA ruta donde se encuentra tu archivo
en Dropbox + nombre del archivo.
"""
import dropbox
dbx = dropbox.Dropbox("TOKEN")
with open("<ARCHIVO_LOCAL>", "wb") as f:
md, res = dbx.files_download(path="/<RUTA_REMOTA>")
f.write(res.content)
| true |
e97559d11ba69abc082b46c85e2220954c79de53
|
Python
|
HisarCS/HisarCS-PiWarsUK
|
/HisarCS_PiWarsUK/MotorControl.py
|
UTF-8
| 2,835 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
import Adafruit_PCA9685
import RPi.GPIO as GPIO
import board
import pygame
import math
class MotorControl:
def __init__(self, rightChannel, rightDIR, leftChannel, leftDIR, GPIONumbering=GPIO.BCM):
self.rightChannel = rightChannel
self.leftChannel = leftChannel
self.GPIONumbering = GPIONumbering
self.rightDIR = rightDIR
self.leftDIR = leftDIR
GPIO.setmode(GPIONumbering)
self.pwm = Adafruit_PCA9685.PCA9685()
self.pwm.set_pwm_freq(1000)
GPIO.setup(rightDIR, GPIO.OUT)
GPIO.setup(leftDIR, GPIO.OUT)
self.isArmed = False
#self.kit.servo[self.rightChannel].angle = 0
#self.kit.servo[self.leftChannel].angle = 0
def armMotors(self):
#pygame.init()
#HeyLightningYouReady = pygame.mixer.Sound("sounds/HeyLightningYouReady.wav")
#HeyLightningYouReady.play()
self.isArmed = True
def disArm(self):
self.isArmed = False
def controllerToMotor(self, x, y):
r = math.hypot(x, y)
t = math.atan2(y, x)
t += math.pi / 4
left = r * math.cos(t) * math.sqrt(2)
right = r * math.sin(t) * math.sqrt(2)
left = max(-1, min(left, 1))
right = max(-1, min(right, 1))
return int(left * 50), -int(right * 50)
def setMotorSpeeds(self, rightMotorSpeed, leftMotorSpeed, turbo=False):
self.turbo = turbo
if self.isArmed is True:
self.rightMotorSpeed = rightMotorSpeed
self.leftMotorSpeed = leftMotorSpeed
if int(self.leftMotorSpeed) > 0:
GPIO.output(self.leftDIR, GPIO.HIGH)
print("right motors forward")
else:
GPIO.output(self.leftDIR, GPIO.LOW)
print("right motors backwards")
if int(self.rightMotorSpeed) > 0:
GPIO.output(self.rightDIR, GPIO.HIGH)
print("left motors forward")
else:
GPIO.output(self.rightDIR, GPIO.LOW)
print("left motors backwards")
if self.turbo:
self.pwm.set_pwm(self.rightChannel, 0, abs(int(self.rightMotorSpeed*40.95)))
self.pwm.set_pwm(self.leftChannel, 0, abs(int(self.leftMotorSpeed*40.95)))
if not self.turbo:
self.pwm.set_pwm(self.rightChannel, 0, abs(int(self.rightMotorSpeed*40.95*0.8)))
self.pwm.set_pwm(self.leftChannel, 0, abs(int(self.leftMotorSpeed*40.95*0.8)))
print("set the pwm values:{} {}".format(self.rightMotorSpeed, self.leftMotorSpeed))
else:
self.pwm.set_pwm(self.rightChannel, 0, 0)
self.pwm.set_pwm(self.leftChannel, 0, 0)
print(" You need to arm the motors first!!! ")
| true |
ecccba6d02d21f2708f7a9b497dcc364c27afc9f
|
Python
|
sohannaik7/python-fun-logic-programs-
|
/guess_the_number_game_usingpython.py
|
UTF-8
| 1,429 | 3.8125 | 4 |
[] |
no_license
|
import random
def check(val,ran):
if ran == val:
print("you have guessed correct number that is ", ran)
return False
elif ran > val:
print("it woant that far, was't ", val)
return True
elif ran < val:
print("you have gonne too far, it was", val)
return True
if __name__ == '__main__':
won = False
while not won:
ran = random.randint(1000, 1020)
u1 = int(input("enter your choice person 1..."))
won = check(u1,ran)
if won == False:
print("you have won this round")
break
u2 = int(input("enter your choice person 2..."))
won = check(u2, ran)
if won == False:
print("you have won this round")
break
u3 = int(input("enter your choice person 3..."))
won = check(u3, ran)
if won == False:
print("you have won this round")
break
u4 = int(input("enter your choice person 4..."))
won = check(u4, ran)
if won == False:
print("you have won this round")
break
u5 = int(input("enter your choice person 5..."))
won = check(u5, ran)
if won == False:
print("you have won this round")
break
won = False
print("next round.............................")
| true |
c07bb00cc90c28fbdd984aecd6186e305a74e683
|
Python
|
KimOanhuit/khoa-luan-document
|
/Tai lieu tham khao/Draft/Source_code/cook_files.py
|
UTF-8
| 1,582 | 3.015625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @author: JapHien
import os, re, time
start_time = time.time()
folder_path = 'DATA/MATERIAL/'
save_path = 'DATA/COOKED/'
def get_stopwords():
tmp_stop_words = []
stop_words = []
for file in os.listdir('./stopword/'):
print ('Found stop word file', file)
with open ('./stopword/' + file) as f:
for line in f:
line = line.strip().replace('_', ' ')
if line not in tmp_stop_words:
tmp_stop_words.append(line)
for i in reversed(tmp_stop_words):
stop_words.append(i)
return stop_words
def cooking(file, stop_words):
ls = []
with open(file) as f:
for string in f:
if string != '':
tmp = re.sub('[0-9;:,\.\?!%&\*\$\>\<\(\)\'\'\“\”\"\"/…\-\+]', '', string)
tmp = re.sub('[\-\–\+\=\≥\\\]', '', tmp).strip().lower()
tmp = re.sub('\s+', ' ', tmp)
if tmp != '':
ls.append(tmp.strip())
meal = ' '.join(ls)
# meaningful_words = [w for w in meal.split() if not w in stop_words]
# meal = ' '.join(meaningful_words)
return (meal)
def cook_files(material, table):
stop_words = get_stopwords()
for stuff in os.listdir(material):
print ('Working on', stuff)
disk = open(table + re.sub('\.done', '', stuff) + '.txt', 'w')
for item in os.listdir(material + stuff):
content = ''
raw = material + stuff + os.sep + item
meal = cooking(raw, stop_words)
disk.write('\n'+meal)
disk.close()
if __name__ == '__main__':
print ('Hello World!!!')
cook_files(folder_path,save_path)
| true |
51f8738eb8f33469600f6c9bd5f6cd6e1857b3e3
|
Python
|
NeaHerforth/Completed-Kattis-Files
|
/quick estimate.py
|
UTF-8
| 167 | 2.90625 | 3 |
[] |
no_license
|
#! /usr/bin/env python3
import sys
#s=sys.stdin.read().splitlines()
s='''3
0
10
100'''
s=s.splitlines()
n=int(s[0])
for i in range(1, len(s)):
print(len(s[i]))
| true |
3e5ea900c670dd81f4293da9881f45a4c8a97091
|
Python
|
takoe-sebe/2019-fall-polytech-cs
|
/sketch_191204a_list61.pyde
|
UTF-8
| 412 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
k=random(5,15)
xCoordinate = [k]
def setup():
size(500,500)
smooth()
noStroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35*i + 90
def draw():
background(50)
for coordinate in xCoordinate:
fill(200)
ellipse(coordinate, 250, 30, 30)
fill(0)
ellipse(coordinate, 250, 3,3)
def keyPressed():
if (key == 's'):
saveFrame("Photo")
| true |
1bfde23c256733f3c9bc627ad9d642e8f34d8d1b
|
Python
|
NguyenBang98/PythonExercise
|
/Ex14.py
|
UTF-8
| 120 | 3.828125 | 4 |
[] |
no_license
|
def sumOfSquare(x):
sum = 0
for i in range(1, x + 1):
sum += i ** 2
return sum
print(sumOfSquare(5))
| true |
26cabcca3e88d01db887ef8775bf1449bea76080
|
Python
|
ihayhurst/StormyRoseSplice
|
/mandelbrot.py
|
UTF-8
| 12,777 | 2.5625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# coding: utf-8
import sys, math, copy, os
import numpy as np
from PIL import Image, ImageOps
from numba import jit, int32, complex64
from functools import cmp_to_key
import pyopencl as cl
from matplotlib import colormaps
@jit
def mandelbrot(c, maxiter):
z = c
for n in range(maxiter):
if abs(z) > 2.0**40:
return n
z = z * z + c
return 0
def mandelbrot_gpu(q, maxiter):
queue = cl.CommandQueue(settings.context)
output = np.empty(q.shape, dtype=np.uint16)
prg = cl.Program(
settings.context,
"""
#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable
__kernel void mandelbrot(__global float2 *q,
__global ushort *output, ushort const maxiter)
{
int gid = get_global_id(0);
float real = q[gid].x;
float imag = q[gid].y;
output[gid] = 0;
for(int curiter = 0; curiter < maxiter; curiter++) {
float real2 = real*real, imag2 = imag*imag;
if (real*real + imag*imag > 4.0f){
output[gid] = curiter;
return;
}
imag = 2* real*imag + q[gid].y;
real = real2 - imag2 + q[gid].x;
}
}
""",
).build()
mf = cl.mem_flags
q_opencl = cl.Buffer(settings.context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q)
output_opencl = cl.Buffer(settings.context, mf.WRITE_ONLY, output.nbytes)
prg.mandelbrot(
queue, output.shape, None, q_opencl, output_opencl, np.uint16(maxiter)
)
cl.enqueue_copy(queue, output, output_opencl).wait()
return output
# Progress bar to get an idea of when the image will be finished
def progressIndication(x, screenSize):
if x % 32 == 0:
prog = round(x / screenSize * 100)
print(str(prog) + "% done", end="\r")
# Used for processing on CPU
def mandelbrot_iterate_bypixel(xmin, xmax, ymin, ymax, width, height, maxiter):
r1 = np.arange(xmin, xmax, (xmax - xmin) / width)
r2 = np.arange(ymin, ymax, (ymax - ymin) / height)
data = np.zeros((height, width, 3), dtype=np.uint8)
for x in range(0, height - 1):
for y in range(0, width - 1):
c = r1[y] + r2[x] * 1j
delta = mandelbrot(c, maxiter)
red = int(delta % 255)
green = int(delta % 128)
blue = int(delta % 64)
data[x, y] = (red, green, blue)
progressIndication(x, height)
return data
# Used for processing on GPU
def mandelbrot_iterate_byarray(xmin, xmax, ymin, ymax, width, height, maxiter):
r1 = np.arange(xmin, xmax, (xmax - xmin) / width)
r2 = np.arange(ymin, ymax, (ymax - ymin) / height) * 1j
c = r1 + r2[:, np.newaxis]
c = np.ravel(c).astype(np.complex64)
n3 = mandelbrot_gpu(c, maxiter)
n3 = (n3.reshape((height, width)) / float(n3.max()) * 255.0).astype(np.uint8)
return n3
def mandelbrot_iterate(xmin, xmax, ymin, ymax, width, height, maxiter):
if settings.iterateMethod == "array":
return mandelbrot_iterate_byarray(
xmin, xmax, ymin, ymax, width, height, maxiter
)
elif settings.iterateMethod == "pixel":
return mandelbrot_iterate_bypixel(
xmin, xmax, ymin, ymax, width, height, maxiter
)
else:
print(f'Unrecognised iteration method "{settings.iterateMethod}", exiting')
exit(1)
def mandelbrot_prepare(coords):
sideLength = coords["x"]["max"] - coords["x"]["min"]
if sideLength != (coords["y"]["max"] - coords["y"]["min"]):
print("X and Y length must be the same")
exit(1)
class tile:
def __init__(self, total):
self.totalTiles = total
self.tilesPerSide = int(math.sqrt(self.totalTiles))
self.length = int(imageSettings.length / self.tilesPerSide)
self.maxIter = imageSettings.maxIter
def setXInfo(self, xCount):
self.x["min"] = coords["x"]["min"] + (
(sideLength / self.tilesPerSide) * xCount
)
self.x["max"] = coords["x"]["min"] + (
(sideLength / self.tilesPerSide) * (xCount + 1)
)
def setYInfo(self, yCount):
self.y["min"] = coords["y"]["min"] + (
(sideLength / self.tilesPerSide) * yCount
)
self.y["max"] = coords["y"]["min"] + (
(sideLength / self.tilesPerSide) * (yCount + 1)
)
x = {}
y = {}
tileCount = imageSettings.tilesPerSide**2
tileInfo = tile(tileCount)
tiles = []
for x in range(0, tileInfo.tilesPerSide):
tempTile = tile(tileCount)
tempTile.setXInfo(x) # Work out x min and max values for that tile
for y in range(0, tileInfo.tilesPerSide):
tempTile.id = (tileInfo.tilesPerSide - y) + (
x * tileInfo.tilesPerSide
) # Get the tile ID, using x and y
tempTile.setYInfo(y) # Work out y min and max values for that tile
tiles.append(copy.deepcopy(tempTile))
tiles[len(tiles) - 1].x = copy.deepcopy(tempTile.x)
tiles[len(tiles) - 1].y = copy.deepcopy(tempTile.y)
def orderById(a, b):
if a.id > b.id:
return 1
else:
return -1
tiles.sort(key=cmp_to_key(orderById))
for tile in tiles:
print(
f'{tile.id}: {tile.x["min"]}, {tile.x["max"]}, {tile.y["min"]}, {tile.y["max"]}, {tile.length}, {tile.length}, {tile.maxIter}'
)
data = mandelbrot_iterate(
tile.x["min"],
tile.x["max"],
tile.y["min"],
tile.y["max"],
tile.length,
tile.length,
tile.maxIter,
)
mandelbrot_image_pil(
data, tile, f"plots/plot{tile.id}.{imageSettings.fileType}"
)
# Merge all the images into 1
combine_images("output")
def mandelbrot_image_pil(data, tile, outputPath):
# Normalise data
data = data / (data.max() / 1.0)
# Apply a colourmap, remap to 0-255
colourMap = colormaps.get_cmap(imageSettings.colourMap)
data = np.uint8(colourMap(data) * 255)
# Create image and flip
image = Image.fromarray(data)
image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
if not os.path.exists("plots"):
os.mkdir("plots")
image.save(outputPath)
print(f"Rendered region {tile.id}/{tile.totalTiles}\n")
def combine_images(outputImage):
outputPath = f"{outputImage}.{imageSettings.fileType}"
print(f"Exporting images to {outputPath}")
images = []
for file in os.listdir("plots"):
if file.endswith(imageSettings.fileType):
images.append(f"plots/{file}")
def plotSort(a, b):
# Remove 'plots/plot' and file extension from files, then compare numerically
a = a.split(".")[0].replace("plots/plot", "")
b = b.split(".")[0].replace("plots/plot", "")
if int(a) > int(b):
return 1
else:
return -1
images.sort(key=cmp_to_key(plotSort))
shape = (imageSettings.tilesPerSide, imageSettings.tilesPerSide)
length = int(imageSettings.length / imageSettings.tilesPerSide)
size = (length, length)
shape = shape if shape else (1, len(images))
image_size = (length * shape[1], length * shape[0])
image = Image.new("RGB", image_size)
# Paste images into final image
for row in range(shape[0]):
for col in range(shape[1]):
offset = length * col, length * row
imageCount = col * shape[1] + row
images[imageCount] = Image.open(images[imageCount])
image.paste(images[imageCount], offset)
images[imageCount] = None
image.save(outputPath, imageSettings.fileType)
"""
#Top level
#xmin, xmax, ymin, ymax = -2.0, 0.5,-1.25, 1.25
#Test Zoom 1
#xmin,xmax,ymin,ymax = -0.375,0.125, -1.125,-0.675
#Test Zoom 2
#min,xmax,ymin,ymax = -0.25,-0.125, -0.9,-0.775
#Test Zoom 3
#xmin,xmax,ymin,ymax = -0.1875,-0.1725, -0.845,-0.830
#Interesting region from JFP's page
#xmin,xmax,ymin,ymax = -0.74877, -0.74872, 0.065053 , 0.065103
#dcutchen post marksmath,org
xmin,xmax,ymin,ymax =-0.34853774148008254, -0.34831493420245574, -0.6065922085831237, -0.606486596104741
mandelbrot_image_mpl(xmin,xmax,ymin,ymax,width,height,maxiter)
#mandelbrot_image_PIL(xmin,xmax,ymin,ymax,width,height,maxiter)
"""
def main():
# Set co-ordinate boundary below
coords = {
"default": {
"x": {"min": -0.74877, "max": -0.74872},
"y": {"min": 0.065053, "max": 0.065103},
},
"alternative": {
"x": {"min": -0.750222, "max": -0.749191},
"y": {"min": 0.030721, "max": 0.031752},
},
}
# Cleanup old plots
if os.path.isdir("plots"):
oldPlots = os.listdir("plots")
if oldPlots != []:
for file in oldPlots:
os.remove(f"plots/{file}")
mandelbrot_prepare(coords["default"])
print("Image complete!")
sys.exit(1)
# Program operation settings
class settings:
iterateMethod = "pixel" # Handled by arguments, 'pixel' uses cpu
context = "" # Handled by arguments
coreCount = 1
# Settings to generate image from
class imageSettings:
def __init__(self):
self.fileType = "png"
self.tilesPerSide = 2
self.resolutionMultiplier = 1
self.length = 4096 * self.resolutionMultiplier
self.maxIter = 2048
self.colourMultiplier = 1
self.colourMap = "twilight"
imageSettings = imageSettings()
class deviceSettings:
defaultPlatform = 0
defaultDevice = 0
# Handled by arguments from here
platform = None
device = None
useSettings = False
def createContext():
# Don't change context if one is already selected
if settings.context != "":
return settings.context
# Turn pre-selected device into a context
if deviceSettings.useSettings:
platform = cl.get_platforms()[
deviceSettings.platform
] # Select the chosen platform
device = platform.get_devices()[
deviceSettings.device
] # Select the chosen device
return cl.Context([device])
# Ask for a device and return it
return cl.create_some_context(interactive=True)
if __name__ == "__main__":
for i, arg in enumerate(sys.argv):
if arg == "--cpu": # Setup settings for CPU processing
settings.iterateMethod = "pixel"
elif arg == "--gpu": # Setup settings for GPU processing
settings.iterateMethod = "array"
elif (
arg == "--platform"
): # If a platform is specified, get the next argument and set it as the platform
if len(sys.argv) >= i + 2:
platform = sys.argv[i + 1]
try:
platform = int(platform)
deviceSettings.platform = platform
deviceSettings.useSettings = True
except:
print(f'--platform must be one of the following, not "{platform}":')
for i, platform in enumerate(cl.get_platforms()):
print(f"{i}: {platform}")
exit(1)
elif (
arg == "--device"
): # If a device is specified, get the next argument and set it as the device
if len(sys.argv) >= i + 2:
device = sys.argv[i + 1]
try:
device = int(device)
deviceSettings.device = device
deviceSettings.useSettings = True
except:
print(f'--device must be an integer, not "{device}"')
exit(1)
elif arg == "--help":
print("Help page:")
print(" --cpu : Run the program on CPU")
print(" --gpu : Run the program on GPU")
print(" --platform [PLATFORM] : Select which platform the device is on")
print(" --device [DEVICE] : Select the device to run on")
exit(0)
# If creating a context is required, do it
if settings.iterateMethod == "array":
# If settings are to be used, fill in defaults where needed
if deviceSettings.useSettings:
if deviceSettings.platform == None:
deviceSettings.platform = deviceSettings.defaultPlatform
if deviceSettings.device == None:
deviceSettings.device = deviceSettings.defaultDevice
settings.context = createContext()
main()
| true |
d309cd3f5bc3f0bb482d37499044bee6002bce77
|
Python
|
HyeonJun97/Python_study
|
/Chapter05/Chapter5_pb53.py
|
UTF-8
| 1,025 | 3.78125 | 4 |
[] |
no_license
|
#Q5.53
import turtle
import math
turtle.penup()
turtle.goto(-200,0)
turtle.pendown()
turtle.goto(200,0)
turtle.setheading(150)
turtle.forward(20)
turtle.goto(200,0)
turtle.setheading(210)
turtle.forward(20) #축 화살표 그리기
turtle.penup()
turtle.goto(0,-80)
turtle.pendown()
turtle.goto(0,80)
turtle.setheading(240)
turtle.forward(20)
turtle.goto(0,80)
turtle.setheading(300)
turtle.forward(20)
turtle.penup()
turtle.goto(-100,-15)
turtle.pendown()
turtle.write("-2\u03c0")
turtle.penup()
turtle.goto(100,-15)
turtle.pendown()
turtle.write("2\u03c0")
turtle.penup()
turtle.color("red")
turtle.goto(-175,50*math.sin((-175/100)*2*math.pi))
turtle.pendown()
for x in range(-175, 176):
turtle.goto(x,50*math.sin((x/100)*2*math.pi))
turtle.penup()
turtle.color("blue")
turtle.goto(-175,50*math.cos((-175/100)*2*math.pi))
turtle.pendown()
for x in range(-175, 176):
turtle.goto(x,50*math.cos((x/100)*2*math.pi))
turtle.hideturtle()
turtle.done()
| true |
5e369d5441c722baa93843ff30750e7be4232d41
|
Python
|
dariosanfilippo/bitstream_DSP_ANN
|
/freq_est_plot.py
|
UTF-8
| 1,387 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
# This program generates scatter plots from .csv files data.
# Run this from within the folder containing the .csv files to
# convert them all into .pdf plots.
#
# Make sure to change the title to reflect your data.
#
# Copyright (c) Dario Sanfilippo 2021
import sys
import glob
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
for filename in glob.glob('*.csv'):
freq = []
error = []
tmp = []
name = []
name = filename
name = name + ".pdf"
data = pd.read_csv(filename)
tmp = data.to_numpy()
l = len(data)
for i in range(l):
freq = np.append(freq, tmp[i][0])
error = np.append(error, tmp[i][1])
print(freq)
plt.xlabel('Frequency (Hz) target')
plt.ylabel('Prediction error (target-ANN ratio complement)')
plt.axhline(y = 0, linewidth = .25, color = 'r', label = "Best fit")
plt.scatter(freq, error, marker = "o", s = .1, linewidth = 1, color = 'black', label = "Prediction error")
#plt.plot(freq, error, marker = ".", linewidth = 0, color = 'black', label = "ANN output")
plt.title("Frequency estimation")
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())
plt.grid(True)
plt.savefig(name)
plt.clf()
| true |
db72f7b5a472f5d4d90879257bfce1485cb51d8f
|
Python
|
maxweldsouza/reps
|
/moderate/tic_tac_win.py
|
UTF-8
| 1,261 | 3.53125 | 4 |
[] |
no_license
|
# ctci 16.4
import unittest
def tictacwin(board):
score = {'X': 0, 'Y': 0, ' ': 0}
def match(a, b, c):
if a == b == c:
score[a] += 1
for i in range(3):
match(*board[i])
transpose = zip(*board)
for i in range(3):
match(*transpose[i])
match(board[0][0], board[1][1], board[2][2])
match(board[0][2], board[1][1], board[2][0])
if score['X'] > 0 and score['Y'] > 0:
raise ValueError('Invalid input')
elif score['X'] > 0:
return 'X'
elif score['Y'] > 0:
return 'Y'
else:
return None
print tictacwin([('X', ' ', ' '),(' ', ' ', ' '),(' ', ' ', ' ')])
print tictacwin([('X', 'Y', ' '),(' ', ' ', ' '),(' ', ' ', ' ')])
print tictacwin([('X', 'X', 'X'),(' ', ' ', ' '),(' ', ' ', ' ')])
print tictacwin([('X', ' ', ' '),('X', ' ', ' '),('X', ' ', ' ')])
print tictacwin([('X', ' ', ' '),(' ', 'X', ' '),(' ', ' ', 'X')])
print tictacwin([(' ', ' ', 'X'),(' ', 'X', ' '),('X', ' ', ' ')])
print tictacwin([('Y', 'Y', 'Y'),(' ', ' ', ' '),(' ', ' ', ' ')])
print tictacwin([('Y', ' ', ' '),('Y', ' ', ' '),('Y', ' ', ' ')])
print tictacwin([('Y', ' ', ' '),(' ', 'Y', ' '),(' ', ' ', 'Y')])
print tictacwin([(' ', ' ', 'Y'),(' ', 'Y', ' '),('Y', ' ', ' ')])
| true |
4a6dad3e35e3fea5d71726c73cf4e31667fecbfb
|
Python
|
IvayloSavov/OOP
|
/Exercise_Attributes_and_Methods/gym/project/trainer.py
|
UTF-8
| 336 | 3.078125 | 3 |
[] |
no_license
|
class Trainer:
_count_trainers = 0
def __init__(self, name: str):
Trainer._count_trainers += 1
self.name = name
self.id = Trainer._count_trainers
def __repr__(self):
return f"Trainer <{self.id}> {self.name}"
@classmethod
def get_next_id(cls):
return cls._count_trainers + 1
| true |
b3bfedbd3f2f2f90622819aee5e00340f99e88e2
|
Python
|
martat96/K-Means-Visualization
|
/Menu.py
|
UTF-8
| 6,519 | 2.890625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from tkinter import *
import tkFileDialog
from PIL import Image, ImageTk
import numpy as np
import cv2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import colors
import plotly.express as px
import plotly.graph_objects as go
import scipy.misc
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
# initiating the application window and menu
def init_window(self):
self.master.title("Algorytm K-Średnich")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label="Wgraj zdjęcie", command=self.foto)
file.add_command(label="O algorytmie", command=self.info)
file.add_command(label="Wyjście", command=self.client_exit)
menu.add_cascade(label="Menu", menu=file)
w = Label(self.master, text="Wizualizacja działania metody K-Średnich",font=("Helvetica", 16))
w.place(x=205, y=10)
# window with information about algorithm
def info(self):
path = r'info.jpg'
image = cv2.imread(path)
window_name = "Informacje o algorytmie"
cv2.imshow(window_name, image)
# exiting application
def client_exit(self):
exit()
# getting image from user folder and displaying it
def foto(self):
# getting path of an image
path = tkFileDialog.askopenfilename()
img = Image.open(path)
# changing the size of an image
size=img.size
width = size[0]
ratio=width/225
heigth=size[1]/ratio
img=img.resize((225,heigth))
img_send = np.array(img)
# displaying image on window
render = ImageTk.PhotoImage(img)
img = Label(self, image=render)
img.grid(row=20, column=0, sticky=W, pady=2)
img.image = render
img.place(x=50, y=80)
l1 = Label(self.master, text = "K = ")
l1.place(x=80, y=40)
# pixel graph of the input image
def plotIn(img):
# OpenCV split() - divides the image into component channels
r, g, b = cv2.split(img)
# spliting the image and configuration of the 3D graph
fig = plt.figure()
axis = fig.add_subplot(1, 1, 1, projection="3d")
# setting the color of pixels
pixel_colors = img.reshape((np.shape(img)[0] * np.shape(img)[1], 3))
norm = colors.Normalize(vmin=-1., vmax=1.)
# Colors to flatten them into a list and normalize them so that they can be passed to the facecolors parameter of Matplotlib.scatter()
norm.autoscale(pixel_colors)
pixel_colors = norm(pixel_colors).tolist()
axis.scatter(r.flatten(), g.flatten(), b.flatten(), facecolors=pixel_colors, marker=".")
axis.set_xlabel("Red")
axis.set_ylabel("Green")
axis.set_zlabel("Blue")
plt.show()
# k-means algorithm
def onClicked():
# getting the input value of K
k = entry.get()
Z = img_send.reshape((-1, 3))
Z = np.float32(Z)
# determining the criteria of the algorithm and executing it
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = int(k)
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img_send.shape))
# output plot of clustered image
def plotOut(Z, center):
fig = plt.figure()
axis = fig.add_subplot(1, 1, 1, projection="3d")
axis.scatter(Z[:, 0], Z[:, 1], Z[:, 2], c=label[:, 0], cmap='viridis', alpha=0.05)
axis.scatter(center[:, 0], center[:, 1], center[:, 2], s=500, c='black', alpha=1)
axis.set_xlabel("Red")
axis.set_ylabel("Green")
axis.set_zlabel("Blue")
plt.show()
# output plot of clustered image - online using Plotly
def plotOnline(Z, center):
# pixel visualization
figure1 = go.Scatter3d(x=Z[:, 0], y=Z[:, 1], z=Z[:, 2],name = 'pixels', mode='markers', marker=dict(
color=label[:, 0],
size=1.5,
symbol='circle'
)
)
# centroids visualization
figure2 = go.Scatter3d(x=center[:, 0], y=center[:, 1], z=center[:, 2], name = 'centroids', mode='markers', marker=dict(
size=50,
color='rgb(127,127,127)',
symbol='circle'
), opacity=0.7
)
data = [figure1, figure2]
layout = go.Layout()
figure = go.Figure(data, layout)
figure.show()
buttonPlotOut = Button(self.master, text="Wykres obrazu wyjściowego", command= lambda: plotOut(Z,center))
buttonPlotOut.place(x=300, y=170)
buttonPlotOnline = Button(self.master, text="Wykres obrazu wyjściowego online", command= lambda: plotOnline(Z,center))
buttonPlotOnline.place(x=300, y=200)
# displaying the output image
res2=Image.fromarray(res2)
render2 = ImageTk.PhotoImage(res2)
res2 = Label(self, image=render2)
res2.grid(row=20, column=0, sticky=W, pady=2)
res2.image = render2
res2.place(x=500, y=80)
entry = Entry(self.master)
entry.place(x=110, y=45)
entry.insert(0, "4")
button = Button(self.master, text="OK", command=lambda: onClicked())
button.place(x=250, y=43)
buttonPlotIn = Button(self.master, text="Wykres obrazu wejsciowego", command=lambda: plotIn(img_send))
buttonPlotIn.place(x=300, y=140)
label = Label(root)
label.pack()
root = Tk()
root.geometry("800x400")
app = Window(root)
root.mainloop()
| true |
ae0a243d2befdeb9a7835bd10e5e88f0fe888d5d
|
Python
|
LourdesOshiroIgarashi/coursera-ime-usp
|
/Python 1/Semana 8/Tarefa de programação/1-remove_repetidos.py
|
UTF-8
| 517 | 4.3125 | 4 |
[
"MIT"
] |
permissive
|
# Escreva a função remove_repetidos que recebe como parâmetro uma lista com números inteiros,
# verifica se tal lista possui elementos repetidos e os remove.
# A função deve devolver uma lista correspondente à primeira lista, sem elementos repetidos.
# A lista devolvida deve estar ordenada.
# Dica: Você pode usar lista.sort() ou sorted(lista).
# >>>lista = [2, 4, 2, 2, 3, 3, 1]
# >>>remove_repetidos(lista)
# [1, 2, 3, 4]
def remove_repetidos(lista):
lista = sorted(set(lista))
return lista
| true |
55f3f195b2a390e8dfef3babb0f2fbdd71426c9f
|
Python
|
s123600g/asr_edgetpu_demo
|
/plot_audio.py
|
UTF-8
| 4,463 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
# -*- coding:utf-8 -*-
import librosa
import librosa.display
import os
import numpy as np
import matplotlib.pyplot as plt
sample_rate = 16000
channel = 1 # 單一通道(single channel)
Audio_Data_DirectoryName = "prediction_data"
Audio_Data_Path = os.path.join(
os.getcwd(),
Audio_Data_DirectoryName
)
Save_Img_Root_DirectoryName = "plot_figure"
Save_Img_DirectoryName = "audio_spectrum"
Save_Img_Path = os.path.join(
os.getcwd(),
Save_Img_Root_DirectoryName,
Save_Img_DirectoryName
)
if __name__ == "__main__":
# try:
if not os.path.exists(Audio_Data_Path): # 判斷音檔存放位置是否存在
raise Exception(
"The ['{}'] is not exists !!".format(Audio_Data_Path)
)
elif not os.path.exists(Save_Img_Path): # 判斷輸出圖片存放位置是否存在
raise Exception(
"The ['{}'] is not exists !!".format(Save_Img_Path)
)
else:
print("[plot_audio] Start load audio data....\n")
''' 判斷放置紀錄檔案目錄位置內是否存在有目錄 '''
if os.listdir(Save_Img_Path) != 0:
''' 讀取放置紀錄檔案目錄位置內容 '''
for read_dir in os.listdir(Save_Img_Path):
''' 判斷當前讀取放置紀錄檔案目錄位置內容項目是否為目錄 '''
if os.path.isdir(os.path.join(Save_Img_Path, read_dir)):
''' 讀取當前放置紀錄檔案目錄位置內容目錄內檔案 '''
for read_content in os.listdir(os.path.join(Save_Img_Path, read_dir)):
''' 刪除當前讀取到檔案 '''
os.remove(
os.path.join(
Save_Img_Path,
read_dir,
# 當前讀取放置紀錄檔案目錄位置內容目錄內檔案
read_content
)
)
''' 刪除當前目錄 '''
os.rmdir(
os.path.join(
Save_Img_Path,
read_dir,
)
)
''' 讀取當前指定位置內容 '''
for read_dir in os.listdir(Audio_Data_Path):
''' 判斷當前的路徑是否為一個目錄 '''
if os.path.isdir(os.path.join(Audio_Data_Path, read_dir)):
print(
"[plot_audio] Current Load Directory Name ['{}']".format(
read_dir)
)
''' 建立當前類別目錄 '''
os.mkdir(
os.path.join(
Save_Img_Path,
read_dir
)
)
''' 掃描檔案 '''
for read_file in os.listdir(os.path.join(Audio_Data_Path, read_dir)):
print(
"[plot_audio] Current Load Directory Name ['{}'] --> File ['{}']".format(
read_dir,
read_file
)
)
''' 讀取音頻檔案 '''
wave, sr = librosa.load(os.path.join(
Audio_Data_Path,
read_dir,
read_file
),
duration=5.0,
mono=True,
sr=sample_rate
)
''' 設置圖片大小 '''
plt.figure(figsize=(12, 8))
# plt.subplot(4, 2, 7)
data = librosa.amplitude_to_db(
np.abs(librosa.stft(wave)), ref=np.max)
''' 產生音頻頻譜圖 '''
librosa.display.specshow(
data=data, sr=sample_rate, x_axis='time', y_axis='log')
plt.colorbar(format='%+2.0f dB')
plt.title('Log power spectrogram')
''' 音頻頻譜圖存檔 '''
plt.savefig(os.path.join(Save_Img_Path,
read_dir, str(read_file+'.png')))
print()
# except Exception as err:
# print("\n>>> {} <<<".format(err))
| true |
72a306ac2a15db909b1cc4fd2d019f046fcea8d5
|
Python
|
PigSupreme/clayton-rpi-tactical
|
/castle01.py
|
UTF-8
| 2,928 | 2.6875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
"""
Student-designed FSM
"""
# for python3 compat
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from random import randint as roll_int
# Game world constants
from fsm_student01.gamedata import WALL_MAX, LADDER_HEIGHT, WINNING_SCORES, MAX_TURNS, GameOver
# Messaging
#from fsm_student.gamedata import LADDER_PLACED, LADDER_DOWN, LOOK_FOR_SPACE
from fsm_ex.base_entity import DELAY, SEND_ID, RECV_ID, MSG_TYPE, EXTRA
# Game Entities
#from fsm_ex.base_entity import BaseEntity
from fsm_student01.gamedata import CASTLE_WALL, ATTACKER, DEFENDER
# State Machines
#from fsm_ex.state_machine import State, STATE_NONE, StateMachine
##############################################################################
class GameClock(object):
"""Class for managing game world clocks/timers."""
def __init__(self, start=0, tick=1):
self.gametime = start
# Tick interval must be positive; default to 1 if not
if tick > 0:
self.tick = tick
else:
self.tick = 1
def now(self):
"""Returns the current time on this clock."""
return self.gametime
def update(self):
"""Advances the clock by one tick."""
self.gametime += self.tick
def since(self, time):
"""Returns the time elasped on this clock since the given time.
If negative, time is in the future."""
return self.gametime - time
##############################################################################
from fsm_ex.base_entity import EntityManager, MessageDispatcher
from fsm_student01.ent_attacker import Attacker
from fsm_student01.ent_sentry import Sentry
from fsm_student01.ent_wall import Wall
##############################################################################
if __name__ == "__main__":
# Initialize Manager-type objects:
MASTER_CLOCK = GameClock()
ENTITY_MGR = EntityManager()
MSG_DISPATCHER = MessageDispatcher(MASTER_CLOCK.now, ENTITY_MGR)
# Create and register entities
# Wall must be initialized first
WALLS = Wall(CASTLE_WALL, MSG_DISPATCHER)
ENTITY_MGR.register(WALLS)
# Sentries and attackers must be assigned to a wall
ent_list = [(ATTACKER, Attacker), (DEFENDER, Sentry)]
for (ename, etype) in ent_list:
new_entity = etype(ename, MSG_DISPATCHER, WALLS)
ENTITY_MGR.register(new_entity)
# Start FSM logic: Must be done AFTER all entities are registered.
ENTITY_MGR.start_all_fsms()
# Main Loop
while MASTER_CLOCK.since(0) < MAX_TURNS:
try:
MASTER_CLOCK.update()
print("\n *** Game Turn %d ***" % MASTER_CLOCK.since(0))
ENTITY_MGR.update()
MSG_DISPATCHER.dispatch_delayed()
except GameOver:
break
print("Elapsed time: %d clock ticks." % MASTER_CLOCK.since(0))
| true |
bbbbe12fc88b8db073cdfd8856a0b3fdfa7a08c6
|
Python
|
chandramouli369/courseplan
|
/fileupload/uploads/individual_timetable/1_Hash Code.py
|
UTF-8
| 913 | 2.65625 | 3 |
[] |
no_license
|
for k in range(1,2):
file = open("input"+str(k)+".txt", "r")
tot_books,tot_lib,tot_days=map(int, file.readline().split())
scores = list(map(int, file.readline().split()))
sort_index = []
sl=len(scores)
for i in range(sl):
m=max(scores[i:])
t=scores[i]
scores[i] = m
scores[scores.index(m)]
print()
# for j in range (i+1,sl):
# if (scores[i]<scores[j]):
library = []
for i in range(tot_lib):
tmp = []
lib = list(map(int, file.readline().split()))
lib_book_index = list(map(int, file.readline().split()))
tmp.append(lib)
tmp.append(lib_book_index)
library.append(tmp)
# print (tot_books,tot_lib,tot_days)
file = open("output"+str(k)+".txt", "w")
file.write(str(tot_lib)+"\n")
for i in range (0,tot_lib):
file.write(str(i)+" "+str(len(library[i][1]))+"\n")
str1= ""
for j in range(len(library[i][1])):
str1 += str(library[i][1][j])+" "
file.write(str1+"\n")
| true |
d38c067e932ec012e07216f16317c3ec409f9e75
|
Python
|
asolisn/-ejercicios-de-python
|
/ejercicios de python/ejercicio 7.py
|
UTF-8
| 346 | 3 | 3 |
[] |
no_license
|
#string
nombres='Arianna Solis'
dirDomiciaria= "Chile y Guayaquil"
Tipo_sexo='M'
#Boolean
#Colecciones
usuario=('dchiki','1234','chiki@gmail.com')
materias=['Programacion Web','PHP','POO']
docente={'nombre','Arianna','edad':20,'fac':'faci'}
#Imprimir
print("""Mi nombre es {},tengo {} años"""format(nombres,edad))
print(usuario,materias,docente)
| true |
def9eb0023e1409c1abbdc202add0f94f4b7b0b8
|
Python
|
yezigege/offer
|
/定时任务/官方文档/test002.py
|
UTF-8
| 661 | 3.078125 | 3 |
[] |
no_license
|
from datetime import date
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
def my_job(text):
print(text)
"""
date 在指定时间点触发任务
"""
# 在2019年12月5日执行
# sched.add_job(my_job, 'date', run_date=date(2009, 12, 5), args=['text'])
# datetime类型(用于精确时间) 在2019年11月6日 16:30:05执行
# sched.add_job(my_job, 'date', run_date=datetime(2019, 11, 6, 16, 30, 5), args=['text'])
# 文本类型
# sched.add_job(my_job, 'date', run_date='2019-12-05 16:15:00', args=['text'])
# 未显式指定,那么则立即执行
sched.add_job(my_job, args=['text'])
sched.start()
| true |
7e50b031583e22a1b41e7173968acdd4e90fb42d
|
Python
|
yubanUpreti/IWAcademy_PythonAssignment
|
/Python Assignment III/Question-A/tower_of_hanoi.py
|
UTF-8
| 488 | 3.96875 | 4 |
[] |
no_license
|
print("#"*50)
print("")
print("*"*20+" Tower of Hanoi problem for ‘n’ number of disks. "+"*"*20)
def tower_of_hanoi(number_of_disks,src,dst,temp):
if number_of_disks == 1:
print(f" Move disk {number_of_disks} from {src} to {dst} ")
return
tower_of_hanoi(number_of_disks-1,src,dst,temp)
print(f" Move disk {number_of_disks} from {src} to {dst} ")
tower_of_hanoi(number_of_disks-1,temp,dst,src)
tower_of_hanoi(3,'A','B','C')
print("")
print("#"*50)
| true |
67c321616dde3afafef263e98c35d74fd4bfe09c
|
Python
|
ogandolfo/Mid-Earth-Python
|
/Python - Curso em vídeo/Mundo 1/desafios/desafio023 - Separando dígitos de um número.py
|
UTF-8
| 379 | 4.5 | 4 |
[] |
no_license
|
# Faça um programa que leia um númer de 0 a 9999 e mostre na tela cada um dos digitos separados
num = int(input("Digite um número entre '1' e '9999': "))
m = num // 1000 % 10
c = num // 100 % 10
d = num // 10 % 10
u = num // 1 % 10
print(f'Analisando o número {num}')
print(f'Milhar: {m}')
print(f'Centena: {c}')
print(f'Dezena: {d}')
print(f'Unidade: {u}')
| true |
e2d1376b8bc60516d10bfed7007416fce5c4156c
|
Python
|
bfernando1/pynet
|
/week3/exercise2.py
|
UTF-8
| 1,645 | 3.703125 | 4 |
[] |
no_license
|
#! /usr/bin/env python3
"""
Author: Bradley Fernando
Purpose: Reads in a file from a `show arp` output. Uses a loop to find the ip/
mac addresses and prints them to standard output if it meets a
condition. Once conditons are met, the loop terminates.
Usage:
python exercise2.py
Output:
--------------------------------------------------------------------------------
Default Gateway IP: 10.220.88.1
MAC Address: 0062.ec29.70fe
--------------------------------------------------------------------------------
Arista3 IP/Mac: 10.220.88.30
MAC Address: 5254.ab71.e119
--------------------------------------------------------------------------------
"""
# Read in the file 'show arp'
with open('show_arp.txt') as f:
arp_lines = f.readlines()
arista3_ip, default_gw = '', ''
line_break = '-' * 80
# Parse through the 'show arp' output and store the ip/mac address
for line in arp_lines:
if line.startswith('Protocol'):
continue
ip_addr = line.split()[1]
mac_addr = line.split()[3]
# Look for the Default Gateway and Arista3 IP/MAC
if ip_addr == '10.220.88.1':
print(line_break)
print(f"Default Gateway IP: {ip_addr}")
print(f"MAC Address: {mac_addr}")
print(line_break)
default_gw = ip_addr
elif ip_addr == '10.220.88.30':
print(f"Arista3 IP/Mac: {ip_addr}")
print(f"MAC Address: {mac_addr}")
print(line_break)
arista3_ip = ip_addr
# Break out of loop once both IPs are found
if arista3_ip and default_gw:
print("Found both IPs, exiting...")
break
| true |
3f3b19fd1a4abe0fe43d2eeaf1c0c8534838358d
|
Python
|
msabbir007/Introduction-to-Python
|
/Assignment (Round5)/isthe_listin_order.py
|
UTF-8
| 195 | 3.09375 | 3 |
[] |
no_license
|
def is_the_list_in_order(l):
if len(l) == 0:
return True
else:
sort_l=sorted(l)
if sort_l == l:
return True
else:
return False
| true |
a59cedd2b868e5207111fbe56a5d9cdeae18c67c
|
Python
|
Allenhe123/PythonAlgorithm
|
/Other/scipyTest.py
|
UTF-8
| 925 | 2.546875 | 3 |
[] |
no_license
|
import numpy as np
import scipy as sp
'''
based on the effective data structures of numpy, scipy provides the senior algorithm applications.
数值分析算法库: 矩阵运算,线性代数,最优化方法,聚类,空间运算,FFT
cluster - 层次聚类(cluster.hierarchy) 矢量量化/K均值(cluster.vq)
constants - 物理和数学常量 转换方法
fftpack - 离散傅里叶变换
integrate - 积分例程
interpolate - 插值(线性,三次方。。等等)
io - 数据输入输出
linalg - 采用优化BLAS和APACK库的线性代数函数
maxentropy - 最大熵模型函数
ndimage - n维图像工具包
odr - 正交距离回归
optimize - 最优化(寻找极小值和方程的根)
signal - 信号处理
sparse - 稀疏矩阵
spatial - 空间数据结构和算法
special - 特殊数学函数如贝塞尔函数,雅可比函数
stats - 统计学工具包
'''
# print(scipy.dot is np.dot)
| true |
41c293535fa9355195d86b7396d0e62e6f774f8f
|
Python
|
salasgar/Ecosystems
|
/Biotope.py
|
UTF-8
| 14,640 | 3.15625 | 3 |
[] |
no_license
|
from basic_tools import Matrix, is_number
from random import shuffle, choice
from math import sqrt
from basic_tools import is_function
from basic_tools import print_methods_names
class Feature(object): # A float variable
def __init__(self, feature_name, feature_settings, parent_ecosystem):
self.feature_name = feature_name
self.parent_ecosystem = parent_ecosystem
functions_dict = parent_ecosystem.function_maker\
.turn_settings_into_functions(
feature_settings,
caller='#ecosystem'
)
self.current_value = functions_dict['initial value'](
self.parent_ecosystem)
try:
self.calculate_value_after_update = functions_dict[
# we take the function without calling it
'value after updating']
try:
self.update_once_every = functions_dict[
'update once every'](self.parent_ecosystem)
except Exception:
self.update_once_every = 1
self.time_of_next_update = \
self.parent_ecosystem.time + self.update_once_every
except Exception:
pass
def update(self): # or def evolve(self):
# print 'Updating', self.feature_name # ***
if (
hasattr(self, 'time_of_next_update') and
self.parent_ecosystem.time > self.time_of_next_update
):
self.current_value = self.calculate_value_after_update(
self.parent_ecosystem)
self.time_of_next_update += self.update_once_every
def get_value(self):
return self.current_value
def set_value(self, new_value):
self.current_value = new_value
return new_value
def modify_proportionally(self, proportion):
value = self.get_value()
increment = proportion * value
self.set_value(value + increment)
return increment
def modify(self, increment):
value = self.get_value() + increment
self.set_value(value)
return increment
class FeatureMap(object): # A function f(x, y)
def __init__(self, feature_name, feature_settings, parent_ecosystem):
self.feature_name = feature_name
self.parent_ecosystem = parent_ecosystem
functions_dict = parent_ecosystem.function_maker.\
turn_settings_into_functions(
feature_settings,
caller='#ecosystem'
)
(self.size_x, self.size_y) = feature_settings['matrix size']
(size_x, size_y) = (self.size_x, self.size_y)
self.current_value = Matrix(size_x, size_y)
for i in range(size_x):
for j in range(size_y):
self.current_value[i, j] = \
functions_dict['initial value'](
self.parent_ecosystem,
float(i) / size_x,
float(j) / size_y)
try:
self.calculate_value_after_update = functions_dict[
'value after updating'
] # we take the function without calling it
try:
self.update_once_every = functions_dict['update once every'](
self.parent_ecosystem)
except Exception:
self.update_once_every = 1
self.time_of_next_update = (
self.parent_ecosystem.time + self.update_once_every)
except Exception:
pass
def update(self): # or def evolve(self):
# print 'Updating', self.feature_name # ***
if (
hasattr(self, 'time_of_next_update') and
self.parent_ecosystem.time > self.time_of_next_update
):
new_value = Matrix(self.size_x, self.size_y)
for i in range(self.size_x):
for j in range(self.size_y):
new_value[i, j] = \
self.calculate_value_after_update(
self.parent_ecosystem,
float(i) / self.size_x,
float(j) / self.size_y)
self.current_value = new_value
self.time_of_next_update += self.update_once_every
def get_value(self, x, y):
# PRECONDITION: 0 <= x <= 1, 0 <= y <= 1
for n in (x, y, self.size_x, self.size_y):
if not is_number(n):
print n, 'is not a FLOAT!!!' # ***
exit()
return self.current_value[
int(round(x * self.size_x)),
int(round(y * self.size_y))
]
def set_value(self, x, y, new_value):
# PRECONDITION: 0 <= x <= 1, 0 <= y <= 1
self.current_value[
int(round(x * self.size_x)),
int(round(y * self.size_y))
] = new_value
return new_value
def modify_proportionally(self, x, y, proportion):
# PRECONDITION: 0 <= x <= 1, 0 <= y <= 1
value = self.get_value(x, y)
increment = proportion * value
self.set_value(x, y, value + increment)
return increment
def modify(self, x, y, increment):
# PRECONDITION: 0 <= x <= 1, 0 <= y <= 1
value = self.get_value(x, y) + increment
self.set_value(x, y, value)
return increment
class Biotope(object):
class random_free_locations_list(object):
# warning: this is not the __init__ method of Biotope class!
def __init__(self, parent_biotope):
self.parent_biotope = parent_biotope
self.reset()
def reset(self):
size = self.parent_biotope['size']
self.list = [(x, y) for x in range(size[0])
for y in range(size[1])]
shuffle(self.list)
self.last_location_index = len(self.list) - 1
def get_new_free_location(self):
if len(self.list) == 0:
return None
i = (self.last_location_index + 1) % len(self.list)
while (
self.parent_biotope.organisms_matrix[self.list[i]] is not None
and i != self.last_location_index
):
i = (i + 1) % len(self.list)
if self.parent_biotope.organisms_matrix[self.list[i]] is None:
self.last_location_index = i
return self.list[i]
else:
# Error: Full biotope. There're no more free locations
return None
def __init__(self, settings, parent_ecosystem):
self.settings = settings
self.parent_ecosystem = parent_ecosystem
self.organisms_matrix = Matrix(*self.settings['size'])
self.initialize_biotope_features()
self.random_free_locations = self.random_free_locations_list(self)
# The 'distance' between two points A and B is subjective. Depends on
# the topology of the biotope (currently it's a flat torus) and the
# metric we use (euclidean, chess, taxicab,...). So, we define:
try:
self.set_distance(self.settings['distance'])
except Exception:
self.set_distance('euclidean distance')
def __getitem__(self, keys):
return self.settings[keys]
def __setitem__(self, keys, value):
self.settings[keys] = value
def __str__(self):
return str(self.organisms_matrix)
def size_x(self):
return self.settings['size'][0]
def size_y(self):
return self.settings['size'][1]
def print_matrix(self):
for y in range(self.size_y()):
print [
0
if self.organisms_matrix[x, y] is None
else 1 for x in range(self.size_x())
]
def add_feature(self, feature_name, feature_settings):
# print 'add_feature:', feature_name # ***
self.biotope_features[feature_name] = Feature(
feature_name, feature_settings, self.parent_ecosystem)
def add_feature_map(self, feature_name, feature_settings):
# print 'add_feature_map:', feature_name # ***
self.biotope_features[feature_name] = FeatureMap(
feature_name, feature_settings, self.parent_ecosystem)
def initialize_biotope_features(self):
"""
We don't need to initialize features in a particular
order. That's why we don't initialize them the same way as genes or
new operators. Features can refer to each other and can even refer to
themselves, because we built feature operators (such as '#biotope
seasons speed' or 'extract #biotope nutrient A') before initializing
features themselves. We built them out of features' names.
"""
if print_methods_names:
print 'Biotope.py: initialize_biotope_features' # ***
self.biotope_features = {}
if 'biotope features' in self.settings:
for feature_name in self.settings['biotope features']:
if 'matrix size' in self.settings[
'biotope features'][
feature_name
]:
self.add_feature_map(
feature_name,
self.settings['biotope features'][feature_name]
)
else:
self.add_feature(
feature_name,
self.settings['biotope features'][feature_name])
if print_methods_names:
print 'initialize_biotope_features done!!' # ***
def get_organism(self, location):
return self.organisms_matrix[location]
def add_organism(self, organism, location='find location'):
if location == 'find location':
try:
location = organism['location']
except Exception:
location = self.seek_free_location()
if location is not None and self.organisms_matrix[location] is None:
# this way we assure that everything is in its place
organism['location'] = location
self.organisms_matrix[location] = organism
# print "in", location, "there is", organism # ***
return 'success'
else:
return 'fail'
def move_organism(self, old_location, new_location):
if old_location != new_location:
self.organisms_matrix[
new_location] = self.organisms_matrix[old_location]
self.organisms_matrix[old_location] = None
def delete_organism(self, location):
if location:
self.organisms_matrix[location] = None
def seek_free_location(self):
"""
This method return a random free position
(None if not possible)
"""
return self.random_free_locations.get_new_free_location()
def list_of_locations_close_to(
self,
center,
radius,
condition=lambda x: (x is None)
):
(xc, yc) = center
# borders of a square around center (xc, yc):
left = int(round(xc - radius))
# we write + 1 because range(a, b+1) = [a, a+1, a+1, ..., b] = [a, ...,
# b]
right = int(round(xc + radius)) + 1
up = int(round(yc - radius))
# we write + 1 because range(a, b+1) = [a, a+1, a+1, ..., b] = [a, ...,
# b]
down = int(round(yc + radius)) + 1
return [
(x, y)
for x in range(left, right)
for y in range(up, down)
if (
condition(self.organisms_matrix[x, y]) and
self.distance(center, (x, y)) <= radius
)
]
def seek_free_location_close_to(self, center, radius):
"""
This method return a random free position close to a center within
a radius (None if not possible)
"""
list_of_free_locations = self.list_of_locations_close_to(
center,
radius,
lambda x: (x is None)
)
if list_of_free_locations == []:
return None
else:
(x, y) = choice(list_of_free_locations)
return (x % self['size'][0], y % self['size'][1])
def seek_organism_close_to(self, center, radius, condition=None):
def default_condition(organism):
return (organism is not None) and (organism['location'] != center)
if condition is None:
condition = default_condition
list_of_locations = self.list_of_locations_close_to(
center, radius, condition)
if list_of_locations == []:
return None
else:
(x, y) = choice(list_of_locations)
return (x % self['size'][0], y % self['size'][1])
def calculate_distance(self, A, B, distance='euclidean distance'):
"""
Gives the distance from the location A to the location B, taking
into account that coordinates are taken (x % size_x, y % size_y)
and, thus, the location (size_x, size_y) is equivalent to (0, 0),
so the distance between the locations (0, 0) and
(size_x - 1, size_y - 1) is really small
"""
if (
hasattr(A, '__iter__') and
hasattr(B, '__iter__') and
len(A) == 2 and
len(B) == 2
):
size_x, size_y = self['size']
Ax, Ay, Bx, By = A[0] % size_x, A[
1] % size_y, B[0] % size_x, B[1] % size_y
dif_x = min(abs(Bx - Ax), size_x - abs(Bx - Ax))
dif_y = min(abs(By - Ay), size_y - abs(By - Ay))
if distance in {'square', 'chess', 'chess distance'}:
return max(dif_x, dif_y)
elif distance in {'circle', 'euclidean', 'euclidean distance'}:
return sqrt(dif_x**2 + dif_y**2)
elif distance in {
'tilted square',
'taxicab',
'taxist',
'taxist distance',
'taxicab distance'
}:
return dif_x + dif_y
else:
return None
def set_distance(self, distance):
if is_function(distance):
self.distance = distance
elif isinstance(distance, str):
self.distance = lambda A, B: self.calculate_distance(
A, B, distance)
def evolve(self):
for feature in self.biotope_features:
self.biotope_features[feature].update()
| true |
fc6d2cb7b184110bf0a77eff30f005bc022f9268
|
Python
|
rahuljain1310/BillReader
|
/filter.py
|
UTF-8
| 1,041 | 2.890625 | 3 |
[] |
no_license
|
from utilities import saveImage, GetColoredSegmentationMask, isText, getArea
def applyAreaFilter(segPositions, area, threshold = 0.3):
""" Requires a list of pos_coord tuples """
""" Output THose segmentations With Less Area """
segPositions = segPositions[[getArea(pos_coord) < threshold *area for pos_coord in segPositions]]
print("Segments After Eliminating Big Segments: ", len(segPositions))
return segPositions
def applyCoverFilter(segPositions):
length = len(segPositions)
res = list()
for i in range(length):
minX, maxX, minY, maxY = segPositions[i]
for f in segPositions:
minX1, maxX1, minY1, maxY1 = f
if (minX1>=minX and maxX1<=maxX and minY1>=minY and maxY1<=maxY):
res.append(segPositions[i])
break
return res
def filterHlist(H_List):
length = len(H_List)
sumArea = 0
for i in range(length):
sumArea = sumArea + H_List[i]['details']['area']
res = list()
for c in H_List:
area = c['details']['area']
if (area < sumArea/2): res.append(c)
return res
| true |
657f687d15e346ce970ecb3562fd178c901e2a9e
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p02762/s060694594.py
|
UTF-8
| 2,092 | 3.546875 | 4 |
[] |
no_license
|
import sys
from collections import defaultdict
# https://ikatakos.com/pot/programming_algorithm/data_structure/union_find_tree
class UnionFind:
def __init__(self, n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def union(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
# ランクの取得
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
if d1 == d2:
self.table[r1] -= 1
else:
self.table[r1] = r2
def friend_candidate(self):
tbl = self.table
n = len(tbl)
candidates = [0] * n
root = [-1] * n
for i, parent in enumerate(tbl):
if parent >= 0:
root[i] = self._root(parent)
candidates[root[i]] += 1
for i in range(n):
if tbl[i] >= 0:
candidates[i] = candidates[root[i]]
return candidates
def main():
input = sys.stdin.buffer.readline
n, m, k = map(int, input().split())
uf = UnionFind(n)
num_friends = [0] * n
for _ in range(m):
a, b = map(lambda x: int(x) - 1, input().split())
uf.union(a, b)
num_friends[a] += 1
num_friends[b] += 1
num_block = [0] * n
for _ in range(k):
c, d = map(lambda x: int(x) - 1, input().split())
if uf.find(c, d):
num_block[c] += 1
num_block[d] += 1
fc = uf.friend_candidate()
ans = [0] * n
for i in range(n):
ans[i] = fc[i] - num_friends[i] - num_block[i]
print(*ans)
if __name__ == "__main__":
main()
| true |
cfd64fb723f75043d6ecd3c903fd32e02575d44f
|
Python
|
rohanJa/LCM-LeetCodeMaychallenge-
|
/arrayManipulation.py
|
UTF-8
| 792 | 2.875 | 3 |
[] |
no_license
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
list_=[0 for i in range(0,n+2)]
itre=len(queries)
m=-1
for query in queries:
i=query[0]
while(i<=query[1]):
list_[i]=list_[i]+query[2]
if(m<list_[i]):
m=list_[i]
i=i+1
itre=itre-1
return m
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
fptr.write(str(result) + '\n')
fptr.close()
| true |
330fef4d70318b6cb027cac0c6c6b602aa3d5474
|
Python
|
OmranKaddah/Disentangled-Representation-Learning
|
/source_code/models/layers.py
|
UTF-8
| 562 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
import torch
from torch import nn
class Lambda(nn.Module):
def __init__(self, lambda_function):
super(Lambda, self).__init__()
self.lambda_function = lambda_function
def forward(self, *args):
if len(args) == 1:
return self.lambda_function(args[0])
else:
return self.lambda_function(args)
class Reshape(nn.Module):
def __init__(self, shape):
super(Reshape, self).__init__()
self.shape = shape
def forward(self, inp: torch.Tensor):
return inp.view(self.shape)
| true |
559b10b739a63006f6eac211e5142961273a217c
|
Python
|
iamabdil/python_competition
|
/Q10.py
|
UTF-8
| 1,726 | 4.46875 | 4 |
[] |
no_license
|
'''
Q10: Create a function called summary that gets a list of filenames as a parameter. The input files should contain a floating point number on each line of the file. Make your function read these numbers and then return a triple containing the sum, average, and standard deviation of these numbers for the file. https://en.wikipedia.org/wiki/Standard_deviation#Sample_standard_deviation_of_metabolic_rate_of_northern_fulmars
The main function should call the function summary for each filename in the list sys.argv[1:] of command line parameters. (Skip sys.argv[0] since it contains the name of the current program.)
Summary Function:
Args:
filename: files containing floating point numbers
Returns:
total_sum, average, stddev
'''
import sys
import numpy as np
def summary(filename):
# read the file
f = open(filename, "r")
# splitting the file content by lines
str_numbers = f.read().splitlines()
numbers = []
# looping through numbers and appending them to numbers list
for num in str_numbers:
try:
numbers.append(float(num))
except:
pass
# calculations
total_sum = sum(numbers)
average = total_sum/len(numbers)
stddev = np.std(numbers)
return total_sum, average, stddev
def main():
filenames = sys.argv[1:]
print(filenames)
for name in filenames:
total_sum, average, stddev = summary(name)
print(f"File {name} Sum: {total_sum} Average: {average} Stddev: {stddev}")
if __name__ == "__main__":
main()
'''
Joke of the Question:
Two random variables were talking in a bar. They thought they were being discrete, but I heard their chatter continuously.
'''
| true |
991a1d998a429a1ca676a997035931375409e5c0
|
Python
|
isaiahh812/Lab7
|
/ED.py
|
UTF-8
| 920 | 3.390625 | 3 |
[] |
no_license
|
#Isaiah Hernandez
#80591211
#date modified 12/14/18
#cs2302
S1 = "fool"
S2 = "fuel"
s1List = list(S1)#seperates both strings into list
s2List = list(S2)#seperates both strings into list
Table = [[0 for i in range(len(s1List)+1)] for j in range(len(s2List)+1)]
for i in range(len(s1List)+1):#set the first row
Table[0][i] = i
for i in range(len(s2List)+1):#sets the first coloumn
Table[i][0] = i
for i in range(len(s2List)):#
for j in range(len(s1List)):#checks if the characters are the same
if s1List[j] == s2List[i]:#if so uses the diagonal vaule
Table[i+1][j+1] = Table[i][j]
else():
Table[i+1][j+1] = min(Table[i][j], Table[i][j], Table[i+1][j])+1#checks for the lowest number
changes = Table[len(s1List)][len(s2List)]
print(changes)
file = open("results_for_lab_7.txt","w")
file.write("The number of changes for the the two words is " + str(changes))
| true |
6e0026018f816f4b1c29f0bdb7e145f919ce4e6c
|
Python
|
Insanityandme/python-the-hard-way
|
/pthway/recap_ex22.py
|
UTF-8
| 1,747 | 3.40625 | 3 |
[] |
no_license
|
from sys import argv
import datetime
script, in_file, out_file = argv
print "calling on: %s, in_file: %s, out_file: %s)" % (script, in_file, out_file)
f = open(in_file, 'w+')
f2 = open(out_file, 'w+')
write_to_file = f.write(raw_input("Write something in here please: "))
f.seek(0)
read_file = f.read()
print "%s: %s" % (in_file, read_file)
f2.write(read_file)
f2.seek(0)
read_file_2 = f2.read()
print "%s: %s" % (out_file, read_file)
d = datetime.date.today()
print str(d)
print repr(d)
print 5 > 2
print 5 < -2
print 5 >= 5
print 5 <= -2
string = "This is a string"
addition = 2+2
subtraction = 2-2
divison = 2/2
multiply = 2*2
modulus = 16 % 4
# print "addition: 2+2 = %d\n subtraction: 2/2 = %d\n divison: 2/2 = %d\n multiplication: 2*2 = %d\n modolus: 16 % 4 = %d" % (addition, subtraction, divison, multiply, modulus)
print "addition: 2+2 = %d\nsubtraction: 2-2 = %d\ndivsion: 2/2 = %d\nmultiplication: 2*2 = %d\nmodulus: 16 %% 4 = %d" % (addition, subtraction, divison, multiply, modulus)
print "16 % 4"
# print "\n, \t, \f, \a, \ooo, \v, \uxxxx, \Uxxxxxxxx, \xhh, \r, \\, \', \", \b"
def add(arg1, arg2):
print "ADDING: %d + %d" % (arg1, arg2)
return arg1 + arg2
def subtract(arg1, arg2):
print "SUBTRACTING: %d - %d" % (arg1, arg2)
return arg1 - arg2
def multiply(arg1, arg2):
print "MULTIPLYING: %d * %d" % (arg1, arg2)
return arg1 * arg2
def division(arg1, arg2):
print "DIVIDING: %d / %d" % (arg1, arg2)
return arg1 / arg2
age = add(30, 5)
weight = subtract(78, 4)
height = multiply(90, 2)
poop_size = division(100, 2)
formatter = "%r\n%r\n%r\n%r"
print formatter % (age, weight, height, poop_size)
puzzle = add(multiply(age, weight), division(height, poop_size))
print puzzle
| true |
74a46f3a5c164302e802ff9206ed2a5ed47ac123
|
Python
|
Villafly/Principled-approach-to-the-selection-of-the-embedding-dimension-of-networks
|
/embedding_dist.py
|
UTF-8
| 3,586 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
import numpy as np
import networkx as nx
import node2vec
from gensim.models import Word2Vec
from scipy.spatial.distance import cdist
from scipy import optimize
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def read_graph(args):
'''
Reads the input network in networkx.
'''
if args.weighted:
G = nx.read_edgelist(args.input, nodetype=int, data=(('weight',float),), create_using=nx.DiGraph())
else:
G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph())
for edge in G.edges():
G[edge[0]][edge[1]]['weight'] = 1
#G = nx.read_edgelist(file_name, nodetype=int)
if not args.directed:
G = G.to_undirected()
return G
def fitting_func(dims,s,a,L):
return s/np.power(dims,a) + L
def identify_optimal_dim(embedding_dims, loss):
'''
Identify the optimal dimension range and compute the curve fitting parameter for graph.
'''
(s,a,l),cov = optimize.curve_fit(fitting_func, embedding_dims,loss)
fit_values = (fitting_func(np.array(embedding_dims),s,a,l))
MSE = ((np.array(loss)-np.array(fit_values))**2).mean()
opt = np.power((s/0.05),1/a)
print 'the optimal dimension at 0.05 accuracy level is {}'.format(int(math.ceil(opt)))
print 'the MSE of curve fitting is {}'.format(MSE)
def cal_cosine_matrices(G,walks,args):
'''
Compute the cosine distance between every node pair over different embedding dimensions.
'''
norm_loss = []
walks = [map(str, walk) for walk in walks]
node_num = len(G.nodes())
if node_num < args.end_dim:
args.end_dim = node_num
embedding_dims = range(args.start_dim,args.end_dim,args.step)
if node_num < 500:
embedding_dims.insert(0,node_num)
print 'graph size smaller than the default end dimension, thus has been automatically set to {}'.format(node_num)
else:
embedding_dims.insert(0,500)
#cosine_matrices = np.zeros((len(embedding_dims),node_num,node_num))
for _index, dim in enumerate(embedding_dims):
#print (dim)
model = Word2Vec(walks, size=dim,window=args.window_size, min_count=0, sg=1, workers=args.workers, iter=args.iter)
emb_matrix = np.zeros((node_num,dim))
for _cnt,node in enumerate(G.nodes()):
emb_matrix[_cnt,:] = model[str(node)]
emb_matrix = emb_matrix - np.mean(emb_matrix,axis=0)
cosine_matrix = 1 - cdist(emb_matrix,emb_matrix,'cosine')
if _index == 0:
benchmark_array = np.array(upper_tri_masking(cosine_matrix))
#np.savez_compressed('./pic/conect_data/npz/{}'.format(str.split(args.input,'/')[6]),benchmark_array)
else:
dim_array = np.array(upper_tri_masking(cosine_matrix))
loss = np.linalg.norm((dim_array-benchmark_array),ord=1)
norm_loss.append(loss/len(dim_array))
return embedding_dims[1:],norm_loss
def upper_tri_masking(A):
'''
Masking the upper triangular matrix.
'''
m = A.shape[0]
r = np.arange(m)
mask = r[:,None] < r
return A[mask]
def cal_embedding_distance(args):
'''
The overall random walk, graph embedding and cosine distance calculation process.
'''
nx_G = read_graph(args)
G = node2vec.Graph(nx_G, args.directed, args.p, args.q)
G.preprocess_transition_probs()
walks = G.simulate_walks(args.num_walks, args.length)
dims, loss = cal_cosine_matrices(nx_G,walks,args)
plt.plot(dims,loss)
plt.savefig('./a.png')
identify_optimal_dim(dims, loss)
#return cosine_matrices
| true |
0735654cd3c50a7ee212fd06b15cf87a8856ab0b
|
Python
|
351116682/Test
|
/21.py
|
UTF-8
| 737 | 4.1875 | 4 |
[] |
no_license
|
coding=utf-8
'''
使用lambda来创建匿名函数。关键在于lambda表达式紧跟参数,以分号分隔后的表达式只能为算术逻辑表达式,不能有判断等语句
'''
MAX = lambda x,y: (x > y) * x + (x < y) * y
MIN = lambda x,y: (x < y) * x + (x > y) * y
SUM = lambda x,y: x + y
SUB = lambda x,y: (x > y) * (x) + (x < y) * (y - x)
MUT = lambda x,y:(x != 0) * (x * y) or 0
DIV = lambda x,y: (x * y != 0) * (((float)(x) / (float)(y))) or "除数不能为0!"
if __name__ == "__main__":
x = 10
y = 100
print "MAX:",MAX(x,y)
print "MIN:",MIN(x,y)
print "SUM:",SUM(x,y)
print "SUB:",SUB(x,y)
print "SUB:",SUB(y,x)
print "MUT:",MUT(x,y)
print "DIV:",DIV(x,y)
print "DIV:",DIV(y,x)
| true |
5fec9f285b19bc194a3928aea4608a4dd1f4cf0e
|
Python
|
Vipning/latest-chinese-ner-model
|
/bilstm-crf/dataset_loader.py
|
UTF-8
| 2,241 | 2.9375 | 3 |
[] |
no_license
|
import math
import random
class BatchManager(object):
def __init__(self,data,batch_size,vocab,label2id,shuffle=True):
self.data = data
self.shuffle = shuffle
self.batch_size=batch_size
self.vocab = vocab
self.label2id = label2id
self.reset()
def reset(self):
data=self.preprocess(self.data)
self.batch_data = self.shuffle_and_pad(data,self.batch_size,self.shuffle)
self.len_data = len(self.batch_data)
def preprocess(self, data):
""" Preprocess the data and convert to ids. """
processed = []
for d in data:
text_a = d['context']
tokens = [self.vocab.to_index(w) for w in text_a.split(" ")]
x_len = len(tokens)
text_tag = d['tag']
tag_ids = [self.label2id[tag] for tag in text_tag.split(" ")]
processed.append((tokens, tag_ids, x_len, text_a, text_tag))
return processed
def shuffle_and_pad(self, data, batch_size,shuffle=True):
num_batch = int(math.ceil(len(data) /batch_size))
shuffle_data=data
if shuffle:
random.shuffle(shuffle_data)
batch_data = list()
for i in range(num_batch):
batch_data.append(self.pad_data(shuffle_data[i*batch_size:(i+1)*batch_size]))
return batch_data
@staticmethod
def pad_data(data):
#tokens, tag_ids, x_len, text_a, text_tag
input_ids = []
labels_ids = []
input_mask = []
input_lens = []
max_length = max([sentence[2] for sentence in data])
for line in data:
tokens,tag_ids,x_len,_,_ = line
padding = [0] * (max_length - len(tokens))
input_ids.append(tokens + padding)
labels_ids.append(tag_ids + padding)
input_lens.append(x_len)
mask_ = [0] * max_length
mask_[:len(tokens)] = [1]*len(tokens)
input_mask.append(mask_)
return [input_ids,input_mask,labels_ids,input_lens]
def iter_batch(self, shuffle=True):
if shuffle:
random.shuffle(self.batch_data)#batch间打乱
for idx in range(self.len_data):
yield self.batch_data[idx]
| true |
3aa6866737f775030cf94d8ba9b135ad46e04fb7
|
Python
|
Man1exter/otherGames.py
|
/gam.py
|
UTF-8
| 2,465 | 3.21875 | 3 |
[] |
no_license
|
import instaloader
import sys
import pygame
import os
from sgame import seek
from sec import geckon
import io
import pyttsx3
import phonenumbers
from phonenumbers import geocoder, carrier, timezone
def panel():
print("[1] => Info About Application <= ")
print("[2] => SnakeGame 1s game <= ")
print("[3] => SecretGame 2s game <= ")
print("[4] => Info About files/directories <= ")
print("[5] => Download Image from INSTAGRAM <= ")
print("[6] => Voice Channel (yours text) <= ")
print("[7] => PASSSSSSSSSSSSSSSSSSSSSS <= ")
print("[8] => info about phonenumbers... <= ")
print(" ")
def imge():
print("it is good if you write lowercase => username <=")
iginit = instaloader.Instaloader()
who = input("USERNAME FROM INSTAGRAM ===> ")
iginit.download_profile(who, profile_pic_only = True)
print(" ")
print("everything is ready....")
def infoapp():
pass
def ss11():
print("My first game with pygame...")
seek()
def ss12():
print("SECRET GAME ABOUT RULONICKA BANDICKA..")
geckon()
def voiceBot():
print(" ")
print("Bot say your text..")
engine = pyttsx3.init()
text = input("Enter Your Text..... =====> ")
engine.say(text)
engine.runAndWait()
print(" ")
def number_phone_function():
print(" ")
print("ATTENTION DONT FORGET => +48... <= OR SOMETHING LIKE THAT...")
y = input("write phonenumber => ")
x = phonenumbers.parse(y, None)
print(x)
x2 = phonenumbers.is_possible_number(x)
print("is possible number? =>",x2)
x3 = phonenumbers.is_valid_number(x)
print("is valid number? =>",x3)
#country..
print("from where is use the number? =>",geocoder.description_for_number(x, 'pl'))
#services..
print("services of phonenumber? =>",carrier.name_for_number(x, 'pl'))
#timezone..
print("timezone =>",timezone.time_zones_for_number(x))
print(" ")
def main():
print("WELCOME ON PANEL ABOUT GAME IN WINDOW + other useful function (programs)")
print(" ")
panel()
way = int(input("Your choice from menu ==> "))
if way == 1:
infoapp()
elif way == 2:
ss11()
elif way == 3:
ss12
elif way == 4:
pass
elif way == 5:
imge()
elif way == 6:
voiceBot()
elif way == 7:
print(" ")
pass
print(" ")
elif way == 8:
number_phone_function()
print(" ")
main()
| true |
01c4ca868ef7095e7facf81b91d62d8d163d57c6
|
Python
|
jnibali/software-extra-credit
|
/unit_test.py
|
UTF-8
| 371 | 2.6875 | 3 |
[] |
no_license
|
import unittest
import sentence_reverse
class testCaseAdd(unittest.TestCase):
def test_volume(self):
self.assertEqual(sentence_reverse.reverse("My name is V Tadimeti"),"Tadimeti V is name My")
#tests for additon, then subtraction, then multiply, and then division
#select right options in terminal when testing
if __name__ == '__main__':
unittest.main()
| true |
bf9a8a5ac094f6359ffa7ed700af263eeba56a78
|
Python
|
hmasha/MTF_Alabi
|
/MTF_predict.py
|
UTF-8
| 2,470 | 2.796875 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 16:08:32 2019
https://stackoverflow.com/questions/18869550/python-pil-cut-off-my-16-bit-grayscale-image-at-8-bit
https://stackoverflow.com/questions/8832714/how-to-use-multiple-wildcards-in-python-file-dialog
https://www.datacamp.com/community/tutorials/convolutional-neural-networks-python
@author: hillary.masha
"""
# Helper libraries
from keras.models import load_model
from keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
import os
from keras.models import Model
import cv2
import wx
#fileselector for test image
def get_path( ):
app = wx.App(None)
style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
dialog = wx.FileDialog(None, 'Select Test Image(.tif,.png,.jpg)', wildcard="pictures (*.jpeg,*.png,*.tif,*.jpg)|*.jpeg;*.png;*.tif;*.jpg", style=style)
if dialog.ShowModal() == wx.ID_OK:
path = dialog.GetPath()
picfile = dialog.GetFilename()
for item in wx.GetTopLevelWindows():
if isinstance(item, wx.Dialog):
item.Destroy()
item.Close()
else:
path = None
dialog.Destroy()
return path, picfile
filename , imgname = get_path()
y_test = []
test_data = []
IMG_Width = 30
IMG_Height = 270
#resize and store test data in array
try:
image = cv2.imread (filename, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (IMG_Width, IMG_Height))
test_data.append (image)
except Exception as e:
print(str(e))
test_data = np.array(test_data)
test_data = test_data.astype('float32') / 255
print(test_data)
test_X = test_data.reshape(-1,IMG_Height,IMG_Width,1)
# load model
model = load_model("model.h5")
print("Loaded model from disk")
#model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
predicted_classes = model.predict(test_X)
predicted_classes = np.argmax(np.round(predicted_classes),axis=1)
print("\nPredicted Class")
print(predicted_classes)
#display Result
if predicted_classes[0] == 1:
print("PASS")
arr = np.asarray(test_X.reshape(IMG_Height,IMG_Width))
plt.imshow(arr, cmap='gray')
plt.title("Prediction for {} : PASS".format(imgname))
plt.show()
elif predicted_classes[0] == 0:
print("FAIL")
arr = np.asarray(test_X.reshape(IMG_Height,IMG_Width))
plt.imshow(arr, cmap='gray')
plt.title("Prediction for {} : FAIL".format(imgname))
plt.show()
| true |
2bbcd46bb9404811e8d121c33f63bf9419e873ab
|
Python
|
quoppy/sbscraper
|
/sbscraper/executable.py
|
UTF-8
| 2,694 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Console script."""
import logging
import os
import sys
import sbscraper
import sbscraper.scraper
# Environment variables.
PREFIX = 'SBSCRAPER'
EXTRACTOR_CATEGORIES = 'EXTRACTOR_CATEGORIES'
EXTRACTOR_URL = 'EXTRACTOR_URL'
LOADER_URI = 'LOADER_URI'
SCRAPER_LABEL = 'SCRAPER_LABEL'
LOG_FORMAT = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s'
LOG_DATE_FORMAT = '%y%m%d %H:%M:%S'
def get_setting(key, default=None):
"""Gets the value of a setting from the environment.
Arguments:
key (str): Name of setting.
Returns:
str: Value of setting.
Raises:
KeyError: Setting does not exist in the environment.
"""
key = "%s_%s" % (PREFIX, key)
return os.environ[key]
def configure_stream_logging(logger):
"""Configures logging to output to stderr.
Arguments:
logger (:class:`logging.Logger`): Logger to configure.
"""
handler = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter(LOG_FORMAT, LOG_DATE_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
def main():
"""Runs the Scraper based on the environment.
Returns:
int: Exit status.
"""
configure_stream_logging(logging.getLogger(sbscraper.__name__))
logger = logging.getLogger(__name__)
try:
label = get_setting(SCRAPER_LABEL)
except KeyError:
logger.error('no scraper label set')
return 1
try:
(scraper, extractor, transformer,
loader) = sbscraper.scraper.LABELS[label]
except KeyError:
logger.error("invalid label: %s", label)
return 1
try:
extractor_url = get_setting(EXTRACTOR_URL)
except KeyError:
logger.error('no extractor URL set')
return 1
try:
extractor_categories = get_setting(EXTRACTOR_CATEGORIES)
except KeyError:
logger.error('no extractor categories set')
return 1
categories = [category.strip()
for category in extractor_categories.split(',')]
if not categories:
logger.error("no extractor categories found: %s", categories)
return 1
try:
loader_uri = get_setting(LOADER_URI)
except KeyError:
logger.error('no loader URI set')
return 1
extractor = extractor(extractor_url, categories)
transformer = transformer()
loader = loader(loader_uri)
scraper = scraper(extractor, transformer, loader)
logger.info('Starting scraping process')
scraper.run()
logger.info('Done scraping')
if __name__ == '__main__':
sys.exit(main())
| true |
87825ca5593e1ca4370a38ae4825c31f528dc005
|
Python
|
stefansilverio/holbertonschool-higher_level_programming
|
/0x0F-python-object_relational_mapping/3-my_safe_filter_states.py
|
UTF-8
| 511 | 2.828125 | 3 |
[] |
no_license
|
#!/usr/bin/python3
"""display matching arguments"""
import MySQLdb
import sqlalchemy
import sys
if __name__ == '__main__':
db = MySQLdb.connect(host="localhost", user=sys.argv[1],
passwd=sys.argv[2],
db=sys.argv[3], port=3306)
c = db.cursor()
c.execute("SELECT * FROM states WHERE `name` = %s ORDER BY states.id ASC",
(sys.argv[4],))
states = c.fetchall()
for state in states:
print(state)
c.close()
db.close()
| true |
0ba416b037876b940093ceb0f49b5c096f2dd806
|
Python
|
kh7160/algorithm
|
/SWExpert/1940.py
|
UTF-8
| 542 | 3.296875 | 3 |
[] |
no_license
|
# import sys
# sys.stdin = open("input.txt", "r")
t = int(input())
for case in range(t):
n = int(input())
speed = 0
length = 0
for i in range(n):
line = input().split(' ')
if line[0] == '0':
length += speed
elif line[0] == '1':
speed += int(line[1])
length += speed
else:
if speed - int(line[1]) < 0:
speed = 0
else:
speed -= int(line[1])
length += speed
print(f"#{case+1} {length}")
| true |
cc1f95114d60e7cb4931b996a3c16da68fa164ce
|
Python
|
zoulala/exercise
|
/nlps/Alg_VSM.py
|
UTF-8
| 2,999 | 3.109375 | 3 |
[] |
no_license
|
#!/user/bin/env python
#-*- coding: utf-8 -*-
'''
Created on 2017年3月23日
@author: zoulingwei
vsm向量空间模型实现,计算两个文本的相似度(通过构建文档的字频向量,计算两个文档字频向量的相似度)
'''
# first: cipintongji
import math
import ast
from collections import Counter
wordsCount=0#variable for wordsfrequency
def CountKeyByWen(fileName1):#对文本进行所有词,词数统计(只对英文文章有效)
global wordsCount
f1=open(fileName1,'r')
f1=open(fileName2,'r')
table={}
for lines in f1:
for line in lines.split(' '):
if line!=' ' and table.has_key(line):
table[line]+=1
wordsCount+=1
elif line!=' ':
wordsCount+=1
table[line]=1
dic = sorted(table.iteritems(),key= lambda asd:asd[1], reverse=True)
# print len(dic) code for testing
return dic
# seconde:create vocabulary
def CreateVocabulary(dic1=None, dic2=None):#创建字表
vocabulary=[]
for dicEle in dic1:
if dicEle[0] not in vocabulary:
vocabulary.append(dicEle[0])
for dicEle in dic2:
if dicEle[0] not in vocabulary:
vocabulary.append(dicEle[0])
# print len(vocabulary) code for testing
return vocabulary
# third:compute TF-IDF output: a vector
# In this code we just use TF for computing similarity
def ComputeVector(dic1=None,vocabulary=None):#统计字频,生成字频向量
# 3.1compute cipin global wordscount wordsCount
# 3.2create vector
dicVector = {}
for elem in vocabulary:
dicVector[elem]=0
# dicVector = sorted(dicVector.iteritems(),key= lambda asd:asd[1], reverse=True)
dicTemp1,dicTemp2=Counter(dicVector), Counter(dic1)
dicTemp=dict(dicTemp1+dicTemp2)
# dicTemp = sorted(dicTemp.iteritems(),key= lambda asd:asd[1], reverse=True)
return dicTemp
# fourth: compute TF-IDF
def ComputeSimlirity(dic1Vector=None,dic2Vector=None):#通过字频向量,计算两个文本的相似度
x=0.0 #fenzi
#fenmu
y1=0.0
y2=0.0
for k in dic1Vector:# because of the element of dic1 and dic2 are the same
temp1=(float)(float(dic1Vector[k])/float(wordsCount))
temp2=(float)(float(dic2Vector[k])/float(wordsCount))
x=x+ (temp1*temp2)
y1+=pow(temp1,2)
y2+=pow(temp2,2)
return x/math.sqrt(y1*y2)
if __name__=='__main__':
fileName1='C:\\Users\\zoulingwei\\Desktop\\testr.txt';
fileName2='C:\\Users\\zoulingwei\\Desktop\\testw.txt';
dic1 = CountKeyByWen(fileName1)
dic2 = CountKeyByWen(fileName2)
vocabulary = CreateVocabulary(dic1, dic2)
dic1Vector = ComputeVector(dic1, vocabulary)
dic2Vector = ComputeVector(dic2, vocabulary)
for elem in dic1Vector:
print "<"+elem[0],',',str(elem[1])+">"
sim=ComputeSimlirity(dic1Vector,dic2Vector)
print sim
| true |
ed9a10ee0974e87b2256f08f1855acce19e5f7c7
|
Python
|
janhapis/Hangaroo
|
/Hangaroo_HAPIS.py
|
UTF-8
| 3,332 | 3.84375 | 4 |
[] |
no_license
|
import random
import string
import time
words = ['apple', 'orange', 'mango', 'cherry']
secretWord = random.choice(words)
lettersGuessed = []
def isWordGuessed(secretWord, lettersGuessed):
update = 0
for i, character in enumerate(secretWord):
if character in lettersGuessed:
update += 1
if update == len(secretWord):
return True
else:
return False
def getGuessedWord(secretWord, lettersGuessed):
update = 0
underScore = ['_'] * len(secretWord)
for i, character in enumerate(secretWord):
if character in lettersGuessed:
update += 1
underScore.insert(update-1,character)
underScore.pop(update)
if update == len(secretWord):
return ''.join(str(w) for w in underScore)
else:
update += 1
underScore.insert(update-1,'_')
underScore.pop(update)
if update == len(secretWord):
return ''.join(str(w) for w in underScore)
def getAvailableLetters(lettersGuessed):
availableLetters = list(string.ascii_lowercase)
availableLetters2 = availableLetters[:]
def removeLetters(L, l):
LetterStart = L[:]
for w in L:
if w in LetterStart:
l.remove(w)
return ''.join(str(w) for w in l)
return removeLetters(lettersGuessed, availableLetters2)
def Hangaroo(secretWord):
begin = (len(secretWord))
guess = str
mistakesMade = 4
wordGuessed = False
print ('Welcome to Hanagaroo!')
while True:
n = input("What is your Name? ").strip()
if n == '':
print("Invalid Input")
else: break
print("Hello, " + n, "let's play Hangaroo!!!")
time.sleep(1)
print ('There are ', begin, ' letters you will need to guess.')
time.sleep(0.5)
print("Start guessing...")
while mistakesMade > 0 and mistakesMade <= 8 and wordGuessed is False:
if secretWord == getGuessedWord(secretWord, lettersGuessed):
wordGuessed = True
break
print (('You have ') + str(mistakesMade) + (' more guesses.'))
print (('Letters left: ') + getAvailableLetters(lettersGuessed))
guess = input('Guess a letter: \n').lower()
if guess in secretWord:
if guess in lettersGuessed:
print (("You've already guessed the letter!!! Mr. Kangaroo is mad ") + getGuessedWord(secretWord, lettersGuessed))
else:
lettersGuessed.append(guess)
print (("You've guessed a letter!!! That's a relief ") + getGuessedWord(secretWord, lettersGuessed))
else:
if guess in lettersGuessed:
print (("You've already guessed the letter!!! Mr. Kangaroo is mad ") + getGuessedWord(secretWord, lettersGuessed))
else:
lettersGuessed.append(guess)
mistakesMade -= 1
print (('Wrong letter!!! Poor Mr. Kangaroo ') + getGuessedWord(secretWord, lettersGuessed))
if wordGuessed == True:
print('CONGRATULATIONS, you won!')
elif mistakesMade == 0:
print ('GAME OVER!!! The secret word was: ' + secretWord)
Hangaroo(secretWord)
| true |
ecc204ba8bef8c519897bd8250df92ace30f3672
|
Python
|
ninjanoodles/python_scripts
|
/cust-packages/diff.py
|
UTF-8
| 498 | 2.65625 | 3 |
[] |
no_license
|
def diff_func(set1, set2, lines2, lines1):
file2_added = set2 - set1
file2_removed = set1 - set2
results = []
results.append('Lines added to')
count = 1
for line in lines2:
if line in file2_added:
text = str(count) + ': ' + line
results.append(text)
count += 1
results.append('Lines removed from')
count = 1
for line in lines1:
if line in file2_removed:
text = str(count) + ': ' + line
results.append(text)
count += 1
return results
| true |
1c1dd2649a5ca00680d8fde69e322886bb074a50
|
Python
|
chris09/Python-tut
|
/Master_Python/02-basic/loops.py
|
UTF-8
| 224 | 3.8125 | 4 |
[] |
no_license
|
name = input("What's your name? ")
for i in name:
print(name, i)
x = 0
while True:
print(x)
x += 1
if x == 15:
break
my_list = ['lions', 'tigers', 'bears', 'ohmy']
for i in my_list:
print(i)
| true |
675816aae197d4a4b058ccbd18a827f956e1c4f1
|
Python
|
Ananda9470/programming_practise
|
/BST/findClosestValueInBst.py
|
UTF-8
| 1,438 | 3.890625 | 4 |
[] |
no_license
|
from BST import BST
# O(n) | O(1)
# Θ(log(n)) | O(1)
def findClosestValueInBst1(tree, target):
closest = float("inf")
while True:
if abs(tree.value - target) < abs(closest - target):
closest = tree.value
if tree.value > target:
if tree.left is not None:
tree = tree.left
else:
return closest
elif tree.value < target:
if tree.right is not None:
tree = tree.right
else:
return closest
else:
return tree.value
# O(n) | O(n)
# Θ(log(n)) | O(log(n)
def findClosestValueInBst2(tree, target):
def findClosestValueInBstRecussor(tree, target, smallest):
if tree is None:
return smallest
if abs(tree.value - target) < abs(smallest - target):
smallest = tree.value
if tree.value > target:
tree = tree.left
elif tree.value < target:
tree = tree.right
else:
return smallest
return findClosestValueInBstRecussor(
tree,
target,
smallest
)
return findClosestValueInBstRecussor(tree, target, float("inf"))
if __name__ == "__main__":
bst = BST(100)
bst.insert(5)
bst.insert(6)
bst.insert(105)
bst.insert(103)
bst.insert(1)
ans = findClosestValueInBst2(bst, 101)
print(ans)
| true |
39106a397121e9b3b6772a4945ee4cabf99b712a
|
Python
|
GeorgeZ1917/Python
|
/Algorithms.py
|
UTF-8
| 8,562 | 3.03125 | 3 |
[] |
no_license
|
#Algorithms.py
#Basic sorting algorithms
from random import randint
from copy import copy
from math import inf
length = 10 ** 1
bubbleSort = [ randint ( 0, length ) for data in range ( 0, length ) ]
insertionSort = bubbleSort.copy()
selectionSort = bubbleSort.copy()
countingSort = bubbleSort.copy()
heapSort = bubbleSort.copy()
mergeSort = bubbleSort.copy()
quickSort = bubbleSort.copy()
countingSortNew = [ 0 ] * length
countingSortAuxiliary = [ 0 ] * ( max ( countingSort ) + 1 )
def heapify ( i, n, A ) :
'Heapify algorithm'
left = 2 * i + 1
right = 2 * i + 2
if left < n and A [ left ] > A [ i ] :
max = left
else :
max = i
if right < n and A [ right ] > A [ max ] :
max = right
if max != i :
A [ max ], A [ i ] = A [ i ], A [ max ]
heapify ( max, n, A )
def heapSortFun ( A ) :
'HeapSort algorithm'
n = len ( A )
for i in range ( n // 2 - 1, - 1, - 1 ) :
heapify ( i, n, A )
for i in range ( n - 1, - 1, - 1 ) :
A [ 0 ], A [ i ] = A [ i ], A [ 0 ]
heapify ( 0, i, A )
#print ( "\n\nHeapSort algorithm:" )
#print ( A )
def mergeSortAlg ( A ) :
mergeSortFun ( 0, length - 1, A )
print ( "\n\nMergeSort algorithm:" )
#print ( A )
def mergeSortFun ( p, r, A ) :
if p < r :
q = ( p + r ) // 2
mergeSortFun ( p, q, A )
mergeSortFun ( q + 1, r, A )
merge ( p, q, r, A )
def merge ( p, q, r, A ) :
n1 = q - p + 1
n2 = r - q
L = [ 0 for i in range ( 0, n1 + 1 ) ]
R = [ 0 for i in range ( 0, n2 + 1 ) ]
for i in range ( 0, n1 ) :
L [ i ] = A [ p + i ]
for j in range ( 0, n2 ) :
R [ j ] = A [ q + j + 1 ]
L [ n1 ] = inf
R [ n2 ] = inf
i = 0
j = 0
for k in range ( p, r + 1 ) :
if L [ i ] <= R [ j ] :
A [ k ] = L [ i ]
i += 1
else :
A [ k ] = R [ j ]
j += 1
def bubbleSortFun ( length, A ) :
'BubbleSort algorithm'
for i in range ( length, - 1, - 1 ) :
for j in range ( 0, i - 1 ) :
if A [ j ] > A [ j + 1 ] :
A [ j ], A [ j + 1 ] = A [ j + 1 ], A [ j ]
print ( "BubbleSort algorithm:" )
print ( A )
def insertionSortFun ( length, A ) :
'InsertionSort algorithm'
for i in range ( 1, length ) :
j = i
while j > 0 and ( A [ j ] < A [ j - 1 ] ) :
A [ j ], A [ j - 1 ] = A [ j - 1 ], A [ j ]
j -= 1
print ( "\n\nInsertionSort algorithm:" )
print ( A )
def selectionSortFun ( length, A ) :
'selectionSort algorithm'
for i in range ( 0, length - 1 ) :
min = i
for j in range ( i + 1, length ) :
if A [ j ] < A [ min ] :
min = j
A [ i ], A [ min ] = A [ min ], A [ i ]
print ( "\n\nselectionSort algorithm:" )
print ( A )
def countingSortFun ( originalList = [], outputList = [], auxList = [] ) :
'countingSort algorithm'
for j in range ( 0, length ) :
auxList [ originalList [ j ] ] += 1
for i in range ( 1, ( max ( originalList ) + 1 ) ) :
auxList [ i ] += auxList [ i - 1 ]
for j in range ( length - 1 , - 1, - 1 ) :
outputList [ auxList [ originalList [ j ] ] - 1 ] = originalList [ j ]
auxList [ originalList [ j ] ] -= 1
del originalList
del auxList
print ( "\n\nCountingSort algorithm:" )
print ( outputList )
def quickSortAlg ( A ) :
quickSortFun ( A, 0, len ( A ) - 1 )
print ( "\n\nquickSort algorithm:" )
#print ( A )
def quickSortFun ( A, l, h ) :
if h > l :
p = partition ( A, l, h )
quickSortFun ( A, l, p - 1 )
quickSortFun ( A, p + 1, h )
def partition ( A, l, h ) :
p = h
firstHigh = l
for i in range ( l, h ) :
if A [ i ] < A [ p ] :
A [ i ], A [ firstHigh ] = A [ firstHigh ], A [ i ]
firstHigh += 1
A [ p ], A [ firstHigh ] = A [ firstHigh ], A [ p ]
return firstHigh
def sum1 ( A, B, x ) :
heapSortFun ( A )
heapSortFun ( B )
C = [ 0 ] * len ( A )
j = 0
k = 0
l = 0
for i in range ( len ( A ) - 1, - 1, - 1 ) :
C [ j ] = x - A [ i ]
j = j + 1
while k <= ( len ( A ) - 1 ) and l <= ( len ( A ) - 1 ) :
while B [ l ] > C [ k ] :
if k < len ( A ) - 1 :
k = k + 1
else :
break
if ( B [ l ] == C [ k ] ) :
return True
l = l + 1
return False
def sum2 ( A, x ) :
heapSortFun ( A )
y = 0
temp = 0
for i in range ( 0, len ( A ) - 1 ) :
y = x - A [ i ]
temp = binarySearch ( A, y, 0, len ( A ) - 1 )
if temp != - 1 and temp != i :
return True
return False
def binarySearch ( A, key, low, high ) :
if low > high :
return ( - 1 )
middle = ( low + high ) // 2
if A [ middle ] is key :
return middle
if A [ middle ] > key :
return binarySearch ( A, key, low, middle - 1 )
else :
return binarySearch ( A, key, middle + 1, high )
def sum3 ( A, x ):
S = [ 0 ] * len ( A )
j = 0
k = 0
l = 0
for i in range ( len ( A ) - 1, - 1, - 1 ):
if x != 2 * A [ i ] :
S [ j ] = x - A [ i ]
else :
pass
j = j + 1
while k < len ( A ) - 1 and l < len ( A ) - 1 :
while A [ l ] > S [ k ] :
if k < len ( A ) - 1 :
k = k + 1
else :
break
if A [ l ] == S [ k ] and S [ k ] != x :
return True
l = l + 1
return False
def Union ( A, B ):
heapSortFun ( A )
heapSortFun ( B )
m = len ( A )
p = len ( B )
size = max ( m, p )
if size == m :
for i in range ( 0, p ) :
if BinarySearch ( A, B [ i ], 0, m - 1 ) == False :
size = size + 1
else :
for i in range ( 0, m ) :
if BinarySearch ( B, A [ i ], 0, p - 1 ) == False :
size = size + 1
Output = [ 0 ] * size
if max ( m, p ) == m :
for i in range ( 0, m ) :
Output [ i ] = A [ i ]
k = 0
for i in range ( 0, p ) :
if BinarySearch ( A, B [ i ], 0, m - 1 ) == False :
Output [ m + k ] = B [ i ]
k = k + 1
heapSortFun ( Output )
return Output
else :
for i in range ( 0, p ) :
Output [ i ] = B [ i ]
k = 0
for i in range ( 0, m ) :
if BinarySearch ( B, A [ i ], 0, p - 1 ) == False :
Output [ p + k ] = A [ i ]
k = k + 1
heapSortFun ( Output )
return Output
def BinarySearch ( S, key, low, high ) :
middle = 0
if low > high :
return False
middle = ( low + high ) // 2
if S [ middle ] == key :
return True
elif S [ middle ] > key :
return BinarySearch ( S, key, low, middle - 1 )
else :
return BinarySearch ( S, key, middle + 1, high )
def Smallest ( S, k ) :
O = [ 0 ] * k
n = len ( S )
l = 0
for i in range ( n // 2 - 1, - 1, - 1 ) :
Heapify412 ( i, n, S )
for i in range ( n - 1, - 1, - 1 ) :
S [ 0 ], S [ i ] = S [ i ], S [ 0 ]
if l < k :
if O [ l ] != S [ 0 ]:
O [ l ] = S [ 0 ]
l = l + 1
else :
break
Heapify412 ( 0, i, S )
return ( O )
def Heapify412 ( i, n, S ) :
left = 2 * i + 1
right = 2 * i + 2
if left < n & S [ left ] < S [ i ] :
min = left
else :
min = i
if right < n & S [ right ] < S [ min ] :
min = right
if min != i :
S [ min ], S [ i ] = S [ i ], S [ min ]
Heapify412 ( min, n, S )
#bubbleSortFun ( length, bubbleSort )
#insertionSortFun ( length, insertionSort )
#selectionSortFun ( length, selectionSort )
#countingSortFun ( countingSort, countingSortNew, countingSortAuxiliary )
heapSortFun ( heapSort )
#mergeSortAlg ( mergeSort )
#quickSortAlg ( quickSort )
arr1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
arr2 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
#for i in range ( 0, 20 ) :
# print ( i, sum1 ( arr1, arr2, i ) )
#for i in range ( 0, 30 ) :
# print ( i, sum2 ( arr1, i ) )
#heapSortFun ( arr1 )
#for i in range ( 0, 20 ) :
# print ( i, sum3 ( arr1, i ) )
#print ( Union ( arr1, arr2 ) )
print ( Smallest ( heapSort, 4 ) )
wait = input ( "\n\nPress any key to exit..." )
| true |
6b3c9e957c6a982e7d90549c482b009a1586a8b0
|
Python
|
paulocheque/django-dynamic-fixture
|
/django_dynamic_fixture/tests/test_ddf_teaching_and_lessons.py
|
UTF-8
| 9,709 | 2.65625 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
import re
from django.test import TestCase
import pytest
from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture
data_fixture = SequentialDataFixture()
class DDFTestCase(TestCase):
def setUp(self):
self.ddf = DynamicFixture(data_fixture)
DDFLibrary.get_instance().clear()
class TeachAndLessonsTest(DDFTestCase):
def test_teach_a_default_lesson_for_a_model(self):
self.ddf.teach(ModelForLibrary, integer=1000)
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1000
def test_default_lesson_may_be_overrided_although_it_is_an_anti_pattern(self):
self.ddf.teach(ModelForLibrary, integer=1000)
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1000
self.ddf.teach(ModelForLibrary, integer=1001)
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1001
def test_it_must_NOT_raise_an_error_if_user_try_to_use_a_not_saved_default_configuration(self):
self.ddf.get(ModelForLibrary)
def test_it_must_raise_an_error_if_try_to_set_a_static_value_to_a_field_with_unicity(self):
with pytest.raises(InvalidConfigurationError):
self.ddf.teach(ModelForLibrary, integer_unique=1000)
def test_it_allows_to_use_masks_as_lessons_for_unique_integer_fields(self):
self.ddf.teach(ModelForLibrary, integer_unique=Mask('1###'))
instance = self.ddf.get(ModelForLibrary)
assert 1000 <= int(instance.integer_unique) <= 1999
def test_it_allows_to_use_masks_as_lessons_for_unique_char_fields(self):
self.ddf.teach(ModelWithUniqueCharField, text_unique=Mask('---- ### __'))
instance = self.ddf.get(ModelWithUniqueCharField)
assert re.match(r'[A-Z]{4} [0-9]{3} [a-z]{2}', instance.text_unique)
def test_it_must_accept_dynamic_values_for_fields_with_unicity(self):
self.ddf.teach(ModelForLibrary, integer_unique=lambda field: 1000)
def test_it_must_NOT_propagate_lessons_for_internal_dependencies(self):
self.ddf.teach(ModelForLibrary, foreignkey=DynamicFixture(data_fixture, integer=1000))
instance = self.ddf.get(ModelForLibrary)
assert instance.integer != 1000
assert instance.foreignkey.integer == 1000
def test_it_must_use_lessons_for_internal_dependencies(self):
# ModelForLibrary.foreignkey is a `ModelForLibrary2`
self.ddf.teach(ModelForLibrary, integer=1000)
self.ddf.teach(ModelForLibrary2, integer=1001)
instance = self.ddf.get(ModelForLibrary, foreignkey=DynamicFixture(data_fixture))
assert instance.integer == 1000
assert instance.foreignkey.integer == 1001
# Not implemented yet
# def test_teaching_must_store_ddf_configs_too(self):
# self.ddf.teach(ModelForLibrary, fill_nullable_fields=False)
# instance = self.ddf.get(ModelForLibrary)
# assert instance.integer is None
# DDFLibrary.get_instance().clear()
# self.ddf.teach(ModelForLibrary, fill_nullable_fields=True)
# instance = self.ddf.get(ModelForLibrary)
# assert instance.integer is not None
# Not implemented yet
# def test_teaching_ddf_configs_must_NOT_be_propagated_to_another_models(self):
# self.ddf.teach(ModelForLibrary, fill_nullable_fields=False)
# instance = self.ddf.get(ModelForLibrary)
# assert instance.integer is None
# assert instance.foreignkey.integer is None
# DDFLibrary.get_instance().clear()
# self.ddf.teach(ModelForLibrary, fill_nullable_fields=True)
# instance = self.ddf.get(ModelForLibrary)
# assert instance.integer is not None
# assert instance.foreignkey.integer is None # not populated
class TeachingAndCustomLessonsTest(DDFTestCase):
def test_a_model_can_have_custom_lessons(self):
self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson=None)
self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson='a name')
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1000
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
assert instance.integer == 1001
def test_custom_lessons_must_not_be_used_if_not_explicity_specified(self):
self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
instance = self.ddf.get(ModelForLibrary)
assert instance.integer != 1000
def test_a_model_can_have_many_custom_lessons(self):
self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson='a name 2')
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
assert instance.integer == 1000
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name 2')
assert instance.integer == 1001
def test_it_must_raise_an_error_if_user_try_to_use_a_not_saved_configuration(self):
with pytest.raises(InvalidConfigurationError):
self.ddf.get(ModelForLibrary, ddf_lesson='a not teached lesson')
def test_default_lesson_and_custom_lesson_must_work_together(self):
# regression test
self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson=True)
self.ddf.teach(ModelForLibrary, integer=1002, ddf_lesson='a name2')
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
assert instance.integer == 1000
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1001
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name2')
assert instance.integer == 1002
def test_default_lesson_and_custom_lesson_must_work_together_for_different_models(self):
# regression test
self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson=True)
self.ddf.teach(ModelForLibrary, integer=1002, ddf_lesson='a name2')
self.ddf.teach(ModelForLibrary2, integer=2000, ddf_lesson='a name')
self.ddf.teach(ModelForLibrary2, integer=2001, ddf_lesson=True)
self.ddf.teach(ModelForLibrary2, integer=2002, ddf_lesson='a name2')
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
assert instance.integer == 1000
instance = self.ddf.get(ModelForLibrary)
assert instance.integer == 1001
instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name2')
assert instance.integer == 1002
instance = self.ddf.get(ModelForLibrary2, ddf_lesson='a name')
assert instance.integer == 2000
instance = self.ddf.get(ModelForLibrary2)
assert instance.integer == 2001
instance = self.ddf.get(ModelForLibrary2, ddf_lesson='a name2')
assert instance.integer == 2002
class DDFLibraryTest(TestCase):
def setUp(self):
self.lib = DDFLibrary()
def test_add_and_get_configuration_without_string_name(self):
self.lib.add_configuration(ModelForLibrary, {'a': 1})
assert self.lib.get_configuration(ModelForLibrary) == {'a': 1}
assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 1}
assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 1}
self.lib.clear()
self.lib.add_configuration(ModelForLibrary, {'a': 2}, name=None)
assert self.lib.get_configuration(ModelForLibrary) == {'a': 2}
assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 2}
assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 2}
self.lib.clear()
self.lib.add_configuration(ModelForLibrary, {'a': 3}, name=True)
assert self.lib.get_configuration(ModelForLibrary) == {'a': 3}
assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 3}
assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 3}
def test_add_and_get_configuration_with_name(self):
self.lib.add_configuration(ModelForLibrary, {'a': 1}, name='x')
assert self.lib.get_configuration(ModelForLibrary, name='x') == {'a': 1}
def test_clear_config(self):
self.lib.clear_configuration(ModelForLibrary) # run ok if empty
self.lib.add_configuration(ModelForLibrary, {'a': 1})
self.lib.add_configuration(ModelForLibrary, {'a': 2}, name='x')
self.lib.add_configuration(ModelForLibrary2, {'a': 3})
self.lib.clear_configuration(ModelForLibrary)
assert self.lib.get_configuration(ModelForLibrary) == {}
with pytest.raises(Exception):
self.lib.get_configuration(ModelForLibrary, name='x')
assert self.lib.get_configuration(ModelForLibrary2) == {'a': 3}
def test_clear(self):
self.lib.add_configuration(ModelForLibrary, {'a': 1})
self.lib.add_configuration(ModelForLibrary, {'a': 2}, name='x')
self.lib.add_configuration(ModelForLibrary2, {'a': 3})
self.lib.add_configuration(ModelForLibrary2, {'a': 4}, name='x')
self.lib.clear()
assert self.lib.get_configuration(ModelForLibrary) == {}
with pytest.raises(Exception):
self.lib.get_configuration(ModelForLibrary, name='x')
assert self.lib.get_configuration(ModelForLibrary2) == {}
with pytest.raises(Exception):
self.lib.get_configuration(ModelForLibrary2, name='x')
| true |