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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0ef405a933a049278c1e1cee4daca7b4cbc80dda | Python | radomirbrkovic/algorithms | /dynamic-programming/exercises/tiling-problem.py | UTF-8 | 241 | 4.0625 | 4 | [] | no_license | # Tiling Problem https://www.geeksforgeeks.org/tiling-problem/
def getNoOfWays(n):
if n >= 0 and n <= 1:
return n
return getNoOfWays(n-1) + getNoOfWays(n - 2)
print(getNoOfWays(4)) #3
print(getNoOfWays(3)) #2 | true |
d3b98d8c5e0d8d79282ca30379cf8b9c341f86b7 | Python | soic1/lear_python_and_ethical_hacking_from_scratch | /Network_scanner/network_scanner.py | UTF-8 | 1,147 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python
import scapy.all as scapy
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--ip", dest="ip", help="IP address to be scanned")
options = parser.parse_args()
if not options.ip:
parser.error("Please enter a valid IP address")
return options
def scan(ip):
if not ip:
print("No input given. Exiting program")
exit()
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
client_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
client_list.append(client_dict)
return client_list
def print_scan_result(list):
print("IP\t\t\tMAC address")
print("=================================================")
for client in list:
print(client["ip"] + "\t\t" + client["mac"])
arguments = get_arguments()
scan_results = scan(arguments.ip)
print_scan_result(scan_results) | true |
be50ead68a75680f96bd09ed4408515da1dc20e0 | Python | Harvus/CodaAcademy_Python_Code | /CodeAcademy_Code_Test01.py3 | UTF-8 | 4,269 | 4.1875 | 4 | [] | no_license | print("-------------------Turn up the Temperature-------------------")
print("")
#define the function called f_to_c
def f_to_c(f_temp):
return (f_temp - 32) * 5/9
print("Converting 70 Fahrenheit to celsius: ")
print(f_to_c(70))
print()
print()
#Define the var f100_in_celsius and set it equal to the value of f_to_c with 100 as input
print("Converting 100 Fahrenheit to celsius: ")
f100_in_celsius = f_to_c(100)
print(f100_in_celsius)
print()
print()
#Define function c_to_f has a input of temp in celsius and converts it into Fahrenheith
def c_to_f(c_temp):
return (c_temp * (9/5)) + 32
print("Converting 0 Celsius in to Fahrenheit: ")
c0_in_fahrenheit = c_to_f(0)
print(c0_in_fahrenheit)
print("")
print("")
print("-------------------USE THE FORCE--------------------------")
print("")
#define the function get_force that takes in mass and acceleration. and returns mass multiplied by acceleration
print("Force is mass multiplied by acceleration")
print("")
train_mass = 22680
train_acceleration = 10
train_distance = 100
bomb_mass = 1
def get_force(mass, acceleration):
return mass * acceleration
train_force = get_force(train_mass, train_acceleration)
print ("The GE train supplies " + str(train_force) + " Newtons of force." )
print(train_force)
print("-------------------USE THE FORCE | Get energy --------->")
print("")
#Defining the function get_energy that taks in mass and c.
#Default value c is 3 * 1^8
def get_energy(mass, c = 3 * 10**8):
return mass * c**2
bomb_energy = get_energy(bomb_mass)
print("A 1kg bomb supplies " + str(bomb_energy) + " Joules.")
print("")
print("-------------------Do the Work--------------------------")
#Defining get_work and take in mass, acceleration, and distance.
def get_work(mass, acceleration, distance):
#Using get_force function and calculate the force and save
force = get_force(mass, acceleration)
return force * distance
# step 12 Test get_work by using it on train_mass, train_acceleration, and train_ distance
# and save the result to var train_work
train_work = get_work(train_mass, train_acceleration, train_distance)
#Print the string
print("The GE train does " + str(train_work) + " Joules of work over " + str(train_distance) + " meters.")
# Test function
def force(mass, acceleration):
force_val = mass*acceleration
return force_val
test_force = force(10, 9.81)
print("This is testing a new function called force and the force for that is: " + str(test_force) + "")
print("Hello World")
print(" <----------------------------------- Testing challenges ----------------------------------------->")
print("")
#Defining a refresh function
def some_function(some_input1, some_input2):
# ...do something with the inputs ...
return output
print(" <----------------------------------- Testing challenges | Tenth Power----------------------------------------->")
# Write your tenth_power function here:
def tenth_power(s):
tenth = s **10
return tenth
# Uncomment these function calls to test your
#tenth_power function:
print(tenth_power(1))
# 1 to the 10th power is 1
print(tenth_power(0))
# 0 to the 10th power is 0
print(tenth_power(2))
# 2 to the 10th power is 1024
#s = 2
#p = 10
#print(s**p)
print("<----------------------------------- Testing challenges | Squere_root----------------------------------------->")
print("")
# Write your square_root function here:
def square_root(num):
num = num**(1/2)
return num
# Uncomment these function calls to test your square_root function:
print(square_root(16))
# should print 4
print(square_root(100))
# should print 10
print("<----------------------------------- Testing challenges | Win_Percentage----------------------------------------->")
print("")
#Create a function called win_percentage() that takes two parameters named wins and losses.
#This function should return out the total percentage of games won by a team based on these two numbers.
# Write your win_percentage function here:
def win_percentage(win, losses):
percentage = win/losses
return percentage, win, losses
# Uncomment these function calls to test your win_percentage function:
print(win_percentage(5, 5))
# should print 50
print(win_percentage(10, 0))
# should print 100
#testing percentage print:
| true |
e040257089538c0612e00974c0c136801e776602 | Python | Snooker4Real/Python_files | /Remplissage d'un cotour.py | UTF-8 | 4,093 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 13:51:56 2017
@author: jonathancindanomwamba
"""
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def F1(x,y):
norme = np.sqrt(x**2+y**2)
tx, ty = x/norme, y/norme
nx, ny = -y/norme, x/norme
return nx, ny, tx, ty
def F2(xA, yA, xB, yB, x, y):
nx, ny, tx, ty = F1(xB-xA,yB-yA)
# coordonnée de AM selon le vecteur n
AMn = nx*(x-xA) + ny(y-yA)
# coordonnée de AM selon le vecter t
AMt = tx*(x-xA) + ty*(y-yA)
return AMn, AMt
def F3(xA, yA, xB, yB, x, y):
AMn, AMt = F2(xA, yA, xB, yB, x, y)
AB = np.sqrt((xB-xA)**2+(yB-yA)**2)
if 0 < AMn < AB :
return abs(AMt)
elif AMn<=0:
return np.sqrt(AMn**2+AMt**2)
else:
return np.sqrt((x-xB)**2+(y-yB)**2)
def F4(Lx, Ly, x, y, L, H, epsilon = 2):
if x < epsilon :
return True
N = len(Lx)
for i in range(N-1):
xA, yA = Lx[i], Ly[i]
xB, yB = Lx[i+1], Ly[i+1]
d = F3(xA, yA, xB, yB, x, y)
if d< epsilon:
return True
def F5(H,L,i0,y0):
INFO = np.zeros((H,L), dtype='int')
H,L = len(INFO),len(INFO[0])
INFO[j0,i0] = 1
while True :
if F5bis(INFO, Lx, Ly):
return INFO
""" La fonction F5bis() test dans INFO tous les voisins des pixels qui sont à 1
(celle sont les voisins n'ont pas encore été traités) """
def F5bis(INFO,Lx,Ly):
H, L = len(INFO), len(INFO[0])
for j in range(H):
for i in range(L):
"""On parcourt l'image de gauche à droite et de haut en bas."""
if INFO[j,i] ==1 :
"""Comme on teste tous les voisins INFO[i,j] passe à 2"""
INFO[j,i] = 2
for (a,b) in [(-1,0),(-1,1),(-1,-1),(0,1),(0,-1),(1,1),(1,0),(1,-1)]:
if INFO[j+b,i+a]== 0 and not F4(Lx,Ly,i+a,j+b,L,H):
"""On vérifie que les pixel pixel voisin est à zéro et
que le pixel est loin du contour donc dans le contour"""
INFO[j+b,i+a] = 1
"""Ayant de sortir de la fonction, on renvoie False
il n'y a plus aucun 1 dans INFO"""
test = np.sum(INFO == 1)
if test == 0:
return False
return True
NOM1 = "IMG_0706.jpg"
Lx = [50,300,400,500,50,50]
Ly = [50,50,300,300,50]
H, L = len(INFO), len(INFO[0])
i0, j0 = 75, 75
INFO = F5(H,L,i0,j0,Lx,Ly)
for i in range(L):
for j in range(H):
if INFO[j,i] == 2:
INFO[j,i,0] = 255 - IMA[j,i,0]
INFO[j,i,1] = 255 - IMA[j,i,1]
INFO[j,i,2] = 255 - IMA[j,i,2]
CreerImage (INFO,"justeLeContour.jpg")
"""def ExtractData(Nom) : # Renvoie un tableau H*L*3
im = Image.open(Nom) L, H = im.size # Lecture de l’image
data = im.getdata() # Taille de l’image
d = np.array(data) # On récupère les données dans la variable data # conversion de data en tableau
IMA = d.reshape((H,L,3)) # On transforme un tableau 1D en tableau avec 3 indices.
return IMA
# Cette fonction crée une image qui s’appelle « nom » (n’oubliez pas l’extension « .jpg », « .png », ...
def CreerImage(IMA,nom) : # IMA est un tableau de dimensions H*L*3.
H, L = len(IMA), len(IMA[0]) im = Image.new('RGB',(L,H)) pix = im.load()
for i in range(L) :
for j in range(H) :
pix[i,j] = tuple(IMA[j,i]) # On rentre pixel par pixel les valeurs de l’image à partir de IMA
im.save(nom)
NOM1 = "image1.jpg"
IMA1 = ExtractData(NOM1) # On lit une image
# Définition du contour
x = np.array([112,118,131,163,209,239,278,321,366,395,419,433, 446,454,455,438,432,403,348,261,199,149,122,112])
y = np.array([369,436,528,573,600,614,623,610,579,556,506,454, 409,394,366,361,337,303,281,276,277,299,325,369])
# Création d’une image
IMA3 = np.zeros((H, L, 3), dtype = 'int') # image noire pour l’instant (qu’il faut modifier)
# image avec L colonnes et H lignes
# Une fois l’image IMA3 complétée on peut créer un fichier .jpg ou .png.
CreerImage(IMA3,"VotreImage.jpg")""" | true |
9af9c28ab880b7c5e64d30e44b2582a756f21587 | Python | L1nwatch/leetcode-python | /717.1-比特与-2-比特字符.py | UTF-8 | 493 | 2.890625 | 3 | [] | no_license | #
# @lc app=leetcode.cn id=717 lang=python3
#
# [717] 1比特与2比特字符
#
# @lc code=start
class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
index = 0
length = len(bits)
while index < length:
if bits[index] == 1:
index += 2
continue
if index == length - 1:
return True
if bits[index] == 0:
index += 1
return False
# @lc code=end
| true |
954bfb7cca4800744eff56dbf504d2e96c360103 | Python | AnteDujic/pands-problem-sheet | /weekday.py | UTF-8 | 836 | 4.4375 | 4 | [] | no_license | # Program that outputs a different message depending if today is weekday or weekend
# Author: Ante Dujic
# Importing module datetime to work with dates as date objects
import datetime as dt
# Setting variable for current day
today = dt.datetime.now()
# Comparing current day (1-7) to Friday (5)
# strf.time() formats date objects as strings (converted to int)
if (int ((today.strftime("%u"))) > 5): # "%u" = ISO 8601 weekday Mon(1) - Sun (7)
print ("Today is the weekend, yay!")
else:
print ("Yes, unfortunately today is a weekday.")
"""
REFERENCES:
- datetime module: https://www.w3schools.com/python/python_datetime.asp
- day today: https://www.programiz.com/python-programming/datetime
- strftime() formatting: https://www.w3schools.com/python/python_datetime.asp
""" | true |
b8a8d5b8110b0a1c9496699c3e0c62a10c52b1b4 | Python | lfdyf20/Leetcode | /Self Dividing Numbers.py | UTF-8 | 523 | 3.34375 | 3 | [] | no_license | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for num in range(left, right + 1):
snum = str( num )
if '0' in snum:
continue
if all( map( lambda x:num % int(x) == 0, snum ) ):
res.append( num )
return res
left, right = 1, 22
left, right = 1, 1
sl = Solution()
print( sl.selfDividingNumbers( left, right ) ) | true |
abb20e01bfcd82f5d8c0c37b0f9a08ca45dfb1ec | Python | dpasacrita/server_manager | /combat.py | UTF-8 | 3,681 | 3.96875 | 4 | [] | no_license | #!/usr/bin/python3.5
import random
# Globals
BASE_DAMAGE = 1
UNARMED_DAMAGE = 1
CRITICAL_MULTIPLIER = 2
def calculate_weapon_damage(char1):
"""
Calculate the damage that char1 will do against something
This is determined by rolling for how much damage char1 does based on their weapon.
:param char1: Damage Dealer
:return: damage: The damage we've done.
"""
# Start with base damage.
damage = BASE_DAMAGE
# First determine if char1 has a weapon
if bool(char1.get_current_weapon()) is False:
print("COMBAT: %s has no weapon. Damage set to 1." % char1.get_name())
damage = UNARMED_DAMAGE
return damage
# They have a weapon, so let's grab it.
try:
weapon = char1.get_current_weapon()
except Exception as e:
print("ERROR: %s" % e)
print("ERROR: Failed to get current weapon, even though char1 should have one.")
return damage
rolled_damage = roll_damage(weapon)
final_damage = calculate_critical(weapon, rolled_damage)
print("COMBAT: " + char1.get_name() + " rolled %s damage." % final_damage)
return final_damage
def roll_damage(weapon):
"""
Rolls for a random number in between the weapon's minimum and maximum.
:param weapon: The Weapon we're working with here.
:return: damage: random number in between min and max.
"""
# Start with Base damage:
damage = BASE_DAMAGE
# Now let's calculate the damage.
try:
minimum = weapon["damage min"]
except Exception as e:
print("ERROR: %s" % e)
print("ERROR: Failed to get weapon's minumum damage. Perhaps something went wrong with validation?")
return damage
try:
maximum = weapon["damage max"]
except Exception as e:
print("ERROR: %s" % e)
print("ERROR: Failed to get weapon's maximum damage. Perhaps something went wrong with validation?")
return damage
# Now get a number between those.
try:
rolled_damage = random.randint(minimum, maximum)
return rolled_damage
except Exception as e:
print("ERROR: %s" % e)
print("ERROR: Couldn't roll damage. Minimum and Maximum possible invalid.")
return damage
def calculate_critical(weapon, rolled_damage):
"""
This method calculates whether or not a critical hit has occurred.
:param weapon: The Weapon we're dealing with.
:param rolled_damage: How much damage was rolled initially.
:return: The final calculated damage, whether or not a crit occurred.
"""
# Use the rolled damage as a base.
final_damage = rolled_damage
# Grab the weapon's critical rate:
try:
crit_rate = weapon["critical rate"]
except Exception as e:
print("ERROR: %s" % e)
print("ERROR: Failed to get weapon's critical rate. Perhaps something went wrong with validation?")
return final_damage
# Now let's calculate the critical.
# We'll roll a number between 1 and 100.
# If the number is less than or equal to the crit rate, it criticals.
critical = random.randint(1, 100)
# If we succeeded, double damage.
if critical <= crit_rate:
print("COMBAT: CRITICAL HIT!")
final_damage = rolled_damage * CRITICAL_MULTIPLIER
return final_damage
else:
return final_damage
def inflict_damage(char1, damage):
# First lets double check that char1 has appropriate health
try:
health = int(char1.health)
except Exception as e:
print("FATAL ERROR: %s" % e)
print("FATAL ERROR: Problem getting health!")
exit(1)
# Make sure health is a positive number.
| true |
3d4555eb57d6e411797ecccb8e00326f650239f0 | Python | Hiroki39/CS-UY-1134 | /DataStructure/MeanQueue.py | UTF-8 | 785 | 3.578125 | 4 | [] | no_license | from ArrayQueue import ArrayQueue
class MeanQueue:
def __init__(self):
self.data = ArrayQueue()
self.curr_sum = 0
def __len__(self):
return len(self.data)
def is_empty(self):
return self.data.is_empty()
def enqueue(self, e):
if not isinstance(e, (int, float)):
raise TypeError("could only enqueue int or float")
self.data.enqueue(e)
self.curr_sum += e
def dequeue(self):
e = self.data.dequeue()
self.curr_sum -= e
return e
def first(self):
return self.data.first()
def sum(self):
return self.curr_sum
def mean(self):
if self.is_empty():
raise Exception("MeanQueue is empty")
return self.curr_sum / len(self)
| true |
506f053a5695a697513ed9599f28d76c70069869 | Python | abhiunix/python-programming-basics. | /enumerate.py | UTF-8 | 745 | 4.78125 | 5 | [] | no_license | #Enumerate
#enumerate is a built in function that returns an iterator of tuples containing indices and values of
#a list. You'll often use this when you want the index along with each element of an iterable in a loop.
letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
#Quiz: Enumerate
#Use enumerate to modify the cast list so that each element contains the name followed by the
#character's corresponding height. For example, the first element of cast should change from
#"Barney Stinson" to "Barney Stinson 72".
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
#forLoop
for i, character in enumerate(cast):
cast[i] = character + " " + str(heights[i])
print(cast) | true |
d25a4542b5c985f6f25236e6a73614b4dbbe26bc | Python | wolfhardfehre/olli-simulation | /app/app/routing/booking.py | UTF-8 | 1,265 | 2.828125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | class Booking:
counter = 1000
@classmethod
def get_counter(cls):
cls.counter += 1
return cls.counter
def __init__(self, start_node, end_node, earliest_departure, latest_arrival):
self.start_node = start_node
self.end_node = end_node
self.earliest_departure = earliest_departure
self.latest_arrival = latest_arrival
def to_geojson_unloaded(self):
return [self.geojson_point(p, Booking.get_counter(), color) for p, color in
[(self.start_node.geometry, '#9DBD0F'), (self.end_node.geometry, '#3110BD')]]
def to_geojson_loaded(self):
return [self.geojson_point(self.end_node.geometry, Booking.get_counter())]
@staticmethod
def geojson_point(point, id, color='#3110BD'):
return {
"geometry": {
"type": "Point",
"coordinates": [
point.x, point.y
]
},
"type": "Feature",
"style": {
"color": color,
"fillOpacity": 0.5,
"weight": 2,
"radius": 20,
"opacity": 0.7
},
"properties": {
"id": id
}
}
| true |
eade6654f0b57fda51ef76d0e7d1682a0b5f2a80 | Python | jianmink/geoip2dataloader | /src/e164cc.py | UTF-8 | 2,020 | 2.515625 | 3 | [] | no_license |
import time
import unittest
e164ccList=[]
def load():
with open("./result_e164cc2mcc.csv_ready4use",'r') as f:
for record in f:
fields = record.split(',')
e164ccList.append(fields[0].strip())
#print e164ccList
def e164cc(vlrnum):
cc = ""
for each in e164ccList:
if vlrnum.startswith(each) and len(each) > len(cc):
cc = each
return cc
dictE164Cc={}
def addE164Cc(cc):
global dictE164Cc
dict_ = dictE164Cc
for c in cc[:-1]:
if c not in dict_.keys():
dict_[c]={}
dict_=dict_[c]
if cc[-1] in dict_.keys():
dict_[cc[-1]]
else:
dict_[cc[-1]] = cc
def loadplus(filename):
with open(filename) as f:
for record in f:
fields =record.split(',')
cc = fields[0].strip()
print cc
addE164Cc(cc)
def e164ccplus(vlrnum):
pass
def genVlrnumList(n):
import random
vlrnums=[]
for _ in range(n):
vlrnum = ""
len_ = 3+int(random.random()*10)%10
for _ in range(len_):
vlrnum+="%d" %(int(random.random()*10)%10)
vlrnums.append(vlrnum+"\n")
with open("./vlrnumlist%d"%(n), 'w+') as f:
f.writelines(vlrnums)
if __name__ == "__main__":
begin = time.time()
load()
with open("vlrnumList10000",'r') as f:
for vlrnum in f:
e164cc(vlrnum)
e164cc("91500")
end = time.time()
delta = (end - begin)
print "delta: %.06f ms" %(delta*1000)
class TestE164cc(unittest.TestCase):
def setUp(self):
load()
def test86139(self):
cc = e164cc("86139")
self.assertEqual("86", cc)
def test91500(self):
cc = e164cc("91500")
self.assertEqual("91", cc)
def test214139(self):
cc = e164cc("214139")
self.assertEqual("", cc)
| true |
ee551a5d173107f4a1b8442a7c67db1a01ab010a | Python | Aasthaengg/IBMdataset | /Python_codes/p02802/s411687593.py | UTF-8 | 351 | 2.75 | 3 | [] | no_license | N, M = map(int, input().split())
Q = [list(map(str, input().split())) for _ in range(M)]
ans = [0] * N
AC = 0
WA = 0
for P in Q:
p = int(P[0])
S = P[1]
if ans[p - 1] == "END":
continue
if S == "WA":
ans[p - 1] += 1
if S == "AC":
WA += ans[p - 1]
AC += 1
ans[p - 1] = "END"
print(AC, WA)
| true |
597c9464fd5e75ea66273fb08ef59bf335524952 | Python | fall-2018-csc-226/t04-master | /t04_refactored.py | UTF-8 | 46,535 | 3.953125 | 4 | [
"MIT"
] | permissive | ######################################################################
# Author: The Fall 2018 226 Class!
#
# Assignment: T04: Adventure in Gitland
#
# Purpose: To recreate a choose-your-own-adventure style game
# by refactoring T01.
#
# Each "twist" in the story is from a different group. The resulting story
# will either be incoherently random, or entertainingly "Mad Lib" like.
# Either way, it should be fun!
#
# This new version will take advantage of functions, as well as
# demonstrate the value of git as a tool for collaborating.
######################################################################
# Acknowledgements:
# Original Author: Scott Heggen
#
######################################################################
import random
from time import sleep
delay = 1.0 # change to 0.0 for testing/speed runs; larger for dramatic effect!
dead = False
def start_story():
"""
Introduction text for the story. Don't modify this function.
:return: the user's name, captured from user input
"""
user = input("What do they call you, unworthy adversary? ")
print()
print("Welcome,", user, ", to the labyrinth")
sleep(delay)
print("Before you lies two paths. One path leads to treasures of unimaginable worth.")
print("The other, certain death. Choose wisely.")
print()
sleep(delay * 2)
print("You are in a dark cave. You can see nothing.")
print("Staying here is certainly not wise. You must find your way out.")
print()
sleep(delay)
return user
def end_story(user):
"""
This is the ending to the story. Don't modify this function, either.
:param user: the user's name
:return: None
"""
print("Congratulations, " + user + ", you have made it to the end of this... strange... adventure. I hope you feel accomplished.")
print()
print()
print()
sleep(delay*5)
print("Now go play again.")
def kill_if_dead(dead):
"""
Simple function to check if you're dead
:param dead: A boolean value where false let's the story continue, and true ends it.
:return: None
"""
if dead:
quit()
###################################################################################
def scott_adventure():
"""
My original adventure text I gave as an example. Leave it alone as well.
:return: None
"""
global dead # You'll need this to be able to modify the dead variable
direction = input("Which direction would you like to go? [North/South/East/West]")
if direction == "North":
# Good choice!
print("You are still trapped in the dark, but someone else is there with you now! I hope they're friendly...")
sleep(delay)
elif direction == "South":
# Oh... Bad choice
print("You hear a growl. Not a stomach growl. More like a big nasty animal growl.")
sleep(delay)
print("Oops. Turns out the cave was home to a nasty grizzly bear. ")
print("Running seems like a good idea now. But... it's really, really dark.")
print("You turn and run like hell. The bear wakes up to the sound of your head bouncing off a low stalactite. ")
print()
sleep(delay*2)
print("He eats you. You are delicious.")
dead = True
else:
# Neutral choice
print("You're in another part of the cave. It is equally dark, and equally uninteresting. Please get me out of here!")
sleep(delay)
kill_if_dead(dead)
def places_to_go():
"""
https://docs.google.com/document/d/1ydkRlcWI9bj7BYYdBTKScwrTixQgIL6u_Hl1hY28p98/edit?usp=sharing
The docstring is linked to the Google Doc for the Teamo4 Assignment of toktobaeva and alfaro
The function places_to_go() you are faced with a decision to choose between cities: Wakanda, Asgard, New You or Gotham City
:return: None
"""
global dead
direction = input("Where do you want to go today?. Choose carefully hahaahhaha [Wakanda, New York, Asgard, Gotham City]")
if direction == "Asgard" or direction=="asgard":
# Well done!
print()
print("Wow, I'm shocked!. Good Choice!")
print()
print()
sleep(delay)
print("Thor deems you worthy to fight by his side! Welcome to Asgard")
sleep(delay)
elif direction == "Gotham City" or direction=="gotham city":
# oh.. bad choice
print()
sleep(delay*2)
print("You find yourself in an dark alley, you hear two gunshots *bang, bang*")
sleep(delay*2)
print("A man runs past you, no witnesses he says...")
sleep(delay*2)
print("*Bang*")
print("You're Dead")
dead = True
print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ")
elif direction=="Wakanda" or direction=="wakanda":
# interesting choice
print()
name = input("Are you a Wakanda citizen ?")
if name == "Yes":
sleep (delay *2)
print("Welcome back, your family missed you")
else:
sleep (delay*2)
print ("You can't find Wakanda. You only see a rhino here")
print("He looks friendly but this is boring")
sleep (delay*2)
else:
# neutral choice
print("You are in New York. Not much for you to do here")
sleep (delay*2)
print("Press the green button so you can see if you have better luck next time")
sleep(delay*2)
kill_if_dead(dead)
def team_2_adv():
"""
Google Doc: https://docs.google.com/document/d/19jYjDRX_WR4pPynsAYmeglDpQWDvNVMDgYvd4EUWqm8/edit?usp=sharing
Goes through the berea section of the story. Asks if you want to go to dining or go do homework.
Choosing either will take you to two possibilities of being "dead" or being asked how much money you have.
This choice then will make you "dead" or will continue on the "story" to the next function
"""
global dead
print()
print()
direction = input ("As a Berean, no matter where you end up, you have to constantly make this hard decision: Go to dining or Go do homework, what do you say? [Go to dining/Go do homework]")
if direction == "Go to dining" or "go to dining": # Good choice! asking if they want to go to dining
print()
print("you get tired of this trivial cave and leave and head to dining to meet up friends")
print()
sleep(delay*3)
elif direction == "Go do homework" or "go do homework": # Bad choice! asking if they want to do homework
print()
sleep(delay*3)
print("You think you are making the right choice to conform to this capitalist world.")
sleep(delay*3)
print()
print("When you, at heart, are a leftist Marxist")
sleep(delay*3)
print()
print("You know you shouldn't be enslaved by the institution that is generally accepted in the form of")
sleep(delay*3)
print()
print("'all american college'")
sleep(delay*3)
print()
print("You graduate with a degree.")
sleep(delay*3)
print()
print("Work an 8-5 job.")
sleep(delay*3)
print()
print("Have two children.")
sleep(delay*3)
print()
print("Get old.")
sleep(delay*3)
print()
print("And, when sitting at your white wood porch, looking at your old pictures, quietly sob realizing...")
sleep(delay*3)
print()
print("that you should have gone to the dining hall")
sleep(delay*3)
print()
print("You die a victim of this machine.")
print()
print()
dead = True
else: #user inputs something other than the dining or homework asnwers
sleep(delay)
print()
print("You are not a true Berean.")
print()
sleep(delay)
if dead == True: #end of the homework answer
sleep(delay)
print("Oh no. You are dead. Bye.")
quit()
money = int(input ("How much is your family income?")) #ask what family income is
if money < 30000: #does the print if they asnwer with something below 30000
sleep (delay)
print()
print("Berea, berea, beloved")
elif money > 30000: #does the print if they answer with something above 30000
sleep(delay)
print()
print("you don't belong here")
dead = True
else: #catches any answers that are not the ones we want
sleep(delay)
print("illiterate. bye. *middle finger emoji* *clown emoji* *middle finger emoji*")
if dead == True:
print("go back to the centre college where you belong.")
quit()
def team_3_adv():
"""
This branch was created by Guillermo and Adam.
Google Doc Link: https://docs.google.com/document/d/1B75UoewLi3qD1kfC3ptPuWox-RwT00VteOleVjZUbro/edit?usp=sharing
:return:
"""
decision = input("The stranger tells you that he knows the way out, but you have to follow his every word. What is your decision? [I trust you/No way, No thank you] ")
global dead
if decision == "I trust you":
# Good choice! This will reward the user, and keep the user alive.
print("The stranger is overcome with joy, and hands you flashlight and a ham sandwich.")
sleep(delay)
elif decision == "No way":
# Bad choice... This will kill the user, and terminate the code.
print("Your unwillingness to trust the stranger angers him. He begins to chase you through the dark cave, and you find a place to hide. You hide there for several days.")
sleep(delay)
print("After several days of hiding, you begin to fell fatigued. You lose consciousness, and the stranger is able to find your body and he dismembers you.")
dead = True
print("You died, oh no! Try again by hitting the green button.")
quit()
else:
# Neutral choice, this choice will not help or hurt the user, and will keep them alive.
print("You respectfully decline his offer, and decide to wonder around in the dark by yourself. You wonder in the dark for hours, and make no progress. ")
sleep(delay)
def team_4_adv():
pass
# TODO Add your code here
def team_5_adv():
"""
Google doc: https://docs.google.com/document/d/1BzQqW9mFzMhzRlAyL1DkV31Ps5QJOwXgqQtEBJ4gJAI/edit?usp=sharing
Team 5's refactored chapter
Originally by Dunn & Dovranov , refactored by Jacob Hill, Bryan Epperson, Susan Coreas
:return: None
"""
# Dunn & Dovranov
# Refactored by Team 5
global dead
direction = input("Where do you want to go? [North/South/East/West]")
if direction == "East" or direction == "east":
# Bad Choice
print("You followed the light and it led to another person that was lost.")
print("Slowly approaching the other person you fall and they now know they are not alone.")
print("You are now injured and the other person is leaving you because of the noise.")
print("After they have left you fall asleep.")
sleep(delay)
print("You awaken to the noise of bear that is approaching closer to you.")
print("Unfortunately, you can't walk and the bear is close to you.")
print("The bear is hungry and is looking for a delicious meal.")
print("The bear begins to eat you.")
print("You have one more chance to live. You see a rock.")
userinput = input("Can you grab it? [Yes/No]")
if userinput == "Yes":
print("You hit the bear and it runs off.")
elif userinput == "No":
print("The bear ate you.")
else:
print("The bear ate you.")
dead = True
elif direction == "West" or direction == "west":
# Good choice
print("You are walking in the dark and you stumble across something on the ground.")
print("You bend over and pick it up.")
print("It is a flashlight!")
print("However, you are still in the dark but now you have a flashlight to see more with so you do not fall.")
sleep(delay)
elif direction == "North" or direction == "north":
# Neutral choice
print("You found a place to stay for the night until daytime.")
sleep(delay)
elif direction == "South" or direction == "south":
# Neutral choice
print("You found a place to stay for the night until daytime.")
sleep(delay)
else:
print("That is not a direction! Please input a direction")
team_5_adv()
if dead == True:
print("Oh no! You died. Try again by hitting the green play button.")
quit()
def team_6_adv():
"""
Team 6's refactored chapter.
Originally by lovelle, refactored by lovelle.
:return: None
"""
global dead
direction = input("Which direction would you like to go? [North/South/East/West] ")
if direction == "East":
# Good choice
print()
print("You come upon an underground lake, fed by a glistening stream.")
print()
print("The sound of the water soothes your troubled nerves.")
sleep(delay)
print()
elif direction == "South":
# Bad choice
print()
print("Ever so suddenly, you find yourself surrounded by ogres twice your size.")
print("They realize you are harmless and you catch your breath. It seems they might let you pass...")
sleep(delay * 5)
print()
print("They strike up a song, ready to continue on their way.")
print("Oh, but how loud their voices are! And you aren't feeling so good...")
sleep(delay * 5)
print()
print("The leader asks you to rank the quality of their singing, on a scale of 1 to 10.")
rating = int(input("What do you say? Choose wisely; your life depends on it... "))
print()
if rating < 10:
print("You fall to the ground, feeling the power of a cursed song. Looks like your time is up, friend.")
dead = True
sleep(delay)
print()
else:
print("The ogre thanks you for the complement and sends you on your merry way.")
sleep(delay)
print()
else:
# Neutral choice
print()
print("Phew, you're still on solid ground. But still in the dark. Think fast!")
sleep(delay)
print()
if dead == True:
print("Oh no! You died. And what a shame it had to happen this way.")
print("Better luck next time - try again by hitting the green play button!")
quit()
def team_7_adv():
"""
Team 7's refactored chapter.
Originally done by EppersonB and BarnettH, refactored by BarnettH and DunnA
google doc link: https://docs.google.com/document/d/1PeAwI9PZtPMI5_4KJMAsPv3blZDpBLS_9ZuFGaBhayg/edit?usp=sharing
:return: None
"""
global dead
print()
print("You continue your path in the forest")
print("As you walk through the forest, you encounter a bear wearing a fez and sunglasses.")
print("You notice that the fez has the name 'Bosco' labeled on it. You deduce that this is the famous runaway circus bear, Bosco the Bear.")
sleep(delay)
print()
print("However, Bosco has took notice of you and stands on his hind legs and takes interest in you.")
print("You must make a choice, or it could end very badly for you!")
choice = input("What would you like to do? [Entertain or Fight?]")
if choice == "Fight":
#Good Choice!
print("You choose to engage in fisticuffs with Bosco the Bear. This seems like a very bad idea.")
print()
sleep(delay)
print("Luckily for you, Bosco the Bear lived in the circus his whole life. He does not know how to fight.")
print("Feeling intimated, Bosco the Bear flees. Dropping his fez and glasses.")
print()
print("You are free to continue on your journey while rocking the fez and glasses. Well at least you look nice.")
print()
elif choice == "Entertain":
# Bad Choice
print("Bosco the Bear is not amused with your performance.")
print()
sleep(delay)
print("He ran away from the circus because he hated that life.")
print("Your entertainment reminded him of that hatred. How inconsiderate of you.")
print()
sleep(delay)
print("In a fit of rage, Bosco the Bear kills you with his bare hands.")
print()
dead = True
else:
#Neutral Choice
print("Bosco the Bear is confused by your actions.")
print("Bosco the Bear does not see you as a threat and leaves.")
print()
print("You are free to continue on your journey.")
print()
if dead == True:
print("Oh no! You died. Better luck next time! Try again by hiting the green play button. ")
quit()
def team_8_adv():
pass
# TODO Add your code here
def team_9_adv():
"""
Team 9's refactored chapter.
Originally by hilljac & nudgarrobot, refactored by Juem, Jamalie, Gutheriet.
Google doc:
https://docs.google.com/document/d/1gmxTnKp2swHlYWCZ1cTMZxnLcmNqr2PQnm7XLbYNwsU/edit?usp=sharing
:return: None
"""
global dead
injured = 0 # You start with 100% of your limbs! When this reaches two, you die!
flashlight = 0 # You have no source of light!
anti_soft_lock = 0 # For loops
checkGlint = 0 # Tracking!
checkPool = 0 # ^
direction = input("Which direction would you like to go? [North/South/East/West]")
if direction == "South" or direction == "south" or direction == "S" or direction == "s":
# Good choice!
print("...")
sleep(delay)
print("Ooooooo boy!! You enter a room FILLED WITH GOLD!")
sleep(delay)
print("In addition to the gold, there seems to be a flashlight right in front of you! This is too good to be true!!")
sleep(delay)
itemChoice = input("What do you do? [Pocket the gold]/[Grab the flashlight]/[Try to grab both]")
sleep(delay)
if itemChoice == "Pocket the gold" or itemChoice == "pocket the gold":
print("You stuff your pockets as full as you can, and continue on your journey")
sleep(delay*3)
print("But wait!!")
sleep(delay)
print("Suddenly an enchanted skeleton appears, demanding that you return the gold, or pay with your life")
skeletonChoice = input("Which will you do? [Keep the gold / Leave the gold]")
sleep(delay)
# branching good path
if skeletonChoice == "Keep the gold" or skeletonChoice == "keep the gold":
print("You decide to keep the gold for yourself, and attempt to run for your life. You escape the room, but in the process, the skeleton stabs you in the shoulder, injuring you for the duration of the adventure")
elif skeletonChoice == "Leave the gold":
print("You leave the gold and peacefully leave the room. Satisfied with your following his orders, the skeleton disappears. Your adventure continues")
else:
print("You have the confused the skeleton.")
sleep(delay)
print("Now the skeleton is angry!")
sleep(delay*5)
print("the skeleton has killed you...")
sleep(delay)
dead = True
sleep(delay)
if dead is True:
print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ")
quit()
elif itemChoice == "Grab the flashlight":
print("You decide to play it safe and only grab the flashlight. Obviously, the gold was a trap.")
sleep(delay)
print("You peacefully leave the room and your adventure continues. Also, now you have a flashlight!")
elif itemChoice == "Try to grab both":
print("You rush towards the motherlode in front of you!")
sleep(delay)
print("You grab the flashlight and start stuffing your pockets with as much gold as you can carry.")
sleep(delay)
print("You're gonna be so ri-")
sleep(delay*2)
print("everything is going dark...")
sleep(delay*2)
print("you're not sure, but you feel as though you have been stabbed from behind.")
sleep(delay*2)
print("You fall to the ground...")
sleep(delay*2)
dead = True
sleep(delay)
if dead is True:
print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ")
quit()
else:
print("You decide this whole situation is too good to be true, and is certainly a trap.")
sleep(delay)
print("You turn away and your adventure continues.")
elif direction == "East":
# Bad direction 2. Internal decisions can make it a trade, but an injury is normally guaranteed.
print("You notice a rather low overhang in the darkness of the cave")
sleep(delay)
print("You're wary, but nothing's going to get done if you're overly hesitant.")
sleep(delay)
print("You crawl under the overhang and realize it's more of a short tunnel-")
sleep(delay)
print("It's very narrow, and you barely make your way out the other side.")
sleep(delay*1.33)
print("The air is has a notable chill and movement on the other side of the tunnel,")
sleep(delay)
print("and you hear a faint dripping reverberating through the space.")
sleep(delay)
if flashlight == 1:
print("You sweep the flashlight over the space, but its beam doesn't reach the opposite wall.")
sleep(delay*2)
print("The stone in this part of the cave is smooth, seemingly worn down.")
sleep(delay)
print("The light does, however, illuminate a layer of mist swirling over a small pool")
sleep(delay*1.33)
print("The pool is perfectly still, and despite the darkness, is a deep, almost ethereal blue.")
sleep(delay*2.33)
print("In the far side of the cave, you see something small glisten as you sweep the flashlight over it.")
choice = input("[Inspect pool]/[Check Glint]")
# TODO Flesh out choices for flashlight-enabled play!
if choice == "Check Glint":
print("You carefully walk around the pool and inspect the base of the wall for anything unusual.")
sleep(delay)
print("Unlike most of the room, there are rough, broken rocks here and a crack in the wall.")
sleep(delay)
print("Sifting through the rocks and debris, you find a kind of cup--")
sleep(delay)
print("The cup is shaped in such a way as to resemble a stemless goblet.")
sleep(delay)
print("It's inlaid with small gemstones, and strange symbols mark its surface.")
sleep(delay)
print("You decide that it's worth keeping.")
checkGlint = 1
chalice = 1
elif choice == "Inspect pool":
checkPool = 1
print("You walk up to the lip of the pool. As you approach, the mist recedes.")
sleep(delay)
print("Thick and unnatural, the mist seems almost to pulse as you draw near.")
sleep(delay)
print("Upon closer observation, the pool is by no means water-")
sleep(delay)
print("Instead, it's a thinner liquid, so much so that the edge seems at times to blur with the mist above it.")
sleep(delay)
print("As you remain by the edge, the mist seems to grow more agitated in its swirling.")
sleep(delay)
if checkGlint == 1:
choice = input("[Collect from Pool]/[Touch Pool]/[Remain Motionless]/[Retreat]")
else:
choice = input("[Check Glint]/[Touch Pool]/[Remain Motionless]/[Retreat]")
if choice == "Touch Pool":
print("You dip your hand into the crystal clear liquid.")
sleep(delay)
print("It feels strange, as if it were fine silk that was impossible to hold.")
sleep(delay)
print("Suddenly, you feel something coil around your wrist")
sleep(delay)
print("But the pool is still perfectly clear, and you see nothing.")
sleep(delay)
print("In panic you try to wrest your arm free, but only throw yourself off balance.")
sleep(delay)
print("Your other arm plunges into the pool as you try to steady yourself")
sleep(delay)
print("You claw at your bound wrist, trying to remove the invisible restraint")
sleep(delay)
print("But your hand finds nothing to grasp.")
sleep(delay)
print("You struggle helplessly against the swirling fluid, which is now pulling your arms deeper")
sleep(delay)
print("Absorbed in your struggle, you notice the mist too late--")
sleep(delay)
print("It has rolled forward, and is upon you, enveloping you.")
sleep(delay)
print("Forced to breathe it in, the last of your strength drains away")
sleep(delay)
print("As your vision slowly goes black, the last you feel is the soft, silky feeling of the pool's embrace.")
sleep(delay)
sleep(delay)
dead = True
elif choice == "Check Glint":
print("You carefully walk around the pool and inspect the base of the wall for anything unusual.")
sleep(delay)
print("Unlike most of the room, there are rough, broken rocks here and a crack in the wall.")
sleep(delay)
print("Sifting through the rocks and debris, you find a kind of cup--")
sleep(delay)
print("The cup is shaped in such a way as to resemble a stemless goblet.")
sleep(delay)
print("It's inlaid with small gemstones, and strange symbols mark its surface.")
sleep(delay)
print("You decide that it's worth keeping, but upon taking it the wall behind caves in--")
sleep(delay)
print("You're blinded by light pouring through the opening the cave in created.")
sleep(delay)
print("When you can see again, you realize you're looking out over a range of mountains.")
sleep(delay)
print("Far from being deep underground, you had been trapped in the top of a mountain!")
sleep(delay)
print("You step out and breathe a sigh of relief in the clean mountain air.")
checkGlint = 1
chalice = 1
else:
print("If you're seeing this, you've probably referred to one of our placeholders!")
print("While we intend to flesh these out later, at present it would be detrimental")
print("to assignment deadlines! Speaking of deadlines, this is one! Have fun replaying!")
dead = True
else:
print("Although the room is still too dark to see anything, the cavern feels immense.")
sleep(delay)
print("The cave floor under you feels smoother than the rest of the cave so far.")
print("You place a hand on the wall to ground yourself- In the pitch blackness, you feel you could easily lose yourself.")
sleep(delay*1.33)
print("The wall is angled inward, and is just as smooth as the floor.")
print("You don't particularly feel the space inviting...")
sleep(delay*2)
print("...But you still need to find a way out of here.")
while anti_soft_lock == 0:
choice = input("[Follow wall]/[Venture into dark]/[Retreat through tunnel]")
if choice == "Follow wall":
print("Placeholder text, you follow the wall.")
anti_soft_lock = anti_soft_lock + 1
elif choice == "Venture into dark":
print("Placeholder text, you leave the wall and walk into the inky blackness.")
anti_soft_lock = anti_soft_lock + 1
elif choice == "Retreat through tunnel":
print("Placeholder text. The tunnel is too wide to retreat through without forcing yourself through.")
else:
print("If you're seeing this, you've probably referred to one of our placeholders!")
print("(Or just something that doesn't exist!)")
print("While we intend to flesh these out later, at present it would be detrimental")
print("to assignment deadlines! Speaking of deadlines, this is one! Have fun replaying!")
dead = True
else:
# Neutral choice
print("You're in another part of the cave. It is equally dark, and equally uninteresting. Please get me out of here!")
sleep(delay)
if dead is True:
print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ")
quit()
def team_10_adv():
# jamalie & juem
# Refactored by nashab, stetzera
#https://docs.google.com/document/d/17Yz7-0dx2HY8ysxpR5TYoAwOJzgdK63a0maeYIfQ8hM/edit?usp=sharing
global dead # You'll need this to be able to modify the dead variable
direction = input("There is a river in your path, what would you do to cross the river? (Swim, Make a bridge,etc)")
#this prompts user to pick a direction
sleep(delay)
if direction == "Make a bridge" or direction == "make a bridge":
# this is the best choice!
print("Well done, you have made a wise choice!")
print("Your reward is that you will survive and explore more of the jungle!")
sleep(delay)
elif direction == "Swim" or direction == "swim":
# surprisingly, this is a bad choice!
print("Oh,no!! Just like Goblet of Fire, there are deadly mermaids looking for fresh blood!")
print("You will be dragged down the ocean to be eaten at a feast!")
sleep(delay*3)
print("Now you're in their territory, you see some Gillyweeds just next to where you're trapped!")
sleep(delay*3)
print("You should be careful with eating Gillyweed")
direction = int(input("You have the option to eat between 1-3 strands of Gillyweed, what will you do?"))
if direction <= 2:
# Good idea
print("Good job! Now you have more strength and you can breath under water!")
sleep(delay*3)
print("Fight them and survive!")
elif direction > 2 and direction <= 3:
# this is a bad idea
print("Too much Gillyweed will cause suffocation!")
dead = True
sleep(delay*5)
else:
# We would like the user to use whole number
print("Since you did not choose from the given numbers, your only chance is to fight and survive.")
else:
# this is a neutral choice!
print("Well done for the creativity! You crossed the river!")
sleep(delay*3)
print("But...")
sleep(delay*3)
print("You got injured for the hard work, so you can't move on and you need to rest by the river!")
sleep(delay)
if dead == True:
print("oops.. I guess that's all for you!")
sleep(delay*3)
print("you were not very successful this time")
sleep(delay*3)
print("see you in your next journey")
#This choice kills you
def cullomn_whitfordr(): # Refactored by Team 11
"""
Journey to a house.
https://docs.google.com/document/d/1trPAy_4RAI__kv4UXJYL8SUDABny1Yp-sSZgqdX9sFE/edit?usp=sharing
:return:
Print statements. No return. None.
"""
print()
print("To your left, you notice a house. Curious,... Looking around more, you see a cat behind you.")
print("The cat has seven tails and a missing eye. You ponder for a moment. You feel sleepy.")
sleep(delay * 2)
print()
direction = input("What will you do? [House/Cat/Sleep]")
if direction == "House" or direction == "house":
# bad choice
print("You decide that you need help and make your way towards the house. The path is a bit rocky though...")
sleep(delay)
print("...")
sleep(delay)
print("......")
sleep(delay)
print(".........")
sleep(delay * 2)
print("Oh no! You tripped on a rock! It was so shocking, you die before you hit the ground.")
dead = True
elif direction == "Cat" or direction == "cat":
# neutral choice
print("The cat is just so damn intriguing, you can't help but examine it.")
print("You stretch out your hand, and the cat nuzzles you, its several tails twitching affectionately.")
print("This is nice, but accomplishes nothing.")
sleep(delay)
print()
print("You waste time loving the cat, but nothing gets done.")
sleep(delay)
dead = False
else:
print("You disregard that because you fell asleep.")
sleep(delay * 5)
print("You awake feeling refreshed.")
dead=False
if dead:
print("What a sad way to die.")
quit()
def westth_benningfield():
""" inputs the room we were asked to refactor.
link to our google doc: https://docs.google.com/document/d/11l9OqTJTGxCbiatW3S5czFA036_AvCPBq0RjwNz4eaA/edit?usp=sharing"""
print()
print('An eerie box lays before you, and for some reason you are drawn to it.')
print()
print('As you draw closer you hear a voice in your head...')
print()
print('"In order to receive the treasures of the box you must reveal your deepest and darkest secret"')
choice = input('Will you reveal your secret? [Yes/No]')
if choice == "Yes" or choice == "Y" or choice == "yes":
secret = input('Speak now and reveal the truth.')
print(secret)
print("The box opens and you reach inside to retrieve your treasure...")
sleep(delay)
print()
print('''It's a flower with petals made of fire and a note that says, "It's a me, copyright."''')
sleep(delay)
print()
print('Confused by the note, you take your reward and move on.')
print()
sleep(delay)
elif choice == "No" or choice == "N" or choice == "no":
death = input('Will you open the box? [Yes/No]')
if death == "Yes" or choice == "Y" or choice == "yes":
print('You attempt to open the box but you become consumed by a deadly darkness that envelops your body.')
print()
print('You died. LOL')
revive = input("would You like to restart")
if revive == "Yes" or choice == "Y" or choice == "yes":
riddle = input("What starts with 'e' ends with 'e' and contains one letter? ""[a/an]")
if riddle == "envelope":
print("You live. Good job! However, you don't get the treasure.")
if revive == "No" or choice == "N" or choice == "no":
print("ah its your choice")
quit()
elif death == "No" or choice == "N" or choice == "no":
print('You decide not to open the box.')
print()
print('You feel like you have avoided some mysterious danger but missed out on some sweet loot.')
else:
print("You walk away")
pass
# TODO Add your code here
def team_13_adv():
# tori and jessie
# https://docs.google.com/document/d/1oPzq92-44tG37zoKnEG_hnjtZtgnz1UUe1kYTGTp81A/edit?usp=sharing
print()
print("You find yourself on a cliff. There doesn't seem to be a path down. You chance a glance over the edge")
print("Seems like a long way...")
print()
jump = input("What would you like to do?[jump/stay/parachute]")
if jump == "jump" or jump == "Jump" or jump == "j" or jump == "J" or jump == " jump" or jump == " Jump" or jump == " j" or jump == "J":
# bad choice
print("You fall from the sky and land on your head...")
sleep(delay)
print("Your skull burst open and your brains spread everywhere")
sleep(delay)
print("Your chances of survival are zero.")
sleep(delay * 2)
print("You're dead meat.")
print()
dead = True
if dead is True:
print("You died, but at least you don't have to take 226 anymore. :)")
quit()
elif jump == "parachute" or jump == "Parachute" or jump == "p" or jump == "P" or jump == " parachute" or jump == " Parachute" or jump == " p" or jump == " P":
# good choice
print("You open your parachute at approximately 1000 feet and you avoid injury.")
sleep(delay * 2)
print("Congratulations, you passed your parachute test!")
print()
elif jump == "stay" or jump == "Stay" or jump == "s" or jump == "S" or jump == " stay" or jump == " Stay" or jump == " s" or jump == " S":
print("You decided to stay. The wind is pretty fierce this high up.")
else:
print("What was that?")
print()
def team_14_adv():
"""
Team 14's refactored chapter.
https://docs.google.com/document/d/165eAoj1XNMW9XfruJp3p0qiJc1H9ZdS3PNCT9htqiPQ/edit?usp=sharing
"""
global dead
direction = input("As you enter a new part of the cave you see a ladder in fron of you, you hear water to your right,"
"and see a tunnel to your right. Would you like to Swim, Hike, or Climb?"
"[Swim,Hike,or Climb]")
if direction == "Swim":
print("As you go into the water you see a faint outline of a hole accros from you and you begin to swim towards it.")
print("With your nose almost even with the watter you are able to fit through the hole.")
sleep(delay)
elif direction == "Climb":
print(" When you reach the top of the ladder you come face to face with a demented clown")
print("The clown jumps at you trying to grab you and you slip and fall back down")
sleep(delay)
dead = True
elif direction == "Hike":
print("As you are walking down the new tunnel you hear something large following behind you!"
"You become more and more scared and breakout into a sprint tryig to get away from whatever "
"is following you...")
print("You were not fast enough...")
dead = True
else:
print("Sorry that was not an option please choose again.")
team_14_adv()
if dead == True:
sleep(delay)
print("Oh no! You died. Better luck next time! Try again by hitting the green play button.")
quit()
# TODO Add your code here
def team_15_prattw_vankirkj():
"""
Team 15's refactored chapter.
Originally by stetzera and whitfordr, refactored by prattw and vankirkj.
https://docs.google.com/document/d/15Vn_ovikxYFLnAGB2R_f8-kFiFdRDe6teK0p_NSIZzo/edit?usp=sharing
:return: none
"""
# stetzera and whitfordr
# Refactored by Team 15
global dead
print()
print("A figure emerges from the shadows, hunched and withered. Her single good eye turns to face you -- a witch!")
sleep(delay)
print("Two more eyes blink out of the darkness, the witch's black cat slinking their way out from around the hem of her dress.")
sleep(delay)
# Exposition for the upcoming choices.
choice = input("The witch stares at you, blocking the way forward. What do you do? [Pet the cat/Attack the witch/Run away]")
if choice == "Pet the cat" or choice == "pet the cat":
# Cats always equal best choice.
print("You kneel down, holding out a hand to the cat.")
print("The kitty pads forward, sniffing at you...")
sleep(delay * 5)
print("The little black cat purrs.")
print("With a throaty laugh the witch shuffles to the side, apparently trusting her cat's judgement. You're free to go!")
elif choice == "Attack the witch" or choice == "attack the witch" or choice == "dab":
# What sort of idiot attacks a mysterious woman with a cat? How rude.
# the dab is a special easter egg :D
print("Fearing for your life -- it's a witch, who trusts witches? -- you pull out a dagger from the sheathe at your belt.")
print("With a echoing bellow you rush forward, only to find yourself frozen in place.")
sleep(delay * 2)
print("A hex!")
dead = True
elif choice == "Run away" or choice == "run away":
# Arguably the most rational.
print("Not your circus, not your monkeys.")
print("You just turn around, avoid eye contact and meander back into the darkness of the cave from whence you came.")
else:
# Neutral/indecisive choice.
print("You find yourself full of strange thoughts, pulled backwards into the labyrinth once more.")
sleep(delay * 5)
if dead:
print("Your muscles lock up, which, unfortunately, includes your heart.")
sleep(delay)
print("As your lifeless body falls to the ground, the witch and cat both turn, melting back into the shadows of the cave.")
print("Serves you right for attacking a mostly-defenseless old woman.")
print("Better luck next time! Try again by hitting the green play button.")
quit()
# TODO Add your code here
def dovranovs_adventure():
"""
This code gives user choices when user found a little crying girl and define what is gonna happen if user selects one of the options.
https://docs.google.com/document/d/16R-KA0PvMLgTYy4DjvFSHpCJNWzw6fgGkAn_TYCmlr0/edit?usp=sharing
# Originally by Team 16
# Refactored by Sahet Dovranov
"""
# Beginning description
global dead
print()
print("Deeper in the cave, you hear the sound of someone crying!")
sleep(delay)
print("As you investigate the noise, you discover that it is coming from a little girl in a pink dress.")
sleep(delay)
# Giving choices to user and ask to pick one.
choice = input("She looks up at you tearfully, huddled against the wall. What do you do? [Pick_her_up/Interrogate_her/Back_away_slowly]")
if choice == "Interrogate_her":
# Neutral choice.
print("Frankly you find this to be a bit suspect. What's a little kid doing in some kind of creepy magic cave?")
sleep(delay)
print("You point an accusatory finger at her and ask what her deal is")
print("she immediately stops crying and looks grumpy instead. She sticks her tongue out at you and turns into a bat, flying away")
print("Well. guess you dodged that bullet.")
dead = False
elif choice == "Back_away_slowly":
# Neutral choice.
print("Ok you never signed up to be a childcare service. This is someone else's problem. You turn and leave")
sleep(delay)
print("The little girl looks at you incredulously but doesn't stop you")
dead = False
elif choice == "Pick_her_up":
# Bad choice.
print("Despite your best efforts to calm her, the girl keeps crying. ...but after a moment, her cries begin to change.")
sleep(delay)
print("you realize she is laughing just as sharp fangs pierce your neck. You fall to the ground in surprise")
print("As you look up, you realize that her eyes have turned deep red! Vampire!")
dead = True
else:
# Neutral choice.
print("Before you can decide what to do about the little kid, the ground collapses beneath you")
sleep(delay)
print("You find yourself in a totally different tunnel. A bit startled, but miraculously unhurt.")
dead = False
if dead == True:
print("As your consiousness fades away, her giggles continue.")
print("This is what you get for trying to help kids lost in caves apparently")
print("Better luck next time! Try again by hitting the green play button.")
quit()
def team_17_adv():
pass
# TODO Add your code here
def team_18_adv():
pass
# TODO Add your code here
def team_19_adv():
pass
# TODO Add your code here
def team_20_adv():
pass
# TODO Add your code here
def main():
"""
The main function, where the program starts.
:return: None
"""
user = start_story()
paths = [scott_adventure, places_to_go(), team_2_adv,
team_3_adv, team_4_adv, team_5_adv,
team_6_adv, team_7_adv, team_8_adv,
team_9_adv, team_10_adv, cullomn_whitfordr,
westth_benningfield, team_13_adv, team_14_adv,
team_15_prattw_vankirkj, dovranovs_adventure, team_17_adv,
team_18_adv, team_19_adv, team_20_adv]
random.shuffle(paths) # Shuffles the order of paths, so each adventure is different
for i in range(len(paths)):
paths[i]() # Runs each function in the paths list
end_story(user)
main()
| true |
26be0f6fb3c405cafb11dc0cc6c6ba1494140a29 | Python | han8909227/data-structures | /src/test_graph_1.py | UTF-8 | 8,220 | 3.546875 | 4 | [
"MIT"
] | permissive | """Test for Graph_1."""
import pytest
from graph_1 import Graph
@pytest.fixture(scope='function')
def graph_1():
"""Making one empty graph instance per test."""
return Graph()
@pytest.fixture(scope='function')
def graph_5():
"""Making one graph instance with len of 5 per test."""
g = Graph()
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)
g.add_edge(4, 5)
g.add_edge(5, 6)
return g
@pytest.fixture()
def t_graph():
"""Make a graph for traversal and weights."""
g = Graph()
g.add_edge(1, 2, 5)
g.add_edge(1, 3, 9)
g.add_edge(2, 4, 4)
g.add_edge(2, 5, 2)
g.add_edge(3, 6, 1)
g.add_edge(3, 7)
return g
def test_add_node(graph_1):
"""Test the add_node method."""
for num in range(1, 7):
graph_1.add_node(num)
assert graph_1.nodes() == [1, 2, 3, 4, 5, 6]
def test_add_edge(graph_1):
"""Test adding a edge to the graph."""
g = graph_1
g.add_edge(1, 2)
assert 2 in g.graph[1]
def test_del_node(graph_5):
"""Test if del node method works."""
for num in range(1, 7):
graph_5.del_node(num)
assert graph_5.nodes() == []
def test_when_node_deleted_removed_from_edges(graph_1):
"""Test that after a node is deleted it is removed from edges list."""
g = graph_1
g.add_edge(1, 2)
g.add_edge(1, 3)
g.del_node(1)
assert g.edges() == []
def test_delete_node_from_empty_graph(graph_1):
"""Test key error is raised when no node to delete."""
with pytest.raises(ValueError):
graph_1.del_node(3)
def test_del_edges(graph_1):
"""Test if the del edge method works."""
graph_1.add_edge(1, 2)
graph_1.add_edge(1, 3)
graph_1.del_edge(1, 3)
assert graph_1.edges() == [(1, 2, 0)]
def test_has_node(graph_5):
"""Test if the has_node method works."""
for num in range(1, 6):
assert graph_5.has_node(num)
def test_nodes(graph_1):
"""Test if the node method works."""
graph_1.add_node(200)
graph_1.add_node(300)
assert graph_1.nodes() == [200, 300]
def test_edges(graph_5):
"""Test if the edges method works."""
result = [(1, 2, 0), (2, 3, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0)]
assert graph_5.edges() == result
def test_del_edge_with_val_not_in_graph(graph_5):
"""Test if we can del node not in the graph."""
with pytest.raises(ValueError):
graph_5.del_edge(100, 200)
def test_del_edge_from_no_edge_nodes(graph_5):
"""Test if can delete an edge that doesn't exist."""
with pytest.raises(ValueError):
graph_5.del_edge(1, 6)
def test_neighbors(graph_5):
"""Test if the neighbors methods works."""
assert graph_5.neighbors(1) == {2: 0}
def test_adjacent(graph_5):
"""Test if the adjacent method works."""
assert graph_5.adjacent(1, 2)
def test_adjacent_method_on_not_error(graph_5):
"""Test if key error gets raised if val not in graph."""
with pytest.raises(ValueError):
graph_5.adjacent(200, 300)
def test_bft_no_node_exist(graph_1):
"""Test bft for key error when node doesn't exist."""
with pytest.raises(ValueError):
graph_1.breadth_first_traversal(3)
def test_dft_no_node_exist(graph_1):
"""Test dft for key error when node doesn't exist."""
with pytest.raises(ValueError):
graph_1.depth_first_traversal(3)
def test_bft_returns_proper_path(t_graph):
"""Test bft returns proper path with unique neighbors from start point of 1."""
result = [1, 2, 3, 4, 5, 6, 7]
assert t_graph.breadth_first_traversal(1) == result
def test_bft_returns_proper_path_after_deleting_edge(t_graph):
"""Test bft returns proper path with unique neighbors after deleting edge starting at 1."""
t_graph.del_edge(1, 3)
result = [1, 2, 4, 5]
assert t_graph.breadth_first_traversal(1) == result
def test_bft_returns_proper_path_after_deleting_node(t_graph):
"""Test bft returns proper path with unique neighbors after deleting node starting at 1."""
t_graph.del_node(5)
result = [1, 2, 3, 4, 6, 7]
assert t_graph.breadth_first_traversal(1) == result
def test_bft_returns_proper_path_without_repeating_nodes(t_graph):
"""Test bft returns proper path with non unique neighbors from start point of 1."""
t_graph.add_edge(7, 1)
result = [1, 2, 3, 4, 5, 6, 7]
assert t_graph.breadth_first_traversal(1) == result
def test_bft_returns_only_start_if_no_neighbors(t_graph):
"""Test that only the start node is returned when no neighbors."""
t_graph.add_node(9)
assert t_graph.breadth_first_traversal(9) == [9]
def test_dft_returns_proper_path(t_graph):
"""Test dft returns proper path with unique neighbors starting at 1."""
result = [1, 2, 4, 5, 3, 6, 7]
assert t_graph.depth_first_traversal(1) == result
def test_dft_returns_proper_path_without_repeating_nodes(t_graph):
"""Test dft returns proper path with non unique neighbors from start point of 1."""
t_graph.add_edge(7, 1)
result = [1, 2, 4, 5, 3, 6, 7]
assert t_graph.depth_first_traversal(1) == result
def test_dft_returns_only_start_if_no_neighbors(t_graph):
"""Test that only the start node is returned when no neighbors."""
t_graph.add_node(9)
assert t_graph.depth_first_traversal(9) == [9]
def test_dft_returns_proper_path_after_deleting_edge(t_graph):
"""Test dft returns proper path with unique neighbors after deleting edge starting at 1."""
t_graph.del_edge(1, 3)
result = [1, 2, 4, 5]
assert t_graph.depth_first_traversal(1) == result
def test_dft_returns_proper_path_after_deleting_node(t_graph):
"""Test dft returns proper path with unique neighbors after deleting node starting at 1."""
t_graph.del_node(5)
result = [1, 2, 4, 3, 6, 7]
assert t_graph.depth_first_traversal(1) == result
def test_non_int_entered_for_weight(graph_1):
"""Test that value error is raised when A is weight."""
with pytest.raises(ValueError):
graph_1.add_edge(1, 2, 'A')
def test_non_int_entered_for_weight_next(graph_1):
"""Test that value error is raised when A is weight."""
with pytest.raises(ValueError):
graph_1.add_edge(1, 2, '&')
def test_wieght_defaults_to_zero(graph_1):
"""Test that the defalut wieght is applied to edge."""
graph_1.add_edge(1, 2)
assert graph_1.edges() == [(1, 2, 0)]
def test_added_weight_displayed(graph_1):
"""Test weight is added to edge."""
graph_1.add_edge(1, 2, 10)
assert graph_1.edges() == [(1, 2, 10)]
def test_weight_removed_when_edge_deleted(graph_1):
"""Test that weight is removed after deleting edge."""
graph_1.add_edge(1, 2, 9)
graph_1.del_edge(1, 2)
assert graph_1.edges() == []
def test_weight_removed_when_node_deleted(graph_1):
"""Test that weight is removed after deleting node."""
graph_1.add_edge(1, 2, 9)
graph_1.add_edge(1, 3, 6)
graph_1.del_node(1)
assert graph_1.edges() == []
# def test_dijkstra_with_wrong_node(t_graph):
# """Test dijkstra work properly."""
# with pytest.raises(ValueError):
# t_graph.sp_dijkstra(1, 100)
# def test_bellman_ford_with_wrong_node(t_graph):
# """Test bellman_ford work properly."""
# with pytest.raises(ValueError):
# t_graph.sp_bellman_ford(1, 100)
# def test_dijkstra_find_path(t_graph):
# """Test dijkstra work properly."""
# path = t_graph.sp_dijkstra(1, 4)
# assert path == 9
# def test_bellman_ford_find_path(t_graph):
# """Test bellman_ford work properly."""
# path = t_graph.sp_bellman_ford(1, 4)
# assert path == 9
# def test_dijkstra_find_path_1(t_graph):
# """Test dijkstra work properly."""
# path = t_graph.sp_dijkstra(1, 6)
# assert path == 10
# def test_bellman_ford_find_path_1(t_graph):
# """Test bellman_ford work properly."""
# path = t_graph.sp_bellman_ford(1, 6)
# assert path == 10
# def test_dijkstra_find_path_self(t_graph):
# """Test dijkstra work properly."""
# path = t_graph.sp_dijkstra(1, 1)
# assert path == 0
# def test_bellman_ford_find_path_self(t_graph):
# """Test bellman_ford work properly."""
# path = t_graph.sp_bellman_ford(1, 1)
# assert path == 0
| true |
6d94a187fa3532c4329b573c8da0f527f2dfaa29 | Python | Yuchen-Yan/movie-recommender-anna | /endpoint/api.py | UTF-8 | 13,275 | 2.765625 | 3 | [] | no_license | import difflib
import json
import re
import itertools
import ast
from functools import wraps
import pandas as pd
from flask import Flask
from flask import request
from flask_restplus import Resource, Api
from flask_restplus import abort
from flask_restplus import fields
from flask_restplus import inputs
from flask_restplus import reqparse
pd.options.mode.chained_assignment = None
#reading csv file, assuming we are using the dataset from kaggle
def read_csv(file):
#if the file is tmdb_5000
if file == 'tmdb_5000_movies.csv':
df = pd.read_csv(file)
df = extract_tmdb_5000_Columns(df)
return df
#extracting columns from tmdb 5000 csv file
def extract_tmdb_5000_Columns(df):
df = df[['title','tagline', 'overview',
'release_date', 'popularity', 'genres', 'keywords',
'spoken_languages', 'production_companies', 'production_countries',
'vote_average', 'vote_count']]
#preprocess and renaming variable
df['production_countries'] = df['production_countries'].str.replace('iso_3166_1', 'abbrev')
df['spoken_languages'] = df['spoken_languages'].str.replace('iso_639_1', 'abbrev')
df['spoken_languages'] = df['spoken_languages'].str.replace('", "name":.*},', '"},')
df['spoken_languages'] = df['spoken_languages'].str.replace('", "name":.*}]', '"}]')
df.reset_index()
df.index.name="index"
return df
#Displaying columns with percentage of nulls
def display_percentage_of_nulls(df):
num_of_rows = df.shape[0]
for column in df:
percent = 100 * df[column].isnull().sum() / num_of_rows
print(column, str(percent) + '%')
def isNaN(num):
return num != num
#Query
#By title
def get_movies_by_title(df, title):
return df.loc[df['title'].str.contains(title, flags=re.IGNORECASE)]
def get_movies_by_exact_title(df, title):
return df.loc[df['title'] == title]
#By release date
def get_movies_by_release_date(df, date):
return df.loc[df['release_date'] == date]
#By genre
def get_movies_by_genre(df, genre):
return df[df['genres'].str.contains(genre, flags=re.IGNORECASE)]
#By list of genres (Only movie that satisfy all genres will return)
def get_movies_by_list_of_genres(df, genres):
df1 = df
for g in genres:
df1 = df1[df1['genres'].str.contains(g)]
return df1
#By keyword
def get_movies_by_keyword(df, keyword):
return df[df['keywords'].str.contains(keyword, flags=re.IGNORECASE)]
#By list of keywords
def get_movies_by_list_of_keywords(df, keywords):
df1 = df
for k in keywords:
df1 = df1[df1['keywords'].str.contains(k, flags=re.IGNORECASE)]
return df1
#By language
def get_movies_by_language(df, language, ln):
if len(language) > 2:
#ln = ln[ln['full'].str.contains(language)]
for index, row in ln[ln['full'].str.contains(language)].iterrows():
shortForm = row['abb']
return df[df['spoken_languages'].str.contains('"' + shortForm + '"')]
else:
return df[df['spoken_languages'].str.contains('"' + language + '"')]
#By country
def get_movies_by_country(df, country):
if len(country) > 2:
return df[df['production_countries'].str.contains(country)]
else :
return df[df['production_countries'].str.contains('"' + country + '"')]
#By list of countries
def get_movies_by_list_of_countries(df, countries):
df1 = df
for country in countries:
if len(country) > 2:
df1 = df1[df1['production_countries'].str.contains(country)]
else:
df1 = df1[df1['production_countries'].str.contains('"' + country + '"')]
return df1
#By company
def get_movies_by_company(df, company):
return df[df['production_companies'].str.contains(company)]
def get_movies_by_list_of_companies(df, companies):
df1 = df
for c in companies:
df1 = df1[df1['production_companies'].str.contains(company)]
return df1
def get_ids(ss):
ids = []
dict_list = json.loads(ss)
for d in dict_list:
for key, value in d.items():
if key == 'id':
ids.append(value)
return ids
def get_values(ss):
if isNaN(ss) or ss is None:
return None
values = []
#print(type(ss))
dict_list = json.loads(ss)
#print(type(ss))
for d in dict_list:
for key, value in d.items():
if key == 'name':
values.append(value)
return values
def get_string_match(m1, m2, check_ids=True):
match = 0
curr_movie = get_ids(m1) if check_ids else get_values(m1)
target_movie = get_ids(m2) if check_ids else get_values(m2)
if (check_ids):
for x in target_movie:
for y in curr_movie:
if x == y:
match += 1
else:
for x in target_movie:
for y in curr_movie:
if y.contains(x, flags=re.IGNORECASE):
match += 1
return match
def get_rating_match(m1, m2):
if isNaN(m1) or isNaN(m2):
return 0
curr_rating = int(m1)
target_rating = int(m2)
return curr_rating-target_rating
def get_date_match(m1, m2):
if isNaN(m1) or isNaN(m2):
return 0
curr_year = int(m1[0:4])
target_year = int(m2[0:4])
return curr_year-target_year
def get_popularity_match(m1, m2):
if isNaN(m1) or isNaN(m2):
return 0
curr_popularity = float(m1)
target_popularity = float(m2)
return curr_popularity-target_popularity
def get_correlation_score_in_genre(df, genre, check_ids=True):
df1 = df
df1['genre_match_score'] = df1['genres'].apply(lambda x: get_string_match(x, genre, check_ids))
return df1
def get_correlation_score_in_rating(df, voting_average):
df1 = df
df1['rating_score'] = df1['vote_average'].apply(lambda x: get_rating_match(x, voting_average))
return df1
def get_correlation_score_in_keyword(df, keywords, check_ids=True):
df1 = df
df1['keyword_score'] = df1['keywords'].apply(lambda x: get_string_match(x, keywords, check_ids))
return df1
def get_correlation_score_in_date(df, release_date):
df1 = df
df1['date_score'] = df1['release_date'].apply(lambda x: get_date_match(x, release_date))
return df1
def get_correlation_score_in_popularity(df, popularity):
df1 = df
df1['popularity_score'] = df1['popularity'].apply(lambda x: get_popularity_match(x, popularity))
#print(df1['popularity_score'])
return df1
def get_correlation_score_with_other_movies(df, movie):
genre_correlation = get_correlation_score_in_genre(df, movie['genres'].item())
rating_correlation = get_correlation_score_in_rating(genre_correlation, movie['vote_average'].item())
keyword_correleation = get_correlation_score_in_keyword(rating_correlation, movie['keywords'].item())
popularity_correlation = get_correlation_score_in_popularity(keyword_correleation, movie['popularity'].item())
df1 = get_correlation_score_in_date(popularity_correlation, movie['release_date'].item())
df1['final_correlation'] = (df1['genre_match_score']*5) + df1['rating_score'] + (df1['keyword_score']*5) + (df1['popularity_score']/50)
#print(df.iloc[df1['final_correlation'].sort_values(ascending=False).index].head(10))
return df1
#ADD DATAFRAME TO DB (OPTIONAL)
def add_data_to_db(df, name):
db_name = 'comp9321asst2'
mongo_port = 27017
mongo_host = 'localhost'
client = MongoClient(mongo_host, mongo_port)
db = client[db_name]
c = db[name]
records = json.loads(df.T.to_json()).values()
c.insert(records)
def write_json_obj(df1):
json_str = df1.to_json(orient='index')
ds = json.loads(json_str)
ret = []
for idx in ds:
# print(idx)
movie = ds[idx]
movie['index'] = int(idx)
ret.append(movie)
return ret
###########
#API
###########
app = Flask(__name__)
api = Api(app,
default = "Movies",
title="Movie Dataset",
description="This is the movie recommender Anna")
#movie_model = api.model('Movie', {
# 'Title': fields.String,
# 'Genre': fields.String,
# 'Country': fields.String,
# 'Keyword': fields.String,
# 'Date': fields.String,
# 'Language': fields.String,
# 'Company': fields.String
#})
@api.route('/movies')
class MovieList(Resource):
@api.response(200, 'Successful')
@api.doc(description="Get all movies")
def get(self):
json_str = df.to_json(orient='index')
ds = json.loads(json_str)
ret = []
for idx in ds:
#print(idx)
movie = ds[idx]
movie['index'] = int(idx)
ret.append(movie)
return ret
@api.route('/movies/<string:name>')
@api.param('name', 'The name of movie')
class Movie(Resource):
@api.response(404, 'Movie was not found')
@api.response(200, 'Successful')
@api.doc(description="Get a book by its ID")
def get(self, name):
rdf = get_movies_by_title(df, str(name))
if rdf.empty:
api.abort(404, "Movie {} not found".format(name))
else:
json_str = rdf.to_json(orient='index')
ds = json.loads(json_str)
ret = []
for idx in ds:
#print(idx)
movie = ds[idx]
movie['index'] = int(idx)
ret.append(movie)
return ret
#@api.response(201, 'Movie Added Successfully')
#@api.response(400, 'Validation Error')
#@api.doc(description="Add a new movie")
#def post(self):
# pass
@api.route('/movie-recommendation')
@api.param('name', 'The name of movie the person likes, the recommendation would be different to this movie')
@api.param('rating', 'Minimum rating of the movie the person would want to see in the recommendation')
@api.param('year', 'Minimum year of the release year of the movie')
@api.param('genre', 'Genre of the movie the person would like')
class MovieRecommendation(Resource):
@api.response(200, 'Successful')
@api.doc(description="Get a book by its ID")
def get(self):
name = request.args.get('name', None)
rating = request.args.get('rating', None)
year = request.args.get('year', None)
genre = request.args.get('genre', None)
print("NAME = ", name)
print("RATING = ", rating)
print("GENRE = ", genre)
print("YEAR = ", year)
final_df = pd.DataFrame()
# By Movie Name
if name is not None:
movies = get_movies_by_title(df, str(name))
closest_matches = difflib.get_close_matches(str(name), movies['title'], cutoff=0.1)
closest_match = ''
if len(closest_matches) > 1:
closest_match = closest_matches[0]
else:
pass
# No match, just choose random
movie = get_movies_by_exact_title(df, str(closest_match))
if movie.empty:
api.abort(404, "Movie {} not found".format(name))
df1 = get_correlation_score_with_other_movies(df, movie).head(10)
final_df = df1
# By Genre
if genre is not None:
print("In Genre")
genres = []
for curr_genre in df['genres']:
genres.append(get_values(curr_genre))
pass
unique_genres = set(list(itertools.chain.from_iterable(genres)))
closest_matches = difflib.get_close_matches(str(genre), unique_genres, cutoff=0.1)
#print(closest_matches)
if len(closest_matches) > 1:
closest_match = closest_matches[0]
else:
api.abort(404, "Genre {} not found in movies".format(genre))
pass
df2 = get_movies_by_genre(df, closest_match)
#print(df2.sort_values(['popularity'], ascending=False).head(10))
if final_df.empty:
final_df = df2
else:
final_df.append(df2)
# By Rating
if rating is not None:
print('In Rating')
df3 = df[(df['vote_average'] >= float(rating)-1) & (df['vote_average'] <= float(rating)+1)].sort_values(['popularity'], ascending=False).head(10)
if final_df.empty:
final_df = df3
else:
final_df.append(df3)
# By Year
if year is not None:
print('IN YEAR')
df4 = df
df4['date_match'] = df4['release_date'].apply(lambda x: get_date_match(x, year))
df4 = df.iloc[df4[(df4['date_match'] >= -1) & (df4['date_match'] <= 1)].sort_values(['popularity'], ascending=False).index].head(10)
#print(df4)
if final_df.empty:
final_df = df4
else:
final_df.append(df4)
final_df = final_df.sort_values(['popularity', 'vote_average'], ascending=False).head(10)
print(final_df)
return write_json_obj(final_df)
if __name__ == "__main__":
csv_file = "tmdb_5000_movies.csv"
df = read_csv(csv_file)
#dict of language abbrevation and its long form
ln = pd.read_csv("languages.csv")
app.run(debug=True) | true |
20d6a7a57ef3db70b48986750eac1bd298b6945d | Python | hebe3456/algorithm010 | /Week01/9.回文数.py | UTF-8 | 640 | 3.78125 | 4 | [] | no_license | #
# @lc app=leetcode.cn id=9 lang=python3
#
# [9] 回文数
#
# @lc code=start
class Solution:
def isPalindrome(self, x: int) -> bool:
# 暴力法:
# 如果是负数,return False
# 如果是正数,列表或字符串切片
# str:80ms, 80.33%
# list:100ms, 35.03%
if x < 0: return False
if len(str(x)) < 2: return True
return str(x) == str(x)[::-1]
# return list(str(x)) == list(str(x))[::-1]
s = Solution()
print(s.isPalindrome(-234))
print(s.isPalindrome(0))
print(s.isPalindrome(3))
print(s.isPalindrome(1328))
print(s.isPalindrome(3443))
# @lc code=end
| true |
11c2d514eb3e354b938c9968ca74496bd5ebb6b8 | Python | TheVinhLee/Python | /learning/Advanced_Python/Functions/variable_argument_lists_start.py | UTF-8 | 831 | 4.28125 | 4 | [] | no_license | # Demonstrate the use of variable argument lists
# TODO: define a function that takes variable arguments
def addition(*args):
"""
addition(*args) : sum of all input argument with unknown number of arguments
and it is only has 1 list param rather than (base, *args)
if (base, *args), first param will be missing because it is replace by 'base'
:param args: list of arguments
:return: sum of arg
"""
result = 0
for arg in args:
result += arg
return result
def main():
# TODO: pass different arguments
print(addition(5, 10, 15, 20))
print(addition(25, 10))
# TODO: pass an existing list
myNums = [5, 10, 14, 12]
print(addition(*myNums))
"""
*myNums: we have addition(*arg) hence we need *arg as param
"""
if __name__ == '__main__':
main() | true |
226b16c46edad14f9b24a357a7e58b3a23e827b1 | Python | musabbirsaeed/usaspending | /analysis2020Oct18-2.py | UTF-8 | 1,721 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 12:37:00 2020
@author: Mohammed kamal
[Read the csv files from /data/backups/.spyder-py3/data_noflt/*.csv
and create table name ends withh _Cnt and append for all agencies]
1. Populate “allagency1” table based on allaward and filteredaward
2. Populate “vendors1” table based on
"""
import pandas as pd
import setuprefvar as st
import linuxpostgres_cred as creds
import sqlstmnts as sqst
from sqlalchemy import create_engine
conn_string = "postgresql://"+creds.PGUSER+":"+creds.PGPASSWORD+"@"+creds.PGHOST+":"+creds.PORT+"/"+creds.PGDATABASE
engine = create_engine(conn_string)
agency_year = st.years
agency_abb = st.agencyabb
agency_code = st.agencycode
for m in range(len(agency_abb)):
table_name = 'allagency1'
agencyabb=[agency_abb[m]]
sqlstmt = sqst.sqlst13.format(agency_abb[m])
df = pd.read_sql_query(sqlstmt, engine)
sqlstmt = sqst.sqlst14.format(agency_abb[m])
df1 = pd.read_sql_query(sqlstmt, engine)
df['allaward'] = df1['allaward']
df['allawardtotal'] = df1['allawardtotal']
df['filteredaward'] = df1['filteredaward']
df['filteredawardtotal'] = df1['filteredawardtotal']
for i in range(10):
agencyabb.append(agency_abb[m])
df['agency_abb'] = agencyabb
df.to_sql(table_name, engine, if_exists='append')
table_name = 'vendors1'
for m in range(len(agency_abb)):
sqlst = sqst.sqlst6.format(agency_abb[m])
df = pd.read_sql_query(sqlst, engine)
df[df.columns[1]] = df[df.columns[1]].replace('[\$,]', '', regex=True).astype(float)
df['agency_abb'] = agency_abb[m]
df['index'] = m
df.to_sql(table_name, engine, if_exists='append') | true |
428c39601b2c3827808e7cc46fe54ad144cdb001 | Python | ys0823/python-100examples | /100 examples/93.py | UTF-8 | 623 | 3.09375 | 3 | [] | no_license | #---------------------------------------------------
#题目:使用python把每隔一分钟访问200次的IP,加到黑名单。
#要求:每隔一分钟读区一下日志文件,把统计到的Ip添加到黑名单。
#2018-9-4
#---------------------------------------------------
import time
pin = 0
while True:
ips = []
fr = open(r'kms10.log')
fr.seek(pin)
for line in fr:
ip = line.split()[0]
ips.append(ip)
new_ips = set(ips)
for new_ip in new_ips:
if ips.count(new_ips):
print('加入黑名单的ip是:%s'%new_ip)
pin = fr.tell()
time.sleep(60)
| true |
1feaf761a25db9a5dbc2ce509510dd2fac97bd50 | Python | GG-yuki/bugs | /python/ijcai_spider/test.py | UTF-8 | 264 | 3.078125 | 3 | [] | no_license | import re
with open("test_links.txt", "r") as f: # 打开文件读取信息
for line in f.readlines():
# line = line.strip('\n') # 去掉列表中每一个元素的换行符
print(re.findall(r'https://www.google.com/search\?q=(.*)', line)[0]) | true |
0ca355e41e70b8419c2056d93f49be00af3b731c | Python | xb-chang/SCT | /src/SCT/models/fs_model.py | UTF-8 | 959 | 2.84375 | 3 | [] | no_license | import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
from yacs.config import CfgNode
class Fs(nn.Module):
"""
Fs(Z)
"""
# noinspection PyPep8Naming
def forward(self, Z: Tensor, T: int) -> Tensor:
"""
Predicts the temporal action probabilities S using the intermediate representation Z
:param Z: intermediate representation [1 x D' x T']
:param T: input video X temporal length [1]
:return: S [1 x C x T]
"""
raise NotImplementedError
class Conv(Fs):
def __init__(self, cfg: CfgNode, num_classes):
super().__init__()
self.cfg = cfg
self.classifier = nn.Conv1d(self.cfg.model.fs.hidden_size, num_classes, 1)
# noinspection PyPep8Naming
def forward(self, Z: Tensor, T: int) -> Tensor:
out = self.classifier(Z) # [1 x C x T']
out = F.interpolate(out, T) # [1 x C x T]
return out # [1 x C x T]
| true |
79dd49e554c6f8b9f98c2cd117ea470486038f89 | Python | MarkErickson02/Reddit-Submission-Stream | /PRAW_Stream_Bot.py | UTF-8 | 4,758 | 2.828125 | 3 | [] | no_license | from praw.exceptions import PRAWException
import DictionaryUtility
import UserStatistics
import config
import praw
import time
class StreamBot:
def __init__(self):
self._utility = DictionaryUtility.DictionaryUtility()
self._user_stats = UserStatistics.UserStatistics()
self._reddit = None
self.authenticate()
self._posts = {}
def authenticate(self):
reddit = praw.Reddit(client_id=config.client_id,
client_secret=config.client_secret,
user_agent=config.user_agent,
username=config.username,
password=config.password
)
self._reddit = reddit
def check_background_of_user(self):
username = input("Search User: ")
reddit_user = self._reddit.redditor(username)
posts_dict = self._user_stats.check_user_submissions(reddit_user)
comment_dict = self._user_stats.check_user_comments(reddit_user)
# Merges the two dictionaries
combined = {**posts_dict, **comment_dict}
self._utility.sort_and_print_dict(combined, len(combined))
def check_user_words(self):
username = input("Search User: ")
reddit_user = self._reddit.redditor(username)
self._utility.print_word_freq_dict(self._user_stats.find_users_words(reddit_user))
def check_background_of_posters(self, submission_id):
start_timer = time.clock()
user_submission_frequency = []
submission = self._reddit.submission(submission_id)
user_submission_frequency.append(self._user_stats.check_user_submissions(submission.author))
end_timer = time.clock()
submission.comments.replace_more(limit=0)
print("Fetch and replace comments time: ", end_timer - start_timer)
comments = submission.comments.list()
for comment in comments:
if comment.author is None:
continue
user_submission_frequency.append(self._user_stats.check_user_submissions(comment.author))
end_timer = time.clock()
print("put comments in dictionary time: ", end_timer - start_timer)
combined_submission_dict = {}
for user_dict in user_submission_frequency:
combined_submission_dict.update(user_dict)
end_timer = time.clock()
print("Combining dictionaries time: ", end_timer - start_timer)
self._utility.sort_and_print_dict(combined_submission_dict, limit=len(combined_submission_dict))
def monitor_subreddit(self, included_nsfw=True, show_stream=True):
start_timer = time.clock()
subreddit = self._reddit.subreddit('all')
for submissions in subreddit.stream.submissions():
try:
if submissions.author is None:
print(submissions.title)
if submissions.subreddit is None:
print("Subreddit not found")
else:
if included_nsfw is False and submissions.over_18:
print("censored")
continue
if show_stream is True:
print(submissions.author, " submitted ", submissions.title, " to ", submissions.subreddit)
self._user_stats.check_user_submissions(submissions.author)
self.add_posts_to_dictionary(submissions.subreddit, start_timer)
except PRAWException as err:
print("Error detected: ", err)
def choose_next_action(self):
user_action = input("Press g to graph, s to stream more data, p to print data, b to stream in background: ")
user_action.lower()
if user_action == 'g':
self._utility.bar_graph_total_submission(self._posts)
if user_action == 's':
self.monitor_subreddit()
if user_action == 'p':
self._utility.sort_and_print_dict(len(self._posts))
if user_action == 'b':
self.monitor_subreddit(show_stream=False)
else:
print("Value not recognized")
def add_posts_to_dictionary(self, subreddit, start_timer):
if not (self._posts.get(subreddit)):
self._posts[subreddit] = 1
else:
self._posts[subreddit] += 1
end_timer = time.clock()
self._utility.sort_and_print_dict(self._posts)
print(end_timer - start_timer)
def main():
bot = StreamBot()
# sub_id = input("Enter id of submission: ")
# bot.check_background_of_posters(sub_id)
# bot.choose_next_action()
# bot.check_background_of_user()
bot.check_user_words()
if __name__ == "__main__":
main()
| true |
7b11fa584de0e712694706759da3f2dd73740853 | Python | scxr/eco-dcbot | /cogs/rain.py | UTF-8 | 1,741 | 2.84375 | 3 | [] | no_license | from discord.ext import commands
import random, json, discord
class Rain(commands.Cog):
"""Rain is a cog for the bot to make it rain."""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.guild)
async def rain(self, ctx):
channel = ctx.channel
lastAuthors = []
with open("creds.json") as f:
data = json.load(f)
try:
if data[str(ctx.author.id)] < 350:
await ctx.send("You must have at least 350 pts to make it rain")
except:
pass
async for msg in channel.history(limit=200):
if msg.author not in lastAuthors and msg.author != ctx.author:
lastAuthors.append(msg.author)
if len(lastAuthors) == 10:
break
msg = [author.mention for author in lastAuthors]
amnt = random.randint(100,350)
each_person = amnt/len(lastAuthors)
await channel.send(f"Made it rain {amnt} points " + ', '.join(msg))
data[str(ctx.author.id)] -= amnt
for person in lastAuthors:
if str(person.id) in data.keys():
data[str(person.id)] += each_person
else:
data[str(person.id)] = each_person
with open("creds.json", "w") as f:
json.dump(data, f)
@rain.error
async def command_name_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0xF00000)
await ctx.send(embed=em)
def setup(bot):
bot.add_cog(Rain(bot)) | true |
adff3cb191a4a471eab05421921e1d68254a69b6 | Python | sbavington/Graphing | /JmeterPerfmonGraphs.py | UTF-8 | 2,261 | 2.515625 | 3 | [] | no_license | from matplotlib import pyplot as plt
from matplotlib import style
import datetime
data_noopt = open("./NoOpt.csv", "r")
data_t4 = open("./Opt.csv", "r")
data_crypt = open("./Crypt.csv", "r")
cpu_percent_noopt = []
cpu_percent_t4 = []
cpu_percent_crypt = []
mem_noopt = []
mem_t4 = []
mem_crypt = []
for line in data_noopt.readlines():
line = line.strip()
line = line.split(';')
this_cpu = (float(line[1]))
print('>>{}'.format(line[2]))
this_mem = (float(line[2]))
print(type(this_cpu),this_cpu)
print(type(this_mem),this_mem)
cpu_percent_noopt.append(this_cpu)
mem_noopt.append(this_mem)
for line in data_t4.readlines():
line = line.strip()
line = line.split(';')
this_cpu = (float(line[1]))
this_mem = (float(line[2]))
print(type(this_cpu),this_cpu)
print(type(this_mem),this_mem)
cpu_percent_t4.append(this_cpu)
mem_t4.append(this_mem)
for line in data_crypt.readlines():
line = line.strip()
line = line.split(';')
this_cpu = (float(line[1]))
this_mem = (float(line[2]))
print(type(this_cpu),this_cpu)
print(type(this_mem),this_mem)
cpu_percent_crypt.append(this_cpu)
mem_crypt.append(this_mem)
print (cpu_percent_noopt)
print (cpu_percent_t4)
print (cpu_percent_crypt)
style.use('ggplot')
ticks = 1017
x = range(1,ticks)
fig, ax1 = plt.subplots(figsize=(20, 7))
color1 = 'tab:red'
color2 = 'tab:blue'
color3 = 'tab:green'
ax1.plot(cpu_percent_noopt,linewidth=1)
ax1.plot(cpu_percent_t4,linewidth=1)
ax1.plot(cpu_percent_crypt,linewidth=1,linestyle='--')
ax1.tick_params(axis='y', labelcolor=color1)
plt.title('JMETER CPU Percent {}'.format(datetime.datetime.now()))
ax1.set_ylabel('CPU%')
ax1.set_xlabel('Ticks')
ax1.legend(['CPU NoOpt','CPU T4','CPU Crypt'],loc=3)
fig.tight_layout()
plt.show()
fig, ax1 = plt.subplots(figsize=(20, 7))
color1 = 'tab:red'
color2 = 'tab:blue'
color3 = 'tab:green'
ax1.plot(mem_noopt,linewidth=1)
ax1.plot(mem_t4,linewidth=1)
ax1.plot(mem_crypt,linewidth=1,linestyle='--')
ax1.tick_params(axis='y', labelcolor=color1)
plt.title('JMETER Mem Percent {}'.format(datetime.datetime.now()))
ax1.set_ylabel('Mem%')
ax1.set_xlabel('Ticks')
ax1.legend(['Mem NoOpt','Mem T4','Mem Crypt'],loc=3)
fig.tight_layout()
plt.show()
| true |
2f9979c9c223cf53e18bb3a613e91b0d76afc127 | Python | Yhatoh/ProgramacionCompetitivaUSM | /soluciones/RPC/2020-6/E_Auteams.py | UTF-8 | 824 | 3.296875 | 3 | [
"MIT"
] | permissive | rima=input().strip().split()
n=int(input())
niños=[]
equipo1=[]
equipo2=[]
for i in range (0,n):
temp=input()
niños.append(temp)
while (len(niños)>0):
if len(niños)>n//2:
if(len(rima)<=len(niños)):
equipo1.append(niños[len(rima)-1])
niños.pop(len(rima)-1)
else:
equipo1.append(niños[(len(niños)%len(rima))-1])
niños.pop((len(niños)%len(rima))-1)
else:
if(len(rima)<=len(niños)):
equipo2.append(niños[len(rima)-1])
niños.pop(len(rima)-1)
else:
equipo2.append(niños[(len(niños)%len(rima))-1])
niños.pop((len(niños)%len(rima))-1)
print(len(equipo1))
for n1 in equipo1:
print(n1)
print(len(equipo2))
for n2 in equipo2:
print(n2) | true |
21d92cf2e0027b977d30c7f7af3383d0331e1ed0 | Python | baejinsoo/TIL | /4th/파이썬/python_programming_stu/Practice/prac_2.py | UTF-8 | 577 | 4 | 4 | [] | no_license | # # 일반적인 함수 정의
# def add(x, y):
# return x + y
#
#
# print(add(10, 20))
#
# # 람다식 사용
# my_add = lambda x, y: x + y
# print(my_add(10, 34))
#
# square = lambda x: x ** 2
# print(square(4))
#
# multi = lambda x, y: x * y
# print(multi(40, 3))
#
# division = lambda x, y: x / y
# print(division(50, 5))
my_arr = [1, 2, 3, 4, 5]
my_arr2 = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, my_arr)
print(list(result))
result = list(map(lambda x: x * 2, my_arr))
print(result)
result = list(map(lambda x, y: (x + y) * 6, my_arr, my_arr2))
print(result)
| true |
cb91e549164dc95e60134918b70a3fc4fe3a3ab0 | Python | PieterVDMerwe/Project | /Project/Code/untitled0.py | UTF-8 | 314 | 2.5625 | 3 | [] | no_license | import scipy.integrate as scii
import scipy.constants as scic
import math as mt
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as scio
from scipy.special import hyp2f1
def f(x):
return 1.0*x - 1.0/x;
x = np.arange(0.0,10.0,0.001);
plt.plot(x,f(x));
plt.ylim(-30.0,30.0);
plt.show(); | true |
a9f8c00c778ed0e92b6abf7dbeeb1135e3424603 | Python | amirocha/doktorat | /uv/serpens/profiles/divide_fluxes.py | UTF-8 | 3,916 | 2.828125 | 3 | [] | no_license | '''Divide fluxes (total/wings)'''
def read_data():
total = []
wings = []
file1 = open('fluxes_profiles_wings.txt','r')
lines = file1.readlines()
for i in range(1,len(lines)):
if i%3 == 1:
total.append(float(lines[i].split()[3]))
elif i%3 == 2:
wing = float(lines[i].split()[3])
else:
wings.append(float(lines[i].split()[3])+wing)
file1.close()
return total, wings
def divide_lists_into_molecules(total, wings):
cn_tot = []
cn_wing = []
hcn_tot = []
hcn_wing = []
cs_tot = []
cs_wing = []
co_tot = []
co_wing = []
h13cn_tot = []
h13cn_wing = []
c34s_tot = []
h13cn21_tot = []
for i in range(len(total)):
if i<15:
cn_tot.append(total[i])
cn_wing.append(wings[i])
elif i>=15 and i<30:
hcn_tot.append(total[i])
hcn_wing.append(wings[i])
elif i>=30 and i<45:
h13cn_tot.append(total[i])
h13cn_wing.append(wings[i])
elif i>=45 and i<60:
h13cn21_tot.append(total[i])
elif i>=60 and i<75:
cs_tot.append(total[i])
cs_wing.append(wings[i])
elif i>=75 and i<90:
c34s_tot.append(total[i])
elif i>=90 and i<105:
co_tot.append(total[i])
co_wing.append(wings[i])
return cn_tot, cn_wing, hcn_tot, hcn_wing, cs_tot, cs_wing, co_tot, co_wing, h13cn_tot, h13cn_wing, c34s_tot, h13cn21_tot
def main():
sources=['smm1', 'smm2', 'smm3', 'smm4', 'smm5', 'smm6', 'smm8', 'smm9', 'smm10', 'smm12', 'pos1', 'pos2', 'pos3', 'pos4', 'pos5']
file2=open('fluxes_ratio.txt','w')
file2.write('Protostar Molecules Flux_ratio\n')
total, wings = read_data()
cn_tot, cn_wing, hcn_tot, hcn_wing, cs_tot, cs_wing, co_tot, co_wing, h13cn_tot, h13cn_wing, c34s_tot, h13cn21_tot = divide_lists_into_molecules(total, wings)
for i in range(len(sources)):
file2.write("%s %s %f\n" % (sources[i], 'CN/HCN_tot', cn_tot[i]/hcn_tot[i]))
file2.write("%s %s %f\n" % (sources[i], 'CN/HCN_wings', cn_wing[i]/hcn_wing[i]))
if co_tot[i] != 0:
file2.write("%s %s %f\n" % (sources[i], 'CS/CO_tot', cs_tot[i]/co_tot[i]))
file2.write("%s %s %f\n" % (sources[i], 'CS/CO_wings', cs_wing[i]/co_wing[i]))
file2.write("%s %s %f\n" % (sources[i], 'HCN/CO_tot', hcn_tot[i]/co_tot[i]))
file2.write("%s %s %f\n" % (sources[i], 'HCN/CO_wings', hcn_wing[i]/co_wing[i]))
file2.write("%s %s %f\n" % (sources[i], 'HCN/H13CN_tot', hcn_tot[i]/h13cn_tot[i]))
if h13cn_wing[i] != 0:
file2.write("%s %s %f\n" % (sources[i], 'HCN/H13CN_wings', hcn_wing[i]/h13cn_wing[i]))
file2.write("%s %s %f\n" % (sources[i], 'CS/C34S_tot', cs_tot[i]/c34s_tot[i]))
if h13cn21_tot[i] != 0:
file2.write("%s %s %f\n" % (sources[i], 'H13CN10/H13CN21_tot', h13cn_tot[i]/h13cn21_tot[i]))
file2.close()
file3=open('Profiles_wings_ratio.txt','w')
file3.write('Protostar Molecule Profile/wings \n')
for i in range(len(sources)):
file3.write("%s %s %f\n" % (sources[i], 'CN', cn_tot[i]/cn_wing[i]))
file3.write("%s %s %f\n" % (sources[i], 'HCN', hcn_tot[i]/hcn_wing[i]))
if co_tot[i] != 0:
file3.write("%s %s %f\n" % (sources[i], 'CO', co_tot[i]/co_wing[i]))
if h13cn_wing[i] != 0:
file3.write("%s %s %f\n" % (sources[i], 'H13CN', h13cn_tot[i]/h13cn_wing[i]))
file3.write("%s %s %f\n" % (sources[i], 'CS', cs_tot[i]/cs_wing[i]))
file3.close()
file3=open('Profiles_wings_percent.txt','w')
file3.write('Protostar Molecule Profile/wings \n')
for i in range(len(sources)):
file3.write("%s %s %f\n" % (sources[i], 'CN', cn_wing[i]*100/cn_tot[i]))
file3.write("%s %s %f\n" % (sources[i], 'HCN', 100*hcn_wing[i]/hcn_tot[i]))
if co_tot[i] != 0:
file3.write("%s %s %f\n" % (sources[i], 'CO', 100*co_wing[i]/co_tot[i]))
if h13cn_wing[i] != 0:
file3.write("%s %s %f\n" % (sources[i], 'H13CN', 100*h13cn_wing[i]/h13cn_tot[i]))
file3.write("%s %s %f\n" % (sources[i], 'CS', 100*cs_wing[i]/cs_tot[i]))
file3.close()
if __name__ == '__main__':
main()
| true |
c25d8314c067ed17bd3201837e5b7966408062a7 | Python | KylinHuang7/Account | /bin/add_type.py | UTF-8 | 879 | 2.75 | 3 | [] | no_license | #!/usr/local/bin/python2.6
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import sys
import MySQLdb
def showhelp():
print("Usage: $0 type")
def add_type(title):
conn = MySQLdb.connect(read_default_file='/var/www/accounts/conf/my.cnf', read_default_group="mysql")
cursor = conn.cursor()
cursor.execute("SELECT * FROM type WHERE title = %s", (title, ))
count = len(cursor.fetchall())
if count > 0:
print("type {0} already exist.".format(title))
return False
else:
cursor.execute("""INSERT INTO type(title) VALUES(%s)""", (title, ))
conn.commit()
cursor.close()
print("successful.")
return True
if __name__ == '__main__':
if (len(sys.argv) != 2):
showhelp()
else:
title = sys.argv[1]
if add_type(title):
exit(0)
exit(1)
| true |
29aae9a2e1e53d6e699498af333af569020390ce | Python | exmakhina/xm_rst | /xm_rst_log.py | UTF-8 | 3,045 | 2.515625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 vi:noet
# Log writing utilities
import sys, os, io, subprocess, time, datetime, uuid, hashlib, base64, struct, binascii
def printf(x):
sys.stdout.write(x)
sys.stdout.flush()
def log_echo(txt):
cmd = "xclip -selection clipboard".split()
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
proc.stdin.write(txt.encode("utf-8"))
proc.stdin.close()
res = proc.wait()
assert res == 0
print(txt)
def log_node():
h = hashlib.md5()
try:
import pwd
uid = os.getuid()
name = pwd.getpwuid(uid).pw_gecos
if sys.hexversion < 0x03000000 and isinstance(name, bytes):
name = name.decode("utf-8")
except ImportError:
name = "unknown"
h.update(name.encode("utf-8"))
d = h.digest()
return d
def log_uuid(node=None):
if node is None:
node = log_node()[:6]
node = sum(ord(c) << (i * 8) for i, c in enumerate(node[::-1]))
guid = uuid.uuid1(node=node)
s = "%s" % guid
return s
def log_nuuid(node=None):
"""
Non-universally-unique identifier:
- Space/time encoding
- Compact (12 chars)
- Legible (RFC 4648 Base32 alphabet)
"""
if node is None:
node = log_node()[:3]
t0 = datetime.datetime(year=2012, month=1, day=1)
t1 = datetime.datetime.now()
dt = t1 - t0
dt = int(round(dt.total_seconds()*10))
dts = struct.pack(">I", dt)
#print(binascii.hexlify(dts))
#print(binascii.hexlify(node))
s = dts + node
s = base64.b32encode(s)[:-4]
return s.decode()
def log_admonition(a, **kw):
s = ".. admonition:: {}\n".format(a)
for k, v in kw.items():
s += " :{}: {}\n".format(k, v)
s += "\n "
return s
def log_requirement():
x = log_uuid()
return log_admonition("Requirement :reqid:`%s`" % x)
def log_requirement2():
x = log_nuuid()
return log_admonition("Requirement :reqid:`%s`" % x, **{
"class": "requirement",
"name": x,
},
)
def log_req(name="Requirement"):
x = log_nuuid()
return "%s [%s]:" % (name, x)
def log_heading(decorator, title):
underline = len(title) * decorator
return "\n%s\n%s\n\n" % (title, underline)
def log_date_header(when=None):
when = when or datetime.datetime.now()
return log_heading("=", when.strftime("%Y-%m-%d (%a)"))
def log_timestamp(when=None):
when = when or datetime.datetime.now()
return when.strftime("%Y-%m-%dT%H:%M:%S")
def log_ts(when=None):
when = when or datetime.datetime.now()
return ":time:`%s`" % when.strftime("%H:%M:%S")
def log_day(when=None):
return "".join([
log_date_header(when=when),
"\n",
log_admonition("TODO"),
"- TODO\n\n",
log_admonition("Done"),
"- TODO\n\n"
])
def log_day_consulting(when=None, name=None):
if name is None:
import getpass
name = getpass.getuser()
return "".join([
"\n\n",
".. raw:: latex\n",
"\n",
" \\newpage\n",
log_date_header(when=when),
"\n",
log_admonition("TODO"),
"- TODO\n\n",
log_admonition("Hours - %s" % name),
"- TODO\n\n",
log_admonition("Done"),
"- TODO\n\n",
":Worked: - %s: TODO\n\n" % name,
log_heading("+", "The Plan"),
"TODO\n\n",
log_heading("+", "WIP Notes"),
"TODO\n\n",
])
| true |
14942cd28af655814c60542f51cf8274f79f36d0 | Python | beebopkim/spartan_algorithm | /week_2/homework/02_is_available_to_order.py | UTF-8 | 394 | 3.484375 | 3 | [] | no_license | shop_menus = ["만두", "떡볶이", "오뎅", "사이다", "콜라"]
shop_orders = ["오뎅", "콜라", "만두"]
def is_available_to_order(menus, orders):
order_possible = True
for order in orders:
if not (order in menus):
order_possible = False
break
return order_possible
result = is_available_to_order(shop_menus, shop_orders)
print(result) | true |
85ed991610112e3c1f9a6f4cf6407caa8cf42d8e | Python | amezysk/aoc2020 | /day6.py | UTF-8 | 344 | 2.875 | 3 | [] | no_license | #!/usr/bin/env python3
lines=[]
with open('tmp') as f:
lines = f.readlines()
first=1
total=0
for l in lines:
if first==1:
q=set(l)
first=0
elif l!="\n":
q=q.intersection(set(l))
else:
q.discard("\n")
first=1
total=total+len(q)
q.clear()
total=total+len(q)
print(total) | true |
3c7e6f534e16befa1c3344718e1e4ffadc36c97e | Python | fredrb/advent-of-code-2020 | /23/part1.py | UTF-8 | 2,295 | 3.46875 | 3 | [] | no_license | example = [3, 8, 9, 1, 2, 5, 4, 6, 7]
puzzle = [9, 2, 5, 1, 7, 6, 8, 3, 4]
class Node():
def __init__(self, value, n=None):
self.next = n
self.value = value
class CircularLinkedList():
def __init__(self, initializer):
self.head = Node(initializer[0], None)
cn = self.head
for v in reversed(initializer[1:]):
cn = Node(v, cn)
self.head.next = cn
def append(self, triplet, after=0):
c = self.find(after)
if not c:
return None
cn = c.next
for v in reversed(triplet):
cn = Node(v, cn)
c.next = cn
return True
def remove_after(self, node):
removed = []
root = node
node = node.next
for _ in range(0, 3):
if node == self.head:
self.head = root
removed.append(node.value)
node = node.next
root.next = node
return removed
def get_index(self, i):
n = self.head
for _ in range(0, i):
n = n.next
return n
def find(self, value):
n = self.head
while True:
if n.value == value:
return n
else:
n = n.next
if n == self.head:
return None
def next_from(self, i):
return self.find(i).next
def get_array_from(self, v):
n = self.find(v)
if n is None:
print("FIND FAILED FOR V %s" % v)
start = n
v = []
while True:
v.append(n.value)
n = n.next
if n.value == start.value:
return v
cl = CircularLinkedList(puzzle)
n = None
for i in range(1, 101):
print("-- move %s --" % i)
print("cups: %s" % cl.get_array_from(cl.head.value))
if not n:
n = cl.head
else:
n = n.next
print(" %s" % n.value)
pick = cl.remove_after(n)
print("pick up: %s" % pick)
destination = n.value - 1
if destination == 0:
destination = 9
while destination in pick:
destination -= 1
if destination == 0:
destination = 9
print("destination: %s" % destination)
r = cl.append(pick, destination)
if not r:
print("Failed to append")
print("")
print(''.join([str(i) for i in cl.get_array_from(1)[1:]]))
# print("cups: %s" % )
# def gc(cups, i):
# return cups[i % len(cups)]
# def round(cups, p):
# n = gc(cups, p)
# picked = [gc(cups, p+1), gc(cups, p+2), gc(cups, p+3)]
# list(filter(lambda c: c not in picked, cups))
| true |
118808d89269f85d8c6586a58d1ee5e74320ed37 | Python | ferpoletto/Estudos-Python | /CursoEmVideo/ex053 - Palindromos.py | UTF-8 | 443 | 3.75 | 4 | [] | no_license | frase = input("Digite uma frase: ").strip().upper()
print(f'Você digitou a frase {frase}')
palavras = frase.split()
print(palavras)
semespaco = ''.join(palavras)
print(semespaco)
inverso = ''
for i in range(len(semespaco)-1, -1, -1):
inverso += semespaco[i]
if frase == inverso:
print(f'A frase digitada é um palíndromo')
else:
print(f'A frase digita não é um palíndromo')
print(f'O inverso de "{frase}" é "{inverso}"') | true |
80d6b14558f51f19d47b16dc91c8f0ecc7b0ffee | Python | phac-nml/irida-galaxy-importer | /irida_import/sample_pair.py | UTF-8 | 1,163 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | """
Copyright Government of Canada 2015-2020
Written by: National Microbiology Laboratory, Public Health Agency of Canada
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
class SamplePair:
"""A representation of a sample pair obtained from IRIDA"""
def __init__(self, name, forward, reverse):
"""
Create a sample file instance.
:type name: str
:param name: the name of the sample file
:type path: str
:param path: the URI of the sample file
"""
self.forward = forward
self.reverse = reverse
self.name = name
def __repr__(self):
return self.name + ": \npair -" + str(self.files)
| true |
f9261c1844cc629c91043d1221d0b76f6e22fef6 | Python | ningyuuu/test-gsheets | /gsheets.py | UTF-8 | 2,345 | 2.671875 | 3 | [] | no_license | import os.path as path
from googleapiclient.discovery import build
from google.oauth2 import service_account
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1FSMATLJUNCbV8-XYM8h7yHoWRSGA8JFsaECOZy_i2T8'
def main():
service_account_json = path.join(path.dirname(
path.abspath(__file__)), 'service_account.json')
credentials = service_account.Credentials.from_service_account_file(
service_account_json, scopes=SCOPES)
service = build('sheets', 'v4', credentials=credentials)
sheet_service = service.spreadsheets()
print('Getting pie chart information')
get_pie_chart_info(sheet_service)
print('Getting line chart information')
get_line_chart_info(sheet_service)
print('Getting boolean information')
get_bool_info(sheet_service)
def get_pie_chart_info(sheet_service):
sample_range_name = 'data!F:G'
result = sheet_service.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=sample_range_name).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Race, Breakdown:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[1]))
def get_line_chart_info(sheet_service):
sample_range_name = 'data!D:D'
result = sheet_service.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=sample_range_name).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Time series information:')
for row in values:
print('%s' % row[0])
def get_bool_info(sheet_service):
sample_range_name = 'data!B1'
result = sheet_service.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=sample_range_name).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Time series information:')
for row in values:
print(row[0] == 'TRUE')
if __name__ == '__main__':
main()
| true |
6695532eef823ae3eec77cc8e9cc49fd5f275ef1 | Python | koblas/thistle | /py/thistle/safestring.py | UTF-8 | 5,315 | 3.171875 | 3 | [] | no_license | """
Functions for working with "safe strings": strings that can be displayed safely
without further escaping in HTML. Marking something as a "safe string" means
that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
def curry(_curried_func, *args, **kwargs):
def _curried(*moreargs, **morekwargs):
return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
return _curried
class EscapeData(object):
pass
class EscapeString(str, EscapeData):
"""
A string that should be HTML-escaped when output.
"""
pass
class EscapeUnicode(unicode, EscapeData):
"""
A unicode object that should be HTML-escaped when output.
"""
pass
class SafeData(object):
pass
class SafeString(str, SafeData):
"""
A string subclass that has been specifically marked as "safe" (requires no
further escaping) for HTML output purposes.
"""
def __add__(self, rhs):
"""
Concatenating a safe string with another safe string or safe unicode
object is safe. Otherwise, the result is no longer safe.
"""
t = super(SafeString, self).__add__(rhs)
if isinstance(rhs, SafeUnicode):
return SafeUnicode(t)
elif isinstance(rhs, SafeString):
return SafeString(t)
return t
def _proxy_method(self, *args, **kwargs):
"""
Wrap a call to a normal unicode method up so that we return safe
results. The method that is being wrapped is passed in the 'method'
argument.
"""
method = kwargs.pop('method')
data = method(self, *args, **kwargs)
if isinstance(data, str):
return SafeString(data)
else:
return SafeUnicode(data)
decode = curry(_proxy_method, method = str.decode)
class SafeUnicode(unicode, SafeData):
"""
A unicode subclass that has been specifically marked as "safe" for HTML
output purposes.
"""
def __add__(self, rhs):
"""
Concatenating a safe unicode object with another safe string or safe
unicode object is safe. Otherwise, the result is no longer safe.
"""
t = super(SafeUnicode, self).__add__(rhs)
if isinstance(rhs, SafeData):
return SafeUnicode(t)
return t
def _proxy_method(self, *args, **kwargs):
"""
Wrap a call to a normal unicode method up so that we return safe
results. The method that is being wrapped is passed in the 'method'
argument.
"""
method = kwargs.pop('method')
data = method(self, *args, **kwargs)
if isinstance(data, str):
return SafeString(data)
else:
return SafeUnicode(data)
encode = curry(_proxy_method, method = unicode.encode)
def mark_safe(s):
"""
Explicitly mark a string as safe for (HTML) output purposes. The returned
object can be used everywhere a string or unicode object is appropriate.
Can be called multiple times on a single string.
"""
if isinstance(s, SafeData):
return s
if isinstance(s, str):
return SafeString(s)
if isinstance(s, unicode):
return SafeUnicode(s)
return SafeString(str(s))
def mark_for_escaping(s):
"""
Explicitly mark a string as requiring HTML escaping upon output. Has no
effect on SafeData subclasses.
Can be called multiple times on a single string (the resulting escaping is
only applied once).
"""
if isinstance(s, (SafeData, EscapeData)):
return s
if isinstance(s, str):
return EscapeString(s)
if isinstance(s, unicode):
return EscapeUnicode(s)
return EscapeString(str(s))
#
# From django.utils.html
#
def force_unicode(s):
if isinstance(s, unicode):
return s
try:
if not isinstance(s, basestring,):
if hasattr(s, '__unicode__'):
s = unicode(s)
else:
s = unicode(str(s), 'utf-8', 'strict')
elif not isinstance(s, unicode):
s = s.decode(encoding, errors)
except:
pass
return s
def conditional_escape(html):
"""
Similar to escape(), except that it doesn't operate on pre-escaped strings.
"""
if isinstance(html, SafeData):
return html
return escape(html)
def escape(html):
"""
Returns the given HTML with ampersands, quotes and angle brackets encoded.
"""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
def unescape_string_literal(s):
r"""
Convert quoted string literals to unquoted strings with escaped quotes and
backslashes unquoted::
>>> unescape_string_literal('"abc"')
'abc'
>>> unescape_string_literal("'abc'")
'abc'
>>> unescape_string_literal('"a \"bc\""')
'a "bc"'
>>> unescape_string_literal("'\'ab\' c'")
"'ab' c"
"""
if s[0] not in "\"'" or s[-1] != s[0]:
raise ValueError("Not a string literal: %r" % s)
quote = s[0]
return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
| true |
93ccac9aa75c1b30f717333e48bb14cd41493d8f | Python | matthewdeanmartin/json_kata | /python/simple_calls/time_it_class.py | UTF-8 | 1,480 | 3.828125 | 4 | [
"MIT"
] | permissive | """
Basic utility code to show perf.
Could also have been implemented as a decorator.
usage
with time_it():
do_something_slow()
More elaborate usages
with time_it(show=False) as clock:
for _ in range(0, 10):
single()
print("Average %s" % clock.format_time(clock.elapsed() / 10))
"""
import math
import time
from typing import Any
class time_it(object):
def __init__(self, show: bool = True) -> None:
self.show = show
def __enter__(self) -> "time_it":
self.start_time = time.perf_counter() # in seconds
# don't forget return self
# https://stackoverflow.com/questions/4835611/pythons-with-statement-target-is-unexpectedly-none
return self
def format_time(self, seconds: float) -> str:
whole_seconds = math.floor(seconds)
milliseconds = math.floor((seconds - whole_seconds) * 1000)
if whole_seconds and milliseconds:
return f"{whole_seconds}s {milliseconds}ms"
if whole_seconds:
return f"{whole_seconds}s"
if milliseconds:
return f"{milliseconds}ms"
def elapsed(self) -> float:
so_far = time.perf_counter()
return so_far - self.start_time
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.end_time = time.perf_counter()
self.elapsed_seconds = self.end_time - self.start_time
if self.show:
print(self.format_time(self.elapsed_seconds))
| true |
1c6158f1c18ae6302b9adef01c7c75d46a6a27c2 | Python | MauVlad/Mytest | /ev3dev/texto/F/funcion.py | UTF-8 | 152 | 2.90625 | 3 | [] | no_license | def fun():
x = raw_input("escribe algo: ")
if x == 'hola':
print (x + 'hola')
elif x == 'adios':
print (x + 'hola')
else:
print x
fun()
| true |
188de9456c7ba51a481bced7f47eccc723720369 | Python | lewsn2008/learning_examples | /gensim/text_classification/sense_classifier.py | UTF-8 | 7,505 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python
#coding=utf8
from __future__ import print_function
import argparse
import logging
import re
import sys
from gensim.corpora import Dictionary
from scipy.sparse import csr_matrix
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
reload(sys)
sys.setdefaultencoding("utf8")
# Configure logging.
logging.basicConfig(
level=logging.INFO,
format=('[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d :'
'%(message)s'), datefmt='%a, %d %b %Y %H:%M:%S')
class SenseClassifier(object):
DATE_PTN = re.compile(u'(((19)*9\d|(20)*[01]\d)\-?)?((0[1-9]|1[012])\-?)([012]\d|3[01])')
LABEL_TO_INDEX = {'movie':0, 'episode':1, 'enter':2, 'cartoon':3, 'game':4}
INDEX_TO_LABEL = {0:'movie', 1:'episode', 2:'enter', 3:'cartoon', 4:'game'}
def __init__(self, dict_file=None, model_file=None):
if dict_file:
self.dictionary = Dictionary.load_from_text(dict_file)
else:
self.dictionary = Dictionary()
if model_file:
self.model = joblib.load(model_file)
else:
self.model = None
def dictionary_size(self):
return len(self.dictionary)
def expand_sent_terms(self, sent, center, rm_kw=False):
expd_sent = list(sent)
# Expand with ngram and position_term features.
if center >= 0:
ngram_terms = self._get_ngram_terms(sent, center)
expd_sent.extend(ngram_terms)
posi_terms = self._get_posi_terms(sent, center)
expd_sent.extend(posi_terms)
# Remove the keyword itself.
if rm_kw and center >= 0:
del expd_sent[center]
return expd_sent
def sentence_to_bow(self, sent):
if self.dictionary:
return self.dictionary.doc2bow(sent)
else:
return None
def bow_to_feature_vec(self, bow_corpus):
data = []
rows = []
cols = []
line_count = 0
for bow_sent in bow_corpus:
for elem in bow_sent:
rows.append(line_count)
cols.append(elem[0])
data.append(elem[1])
line_count += 1
return csr_matrix(
(data, (rows,cols)), shape=(line_count, len(self.dictionary)))
def load_text(self, data_file, train=False):
term_corpus = []
labels = []
with open(data_file) as fin:
for line in fin:
parts = line.strip().decode('utf8').split('\t')
if len(parts) < 3:
continue
label, keyword = parts[0:2]
orig_sent = parts[2:]
if train:
keyword_count = sum([1 if x == keyword else 0 for x in orig_sent])
if keyword_count != 1:
continue
# Normalize special terms.
sent = ['@date@' if self.DATE_PTN.match(term) else term for term in orig_sent]
# Expand sentence with more features.
center = sent.index(keyword)
sent = self.expand_sent_terms(sent, center, True)
# Save sentences and labels.
term_corpus.append(sent)
labels.append(self.LABEL_TO_INDEX[label])
# Update dictionary.
if train:
self.dictionary.add_documents([sent])
if train:
# Compacitify dictionary.
self.dictionary.filter_extremes(no_below=5, no_above=0.5, keep_n=None)
self.dictionary.compactify()
# Change text format corpus to bow format.
bow_corpus = []
for sent in term_corpus:
sent_bow = self.dictionary.doc2bow(sent)
bow_corpus.append(sent_bow)
return bow_corpus, labels
WINDOW_SIZE = 3
def _get_posi_terms(self, words, center):
terms = []
for i in range(self.WINDOW_SIZE):
offset = (i + 1)
left_posi = center - offset
if left_posi >= 0:
terms.append('%s-%d' % (words[left_posi], offset))
right_posi = center + offset
if right_posi < len(words):
terms.append('%s+%d' % (words[right_posi], offset))
return terms
NGRAM_WINDOW_SIZE = 10
def _get_ngram_terms(self, words, center):
terms = []
for i in range(1, self.NGRAM_WINDOW_SIZE):
offset = (i + 1)
left_posi = center - offset
if left_posi >= 0:
terms.append('%s_%s' % (words[left_posi], words[left_posi + 1]))
right_posi = center + offset
if right_posi < len(words):
terms.append('%s_%s' % (words[right_posi - 1], words[right_posi]))
return terms
def dump_dict(self, dict_file):
self.dictionary.save_as_text(dict_file)
def dump_model(self, model_file):
if self.model:
joblib.dump(self.model, model_file)
def train(self, x_list, y_list, model='lr'):
X_train, X_test, y_train, y_test = train_test_split(x_list,
y_list,
test_size=0.3)
if model == 'lr':
self.model = LogisticRegression(C=1.0,
multi_class='multinomial',
penalty='l2',
solver='sag',
tol=0.1)
else:
logging.error('Unknown model name!')
return
self.model.fit(X_train, y_train)
score = self.model.score(X_train, y_train)
print("Evaluation on train set : %.4f" % score)
score = self.model.score(X_test, y_test)
print("Evaluation on test set : %.4f" % score)
def predict(self, X):
return self.model.predict(X)
def predict_proba(self, X):
return self.model.predict_proba(X)
def eval(self, X, y):
score = self.model.score(X, y)
print("Evaluation on validation set : %.4f" % score)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--train_file', type=str, help='corpus location')
parser.add_argument('--test_file', type=str, help='corpus location')
parser.add_argument('--dict_file', type=str, help='dict location')
parser.add_argument('--model_file', type=str, help='model location')
args = parser.parse_args()
if args.train_file:
# Train.
clf = SenseClassifier()
sents, labels = clf.load_text(args.train_file, True)
X_train = clf.bow_to_feature_vec(sents)
clf.train(X_train, labels)
# Save model and dictionary.
if args.model_file:
clf.dump_model(args.model_file)
if args.dict_file:
clf.dump_dict(args.dict_file)
elif args.dict_file and args.model_file:
# Init classifier from dictinary and model file.
clf = SenseClassifier(args.dict_file, args.model_file)
else:
logging.error('Wrong usage!')
sys.exit(1)
# Evaluate on test file.
if args.test_file:
sents, labels = clf.load_text(args.test_file)
X_test = clf.bow_to_feature_vec(sents)
clf.eval(X_test, labels)
logging.info('Finished!')
| true |
6b8c7a87ba0c0479bc4916ca0503038447db6acd | Python | FreddyLimachi/rest-api-user-auth | /app/app_users/validators.py | UTF-8 | 1,615 | 3.1875 | 3 | [] | no_license | import re
def validate(username, email, password, confirm_pass, user, verify_email):
if len(username) < 5 or len(username) > 15:
return {'value': False, 'msg': 'El username debe contener entre a 5 a 15 carácteres'}
elif re.match("^[a-zA-Z0-9_-]+$", username) is None:
return {'value': False, 'msg': 'Unicos caracteres especiales permitidos: _ y -'}
elif user and user['username'].lower() == username.lower():
return {'value': False, 'msg': 'Ya existe el nombre de usuario'}
elif validar_email(email) == False:
return {'value': False, 'msg': 'Digite correctamente su email'}
elif verify_email:
return {'value': False, 'msg': 'El email ya esta siendo utilizado'}
elif len(password) < 8:
return {'value': False, 'msg': 'La contraseña debe contener al menos 8 carácteres'}
elif password != confirm_pass:
return {'value': False, 'msg': 'La contraseña de confirmación no coincide'}
else: return True
def validar_email(correo):
try:
expresion_regular = r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"
return re.match(expresion_regular, str(correo)) is not None
except:
False | true |
e2fb788d0c8a32487e5bd751c855b501d577b5fa | Python | eeshadutta/SMAI-Assignments | /Class Assignments/HW8/3.py | UTF-8 | 828 | 3.078125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
x = np.array([[0,0],[3,0],[4,2],[1,2]])
parallelogram = np.array([[0,0],[3,0],[4,2],[1,2],[0,0]])
mu = np.array([np.mean(x[:,0]),np.mean(x[:,1])])
print('mean = ',mu)
sigma = np.cov(x.T)
print('Covariance = \n', sigma)
eigvals, eigvecs = np.linalg.eig(sigma)
print('Eigenvectors are = \n', eigvecs)
fig = plt.figure(figsize = [20,20], dpi = 40)
ax = fig.add_subplot(111)
ax.plot(parallelogram[:,0], parallelogram[:,1])
ax.scatter(x[:,0],x[:,1], marker = 'x', color = 'red', s = 500)
m = [mu[0]],[mu[1]]
ax.quiver(*m, eigvecs[:,0], eigvecs[:,1], color = ['green','black'], scale = 5)
ax.tick_params(axis='both', which='major', labelsize=20)
ax.tick_params(axis='both', which='minor', labelsize=50)
ax.set_xlim([-5,10])
ax.set_ylim([-5,10])
plt.show() | true |
2f0823a779326a597ca585ddc9773b06d3cc629f | Python | zzz136454872/leetcode | /numberOfMatches.py | UTF-8 | 154 | 2.875 | 3 | [] | no_license | from typing import List
class Solution:
def numberOfMatches(self, n: int) -> int:
return n - 1
n = 7
print(Solution().numberOfMatches(n))
| true |
a86c1e5c7bc563209e47ae55c5bc13c3a1224366 | Python | toguchi-taichi/study-03-desktop-01-master | /search.py | UTF-8 | 700 | 2.9375 | 3 | [] | no_license | import pandas as pd
import eel
### デスクトップアプリ作成課題
def kimetsu_search(word, csv_save):
# 検索対象取得
df=pd.read_csv("./{}".format(csv_save))
source=list(df["name"])
# 検索
if word in source:
print("『{}』はあります".format(word))
return "『{}』はあります".format(word)
else:
print("『{}』はありません。{}を追加します".format(word, word))
source.append(word)
df = pd.DataFrame(source, columns=['name'])
df.to_csv('./{}'.format(csv_save), encoding='utf-8')
return "『{}』はありません。{}を追加します".format(word, word)
| true |
8f34ede92589f487793efc2054f738e26cb8c28a | Python | erikkrasner/Project-Euler | /prob3_solution.py | UTF-8 | 300 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
# 6857
# 0.402 s
import sys
from prime_gen import *
def largest_prime_factor(n):
for p in primes():
while not n % p:
n /= p
if n == 1:
return p
if p * p > n:
return n
print largest_prime_factor(int(sys.argv[1]) if sys.argv[1:] else 600851475143)
| true |
ca1b30ccbc289ab34fab825ff0236793b6366c4a | Python | martinleeq/python-100 | /day-09/question-076.py | UTF-8 | 266 | 3.265625 | 3 | [] | no_license | """
问题75
运用zlib包对"hello world!hello world!hello world!hello world!"进行压缩和解压
"""
import zlib
s = 'hello world!hello world!hello world!hello world!'
out = zlib.compress(bytes(s, 'utf-8'))
print(out)
plain = zlib.decompress(out)
print(plain) | true |
82d641bdd168200c286719934e85de50ea3dfcca | Python | Greenwicher/Competitive-Programming | /CodeForces/Python3/598C.py | UTF-8 | 1,626 | 3.359375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 20:47:21 2016
@author: liuweizhi
"""
#%% Version 1
from math import *
# stores counterclockwise angle between vector (1,0) and each vector in a
a = []
n = int(input())
for _ in range(n):
x,y = map(int,input().split())
# calculate counterclockwise angle between (1,0) and this vector
t = acos(x/sqrt(x**2+y**2))
a.append([2*pi-t,t][y>=0])
# sorting a
b = sorted(a)
# calculate difference of angle between adjacent vector
c = [b[i+1]-b[i] for i in range(n-1)]
c.append(b[-1]-b[0])
c = [[2*pi-foo,foo][foo<pi] for foo in c]
# find the nearest vector
i_min = c.index(min(c))
if i_min!=n-1:
i1 = a.index(b[i_min+1])
i2 = a.index(b[i_min])
else:
i1 = a.index(b[0])
i2 = a.index(b[-1])
print(i1+1,i2+1)
#%% Version 2
from math import *
# stores counterclockwise angle between vector (1,0) and each vector in a
a = []
n = int(input())
for i in range(n):
x,y = map(int,input().split())
# calculate counterclockwise angle between (1,0) and this vector
t = acos(x/sqrt(x**2+y**2))
a.append((i+1,[2*pi-t,t][y>=0],x,y))
cmp = lambda x:x[1]
a = sorted(a,key=cmp)
# construct pairs for adjacent vectors
b = []
for i in range(n):
i1,i2 = a[i][0],a[(i+1)%n][0]
x1,y1 = a[i][2:]
x2,y2 = a[(i+1)%n][2:]
inner_prod = x1*x2 + y1*y2
inner_prod *= abs(inner_prod)
norm_prod = ((x1**2+y1**2)*(x2**2+y2**2))
b.append((i1,i2,inner_prod,norm_prod))
# find the nearest vector
better = lambda p1,p2: p1[2]*p2[3]>p2[2]*p1[3]
ans = b[-1]
for i in range(n):
if better(b[i],ans):
ans = b[i]
print(ans[0],ans[1])
| true |
ae193cdaf57f6ff979b4eae3a956a62541bc9050 | Python | neurord/moose_nerp | /moose_nerp/prototypes/logutil.py | UTF-8 | 1,374 | 2.5625 | 3 | [] | no_license | import inspect
import logging
class Message(object):
def __init__(self, fmt, args):
self.fmt = fmt
self.args = args
def __str__(self):
return self.fmt.format(*self.args)
class StyleAdapter(logging.LoggerAdapter):
def __init__(self, logger, extra=None):
super(StyleAdapter, self).__init__(logger, extra or {})
def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level):
msg, kwargs = self.process(msg, kwargs)
self.logger._log(level, Message(msg, args), (), **kwargs)
def debug(self, *args, **kwargs):
return self.log(logging.DEBUG, *args, **kwargs)
def info(self, *args, **kwargs):
return self.log(logging.INFO, *args, **kwargs)
def warning(self, *args, **kwargs):
return self.log(logging.WARNING, *args, **kwargs)
def error(self, *args, **kwargs):
return self.log(logging.ERROR, *args, **kwargs)
def Logger(name=None):
if name is None:
frame = inspect.stack()[1]
mod = inspect.getmodule(frame[0])
if mod is not None:
name = mod.__name__
else:
name = '__main__'
FORMAT = '%(process)d - %(filename)s - %(lineno)d - %(funcName)s - %(levelname)s - %(message)s' #SRIRAM 02152018
logging.basicConfig(format=FORMAT)
return StyleAdapter(logging.getLogger(name))
| true |
7792e82d54c4d091af54cd35cfe9b304d871d575 | Python | tectronics/wepoco-web | /mpe_tools/process/map_tiles_mpe.py | UTF-8 | 3,841 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python
# Michael Saunby. For Wepoco.
# $Date$
#
# The last MPE (grib) file of the day will trigger the creation of a PNG
# image.
# For each of the reporojection LUT files in lutdir this
# script will generate a map tile for use with Google Maps.
##############################################################################
import sys, array, Image
force = False
msatwidth = 2300; msatheight = 2300
msgwidth = 3712; msgheight = 3712
#lut_suffix = '.msat_lut'
lut_suffix = '.msg_lut'
tile_suffix = '.png'
mapconfig = 'map.list'
# Take an image in Meteosat projection, an appropriate reproj LUT and
# generate a new image tile.
def reproj( inpic, lutf, destImgName ):
outcols = 256
outrows = 256
(inrows,incols) = inpic.size
if incols == msgwidth:
proj = "msg"
elif incols == msatwidth:
# "trimmed" meteosat
proj = "msat"
return (1, 'source image old (M7) size')
else:
return (1, 'source image wrong size for reproj')
matrix = array.array('h')
matrix.fromfile( lutf, outrows*outcols*2 )
outpic = Image.new(inpic.mode,(outcols,outrows))
for y in range(outrows):
for x in range(outcols):
xmsat = matrix[y*outcols*2 + x*2]
ymsat = matrix[y*outcols*2 + x*2 +1]
#if incols == msatwidth:
# xmsat = xmsat - 100
# ymsat = ymsat - 100
# pass
try:
p = inpic.getpixel((xmsat,ymsat))
outpic.putpixel((x,y), p)
except:
pass
pass
pass
outpic.putpalette( inpic.getpalette() )
outpic.save( destImgName, transparency=0 )
return (0, '')
import os, string
from fn_mk_tiledir import mk_tiledir
def run( workdir = '/home/mike/wepoco/data/mpe/', sumname=None ):
bindir='/home/mike/wepoco/bin/'
datadir='/home/mike/wepoco/data/mpe/'
#mapdir=datadir + 'map/'
lutdir=datadir + 'lut/'
config = 'acc.out'
if not sumname:
try:
configf = file( workdir + config, 'r' )
discard = string.strip( configf.readline() )
sumname = string.strip( configf.readline() )
lasttmp = string.strip( configf.readline() )
configf.close()
except Exception, inst:
# print inst
return (1, 'Failed to read configuration file')
if (lasttmp == 'last'):
islast = True
else:
return (2, 'Not last file of day')
pass
try:
imgname = sumname + '.png'
tiledir = mk_tiledir( workdir, sumname )
# Open sum image file.
satimg = Image.open( workdir + imgname )
except:
return (3, 'Failed to open input image file %s' % (workdir + imgname))
#
# Create new images
try:
lutconf = file( lutdir + mapconfig, 'r' )
except:
return (4, 'Failed to open map config file' )
if True:
for mapname in lutconf:
mapname = string.strip( mapname )
words = string.split( mapname, '.' )
lutname = words[0] + lut_suffix
tilename = words[0] + tile_suffix
try:
if force:
print "processing", tilename
pass
lutf = file( lutdir + lutname, 'rb' )
(rc, msg) = reproj( satimg, lutf, workdir + tiledir + tilename )
if rc:
print msg
pass
except Exception, inst:
print inst
return (5, 'Failed when processing %s' % (lutname))
pass
pass
return (0, 'OK')
if __name__ == "__main__":
import sys
force = True
(rc, msg) = run( './', sumname=sys.argv[1] )
print msg
sys.exit( rc )
| true |
d52bc47431b63e6ba17a10836f16d321f1f0ca14 | Python | j4velin/photobooth | /trigger.py | UTF-8 | 1,815 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import socket
import sys
import time
import RPi.GPIO as GPIO
import os
import fcntl
import struct
from functools import partial
from multiprocessing import Pool
PORT = 5555
GPIO_TRIGGER_PIN = 4
TAKE_PHOTO_CMD = "TAKE_PHOTO\n"
SCANNER_WORKERS = 10
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def test_port(prefix, suffix):
host = prefix + str(suffix)
print 'testing ' + str(host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
result = s.connect_ex((host, PORT))
s.close()
if result == 0:
return host
else:
return False
def scan_hosts():
prefix = get_ip_prefix()
p = Pool(SCANNER_WORKERS)
test_partial = partial(test_port, prefix)
return filter(bool, p.map(test_partial, range(1,255)))
def get_ip_prefix():
my_ip = get_ip_address('wlan0')
print 'my ip: ' + str(my_ip)
return my_ip[:my_ip.rfind('.')]+'.'
result_ip = None
while result_ip == None:
tablet = scan_hosts()
print str(tablet)
if len(tablet) > 0:
result_ip = tablet[0]
else:
print 'no device found'
time.sleep(10)
print "Result IP: " + result_ip
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_TRIGGER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(None)
s.connect((result_ip, PORT))
try:
while True:
input_state = GPIO.input(GPIO_TRIGGER_PIN)
if input_state == False:
# print "taking photo..."
s.send(TAKE_PHOTO_CMD.encode())
time.sleep(5)
except KeyboardInterrupt:
print "keyboard interrupt"
s.close()
| true |
2f336cfa8b738a8fc9b756afd71870c7fb6282ce | Python | EstelleDutheil/Bronkhorst_flux_afficheur | /convertisseur_string_chr_en_n_hexaDecimal.py | UTF-8 | 341 | 2.625 | 3 | [] | no_license | from convertisseur_1int_1byte import conversion_1int_1byte
def conversion_string_chr_en_n_hexaDecimal(chaine_chr):
hexaDecimal=b''
for bla in range(0,(len(chaine_chr))):
caractere=chaine_chr[bla]
caractere=ord(caractere)
caractere=conversion_1int_1byte(caractere)
hexaDecimal=hexaDecimal+caractere
return(hexaDecimal)
| true |
215a65925829c83877f23339ed67e8abfa658383 | Python | Percygu/algorithm | /leetcode/compare1.py | UTF-8 | 593 | 3.140625 | 3 | [] | no_license | if len(self.hashmap) == self.capacity:
# 去掉哈希表对应项
self.hashmap.pop(self.head.next.key)
# 去掉最久没有被访问过的节点,即头节点之后的节点
self.head.next = self.head.next.next
self.head.next.prev = self.head
# 如果不在的话就插入到尾节点前
new = Node(key, value)
self.hashmap[key] = new
new.prev = self.tail.prev
new.next = self.tail
self.tail.prev.next = new
self.tail.prev = new | true |
a40d2615c71e90cc59f66435915fdf0ce839b0ae | Python | GoncharovVS/GBlearn | /hw03_easy.py | UTF-8 | 2,332 | 4.15625 | 4 | [] | no_license | __author__ = "Гончаров Всеволод Сергеевич"
while True:
print("Введи номер задачи (1-2) или 0 для выхода")
key = int(input())
# Задание-1:
# Напишите функцию, округляющую полученное произвольное десятичное число
# до кол-ва знаков (кол-во знаков передается вторым аргументом).
# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).
# Для решения задачи не используйте встроенные функции и функции из модуля math.
if key == 1:
def my_round(number, ndigits):
factor = 1
for _ in range(ndigits):
factor *= 10
number *= factor
if number % 1 > 0.5:
number += 1
return int(number) / factor
print(my_round(2.1234567, 5))
print(my_round(2.1999967, 5))
print(my_round(2.9999967, 5))
# Задание-2:
# Дан шестизначный номер билета. Определить, является ли билет счастливым.
# Решение реализовать в виде функции.
# Билет считается счастливым, если сумма его первых и последних цифр равны.
# !!!P.S.: функция не должна НИЧЕГО print'ить
elif key == 2:
def lucky_ticket(ticket_number):
ticket_number = str(ticket_number)
ticket_number_list = []
for symbol in ticket_number:
ticket_number_list.append(int(symbol))
sum1 = 0
sum2 = 0
i = 0
while i < int(len(ticket_number_list) / 2):
i += 1
sum1 += ticket_number_list[i-1]
sum2 += ticket_number_list[-i]
return sum1 == sum2
print(lucky_ticket(123006))
print(lucky_ticket(12321))
print(lucky_ticket(436751))
print(lucky_ticket(1234))
elif key == 0:
break
else:
print("Ввел что-то не то, попробуй ещё раз")
| true |
7ed8299433df092aeb60b4592d32790f7d74eb0a | Python | Hiking-Apprentice/python_spider | /scrapy携带cookies爬取拉勾网职位/LGW/LGW/spiders/lgw.py | UTF-8 | 1,246 | 2.546875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
import re
from ..items import LgwItem
class LgwSpider(CrawlSpider):
name = 'lgw'
allowed_domains = ['lagou.com']
start_urls = ['https://www.lagou.com/jobs/6877483.html']
rules = (
Rule(LinkExtractor(allow=r'www\.lagou'), callback='parse_item', follow=True),
)
def parse_item(self, response):
# print('hello')
item = LgwItem()
#item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
position=response.xpath('//dd[@class="job_request"]/h3/span[2]/text()').get()
try:
position=re.findall('/(\w*) /', position)[0]
# print(position)
except:
pass
content=response.xpath('//div[@class="job-detail"]/p/text()').extract()
# print(content)
c=[]
for i in content:
if i !=0 and i !='\n' and i != '\t':
c.append(i)
con=''.join(c).strip('')
# print(con)
item['name'] = response.xpath('//h1[@class="name"]/text()').get()
item['position'] = position
item['description'] = con
yield item
| true |
4ff25e436aa6f8086adaa1a5ffd709994c35fa71 | Python | bielskin/NoStop | /NoStop.py | UTF-8 | 1,617 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 16:20:16 2021
@author: NVB
"""
import argparse
parser = argparse.ArgumentParser(description='NOSTOP: Removes stop codons from a codon aligned fasta formatted nucleotide file and replaces with gaps')
requiredNamed = parser.add_argument_group('required arguments')
requiredNamed.add_argument("-i", "--input_align_file", help="File of codon aligned nucleotide fasta file", required=True)
args = parser.parse_args()
alignment_file=(vars(args)['input_align_file'])
alignment = {}
file_one= open(alignment_file, 'r')
for line in file_one:
line = line.strip()
if not line:
continue
if line.startswith(">"):
active_sequence_name = line[1:]
if active_sequence_name not in alignment:
alignment[active_sequence_name] = []
continue
sequence = line
sequence=sequence.replace('TAG-', '---').replace('TGA-', '---').replace('TAA-', '---')
minusthreeseq=len(sequence)-3
lastcodon=sequence[minusthreeseq:len(sequence)]
if lastcodon == "TAA" or lastcodon== "TAG" or lastcodon== "TGA":
sequence=sequence[0:len(sequence)-3]
sequence=sequence + '---'
alignment[active_sequence_name]=sequence
else:
alignment[active_sequence_name]=sequence
file_one.close()
reduced_alignfile=alignment_file.replace('.fasta', '')
OutFileName=reduced_alignfile + '_NoStop.fasta'
WriteOutFile= True
OutFile=open(OutFileName, 'w')
for seq in alignment:
OutFile.write(">" + seq + '\n')
OutFile.write(alignment[seq] +'\n') | true |
f95f03e909635277015eb5e0f64e9a84e853c0cf | Python | vanisatish/API_SeleniumPython | /GET_Request/FetchUserData.py | UTF-8 | 659 | 3.296875 | 3 | [] | no_license | import requests
import json
import jsonpath
url = "https://reqres.in/api/users?page=2" # API URL
# Send GET request
response = requests.get(url)
print(response)
# display response content
print(response.content)
print(response.json())
print(response.headers)
# another way to print response data using json methods
json_response = json.loads(response.text)
print(json_response)
# fetch specific value from the response by using json path
pages = jsonpath.jsonpath(json_response, 'total_pages')
# print pages of index 1 i.e. first value of total pages
print(pages[0])
# fetch first value of the json value
assert pages[0] == 2
| true |
751ec1918ceca0584afe160504d543db39441af9 | Python | tlherr/PythonChallenge | /Question1.py | UTF-8 | 62 | 2.5625 | 3 | [] | no_license | import url
number = (2 ** 38)
# Question 1
url.format(number) | true |
23425f83b531e0bf945b51c5b02a5c071e8edfb8 | Python | seamustuohy/dockerfiles | /cyobstract/get_indicators_from_url.py | UTF-8 | 2,700 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © 2018 seamus tuohy, <code@seamustuohy.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the included LICENSE file for details.
import argparse
from cyobstract import extract
import requests
from bs4 import BeautifulSoup
import logging
logging.basicConfig(level=logging.ERROR)
log = logging.getLogger(__name__)
def main():
args = parse_arguments()
set_logging(args.verbose, args.debug)
for url in args.URLS:
get_urls(url, args.ignore_missing)
def get_urls(URL, ignore_missing=False):
log.debug("Fetching URL: {0}".format(URL))
r = requests.get(URL)
soup = BeautifulSoup(r.text, 'html.parser')
# remove all scripts
not_content = ['script', 'head',
'header', 'footer',
'style', 'comment',
'foot', 'meta']
for tag in not_content:
[s.extract() for s in soup(tag)]
text = soup.text
results = extract.extract_observables(text)
# print(results)
for indicator_type,indicators in results.items():
if ignore_missing is True:
if len(indicators) != 0:
print_indicator(indicator_type,indicators)
else:
print_indicator(indicator_type,indicators)
def print_indicator(indicator_type,indicators):
print("\n\n=== {0} ===".format(indicator_type))
for i in indicators:
print(i)
# Command Line Functions below this point
def set_logging(verbose=False, debug=False):
if debug == True:
log.setLevel("DEBUG")
elif verbose == True:
log.setLevel("INFO")
def parse_arguments():
parser = argparse.ArgumentParser("Print indicators from a URL.")
parser.add_argument("--verbose", "-v",
help="Turn verbosity on",
action='store_true')
parser.add_argument("--debug", "-d",
help="Turn debugging on",
action='store_true')
parser.add_argument("--ignore_missing", "-i",
help="Don't show missing indicators sections",
action='store_true',
default=False)
parser.add_argument('URLS', nargs='*')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
| true |
0cc9504f313a89df5c2949649b100ed9fd40ab2e | Python | kabilankarunakaran/FakeLabVideo | /inference_video.py | UTF-8 | 3,293 | 2.625 | 3 | [] | no_license | import numpy as np
import torch
from model import create_model
from utils import get_face_crop, parse_vid, predict_with_model, get_front_face_detector
import shutil
import os
import uuid
import datetime
from mysqlhelper import *
from PredictionInfo import *
import cv2
def pred_test(v_path, start_frame=0, end_frame=1500, cuda=False, n_frames=5, user='101'):
unlabeled_dir = "dataset/unlabeled"
inf_metadata = dict()
shutil.copy(v_path, unlabeled_dir)
v_filenames = os.listdir(unlabeled_dir)
for v_filename in v_filenames:
vd_path = str(unlabeled_dir + '/' + v_filename)
"""
Predict and give result as numpy array
"""
pred_frames = [int(round(x)) for x in np.linspace(start_frame, end_frame, n_frames)]
predictions = []
outputs = []
inf_metadata = dict()
imgs, num_frames, fps, width, height = parse_vid(vd_path)
print(num_frames)
front_face_detector = get_front_face_detector()
# Load model
# Define Hyperparams
params = {
'dropout': float(np.random.choice([0.8, 0.9, 0.75])),
'use_hidden_layer': int(np.random.choice([0])),
}
model = create_model(bool(params['use_hidden_layer']), params['dropout'])
model_path = 'fitted_object/best_model.pth'
state_dict = torch.load(model_path, map_location=torch.device('cpu'))
model.load_state_dict(state_dict, strict=False)
model.eval()
inf_metadata['pred_id'] = str(uuid.uuid1())
for fid, img in enumerate(imgs):
if fid in pred_frames:
cropped_face = get_face_crop(front_face_detector, img)
# Actual prediction using our model
prediction, output = predict_with_model(cropped_face, model,
cuda=cuda)
imname = str(inf_metadata['pred_id'] + '_' + str(fid))
cv2.imwrite('images/' + imname + ".jpg", img)
# ------------------------------------------------------------------
# 'predicted_proba real, fake | prediction | label (0: real 1: fake)'
predictions.append(prediction)
outputs.append(output)
plen = len(predictions)
count_zero = 0
for x in predictions:
if x == 0:
count_zero += 1
prob = count_zero / plen
inf_metadata['user_id'] = str(user)
inf_metadata['time_stamp'] = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
inf_metadata['prob'] = str(prob)
inf_metadata['stype'] = str('V')
inf_metadata['fps'] = str(fps)
inf_metadata['nframes'] = str(num_frames)
"""Write to Local MySql Database"""
insert_sql_value = PredictionInfo(inf_metadata['pred_id'], inf_metadata['user_id'], inf_metadata['time_stamp'],
inf_metadata['prob'],inf_metadata['stype'],inf_metadata['fps'],
inf_metadata['nframes']);
# create a database connection
conn = create_connection()
# create a new prediction
create_prediction(conn, insert_sql_value)
#return predictions, outputs
print('Pred List of Frame:', predictions)
print('Probabailities of Frame', outputs)
pred_test(v_path='dataset/test/test12.mp4', start_frame=0, end_frame=500,cuda=False, n_frames=5)
| true |
626e225caf22bcc0d953f5f250a5ade7db845ad7 | Python | changhengliou/ECE-GY-9123-DL-final | /Paper2PPT/baselines/LexRank/example.py | UTF-8 | 2,849 | 2.578125 | 3 | [] | no_license | from lexrank import STOPWORDS, LexRank
from path import Path
documents = []
documents_dir = Path('bbc/politics')
for file_path in documents_dir.files('*.txt'):
with file_path.open(mode='rt', encoding='utf-8') as fp:
documents.append(fp.readlines())
lxr = LexRank(documents, stopwords=STOPWORDS['en'])
sentences = [
'One of David Cameron\'s closest friends and Conservative allies, '
'George Osborne rose rapidly after becoming MP for Tatton in 2001.',
'Michael Howard promoted him from shadow chief secretary to the '
'Treasury to shadow chancellor in May 2005, at the age of 34.',
'Mr Osborne took a key role in the election campaign and has been at '
'the forefront of the debate on how to deal with the recession and '
'the UK\'s spending deficit.',
'Even before Mr Cameron became leader the two were being likened to '
'Labour\'s Blair/Brown duo. The two have emulated them by becoming '
'prime minister and chancellor, but will want to avoid the spats.',
'Before entering Parliament, he was a special adviser in the '
'agriculture department when the Tories were in government and later '
'served as political secretary to William Hague.',
'The BBC understands that as chancellor, Mr Osborne, along with the '
'Treasury will retain responsibility for overseeing banks and '
'financial regulation.',
'Mr Osborne said the coalition government was planning to change the '
'tax system \"to make it fairer for people on low and middle '
'incomes\", and undertake \"long-term structural reform\" of the '
'banking sector, education and the welfare state.',
]
# get summary with classical LexRank algorithm
summary = lxr.get_summary(sentences, summary_size=2, threshold=.1)
print(summary)
# ['Mr Osborne said the coalition government was planning to change the tax '
# 'system "to make it fairer for people on low and middle incomes", and '
# 'undertake "long-term structural reform" of the banking sector, education and '
# 'the welfare state.',
# 'The BBC understands that as chancellor, Mr Osborne, along with the Treasury '
# 'will retain responsibility for overseeing banks and financial regulation.']
# get summary with continuous LexRank
summary_cont = lxr.get_summary(sentences, threshold=None)
print(summary_cont)
# ['The BBC understands that as chancellor, Mr Osborne, along with the Treasury '
# 'will retain responsibility for overseeing banks and financial regulation.']
# get LexRank scores for sentences
# 'fast_power_method' speeds up the calculation, but requires more RAM
scores_cont = lxr.rank_sentences(
sentences,
threshold=None,
fast_power_method=False,
)
print(scores_cont)
# [1.0896493024505858,
# 0.9010711968859021,
# 1.1139166497016315,
# 0.8279523250808547,
# 0.8112028559566362,
# 1.185228912485382,
# 1.0709787574388283]
| true |
303afc4bd70cc10b7286dc1077ec10f40cda2b2a | Python | jsawatzky/ICS3UI | /src/Unit 4 Arrays/Assignment/sky.py | UTF-8 | 1,548 | 2.96875 | 3 | [] | no_license | '''
Created on Nov 8, 2014
@author: Jacob
'''
from utilities import *
class Sky():
def __init__(self, queue):
self.queue = queue
colors = {}
colors['sunrise'] = "#FFC012"
colors['sunset'] = "#DE8501"
colors['day'] = "#3AA0FF"
colors['night'] = "#121C43"
self.colors = colors
def update(self, time):
colors = self.colors
if time in range(0, 26):
color = getColor(getColor(colors['sunset'], colors['sunrise'], 0, 2, 1), colors['sunrise'], 0, 25, time)
elif time in range(26, 76):
color = getColor(colors['sunrise'], colors['day'], 26, 75, time)
elif time in range(76, 726):
color = "#3AA0FF"
elif time in range(726, 776):
color = getColor(colors['day'], colors['sunrise'], 726, 775, time)
elif time in range(776, 826):
color = getColor(colors['sunrise'], colors['sunset'], 776, 825, time)
elif time in range(826, 876):
color = getColor(colors['sunset'], colors['night'], 826, 875, time)
elif time in range(876, 1526):
color = "#121C43"
elif time in range(1526, 1576):
color = getColor(colors['night'], colors['sunset'], 1526, 1576, time)
elif time in range(1576, 1601):
color = getColor(colors['sunset'], getColor(colors['sunset'], colors['sunrise'], 0, 2, 1), 1576, 1600, time)
self.queue.put(QueueItem("config", background = color)) | true |
065c64bfa8463ea62ae0c1b099d848c0065b8ad4 | Python | squadran2003/build_a_soccer_league | /league_builder.py | UTF-8 | 4,554 | 3.515625 | 4 | [
"MIT"
] | permissive | import csv,sys,datetime
num_of_teams = 3
# assign 3 teams Raptors,Sharks,Dragons
Raptors = [] # team1
Sharks = [] # team2
Dragons = [] # team3
exp_and_non_exp_players_count = 0 # hold on to the count for exp and non exp players
experienced_players=[]# will hold all exp players
non_experienced_players=[]# will hold all non exp players
exp_players_per_team = 0 # num exp players each team should have
non_exp_players_per_team = 0 # num of non exp players each team should have
def sort_player_with_team(mydict,mylist):
"""adds each dic to the relevant list i.e team"""
mylist.append(mydict)
def create_team_sheet(mylist2,team):
"""takes a list and string as an argument. Loops around the list
and prints out each dict prefixed with the team"""
with open("teams.csv",'a')as csvfile:
csvfile.write(""+"\n")
csvfile.write(team+"\n")
for mydict in mylist2:
csvfile.write("{Name}, {Soccer Experience},{Guardian Name(s)}".format(**mydict)+"\n")
def letter_to_guardians(mydict3,team):
"""takes a dict and a team name. Then creates a individual letter to his or her guardian
first_name_and_surname = mydict3['Name'].split(" ")
above, the string is split into a list of name and surname
using the contents of the list to create the firstname and surname file name"""
first_name_and_surname = mydict3['Name'].split(" ")
with open("{}_{}.txt".format(first_name_and_surname[0].lower(),
first_name_and_surname[1].lower()),
'a')as csvfile:
csvfile.write("Dear {},".format(mydict3['Guardian Name(s)'])+"\n")
csvfile.write("{}, {}, {}".format(mydict3['Name'],team,
datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")))
def assign_players_to_teams(players,teams,team_names,players_per_team):
"""looping through exp and non exp players and assigning them to teams
players = list of dictionaries where each is a player ;
teams= list of the teams i.e [Raptors,Sharks];
team_names = list of string representation of the teams i.e ["Raptors" "Sharks"] etc
players_per_team= No of exp or non exp players in a team"""
for exp_and_non_exp_players_count in range(len(players)):
if exp_and_non_exp_players_count < players_per_team:# first batch of players.
sort_player_with_team(players[exp_and_non_exp_players_count],teams[0])# adds players to teams
letter_to_guardians(players[exp_and_non_exp_players_count],team_names[0])# create a letter for each player
elif exp_and_non_exp_players_count < (players_per_team * 2):# next batch of players
sort_player_with_team(players[exp_and_non_exp_players_count],teams[1])# adds players to r=teams
letter_to_guardians(players[exp_and_non_exp_players_count],team_names[1]) # create a letter for each player
else: # rest of the exp and non exp players
sort_player_with_team(players[exp_and_non_exp_players_count],teams[2])# adds players to teams
letter_to_guardians(players[exp_and_non_exp_players_count],team_names[2]) # create a letter for each player
exp_and_non_exp_players_count+=1 # incrementing the count. This helps to works out how many players to add to each list
if __name__=="__main__":
#read the file in and sort experienced from non experienced players
with open(sys.argv[1],newline='')as csvfile:
reader =csv.DictReader(csvfile,delimiter=",")
for row in reader:
if row['Soccer Experience']=="YES":
experienced_players.append(row)# getting all exp players
else:
non_experienced_players.append(row)# getting all non exp players
# calculating the no of exp players for eachteam. list of exp players / no of teams
exp_players_per_team = len(experienced_players)/num_of_teams
# calculating the no of non exp players for eachteam. list of non exp players / no of teams
non_exp_players_per_team = len(non_experienced_players)/num_of_teams
assign_players_to_teams(experienced_players,[Raptors,Dragons,Sharks],["Raptors","Dragons","Sharks"],exp_players_per_team)
assign_players_to_teams(non_experienced_players,[Raptors,Dragons,Sharks],["Raptors","Dragons","Sharks"],non_exp_players_per_team)
create_team_sheet(Raptors,"Raptors")
create_team_sheet(Dragons,"Dragons")
create_team_sheet(Sharks,"Sharks")
| true |
d6a72ee4bc4cd43a6f63d8b3ae80751cceb5ca18 | Python | ktritz/fdp | /fdp/methods/fft.py | UTF-8 | 1,863 | 2.671875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 8 16:28:32 2016
@author: drsmith
"""
from warnings import warn
import matplotlib.pyplot as plt
from fdp.classes.utilities import isSignal, isContainer
from fdp.classes.fdp_globals import FdpWarning
from fdp.classes.fft import Fft
from . import utilities as UT
def fft(obj, *args, **kwargs):
"""
Calculate FFT(s) for signal or container.
Return Fft instance from classes/fft.py
"""
if isSignal(obj):
return Fft(obj, *args, **kwargs)
elif isContainer(obj):
signalnames = UT.get_signals_in_container(obj)
ffts = []
for sname in signalnames:
signal = getattr(obj, sname)
ffts.append(Fft(signal, *args, **kwargs))
return ffts
def plotfft(signal, fmax=None, *args, **kwargs):
"""
Plot spectrogram
"""
if not isSignal(signal):
warn("Method valid only at signal-level", FdpWarning)
return
sigfft = fft(signal, *args, **kwargs)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
pcm = ax.pcolormesh(sigfft.time,
sigfft.freq,
sigfft.logpsd.transpose(),
cmap=plt.cm.YlGnBu)
pcm.set_clim([sigfft.logpsd.max()-100, sigfft.logpsd.max()-20])
cb = plt.colorbar(pcm, ax=ax)
cb.set_label(r'$10\,\log_{10}(|FFT|^2)$ $(V^2/Hz)$')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Frequency (kHz)')
tmin = kwargs.get('tmin', 0)
tmax = kwargs.get('tmax', 2)
ax.set_xlim([tmin,tmax])
if fmax:
if sigfft.iscomplexsignal:
ax.set_ylim([-fmax,fmax])
else:
ax.set_ylim([0,fmax])
ax.set_title('{} | {} | {}'.format(
sigfft.shot,
sigfft.parentname.upper(),
sigfft.signalname.upper()))
return sigfft
| true |
ab18e50c659df0f08f94d96c7ad9530519ebbc7b | Python | vivekbarsagadey/accent | /accent-poc/src/recommender.py | UTF-8 | 2,148 | 3.28125 | 3 | [
"MIT"
] | permissive | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
import numpy
texts = ["This first text talks about houses and dogs",
"This is about airplanes and airlines",
"This is about dogs and houses too, but also about trees",
"Trees and dogs are main characters in this story",
"This story is about batman and superman fighting each other",
"Nothing better than another story talking about airplanes, airlines and birds",
"Superman defeats batman in the last round"]
#file = open('wordlist.txt', 'r')
#texts = file.readlines()
# vectorization of the texts
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)
# used words (axis in our multi-dimensional space)
words = vectorizer.get_feature_names()
print("words", len(words))
print(words)
print(X.shape)
n_clusters=3
number_of_seeds_to_try=10
max_iter = 300
number_of_process=2 # seads are distributed
model = KMeans( n_clusters=n_clusters,max_iter=max_iter, n_init=number_of_seeds_to_try).fit(X)
labels = model.labels_
# indices of preferible words in each cluster
ordered_words = model.cluster_centers_.argsort()[:, ::-1]
print("centers:", model.cluster_centers_)
print("labels", labels)
print("intertia:", model.inertia_)
texts_per_cluster = numpy.zeros(n_clusters)
for i_cluster in range(n_clusters):
for label in labels:
if label==i_cluster:
texts_per_cluster[i_cluster] +=1
print("Top words per cluster:")
for i_cluster in range(n_clusters):
print("Cluster:", i_cluster, "texts:", int(texts_per_cluster[i_cluster])),
for term in ordered_words[i_cluster, :10]:
print("\t"+words[term])
print("\n")
print("Prediction")
text_to_predict = "Why batman was defeated by superman so easy"
Y = vectorizer.transform([text_to_predict])
predicted_cluster = model.predict(Y)[0]
texts_per_cluster[predicted_cluster]+=1
print(text_to_predict)
print("Cluster:", predicted_cluster, "texts:", int(texts_per_cluster[predicted_cluster])),
for term in ordered_words[predicted_cluster, :10]:
print("\t"+words[term]) | true |
c7219d38fc264d9ee9553fe1958485c2fc64fd0e | Python | Aatish-Dhami/AD_Leetcode | /_1281.py | UTF-8 | 317 | 3.15625 | 3 | [] | no_license | class Solution:
def subtractProductAndSum(self, n: int) -> int:
sum = 0
product = 1
while n > 0:
sum = sum + (n % 10)
product = product * (n % 10)
n //= 10
return (product - sum)
n = 4421
c1 = Solution()
x = c1.subtractProductAndSum(n)
print(x) | true |
e3b50bf3ccf72dcc9c35a715cca4c3c877c57102 | Python | nailbiter/panoptic-submission | /py/image_analyzer.py | UTF-8 | 1,080 | 2.84375 | 3 | [] | no_license | import sys;
import cv2;
import argparse;
#procedures
def parseArgs():
parser = argparse.ArgumentParser();
parser.add_argument('--mode',type=str,default='COUNTPIXELS',help='');
parser.add_argument('files',type=str,nargs='+');
args = parser.parse_args();
return vars(args);
def countPixels(filename,args):
image = cv2.imread(filename,-1);
shape = image.shape;
print("shape: {}".format(shape));
dic = {};
for x in range(shape[0]):
for y in range(shape[1]):
pix = tuple(image[x,y]);
if( pix not in dic ):
dic[pix] = 0;
dic[pix] = dic[pix]+1;
keys = sorted(dic.keys());
print("{} different values".format(len(keys)));
for key in keys:
print("{0:<20}: {1:<20}".format(str(key),dic[key]));
#main
args = parseArgs();
for filename in args['files']:
print("****** process {} with {} ******".format(filename,args['mode']));
if(args['mode'] == 'COUNTPIXELS'):
countPixels(filename,args);
else:
print("unknown mode {}".format(args['mode']));
| true |
d163b0d227a72608eb83ed04fa43c87fd610dc83 | Python | zx1989031/pytest | /layNumber.py | UTF-8 | 80 | 2.6875 | 3 | [] | no_license | #coding:utf8
strnum = {}
for x in range(0,12,1):
strnum[x]=x+1
print strnum | true |
c62213f45798ce4647c55c1efaf0c773cfa105df | Python | TPei/Base-Converter | /Python/decode.py | UTF-8 | 570 | 4.25 | 4 | [] | no_license | '''
decode a number from any base to base 10
'''
def decode(number, source_base):
result = 0
number_of_digits = len(number)
for index in range (0, number_of_digits):
digit = number[index]
result = result + int(digit) * pow(source_base, index)
return result
if __name__ == '__main__':
print 'Encoding a number from any base to base ten...'
# number needs to be reversed because we want to go through right to left
number = raw_input('Choose a number to convert: ')[::-1]
base = int(raw_input('Choose a base to convert from: '))
print decode(number, base) | true |
c90d623de4138ad7720a409ffa454bc79f07bd9d | Python | maumruiz/BasicAgents | /PartiallyObservableEnvironment.py | UTF-8 | 1,634 | 3.09375 | 3 | [] | no_license | import numpy as np
from FullyObservableEnvironment import FullyObservableEnvironment
from ModelBasedAgent import ModelBasedAgent
from agents import *
from Objects import *
'''
This class is a representation of a Partially Observable Environment
where some of the information required for optimal decision making is
hidden until it emerges due to Agents' level activity.
'''
class PartiallyObservableEnvironment(FullyObservableEnvironment):
'''Creates a PartiallyObservableEnvironment as a subclass of FullyObservableEnvironment,
they have the same function but the Partially Observable one is limited to a radius of information
around the agent.
'''
def __init__(self):
FullyObservableEnvironment.__init__(self)
self.radius_of_vision = 1
def percept(self, agent):
'''Only perceive near things'''
x, y = agent.location
near_locations = [(x-1, y-1), (x-1, y), (x-1, y+1), (x, y-1), (x, y), (x, y+1), (x+1, y-1), (x+1, y), (x+1, y+1)]
things_near = []
for loc in near_locations:
things_near += self.percepts_from(agent, loc)
return things_near
def percepts_from(self, agent, location, tclass=Thing):
''' Get percepts from a defined location'''
things = self.list_things_at((location[0], location[1]))
percepts = [(p, distance_m(agent.location, p.location), p.location) for p in things if not isinstance(p, Agent)]
return percepts
def print_agent_percept(self, agent, percepts):
agent.print_percepts(percepts, self.radius_of_vision)
| true |
6616f3fe79952179209f75a0eae475d9fa391ffe | Python | destinyu/Python_Crash_Crouse | /traceback_practise_10.py | UTF-8 | 577 | 4.15625 | 4 | [] | no_license | #10——6
print("Give me two numbers,and i'll plus them.")
print("Enter 'q' to quit.")
while True:
first_number=input("\nFirst number: ")
if first_number=='q':
break
second_number=input("\nSecond number: ")
try:
answer=int(first_number)+int(second_number)
except ValueError:
print("You must input two numbers")
else:
print(answer)
#10_10
filename='Alice in Wonderland.txt'
with open(filename) as f_obj:
contents = f_obj.read()
num=contents.lower().count('the')
print("The 'the' has come out "+str(num)+" times")
| true |
1254fa3256bf5bc4fbcb494cee21c51c45265c75 | Python | Statistical-model-in-R-and-Python/python-data-science-indrani-sen2003 | /hello_test.py | UTF-8 | 88 | 2.515625 | 3 | [] | no_license | import pandas as pd;
df=pd.read_csv("Walmart2.csv");
df.dtypes
df.head(15)
df.tail(15)
| true |
631316cfc067232103503a5696be32c7df73dd98 | Python | Jigar710/Python_Programs | /networking/client3.py | UTF-8 | 275 | 2.796875 | 3 | [] | no_license | import socket
ip = socket.gethostname()
port = 1600
s = socket.socket()
s.connect((ip,port))
while True:
msg = s.recv(1024).decode()
print("server says :",msg)
if msg=='bye':
break;
msg = input("Enter msg : ")
s.send(msg.encode())
if msg=='bye':
break; | true |
454ab20a3eb0cb13da1248ae1f1690f792efd0e6 | Python | Zer0xPoint/Algorithms4_python | /1.Fundamentals/3.Bag Queue And Stack/44.py | UTF-8 | 880 | 3.625 | 4 | [] | no_license | import random
from algs4.Stack import Stack
class Buffer:
def __init__(self):
self.__right = Stack()
self.__left = Stack()
self.__N = 0
def insert(self, c):
self.__right.push(c)
self.__N += 1
def delete(self):
self.__N -= 1
return self.__right.pop() if not self.__right.is_empty() else ''
def left(self, k):
for i in range(k):
if self.__left.is_empty():
return
self.__right.push(self.__left.pop())
def right(self, k):
for i in range(k):
if self.__right.is_empty():
return
self.__left.push(self.__right.pop())
def size(self):
return self.__N
b = Buffer()
for i in range(100):
b.insert(random.randint(0, 99))
b.right(10)
print(b.delete())
b.left(5)
print(b.delete())
print(b.size())
| true |
0d6fee50cea3d9e1898079b37846a6748f42aa3c | Python | imrivera/TuentiChallenge2013 | /18 - Energy will be infinities/18-energy_will_be_infinities.py | UTF-8 | 3,930 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env pypy
# -*- coding: utf-8 -*-
# Tuenti Challenge 3
#
# Challenge 18 - Energy will be infinities
# To infinity and beyond!
import sys
# First find the strongly connected components of the graph with Tarjan's algorithm
# and then apply the Bellman-Ford in each of the components to find positive cycles
class Vertex:
def __init__(self, number = None):
self.output_edges = set()
self.number = number
self.index = None
def add_edge(self, w, cost):
self.output_edges.add((w, cost))
def __str__(self):
return "<Vertex %s>" % (self.number)
def __repr__(self):
return "<Vertex %s>" % (self.number)
def tarjan(V):
list_of_sets = []
def strongconnect(v, index, S, set_S):
v.index = index[0]
v.lowlink = index[0]
index[0] += 1
S.append(v)
set_S.add(v)
for w, cost in v.output_edges:
if w.index is None:
strongconnect(w, index, S, set_S)
v.lowlink = min(v.lowlink, w.lowlink)
elif w in set_S:
v.lowlink = min(v.lowlink, w.index)
if v.lowlink == v.index:
new_set = []
while True:
w = S.pop()
set_S.discard(w)
new_set.append(w)
if w == v:
break
new_set.reverse()
list_of_sets.append(new_set)
S = []
index = [0]
for v in V:
v.index = None
for v in V:
if v.index is None:
strongconnect(v, index, S, set())
return list_of_sets
def bellman_ford_find_cycle(V, edge_list, source):
''' Returns True is there is any negative cycle '''
# Initialize distance to 1.0 because our weights are multiplied, not added
for v in V:
if v == source:
v.distance = 1.0
else:
v.distance = None
for i in xrange(len(V) - 1):
for u, v, cost in edge_list:
if u.distance is not None:
if (v.distance is None) or (u.distance * cost < v.distance):
v.distance = u.distance * cost
for u, v, cost in edge_list:
if (v.distance is None) or (u.distance * cost < v.distance):
return True
return False
if __name__ == '__main__':
sys.setrecursionlimit(50000)
num_cases = int(sys.stdin.readline())
for num_case in range(num_cases):
#print "num_case = ", num_case
number_vertices = int(sys.stdin.readline())
number_edges = int(sys.stdin.readline())
V = []
for i in xrange(number_vertices):
V.append(Vertex(i))
for n in xrange(number_edges):
id_source, id_dest, cost = [ int(x) for x in sys.stdin.readline().split() ]
V[id_source].add_edge(V[id_dest], cost)
# Look for a node without output edges, that will be an error
buggy = False
list_of_sets = tarjan(V)
for scc in list_of_sets:
# Check for infinite positive cycle in each component
# Generate an edge list only for our component
edge_list = []
for v in scc:
for w, cost in v.output_edges:
if w in scc:
# Normally Bellman-Ford detects negative cycles
# Invert the cost to detect positive energy cycles
edge_list.append((v, w, 1.0 / (1.0 + (cost / 100.0) )))
buggy = bellman_ford_find_cycle(scc, edge_list, scc[0])
if buggy:
break
print buggy
| true |
243c48d3e28d41d0c18072f52da223e3d8a75d24 | Python | Devin6Tam/python_example | /ting89_vocal_story/vocal_story_example01.py | UTF-8 | 2,046 | 2.53125 | 3 | [] | no_license | """
============================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/9 15:00
# @Author : tanxw
# @Desc : 幻听网-有声小说
============================
"""
from urllib.parse import urljoin
from lxml import etree
import re
import requests
def downs(url):
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
for i in range(1, 452):
ss = '大明王侯'
nsss = ss+str(i)
response = requests.get(url, headers=headers)
response.encoding = 'gb2312'
# print(response.text)
# dems = etree.HTML(response.text)
# # print(dems)
# nodos = dems.xapth('')
# print(nodos)
ns = re.findall(r'''<script>var param=getAspParas.*;var datas=(.*).split.*;</script>''',response.text)
# print(ns)
nss = str(ns)[4:54]
# print(nss)
with open('有声小说/{}.mp3'.format(nsss), 'wb')as f :
music = requests.get(nss)
f.write(music.content)
print('%s下载完毕'%nsss)
def urlm():
urls = 'http://www.ting89.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
url_s = 'http://www.ting89.com/books/11165.html'
response = requests.get(url_s, headers=headers)
response.encoding = 'gb2312'
# print(response.text)
dom = etree.HTML(response.text)
# print(dom)
nodes = dom.xpath('//div[@class="compress"]/ul/li')
# print(nodes)
url_list = []
for node in nodes:
dic = {}
dic['title'] = node.xpath('./a/text()')[0]
dic['url'] = urljoin(urls, node.xpath('./a/@href')[0])
url_list.append(dic['url'])
urls = url_list[0:452]
for url in urls:
# print(url)
# for url in url_list:
# if 'playbook' in url:
# print(url)
downs(url)
urlm()
| true |
3bf47f159ef311013ffc18fe6f9ce8cd0707b435 | Python | ShadowElf37/ProjectMercury | /lib/server/response.py | UTF-8 | 10,658 | 2.515625 | 3 | [] | no_license | """
response.py
Project Mercury
Yovel Key-Cohen and Alwinfy
"""
ENCODING = 'UTF-8'
from os.path import dirname, realpath
from re import split
from urllib.parse import unquote
def create_navbar(active, logged_in):
"""kwargs should be 'Home="home.html"'; active should be "home.html" """
navbar = []
pages = []
links = []
enabled = []
cfg = open('conf/navbar.cfg', 'r')
data = cfg.read()
for line in list(reversed(data.split('\n'))):
l = line.split()
l[0] = l[0].split('|')
pages.append(l[0])
links.append(l[1])
enabled.append(l[2])
cfg.close()
for i in range(len(pages)):
if (pages[i][0] != '_' and not logged_in) or (pages[i][1] != '_' and logged_in):
if enabled[i] == 'e':
navbar.append('<li><a href="/{0}"{2}>{1}</a></li>'.format(links[i],
(pages[i][0] if not logged_in else pages[i][1]),
(' class="active-nav"' if links[i] == active else '')))
else:
navbar.append('<li><a class="disabled-nav">{0}</a></li>'.format((pages[i][0] if not logged_in else pages[i][1])))
bar = '<center>\n\t<div id="menu-bar" class="menu-bar">\n\t\t<ul class="nav-bar">\n\t\t\t' \
+ '\n\t\t\t'.join(navbar) \
+ '\n\t\t\t<li class="page-title">Project Mercury</li>\n\t\t</ul>\n\t</div>\n</center>'
return bar
def js_escape(d):
d = d.replace('+', ' ')
i = d.find('%')
while True:
i = d.find('%')
code = d[i + 1:i + 3]
if i == -1:
break
d = d.replace('%' + code, '&#x{};'.format(code))
return d
def render(text, **resources):
if type(text) == type(bytes()):
try:
text = text.decode(ENCODING)
except Exception as e:
print(text)
raise e
for i in list(resources.keys()):
# print('#', '[['+i+']]')
# print('@', resources[i])
text = text.replace('[['+i+']]', str(resources[i]))
while text.find('{{') != -1:
s = text.find('{{')+2
e = text.find('}}')
t = text[s:e]
try:
v = str(eval(t))
except Exception as e:
v = '<span style="color: red;">%RenderError%<span>'
text = text.replace('{{'+t+'}}', v)
return text.encode(ENCODING)
class Response:
# Easy response codes
REDIRECTS = [301, 302, 303, 307, 308]
codes = {}
ext = {}
folders = {}
@staticmethod
def code(hcode, **kwargs):
r = Response(hcode)
if hcode in Response.REDIRECTS:
if kwargs.get("location") == None:
raise TypeError("{} Errors must include redirect address".format(hcode))
else:
r.add_header_term('location', (kwargs["location"]))
else:
for k, v in kwargs:
r.add_header_term(k, v)
return r
def __init__(self, code=200, body='', **kwargs):
if len(self.codes) == 0:
with open('conf/codes.cfg', 'r') as code:
for line in code:
splitted = line.split()
Response.codes[int(splitted[0])] = ' '.join(splitted[1:])
with open('conf/ext.cfg', 'r') as exts:
for line in exts:
splitted = line.split()
for e in splitted[1:]:
Response.ext[e] = splitted[0]
with open('conf/folders.cfg', 'r') as exts:
for line in exts:
splitted = line.split()
for e in splitted[1:]:
Response.folders[e] = splitted[0]
self.header = []
self.header.append('HTTP/1.1 {} {}'.format(code, Response.codes.get(code, '[undefined]')))
#print(self.header)
self.cookie = []
self.body = body
self.logged_in = False
self.default_renderopts = dict()
self.error = ''
if type(self.body) == type(int()):
self.set_status_code(self.body, **kwargs)
self.body = ''
# Adds a field to the header (ie 'Set-Cookie: x=5')
def add_header_term(self, field, string):
#print(self.header)
self.header.append("{}: {}".format('-'.join(i.title().replace("Id", "ID").replace("Md5", "MD5") for i in split('[ _-]+', field)), string))
# Easier way of setting cookies than manually using add_header_term()
def add_cookie(self, key, value, *flags):
self.cookie.append(("Set-Cookie: %s=%s; " % (key, value)) + '; '.join(flags))
# Sets the status code
def set_status_code(self, code, **kwargs):
self.header = Response.code(code, **kwargs).header
# Sets the header; use if there's no other way
def set_header(self, lst):
self.header = lst
# Sets body if you changed your mind after init
def set_body(self, string):
self.body = string
# Puts a file in the body
def attach_file(self, faddr, nb_page='none', logged_in=None, rendr=True, rendrtypes=(), **renderopts):
"""faddr should be the file address accounting for ext.cfg
rendr specifies whether the page should be rendered or not (so it doesn't try to render an image)
rendrtypes adds extra control when you don't know if you'll be passed an image or a webpage and want to only render one; should be a tuple of files exts
renderopts is what should be replaced with what; if you have [[value]], you will put value='12345' """
if nb_page == 'none':
nb_page = faddr
renderopts['navbar'] = create_navbar(nb_page, self.logged_in if logged_in is None else logged_in)
if type(rendrtypes) != type(tuple()):
raise TypeError("rendrtypes requires tuple")
prefixa = 'web/'
prefixb = self.ext.get(faddr.split('.')[-1], '')
prefixc = '' #self.folders.get(faddr, '')
# Get browser caching config
name = faddr.split('/')[-1]
caching = open('conf/cache.cfg', 'r').read().split('\n')
cache = ''
last = ''
for line in caching:
l = line.split()
if (line+' ')[0] == 'f' and l[1] == name:
try:
cache = last = l[2]
except IndexError:
cache = last
continue
elif (line+' ')[0] == 't' and l[1] == name.split('.')[-1]:
try:
cache = last = l[2]
except IndexError:
cache = last
continue
if cache:
self.add_header_term('Cache-Control', 'max-age='+cache)
fo = faddr.split('/')[-1]
faddr = prefixa + prefixc + faddr
found = False
last = False
# Actual body set and finding file in parent directories
for i in range(10): # Don't even try this more than ten times
try:
if not faddr or faddr == fo:
last = True
faddr = prefixb + fo
continue
f = open(faddr, 'rb')
if rendr and (rendrtypes == () or faddr.split('.')[-1] in rendrtypes):
renderopts.update(self.default_renderopts)
fl = render(f.read(), **renderopts)
else:
fl = f.read()
self.set_body(fl)
f.close()
found = True
break
except (FileNotFoundError, PermissionError):
if last:
break
faddr = '/'.join(faddr.split('/')[:-2] + [fo,])
continue
if not found:
self.set_status_code(404)
# Throws together the header, cookies, and body, encoding them and adding whitespace
def compile(self):
return self.__bytes__()
def __bytes__(self):
try:
b = self.body.encode(ENCODING)
except AttributeError:
b = self.body
return '\r\n'.join(self.header).encode(ENCODING) + b'\r\n' + '\r\n'.join(self.cookie).encode(ENCODING) + b'\r\n' * (2 if self.cookie else 1) + b
class Request:
def __init__(self, request):
self.request_text = request
self.req_list = self.parse(request)
if self.req_list == 'ERROR_0':
return
self.method = self.req_list[0]
self.address = self.req_list[1][1:]
if self.address[0] in ('http:', 'https:'):
self.address = self.address[3:]
self.file_type = self.address[-1].split('.')[-1]
self.flist = list(map(lambda x: x.split(': '), self.req_list[2]))
self.flags = dict(self.flist[:-2])
# All this is what allows us to have multiple values for one key in post
try:
pv_primer = list(map(lambda x: x.strip().split('='), self.flist[-1][0].strip().split('&')))
counter = dict()
for pair in pv_primer:
if not counter.get(pair[0]):
counter[pair[0]] = [pair[1],]
else:
counter[pair[0]].append(pair[1])
self.post_values = dict([(k,v) if (len(v) != 1) else (k,v[0]) for k,v in counter.items()]) if self.flist[-1][0] else dict()
except (IndexError, ValueError):
self.post_values = dict()
try:
self.cookies = dict(
map(lambda x: x.strip().split('='), self.flags['Cookie'].strip().split(';'))) if self.flags.get(
'Cookie') else dict()
except ValueError:
print('post###', self.flags[-1])
print('cook@@@', self.flags[-3])
print('all$$$', self.req_list[2])
raise ValueError('REALLY BAD ERROR IN REQUEST')
def get_cookie(self, cname):
return self.cookies.get(cname, None)
def get_last_page(self):
p = self.flags.get('Referer', self.get_cookie('page'))
if 'http://' in p:
p = '/'.join(p.split('/')[3:])
return p
def get_post(self, key):
return unquote(self.post_values.get(key, '').replace('+', ' '), 'UTF-8')
@staticmethod
def parse(request):
req = request.split('\r\n')
# Reduce the request to a list
request2 = request.split(' ')
try:
request = [request2[0], request2[1].split('/'), req[2:]] # [GET, xx/x.x, [x:xx, x:xx]]
except IndexError: # Sometimes this happens?
return 'ERROR_0'
return request
| true |
a14971229dd10bbf9c7dfd17279968e09c032f17 | Python | olesmith/SmtC | /Display/Body.py | UTF-8 | 1,710 | 3.0625 | 3 | [
"CC0-1.0"
] | permissive |
class Display_Body():
##!
##! Generates HTML BODY.
##!
def Display_Body(self):
html=[]
html=html+[ self.XML_Tag_Start("BODY") ]
args={
"width": "100%",
"border": "1",
}
html=html+[ self.XML_Tag_Start("TABLE",args) ]
html=html+self.Display_Top()
html=html+self.Display_Middle()
html=html+self.Display_Bottom()
html=html+[ self.XML_Tag_End("TABLE") ]
html=html+[ self.XML_Tag_End("BODY") ]
return html
def Display_Cell(self,horisontal,vertical):
html=[]
##hack to make css classes become right
if (horisontal=="Top"): n=0
elif (horisontal=="Middle"): n=1
else: n=2
if (horisontal=="Left"): m=0
elif (horisontal=="Center"): m=1
else: m=2
widths={
"Left": "20%",
"Center": "70%",
"Right": "10%",
}
args={
"width": widths[ vertical ],
#"class": horisontal+"_"+vertical
"class": " ".join([
self.Body_Matrix_TR_CSS[ n ]+" "+self.Body_Matrix_TD_CSS[ m ],
]),
}
html=html+[ self.XML_Tag_Start("TD",args) ]
method="Display_"+horisontal+"_"+vertical+"_Cell"
if (hasattr(self,method)):
method=getattr(self,method)
html=html+method()
else:
html=html+[ horisontal+"_"+vertical ]
html=html+[ self.XML_Tag_End("TD") ]
return html
| true |
33914735ea94144c7b60c53804da26414f7f9154 | Python | uwescience/raco | /raco/myrial/keywords.py | UTF-8 | 825 | 2.625 | 3 | [] | no_license | """Emit all Myrial/SQL keywords as lowercase strings."""
from raco.myrial.scanner import (builtins, keywords,
types, comprehension_keywords,
word_operators)
from raco.expression.expressions_library import EXPRESSIONS
def get_keywords():
"""Return a list of Myrial/SQL keywords.
This includes reserved lex tokens and system-defined functions.
"""
return {
'builtins': sorted(
EXPRESSIONS.keys() + [kw.lower() for kw in builtins]),
'keywords': sorted(kw.lower() for kw in keywords),
'types': sorted(kw.lower() for kw in types),
'comprehension_keywords': sorted(
kw.lower() for kw in comprehension_keywords),
'word_operators': sorted(kw.lower() for kw in word_operators),
}
| true |
cf7da661b542146c48e735dc600f69aa99c547ca | Python | sunminky/algorythmStudy | /알고리즘 스터디/3차/16주차/GasStation.py | UTF-8 | 971 | 3.171875 | 3 | [] | no_license | # https://www.acmicpc.net/problem/13305
import sys
if __name__ == '__main__':
n_gasStation = int(sys.stdin.readline())
distance = list(map(int, reversed(sys.stdin.readline().split())))
cost_dict = dict() #기름가격별 도착지에서 가장 먼 노드 저장
max_distance = 0 #출발지에서 도착지의 거리
cur_loc = 0
answer = 0
for seq, _cost in enumerate(map(int, reversed(sys.stdin.readline().split()[:-1]))):
max_distance += distance[seq] #도착지까지의 거리
cost_dict[_cost] = max_distance
#기름 가격이 싼 순서대로 탐색
for k in sorted(cost_dict.keys()):
#이전에 기름 넣었던 위치보다 더 멀어진 경우
if cost_dict[k] > cur_loc:
answer += k * (cost_dict[k] - cur_loc)
cur_loc = cost_dict[k]
# 출발지에 도착하면 종료
if cur_loc == max_distance:
break
print(answer)
| true |
62843076f2c47d90996122d6ff4a742809818b9e | Python | 10qpal/kfq_python | /flask/flaskjinja/app.py | UTF-8 | 1,206 | 2.640625 | 3 | [] | no_license | from flask import Flask, request, render_template, send_from_directory, redirect, url_for
import os
UPLOAD_DIRECTORY = os.path.dirname(__file__)+'/files'
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload')
def upload():
return render_template('upload.html')
# 파일 업로드
@app.route('/fileUpload', methods=['POST'])
def fileUpload():
f = request.files['file']
# 저장할 경로 + 파일명
dirname = os.path.dirname(__file__)+'/files/'+f.filename
# print(dirname)
f.save(dirname)
return redirect('/files')
# 업로드한 파일 목록
@app.route('/files')
def list_files():
files = []
for filename in os.listdir(UPLOAD_DIRECTORY):
path = os.path.join(UPLOAD_DIRECTORY, filename)
if os.path.isfile(path):
files.append(filename)
return render_template('list.html', files=files)
# 파일 다운로드
@app.route('/files/<path:path>')
def get_file(path):
return send_from_directory(UPLOAD_DIRECTORY, path, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True,port=8089) | true |
49dd082a63132526c9b78b502e7cb2365ab34f2d | Python | kharddie/is-pepsi-okay | /IsPepsiOkay/database/better_pop.py | UTF-8 | 1,109 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
import os
import MySQLdb
import sys
import re
from bs4 import BeautifulSoup
def check_type(column_names):
"""
column_names: (list of strings) MySQL column names)
"""
t = {}
def build_query(filename, table_name, column_names, column_numbers,
type_convert, offset=0):
"""
filename: (string) absolute path to UCI data file
table_name: (string) MySQL table name
column_names: (list of strings) MySQL column names
column_numbers: (list of integers) UCI column numbers
type_convert: (list of types) type conversions if necessary
"""
assert len(column_names) == len(column_numbers)
cols = ",".join(column_names)
QUERY = """INSERT INTO %s (%s) VALUES """ % (table_name, cols)
# keep track of how many
count = 0
with open(filename, 'r') as f:
soup = BeautifulSoup(f.read())
tables = soup.findAll('table')
for table in tables[offset:]:
for row in table.findAll('tr')[1:]: # first row is header always
cells = row.findAll('td')
if len(cells) > 0:
| true |
4c55e96bec6501d9885a232b587c4d63a1ec79d6 | Python | Hygens/hackerearth_hackerrank_solutions | /python_problems_competitive/LittleShinoandFibonacci_2.py | UTF-8 | 702 | 2.875 | 3 | [] | no_license | from decimal import Decimal,getcontext
import sys
sys.setrecursionlimit(10000000)
getcontext().prec=10**1000
M = 1000000007
def fibSum2(n):
v1, v2, v3 = Decimal(1), Decimal(1), Decimal(0)
if n==0 or n==1: return 0
elif n==2: return 1
else:
n+=1
for rec in bin(n)[3:]:
calc = v2*v2
v1, v2, v3 = Decimal(v1*v1+calc), Decimal((v1+v3)*v2), Decimal(calc+v3*v3)
if rec=='1': v1, v2, v3 = v1+v2, v1, v2
return v2-1
n = int(sys.stdin.readline().strip())
while n>0:
l,r = map(long,sys.stdin.readline().strip().split(' '))
s1 = fibSum2(l-1)
s2 = fibSum2(r)
s = (s2-s1)%10000
print(s%M)
n-=1 | true |
f0d6283f9b1f79247ff70268cdf983228cd0c3f6 | Python | HectorZetino/PythonPractices | /Problems/Update a list/task.py | UTF-8 | 58 | 3.109375 | 3 | [] | no_license | numbers = [4, 1, 0, 3, 2, 5]
numbers.sort()
print(numbers) | true |
e7594334c9993e0fe65f5fd758e78d402ca66698 | Python | devmittal/EID-Final-Project | /mic.py | UTF-8 | 3,676 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python3
import pyaudio
import wave
import logging
import boto3
import time
from botocore.exceptions import ClientError
import json
import requests
form_1 = pyaudio.paInt16 # 16-bit resolution
chans = 1 # 1 channel
samp_rate = 44100 # 44.1kHz sampling rate
chunk = 4096 # 2^12 samples for buffer
record_secs = 5 # seconds to record
dev_index = 1 # device index found by p.get_device_info_by_index(ii)
wav_output_filename = 'test1.wav' # name of .wav file
bucket_name = 'eid-superproject'
def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name
# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True
# purpose: get and return the transcript structure given the provided uri
def getTranscript( transcriptURI ):
# Get the resulting Transcription Job and store the JSON response in transcript
result = requests.get( transcriptURI )
return result.text
def transcribe_file(file_name, bucket):
transcribe = boto3.client('transcribe')
s3 = boto3.client('s3')
job_name = "Test_EID11"
result_file_name = "%s.json" % (file_name)
job_uri = "s3://%s/%s" % (bucket, file_name)
transcribe.start_transcription_job(
TranscriptionJobName=job_name,
Media={'MediaFileUri': job_uri},
MediaFormat='wav',
LanguageCode='en-US'
#OutputBucketName=bucket
)
while True:
status = transcribe.get_transcription_job(TranscriptionJobName=job_name)
if status['TranscriptionJob']['TranscriptionJobStatus'] in ['COMPLETED', 'FAILED']:
break
print("Not ready yet...")
time.sleep(5)
print("Ready")
# Now get the transcript JSON from AWS Transcribe
transcript = getTranscript( str(status["TranscriptionJob"]["Transcript"]["TranscriptFileUri"]) )
data = json.loads(transcript)
Actual_Transcript = data['results']['transcripts'][0]['transcript']
print("Spoken CMD = " + Actual_Transcript)
if(Actual_Transcript == "identify."):
print("Capture Image")
else:
print("Do not capture Image")
def capture_audio():
audio = pyaudio.PyAudio() # create pyaudio instantiation
# create pyaudio stream
stream = audio.open(format = form_1, rate = samp_rate, channels = chans, input_device_index = dev_index,input = True, frames_per_buffer=chunk)
print("recording")
frames = []
# loop through stream and append audio chunks to frame array
for ii in range(0,int((samp_rate/chunk)*record_secs)):
data = stream.read(chunk, exception_on_overflow = False)
frames.append(data)
print("finished recording")
# stop the stream, close it, and terminate the pyaudio instantiation
stream.stop_stream()
stream.close()
audio.terminate()
# save the audio frames as .wav file
wavefile = wave.open(wav_output_filename,'wb')
wavefile.setnchannels(chans)
wavefile.setsampwidth(audio.get_sample_size(form_1))
wavefile.setframerate(samp_rate)
wavefile.writeframes(b''.join(frames))
wavefile.close()
capture_audio()
upload_file(wav_output_filename, bucket_name)
transcribe_file(wav_output_filename, bucket_name)
| true |
7604750c6e0996b5e624c23947d1bc277e6caf4e | Python | zy31415/blackjack | /blackjack/game.py | UTF-8 | 2,981 | 3.109375 | 3 | [] | no_license | import random
from .player import Player, Dealer
class Game(object):
def __init__(self, player=None):
self.dealer = None
self.player = Player() if player is None else player
self.dealer = Dealer()
self.verbose = True
self.faceup = None
@staticmethod
def draw():
card = random.randint(1, 13)
return card if card < 10 else 10
def init(self):
if self.verbose:
print('Game start.')
faceup = self.draw()
self.dealer.init(faceup=faceup, card1=faceup, card2=self.draw())
self.player.init(faceup=faceup, card1=self.draw(), card2=self.draw())
if self.verbose:
print(' Init:')
print(' Faceup: %d, %s' % (faceup, self._str_players_status()))
self.faceup = faceup
def play(self):
reward = self._play()
self.player.finish(reward)
self.dealer.finish(reward)
return reward
def _play(self):
# when player has a natural:
if self.player.sum == 21:
reward = 0 if self.dealer.sum == 21 else 1
if self.verbose:
print('Game over.')
print(' Player has a natural. Reward: %d.' % reward)
return reward
if self.verbose:
print(" Player's Round:")
while True:
if self.player.if_hit():
_draw = self.draw()
self.player.hit(_draw)
if self.verbose:
print(" " + "Draw %d, " % _draw + self._str_players_status())
else:
self.player.stick()
break
if self.player.if_busted():
if self.verbose:
print('Game Over. Player is lost. He is busted')
return -1
if self.verbose:
print(" Dealer's Round:")
while True:
if self.dealer.if_hit():
_draw = self.draw()
self.dealer.hit(_draw)
if self.verbose:
print(" " + "Draw %d, " % _draw + self._str_players_status())
else:
self.dealer.stick()
break
if self.dealer.if_busted():
if self.verbose:
print('Game Over. Dealer is lost. He is busted')
return -1
if self.player.sum == self.dealer.sum:
if self.verbose:
print('Game Over. Tie.')
return 0
if 21 - self.player.sum < 21 - self.dealer.sum:
if self.verbose:
print('Game Over. Player wins.')
return 1
if self.verbose:
print('Game Over. Dealer wins.')
return -1
def _str_players_status(self):
da = "(A)" if self.dealer.usable_ace else ""
pa = "(A)" if self.player.usable_ace else ""
return "Dealer: %d%s, Player: %d%s" % (self.dealer.sum, da, self.player.sum, pa)
| true |
33ced9682d05a054df234f452505ba56708eef60 | Python | almirms/adventofcode | /day5/trampolines.py | UTF-8 | 1,191 | 3.390625 | 3 | [] | no_license | import os
import input_file
def jump(current_position, jumps):
jump_size = int(jumps[current_position])
jumps[current_position] = int(jumps[current_position]) + 1
current_position += jump_size
return current_position, jumps
def jump_part2(current_position, jumps):
jump_size = int(jumps[current_position])
if jump_size >= 3:
jumps[current_position] = int(jumps[current_position]) - 1
else:
jumps[current_position] = int(jumps[current_position]) + 1
current_position += jump_size
return current_position, jumps
diretorio = os.path.dirname(os.path.abspath(__file__))
input_string = input_file.read_lines(diretorio)
jumps = list(input_string)
jumps = [s.strip() for s in jumps]
jumps_part1 = jumps[:]
jumps_part2 = jumps[:]
jumps_size = len(jumps)
current_position = 0
iterations = 0
while current_position < jumps_size:
iterations += 1
current_position, jumps_part1 = jump(current_position, jumps_part1)
print(iterations)
current_position = 0
iterations = 0
while current_position < jumps_size:
iterations += 1
current_position, jumps_part2 = jump_part2(current_position, jumps_part2)
print(iterations)
| true |
2c10674189b5af01750b90e15403f3c7ccb02369 | Python | lazyjek/MachineLearning-Course | /homework3/src/main.py | UTF-8 | 1,036 | 2.734375 | 3 | [] | no_license | import sys
from data_provider import data_provider
from cv import CrossValidate
from perceptron import Perceptron
if __name__ == '__main__':
try:
trainFileName = sys.argv[1]
nfolds = int(sys.argv[2])
learningRate = float(sys.argv[3])
epochNum = int(sys.argv[4])
except:
print >> sys.stderr, '[ERROR] wrong input format! 4 inputs: [string] [int] [float] [int]'
attrNum, labels, instances = data_provider(trainFileName)
cv = CrossValidate(nfolds, instances, labels)
"""
output: fold_of_instance | predicted_class | actual_class | confidence_of_prediction
"""
perceptron = Perceptron(attrNum, labels, learningRate, epochNum)
# nfolds training
for i in range(nfolds):
train, test = cv.fold(i)
perceptron.fit(train[0], train[1])
confidences = perceptron.confidence(test[0])
predict = perceptron.predict(test[0])
for j in range(test[0].shape[0]):
print i, predict[j][0], test[1][j], '%6f'%confidences[j]
| true |
1ff2b9c520599d5db980113cb62b55c99830f741 | Python | sdvinay/lounge_trivia_bot | /lounge_parser.py | UTF-8 | 1,459 | 3.078125 | 3 | [] | no_license | from bs4 import BeautifulSoup
class LoungePost:
""" A lounge post"""
def get_lounge_posts(fp):
soup = BeautifulSoup(fp, features="lxml")
for post in soup('div', 'post'): # <div class="post">
response = LoungePost()
response.text = post.text
response.soup = post.parent.parent.parent
response.username = post.parent.parent.a.text
if 'Harold' in response.username:
continue
response.time = response.soup.find_all('td')[1].text[8:]
response.num = response.soup.find_all('a')[3].text[2:]
response.id = response.soup.find_all('a')[3]['name']
yield response
def get_guesses(fp):
for response in get_lounge_posts(fp):
if '#LoungeTrivia_86Mets' not in response.text:
continue
# The guesses are in the text that follows the quote
# So find the quote, and then move to the following siblings
cursor = response.soup.blockquote
response.guesses = []
# guesses might be in separate <p>s or in separate lines in one <p>
while cursor and cursor.find_next_sibling('p'):
cursor = cursor.find_next_sibling('p')
response.guesses += cursor.text.split("\n")
yield(response)
if __name__ == "__main__":
with open("fixtures/lounge_6329_600.html") as fp:
for r in get_guesses(fp):
print(f"{r.id} {r.num} {r.time[14:]} | {r.username}, {r.guesses}")
| true |
3acad0a89d8d597ca24495d9f5b600060a00bbd5 | Python | bruno5182/coronavirus-analysis | /coronavirus/python_scripts/us_data_cleaner.py | UTF-8 | 4,268 | 3.34375 | 3 | [
"MIT"
] | permissive | """
US data format was changed in the JHU data.
This class should help handle standardizing it.
"""
# pylint: disable=invalid-name, line-too-long
import os
from datetime import datetime
import pandas as pd
class USDataCleanUp:
"""
Take in a dataset, clean up the US data that has changed format,
and then aggregate back into main dataset
"""
def __init__(self, df, key_col):
self.original_df = df
# self.cleaned_us_data = pd.DataFrame()
self.data = pd.DataFrame()
self.key_col = key_col
self.US_old = pd.DataFrame()
self.US_new = pd.DataFrame()
def setup_US_data(self):
"""
Add a city and state column for old historical data
Then split between old data format and new
"""
df = self.original_df.copy()
# Limit to US only
df = df.loc[df["country_or_region"] == "US"]
# Split province and state by comma into 2 columns (city and state)
df = pd.concat(
[df, df["province_or_state"].str.split(", ", expand=True)], axis=1
)
df = df.rename(columns={0: "city", 1: "state"})
df['city'] = df['city'].str.strip()
df['state'] = df['state'].str.strip()
# Add a state abbreviation for new US data
# df['state_code'] = df['province_or_state'].map(us_state_abbrev)
df = df.merge(
self.load_ref_data(),
how="left",
left_on="province_or_state",
right_on="state_name",
)
# The Diamond/Grand princess are in here but NOT states
df["state_cleaned"] = (
df["state_code"]
.combine_first(df["state"])
.combine_first(df["province_or_state"])
)
# DC comes thru as DC and D.C.
df["state_cleaned"] = df.state_cleaned.str.replace(".", "")
df = self.rename_any_states(df)
# Split between old and new
self.US_old = df.loc[df["date"] <= datetime(2020, 3, 9)]
self.US_new = df.loc[df["date"] > datetime(2020, 3, 9)]
def rename_any_states(self, df):
"""
Will clean up some bad states
"""
df.loc[df['state_cleaned'] == 'District of Columbia', 'province_or_state'] = 'DC'
df.loc[df['state_cleaned'] == 'District of Columbia', 'state_cleaned'] = 'DC'
return df
def handle_old_data(self):
"""
Logic to aggregate old data
"""
old_df = (
self.US_old.groupby(["state_cleaned", "date"])[self.key_col]
.sum()
.reset_index()
)
return old_df
def handle_new_data(self):
"""
Logic to aggregate new data
"""
new_df = (
self.US_new.groupby(["state_cleaned", "date"])[self.key_col]
.sum()
.reset_index()
)
# new_df = self.US_new[['state_cleaned','date','confirmed_cases']]
return new_df
def combine_US_data(self):
"""
Combine old and new US data
"""
df = pd.concat([self.handle_old_data(), self.handle_new_data()])
df["country_or_region"] = "US"
df = df.rename(columns={"state_cleaned": "province_or_state"})
return df
def prepare_final_cleaned_data(self):
"""
Concat the new US data with the original data
"""
df1 = self.original_df
df2 = self.combine_US_data()
# Remove old US data
df1 = df1.loc[df1["country_or_region"] != "US"]
# Combine old data with cleaned US
self.data = pd.concat([df1, df2], axis=0)
def load_ref_data(self):
"""
Load our state reference table
"""
dirname = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
ref_path = os.path.join(dirname, 'ref_data','ref_table_us_states.csv')
ref = pd.read_csv(ref_path)
ref.columns = ref.columns.str.lower().str.replace(" ", "_")
ref = ref[["state_code", "state_name"]]
return ref
def run(self):
"""
Main run function to execute logic
"""
self.setup_US_data()
self.combine_US_data()
self.prepare_final_cleaned_data()
| true |
9c698f8299e24a71a0c2ba95cea9a4cba4ba48c2 | Python | BBackJK/2020tech | /python/200520/06_ifElseExample1.py | UTF-8 | 318 | 2.703125 | 3 | [] | no_license | # 교재 p.122 영화 조조 할인 판정
from time import localtime
hour = localtime().tm_hour
mnt = localtime().tm_min
if hour < 10:
print("현재 시각: %d시 %d분, 조조 할인 가능합니다." %(hour, mnt))
else:
print("현재 시각: %d시 %d분, 조조 할인 불가능합니다." %(hour, mnt)) | true |
ca3dfa8ab29b55e526f2e96eec063458790051b4 | Python | 448Watanabe/python_random_test | /classMethodTest.py | UTF-8 | 1,495 | 3.875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
class Boku(object):
# これはクラス変数
subject = "ぼくは"
name = "ドラえもん"
def __init__(self, nickname):
self.nickname = nickname # これはインスタンス変数
# これはインスタンスメソッド
def get_name_instance(self, class_var=False):
if class_var:
return Boku.subject + Boku.name + "。"
else:
return "ぼくは" + self.nickname + "。"
def set_name_instance(self, nickname, class_var=False):
if class_var:
Boku.name = nickname
else:
self.nickname = nickname
def dialogue_instance(self, dialogue, class_var=False):
return self.get_name_instance(class_var) + dialogue + "!"
# これはクラスメソッド
@classmethod
def get_name_class(cls):
return cls.subject + cls.name + "。"
@classmethod
def set_name_class(cls, nickname):
cls.name = nickname
@classmethod
def dialogue_class(cls, dialogue):
return cls.get_name_class() + dialogue + "!"
# これはスタティックメソッド
@staticmethod
def get_name_static():
return "ぼくは" + Boku.name + "。"
@staticmethod
def set_name_static(nickname):
Boku.name = nickname
@staticmethod
def dialogue_static(dialogue):
return get_name_static() + dialogue + "!"
class Ore(Boku):
subject = "オレは" | true |
0178ddcd952db5929eeab96a6b3499e45b69c5ac | Python | Luolingwei/LeetCode | /OA/Amazon/QAmazon_Closest Two Sum.py | UTF-8 | 610 | 3.796875 | 4 | [] | no_license | # Intput: [1,6,4,2], 7
# Output: 6,2
# 思路: 先排序,然后two pointers寻找closest pair
class Solution:
def closest_two(self,nums,target):
nums.sort()
l,r=0,len(nums)-1
mingap=float('inf')
n1,n2=-1,-1
while l<r:
v=nums[l]+nums[r]
if v>target:
r-=1
else:
if target-v<mingap:
mingap=target-v
n1,n2=nums[l],nums[r]
l+=1
return [n1,n2]
a=Solution()
print((a.closest_two([1,6,4,2],2)))
print(a.closest_two([6,4,0,29,5,5,1,2],9)) | true |
2cb71fd378e7b42eb99ba4452a4f6c2f6bc73271 | Python | brianchun16/PythonPractices | /Review/quiz2-1.py | UTF-8 | 440 | 3.796875 | 4 | [] | no_license | import sys
x = int(raw_input("Enter a number: "))
y = int(raw_input("Enter a number: "))
z = int(raw_input("Enter a number: "))
has_odd = False
odd_max = -sys.maxint - 1
if x % 2 == 1:
has_odd = True
if x > odd_max:
odd_max = x
if y % 2 == 1:
has_odd = True
if y > odd_max:
odd_max = y
if z % 2 == 1:
has_odd = True
if z > odd_max:
odd_max = z
if has_odd == False:
print('No odd number found')
else:
print(odd_max)
| true |
70b01183a0a7e2d760264f17937853e343d165d7 | Python | elliothevel/trep_collisions | /examples/basic/simplenc.py | UTF-8 | 1,204 | 2.8125 | 3 | [] | no_license | """
In this example, we have two pendula that can contact one another (basically newton's cradle
with only two masses).
"""
import trep
from trep import ty, tz, rx
from trep.visual import *
import numpy as np
import trep_collisions as tc
# Define the system. We include gravity and damping.
frames = [ty(0.0), [rx('theta-1'), [tz(-1.0, mass=1.0)]],
ty(-2*0.164), [rx('theta-2'), [tz(-1.0, mass=1.0)]],
ty(2*0.164), [rx('theta-3'), [tz(-1.0, mass=1.0)]]]
s = trep.System()
s.import_frames(frames)
trep.potentials.Gravity(s)
trep.forces.Damping(s, 0.0)
# Create an instance of the new surface and the integrator. Give initial
# conditions. We set the coefficient of restitution to be 0.5.
surfaces = [tc.surfaces.Distance(s, s.masses[0], s.masses[1], 2*0.165, invalid='short'),
tc.surfaces.Distance(s, s.masses[0], s.masses[2], 2*0.165, invalid='short')]
#surfaces = []
cmvi = tc.CollisionMVI(s, surfaces, release_method='endpoint', cor=0.0)
cmvi.initialize_state(0.0, [.0, -1.5, .10], [0, 0, 0])
# Simulate the dynamics.
tf = 2.0
dt = 0.1
(t, q, lam) = tc.simulate(cmvi, tf, dt)
# Visulize the system.
cmvi.prepare_to_visualize()
visualize_3d([VisualItem3D(s, t, q)])
| true |
81c2c58491b35d69ba0e145db56d0f2794a42192 | Python | paro87/Machine-Learning-with-Python | /ML3/sheet3.py | UTF-8 | 13,710 | 3.1875 | 3 | [] | no_license | from typing import Dict, List, Tuple, Optional
from unittest import TestCase
import numpy as np
import matplotlib.pyplot as plt
from utils import train_test_idxs
t = TestCase()
from minified import max_allowed_loops, no_imports
from IPython.display import Markdown as md
from ML3.minified import max_allowed_loops, no_imports
@no_imports
@max_allowed_loops(1)
def read_from_file(file: str = "data.csv") -> Dict[str, List[Tuple[float, float]]]:
"""
Opens a csv file and parses it line by line. Each line consists of a label and two
data dimensions. The function returns a dictionary where each key is a label and
the value is a list of all the datapoints that have that label. Each datapoint
is represented by a pair (2-element tuple) of floats.
Args:
file (str, optional): The path to the file to open and parse. Defaults to
"data.csv".
Returns:
Dict[str, List[Tuple[float, float]]]: The parsed contents of the csv file
"""
D = {}
lst = []
with open('./'+file, 'r') as f:
for line in f:
lst = line.split(',')
key = lst[0]
value = (float(lst[1]), float(lst[2].strip()))
D.setdefault(key, []).append(value)
return D
@no_imports
@max_allowed_loops(1)
def stack_data(D: Dict[str, List[Tuple[float, float]]]) -> Tuple[np.ndarray, np.ndarray]:
"""
Convert a dictionary dataset into a two arrays of data and labels. The dictionary
keys represent the labels and the value mapped to each key is a list that
contains all the datapoints belonging to that label. The output are two arrays
the first is the datapoints in a single 2d array and a vector of intergers
with the coresponding label for each datapoint. The order of the datapoints is
preserved according to the order in the dictionary and the lists.
The labels are converted from a string to a unique int.
The datapoints are entered in the same order as the keys in the `D`. First
all the datapoints of the first key are entered then the second and so on.
Within one label order also remains.
Args:
D (Dict[str, List[Tuple[float, float]]]): The dictionary that should be stacked
Returns:
Tuple[np.ndarray, np.ndarray]: The two output arrays. The first is a
float-matrix containing all the datapoints. The second is an int-vector
containing the labels for each datapoint
"""
X = []
y = np.array([])
label = 0
for key, value in D.items():
key_array = np.array([1] * len(value))*label
y = np.hstack((y, key_array))
label += 1
X.extend(value)
X = np.array(X)
y = y.astype(np.int64)
return X, y
@no_imports
@max_allowed_loops(1)
def get_clusters(X: np.ndarray, y: np.ndarray) -> List[np.ndarray]:
"""
Receives a labeled dataset and splits the datapoints according to label
Args:
X (np.ndarray): The dataset
y (np.ndarray): The label for each point in the dataset
Returns:
List[np.ndarray]: A list of arrays where the elements of each array
are datapoints belonging to the label at that index.
Example:
>>> get_clusters(
np.array([[0.8, 0.7], [0, 0.4], [0.3, 0.1]]),
np.array([0,1,0])
)
>>> [array([[0.8, 0.7],[0.3, 0.1]]),
array([[0. , 0.4]])]
"""
pointList = []
maxValue = np.max(y)
for i in range(maxValue+1):
result = np.where(y == i)
new_X = np.array(X[result[0]])
pointList.append(new_X)
return pointList
@no_imports
@max_allowed_loops(0)
def split(X: np.ndarray, y: np.ndarray) -> Tuple[List[np.ndarray], List[np.ndarray]]:
"""
Split the data into train and test sets. The training and test set are clustered by
label using `get_clusters`. The size of the training set is 80% of the whole
dataset
Args:
X (np.ndarray): The dataset (2d)
y (np.ndarray): The labels (1d)
Returns:
Tuple[List[np.ndarray], List[np.ndarray]]: The clustered training and
testset
"""
(X_test_indices, X_train_indices) = train_test_idxs(len(X), 0.8)
(y_test_indices, y_train_indices) = train_test_idxs(len(y), 0.8)
X_train = X[X_train_indices]
y_train = y[y_train_indices]
X_test = X[X_test_indices]
y_test = y[y_test_indices]
tr_ratio = 0.8
limit = int(tr_ratio * len(X))
# X_train = X[:limit]
# y_train = y[:limit]
# X_test = X[limit:]
# y_test = y[limit:]
tr_clusters = get_clusters(X_train, y_train)
te_clusters = get_clusters(X_test, y_test)
return tr_clusters, te_clusters
@no_imports
@max_allowed_loops(1)
def calc_means(clusters: List[np.ndarray]) -> np.ndarray:
"""
For a collections of clusters calculate the mean for each cluster
Args:
clusters (List[np.ndarray]): A list of 2d arrays
Returns:
List[np.ndarray]: A matrix where each row represents a mean of a cluster
Example:
>>> tiny_clusters = [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
]
>>> calc_means(tiny_clusters)
[array([0.15, 0.25]), array([0.7,0.7])]
"""
meanList = []
for cluster in clusters:
cluster_mean = np.mean(cluster, axis = 0)
meanList.append(cluster_mean)
result = np.array(meanList)
return result
@no_imports
def plot_scatter_and_mean(clusters: List[np.ndarray], letters: List[str], means: Optional[List[np.ndarray]] = None,
) -> None:
"""
Create a scatter plot visulizing each cluster and its mean
Args:
clusters (List[np.ndarray]): A list containing arrrays representing
each cluster
letters (List[str]): The "name" of each cluster
means (Optional[List[np.ndarray]]): The mean of each cluster. If not
provided the mean of each cluster in `clusters` should be calculated and
used
"""
assert len(letters) == len(clusters)
title = "Scatter plot of the clusters"
plt.figure(figsize=(8,8))
plt.title(title, fontsize=20)
mean_list = calc_means(clusters)
mean_index = 0
for cluster in clusters:
x_vals = cluster[:,0]
y_vals = cluster[:,1]
x_mean = np.float16(mean_list[mean_index, 0])
y_mean = np.float16(mean_list[mean_index, 1])
plt.plot(x_vals, y_vals, 'o', color='b', ms=5, alpha=0.6, label=f'Cluster: {letters[mean_index]}')
plt.plot(x_mean, y_mean, 'x', color='r', ms=7, label=f'mean: {x_mean}, {y_mean}', zorder=3)
mean_index += 1
plt.legend(loc='best')
plt.show()
@no_imports
def plot_projection(clusters: List[np.ndarray], letters: List[str], means: np.ndarray, axis: int = 0):
"""
Plot a histogram of the dimension provided in `axis`
Args:
clusters (List[np.ndarray]): The clusters from which to create the historgram
letters (List[str]): The string representation of each class
means (np.ndarray): The mean of each class
axis (int): The axis from which to create the historgram. Defaults to 0.
"""
title = f"Projection to axis {axis} histogram plot"
plt.figure(figsize=(14, 5))
plt.title(title, fontsize=20)
mean_index = 0
for cluster in clusters:
vals = cluster[:, axis]
plt.hist(vals, bins=30, rwidth=0.8, alpha=0.6, label=f'Cluster: {letters[mean_index]}', density=True) # num of bins, block width percentage
plt.axvline(x=vals.mean(), ls='--', c='r') # plot dashed mean line
mean_index += 1
plt.legend(loc='best')
plt.show()
@no_imports
@max_allowed_loops(1)
def within_cluster_cov(clusters: List[np.ndarray]) -> np.ndarray:
"""
Calculate the within class covariance for a collection of clusters
Args:
clusters (List[np.ndarray]): A list of clusters each consisting of
an array of datapoints
Returns:
np.ndarray: The within cluster covariance
Example:
>>> within_cluster_cov(
[array([[0.2, 0.3], [0.1, 0.2]]), array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]])]
)
>>> array([[0.025, 0.025],
[0.025, 0.085]])
"""
d = clusters[0].shape[1]
S_w = np.zeros((d, d))
mean_list = calc_means(clusters)
mean_index = 0
for cluster in clusters:
mean = mean_list[mean_index]
res = cluster - mean
resT = res.T
S_w += np.dot(resT, res)
mean_index += 1
return S_w
@no_imports
@max_allowed_loops(0)
def calc_mean_of_means(clusters: List[np.ndarray]) -> np.ndarray:
"""
Given a collection of datapoints divided in clusters, calculate the
mean of all cluster means.
Args:
clusters (List[np.ndarray]): A list of clusters represented in arrays
Returns:
np.ndarray: A single datapoint that represents the mean of all the
cluster means
Example:
>>> calc_mean_of_means(
[np.array([[0.222, 0.333], [0.1, 0.2]]), np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]])]
)
>>> array([0.4305 , 0.48325])
"""
mean_list = calc_means(clusters)
return np.mean(mean_list, axis=0)
@no_imports
@max_allowed_loops(1)
def between_cluster_cov(clusters: List[np.ndarray], cluster_means: List[np.ndarray], mean_of_means: np.ndarray) -> np.ndarray:
"""
Calculate the covariance between clusters.
Args:
clusters (List[np.ndarray]): A list of datapoints divided by cluster
cluster_means (List[np.ndarray]): A list of vectors representing the mean
of each cluster
mean_of_means (np.ndarray): A vector, the mean of all datapoints
Returns:
np.ndarray: Covariance between clusters
Example:
>>> tiny_clusters = [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
]
>>> tiny_means = [np.array([0.15, 0.25]), np.array([0.7, 0.7])]
>>> tiny_mean_of_means = np.array([0.425, 0.475])
>>> between_cluster_cov(tiny_clusters, tiny_means, tiny_mean_of_means)
array([[0.378125, 0.309375],
[0.309375, 0.253125]])
"""
d = clusters[0].shape[1]
S_b = np.zeros((d, d))
mean_index = 0
for cluster in clusters:
Nk = len(cluster)
mean_diff = cluster_means[mean_index] - mean_of_means
mean_diff = np.array([mean_diff])
mean_diff_transpose = mean_diff.T
dot1 = np.dot(Nk, mean_diff_transpose)
dot2 = np.dot(dot1, mean_diff)
S_b +=dot2
mean_index += 1
return S_b
@no_imports
@max_allowed_loops(0)
def rotation_matrix(S_w: np.ndarray, S_b: np.ndarray) -> Tuple[np.ndarray, int]:
"""
Calculate the transformation matrix given the within- and between cluster
covariance matrices.
Args:
S_w (np.ndarray): The within cluster covariance
S_b (np.ndarray): The between cluster covariance
Returns:
np.ndarray: The transformation matrix
int: The axis along with the transformed data achieves maximal variance
Example:
>>> tiny_S_w = np.array([[0.025, 0.025], [0.025, 0.085]])
>>> tiny_S_b = np.array([[0.378125, 0.309375], [0.309375, 0.253125]])
>>> rotation_matrix(tiny_S_w, tiny_S_b)
(array([[ 0.99752952, -0.63323779],
[-0.07024856, 0.7739573 ]]), 0)
"""
A = np.linalg.solve(S_w, S_b)
w, v = np.linalg.eig(A)
max_axis = np.argmax(w)
tup = tuple((v, max_axis))
return tup
@no_imports
@max_allowed_loops(1)
def rotate_clusters(W_rot: np.ndarray, clusters: List[np.ndarray]) -> List[np.ndarray]:
"""
Rotate all the datapoints in all the clusters
Args:
W_rot (np.ndarray): The rotation matrix
clusters (List[np.ndarray]): The list of datapoints divided in clusters that
will be rotated
Returns:
List[np.ndarray]: The rotated datapoints divided by cluster
"""
result = []
for cluster in clusters:
cluster_rotation = cluster.dot(W_rot)
result.append(cluster_rotation)
return result
if __name__ == '__main__':
letters = "MNU"
D = read_from_file(file="data.csv")
X, y = stack_data(D)
output = split(X, y)
tr_clusters, te_clusters = output
means = calc_means(tr_clusters)
mean_of_means = calc_mean_of_means(tr_clusters)
S_w = within_cluster_cov(tr_clusters)
S_b = between_cluster_cov(tr_clusters, means, mean_of_means)
output = rotation_matrix(S_w, S_b)
W_rot, max_axis = output
rad = np.deg2rad(30)
c, s = np.cos(rad), np.sin(rad)
rot30 = np.array([[c, -s], [s, c]])
tiny_clusters = [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
]
tiny_rotated_result = rotate_clusters(rot30, tiny_clusters)
print(tiny_rotated_result)
tiny_rotated_expected = [
np.array([[0.32320508, 0.15980762], [0.18660254, 0.12320508]]),
np.array(
[[1.14282032, 0.37942286], [0.85621778, 0.0830127], [0.86961524, 0.30621778]]
),
]
for r, e in zip(tiny_rotated_result, tiny_rotated_expected):
np.testing.assert_allclose(r, e)
rot_tr_clusters = rotate_clusters(W_rot, tr_clusters)
t.assertIsInstance(rot_tr_clusters, List)
for norm, rotated in zip(tr_clusters, rot_tr_clusters):
t.assertIsInstance(rotated, np.ndarray)
t.assertEqual(norm.shape, rotated.shape)
| true |
92573afaa8fa079da762900ef6842e09557919ab | Python | VismantasD/tic_tac_toe | /deepTic.py | UTF-8 | 20,735 | 3.59375 | 4 | [] | no_license | import random
import pickle
from pprint import pprint
class Symmetries():
"""Class for finding invariant states of the tic tac toe board.
Given a state will return an invariant state based on 8 symmetries
Attributes:
multiplier: multipliers for different positions on the board
perm: encodings for basic allSymmetries of identity, rotation
and mirroring
allSymmetries: stores the recipies for generating all symmetry transformations
using the primitive operations or rotation and mirroring
"""
multiplier = tuple( range( 10 , 0, -1 ) )
perm = {
'r': ( 2, 5, 8, 1, 4, 7, 0, 3, 6 ), #rotation left
'm': ( 6, 7, 8, 3, 4, 5, 0, 1, 2 ), #mirroring
'e': tuple( range( 9 ) ) } #identity
allSymmetries = ( 'e', 'r', 'rr', 'rrr', 'm','mr','mrr','mrrr' )
def __init__( self ):
self.p = [[]] * len(Symmetries.allSymmetries) * 2
state = tuple(range(9))
#cache the allSymmetries
for permutationIndex in range( len( Symmetries.allSymmetries ) ):
r = self.initPermute( state, Symmetries.allSymmetries[ permutationIndex ] )
self.p[ permutationIndex ] = r
def invariant( self, state ):
"""For a given state returns its invariant under the symmetries.
Args:
state: A state of the tic tac toe board - tuple of length 9 with values 0, 1, or 2
"""
bestState = tuple( state )
bestPerm = 0
bestScore = self.score( state )
for p in range( len( Symmetries.allSymmetries ) ):
newState = self.permuteState( state, p )
tempScore = self.score( newState )
if tempScore > bestScore:
bestState, bestPerm, bestScore = newState, p, tempScore
return ( bestState, bestPerm )
def score( self, state ):
"""Returns a score for a state. This score is used to find invariante state.
The state transformed with symmetry transformation with the highest score
will be the invariant for a given state.
Args:
state: state of the tic tac toe board.
"""
return sum( a * 10**b for ( a, b ) in zip( state, Symmetries.multiplier ) )
def initPermute( self, state, permutation ):
"""Permutes given state with a sequence of basic transformations"
Args:
state: state of the tic tac toe board.
permutation: string of r and m letters encoding a sequence of
rotation and mirroring transformations.
"""
cs = state
for op in permutation:
cs = tuple( cs[ i ] for i in Symmetries.perm[ op ] )
return cs
def permuteState( self, state, permutationIndex ):
"""Permutes state using cached allSymmetries"""
return tuple( state[ i ] for i in self.p[ permutationIndex ] )
def permuteAction( self, action, permutation):
"""Gives action value under permutation"""
return self.p[ permutation ].index( action )
def inverseAction( self, action, permutation):
"""Given action under permutation, returns original action"""
return self.p[ permutation ][ action ]
class Game( object ):
"""Represents the state of the game.
Attributes:
__state: stores the state of the game
__invState: stores the invariante of the current
state of the game ( it is cached for performance )
debug: flag to indicate if debog output should be printed
useSymmetry: stores instance of the Symmetries class for
computing invariants of the states
"""
def __init__( self, state = None, debug = False ):
"""
Args:
state: Initial state of the game
debug: indicates if deboug output should be printed
"""
if state is not None:
self.__state = tuple( state )
else:
self.__state = [ 0 ] * 9
self.debug = debug
self.useSymmetry = Symmetries()
self.__invState = self.useSymmetry.invariant( self.__state )
@staticmethod
def mapper( s ):
"""Maps numerical representations of the board
to characters for printing
"""
if s == 0:
return ' '
elif s == 1:
return 'X'
else:
return 'O'
def __repr__( self ):
"""Returns string representation of the board
"""
lines = ( lineIndex for lineIndex in range( 3 ) )
lineState = ( self.__state[ line * 3 : line * 3 + 3 ] for line in lines )
allLines = ( "|".join( ( Game.mapper( x ) for x in line ) ) for line in lineState )
return "\n-----\n".join( allLines )
def setState( self, pos, symbol , usingSymmetry ):
"""Updates the state of the game.
Args:
pos: position on the board to be updates 0-8
symbol: 0 - emptu, 1-X, 2-O
usingSymmetry: flag, denoting if the 'pos' is given
w.r.t. the symmetric invariant of the current state (__invState)
or not
"""
if usingSymmetry:
pos = self.useSymmetry.inverseAction( pos, self.__invState[1] )
self.__state[ pos ] = symbol
self.__invState = self.useSymmetry.invariant( self.__state )
if self.debug: print( self.__state )
def returnState( self, usingSymmetry ):
"""Gives current state.
Args:
usingSymmetry: if True the symmetric invariant of the state is returned
"""
if usingSymmetry:
return self.__invState[ 0 ]
else:
return tuple(self.__state)
def terminalState( self, state ):
"""Checks if the state is in a wining position.
Args:
state: state of the board
"""
if ( ( ( state[ 0 ] != 0) and ( state[ 0 ] == state[ 4 ] == state[ 8 ] ) ) or
( ( state[ 2 ] != 0 ) and ( state[ 2 ] == state[ 4 ] == state[ 6 ] ) ) ):
return True
for line in range( 3 ):
tmpLine = state[ line*3:line*3 + 3 ]
tmpCol = state[ line:line + 2 * 3 + 1:3]
if tmpLine[ 0 ] != 0 and all( ( x == tmpLine[ 0 ] for x in tmpLine ) ):
return True
if tmpCol[0] != 0 and all((x == tmpCol[0] for x in tmpCol)):
return True
return False
def getAvailableActions( self, usingSymmetry ):
"""Returns all available actions in the current game state.
Args:
usingSymmetry: flag denoting if the actions should be returned
w.r.t the symmetric invariant of the current state or not.
"""
if usingSymmetry:
r = self.__invState[ 0 ]
return tuple( i for (i, v) in enumerate( r ) if v == 0)
else:
return tuple( i for (i, v) in enumerate( self.__state ) if v == 0)
def end( self ):
"""Returns true if the game is in a terminal state with a player winning.
"""
return self.terminalState( self.__state )
def tie( self ):
"""Returns true if the game is in a terminal state which is a tie.
"""
return (not self.end()) and (len( self.getAvailableActions( False ) ) == 0)
class Update( object ):
'''
Class to store SARSA updates to the agents
'''
def __init__( self, callback ):
self.a1 = None #action in first state
self.s1 = None #first state
self.a2 = None #action in subsequent state
self.s2 = None #subsequent state
self.t = None #denotes terminal state, it is used by agent to know to ignore s2 and a2 when doing update
self.r = None #reward experienced after taking a1 in s1
self.firstPush = True
self.callback = callback #agent who should receive this update
def send( self ):
'''
Sends SARSA update to the registered agents
'''
r = {
'a1': self.a1,
'a2': self.a2,
's1': self.s1,
's2': self.s2,
'r': self.r,
't': self.t}
self.callback.update( r )
def push(self, state, action, reward, terminal):
"""Push data, to build an update packet for the agent.
Args:
state: state of the game
action: action taken in the state
reward: reward aboserved after taking that action
terminal: flag denoting if the state is a terminal state
"""
if self.firstPush:
self.s2 = state
self.a2 = action
#we do not send update on first push, because
#we do not have the full necessary information
#for a full SARSA update (we have not seen the second state yet)
self.firstPush = False
else:
self.a1 = self.a2
self.s1 = self.s2
self.a2 = action
self.s2 = state
self.t = terminal
self.r = reward
self.send()
class GameEnvironment( object ):
"""Class to manage the gameplay.
Class manages the game-play: keeps the state of the game, notices when it
the game has terminated, alternates player moves. Also keeps track of
player actions and builds SARSA updates for the players and sends them
at appropriate time.
Attributes:
__p1: Player one
__p2: Player two
__game: State of the game
debug: Flag denoting if debug output should be printed
sym:
"""
def __init__(self, p1, p2, game):
"""Constructor
Args:
p1: player one
p2: player two
game: game to play
"""
self.__p1 = p1
self.__p2 = p2
self.__game = game
self.debug = False
def step( self, p1, p2, game, p1Update, p2Update, symbol ):
"""Conducts a single step of a game.
Conducts a single step of a game. One player makes a move,
the game state is updated. It is checked for termination
cirterions and then appropriate updates of state, action and
rewards are sent to the players.
Args:
p1: player one. The one who makes a move in this step
p2: the other player
game: object representing current state of the game
p1Update: object managing updates to the player 1
p2Update: object managing updates to the player 2
symbol: symbol to be placed on the board by the current
player
Returns:
1 if the game is in terminal winning position
0 if the game ended in a tie
-1 if the game continues
"""
currentGameState = game.returnState( p1.useSymmetry )
move = p1.makeMove( currentGameState, game.getAvailableActions( p1.useSymmetry ) )
p1Update.push( currentGameState, move, 0, False )
game.setState( move, symbol, p1.useSymmetry )
if game.end():
currentGameState = game.returnState( p1.useSymmetry )
p1Update.push( currentGameState, -1, 1, True )
currentGameState = game.returnState( p2.useSymmetry )
p2Update.push( currentGameState, -1, -1, True )
return 1
elif game.tie():
currentGameState = game.returnState( p1.useSymmetry )
p1Update.push( currentGameState, -1, 0, True )
currentGameState = game.returnState( p2.useSymmetry )
p2Update.push( currentGameState, -1, 0, True )
return 0
else:
return -1
def play( self ):
"""Conducts the game play.
Starts the game. Alternates players, keeps track of the state
of the game and it termination.
Returns:
1 if Player 1 won
0 if the game ended in a tie
-1 if the Player 1 lost
"""
currentPlayer = 1
result = -1
if self.debug:
print( self.__game )
print( "======" )
p1Update = Update( self.__p1 )
p2Update = Update( self.__p2 )
while result == -1:
if self.debug: print( "Player's {} move!".format( currentPlayer ) )
if currentPlayer == 1:
result = self.step( self.__p1, self.__p2, self.__game, p1Update, p2Update, 1 )
if result == -1:
currentPlayer = 2
else:
result = self.step( self.__p2, self.__p1, self.__game, p2Update, p1Update, 2 )
if result == -1:
currentPlayer = 1
if self.debug:
print( self.__game )
print( "======" )
if self.debug:
if result * currentPlayer == 0:
print( "It is a tie!" )
elif result * currentPlayer == 1:
print( "Player one wins!" )
elif result * currentPlayer == 2:
print( "Player two wins!" )
if result * currentPlayer == 2:
return -1
else:
return result
class HumanPlayer( object ):
"""Class representing a human player.
"""
def __init__( self ):
self.debug = False
self.useSymmetry = False
def makeMove( self, _, possibleActions ):
"""Get the move from they keyboard
Args:
state: but for human player we do not need the state
possibleActions: actions possible in the current state
"""
moveDone = False
print( "You have the following choices: {}".format( possibleActions ) )
while not moveDone:
try:
action = int(raw_input())
except ValueError:
continue
if action in possibleActions:
return action
def update( self, state ):
"""Method to update the startegy. Irrelevant for human player.
"""
if self.debug:
print( "Update received: ")
pprint( state )
class AIPlayer( object ):
"""Represents an AI player.
Attributes:
__q: State action pair values. Hash table storing the values
for all encountered state action pairs.
__eps: The epsilon parameter for the epsilon-greedy strategy.
debug: Flag denoting if the debug output should be printed.
competitionMode: flag denoting if the agent should do exploratory moves
and update its strategy based on experience. When set to True
agent does not do policy imporovements and uses completely
greedy strategy.
sarsa: Flag denoting if SARSA ( when set to True ) or Q-learning (when set
to False) algorithm should be used when updating state action pair
values.
initialStateActionValue: Initial value for state action pairs, when initialising
them.
learningRate: learning rate as define in SARSA and Q-learning algorithms
useSymmetry: Flag denoting if the agent is aware of symmetric states.
"""
def __init__( self, eps, pretaindFile = None ):
"""Constructor
Args:
eps: epsilon parameter for the epsilon greedy strattegy.
controls how may exploratory moves the agent does.
pretrainedFile: path to file containint pretrained state action
values ( can be created using saveState method ).
"""
if pretaindFile is None:
self.__q = {}
else:
with open( pretaindFile, 'rt' ) as f:
self.__q = pickle.load( f )
self.__eps = eps
self.debug = False
self.competitionMode = False
self.sarsa = True
self.initialStateActionValue = 0.01
self.learningRate = 0.2
self.useSymmetry = True
def saveState( self, fileName ):
"""Saves the current state of state action pair values.
The saved data can be used to initialise new instances
of the agent.
"""
with open( fileName, 'wt') as f:
pickle.dump( self.__q, f )
def setEps(self, eps ):
"""Sets the epsilon parameter
"""
self.__eps = eps
def selectAction( self, actions, values ):
"""Selects action using epsilon greedy strategy
Args:
actions: All available actions
values: Corresponding values of the actions.
"""
if ( ( random.random() < self.__eps ) and ( not self.competitionMode ) ):
return random.choice( actions )
else:
return actions[values.index( max( values ) ) ]
def initializeStateActions( self, state, possibleActions ):
"""Initializes unseen states (state, action) pairs with default values.
Args:
state: Unseen state.
possibleActions: all actions, possible in the given state.
"""
values = [ self.initialStateActionValue ] * len(possibleActions)
self.__q[ state ] = dict(zip(possibleActions, values) )
def makeMove( self, state, possibleActions ):
"""Chooses a move, best in the given state using epsilon greedy strategy
Args:
state: State for which action is needed.
possibleActions: All actions possible in the given state.
"""
#check if state is in q already
state = tuple(state)
if state not in self.__q:
#initialize q(s, a) for given state arbitrarily
self.initializeStateActions( state, possibleActions )
#now that the q(s, a) is initialized, proceed
return self.selectAction( self.__q[ state ].keys(), self.__q[ state ].values() )
def strategy( self ):
pprint( self.__q )
def update( self, stateUpdate ):
"""Updates state action pairs.
Args:
stateUpdate: dictionary containing state action pairs for two consecutive
states experienced by agent. Also contains reward gained after making
first action. Also contains flat, that indicates if the second state
is a terminal state for the game.
"""
if self.competitionMode:
return
if self.debug:
print( "Update received: ")
pprint( stateUpdate )
if not stateUpdate[ 't' ]: #if the stateUpdate is not terminal, then we care about s2,a2 reward.
s2 = stateUpdate[ 's2' ]
s1 = stateUpdate[ 's1' ]
a1 = stateUpdate[ 'a1' ]
a2 = stateUpdate[ 'a2' ]
currVal = self.__q[ s1 ][ a1 ]
if self.sarsa: #SARSA update
currVal = currVal + self.learningRate * ( stateUpdate[ 'r' ] + self.__q[ s2 ][ a2 ] - currVal )
else: #Q-learning update
tmpVal = max( self.__q[ s2 ].values() )
currVal = currVal + self.learningRate * ( stateUpdate[ 'r' ] + tmpVal - currVal )
self.__q[ s1 ][ a1 ] = currVal
else:
#in a terminal state we know the value for s2,a2 is zero.
#Therefore We only care about the transition reward.
s1 = stateUpdate[ 's1' ]
a1 = stateUpdate[ 'a1' ]
currVal = self.__q[ s1 ][ a1 ]
currVal = currVal + 0.1 * ( stateUpdate[ 'r' ] - currVal )
self.__q[ s1 ][ a1 ] = currVal
| true |
83b3f7df6a45332006b32fbe6c199995b4358fb9 | Python | Neethu-nr/aa203_project | /RF/RunAgent.py | UTF-8 | 3,799 | 3.125 | 3 | [] | no_license | #From https://github.com/the-deep-learners/TensorFlow-LiveLessons/
#modified by Albin
import os
import gym
import numpy as np
from DQNAgent import DQNAgent
from Airplane import Airplane_Env
def train():
agent = DQNAgent(state_size, action_size) # initialise agent
#choice = raw_input("Name weight: ")
#filename = output_dir + "weights_" + choice + ".hdf5"
#agent.load(filename)
batch_size = 32
n_episodes = 10001 # n games we want agent to play (default 1001)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
done = False
for e in range(n_episodes): # iterate over new episodes of the game
state = env.reset() # reset state at start of each new episode of the game
state = np.reshape(state, [1, state_size])
score = 0
for time in range(100): # time represents a frame of the game; goal is to keep pole upright as long as possible up to range, e.g., 500 or 5000 timesteps
# env.render()
action = agent.act(state) # action is either 0 or 1 (move cart left or right); decide on one or other here
next_state, reward, done, _ = env.step(action) # agent interacts with env, gets feedback; 4 state data points, e.g., pole angle, cart position
#reward = reward if not done else -1000 # reward +1 for each additional frame with pole upright
next_state = np.reshape(next_state, [1, state_size])
agent.remember(state, action, reward, next_state, done) # remember the previous timestep's state, actions, reward, etc.
state = next_state # set "current state" for upcoming iteration to the current next state
score = score + reward
if done: # episode ends if agent drops pole or we reach timestep 5000
print("episode: {}/{}, score: {}, e: {:.2}, time: {}, x: {:.2}" # print the episode's score and agent's epsilon
.format(e, n_episodes, score, agent.epsilon, time, state[0,0]))
break # exit loop
if len(agent.memory) > batch_size:
agent.replay(batch_size) # train the agent by replaying the experiences of the episode
if e % 500 == 0:
agent.save(output_dir + "weights_" + '{:04d}'.format(e) + ".hdf5")
#print(env.get_traj())
#env.plot_traj()
env.plot_traj()
env = Airplane_Env()
state_size = 6
action_size = 26*5
output_dir = 'model_output/cartpole/'
choice = raw_input("Train? Y/N: ")
if choice == "Y" :
train()
else:
agent = DQNAgent(state_size, action_size,0) # initialise agent
choice = raw_input("Name weight: ")
filename = output_dir + "weights_" + choice + ".hdf5"
if not os.path.isfile(filename):
exit()
print("Load: " + filename)
agent.load(filename)
state = env.reset() # reset state at start of each new episode of the game
state = np.reshape(state, [1, state_size])
done = False
while(True):
state = env.reset() # reset state at start of each new episode of the game
state = np.reshape(state, [1, state_size])
for time in range(5000): # time represents a frame of the game; goal is to keep pole upright as long as possible up to range, e.g., 500 or 5000 timesteps
action = agent.act(state) # action is either 0 or 1 (move cart left or right); decide on one or other here
next_state, reward, done, _ = env.step(action) # agent interacts with env, gets feedback; 4 state data points, e.g., pole angle, cart position
if done: # episode ends if agent drops pole or we reach timestep 5000
break # exit loop
print(env.get_traj())
print(env.get_controlls())
env.plot_traj()
| true |
0bd4d72f75838ccef71c9f7781373de9031f8fef | Python | AaronYang2333/CSCI_570 | /records/09-05/brackets.py | UTF-8 | 793 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '9/5/2020 4:06 AM'
class Solution:
def getHouses(self, t, xa):
# write code here
arr = []
for i in range(0, len(xa), 2):
left = xa[i] - xa[i + 1] // 2
right = xa[i] + xa[i + 1] // 2
arr.append((left, right))
arr.sort(key=lambda item: item[1])
dp = [1] * t
ans = 1
for i in range(t):
for j in range(i - 1, -1, -1):
if arr[i][0] >= arr[j][1]:
dp[i] = max(dp[i], dp[j] + 1)
break
dp[i] = max(dp[i], dp[i - 1])
ans = max(ans, dp[i])
return 2 * ans
if __name__ == '__main__':
res = Solution().getHouses(2, [-1, 4, 5, 2])
print(res)
| true |
f4b84748fa2362dcee63d31e7712221b3818a6d6 | Python | kmcginn/advent-of-code | /2021/day02/dive2.py | UTF-8 | 2,386 | 4.3125 | 4 | [
"MIT"
] | permissive | #! python3
"""
--- Part Two ---
Based on your calculations, the planned course doesn't seem to make any sense. You find the
submarine manual and discover that the process is actually slightly more complicated.
In addition to horizontal position and depth, you'll also need to track a third value, aim, which
also starts at 0. The commands also mean something entirely different than you first thought:
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by your aim multiplied by X.
Again note that since you're on a submarine, down and up do the opposite of what you might expect:
"down" means aiming in the positive direction.
Now, the above example does something different:
forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does
not change.
down 5 adds 5 to your aim, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth
increases by 8*5=40.
up 3 decreases your aim by 3, resulting in a value of 2.
down 8 adds 8 to your aim, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth
increases by 2*10=20 to a total of 60.
After following these new instructions, you would have a horizontal position of 15 and a depth of
60. (Multiplying these produces 900.)
Using this new interpretation of the commands, calculate the horizontal position and depth you
would have after following the planned course. What do you get if you multiply your final
horizontal position by your final depth?
"""
import os
def main(filename):
"""Solve the problem!"""
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, filename)
horizontal = 0
depth = 0
aim = 0
with open(file_path) as input_file:
for line in input_file:
command, amount = line.split(" ", 2)
if command == "forward":
horizontal += int(amount)
depth += aim * int(amount)
elif command == "down":
aim += int(amount)
elif command == "up":
aim -= int(amount)
print(horizontal * depth)
if __name__ == "__main__":
main('example.txt')
main('input.txt') | true |