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
5427fec1aae5c8497a6a7f4621d724ebadff88b0
Python
kayak0806/pretty-pictures
/trash/squares.py
UTF-8
2,225
3.03125
3
[]
no_license
import pyglet class Square(object): #blue square ''' A blue Square''' def __init__(self,environment,x,y): self.envi = environment self.velocity = -1 self.active = False self.vert1 = x self.hznt1 = y self.vert2 = x self.hznt2 = y points = self.get_points() self.vert = environment.batch.add(4, pyglet.gl.GL_QUADS, None, ('v2i', points),('c3B', (0,0,255,0,0,255,0,0,255,0,0,255))) def resize(self,x,y): ''' changes the size of the square by moving p1 to (x,y)''' self.vert2 = x self.hznt2 = y self.vert.vertices = self.get_points() def relocate(self,x,y): ''' moves the first point to (x,y)''' self.vert1 = x self.hznt1 = y self.vert.vertices = self.get_points() def get_points(self): ''' Given the defining points, return tuple to make vertex_list''' x1, y1 = self.vert1, self.hznt1 x2, y2 = self.vert2, self.hznt1 x3, y3 = self.vert2, self.hznt2 x4, y4 = self.vert1, self.hznt2 return (int(x1), int(y1), int(x2), int(y2), int(x3), int(y3), int(x4), int(y4)) def update(self,dt): if self.active: dy = dt*30*self.velocity if self.hznt2 < 0 or self.hznt1 < 0: self.velocity = 1 if self.hznt2 > 400 or self.hznt1>500: self.velocity = -1 self.hznt1 += dy self.hznt2 += dy points = self.get_points() self.vert.vertices = points class Square2(Square): def __init__(self,environment,x,y): Square.__init__(self, environment, x,y) points = self.get_points() self.vert = environment.batch.add(4, pyglet.gl.GL_QUADS, None, ('v2i', points)) def update(self,dt): if self.active: dy = dt*30*self.velocity if self.vert2 < 0 or self.vert1 < 0: self.velocity = 1 if self.vert2 > 400 or self.vert1>700: self.velocity = -1 self.vert1 += dy self.vert2 += dy points = self.get_points() self.vert.vertices = points
true
8541332eee4fc99d4bf152d7897895d540360783
Python
rafaelperazzo/programacao-web
/moodledata/vpl_data/94/usersdata/213/57132/submittedfiles/mediaLista.py
UTF-8
314
3.359375
3
[]
no_license
# -*- coding: utf-8 -*- n=int(input('Informe a quantidade de elementos da lista: ')) lista=[] for i in range(0,n,1): elemento=int(input('Informe os elementos da lista: ')) lista.append(elemento) soma=0 for i in range(0, len(lista),1): soma=soma+lista[i] media=soma/len(lista) print('%.2d',%lista[0])
true
d962dad608dadf4ce5efc3e224249ad8fe2f6875
Python
Jeet0204/Leet_Code
/Medium_200_Number_of_Islands.py
UTF-8
614
2.921875
3
[]
no_license
class Solution: def numIslands(self, grid: List[List[str]]) -> int: m = len(grid) n = len(grid[0]) count=0 for row in range(m): for col in range(n): if grid[row][col]=="1": count+=1 dfs(grid,m,n,row,col) return count def dfs(grid,m,n,row,col): if(row<0 or col<0 or row>=m or col>=n or grid[row][col]=="0"): return grid[row][col]="0" dfs(grid,m,n,row+1,col) dfs(grid,m,n,row-1,col) dfs(grid,m,n,row,col+1) dfs(grid,m,n,row,col-1) return
true
97a948531e864b66092b2b66383a8b40aac75978
Python
sguernion/myPI
/serveur/python/gpio/alarm.py
UTF-8
1,567
2.84375
3
[]
no_license
#!/usr/bin/python #-------------------------------------- # Alarm # # Author : sguernion # Date : 20/05/2013 # # https://github.com/sguernion/myPI # #-------------------------------------- # Import required libraries import RPi.GPIO as GPIO import time import sys # Tell GPIO library to use GPIO references GPIO.setmode(GPIO.BCM) # Configure GPIO8 as an outout GPIO.setup(8, GPIO.OUT) # Set Switch GPIO as input GPIO.setup(7 , GPIO.IN) #4,17 LedSeq = [4] LedSize = 1 for x in range(LedSize): GPIO.setup(LedSeq[x], GPIO.OUT) GPIO.output(LedSeq[x], False) # Turn Buzzer off GPIO.output(8, False) alarm = True def my_callback(channel): global alarm alarm = False GPIO.cleanup() sys.exit() return try: GPIO.add_event_detect(7, GPIO.RISING) GPIO.add_event_callback(7, my_callback) # Loop until users quits with CTRL-C while alarm : # Turn Buzzer on GPIO.output(8, True) for x in range(LedSize): GPIO.output(LedSeq[x], True) # Wait 1 second time.sleep(0.5) # Turn Buzzer off GPIO.output(8, False) for x in range(LedSize): GPIO.output(LedSeq[x], False) time.sleep(0.2) # long sequence # Turn Buzzer on GPIO.output(8, True) for x in range(LedSize): GPIO.output(LedSeq[x], True) # Wait 1 second time.sleep(1) # Turn Buzzer off GPIO.output(8, False) for x in range(LedSize): GPIO.output(LedSeq[x], False) time.sleep(0.5) except KeyboardInterrupt: # Reset GPIO settings GPIO.cleanup()
true
4b59b507250d9ca0928bb93a3083fd5bcfc43280
Python
Aiyane/aiyane-LeetCode
/51-100/颜色分类.py
UTF-8
1,892
4.21875
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 颜色分类.py """ 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] 进阶: 一个直观的解决方案是使用计数排序的两趟扫描算法。 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 你能想出一个仅使用常数空间的一趟扫描算法吗? """ """ 思路:x,y,z指针分别指向0位置起点,1位置起点,2位置起点。那么当当前数字为1时,这时三个指针都需要后移一位,并且将对应位置赋值对应数字。 必须是倒序赋值,但是又要注意当前位置数字不变,也要注意还未开始移动的指针不赋值。 """ __author__ = 'Aiyane' class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ x = y = z = -1 for i in range(len(nums)): if nums[i] == 0: x += 1 y += 1 z += 1 nums[z] = 2 nums[y] = 1 nums[x] = 0 elif nums[i] == 1: y += 1 z += 1 nums[z] = 2 if x != -1: nums[x] = 0 nums[y] = 1 elif nums[i] == 2: z += 1 if y != -1: nums[y] = 1 if x != -1: nums[x] = 0 nums[z] = 2
true
f548249b7257daa7b0c0b11ec7e59566fe3a1408
Python
Aladl88/pdsnd_github
/bikeshare_2.py
UTF-8
3,014
3.515625
4
[]
no_license
#This will be a part of the 3rd project requirements import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): "" " Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze(str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter "" " print('Hello! Let\'s explore some US bikeshare data!')# get user input for city(chicago, new york city, washington).HINT: Use a while loop to handle invalid inputs# get user input for month(all, january, february, ..., june)# get user input for day of week(all, monday, tuesday, ...sunday) print('-' * 40) return city, month, day def load_data(city, month, day): "" " Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze(str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day "" " return df def time_stats(df): "" "Displays statistics on the most frequent times of travel." "" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month# display the most common day of week# display the most common start hour print("\nThis took %s seconds." % (time.time() - start_time)) print('-' * 40) def station_stats(df): "" "Displays statistics on the most popular stations and trip." "" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station# display most commonly used end station# display most frequent combination of start station and end station trip print("\nThis took %s seconds." % (time.time() - start_time)) print('-' * 40) def trip_duration_stats(df): "" "Displays statistics on the total and average trip duration." "" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time# display mean travel time print("\nThis took %s seconds." % (time.time() - start_time)) print('-' * 40) def user_stats(df): "" "Displays statistics on bikeshare users." "" print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types# Display counts of gender# Display earliest, most recent, and most common year of birth print("\nThis took %s seconds." % (time.time() - start_time)) print('-' * 40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
true
6200eb8542baac779d57aac35a272454e09de95e
Python
Tsurikov-Aleksandr/python-algorithms
/algorithm-prima.py
UTF-8
1,357
3.296875
3
[]
no_license
#------------------------------------------------- # Алгоритм Прима поиска минимального остова графа #------------------------------------------------- import math def get_min(R, U): rm = (math.inf, -1, -1) for v in U: rr = min(R, key=lambda x: x[0] if (x[1] == v or x[2] == v) and (x[1] not in U or x[2] not in U) else math.inf) if rm[0] > rr[0]: rm = rr return rm # список ребер графа (длина, вершина 1, вершина 2) # первое значение возвращается, если нет минимальных ребер R = [(math.inf, -1, -1), (13, 1, 2), (18, 1, 3), (17, 1, 4), (14, 1, 5), (22, 1, 6), (26, 2, 3), (19, 2, 5), (30, 3, 4), (22, 4, 6)] N = 6 # число вершин в графе U = {1} # множество соединенных вершин T = [] # список ребер остова while len(U) < N: r = get_min(R, U) # ребро с минимальным весом if r[0] == math.inf: # если ребер нет, то остов построен break T.append(r) # добавляем ребро в остов U.add(r[1]) # добавляем вершины в множество U U.add(r[2]) print(T)
true
45c3c69c6208f34c4ab793a412ac0926fcde9ee4
Python
FI18-Trainees/FISocketChat
/src/utils/shell.py
UTF-8
897
2.96875
3
[ "MIT" ]
permissive
import os from datetime import datetime black = '\033[30m' red = '\033[31m' green = '\033[32m' yellow = '\033[33m' blue = '\033[34m' violet = '\033[35m' beige = '\033[36m' white = '\033[37m' grey = '\033[90m' red2 = '\033[91m' green2 = '\033[92m' yellow2 = '\033[93m' blue2 = '\033[94m' violet2 = '\033[95m' beige2 = '\033[96m' white2 = '\033[97m' class Console: def ts(self, c=False): if c: return f'{yellow2}[{str(datetime.now()).split(".", 1)[0]}]{white}' return f'[{str(datetime.now()).split(".", 1)[0]}]' def __init__(self, prefix, cls=False): if cls: os.system("cls" if os.name == "nt" else "clear") self.prefix = f'{green2}[{prefix}]{white}' def output(self, text, p=""): if p: print(f'{self.ts(1)} {green2}[{p}]{white} {str(text)}') else: print(f'{self.ts(1)} {self.prefix} {str(text)}')
true
d23aaf22a7e88fcaeb3fdd094fd80987477f8c5b
Python
KevinQL/LGajes
/PYTHON/Métodos de cadenas - V33.py
UTF-8
1,842
4.28125
4
[]
no_license
"""" Uso de métodos de cadenas. objetos String upper() - convierte en mayuscula un strings lower() - pasa a minusculas un string capitalize() - poner la primera letra en mayuscula count() - contar cuantas veces aparece una letra o cadena dentro de un mensaje, frase find() - Representar el índice, la posición de un caracter dentro de un texto isdigit() - true/flase. si el valor introducido es un número o no lo es isalum() - true/flase. son alfa numéricos (1,2,...9, A, B, C .... Z) isalpha() - true/flase. si hay solo letras. los espacios no cuentam split() - Separa por palabras utilizando espacios strip() - borra los espacios sobrantes al principio y al final replace() - cambia una palabra o letra por otra, dentro de un string rfind() - representar el indice de un caracter, contando desde atras asistir a la siguiente web: http://pyspanishdoc.sourceforge.net/ """ nombre = "kevin" apellido = "qUispe LIMA" edad = "22" numero = 983677639 # no funcionarán con números print("------- OBJETO STRING----------") print(nombre.upper()) ### KEVIN print(apellido.lower()) ### quispe lima print(apellido.capitalize()) ### Quispe lima print(nombre.count("e")) ### 1 print(nombre.find("i")) ### 3 print(edad.isdigit()) ### True print(nombre.isdigit()) ### False print(edad.isalnum()) # los números del 1-9 y las letras del alfabeto son alfanumérico.:D ### True print(apellido.isalnum()) # espacios no cuenta ### False print(nombre.isalnum()) # no hay espacios ### True print(apellido.isalpha()) # hay espacio ### False print(nombre.isalpha()) # No hay espacio ### True print(edad.isalpha()) # hay número ### False print(apellido.split("U")) ### ['q', 'ispe LIMA'] palabra = " espacios final " print(palabra) ### espacios final print(palabra.strip()) ### espacios final
true
45d44ad2a6b6aada3de17842c3f36dc080db9111
Python
oppih/inst-ubuntu
/sources_update.py
UTF-8
1,201
2.578125
3
[]
no_license
#! usr/bin/env python # coding:utf-8 # Filename:sources_upate.py import os import time def source_update(): flag = "-" width = 25 print flag * width + "\n" + flag * width print "以下更新源地址列表为教育网IPv6适用" print "默认将对系统自带源列表进行备份,如果修改源失败的话,使用以下命令恢复至默认的源地址文件:\nsudo cp /etc/apt/sources.list_backup /etc/apt/sources.list" print flag * width + "\n" + flag * width time.sleep(2) """ #备份源列表,已经测试通过,平时测试时不启用 #如果修改源失败的话,使用以下命令恢复至默认的源地址文件: #sudo cp /etc/apt/sources.list_backup /etc/apt/sources.list #os.system("cp /etc/apt/sources.list /etc/apt/sources.list_backup") """ #[!!!]用于编写导入自己需要用的源地址文件才好,需要做版本测试,参考其他;要不先做的简单一些,就针对单一版本,以后改进 os.system("cp /etc/apt/sources.list /etc/apt/sources.list_backup") os.system("sudo cp ./sources_list/ipv6_edu /etc/apt/sources.list")#./test_envi/sources.list if __name__ == '__main__': source_update()
true
33dc72c01965de8596d6f910d0290f771bf158d6
Python
zhoudada/PCInvaderDetector
/client/image_saver.py
UTF-8
479
2.9375
3
[]
no_license
import cv2 import os class ImageSaver: def __init__(self, prefix, save_dir, multiple=1): self.index = 0 self.prefix = prefix self.save_dir = save_dir self.multiple = multiple def save(self, image): if self.index % self.multiple == 0: name = '{}_{}.png'.format(self.prefix, self.index) path = os.path.join(self.save_dir, name) cv2.imwrite(path, image) self.index += 1
true
1c03e372e583db58f4a0702bb8cb27a778908f2d
Python
gmangini/python-stack
/stack.py
UTF-8
1,175
4.28125
4
[]
no_license
""" Stack ADT """ class Stack: """class has given attributes for adt, stack.""" def __init__(self, size=0): self.items = [] self.stack_size = size def push(self, item): """inserts item at the top of the stack""" self.items.append(item) def is_empty(self): """checks to see stack is empty""" return self.items == [] def pop(self): """removes and returns item at the top of the stack. Precondition: the stack is not empty, raises keyError Postcondition: the top item is removed from stack.""" if self.is_empty(): raise IndexError else: return self.items.pop() def top(self): """returns item at the top of the stack. Precondition: the stack is not empty.""" if self.is_empty(): raise IndexError else: return self.items[len(self.items) - 1] def size(self): """returns the number of items in stack""" return len(self.items) def clear(self): """makes self become empty""" self.items = []
true
c076f6d91c94b7d7ff35612780dfe9481306cc9f
Python
nklb/webpics
/webpics
UTF-8
2,128
2.671875
3
[ "Unlicense" ]
permissive
#!/usr/bin/python import sys, subprocess, os, shutil def pixels (filename): info = str(subprocess.check_output(["file", filename])).split() return (int(info[4]), int(info[6][:-1])) max_x_pixels = 1280 dspace_thresh = 800 * 1024 for img in sys.argv[1:]: (whitespace, scaled, compression) = (False, False, 100) split = os.path.splitext(os.path.basename(img)) backup = split[0] + '_orig' + split[1] orig_dspace = os.stat(img).st_size textout = img + ': ' + str(orig_dspace / 1024) + 'kB -> ' # convert to png if jpg if split[1] == ".jpg" or split[1] == ".jpeg": backup_png = split[0] + '_orig.png' subprocess.call(["convert", backup, backup_png]) backup = backup_png img = split[0] + '.png' # Add whitespace to the sides of portrait format images os.rename(img, backup) if pixels(backup)[0] < pixels(backup)[1]: ypix = pixels(backup)[1] subprocess.call(["convert", "-size", str( int(4./3 * ypix)) + "x" + str(ypix), "xc:white", backup, "-gravity", "center", "-composite", img]) whitespace = True else: shutil.copy(backup, img) # Scale down large images if pixels(img)[0] > max_x_pixels: subprocess.call(["convert", img, "-resize", str(max_x_pixels), img]) scaled = True temp = split[0] + '_temp' + split[1] shutil.copy(img, temp) # compress with pngquant until small enough while os.stat(temp).st_size > dspace_thresh and compression > 20: compression -= 10 subprocess.call(["pngquant", "--ext", "_temp.png", "--force", "--quality=" + str(compression - 15) + "-" +str(compression), img]) os.rename(temp, img) # text output info = "" if scaled: info += "scaled down" if compression < 100: if info: info += ", " info += "compressed to " + str(compression) + "%" textout += str(os.stat(img).st_size / 1024) + 'kB' if info: textout += " (" + info + ")" if whitespace: textout += ", whitespace added" print textout
true
aea115974e7ad8bd0145af30646fe524479fb819
Python
NeonWizard/Florchestra
/master/python/listplayer.py
UTF-8
1,682
2.8125
3
[ "MIT" ]
permissive
from time import sleep, time from songs import * from serialcomm import * import thread # Octave with naturals and sharps (Zz = rest) octave1 = ["Cn", "Cs", "Dn", "Ds", "En", "Fn", "Fs", "Gn", "Gs", "An", "As", "Bn"] # Octave with flats and the remaining sharps octave2 = ["Bs", "Df", "Dn2", "Ef", "En2", "Es", "Gf", "Gn2", "Af", "An2", "Bf", "Bn2"] def findIndex(note): try: ind = octave1.index(note) except: ind = octave2.index(note) return ind myepoch = int(round(time()*1000)) def millis(): return int(round(time()*1000)) - myepoch def playNote(note, frive, duration): duration = duration/1000.0 sendNote(note, frive) sleep(duration*7/8.0) sendNote(0, frive) sleep(duration/8.0) try: # for note in song4: # if note[0] == "Zz" or note[0] == "Zz2": # ind = 0 # else: # ind = ((findIndex(note[0])+2)%13)+(note[1]-2)*12 # print note[0] # sendNote(ind, 1) # delay = 60.0/song4_tempo*note[2] # sleep(delay*7/8.0) # sendNote(0, 1) # sleep(delay/8.0) playing = True tmp = millis() # Index, lastplay, songlist friveinfo = [ [0, int(tmp), song5], [0, int(tmp), song4] ] basedelay = 60000.0/tempo while playing: tmp = millis() for i in range(len(friveinfo)): frive = friveinfo[i] if (tmp-frive[1]) >= frive[2][frive[0]][2]*basedelay: frive[0] += 1 frive[1] = millis() note = frive[2][frive[0]][0] octave = frive[2][frive[0]][1] if note == "Zz" or note == "Zz2": ind = 0 else: ind = ((findIndex(note)+2)%13)+(octave-2)*12 thread.start_new_thread(playNote, (ind, i, basedelay*frive[2][frive[0]][2])) except: # Reset on early termination/crash sendNote(0, 0) sendNote(0, 1)
true
ed9f43fe405bd162bbc4809f51620988f75c0d9a
Python
Prabhurajhc/Data_Science
/Python/prog1.py
UTF-8
45
3.109375
3
[]
no_license
#add two number a and b a=10 b=20 print(a+b)
true
20813878fb7e6346fb1ab86e8a77a79fb1264b5b
Python
benbendaisy/CommunicationCodes
/python_module/examples/430_Flatten_a_Multilevel_Doubly_Linked_List.py
UTF-8
2,896
3.984375
4
[]
no_license
""" # Definition for a Node. """ class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child class Solution: """ You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. Example 1: Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 2: Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 3: Input: head = [] Output: [] Explanation: There could be empty list in the input. """ def flatten1(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head def flat_dfs(prev_node: Node, cur_node: Node): if not cur_node: return prev_node prev_node.next = cur_node cur_node.prev = prev_node # the curr.next would be tempered in the recursive function t = cur_node.next tail = flat_dfs(cur_node, cur_node.child) cur_node.child = None return flat_dfs(tail, t) prev = Node(0, None, head, None) flat_dfs(prev, head) prev.next.prev = None return prev.next def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head pseudo_head = Node(0, None, head, None) prev = pseudo_head stack = [] stack.append(head) while stack: cur = stack.pop() prev.next = cur cur.prev = prev if cur.next: stack.append(cur.nemxt) if cur.child: stack.append(cur.child) cur.child = None prev = cur pseudo_head.next.prev = None return pseudo_head.next
true
55e5ca1ab4299de690ca882de904f3466e7c52a7
Python
bytehala/imlearningpython
/ch6/q22.py
UTF-8
332
3.65625
4
[]
no_license
first = int(input('First number: ')) second = int(input('Second number: ')) if first > second: temp = first first = second second = temp product = 1 for i in range(first, second+1): if i != 0: product *= i if product < -500 or product > 500: print('Exceeded') break print(product)
true
e8b9a4e0cf7f35a3a1a6a6e20ea8239674fdf2f3
Python
cpradip/Instacart_Recommender
/evaluation/MeanPercentileRank.py
UTF-8
1,486
3.421875
3
[]
no_license
import pandas as pan ###------------------------------------------------------------------### # Evaluate Mean Percentile Rank (MPR) from the prediction results # Get mean of test values with percentile of predicted values ###------------------------------------------------------------------### def Evaluate(filename): print "Loading Unique Users .... " uniqueUsersDF = pan.read_csv("data_source/uniqueUsers.csv") print "Loading Prediction Results ..." predictionResultsDF = pan.read_csv("data_source/" + filename, header=None) rankValue = 0 totalPredictedVal = predictionResultsDF[2].sum(axis=0) print "Calculating rank ..." for index, row in uniqueUsersDF.iterrows(): userId = row["user_id"] ## Get prediction results for each user userResultDF = predictionResultsDF.loc[predictionResultsDF[1] == row["user_id"]] resultCount = len(userResultDF.index) ## Calculate PR for each user for index1, predictionRow in userResultDF.iterrows(): predictionVal = predictionRow[3] actualVal = predictionRow[2] greaterVal = len(userResultDF.loc[userResultDF[3] > predictionVal].index) equalVal = len(userResultDF.loc[userResultDF[3] == predictionVal].index) ## Percentile for each user product percentile = (greaterVal + 0.5*equalVal)*100/resultCount ## Percentile Rank from each user product added to Rank rankValue = rankValue + percentile * actualVal rank = rankValue / totalPredictedVal print "MPR for the test set is:" print rank
true
7789f4fd7278d47382aebc68c79a5b801ca31c21
Python
rquinlivan/music_indexer
/command.py
UTF-8
2,912
2.796875
3
[]
no_license
from os import walk, path from typing import Optional, List, Generator import click import eyed3 from dataclasses import dataclass from mutagen.flac import FLAC, StreamInfo import sqlite3 file_extensions = ['mp3', 'flac'] @dataclass class MusicFile: title: str artist: str album: str album_artist: str track_number: int full_path: str length: int def file_extension(filename): return filename.split('.')[-1] def mp3_handler(file_path) -> MusicFile: audiofile = eyed3.load(file_path) return MusicFile( title = audiofile.tag.title, artist = audiofile.tag.artist, album = audiofile.tag.album, album_artist = audiofile.tag.album_artist, track_number = audiofile.tag.track_num, full_path = file_path, length = 0 ) def flac_handler(file_path) -> MusicFile: audiofile = FLAC(file_path) stream_info: StreamInfo = audiofile.info metadata = {k: v for (k, v) in audiofile.metadata_blocks[2]} return MusicFile( title = metadata['TITLE'], artist = metadata['ARTIST'], album = metadata['ALBUM'], album_artist = metadata['ALBUMARTIST'], track_number = int(metadata['TRACKNUMBER']), full_path = file_path, length = 0 ) handlers = { 'mp3': lambda f: mp3_handler(f), 'flac': lambda f: flac_handler(f) } def index_files(search_path) -> Generator[MusicFile, None, None]: for root, dirs, files in walk(search_path): music_files = ((f, file_extension(f)) for f in files if file_extension(f) in file_extensions) for filename, extension in music_files: handler = handlers.get(extension) if not handler: print(f"Couldn't find handler for file type {extension}") else: music_file = handler(path.join(root, filename)) yield music_file def escape(in_str) -> str: if not in_str or type(in_str) is not str: return "unknown" in_str = in_str.replace('\'', '') return r""+in_str @click.command() @click.option('--search_path', help = 'Path to your music files') @click.option('--database', help = 'Path to output SQLite data files') def index(search_path, database): """ Index files and build a database. """ music_files = index_files(search_path) conn = sqlite3.connect(database) conn.execute(f""" create table if not exists music_files ( title text, artist text, album text, album_artist text, track_number integer, full_path text, length integer ) """) for mf in music_files: sql = f""" insert into music_files (title, artist, album, album_artist, track_number, full_path, length) values ( '{escape(mf.title)}', '{escape(mf.artist)}', '{escape(mf.album)}', '{escape(mf.album_artist)}', '{escape(mf.track_number)}', '{escape(mf.full_path)}', {mf.length} ) """ conn.execute(sql) conn.commit() conn.close()
true
33311df12b5d0bf8561b642a2c559318d64dc004
Python
KiyoshiMu/Survival-Analysis-by-Breast-Cancer-Slides
/useless/toy_snn.py
UTF-8
3,495
2.640625
3
[]
no_license
from keras.models import Sequential import keras.backend as K from keras.layers import Dense, Dropout, BatchNormalization from keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard from keras.regularizers import l2 from keras.optimizers import Adagrad from lifelines.utils import concordance_index import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import os, sys #Loss Function def negative_log_likelihood(E): def loss(y_true,y_pred): hazard_ratio = K.exp(y_pred) log_risk = K.log(K.cumsum(hazard_ratio)) uncensored_likelihood = K.transpose(y_pred) - log_risk censored_likelihood = uncensored_likelihood * E num_observed_event = K.sum([float(e) for e in E]) return K.sum(censored_likelihood) / num_observed_event * (-1) return loss def gen_model(input_shape): model = Sequential() model.add(Dense(128, activation='relu', kernel_initializer='glorot_uniform', input_shape=input_shape)) model.add(Dense(128, activation='relu', kernel_initializer='glorot_uniform')) model.add(Dropout(0.7)) # model.add(Dense(128, activation='relu', kernel_initializer='glorot_uniform')) # model.add(Dropout(0.5)) model.add(Dense(1, activation="linear", kernel_initializer='glorot_uniform', kernel_regularizer=l2(0.01), activity_regularizer=l2(0.01))) return model def eval(model, x, y, e): hr_pred=model.predict(x) hr_pred=np.exp(hr_pred) ci=concordance_index(y,-hr_pred,e) return ci def gen_data(fp): df = pd.read_excel(fp) y = (df.loc[:, ["duration","observed"]]).values x = df.loc[:,'epi_area':'hist_type'] x = (pd.get_dummies(x, drop_first=True)).values return x, y def run_model(fp, dst): x, t_e = gen_data(fp) x_train, x_test, t_e_train, t_e_test = train_test_split(x, t_e, test_size=0.2, random_state=42) # print(t_e_train[:10]) y_train, e_train = t_e_train[:, 0], t_e_train[:, 1] y_test, e_test = t_e_test[:, 0], t_e_test[:, 1] sort_idx = np.argsort(y_train)[::-1] #! x_train = x_train[sort_idx] y_train = y_train[sort_idx] e_train = e_train[sort_idx] x_t_shape = np.shape(x_train) print('{} training images have prepared, shape is {}\ and {}'.format(len(x_train), x_t_shape, np.shape(y_train))) print('{} test images have prepared, shape is {}\ and {}'.format(len(x_test), np.shape(x_test), np.shape(y_test))) model = gen_model(x_t_shape[1:]) ada = Adagrad(lr=1e-3, decay=0.1) model.compile(loss=negative_log_likelihood(e_train), optimizer=ada) cheak_list = [EarlyStopping(monitor='loss', patience=10), ModelCheckpoint(filepath=os.path.join(dst, 'toy.h5') , monitor='loss', save_best_only=True), TensorBoard(log_dir=os.path.join(dst, 'toy_log'), histogram_freq=0)] model.fit( x_train, y_train, batch_size=len(e_train), epochs=10000, verbose=False, callbacks=cheak_list, shuffle=False) ci = eval(model, x_train, y_train, e_train) ci_val = eval(model, x_test, y_test, e_test) with open(os.path.join(dst, 'toy_outcome.txt'), 'w+') as out: line = 'Concordance Index for training dataset:{},\ Concordance Index for test dataset:{}'.format(ci, ci_val) print(line) out.write(line) if __name__ == "__main__": fp = sys.argv[1] dst = sys.argv[2] os.makedirs(dst, exist_ok=True) run_model(fp, dst)
true
252b28d54f7771a8cee4e3ce977508ff96d886b2
Python
j16949/Programming-in-Python-princeton
/3.3/testError.py
UTF-8
210
3.59375
4
[]
no_license
#没有try except时 ''' while True: x = int(input('请输入数字:')) ''' #用try except while True: try: x = int(input('请输入数字:')) except: print('输入数字非法。')
true
97809604fb6a579b014dd53e422534503cd37dd1
Python
guilherme-witkosky/MI66-T5
/Lista 6/L6E04.py
UTF-8
110
4.09375
4
[]
no_license
#Exercício 4 nome = input("DIGITE SEU NOME: ").upper() for i in range(0, len(nome)+1): print(nome[:i])
true
88ef5d987e316768e846a2ecd54a909383d4bb25
Python
zhimingluo/brainmix
/brainmix/core/data.py
UTF-8
728
3.1875
3
[]
no_license
''' Main data structure to contain images stacks. Please see the AUTHORS file for credits. ''' import copy class ImageStack(object): def __init__(self): '''Data structure for images''' self.fileNames = [] self.images = [] self.nImages = 0 self.bitDepth = None def set_images(self, images, bitdepth=None): '''Set the number of images and the original image data''' self.nImages = len(images) self.images = images if bitdepth is not None: self.bitDepth = bitdepth def set_filenames(self, files): '''Set the names of the image files''' self.fileNames = files def copy(self): return copy.deepcopy(self)
true
9cfeb66be15d762952ba68b2eecf87651b3e1ab3
Python
yankur/lab14
/task2_search_time_test/search_time_test.py
UTF-8
861
3.328125
3
[]
no_license
import random import time from linkedbst import LinkedBST def main(): with open('words.txt', ) as words: words = words.readlines() to_find = [] while len(to_find) < 10000: word = random.choice(words) if word not in to_find: to_find.append(word) search_list_test(words, to_find) random.shuffle(words) tree = LinkedBST() for word in words: tree.add(word) search_tree_test(tree, to_find) tree.rebalance() search_tree_test(tree, to_find) def search_list_test(words, to_find): start = time.time() for word in to_find: ind = words.index(word) end = time.time() print(end - start) def search_tree_test(tree, to_find): start = time.time() for word in to_find: ind = tree.find(word) end = time.time() print(end - start) main()
true
373563a1573ff383f14e40abbc65c3c0e64ed1c0
Python
Arkronus/tableau_hyper_demo
/main.py
UTF-8
1,665
2.5625
3
[]
no_license
import os import glob import shutil import argparse from extract import Extract from db import DBWrapper parser = argparse.ArgumentParser(description='Обновление данных в рабочей книге') parser.add_argument('--filename', '-f', required=True, help='Название книги Tableau') parser.add_argument('--date', '-d', required=True, help='Дата обновления в формате ГГГГ-ММ-ДД') args = parser.parse_args() filename = args.filename date = args.date folder_name = os.path.splitext(filename)[0] currentDirectory = os.getcwd() # Файл twbx - архив zip, который можно распаковать с помощью любого архиватора shutil.unpack_archive(filename, extract_dir=folder_name, format='zip') path_to_extract = glob.glob(currentDirectory + '/' + folder_name + '/**/*.hyper', recursive=True)[0] # получаем данные после нужной нам даты data = DBWrapper().get_new_data(date) # подключаемся к экстракту, удаляем старые данные и добавляем новые extract = Extract(path_to_extract) extract.delete_data(date) extract.insert_data(data) del extract # После того, как данные в экстракте обновлены, его нужно снова запаковать и поменять расширение с .zip на .twbx archive_name = shutil.make_archive(folder_name, 'zip', folder_name) os.rename(filename, filename + ".backup") # далаем бэкап предыдущей версии отчета os.rename(folder_name + ".zip", folder_name + ".twbx")
true
eb5b53a0cfa35ee9d7eec5fc0612420e220a53a0
Python
rodrigosantiag/loan-serverless
/src/policies/tests/test_age_policy.py
UTF-8
539
2.65625
3
[]
no_license
import pytest from src.exceptions.policy_exception import PolicyException from src.domains.loan import Loan import datetime from src.policies.age_policy import AgePolicy def test_shouldnt_throw_policy_exception(): loan = Loan('name', 'cpf', datetime.date(2000, 7, 12), 1000, 6, 1000) AgePolicy().apply(loan) def test_should_throw_policy_exception(): with pytest.raises(PolicyException, match='Política negada: age'): loan = Loan('name', 'cpf', datetime.date.today(), 1000, 6, 1000) AgePolicy().apply(loan)
true
c643ac01e68a1bbbdf429244a7ff3b225d8bcfd0
Python
WeiPromise/study
/day05_列表/02-列表的操作.py
UTF-8
1,439
3.609375
4
[]
no_license
#!/usr/bin/env python3.5 # encoding: utf-8 # Created by leiwei on 2020/8/14 16:04 # 列表是有序的,可变的,可进行CRUD操作 names = ['zansan', 'lisi', 'wangwu', 'zhaoliu', 'ake', 'yingzhneg', 'zhaoliu', 'hangxing', 'huangzhong'] # ========================增加======================================= # C 添加 # append 列表末尾添加元素 # insert 列表指定位置之前插入数据 names.insert(names.index('ake'), 'lidema') # extend 末尾追加可迭代对象 a.extend(b),a变b不变 new_names = ['derenjie', 'mkbl'] names.extend(new_names) print(names) # ========================删除======================================= # pop():删除指定位置元素,默认最后一位,返回被删除值 # remove():删除指定元素,没返回值 # clear():清空 # del() : 建议不要用,删除对象 # print(names.pop()) # print(names.remove('zhaoliu')) # names.clear() # print(names) # ========================查询======================================= # 查询某个元素第一次出现位置 print(names.index('zhaoliu')) # 查询某个元素出现次数 print(names.count('zhaoliu')) # in 运算符 if 'zhaoliu' in names: print(names.index('zhaoliu')) # ========================修改======================================= names[3] = 'luguannan' print(names) # ========================反转======================================= names[3] = 'luguannan' names.reverse() print(names)
true
48c4abe218506337225e160660191715add4df87
Python
PavelEgorenko/OOP
/diagonal_matrix.py
UTF-8
1,671
3.25
3
[]
no_license
from matrices import matrices def OutDataFiltr(): return None class diagonal_matrix(matrices): def __init__(self): super().__init__() self.type = "Diagonal" self.mtx = "" def In(self, line): mtx1 = line.split(" ") for i in mtx1: if not i.isdigit(): print("В матрице содержаться не только числа", end=", ") self.isError = True return self.key = mtx1.pop(0) if self.key != "1" and self.key != "2": print("Неверно введен тип вывода данных в диагональной матрице", end=", ") self.isError = True return self.size = len(mtx1) for i in mtx1: mtx2 = "" for k in range(len(mtx1)): if i == mtx1[k]: mtx2 += (i + " ") else: mtx2 += "0 " self.mtx += mtx2 + "\n" self.mtx = self.mtx[:-2] if self.key == "2": self.mtx = self.mtx.replace("\n", "") self.sum_of_elements() def Out(self, ofst): ofst.write("Diagonal two-dimensional array:\n") ofst.write("Size = " + str(self.size) + "\n") ofst.write("Output Type = " + self.OutputType[int(self.key)] + "\n") ofst.write("Sum of elements = " + str(self.sumelems) + "\n") ofst.write(self.mtx + "\n") def OutDataFiltr(self, ofst1): ofst1.write("Diagonal two-dimensional array:\n") ofst1.write("Size = " + str(self.size) + "\n") ofst1.write(self.mtx + "\n\n")
true
accd856cedf82f2d3424153b9ad630cf03ef2b63
Python
ClaudiaWinklmayr/classify-rotated-digits
/functions_and_scripts/create_datasets.py
UTF-8
3,608
2.765625
3
[]
no_license
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import random import pickle from scipy.misc import imrotate ''' This script creates different versions of the MNIST test set (everything rotated by a certain angle or mixed rotations) and saves the resulting datasets as well as additional information (labels, indices of single digits, rotation angles) to a pickled dictionary ''' FILENAME = 'all_mnist_variants.p' #----------------------------------------------------------------------------------# # Load MNIST test set and save to dictionary #----------------------------------------------------------------------------------# mnist = input_data.read_data_sets("MNIST_data", one_hot=True) DATA_SETS = {} DATA_SETS['mnist'] = mnist.test.images DATA_POINTS = mnist.test.images.shape[0] DATA_SHAPE = mnist.test.images.shape #----------------------------------------------------------------------------------# # Create test sets with single rotation angle #----------------------------------------------------------------------------------# mnist_30 = np.zeros(DATA_SHAPE) mnist_60 = np.zeros(DATA_SHAPE) mnist_90 = np.zeros(DATA_SHAPE) mnist_neg30 = np.zeros(DATA_SHAPE) mnist_neg60 = np.zeros(DATA_SHAPE) mnist_neg90 = np.zeros(DATA_SHAPE) for i in range(DATA_POINTS): im = np.reshape(mnist.test.images[i], (28,28)) im30 = imrotate(im, 30, interp='bilinear') im60 = imrotate(im, 60, interp='bilinear') im90 = imrotate(im, 90, interp='bilinear') im_neg30 = imrotate(im, -30, interp='bilinear') im_neg60 = imrotate(im, -60, interp='bilinear') im_neg90 = imrotate(im, -90, interp='bilinear') mnist_30[i] = np.reshape(im30, (784,)) mnist_60[i] = np.reshape(im60, (784,)) mnist_90[i] = np.reshape(im90, (784,)) mnist_neg30[i] = np.reshape(im_neg30, (784,)) mnist_neg60[i] = np.reshape(im_neg60, (784,)) mnist_neg90[i] = np.reshape(im_neg90, (784,))# DATA_SETS['mnist_30'] = mnist_30 DATA_SETS['mnist_60'] = mnist_60 DATA_SETS['mnist_90'] = mnist_90 DATA_SETS['mnist_neg30'] = mnist_neg30 DATA_SETS['mnist_neg60'] = mnist_neg60 DATA_SETS['mnist_neg90'] = mnist_neg90 #----------------------------------------------------------------------------------# # Create mixed set and save angles #----------------------------------------------------------------------------------# angles = range(-90,90+1,15) phis = np.zeros(DATA_POINTS) mnist_mix = np.zeros(DATA_SHAPE) for i in range(DATA_POINTS): im = np.reshape(mnist.test.images[i], (28,28)) phi = random.sample(angles,1)[0] phis[i] = phi im_rot = imrotate(im, phi, interp='bilinear') mnist_mix[i] = np.reshape(im_rot, (784,)) DATA_SETS['mnist_mix'] = mnist_mix DATA_SETS['mnist_mix_angles'] = phis #----------------------------------------------------------------------------------# # Save lables vector and dictionary with single digit indices #----------------------------------------------------------------------------------# single_numbers_test = {} for i in range(10): single_numbers_test['only_'+str(i)] = [] for idx in range(DATA_POINTS): d = np.flatnonzero(mnist.test.labels[idx])[0] single_numbers_test['only_'+str(d)].append(idx) DATA_SETS['digit_idx'] = single_numbers_test DATA_SETS['labels'] = mnist.test.labels #----------------------------------------------------------------------------------# # Save pickled data #----------------------------------------------------------------------------------# pickle.dump(DATA_SETS, open(FILENAME, 'wb'))
true
7164153df6340f8b919ce6711a1dd209d140f94c
Python
janani-02/project_s
/prog7.py
UTF-8
231
3.046875
3
[]
no_license
class human: species="h.sapiens" def _init_(self,name): self.name=name self.age=0 def say(self,msg): print("{name}:{message}".format(name=self.name,message=msg))
true
26a9828b147b9fe70263101a4f93d15c49ffcc62
Python
yeduxiling/pythonmaster
/absex80.py
UTF-8
263
3.640625
4
[]
no_license
cannoteat_food = ['油泼面', '小面', '火锅儿'] for food in cannoteat_food: print(food) print() for food in cannoteat_food: print(f'我不能吃{food},我真是太难了!') print() print('养成良好的饮食习惯,从你我身边做起!')
true
7025063caf64e58fe34d99fe3411109d29b35fd4
Python
sp-shaopeng/leetcode-practice
/1905.py
UTF-8
1,157
2.984375
3
[]
no_license
class Solution(object): def countSubIslands(self, grid1, grid2): """ :type grid1: List[List[int]] :type grid2: List[List[int]] :rtype: int """ count = 0 m = len(grid1) n = len(grid1[0]) visited = [[0 for i in range(n)] for j in range(m)] def find(x,y) : if(x >= 0 and x < m and y >= 0 and y < n and grid2[x][y] == 1 and visited[x][y] == 0) : visited[x][y] = 1 if(grid2[x][y] == grid1[x][y]) : t = find(x-1, y) l = find(x, y-1) r = find(x, y+1) d = find(x+1, y) return t and l and r and d else : find(x-1, y) find(x, y-1) find(x, y+1) find(x+1, y) return False return True for i in range(m) : for j in range(n) : if(grid2[i][j] and visited[i][j] == 0 and find(i,j)) : count += 1 return count
true
0afe6a7000563263bce78142b9454d0d2c6befd9
Python
yuwenjuan/douban_movie_top250
/douban_movie_top250.py
UTF-8
3,600
3.03125
3
[]
no_license
#-*-coding:utf-8-*- import sys reload(sys) sys.setdefaultencoding('utf8') import numpy as np import pandas as pd from pandas import DataFrame,Series from bs4 import BeautifulSoup from urllib2 import urlopen import re #正则表达式分割字符串 def func_split(string,pattern): return re.split(pattern,string) def trans_list(main_list,sub_list): index = main_list.index(sub_list) sub_list.reverse() #反转list的排列 for ele in sub_list: main_list.insert(index,ele) #后一元素插入在前一元素之前 main_list.pop(main_list.index(sub_list)) return main_list def extract_info(li_tag): info = [] for string in li_tag.stripped_strings: info.append(string) if '[可播放]' in info: index = info.index('[可播放]') info.pop(index) #pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 class_hd = li_tag.find('div',{'class':'hd'}) if len(class_hd.a.find_all('span')) == 2: if ' / ' in info[2]: info.insert(2,np.NaN) #缺失则插入NaN info[3] = info[3][2:] else: info[2] = info[2][2:] info.insert(3,np.NaN) else: info[2] = info[2][2:] #电影中文名,\xa0表示16进制下A0的一个数,为一个字符 info[3] = info[3][2:] #电影外文名 Dir_and_Act = func_split(info[4],r':|\xa0\xa0\xa0') #分割字符串:导演、主演 if len(Dir_and_Act) == 3:#分割后列表里不含‘主演名字’的情况 Dir_and_Act.append('NaN') elif len(Dir_and_Act) == 2:#分割后列表里只含‘导演’和‘导演名字’的情况 Dir_and_Act.append('NaN') Dir_and_Act.append('NaN') Yea_Cou_Gen = func_split(info[5],r'\xa0/\xa0') info[4] = Dir_and_Act info[5] = Yea_Cou_Gen info = trans_list(info,Dir_and_Act) info = trans_list(info,Yea_Cou_Gen) info.pop(4) #删除列表中的‘导演’项 info.pop(5) #删除列表中的'演员'项 return info #返回一行movie的数据,list的形式 def collecting_data(url,database): soup = BeautifulSoup(urlopen(url),'lxml') movie_grid = soup.find_all('ol',{'class':'grid_view'}) #找到电影表单 movie = movie_grid[0].find_all('li') for li in movie: database.append(extract_info(li)) #data为list前提下,DataFrame([data])为行排列,DataFrame(data)为列排列 return database #database=[[],[],[],....] def collect_all(url): database=[] collecting_data(url,database) data=pd.DataFrame(database) return data #返回一行数据 def main(): page = [] for sequence in list(range(0,250,25)): url = r'https://movie.douban.com/top250?start=%d&filter=' %sequence #所有的网页地址 page.append(collect_all(url)) #添加爬取的相关数据 GeneralData = pd.DataFrame() for i in range(len(page)): GeneralData = pd.concat([GeneralData,page[i]],ignore_index = True) #pd.concat:[]内要为DataFrame形式 #保存数据为csv #GeneralData = GeneralData.drop(0,axis=1) column = ['排名','电影中文名','电影外文名','电影别名','导演','演员','年份','地区','类别','评分','评分人数','电影概况'] GeneralData.columns = column #GeneralData.to_csv('MovieTop250.csv',encoding='utf-8') #此函数默认解码方式为utf-8,但是在保存时不加encoding的话,读取会产生错误 GeneralData.to_csv('E:/Movie.csv') if __name__ == '__main__': main()
true
bfebb9dfafd46a5ff43dff642c982543c638d235
Python
paw-lu/modern-pandas
/modern-pandas/6_visualization.py
UTF-8
4,986
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent,md # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.3.0 # kernelspec: # display_name: modern-pandas # language: python # name: modern-pandas # --- # %% [markdown] Collapsed="false" # # Visualization and exploratory analysis # %% Collapsed="false" import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # %% [markdown] Collapsed="false" # ## Data # %% Collapsed="false" df = pd.read_csv( "http://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/diamonds.csv", index_col=0, ) df.head() # %% Collapsed="false" df.info() # %% Collapsed="false" sns.set(context="talk", style="ticks") # %matplotlib inline # %% [markdown] Collapsed="false" # ## Matplotlib # %% [markdown] Collapsed="false" # Matplotlib can plot labeled data now I guess # %% Collapsed="false" fig, ax = plt.subplots() ax.scatter(x="carat", y="depth", data=df, c="k", alpha=0.15) # %% [markdown] Collapsed="false" # ## Pandas built-int # %% [markdown] Collapsed="false" # <div class="alert alert-block alert-info"> # <H3>Techniques of note</H3> # <li><b><code>pandas_datareader</code></b> library to pull data from various sources into a DataFrame</li> # </div> # %% Collapsed="false" df.plot.scatter(x="carat", y="depth", c="k", alpha=0.15) plt.tight_layout() # %% [markdown] Collapsed="false" # Convenient to plot in when index is timeseries # %% Collapsed="false" from pandas_datareader import fred gdp = fred.FredReader(["GCEC96", "GPDIC96"], start="2000-01-01").read() gdp.rename( columns={"GCEC96": "Government Expenditure", "GPDIC96": "Private Investment"} ).plot(figsize=(12, 6)) plt.tight_layout() # %% Collapsed="false" gdp.head() # %% [markdown] Collapsed="false" # ## Seaborn # %% [markdown] Collapsed="false" # <div class="alert alert-block alert-info"> # <h3>Techniques of note</h3> # <h4>Pandas</h4> # <li><b><code>.quantile</code></b> get the value of a certain quantile per column</li> # <li><b><code>.all</code></b> to test if all values in a column are True</li> # <h4>Seaborn</h4> # <li><b><code>countplot</code></b> histogram</li> # <li><b><code>jointplot</code></b> scatter</li> # <li><b><code>pairplot</code></b> pairwise scatter and histogram</li> # <li><b><code>PairGrid</code></b> to make a seaborn grid of pairs</li> # <li><b><code>FacetGrid</code></b> to make a seaborn grid of different values</li> # <li><b><code>catplot</code></b> to make a seaborn out of different categories</li> # <li><b><code>.map</code></b> For assigning different plots seaborn <code>Grid</code>s</li> # <li><b><code>.map_upper/.map_diag/.map_lower</code></b> For assigning different plots to <code>PairGrid</code></li> # # </div> # %% Collapsed="false" sns.countplot(x="cut", data=df) sns.despine() plt.tight_layout() # %% Collapsed="false" sns.jointplot(x="carat", y="price", data=df, height=8, alpha=0.25, color="k", marker=".") plt.tight_layout() # %% Collapsed="false" g = sns.pairplot(df, hue="cut") # %% [markdown] Collapsed="false" # Seaborn has `Grid`s—which you can use to plot functions over each axis. # %% Collapsed="false" def core(df, α=0.05): mask = (df > df.quantile(α)).all(1) & (df < df.quantile(1 - α)).all(1) return df[mask] # %% Collapsed="false" cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True) ( df.select_dtypes(include=[np.number]) .pipe(core) .pipe(sns.PairGrid) .map_upper(plt.scatter, marker=".", alpha=0.25) .map_diag(sns.kdeplot) .map_lower(plt.hexbin, cmap=cmap, gridsize=20) ); # %% Collapsed="false" agged = df.groupby(["cut", "color"]).mean().sort_index().reset_index() g = sns.PairGrid( agged, x_vars=agged.columns[2:], y_vars=["cut", "color"], size=5, aspect=0.65 ) g.map(sns.stripplot, orient="h", size=10, palette="Blues_d"); # %% Collapsed="false" g = sns.FacetGrid(df, col="color", hue="color", col_wrap=4) g.map(sns.regplot, "carat", "price"); # %% Collapsed="false" from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # %% Collapsed="false" df = sns.load_dataset("titanic") clf = RandomForestClassifier() param_grid = dict( max_depth=[1, 2, 5, 10, 20, 30, 40], min_samples_split=[2, 5, 10], min_samples_leaf=[2, 3, 5], ) est = GridSearchCV(clf, param_grid=param_grid, n_jobs=4) y = df["survived"] X = df.drop(["survived", "who", "alive"], axis=1) X = pd.get_dummies(X, drop_first=True) X = X.fillna(value=X.median()) est.fit(X, y); # %% Collapsed="false" scores = pd.DataFrame(est.cv_results_) scores.head() # %% Collapsed="false" sns.catplot( x="param_max_depth", y="mean_test_score", col="param_min_samples_split", hue="param_min_samples_leaf", data=scores, ); # %% Collapsed="false"
true
678946f7e5f6f9df3d285f265b41cfea0ad453b5
Python
SnoopySYF/leetcode
/weekly/160/3.py
UTF-8
447
2.96875
3
[]
no_license
class Solution(object): def maxLength(self, arr): """ :type arr: List[str] :rtype: int """ alen = len(arr) if(alen == 0): return 0 lenset = {} for i in range(alen): lenset[arr[i]] = len(arr[i]) a = sorted(lenset.items(), key=lambda x: x[1], reverse=True) res = 0 for key, value in a:
true
eafd91eeccf9732ef00dcc0141bcb338325fef77
Python
Manish789/FunWithPython
/algoCode/selectionSort.py
UTF-8
493
3.734375
4
[]
no_license
# selectionSort # This takes O(n * n) time or O(n^2) time. def findSmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionSort(arr): newArr = [] for i in range(len(arr)): smallest = findSmallest(arr) newArr.append(arr.pop(smallest)) return newArr print(selectionSort([5,3,6,210,10,5,8,34,5]))
true
6a438fffccfac74f96ca15b874dedb2b537c680e
Python
melvinperello/PythonSimpleNetworkedATM
/AtmTestCase/src/main/UserInterface.py
UTF-8
25,066
2.796875
3
[]
no_license
''' Created on Jul 26, 2017 @author: Jhon Melvin ''' from Tkinter import Tk, Toplevel from Tkinter import Label from Tkinter import Button from Tkinter import PhotoImage from Tkinter import X from Tkinter import Entry from tkMessageBox import showinfo,showerror,showwarning from Oras import Time from Depositor import Depositor ''' Messenger ''' class Message(): def __init__(self): pass #end construct @staticmethod def info(msg): showinfo(title="Information",message=msg) pass @staticmethod def error(msg): showerror(title="Error",message=msg) pass @staticmethod def warning(msg): showwarning(title="Warning",message=msg) pass pass# end class ''' Create Account Class --------------------------------------------------------------------------------------- ''' class CreateAccount(): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.constructWindow() pass # end construct def constructWindow(self): self.frm_create = Tk() self.frm_create.geometry('300x400+310+0') self.frm_create.title('Welcome') self.frm_create.resizable(False, False) self.lbl_menu = Label(self.frm_create,text="New Account",font=("Courier", 20)).pack() self.lbl_divider1 = Label(self.frm_create,text="------------------",font=("Courier", 20)).pack() # Label(self.frm_create,text="Account Number",font=("Courier", 15)).pack() # account number field self.txt_accountNumber = Entry(self.frm_create,justify='center',font=("Courier", 15)) self.txt_accountNumber.pack(fill=X,padx=30) # Label(self.frm_create,text="Account Name",font=("Courier", 15)).pack() # self.txt_accountName = Entry(self.frm_create,justify='center',font=("Courier", 15)) self.txt_accountName.pack(fill=X,padx=30) # Label(self.frm_create,text="Pin",font=("Courier", 15)).pack() # self.txt_pin = Entry(self.frm_create,show="*",justify='center',font=("Courier", 15)) self.txt_pin.pack(fill=X,padx=30) # Label(self.frm_create,text="Confirm Pin",font=("Courier", 15)).pack() # self.txt_confirmPin = Entry(self.frm_create,show="*",justify='center',font=("Courier", 15)) self.txt_confirmPin.pack(fill=X,padx=30) # Label(self.frm_create,text="Initial Deposit",font=("Courier", 15)).pack() # self.txt_initial = Entry(self.frm_create,justify='center',font=("Courier", 15)) self.txt_initial.pack(fill=X,padx=30) # self.btn_create = Button(self.frm_create,text="Create Account",font=("Courier", 10),bg='#FFFFFF',height='20',command = lambda: self.onCreateAccount()) self.btn_create.pack(fill=X,padx=10,pady=5) self.frm_create.mainloop() pass # end function ''' button events ''' def onCreateAccount(self): self.validateForm() pass # end func ''' class methods''' def validateForm(self): ''' Empty Field Checker ''' if(self.txt_accountNumber.get() == ""): Message.warning("Account Number is Empty") return ''' Check if Existing ''' depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) res = depositor.fetch(self.txt_accountNumber.get()) if res: Message.warning("Account Number Already Existing.") depositor.clearFields() return pass ''' ---------------------------------------------''' if(self.txt_accountName.get() == ""): Message.warning("Account Name is Empty") return if(self.txt_pin.get() == ""): Message.warning("Pin is Empty") return if(self.txt_confirmPin.get() == ""): Message.warning("Confirm Pin is Empty") return if(self.txt_initial.get() == ""): Message.warning("Initial Deposit is Empty") return ''' if all fields are filled up proceed to validation ''' if(not self.isValidAccountNumber(self.txt_accountNumber.get())): return ''' if account number is valid ''' # proceed check if account name is alpha space accountName = self.txt_accountName.get() if not all(x.isalpha() or x.isspace() for x in accountName): Message.warning("Account Name must be letters and spaces only.") return pass ''' if account name is valid ; check for pin code''' pin = self.txt_pin.get() # check if 4 digits if(len(pin) <> 4): Message.warning("Pin Code must be Four (4) Digits.") return if(not pin.isdigit()): Message.warning("Pin Code must contain Numbers only.") return # if pincode is ok check if match confirmPin = self.txt_confirmPin.get() if(pin <> confirmPin): Message.warning("Pin and Confirm Pin does not match.") return # if match ''' Check initial deposit ''' initialDeposit = self.txt_initial.get() if not all(c.isdigit() or c =="." for c in initialDeposit): Message.warning("Invalid Initial Deposit Amount") return if float(initialDeposit) < 2000: Message.warning("Insufficient initial deposit, must be atleast P 2000.00") return ''' ---------- Filters all; completed successfully --------------------''' depositor.clearFields() # reset fields depositor.setAccountNumber(self.txt_accountNumber.get()) depositor.setAccountName(accountName) depositor.setPinCode(pin) depositor.setBalance(initialDeposit) depositor.setCreatedDate(Time.now()) result = depositor.save() depositor.clearFields() # reset fields # transaction result Message.info(result) self.frm_create.destroy() pass #end function # checks the account number def isValidAccountNumber(self,accountNumber): length = len(accountNumber) # if not 10 digits if (length <> 10): Message.warning("Account Number must be Ten (10) Digits.") return False pass #end if # if 10 digits proceed to checking # check if all numbers if(not accountNumber.isdigit()): Message.warning("Account Number must be digits only") return False pass # if OK return True pass #end # end class ''' Home Screen Class --------------------------------------------------------------------------------------- ''' class HomeScreen(): ''' classdocs ''' def __init__(self): ''' Constructor ''' ''' Start Server ''' depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) if not depositor.configureNetwork(): Message.error("Cannot Connect To Server.") exit() pass ## self.constructWindow() pass # end construct def constructWindow(self): self.frm_home = Tk() self.frm_home.geometry('300x370+0+0') self.frm_home.title('Welcome') self.frm_home.resizable(False, False) Label(self.frm_home,text="Your Bank Name",font=("Courier", 20)).pack() Label(self.frm_home,text="------------------",font=("Courier", 20)).pack() # Label(self.frm_home,text="Enter Account #",font=("Courier", 15)).pack() self.txt_accountNumber = Entry(self.frm_home,justify='center',font=("Courier", 15)) self.txt_accountNumber.pack(fill=X,padx=30) # self.img_begin = PhotoImage(file="img_begin.gif") self.btn_begin = Button(self.frm_home,text="Begin Transaction",font=("Courier", 10),bg='#FFFFFF',image=self.img_begin,compound='left',command = lambda: self.onBeginTransaction()) self.btn_begin.pack(fill=X,padx=10,pady=5) # Label(self.frm_home,text="------- OR -------",font=("Courier", 20)).pack() # self.img_create = PhotoImage(file="img_add_account.gif") self.btn_create = Button(self.frm_home,text="Create Account",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_create,compound='left',command = lambda: self.onCreate()) self.btn_create.pack(fill=X,padx=10,pady=5) # self.img_exit = PhotoImage(file="img_exit.gif") self.btn_exit = Button(self.frm_home,text="Exit",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_exit,compound='left',command = lambda: self.onExit()) self.btn_exit.pack(fill=X,padx=10,pady=5) self.frm_home.mainloop() pass # end ''' button events ''' def onBeginTransaction(self): accountNumber = self.txt_accountNumber.get() if accountNumber == "": Message.warning("Please Enter Your Account Number To Begin Transaction.") return #----------------------------------------- depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) res = depositor.fetch(accountNumber) if(res): self.frm_home.destroy() Menu() else: Message.error("Account Not Existing") #----------------------------------------- pass #end def onCreate(self): print "create" CreateAccount() pass #end def onExit(self): print "exit" exit() pass #end pass # end class ''' Menu Class --------------------------------------------------------------------------------------- ''' class Menu(): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.constructWindow() pass # end construct ''' creates the main menu window ''' def constructWindow(self): self.frm_menu = Tk() self.frm_menu.geometry('400x450+0+0') self.frm_menu.title('Main Menu') self.frm_menu.resizable(False, False) Label(self.frm_menu,text="ATM Menu",font=("Courier", 30)).pack() Label(self.frm_menu,text="Select Your Transaction",font=("Courier", 10)).pack() self.lbl_menu = Label(self.frm_menu,text="Account # 0123456789",font=("Courier", 10)) self.lbl_menu.pack() depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) self.lbl_menu.config(text="Account # " +depositor.getAccountNumber()) ''' buttons ''' self.img_deposit = PhotoImage(file="img_deposit.gif") self.btn_deposit = Button(self.frm_menu,text="Deposit",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_deposit,compound='left',command = lambda:self.onDeposit()) self.btn_deposit.pack(fill=X,padx=10) # self.img_withdraw = PhotoImage(file="img_withdraw.gif") self.btn_withdraw = Button(self.frm_menu,text="Withdraw",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_withdraw,compound='left',command = lambda:self.onWithraw()) self.btn_withdraw.pack(fill=X,padx=10) # self.img_balance = PhotoImage(file="img_balance.gif") self.btn_balance = Button(self.frm_menu,text="Balance Inquiry",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_balance,compound='left',command = lambda:self.onBalance()) self.btn_balance.pack(fill=X,padx=10) # self.img_change = PhotoImage(file="img_change_pin.gif") self.btn_changepin = Button(self.frm_menu,text="Change Pin",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_change,compound='left',command = lambda:self.onPinChange()) self.btn_changepin.pack(fill=X,padx=10) # self.img_view = PhotoImage(file="img_view_account.gif") self.btn_view = Button(self.frm_menu,text="View Account",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_view,compound='left',command = lambda:self.onViewInfo()) self.btn_view.pack(fill=X,padx=10) # self.img_end = PhotoImage(file="img_end_transaction.gif") self.btn_end = Button(self.frm_menu,text="End Transaction",anchor='w',font=("Courier", 10),bg='#FFFFFF',image=self.img_end,compound='left',command = lambda:self.onEndTransaction()) self.btn_end.pack(fill=X,padx=10) ''' display the window ''' self.frm_menu.mainloop() pass #end ''' button events ''' def verify(self): try: verify = popupWindow(self.frm_menu) self.frm_menu.wait_window(verify.top) depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) if(verify.value == depositor.getPinCode()): return True else: Message.info("Wrong Pin Code") return False except: Message.info("Transaction Cancelled") return False pass pass # def onDeposit(self): print "deposit" if self.verify(): DepositWindow() pass # end func def onWithraw(self): print "withdraw" if self.verify(): WithdrawWindow() pass #end func def onBalance(self): print "balance" if self.verify(): BalanceWindow() pass #end func def onViewInfo(self): print "view" if self.verify(): ViewWindow() pass #end func def onPinChange(self): if self.verify(): ChangePinWindow() print "change" pass #end func def onEndTransaction(self): print "end" depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) depositor.clearFields() self.frm_menu.destroy() HomeScreen() pass #end func pass # end class ''' Window Classes --------------------------------------------------------------------------------------- Deposit Window ''' class DepositWindow(): def __init__(self): self.constructWindow() pass # end cons def constructWindow(self): self.frm_deposit = Tk() self.frm_deposit.geometry('400x200+405+115') self.frm_deposit.title('Transaction') self.frm_deposit.resizable(False, False) Label(self.frm_deposit,text="Deposit",font=("Courier", 20)).pack() Label(self.frm_deposit,text="------------------",font=("Courier", 20)).pack() Label(self.frm_deposit,text="Enter Amount",font=("Courier", 15)).pack() self.txt_amount = Entry(self.frm_deposit,justify='center',font=("Courier", 15)) self.txt_amount.pack(fill=X,padx=30) # self.btn_deposit = Button(self.frm_deposit,text="Deposit",font=("Courier", 10),bg='#FFFFFF',height = 15,command = lambda: self.onDeposit()) self.btn_deposit.pack(fill=X,padx=10,pady=5) self.frm_deposit.mainloop() pass # end function def onDeposit(self): amount = self.txt_amount.get() try: peso = float(amount) if peso < 1.00: Message.warning("Insufficient Amount !, Minimum is One (1) pesos/s") return self.depositFunds(peso) pass except: Message.error("Cannot Deposit, Invalid Amount !") pass pass def depositFunds(self,peso): depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) current_funds = float(depositor.getBalance()) + peso depositor.setBalance(str(current_funds)) result = depositor.save() Message.info("Deposit Transaction: " + result) self.frm_deposit.destroy() pass pass # end class ''' Withdraw Window ---------------------------------------------------------------------- ''' class WithdrawWindow(): def __init__(self): self.constructWindow() pass # end construct def constructWindow(self): self.frm_withdraw = Tk() self.frm_withdraw.geometry('400x200+405+170') self.frm_withdraw.title('Transaction') self.frm_withdraw.resizable(False, False) Label(self.frm_withdraw,text="Withdraw",font=("Courier", 20)).pack() Label(self.frm_withdraw,text="------------------",font=("Courier", 20)).pack() Label(self.frm_withdraw,text="Enter Amount",font=("Courier", 15)).pack() self.txt_amount = Entry(self.frm_withdraw,justify='center',font=("Courier", 15)) self.txt_amount.pack(fill=X,padx=30) # self.btn_withdraw = Button(self.frm_withdraw,text="Withdraw",font=("Courier", 10),bg='#FFFFFF',height = 15,command = lambda: self.onWithdraw()) self.btn_withdraw.pack(fill=X,padx=10,pady=5) self.frm_withdraw.mainloop() pass # EF def onWithdraw(self): amount = self.txt_amount.get() try: peso = float(amount) butal = peso % 100 if(butal == 50.00 or butal == 0.00): self.withdrawFunds(peso) pass else: Message.warning("Unsupported Denomination, Please Withdraw with Fifty(50) as the lowest bill.") pass pass except Exception as e: Message.error("Cannot Withdraw, Invalid Amount !") pass pass def withdrawFunds(self,peso): depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) # check if have sufficient funds current_funds = float(depositor.getBalance()) if (current_funds - peso) >= 0.00 and (current_funds - peso) < 2000.00: Message.warning("Cannot Withdraw, Must Maintain atleast P 2000.00") return pass if (current_funds - peso) < 0: Message.warning("Insufficient Funds") return current_funds = current_funds - peso depositor.setBalance(str(current_funds)) result = depositor.save() Message.info("Withdraw Transaction: " + result) self.frm_withdraw.destroy() pass pass #end class ''' Balance ------------------------------------------------------------------------- ''' class BalanceWindow(): def __init__(self): self.constructWindow() pass # end construct def constructWindow(self): self.frm_withdraw = Tk() self.frm_withdraw.geometry('400x200+405+225') self.frm_withdraw.title('Transaction') self.frm_withdraw.resizable(False, False) Label(self.frm_withdraw,text="Balance Inquiry",font=("Courier", 20)).pack() Label(self.frm_withdraw,text="------------------",font=("Courier", 20)).pack() Label(self.frm_withdraw,text="Remaining Balance",font=("Courier", 15)).pack() self.lbl_balance = Label(self.frm_withdraw,text="P 150000",font=("Courier", 30)) self.lbl_balance.pack() depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) self.lbl_balance.config(text = "P " + depositor.getBalance()) self.frm_withdraw.mainloop() pass # EF pass #end class ''' Change Pin ------------------------------------------------------------------------- ''' class ChangePinWindow(): def __init__(self): self.constructWindow() pass # end construct def constructWindow(self): self.frm_change_pin = Tk() self.frm_change_pin.geometry('400x250+405+280') self.frm_change_pin.title('Transaction') self.frm_change_pin.resizable(False, False) Label(self.frm_change_pin,text="Change Pin",font=("Courier", 20)).pack() Label(self.frm_change_pin,text="------------------",font=("Courier", 20)).pack() Label(self.frm_change_pin,text="Enter New Pin",font=("Courier", 15)).pack() self.txt_old = Entry(self.frm_change_pin,show="*",justify='center',font=("Courier", 15)) self.txt_old.pack(fill=X,padx=30) # Label(self.frm_change_pin,text="Confirm New Pin",font=("Courier", 15)).pack() self.txt_new = Entry(self.frm_change_pin,show="*",justify='center',font=("Courier", 15)) self.txt_new.pack(fill=X,padx=30) # self.btn_withdraw = Button(self.frm_change_pin,text="Change",font=("Courier", 10),bg='#FFFFFF',height = 15,command = lambda: self.onChange()) self.btn_withdraw.pack(fill=X,padx=10,pady=5) self.frm_change_pin.mainloop() pass # EF def onChange(self): new_pin = self.txt_old.get() confirm_pin = self.txt_new.get() try: int(new_pin) if(len(new_pin) <> 4): Message.warning("Pin Code Must Be Four (4) Digits") return if(confirm_pin <> new_pin): Message.warning("New Pin and Confirm New Pin Does Not Match.") return # Pin Change self.changePin(new_pin) pass except: Message.warning("Invalid New Pin Code") pass pass def changePin(self,new_pin): depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) depositor.setPinCode(new_pin) result = depositor.save() Message.info("Pin Change Transaction: " + result) self.frm_change_pin.destroy() pass pass #end class ''' Change Pin ------------------------------------------------------------------------- ''' class ViewWindow(): def __init__(self): self.constructWindow() pass # end construct def constructWindow(self): self.frm_withdraw = Tk() self.frm_withdraw.geometry('400x250+405+335') self.frm_withdraw.title('Transaction') self.frm_withdraw.resizable(False, False) Label(self.frm_withdraw,text="Account Information",font=("Courier", 20)).pack() Label(self.frm_withdraw,text="------------------",font=("Courier", 20)).pack() # Label(self.frm_withdraw,text="Account #",font=("Courier", 15,'bold')).pack() self.lbl_accountNumber = Label(self.frm_withdraw,text="01210120112",font=("Courier", 15)) self.lbl_accountNumber.pack() # Label(self.frm_withdraw,text="Account Name",font=("Courier", 15,'bold')).pack() self.lbl_accountName = Label(self.frm_withdraw,text="Juan Dela Cruz",font=("Courier", 15)) self.lbl_accountName.pack() # Label(self.frm_withdraw,text="Date Created",font=("Courier", 15,'bold')).pack() self.lbl_date = Label(self.frm_withdraw,text="07/26/2017",font=("Courier", 15)) self.lbl_date.pack() depositor = Depositor.getInstance() assert isinstance(depositor, Depositor) self.lbl_accountNumber.config(text = depositor.getAccountNumber()) self.lbl_accountName.config(text = depositor.getAccountName()) self.lbl_date.config(text = depositor.getCreatedDate()) self.frm_withdraw.mainloop() pass # EF pass #end class class popupWindow(object): def __init__(self,master): top=self.top=Toplevel(master) self.top.geometry('250x100+405+100') self.top.title("Verification") self.top.resizable(False, False) self.l=Label(top,text="Enter Pin",font=("Courier", 20)) self.l.pack() self.e=Entry(top,show="*",justify='center') self.e.pack(fill=X,padx=30) self.b=Button(top,text='Proceed',command=self.cleanup) self.b.pack() def cleanup(self): self.value=self.e.get() self.top.destroy() pass
true
d40bda8ea4a26963bc999c06136933b3dfb87f70
Python
winan305/Algorithm-with-Python3
/BOJ2947.py
UTF-8
211
3.140625
3
[]
no_license
tree = list(map(int, input().split())) for i in range(5) : for j in range(4) : if tree[j] > tree[j+1] : tree[j], tree[j+1] = tree[j+1], tree[j] print(' '.join(map(str,tree)))
true
2ddadf9019232739cbb87f571dd8c8567640243e
Python
jrahman-zz/CS307
/executionserver/python/runtests.py
UTF-8
1,320
2.609375
3
[]
no_license
import urllib import urllib2 import json import requests url = 'http://localhost:5000/level/submit' combined_data = {} combined_data['valid_context'] = {'jsondata':json.dumps({"codelines":["z=x+2", "y=y*z"], "context":{"y":2, "x":3}})} combined_data['valid_no_context'] = {'jsondata':json.dumps({"codelines":["x=3", "y=2", "z=x+2", "y=y*z"]})} combined_data['valid_for_loop'] = {'jsondata':json.dumps({"codelines":["y=0", "for n in range(1,10):", " y+=n"]})} response = requests.post(url, data = combined_data['valid_context']) print(response.text) response = requests.post(url, data = combined_data['valid_context']) print(response.text) response = requests.post(url, data = combined_data['valid_no_context']) print(response.text) response = requests.post(url, data = combined_data['valid_for_loop']) print(response.text)
true
949dfd3e01b1a9490fa9e884ff79242ae83c302f
Python
YeWR/robosuite
/robosuite/controllers/baxter_ik_controller.py
UTF-8
13,324
2.734375
3
[ "MIT" ]
permissive
""" NOTE: requires pybullet module. Run `pip install pybullet==1.9.5`. """ import os import numpy as np try: import pybullet as p except ImportError: raise Exception( "Please make sure pybullet is installed. Run `pip install pybullet==1.9.5`" ) import robosuite.utils.transform_utils as T from robosuite.controllers import Controller class BaxterIKController(Controller): """ Inverse kinematics for the Baxter robot, using Pybullet and the urdf description files. """ def __init__(self, bullet_data_path, robot_jpos_getter): """ Args: bullet_data_path (str): base path to bullet data. robot_jpos_getter (function): function that returns the joint positions of the robot to be controlled as a numpy array. """ # Set up inverse kinematics self.robot_jpos_getter = robot_jpos_getter path = os.path.join(bullet_data_path, "baxter_description/urdf/baxter_mod.urdf") self.setup_inverse_kinematics(path) self.rest_joints = np.zeros(14) self.commanded_joint_positions = robot_jpos_getter() self.sync_state() def get_control(self, right=None, left=None): """ Returns joint velocities to control the robot after the target end effector positions and orientations are updated from arguments @left and @right. If no arguments are provided, joint velocities will be computed based on the previously recorded target. Args: left (dict): A dictionary to control the left end effector with these keys. dpos (numpy array): a 3 dimensional array corresponding to the desired change in x, y, and z left end effector position. rotation (numpy array): a rotation matrix of shape (3, 3) corresponding to the desired orientation of the left end effector. right (dict): A dictionary to control the left end effector with these keys. dpos (numpy array): a 3 dimensional array corresponding to the desired change in x, y, and z right end effector position. rotation (numpy array): a rotation matrix of shape (3, 3) corresponding to the desired orientation of the right end effector. Returns: velocities (numpy array): a flat array of joint velocity commands to apply to try and achieve the desired input control. """ # Sync joint positions for IK. self.sync_ik_robot(self.robot_jpos_getter()) # Compute new target joint positions if arguments are provided if (right is not None) and (left is not None): self.commanded_joint_positions = self.joint_positions_for_eef_command( right, left ) # P controller from joint positions (from IK) to velocities velocities = np.zeros(14) deltas = self._get_current_error( self.robot_jpos_getter(), self.commanded_joint_positions ) for i, delta in enumerate(deltas): velocities[i] = -2 * delta velocities = self.clip_joint_velocities(velocities) self.commanded_joint_velocities = velocities return velocities # For debugging purposes: set joint positions directly # robot.set_joint_positions(self.commanded_joint_positions) def sync_state(self): """ Syncs the internal Pybullet robot state to the joint positions of the robot being controlled. """ # sync IK robot state to the current robot joint positions self.sync_ik_robot(self.robot_jpos_getter()) # make sure target pose is up to date pos_r, orn_r, pos_l, orn_l = self.ik_robot_eef_joint_cartesian_pose() self.ik_robot_target_pos_right = pos_r self.ik_robot_target_orn_right = orn_r self.ik_robot_target_pos_left = pos_l self.ik_robot_target_orn_left = orn_l def setup_inverse_kinematics(self, urdf_path): """ This function is responsible for doing any setup for inverse kinematics. Inverse Kinematics maps end effector (EEF) poses to joint angles that are necessary to achieve those poses. """ # These indices come from the urdf file we're using self.effector_right = 27 self.effector_left = 45 # Use PyBullet to handle inverse kinematics. # Set up a connection to the PyBullet simulator. p.connect(p.DIRECT) p.resetSimulation() self.ik_robot = p.loadURDF(urdf_path, (0, 0, 0), useFixedBase=1) # Relevant joints we care about. Many of the joints are fixed and don't count, so # we need this second map to use the right ones. self.actual = [13, 14, 15, 16, 17, 19, 20, 31, 32, 33, 34, 35, 37, 38] self.num_joints = p.getNumJoints(self.ik_robot) n = p.getNumJoints(self.ik_robot) self.rest = [] self.lower = [] self.upper = [] self.ranges = [] for i in range(n): info = p.getJointInfo(self.ik_robot, i) # Retrieve lower and upper ranges for each relevant joint if info[3] > -1: self.rest.append(p.getJointState(self.ik_robot, i)[0]) self.lower.append(info[8]) self.upper.append(info[9]) self.ranges.append(info[9] - info[8]) # Simulation will update as fast as it can in real time, instead of waiting for # step commands like in the non-realtime case. p.setRealTimeSimulation(1) def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True): """ Force the internal robot model to match the provided joint angles. Args: joint_positions (list): a list or flat numpy array of joint positions. simulate (bool): If True, actually use physics simulation, else write to physics state directly. sync_last (bool): If False, don't sync the last joint angle. This is useful for directly controlling the roll at the end effector. """ num_joints = len(joint_positions) if not sync_last: num_joints -= 1 for i in range(num_joints): if simulate: p.setJointMotorControl2( self.ik_robot, self.actual[i], p.POSITION_CONTROL, targetVelocity=0, targetPosition=joint_positions[i], force=500, positionGain=0.5, velocityGain=1., ) else: # Note that we use self.actual[i], and not i p.resetJointState(self.ik_robot, self.actual[i], joint_positions[i]) def ik_robot_eef_joint_cartesian_pose(self): """ Returns the current cartesian pose of the last joint of the ik robot with respect to the base frame as a (pos, orn) tuple where orn is a x-y-z-w quaternion. """ out = [] for eff in [self.effector_right, self.effector_left]: eef_pos_in_world = np.array(p.getLinkState(self.ik_robot, eff)[0]) eef_orn_in_world = np.array(p.getLinkState(self.ik_robot, eff)[1]) eef_pose_in_world = T.pose2mat((eef_pos_in_world, eef_orn_in_world)) base_pos_in_world = np.array( p.getBasePositionAndOrientation(self.ik_robot)[0] ) base_orn_in_world = np.array( p.getBasePositionAndOrientation(self.ik_robot)[1] ) base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world)) world_pose_in_base = T.pose_inv(base_pose_in_world) eef_pose_in_base = T.pose_in_A_to_pose_in_B( pose_A=eef_pose_in_world, pose_A_in_B=world_pose_in_base ) out.extend(T.mat2pose(eef_pose_in_base)) return out def inverse_kinematics( self, target_position_right, target_orientation_right, target_position_left, target_orientation_left, rest_poses, ): """ Helper function to do inverse kinematics for a given target position and orientation in the PyBullet world frame. Args: target_position_{right, left}: A tuple, list, or numpy array of size 3 for position. target_orientation_{right, left}: A tuple, list, or numpy array of size 4 for a orientation quaternion. rest_poses: A list of size @num_joints to favor ik solutions close by. Returns: A list of size @num_joints corresponding to the joint angle solution. """ ndof = 48 ik_solution = list( p.calculateInverseKinematics( self.ik_robot, self.effector_right, target_position_right, targetOrientation=target_orientation_right, restPoses=rest_poses[:7], lowerLimits=self.lower, upperLimits=self.upper, jointRanges=self.ranges, jointDamping=[0.7] * ndof, ) ) ik_solution2 = list( p.calculateInverseKinematics( self.ik_robot, self.effector_left, target_position_left, targetOrientation=target_orientation_left, restPoses=rest_poses[7:], lowerLimits=self.lower, upperLimits=self.upper, jointRanges=self.ranges, jointDamping=[0.7] * ndof, ) ) for i in range(8, 15): ik_solution[i] = ik_solution2[i] return ik_solution[1:] def bullet_base_pose_to_world_pose(self, pose_in_base): """ Convert a pose in the base frame to a pose in the world frame. Args: pose_in_base: a (pos, orn) tuple. Returns: pose_in world: a (pos, orn) tuple. """ pose_in_base = T.pose2mat(pose_in_base) base_pos_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[0]) base_orn_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[1]) base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world)) pose_in_world = T.pose_in_A_to_pose_in_B( pose_A=pose_in_base, pose_A_in_B=base_pose_in_world ) return T.mat2pose(pose_in_world) def joint_positions_for_eef_command(self, right, left): """ This function runs inverse kinematics to back out target joint positions from the provided end effector command. Same arguments as @get_control. Returns: A list of size @num_joints corresponding to the target joint angles. """ dpos_right = right["dpos"] dpos_left = left["dpos"] self.target_pos_right = self.ik_robot_target_pos_right + np.array([0, 0, 0.913]) self.target_pos_left = self.ik_robot_target_pos_left + np.array([0, 0, 0.913]) self.ik_robot_target_pos_right += dpos_right self.ik_robot_target_pos_left += dpos_left rotation_right = right["rotation"] rotation_left = left["rotation"] self.ik_robot_target_orn_right = T.mat2quat(rotation_right) self.ik_robot_target_orn_left = T.mat2quat(rotation_left) # convert from target pose in base frame to target pose in bullet world frame world_targets_right = self.bullet_base_pose_to_world_pose( (self.ik_robot_target_pos_right, self.ik_robot_target_orn_right) ) world_targets_left = self.bullet_base_pose_to_world_pose( (self.ik_robot_target_pos_left, self.ik_robot_target_orn_left) ) # Empirically, more iterations aren't needed, and it's faster for _ in range(5): arm_joint_pos = self.inverse_kinematics( world_targets_right[0], world_targets_right[1], world_targets_left[0], world_targets_left[1], rest_poses=self.robot_jpos_getter(), ) self.sync_ik_robot(arm_joint_pos, sync_last=True) return arm_joint_pos def _get_current_error(self, current, set_point): """ Returns an array of differences between the desired joint positions and current joint positions. Useful for PID control. Args: current: the current joint positions. set_point: the joint positions that are desired as a numpy array. Returns: the current error in the joint positions. """ error = current - set_point return error def clip_joint_velocities(self, velocities): """ Clips joint velocities into a valid range. """ for i in range(len(velocities)): if velocities[i] >= 1.0: velocities[i] = 1.0 elif velocities[i] <= -1.0: velocities[i] = -1.0 return velocities
true
b94bd4b1e95cfe55d7be208638b837d9de8f4997
Python
ranra/git_forritun
/git verk 1.py
UTF-8
758
3.625
4
[]
no_license
#dæmi1 ''' tala1=int(input("sláðu inn tölu")) tala2=int(input("sláðu inn aðra tölu")) marg=tala1*tala2 plus=tala1+tala2 print("tölurnar lagðar saman = "+str(plus)+" tölurnar margfaldaðar saman = "+str(marg)) #dæmi 2 fornafn=input("slaðu inn fornafn ") eftirnafn =input("sláðu inn eftirnafn ") print("halló "+fornafn,eftirnafn) ''' #dæmi3 hair=0 lair=0 strax=0 eftir = 0 texti=input("sláðu inn texta") for x in range(len(texti)): if texti[x].isupper(): hair=hair+1 if texti[x].islower(): lair=lair+1 if x != 0 and texti[x-1].isupper(): eftir += 1 print("í þessum texta eru "+str(hair)+" háir stafir og "+str(lair)+"lágstafir og "+str(eftir)+" lágstafir koma strax á eftir hástaf.")
true
344d2777fa57ced773e6f5e0a70c7ad454681e65
Python
sherphys/UdeA
/PythonPlot/2dfigures/lib/functions.py
UTF-8
1,168
3.765625
4
[]
no_license
import sys import math as m import numpy as np #Vamos hacer varias gráficas en una sóla ventana #Y=MX+B #Y=AX^2+BX+C #(X-A)^2+(Y-B)^2=R^2 #((X-X1)/A)^2+((Y-Y1)/B)^2=1 #la sentencia isinstance(a,tipo) es para comprobar si a es de tal tipo, sino hay un problema de ejecución def check_array(x): return isinstance(x,np.ndarray) def check_list(x): return isinstance(x,list) def check_number(x): return (isinstance(x,float) or isinstance(x,int)) def line(x,m,b): if (check_array(x) and check_number(m) and check_number(b)): return m*x+b else: print("Error data!") def parable(x,a,b,c): if (check_array(x) and check_number(a) and check_number(b) and check_number(c)): return a*x**2.0+b*x+c else: print("Error data!") def circle(theta,R,A,B): if (check_array(theta) and check_number(R) and check_number(A) and check_number(B)): x=np.cos(theta)*R+A y=np.sin(theta)*R+B return x,y else: print("Error data!") def elipse(theta,X1,Y1,A,B): if (check_array(theta) and check_number(A) and check_number(B) and check_number(Y1) and check_number(X1)): x=A*np.cos(theta)+X1 y=B*np.sin(theta)+Y1 return x,y else: print("Error data!")
true
c8de989eb9fef1d21eb974db92facafc6c378647
Python
shifelfs/shifel
/60.py
UTF-8
72
3.453125
3
[]
no_license
a=int(input()) sum=0 for i in range(1,a+1): sum=sum+i print(sum)
true
40e0f1ef3fc2e2c1cab82174aba8b68d26b8e7d9
Python
tobyjohansen/Oblig5
/client_test.py
UTF-8
746
3.015625
3
[]
no_license
import socket import pickle class ClientNetwork: def __init__(self): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_host = "127.0.0.1" self.port = 5555 self.addr = (self.server_host, self.port) def connect(self): try: self.client.connect(self.addr) except socket.error as e: print("Connection timed out") def send(self, data): try: self.client.send(data) except socket.error as e: print(e) def get_data(self): data = self.client.recv(4096*4) return data ''' client = ClientNetwork() client.connect() client.send_data() print('received', repr(client.get_data())) '''
true
bef59d1f9d0f3808f3fb99ec4d6053c5ed5c49bc
Python
austinhulak/meetme
/utils/time.py
UTF-8
1,038
3.484375
3
[]
no_license
import datetime days = ['Mon.', 'Tues.', 'Wed.', 'Thurs', 'Fri.', 'Sat.', 'Sun.'] def get_available_times(): now = datetime.datetime.today() day = now.weekday() time_rng = get_time_range(now) available = ['{} {}'.format(days[day], time_rng)] for i in range(2): [next, next_day, next_rng] = get_next_time_range(day, time_rng) day = next_day time_rng = next_rng available.append(next) return available def get_time_range(time): hr = time.hour rng = None if (hr < 13): rng = 'morning' elif (hr < 17): rng = 'afternoon' else: rng = 'evening' return rng def get_next_time_range(day, time_rng): next = None tomorrow = (day + 1) % 7 if (time_rng == 'morning'): next_day = day next_rng = 'afternoon' elif (time_rng == 'afternoon'): next_day = day next_rng = 'evening' else: next_day = tomorrow next_rng = 'morning' next = '{} {}'.format(days[next_day], next_rng) return [next, next_day, next_rng] if (__name__ == '__main__'): avail = get_available_times() for a in avail: print(a)
true
d5cf8a29dfac969d2bcbeea28ff1b55e2478596a
Python
KevinMichelle/Vision_FIME_2015
/package/utilities/structures.py
UTF-8
2,316
4.1875
4
[]
no_license
import sys # Explanation about the 'dict_to_list' function # # We know that the basic element in a dictionary structure is a tuple: the key and their value corresponding to that key. # # The key must be hashable, so it may be a number, a tuple, things like that. If am not in a mistake, the value of can be anything. # # So, suppose I have the following dictionary # # Hello = {} # Hello[1] = 10 # Hello[2] = 7 # Hello[3] = 5 # # If print the dictionary it would be like this # # Hello = {1:10, 2:7, 5:7} # # I like use dictionary to check the frecuency of a certain colecction of items. It seems so natural do this task with dictionary. # But also I find difficult to do certain statistics things with a dictionary. # # So maybe you can try the following process: # "build" your structure as a dictionary because it is easier # convert the dictionary structure to a list. # # I find three situations about this process converting. # 1 - You dont care about the keys in the dictionary, only the values # Example: 10, 7, 5 # 2 - You care only the keys # Example: 1, 2, 3 # 3 - You care both the key and their value and want see how many times a element repeats # Example: 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 # # The 'bool_key' variable is a boolean that defines the flow of how you want convert the dictionary. # If it is true, definitely you want that the keys be in the list. If it is false, then you only will see their values, like in the case 1. # And the 'bool_dictio' variable is another boolean that only affecs the flow of the progam in if the 'bool_key' variable is true. # If it is true then you will see the list like in the case 3. If is is false, then it will be like in the case 2. def dict_to_list(structure, bool_key, bool_dictio): if type(structure) is dict: new_list = [] if bool_key: for element in structure: if bool_dictio: new_list.append(element) else: count = structure[element] for dummy in xrange(count): new_list.append(element) return new_list else: for element in structure: new_list.append(structure[element]) return new_list else: return None def tuple_to_list(structure): if type(structure) is tuple: new_list = [] for element in structure: new_list.append(element) return new_list else: return None
true
df323cec2ffe8ecf141bf3ddde83297042081cdf
Python
TejaswitaW/Advanced_Python_Concept
/RegEx.py
UTF-8
317
3.6875
4
[]
no_license
#use of regular expression import re rgobj=re.compile("Teju")#created reg ex object miter=rgobj.finditer("Hi Teju how are you Teju,Hello Teju")#got iterator count=0 for m in miter: count+=1 print("Pattern found at: ",m.start())#start gives index of found print("Total number of times it is found is: ",count)
true
bb04dd491a782081e039a9541d4d5cefc3847b16
Python
israelburigo/FresaCnc
/Utils.py
UTF-8
907
3.359375
3
[]
no_license
from math import* def Comprimento(x, y, z): return sqrt(x * x + y * y + z * z) def Reparte(x1, x2, y1, y2, z1, z2, dist): dx = x2 - x1 dy = y2 - y1 dz = z2 - z1 comprimento = Comprimento(dx, dy, dz) maxDistance = sqrt(3 * dist * dist) if(comprimento < maxDistance): return [(dx, dy, dz)] fator = comprimento / maxDistance qntPontos = round(fator) fxyz = (dx / fator, dy / fator, dz / fator) ultimoPonto = (x1, x2, z1) novosPontos = [] novosPontos.append(ultimoPonto) i = 1 while i < qntPontos: i+=1 novoPonto = (ultimoPonto[0] + fxyz[0], ultimoPonto[1] + fxyz[1], ultimoPonto[2] + fxyz[2]) novosPontos.append(novoPonto) ultimoPonto = (novoPonto[0], novoPonto[1], novoPonto[2]) return novosPontos;
true
794109b3640418eef09fea4756ea96e16066a879
Python
calumpetergunn/w4d4_book_manager
/console.py
UTF-8
593
2.59375
3
[]
no_license
import pdb from models.book import Book from models.author import Author import repositories.book_repository as book_repository import repositories.author_repository as author_repository book_repository.delete_all() author_repository.delete_all() author1 = Author("JRR Tolkien") author_repository.save(author1) author2 = Author("HG Wells") author_repository.save(author2) author_repository.select_all() book1 = Book("The Invisible Man", 1897, "Fiction", author2) book_repository.save(book1) book2 = Book("The Silmarillion", 1977, "Fantasy", author1) book_repository.save(book2) pdb.set_trace()
true
6233dba9fe12fcd1da930fe940aaf95c33cc6f0a
Python
mayank31398/brain-tumor-detection
/src/ExtractTestData.py
UTF-8
2,694
2.640625
3
[]
no_license
import cv2.cv2 as cv2 import os import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt NEW_SIZE = 240 RANDOM_SEED = 42 def PadImage(im): desired_size = 240 old_size = im.shape[:2] ratio = float(desired_size) / max(old_size) new_size = tuple([int(x * ratio) for x in old_size]) im = cv2.resize(im, (new_size[1], new_size[0])) delta_w = desired_size - new_size[1] delta_h = desired_size - new_size[0] top, bottom = delta_h // 2, delta_h - (delta_h // 2) left, right = delta_w // 2, delta_w - (delta_w // 2) color = [0, 0, 0] new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) return new_im def GetBrain(image): ret, thresh = cv2.threshold(image, 70, 255, cv2.THRESH_BINARY) # plt.subplot(121) # plt.imshow(image) # plt.subplot(122) # plt.imshow(thresh) # plt.show() ret, markers = cv2.connectedComponents(thresh) try: marker_area = [np.sum(markers == m) for m in range(np.max(markers)) if m != 0] largest_component = np.argmax(marker_area) + 1 brain_mask = markers == largest_component plt.imshow(brain_mask) plt.show() brain_out = image.copy() brain_out[brain_mask == False] = 0 return brain_out except: return image def main(): dataset_x = [] dataset_y = [] files = os.listdir(os.path.join("Data", "Test_original", "abnormalsJPG")) for file in files: dataset_y.append(1) file = cv2.imread(os.path.join("Data", "Test_original", "abnormalsJPG", file)) file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY) file = PadImage(file) dataset_x.append(file) files = os.listdir(os.path.join("Data", "Test_original", "normalsJPG")) for file in files: dataset_y.append(0) file = cv2.imread(os.path.join("Data", "Test_original", "normalsJPG", file)) file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY) file = PadImage(file) dataset_x.append(file) dataset_x, dataset_y = shuffle( dataset_x, dataset_y, random_state=RANDOM_SEED) dataset_x = np.array(dataset_x) dataset_y = np.array(dataset_y) # dataset_x = dataset_x.sum(axis = 0) # plt.hist(dataset_x.ravel()) # plt.show() np.save(os.path.join("Data", "Test_x.npy"), dataset_x) np.save(os.path.join("Data", "Test_y.npy"), dataset_y) def MyFunc(): x=np.load("Data/Test_x.npy") for i in range(x.shape[0]): plt.imshow(x[i, ...]) plt.show() if(__name__ == "__main__"): main() # MyFunc()
true
b68c02288b6606c1a8bb75b61930bdcc7194437c
Python
AISelf/RLearning
/stable-baselines-example/monitoring_training.py
UTF-8
2,156
2.609375
3
[]
no_license
""" -*- coding:utf-8 -*- @Author : liaoyu @Contact : doitliao@126.com @File : monitoring_training.py @Time : 2020/1/16 00:22 @Desc : """ import os import gym import matplotlib.pyplot as plt import numpy as np from stable_baselines import DQN from stable_baselines import results_plotter from stable_baselines.bench import Monitor from stable_baselines.results_plotter import load_results, ts2xy best_mean_reward, n_steps = -np.inf, 0 def callback(_locals, _globals): """ Callback called at each step (for DQN an others) or after n steps (see ACER or PPO2) :param _locals: (dict) :param _globals: (dict) """ global n_steps, best_mean_reward # Print stats every 1000 calls if (n_steps + 1) % 1000 == 0: # Evaluate policy training performance x, y = ts2xy(load_results(log_dir), 'timesteps') if len(x) > 0: mean_reward = np.mean(y[-100:]) print(x[-1], 'timesteps') print( "Best mean reward: {:.2f} - Last mean reward per episode: {:.2f}".format(best_mean_reward, mean_reward)) # New best model, you could save the agent here if mean_reward > best_mean_reward: best_mean_reward = mean_reward # Example for saving best model print("Saving new best model") _locals['self'].save(log_dir + 'best_model.pkl') n_steps += 1 return True # Create log dir log_dir = "tmp/" os.makedirs(log_dir, exist_ok=True) # Create and wrap the environment env = gym.make('CartPole-v1') env = Monitor(env, log_dir, allow_early_resets=True) # Add some param noise for exploration # param_noise = AdaptiveParamNoiseSpec(initial_stddev=0.1, desired_action_stddev=0.1) # Because we use parameter noise, we should use a MlpPolicy with layer normalization model = DQN('MlpPolicy', env, learning_rate=1e-3, prioritized_replay=True, param_noise=True, verbose=1) # Train the agent time_steps = 1e5 model.learn(total_timesteps=int(time_steps), callback=callback) results_plotter.plot_results([log_dir], time_steps, results_plotter.X_TIMESTEPS, "DQN CartPole") plt.show()
true
1acc4b13e76b31b92e9df37a7c3f9c68379a624b
Python
dantangfan/hackWithPython
/Layer2/ARPWatcher.py
UTF-8
1,808
2.609375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 """ 代码监听了所有新连接到网络的设备,因此这回记录下所有的IP和MAC对应地址。 这将能检测有哪些设备突然改变了MAC地址 代码有bug************************* """ from scapy.all import sniff, ARP from signal import signal, SIGINT import sys arp_watcher_db_file = "/var/cache/arp-watcher.db" ip_mac = {} # 关闭时保存数据 def sig_int_handler(signum, frame): print "Got SIGINT, Savint ARP database..." try: f = open(arp_watcher_db_file, "w") for (ip, mac) in ip_mac.items(): f.write(ip + " " + mac + "\n") f.close() print "Done." except IOError: print "Cannot write file " + arp_watcher_db_file sys.exc_clear(1) def watch_arp(pkt): # got is-at pkt(ARP response) if pkt[ARP].op == 2: print pkt[ARP].hwsrc + " " + pkt[ARP].psrc # if device is new, remember it if ip_mac.get(pkt[ARP].psrc) == None: print "Found new device " + pkt[ARP].hwsrc + " " + pkt[ARP].psrc ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc # if device is known but has a different IP elif ip_mac.get(pkt[ARP].psrc) and ip_mac(pkt[ARP].psrc) != pkt[ARP].hwsrc: print pkt[ARP].hwsrc + " has got new ip " + pkt[ARP].psrc + " (old " + ip_mac[pkt[ARP].psrc] + " )" ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc signal(SIGINT, sig_int_handler) if len(sys.argv) < 2: print sys.argv[0] + " <iface>" sys.exit(0) try: fh = open(arp_watcher_db_file, "r") except IOError: print "Cannot read file " + arp_watcher_db_file sys.exit(1) for line in fh: line.chomp() (ip, mac) = line.split(' ') ip_mac[ip] = mac sniff(prn=watch_arp, filter="arp", iface=sys.argv[1], store=0)
true
7563b708b396dca428e9d7b4b47677d014cdf1f7
Python
Lmineor/Sword-to-Offer
/bin/50.py
UTF-8
147
3.046875
3
[]
no_license
def Fisrt1(s): for i in range(len(s)): if s[i] not in s[i+1:]: return s[i] s = 'abcdefgheighkldiejdabc' print(Fisrt1(s))
true
cc70572ae33874ab280fe09323a6cdda4fb34140
Python
sho000/Rhombusome
/emblem/Rhomboid.py
UTF-8
2,414
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- import rhinoscriptsyntax as rs import math from System.Drawing import Color import random ######################################################################## #Rhomboid Class ######################################################################## class Rhomboid(): def __init__(self,no,name,angle,rotateAng,movePt,l,lines): self.no=no self.name=name #交差しているlineとlineのナンバー「0-0」 self.angle=angle #ひし形の角度 self.rotateAng=rotateAng #頂点周りの回転角度 self.movePt=movePt #中心からの絶対移動距離 self.l=l #辺の長さ self.lines=lines #Line[] self.pts=[] #ひし形を構成する点 self.midPts=[] #中点 self.ellipsePts=[] #楕円の点、[中心、X軸の点、Y軸の点] self.setPts() def setPts(self): #外周点 pt0=[0,0,0] pt1=[self.l,0,0] pt1=rs.VectorRotate(pt1, self.angle/2.0, [0,0,1]) pt3=[self.l,0,0] pt3=rs.VectorRotate(pt3, -self.angle/2.0, [0,0,1]) pt2=rs.VectorAdd(pt1, pt3) self.pts.append(pt0) self.pts.append(pt1) self.pts.append(pt2) self.pts.append(pt3) #中点 for i in range(len(self.pts)): if(i==len(self.pts)-1): pt=rs.VectorAdd(self.pts[i], self.pts[0]) pt=rs.VectorDivide(pt, 2) else: pt=rs.VectorAdd(self.pts[i], self.pts[i+1]) pt=rs.VectorDivide(pt, 2) self.midPts.append(pt) #楕円 pt0=rs.VectorDivide(self.pts[2],2.0) l0=self.l*math.sin(math.radians(90/2.0)) l1=self.l*math.cos(math.radians(self.angle/2.0)) l2=self.l*math.sin(math.radians(self.angle/2.0)) pt1=rs.VectorScale([self.l/2.0,0,0], l1/l0) pt1=rs.VectorAdd(pt0, pt1) pt2=rs.VectorScale([0,self.l/2.0,0], l2/l0) pt2=rs.VectorAdd(pt0, pt2) self.ellipsePts.append(pt0) self.ellipsePts.append(pt1) self.ellipsePts.append(pt2) def getAbsolutePt(self,pt): pt=rs.VectorRotate(pt, self.rotateAng,[0,0,1]) pt=rs.VectorAdd(pt, self.movePt) return pt
true
93d0e4dd444502c00e6af3589424f192c7ff4e64
Python
HsuYR/track
/track.py
UTF-8
12,153
3.1875
3
[]
no_license
"""A simple bookkeeping module""" # Written in Python 3 import sqlite3 import os import datetime class Book: """A book for bookkeeping""" def __init__(self, database_name): """Open an existing book. Each instance has its own connection to the database. The connection will be shared and used among methods of the instance. """ if os.path.exists(database_name): self.conn = sqlite3.connect(database_name) self.conn.row_factory = sqlite3.Row self.conn.execute('PRAGMA foreign_keys = ON') else: raise FileNotFoundError @classmethod def new(cls, database_name): """Create a new book. Create a new blank book by initializing an empty database. Return an instance of the newly created book. """ if os.path.exists(database_name): raise FileExistsError else: conn = sqlite3.connect(database_name) with conn: c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS accounts ( id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL, type_id INTEGER NOT NULL, description TEXT, hidden INTEGER NOT NULL, FOREIGN KEY (type_id) REFERENCES account_types(id) );''') c.execute('''CREATE TABLE IF NOT EXISTS account_types( id INTEGER PRIMARY KEY, type TEXT UNIQUE NOT NULL );''') c.executemany('''INSERT INTO account_types (type) VALUES (?);''', [('ASSET',), ('LIABILITY',), ('EQUITY',), ('INCOME',), ('EXPENSE',)]) c.execute('''CREATE TABLE IF NOT EXISTS transactions( id INTEGER PRIMARY KEY, date DATE NOT NULL, description TEXT );''') c.execute('''CREATE TABLE IF NOT EXISTS splits( id INTEGER PRIMARY KEY, transaction_id INTEGER NOT NULL, account_id INTEGER NOT NULL, amount REAL NOT NULL, description TEXT, FOREIGN KEY (transaction_id) REFERENCES transactions(id), FOREIGN KEY (account_id) REFERENCES accounts(id) );''') return cls(database_name) # # Account # # account_detail is a dict with the following key: # name -- the name string of the account, # type_id -- the id of the account type, # description -- optional text description of the account, # hidden -- boolean value representing whether account will be hidden. # # Account type falls into one of the basic types: # ASSET -- with type_id 1, # LIABILITY -- with type_id 2, # EQUITY -- with type_id 3, # INCOME -- with type_id 4, or # EXPENSE -- with type_id 5. # def insert_account(self, account_detail): """Insert a new account with the provided account detail.""" name = account_detail['name'] type_id = account_detail['type_id'] if 'description' not in account_detail: description = '' if 'hidden' not in account_detail: hidden = False with self.conn: c = self.conn.cursor() c.execute( 'INSERT INTO accounts (name, type_id, description, hidden) VALUES (?,?,?,?);', (name, type_id, description, hidden) ) def update_account(self, account_id, account_detail): """Update the account detail of the given account id.""" with self.conn: c = self.conn.cursor() for key, value in account_detail.items(): if key in ['name', 'type_id', 'description', 'hidden']: c.execute('UPDATE accounts SET %s=? WHERE id=?;' % key, (value, account_id)) def delete_account(self, account_id, move_to_id = 0): """Delete the specified account. Delete the account with specified account id. If there are not existing transactions related to the account, delete the account directly. If there are transactions related to the account, one can specify another account that substitute the to-be-deleted account using move_to_id argument. If move_to_id is set to 0 (also as default value), all transactions related to the account will be deleted.""" with self.conn: c = self.conn.cursor() c.execute('SELECT COUNT(*) FROM splits WHERE account_id=?', (account_id,)) if c.fetchone()['COUNT(*)']: if move_to_id: c.execute('SELECT * FROM splits') c.execute('UPDATE splits SET account_id=? WHERE account_id=?', (move_to_id, account_id)) else: c.execute('SELECT transaction_id FROM splits WHERE account_id=?', (account_id,)) for row in c.fetchall(): self.delete_transaction(row['transaction_id']) for row in c.fetchall(): print(row['transaction_id'], row[2], row[3], row[4]) c.execute('DELETE FROM accounts WHERE id=?', (account_id,)) def account_detail_by_id(self, account_id): """Return the account detail of the given id. The returned account detail is a python dict. """ with self.conn: c = self.conn.cursor() c.execute('SELECT * FROM accounts WHERE id=?', (account_id,)) cols = ['account_id', 'name', 'type_id', 'description', 'hidden'] account = dict(zip(cols, c.fetchone())) return account def account_type_id(self, account_type): """Return the type id of the account type name.""" with self.conn: c = self.conn.cursor() c.execute('SELECT (id) FROM account_types WHERE type=?', (account_type,)) return c.fetchone()['id'] def account_ids(self): """Generator function of account ids""" with self.conn: c = self.conn.cursor() c.execute('SELECT id FROM accounts') for row in c.fetchall(): yield row['id'] def account_ids_list(self): """Return a list of account id""" return [i for i in self.account_ids()] def account_balance(self, account_id): with self.conn: c = self.conn.cursor() c.execute('SELECT SUM(amount) FROM splits WHERE account_id=?', (account_id,)) return c.fetchone()['SUM(amount)'] # # Transaction # # Each transaction is a dict consists of # date -- a date, which would be default to today, # splits -- list of at least two splits which balance, and # description -- an optional description. # # Each split has # account_id -- the affected account id, # amount -- the amount taking effect, # which is either Dr. or Cr., # represented by positive or negative amount respectively, and # description -- an optional description. def insert_transaction(self, transaction_detail): """Insert a new transaction.""" with self.conn: c = self.conn.cursor() if 'date' not in transaction_detail: transaction_detail['date'] = datetime.date.today() if 'description' not in transaction_detail: transaction_detail['description'] = '' Book.check_split_sum(transaction_detail['splits']) c.execute('INSERT INTO transactions (date, description) VALUES (?, ?)', (transaction_detail['date'], transaction_detail['description']) ) transaction_id = c.lastrowid self.write_splits(transaction_id, transaction_detail['splits']) def update_transaction(self, transaction_id, transaction_detail): """Update the transaction with the specified id. Update the transaction detail and overwrite the splits of the transaction. """ with self.conn: c = self.conn.cursor() for key, value in transaction_detail.items(): if key in ['date', 'description']: c.execute('UPDATE transactions SET %s=? WHERE id=?' % key, (value, transaction_id)) elif key == 'splits': Book.check_split_sum(value) self.write_splits(transaction_id, value) def delete_transaction(self, transaction_id): """Delete the specified transaction.""" with self.conn: c = self.conn.cursor() c.execute('DELETE FROM splits WHERE transaction_id=?', (transaction_id,)) c.execute('DELETE FROM transactions WHERE id=?', (transaction_id,)) def transaction_detail_by_id(self, transaction_id): """Return the transaction detail with the specified id. The transaction detail returned is a python dict. """ with self.conn: c = self.conn.cursor() c.execute('SELECT * FROM transactions WHERE id=?', (transaction_id,)) transaction_detail = {} row = c.fetchone() transaction_detail['date'] = row['date'] transaction_detail['description'] = row['description'] transaction_detail['splits'] = [] c.execute('SELECT * FROM splits WHERE transaction_id=?', (transaction_id,)) for row in c.fetchall(): split = { 'account_id': row['account_id'], 'amount': row['amount'], 'description': row['description'], } transaction_detail['splits'].append(split) return transaction_detail def transaction_ids(self): """Generator function of transaction ids""" with self.conn: c = self.conn.cursor() c.execute('SELECT id FROM transactions') for row in c.fetchall(): yield row['id'] def transaction_ids_list(self): """Return a list of transaction id""" return [i for i in self.transaction_ids()] def transaction_ids_between_date(self, start_date, end_date): """Generator function yielding transaction ids between dates Both start_date and end_date are inclusive. Both start_date and end_date are strings and follow the format "YYYY-MM-DD". """ with self.conn: c = self.conn.cursor() c.execute('SELECT id FROM transactions WHERE date BETWEEN ? AND ?', (start_date, end_date)) for row in c.fetchall(): yield row['id'] @staticmethod def check_split_sum(splits): """Check whether the splits are balanced. The total amount of debit, represented as positive, and credit, represented as negative, for each transaction should be the same and therefore should sums up to zero. """ if sum(split['amount'] for split in splits) != 0: raise ValueError('Total debit and credit amount should balance') def write_splits(self, transaction_id, splits): """Overwrite all existing splits related to the specified transaction.""" with self.conn: c = self.conn.cursor() c.execute('SELECT COUNT(*) FROM splits WHERE transaction_id=?', (transaction_id,)) if c.fetchone()['COUNT(*)']: c.execute('DELETE FROM splits WHERE transaction_id=?', (transaction_id,)) for split in splits: if 'description' not in split: split['description'] = '' c.execute( 'INSERT INTO splits (transaction_id, account_id, amount, description) VALUES (?, ?, ?, ?)', (transaction_id, split['account_id'], split['amount'], split['description']) )
true
c04c2c5e37153795f13a608591821bba21d0ba81
Python
Ravi8288/GitLocalProjects
/tmdb_upcoming2.py
UTF-8
1,134
3.234375
3
[]
no_license
import requests as req import json def tmdb_api_call(requestURL,parameters): response = req.get(url=requestURL,params=parameters) if response.status_code != 200: print(response.json()) exit() data = response.json() return json.dumps(data) def get_upcoming_movies_by_page(api_key,page_number=1): requestURL = "https://api.themoviedb.org/3/movie/upcoming" parameters = {"api_key" : api_key, "page" : page_number } return tmdb_api_call(requestURL,parameters) def main(): api_key = "61fd3cddfd71c0c9755ea27ab9d235c4" upcoming_movie_list = get_upcoming_movies_by_page(api_key,1) data = json.loads(upcoming_movie_list) print(data["results"]) Quality of Task: Good Productivity: More Than Expected Comments: He is working better day by day. Always Eager to Learn New Things. Does In-Depth Research on New Technologies, Did good job on all new technologies, Little Guidance can help him achieve all goal Need to Improve Presentation Skills more with all learned data for Thorough Knowledge Sharing on Technologies/Product Showcases.
true
df02e3fa3b58057e941ff698fe309e906453bc1a
Python
robotframework/robotframework
/atest/testdata/standard_libraries/remote/variables.py
UTF-8
483
3.171875
3
[ "Apache-2.0", "CC-BY-3.0" ]
permissive
from collections.abc import Mapping class MyObject: def __init__(self, name='<MyObject>'): self.name = name def __str__(self): return self.name class MyMapping(Mapping): def __init__(self, data=None, **extra): self.data = data or {} self.data.update(extra) def __getitem__(self, item): return self.data[item] def __len__(self): return len(self.data) def __iter__(self): return iter(self.data)
true
61cc9fec1860739d0b3bb8d2778a0da8aa838bf0
Python
FancccyRay/Cat-images-recognization-using-logistic-regression
/AI_assignment2_2
UTF-8
7,314
3.359375
3
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Aug 17 16:27:31 2018 @author: fancy """ """ Bulid the general architecture of a learning algorithm--a simple neural: -initializing paramaters -calculating the cost function and gradient -using an optimization algorithm (gradient descent) """ """ what should be remembered 1. Preprocessing the dataset is important 2. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model() 3. Tuning the learning rate can make a big difference to the algorithm. """ import numpy as np import matplotlib.pyplot as plt import h5py import scipy import PIL from PIL import Image from scipy import ndimage from lr_utils import load_dataset ###(1)load data train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() #print train_set_x_orig.shape,train_set_y.shape,test_set_x_orig.shape,test_set_y.shape ###plot the images in train_set, do it if you like, for checking #index = 1 #plt.imshow(train_set_x_orig[index]) ##np.squeeze: eliminate the 1-D item #print "y = " + str(train_set_y[:,index]) + "\n" + " it's a " \ # + classes[np.squeeze(train_set_y[:,index])] ###(2)preprocessing ###reshape images[x,x,3] in a numpy-array[x*x*3,1] ###each column represents a flattened image m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] train_set_x_flatten = train_set_x_orig.reshape(m_train,-1).T test_set_x_flatten = test_set_x_orig.reshape(m_test,-1).T ##center and standardize the data train_set_x = train_set_x_flatten / 255. test_set_x = test_set_x_flatten / 255. #print train_set_x,train_set_x.shape ###(3)define functions ##build a logistic regression ##definition of sigmoid function def sigmoid_function(z): s = 1 / (1 + np.exp(-z)) return s ##initializing parameters w&b, create a vector of zeros of shape((dim,1),type = float64) def initiolize_with_zeros(dim): w = np.zeros((dim,1)) b = 0 return w, b ##propagation def propagation(w, b, x ,y): ##forward propagation y_hat = sigmoid_function(np.dot(w.T,x) + b) y_diff = y_hat - y L = -(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat)) ##Loss function cost = np.sum(L) / x.shape[1] ##backward propagation dw = np.dot(x, y_diff.T) / x.shape[1] db = np.sum(y_diff) / x.shape[1] assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) ##save as dictionary grads = {"dw" : dw, "db" : db} return grads, cost ##optimization, learn w&b by minimizing the cost ##update parameters using gradient descent def optimize(w, b, x, y, num_iterations, learning_rate): costs = [] best_cost = np.array([1.]) best_params = {} decay = 0.999 ##decay of learning_rate for i in range(num_iterations): grads, cost = propagation(w, b ,x ,y) dw = grads["dw"] db = grads["db"] ##update params w = w - learning_rate * dw b = b - learning_rate * db learning_rate *= decay ##record cost every 100 iteration if i % 100 == 0: costs.append(cost) # print "cost after iteration %d: %+f" %(i, cost) # print "learning_rate:%f"%learning_rate ##when the data_set is big enough ##save the params at the smallest cost if cost < best_cost: best_cost = cost best_params["w"] = w best_params["b"] = b print "best cost : %f"%best_cost params = {"w" : w, "b" : b, "learning_rate" : learning_rate, "best_w" : best_params["w"], \ "best_b" : best_params["b"]} grads = {"dw" : dw , "db" : db} return params, grads, costs ##prediction ##step1:calculate y_hat ##step2:1(activation>0.5),0(activation<=0.5) def predict(w, b, x): y_hat = sigmoid_function(np.dot(w.T,x) + b) assert(y_hat.shape[1] == x.shape[1]) y_pred = np.zeros((1,y_hat.shape[1])) for i in range(y_hat.shape[1]): if y_hat[:,i] <= 0.5: y_pred[:,i] = 0 else: y_pred[:,i] = 1 return y_pred ##(4)merge all functions into a model def model(x_train, y_train, x_test, y_test, num_iterations = 2000, \ learning_rate = 0.05): features_num = x_train.shape[0] w, b = initiolize_with_zeros(features_num) params, grads, costs = optimize(w, b, x_train, y_train, \ num_iterations , learning_rate) w, b, learning_rate = params["w"],params["b"],params["learning_rate"] y_pred_train = predict(w, b, x_train) y_pred_test = predict(w, b, x_test) accuracy_train = 100 - np.mean(np.abs(y_pred_train - y_train) * 100) accuracy_test = 100 - np.mean(np.abs(y_pred_test - y_test) * 100) ##predict y_hat with best_params best_w, best_b = params["best_w"], params["best_b"] best_y_pred_train = predict(best_w, best_b, x_train) best_y_pred_test = predict(best_w, best_b, x_test) best_accuracy_train = 100 - np.mean(np.abs(best_y_pred_train - y_train) * 100) best_accuracy_test = 100 - np.mean(np.abs(best_y_pred_test - y_test) * 100) ##comparison between last w&b and best w&b print "learning_rate : %f"%learning_rate print "train accuracy -- %f%% : %f%%"%(accuracy_train,best_accuracy_train) print "test accuracy -- %f%% : %f%%"%(accuracy_test, best_accuracy_test) result = {"costs" : costs, "y_pred_test" : y_pred_test, \ "y_pred_train" : y_pred_train, "w" : w, "b" : b, \ "learning_rate" : learning_rate, "num_iterations" : num_iterations} return result ##for (6)、(7) training_result = model(train_set_x,train_set_y,test_set_x,test_set_y) ###(5)chose different learning_rate and check which is better ##choices of certain learning rate #learning_rate = [0.01 ,0.001, 0.0001] #models = {} ##dictionary #for i in learning_rate: # models[str(i)] = model(train_set_x,train_set_y,test_set_x,test_set_y,learning_rate=i) #for i in learning_rate: # ###show result # plt.plot(models[str(i)]["costs"],label = str(models[str(i)]["learning_rate"])) # plt.ylabel('cost') # plt.xlabel('iterations/100') # legend = plt.legend(loc = 'upper center', shadow = True) # frame = legend.get_frame().set_facecolor('red') # plt.show() ##(6)check a single image plt.imshow(test_set_x[:,1].reshape(64,64,3)) print ("y = " + str(test_set_y[0,1]) + ", you predicted that it is a " + classes[int(training_result["y_pred_test"][0,1])].decode("utf-8") + " picture") costs = np.squeeze(training_result["costs"]) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations/100') plt.title("Learning rate = " + str(training_result["learning_rate"])) #plt.show() ###(7)sohw a single image besides training/testing data my_image = "images/cat_in_iran.jpg" image = np.array(ndimage.imread(my_image,flatten = False)) my_image = scipy.misc.imresize(image,(64,64)).reshape((1,64*64*3)).T my_pred_image = predict(training_result["w"],training_result["b"],my_image) plt.imshow(image) print "y = " + str(np.squeeze(my_pred_image)) + ",your algorithm predicts a " \ + classes[int(np.squeeze(my_pred_image)),].decode("utf-8")
true
a46a053a35b31b4d06d373f83877644ff8e51066
Python
GiacomoCrevani/CESP_MSc_thesis
/mintohours_norm.py
UTF-8
748
2.765625
3
[ "CC0-1.0" ]
permissive
# -*- coding: utf-8 -*- """ Created on Fri Sep 10 10:18:55 2021 @author: giaco """ #code useful to shift from min resolution to hourly, such that the csv load demand can be fed as input to MicrogridsPy #yearly profile is required import numpy as np import pandas as pd #minute and hour indexes minute_index = pd.date_range("2021-01-01 00:00:00", "2021-12-31 23:59:00", freq="1min") hour_index = np.linspace(1,8760,8760,dtype=int) #from load to loadH load=pd.read_csv('#INSERT THE PATH TO THE .csv FILE FROM RAMP OUTPUT#',usecols=['0']) load.index = minute_index loadH = load.resample('H').mean() loadH.index = hour_index #export in .csv loadH.to_csv('#XXX.csv TO NAME THE FILE OF OUTPUT IN HOURLY RESOLUTION#')
true
c9878aed30f15b25ad6b68afb4c994786243d0c4
Python
facunava92/VxC_Grupo6
/Practico_2/umbralizado.py
UTF-8
1,316
3.84375
4
[]
no_license
#!/usr/bin/python #Escribir un programa en python que lea una imagen y realice un umbralizado binario,guardando el resultado en otra imagen. # NOTA: No usar ninguna función de las OpenCV, excepto para leer y guardar la imagen #la idea es generar una mascara , donde cada valor va represetnar la intecidad de las imagenes , todo lo que superer ese umbral se represente en blanco y todo lo que represente en negro import cv2 img = cv2.imread ('hoja.png', cv2.IMREAD_GRAYSCALE) #leer en escala de grises los pixeles q no sean blanco y negro van a estar entre 0 y 255 #image[0, 0] el primero indica y o row(fila) y el segundo x o column(columna). #image[0, 0, 0] igual, agrego el canal de color BGR respectivamente. #image[0,0] upper-left corner umbral = int(input('Introduzca el valor del umbral entre 0-255: ')) x , y= img.shape #dimencione de la imagen #utilizamos 2 for anidados , donde voy a recorrer las filas for row in range(x): # trae todas las filas for col in range(y): # trae cada uno de los elementos de esa fila if (img[row, col] <= umbral): #si el elemento de la iamgen es menor al umbral img[row, col] = 0 cv2.imwrite('resultado.png', img) cv2.imshow('Imagen Umbralizada', img) cv2.waitKey(0) #espera que el usuario preciono una tecla cv2.destroyAllWindows()
true
8438d978b712604bf3f67a5a41f1da668f92e0cf
Python
liketheflower/cifar10
/big_data_assignment3_three_layers.py
UTF-8
2,296
2.859375
3
[]
no_license
# coding: utf-8 #!/usr/bin/env python2 """ three layer neural network is used here Created on April 2017 @author: Jimmy Shen """ #import six.moves.cPickle as pickle import cPickle from sklearn.model_selection import train_test_split import numpy from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils import keras f = open('/Users/jimmy/Dropbox/python_code/big_data/cifar.pkl', 'rb') dict = cPickle.load(f) f.close() print("type of dict",type(dict)) features = dict['data'] print("type of features",type(features)) print("shape of features",features.shape) lbl = dict['labels'] print("lbl[0]",lbl[0]) print("type of lbl",type(lbl)) print("shape of lbl",lbl.shape) # added by jimmy shen on Dec 11 2016 #import tensorflow as tf #import random seed = 7 numpy.random.seed(seed) X_train, X_test, y_train, y_test = train_test_split(features, lbl, test_size=0.1, random_state=seed) num_pixels = X_train.shape[1] #y_train = keras.utils.to_categorical(y_train, num_classes=10) #y_test = keras.utils.to_categorical(y_test, num_classes=10) # normalize inputs from 0-255 to 0-1 X_train = X_train / 255.0 X_test = X_test / 255.0 # one hot encode outputs #y_train = np_utils.to_categorical(y_train) #y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # define baseline model def baseline_model(): # create model model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) model.add(Dropout(0.2)) model.add(Dense(128, kernel_initializer='normal', activation='relu')) model.add(Dropout(0.2)) model.add(Dense(64, kernel_initializer='normal', activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # build the model model = baseline_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=25, batch_size=200, verbose=2) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Three layer Neural Network Accuracy: %.2f%%" % (scores[1]*100))
true
916b3772ed774d9b968d9d10afebf260efb21cec
Python
Yang-chen205/badou-Turing
/47+洪杰+上海/第五周/层次聚类.py
UTF-8
914
3.140625
3
[]
no_license
###cluster.py #导入相应的包 from scipy.cluster.hierarchy import dendrogram, linkage,fcluster from matplotlib import pyplot as plt ''' linkage(y, method=’single’, metric=’euclidean’) 共包含3个参数: 1. y是距离矩阵,可以是1维压缩向量(距离向量),也可以是2维观测向量(坐标矩阵)。 若y是1维压缩向量,则y必须是n个初始观测值的组合,n是坐标矩阵中成对的观测值。 2. method是指计算类间距离的方法。 ''' ''' fcluster(Z, t, criterion=’inconsistent’, depth=2, R=None, monocrit=None) 1.第一个参数Z是linkage得到的矩阵,记录了层次聚类的层次信息; 2.t是一个聚类的阈值-“The threshold to apply when forming flat clusters”。 ''' X = [[1,2],[3,2],[4,4],[1,2],[1,3]] Z = linkage(X, 'ward') f = fcluster(Z,4,'distance') fig = plt.figure(figsize=(5, 3)) dn = dendrogram(Z) print(Z) plt.show()
true
620b182a9aa78a391b4039ae0373ec55e72865ad
Python
cristian372/ejercicio4
/ocho.py
UTF-8
146
3.15625
3
[]
no_license
cadena = "holasmundos1234" c = 0 C = 0 for h in cadena: if h in '0123456789': c += 1 else: C += 1 print "Letras : ", C print "Numeros : ", c
true
6f274932f19fd13550162ee00a39baac0031b52b
Python
Shorstko/mai_python
/03 Commandline/main.py
UTF-8
8,865
3.203125
3
[]
no_license
import sys import argparse from datetime import datetime import os # ЛОГИРОВАНИЕ # функция create_log создает пустой текстовый файл. Режимы: # w - открыть на запись (сотрет все, что было), # a - открыть на дозапись (пишет в конец существующего файла) # r - открыть на чтение. Если не указать флаг, откроет именно в этом режиме: with open(log_filename) as f: # encoding='utf-8' означает, что файл создается в кодировке UTF-8 def create_log(log_filename): with open(log_filename, 'w', encoding='utf-8') as f: pass # функция write_log записывает в файл строку текстовое сообщение. # Параметры: text - текстовое сообщение, log_filename - имя файла лога (с полным путем) def write_log(text, log_filename): if text is not None: with open(log_filename, 'a', encoding='utf-8') as f: f.write("{} {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), text)) f.write("\n") # матчасть по тому, как работать с датой и временем в python: https://python-scripts.com/datetime-time-python # все ключи форматирования (Y, m, d и т.д.) в таблице по ссылке: https://pythonworld.ru/moduli/modul-time.html # ВЫЗОВ СКРИПТА ИЗ КОМАНДНОЙ СТРОКИ С ПАРАМЕТРАМИ # 1) Матчасть по параметрам командной строки # 1.1) Запуск скрипта # Первым пишем название программы, которую мы запускаем. У нас это будет python.exe или просто python. Это еще не параметр # Скрипт лучше запускать из той директории, в которой он находится. # Если python.exe определен в системных переменных, можно писать просто python. # Если нет, придется писать полный путь, например: c:\PythonVenv\vePython36\Scripts\python.exe # 1.2) Задание параметров # Первый параметр - имя самого скрипта: *.py. Далее идут все остальные параметры: ключи и их значения, т.е. "настройки" нашего скрипта # Параметры оформляются следующим образом: # а) сокращенное название ключа вызываем с одним тире: -d (также бывает /d); # б) полное название ключа вызываем с двумя тире: --digits, но может встречаться и -digits # в) после названия ключа идет его значение (если оно есть) через пробел: --digits 4, --logfile d:\tracelog.log # либо может быть сложнее, например, когда присваивается определенное значение (==) # примеры из реальной жизни: # python -m pip install –upgrade pip # python -m pip install pip==18.1 # 2) Функция main # Для того, чтобы запущенный из командной строки скрипт работал, в нем должна быть функция main (аналогично С++ и другим языкам) # Реализация в python: # 2.1) написать в коде: ''' if __name__ == "__main__": main() ''' # 2.2) определить функцию main: ''' def main(): тело функции ''' # передача параметров в функцию не требуется, т.к. они уже хранятся в глобальной переменной sys.argv # 3) Реализация параметров командной строки для скриптов python: # 3.1) Через простой список параметров sys.argv. Тип: list. Разбор: полностью вручную. # это аналог передачи списка неименованных параметров неизвестной длины: *args # Примерная стратегия: находим элемент списка с известным нам названием и берем следующий за ним элемент-значение ''' args = sys.argv[1:] if "--digits" in args: position = args.index("--digits") + 1 arg = args[position] ''' # 3.2) Через модуль argparse, который сделает все это за нас. # это аналог передачи списка именованных параметров неизвестной длины: **kwargs # справка по argparse: https://docs.python.org/2/library/argparse.html # как превратить список именованных параметров в словарь: http://qaru.site/questions/53327/what-is-the-right-way-to-treat-python-argparsenamespace-as-a-dictionary vars(args) ''' def createParser(): parser = argparse.ArgumentParser() parser.add_argument(имя_параметра, тип_параметра, значение_по_умолчанию, описание_параметра) return parser def main(): parser = createParser() args = parser.parse_args(sys.argv[1:]) args.digits - значение параметра "--digits" vars(args) - получить все пары "параметр-значение" в виде словаря. точно так же, как для **kwargs ''' # Важно! В любом из вариантов необходимо исключить первый по счету параметр (имя скрипта): sys.argv[1:] # создаем парсер, заводим все нужные нам параметры # плюсы: ключ -h,--help заводить не нужно, он заведется по умолчанию и при неправильном вводе пользователя будет работать самостоятельно, как при запуске любой утилиты Windows или Linux def createParser(): parser = argparse.ArgumentParser(description="mai_commandline.py [--digits] [--fullsign] [--partialsign] [--logfile]") parser.add_argument("--digits", type=int, default=4, help = u"Количество цифр в загаданном числе. Пример: --digits 5. По умолчанию 4 цифры") parser.add_argument("--fullsign", default="B", type=str, help = u"Каким символом помечать совпадение по значению и месту. Пример: --fullsign F. По умолчанию B") parser.add_argument("--partialsign", default="K", type=str, help = u"Каким символом помечать совпадение по месту. Пример: --partialsign P. По умолчанию K") parser.add_argument("--logfile", default="", help = u"Записывать историю ходов в файл (имя файла). Пример: --logfile c:\guessthenumber.log") return parser # переменная, в которую сохраним имя файла лога logfile_name = "" def main(): # создаем объект парсера командной строки parser = createParser() # получаем список уже разобранных аргументов (за исключением имени скрипта) args = parser.parse_args(sys.argv[1:]) print(type(args)) # получаем значение ключа "--digits" - из скольких цифр генерить число в игре. остальные параметры обработаете сами if args.digits is not None: print(f"Количество цифр, заданное пользователем: {args.digits}") digits = args.digits # создаем файл лога if os.path.exists(args.logfile): logfile_name = args.logfile create_log(logfile_name) # как превратить сисок аргументов в словарь: args_dict = vars(args) print(f"Аргументы: {args_dict}, тип аргументов: {type(args_dict)}") if __name__ == "__main__": # вот так можно посмотреть аргументы командной строки: print(f"Системные аргументы: {sys.argv}, тип: {type(sys.argv)}") main()
true
2a28b98860fc170c06ab02e6f26de48f86e061c5
Python
henryji96/LeetCode-Solutions
/Medium/103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.py
UTF-8
1,253
3.4375
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ q, ans = [], [] if root: q.append(root) ans.append([root.val]) else: return ans nextLayer = [] nextLayerVal = [] temp = 1 zigzag = 1 while q: node = q.pop(0) temp -= 1 if node.left: nextLayer.append(node.left) nextLayerVal.append(node.left.val) if node.right: nextLayer.append(node.right) nextLayerVal.append(node.right.val) if temp == 0: if zigzag == 0: ans.append(nextLayerVal) zigzag = 1 elif zigzag == 1: ans.append(nextLayerVal[::-1]) zigzag = 0 temp = len(nextLayer) q += nextLayer nextLayer = [] nextLayerVal = [] return ans[:-1]
true
346acb9d223f0a18da6105e9846ddbf4f970a15e
Python
andreplacet/reiforcement-python-tasks-2
/exe10.py
UTF-8
295
3.984375
4
[]
no_license
# Exercicio 10 horario = str(input('Qual periodo voce estuda?\n[V] - Vespertino\n[O] - Diurno\n[N] - Nohorario\n --> ')).upper() if horario == 'V': print("Boa Tarde") elif horario == 'D': print("Bom dia") elif horario == 'N': print("Boav Noite") else: print("Entrada invalida")
true
155953e3f56b4c7cd643ab814d8377634547a4a6
Python
tioguerra/robot2d
/robot2d/robot2d.py
UTF-8
46,154
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Copyright 2019 Rodrigo da Silva Guerra Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import pygame from pygame.locals import * from Box2D.b2 import * import numpy as np from .params import * from .utils import * import pydmps import pydmps.dmp_discrete # Here the code that defines the robot simulation class class Robot2D: """ This class defines a 2D robot simulation. To use it you just need to instantiate an object and call the step() method, in a loop. The step() method returns a boolean True while the simulation is running. If the user closes the window, then the step method returns False. This can be used to know when the simulation has finished. Example ------- r = Robot2D while r.step(): pass """ def __init__(self): """ This constructor takes no parameters. Just initializes data structures related to GUI and physics simulation. """ # PyGame window setup self.screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('Simple 2D Robot Simulator') # PyGame Clock self.clock = pygame.time.Clock() # Box2D World self.world = world(gravity=(0,-10), doSleep=True) # Box2D ground (static body) self.ground_body = self.world.CreateStaticBody( position=(0, 1), shapes=polygonShape(box=(3*CENTER[0],5)), ) # A flag to tell if the simulation is still running self.running = True # This will hold the color mapping self.colors = {} self.colors[self.ground_body] = COLORS['GROUND'] # This list holds references to all simulation bodies self.bodies = [self.ground_body] self.balls = [] # This list will hold all joints self.joints = [] # Create the robot self._createRobot() # Set torque self.isTorqueEnabled = False # Setting up GUI mouse isDragging vars and flags self.pos = 0,0 # used for isDragging and isDrawing mouse coordinates self.isDragging = False self.isDrawing = False self.gripper = False # Set also some dynamic interaction related vars and flags self.isPathFollowing = False self.path_counter = 0.0 self.draggedBodies = {} self.use_weld_grasp = USE_WELD_GRASP # Flag for joint based grasping # Some lists to hold things to be drawn on the screen self.dots = [] self.lines = [] self.path = [] # DMP related variables self.dmps = [] # this list will store dmp objects self.dmp_training_paths = [[]] # this will store the paths self.dmp_startendpoints = [] self.draggingWaypoint = -1 # This will register if dragging a DMP # waypoint def _createRobot(self): ''' This method creates the robot itself, creating the bodies, joints, and geometries (fixtures) using Box2D. The method is supposed to be called from the constructor only. ''' # Create the base self.robot_base0_body = self.world.CreateStaticBody(position=(ROBOTY,\ 3.8)) self.robot_base0_body.CreatePolygonFixture(box=(4,3)) self.robot_base1_body = self.world.CreateStaticBody( \ position=(ROBOTY,6+BASE_LENGTH)) self.robot_base1_body.CreatePolygonFixture(box=(ROBOT_WIDTH,LINK0_LENGTH)) # Create the first link self.robot_link0_body = self.world.CreateDynamicBody( position=(ROBOTY, \ 6+BASE_LENGTH+2*LINK0_LENGTH)) self.robot_link0_body.CreatePolygonFixture(box=(ROBOT_WIDTH,LINK0_LENGTH), \ density=2, friction=0.2) # Create the second link self.robot_link1_body = self.world.CreateDynamicBody( \ position=(ROBOTY,\ 6+BASE_LENGTH \ +3*LINK0_LENGTH+LINK1_LENGTH)) self.robot_link1_body.CreatePolygonFixture(box=(ROBOT_WIDTH,LINK1_LENGTH), \ density=0.5, friction=0.2) # Create the third link (wrist) self.robot_link2_body = self.world.CreateDynamicBody( \ position=(ROBOTY,\ 6+BASE_LENGTH \ +3*LINK0_LENGTH \ +2*LINK1_LENGTH+LINK2_LENGTH)) self.robot_link2_body.CreatePolygonFixture(box=(ROBOT_WIDTH,LINK2_LENGTH), \ density=0.125, friction=0.2) # This fourth link is just a bar-like shape to simulate # the gripper attachment. This body will be welded to the # third link. self.robot_link3_body = self.world.CreateDynamicBody( \ position=(ROBOTY,\ 6+BASE_LENGTH \ +3*LINK0_LENGTH \ +2*LINK1_LENGTH \ +2*LINK2_LENGTH+LINK3_LENGTH)) self.robot_link3_body.CreatePolygonFixture(box=(LINK3_WIDTH,LINK3_LENGTH), \ density=0.01, friction=0.2) # This is the left finger (if you look gripper facing downwards) self.robot_link4_body = self.world.CreateDynamicBody( \ position=(ROBOTY-FINGER_WIDTH/2.0,\ 6+BASE_LENGTH \ +3*LINK0_LENGTH \ +2*LINK1_LENGTH \ +2*LINK2_LENGTH \ +2*LINK3_LENGTH \ +FINGER_LENGTH)) self.robot_link4_body.CreatePolygonFixture(box=(FINGER_WIDTH,FINGER_LENGTH), \ density=0.01, friction=100.0) # This is the right finger (if you look gripper facing downwards) self.robot_link5_body = self.world.CreateDynamicBody( \ position=(ROBOTY+FINGER_WIDTH/2.0,\ 6+BASE_LENGTH \ +3*LINK0_LENGTH \ +2*LINK1_LENGTH \ +2*LINK2_LENGTH \ +2*LINK3_LENGTH \ +FINGER_LENGTH)) self.robot_link5_body.CreatePolygonFixture(box=(FINGER_WIDTH,FINGER_LENGTH), \ density=0.01, friction=100.0) # This is the first actuated joint self.j0 = self.world.CreateRevoluteJoint(bodyA=self.robot_base1_body, bodyB=self.robot_link0_body, anchor=(ROBOTY,6+BASE_LENGTH+LINK0_LENGTH), collideConnected = False, maxMotorTorque=MAX_JOINT_TORQUE) # This is the second actuated joint self.j1 = self.world.CreateRevoluteJoint(bodyA=self.robot_link0_body, bodyB=self.robot_link1_body, anchor=(ROBOTY, 6+BASE_LENGTH+3*LINK0_LENGTH), collideConnected = False, maxMotorTorque=MAX_JOINT_TORQUE) # This is the third actuated joint (wrist). It may seem like the # wrist is just dangling by gravity, but it is actually being # actuated. self.j2 = self.world.CreateRevoluteJoint(bodyA=self.robot_link1_body, bodyB=self.robot_link2_body, anchor=(ROBOTY, 6+BASE_LENGTH+3*LINK0_LENGTH+2*LINK1_LENGTH), collideConnected = False, maxMotorTorque=MAX_JOINT_TORQUE) # This is a welding joint (not really a "joint", because # these bodies are not supposed to move relative to each # other) self.j3 = self.world.CreateWeldJoint(bodyA=self.robot_link2_body,\ bodyB=self.robot_link3_body,\ anchor=(ROBOTY,\ 6+BASE_LENGTH\ +3*LINK0_LENGTH\ +2*LINK1_LENGTH\ +2*LINK2_LENGTH), collideConnected = False) # We define this propertie for later reference self.gripperMax = LINK3_WIDTH-1.5*FINGER_WIDTH # This is the left finger prismatic (linear translation) joint self.j4 = self.world.CreatePrismaticJoint(bodyA=self.robot_link3_body,\ bodyB=self.robot_link4_body,\ anchor=(ROBOTY,\ 6+BASE_LENGTH\ +3*LINK0_LENGTH\ +2*LINK1_LENGTH\ +2*LINK2_LENGTH\ +2*LINK3_LENGTH), axis=(1,0), lowerTranslation=-self.gripperMax, upperTranslation=0.0, enableLimit = True, collideConnected = False, maxMotorForce=MAX_GRIPPER_FORCE) # This is the right finger prismatic (linear translation) joint self.j5 = self.world.CreatePrismaticJoint(bodyA=self.robot_link3_body, bodyB=self.robot_link5_body, anchor=(ROBOTY, 6+BASE_LENGTH\ +3*LINK0_LENGTH\ +2*LINK1_LENGTH\ +2*LINK2_LENGTH\ +2*LINK3_LENGTH), axis=(1,0), lowerTranslation=0.0, upperTranslation=LINK3_WIDTH\ -1.5*FINGER_WIDTH, enableLimit = True, collideConnected = False, maxMotorForce=MAX_GRIPPER_FORCE) # Create a gear joint to make the fingers move together # This means that one finger will always move with the other self.j6 = self.world.CreateGearJoint(bodyA=self.robot_link4_body, bodyB=self.robot_link5_body, joint1=self.j4, joint2=self.j5, ratio = 1.0) # This is for grasping (placeholder) self.j7 = None # Append the bodies to our queue for isDrawing later self.robot_bodies = [] self.robot_bodies.append(self.robot_base0_body) self.robot_bodies.append(self.robot_base1_body) self.robot_bodies.append(self.robot_link0_body) self.robot_bodies.append(self.robot_link1_body) self.robot_bodies.append(self.robot_link2_body) self.robot_bodies.append(self.robot_link3_body) self.robot_bodies.append(self.robot_link4_body) self.robot_bodies.append(self.robot_link5_body) self.bodies = self.bodies + self.robot_bodies # Append the revolute joints to our joints list for PID # control and for isDrawing later self.joints.append(self.j0) self.joints.append(self.j1) self.joints.append(self.j2) self.joints.append(self.j4) # Define the color of the robot parts, using the global # dictionary defined on the header self.colors[self.robot_base0_body] = COLORS['ROBOT'] self.colors[self.robot_base1_body] = COLORS['ROBOT'] self.colors[self.robot_link0_body] = COLORS['ROBOT'] self.colors[self.robot_link1_body] = COLORS['ROBOT'] self.colors[self.robot_link2_body] = COLORS['ROBOT'] self.colors[self.robot_link3_body] = COLORS['GRIPPER'] self.colors[self.robot_link4_body] = COLORS['GRIPPER'] self.colors[self.robot_link5_body] = COLORS['GRIPPER'] # Starts with disabled torque (this also initialize internal variables # for the PID control) self.disableTorque() def _jointPID(self): ''' Here we implement a simple PID controller to control each joint of the robot using the PID gains that were defined using the global variables on the header. This PID control controls the velocity of the joints, which in turn are torque/force actuated in the Box2D framework. This is NOT setting velocities directly. ''' acc_angle = 0 for i,joint in enumerate(self.joints): if i<=2: # revolute joints error = self.target[i] - joint.angle else: # prismatic joints error = self.target[i] - joint.translation # Keep the error within -np.pi and np.pi if error > np.pi: error = error - 2*np.pi if error < -np.pi: error = error + 2*np.pi # Compute the derivative error if self.error_old[i] is not None: derror = error - self.error_old[i] # We add a moving average to smooth jitter self.derror = 0.8 * self.derror + 0.2*derror else: # If this is the first call, just zero self.derror = 0.0 derror = 0.0 # Integral is approximated by a sum self.error_sum[i] = self.error_sum[i] + error # This sends the speed command to the joint, # for the Box2D simulation to compute the torques joint.motorSpeed = (KPID[i][0]*error\ + KPID[i][1]*self.error_sum[i]\ + KPID[i][2]*self.derror) # Saves the error for computing the derivative # next call self.error_old[i] = error def getLastError(self): ''' This method is here to give the joint errors (differences between target angle/pos and current angle/pos for each joint). These values are computed in the _jointPID method. ''' return self.error_old def getMotorCommands(self): ''' Return the motor speeds ''' return [joint.motorSpeed for joint in self.joints] def enableTorque(self): ''' Enables the torque on the joints ''' self.isTorqueEnabled = True for joint in self.joints: joint.motorEnabled = True def disableTorque(self): ''' Disables the torque on the joints ''' # When disabling torque we also reset # the PID variables, just in case. self.derror = 0.0 self.target = [0.0] * len(self.joints) self.error_old = [None] * len(self.joints) self.error_sum = [0.0] * len(self.joints) # From here, torque off self.isTorqueEnabled = False for joint in self.joints: joint.motorEnabled = False def setJointTarget(self, target): [j0, j1, j2, j4, j5] = target self.target = target def getFK(self): ''' This method returns the current position of the gripper in world 2D coordinates ''' x0, y0 = (ROBOTY,\ 6+BASE_LENGTH+LINK0_LENGTH) # These are the link lengths a1 = 2*LINK0_LENGTH a2 = 2*LINK1_LENGTH a3 = 2*LINK2_LENGTH+2*LINK3_LENGTH+2*FINGER_LENGTH x = a1*np.cos(self.j0.angle + np.pi/2.0) \ + a2*np.cos(self.j0.angle + np.pi/2.0 + self.j1.angle) \ + a3*np.cos(self.j0.angle + np.pi/2.0 + self.j1.angle + self.j2.angle) y = a1*np.sin(self.j0.angle + np.pi/2.0) \ + a2*np.sin(self.j0.angle + np.pi/2.0 + self.j1.angle) \ + a3*np.sin(self.j0.angle + np.pi/2.0 + self.j1.angle + self.j2.angle) # Here is offset the joint coordinates x = x + x0 y = y + y0 return x,y def setIKTarget(self, target): ''' This implements the closed-form solution of the inverse kinematics for the 2DOF arm. Parameters ---------- target: list or tuple, with [x, y, gripper], where gripper is a value between 0:closed and 1:open ''' # Get the target variables x, y, gripper = target # Make sure the gripper is between 0 and 1 gripper = np.max([np.min([gripper,1.0]),0.0]) # This is the offset for accounting for the horizontal # displacement of the robot, and for the vertical displacement # adding the height up to first link and subtracting gripper # assembly height (we assume the gripper is always pointing # down). x0, y0 = (ROBOTY,\ 6+BASE_LENGTH+LINK0_LENGTH \ -(2*LINK2_LENGTH+2*LINK3_LENGTH+2*FINGER_LENGTH)) # Here is offset the joint coordinates x = x - x0 y = y - y0 # These are the link lengths a1 = 2*LINK0_LENGTH a2 = 2*LINK1_LENGTH # This computes the closed-form 2DoF inverse kinematics num = x**2 + y**2 - a1**2 - a2**2 den = 2*a1*a2 # We can only proceed if num/den <= 1, which means # the target is reachable. if np.abs(num/den) <= 1.0: q2 = np.arccos(num / den) # For elbow-symmetric solutions (always elbow up) # we inverd the signal of q2 if the target is to # the right of the robot. This will flip the pose # so that the elbow is always up. However, this # causes some sudden discontinuity in the movement # when moving in a path from the left of the robot # to the right. I would avoid working on the space # to the right of the robot. If you do not want the # flip, just comment the two lines marked "this" below if x > 0.0: # <= this q2 = -q2 # <= this q1 = np.arctan2(y,x) \ - np.arctan2(a2*np.sin(q2),a1+a2*np.cos(q2)) - np.pi/2.0 # Great, we got a new target. self.target = [q1, q2, np.pi-q1-q2, \ -gripper*self.gripperMax] def getGripperGoal(self): ''' Tells if gripper is closed (True) or opened (False) ''' #gripper = - self.j4.translation / self.gripperMax gripper = - self.target[-1] / self.gripperMax if gripper > 0.25: return False else: return True def _is_grasping(self): ''' Returns true if welding grasping is active ''' if self.j7 is None: return False else: return True def _ungrasp(self): ''' Undo the weld joint grasping (if any) ''' if self.j7 is not None: self.world.DestroyJoint(self.j7) self.world.DestroyJoint(self.j8) self.world.DestroyJoint(self.j9) self.j7 = None self.j8 = None self.j9 = None def _grasp(self, body, pos=None): ''' This function creates a weld joint for a firm grasp, not letting the object go easily''' if pos is None: pos = self.getFK() #self.j7 = self.world.CreateWeldJoint( \ self.j7 = self.world.CreateRevoluteJoint( \ bodyA=self.robot_link2_body,\ bodyB=body,\ anchor=pos,\ collideConnected = False) #self.j8 = self.world.CreateWeldJoint( \ self.j8 = self.world.CreateRevoluteJoint( \ bodyA=self.robot_link4_body,\ bodyB=body,\ anchor=pos,\ collideConnected = False) #self.j9 = self.world.CreateWeldJoint( \ self.j9 = self.world.CreateRevoluteJoint( \ bodyA=self.robot_link5_body,\ bodyB=body,\ anchor=pos,\ collideConnected = False) def startFollowingPath(self, path = None): ''' Tells the robot to start following a path Parameters ---------- path : an array with 3-tuples (x,y,g) where g is the gripper (1 for open, 0 for closed) ''' if path: # We overwrite the path one is provided self.path = path self.path_counter = 0 self.enableTorque() self.isPathFollowing = True def stopFollowingPath(self): ''' Stops following a path ''' self.isPathFollowing = False def _compute_DMPs(self): ''' This method creates the DMP objects and fits paths to the DMP forcing function kernel weights. The resulting (possibly smoother) path then replaces the originally hand drawn one. ''' self.dmps = [] self.dmp_startendpoints = [] self.path = [] y, dy, ddy = [], [], [] for i in range(len(self.dmp_training_paths)): self.dmps.append(pydmps.dmp_discrete.DMPs_discrete(n_dmps=3,\ n_bfs=DMP_KERNELS, \ ay=np.ones(3)*10.0,\ axis_to_not_mirror=7,\ axis_not_to_scale=2)) if i == 0: start_point = self.dmp_training_paths[i][0] else: start_point = self.dmp_training_paths[i-1][-1] end_point = self.dmp_training_paths[i][-1] self.dmp_startendpoints.append((start_point[:2], end_point[:2])) y_des = np.array(self.dmp_training_paths[i].copy()).T self.dmps[i].imitate_path(y_des, plot=False) y, dy, ddy = self.dmps[i].rollout() for t in range(len(y)): if y[t][2] > 0.5: gripper = 1.0 else: gripper = 0.0 gripper = y[t][2] self.path.append((y[t][0], y[t][1], gripper)) def _updatePathWithDMPs(self): ''' This method rolls-out the DMPs and regenerate their paths, for the case when their waypoints were dragged ''' self.path = [] y, dy, ddy = [], [], [] for i in range(len(self.dmps)): self.dmps[i].reset_state() self.dmps[i].y0 = np.array((self.dmp_startendpoints[i][0][0], self.dmp_startendpoints[i][0][1], self.dmp_training_paths[i][0][2])) self.dmps[i].goal = np.array((self.dmp_startendpoints[i][1][0], self.dmp_startendpoints[i][1][1], self.dmp_training_paths[i][-1][2])) y, dy, ddy = self.dmps[i].rollout() for t in range(len(y)): if y[t][2] > 0.5: gripper = 1.0 else: gripper = 0.0 gripper = y[t][2] self.path.append((y[t][0], y[t][1], gripper)) def step(self, show_graphics=True): ''' This is the main method for performing one step of simulation, updating position of objects according to torques, forces, constraints, gravity and so on. This also updates the GUI picture. Parameters ---------- show_graphics: This is a boolean flag to define wheter or not the GUI should be updated. If set to False then we will not draw anything on the window and we will not try to throttle the framerate. ''' # First we check if we should be running at all. If # the user closes the GUI window, then the simulation # is over. if not self.running: return False moved_mouse = False # This flag will be set by the event # Check PyGame's event queue for event in pygame.event.get(): # Check if the application was closed if event.type == QUIT: pygame.quit() self.running = False return False # Handle event keys # Key-down is only used for the gripper. When isDragging # with the mouse, isDrawing a path, if the shift key is # pressed, then the gripper target for that point will # be the gripper-closed configuration. elif event.type == KEYDOWN: if event.key == K_LSHIFT or event.key == K_RSHIFT: self.gripper = True # Key-up is the standard for handling key presses # so we only act after the key is released. elif event.type == KEYUP: # Pressing return (enter) toggles joint torque if event.key == K_RETURN: if self.isTorqueEnabled: self.disableTorque() else: self.enableTorque() # Pressing DEL or BACKSPACE deletes the path and # the DMP waypoints if event.key == K_DELETE or event.key == K_BACKSPACE: self.path = [] self.dmp_training_paths = [[]] # Pressing the SPACE BAR will make the target # follow the defined path (if one exists) if event.key == K_SPACE: if not self.isPathFollowing: self.path_counter = 0 self.isPathFollowing = True else: self.isPathFollowing = False # These are some shortcuts to move the joints # of the robot go to specific positions, # or incrementing/decrementing the angles # by 45 deg steps if event.key == K_0: self.target = 0.0, 0.0, 0.0, 0.0 if event.key == K_1: self.target[0] -= np.pi/4 if event.key == K_2: self.target[0] += np.pi/4 if event.key == K_3: self.target[1] -= np.pi/4 if event.key == K_4: self.target[1] += np.pi/4 if event.key == K_5: self.target[2] -= np.pi/4 if event.key == K_6: self.target[2] += np.pi/4 if event.key == K_7: self.target[3] -= 0.25 if event.key == K_8: self.target[3] += 0.25 if event.key == K_LSHIFT or event.key == K_RSHIFT: self.gripper = False # The control (CTRL) keys are used to add waypoints # to the DMP if (event.key == K_LCTRL or event.key == K_RCTRL) \ and self.isDrawing: self.dmp_training_paths.append([]) if len(self.dmp_training_paths) > 1: self.dmp_training_paths[-1].append(self.dmp_training_paths[-2][-1]) # Check if the user has clicked an object with the mouse elif event.type == MOUSEBUTTONDOWN: self.pos = pygame_to_b2d(event.pos) # PyGame to Box2D coords # First let's check if we are trying to drag a DMP waypoint for i,(start_point,end_point) in enumerate(self.dmp_startendpoints): if distance(self.pos[:2], start_point) <= DMPMINDRAGDIST: self.draggingWaypoint = i self.isDragging = True elif i == len(self.dmp_startendpoints)-1 and \ distance(self.pos[:2], end_point) <= DMPMINDRAGDIST: self.draggingWaypoint = i + 1 self.isDragging = True # Check if we are trying to drag a body if not self.isDragging: for body in self.bodies: # Iterate over all bodies... for fixture in body.fixtures: #...and their fixtures if fixture.TestPoint(self.pos): # Test clicked pos self.isDragging = True # Convert the clicked pos into polar coordinates # relative to the clicked body dx = self.pos[0] - body.worldCenter[0] dy = self.pos[1] - body.worldCenter[1] radius = np.sqrt(dx**2 + dy**2) angle = np.arctan2(dy, dx) - body.angle # Save this info in a dictionary self.draggedBodies[fixture.body] = radius, angle # Okay, not dragging, let's just start drawing. if not self.isDragging: self.path = [] self.dmp_training_paths = [[]] self.isDrawing = True # If the mouse moved and we are isDragging, then update the pos elif event.type == MOUSEMOTION and self.isDragging: moved_mouse = True self.pos = pygame_to_b2d(event.pos) # If the mouse moved and we are isDrawing, then update the pos elif event.type == MOUSEMOTION and self.isDrawing: moved_mouse = True self.pos = pygame_to_b2d(event.pos) # If the button was released, then stop isDragging # and also stop isDrawing elif event.type == MOUSEBUTTONUP: # If we actually were drawing a path, then # we will also add this last point as the # end point of the last DMP, and then we # will compute the DMP if self.isDrawing: self._compute_DMPs() self.isDragging = False self.isDrawing = False self.draggedBodies = {} self.draggingWaypoint = -1 # Append a new target for each time step of the isDrawing if self.isDrawing: # self.pos = pygame_to_b2d(pygame.mouse.get_pos()) if self.gripper: gripper_goal = 0.0 else: gripper_goal = 1.0 self.path.append(self.pos+[gripper_goal]) self.dmp_training_paths[-1].append(self.pos+[gripper_goal]) # add to DMP path # Path following if self.isPathFollowing and self.path: self.setIKTarget(self.path[self.path_counter]) self.path_counter = self.path_counter + 1 if self.path_counter >= len(self.path): self.path_counter = 0 self.isPathFollowing = False # Grasp using weld joints if self.use_weld_grasp: if not self._is_grasping() and self.getGripperGoal(): grip_pos = self.getFK() for body in self.bodies: # Iterate over all bodies... if not body in self.robot_bodies: # Must not belong to robot for fixture in body.fixtures: # Iterate the fixtures if fixture.TestPoint(grip_pos): # Test clicked pos self._grasp(body,grip_pos) break # pick only one elif self._is_grasping() and not self.getGripperGoal(): self._ungrasp() # Update joint torques if self.isTorqueEnabled: self._jointPID() # Update forces on dragged objects if self.isDragging: # Let's try first to handle dragging waypoints if self.draggingWaypoint is not -1 and moved_mouse: i = self.draggingWaypoint if i < len(self.dmp_startendpoints): start_point, end_point = self.dmp_startendpoints[i] self.dmp_startendpoints[i] = self.pos, end_point x,y,gripper = self.dmp_training_paths[i][0] self.dmp_training_paths[i][0] = \ self.pos[0], self.pos[1], gripper if i > 0: start_point, end_point = self.dmp_startendpoints[i-1] self.dmp_startendpoints[i-1] = start_point, self.pos x,y,gripper = self.dmp_training_paths[i-1][-1] self.dmp_training_paths[i-1][-1] = \ self.pos[0], self.pos[1], gripper self._updatePathWithDMPs() else: # The keys of this dictionary are the dragged objects for body in self.draggedBodies.keys(): # Get the relative polar coordinates of the anchor drag # point and convert to world coordinates radius, angle = self.draggedBodies[body] pos0 = body.worldCenter[0]+radius*np.cos(body.angle + angle), \ body.worldCenter[1]+radius*np.sin(body.angle + angle) # Append this point to be drawn later self.dots.append(b2d_to_pygame(pos0)) force = FORCE_SCALE*(self.pos[0] - pos0[0]),\ FORCE_SCALE*(self.pos[1] - pos0[1]) body.ApplyForce(force, pos0, True) # Paint the sky self.screen.fill(COLORS['SKY']) # Draw the bodies for body in self.bodies: for fixture in body.fixtures: shape = fixture.shape vertices = [b2d_to_pygame(body.transform*v) \ for v in shape.vertices] pygame.draw.polygon(self.screen, self.colors[body], vertices) for ball in self.balls: for fixture in ball.fixtures: #print(fixture.shape) #print(dir(fixture.shape)) pygame.draw.circle(self.screen, self.colors[ball], b2d_to_pygame(ball.transform*fixture.shape.pos), int(fixture.shape.radius*PPM), 0) # Draw the revolute joints if self.isTorqueEnabled: joint_color = COLORS['JOINTSON'] else: joint_color = COLORS['JOINTSOFF'] for joint in self.joints[:3]: pygame.draw.circle(self.screen, joint_color, \ b2d_to_pygame(joint.anchorA), JOINT_RADIUS) # Draw the dots for dot in self.dots: pygame.draw.circle(self.screen, COLORS['RED'], dot, 5) # Draw the path if self.isDrawing: path_radius = 2 else: path_radius = 5 for x,y,gripper in self.path: point = x,y if gripper > 0.5: color = COLORS['PATHOFF'] else: color = COLORS['PATHON'] pygame.draw.circle(self.screen, color, b2d_to_pygame(point), path_radius) # If it is following a path, then draw a red circle if self.path and self.isPathFollowing: pygame.draw.circle(self.screen, COLORS['TARGET'], b2d_to_pygame(self.path[self.path_counter]), 8) # Draw the current pos pygame.draw.circle(self.screen, COLORS['CURRPOS'], b2d_to_pygame(self.getFK()), 9, 2) self.dots = [] # Draw DMP waypoints (start and end positions of each DMP) for dmp_training_path in self.dmp_training_paths: if len(dmp_training_path) > 0: start_point = dmp_training_path[0][:2] end_point = dmp_training_path[-1][:2] pygame.draw.circle(self.screen, COLORS['DMPWAYPOINT'], b2d_to_pygame(start_point), 9, 2) pygame.draw.circle(self.screen, COLORS['DMPWAYPOINT'], b2d_to_pygame(end_point), 9, 2) # Simulation step self.world.Step(TIME_STEP, 10, 10) if show_graphics: # Update the screen pygame.display.flip() # Pace the framerate self.clock.tick(FPS) return True def createBoxes(self): ''' Creates 25 little boxes, for interaction ''' self.box_bodies = [] for i in range(25): # create a random box at random horizontal positions # around position 25,15 self.box_bodies.append(self.world.CreateDynamicBody( \ position=(25 + np.random.random()*10, 15), angle=np.random.random()*90.0)) # define the box perimeter fixture and its friction is high # to make it easier for the robot to grasp the box self.box_bodies[-1].CreatePolygonFixture(box=(1.25, 1.25), density=0.125, friction=100.0, restitution=BOX_RESTITUTION) # We color all these boxes in the BOX color for box in self.box_bodies: self.colors[box] = COLORS['BOX'] # And finally we append them to our simulation queue self.bodies = self.bodies + self.box_bodies def createSeeSawEnv(self): ''' Creates a see-saw environment, for simulating a dynamic pouring task''' self.table = self.world.CreateStaticBody(position=(40,10)) self.table.CreatePolygonFixture(box=(3,5)) self.base = self.world.CreateDynamicBody(position=(40,10)) self.base.CreatePolygonFixture(box=(5,1), density=0.05, friction=100.0) self.seesaw = self.world.CreateDynamicBody(position=(40,20)) self.seesaw.CreatePolygonFixture(box=(10,1), density=0.05, friction=100.0) self.handle = self.world.CreateDynamicBody(position=(40+9,21)) self.handle.angularDamping = 0.75 self.handle.CreatePolygonFixture(box=(0.75,8), density=0.05, friction=100.0) self.weight = self.world.CreateDynamicBody(position=(40+9,22-7)) self.weight.CreatePolygonFixture(box=(2,2), density=0.05, friction=100.0) self.weight.angularDamping = 0.75 self.jssb = self.world.CreatePrismaticJoint(bodyA=self.table, bodyB=self.base, anchor=(40,20), axis=(1,0), collideConnected = False) self.jss = self.world.CreateRevoluteJoint(bodyA=self.base, bodyB=self.seesaw, anchor=(40-10,20), collideConnected = True) self.jssh = self.world.CreateRevoluteJoint(bodyA=self.seesaw, bodyB=self.handle, anchor=(40+9,20), collideConnected = False) self.jssw = self.world.CreateWeldJoint(bodyA=self.handle, bodyB=self.weight, anchor=(40+9,22-7)) radius = 1.5 for i in range(4): ball = \ self.world.CreateDynamicBody(position=(40-5+2*radius*i,22)) ball.CreateCircleFixture(radius=radius, density=0.01, friction=0.3, restitution=0.0) self.balls.append(ball) self.colors[self.balls[0]] = COLORS['REDBALL'] self.colors[self.balls[1]] = COLORS['GREENBALL'] self.colors[self.balls[2]] = COLORS['BLUEBALL'] self.colors[self.balls[3]] = COLORS['YELLOWBALL'] self.colors[self.base] = COLORS['TABLE'] self.colors[self.table] = COLORS['TABLE'] self.colors[self.seesaw] = COLORS['TABLE'] self.colors[self.handle] = COLORS['TABLE'] self.colors[self.weight] = COLORS['TABLE'] self.bodies = self.bodies + [self.base, self.table, self.seesaw, self.handle, self.weight] def fallenBalls(self): count = 0 for ball in self.balls: for fixture in ball.fixtures: pos = ball.transform*fixture.shape.pos if pos[1] < 10: count = count+1 return count def createTablesEnv(self): ''' Creates an environment with two tables and some boxes for manipulation tasks ''' self.table1 = self.world.CreateStaticBody(position=(25,10)) self.table1.CreatePolygonFixture(box=(3,5)) self.table2 = self.world.CreateStaticBody(position=(40,10)) self.table2.CreatePolygonFixture(box=(3,5)) self.box = self.world.CreateDynamicBody(position=(25,15+1.25)) self.box.CreatePolygonFixture(box=(1.25,1.25), density=0.125, friction=100.0, restitution=BOX_RESTITUTION) self.colors[self.table1] = COLORS['TABLE'] self.colors[self.table2] = COLORS['TABLE'] self.colors[self.box] = COLORS['BOX'] self.bodies = self.bodies + [self.table1, self.table2, self.box] pos0 = (32.5,30) pos_above_goal1 = (25,20) pos_goal1 = (25,15+1.25) pos_above_goal2 = (40,20) pos_goal2 = (40,15+1.25) self.goal = pos_goal2 path = [] path = path + interpolate_path(pos0, pos_above_goal1, 1.0, 25) path = path + interpolate_path(pos_above_goal1, pos_goal1, 1.0, 50) path = path + interpolate_path(pos_goal1, pos_goal1, 0.0, 25) path = path + interpolate_path(pos_goal1, pos_above_goal1, 0.0) path = path + interpolate_path(pos_above_goal1, pos_above_goal2, 0.0) path = path + interpolate_path(pos_above_goal2, pos_goal2, 0.0) path = path + interpolate_path(pos_goal2, pos_goal2, 1.0, 25) path = path + interpolate_path(pos_goal2, pos_above_goal2, 1.0, 50) path = path + interpolate_path(pos_above_goal2, pos0, 1.0, 25) self.path = path if __name__ == '__main__': robot = Robot2D() while robot.step(): pass
true
8d6f46c854fd5763e2e62e5646d274f2d5ef6c0a
Python
Yuki-Inamoto/python-lesson
/02_Subst_tab2blank.py
UTF-8
467
2.984375
3
[]
no_license
# -*- coding: utf-8 -*- import sys argvs = sys.argv argc = len(argvs) if (argc < 3): # 引数チェック print('Usage: # python %s input_filename output_filename' % argvs[0]) raise SystemExit() # プログラムの終了 with open(argvs[1], 'r', encoding='utf-8') as candidate_f,\ open(argvs[2], "w", encoding='utf-8') as f: for row in candidate_f: row = row.replace('\t', ' ') # タブを空白に置き換え f.write(row)
true
1863e79e84a38e3b424701330de99b40f4267517
Python
madebits/python-image-viewer
/impl/UserCommands.py
UTF-8
2,078
2.65625
3
[]
no_license
import os, sys import subprocess class UserCommands: def __init__(self, commandsFile): self.commands = None if (commandsFile != None) and os.path.isfile(commandsFile): with open(commandsFile) as f: self.commands = f.readlines() # quit|separator|commandParts def parseCommand(self, command, currentFile): if (command == None) or (len(command) <= 0): return None parts = command.strip('\r\n \t').split('|', 3); if len(parts) < 3: return None shouldQuit = parts[0].strip() == 'quit' commandParts = parts[2].split(parts[1]) for i, p in enumerate(commandParts): p = p.strip() if currentFile != None: p = p.replace("%f%", currentFile) commandParts[i] = p return (shouldQuit, commandParts) def runCommand(self, commandIndex, currentFile): if currentFile == None: return if (self.commands == None) or (len(self.commands) == 0) or commandIndex >= len(self.commands): return commandText = self.commands[commandIndex] command = self.parseCommand(commandText, currentFile) if command == None: return commandText = " ".join(command[1]) text = "Run" if command[0]: text += " and quit" if not askokcancel("Confirm Command", text + ":\n" + commandText): return #subprocess.call(command[1], shell=False) subprocess.Popen(command[1], shell=False) if command[0]: quit(None) def listCommands(self): if (self.commands == None) or (len(self.commands) == 0): return "" res = "Custom commands (key command):\n" for i, c in enumerate(self.commands): if i > 9: break command = self.parseCommand(c, None) if command == None: continue commandText = " ".join(command[1]) if command[0]: commandText += " # quit after run" res += " {0} {1}\n".format(i + 1, commandText) return res
true
8efee8bc7785eed3492cffc0b113d5dc41e7ec84
Python
yesrgang/m2-frequency-servo
/gui/widgets/led_widget.py
UTF-8
1,338
2.640625
3
[]
no_license
from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtCore import pyqtSlot class LEDWidget(QtGui.QWidget): green_color = Qt.QColor(50,213,18) green_border_color = Qt.QColor(43,176,16) red_color = Qt.QColor(255,18,18) red_border_color = Qt.QColor(168,20,20) def __init__(self, status=True, size=20, parent=None): super(LEDWidget, self).__init__(parent) self.status = status self.size = size vbox = QtGui.QVBoxLayout() vbox.setContentsMargins(0, 0, 0, 0) self.setLayout(vbox) self.pixmap_label = QtGui.QLabel() vbox.addWidget(self.pixmap_label) self.update(self.status) @pyqtSlot(bool) def update(self, status=True): self.status = status border_color = self.green_border_color if self.status else self.red_border_color fill_color = self.green_color if self.status else self.red_color pm = QtGui.QPixmap(QtCore.QSize(self.size + 1, self.size + 1)) pm.fill(Qt.QColor('transparent')) qp = QtGui.QPainter(pm) qp.setRenderHint(QtGui.QPainter.Antialiasing) qp.setPen( QtGui.QPen(border_color) ) qp.setBrush( QtGui.QBrush(fill_color) ) qp.drawEllipse(1, 1, self.size-2, self.size-2) del qp self.pixmap_label.setPixmap(pm)
true
62d34355f888eef27ab0e486c354c75c5718efa5
Python
amas-eye/argus_alert
/core/notice/wechat_server/blueprints/wechat_alert_push_bp.py
UTF-8
1,616
2.625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- """ I was trying to decouple web framework the one provide us capability of handling http request, specifically, in `flask`, we could manipulate urls via coding view functions and the Wechat Official Account application logic which allow us interact with followers by handle some http requests too. Turns out, there is not neccessary to decouple them, aka, they are related. Here i use flask's elegant class-based view function as our broker of accepting http requests and returning response. All the wechat logic is stashed with the help of Python decorators. """ from flask import Blueprint from flask.views import MethodView from wechat_server.blueprints import __version__ from wechat_server.blueprints.official_account import OfficialAccount __all__ = ['alert_bp'] wechat_app = OfficialAccount() alert_bp = Blueprint('alert', __name__, url_prefix='/' + __version__ + '/wechat_alert') class WechatAlertAPI(MethodView): """ A class-based http method handler. All the business logic is handle by the decorators. To add functionalities, implement them and append them to `decorators`. """ decorators = wechat_app.handlers def get(self): """Wechat will visit us via GET to ensure secure communication.""" pass def post(self): """ Whenever the followers make some actions, Wechat will post some data to us and hope us react to followers' behavior via POST something back to it. """ pass alert_bp.add_url_rule('/', view_func=WechatAlertAPI.as_view('alert_view'))
true
8bd717b507ed6d4d3ae7bed7b372c1b528350000
Python
mapra99/platzi_webScraping
/scraping.py
UTF-8
2,398
2.890625
3
[]
no_license
import requests from bs4 import BeautifulSoup url='https://www.pagina12.com.ar/' p12=requests.get(url) dict_content={} print('#############################################################################################################') print('#############################################################################################################') print(p12.status_code) print('#############################################################################################################') print('#############################################################################################################') # print(p12.text) print('#############################################################################################################') print('#############################################################################################################') # print(p12.headers) print('#############################################################################################################') print('#############################################################################################################') # print(p12.request.headers) print('#############################################################################################################') print('#############################################################################################################') # print(p12.cookies) s = BeautifulSoup(p12.text, 'html.parser') arreglo=s.find('li',attrs={'class':'sections'}).find_all('li') array_liks_sections=[] for i in arreglo: linkSection=i.a.get('href') array_liks_sections.append(linkSection) dict_content[i.a.contents[0]]=[] dict_content[i.a.contents[0]].append(linkSection) print('{} -- {} \n'.format(i.a.contents[0],linkSection)) def extract_url_article(url_in,use_class): p_temp=requests.get(url_in) s_temp = BeautifulSoup(p_temp.text, 'html.parser') array_container=s_temp.find_all('div',attrs={'class':use_class}) array_container_resulting=[i.find('h2').find('a').get('href') for i in array_container] print(array_container_resulting) for section in dict_content: print('\n{}'.format(section)) print('{}'.format(dict_content[section][0])) extract_url_article(dict_content[section][0],'featured-article__container') extract_url_article(dict_content[section][0],'article-box__container')
true
cbe9fecdda3d61352d519f1ffeaba293320652b2
Python
nHunter0/Discord-Bots
/DiscordSpamBot.py
UTF-8
431
2.578125
3
[]
no_license
import discord client = discord.Client() keywords = ["!releaseSpamBot"] #discord command @client.event async def on_message(message): for i in range(len(keywords)): if keywords[i] in message.content: for j in range(10): #amount of time message will be spamed by bot await message.channel.send("spamMessage") #message that will be spamed by bot client.run('DISCORD_TOKEN')
true
f8ea4d2b79bc2137803a8680cf1ec20143436cae
Python
Augustin-Louis-Xu/python_work
/第五章/5.2 条件测试 知识点.py
UTF-8
1,341
3.90625
4
[]
no_license
#一个简单列子 cars=['audi','bmw','subaru','toyota'] for car in cars: if car == 'bmw':#此处为检查变量的值与特定值是否相等 print(car.upper()) else: print(car.title()) #car='Audi',car.lower() == 'audi',此处将返回True,函数Lower()不会改变存储在变量car中的值,因此在比较时不会影响原来的变量。 requested_topping='mushrooms' if requested_topping!='anchovies': print('\nHold the anchovies') answer=17 if answer != 42:#在这里输入的答案是17,不是42. print('\nThat is not the correct answer,please try again!') #检查多个条件,可使用and或者or将测试条件合二为一。 #age_0=21,age_1=18,age_0>=21 and age_1>=21,此处将返回Flase. #age_0=21,age_1=18,age_0>=21 or age_1>=21,此处将返回Ture ,使用or检查条件只需要一个条件满足即可. #检查特定值是否包含在列表中。requested_topping=['mushrooms','onions','pineapple'],'mushrooms' in requested_toppings 此处返回True. #检查特定值是否不包含在列表中。 banned_users=['andrew','caroline','david'] user='marie' if user not in banned_users: print('\n'+user.title()+',you can post a response if you wish.') #布尔表达式 它是条件表达式的一种别名,返回的结果为True或者False,是一种高效的方式。
true
dd9b48c311801854dffc191611d09a6bb552f034
Python
satyanrb/Mini_Interview_programs
/flip_coin.py
UTF-8
82
3.140625
3
[]
no_license
import math if (math.random() < 0.5 ): print("Heads") else: print("Tails")
true
d760c6fadad31e5512d2f08979b272ed4717b3d8
Python
hwagok92/Python-Pandas
/Ex04.py
UTF-8
1,577
3.40625
3
[]
no_license
#-*- coding:utf-8 ''' Created on 2020. 11. 2. @author: hwago ''' import numpy as np from pandas import * import pandas as pd df = DataFrame([[3,5,1],[9,2]], index=['apple','banana'], columns=['kim','park','jung']) print('df:\n',df) print() #끝자리에 값을 넣고 싶지않으면 그냥 안넣으면 돼지만 중간에 데이터를 넣고 싶다면 np.NaN을 넣어야 한다 df = DataFrame([[3,np.NaN,1],[9,2]], index=['apple','banana'], columns=['kim','park','jung']) print('df:\n',df) print() filename = 'mynan.csv' table = pd.read_csv(filename,encoding='euc-kr') print('table:\n',table) table = pd.read_csv(filename,encoding='euc-kr', index_col=0) print('table:\n',table) print(type(table)) print(table.size) #데이터가 있으면 False 없으면 True print(table.isna()) print() print(pd.isna(table)) print() #데이터 없으면 True 있으면 False print(table.notnull()) print() #이용할 수 없는걸 빼라=데이터가 없으면 빼라 table2 = table.dropna() print('table2:\n',table2) print() #기본값 how='any' 어디라도 데이터가 없으면 지워라 table2 = table.dropna(how='any') print('table2:\n',table2) print() table2 = table.dropna(how='all') print('table2:\n',table2) print() #데이터가 없는 곳에 값을 넣는 코드 fillna table = table.fillna({'kor':20,'eng':90}) print('table:\n',table) filename="mynan2.csv" table.to_csv(filename,encoding='euc-kr')
true
cdb70b7bbe6456868dffedc914b08800fe1331b8
Python
anyboby/CarlaRL
/semantic_birdseyeview/view_history.py
UTF-8
963
2.546875
3
[]
no_license
# Visualize training history from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt import numpy import pickle # Fit the model with open("histories/multi_model_rgb_sweep=4_decimation=2_numclasses=3_valloss=0.061.pkl", 'rb') as f: histories = pickle.load(f) #history = model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, verbose=0) # list all data in history print(len(histories)) history = histories[9] print(history.keys()) # summarize history for accuracy plt.plot(history['val_birdseye_reconstruction_loss']) # plt.plot(history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()
true
06dccad0c3383d576ab03582fa8aaf28d285c920
Python
lugy-bupt/algorithm
/leet/0434-number-of-segments-in-a-string/number-of-segments-in-a-string.py
UTF-8
164
2.625
3
[]
no_license
class Solution: def countSegments(self, s: str) -> int: if len(s) == 0 : return 0 return len(list(filter(lambda x: len(x) > 0, s.split(" ")) ))
true
f6c115de59e787a7e44c4644693c45addade5633
Python
binonguyen1090/LeetCode
/LeetCode-66.py
UTF-8
613
3.203125
3
[]
no_license
#https://leetcode.com/problems/plus-one/submissions/ # class Solution: # def plusOne(self, digits: List[int]) -> List[int]: # total = 0 # for i in digits: # total = total*10 + i # s = str(total+1) # result = list(s) # return(result) class Solution: def plusOne(self, digits: List[int]) -> List[int]: if digits[-1] == 9: if len(digits) == 1: return([1,0]) else: return self.plusOne(digits[:-1]) + [0] digits[-1] = digits[-1]+ 1 return(digits)
true
f18e8e1a54219a0da283c7e85159988c47a55c3a
Python
EdmundMartin/inverted
/examples/using_typed_injector.py
UTF-8
708
3.40625
3
[]
no_license
from inverted.typed_injector import InvertedTypedContainer class Dog: def __init__(self, name: str): self.name = name class MyPet: def __init__(self, ronald: Dog): self.val = ronald def __repr__(self): return self.val.name class TestClass: def __init__(self, hello: str, pet: MyPet): self.hello = hello self.pet = pet def __repr__(self): return f"{self.hello} {self.pet}" if __name__ == '__main__': container = InvertedTypedContainer() container.bind_to_name_and_type("hello", str, "Привет") container.bind_to_name_and_type("name", str, "Ronald") result = container.get_instance(TestClass) print(result)
true
beb58fac4aca47fc589d0894a46fceef275906ca
Python
General-Mudkip/Computer-Science-y10
/Final RPG/FinalRPG.py
UTF-8
43,681
3.140625
3
[]
no_license
import tkinter as tk from PIL import Image, ImageTk from tkinter import font as tkFont from tictactoeGUI import ticTacToe as tttGame import configFile as cf import random import time # Initializes main window root = tk.Tk() root.geometry("720x600") root.title("RPG - Bence Redmond") # Creates fonts helv10 = tkFont.Font(family = "Helvetica", size = 10) helv15 = tkFont.Font(family = "Helvetica", size = 15) helv20 = tkFont.Font(family = "Helvetica", size = 17) helv25 = tkFont.Font(family = "Helvetica", size = 25) helv35 = tkFont.Font(family = "Helvetica", size = 35) tooltipList = [] # Function containing all of the tic tac toe code def ticTacToe(): # Initializes main window global tttWindow tttWindow = tk.Toplevel() tttWindow.title("Tic Tac Toe") tttWindow.geometry("425x650") global playerSymbol playerSymbol = "x" # Creates the board # Each upper dictionary represents a row, and each nested dictionary # Represents a column. So if printed (as a board would be) this would output: # Column: # 1 2 3 # _____ # 1 | x o x # Row: 2 | x o x # 3 | x o x board = { 1:{1:"-",2:"-",3:"-"}, 2:{1:"-",2:"-",3:"-"}, 3:{1:"-",2:"-",3:"-"} } # Creates fonts helv25 = tkFont.Font(family = "Helvetica", size = 25) helv50 = tkFont.Font(family = "Helvetica", size = 50) # Initalizes boxes b1 = tk.Button(tttWindow, text = board[1][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b1,1,1,playerSymbol)) b2 = tk.Button(tttWindow, text = board[1][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b2,1,2,playerSymbol)) b3 = tk.Button(tttWindow, text = board[1][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b3,1,3,playerSymbol)) b4 = tk.Button(tttWindow, text = board[2][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b4,2,1,playerSymbol)) b5 = tk.Button(tttWindow, text = board[2][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b5,2,2,playerSymbol)) b6 = tk.Button(tttWindow, text = board[2][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b6,2,3,playerSymbol)) b7 = tk.Button(tttWindow, text = board[3][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b7,3,1,playerSymbol)) b8 = tk.Button(tttWindow, text = board[3][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b8,3,2,playerSymbol)) b9 = tk.Button(tttWindow, text = board[3][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b9,3,3,playerSymbol)) # Creates list of the button objects that can be iterated through later buttonList = [b1, b2, b3, b4, b5, b6, b7, b8, b9] # Creates labels turnLabel = tk.Label(tttWindow, text = f"It is {playerSymbol}'s turn.", font = helv25) label2 = tk.Label(tttWindow, text = "Pick a slot!") # Displays buttons in the 3x3 grid pattern b1.grid(row = 0, column = 0) b2.grid(row = 0, column = 1) b3.grid(row = 0, column = 2) b4.grid(row = 1, column = 0) b5.grid(row = 1, column = 1) b6.grid(row = 1, column = 2) b7.grid(row = 2, column = 0) b8.grid(row = 2, column = 1) b9.grid(row = 2, column = 2) # Displays labels at the bottom of the screen turnLabel.grid(row = 3, column = 0, columnspan = 3) # Displays who's turn it is label2.grid(row = 4, column = 0, columnspan = 3) # Displays smaller misc message # Changes the symbol, takes the button object for modification, x and y for board dict coords, and symbol for the player symbol def changeSymbol(buttonObj, x, y, symbol): if board[x][y] != "-": # Checks if the slot is empty or not label2.config(text = "Invalid Slot!") else: board[x][y] = symbol buttonObj.config(text = board[x][y], state = "disabled") # Sets the button the player clicked to their symbol and disables it if winCheck(board, symbol) == 0: global tttWindow for i in buttonList: # Iterates through the list of button objects i.config(state = "disabled") # Sets each button to disabled label2.config(text = "Close the window to continue!") cf.tttGame_returnVal = symbol tttWindow.destroy() return # Modifies the player's symbol global playerSymbol if symbol == "x": playerSymbol = "o" else: playerSymbol = "x" turnLabel.config(text = f"It is {playerSymbol}'s turn!") def winCheck(board,symbol): # Checks for horizontal wins for i in board: # Creates set of the values in each row rowSet = set(board[i].values()) # As sets cannot contain duplicate values, a row such as "x o x" will become {"x","o"} # We can then check if the row contains only one value (such as {"x"}) and if the value in the set is the player's symbol. if len(rowSet) == 1 and playerSymbol in rowSet: turnLabel.config(text = f"{symbol} wins horizontally!") return 0 # Checks for vertical wins boardSet = set() for i in range(1,4): colSet = set() # Have to use range(1,4) since range(1,3) won't go up to 3 for whatever reason. for row in range(1,4): colSet.add(board[row][i]) boardSet.add(board[row][i]) # Same as above if len(colSet) == 1 and playerSymbol in colSet: turnLabel.config(text = f"{symbol} wins vertically!") return 0 # Checks for diagonal wins diag1 = set(board[1][1]+board[2][2]+board[3][3]) # Top left to bottom right diag2 = set(board[1][3]+board[2][2]+board[3][1]) # Top right to bottom left # Same check system as above if len(diag1) == 1 and playerSymbol in diag1: turnLabel.config(text = f"{symbol} wins diagonally!") return 0 if len(diag2) == 1 and playerSymbol in diag2: turnLabel.config(text = f"{symbol} wins diagonally!") return 0 # Checks for draws using boardSet, which will contain all values in the dictionary if "-" not in boardSet: # Checks if there are any empty slots left turnLabel.config(text = f"It's a draw!") return 0 def guessingGame(): answerNum = random.randint(1,100) print(answerNum) global playerAttempts playerAttempts = 0 global gGame gGame = True def submit(): try: global gGame pAnswer = inputBox.get() pAnswer = int(pAnswer) global playerAttempts playerAttempts += 1 if pAnswer < answerNum: answerLabel.config(text = "Too low!") elif pAnswer > answerNum: answerLabel.config(text = "Too high!") else: answerLabel.config(text = f"Correct! {playerAttempts} guesses.") cf.gGame_returnVal = 1 gGame = False ngWindow.destroy() if playerAttempts >= 10: cf.gGame_returnVal = 0 gGame = False ngWindow.destroy() except: answerLabel.config(text = "Error Encountered! Guess again.") # Initializes main window global ngWindow ngWindow = tk.Toplevel(root) ngWindow.title("Number Guessing Game") ngWindow.geometry("170x130") # Initializes widgets guessingTitle = tk.Label(ngWindow, text = "Guess a Number!", font= helv15) answerLabel = tk.Label(ngWindow, text = "Guess...") inputBox = tk.Entry(ngWindow, width = 20, borderwidth = 4) submitButton = tk.Button(ngWindow, text = "Submit Number", command = submit) # Displays widgets inputBox.grid(row = 2, column = 0) guessingTitle.grid(row = 0, column = 0) answerLabel.grid(row = 1, column = 0) submitButton.grid(row = 3, column = 0) def codeEnter(code): # Initialize main window global ceWindow ceWindow = tk.Toplevel() ceWindow.title("Keypad") ceWindow.geometry("233x320") # Initialize widgets display = tk.Entry(ceWindow, width = 17, borderwidth = 5, font = helv20) display.grid(row = 0, column = 0, columnspan = 3) def button_click(num): newText = display.get() + str(num) display.delete(0, tk.END) display.insert(0, newText) def submit(): print(code) answer = display.get() if answer == "": display.delete(0, tk.END) display.insert(0, "Enter a code!") display.update() time.sleep(2) display.delete(0, tk.END) else: if answer == code: display.delete(0, tk.END) display.insert(0, "Correct!") display.update() time.sleep(2) cf.ceGame_returnVal = "correct" ceWindow.destroy() else: if len(answer) == 4: display.delete(0, tk.END) display.insert(0, "Incorrect!") display.update() time.sleep(2) display.delete(0, tk.END) elif len(answer) < 4: display.delete(0, tk.END) display.insert(0, "Too short!") display.update() time.sleep(2) display.delete(0, tk.END) elif len(answer) > 5: display.delete(0, tk.END) display.insert(0, "Too long!") display.update() time.sleep(2) display.delete(0, tk.END) text = tk.Label(ceWindow, text = "Enter The Code.") button_1 = tk.Button(ceWindow, text = "1", padx = 30, pady = 20, command = lambda: button_click(1)) button_2 = tk.Button(ceWindow, text = "2", padx = 30, pady = 20, command = lambda: button_click(2)) button_3 = tk.Button(ceWindow, text = "3", padx = 30, pady = 20, command = lambda: button_click(3)) button_4 = tk.Button(ceWindow, text = "4", padx = 30, pady = 20, command = lambda: button_click(4)) button_5 = tk.Button(ceWindow, text = "5", padx = 30, pady = 20, command = lambda: button_click(5)) button_6 = tk.Button(ceWindow, text = "6", padx = 30, pady = 20, command = lambda: button_click(6)) button_7 = tk.Button(ceWindow, text = "7", padx = 30, pady = 20, command = lambda: button_click(7)) button_8 = tk.Button(ceWindow, text = "8", padx = 30, pady = 20, command = lambda: button_click(8)) button_9 = tk.Button(ceWindow, text = "9", padx = 30, pady = 20, command = lambda: button_click(9)) button_0 = tk.Button(ceWindow, text = "0", padx = 30, pady = 20, command = lambda: button_click(0)) submit = tk.Button(ceWindow, text = "Submit", padx = 53, pady = 20, command = submit) button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=0) submit.grid(row=4, column=1, columnspan=2) text.grid(row = 5, column = 0, columnspan = 4) def displayEnd(ending, endingNo): global endScreen # Creates the end screen window endScreen = tk.Toplevel(root) endName = ending["name"] endScreen.title(f"New Ending - {endName}") endScreen.geometry("550x150") # Updates the player's end dictionary player.unlockEnding(endingNo) # Creates the labels endName_label = tk.Label(endScreen, text = f"Ending Reached - {endName}", font = helv25) endText_label = tk.Label(endScreen, text = ending["text"], font = helv15) end2Text_label = tk.Label(endScreen, text = f"You've now unlocked {player.unlockedEndings}/{len(player.endDict)} endings.") restartButton = tk.Button(endScreen, text = "Restart Game", command = lambda: player.resetGame(endScreen), font = helv20) # Button to restart the game # Displays widgets endName_label.grid(row = 0, column = 0, sticky = "w") endText_label.grid(row = 2, column = 0, sticky = "w") end2Text_label.grid(row = 1, column = 0, sticky = "w") restartButton.grid(row = 3, column= 0, sticky = "w") def wineGuesser(): # Python garbage collector goes ahead and gets rid of the image variables if they are local for whatever reason global wgWindow, wine1_img, wine2_img, wine3_img wgWindow = tk.Toplevel() wgWindow.title("Wine Guesser") wgWindow.geometry("500x300") def submit(choice): if choice == random.randint(1,3): descLabel.config(text = "You died! Ahhh.") descLabel.update() time.sleep(2) wgWindow.destroy() cf.wgGame_returnVal = 0 else: descLabel.config(text = "You chose the wine. Nice job!") descLabel.update() time.sleep(2) wgWindow.destroy() cf.wgGame_returnVal = 1 titleLabel = tk.Label(wgWindow, text = "Wine Guesser", font = helv25) descLabel = tk.Label(wgWindow, text = "Choose a poi- wine. Be careful now.", font = helv15) # Create wine bottles preWine1_img = Image.open("winebottle1.png") preWine1_img = preWine1_img.resize((60, 90), Image.ANTIALIAS) wine1_img = ImageTk.PhotoImage(preWine1_img) preWine2_img = Image.open("winebottle2.png") preWine2_img = preWine2_img.resize((60, 90), Image.ANTIALIAS) wine2_img = ImageTk.PhotoImage(preWine2_img) preWine3_img = Image.open("winebottle3.png") preWine3_img = preWine3_img.resize((60, 90), Image.ANTIALIAS) wine3_img = ImageTk.PhotoImage(preWine3_img) # Creates image labels wine1 = tk.Button(wgWindow, image = wine1_img, command = lambda: submit(1)) wine2 = tk.Button(wgWindow, image = wine2_img, command = lambda: submit(2)) wine3 = tk.Button(wgWindow, image = wine3_img, command = lambda: submit(3)) titleLabel.grid(row = 0, column = 0, sticky = "w", columnspan = 3) descLabel.grid(row = 1, column = 0, sticky = "w", columnspan = 3) wine1.grid(row = 2, column = 0) wine2.grid(row = 2, column = 1) wine3.grid(row = 2, column = 2) def multipleChoice(): global mcWindow, questionNo, correctAnswer # Sets up the window mcWindow = tk.Toplevel() mcWindow.title("Quiz") mcWindow.geometry("600x200") questionNo = 0 correctAnswer = 0 # Dictionary to store the questions (q), answers (answers), and correct answer number (c). questionsDict = {1:{"q":"How old am I?", "answers":{1:"I don't know", 2:"INT", 3:"FLOAT", 4:"14"}, "c":4}, 2:{"q":"What's my name?","answers":{1:"James",2:"Dolt",3:"Bence",4:"Arthur"},"c":3}, 3:{"q":"What programming language are Operating Systems coded in?","answers":{1:"C",2:"Python",3:"Scratch",4:"Java"},"c":1}, 4:{"q":"What is the lowest level programming language?","answers":{1:"Assembly",2:"Factory",3:"C",4:"JVM"}, "c":1}, 5:{"q":"What programming language are websites made in?","answers":{1:"C",2:"Javascript",3:"Java",4:"Python"}, "c":2}, 6:{"q":"What programming language is used for data science?","answers":{1:"Javascript",2:"Java",3:"Python",4:"Java"}, "c":3} } # Read start() first, most variables are initialized there def submit(answer): global qName, qDesc, questionNo, correctAnswer try: if answer == questionsDict[qList[questionNo]]["c"]: print("Correct!") correctAnswer += 1 qDesc.config(text = "Correct!") else: print("Incorrect!") qDesc.config(text = "Incorrect!") questionNo += 1 qName.config(text = questionsDict[qList[questionNo]]["q"]) for i in range(1,5): buttonDict[i].config(text = questionsDict[qList[questionNo]]["answers"][i]) except KeyError: qDesc.config(text = "End of Game!") qName.config(text = f"You got: {correctAnswer}/{len(qList)}") qDesc.update() qName.update() for i in range(1,5): buttonDict[i].config(state = "disabled") time.sleep(2) if correctAnswer >= len(questionsDict)/2: cf.mcGame_returnVal = 1 else: cf.mcGame_returnVal = 0 mcWindow.destroy() except IndexError: qDesc.config(text = "End of Game!") qName.config(text = f"You got: {correctAnswer}/{len(qList)}") qDesc.update() qName.update() for i in range(1,5): buttonDict[i].config(state = "disabled") time.sleep(2) if correctAnswer >= len(questionsDict)/2: cf.mcGame_returnVal = 1 else: cf.mcGame_returnVal = 0 mcWindow.destroy() title = tk.Label(mcWindow, text = "Multiple Choice Quiz", font = helv25) a1 = tk.Button(mcWindow, font = helv10, command = lambda: submit(1)) a2 = tk.Button(mcWindow, font = helv10, command = lambda: submit(2)) a3 = tk.Button(mcWindow, font = helv10, command = lambda: submit(3)) a4 = tk.Button(mcWindow, font = helv10, command = lambda: submit(4)) a1.grid(row = 3, column = 0) a2.grid(row = 3, column = 1) a3.grid(row = 3, column = 2) a4.grid(row = 3, column = 3) buttonDict = {1:a1,2:a2,3:a3,4:a4} def start(): global qName, qDesc, qList qList = list(range(1,len(questionsDict)+1)) # Creates a list from 1 - to the length of the list for i in range(len(qList)-3): # Pops all values except for three. popNo = random.randint(0,len(qList)-1) print(f"Pop: {popNo} || Length: {len(qList)} || List: {qList}") qList.pop(popNo) qName = tk.Label(mcWindow, text = questionsDict[qList[0]]["q"], font = helv15) qName.grid(row = 2, column = 0, sticky = "w", columnspan = 5) qDesc = tk.Label(mcWindow, text = "Make your choice!",font = helv15) qDesc.grid(row = 1, column = 0, sticky = "w", columnspan = 5) for i in range(1,5): buttonDict[i].config(text = questionsDict[qList[0]]["answers"][i]) title.grid(row = 0, column = 0, columnspan = 4) start() def doorGuesser(): # Python garbage collector goes ahead and gets rid of the image variables if they are local for whatever reason global dgWindow, door1_img, door2_img, door3_img dgWindow = tk.Toplevel() dgWindow.title("Door Guesser") dgWindow.geometry("500x300") def submit(choice): if choice in [1,3]: descLabel.config(text = "Wrong door! Try again.") descLabel.update() time.sleep(2) dgWindow.destroy() cf.dgGame_returnVal = 0 else: descLabel.config(text = "You chose the right door. Nice job!") descLabel.update() time.sleep(2) dgWindow.destroy() cf.dgGame_returnVal = 1 titleLabel = tk.Label(dgWindow, text = "Door Guesser", font = helv25) descLabel = tk.Label(dgWindow, text = "Choose the right door. May or may not lead to death.", font = helv15) # Create doors preDoor1_img = Image.open("door1.png") preDoor1_img = preDoor1_img.resize((60, 90), Image.ANTIALIAS) door1_img = ImageTk.PhotoImage(preDoor1_img) preDoor2_img = Image.open("door2.jpg") preDoor2_img = preDoor2_img.resize((60, 90), Image.ANTIALIAS) door2_img = ImageTk.PhotoImage(preDoor2_img) preDoor3_img = Image.open("door3.png") preDoor3_img = preDoor3_img.resize((60, 90), Image.ANTIALIAS) door3_img = ImageTk.PhotoImage(preDoor3_img) # Creates image labels door1 = tk.Button(dgWindow, image = door1_img, command = lambda: submit(1)) door2 = tk.Button(dgWindow, image = door2_img, command = lambda: submit(2)) door3 = tk.Button(dgWindow, image = door3_img, command = lambda: submit(3)) titleLabel.grid(row = 0, column = 0, sticky = "w", columnspan = 3) descLabel.grid(row = 1, column = 0, sticky = "w", columnspan = 3) door1.grid(row = 2, column = 0) door2.grid(row = 2, column = 1) door3.grid(row = 2, column = 2) def keyGet(): global kgWindow, key_img kgWindow = tk.Toplevel() kgWindow.title("Item get!") kgWindow.geometry("300x220") title = tk.Label(kgWindow, text = "Item Get!", font = helv25) subText = tk.Label(kgWindow, text = "You picked up a key!", font = helv20) exitButton = tk.Button(kgWindow, text = "Exit", font = helv15, command = kgWindow.destroy) preKey_img = Image.open("key.png") preKey_img = preKey_img.resize((150, 90), Image.ANTIALIAS) key_img = ImageTk.PhotoImage(preKey_img) keyLabel = tk.Label(kgWindow, image = key_img) title.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 1, column = 0, sticky = "w") keyLabel.grid(row = 2, column = 0, sticky = "w") exitButton.grid(row = 3, column = 0, sticky = "w") player.keyGot = 1 def lock(): global lWindow, lock_img lWindow = tk.Toplevel() lWindow.title("Lock") lWindow.geometry("300x300") def unlock(): if player.keyGot == 1: cf.lGame_returnVal = 1 lWindow.destroy() else: subText.config(text = "You don't seem to have the key!") subText.update() title = tk.Label(lWindow, text = "Lock!", font = helv25) subText = tk.Label(lWindow, text = "Hmm... do you have a key?", font = helv15) preLock_img = Image.open("lock.png") preLock_img = preLock_img.resize((150, 150), Image.ANTIALIAS) lock_img = ImageTk.PhotoImage(preLock_img) lockImg = tk.Button(lWindow, image = lock_img, command = unlock) title.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 1, column = 0, sticky = "w") lockImg.grid(row = 2, column = 0, sticky = "w") def winScene(): global fWindow fWindow = tk.Toplevel() fWindow.title("The End") fWindow.geometry("400x200") titleLabel = tk.Label(fWindow, text = "The End.", font = helv35) subText = tk.Label(fWindow, text = "Congratulations on finishing the game!", font = helv20) author = tk.Label(fWindow, text = "'RPG' by Bence Redmond") exitButton = tk.Button(fWindow, text = "Exit", font = helv20, command = fWindow.destroy) titleLabel.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 2, column = 0, sticky = "w") author.grid(row = 1, column = 0, sticky = "w") exitButton.grid(row = 3, column = 0, sticky = "w") class ToolTip(object): # Throws a lot of errors but works fine def __init__(self, widget, text): self.widget = widget self.text = text def enter(event): self.showTooltip() def leave(event): self.hideTooltip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) def showTooltip(self): if self.widget["state"] != "disabled": self.tooltipwindow = tw = tk.Toplevel(self.widget) tw.wm_overrideredirect(1) # Window without border and no normal means of closing tw.wm_geometry("+{}+{}".format(self.widget.winfo_rootx(), self.widget.winfo_rooty())) # Sets size of tooltip label = tk.Label(tw, text = self.text, background = "#ffffe0", relief = 'solid', borderwidth = 1) label.pack() tooltipList.append(self) def hideTooltip(self): for i in tooltipList: if i.widget["state"] == "disabled": i.tooltipwindow.destroy() tooltipList.remove(self) if self.widget["state"] != "disabled" or type(self.tooltipwindow) == "tkinter.TopLevel": if self in tooltipList: self.tooltipwindow.destroy() tooltipList.remove(self) self.tooltipwindow = None # Class to store player information class playerState(): def __init__(self, room, lives): self.room = room # Stores current room as an object self.lives = lives self.unlockedEndings = 0 # Dictionary to store different end conditions self.endDict = {0:{"name":"Death", "unlocked":False, "text":"Expected to be honest.", "room":"N/A", "c":"None!"}, 1:{"name":"Awkward...","unlocked":False, "text":"Well, you weren't supposed to do that.", "room":"Doorway", "c":"1"}, 2:{"name":"Scaredy Cat","unlocked":False, "text":"Hide from your fears.", "room":"Closet", "c":"9"}, 3:{"name":"Relaxation Time","unlocked":False,"text":"Sometimes you just need to sit back and relax.","room":"Theatre", "c":"7"}, 4:{"name":"Tasty!","unlocked":False, "text":"Too much food...","room":"Food Closet","c":"6"} } self.code = ["-","-","-","-"] self.keyGot = 0 def loseLife(self, lost): self.heartDict[self.lives].config(image = emptyHeart_img) self.lives -= lost if self.lives <= 0: displayEnd(player.endDict[0], 0) self.unlockEnding(0) self.lives = 3 for i in range(1,4): self.heartDict[i].config(image = heart_img) def resetGame(self, destroyWindow): # Closes the end screen window destroyWindow.destroy() # Resets the the rooms' text and puzzles createRooms() createNeighbours() player.room = startingRoom # Reloads the "map" startingRoom.initState() def unlockEnding(self, ending): # Checks if the ending has already been unlocked if self.endDict[ending]["unlocked"] != True: self.unlockedEndings += 1 self.endDict[ending].update({"unlocked":True}) if ending - 1 >= 0: self.code[ending-1] = self.endDict[ending]["c"] # Class used to create the rooms class room(): def __init__(self, puzzle, name, text, winText, loseText, code = 0): self.name = name self.puzzle = puzzle self.text = text # Text to display when the player enters a room self.loseText = loseText self.winText = winText self.code = code def assignNeighbours(self, left, right, up, down): # Stores the information about the room's neighbours, and the button object that leads to that room self.neighbours = {"left":{"button":leftArrow, "room":left}, "right":{"button":rightArrow, "room":right}, "up":{"button":upArrow, "room":up}, "down":{"button":downArrow, "room":down}} # Loads the room def initState(self): global secondLabel, interactButton, roomLabel, roomText # Edits the text to the appropriate room's roomLabel.config(text = player.room.name) roomText.config(text = player.room.text) # List to iterate through later dictList = ["left","right","up","down"] print("Initialized") for i in dictList: neighbour = self.neighbours[i] # Ease of access if neighbour["room"] == False: # Checks if there is a neighbouring room in that direction neighbour["button"].grid_remove() # neighbour["button"].config(state = "disabled", bg = "#ff8080") else: # If not, loads appropriately neighbour["button"].grid() if self.puzzle == "fin": # Checks if the player has completed the puzzle neighbour["button"].config(state = "active", bg = "white") idToolTip = ToolTip(neighbour["button"], text = neighbour["room"].name) print(idToolTip) else: if neighbour["room"].puzzle == "fin": neighbour["button"].config(state = "active", bg = "white") else: neighbour["button"].config(state = "disabled", bg = "#ff8080") if self.puzzle != "fin": # Checks to see if the interact button needs to be locked or not interactButton.config(state = "active", bg = "white") else: interactButton.config(state = "disabled", bg = "#ff8080") def moveRoom(self, direction): global roomLabel, roomText, tooltipList for i in tooltipList: i.tooltipwindow.destroy() tooltipList = [] player.room = self.neighbours[direction]["room"] # Sets the player's current room to the room at that given direction roomLabel.config(text = player.room.name) roomText.config(text = player.room.text) player.room.initState() # Handles puzzle loading and outcome determination def interact(self): global interactButton, roomText interactButton.config(state = "disabled") if player.room.puzzle == "gGame": guessingGame() root.wait_window(ngWindow) # Pauses the following code until the game window has been closed returnVal = cf.gGame_returnVal # Ease of use if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) # Edits the room text to be the win text interactButton.config(state = "active") player.room.puzzle = "fin" cf.gGame_returnVal = -1 # Resets cf.gGame_returnVal for future games (after in-game restart) elif returnVal == 0: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) player.room.initState() cf.gGame_returnVal = -1 elif player.room.puzzle == "ttt": # Follows same principles as above ticTacToe() root.wait_window(tttWindow) returnVal = cf.tttGame_returnVal if returnVal == "x": player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" elif returnVal == "o": player.room.text = player.room.loseText roomText.config(text = player.room.text) interactButton.config(state = "active") else: interactButton.config(state = "active") cf.tttGame_returnVal = 0 player.room.initState() elif player.room.puzzle == "code": codeEnter(player.room.code) root.wait_window(ceWindow) returnVal = cf.ceGame_returnVal if returnVal == "correct": player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" player.room.initState() elif player.room.puzzle == "wGame": wineGuesser() root.wait_window(wgWindow) returnVal = cf.wgGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.wgGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "mc": multipleChoice() root.wait_window(mcWindow) returnVal = cf.mcGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.mcGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "end": winScene() root.wait_window(fWindow) root.destroy() elif player.room.puzzle == "door": doorGuesser() root.wait_window(dgWindow) returnVal = cf.dgGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) keyGet() root.wait_window(kgWindow) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.dgGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "lock": lock() root.wait_window(lWindow) returnVal = cf.lGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.room.initState() elif player.room.puzzle == "none": player.room.puzzle = "fin" player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.initState() else: # If the puzzle is not any of the above, then it must be an ending. displayEnd(player.endDict[player.room.puzzle], player.room.puzzle) def createRooms(): # room() takes the puzzle, name of room, text to display when the player enters, text to display when the players loses/wins. global startingRoom, hallway1, doorway, kitchen, ballroom, hallway2, bossroom, slide, stairs1, basement, closet, stairs2, cellar, theatre, dining_room, hallway3, kitchen, closet2, hallway4, living_room startingRoom = room("gGame", "Entrance", "Ho ho ho... welcome to my house of Death!", "Hmm, maybe that was a bit too easy.", "Well that was a good effort... down one life!", "1976") hallway1 = room("ttt", "Hallway", "You see a whiteboard on the wall, with a Tic Tac Toe board. Let's play!", "I would have been worried if you hadn't won that.", "How did you... lose against yourself?") doorway = room(1, "Doorway", "Well, I guess you win?", "N/A", "N/A") ballroom = room("mc", "Ballroom", "Pop quiz! No dancing or music unfortunately.", "Maybe I should have made the questions a bit harder.", "You should brush up on your trivia.") hallway2 = room("code", "Hallway", "You here a faint hum ahead. Spooky.", "There's no turning back once you go forward.", "Go and explore more. Open up the endings screen to see what you have so far.", "1976") bossroom = room("end", "The Exit", "Damn you!", "Begone fool...", "Muahahaha! Try again.") slide = room("none", "Slide!", "Down you go!", "N/A", "N/A") stairs1 = room("gGame", "Basement Stairs", "The stairs lead down to a very dark room.", "I should stop using these number guessing games.", " Get good.") basement = room("none", "Basement", "Ahhhh! I'm joking. Why would I get scared in my own house?", "Well, you've still got a ways to go.", "Hahahahaha.") closet = room(2, "Closet", "Just hide and everything will be alright.", "N/A", "N/A") stairs2 = room("door", "Deeper Stairs", "These lead deeper down...", "Good luck in the next room. Hehehe...", "Come on. You just have to pick a door.") cellar = room("wGame", "Wine Cellar", "Ah, a proud collection. Don't touch anything!", "That was expensive...", "Serves you right!") theatre = room(3, "Theatre", "Sometimes it's nice to relax with some popcorn and watch a movie.", "N/A", "N/A") dining_room = room("none", "Dining Room", "Good luck finding your way through this maze of tables.", "What do you mean it was just a restaurant?.", "If you stick to the right it might work.") hallway3 = room("ttt", "Hallway", "Maybe this will stump you.", "Well, congrats. You've done the bare minimum.", "How...?") kitchen = room("none", "Kitchen", "Let's test your cooking skills.", "Ah... I may have forgotten to lay out the food. Forget this.", "How many times have you cooked in your life?") closet2 = room(4, "Food Closet", "Eat your problems away.", "N/A", "N/A") hallway4 = room("lock", "Hallway", "Good luck picking this!", "Darn it. I paid a lot for that lock.", "Hahah! Wait... where did I put that key?") living_room = room("none", "Living Room", "Let's watch some TV and relax.", "Do you mind getting some food?","Have you never used a remote in your life?") def createNeighbours(): global startingRoom, hallway1, doorway, kitchen # Assigns the room's neighbours as room objects # assignNeighbours(Left, Right, Up, Down) startingRoom.assignNeighbours(False, False, hallway1, doorway) doorway.assignNeighbours(False, False, startingRoom, False) hallway1.assignNeighbours(False, False, ballroom, startingRoom) ballroom.assignNeighbours(stairs1, dining_room, hallway2, hallway1) hallway2.assignNeighbours(slide, False, bossroom, ballroom) bossroom.assignNeighbours(False, False, False, hallway2) slide.assignNeighbours(basement, False, False, False) stairs1.assignNeighbours(basement, ballroom, False, False) basement.assignNeighbours(False, stairs1, closet, stairs2) closet.assignNeighbours(False, False, False, basement) stairs2.assignNeighbours(False, False, basement, cellar) cellar.assignNeighbours(False, theatre, stairs2, False) theatre.assignNeighbours(cellar, False, False, False) dining_room.assignNeighbours(ballroom, False, hallway3, hallway4) hallway3.assignNeighbours(False, False, kitchen, dining_room) kitchen.assignNeighbours(False, False, closet2, hallway3) closet2.assignNeighbours(False, False, False, kitchen) hallway4.assignNeighbours(False, False, dining_room, living_room) living_room.assignNeighbours(False, False, hallway4, False) createRooms() player = playerState(startingRoom, 3) # Handles the ending screen window def endingsScreen(endings): global endingsButton endingsButton.config(state = "disabled") endingsWin = tk.Toplevel() endingsWin.title("Your Unlocked Endings") endingsWin.geometry("650x500") codeText = "".join(player.code) endingsTitle = tk.Label(endingsWin, font = helv35, text = f"All Endings || {player.unlockedEndings}/{len(endings)} Unlocked") codeLabel = tk.Label(endingsWin, font = helv25, text = f"Code: {codeText}\n---------------------------------------") row = 2 # Used to iterate through the ending dictionary, and display each value there # This system doesn't require me to come back and edit when I need to add new endings for i in range(0,len(endings)): print(endings[i]) tempTitle = tk.Label(endingsWin, text = endings[i]["name"], font = helv25, anchor = "w") tempLabel = tk.Label(endingsWin, text = f"Unlocked: {endings[i]['unlocked']} || {endings[i]['text']}") tempTitle.grid(row = row, column = 0, sticky = "w") tempLabel.grid(row = row + 1, column = 0, sticky = "w") row += 2 endingsTitle.grid(row = 0, column = 0, columnspan = 2, sticky = "w") codeLabel.grid(row = 1, column = 0, columnspan = 2, sticky = "w") root.wait_window(endingsWin) # Waits until the player closes the ending screen endingsButton.config(state = "active") def displayMenu(): global endingsButton, restartButton menuWindow = tk.Toplevel() menuWindow.geometry("220x200") menuTitle = tk.Label(menuWindow, text = "Menu", font = helv35) endingsButton = tk.Button(menuWindow, text = "Unlocked Endings", font = helv20, command = lambda: endingsScreen(player.endDict)) restartButton = tk.Button(menuWindow, text = "Restart", font = helv20, command = lambda: player.resetGame(menuWindow)) menuTitle.pack() endingsButton.pack() restartButton.pack() # Initializes main images preHeart_img = Image.open("heart.png") preHeart_img = preHeart_img.resize((60, 60), Image.ANTIALIAS) preEmptyHeart_img = Image.open("emptyHeart.png") preEmptyHeart_img = preEmptyHeart_img.resize((60, 60)) emptyHeart_img = ImageTk.PhotoImage(preEmptyHeart_img) heart_img = ImageTk.PhotoImage(preHeart_img) # Creates the heart labels heart1 = tk.Label(root, image = heart_img, anchor = "w") heart2 = tk.Label(root, image = heart_img, anchor = "w") heart3 = tk.Label(root, image = heart_img, anchor = "w") player.heartDict = {1:heart1, 2:heart2, 3:heart3} # Creates main text roomLabel = tk.Label(root, text = player.room.name, font = helv35) roomText = tk.Label(root, text = player.room.text, font = helv20) secondLabel = tk.Label(root, text = "Choose a direction to go:", font = helv15) # Creates buttons menuButton = tk.Button(root, text = "Menu", font = helv25, borderwidth = 5, command = displayMenu) upArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "^", font = helv15, command = lambda: player.room.moveRoom("up")) leftArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "<", font = helv15, command = lambda: player.room.moveRoom("left")) downArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "v", font = helv15, command = lambda: player.room.moveRoom("down")) rightArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = ">", font = helv15, command = lambda: player.room.moveRoom("right")) interactButton = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "x", font = helv15, command = player.room.interact) # Creates empty canvas spaces topCanvas = tk.Canvas(root, width = 140, height = 10) # Displays the created widgets heart1.grid(row = 0, column = 0) heart2.grid(row = 0, column = 1) heart3.grid(row = 0, column = 2) roomLabel.grid(row = 0, column = 3, padx = 20) secondLabel.grid(row = 2, column = 0, columnspan = 3) topCanvas.grid(row = 0, column = 4, columnspan = 1) roomText.grid(row = 1, column = 0, columnspan = 8, sticky = "w") upArrow.grid(row = 3, column = 1) leftArrow.grid(row = 4, column = 0) downArrow.grid(row = 5, column = 1) rightArrow.grid(row = 4, column = 2) interactButton.grid(row = 4, column = 1) menuButton.grid(row = 0, column = 5) createNeighbours() startingRoom.initState() root.mainloop() # Starts main window
true
44eba16129c337868686be04717406aa01e38de0
Python
brianhu0716/LeetCode-Solution
/146. LRU Cache.py
UTF-8
901
3.078125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun May 23 23:44:11 2021 @author: brian.hu """ class LRUCache: def __init__(self, capacity: int): self.cashe = list() self.dict = dict() self.capacity = capacity def get(self, key: int) -> int: if key in self.dict : self.cashe.remove(key) self.cashe.append(key) return self.dict[key] return -1 def put(self, key: int, value: int) -> None: if key in self.dict : self.dict[key] = value self.cashe.remove(key) self.cashe.append(key) return if len(self.dict) >= self.capacity : rmv_key = self.cashe.pop(0) # cashe超出最大容量時,remove最不常用的key值 del self.dict[rmv_key] self.dict[key] = value self.cashe.append(key) return
true
361848aa469bb2e837e80d779b650418d0f7dcc8
Python
getabear/leetcode
/LCP 07. 传递信息.py
UTF-8
1,199
3.21875
3
[]
no_license
from typing import List # 提交通过,但是含有子问题,可以进行优化 class Solution1: def numWays(self, n: int, relation: List[List[int]], k: int) -> int: list=[[] for i in range(n)] for rel in relation: list[rel[0]].append(rel[1]) self.res=0 # addr:当前的位置 deep是调用的深度,也可以理解为路程 def dfs(addr,deep): if deep==k: if addr==n-1: self.res+=1 return for nextAddr in list[addr]: dfs(nextAddr,deep+1) dfs(0,0) return self.res class Solution: def numWays(self, n: int, relation: List[List[int]], k: int) -> int: #dp[i][j]代表第i轮,可以传到节点j的路径数 # 递推关系 dp[i][j]=dp[i-1][x] 其中x可以下一步到达节点j dp=[[0 for _ in range(n)] for i in range(k+1)] dp[0][0]=1 for i in range(1,k+1): for rela in relation: dp[i][rela[1]]+=dp[i-1][rela[0]] return dp[k][n-1] a=Solution() n = 5 relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]] k = 3 print(a.numWays(n,relation,k))
true
dfeb4cce82a25e82a5d2e737a8c0a4bdb4c989a1
Python
DWhistle/Python3
/Education/Books/PythonTricks/tricks/dicts.py
UTF-8
922
3.765625
4
[]
no_license
names = { 1 : 'Alice', 2 : 'Bob', 3 : 'Robert', } #straightforward dict search def greeting(userid): return f'Hey, {names[userid]}' print(greeting(2)) #default parameter def greeting(userid): return f'Hey, {names.get(userid, "everyone")}' print(greeting(22)) #sorting print(names) # could be not sorted by default #sorting by value sorted(names.items(), key=lambda x : x[1]) import operator #operators sorted(names.items(), key=operator.itemgetter(1)) #sorting by abs key in reversed sorted(names.items(), key=lambda x: abs(x[0])) #updating dicts d1 = {'1':'1', '2':2, '3':3} d2 = {'1':'1', '2':5, '3':3} d1.update(d2) #collision resolve by last addition print(d1) #more ways d3 = dict(d1, **d2) d4 = {**d1, **d2} print(d3,d4) #for better printing and serializing import json print(json.dumps(d1, indent=4)) #pprint for printing complex objs import pprint pprint.pprint({1: 2, 2: (1,2,3), 3: {1,2,3}})
true
cb42ada6ceb60f81ebd1c0502eb840df59935189
Python
doyacadoyaca/testy
/my_math.py
UTF-8
377
3.921875
4
[]
no_license
# funkcja która zwraca sumę i testy do niej def add(x, y): return x + y # funkcja która zwraca iloczyn i testy do niej def product(x, y): return x * y # fukcja która odwraca napis def words(string): return string[::-1] def sq(n): return n**2 # fukcja która sprawdza czy slowo jest palindromem def is_palindrom(word): return word == word[::-1]
true
d872e94cdb94844cad93cad2cc8f97dff842d6c1
Python
oli415/IoT-project
/raspberry_pi/websocket.py
UTF-8
1,389
2.578125
3
[]
no_license
import asyncio import websockets import comm URL = 'ws://79cb755.online-server.cloud:4567' class WebSocket: def __init__(self): #async with websockets.connect('ws://79cb755.online-server.cloud:4567') as websocket: self.ws = None self.loop = asyncio.new_event_loop() #perform a synchronous connect self.loop.run_until_complete(self.wsConnect()) async def wsConnect(self): print("attempting connection to {}".format(URL)) # perform async connect, and store the connected WebSocketClientProtocol object, for later reuse for send & recv self.ws = await websockets.connect(URL) print("connected") async def wsRun(self): while True: response = await self.ws.recv() print(response) if response == "LED = ON": comm.sendToArduino(b"#LED = ON#") if response == "LED = OFF": comm.sendToArduino(b"#LED = OFF#") async def wsSend(self, msg): await self.ws.send(msg) def start(self): self.loop.run_until_complete(self.wsRun()) def send(self, msg): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.wsSend(msg)) #asyncio.ensure_future(self.wsSend(msg)) #self.loop.run_until_complete(self.wsSend(msg)) #self.loop.run(self.wsSend(msg)) #task_obj = self.loop.create_task(self.wsSend(msg)) #self.loop.run_until_complete(task_obj)
true
5b4cd6785b5bac24a13d9ec6a6364551e354b566
Python
muodov/labs-translate
/server/yandex.py
UTF-8
1,380
2.609375
3
[ "MIT" ]
permissive
import os import requests YANDEX_API_KEY = os.getenv('YANDEX_API_KEY') LANG_CODES = [ 'az', 'be', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fi', 'fr', 'hr', 'hu', 'hy', 'it', 'lt', 'lv', 'mk', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sv', 'tr', 'uk' ] def translate(word, src=None, dest=None, logger=None): if src and src not in LANG_CODES: src = None if dest not in LANG_CODES: dest = 'en' translation_dir = (src + '-' + dest) if src else dest resp = requests.post( 'https://translate.yandex.net/api/v1.5/tr.json/translate', params={ 'key': YANDEX_API_KEY, 'lang': translation_dir, 'options': '1', # return detected language 'format': 'plain', 'text': word }, timeout=5 ) if resp.status_code == 200: r_data = resp.json() det_src = src or r_data['detected']['lang'] return { 'src': det_src, 'dst': dest, 'translation': r_data['text'][0], 'dictionary': det_src + '-' + dest, 'raw': r_data } else: if logger: logger.error('Translation error: %r', resp.text)
true
19d08c5ff28e1ad5f83b88b8d5b309730baee9bf
Python
ando-huang/ABSpython
/oswalk.py
UTF-8
399
4.0625
4
[]
no_license
import os #pass the path to a root folder os.walk("") #os.walk returns three things, foldername, subfolders, filenames #this loops runs through a tree of all the folders for folderName, subfolders, filenames in os.walk(""): print("The folder we are at is: " + folderName) print("The subfolders are : " + str(subfolders)) print("The files in folder are: " + str(filenames))
true
fae36f976fbbfc6fa24a684547d7b6e7a57d4dd4
Python
alchemyst/LoopRank
/ranking/controlranking.py
UTF-8
5,058
3.1875
3
[]
no_license
"""This method is imported by looptest @author: St. Elmo Wilken, Simon Streicher """ #from visualise import visualiseOpenLoopSystem from gainrank import GainRanking from numpy import array, transpose, arange, empty import networkx as nx import matplotlib.pyplot as plt from operator import itemgetter from itertools import permutations, izip import csv class LoopRanking: """This class: 1) Ranks the importance of nodes in a system with control 1.a) Use the local gains to determine importance 1.b) Use partial correlation information to determine importance 2) Determine the change of importance when variables change """ # TODO: Generalize alpha definition def __init__(self, fgainmatrix, fvariablenames, fconnectionmatrix, bgainmatrix, bvariablenames, bconnectionmatrix, nodummyvariablelist, alpha=0.35): """This constructor creates grapgs with associated node importances based on: 1) Local gain information 2) Partial correlation data """ self.forwardgain = GainRanking(self.normalise_matrix(fgainmatrix), fvariablenames) self.backwardgain = GainRanking(self.normalise_matrix(bgainmatrix), bvariablenames) self.create_blended_ranking(nodummyvariablelist, alpha) def create_blended_ranking(self, nodummyvariablelist, alpha=0.35): """This method creates a blended ranking profile of the object.""" self.variablelist = nodummyvariablelist self.blendedranking = dict() for variable in nodummyvariablelist: self.blendedranking[variable] = ((1 - alpha) * self.forwardgain.rankdict[variable] + (alpha) * self.backwardgain.rankdict[variable]) slist = sorted(self.blendedranking.iteritems(), key=itemgetter(1), reverse=True) for x in slist: print(x) print("Done with controlled importances") def normalise_matrix(self, inputmatrix): """Normalises the absolute value of the input matrix in the columns i.e. all columns will sum to 1. """ [r, c] = inputmatrix.shape inputmatrix = abs(inputmatrix) # Does not affect eigenvalues normalisedmatrix = [] for col in range(c): colsum = float(sum(inputmatrix[:, col])) for row in range(r): if (colsum != 0): normalisedmatrix.append(inputmatrix[row, col] / colsum) else: normalisedmatrix.append(0.0) normalisedmatrix = transpose(array(normalisedmatrix).reshape(r, c)) return normalisedmatrix def display_control_importances(self, nocontrolconnectionmatrix, controlconnectionmatrix): """This method will create a graph containing the connectivity and importance of the system being displayed. Edge Attribute: color for control connection Node Attribute: node importance """ nc_graph = nx.DiGraph() n = len(self.variablelist) for u in range(n): for v in range(n): if nocontrolconnectionmatrix[u, v] == 1: nc_graph.add_edge(self.variablelist[v], self.variablelist[u]) edgelist_nc = nc_graph.edges() self.control_graph = nx.DiGraph() for u in range(n): for v in range(n): if controlconnectionmatrix[u, v] == 1: if (self.variablelist[v], self.variablelist[u]) in \ edgelist_nc: self.control_graph.add_edge(self.variablelist[v], self.variablelist[u], controlloop=0) else: self.control_graph.add_edge(self.variablelist[v], self.variablelist[u], controlloop=1) for node in self.control_graph.nodes(): self.control_graph.add_node(node, nocontrolimportance= self.blendedranking_nc[node], controlimportance= self.blendedranking[node]) plt.figure("The Controlled System") nx.draw_circular(self.control_graph) def show_all(self): """This method shows all figures.""" plt.show() def exportogml(self): """This method will just export the control graphs to a gml file. """ try: if self.control_graph: print("control_graph exists") nx.write_gml(self.control_graph, "control_graph.gml") except: print("control_graph does not exist")
true
42d70600911004beee70920eb4dc47a675e607dd
Python
wabain/rstarc
/test/programs/runnable/logical_ops.py
UTF-8
1,915
3.484375
3
[]
no_license
#!/usr/bin/env python3 import os fname = os.path.basename(__file__) unary_ops = [ ('not', lambda x: not x), ] binary_ops = [ ('and', lambda x, y: x and y), ('or', lambda x, y: x or y), ('nor', lambda x, y: (not x) and (not y)), ] unary_inputs = [True, False] binary_inputs = [ (True, True), (False, True), (True, False), (False, False), ] prelude = f'''\ (NOTE: This is generated code. Apply changes to {fname} and recompile) (Test logic tables and short-circuiting) SayTrue takes ArgId say ArgId give back true SayFalse takes ArgId say ArgId give back false ''' def main(): print(prelude) generate_binary() generate_unary() def generate_binary(): for op, expected in binary_ops: for (in1, in2) in binary_inputs: base_id = f'{op}({int(in1)},{int(in2)})' arg1 = 'true' if in1 else 'false' fn2 = 'SayTrue' if in2 else 'SayFalse' arg2 = f'{fn2} taking " {base_id}: eval2"' exp = expected(in1, in2) true_indicator = ' ' if exp else '!' false_indicator = '!' if exp else ' ' print('if', arg1, op, arg2) print(f' say "{true_indicator} {base_id}: TRUE"') print('else') print(f' say "{false_indicator} {base_id}: FALSE"') print() def generate_unary(): for op, expected in unary_ops: for in_value in unary_inputs: base_id = f'{op}({int(in_value)})' arg = 'true' if in_value else 'false' exp = expected(in_value) true_indicator = ' ' if exp else '!' false_indicator = '!' if exp else ' ' print('if', op, arg) print(f' say "{true_indicator} {base_id}: TRUE"') print('else') print(f' say "{false_indicator} {base_id}: FALSE"') print() main()
true
dcc466c1c91736a2cd2c0481435a20aff64cfbd7
Python
adamadejska/Rosalind
/PHRE.py
UTF-8
445
2.703125
3
[]
no_license
# Given: A quality threshold, along with FASTQ entries for multiple reads # Return: The number of reads whose average quality is below the threshold from Bio import SeqIO fastq = "" below = 0 with open("rosalind_phre.txt", "rU") as handle: threshold = int(handle.readline()) for record in SeqIO.parse(handle, "fastq"): q = record.letter_annotations['phred_quality'] if (sum(q) / float(len(q))) < threshold: below += 1 print(below)
true
9072b7708998e57760710a2943e3b5e556f4225b
Python
UWPCE-PythonCert-ClassRepos/py220BV201901
/students/jjakub/lessons/lesson08/assignment/inventory.py
UTF-8
1,408
3.390625
3
[]
no_license
"""" Module to create and modify inventory invoice's that contain customer and rental information """ import csv def add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price): """ adds customer name and rental details to a csv file """ with open(invoice_file, mode="a", newline="") as csv_file: csv.writer(csv_file).writerow([customer_name, item_code, item_description, item_monthly_price]) def single_customer(customer_name, invoice_file): """ curried function to create an invoice for a single customer """ invoice_data = [] def create_invoice(inventory_file): # open csv invoice file and read data with open(invoice_file, mode="r", newline="") as csv_file: for row in csv_file: invoice_row = list(row.strip().split(',')) invoice_data.append(invoice_row) # open csv inventory file and write data with open(inventory_file, mode="a", newline="") as csv_file: for row in invoice_data: csv.writer(csv_file).writerow([customer_name, row[0], row[1], row[2]]) return create_invoice
true
f5ba98c7ac3cacf6dd1bddf73475dd61cc9361ec
Python
luisFebro/hangman-game_jogo-da-forc
/game-hangman.py
UTF-8
4,410
3.671875
4
[]
no_license
#By: Luis Febro #Goal: Hangman game with a robot character. You have to find the right answer for each question before your robot end up being hung tragically. #Date: 05/20/19 #Issues: if you guys know how to fix this box that appears at the beginning before it supossed to pop up, just let me know in the comments. If you are resolute of some other enhancements, I will be your ears. (= from random import choice print('') print('=-' * 20) print('{:-^30}'.format('HANGMAN GAME BY LUIS FEBRO')) print('=-' * 20) def body_hang(c): body1 = body2 = body3 = body4 = body5 = body6 = ' ' if c == 0: print('') elif c == 1: body1 = '(00)' elif c == 2: body1 = '(00)' body2 = ' ||' elif c == 3: body1 = '(00)' body2 = '||' body3 = 'o--' elif c == 4: body1 = '(00)' body2 = '||' body3 = 'o--' body4 = '--o' elif c == 5: body1 = '(00)' body2 = '||' body3 = 'o--' body4 = '--o' body5 = 'o/' elif c == 6: body1 = '(00)' body2 = '||' body3 = 'o--' body4 = '--o' body5 = 'o/' body6 = ' \\o' print('\n___________') print('| |') print(f'| {body1}') print(f'| {body3}{body2}{body4}') print(f'| {body5}{body6} ') print('|') print('|') print('') ################################################################ # DATA BASE - QUESTIONS AND HIDDEN ANSWERS (DO NOT CHEAT HERE (; ) ################################################################ # 5 questions (1st Hint keys followed by their respective Answers) database = ['A brazilian City', 'Rio de Janeiro', 'A color', 'Yellow', 'A movie', 'Batman', 'A book', 'Harry Potter', 'An occupation', 'Programmer'] #choosing data tips = choice(list(database[n] for n in range(0, len(database), 2))) #here we create only the tips data answers = database[database.index(tips) + 1].upper() hidden_ans = list(answers) discovered_letters = [] print(f'\nKEY HINT: {tips}') for l in range(0, len(hidden_ans)): discovered_letters.append(' -- ') cont = contover = amount = 0 print(f'The word has {len(hidden_ans)} letters. Lets get started!') body_hang(contover) print(' -- ' * len(hidden_ans), end = '') while True: user_letter = str(input('\nType a letter: ')).strip().upper() if user_letter == '': print("It seems like you didn't inserted a letter, pal") continue if user_letter[0] in '123456789': print('Common!!! Numbers are not allowed...just letters') continue if len(user_letter) > 1: print(f'Do you mean {user_letter[0]}, is it not? \nLets consider the first letter! (=') user_letter = user_letter[0] #user got one letter if user_letter in discovered_letters: print('You already put this letter. Try again!') continue if user_letter in hidden_ans: body_hang(contover) for l in range(0, len(hidden_ans)): #inserting the letter into empty list and replacing ' -- ' if hidden_ans[l] == user_letter: discovered_letters[l] = user_letter cont += 1 #printing the traces print(discovered_letters[l], end = ' ') # user not got any letter if cont == 0: contover += 1 body_hang(contover) print(' -- ' * len(hidden_ans), end = '') # gameover condition if contover == 6: body_hang(contover) print('\nGAME OVER!') break print('\nNope! ain\'t got this letter...Try again!') # renewed for a new counting # cont = 0 # results print('\nYou guessed {} letters so far! '.format(cont)) print(f'LEFT: {6 - contover} TRIES...') #Option to reveal word already with 4 traces left: if discovered_letters.count(' -- ') <= 4: final_word = ''.join(hidden_ans) final_word_user = ' ' while final_word_user not in 'YN': final_word_user = str(input('Do you already know the hidden word [Y/N]? ')).strip().upper() if final_word_user == 'Y': final_word_user = str(input('You can write over here: ')).strip().upper() if final_word == final_word_user: print('CONGRATS! YOU GOT IT!') break print('It seems not the right one...try again...') if ' -- ' not in discovered_letters: print('CONGRATS! YOU GOT IT!') break print('GAME IS OVER') # NOTES: # l means letters. this is requires in both for iteration
true
4cbd8d0c220ec3b9b045ec421e03f83d038f2eaa
Python
Velythyl/BrujinGraph
/main.py
UTF-8
13,781
3.25
3
[]
no_license
""" # test de colisions avec notre fonction de hashage import itertools alphabet = ['A', 'T', 'C', 'G'] str_tab = [] for i in itertools.product(alphabet, repeat = 6): str_tab.append(''.join(i)) print(len(str_tab)) from HashTab import HashTabADN test_set = str_tab[:2000] temp = HashTabADN(test_set, 6) temp.colision_test(test_set) """ # Function vraiment pas efficace: je le sais. Elle n'a besoin que de rouler une seule fois pour trouver les primes entre # 0 et 4^21 pour notre fonction de compression. Après, la liste de primes est mise en fichier. import gzip import multiprocessing as mp import time import BrujinGraph from BrujinGraph import DeBrujinGraph def read_zipped_fasta(path): with gzip.open(path, 'rt') as f: accession, description, seq = None, None, None for line in f: if line[0] == '>': # yield current record if accession is not None: yield accession, description, seq # start a new record accession, description = line[1:].rstrip().split(maxsplit=1) seq = '' else: seq += line.rstrip() def get_all_kmer(path): counter = 0 with gzip.open(path, 'rt') as f: for line in f: seqid, description = line[1:].rstrip().split(maxsplit=1) sequence = f.readline().rstrip() _ = f.readline() quality = f.readline().rstrip() for kmer in BrujinGraph.build_kmers(sequence): yield kmer print("\t", counter, "kmerised.") counter += 1 def read_fastq(path, only_seq=False): with gzip.open(path, 'rt') as f: for line in f: seqid, description = line[1:].rstrip().split(maxsplit=1) sequence = f.readline().rstrip() _ = f.readline() quality = f.readline().rstrip() if only_seq: yield sequence else: yield seqid, description, sequence, quality # Cette fonction initialise le pool de mp pour le hashage: on a besoin d'un semaphore pour se limiter contre main def _mp_init(semaphore_): global semaphore semaphore = semaphore_ # Cette fonction hash tous les kmers pouvant etre tires d'un string def _mp_hash_mapper(string): semaphore.acquire() kmer_list = [] for kmer in BrujinGraph.build_kmers(string): kmer_list.append(BrujinGraph.hash(kmer)) return kmer_list # Cette fonction initialise le pool qui parcours le graph: elle a besoin du graph def _mp_init_walk(graph_): global graph graph = graph_ # Pourquoi ne pas simplement retourner temp ssi il n'a pas de predecesseurs? Etrangement, les fonctions de mappage de mp # Retournent TOUJOURS un element, meme si on n'en retourne pas. De cette facon-ci, si temp_start n'est pas vraiment un # start, on retourne une liste vide! Comme ca, lorsqu'on construira la liste de starts, on aura simplement rien dans la # liste. def _mp_get_starts(ele): temp_list = [] temp_start = BrujinGraph.unhash(ele) if len(graph.predecessors(temp_start)) == 0: temp_list.append(temp_start) return temp_list # Cette fonction parcours le graph a partir d'un point start def _mp_walk_mapper(start): temp_set = set() temp_set.add(start) contig_list = [] for contig in graph._walk(start, temp_set, start): contig_list.append(contig) return contig_list def _mp_comp_mapper(triple): occurence_list = [] for triple2 in read_zipped_fasta("GCF_000002985.6_WBcel235_rna.fna.gz"): contig = triple[2] start = triple2[2].find(contig) if start == -1: continue start += 1 end = len(contig) + start occurence_list.append(str(triple2[0]) + "\t" + str(start) + "\t" + str(end) + "\t" + str(triple[0]) + "\n") return occurence_list use_mp = True if __name__ == '__main__': start = time.time() # print(sys.getsizeof(786945046841)) # print(sys.getsizeof("ATGCGAGTCTCCACGTCAGTC")) graph = None if use_mp: # Pourquoi est-ce que les methodes de mp sont dans main.py? # # Python gere mal le multiprocessing. Lorsque les threads de mp requierent des methodes provenant d'une instance # il y a une explosion de memoire. Ceci est arrangeable avec des methodes statiques ou des fonctions, mais en # instanciant le pool de mp dans le DeBrujinGraph, on gardait quand meme une copie en memoire de l'instance dans # chaque process. Donc, on les instancie ici. # # Cependant, on a besoin d'un sephamore: meme si hash est la methode la plus lente, on se retrouve avec trop # de kmer hashes pour la methode add_hashed_node_list: il y a explosion de memoire ici aussi. On ne peut pas # instancier le pool ici avec son sephamore et utiliser ce dernier dans DeBrujinGraph: python dit qu'il ne # reconnait pas le "name sephamore"... Le plus simple est donc de hasher ici et de passer le resultat au # graph, meme si c'est un peu moins propre. # # Logique du mp: le pool hashe les kmer des noms et retourne une liste de hash par nom. Le process main itere # sur ces hash et les ajoute au graph avec add_hashed_node_list, qui teste tous les nodes et les ajoute au # hash_table ssi le hash n'y est pas deja cpu_nb = min(mp.cpu_count(), 3) # On veut un core juste pour add_hashed_node_list (donc qui traite le resultat # des autres), et max 3 (car teste avec 3 pour sephamore=2000) # https://stackoverflow.com/questions/40922526/memory-usage-steadily-growing-for-multiprocessing-pool-imap-unordered semaphore = mp.Semaphore(2000) pool = mp.Pool(cpu_nb, initializer=_mp_init, initargs=(semaphore,)) graph = DeBrujinGraph() # Note sur le counter et son impression: au debut, ils etaient la pour montrer le progres du programme lors du # debugage. Lorsqu'on a voulu les enlever une fois cette partie terminee, on s'est rendues compte qu'en fait le # programme va plus vite AVEC ces instructions de plus que SANS! # # Apres avoir enleve les incrementations de counter, on se rend compte qu'en fait c'est print qui importe. Les # operations sur counter on ete laissees pour montrer des traces de notre demarche... # # Voir la fin du rapport pour plus de details. #counter = 0 # Traces de counter iterator = pool.imap_unordered(_mp_hash_mapper, read_fastq('reads.fastq.gz', True), chunksize=500) pool.close() for node_list in iterator: graph.add_hashed_node_list(node_list) print("\tadded") # Rend plus rapide... decommenter au besoin #counter += 1 # Traces de counter semaphore.release() #if counter == 100: break # Si jamais on veut seulement un subset pool.terminate() else: print("FASTA loaded. Building graph...") graph = DeBrujinGraph(get_all_kmer('reads.fastq.gz')) print("Graph built in", time.time() - start, "seconds.") # build_id genere des id uniques id_counter = 0 def build_id(): global id_counter temp = str(id_counter) while len(temp) < 10: temp = "0" + temp id_counter += 1 return temp # Cette fonction append un contigs.fa avec une "batch" de contigs def contig_to_file(batch): with open("contigs.fa", "a") as file: file.write(batch) with open("contigs.fa", "w") as file: file.write("") # wipes previous file counter = 0 # Nombre de contigs pris batch = "" # Batch initialement vide batch_size = 5000 # Nombre de contigs a prendre avant de les sauvegarder sur le fichier print("Walking graph...") if use_mp: start = time.time() # Ici, c'est le contraire de lorsqu'on utilise le mp pour le hashing: on VEUT que le graph se partage # On pourrait donc s'attendre a ce qu'en placant les methodes dans DeBrujinGraph on obitenne le resultat # escompte. # # Oui, le graph se partage de cette facon, mais il doit se re-partager periodiquement, produisant BEAUCOUP # d'overhead. En placant le graph comme parametre d'initialisation (dans initargs), on ne fait le partage qu'une # seule fois et tout fonctionne. Les methodes de cette mp sont donc aussi dans main pour eviter le overhead # # Logique de cette mp: le pool s'occupe de parcourir le graphe a partir des starts. Pour ce faire, on commence # par lui demander de produire la liste de starts du graph. Le pool utilise la meme logique que get_all_starts # de DeBrujinGraph, mais au lieu de yield chaque start il retourne une liste de liste de starts. Cette liste de # liste sera transformee en une liste propre plus tard. # # Une fois la liste de starts obtenue, il va appliquer _mp_walk_mapper, une methode de map qui appelle en fait # _walk sur chaque start a mapper. Cette methode retourne une list de list de contig. cpu_nb = mp.cpu_count() - 1 # - 1 car previent de foncer dans le 100% CPU usage et de ralentir l'operation # d'ecriture pool = mp.Pool(cpu_nb, initializer=_mp_init_walk, initargs=(graph,)) # Transformation de la liste de listes de starts en la liste des starts start_list = [] for temp_list in pool.imap_unordered(_mp_get_starts, graph.hash_table, chunksize=500): for temp_start in temp_list: start_list.append(temp_start) print("\tStart found...") # Rend plus rapide (voir premiere mp) iterator = pool.imap_unordered(_mp_walk_mapper, start_list, chunksize=500) pool.close() # Pour chaque contig dans les listes de contigs retournees par _mp_walk_mapper, on accumule les contigs et on # les met en fichier lorsqu'on en a 500. for contig_list in iterator: for contig in contig_list: print("\tContig added to batch") # Rend plus rapide (voir premiere mp) batch += ">" + build_id() + " DESCRIPTION\n" + contig + "\n" counter += 1 if counter >= batch_size: contig_to_file(batch) batch = "" counter = 0 pool.terminate() else: start = time.time() for ele in graph.walk(): batch += ">" + build_id() + " DESCRIPTION\n" + ele + "\n" counter += 1 if counter >= batch_size: contig_to_file(batch) batch = "" counter = 0 if counter < batch_size: contig_to_file(batch) print("Graph walked in", time.time() - start, "seconds.") def read_fasta(path): with open(path, 'rt') as f: accession, description, seq = None, None, None for line in f: if line[0] == '>': # yield current record if accession is not None: yield accession, description, seq # start a new record accession, description = line[1:].rstrip().split(maxsplit=1) seq = '' else: seq += line.rstrip() # Cette fonction append un occrences.bed avec une "batch" d'occurences def occurence_to_file(batch): with open("occurences.bed", "a") as file: file.write(batch) with open("occurences.bed", "w") as file: file.write("") # wipes previous file print("Comparing contigs...") start = time.time() accumulator = 0 batch = "" if use_mp: cpu_nb = mp.cpu_count() - 1 # - 1 car previent de foncer dans le 100% CPU usage et de ralentir l'operation # d'ecriture pool = mp.Pool(cpu_nb) def call_mp(triple_list): global batch, accumulator iterator = pool.imap_unordered(_mp_comp_mapper, triple_list, chunksize=500) for occurence_list in iterator: for occurence in occurence_list: batch += occurence accumulator += 1 print("\tOccurence added to batch") # rend plus rapide (voir premiere mp) if accumulator >= batch_size: occurence_to_file(batch) accumulator = 0 batch = "" triple_list = [] for triple in read_fasta("contigs.fa"): triple_list.append(triple) if len(triple_list) >= (cpu_nb*500): call_mp(triple_list) triple_list = [] if len(triple_list) < (cpu_nb*500): call_mp(triple_list) pool.close() pool.terminate() else: for triple in read_fasta("contigs.fa"): for triple2 in read_zipped_fasta("GCF_000002985.6_WBcel235_rna.fna.gz"): contig = triple[3] start_index = triple2[3].find(contig) if start_index == -1: continue start_index += 1 end = len(contig) + start_index batch += str(triple2[1])+"\t"+str(start_index)+"\t"+str(end)+"\t"+str(triple[1])+"\n" accumulator += 1 if accumulator >= batch_size: occurence_to_file(batch) accumulator = 0 if accumulator < batch_size: occurence_to_file(batch) print("Occurences found in", time.time() - start, "seconds.")
true
a2f99462a5d8f31e79f3766a1965b7ca70e2231b
Python
meeththakkar/python-tutorial
/tutorial-programms/advanced-tutorials-code/async-write.py
UTF-8
676
3.421875
3
[]
no_license
import threading import time class AsyncfileWriter(threading.Thread): def __init__(self,text,outfile): threading.Thread.__init__(self) self.text = text self.outfile = outfile def run(self): f = open(self.outfile, "w") f.write(self.text) f.close() time.sleep(2) print("finished background file write"+ self.outfile) def main(): message = input("enter a string to store") out = input("enter file name ") background = AsyncfileWriter(message,out) background.start() print("programm can continue while it writes in another thread") background.join() print("everyting is done now .. all thread completed") if __name__ == "__main__": main()
true
485fdd494de760439967902076be00065b733393
Python
mizalets/myhackathon
/tests/test.py
UTF-8
1,814
3.5
4
[]
no_license
from mypackage import recursion, sorting def sum_array_test(array): """ make sure sum_array works correctly """ assert recursion.sum_array([8, 3, 2, 7, 4]) == 24, 'incorrect' assert recursion.sum_array([10, 1, 12]) == 23, 'incorrect' assert recursion.sum_array([1, 2, 3, 4, 5, 6]) == 21, 'incorrect' def fibonacci_test(n): """ returns nth term in fibonacci sequence """ assert recursion.fibonacci(2) == 1, 'incorrect' assert recursion.fibonacci(5) == 5 , 'incorrect' assert recursion.fibonacci(10) == 55, 'incorrect' def factorial_test(n): """ retruns n! """ assert recursion.factorial(5) == 120, 'incorrect' assert recursion.factorial(11) ==39916800 , 'incorrect' assert recursion.factorial(7) == 5040, 'incorrect' def reverse_test(word): """ returns word in reverse """ assert recursion.reverse(nakedi) == idekan, 'incorrect' assert recursion.reverse(evol) ==love, 'incorrect' assert recursion.reverse(madam) == madam, 'incorrect' def bubble_sort_test(items): assert sorting.bubble_sort([50,30,40,10,20]) == [10,20,30,40,50], 'incorrect' assert sorting.bubble_sort([9,8,7]) == [7,8,9], 'incorrect' assert sorting.bubble_sort([10,4,2,0]) == [0,2,4,10], 'incorrect' def merge_sort_test(items): assert sorting.merge_sort([77,31,45,55,10]) == [10, 31,45,55, 77, 93], 'incorrect' assert sorting.merge_sort([3, 1, 2]) == [1,2,3], 'incorrect' assert sorting.merge_sort([5,12,78,1,2,6]) == [1,2,5,6,12,78], 'incorrect' def quick_sort_test(items): assert sorting.quick_sort([77,31,44,55,20]) == [31, 44, 54, 55, 77], 'incorrect' assert sorting.quick_sort([31, 21, 23]) == [21,23,31], 'incorrect' assert sorting.quick_sort([5,12,78,1]) == [1,5,12,78], 'incorrect'
true
1ea35de8e9204ef70c9696466747eb27746d3295
Python
shubee17/Algorithms
/Array_Searching/max_diff_subs.py
UTF-8
351
3.25
3
[ "MIT" ]
permissive
# Maximum difference between two subsets of m elements import sys def max_diff_subs(Array,k): Array.sort() # Use Merge Sort j = len(Array) - 1 maxi = mini = 0 for i in range(int(k)): mini += Array[i] maxi += Array[j] j -= 1 print maxi - mini Array = sys.argv[1] k = sys.argv[2] Array = map(int, Array.split(",")) max_diff_subs(Array,k)
true
d5e42cf38ae89a9afb9dfc6d73307f96a0ff763a
Python
A-meerdervan/A3CcapitaSelectaRarm
/PongImplementation/FilesFromPreviousPongAML/MOVErunBotagainstBot.py
UTF-8
3,610
2.96875
3
[]
no_license
""" Created on Wed Oct 3 15:12:43 2018 @author: Alex """ import MyPong # My PyGame Pong Game #import MyAgent # My DQN Based Agent import SimpleBot #import SelfplayAgent # previous version of DQN agent import numpy as np #import random #import matplotlib.pyplot as plt from GlobalConstants import gc # SEE GLOBALCONSTANTS.py # For hyperparameters # ======================================================================= # Normalise GameState def CaptureNormalisedState(PlayerYPos, OppYpos, BallXPos, BallYPos, BallXDirection, BallYDirection): gstate = np.zeros([gc.STATECOUNT]) gstate[0] = PlayerYPos/gc.NORMALISATION_FACTOR # Normalised PlayerYPos gstate[1] = OppYpos/gc.NORMALISATION_FACTOR # Normalised OpponentYpos gstate[2] = BallXPos/gc.NORMALISATION_FACTOR # Normalised BallXPos gstate[3] = BallYPos/gc.NORMALISATION_FACTOR # Normalised BallYPos gstate[4] = BallXDirection/1.0 # Normalised BallXDirection gstate[5] = BallYDirection/1.0 # Normalised BallYDirection return gstate # ========================================================================= def PlayGame(TheAgent, OpponentAgent, renderScreen): GameTime = 0 #Create our PongGame instance TheGame = MyPong.PongGame(OpponentAgent.type) # Initialise Game if renderScreen: TheGame.InitialDisplay() GameState = CaptureNormalisedState(200.0, 200.0, 200.0, 200.0, 1.0, 1.0) GameStateOpp = CaptureNormalisedState(200.0, 200.0, 200.0, 200.0, 1.0, 1.0) #reset scores and game stats MyPong.gameStats.resetVariables() [scoreAI, scoreOld] = MyPong.gameStats.getScore() while (scoreAI < gc.GAME_POINTS_WIN and scoreOld < gc.GAME_POINTS_WIN): # Determine next action from opponent OpponentAction = OpponentAgent.Act_Mature(GameStateOpp) # Determine Next Action From the Agent BestAction = TheAgent.Act_Mature(GameState) # TODO dit terug veranderen. [ReturnScore,PlayerYPos, OppYPos, BallXPos, BallYPos, BallXDirection, BallYDirection]= TheGame.PlayNextMove(BestAction, OpponentAction, GameTime) GameStateOpp = CaptureNormalisedState(OppYPos, PlayerYPos, BallXPos, BallYPos, BallXDirection, BallYDirection) GameState = CaptureNormalisedState(PlayerYPos, OppYPos, BallXPos, BallYPos, BallXDirection, BallYDirection) # update score [scoreAI, scoreOld] = MyPong.gameStats.getScore() # Move GameTime Click GameTime = GameTime+1 # Periodically check if the game window was closed, if so, quit. if GameTime % 200 == 0: if TheGame.hasQuit(): # Close the pygame window TheGame.quit_() # Save game statistics MyPong.gameStats.addGameTime(GameTime) # TODO dit verwijderen als het zonder goed blijkt te werken # Only save if iteration > 0 , in the TestAgent file, -1 is used for the iteration #if (iteration >= 0): # MyPong.gameStats.saveStatsIteration(gc.CSV_FILE_PATH) if (scoreAI == gc.GAME_POINTS_WIN): return [scoreAI,scoreOld,1] else: return [scoreAI,scoreOld,0] def main(): renderScreen = True botType = 10 #Play two bots against eachother oppAgent = SimpleBot.SimpleBot(botType) theAgent = oppAgent PlayGame(theAgent, oppAgent, renderScreen) if __name__ == "__main__": try: main() if gc.RENDER_SCREEN: MyPong.quit_() except: print("Unexpected error") #Quit the pygame window if gc.RENDER_SCREEN: MyPong.quit_() raise
true
61ba13b218e1d98e4c99b3427391e711df2662ca
Python
detiuaveiro/trabalho-de-grupo-sokoban-93305_93301
/tree_search.py
UTF-8
4,772
2.859375
3
[ "MIT" ]
permissive
from abc import ABC, abstractmethod from state import * import asyncio from transposition_table import * from queue import PriorityQueue A_STAR_STRATEGY = True GREEDY_STRATEGY = False class SearchDomain(ABC): @abstractmethod def __init__(self): pass @abstractmethod def actions(self, state): pass @abstractmethod def result(self, state, action): pass @abstractmethod def cost(self, state, action): pass @abstractmethod def heuristic(self, state, goal): pass @abstractmethod def satisfies(self, state, goal): pass class SearchProblem: def __init__(self, domain, initial_state, goal): self.domain = domain self.initial_state = initial_state self.goal = goal self.goal.sort() def goal_test(self, state): return self.domain.satisfies(state.boxes, self.goal) class SearchNode: def __init__(self, state, path, parent, depth, cost, heuristic, reacheable_positions): self.state = state self.parent = parent self.depth = depth self.cost = cost self.heuristic = heuristic self.path = path self.reacheable_positions = reacheable_positions self.priority = heuristic + cost def __str__(self): return f"no(State Keeper: {self.state_keeper}, State Boxes: {self.state_boxes}, Depth: {self.depth}, Parent: {self.parent})" def __lt__(self, other): return self.priority < other.priority def __repr__(self): return str(self) class SearchNodeGreedy(SearchNode): def __init__(self, state, path, parent, depth, cost, heuristic, reacheable_positions): super().__init__(state, path, parent, depth, cost, heuristic, reacheable_positions) self.priority = heuristic class SearchTree: def __init__(self, problem, strategy=A_STAR_STRATEGY): self.strategy = strategy self.problem = problem root = SearchNode(problem.initial_state, None, None, 0, 0, self.problem.domain.heuristic(problem.initial_state.boxes, problem.goal), self.problem.domain.logic.reacheable_positions(problem.initial_state.keeper, problem.initial_state.boxes)) self.transposition_table = TranspositionTable(problem.domain.logic.area) self.open_nodes = PriorityQueue() self.open_nodes.put( root ) self.solution = None def get_path(self,node): if node.parent == None: return [node.state.keeper] path = self.get_path(node.parent) path.extend(node.path) return path @property def length(self): return self.solution.depth async def search(self, steps): step = 0 while not self.open_nodes.empty(): if (not steps.empty()): step = await steps.get() await asyncio.sleep(0) node = self.open_nodes.get() if self.problem.goal_test(node.state): self.solution = node return self.get_path(node) lnewnodes = [] if(self.strategy != GREEDY_STRATEGY and step >=1500): self.strategy = GREEDY_STRATEGY nQueue = PriorityQueue() while not self.open_nodes.empty(): await asyncio.sleep(0) node = self.open_nodes.get() nQueue.put(SearchNodeGreedy(node.state, node.path, node.parent, node.depth, node.cost, node.heuristic, node.reacheable_positions)) self.open_nodes = nQueue for a in self.problem.domain.actions(node.state, node.reacheable_positions): newstate, reacheable_positions = self.problem.domain.result(node.state, a) if(self.strategy == GREEDY_STRATEGY): newnode = SearchNodeGreedy(newstate, a[1], node, node.depth + 1, node.cost + self.problem.domain.cost(node.state,a), self.problem.domain.heuristic(newstate.boxes, self.problem.goal), reacheable_positions) else: newnode = SearchNode(newstate, a[1], node, node.depth + 1, node.cost + self.problem.domain.cost(node.state,a), self.problem.domain.heuristic(newstate.boxes, self.problem.goal), reacheable_positions) if not self.transposition_table.in_table(newnode.state): self.transposition_table.put(newnode.state) lnewnodes.append(newnode) self.add_to_open(lnewnodes) return self.get_path(node) def add_to_open(self,lnewnodes): for node in lnewnodes: self.open_nodes.put(node)
true
b7a31a92cf9e1874c365029185c3bfe865c34579
Python
durant35533/Python
/Soma.py
UTF-8
147
3.90625
4
[]
no_license
n1=int(input('Digite um número:')) n2=int(input('Digite outro número:')) s=n1+n2 print('A soma entre {} e o número {} vale:{}'.format(n1,n2,s))
true