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
28fa8cae1e39309d07173657d7c0bcbccc125cd2
Python
alisson-fs/POO-II
/Lista de exercicios 1/Q6.py
UTF-8
1,622
3.953125
4
[]
no_license
#Aluno: Alisson Fabra da Silva Matricula: 19200409 '''Neste exercício criei apenas a classe baralho que recebe uma lista de cartas, para que possa ser utilizado para qualquer tipo de baralho. Criei um metodo para distribuir as cartas e outro para mostrar a carta de cada jogador.''' from random import randint class Baralho: def __init__(self, cartas: list): self.__cartas = cartas def distribuir(self, quantidade_cartas, quantidade_jogadores): cartas_distribuidas = [] jogador = [] for i in range(quantidade_jogadores): for j in range(quantidade_cartas): carta_aleatoria = randint(0, len(self.__cartas)) jogador.append(self.__cartas[carta_aleatoria]) del self.__cartas[carta_aleatoria] cartas_distribuidas.append(jogador) jogador = [] return cartas_distribuidas def mostrar_cartas(self, jogador, cartas_distribuidas): print(f'Jogador {jogador}: {cartas_distribuidas[jogador - 1]}') def main(): naipes = ['OURO', 'ESPADA', 'COPAS', 'PAUS'] numeros = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] cartas = [] for i in naipes: for j in numeros: cartas.append([f'{i} - {j}']) copag = Baralho(cartas) cartas_distribuidas = copag.distribuir(3, 5) copag.mostrar_cartas(1, cartas_distribuidas) copag.mostrar_cartas(2, cartas_distribuidas) copag.mostrar_cartas(3, cartas_distribuidas) copag.mostrar_cartas(4, cartas_distribuidas) copag.mostrar_cartas(5, cartas_distribuidas) main()
true
63ca5d9e9eee13486456639b77f0c0c95a86d6a7
Python
dingdian110/alpha-ml
/alphaml/datasets/cls_dataset/mushroom.py
UTF-8
337
2.6875
3
[ "BSD-3-Clause" ]
permissive
import pandas as pd def load_mushroom(data_folder): file_path = data_folder + 'dataset_24_mushroom.csv' data = pd.read_csv(file_path, delimiter=',').values return data[:, 1:], data[:, 0] if __name__ == '__main__': x, y = load_mushroom('/home/thomas/PycharmProjects/alpha-ml/data/cls_data/mushroom/') print(x[:2])
true
95f1d6bc9e121484487a245c1c47237f1593f658
Python
DmitryChitalov/Interview
/lesson_2/task_3.py
UTF-8
883
3.78125
4
[]
no_license
# 3. Усовершенствовать родительский класс таким образом, чтобы получить доступ к защищенным переменным. # Результат выполнения заданий 1 и 2 должен быть идентичным. data = dict(name='Bred', price=42) class ItemDiscount: def __init__(self, name, price): self.__name = name self.__price = price @property def get_name(self): return self.__name @property def get_price(self): return self.__price class ItemDiscountReport(ItemDiscount): def __init__(self, name, price): super().__init__(name, price) def get_parent_data(self): return f'label: {self.get_name}\tprice: {self.get_price}' a = ItemDiscount(**data) r = ItemDiscountReport(**data) print(r.get_parent_data())
true
64f512827d311b6fa54f98f9c5aca4161d843984
Python
a01633908/m-todosn
/vowel.py
UTF-8
133
3.65625
4
[]
no_license
def count_vowels(txt): vowels = ['a','e','i','o','u'] v = 0 for p in txt: if p in vowels: v += 1 return v
true
027bd9447a7b8ad66065475cc9916ceba37da3cc
Python
Nooralwachi/runtime
/runtime.py
UTF-8
885
2.59375
3
[]
no_license
from datetime import datetime, timedelta def runtime(filename): process ={} with open(filename) as file: file.readline() for line in file: result = [] time,date, pid, status = line.split() process_time = datetime.strptime(time+ ' '+date, '%H:%M:%S %m/%d/%Y') #print(process_time, pid, status) if status == 'start': process[pid] =[status, process_time, timedelta(0)] elif status == 'pause' and pid in process.keys(): #print(process) process[pid] =[status, process_time, process_time - process[pid][1]] elif status == 'resume' and pid in process.keys(): #print(process) process[pid][0],process[pid][1] =status,process_time elif status == 'exit' and pid in process.keys(): time = process_time- process[pid][1] process[pid] =[status, process_time,process[pid][2] +time] print(pid,str(process[pid][2])) runtime('pid.txt')
true
098e10680eacbe906cb1c83770f452aa847d29f5
Python
Corona-/Tower-of-dragon
/shop_window.py
UTF-8
23,316
2.640625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame from pygame.locals import * import window import system_notify import character_view import item import shop TITLE, CITY, BAR, INN, SHOP, TEMPLE, CASTLE, TOWER, STATUS_CHECK, GAMEOVER = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) CHARACTER_MAKE = 10 NO_EXTRA, CHARACTER_VIEW, PARTY_REMOVE, CHARACTER_CHECK = 100, 101, 102, 103 SCREEN_RECTANGLE = Rect(0,0,640,480) COLOR_BLACK = (0,0,0) COLOR_GLAY = (128,128,128) COLOR_WHITE = (255,255,255) class Shop_window(window.Window): SWORD, KATANA, BLUNT, GUN, THROW = 0, 1, 2, 3, 4 SHIELD, ARMOR, HELMET, GAUNTLET, ACCESSORY = 5, 6, 7, 8, 9 ITEM = 10 MENU_MAX = 10 def __init__(self, rectangle): window.Window.__init__(self, rectangle) self.is_visible = False self.menu = 0 self.top = rectangle.top self.left = rectangle.left self.right = rectangle.right self.centerx = rectangle.centerx self.menu_font = pygame.font.Font("ipag.ttf", 20) self.top_font = self.menu_font.render( u"何が欲しいんだい?", True, COLOR_WHITE) self.sword_font = self.menu_font.render( u"剣", True, COLOR_WHITE) self.katana_font = self.menu_font.render( u"刀", True, COLOR_WHITE) self.blunt_font = self.menu_font.render( u"鈍器", True, COLOR_WHITE) self.gun_font = self.menu_font.render( u"銃", True, COLOR_WHITE) self.throw_font = self.menu_font.render( u"投擲", True, COLOR_WHITE) self.shield_font = self.menu_font.render( u"盾", True, COLOR_WHITE) self.armor_font = self.menu_font.render( u"鎧", True, COLOR_WHITE) self.helmet_font = self.menu_font.render( u"兜", True, COLOR_WHITE) self.gauntlet_font = self.menu_font.render( u"篭手", True, COLOR_WHITE) self.accessory_font = self.menu_font.render( u"アクセサリー", True, COLOR_WHITE) self.item_font = self.menu_font.render( u"アイテム", True, COLOR_WHITE) self.buy_window = Buy_window(Rect(120, 50, 400, 360)) def draw( self, screen, game_self): """draw the shop window on screen""" if self.is_visible == False: return window.Window.draw(self, screen) screen.blit( self.top_font, ((self.centerx-self.top_font.get_width()/2), 60)) if self.menu == self.SWORD: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 95, 232, 30), 0) if self.menu == self.KATANA: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 125, 232, 30), 0) if self.menu == self.BLUNT: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 155, 232, 30), 0) if self.menu == self.GUN: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 185, 232, 30), 0) if self.menu == self.THROW: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 215, 232, 30), 0) if self.menu == self.SHIELD: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 245, 232, 30), 0) if self.menu == self.ARMOR: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 275, 232, 30), 0) if self.menu == self.HELMET: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 305, 232, 30), 0) if self.menu == self.GAUNTLET: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 335, 232, 30), 0) if self.menu == self.ACCESSORY: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 365, 232, 30), 0) if self.menu == self.ITEM: pygame.draw.rect(screen, COLOR_GLAY, Rect(204, 395, 232, 30), 0) screen.blit(self.sword_font, ((self.centerx-self.sword_font.get_width()/2), 100)) screen.blit(self.katana_font, ((self.centerx-self.katana_font.get_width()/2), 130)) screen.blit(self.blunt_font, ((self.centerx-self.blunt_font.get_width()/2), 160)) screen.blit(self.gun_font, ((self.centerx-self.gun_font.get_width()/2), 190)) screen.blit(self.throw_font, ((self.centerx-self.throw_font.get_width()/2), 220)) screen.blit(self.shield_font, ((self.centerx-self.shield_font.get_width()/2), 250)) screen.blit(self.armor_font, ((self.centerx-self.armor_font.get_width()/2), 280)) screen.blit(self.helmet_font, ((self.centerx-self.helmet_font.get_width()/2), 310)) screen.blit(self.gauntlet_font, ((self.centerx-self.gauntlet_font.get_width()/2), 340)) screen.blit(self.accessory_font, ((self.centerx-self.accessory_font.get_width()/2), 370)) screen.blit(self.item_font, ((self.centerx-self.item_font.get_width()/2), 400)) #draw extra window self.buy_window.draw(screen, game_self) def shop_window_handler( self, event, game_self): if self.buy_window.is_visible == True: self.buy_window.buy_window_handler( event, game_self) return #moves the cursor up if event.type == KEYDOWN and event.key == K_UP: game_self.cursor_se.play() self.menu -= 1 if self.menu < 0: self.menu = self.MENU_MAX #moves the cursor down elif event.type == KEYDOWN and event.key == K_DOWN: game_self.cursor_se.play() self.menu += 1 if self.menu > self.MENU_MAX: self.menu = 0 #moves back to shop elif event.type == KEYDOWN and event.key == K_x: game_self.cancel_se.play() self.menu = 0 self.is_visible =False #select category to buy elif event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN): self.buy_window.is_visible = True class Buy_window(window.Window): SWORD, KATANA, BLUNT, GUN, THROW = 0, 1, 2, 3, 4 SHIELD, ARMOR, HELMET, GAUNTLET, ACCESSORY = 5, 6, 7, 8, 9 ITEM = 10 MENU_MAX = 9 def __init__(self, rectangle): window.Window.__init__(self, rectangle) self.is_visible = False self.menu = 0 self.page = 0 self.top = rectangle.top self.left = rectangle.left self.right = rectangle.right self.centerx = rectangle.centerx self.menu_font = pygame.font.Font("ipag.ttf", 20) self.top_font = self.menu_font.render( u"商品一覧:", True, COLOR_WHITE) self.category_item = [] self.character_select = Character_select_window( Rect(100, 50, 440, 230)) def draw( self, screen, game_self): """draw the shop window on screen""" if self.is_visible == False: return window.Window.draw(self, screen) screen.blit( self.top_font, (self.left + 20, self.top+20)) selected = game_self.shop.shop_window.menu #show what is the category if selected == self.SWORD: category_font = self.menu_font.render( u"剣", True, COLOR_WHITE) if selected == self.KATANA: category_font = self.menu_font.render( u"刀", True, COLOR_WHITE) if selected == self.BLUNT: category_font = self.menu_font.render( u"鈍器", True, COLOR_WHITE) if selected == self.GUN: category_font = self.menu_font.render( u"銃", True, COLOR_WHITE) if selected == self.THROW: category_font = self.menu_font.render( u"投擲", True, COLOR_WHITE) if selected == self.SHIELD: category_font = self.menu_font.render( u"盾", True, COLOR_WHITE) if selected == self.ARMOR: category_font = self.menu_font.render( u"鎧", True, COLOR_WHITE) if selected == self.HELMET: category_font = self.menu_font.render( u"兜", True, COLOR_WHITE) if selected == self.GAUNTLET: category_font = self.menu_font.render( u"篭手", True, COLOR_WHITE) if selected == self.ACCESSORY: category_font = self.menu_font.render( u"アクセサリー", True, COLOR_WHITE) if selected == self.ITEM: category_font = self.menu_font.render( u"アイテム", True, COLOR_WHITE) screen.blit( category_font, (self.left + 20 + self.top_font.get_width(), self.top+20)) #store the item in the shop and quantity of it item_data = game_self.item_data #category item is the array of selected category items self.category_item = game_self.shop.stock[selected] #draw the box on item selected if self.category_item != []: #draws rectangle on the menu item size of rectangle has width of window rectangle - edge_length*2 #the height depends on the size of font pygame.draw.rect(screen, COLOR_GLAY, Rect( self.left+4, self.top+55 + 30*self.menu,(self.right-self.left)-8,30), 0) #draws the item 10 at a time in the page i = 0 for item in self.category_item[self.page*10:(self.page+1)*10]: item_font = item_data[item.id][0].strip("\"") item_font = unicode(item_font, encoding="sjis") item_font = self.menu_font.render( item_font, True, COLOR_WHITE) screen.blit( item_font, (self.left + 20, self.top+60+i*30)) cost_font = self.menu_font.render( item_data[item.id][2] + "TG", True, COLOR_WHITE) screen.blit( cost_font, (self.right - 20 - cost_font.get_width(), self.top+60+i*30)) i+=1 self.character_select.draw( screen, game_self) def buy_window_handler(self, event, game_self): if self.character_select.is_visible == True: self.character_select.character_select_handler( event, game_self) return #moves back to shop if event.type == KEYDOWN and event.key == K_x: game_self.cancel_se.play() self.menu = 0 self.page = 0 self.is_visible =False #moves the cursor up elif event.type == KEYDOWN and event.key == K_UP: game_self.cursor_se.play() self.menu -= 1 if self.menu < 0: self.menu = 0 #moves the cursor down elif event.type == KEYDOWN and event.key == K_DOWN: game_self.cursor_se.play() if len(self.category_item) > self.menu+self.page*10+1: self.menu += 1 if self.menu > self.MENU_MAX: self.menu = self.MENU_MAX #moves the cursor down elif event.type == KEYDOWN and event.key == K_LEFT: game_self.cursor_se.play() if self.page > 0: self.page-= 1 self.menu = 0 #moves the cursor down elif event.type == KEYDOWN and event.key == K_RIGHT: game_self.cursor_se.play() if len(self.category_item) > (self.page+1)*10: self.page += 1 self.menu = 0 #select item elif event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN): if len(self.category_item) > 0: game_self.select_se.play() self.character_select.is_visible = True class Sell_window(window.Window): MENU_MAX = 9 def __init__(self, rectangle): window.Window.__init__(self, rectangle) self.is_visible = False self.menu = 0 self.top = rectangle.top self.left = rectangle.left self.right = rectangle.right self.centerx = rectangle.centerx self.menu_font = pygame.font.Font("ipag.ttf", 20) self.top_font = self.menu_font.render( u"の持ち物:", True, COLOR_WHITE) self.sold_item_window = system_notify.Donate_finish_window( Rect(150, 160 ,300, 50), 6) def draw( self, screen, character): """draw the shop window on screen""" if self.is_visible == False: return window.Window.draw(self, screen) name_font = self.menu_font.render( character.name, True, COLOR_WHITE) screen.blit( name_font, (self.left+20, self.top+20)) screen.blit( self.top_font, (self.left+20+name_font.get_width(), self.top+20)) #draw the box on item selected if character.items != []: #draws rectangle on the menu item size of rectangle has width of window rectangle - edge_length*2 #the height depends on the size of font pygame.draw.rect(screen, COLOR_GLAY, Rect( self.left+4, self.top+55 + 30*self.menu,(self.right-self.left)-8,30), 0) i = 0 for item in character.items: item_font = self.menu_font.render( item.name, True, COLOR_WHITE) screen.blit ( item_font, (self.left+20, self.top+60+i*30)) cost_font = self.menu_font.render( str(item.price/2) + "TG", True, COLOR_WHITE) screen.blit( cost_font, (self.right-20 - cost_font.get_width(), self.top+60+i*30)) i += 1 self.sold_item_window.draw(screen) def character_sell_window_handler( self, event, game_self): if self.sold_item_window.is_visible == True: self.sold_item_window.donate_finish_window_handler( event, game_self) return character = game_self.party.member[game_self.shop.sell_window.menu] #moves back to shop if event.type == KEYDOWN and event.key == K_x: game_self.cancel_se.play() self.menu = 0 self.is_visible =False #moves the cursor up elif event.type == KEYDOWN and event.key == K_UP: game_self.cursor_se.play() self.menu -= 1 if self.menu < 0: self.menu = 0 #moves the cursor down elif event.type == KEYDOWN and event.key == K_DOWN: game_self.cursor_se.play() if len(character.items) > self.menu+1: self.menu += 1 if self.menu > self.MENU_MAX: self.menu = self.MENU_MAX elif event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN): if len(character.items) > 0: self.sold_item_window.is_visible = True money = character.items[self.menu].price #if not_found is 100, it means that there was no item with that id so add new one not_found = shop_item_change( character.items[self.menu].id , game_self, 0) if not_found == 100: add_new_shop_item( character.items[self.menu].id, game_self ) #delete character's items and adjust money del character.items[self.menu] character.money += (money/2) if self.menu+1 > len(character.items): self.menu -= 1 class Character_select_window(window.Window): def __init__(self, rectangle): window.Window.__init__(self, rectangle) self.is_visible = False self.menu = 0 self.top = rectangle.top self.left = rectangle.left self.right = rectangle.right self.centerx = rectangle.centerx self.menu_font = pygame.font.Font("ipag.ttf", 20) #if there is no more item left in stock self.no_more = 0 self.top_font = self.menu_font.render( u"誰が買いますか?", True, COLOR_WHITE) self.status = character_view.Status_view_window( Rect(20,20,600, 440)) self.buy_window = system_notify.Donate_finish_window( Rect(150, 160 ,300, 50), 4) self.not_enough_window = system_notify.Donate_finish_window( Rect(150, 160 ,300, 50), 0) self.too_much_item_window = system_notify.Donate_finish_window( Rect(150, 160 ,300, 50), 5) self.not_movable = system_notify.Donate_finish_window( Rect(150,160,300,50), system_notify.Donate_finish_window.TEMPLE_NOT_MOVABLE) def draw(self, screen, game_self): if self.is_visible == False: return window.Window.draw(self, screen) screen.blit( self.top_font, ( self.centerx - self.top_font.get_width()/2 , self.top+20)) #draw the box on item selected if game_self.party.member != []: #draws rectangle on the menu item size of rectangle has width of window rectangle - edge_length*2 #the height depends on the size of font pygame.draw.rect(screen, COLOR_GLAY, Rect( self.left+4, self.top+45 + 30*self.menu,(self.right-self.left)-8,30), 0) i = 0 for character in game_self.party.member: character_font = self.menu_font.render( character.name, True, COLOR_WHITE) screen.blit(character_font, (self.left+20, self.top+50 + 30*i)) money_font = self.menu_font.render( u"所持金:" + str(character.money) + "TG", True, COLOR_WHITE) screen.blit(money_font, (self.right - 20 - money_font.get_width(), self.top+50 + 30*i)) i+=1 self.status.draw( screen, game_self.party.member) self.buy_window.draw( screen) self.not_enough_window.draw(screen) self.too_much_item_window.draw(screen) self.not_movable.draw(screen) def character_select_handler(self, event, game_self): if self.buy_window.is_visible == True: self.buy_window.donate_finish_window_handler( event, game_self) return elif self.not_enough_window.is_visible == True: self.not_enough_window.donate_finish_window_handler( event, game_self) return elif self.status.is_visible == True: self.status.status_view_window_handler( game_self, event, None) return elif self.too_much_item_window.is_visible == True: self.too_much_item_window.donate_finish_window_handler( event, game_self) return elif self.not_movable.is_visible == True: self.not_movable.donate_finish_window_handler( event, game_self) return length = len(game_self.party.member)-1 #moves back to item window if event.type == KEYDOWN and event.key == K_x: game_self.cancel_se.play() self.menu = 0 self.is_visible =False #moves the cursor up elif event.type == KEYDOWN and event.key == K_UP: game_self.cursor_se.play() self.menu -= 1 self.status.menu -= 1 if self.menu < 0: self.menu = length self.status.menu = length #moves the cursor down elif event.type == KEYDOWN and event.key == K_DOWN: game_self.cursor_se.play() self.menu += 1 self.status.menu += 1 if self.menu > length: self.menu = 0 self.status.menu = 0 #status view elif event.type == KEYDOWN and event.key == K_LSHIFT: game_self.cursor_se.play() self.status.is_visible = True #buy elif event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN): game_self.select_se.play() #get the cost of the item category_item = game_self.shop.shop_window.buy_window.category_item item_menu = game_self.shop.shop_window.buy_window.menu if game_self.party.member[self.menu].status != [0,0,0,0,0,0,0,0,0]: self.not_movable.is_visible = True elif game_self.party.member[self.menu].money >= int(game_self.item_data[category_item[item_menu].id][2]) and len(game_self.party.member[self.menu].items) < 10: game_self.party.member[self.menu].money -= int(game_self.item_data[category_item[item_menu].id][2]) game_self.party.member[self.menu].items.append( item.Item( game_self.item_data[category_item[item_menu].id] )) self.no_more = shop_item_change( category_item[item_menu].id, game_self, 1) self.buy_window.is_visible = True elif game_self.party.member[self.menu].money < int(game_self.item_data[category_item[item_menu].id][2]): self.not_enough_window.is_visible = True elif len(game_self.party.member[self.menu].items) == 10: self.too_much_item_window.is_visible = True #increase(0) or decrease(1) item #if no item was found, it returns 100, else it returns 101 def shop_item_change( item_id, game_self, i ): found = 100 j = 0 k = 0 for item_array in game_self.shop.stock: for item in item_array: if i == 1: if item.id == item_id: found = 101 #if stock is negative it has infinity stock if item.stock < 0: return found item.stock -= 1 if item.stock == 0: del game_self.shop.stock[j][k] game_self.shop.shop_window.buy_window.menu -= 1 if game_self.shop.shop_window.buy_window.menu < 0: game_self.shop.shop_window.buy_window.menu = 0 return 1 else: if item.id == item_id: if item.stock == -1: return 101 item.stock += 1 found = 101 if item.stock > 99: item.stock = 99 k += 1 j += 1 k = 0 return found def add_new_shop_item( item_id, game_self ): item_id = int(item_id) new_item = shop.Shop_item( item_id, 1) if item_id <= 100: game_self.shop.stock[10].append(new_item) elif item_id < 150: game_self.shop.stock[0].append(new_item) elif item_id < 200: game_self.shop.stock[1].append(new_item) elif item_id < 250: game_self.shop.stock[2].append(new_item) elif item_id < 300: game_self.shop.stock[3].append(new_item) elif item_id < 350: game_self.shop.stock[4].append(new_item) elif item_id < 400: game_self.shop.stock[5].append(new_item) elif item_id < 500: game_self.shop.stock[6].append(new_item) elif item_id < 550: game_self.shop.stock[7].append(new_item) elif item_id < 600: game_self.shop.stock[8].append(new_item) elif item_id < 700: game_self.shop.stock[9].append(new_item)
true
6f12b3563910501a611476d4325cf7373e9c91d2
Python
DylanDelucenauag/cspp10
/unit3/ddelucena_numguess.py
UTF-8
650
4.0625
4
[]
no_license
import random comp_number = random.randint(1,100) player_guess = int(input("Guess a number from 1 to 100: ")) while (player_guess != comp_number): if player_guess > comp_number: print ("Too high!") print ("Try again") player_guess = int(input("Guess again: ")) elif player_guess < comp_number: print ("Too low!") print ("Try again!") player_guess = int(input("Guess again: ")) if (player_guess == comp_number): print ("Good Job") print ("The number was " + str(comp_number)) print("You're like the best person ever!") #first_guess = input("Guess a number")
true
23cceda111798bbc64df18a91c91f9ba6ed0fce7
Python
TakahiroSono/atcoder
/contest/ABC171/python/A.py
UTF-8
85
2.90625
3
[]
no_license
upper = "QWERTYUIOPASDFGHJKLZXCVBNM" A = input() print('A' if A in upper else 'a')
true
64ded8624318d508b1dce3d36b242797591d1ed8
Python
wanghan79/2019_Python_Tech
/2016010484-张旻政/2016010484-张旻政-第二次作业/第二次作业类运算运行.py
UTF-8
341
3
3
[]
no_license
from Statistic import Statistic # 导入Statistic类 a = Statistic('students.txt') sum = a.statistic_sum() # 求和 print('the sum is ', sum) ava = a.statistic_average() # 求平均值 print('the average is ', ava)
true
cc511f623c747a3834728de4e462309560657ddd
Python
parekh0711/library-system
/main.py
UTF-8
2,643
2.828125
3
[]
no_license
from tables import * from insert import * from create import * import sqlite3 from sqlite3 import Error import pandas as pd def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def execute_instruction(conn,instruction): try: c=conn.cursor() c.execute(instruction) except Error as e: print(e) def select(conn,instruction): try: c=conn.cursor() c.execute(instruction) rows=c.fetchall() for row in rows: for element in row: print(element,end="\t\t") print("") except Error as e: print(e) def select_and_print(conn,instruction): try: c=conn.cursor() c.execute(instruction) rows=c.fetchall() return rows except Error as e: print(e) def create_tables(conn): execute_instruction(conn, customer_table) execute_instruction(conn, product_table) execute_instruction(conn, reservation_table) execute_instruction(conn, profit_table) execute_instruction(conn, borrowed_table) execute_instruction(conn, employee_table) execute_instruction(conn, outstanding_table) execute_instruction(conn, author_table) execute_instruction(conn,book_table) execute_instruction(conn, media_table) execute_instruction(conn, salary_table) execute_instruction(conn, policies_table) def insert_data(conn): execute_instruction(conn, insert_customer) execute_instruction(conn,insert_employee) execute_instruction(conn,insert_salary) execute_instruction(conn,insert_product) execute_instruction(conn,insert_author) execute_instruction(conn,insert_book) execute_instruction(conn, insert_media) execute_instruction(conn, insert_reservation) execute_instruction(conn, insert_borrowed) execute_instruction(conn, insert_profit) execute_instruction(conn, insert_outstanding) execute_instruction(conn, insert_policies) def main(): database = r"lib.db" conn = create_connection(database) if conn is not None: # create projects table execute_instruction(conn,"""PRAGMA foreign_keys = ON;""") create_tables(conn) insert_data(conn) conn.commit() print("Database is ready.") # select(conn,"""select * from book;""") # print(pd.read_sql_query("SELECT customer_id FROM outstanding", conn)) #conn.commit() else: print("Error! cannot create the database connection.") if __name__ == '__main__': main()
true
aac9e85746021583216a85846531980835ac75e4
Python
ArturoBarrios/MusicClassification
/PredictorScripts/CustomFeatureSet.py
UTF-8
28,646
2.78125
3
[]
no_license
from music21 import * from collections import Counter import re from collections import OrderedDict class CustomFeatures: def __init__(self): print(self," doesn't have any arguments") # def maxDensity(self,score): #advanced rhythmic similarity #how similar is each measure in comparison to entire piece #score1 is the score to search for(looking for these notes) #score2 is the score to search(looking at this corpus) def advancedRhythm2Similarity(self,score1,score2): similarity = 0 aggregate_similarity = 0 total_measures = 0 if score1 is not None and score2 is not None: stream_segments1 = score1.getElementsByClass(stream.Part) stream_segments2 = score2.getElementsByClass(stream.Part) similar_measures = 0 total_measures = len(stream_segments1[0])-1 print("total measures: ",total_measures) i = 1 while i < len(stream_segments1[0]): stream_segment1 = stream_segments1[0][i] new_score = stream.Score() new_score.insert(0,stream_segment1) notes_and_rest_to_search = new_score.flat.notesAndRests.stream() j = 1 while j<len(stream_segments1[0]): measure_segment = stream_segments2[0][j] segment_score = stream.Score() segment_score.insert(0,measure_segment) notes_and_rest_search = segment_score.flat.notesAndRests.stream() a = 0 rhythm_match = True #print(len(notes_and_rest_search), " ",len(notes_and_rest_to_search)) if len(notes_and_rest_search)==len(notes_and_rest_to_search): while a<len(notes_and_rest_to_search): note_to_match = notes_and_rest_search[a] curr_note = notes_and_rest_to_search[a] if not(type(note_to_match)==type(curr_note) or ((type(note_to_match)==note.Note and type(curr_note)==chord.Chord)or(type(note_to_match)==chord.Chord and type(curr_note)==note.Note))): rhythm_match = False a+=1 if rhythm_match: similar_measures+=1 j+=1 i+=1 #print("similar measures: ",similar_measures) avg_for_measure = similar_measures/total_measures aggregate_similarity+=avg_for_measure #print("avg ", avg_for_measure) similar_measures = 0 similarity = aggregate_similarity/total_measures print("advanced similarity(2): ",similarity) return similarity #advanced rhythmic similarity #how similar is each measure in comparison to entire piece def advancedRhythmSimilarity(self,score): similarity = 0 aggregate_similarity = 0 total_measures = 0 if score is not None: stream_segments = score.getElementsByClass(stream.Part) similar_measures = 0 total_measures = len(stream_segments[0])-1 print("total measures: ",total_measures) i = 1 while i < len(stream_segments[0]): stream_segment = stream_segments[0][i] new_score = stream.Score() new_score.insert(0,stream_segment) notes_and_rest_to_search = new_score.flat.notesAndRests.stream() j = 1 while j<len(stream_segments[0]): measure_segment = stream_segments[0][j] segment_score = stream.Score() segment_score.insert(0,measure_segment) notes_and_rest_search = segment_score.flat.notesAndRests.stream() a = 0 rhythm_match = True #print(len(notes_and_rest_search), " ",len(notes_and_rest_to_search)) if len(notes_and_rest_search)==len(notes_and_rest_to_search): while a<len(notes_and_rest_to_search): note_to_match = notes_and_rest_search[a] curr_note = notes_and_rest_to_search[a] if not(type(note_to_match)==type(curr_note) or ((type(note_to_match)==note.Note and type(curr_note)==chord.Chord)or(type(note_to_match)==chord.Chord and type(curr_note)==note.Note))): rhythm_match = False a+=1 if rhythm_match: similar_measures+=1 j+=1 i+=1 #print("similar measures: ",similar_measures) avg_for_measure = similar_measures/total_measures aggregate_similarity+=avg_for_measure #print("avg ", avg_for_measure) similar_measures = 0 similarity = aggregate_similarity/total_measures print("advanced similarity: ",similarity) return similarity #similarity of rythm def rhythmSimilarity(self,score1,score2): similarity = 0 if score1 is not None and score2 is not None: score1.getElementsByClass(stream.Part)[0][0:5] try: l = search.approximateNoteSearchOnlyRhythm(score1,score2) similarity = l[0].matchProbability except: print("error when getting rhythm similairty") print("similarity: ",similarity) return similarity #similarity between two scores def similarityBetween1Score(self,score,file): total_similarity = 0 avg_similarity = 0 if score is not None: scoreDict = OrderedDict() scoreList = search.segment.indexScoreParts(score) scoreDict["1 "+file] = scoreList scoreDict["2 "+file] = scoreList scoreSim = search.segment.scoreSimilarity(scoreDict,minimumLength=5,includeReverse=False) total_segments = len(scoreSim) count = 0 for result in scoreSim: similarity = float(result[len(result)-1]) total_similarity+=similarity try: avg_similarity = total_similarity/total_segments except: print("cannot divide by 0 error(similarityBetween1Score)") return -1 print("similarityBetween1Score: ",avg_similarity) return avg_similarity #similarity between two scores def similarityBetween2Score(self,score1,score2,file): total_similarity = 0 avg_similarity = 0 scoreDict = OrderedDict() if score1 is not None and score2 is not None: scoreList1 = search.segment.indexScoreParts(score1) scoreList2 = search.segment.indexScoreParts(score2) scoreDict["1 "+file] = scoreList1 scoreDict["2 "+file] = scoreList2 scoreSim = search.segment.scoreSimilarity(scoreDict,minimumLength=5,includeReverse=False) total_segments = len(scoreSim) count = 0 for result in scoreSim: similarity = float(result[len(result)-1]) total_similarity+=similarity try: avg_similarity = total_similarity/total_segments except: print("cannot divide by 0 error(similarityBetween2Score)") return -1 print("similarityBetween2Score: ",avg_similarity) return avg_similarity #total x chord notes def totalXChordNotes(self,chords,number_of_notes): total = 0 if chords is not None: for chord in chords: #print("length of chord: ",len(chord)) if len(chord)==number_of_notes: total+=1 print("total",number_of_notes,"ChordNotes: ",total,"\n") return total #average x chord notes def averageXChordNotes(self,chords,number_of_notes): average = 0 if chords is not None: total_x_chord_notes = float(self.totalXChordNotes(chords,number_of_notes)) total = float(len(chords)) average = total_x_chord_notes/total print("average",number_of_notes,"ChordNotes: ",average) return average #average range of top x percent of notes #tested def averageRange2OfTopXPercent(self,stream,percent): average_range = 0 if stream is not None: notes_count = dict() notes = stream.flat.getElementsByClass("Note") topX = [] totalSharpNotes = 0 total_notes = len(notes) #print("total notes during call: ",total_notes) number_of_notes_to_get = int(total_notes*percent) #print("total notes to get during call: ",number_of_notes_to_get) notes_array = [] #store count of notes in dictionary for note in notes: #print(note) if note.nameWithOctave not in notes_count: notes_count[note.nameWithOctave] = 1 notes_array.append(note) else: notes_count[note.nameWithOctave] += 1 #sort notes by count c = Counter(notes_count) #print(c) #x = percent*len(notes_count) #get the top x notes numberOfNotes = int(percent*len(notes_count)) top_x_tuple = c.most_common(len(c)) #print(top_x_tuple) #print("number of notes: ",numberOfNotes) index = 0 top_x_note_objects = [] #iterate through note_array and get top x note objects top_x_note_objects = self.return_x_top_notes(top_x_tuple,notes_array,number_of_notes_to_get) #print("top x notes: ",top_x_note_objects) #get lowest and highest notes # lowest_note = getLowestNote(top_x_note_objects) # highest_note = getHighestNote(top_x_note_objects) notes_total_average = 0 if len(top_x_note_objects)>1: #get total range index1 = 0 #get interval of every note of every note while index1<len(top_x_note_objects): note1 = top_x_note_objects[index1] index2 = 0 total_interval_for_note = 0 average_for_note = 0 #print("length of top x notes objects: ",len(top_x_note_objects)) while index2<len(top_x_note_objects): if(index1!=index2): note2 = top_x_note_objects[index2] #interval between both notes aInterval = interval.Interval(noteStart=note1,noteEnd=note2) aInterval = int(re.search(r'\d+', aInterval.name).group()) range = int(aInterval) total_interval_for_note+=range index2+=1 #average interval for note average_for_note = total_interval_for_note/(len(top_x_note_objects)-1) notes_total_average+=average_for_note index1+=1 #calculate average range of every note's average range to other notes average_range = notes_total_average/len(top_x_note_objects) print('averageRange2OfTopXPercent: ',average_range) return average_range #range of top x percent of notes, def rangeOfTopXPercent(self,stream,percent): range = 0 if stream is not None: notes_count = dict() notes = stream.flat.getElementsByClass("Note") total_notes = len(notes) number_of_notes_to_get = int(total_notes*percent) #print("number of notes to get", number_of_notes_to_get) topX = [] totalSharpNotes = 0 notes_array = [] #store count of notes in dictionary for note in notes: #print(note) if note.nameWithOctave not in notes_count: notes_count[note.nameWithOctave] = 1 notes_array.append(note) else: notes_count[note.nameWithOctave] += 1 #sort notes by count c = Counter(notes_count) #print("c: ",c) #x = percent*len(notes_count) top_x_tuple = c.most_common(len(c)) index = 0 top_x_note_objects = [] #iterate through note_array and get top x note objects top_x_note_objects = self.return_x_top_notes(top_x_tuple,notes_array,number_of_notes_to_get) if len(top_x_note_objects)>1: #print("top x notes: ",top_x_note_objects) # for note in top_x_note_objects: # print(note.fullName,end=" ") #get lowest and highest notes lowest_note = self.getLowestNote(top_x_note_objects) highest_note = self.getHighestNote(top_x_note_objects) #interval between both notes aInterval = interval.Interval(noteStart=lowest_note,noteEnd=highest_note) aInterval = int(re.search(r'\d+', aInterval.name).group()) range = int(aInterval) #print("range: ",range) else: range = 0 print('rangeOfTopXPercent: ',range) return range #takes in a tuple with names of top notes and returns the top notes as objects def return_x_top_notes(self,top_x_tuple,notes_array,numberOfNotes): top_x_note_objects = [] index = 0 current_total_notes = 0 #iterate through note_array and get top x note objects while current_total_notes<numberOfNotes: current_note_name = top_x_tuple[index][0] current_total_notes+=top_x_tuple[index][1] note_found = False arr_index = 0 while not note_found: if(notes_array[arr_index].nameWithOctave==current_note_name): note_found = True top_x_note_objects.append(notes_array[arr_index]) arr_index += 1 index+=1 return top_x_note_objects #gets lowest note #takes in array with note objects def getLowestNote(self,notes): i = 0 lowest_note = notes[0] while i<len(notes): curr = notes[i] #print("compare: ",lowest_note.pitch," ",curr.pitch) if lowest_note>=curr: lowest_note = curr i+=1 return lowest_note #gets highest note #takes in array with note objects def getHighestNote(self,notes): i = 0 highest_note = notes[0] while i<len(notes): curr = notes[i] #print("compare: ",highest_note.pitch," ",curr.pitch) if highest_note<=curr: highest_note = curr i+=1 return highest_note #average interval value of large jumps def averageLargeJumps(self,chords,largeJump): totalLargeJumps = 0 total = 0 average = 0 i = 0 if chords is not None: while i<len(chords)-1: #get first note of first chord note1_chord_1 = chords[i][0] #get first note of second chord note1_chord2 = chords[i+1][0] notelast_chord2 = chords[i+1][len(chords[i+1])-1] #figure out which note to get by comparing first notes of both chords #only need to compare first and last note of chords lower_note = chords[i][len(chords[i])-1] higher_note = chords[i+1][0] #first chord lower than second if note1_chord_1<=notelast_chord2: lower_note = chords[i][0] higher_note = chords[i+1][len(chords[i+1])-1] #print(chords[i]," ",chords[i+1]) #print(chords[i]," ",chords[i+1]," ",note1,">",note2," ",note1<note2) #interval between both notes aInterval = interval.Interval(noteStart=lower_note,noteEnd=higher_note) aInterval = int(re.search(r'\d+', aInterval.name).group()) if(int(aInterval)>=largeJump): totalLargeJumps+=1 total += int(aInterval) #print(aInterval.name) i+=1 #print ("total large jumps: ",totalLargeJumps) if totalLargeJumps>0: average = total/totalLargeJumps print("averageLargeJumps: ",average) return average #average largeJumps #return the number of large jumps>=largeJump def largeJumps(self,chords,largeJump): totalLargeJumps = 0 i = 0 if chords is not None: while i<len(chords)-1: #get first note of first chord note1_chord_1 = chords[i][0] #get first note of second chord note1_chord2 = chords[i+1][0] notelast_chord2 = chords[i+1][len(chords[i+1])-1] #figure out which note to get by comparing first notes of both chords #only need to compare first and last note of chords lower_note = chords[i][len(chords[i])-1] higher_note = chords[i+1][0] #first chord lower than second if note1_chord_1<=notelast_chord2: lower_note = chords[i][0] higher_note = chords[i+1][len(chords[i+1])-1] #print(chords[i]," ",chords[i+1]," ",note1,">",note2," ",note1<note2) #interval between both notes aInterval = interval.Interval(noteStart=lower_note,noteEnd=higher_note) aInterval = int(re.search(r'\d+', aInterval.name).group()) if(int(aInterval)>=largeJump): #print(chords[i]," ",chords[i+1]) totalLargeJumps+=1 #print(aInterval.name) i+=1 print ('largeJumps: ',totalLargeJumps) return totalLargeJumps #average range of played ntoes #range from A3 to B3C4 is the interval from A3 to C4 #new def averageRangeForNextNotes(self,chords): i = 0 total = 0 average = 0 if chords is not None: while i<len(chords)-1: #get first note of first chord note1_chord_1 = chords[i][0] #get first note of second chord note1_chord2 = chords[i+1][0] notelast_chord2 = chords[i+1][len(chords[i+1])-1] #figure out which note to get by comparing first notes of both chords #only need to compare first and last note of chords lower_note = chords[i][len(chords[i])-1] higher_note = chords[i+1][0] #first chord lower than second if note1_chord_1<=notelast_chord2: lower_note = chords[i][0] higher_note = chords[i+1][len(chords[i+1])-1] #print(chords[i]," ",chords[i+1]) #print(chords[i]," ",chords[i+1]," ",note1,">",note2," ",note1<note2) #interval between both notes aInterval = interval.Interval(noteStart=lower_note,noteEnd=higher_note) total+=int(re.search(r'\d+', aInterval.name).group()) #int(aInterval.name[1:]) #print(aInterval.name) i+=1 if(len(chords)>0): average = total/len(chords) print('averageRangeForNextNotes: ',average) return average #assume you have the correct stream############################################## #for every chord, what is the range from one note to the next #basically this tells you how far you have to spread each finger on average #3 note chord,distance from 1-2+distance from 2-3 /2 #average this out def averageChordRangeForHand(self,chords,chord_length): average = 0 chord_average_total = 0 total_chords = 0 if chords is not None: for chord in chords: #calculate range in chord if(len(chord)==chord_length): total_chords+=1 total = 0 average = 0 index = 0 #print(chord) #interval between notes in chord while index!=len(chord)-1: aInterval = interval.Interval(noteStart=chord[index],noteEnd=chord[index+1]) aInterval = int(re.search(r'\d+', aInterval.name).group()) total+=int(aInterval) index+=1 #average of chord average = total/(len(chord)-1) chord_average_total+=average #print(average) if(total_chords>0): average = chord_average_total/total_chords else: average = 0 print('averageChordRangeForHand: ',average) return average #for every chord, what is the range from the left most note to the right most note #basically how far is your hand spread out for each chord #average this out def average2ChordRangeForHand(self,chords,chord_length): total_chords = 0 total = 0 average = 0 #distance between first and last note of each chord if chords is not None: for chord in chords: if(len(chord)==chord_length): aInterval = interval.Interval(noteStart=chord[0],noteEnd=chord[len(chord)-1]) total+=int(aInterval.name[1:]) total_chords+=1 #print(chord ," ",aInterval) if(total_chords>0): average = total/total_chords print('average2ChordRangeForHand: ',average) return average #average def averageWholeNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.totalWholeNotes(given_stream)/totalNotes return average def averageHalfNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.totalHalfNotes(given_stream)/totalNotes return average def averageQuarterNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.totalQuarterNotes(given_stream)/totalNotes return average def averageEighthNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.totalEighthNotes(given_stream)/totalNotes return average def average16thNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.total16thNotes(given_stream)/totalNotes return average def average32ndNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.total32ndNotes(given_stream)/totalNotes return average def average64thNotes(self,given_stream): average = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") totalNotes = len(notes) if totalNotes>0: average = self.total64thNotes(given_stream)/totalNotes return average def totalWholeNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==4: total+=1 #print(total) return total def totalHalfNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==2: total+=1 #print(total) return total def totalQuarterNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==1: total+=1 #print(total) return total def totalEighthNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==.5: total+=1 #print(total) return total def total16thNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==.25: total+=1 #print(total) return total def total32ndNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==.125: total+=1 #print(total) return total def total64thNotes(self,given_stream): total = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if note.quarterLength==.0625: total+=1 #print(total) return total #total notes #total notes right hand #total notes left hand def totalNotes(self,given_stream): if(given_stream.getElementsByClass("Note") is not None): return len(given_stream.getElementsByClass("Note")) else: return 0 #total sharp notes in the entire piece #total sharp notes in right hand #total sharp notes in left hand def totalSharpNotes(self,given_stream): totalSharpNotes = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if '#' in note.name: totalSharpNotes+=1 #print(note.name) return totalSharpNotes #total flat notes in the entrire piece #total flat notes in right hand #total flat notes in left hand def totalFlatNotes(self,given_stream): totalFlatNotes = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if '-' in note.name: totalFlatNotes+=1 #print(note.name) return totalFlatNotes def totalNaturalNotes(self,given_stream): totalNaturalNotes = 0 if given_stream is not None: notes = given_stream.flat.getElementsByClass("Note") for note in notes: if '-' not in note.name and '#' not in note.name: totalNaturalNotes+=1 return totalNaturalNotes
true
2fd69435ee7e7989c09685df961880aa65bc9c4f
Python
AnnanShu/LeetCode
/231-280_py/269-AlienDictionary.py
UTF-8
1,474
3.21875
3
[]
no_license
from collections import deque from functools import reduce class Solution: def alienOrder(self, words: str): indegree = [0] * 26 neibour = [[] for _ in range(26)] m = len(words) for row in range(m-1): if len(words[row]) > len(words[row+1]) and words[row][:len(words[row+1])] == words[row+1]: return '' min_col = min(len(words[row]), len(words[row+1])) i = 0 while i < min_col: if words[row][i] != words[row+1][i]: indegree[ord(words[row+1][i])-ord('a')] += 1 neibour[ord(words[row][i])-ord('a')].append(ord(words[row+1][i])-ord('a')) break i += 1 appears = [ord(char) -ord('a') for char in reduce(lambda x, y: set(x) | set(y), words)] zero_indegree = [i for i in range(26) if indegree[i] == 0 and i in appears] ans = [] Q = deque(zero_indegree) while Q: pre = Q.popleft() ans.append(pre) for cur in neibour[pre]: indegree[cur] -= 1 if indegree[cur] == 0: Q.append(cur) return '' if len(ans) != len(appears) else ''.join(chr(i + ord('a')) for i in ans) dict_ = [ "wrt", "wrf", "er", "ett", "rftt" ] Solution().alienOrder(dict_) Solution().alienOrder(["za","zb","ca","cb"])
true
f98f9876241baf48a432e2d9e2d63013d468b214
Python
GIS-PuppetMaster/DQN-QuantTrade
/ActorNetwork.py
UTF-8
4,250
2.5625
3
[]
no_license
import numpy as np from keras.callbacks import * import tensorflow as tf import keras.backend as K from keras.models import Model from keras.layers import Dense, Flatten, Conv1D, Input, Concatenate, BatchNormalization, Activation from keras.utils import plot_model import glo from math import * class ActorNetwork(object): def __init__(self, sess, stock_state_size, agent_state_size, action_size, TAU, LEARNING_RATE): self.sess = sess self.stock_state_size = stock_state_size self.agent_state_size = agent_state_size self.action_size = action_size self.TAU = TAU self.LEARNING_RATE = LEARNING_RATE K.set_session(sess) self.model, self.weights, self.stock_state, self.agent_state = self.build_actor_network(stock_state_size, agent_state_size) self.target_model, self.target_weights, self.target_stock_state, self.target_agent_state = self.build_actor_network( stock_state_size, agent_state_size) self.action_gradients = tf.placeholder(tf.float32, [None, action_size]) self.params_gradients = tf.gradients(self.model.output, self.weights, -self.action_gradients) grad = zip(self.params_gradients, self.weights) self.global_step = tf.Variable(0, trainable=False) self.learn_rate = tf.train.exponential_decay(LEARNING_RATE, self.global_step, 20000, 0.9) self.optimize = tf.train.AdamOptimizer(self.learn_rate).apply_gradients(grad, global_step=self.global_step) self.sess.run(tf.initialize_all_variables()) def train(self, stock_state, agent_state, action_grads): self.sess.run(self.optimize, feed_dict={ self.stock_state: stock_state, self.agent_state: agent_state, self.action_gradients: action_grads }) def update_target(self): weights = self.model.get_weights() target_weights = self.target_model.get_weights() for i in range(len(weights)): target_weights[i] = self.TAU * weights[i] + (1 - self.TAU) * target_weights[i] self.target_model.set_weights(target_weights) def build_actor_network(self, stock_state_size, agent_state_size): """ 输入:state(stock,agent) 输出:action loss:max(q),即-tf.reduce_mean(q) :return:actor_net_model,weights,stock_state,agent_state """ input_stock_state = Input(shape=(stock_state_size, glo.count)) # input_stock_state_ = BatchNormalization(epsilon=1e-4, scale=True, center=True)(input_stock_state) input_agent_state = Input(shape=(agent_state_size,)) # input_agent_state_ = BatchNormalization(epsilon=1e-4, scale=True, center=True)(input_agent_state) # x_stock_state = Conv1D(filters=25, kernel_size=2, padding='same')(input_stock_state_) # x_stock_state = BatchNormalization(axis=2, epsilon=1e-4, scale=True, center=True)(x_stock_state) x_stock_state = Flatten()(input_stock_state) # x_stock_state = Activation('tanh')(x_stock_state) dense01 = Dense(64)(x_stock_state) # dense01 = BatchNormalization(epsilon=1e-4, scale=True, center=True)(dense01) dense01 = Activation('tanh')(dense01) dense01 = Dense(8)(dense01) # dense01 = BatchNormalization(epsilon=1e-4, scale=True, center=True)(dense01) dense01 = Activation('tanh')(dense01) merge_layer = Concatenate()([dense01, input_agent_state]) dense02 = Dense(8)(merge_layer) # dense02 = BatchNormalization(epsilon=1e-4, scale=True, center=True)(dense02) dense02 = Activation('tanh')(dense02) dense02 = Dense(4)(dense02) # dense02 = BatchNormalization(epsilon=1e-4, scale=True, center=True)(dense02) dense02 = Activation('tanh')(dense02) output = Dense(self.action_size, name='output', activation='tanh')(dense02) model = Model(inputs=[input_stock_state, input_agent_state], outputs=[output]) plot_model(model, to_file='actor_net.png', show_shapes=True) return model, model.trainable_weights, input_stock_state, input_agent_state
true
1c1b6aaf45e616cb2f1468814df5c39a1df2a05a
Python
jonatanwestholm/garageofcode
/garageofcode/other/kmp.py
UTF-8
480
3.34375
3
[ "MIT" ]
permissive
def make_table(W): N = len(W) T = [0]*N T[0] = -1 i = 1 candidate = 0 while i < N: print(i, candidate) if W[i] == W[candidate]: T[i] = T[candidate] else: T[i] = candidate while candidate >= 0 and W[i] != W[candidate]: candidate = T[candidate] i += 1 candidate += 1 return T print(make_table("AABAABCAABAABCDAABAABCAABAABCDEAABAABCAABAABCDAABAABCAABAABCDEF"))
true
116fff7723b2173b2523d68349cddf14d260693e
Python
HazardDede/machine-learning
/ml/repository/datasets/__init__.py
UTF-8
2,413
2.90625
3
[ "MIT" ]
permissive
"""Provides convenience stuff to fetch datasets for training / experimenting.""" import os from typing import Any, List, Optional from ml.repository import Sets from ml.repository.datasets.catalog import Catalog from ml.repository.datasets.loader import BBCNews, Iris, CatsVsDogs from ml.utils import LogMixin class UnknownDatasetError(Exception): """Is raised when an unknown dataset is requested.""" DEFAULT_MESSAGE = "The dataset '{dataset_name}' is unknown." def __init__(self, dataset_name: str): super().__init__(self.DEFAULT_MESSAGE.format(dataset_name=str(dataset_name))) class Repository(LogMixin): """Provides methods to retrieve datasets.""" # Default base path to persisted datasets _DEFAULT_BASE_PATH = os.path.join(os.path.dirname(__file__), '../datasets') _CATALOG_NAME = 'catalog.yaml' _DEFAULT_TEXT_LABEL = 'text' _DEFAULT_TEXT_TARGET_LABEL = 'target' def __init__(self, base_path: Optional[str] = None): self._base_path = base_path or self._DEFAULT_BASE_PATH self._load_map = { Sets.BBC_NEWS: BBCNews, Sets.IRIS: Iris, Sets.CATS_VS_DOGS: CatsVsDogs } catalog_path = os.path.join(self._base_path, self._CATALOG_NAME) if os.path.isfile(catalog_path): self._catalog = Catalog.from_yaml(catalog_path) else: self._catalog = Catalog.empty(self._base_path) def list(self) -> List[str]: """Return a list of available datasets.""" return list(self._load_map.keys()) + self._catalog.list() def fetch(self, dataset_name: str) -> Any: """Fetch the specified dataset. Args: dataset_name: The name of the dataset to fetch. Returns: The dataset (probably a pandas dataframe) and some metadata information. The exact return depends on the dataset to fetch. """ loader_clazz = self._load_map.get(dataset_name) if loader_clazz: real_dataset_name = dataset_name.split('/')[-1] dataset_path = os.path.abspath( os.path.join(self._base_path, real_dataset_name) ) return loader_clazz(dataset_path).retrieve() if dataset_name in self._catalog.list(): return self._catalog.load(dataset_name) raise UnknownDatasetError(dataset_name)
true
c86072ac929087cedf951a27086daf9ff8eab161
Python
habahnow/332L
/Ghost.py
UTF-8
2,375
3.296875
3
[]
no_license
import os import pygame from spritesheet_functions import SpriteSheet import sys debugging = False class Ghost(pygame.sprite.Sprite): __gravity = 1 __movement_frames = [] __current_frame_reference = 0 __movement_counter = 0 __movement_counter_boundary = 2 __movement_speed = 24 def __init__(self, x, y): """ Initializes the image at the given location. Args: x (int): the x coordinate to place the Sprite. y (int): the y coordinate to place the Sprite. """ pygame.sprite.Sprite.__init__(self) #Get the ghost images from the Sprites folder script_dir = sys.path[0] image_directory = os.path.join(script_dir, 'Sprites/ghost2.bmp') # Get the 2 images for the sprite sheet. sprite_sheet = SpriteSheet(image_directory) image = sprite_sheet.get_image(0, 0, 62, 75) self.__movement_frames.append(image) image = sprite_sheet.get_image(64 , 0, 62, 75) self.__movement_frames.append(image) # set the Player to the first sprite self.image = self.__movement_frames[self.__current_frame_reference] self.rect = self.image.get_rect() # Setting the location of rectangle self.rect.x = x self.rect.y = y def set_floor(self, floor): self.rect.y = floor def slow(self):#TODO if debugging: print ('slow') def speedup(self):#TODO if debugging: print ('speedup') def update(self):#TODO if debugging: print ('update') self.__run() def __run(self): """ Moves the Sprite and changes the sprite image. """ if debugging: print ('run') if self.rect.right > 0: self.__movement_counter += 1 if self.__movement_counter >= self.__movement_counter_boundary: self.__movement_counter = 0 self.rect.left -= self.__movement_speed # Switching the sprite image. self.__movement_frames.reverse() self.image = self.__movement_frames[0]
true
381e52cf73d6660778304cd3b9fc9db55af8f793
Python
sciapp/sampledb
/tests/logic/test_units.py
UTF-8
856
2.890625
3
[ "MIT" ]
permissive
# coding: utf-8 """ """ import sampledb.logic def test_unit_registry(): meter = sampledb.logic.units.ureg.Unit("m") inch = sampledb.logic.units.ureg.Unit("in") assert meter.dimensionality == inch.dimensionality def test_custom_units(): sccm = sampledb.logic.units.ureg.Unit("sccm") cubic_centimeter_per_minute = sampledb.logic.units.ureg.Unit("cm**3 / min") assert sccm.dimensionality == cubic_centimeter_per_minute.dimensionality one_sccm = sampledb.logic.units.ureg.Quantity("1sccm") one_cubic_centimeter_per_minute = sampledb.logic.units.ureg.Quantity("1 cm**3 / min") assert one_sccm.to_base_units() == one_cubic_centimeter_per_minute.to_base_units() def test_prettify_degrees_celsius(): celsius = sampledb.logic.units.ureg.Unit("degC") assert sampledb.logic.units.prettify_units(celsius) == '\xb0C'
true
8fbd79b8ff3b60133bf09e17d2267cf34e0e4f2c
Python
khotiashova7/-
/solution.py
UTF-8
1,240
2.640625
3
[]
no_license
import sys from PyQt5 import uic # Импортируем uic from PyQt5.QtWidgets import QApplication, QMainWindow import sqlite3 class MyWidget(QMainWindow): def __init__(self): super().__init__() uic.loadUi('solution.ui', self) self.connection = sqlite3.connect('solution.db') self.cursor = self.connection.cursor() self.pushButton.clicked.connect(self.check) def check(self): glagol = self.lineEdit.text() try: glagol = self.cursor.execute(f"""SELECT * FROM trans WHERE name_trans == '{glagol}'""").fetchall()[0][0] except: pass glagol1 = self.cursor.execute(f"""SELECT name_1f FROM '1f' WHERE id_1f == {glagol}""").fetchone()[0] glagol2 = self.cursor.execute(f"""SELECT name_2f FROM '2f' WHERE id_2f == {glagol}""").fetchone()[0] glagol3 = self.cursor.execute(f"""SELECT name_3f FROM '3f' WHERE id_3f == {glagol}""").fetchone()[0] self.lineEdit_2.setText(glagol1) self.lineEdit_3.setText(glagol2) self.lineEdit_4.setText(glagol3) if __name__ == '__main__': app = QApplication(sys.argv) ex = MyWidget() ex.show() sys.exit(app.exec_())
true
604febde80e37c3d2b2f8e700973b850522a24bb
Python
KellyJason/Python-Tkinter-example.
/Tkinter_Walkthrough_3.py
UTF-8
1,394
3.859375
4
[]
no_license
import os import tkinter as tk #begining of the window root= tk.Tk() #this creates an area for the labes and button to go in canvas1 = tk.Canvas(root, width = 350, height = 400, bg = 'lightsteelblue2', relief = 'raised') canvas1.pack() # this is the label label1 = tk.Label(root, text='Hello Kelly Girls,''\n''Ready to be Awesome?''\n''Click the button!', bg = 'lightsteelblue2',font=('helvetica', 20)) #This adds the label to the canvas canvas1.create_window(175, 80, window=label1) #now to try and configure the button to go somewhere def button (): #begining of the window window= tk.Tk() #this creates an area for the labes and button to go in canvas2 = tk.Canvas(window, width = 350, height = 250, bg = 'lightsteelblue2', relief = 'raised') canvas2.pack() # this is the label label2 = tk.Label(window, text='Hello Kelly Girls,''\n''You are Awesome!!', bg = 'lightsteelblue2',font=('helvetica', 20)) #This adds the label to the canvas canvas2.create_window(175, 80, window=label2) #end of window window.mainloop() # here is the button but1 = tk.Button(text=' The Awesome Button ', command = button, bg='green', fg='white', font=('helvetica', 12, 'bold' )) but1.pack() #this adds the button to the canvas canvas1.create_window(175, 180, window=but1) #end of window root.mainloop()
true
55c43e1e11ea08da7f4d1fe4213d4a017afc4b3d
Python
sri85/coderbyte
/wordCount.py
UTF-8
73
2.640625
3
[]
no_license
def Wordcount(str): print len(str.split()) Wordcount("one 22 three")
true
1671ba0767798e29bff9d96a576ca3a58913388d
Python
kajetant/adventofcode2018
/AOC06/app06.py
UTF-8
2,473
3.265625
3
[]
no_license
import re from itertools import count, groupby, product from functools import reduce from datetime import datetime import operator from typing import List class Point: def __init__(self, x: int, y: int): self.x = x self.y = y def dist(a: Point, b: Point): return abs(a.x - b.x) + abs(a.y - b.y) def get_input(filename): with open(filename) as f: return [x.strip() for x in f.readlines()] def parse_line(line): r = re.compile('(\d+),\s(\d+)') d = r.match(line).groups() return Point(int(d[0]), int(d[1])) def solve1(points: List[Point]): min_x = min(points, key=lambda p: p.x).x min_y = min(points, key=lambda p: p.y).y max_x = max(points, key=lambda p: p.x).x max_y = max(points, key=lambda p: p.y).y area_by_point = [0 for i in range(0, len(points))] for x in range(min_x, max_x + 1): for y in range(min_y, max_y + 1): distances = [(i, dist(points[i], Point(x, y))) for i in range(0, len(points))] closest_points = sorted([(k, list(group)) for k, group in groupby(sorted(distances, key=lambda x:x[1]), key=lambda x: x[1])], key=lambda x: x[0])[0] if len(closest_points[1]) == 1: point_id = closest_points[1][0][0] if x == min_x or y == min_y or x == max_x or y == max_y: area_by_point[point_id] = -1 else: area_by_point[point_id] += 1 return max(area_by_point) def solve2(points: List[Point]): safe_distance = 10000 min_x = min(points, key=lambda p: p.x).x min_y = min(points, key=lambda p: p.y).y max_x = max(points, key=lambda p: p.x).x max_y = max(points, key=lambda p: p.y).y area_by_point = [0 for i in range(0, len(points))] safe_area = 0 for x in range(min_x, max_x + 1): for y in range(min_y, max_y + 1): distances = [(i, dist(points[i], Point(x, y))) for i in range(0, len(points))] total_distance = sum([x[1] for x in distances]) if total_distance < safe_distance: safe_area += 1 return safe_area if __name__ == "__main__": input = get_input('D:\\repos\\adventofcode2018\\AOC06\\input.io') parsed_input = list(map(parse_line, input)) result1 = solve1(parsed_input) #result1 => 3687 print(f'The result is: {result1}') result2 = solve2(parsed_input) # result 2 => 40134 print(f'The result is: {result2}')
true
1616eb367541152f7b95e8d935ba296a81ed88cc
Python
kharithomas/GuessingGame
/guess_game.py
UTF-8
570
4.8125
5
[]
no_license
# Implement a guessing game in python import random class Game: def guess(self): max_num = int(input('Set a max: ')) random_number = random.randint(1, max_num) guess = 0 # loop while guess != random_number: guess = int(input(f'Guess a number between 1 and {max_num}: ')) if guess < random_number: print('Too low!') elif guess > random_number: print('Too high!') print(f'\nYou win! The number was: {random_number}') game = Game() game.guess()
true
926ba8b0c406580cb8e3796786a6371eeda34e39
Python
dalelyunas/MusicAggr
/LastFm.py
UTF-8
2,376
2.5625
3
[]
no_license
import pylast import time import SpotifyHandler import json import os # API information for last.fm API_KEY = os.getenv("LAST_FM_API_KEY") API_SECRET = os.getenv("LAST_FM_API_SECRET") # Seconds in a week WEEK_SECONDS = 604800 cur_time = time.time() # Authentication for the user username = os.getenv("USERNAME") password_hash = pylast.md5(os.getenv("PASSWORD")) network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash) # The user library library = pylast.Library(user=username, network=network) # List of current albums cur_album_list = [] # List of albums to remove albums_to_remove = [] # List of albums to add albums_to_add = [] # Pushes album data to a text file def push_to_text(): json_data = [] for title in cur_album_list: json_data.append(({'title': title})) with open('album_data.txt', 'w') as outfile: json.dump(json_data, outfile) # Pulls album data from a text file def pull_from_text(): if os.stat("album_data.txt").st_size > 0: with open('album_data.txt') as data_file: data = json.load(data_file) for album_data in data: # album = network.get_album(album_data['artist'], album_data['title']) cur_album_list.append(album_data['title']) # Get the albums of the users in the group of the songs listened to in the last week def get_albums(): group = network.get_group("Dorm Jam Radio") # The group members member_array = group.get_members() for member in member_array: # Gets the albums listened to of each user within a week user_songs_to_albums(member) # Gets the albums listened to of a user def user_songs_to_albums(user): cur_user = network.get_user(user) recent_tracks = cur_user.get_recent_tracks(limit=10) # Gets the album for each recently played track for cur_track in recent_tracks: if cur_track.album not in cur_album_list and cur_track.album is not None: cur_album_list.append(cur_track.album) albums_to_add.append(cur_track.album) if len(cur_album_list) >= 10: albums_to_remove.append(cur_album_list.pop(0)) # Execute updating loop pull_from_text() get_albums() SpotifyHandler.add_all_albums(albums_to_add) SpotifyHandler.remove_given_tracks(albums_to_remove) push_to_text()
true
4addf1c249a93fb19878c41f451b5ced6c5045cf
Python
gen0083/atcoder_python
/python/src/abc151/b_achieve_the_goal.py
UTF-8
402
2.6875
3
[]
no_license
# https://atcoder.jp/contests/abc151/tasks/abc151_b def main(): n, k, m = map(int, input().split(" ")) total = 0 for i in input().split(" "): point = int(i) total += point target = m * n remain = target - total if remain <= 0: print("0") elif remain <= k: print(remain) else: print("-1") if __name__ == '__main__': main()
true
17dcfe4c9262ae3eb81f9edc83b884579ab73309
Python
meharbhatia/MIDAS_KG_Construction
/working_code/rest_code/t3.py
UTF-8
10,511
2.9375
3
[]
no_license
# -*- coding: utf-8 -*- import unicodedata import nltk import re from nltk.tokenize import word_tokenize from nltk.tag import pos_tag from nltk import sent_tokenize import csv ex = 'BYD debuted its E-SEED GT concept car and Song Pro SUV alongside its all-new e-series models at the Shanghai International Automobile Industry Exhibition.' # ex = "John was very fast" # ex = "Running is the favourite hobby of John." # ex = "John ran away with his sister." # ex = "John eats Apple, Orange and Coconut." # ex = "The company also showcased its latest Dynasty series of vehicles, which were recently unveiled at the company’s spring product launch in Beijing." # ex = "A total of 23 new car models were exhibited at the event, held at Shanghai’s National Convention and Exhibition Center, fully demonstrating the BYD New Architecture (BNA) design, the 3rd generation of Dual Mode technology, plus the e-platform framework." # ex = "John is doing excercise." # ex = "John is a good boy." # ex = "Father of John taught him dancing." def preprocess(sent): sent = nltk.word_tokenize(sent) sent = nltk.pos_tag(sent) return sent def getTriplets(ex): # print(ex) sent = preprocess(ex) # print("NORMAL POS TAGGING") # print(sent) # print("NER DEFAULT") # print(nltk.ne_chunk(sent)) triplets = [] nn = () ml = [] nstr = "" k=0 # All the consecutive NN pos tags are merged in this loop while k<len(sent): if ("NN" in sent[k][1]): if (k+1 >= len(sent)) or not ( ("\'s" in sent[k][0] or "’s" in sent[k][0] or sent[k+1][0] == '’' ) #if the noun is containing a possesion like John’s, Mary’s, Teachers’ and (len(sent[k][0]) > 1 ) ): #so that it doesn't filter the names like O’Reily and not John’s nstr = nstr + sent[k][0] + " " else: if ("\'s" in sent[k][0] or "’s" in sent[k][0]): sent[k] = (sent[k][0], 'POSS') elif (sent[k+1][0] == "\'s" or sent[k+1][0] == "’s"): sent[k] = (sent[k][0], 'POSS') sent[k+1] = (sent[k+1][0], 'POSS') else: sent[k] = (sent[k][0], 'POSS') sent[k+1] = (sent[k+1][0], 'POSS') if (k+2 < len(sent)): #adding if condition just to be on safe side sent[k+2] = (sent[k+2][0], 'POSS') # so this doesn't go out of range #when the sentence ends with NN's like John’s. Mary’s. Teachers’. k-=1 elif (k!=0 and k!=len(sent)-1 # so that it doesn't raise an error in the coming lines and (sent[k-1][0][0] >= 'A' and sent[k-1][0][0] <= 'Z' and "NN" in sent[k-1][1]) #if the word before it, is a proper noun and ("and" in sent[k][0] or "of" in sent[k][0]) # if it is a conjuction word in the name of a proper noun, like "Reserve Bank 'of' India" and (sent[k+1][0][0] >= 'A' and sent[k+1][0][0] <= 'Z' and "NN" in sent[k+1][1]) # if the next word is also a proper noun ): nstr = nstr + sent[k][0] + " " else: #something other than NN encountered if (len(nstr)>0): # if there is a NN to write nstr = nstr.strip() nn = (nstr,) + ("NN",) ml.append(nn) #write the NN nstr = "" # clear the string ml.append(sent[k]) # add the other-than-NN word else: ml.append(sent[k]) #just add it k+=1 if (k == len(sent)): #in case the last word was a noun in a sentence nstr = nstr.strip() nn = (nstr,) + ("NN",) ml.append(nn) nstr = "" # print("NER MODIFIED") # print(nltk.ne_chunk(ml)) ignore_verbs = ["is","was","were","will","shall","must","should","would","can","could","may","might"] #verbs which are often modal verbs entities = [] k=0 # Here, all nouns NN are catched by their verb VB to form a triplet while k<len(ml): if ("NN" in ml[k][1] or "VBG" in ml[k][1]): # VBG are verbs acting as nouns entities.append(ml[k]) # unless you encounter a VB or CC or IN tag, keep a stack of all nouns elif ("VB" in ml[k][1]): # verb found ismodal = False for x in ignore_verbs: if (ml[k][0] == x): ismodal = True break k2 = k # remember the verb k+=1 while k < len(ml): #find the noun coming after the verb if ("NN" in ml[k][1] or "VBG" in ml[k][1]): break if (ismodal and "VB" in ml[k][1]): k2 = k ismodal = False k+=1 if (k < len(ml)): # if there exists a noun after the verb if(len(entities) > 0): # if there exists a noun before the verb (in the stack) n1 = entities[-1][0] # entities = entities[:-1] # remove that noun from the stack if (k2+1 < len(ml) and "IN" in ml[k2+1][1]): r = ml[k2][0] + " " + ml[k2+1][0] else: r = ml[k2][0] n2 = ml[k][0] triplets.append((n1,)+(r,)+(n2,)) elif ("CC" in ml[k][1]): #conjuction like AND OR found if (len(triplets)>0): # if there already exists a triplet before while k < len(ml): if ("NN" in ml[k][1] or "VBG" in ml[k][1]): #find the NN coming just after CC break k+=1 if (k<len(ml)): # if there exists such a NN n1 = triplets[-1][0] # extract node 1 from last triplet r = triplets[-1][1] # extract relation from last triplet n2 = ml[k][0] # select this NN you just got triplets.append((n1,)+(r,)+(n2,)) elif (len(entities)>0): #list of nouns (@maher not completed yet) while (k<len(ml)): if ("NN" in ml[k][1] or "VBG" in ml[k][1]): break # final entry in the list found k+=1 # if (k<len(ml)): elif ("IN" in ml[k][1]): # a preposition found if (len(triplets)>0): k2 = k while k < len(ml): # find a noun NN after the preposition if ("NN" in ml[k][1] or "VBG" in ml[k][1]): entities.append(ml[k]) # put the noun in entities stack break k+=1 if (k<len(ml)): #if at least one noun is found if(ml[k2][0] == "of" or ml[k2][0] == "alongside"): #these two prepositions are more often associated with object rather than subject (of last triplet) n1 = triplets[-1][2] # node 2 of last triplet r = ml[k2][0] n2 = n2 = ml[k][0] else: n1 = triplets[0][0] # node 1 of first triplet r = triplets[0][1]+" "+ml[k2][0] # relation of first triplet + preposition of this n2 = ml[k][0] triplets.append((n1,)+(r,)+(n2,)) elif (len(entities) > 0): k2 = k while k < len(ml): # find a noun NN after the preposition if ("NN" in ml[k][1] or "VBG" in ml[k][1]): entities.append(ml[k]) # put the noun in entities stack break k+=1 if (k<len(ml)): n1 = entities[-2][0] r = ml[k2][0] n2 = entities[-1][0] triplets.append((n1,)+(r,)+(n2,)) k+=1 k=0 entities = [] # here we select the adjectives while k<len(ml): if ("JJ" in ml[k][1]): n1 = ml[k][0] r = "quality" k2 = k while k<len(ml): #find the NN coming just next to JJ if ("NN" in ml[k][1]): break k+=1 if (k<len(ml) and k==k2+1): # if NN found n2 = ml[k][0] elif (len(entities)>0): # if no NN found after JJ and stack is not empty n2 = entities[-1][0] # assume that the adjective is associated with last NN in stack entities = [] tt=0 while tt<len(triplets): if (n2 in triplets[tt][0]): triplets[tt] = (n1 + " " + triplets[tt][0], triplets[tt][1], triplets[tt][2]) if (n2 in triplets[tt][2]): triplets[tt] = (triplets[tt][0], triplets[tt][1], n1 + " " + triplets[tt][2]) tt+=1 # for x in triplets: # if (n2 in x[0] or n2 in x[2]): # triplets.append((n1,)+(r,)+(n2,)) # break elif "NN" in ml[k][1]: entities.append(ml[k]) # stack of nouns NN k+=1 k=0 entities = [] # here we select the cardinal numbers while k<len(ml): if ("CD" in ml[k][1]): n1 = ml[k][0] r = "number" while k<len(ml): #find the NN coming just next to CD if ("NN" in ml[k][1]): break k+=1 if (k<len(ml)): # if NN found n2 = ml[k][0] triplets.append((n1,)+(r,)+(n2,)) elif (len(entities)>0): # if no NN found after CD and stack is not empty n2 = entities[-1][0] # assume that the number is associated with last NN in stack entities = [] triplets.append((n1,)+(r,)+(n2,)) elif "NN" in ml[k][1]: entities.append(ml[k]) # stack of nouns NN k+=1 k=0 entities = [] # here we select the possessions while k<len(ml): if ("POSS" in ml[k][1]): # if (k+3 >= len(ml)): # print(ml[k-2], ml[k-1], ml[k], ml[k+1], ml[k+2]) # print(ex, len(ml), k) # print(sent) # print(ml) # input() n1 = ml[k][0].replace('\'s','').replace('’s','') if ("POSS" in ml[k+1][1]): # n1 = n1+ml[k+1][0] k+=1 if ("POSS" in ml[k+1][1]): # n1 = n1+ml[k+1][0] k+=1 r = "belongs-to" if ("NN" in ml[k+1][1]): n2 = ml[k+1][0] triplets.append((n2,)+(r,)+(n1,)) #order of n1 and n2 changed intentionally k+=1 # k=0 # while k<len(triplets): # f = True # p=0 # while p<len(triplets): # if(p!=k): # if (triplets[k][0]==triplets[p][0] or triplets[k][0]==triplets[p][2] # or # triplets[k][2]==triplets[p][0] or triplets[k][2]==triplets[p][2]): # f = False # break # p+=1 # if(f): # triplets = triplets[:k]+triplets[k+1:] # k-=1 # k+=1 return triplets def clearBrackets(article): # to clear the text written inside brackets k=0 p1 = p2 = 0 while k<len(article): if (article[k]=='('): p1 = k if (article[k]==')'): p2 = k if(p1!=0 and p2!=0): article = article[:p1]+article[p2+1:] p1 = p2 = 0 k+=1 article = article.replace('(','').replace('(','') return article output = [['industry', 'index', 's1', 'r', 's2']] # for x in getTriplets(ex): # print(x) # input() #change path with open('CLEANED_icdm_contest_data.csv', 'r') as csvFile: reader = csv.reader(csvFile) next(reader) #so that first line is ignored k=0 tlen = 300 for row in reader: # print(row[1]) # input() # continue article = row[1] article = clearBrackets(article) triplets = [] for x in sent_tokenize(article): ml = getTriplets(x) #getting triplets for each sentence triplets+=ml #at this point triplets variable contains all the triples from the article tl = [] for x in triplets: ttl = [] ttl.append(row[2]) ttl.append(row[0]) ttl.append(x[0]) ttl.append(x[1]) ttl.append(x[2]) tl.append(ttl) output+=tl k+=1 print(str(k)+" / "+str(tlen)) # if k>2: #just to see output from top 2 articles # break file = open('new_3.csv','w') for x in output: for y in x: file.write(y.replace(',','').replace('‘','\'').replace('’','\'').replace('“','\'').replace('”','\'')+', ') file.write("\n") file.close() csvFile.close()
true
ac8a7cea7b483445a7eeacf55879268da0dc2f6f
Python
YuxiG-ba/codingworks
/NLP URL.py
UTF-8
3,349
2.71875
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[17]: import pandas as pd import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import statsmodels.formula.api as smf #import urllib2 df = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv') df # In[6]: df.isnull().sum() # In[7]: df.shape # In[19]: p = sns.FacetGrid( data=df, hue='continent', col='continent', col_wrap=2, height=4, aspect=16/9 ).map(plt.plot, 'year', 'lifeExp') plt.show() # In[22]: models = pd.DataFrame({ 'data': [data for _, data in df.groupby('country')], }) models.index = [country for country, _ in df.groupby('country')] models # In[24]: def country_model(dfm): return smf.ols('lifeExp ~ year', data=dfm).fit() models['fit'] = [ country_model(data) for _, data in df.groupby('country') ] # In[26]: def tidy(fit): from statsmodels.iolib.summary import summary_params_frame tidied = summary_params_frame(fit).reset_index() rename_cols = { 'index': 'term', 'coef': 'estimate', 'std err': 'std_err', 't': 'statistic', 'P>|t|': 'p_value', 'Conf. Int. Low': 'conf_int_low', 'Conf. Int. Upp.': 'conf_int_high' } return tidied.rename(columns = rename_cols) def glance(fit): return pd.DataFrame({ 'aic': fit.aic, 'bic': fit.bic, 'ess': fit.ess, # explained sum of squares 'centered_tss': fit.centered_tss, 'fvalue': fit.fvalue, 'f_pvalue': fit.f_pvalue, 'nobs': fit.nobs, 'rsquared': fit.rsquared, 'rsquared_adj': fit.rsquared_adj }, index=[0]) # note that augment() takes 2 inputs, whereas tidy() and glance() take 1 def augment(fit, data): dfm = data.copy() if len(dfm) != fit.nobs: raise ValueError("`data` does not have same number of observations as in training data.") dfm['fitted'] = fit.fittedvalues dfm['resid'] = fit.resid return dfm # In[27]: tidy(models.fit[0]) # In[28]: glance(models.fit[0]) # In[29]: augment(models.fit[0], models.data[0]) # In[30]: models['tidied'] = [tidy(fit) for fit in models.fit] models['glanced'] = [glance(fit) for fit in models.fit] models['augmented'] = [ augment(fit, data) for fit, data in zip(models.fit, models.data) ] # In[31]: models # In[32]: def unnest(dfm, value_col): lst = dfm[value_col].tolist() unnested = pd.concat(lst, keys=dfm.index) unnested.index = unnested.index.droplevel(-1) return dfm.join(unnested).drop(columns=value_col) # In[33]: glance_results = unnest(models, 'glanced') # equivalently glance_results = ( models .pipe(unnest, 'glanced') # little bit of extra cleanup .reset_index() .rename(columns={'index': 'country'}) ) glance_results # In[34]: p = ( sns.FacetGrid( data=glance_results.sort_values('rsquared'), height=8, aspect=16/9 ) .map(plt.scatter, 'rsquared', 'country') ) plt.show() # In[35]: augment_results = unnest(models, 'augmented') p = ( sns.FacetGrid( data=augment_results, col='continent', col_wrap=2, hue='continent', height=5, aspect=16/9) .map(plt.plot, 'year', 'resid') ) plt.show() # In[ ]:
true
956202b9d2d42d33a20d1a4891f3d1770e1b7164
Python
Santiago-Gallego/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
UTF-8
1,468
3.671875
4
[]
no_license
#!/usr/bin/python3 """matrix_divided module""" def matrix_divided(matrix, div): """divides all elements of a matrix""" def check_samesize_lists_in_matrix(matrix): """checks if lists in matrix are same size""" size = len(matrix[0]) for i in range(1, len(matrix)): if len(matrix[i]) != size: return False return True def is_list_of_lists_of_intfloats(matrix): """checks if matrix is a list of lists of ints and floats""" if matrix is None: return False for row in matrix: if type(row) is not list: return False for i in row: if type(i) is not int and type(i) is not float: return False return True if matrix == [[]] or matrix == []: raise TypeError( "matrix must be a matrix (list of lists) of integers/floats") if is_list_of_lists_of_intfloats(matrix) is False: raise TypeError( "matrix must be a matrix (list of lists) of integers/floats") if check_samesize_lists_in_matrix(matrix) is False: raise TypeError("Each row of the matrix must have the same size") if div is None or (type(div) is not int and type(div) is not float): raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") return [[round(i/div, 2) for i in row] for row in matrix]
true
1f64736c1c783a560cbe176342c627a0599ed0ce
Python
phantax/microtags
/plotting.py
UTF-8
5,559
2.515625
3
[]
no_license
#!/usr/bin/python3 import sys import base64 import binascii import microtags import matplotlib import math import numpy as np from scipy import optimize # # _____________________________________________________________________________ # def main(argv): import matplotlib.pyplot as plot globals()['plot'] = plot microtagList = microtags.main(argv) yScale = 1. / 50. yLabel = 'Microseconds' #yScale = 1. #yLabel = 'Ticks' stateTags = ['BenchNum', 'BenchSize', 'BenchRun', 'BenchVariant', 'ComprRounds', 'FinalRounds'] plotTags = ['Benchmark'] state = {} # data: name -> (x value -> (Ysum, Ysum2, N)) data = {} for tag in microtagList.analysedTags: if isinstance(tag, microtags.MicrotagData): if tag.getIdAlias() in stateTags: if tag.getIdAlias() == 'BenchNum' and \ state.get(tag.getIdAlias(), 0) > tag.getTagData(): state['BenchNum_overflow'] = state.get('BenchNum_overflow', 0) + 1 state[tag.getIdAlias()] = tag.getTagData() if isinstance(tag, microtags.MicrotagStop): if tag.getIdAlias() in plotTags: stateVec = (state['BenchVariant'], state['BenchRun']) if stateVec[0] == 0x10: name = 'HMAC-SHA256' elif stateVec == (0x11, 0): name = 'HMAC-SHA256-initial-run' elif stateVec[0] == 0x11 and stateVec[1] > 0: name = 'HMAC-SHA256-followup-run' elif stateVec[0] == 0x20: name = 'AES-128-GMAC (AO)' elif stateVec[0] == 0x21: name = 'AES-256-GMAC (AO)' elif stateVec[0] == 0x28: name = 'AES-128-GCM (AE)' elif stateVec[0] == 0x29: name = 'AES-256-GCM (AE)' elif stateVec[0] == 0x30: name = 'ChaCha20-Poly1305 (AO)' elif stateVec == (0x31, 0): name = 'ChaCha20-Poly1305-initial-run' elif stateVec[0] == 0x31 and stateVec[1] > 0: name = 'ChaCha20-Poly1305-followup-run' elif stateVec[0] == 0x38: name = 'ChaCha20-Poly1305 (AE)' elif stateVec[0] == 0x40: name = 'SHA3' elif stateVec[0] == 0x50: name = 'KMAC' elif stateVec[0] == 0x60: name = 'SipHash-{}-{}-64'.format(state['ComprRounds'], state['FinalRounds']) elif stateVec[0] == 0x61: name = 'SipHash-{}-{}-128'.format(state['ComprRounds'], state['FinalRounds']) else: continue x = state['BenchSize'] end_time = tag.getTagData() start_time = microtagList.getAnalysedTags()[tag.getStartTagIndex()].getTagData() if end_time >= start_time: y = end_time - start_time else: y = (end_time + 0xFFFFFFFF) - start_time if name in data: # >>> New point in existing dataset >>> if x in data[name]: # >>> New point at existing x value >>> data[name][x] = ( data[name][x][0] + y, data[name][x][1] + y**2, data[name][x][2] + 1) else: # >>> New point at new x value >>> data[name][x] = (y, y**2, 1) else: # >>> New point opens new dataset >>> data[name] = { x: (y, y**2, 1) } for name in data: X = [] Y = [] Yvardown = [] Yvarup = [] for x in sorted(data[name].keys()): ysum = data[name][x][0] ysum2 = data[name][x][1] n = data[name][x][2] y = ysum / n yerr = math.sqrt( (ysum2 - ysum**2 / n) / (n - 1) ) if n > 1 else 0. X += [x] Y += [y * yScale] Yvardown += [(y - yerr) * yScale] Yvarup += [(y + yerr) * yScale] print('Plotting {0} with {1} constribution(s)'.format(name, str(set([v[2] for v in data[name].values()])))) plot.scatter(X, Y, 2) plot.plot(X, Y, label=name) plot.fill_between(X, Yvardown, Yvarup, color='lightgrey') if True: # Linear fit B = lambda x, m, c: m*x + c Xnp = np.array(X) Ynp = np.array(Y) #params = [max(Ymean), 1E-5] params, params_covariance = optimize.curve_fit(B, X, Y, p0=[0., 0.]) print(' -> fit: m = {0:.2f} {1}/byte, c = {2:.2f}'.format(params[0], yLabel, params[1])) plot.legend() xmin, xmax = plot.xlim() plot.xlim(0., xmax) ymin, ymax = plot.ylim() plot.ylim(0., ymax) plot.xlabel(r'Payload Size') plot.ylabel(yLabel) plot.grid(which='major', color='#DDDDDD', linewidth=0.9) plot.grid(which='minor', color='#EEEEEE', linestyle=':', linewidth=0.7) plot.minorticks_on() plot.title("ARM Cortex-M4, STM32F429 @100 MHz, mbedTLS 2.16.2") plot.show() # # _____________________________________________________________________________ # if __name__ == "__main__": main(sys.argv[1:]);
true
eb5f96040b28117c9eb9ba2de75148ae7612f202
Python
RiceeeChang/PythonPractice
/newTest.py
UTF-8
137
3.28125
3
[]
no_license
class Some: def __init__(self, number): self.number = number def printSome(self): print(self.number+5) s = Some(10) s.printSome()
true
19b8f0b2cfa88ca64a75f9cffd0d2d90ea9a116c
Python
dxl2016/Leetcode-Contest
/Weekly Contest 183/1404. Number of Steps to Reduce a Number in Binary Representation to One.py
UTF-8
296
3.09375
3
[]
no_license
class Solution: def numSteps(self, s: str) -> int: s_int = int(s, 2) ans = 0 while(s_int != 1): if s_int%2 == 1: s_int += 1 ans += 1 else: s_int //= 2 ans += 1 return ans
true
a5f6f88eec1d9fd4156205eeb5716c03d16114a9
Python
heidonomm/mhopRL
/DQNAnalyser.py
UTF-8
5,813
2.53125
3
[]
no_license
import json from collections import defaultdict import nltk import torch from utils import words_to_ids from dqn import DQNTrainer class DQNAnalyser(DQNTrainer): def __init__(self): super().__init__() self.model.load_state_dict(torch.load('constrained_verb_only.pt')) self.action_predicted_correctly = defaultdict(int) self.action_predicted_falsely = defaultdict(int) self.questions_predicted_correctly = dict() self.questions_predicted_falsely = dict() self.questions_where_predictions_are_different = dict() def load_action_dictionary(self): return open("toy_data/verb_only/constrained_predicate_list.txt").read().splitlines() def load_training_dataset(self): return open("toy_data/verb_only/constrained_training_data.txt").readlines() def model_make_step(self, state_rep, data_index, correct_indices): with torch.no_grad(): statept = torch.LongTensor(state_rep) state_embeds = self.model.get_embeds(statept) x = self.model.get_encoding(state_embeds.unsqueeze(0)) q_values = self.model.predicate_pointer(x) one_hot_y_true = self.get_correct_one_hot_encoded_action_indices( json.loads(self.training_dataset[data_index])) if one_hot_y_true is None: return 0 if len(one_hot_y_true) == 0: return 0 chosen_index = torch.argmax(self.model.softmax(q_values), dim=1) reward = 0 for i, fact_idxs in enumerate(correct_indices): if chosen_index.item() in fact_idxs: reward = 1 correct_indices.pop(i) return chosen_index, reward, correct_indices def evaluate(self): self.model.eval() for data_index in range(len(self.training_dataset)): row = json.loads(self.training_dataset[data_index]) question = row['question'] print(question) correct_indices = self.get_action_indices(row) pred_indices = list() pred_strings = list() state_reps = list() """ Step 1 """ state_rep1 = words_to_ids(self.preprocess( row['formatted_question']), self.word2index) state_reps.append(state_rep1) chosen_index1, reward1, correct_indices = self.model_make_step( state_rep1, data_index, correct_indices) pred_indices.append(chosen_index1) pred_strings.append(self.all_actions[chosen_index1]) if reward1 == 1: self.action_predicted_correctly[pred_strings[-1]] += 1 else: self.action_predicted_falsely[pred_strings[-1]] += 1 """ Step 2 """ state_rep2 = state_rep1 + \ words_to_ids(f" {pred_strings[-1]}", self.word2index) state_reps.append(state_rep2) chosen_index2, reward2, correct_indices = self.model_make_step( state_rep2, data_index, correct_indices) pred_indices.append(chosen_index2) pred_strings.append( self.all_actions[int(pred_indices[-1])]) if reward2 == 1: self.action_predicted_correctly[pred_strings[-1]] += 1 else: self.action_predicted_falsely[pred_strings[-1]] += 1 if reward1 == 1 and reward2 == 1: self.questions_predicted_correctly[question] = ( pred_strings[-2], pred_strings[-1]) if reward1 == 0 and reward2 == 0: self.questions_predicted_falsely[question] = ( pred_strings[-2], pred_strings[-1]) if pred_strings[-2] != pred_strings[-1]: self.questions_where_predictions_are_different[question] = ( pred_strings[-2], pred_strings[-1]) print(len(self.training_dataset)) self.write_analysis_files() def write_analysis_files(self): with open("toy_data/verb_only/analysis_files/predicate_counts.txt", "w") as out_file: correct_keys = self.action_predicted_correctly.keys() for key in correct_keys: if key in self.action_predicted_falsely.keys(): out_file.write( f"{key} | wrongly: {self.action_predicted_falsely[key]}, correctly: {self.action_predicted_correctly[key]}\n") else: out_file.write( f"{key} | correctly: {self.action_predicted_correctly[key]}\n") for key in self.action_predicted_falsely.keys(): if key not in correct_keys: out_file.write( f"{key} | correctly: {self.action_predicted_falsely[key]}\n") with open("toy_data/verb_only/analysis_files/q_all_correct.txt", "w") as out_file: for question in self.questions_predicted_correctly.keys(): out_file.write( f"{question} | {self.questions_predicted_correctly[question]}\n") with open("toy_data/verb_only/analysis_files/q_all_wrong.txt", "w") as out_file: for question in self.questions_predicted_falsely.keys(): out_file.write( f"{question} | {self.questions_predicted_falsely[question]}\n") with open("toy_data/verb_only/analysis_files/q_different_predictions.txt", "w") as out_file: for question in self.questions_where_predictions_are_different.keys(): out_file.write( f"{question} | {self.questions_where_predictions_are_different[question]}\n")
true
8c173b57c9754f022876a283c8cd8549530469b0
Python
m-L-0/17b-Wangshuyun-2015
/FashionMNIST Challenge/code/cnn.py
UTF-8
4,987
2.625
3
[ "MIT" ]
permissive
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np #训练集数据的引入 reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(["/home/srhyme/ML project/DS/train.tfrecords"]) _, example = reader.read(filename_queue) features = tf.parse_single_example( example,features={ 'image_raw': tf.FixedLenFeature([], tf.string), 'pixels': tf.FixedLenFeature([], tf.int64), 'label': tf.FixedLenFeature([], tf.int64), }) train_images = tf.decode_raw(features['image_raw'], tf.uint8) train_labels = tf.cast(features['label'], tf.int32) train_pixels = tf.cast(features['pixels'], tf.int32) #测试集数据的引入 reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(["/home/srhyme/ML project/DS/test.tfrecords"]) _, example = reader.read(filename_queue) features = tf.parse_single_example( example,features={ 'image_raw': tf.FixedLenFeature([], tf.string), 'pixels': tf.FixedLenFeature([], tf.int64), 'label': tf.FixedLenFeature([], tf.int64), }) test_images = tf.decode_raw(features['image_raw'], tf.uint8) test_labels = tf.cast(features['label'], tf.int32) test_pixels = tf.cast(features['pixels'], tf.int32) #数据集的预处理 with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) train_image=[] train_label=[] temp_image=[] temp_label=[] for i in range(55000): image,label=sess.run([train_images,train_labels]) temp_image.append(image) temp=np.zeros((1,10)) temp[0][label]=1 temp_label.append(temp[0]) for j in range(1100): train_image.append(np.array(temp_image[j*50:j*50+50])/255) train_label.append(np.array(temp_label[j*50:j*50+50])/255) print('训练集已加载完毕') temp_image=[] temp_label=[] test_image=[] test_label=[] for i in range(500): image,label=sess.run([test_images,test_labels]) temp_image.append(image/255) temp=np.zeros((1,10)) temp[0][label]=1 temp_label.append(temp[0]) test_image=np.array(temp_image) test_label=np.array(temp_label) print('测试集已加载完毕') #初始化权重 def weight (shape): temp = tf.truncated_normal(shape=shape, stddev = 0.1) return tf.Variable(temp) #初始化偏置值 def bias (shape): temp = tf.constant(0.1, shape = shape) return tf.Variable(temp) #卷积,步长为1,采用SAME边界处理 def convolution (data,weight): return tf.nn.conv2d(data,weight,strides=[1,1,1,1],padding='SAME') #最大池化,步长为2,采用SAME边界处理,滑动窗为2*2 def pooling (data): return tf.nn.max_pool(data,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') #定义输入数据,其中None,-1代表数量不定, x=tf.placeholder(tf.float32,[None,784]) data_image = tf.reshape(x,[-1,28,28,1]) #第一层:一次卷积一次池化 w_1=weight([5,5,1,32]) b_1=bias([32]) #使用relu激活函数处理数据 d_conv1=tf.nn.relu(convolution(data_image,w_1)+b_1) d_pool1=pooling(d_conv1) #第二层:一次卷积一次池化 w_2=weight([5,5,32,64]) b_2=bias([64]) d_conv2=tf.nn.relu(convolution(d_pool1,w_2)+b_2) d_pool2=pooling(d_conv2) #第三层:全连接 w_3=weight([7*7*64,1024]) b_3=bias([1024]) d_3=tf.reshape(d_pool2,[-1,7*7*64]) d_fc3=tf.nn.relu(tf.matmul(d_3,w_3)+b_3) #dropout操作,防止过拟合 keep_prob=tf.placeholder(tf.float32) d_fc3_drop=tf.nn.dropout(d_fc3,keep_prob) #第四层:softmax输出 w_4=weight([1024,10]) b_4=bias([10]) d_4=tf.nn.softmax(tf.matmul(d_fc3_drop,w_4)+b_4) #定义损失函数(交叉熵),并用ADAM优化器优化 y = tf.placeholder("float", [None, 10]) loss_function = - tf.reduce_sum(y * tf.log(d_4)) optimizer = tf.train.AdamOptimizer(0.0001).minimize(loss_function) #判断预测标签和实际标签是否匹配 correct = tf.equal(tf.argmax(d_4,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct,"float")) sess = tf.Session() sess.run(tf.global_variables_initializer()) #利用tensorboard实现loss的可视化 tf.summary.scalar('loss',loss_function) summary_op = tf.summary.merge_all() summary_writer = tf.summary.FileWriter('./graph', sess.graph) #运行与打印 for i in range(1100): if i % 100 == 0: train_accuracy = accuracy.eval(session = sess, feed_dict = {x:train_image[i], y:train_label[i], keep_prob:1.0}) print("step %d, train_accuracy %g" %(i, train_accuracy)) # optimizer.run(session = sess, feed_dict = {x:train_image[i], y:train_label[i],keep_prob:0.5}) summary_str, _ = sess.run([summary_op, optimizer], feed_dict = {x:train_image[i], y:train_label[i],keep_prob:0.5}) summary_writer.add_summary(summary_str,i) print("test accuracy %g" % accuracy.eval(session = sess, feed_dict = {x:test_image, y:test_label, keep_prob:1.0}))
true
fbf4e28a040a9615e2ea31e13f7d5d9221307483
Python
sachinyar/Python_Machine-Learning_Codes
/sna/word.py
UTF-8
306
2.9375
3
[]
no_license
fp=open("title.txt",'r') fp1=open("word_freqYEAR.csv",'w') fp1.write("Word, Year\n") while True: line=fp.readline() if not line: break tk=line.split('@') tk1=tk[0].split(' ') for i in range(0,len(tk1)-1): fp1.write(str(tk1[i])+","+str(tk[1])+"\n") fp.close() fp1.close()
true
c70a37d563376b65682b2ac5750702012b16ca3e
Python
tobarg/python
/outbrain.py
UTF-8
1,051
3.234375
3
[]
no_license
outbrain = open('ob2015.txt') keywords = list() counts = dict() for line in outbrain: line = line.rstrip() line = line.split() for word in line: word = word.lower() #replace characters word = word.replace('-',' ').replace('"','').replace(":",'').replace('?','').replace(',','') keywords.append(word) keywords.sort() print keywords #count words - long method for kw in keywords: if kw not in counts: counts[kw] = 1 else: counts[kw] = counts[kw] + 1 #print counts #count words - using get() for kw in keywords: counts[kw] = counts.get(kw,0) + 1 for key in counts: print key, counts[key] #tuple #print counts.items() top = list() for keys,values in sorted(counts.items()): top.append((values,keys)) top.sort(reverse=True) for values,keys in top[:20]: print values,keys bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print 'Top Word:',bigword, bigcount
true
9bfe27e1f2e2d1085c5f381d80ff81a490284882
Python
x10-utils/nlpaug
/nlpaug/augmenter/word/word_embs.py
UTF-8
6,834
2.609375
3
[ "MIT" ]
permissive
""" Augmenter that apply operation to textual input based on word embeddings. """ from nlpaug.augmenter.word import WordAugmenter from nlpaug.util import Action import nlpaug.model.word_embs as nmw from nlpaug.util.exception.warning import WarningMessage WORD2VEC_MODEL = None GLOVE_MODEL = {} FASTTEXT_MODEL = {} model_types = ['word2vec', 'glove', 'fasttext'] def init_word2vec_model(model_path, force_reload=False, top_k=100): # Load model once at runtime global WORD2VEC_MODEL if WORD2VEC_MODEL and not force_reload: WORD2VEC_MODEL.top_k = top_k return WORD2VEC_MODEL word2vec = nmw.Word2vec(top_k=top_k) word2vec.read(model_path) WORD2VEC_MODEL = word2vec return WORD2VEC_MODEL def init_glove_model(model_path, force_reload=False, top_k=None): # Load model once at runtime global GLOVE_MODEL if model_path in GLOVE_MODEL and not force_reload: GLOVE_MODEL[model_path].top_k = top_k return GLOVE_MODEL[model_path] glove = nmw.GloVe(top_k=top_k) glove.read(model_path) GLOVE_MODEL[model_path] = glove return GLOVE_MODEL[model_path] def init_fasttext_model(model_path, force_reload=False, top_k=None): # Load model once at runtime global FASTTEXT_MODEL if model_path in FASTTEXT_MODEL and not force_reload: FASTTEXT_MODEL[model_path].top_k = top_k return FASTTEXT_MODEL[model_path] fasttext = nmw.Fasttext(top_k=top_k) fasttext.read(model_path) FASTTEXT_MODEL[model_path] = fasttext return FASTTEXT_MODEL[model_path] class WordEmbsAug(WordAugmenter): # https://aclweb.org/anthology/D15-1306, https://arxiv.org/pdf/1804.07998.pdf, https://arxiv.org/pdf/1509.01626.pdf # https://arxiv.org/ftp/arxiv/papers/1812/1812.04718.pdf """ Augmenter that leverage word embeddings to find top n similar word for augmentation. :param str model_type: Model type of word embeddings. Expected values include 'word2vec', 'glove' and 'fasttext'. :param str model_path: Downloaded model directory. Either model_path or model is must be provided :param obj model: Pre-loaded model :param str action: Either 'insert or 'substitute'. If value is 'insert', a new word will be injected to random position according to word embeddings calculation. If value is 'substitute', word will be replaced according to word embeddings calculation :param int top_k: Controlling lucky draw pool. Top k score token will be used for augmentation. Larger k, more token can be used. Default value is 100. If value is None which means using all possible tokens. :param float aug_p: Percentage of word will be augmented. :param int aug_min: Minimum number of word will be augmented. :param int aug_max: Maximum number of word will be augmented. If None is passed, number of augmentation is calculated via aup_p. If calculated result from aug_p is smaller than aug_max, will use calculated result from aug_p. Otherwise, using aug_max. :param int aug_n : Deprecated. Use top_k as alternative. Top n similar word for lucky draw :param list stopwords: List of words which will be skipped from augment operation. :param func tokenizer: Customize tokenization process :param func reverse_tokenizer: Customize reverse of tokenization process :param bool force_reload: If True, model will be loaded every time while it takes longer time for initialization. :param str name: Name of this augmenter >>> import nlpaug.augmenter.word as naw >>> aug = naw.WordEmbsAug(model_type='word2vec', model_path='.') """ def __init__(self, model_type, model_path='.', model=None, action=Action.SUBSTITUTE, name='WordEmbs_Aug', aug_min=1, aug_max=10, aug_p=0.3, top_k=100, aug_n=None, n_gram_separator='_', stopwords=None, tokenizer=None, reverse_tokenizer=None, force_reload=False, verbose=0): super().__init__( action=action, name=name, aug_p=aug_p, aug_min=aug_min, aug_max=aug_max, stopwords=stopwords, tokenizer=tokenizer, reverse_tokenizer=reverse_tokenizer, device='cpu', verbose=verbose) self.model_type = model_type self.model_path = model_path self.top_k = top_k if aug_n is not None: print(WarningMessage.DEPRECATED.format('aug_n', '0.11.0', 'top_k')) self.top_k = aug_n self.n_gram_separator = n_gram_separator self.pre_validate() if model is None: self.model = self.get_model(model_type=model_type, force_reload=force_reload, top_k=self.top_k) else: self.model = model def pre_validate(self): if self.model_type not in model_types: raise ValueError('Model type value is unexpected. Expected values include {}'.format(model_types)) def get_model(self, model_type, force_reload=False, top_k=100): if model_type == 'word2vec': return init_word2vec_model(self.model_path, force_reload, top_k=top_k) elif model_type == 'glove': return init_glove_model(self.model_path, force_reload, top_k=top_k) elif model_type == 'fasttext': return init_fasttext_model(self.model_path, force_reload, top_k=top_k) else: raise ValueError('Model type value is unexpected. Expected values include {}'.format(model_types)) def skip_aug(self, token_idxes, tokens): results = [] for token_idx in token_idxes: # Some words do not come with vector. It will be excluded in lucky draw. word = tokens[token_idx] if word in self.model.w2v: results.append(token_idx) return results def insert(self, data): tokens = self.tokenizer(data) results = tokens.copy() aug_idexes = self._get_random_aug_idxes(tokens) if aug_idexes is None: return data aug_idexes.sort(reverse=True) for aug_idx in aug_idexes: new_word = self.sample(self.model.get_vocab(), 1)[0] if self.n_gram_separator in new_word: new_word = new_word.split(self.n_gram_separator)[0] results.insert(aug_idx, new_word) return self.reverse_tokenizer(results) def substitute(self, data): tokens = self.tokenizer(data) results = tokens.copy() aug_idexes = self._get_aug_idxes(tokens) if aug_idexes is None: return data for aug_idx in aug_idexes: original_word = results[aug_idx] candidate_words = self.model.predict(original_word, n=1) substitute_word = self.sample(candidate_words, 1)[0] results[aug_idx] = substitute_word return self.reverse_tokenizer(results)
true
f42cd7d8e8d96a6a1fa930161f443b3e3504fd2a
Python
lowks/python-prompt-toolkit
/prompt_toolkit/code.py
UTF-8
3,672
3.109375
3
[ "BSD-3-Clause" ]
permissive
""" The `Code` object is responsible for parsing a document, received from the `Line` class. It's usually tokenized, using a Pygments lexer. """ from __future__ import unicode_literals from pygments.token import Token __all__ = ( 'Code', 'CodeBase', 'Completion' 'ValidationError', ) class Completion(object): def __init__(self, display='', suffix=''): # XXX: rename suffix to 'addition' self.display = display self.suffix = suffix def __repr__(self): return 'Completion(display=%r, suffix=%r)' % (self.display, self.suffix) class ValidationError(Exception): def __init__(self, line, column, message=''): self.line = line self.column = column self.message = message class CodeBase(object): """ Dummy base class for Code implementations. The methods in here are methods that are expected to exist for the `Line` and `Renderer` classes. """ def __init__(self, document): self.document = document self.text = document.text self.cursor_position = document.cursor_position def get_tokens(self): return [(Token, self.text)] def complete(self): """ return one `Completion` instance or None. """ # If there is one completion, return that. completions = list(self.get_completions(True)) # Return the common prefix. return _commonprefix([ c.suffix for c in completions ]) def get_completions(self, recursive=False): """ Yield `Completion` instances. """ if False: yield def validate(self): """ Validate the input. If invalid, this should raise `self.validation_error`. """ pass class Code(CodeBase): """ Representation of a code document. (Immutable class -- caches tokens) :attr document: :class:`~prompt_toolkit.line.Document` """ #: The pygments Lexer class to use. lexer_cls = None def __init__(self, document): super(Code, self).__init__(document) self._tokens = None @property def _lexer(self): """ Return lexer instance. """ if self.lexer_cls: return self.lexer_cls( stripnl=False, stripall=False, ensurenl=False) else: return None def get_tokens(self): """ Return the list of tokens for the input text. """ # This implements caching. Usually, you override `_get_tokens` if self._tokens is None: self._tokens = self._get_tokens() return self._tokens def get_tokens_before_cursor(self): """ Return the list of tokens that appear before the cursor. If the cursor is in the middle of a token, that token will be split. """ count = 0 result = [] for c in self.get_tokens(): if count + len(c[1]) < self.cursor_position: result.append(c) count += len(c[1]) elif count < self.cursor_position: result.append((c[0], c[1][:self.cursor_position - count])) break else: break return result def _get_tokens(self): if self._lexer: return list(self._lexer.get_tokens(self.text)) else: return [(Token, self.text)] def _commonprefix(strings): # Similar to os.path.commonprefix if not strings: return '' else: s1 = min(strings) s2 = max(strings) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
true
9e069b61a4f9ac34ceccec8920882762e0b6776a
Python
tartarica/Mephisto
/src/scripts/mephisto-clicker.py
UTF-8
1,517
2.90625
3
[]
no_license
from random import random import pyautogui import argparse from flask import Flask, request app = Flask(__name__) parser = argparse.ArgumentParser(description='A simple backend to perform simulated clicks for the Mephisto chrome extension.') parser.add_argument('--port', '-p', dest='port', action='store', default=8080, help='The port to run the server on. (default: 8080)') parser.add_argument('--drag-time', '-d', dest='drag_time', action='store', default=100, help='Time to drag a piece in ms. (default: 75) [with defaults: 75ms - 125ms]') parser.add_argument('--drag-var', '-v', dest='drag_variance', action='store', default=20, help='Variance for time to drag a piece in ms. (default: 50)') args = parser.parse_args() def perform_click(x, y): duration = (args.drag_variance * random() + args.drag_time) / 1000 pyautogui.moveTo(x, y, duration=duration) pyautogui.mouseDown() pyautogui.mouseUp() def perform_move(x0, y0, x1, y1): perform_click(x0, y0) pyautogui.sleep(4) perform_click(x1, y1) @app.route('/performClick', methods=['POST']) def perform_click_api(): data = request.get_json() perform_click(data.get('x'), data.get('y')) return 'OK' @app.route('/performMove', methods=['POST']) def perform_move_api(): data = request.get_json() perform_move(data.get('x0'), data.get('y0'), data.get('x1'), data.get('y1')) return 'OK' if __name__ == '__main__': app.run(port=args.port)
true
12d9bed08cfd2f284a1899cf671256f7a5fcb8de
Python
Dranoxgithub/covid-webscraping
/Colorado/scripts/douglas.py
UTF-8
1,728
2.875
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[114]: import urllib.request from urllib.request import Request, urlopen import re from bs4 import BeautifulSoup as soup url = 'https://www.douglas.co.us/douglascovid19/' req = Request(url , headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() page_soup = soup(webpage, "html.parser") title = page_soup.find("title") print(title) # In[115]: linksinfo=[] content = page_soup.findAll("p") links= page_soup.findAll("a") for cont in content: print(cont.get_text()) for i in links: linksinfo.append(i.get_text() + ": " + str(i.get('href'))) print(i.get_text()) print(i.get('href')) with open(r"../data/douglas.txt",'w') as outfile: outfile.write("Scraping from " + url + "\n" + "\n") for i in content: print(i.get_text(separator = '\n'), file=outfile) # In[116]: import urllib.request import urllib.parse import requests from requests import get import os from bs4 import BeautifulSoup county="douglas" url = 'https://www.douglas.co.us/douglascovid19/' download_path = "../data/" + county + "-PDF" os.mkdir(download_path) headers = {'User-Agent':'Mozilla/5.0'} request = urllib.request.Request(url, None, headers) html = urllib.request.urlopen(request) soup = BeautifulSoup(html.read(),"html.parser") for tag in soup.findAll('a', href=True): if os.path.splitext(os.path.basename(tag['href']))[1] == '.pdf': print(tag['href']) a = os.path.join(download_path,tag['href'].split('/')[-1]) f = open(a, "wb") response = requests.get(tag['href'], headers=headers) f.write(response.content) f.close() # In[ ]: # In[ ]:
true
feae72433ddb7d7e310d4b308941ddeb7af8efb8
Python
lakshmanboddoju/Deep_Learning_Prerequisites_The_Numpy_Stack_in_Python
/3/19-values_vs_as_matrix.py
UTF-8
146
3.203125
3
[]
no_license
#! python3 import pandas as pd import numpy as np df = pd.DataFrame([[1, 2], [3, 4]]) print(df) print(df.as_matrix()) print(df.values)
true
227fee901daede38870669fb9801f5e39daf84f0
Python
diversen/project-euler
/54.py
UTF-8
4,414
3.421875
3
[]
no_license
""" Python solution to project euler problem 54 """ class Poker(object): def read_file (self, file_name = None): file_name = 'resources/p054_poker.txt' f = open(file_name) fc = f.read() return fc def convert_hand(self, hand): """ convert T to A from 10 to 14. Convert to ints """ n_hand = [] for c in hand: cards = list(c) if cards[0] == 'T': cards[0] = 10 elif cards[0] == 'J': cards[0] = 11 elif cards[0] == 'Q': cards[0] = 12 elif cards[0] == 'K': cards[0] = 13 elif cards[0] == 'A': cards[0] = 14 elif True: cards[0] = int(cards[0]) n_hand.append(cards) # Sort by card weights 2 -> 14 n_hand.sort(key=lambda x: x[0]) return n_hand def high_card(self, hand): """ Get hightest card """ return 0 + hand[4][0] def identical_count(self, hand): """ Get number of identical counts """ d = {} for c in hand: d[c[0]] = 0 for c in hand: d[c[0]] += 1 return d # Return pair value or 0 def pair(self, hand): d = self.identical_count(hand) for key, value in d.items(): if value == 2: return key return 0 def two_pair(self, hand): d = self.identical_count(hand) pairs = [] for key, value in d.items(): if value == 2: pairs.append(key) if len(pairs) == 2: pairs.sort(reverse=True) return [pairs[0], pairs[1]] return [] def three_kind(self, hand): d = self.identical_count(hand) for key, value in d.items(): if value == 3: return key return 0 def straight(self, hand): nums = [] for n in hand: nums.append(n[0]) if nums[1] != (nums[0] + 1): return 0 if nums[2] != (nums[1] + 1): return 0 if nums[3] != (nums[2] + 1): return 0 if nums[4] != (nums[3] + 1): return 0 return nums[4] def flush(self, hand): d = {} for c in hand: d[c[1]] = 0 for c in hand: d[c[1]] += 1 for _, value in d.items(): if value == 5: return hand[4][0] return 0 def full_house(self, hand): if self.three_kind(hand) and self.pair(hand): return [self.three_kind(hand), self.pair(hand)] return [] def four_kind(self, hand): d = self.identical_count(hand) for key, value in d.items(): if value == 4: return key return 0 def straight_flush(self, hand): if self.straight(hand) and self.flush(hand): return hand[4][0] return 0 def get_points(self, hand): sf = self.straight_flush(hand) if sf: return 10**9 + sf sf = self.four_kind(hand) if sf: return 10**8 + sf fh = self.full_house(hand) if fh: return 10**7 + (fh[0] * 10**2) + (fh[1] * 10) fl = self.flush(hand) if fl: return 10**6 + fl st = self.straight(hand) if st: return 10**5 + st tk = self.three_kind(hand) if tk: return 10**4 + tk tp = self.two_pair(hand) if tp: return 10**3 + (tp[0] * 10**2) + (tp[1] * 10) pa = self.pair(hand) if pa: return 10**2 + pa hc = self.high_card(hand) return hc def get_winner(self, hands): pass def run_games(self): fc = self.read_file() lines = fc.split('\n') p1_wins = 0 for l in lines: if (l == ''): continue game = l.split(' ') player_1 = self.convert_hand(game[0:5]) player_2 = self.convert_hand(game[5:]) if self.get_points(player_1) > self.get_points(player_2): p1_wins += 1 print('player one wins', p1_wins) def test(): p = Poker() p.run_games() import timeit timer = timeit.timeit(stmt = test, number = 1) print("In time: ", timer, 'secs')
true
77e7b890d247f74cc76c17cc9c70e9c151c32ac9
Python
pronobility/Laci
/guiablak.py
UTF-8
201
2.640625
3
[]
no_license
from tkinter import * abl1 = Tk() tex1 = Label(abl1, text='Jó napot kívánok!', fg='red') tex1.pack() gomb1 = Button(abl1, text='Kilép', command = abl1.destroy) gomb1.pack() abl1.mainloop()
true
c79836c5bed2ac7049cba677cbf9d86a8d2a3f2b
Python
russelldmatt/brain-teasers
/brain-teasers/reverse-birthday-problem/solve.py
UTF-8
638
3.40625
3
[]
no_license
import math from memoize import memoize @memoize def factorial(n): return math.factorial(n) @memoize def choose(n, k): return factorial(n)/factorial(k)/factorial(n-k) @memoize def f(n, k): return k**n - sum([choose(k,i) * f(n, i) for i in xrange(1, k)]) def enough(N): return f(N, 365) > 365**N / 2 def tighten(too_low, too_high): if too_high - too_low == 1: return (too_low, too_high) else: mid = (too_low + too_high) / 2 print "trying ", mid if enough(mid): return tighten(too_low, mid) else: return tighten(mid, too_high) print tighten(1,10000)
true
9e6534888e7ced5ca4b8c6f51d00551f30e0efb7
Python
aparecida-gui/learning-python
/exercicios/multiplicao.py
UTF-8
479
4.375
4
[ "MIT" ]
permissive
""" Você recebe um integer positivo. Sua função deve calcular o produto dos digitos excluindo qualquer Zeros. Por exemplo: O numero dado é 123405. O resultado será 1*2*3*4*5=120 (Não esquece de excluir os Zeros). """ def checkio(number: int) -> int: produtoDaMultiplicacao = 1 number = str(number) for t in number: if t != '0': t = int(t) produtoDaMultiplicacao *= t return produtoDaMultiplicacao print(checkio(123405))
true
7dff54c2fa8d6417d1b479db60142a8da80a725b
Python
Win-Htet-Aung/kattis-solutions
/datum.py
UTF-8
226
3.59375
4
[ "MIT" ]
permissive
import calendar weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] s = input() d = int(s.split()[0]) m = int(s.split()[1]) y = 2009 wd = calendar.weekday(y, m, d) print(weekdays[wd])
true
a4cb01b106d8a8d01c9799cf46ff63b98dfb772d
Python
shshivam/SFWRTECH3RQ3_Project_Tests
/tests/test_accountregistration.py
UTF-8
5,051
2.515625
3
[]
no_license
import datetime from dinnerisserved.account import Account from dinnerisserved.address import Address from dinnerisserved.discountcoupon import DiscountCoupon from dinnerisserved.history import History from dinnerisserved.order import Order from dinnerisserved.paymentinfo import PaymentInfo from dinnerisserved.profile import Profile # 3.1.1 Profile Creation def test_profile_creation(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) account.set_email('shivam@xyz.com') assert account.name == 'Shivam' and account.email == 'shivam@xyz.com' and account.password == 'password' and account.username == 'shars48', "Account should be created" # 3.1.2 Email Verification def test_valid_email_verification(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) account.set_email('shivam@xyz.com') assert account.email == 'shivam@xyz.com', "Valid email should be added" # 3.1.2 Email Verification def test_invalid_email_verification(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) account.set_email('shivam-xyz.com') assert account.email != 'shivam-xyz.com', "Invalid email should not be added" # 3.1.3 Login for existing users def test_valid_login(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) assert account.authenticate('shars48', 'password'), "Valid credentials should allow login" # 3.1.3 Login for existing users def test_invalid_login(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) assert account.authenticate('shars48', 'pass') is False, "Valid credentials should allow login" # 3.1.4 Check order status def test_check_order_status(): history = History('Salad', 'delivered', datetime.datetime(2020, 5, 17)) profile = Profile() profile.add_order_history(history) assert profile.order_history[0].order_status == 'delivered', "Should be able to check order status from history" # 3.1.5 Order History def test_add_order_history(): profile = Profile() assert len(profile.order_history) == 0, "Order history should be empty" history1 = History('Salad', 'delivered', datetime.datetime(2020, 5, 17)) history2 = History('Burger', 'cancelled', datetime.datetime(2020, 5, 18)) profile.add_order_history(history1) profile.add_order_history(history2) assert len(profile.order_history) == 2, "Order history should contain the items that were ordered" # 3.1.7 Save payment information def test_add_payment_info_to_account(): profile = Profile() payment_info = PaymentInfo('VISA', '0000-1111-2222-3333') profile.add_payment_info(payment_info) assert profile.payment_info.details == '0000-1111-2222-3333', "The saved payment info should be correct" # 3.1.8 Save delivery information def test_save_multiple_delivery_address(): profile = Profile() addresses = [Address('100 John Rd', 'Toronto', 'ON', 'M5R 7U6'), Address('200 Mark Blvd', 'Mississauga', 'ON', 'L5M 1Y1')] profile.add_adresses(addresses) assert len(profile.addresses) == 2, "The profile should now have two addresses" # 3.1.9 Cancel finalized order def test_cancel_order(): order = Order('100') order.set_order_type('confirmed') assert order.cancel_order(), "Should be able to cancel order if not in-progress" # 3.1.9 Cancel finalized order def test_cancel_order_in_progress(): delivery_address = Address('100 John Rd', 'Toronto', 'ON', 'M5R 7U6') order = Order('100') order.set_order_status('in-progress') assert order.cancel_order() is False, "Should not be able to cancel order if in-progress" # 3.1.10 Modify User Profile def test_modify_profile(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) account.set_email('shivam@xyz.com') assert account.email == 'shivam@xyz.com', "The current email should be returned" account.set_email('shivam@abc.com') assert account.email == "shivam@abc.com", "The updated email should be returned" # 3.1.11 Delete account def test_delete_account(): profile = Profile() account = Account('Shivam', 'shars48', 'password', profile) account.delete_account() assert account.authenticate('shars48', 'password') is False, "Should not be able to authenticate after account " \ "has been deleted" # 3.1.12 Apply Discount Coupon def test_apply_valid_discount_coupon(): coupon = DiscountCoupon('15% off', datetime.datetime(2020, 12, 30)) profile = Profile() profile.add_discount_coupon(coupon) assert len(profile.discount_coupon) == 1, "Should be able to add valid coupon" # 3.1.12 Apply Discount Coupon def test_apply_invalid_discount_coupon(): coupon = DiscountCoupon('15% off', datetime.datetime(2020, 10, 30)) profile = Profile() profile.add_discount_coupon(coupon) assert len(profile.discount_coupon) == 0, "Should not be able to add invalid coupon"
true
4323543aedc17123538b0e5f190ab219fea8866d
Python
Zacros7164/Algorithm-Friday
/11:16:18/is-prime.py
UTF-8
1,196
3.578125
4
[]
no_license
# in this universe, 2 and 3 are ALWAY prime known_primes = [2,3] finalPrime = 2 # a function that will find if a number is prime def is_prime(n): # print n total_known_primes = len(known_primes) for i in xrange(0, total_known_primes): if(n % known_primes[i] == 0): # THIS IS DIVISIBLE BY A PRIME NUMBER. # therefore it CANNOT be a prime number return False else: # its not divisible by this one... BUT that doesn't mean its not prime # its just not divisible by this number continue # we went through all KP and never hit return false, which means this must be prime known_primes.append(n) # finalPrime = known_primes[-1] if(i == total_known_primes): return True # print is_prime(31) # print is_prime(8) # print is_prime(11) # print is_prime(13) prime_factor = [] num = int(raw_input("number: ")) for i in xrange(2, num): is_prime(i) print known_primes if num % finalPrime == 0: prime_factor.append(finalPrime) if len(known_primes) > 10: del known_primes[0] # print known_primes print known_primes print prime_factor
true
42d80a74006cb9cd3289f5b324f2c323b8758231
Python
Kito-vini/curso-python
/Meus projetos/YouTube_Downloader/YT_Downloader.py
UTF-8
1,966
3.234375
3
[]
no_license
from pytube import YouTube import PySimpleGUI as sg # Criando as janelas e layouts def janelaInicial(): sg.theme('reddit') layout = [ [sg.Text('Bem vindo ao YouTube Downloader'), sg.Text(' '), sg.Text('By Kito-Vini')], [sg.Text('Digite o link do vídeo: '), sg.Input(key='url1')], [sg.Text('Digite o caminho que deseja salvar o vídeo: '), sg.Input(key='dir1')], [sg.Button('Continuar')] ] return sg.Window('YouTube Downloader', layout=layout, finalize=True) def janelaInfo(): sg.theme('reddit') title = 'Título: ' + yt.title views = 'Visualizações: ' + str(yt.views) length = 'Tamanho do vídeo: ' + str(yt.length) rating = 'Avaliação: ' + str(round(yt.rating, 2)) layout = [ [sg.Text(title)], [sg.Text(views)], [sg.Text(length)], [sg.Text(rating)], [sg.Button('Download'), sg.Button('Sair')] ] return sg.Window('Informações do vídeo', layout=layout, finalize=True) # Criando a janela inicial para exibição janela1, janela2 = janelaInicial(), None # Loop de eventos para leitura da janela while True: # Colhendo as informações das janelas window, event, values = sg.read_all_windows() link = (values['url1']) path = (values['dir1']) yt = YouTube(link) # Quando a janela for fechada if window == janela1 and event == sg.WINDOW_CLOSED: break elif window == janela1 and event == 'Continuar': janela2 = janelaInfo() janela1.hide() elif window == janela2 and event == 'Download': link = (values['url1']) path = (values['dir1']) yt = YouTube(link) # Pegar resolução máxima ys = yt.streams.get_highest_resolution() # Iniciando o download sg.popup('Iniciando Download...') ys.download(path) sg.popup('Download concluído') elif window == janela2 and event == 'Sair': break
true
da608053da2917b6e3dfe5ce04b4ffa890c8440d
Python
roei-birger/Ex3
/src/DiGraph.py
UTF-8
5,017
3.40625
3
[]
no_license
from GraphInterface import GraphInterface from NodeData import NodeData class DiGraph(GraphInterface): """This class implements a directed weighted graph. Every graph contains a map of all its vertexes, a counter of the number of the vertex in the graph, a counter of the number of edges and a counter of the number of changes that were made on the graph .""" def __init__(self): """A default constructor""" self.mc = 0 self.edge_size = 0 self.node_size = 0 self.vertices = {} # <key , NodeData> def get_node(self, node_id: int) -> NodeData: """@param node_id - the node_id @return the node of this key, null if none.""" if node_id in self.vertices: return self.vertices.get(node_id) return None def v_size(self) -> int: """@return the number of vertices (nodes) on the graph.""" return self.node_size def e_size(self) -> int: """@return the number of edges on the graph.""" return self.edge_size def get_all_v(self) -> dict: """@return a dictionary of all the nodes in the Graph, each node is represented using a pair (node_id, node_data)""" return self.vertices def all_in_edges_of_node(self, id1: int) -> dict: """@return a dictionary of all the nodes connected to (into) node_id , each node is represented using a pair (other_node_id, weight)""" return self.get_node(id1).inEdges def all_out_edges_of_node(self, id1: int) -> dict: """@return a dictionary of all the nodes connected from node_id , each node is represented using a pair (other_node_id, weight)""" return self.get_node(id1).outEdges def get_mc(self) -> int: """@return the Mode Count of the changes made on the graph.""" return self.mc def add_edge(self, id1: int, id2: int, weight: float) -> bool: """This function makes an edge from id1 to id2, by inserting one node into the neighbor's list of the others node, in addition inserting one node into the edges list of the others node. @return true if success.""" if weight >= 0 and id1 in self.vertices and id2 in self.vertices and id1 != id2: if id2 in self.get_node(id1).outEdges: return False self.edge_size = self.edge_size + 1 self.mc = self.mc + 1 self.get_node(id1).addNi(self.get_node(id2), weight) return True return False def add_node(self, node_id: int, pos: tuple = None) -> bool: """Add a new node to the graph with the node_id that was received. @param node_id @param pos @return true if success.""" if node_id in self.vertices: return False self.vertices[node_id] = NodeData(node_id, 0, pos) if len(self.vertices) == self.node_size + 1: self.node_size = self.node_size + 1 self.mc = self.mc + 1 return True def remove_node(self, node_id: int) -> bool: """The function passes over all the neighbors of the vertex and removes the common edges. Finally deletes the vertex from the graph. @return true if success.""" if node_id not in self.vertices: return False counter = len(self.get_node(node_id).outEdges) for i in self.vertices.keys(): if i != node_id: if node_id in self.get_node(i).inEdges: self.get_node(node_id).removeNode(self.get_node(i)) self.edge_size = self.edge_size - 1 self.mc = self.mc + 1 if node_id in self.get_node(i).outEdges: self.get_node(i).removeNode(self.get_node(node_id)) self.edge_size = self.edge_size - 1 self.mc = self.mc + 1 self.edge_size = self.edge_size - counter self.vertices.pop(node_id) self.node_size = self.node_size - 1 self.mc = self.mc + 1 return True def remove_edge(self, node_id1: int, node_id2: int) -> bool: """This function removes the edge that exists between two vertexes. and removes it from all the edges lists it was on . @param node_id1 @param node_id2 @return true if success.""" if node_id1 != node_id2 and node_id1 in self.vertices and node_id2 in self.vertices and \ node_id2 in self.get_node(node_id1).outEdges: self.get_node(node_id1).removeNode(self.get_node(node_id2)) self.edge_size = self.edge_size - 1 self.mc = self.mc + 1 return True return False def __str__(self) -> str: """@return a string (str) representation of the DiGraph""" return f"{self.vertices}" def __repr__(self) -> str: """@return a string (repr) representation of the DiGraph""" return f"{self.vertices}"
true
e8e16702da3a76d91cdd29586b7b4d117721b856
Python
BillMaZengou/nature_of_code
/0_Introduction/03_gaussian_distribution/visual_gaussian_distribution.py
UTF-8
710
3.21875
3
[]
no_license
import numpy as np from turtle import * home() std = 100 initial_colour = (0.98, 0.98, 0.98) number_occur = [] while True: h = np.random.randn() h *= std if h not in number_occur: color_factor = number_occur - np.ones_like(number_occur) * h color_factor = [abs(x) <= 10 for x in color_factor] color_factor = sum(color_factor) number_occur.append(h) else: color_factor = 20 penup() goto(h, 0) pendown() if color_factor <= 0: colour = initial_colour else: colour_list = np.divide(initial_colour, color_factor) colour = (colour_list.item(0), colour_list.item(1), colour_list.item(2)) dot(20, colour) done()
true
33b0e3184fddb3e49b4225d46c28208f3bb5077f
Python
melissabaljeet/melissabaljeet.github.io
/sensor.py
UTF-8
387
2.828125
3
[]
no_license
us_dist(15) from gopigo import * def turn_right(): enc_tgt(0,1,2) time.sleep(.1) fwd() time.sleep(5) def turn_left(): enc_tgt(1,0, 2) time.sleep(.1) fwd() time.sleep(5) print us_dist(15) for i in range(1, 10): while us_dist(15) >= 20: servo(90) fwd() if us_dist(15) > 20: servo(180) turn_right() else us_dist(15) < 20: servo(0) turn_left()
true
e345a738c72d688a104e15b2082cb7cbcd7d5c8d
Python
ShlokMohanty/python
/interacting_with_files.py
UTF-8
1,216
3.53125
4
[]
no_license
#interacting with files #its pretty common to need to read xmen_file = open('xmen_base.txt', 'r') xmen_file xmen_file.read() xmen_file.seek(0) xmen_file.read() for line in xmen_file : print(line, end="") #storm #wolverine #Cyclops #Bishop #Nightcrawler xmen_file.close() xmen_base = open('xmen_base.txt') new_xmen = open('new_xmen.txt','w') new_xmen.write(xmen_base.read()) new_xmen.close() new_xmen = open(new_xmen.name, 'r+') new_xmen.read() #read from the base file and used the return value as teh argument to write for our new file . #we closed the new file #we reopened the new file, using the r+ mode which will allow us to read and write content to the file. #we read the content from the new file to ensure that it wrote properly #Now taht we have a file that we can read and write from lets add some more names : new_xmen.seek(0) new_xmen.write("Beast\n") new_xmen.write("Phoenix\n") new_xmen.seek(0) new_xmen.read() #Appending to the file xmen_file.close() with open('xmen_base.txt', 'a') as f: f.write('Professor Xavier\n') f = open('xmen_base.txt', 'a') with f: f.write('Something\n') exit() #Functions are a great way to organize your code for reuse and clarity .script does the following:
true
1fb98df3e0bcc56a78295f430c661a7d17130869
Python
royam0820/Python-Course-Tutorial
/files/gettingSleepy.py
UTF-8
145
3.65625
4
[]
no_license
from time import sleep duration = 5 print("Getting sleepy. See you in", duration, "seconds") sleep(duration) print("I'm back. What did I miss?")
true
571db98bbbad0db3f90e522e7574449592d37268
Python
jegerima/ProyectoSIIGrupo6
/fst.py
UTF-8
162
3.34375
3
[]
no_license
def multiply() : print str(2 * 5) def modulo() : print str(5%2) def main(): print str(2 + 5) print str(5-2) modulo() if __name__ == "__main__": main()
true
91428b045807bfec174e61ddfdc93f6cadba7366
Python
SmallLogin/UAV-hybrid-motion-planning-with-privacy-concerns
/GA/mapTools.py
UTF-8
5,228
2.734375
3
[]
no_license
# map generation tools import numpy as np from random import randint import math # 隐私部分的初始化 def privacy_init(grid_x, grid_y, grid_z, occ_grid, radius): #print(radius[0]) pri_grid = np.zeros((grid_x, grid_y, grid_z)) for i in range(grid_x): for j in range(grid_y): for k in range(grid_z): # 这里隐私等级分为三级,数字越大,级别越高 if (occ_grid[i][j][k] == 2) or (occ_grid[i][j][k] == 3) or (occ_grid[i][j][k] == 4): # different level of privacy restricted area has different affecting radius: temp = int (occ_grid[i][j][k]) r = radius[temp-2] min_x = max(i - r, 0) min_x = math.floor(min_x) max_x = min(i + r, grid_x - 1) max_x = math.ceil(max_x) min_y = max(j - r, 0) min_y = math.floor(min_y) max_y = min(j + r, grid_y - 1) max_y = math.ceil(max_y) min_z = max(k - r, 0) min_z = math.floor(min_z) max_z = min(k + r, grid_z - 1) max_z = math.ceil(max_z) for m in range(min_x, max_x + 1): for n in range(min_y, max_y + 1): for l in range(min_z, max_z + 1): dis = np.sqrt(np.power((i - m), 2) + np.power((j - n), 2) + np.power((k - l), 2)) h = 0 if dis <= r: if occ_grid[i][j][k] == 2: h = 0.1 elif occ_grid[i][j][k] == 3: h = 10 elif occ_grid[i][j][k] == 4: h = 100 # print (dis, np.power(dis, 2),math.exp((-1/2)*np.power(dis, 2)),i,j,k,m,n,l) # print (pri_grid[m][n][l]) pri_grid[m][n][l] += h * math.exp((-1 / 2) * np.power(dis, 2)) # print(pri_grid[m][n][l]) sum_privacy = 0 for i in range(grid_x): for j in range(grid_y): for k in range(grid_z): sum_privacy += pri_grid[i][j][k] return pri_grid, sum_privacy def map_generate(grid_x, grid_y, grid_z, start, end, safety_threshold, privacy_threshold): map_volume = grid_x * grid_y * grid_z obstacle_num = map_volume * safety_threshold restricted_area_num = map_volume * privacy_threshold occ_grid = np.zeros((grid_x, grid_y, grid_z)) occ_grid[start.x][start.y][start.z] = 7 occ_grid[end.x][end.y][end.z] = 8 i = 0 # obstacle while i < obstacle_num: x = randint(0, grid_x - 1) y = randint(0, grid_y - 1) z = randint(0, grid_z - 1) if occ_grid[x][y][z] == 0: i = i+1 occ_grid[x][y][z] = 1 # private house i = 0 while i < restricted_area_num: x = randint(0, grid_x - 1) y = randint(0, grid_y - 1) z = randint(0, grid_z - 1) if occ_grid[x][y][z] == 0: i = i + 1 occ_grid[x][y][z] = randint(2, 4) return occ_grid, obstacle_num ''' def map_init(grid_x, grid_y, grid_z, thickness, obstacles, goals): occ_grid = np.zeros((grid_x, grid_y, grid_z)) objectives = [] # 产生多个立方柱 yoz平面 for i in range(obstacles): ry = randint(0, grid_y - thickness - 1) rz = randint(0, grid_z - thickness - 1) for j in range(grid_x - 1): for k in range(ry, ry + thickness): for l in range(rz, rz + thickness): occ_grid[j][k][l] = 1 # 产生多个立方柱 xoz平面 for i in range(obstacles): rx = randint(0, grid_y - thickness - 1) rz = randint(0, grid_z - thickness - 1) for j in range(grid_y - 1): for k in range(rx, rx + thickness): for l in range(rz, rz + thickness): occ_grid[k][j][l] = 1 # 产生多个立方柱 xoy平面 for i in range(obstacles): rx = randint(0, grid_x - thickness - 1) ry = randint(0, grid_y - thickness - 1) for j in range(grid_x - 1): for k in range(rx, rx + thickness): for l in range(ry, ry + thickness): occ_grid[k][l][j] = 1 while len(objectives) < goals: x = randint(0, grid_x - 1) y = randint(0, grid_y - 1) z = randint(0, grid_z - 1) if occ_grid[x][y][z] == 0: occ_grid[x][y][z] = 1 objectives.append(Point(x, y, z)) for i in range(goals): occ_grid[objectives[i].x][objectives[i].y][objectives[i].z] = 0 s_p = Point(randint(0, grid_x - 1), randint(0, grid_z - 1), randint(0, grid_z - 1)) while occ_grid[s_p.x][s_p.y][s_p.z] > 0: s_p = Point(randint(0, grid_x - 1), randint(0, grid_z - 1), randint(0, grid_z - 1)) return occ_grid, objectives, s_p '''
true
9a5536b40a44eab1dc0d48a4c10e08b61da1f1ad
Python
kevinrodbe/json2html-flask
/main.py
UTF-8
2,910
3.03125
3
[ "MIT" ]
permissive
''' JSON 2 HTML convertor ===================== (c) Varun Malhotra 2013 http://softvar.github.io Source Code: https://github.com/softvar/json2html-flask ------------ LICENSE: MIT -------- ''' # -*- coding: utf-8 -*- import ordereddict import HTMLParser from flask import json from flask import Flask from flask import request from flask import render_template app = Flask(__name__) a = '' @app.route('/') def my_form(): return render_template("my-form.html") @app.route('/about') def aboutMe(): return render_template("about.html") @app.route('/', methods=['POST']) def my_form_post(): ''' receive submitted data and process ''' text = request.form['text'] checkbox = request.form['users'] style="" if(checkbox=="1"): style="<table class=\"table table-condensed table-bordered table-hover\">" else: style="<table border=\"1\">" #json_input = json.dumps(text) try: ordered_json = json.loads(text, object_pairs_hook=ordereddict.OrderedDict) print ordered_json processed_text = htmlConvertor(ordered_json,style) html_parser = HTMLParser.HTMLParser() global a a = '' return render_template("my-form.html", processed_text=html_parser.unescape(processed_text),pro = text) except: return render_template("my-form.html",error="Error Parsing JSON ! Please check your JSON syntax",pro=text) def iterJson(ordered_json,style): global a a=a+ style for k,v in ordered_json.iteritems(): a=a+ '<tr>' a=a+ '<th>'+ str(k) +'</th>' if (v==None): v = unicode("") if(isinstance(v,list)): a=a+ '<td><ul>' for i in range(0,len(v)): if(isinstance(v[i],unicode)): a=a+ '<li>'+unicode(v[i])+'</li>' elif(isinstance(v[i],int) or isinstance(v,float)): a=a+ '<li>'+str(v[i])+'</li>' elif(isinstance(v[i],list)==False): iterJson(v[i],style) a=a+ '</ul></td>' a=a+ '</tr>' elif(isinstance(v,unicode)): a=a+ '<td>'+ unicode(v) +'</td>' a=a+ '</tr>' elif(isinstance(v,int) or isinstance(v,float)): a=a+ '<td>'+ str(v) +'</td>' a=a+ '</tr>' else: a=a+ '<td>' #a=a+ '<table border="1">' iterJson(v,style) a=a+ '</td></tr>' a=a+ '</table>' def htmlConvertor(ordered_json,style): ''' converts JSON Object into human readable HTML representation generating HTML table code with raw/bootstrap styling. ''' global a try: for k,v in ordered_json.iteritems(): pass iterJson(ordered_json,style) except: for i in range(0,len(ordered_json)): if(isinstance(ordered_json[i],unicode)): a=a+ '<li>'+unicode(ordered_json[i])+'</li>' elif(isinstance(ordered_json[i],int) or isinstance(ordered_json[i],float)): a=a+ '<li>'+str(ordered_json[i])+'</li>' elif(isinstance(ordered_json[i],list)==False): htmlConvertor(ordered_json[i],style) return a if __name__ == '__main__': app.run(debug = True)
true
56bf28b4a65708eb6c71625c35ffb83ab7fb596a
Python
srushti-coding-projects/CS-562-NLP
/part3.py
UTF-8
3,075
3.375
3
[]
no_license
''' Counting and Comparing ''' from nltk.corpus import stopwords from collections import Counter from nltk.collocations import BigramCollocationFinder import matplotlib.pyplot as plt import string word_output = open('word_tokenize.txt', 'r') words = word_output.read() word_list = words.split() # Print uniques types list_of_tokens = list(Counter(word_list).values()) print("Answer 1 : All unique unigram tokens",len(list_of_tokens)) # Print number of unique tokens print("Answer 2 : All unigram tokens",len(word_list)) # Plot rank frequency x = [i for i in range(1, len(list_of_tokens) + 1)] y = list(reversed(sorted(list_of_tokens))) plt.xscale('log') plt.yscale('log') plt.title('Zipf Law - Rank Frequency Plot') plt.xlabel('Frequency') plt.ylabel('Rank') plt.plot(x, y, color='red') plt.show() # Print most common 20 words print("Answer 3 : Twenty Most common words") for key,item in Counter(word_list).most_common(20): print(key) # Remove punctuation frm stopwords stop_words = ' '.join(stopwords.words('english')) punct_set = set(string.punctuation) sent = "" # Remove stop words from words list for sw in stop_words: if sw not in punct_set: sent = sent + sw sent = sent.upper().split() filtered_sentence = [] for word in word_list: if not word in sent: filtered_sentence.append(word) print("Number of tokens before removing stopwords", len(word_list)) print("Answer 4 : Removing stopwords",len(filtered_sentence)) print("Answer 5 : Twenty Most common words after stopwords") for key,item in Counter(filtered_sentence).most_common(20): print(key) #calculate bigram frequency count finder = BigramCollocationFinder.from_words(word_list) # calculate unigram probabilies unigram_prob = {} unigram_freq = dict(Counter(word_list).items()) for u_k, u_v in Counter(word_list).items(): unigram_prob[u_k] = u_v/len(word_list) # calculate bigram probabilities bigram_prob = {} finder = BigramCollocationFinder.from_words(word_list) bigram_freq = dict(finder.ngram_fd.items()) for b_k, b_v in finder.ngram_fd.items(): bigram_prob[b_k] = b_v/unigram_prob[b_k[0]] # calculate pmi values pmi_values = {} for b_k, b_v in finder.ngram_fd.items(): pmi_values[b_k] = b_v/(unigram_prob[b_k[0]] * unigram_prob[b_k[1]]) # Computer bigram probabilities and pmi values after threshold bigram_threshold = {} for thr_k , thr_v in finder.ngram_fd.items(): if int(thr_v) > 100: bigram_threshold[thr_k] = bigram_prob[thr_k] pmi_threshold = {} for p_k, p_v in bigram_threshold.items(): pmi_threshold[p_k] = p_v/(unigram_prob[p_k[0]] * unigram_prob[p_k[1]]) # Display first 10 outputs: PMI Values, Frequency Count of bigram, Frequency Count of unigram counter = 0 threshold_data = [(key, pmi_threshold[key]) for key in sorted(pmi_threshold, key=pmi_threshold.get, reverse=True)] for key,value in threshold_data: counter = counter + 1 if counter == 11: break print(key, "=", value, "\t\t", key, '=', bigram_freq[key], '\t', key[0], '=', unigram_freq[key[0]], " ", key[1], "=", unigram_freq[key[1]])
true
9a1f4fd44352cdfbda27f80d376db96665d67d8a
Python
saswatpp/cupy
/cupyx/scipy/special/_statistics.py
UTF-8
2,086
3.078125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
from cupy import _core logit_definition = """ template <typename T> static __device__ T logit(T x) { x /= 1 - x; return log(x); } """ logit = _core.create_ufunc( 'cupy_logit', ('e->f', 'f->f', 'd->d'), 'out0 = logit(in0)', preamble=logit_definition, doc='''Logit function. Args: x (cupy.ndarray): input data Returns: cupy.ndarray: values of logit(x) .. seealso:: :data:`scipy.special.logit` ''') expit_definition = """ template <typename T> static __device__ T expit(T x) { return 1 / (1 + exp(-x)); } """ expit = _core.create_ufunc( 'cupy_expit', ('e->f', 'f->f', 'd->d'), 'out0 = expit(in0)', preamble=expit_definition, doc='''Logistic sigmoid function (expit). Args: x (cupy.ndarray): input data (must be real) Returns: cupy.ndarray: values of expit(x) .. seealso:: :data:`scipy.special.expit` .. note:: expit is the inverse of logit. ''') # log_expit implemented based on log1p as in SciPy's scipy/special/_logit.h log_expit_definition = """ template <typename T> static __device__ T log_expit(T x) { if (x < 0.0) { return x - log1p(exp(x)); } else { return -log1p(exp(-x)); } } """ log_expit = _core.create_ufunc( 'cupy_log_expit', ('e->f', 'f->f', 'd->d'), 'out0 = log_expit(in0)', preamble=log_expit_definition, doc='''Logarithm of the logistic sigmoid function. Args: x (cupy.ndarray): input data (must be real) Returns: cupy.ndarray: values of log(expit(x)) .. seealso:: :data:`scipy.special.log_expit` .. note:: The function is mathematically equivalent to ``log(expit(x))``, but is formulated to avoid loss of precision for inputs with large (positive or negative) magnitude. ''') ndtr = _core.create_ufunc( 'cupyx_scipy_special_ndtr', ('f->f', 'd->d'), 'out0 = normcdf(in0)', doc='''Cumulative distribution function of normal distribution. .. seealso:: :meth:`scipy.special.ndtr` ''')
true
4eb41e0e12b51847ee1a7df4de518dd3a1dc3dc8
Python
Ji-sunny/farmAiPython
/module/box.py
UTF-8
1,010
2.8125
3
[]
no_license
import pandas as pd import datetime def box(data, table_name): def AddDays(sourceDate, count): targetDate = sourceDate + datetime.timedelta(days = count) return targetDate def GetWeekLastDate(sourceDate): temporaryDate = datetime.datetime(sourceDate.year, sourceDate.month, sourceDate.day) weekDayCount = temporaryDate.weekday() targetDate = AddDays(sourceDate, -weekDayCount + 6); return targetDate data['dt'] = data['dt'].map(lambda x : x.split(' ')[0]) data['dt'] = pd.to_datetime(data['dt']) data['dt'] = data['dt'].map(lambda x : GetWeekLastDate(x)) data['box_num'] = data['files_name'].map(lambda x : x.split('_')[1]) data.drop({'s_n','idx','type'}, axis=1, inplace=True) #원핫, 센서가 bed인지 farmbot인지 data['bed'] = data['box_num'].map(lambda x : 0 if int(x) > 6 else 1) data['farmbot'] = data['box_num'].map(lambda x : 1 if int(x) > 6 else 0) data.fillna(0, inplace=True) return data
true
bbb6ba38e7884bd66d4e32d35fa23928f4b05947
Python
sosuke-k/naruhodo
/naruhodo/utils/misc.py
UTF-8
6,278
3
3
[ "MIT" ]
permissive
""" Module for miscellaneous utility functions. """ import re import json from math import sqrt import numpy as np import networkx as nx from nxpd import draw from naruhodo.utils.dicts import NodeType2StyleDict, NodeType2ColorDict, NodeType2FontColorDict, EdgeType2StyleDict, EdgeType2ColorDict _re_sent = re.compile(r'([^ !?。]*[!?。])') """ Precompiled regular expression for separating sentences. """ _re1 = re.compile(r'\(.*?\)') _re2 = re.compile(r'\[.*?\]') _re3 = re.compile(r'\(.*?\)') _re4 = re.compile(r'\<.*?\>') """ Precompiled regular expressions for getting rid of parenthesis. """ def preprocessText(text): """Get rid of weird parts from the text that interferes analysis.""" text = text.replace("\n", "").replace("|", "、").replace(" ", "").strip() text = _re1.sub("", text) text = _re2.sub("", text) text = _re3.sub("", text) text = _re4.sub("", text) return text def parseToSents(context): """Parse given context into list of individual sentences.""" return [sent.strip().replace('*', "-") for sent in _re_sent.split(context) if sent.strip() != ""] def exportToJsonObj(G): """Export given networkx graph to JSON object(dict object in python).""" return nx.node_link_data(G) def exportToJsonFile(G, filename): """Export given networkx graph to JSON file.""" with open(filename, 'w') as outfile: json.dump(exportToJsonObj(G), outfile) def getNodeProperties(info, depth=False): """Convert node properties for node drawing using nxpd.""" ret = dict() ret['shape'] = NodeType2StyleDict[info['type']] ret['fillcolor'] = NodeType2ColorDict[info['type']] ret['fontcolor'] = NodeType2FontColorDict[info['type']] ret['label'] = info['label'] ret['style'] = 'filled' ret['fixedsize'] = True ret['fontsize'] = (5.0 + 20.0 / len(info['label'])) * info['count'] ret['width'] = info['count']*0.75 ret['count'] = info['count'] if depth: d = np.average(info['depth']) # Average depth of the node d = min(d, 5.) # Normalize d to a range of [0, 6] cs = [255, 80, 0] # Base reference color at start ct = [255, 255, 255] # Base reference color at end cn = [0, 0, 0] # Average depth scaled node color for i in range(3): cn[i] = cs[i] + int((ct[i] - cs[i]) / 5. * d) ret['fillcolor'] = rgb2Hex(cn) ret['fontcolor'] = '#000000' return ret def getEdgeProperties(info): """Convert edge properties for node drawing using nxpd.""" ret = dict() ret['label'] = info['label'] ret['penwidth'] = info['weight'] * 2.0 ret['weight'] = info['weight'] ret['style'] = EdgeType2StyleDict[info['type']] ret['color'] = EdgeType2ColorDict[info['type']] return ret def inclusive(A, B): """Find if one of string A and B includes the other.""" if len(A) > len(B): if A.find(B) != -1: ret = 1 else: ret = 0 elif len(A) < len(B): if B.find(A) != -1: ret = -1 else: ret = 0 else: ret = 0 return ret def cosSimilarity(A, B): """Compute the cosine similarity between vectors A and B.""" return np.dot(A, B) / sqrt(np.dot(A, A) * np.dot(B, B)) def harmonicSim(AG, B): """Return the harmonic distance between a group of vectors AG and vector B.""" size = len(AG) ret = 0. for i in range(size): ret += 1. / cosSimilarity(AG[i], B) return float(size) / ret def decorate(G, depth, rankdir): """Generate temporal graph with drawing properties added for nxpd.""" ret = nx.DiGraph() ret.graph['rankdir'] = rankdir for key, val in G.nodes.items(): ret.add_node(key, **getNodeProperties(val, depth)) for key, val in G.edges.items(): ret.add_edge(*key, **getEdgeProperties(val)) return ret def show(G, depth=False, rankdir='TB'): """Decorate and draw given graph using nxpd in notebook.""" return draw(decorate(G, depth, rankdir), show='ipynb') def plotToFile(G, filename, depth=False, rankdir='TB'): """Output given graph to a png file using nxpd.""" return draw(decorate(G, depth, rankdir), filename=filename, show=False) def _mergeGraph(A, B): """Return the merged graph of A and B.""" for key, val in B.nodes.items(): if A.has_node(key): A.nodes[key]['count'] += val['count'] for i in range(len(val['pos'])): if val['pos'][i] not in A.nodes[key]['pos']: A.nodes[key]['pos'].append(val['pos'][i]) A.nodes[key]['lpos'].append(val['lpos'][i]) A.nodes[key]['func'].append(val['func'][i]) A.nodes[key]['surface'].append(val['surface'][i]) A.nodes[key]['yomi'].append(val['yomi'][i]) if 'depth' in A.nodes[key]: A.nodes[key]['depth'].append(val['depth'][i]) else: A.add_node(key, **val) for key, val in B.edges.items(): if A.has_edge(*key): A.edges[key[0], key[1]]['weight'] += val['weight'] else: A.add_edge(*key, **val) return A def _mergeEntityList(A, B): """Return merged entityList os A and B.""" for i in range(len(B)): for key, val in B[i].items(): if key in A[i]: for item in val: A[i][key].append(item) else: A[i][key] = val return A def _mergeProList(A, B): """Return merged proList os A and B.""" for item in B: A.append(item) return A def _mergeAll(A, B): """Return merged result of graph, entity list and pronoun list.""" A[0] = _mergeGraph(A[0], B[0]) A[1] = _mergeEntityList(A[1], B[1]) A[2] = _mergeProList(A[2], B[2]) return A def hex2Rgb(c): """ Convert hex color in #XXXXXX format to RGB list. """ return [int(c.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)] def rgb2Hex(c): """ Convert color in RGB format to hex format. """ return "#{0:02x}{1:02x}{2:02x}".format(clamp(c[0]), clamp(c[1]), clamp(c[2])) def clamp(x): """ Clamp x to 0 <= x <= 255. """ return max(0, min(x, 255))
true
579554c31ef4059285fdfa445c3d996c0e8bdc7d
Python
Rk85/Stock-Watcher
/models/quote_history.py
UTF-8
871
2.640625
3
[]
no_license
from db_base import Base, engine from sqlalchemy import Column, Integer, String, DATETIME, Boolean, DATE from sqlalchemy.sql.expression import and_, func class TradeHistory(Base): """Contains history of the trades for each symbols """ __tablename__ = 'TradeHistory' __table_args__ = {'useexisting' : True} id = Column("Id", Integer, primary_key=True) symbol = Column("Symbol", String(100), nullable=False) date = Column("Date", DATE, nullable=False) open_val = Column("Open Price", Integer, nullable=False) high_val = Column("High Price", Integer, nullable=True) low_val = Column("Low Price", Integer, nullable=True) close_val = Column("Close Price", Integer, nullable=True) volume = Column("Volume", Integer, nullable=True) adj_close = Column("Adj Close", Integer, nullable=True) Base.metadata.create_all(engine)
true
db713cc2eb7c02a7b10d5129ac7083cd846d5f97
Python
ZnGaP/python_learning
/module.py
UTF-8
340
2.65625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'a test mo' __author__ = 'linjx' import sys def test(): args = sys.argv if len(args) == 1: print('hello world!') elif len(args) == 2: print('hello, %s' % args) else: print('Too much argument!') if __name__ == "__main__": test()
true
275dcf7021081b228b8e57006804cd8f067b4e0c
Python
computingForSocialScience/cfss-homework-DanyaLagos
/Assignment5/csvUtils.py
UTF-8
1,732
3.421875
3
[]
no_license
from io import open import csv def writeArtistsTable(artist_info_list): """Given a list of dictionries, each as returned from fetchArtistInfo(), write a csv file 'artists.csv'. The csv file should have a header line that looks like this: ARTIST_ID,ARTIST_NAME,ARTIST_FOLLOWERS,ARTIST_POPULARITY """ f = open('artists.csv', 'w', encoding='utf-8') try: f.write(u'ARTIST_ID,ARTIST_NAME,ARTIST_FOLLOWERS,ARTIST_POPULARITY\n') for artist_info in artist_info_list: artist_id = artist_info['id'] artist_name = artist_info['name'] artist_followers = artist_info['followers'] artist_popularity = artist_info['popularity'] f.write(u'%s,"%s",%d,%d\n' % (artist_id, artist_name, artist_followers, artist_popularity)) finally: f.close() def writeAlbumsTable(album_info_list): """ Given list of dictionaries, each as returned from the function fetchAlbumInfo(), write a csv file 'albums.csv'. The csv file should have a header line that looks like this: ARTIST_ID,ALBUM_ID,ALBUM_NAME,ALBUM_YEAR,ALBUM_POPULARITY """ f = open('albums.csv', 'w', encoding='utf-8') try: f.write(u'ARTIST_ID, ALBUM_ID,ALBUM_NAME,ALBUM_YEAR,ALBUM_POPULARITY\n') for album_info in album_info_list: album_artist_id = album_info['artist_id'] album_id = album_info['album_id'] album_name = album_info['name'] album_year = album_info['year'] album_popularity = album_info['popularity'] f.write(u'%s,%s,"%s",%s,%s\n' % (album_artist_id, album_id, album_name, album_year, album_popularity)) finally: f.close()
true
f316df1f0c671f0a00fd1f971ee37fd50b3a1af5
Python
FMsunyh/RetinaNet
/core/backend/tensorflow_backend.py
UTF-8
9,799
2.625
3
[ "Apache-2.0" ]
permissive
import tensorflow import keras import core.backend def scatter_nd(*args, **kwargs): return tensorflow.scatter_nd(*args, **kwargs) def matmul(*args, **kwargs): return tensorflow.matmul(*args, **kwargs) def range(*args, **kwargs): return tensorflow.range(*args, **kwargs) def gather_nd(params, indices): return tensorflow.gather_nd(params, indices) def meshgrid(*args, **kwargs): return tensorflow.meshgrid(*args, **kwargs) def where(condition, x=None, y=None): return tensorflow.where(condition, x, y) def shuffle(x): """ Modify a sequence by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. """ return tensorflow.random_shuffle(x) def meshgrid(*args, **kwargs): return tensorflow.meshgrid(*args, **kwargs) def where(condition, x=None, y=None): return tensorflow.where(condition, x, y) def bbox_transform(ex_rois, gt_rois): """Compute bounding-box regression targets for an image.""" ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0 ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0 ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0 gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0 gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights targets_dw = keras.backend.log(gt_widths / ex_widths) targets_dh = keras.backend.log(gt_heights / ex_heights) targets = keras.backend.stack((targets_dx, targets_dy, targets_dw, targets_dh)) targets = keras.backend.transpose(targets) return keras.backend.cast(targets, 'float32') def overlapping(anchors, gt_boxes): """ overlaps between the anchors and the gt boxes :param anchors: Generated anchors :param gt_boxes: Ground truth bounding boxes :return: """ assert keras.backend.ndim(anchors) == 2 assert keras.backend.ndim(gt_boxes) == 2 reference = core.backend.overlap(anchors, gt_boxes) gt_argmax_overlaps_inds = keras.backend.argmax(reference, axis=0) argmax_overlaps_inds = keras.backend.argmax(reference, axis=1) indices = keras.backend.stack([ tensorflow.range(keras.backend.shape(anchors)[0]), keras.backend.cast(argmax_overlaps_inds, "int32") ], axis=0) indices = keras.backend.transpose(indices) max_overlaps = tensorflow.gather_nd(reference, indices) return argmax_overlaps_inds, max_overlaps, gt_argmax_overlaps_inds # def label(y_true, y_pred, inds_inside, RPN_NEGATIVE_OVERLAP=0.3, RPN_POSITIVE_OVERLAP=0.7, clobber_positives=False): # """ # Create bbox labels. # label: 1 is positive, 0 is negative, -1 is do not care # # :param inds_inside: indices of anchors inside image # :param y_pred: anchors # :param y_true: ground truth objects # # :return: indices of gt boxes with the greatest overlap, balanced labels # """ # ones = keras.backend.ones_like(inds_inside, dtype=keras.backend.floatx()) # labels = ones * -1 # zeros = keras.backend.zeros_like(inds_inside, dtype=keras.backend.floatx()) # # argmax_overlaps_inds, max_overlaps, gt_argmax_overlaps_inds = overlapping( # y_pred, y_true, inds_inside) # # # assign bg labels first so that positive labels can clobber them # if not clobber_positives: # labels = core.backend.where( # keras.backend.less(max_overlaps, RPN_NEGATIVE_OVERLAP), # zeros, # labels # ) # # # fg label: for each gt, anchor with highest overlap # indices = keras.backend.expand_dims(gt_argmax_overlaps_inds, axis=1) # # updates = keras.backend.ones_like(gt_argmax_overlaps_inds, dtype=keras.backend.floatx()) # # # TODO: generalize unique beyond 1D # unique_indices, unique_indices_indices = tensorflow.unique( # keras.backend.reshape(indices, (-1,)), out_idx='int32') # unique_updates = keras.backend.gather(updates, unique_indices) # inverse_labels = keras.backend.gather(-1 * labels, unique_indices) # unique_indices = keras.backend.expand_dims(unique_indices, 1) # labels = core.backend.scatter_add_tensor(labels, unique_indices, inverse_labels + unique_updates) # # # fg label: above threshold IOU # labels = core.backend.where( # keras.backend.greater_equal(max_overlaps, RPN_POSITIVE_OVERLAP), # ones, # labels # ) # # if clobber_positives: # # assign bg labels last so that negative labels can clobber positives # labels = core.backend.where( # keras.backend.less(max_overlaps, RPN_NEGATIVE_OVERLAP), # zeros, # labels # ) # # return argmax_overlaps_inds, balance(labels) # # def balance(labels): # """ # balance labels by setting some to -1 # :param labels: array of labels (1 is positive, 0 is negative, -1 is dont care) # :return: array of labels # """ # # # subsample positive labels if we have too many # labels = subsample_positive_labels(labels) # # # subsample negative labels if we have too many # labels = subsample_negative_labels(labels) # # return labels # # # def subsample_positive_labels(labels): # """ # subsample positive labels if we have too many # :param labels: array of labels (1 is positive, 0 is negative, -1 is dont care) # # :return: # """ # # num_fg = int(RPN_FG_FRACTION * RPN_BATCHSIZE) # # fg_inds = core.backend.where(keras.backend.equal(labels, 1)) # num_fg_inds = keras.backend.shape(fg_inds)[0] # # size = num_fg_inds - num_fg # # def more_positive(): # # TODO: try to replace tensorflow # indices = tensorflow.random_shuffle( # keras.backend.reshape(fg_inds, (-1,)))[:size] # # updates = tensorflow.ones((size,)) * -1 # # inverse_labels = keras.backend.gather(labels, indices) * -1 # # indices = keras.backend.reshape(indices, (-1, 1)) # # return scatter_add_tensor(labels, indices, inverse_labels + updates) # # def less_positive(): # return labels # # predicate = keras.backend.less_equal(size, 0) # # return tensorflow.cond(predicate, lambda: less_positive(), lambda: more_positive()) # # # def subsample_negative_labels(labels): # """ # subsample negative labels if we have too many # :param labels: array of labels (1 is positive, 0 is negative, -1 is dont care) # # :return: # """ # num_bg = RPN_BATCHSIZE - keras.backend.shape(core.backend.where(keras.backend.equal(labels, 1)))[0] # bg_inds = core.backend.where(keras.backend.equal(labels, 0)) # num_bg_inds = keras.backend.shape(bg_inds)[0] # # size = num_bg_inds - num_bg # # def more_negative(): # indices = core.backend.shuffle(keras.backend.reshape(bg_inds, (-1,)))[:size] # # updates = tensorflow.ones((size,)) * -1 # # inverse_labels = keras.backend.gather(labels, indices) * -1 # # indices = keras.backend.reshape(indices, (-1, 1)) # # return scatter_add_tensor(labels, indices, inverse_labels + updates) # # def less_negative(): # return labels # # predicate = keras.backend.less_equal(size, 0) # # return tensorflow.cond(predicate, lambda: less_negative(), lambda: more_negative()) # # def scatter_add_tensor(ref, indices, updates, name=None): # """ # Adds sparse updates to a variable reference. # # This operation outputs ref after the update is done. This makes it easier to chain operations that need to use the # reset value. # # Duplicate indices: if multiple indices reference the same location, their contributions add. # # Requires updates.shape = indices.shape + ref.shape[1:]. # :param ref: A Tensor. Must be one of the following types: float32, float64, int64, int32, uint8, uint16, # int16, int8, complex64, complex128, qint8, quint8, qint32, half. # :param indices: A Tensor. Must be one of the following types: int32, int64. A tensor of indices into the first # dimension of ref. # :param updates: A Tensor. Must have the same dtype as ref. A tensor of updated values to add to ref # :param name: A name for the operation (optional). # :return: Same as ref. Returned as a convenience for operations that want to use the updated values after the update # is done. # """ # with tensorflow.name_scope(name, 'scatter_add_tensor', # [ref, indices, updates]) as scope: # ref = tensorflow.convert_to_tensor(ref, name='ref') # # indices = tensorflow.convert_to_tensor(indices, name='indices') # # updates = tensorflow.convert_to_tensor(updates, name='updates') # # ref_shape = tensorflow.shape(ref, out_type=indices.dtype, name='ref_shape') # # scattered_updates = tensorflow.scatter_nd(indices, updates, ref_shape, name='scattered_updates') # # with tensorflow.control_dependencies([tensorflow.assert_equal( # ref_shape, # tensorflow.shape(scattered_updates, out_type=indices.dtype))]): # output = tensorflow.add(ref, scattered_updates, name=scope) # # return output # # def unmap(data, count, inds_inside, fill=0): # """ Unmap a subset of item (data) back to the original set of items (of # size count) """ # # if keras.backend.ndim(data) == 1: # ret = keras.backend.ones((count,), dtype=keras.backend.floatx()) * fill # inds_nd = keras.backend.expand_dims(inds_inside) # else: # ret = keras.backend.ones((count,) + keras.backend.int_shape(data)[1:], # dtype=keras.backend.floatx()) * fill # data = keras.backend.transpose(data) # data = keras.backend.reshape(data, (-1,)) # # inds_ii = keras.backend.tile(inds_inside, [4]) # inds_ii = keras.backend.expand_dims(inds_ii) # ones = keras.backend.expand_dims(keras.backend.ones_like(inds_inside), # 1) # inds_coords = keras.backend.concatenate( # [ones * 0, ones, ones * 2, ones * 3], 0) # inds_nd = keras.backend.concatenate([inds_ii, inds_coords], 1) # inverse_ret = tensorflow.squeeze(tensorflow.gather_nd(-1 * ret, inds_nd)) # ret = core.backend.scatter_add_tensor(ret, inds_nd, inverse_ret + data) # return ret
true
f328ec242745a0d619e549c4c82fd1df7a7df577
Python
kevinch2008/SublimePlayer
/SublimePlayer.py
UTF-8
2,243
2.671875
3
[]
no_license
# -*- coding: utf-8 -*- import sublime, sublime_plugin import subprocess import threading class RunAsync(threading.Thread): def __init__(self, cb): self.cb = cb threading.Thread.__init__(self) def run(self): self.cb() def run_async(cb): res = RunAsync(cb) res.start() return res class Player(): url = None popen = None _enabled = False last_view = None def __init__(self, url=None): self.url = url def _play(self): self.popen = subprocess.Popen(["ffplay", "-nodisp", "-autoexit", self.url], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) out, err = self.popen.communicate() def play(self): if self.url is None: return self._enabled = True self.load_to_view(sublime.active_window().active_view()) run_async(self._play) def stop(self): if self._enabled: self._enabled = False self.unload_view() self.popen.kill() self.popen = None def set_url(self, url): was_enabled = self._enabled self.stop() self.url = url if was_enabled: self.play() def enabled(self): return self._enabled def unload_view(self): if self.last_view is not None: self.last_view.erase_status("SublimePlayer") self.last_view = None def load_to_view(self, view): self.unload_view() if not self._enabled: return view.set_status("SublimePlayer", "Playing: %s" % (self.url)) self.last_view = view player = Player() class SublimePlayerPlay(sublime_plugin.ApplicationCommand): def run(self): player.play() def is_enabled(self): return not player.enabled() class SublimePlayerStop(sublime_plugin.ApplicationCommand): def run(self): player.stop() def is_enabled(self): return player.enabled() class SublimePlayerSetUrl(sublime_plugin.WindowCommand): def run(self): self.window.show_input_panel("Select file:", "", self.set_url, None, None) def set_url(self, url): player.set_url(url) def plugin_unloaded(): player.stop()
true
5e3d0f9bbac9becd02f61d5c0d3a55dd1c0d56c0
Python
patjenk/dummydb
/dummydb/ddb.py
UTF-8
2,851
3.3125
3
[]
no_license
from .serializer import dumps, loads class DummyDBException(Exception): pass class DummyDB(): data = None def __init__(self, filename=None): if filename is not None: self.data = self.load_from_disk(filename) else: self.data = {} def load_from_disk(self, filename): filehandle = open(filename, "r") self.load_from_filehandle(filehandle) filehandle.close() def load_from_filehandle(self, filehandle): filehandle.seek(0) self.data = loads(filehandle.read()) def write_to_disk(self, filename): filehandle = open(filename, "w") self.write_to_filehandle(filehandle) filehandle.close() def write_to_filehandle(self, filehandle): filehandle.write(dumps(self.data)) def create_table(self, table_name, columns): """ Create an empty table. """ if table_name in self.data: raise DummyDBException("Table named '{}' already exists.".format(table_name)) self.data[table_name] = { 'definitions': columns, 'data': [], } def insert(self, table_name, **kwargs): """ Add data to a table. """ if table_name not in self.data: raise DummyDBException("Table '{}' does not exist.".format(table_name)) for key, val in self.data[table_name]['definitions'].items(): if key not in kwargs: raise DummyDBException("Cannot insert into table '{}' without column {}.".format(table_name), key) if not isinstance(kwargs[key], val): raise DummyDBException("Table '{}' column {} requires type {}, not type {}.".format(table_name), key, val, type(kwargs[key])) self.data[table_name]['data'].append(kwargs) def select(self, table_name, **kwargs): """ Get data from a table. Returns a list of dicts. """ if table_name not in self.data: raise DummyDBException("Table '{}' does not exist.".format(table_name)) for key, val in kwargs.items(): if key not in self.data[table_name]['definitions']: raise DummyDBException("Table '{}' does not have a column '{}'.".format(table_name, key)) if not isinstance(val, self.data[table_name]['definitions'][key]): raise DummyDBException("Table '{}' column is type {}, not type {}".format(table_name, self.data[table_name]['definitions'][key], type(val))) result = [] for row in self.data[table_name]['data']: all_match = True for key, val in kwargs.items(): if row[key] != val: all_match = False break if all_match: result.append(row) return result
true
1f3f25de7b5eabab93339da5000a001ecf59ea87
Python
scholer/rsenv
/rsenv/rsfavmodules.py
UTF-8
3,848
2.53125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2011 Rasmus Scholer Sorensen, rasmusscholer@gmail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Created on Mon Apr 4 12:00:06 2011 @author: scholer Imports my favorite modules that makes it possible for me to work efficiently with a python command prompt. It should never be loaded automatically, as loading takes quite some time. Load this module with: from rsfavmods import * Alternatively, just use this file as reference when you cannot remember what a particular module is named. """ """ --------------------------------- --- Modules from standard library --- ------------------------------------- """ # http://docs.python.org/2/library/ import os # Has os.path, os.getcwd(), etc. import sys # has sys.argv, etc. import math # has math.pi and other mathematical constants and functions. import re # Regular expressions import itertools # Fast iteration routines. import string # String functions import datetime # datatime functions import random # Making random numbers, etc. import glob # glob.glob(path_pattern) returns list of files matching a certain glob pattern. import pickle # For persisting of objects and other python data import json # Persisting data in javascript object notation format # yaml # Persisting in Yet Anoter Markup Language. Is imported via try-except statement. #import psycopg2# Connection to postgresql database. Is imported via try-except statement. # numpy # Imported via try-except statement # scipy # Imported via try-except statement # import email # For sending emails via python. See also smtplib, poplib and imaplib # import xmlrpclib # Remote procedure call library # import curses # Primitive command-line semi-GUI. # import tkinter # Python interface to Tcl/tk primitive GUI (http://docs.python.org/2/library/tk.html) # # used for e.g. the IDLE python code editor. # For other GUIs, see http://docs.python.org/2/library/othergui.html # -------------------------------------------- # --- Modules outside the standard library --- # -------------------------------------------- ## Clipboard in GTK: try: import pygtk pygtk.require('2.0') import gtk # gtk provides clipboard access: # clipboard = gtk.clipboard_get() # text = clipboard.wait_for_text() except ImportError: # Will happen on Windows/Mac: pygtk = None gtk = None try: import yaml except ImportError: print("YAML module not available.") yaml = None # Postgres SQL driver: try: import psycopg2 except ImportError: print("psycopg2 module not available") psycopg2 = None # Scientific modules: try: import numpy try: import scipy except ImportError: print("scipy module not available.") except ImportError: print("numpy module not available.") print(" - this also means no biopython, scipy, etc.") numpy = None scipy = None # Biopython, for DNA/Protein stuff: try: import Bio import Bio as biopython # http://biopython.org/DIST/docs/tutorial/Tutorial.html except ImportError: print("biopython ('Bio') module not available.") Bio = None biopython = None
true
a64528a25d320523afa6fd6edf0b0a80d21e6c55
Python
kapnan/AdventOfCode
/AoC_2019/Final_Completed/Day_5.py
UTF-8
4,519
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Jun 1 11:15:50 2020 @author: kriti """ #import math import numpy as np import os import sys import time if __name__ = '__main__': print('Hello, I am Day_5 :)') def Day_5(): t = time.time() os.chdir("C:/Users/kriti/Documents/Learning Python/AdventOfCode/2019") with open("Data/Intcode_Day5.txt",'r') as f: ints = np.genfromtxt(f,dtype=int, delimiter=',') #or ints = list(map(int,f)). This assigns the list to variable ints #CP = ints.copy() ##nouns = range(0,99) ##verbs = range(0,99) #ints = CP.copy() #print(ints) #copy = [] #initialises a checker to check when no more changes are occuring i = 0 #Initialise the indexing for stepping through ints i_3 = i+3 while (i_3 < len(ints)and (i+1) < len(ints)): # ============================================================================= # if int(i)/(10**4) > 1 : # i3 = i+3 # elif int(i)/(10**3): # # # elif int(i)/10 < 1: # i1 = int(ints[i+1]) #resets i values for new loop of value for i. This process reads the values in the 4 block chain and assigns them (the locations) to variables # i2 = int(ints[i+2]) # i3 = int(ints[i+3]) # ============================================================================= opcode = str(ints[i]) i1 = int(ints[i+1]) #resets i values for new loop of value for i. This process reads the values in the 4 block chain and assigns them (the locations) to variables i2 = int(ints[i+2]) i3 = int(ints[i+3]) # print('o') try: opcode_num = opcode[-1] if opcode_num =='9': opcode_num ='99' if opcode[-3] == '1': i1 = i+1 # elif opcode[-3] == '0': # i1 = int(ints[i+1]) if opcode[-4] == '1': i2 = i+2 # elif opcode[-4] == '0': # i2 = int(ints[i+2]) if opcode[-5] == '1': i3 = i+3 # elif opcode[-5] =='0': # i3 = int(ints[i+3]) # print('x') except IndexError: #print('x') pass # print('opcode num is', opcode_num) #opcode = str(ints[i]) # if (len(opcode) == 1 ): # opcode_num = int(opcode[-1]) # else: # opcode_num = int(opcode[-2]+opcode[-1]) #Needed as 99 is a possibility for the opcode # print(opcode_num) if opcode_num == '1': ints[i3]= ints[i1] + ints[i2] i+= 4 elif opcode_num == '2': ints[i3] = ints[i1]*ints[i2] i+=4 elif opcode_num == '3': #added for Day_5 ints[i1] = int(input('value:')) #ints[i1] = 3 i+=2 elif opcode_num == '4': #Added for Day_5 i+=2 print('Opcode 4 value is: ', ints[i1]) print((time.time()-t)*1000, 'ms to complete') sys.exit('Done') elif opcode_num == '5': if (ints[i1] != 0): i = ints[i2] else: i+=3 elif opcode_num == '6': if ints[i1] == 0: i = ints[i2] else: i+=3 elif opcode_num == '7': if ints[i1] < ints[i2]: ints[i3] = 1 else: ints[i3] = 0 i+=4 elif opcode_num =='8': if ints[i1] == ints[i2]: ints[i3] = 1 else: ints[i3] = 0 i+=4 #elif ints[i] == 99: #sys.exit(opcode_num == '99') #print('is this it?') #print(ints) if opcode_num == '99': print('HALTED') print(time.time()-t) sys.exit() # ============================================================================= # if ints[0] == 19690720: # print("noun =", n, ", verb =", v) # #print(ints) # sys.exit('reached 19690720') # ============================================================================= #i += 4 #i_3 = i+3
true
ab2c2ec41b358e6b5e1938ba72a6880a21071ef7
Python
ropert911/study01_python
/pythoTest/function/namedtuple.py
UTF-8
348
2.8125
3
[]
no_license
from collections import namedtuple user1 = {'userId': 1, 'topAreaList': [12, 13, 14]} user2 = {'userId': 2, 'topAreaList': [22, 23, 24]}; user_list = [user1, user2]; UserWithArea = namedtuple('UserWithArea', ('id', 'top_areas')) user_list = [UserWithArea(user['userId'], [_ for _ in user['topAreaList']]) for user in user_list] print(user_list)
true
7a168605be529e6872f4eef2f2073d0ee6ddf2e3
Python
czs108/LeetCode-Solutions
/Medium/256. Paint House/solution (1).py
UTF-8
1,113
3.40625
3
[ "MIT" ]
permissive
# 256. Paint House # Runtime: 68 ms, faster than 42.13% of Python3 online submissions for Paint House. # Memory Usage: 14.9 MB, less than 7.26% of Python3 online submissions for Paint House. class Solution: # Recursive Tree def minCost(self, costs: list[list[int]]) -> int: Red, Green, Blue = 0, 1, 2 memo = {} def paint_cost(n: int, color: int) -> int: if (n, color) in memo: return memo[(n, color)] total_cost = costs[n][color] if n == len(costs) - 1: pass elif color == Red: total_cost += min(paint_cost(n + 1, Green), paint_cost(n + 1, Blue)) elif color == Green: total_cost += min(paint_cost(n + 1, Red), paint_cost(n + 1, Blue)) else: total_cost += min(paint_cost(n + 1, Red), paint_cost(n + 1, Green)) memo[(n, color)] = total_cost return total_cost if not costs: return 0 else: return min(paint_cost(0, Red), paint_cost(0, Green), paint_cost(0, Blue))
true
af081807f141e02a8e1b67a2dcf5eff5fbe0b048
Python
MasterfulDingo/spells
/sqlformat.py
UTF-8
4,276
3.546875
4
[]
no_license
#this list contains a number of lists which have the database column name in the first position and the possible values of the entry following. entfields = [['level','0','1','2','3','4','5','6','7','8','9'],['school','abjuration','conjuration','divination','enchantment','evocation','illusion','necromancy','transmutation'],['concentration','no','yes'],['ritual','no','yes'],['casters','bard','cleric','druid','paladin','ranger','sorcerer','warlock','wizard']] def filtermfunc(filterraw): sql = [] #setting up some empty lists and variables for use in formatting the returned data. schools = [] schoolstr = "spell.school IN ({})" levels = [] levelstr = "spell.level IN ({})" concentration = [] concentrationstr = "spell.concentration IN ({})" ritual = [] ritualstr = "spell.ritual IN ({})" caster = [] casterstr = "spell.id IN (SELECT sid FROM spellcaster WHERE cid == {})" #nested SQL query, gathering all of the spell ids from the joining table "spellcaster" where the caster id matches that of the id given, which is gathered later in the function. for term in filterraw: #iterates through the returned terms from the form in the "search" page term = term.split("_") #splits each term by the underscore, as they were connected when being sent from the webpage. this gives us the first term, the column name in the database in the table "spells", and the value that we want to search by, which will need formatting in the following functions. if term[0] == "school": term[1] = entfields[1].index(term[1]) #finds the entry in the second list of the list "entfields" established at the start of this file that matches the current term being analysed, then takes the index of said matching entry and replaces the two. This works because though python is a 0 index language, I have the field name (not a value) in the 0 index position. schools.append(str(term[1])) #turns the index into a string and puts it in the list elif term[0] == "level": levels.append(str(term[1])) elif term[0] == "casters": term[1] = entfields[4].index(term[1]) #this acts much the same as the function used at the start of this if statement for schools, gathering the index of the matching term in the fifth list in the main list 'entfields' and later comparing it to the caster id in the joining table caster.append(casterstr.format(str(term[1]))) #for each spellcaster, a different list of spells must be returned, so the sql string used before is combined together with OR parameters. The database will only return the information for each spell once, so if multiple classes can cast the same spell there is no problem elif term[0] == "concentration": term[1] = (entfields[2].index(term[1]))-1 #with concentration and ritual, in the database they are represented as 0 and 1, so i must subtract one from their indexes in the list "entfields" concentration.append(str(term[1])) elif term[0] == "ritual": term[1] = (entfields[3].index(term[1]))-1 ritual.append(str(term[1])) #these four statements take an input of whether there is anything in the list, and if there are then joins the altered terms into a string and adds the string to the list of completed strings if schools: schoolstr = schoolstr.format(", ".join(schools)) sql.append(schoolstr) if levels: levelstr = levelstr.format(", ".join(levels)) sql.append(levelstr) if caster: casterstr = " OR ".join(caster) #joining the nested SQL queries with OR statements so it returns the spells that are available to any of the selected classes sql.append(casterstr) if concentration: concentrationstr = concentrationstr.format(", ".join(concentration)) sql.append(concentrationstr) if ritual: ritualstr = ritualstr.format(", ".join(ritual)) sql.append(ritualstr) sqlstring = str(" AND ".join(sql)) #joins the completed strings together via SQL conventions sqlstring = " WHERE {}".format(sqlstring) #throws a "WHERE" on the front to make the statement a parameter! this SQL parameter is now complete! return sqlstring
true
5d0c08b4054b36604ac0c381e3fe879bee6890d7
Python
J216/snake-engine
/snakec.py
UTF-8
9,991
2.90625
3
[ "MIT" ]
permissive
#execfile('./snakec.py') from math import sin, cos, radians from random import randrange, choice from time import sleep import os class Engine: def __init__(self, location=[-1,-1], engine_type=-1): self.location = location if engine_type == -1: self.item_type = choice([0]) else: self.item_type = engine_type class Snake: def __init__(self, location=[-1,-1],name='Snake', snake_type=0): self.location = location self.plocation = location self.name = name self.engines_ate = 0 self.heading = 0 if snake_type == -1: self.item_type = choice([0,1]) else: self.item_type = snake_type def turn(self, degrees=-1): if degrees == -1: degrees += choice([-45,-15,0,15,45]) self.heading += degrees if self.heading > 360: self.heading -= 360 if self.heading < 0: self.heading += 360 def eat_engine(self, engines): for e in engines: if self.location == e.location: engines.remove(e) self.engines_ate += 1 if self.item_type == 0: self.item_type = 1 def forward(self, blocked, width, height, engines): self.plocation = self.location self.location[0] += int(sin(radians(self.heading))) self.location[1] += int(cos(radians(self.heading))) if self.location[0] < 0: self.location[0] = 0 if self.location[0] > width - 1: self.location[0] = width - 1 if self.location[1] < 0: self.location[1] = 0 if self.location[1] > height - 1: self.location[1] = height - 1 if any(x.location == self.location for x in engines): self.eat_engine(engines) return 1 return 0 class World: engines = [] snakes=[] environ = [] blocked = [] def __init__(self,width=16,height=16): self.width = width self.height = height def find_random_open(self): open_space = [] while not open_space: open_space = [randrange(self.width-1),randrange(self.height-1)] if open_space in self.blocked: open_space = [] return open_space def random_terra(self): return [choice([0,1,2,2,2,3,4]),choice([0,1,1,1])] def create_environ(self): environ=[] for y_row in range(self.height): environ_row = [] for x_tile in range(self.width): environ_row.append(self.random_terra()) environ.append(environ_row) self.environ = environ def add_engine(self, coord): e = Engine(coord) self.engines.append(e) self.blocked.append(e.location) def add_snake(self, coord, name): s = Snake(coord, name) self.snakes.append(s) def snake_on_engine(self): for s in self.snakes: for e in self.snakes: if s.location == e.location: return True return False # image set up from gimp_be def imageSetup(w=256, h=256,file_name=""): #Create new image from height and width image = gimp.Image(w, h, RGB) new_layer = gimp.Layer(image, "Background", image.width, image.height, 0, 100, 0) pdb.gimp_image_add_layer(image, new_layer, 0) gimp.Display(image) return image # Close all - working but just guesses displays def ca(): try: for x in range(0, 500): gimp.delete(gimp._id2display(x)) except: print("close all failed") def load_sprites(image, fn='./snake_sprite.png'): if not pdb.gimp_image_get_layer_by_name(image, 'sprites'): layer = pdb.gimp_file_load_layer(image, os.path.expanduser(fn)) layer.name ='sprites' pdb.gimp_image_add_layer(image, layer, 0) pdb.gimp_item_set_visible(layer, 0) return True else: return False def load_layer(image,layer_type='un-named!!!', opacity=100): if not pdb.gimp_image_get_layer_by_name(image, layer_type): layer = pdb.gimp_layer_new(image, image.width, image.height, 1, layer_type, opacity, 0) pdb.gimp_image_add_layer(image, layer, 0) pdb.gimp_item_set_visible(layer, 1) pdb.gimp_image_set_active_layer(image, layer) return True else: layer = pdb.gimp_image_get_layer_by_name(image, layer_type) pdb.gimp_image_set_active_layer(image, layer) pdb.gimp_selection_all(image) drawable = pdb.gimp_image_active_drawable(image) pdb.gimp_edit_clear(drawable) return False def paint_tile(image,loc,paint=[0,0],layer_type='environ'): sprite_layer = pdb.gimp_image_get_layer_by_name(image, "sprites") pdb.gimp_image_set_active_layer(image, sprite_layer) pdb.gimp_image_select_rectangle(image, 2, paint[0]*32, paint[1]*32, 32, 32) drawable = pdb.gimp_image_active_drawable(image) non_empty = pdb.gimp_edit_copy(drawable) paint_layer = pdb.gimp_image_get_layer_by_name(image, layer_type) pdb.gimp_image_set_active_layer(image, paint_layer) pdb.gimp_image_select_rectangle(image, 2, loc[0]*32, loc[1]*32, 32, 32) drawable = pdb.gimp_image_active_drawable(image) floating_sel = pdb.gimp_edit_paste(drawable, 1) pdb.gimp_floating_sel_anchor(floating_sel) pdb.gimp_selection_none(image) def clear_tile(image,loc,layer_type='environ'): edit_layer = pdb.gimp_image_get_layer_by_name(image, layer_type) pdb.gimp_image_set_active_layer(image, edit_layer) pdb.gimp_image_select_rectangle(image, 2, loc[0]*32, loc[1]*32, 32, 32) drawable = pdb.gimp_image_active_drawable(image) pdb.gimp_edit_clear(drawable) pdb.gimp_selection_none(image) def paint_environ(image,environ_in,blur=1): for y_row in range(len(environ_in)): for x_pos in range(len(environ_in[0])): paint_tile(image,[x_pos, y_row], (environ_in[y_row][x_pos][0],environ_in[y_row][x_pos][1])) if blur: environ_layer = pdb.gimp_image_get_layer_by_name(image, "environ") pdb.gimp_image_set_active_layer(image, environ_layer) drawable = pdb.gimp_image_active_drawable(image) pdb.plug_in_gauss(image, drawable, 30, 30, 0) def paint_engines(image,engines): engine_types=[[0,3]] for e in engines: paint_tile(image,e.location, engine_types[e.item_type], 'engines') def paint_snakes(image,snakes): snake_types=[[1,2],[2,2]] for snake in snakes: clear_tile(image,snake.plocation, 'snakes') paint_tile(image,snake.location, snake_types[snake.item_type], 'snakes') def paint_text(image, location=[10,10], size = 16, text="Default!@$#", clear=0, text_layer= 'hud', color=(255,0,0) ): hud_layer = pdb.gimp_image_get_layer_by_name(image, text_layer) pdb.gimp_image_set_active_layer(image, hud_layer) drawable = pdb.gimp_image_active_drawable(image) if clear: pdb.gimp_selection_all(image) pdb.gimp_edit_clear(drawable) pdb.gimp_selection_none(image) pdb.gimp_context_set_foreground(color) text_layer = pdb.gimp_text_fontname(image, drawable, location[0], location[1], text, 0, 0, size, 1, 'Sans Bold') pdb.gimp_floating_sel_anchor(text_layer) pdb.gimp_selection_none(image) def paint_hud(image,snakes=[]): score_row = 0 for s in snakes: paint_text(image,[10, score_row*24+10], 16, 'Snake'+str(score_row+1)+': '+str(s.engines_ate), score_row==0) score_row += 1 def make_animation(image, animation,ms=70,): non_empty = pdb.gimp_edit_copy_visible(image) layer = pdb.gimp_layer_new(animation, image.width, image.height, 1, 'frame '+str(pdb.gimp_image_get_layers(animation)[0]+1)+'('+str(ms)+'ms)', 100, 0) pdb.gimp_image_add_layer(animation, layer, 0) pdb.gimp_item_set_visible(layer, 1) pdb.gimp_image_set_active_layer(animation, layer) drawable = pdb.gimp_image_active_drawable(animation) floating_sel = pdb.gimp_edit_paste(drawable, True) pdb.gimp_floating_sel_anchor(floating_sel) def load_layers(image): load_sprites(image) load_layer(image,'environ') load_layer(image,'engines',90) load_layer(image,'snakes') load_layer(image,'hud',60) ########################## ## MAIN METHOD ### ######################### def snake_world(blur=1,size=8,engines=20,snakes=6,snake_delay=0,animate=1): ca() if animate: animation = imageSetup(size*32,size*32) image = imageSetup(size*32,size*32) load_layers(image) w = World(size, size) w.create_environ() paint_environ(image,w.environ, blur) for i in range(engines): eng_loc = w.find_random_open() w.add_engine(eng_loc) paint_engines(image, w.engines) snake_pos = 0 for i in range(snakes): w.add_snake([(w.width/2+snake_pos)-snakes/2,w.height/2],'Snake '+str(snake_pos+1)) snake_pos += 1 paint_snakes(image, w.snakes) while not len(w.engines) == 0: for s in w.snakes: clear_tile(image, s.location, 'snakes') s.forward(w.blocked, w.width, w.height, w.engines) s.turn( choice([-90,0,0,90,180])) paint_snakes(image, [s]) if w.snake_on_engine(): clear_tile(image, s.location, 'engines') pdb.gimp_displays_flush() paint_hud(image,w.snakes) if animate: make_animation(image, animation) winner = w.snakes[0] for s in w.snakes: if s.engines_ate > winner.engines_ate: winner = s paint_text(image, location=[image.width/10,image.height/2], size=24, text=winner.name+" WINS!!!", clear=0, text_layer= 'hud', color=(0,255,255) ) print(winner.name+" WINS!!!") if animate: make_animation(image, animation,8000) if __name__ == '__main__': for i in range(1): snake_world()
true
716bc3cfe3d90b8db97a5424e0bab30b71f4bbef
Python
diegoponciano/challenge-for-developers
/githubstars/core/management/commands/createuser.py
UTF-8
1,707
2.53125
3
[]
no_license
import sys from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.hashers import make_password from getpass import getpass User = get_user_model() class Command(BaseCommand): help = 'Creates user' requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument('username') parser.add_argument('password') parser.add_argument('email') def _ask_password(self): password = None try: while True: if password is None: password = getpass('Password: ') password2 = getpass('Password (again): ') if password != password2: sys.stderr.write( "Error: Your passwords didn't match.\n") password = None continue if password.strip() == '': sys.stderr.write("Error: Blank passwords aren't allowed.\n") password = None continue break except KeyboardInterrupt: raise CommandError('Cancelled.') return password def handle(self, *args, **options): # password = self._ask_password() u = User.objects.create_user( username=options['username'], email=options['email'], password=make_password(options['password']), is_staff=True, is_superuser=True) u.save() self.stdout.write(self.style.SUCCESS( 'Usuário "%s" criado com sucesso.' % options['username']))
true
2c57eecf0efc5290e81d1d5e2fb9640862cafa44
Python
blueones/LeetcodePractices
/backpack92lintcode.py
UTF-8
1,465
2.921875
3
[]
no_license
class Solution: """ @param m: An integer m denotes the size of a backpack @param A: Given n items with size A[i] @return: The maximum size """ def backPack(self, m, A): # write your code self.max_res = 0 self.memo = [[None for i in range(m+1)] for j in range(len(A))] def dfs(index, current_storage): if self.memo[index][current_storage]: return self.memo[index][current_storage] if current_storage == 0: self.memo[index][current_storage] = 0 return 0 if index == len(A) - 1: if current_storage >= A[index]: self.memo[index][current_storage] = A[index] return A[index] else: self.memo[index][current_storage] = 0 return 0 else: max_rest = 0 include_rest = 0 if current_storage - A[index] >= 0: include_rest = dfs(index+1, current_storage - A[index]) + A[index] not_rest = dfs(index+1, current_storage) max_rest = max(include_rest, not_rest) self.memo[index][current_storage] = max_rest self.max_res = max(self.max_res, max_rest) return max_rest dfs(0, m) return self.max_res
true
6fcf57b6173a2fee165a945352592e7137a24df9
Python
glantucan/Pi-learning
/PyGame/basicMovement.py
UTF-8
1,356
3.625
4
[]
no_license
#!/usr/bin/env/ python3 # -*- coding: utf-8 -*- import pygame # Define colors white = (255, 255, 255) black = (0, 0, 0) red = (255, 0 , 0) gameExit = False lead_x = 300 lead_y = 300 # Initialize pygame pygame.init() # Setup the pygame canvas (called surface) gameDisplay = pygame.display.set_mode((800, 600)) #The parameter is a tuple pygame.display.set_caption('Slither') # Game loop while not gameExit: for event in pygame.event.get(): # Setup eevent conditions # See http://www.pygame.org/docs/ref/event.html for documentation on events if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x -= 10 if event.key == pygame.K_RIGHT: lead_x += 10 if event.key == pygame.K_UP: lead_y -= 10 if event.key == pygame.K_DOWN: lead_y += 10 if event.type == pygame.QUIT: gameExit = True gameDisplay.fill(white) # Let's draw the head of the snake # pygame.draw.rect(gameDisplay, black, [400, 300, 10, 100]) gameDisplay.fill(red, rect=[lead_x, lead_y, 10, 10]) #pygame.display.flip() # Updates the entire surface at once pygame.display.update() # Updates only what's needed pygame.quit() # Close pygame and cleanup quit() # exit out of python
true
0f7253e1925913a3e20548778615d8a748c99c5e
Python
venkatvi/Kaggle
/Titanic/predictWOCabinGridSearchRF.py
UTF-8
3,141
2.875
3
[]
no_license
import pandas as pd import numpy as np import math import re from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import accuracy_score def mapTitle(titleStr): if titleStr == 'MASTER': return 1 elif titleStr == 'MISS': return 2 elif titleStr == 'MR': return 3 elif titleStr == 'MRS': return 4 else: return 0 # Use only age, sex, fare, cabin class # dropna for age, cabin, and embarkment def cleanUpData(fileName, dataType): ds = pd.read_csv(fileName) # clean ups # 1. map sex - to [0-female, 1-male] # Add a new col which is nominal for sex. ds['Sex'] = ds['Sex'].map(lambda x: 0 if x is 'female' else 1) # 2. map embarked - [1-C , 2-Q, 3-S] ds['EmbarkedOrd'] = ds['Embarked'].map(lambda x: ord(x) if x and type(x) is str else 0).astype(int) # 3. map title - [0 - Other, 1 - Master, 2 - Miss, 3 - Mr, 4 - Mrs] ds['Title'] = ds['Name'].map(lambda x: re.match(r'([^,]*)\,([^.]*).', x).group(2).upper().replace(".", "").strip()) ds['Title'] = ds['Title'].map(lambda x: mapTitle(x) ) # backup passenger id passengerIds = ds['PassengerId'] # Drop PassengerId, Name, Sex, Embarked ds = ds.drop(['PassengerId', 'Name', 'Embarked', 'Cabin', 'Ticket'], axis=1) # clean ups # only age, cabin and embarked are underfilled # when age not available, fill it with mean age meanAge = ds['Age'].mean() ds['Age'] = ds['Age'].map(lambda x: x if np.isfinite(x) else meanAge).astype(float) # when cabin not available, fill it with cabin of the previous next ticket number if available, else fill with -1 # already taken care of in cabinclass and cabinnumber # when emabrked not available, randomly choose one of C, Q, S # already taken care of in CQS map earlier # fill up missing value in Fare meanFare = ds['Fare'].mean() ds['Fare'] = ds['Fare'].map(lambda x: x if np.isfinite(x) else meanFare).astype(float) print ds.info(verbose=True) return [ds, passengerIds] if __name__ == '__main__': [train, trainPassengerIds] = cleanUpData('Data/train.csv', 'train') [test, testPassengerIds] = cleanUpData('Data/test.csv', 'test') # Fit the training data to the Survived labels and create the decision trees target = train.filter(['Survived']) target = np.array(target.values).ravel() train = train.drop(['Survived'], axis=1) X,X_test,y,y_test = train_test_split(train,target, test_size=.20, random_state=1899) parameters = [{'n_estimators': np.arange(100,1000,100)}] clf = GridSearchCV(RandomForestClassifier(), parameters, cv=10, scoring='accuracy', verbose='3') clf.fit(X,y) # running the grid search prediction_accuracy = accuracy_score(y_test, clf.best_estimator_.predict(X_test)) print prediction_accuracy #Take the same decision trees and run it on the test data output = clf.best_estimator_.predict(test) submissionData = {'PassengerId': testPassengerIds, 'Survived': output} submissionDF = pd.DataFrame(submissionData) submissionDF.to_csv('Data/Titanic_NB_RF.csv', index=False)
true
db937f15f5d68df139eaadab5fb5baebcf38e371
Python
SebGeek/Kenobi
/motor/motor.py
UTF-8
4,496
2.640625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import time from rrb3 import RRB3 import multiprocessing import signal import syslog ''' https://github.com/simonmonk/raspirobotboard3 ''' class ThreadMotor(multiprocessing.Process): ''' Create a thread ''' def __init__(self, com_queue_RX, com_queue_TX): self.com_queue_RX = com_queue_RX self.com_queue_TX = com_queue_TX self.RqTermination = False super(ThreadMotor, self).__init__() def run(self): signal.signal(signal.SIGINT, self.handler) # battery voltage is 7.4V, max voltage for motors is 6.0V self.raspirobot = RRB3(7.4, 6) # Do not call from __init__() else the library doesn't work self.raspirobot.set_motors(0, 0, 0, 0) self.raspirobot.set_oc1(0) while self.RqTermination == False: ''' read com_queue_RX ''' com_msg = self.com_queue_RX.get(block=True, timeout=None) if com_msg[0] == "STOP": self.RqTermination = True elif com_msg[0] == "MOTOR_ROLL_MAGNITUDE": (roll, magnitude, angle) = com_msg[1] self.motor_run(roll, magnitude, angle) elif com_msg[0] == "MOTOR_Request_Distance": distance = self.raspirobot.get_distance() self.com_queue_TX.put(("MOTOR_Distance", distance)) elif com_msg[0] == "MOTOR_FORWARD": motor_speed = com_msg[1] self.raspirobot.forward(0, motor_speed) # 0 means motors run infinitely elif com_msg[0] == "MOTOR_BACKWARD": motor_speed = com_msg[1] self.raspirobot.reverse(0, motor_speed) # 0 means motors run infinitely elif com_msg[0] == "MOTOR_RIGHT": motor_speed = com_msg[1] # left motors turn to go in right direction, allright ? self.raspirobot.left(0, motor_speed) # 0 means motors run infinitely elif com_msg[0] == "MOTOR_LEFT": motor_speed = com_msg[1] self.raspirobot.right(0, motor_speed) # 0 means motors run infinitely elif com_msg[0] == "MOTOR_OC": on_off = com_msg[1] self.raspirobot.set_oc1(on_off) else: syslog.syslog("ThreadMotor: unknown msg") self.raspirobot.set_motors(0, 0, 0, 0) self.raspirobot.set_oc1(0) self.raspirobot.cleanup() syslog.syslog("ThreadMotor: end of thread") def motor_run(self, roll, magnitude, angle): # SPEED: magnitude is 0 to 1000 motor_speed = magnitude / 300. if motor_speed < 0.1: motor_speed = 0.0 elif motor_speed > 1.0: motor_speed = 1.0 motor_speed_left = motor_speed_right = motor_speed # FORWARD/REVERSE: angle is negative in reverse position, else positive if angle >= 0: direction_left = 0 direction_right = 0 else: direction_left = 1 direction_right = 1 # DIRECTION: roll is -90 at right, +90 at left if roll < 0: motor_speed_right -= abs(roll / 90.) else: motor_speed_left -= abs(roll / 90.) if motor_speed_right < 0: motor_speed_right = 0 if motor_speed_left < 0: motor_speed_left = 0 self.raspirobot.set_motors(motor_speed_left, direction_left, motor_speed_right, direction_right) def handler(self, signum, frame): syslog.syslog('ThreadMotor: Signal handler called with signal', signum) self.raspirobot.set_motors(0, 0, 0, 0) if __name__ == '__main__': rr = RRB3(7.4, 6) # battery voltage is 7.4V, max voltage for motors is 6.0V print(rr.get_distance()) speed = 0.6 #rr.set_motors(speed, 0, speed, 0) #rr.forward(1, speed) rr.right(0.5, speed) time.sleep(2) rr.cleanup() # ThreadMotor_com_queue_TX = multiprocessing.Queue() # ThreadMotor_com_queue_TX.cancel_join_thread() # ThreadMotor_com_queue_RX = multiprocessing.Queue() # ThreadMotor_com_queue_RX.cancel_join_thread() # ThreadMotor = ThreadMotor(ThreadMotor_com_queue_RX, ThreadMotor_com_queue_TX) # # ThreadMotor.start() # Start the thread by calling run() method # ThreadMotor_com_queue_RX.put(("MOTOR_ROLL_MAGNITUDE", (0, 200))) # time.sleep(1) # print "QUIT !!" # ThreadMotor_com_queue_RX.put(("STOP", None))
true
97b90caf20a2abd3072336a1d01b9aacccb47928
Python
Tauror/VxRailSentimentAanalysis
/mTest/timeline_bar_4.7.xx.py
UTF-8
5,957
2.59375
3
[]
no_license
import xlrd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime def get_excel_date(t): t_as_datetime = datetime(*xlrd.xldate_as_tuple(t, workbook.datemode)) date = str(t_as_datetime.year)+'-'+str(t_as_datetime.month)+'-'+str(t_as_datetime.day) return date # read the defaultdict and plot it xls_file = './SentimentAanalysis/mean_sentiments.xls' workbook = xlrd.open_workbook(xls_file) # 打开工作簿 sheets = workbook.sheet_names() # 获取工作簿中的所有表格 # 获取工作簿中所有表格中的的第1个表格数据 worksheet0 = workbook.sheet_by_name(sheets[0]) rows = worksheet0.nrows cols = worksheet0.ncols sentiment_months = [worksheet0.cell_value(i, 0) for i in range(1, rows)] sentiment_scores = [round(worksheet0.cell_value(i, 1),1) for i in range(1, rows)] # Convert date strings (e.g. 2014-10-18) to datetime sentiment_months = [datetime.strptime(m, "%Y-%m") for m in sentiment_months] # Create figure and plot a stem plot with the date fig, ax = plt.subplots() # fig, ax = plt.subplots(figsize=(8.8, 4), constrained_layout=True) ax.set(title="Sentiment Survey of VxRail on Reddit") ################################################# plt.plot(sentiment_months, sentiment_scores, 'b', linewidth=1, label='sentiment level') plt.plot(sentiment_months, sentiment_scores, 'bo') plt.plot(sentiment_months, np.ones((len(sentiment_months)))*3, 'r--', label='standard line') ax.set_ylim([-3, 9]) plt.ylabel('Satisfaction level') ################################################# # 第6个表格数据4.7.xxx:画层叠柱状图 worksheet4 = workbook.sheet_by_name(sheets[5]) rows = worksheet4.nrows cols = worksheet4.ncols installbase47_date = [get_excel_date(worksheet4.cell_value(i, 0)) for i in range(1, rows)] installbase47000 = [int(worksheet4.cell_value(i, 1)) for i in range(1, rows)] installbase47001 = [int(worksheet4.cell_value(i, 2)) for i in range(1, rows)] installbase47100 = [int(worksheet4.cell_value(i, 3)) for i in range(1, rows)] installbase47110 = [int(worksheet4.cell_value(i, 4)) for i in range(1, rows)] installbase47111 = [int(worksheet4.cell_value(i, 5)) for i in range(1, rows)] installbase47200 = [int(worksheet4.cell_value(i, 6)) for i in range(1, rows)] installbase47211 = [int(worksheet4.cell_value(i, 7)) for i in range(1, rows)] installbase47212 = [int(worksheet4.cell_value(i, 8)) for i in range(1, rows)] # Convert date strings (e.g. 2014-10-18) to datetime installbase47_date = [datetime.strptime(d, "%Y-%m-%d") for d in installbase47_date] b1 = [installbase47000[i] + installbase47001[i] for i in range(len(installbase47000))] b2 = [b1[i] + installbase47100[i] for i in range(len(installbase47100))] b3 = [b2[i] + installbase47110[i] for i in range(len(installbase47110))] b4 = [b3[i] + installbase47111[i] for i in range(len(installbase47111))] b5 = [b4[i] + installbase47200[i] for i in range(len(installbase47200))] b6 = [b5[i] + installbase47211[i] for i in range(len(installbase47211))] ax2 = ax.twinx() # this is the important function ax2.get_xaxis().set_major_locator(mdates.MonthLocator(interval=1)) plt.bar(installbase47_date, installbase47000, width=15, label='4.7.000', fc='blue', zorder=1) plt.bar(installbase47_date, installbase47001, width=15, bottom=installbase47000, label='4.7.001', fc='yellow', zorder=1) plt.bar(installbase47_date, installbase47100, width=15, bottom=b1, label='4.7.100', fc='green', zorder=1) plt.bar(installbase47_date, installbase47110, width=15, bottom=b2, label='4.7.110', fc='hotpink', zorder=1) plt.bar(installbase47_date, installbase47111, width=15, bottom=b3, label='4.7.111', fc='orange', zorder=1) plt.bar(installbase47_date, installbase47200, width=15, bottom=b4, label='4.7.200', fc='royalblue', zorder=1) plt.bar(installbase47_date, installbase47211, width=15, bottom=b5, label='4.7.211', fc='gold', zorder=1) plt.bar(installbase47_date, installbase47212, width=15, bottom=b6, label='4.7.212', fc='lawngreen', zorder=1) ax2.set_ylim([0, 8000]) ax2.set_ylabel('Install Base') # for i in range(1,4): ################################################# # 获取4.7.xxx release信息 worksheet1 = workbook.sheet_by_name(sheets[3]) rows = worksheet1.nrows cols = worksheet1.ncols release_no40 = [str(worksheet1.cell_value(i, 0)).strip(u'\u200b') for i in range(1, rows)] release_date40 = [get_excel_date(worksheet1.cell_value(i, 1)) for i in range(1, rows)] # Convert date strings (e.g. 2014-10-18) to datetime release_date40 = [datetime.strptime(d, "%Y-%m-%d") for d in release_date40] # Choose some nice levels levels = np.tile([-2, 8, -1, 7, 0, 6, 1, 5, 2, 4], int(np.ceil(len(release_date40)/6)))[:len(release_date40)] markerline, stemline, baseline = ax.stem(release_date40, levels, bottom=3, linefmt="y:", basefmt=" ", use_line_collection=True, label='release version') baseline.set_ydata(3) # Shift the markers to the baseline by replacing the y-data by zeros. # markerline.set_ydata(np.ones((len(release_date40)))*3) # setp(): Set a property on an artist object. plt.setp(markerline, mec="k", mfc="w", zorder=3) # annotate lines vert = np.array(['top', 'bottom'])[(levels > 3).astype(int)] for d, l, r, va in zip(release_date40, levels, release_no40, vert): ax.annotate(r, xy=(d, l), xytext=(-3, np.sign(l)*3), textcoords="offset points", va=va, ha="right") ########################################################################################## # format xaxis with 1 month intervals # ax.xaxis.set_major_formatter(mdates.DateFormatter('%-m')) ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=1)) ax.get_xaxis().set_major_formatter(mdates.DateFormatter("%b %Y")) plt.setp(ax.get_xticklabels(), rotation=30, ha="right") # remove y axis and spines # ax.get_yaxis().set_visible(False) for spine in ["top", "right"]: ax.spines[spine].set_visible(False) ax.margins(y=0.1) plt.tight_layout() plt.legend() plt.show()
true
6ed7c66c3dd8ee2ef7516151392dce85aab87711
Python
jhoeksem/SE_with_drones
/01_gettingstarted/hello_drone.py
UTF-8
1,479
2.71875
3
[ "MIT" ]
permissive
# Import DroneKit-Python from dronekit import connect, VehicleMode, time #Setup option parsing to get connection string import argparse parser = argparse.ArgumentParser(description='Print out vehicle state information') parser.add_argument('--connect',help="vehicle connection target string. If not specified, SITL automatically started and used") args=parser.parse_args() connection_string = args.connect sitl = None #Start SITL if no connection string specified if not connection_string: import dronekit_sitl sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() # Connect to the Vehicle. # Set `wait_ready=True` to ensure default attributes are populated before `connect()` returns. print "\nConnecting to vehicle on: %s" % connection_string vehicle = connect(connection_string, wait_ready=False, baud=56700) vehicle.wait_ready(timeout=500) #vehicle.wait_ready('autopilot_version') #Get some vehicle attributes (state) print "Autopilot_version: %s" % vehicle.version print "Get some vehicle attribute values:" print "GPS: %s" % vehicle.gps_0 print "Battery: %s" % vehicle.battery print "Last Heartbeat: %s" % vehicle.last_heartbeat print "Is Armable?: %s" % vehicle.system_status.state print "Mode: %s" % vehicle.mode.name # settable print vehicle.location.global_relative_frame.lat print vehicle.location.global_relative_frame.lon # Close vehicle object before exiting script vehicle.close() time.sleep(5) print("Completed")
true
02bfd63aad6189c0267ac1f566ac803e1c8ff0da
Python
dlwns147/Projects
/python/10.py
UTF-8
190
3.640625
4
[]
no_license
sum = 0 n = 1 print("덧셈을 하고 싶은 양의 정수들을 입력하세요. 0 입력시 종료.") while n != 0 : n=int(input()) sum += n print("총합은", sum, "입니다.")
true
a6acdd8bb2cece07b58649ded00f086a313f843e
Python
Dhadhazi/PD52-InstagramFollowerBot
/main.py
UTF-8
1,793
2.546875
3
[]
no_license
from selenium import webdriver from selenium.common.exceptions import ElementClickInterceptedException import time chrome_driver_path = "" ACCOUNT_TO_FOLLOW_FOLLOWERS = "" USERNAME = "" PASSWORD = "" driver = webdriver.Chrome(executable_path=chrome_driver_path) driver.get("https://www.instagram.com/") def login(): accept_cookies_button = driver.find_element_by_xpath("/html/body/div[2]/div/div/div/div[2]/button[1]") time.sleep(2) if (accept_cookies_button): accept_cookies_button.click() time.sleep(2) username_input = driver.find_element_by_name("username") username_input.send_keys(USERNAME) password_input = driver.find_element_by_name("password") password_input.send_keys(PASSWORD) time.sleep(2) login_button = driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button') login_button.click() def find_followers(): driver.get(f"https://www.instagram.com/{ACCOUNT_TO_FOLLOW_FOLLOWERS}/") time.sleep(2) followers_button = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a') followers_button.click() time.sleep(2) modal = driver.find_element_by_xpath('/html/body/div[5]/div/div/div[2]') for i in range(10): driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", modal) time.sleep(2) def follow(): all_buttons = driver.find_elements_by_css_selector("li button") for button in all_buttons: try: button.click() time.sleep(1) except ElementClickInterceptedException: cancel_button = driver.find_element_by_xpath('/html/body/div[5]/div/div/div/div[3]/button[2]') cancel_button.click() login() time.sleep(2) find_followers() follow()
true
8ba5836cc4bab9c20f3eaede4210da1f7fb88aa7
Python
fun-math/Autumn-of-Automation
/OpenCV/Q1,3.py
UTF-8
549
2.640625
3
[ "MIT" ]
permissive
import cv2 import numpy as np img=cv2.imread("meme.jpg",1) rows,cols,channels=img.shape img_hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) mask=cv2.inRange(img_hsv,(-5,50,70),(5,255,255)) mask_inv=cv2.bitwise_not(mask) dst_bg=cv2.bitwise_and(img,img,mask=mask_inv) blue=np.zeros([rows,cols,channels]) blue[:,:,0]=255*np.ones([rows,cols]) blue=blue.astype(np.uint8) dst_fg=cv2.bitwise_and(blue,blue,mask=mask) dst=cv2.add(dst_bg,dst_fg) cv2.imshow('mask',mask) cv2.imshow('result',dst) cv2.imshow('original',img) cv2.waitKey(0) cv2.destroyAllWindows()
true
a6777a969158aece3f8527fa2253c34197fc1069
Python
jaymax01/web_scraping
/taking screenshots with selenium/scraping_excersise.py
UTF-8
1,084
3.109375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Mar 12 13:58:56 2021 @author: Max """ import re from bs4 import BeautifulSoup import requests url = 'https://www.marketwatch.com/investing/stock/amzn?mod=over_search' page = requests.get(url) #print(page.text) soup = BeautifulSoup(page.text, 'lxml') #print(soup) # Price of the stock price = soup.find_all('div', class_ ='intraday__data')[0] print('The stock price is : {}'.format(price.find('h3').text) ) print() # Closing price of the stock closing_price = soup.find('td', class_ = re.compile('u-semi')) print('The closing price is :', closing_price.text) print() # 52 week range (lower, upper) week_range = soup.find_all('div', class_ = 'range__header')[2] week_range_2 = week_range.find_all('span', class_= 'primary') print('The 52 week range for the stock') for i in week_range_2: print(i.text) print() # Analyst rating rating = soup.find_all('div', class_ = 'analyst__chart')[0] rating_2 = rating.find_all('li', class_ = 'analyst__option active')[0] print('The analyst rating for the stock is :', rating_2.string)
true
d9f35b277d9df2c77f61f7f8f1811abce78efc3f
Python
sgk-000/algorithm
/Ex08/huhman.py
UTF-8
1,365
3.34375
3
[]
no_license
import sys import heapq class Node: def __init__(self, x): self.data = x self.left = None self.right = None def insert(self,node, x): if node is None: return Node(x) elif x == node.data: return node elif x < node.data: node.left = self.insert(node.left, x) else: node.right = self.insert(node.right, x) return node def traverse(self,node): if node: self.traverse(node.left) print(node.data) self.traverse(node.right) inp = "AIZUWAKAMATASUINAWASIROKITAKATAKORIYAMA" heap = [] data = {} mini1 = mini2 = () for i in range(len(inp)): data[inp[i]] = data.get(inp[i],0) + 1 data = {v:k for k,v in data.items()} print(data) list = tuple(data.items()) new_node = () for i in range(len(list)): heapq.heappush(heap,list[i]) mini1 = heapq.heappop(heap) mini2 = heapq.heappop(heap) sum = int(mini1[0]) + int(mini2[0]) new_node = (sum,) nod = Node(mini1) nod.insert(nod,mini2) heapq.heappush(heap,new_node) while(True): if(len(heap) <= 1):break mini1 = heapq.heappop(heap) mini2 = heapq.heappop(heap) sum = int(mini1[0]) + int(mini2[0]) new_node = (sum,) nod.insert(nod,mini1) nod.insert(nod,mini2) heapq.heappush(heap,new_node) #nod.traverse(nod)
true
14b1adffb349cc954952b0ce4c156dd3235bbe02
Python
davidwparker/csci5606-numcomp
/final.py
UTF-8
21,526
3.328125
3
[]
no_license
from __future__ import division import math class final: epsilon = 0.0 """ final project class """ def __init__(self): self.epsilon = self.machineEpsilon() def printHeader(self): """ Prints the header for the class """ print '\nPrinciples of Numerical Computation' print 'David Parker' print 'Final Project, December 3, 2011' ######################################################## ## Run tests on our algorithms to make sure they're ok ######################################################## def testFunctions(self): """ Tests the functionality of the algorithms """ print '\nTests the functionality of the algorithms' print 'Machine epsilon =',self.epsilon # Tests for Newton det = self.determinant2x2([[1,1],[2,10]]) assert det == 8 assert self.matrixScale([[1,2],[-3,1]],2) == [[2,4],[-6,2]] assert self.inverse2x2([[1,1],[2,10]],det) == [[1.25,-0.125],[-0.25,0.125]] assert self.jacobi2x2(1,5,self.testF1dx,self.testF1dy,self.testF2dx,self.testF2dy) == [[1,1],[2,10]] self.testNewton() self.test2Newton() # Tests for Conjugate Gradient assert self.dot([1,2],[3,-4]) == -5 assert self.vectorScale([1,2],5) == [5,10] assert self.multiplyAx([[1,2],[0,1]],[2,1]) == [4,1] assert self.vectorSubtract([2,1],[1,-1]) == [1,2] assert self.vectorAddition([2,1],[1,-1]) == [3,0] self.testConjugateGradient([[4,1],[1,3]],[1,2],[2,1],50) # Tests for Cubic Spline self.testCubicSpline() # Tests for PQ Decomposition p,q = self.testPQ(2,[[3, 15],[-1,-1]]) assert p == [[0,3],[4,-1]] assert q == [[0,1],[1,5]] p,q = self.testPQ(3,[[2,6,4],[4,15,5],[5,17,7]]) assert p == [[0,0,2],[0,3,4],[-1,2,5]] assert q == [[0,0,1],[0,1,-1],[1,3,2]] assert self.solveAxb([[0,3],[4,-1]],[33,-3]) == [2,11] assert self.solvePQxb([[0,3],[4,-1]],[[0,1],[1,5]],[33,-3]) == [1,2] ######################################################## ## Algorithms and Functions ######################################################## def machineEpsilon(self,func=float): """ Returns the machine epsilon """ mEpsilon = func(1) while func(1)+func(mEpsilon) != func(1): mEpsilonLast = mEpsilon mEpsilon = func(mEpsilon) / func(2) return mEpsilonLast def multiplyAx(self,a,x): """ Return a matrix-vector product """ ax = [(sum([a[i][j]*x[j] for j in range(len(x))])) for i in range(len(x))] if printDetails: print 'Matrix multiplied by a vector' print 'A =',a print 'x =',x print 'Ax =',ax return ax def determinant2x2(self,a): """ Return the determinant of a 2x2 matrix """ det = a[1][1]*a[0][0]-a[0][1]*a[1][0] if printDetails: print 'Determinant of a 2x2 matrix A = a[1][1]*a[0][0]-a[0][1]*a[1][0]' print 'A =',a print 'Det A =',det return det def matrixScale(self,a,s): """ Return a matrix-constant product (a scaled matrix) """ scaled = [[s * a[i][j] for j in range(len(a))] for i in range(len(a))] if printDetails: print 'Matrix scaled by S' print 'A =',a print 'S =',s print 'Scaled matrix =',scaled return scaled def inverse2x2(self,a,d): """ Return the inverse of a 2x2 matrix A^-1 = (1/Determinant(A))( D -B ) ( -C A ) """ # change positions ainv = [[0 for j in range(0,2)] for i in range(0,2)] ainv[0][0] = a[1][1] ainv[0][1] = -a[0][1] ainv[1][0] = -a[1][0] ainv[1][1] = a[0][0] # scale ainv = self.matrixScale(ainv,1.0/d) if printDetails: print 'Inverse of a 2x2 matrix' print 'a =',a print 'det a =',d print 'ainv =',ainv return ainv def jacobi2x2(self,x,y,f1,f2,f3,f4): """ Return the Jacobi of a 2x2 matrix """ j = [[0 for j in range(0,2)] for i in range(0,2)] j[0][0] = f1(x,y) j[0][1] = f2(x,y) j[1][0] = f3(x,y) j[1][1] = f4(x,y) return j def newton(self,x,y,max,f1,f1dx,f1dy,f2,f2dx,f2dy): """ Return the newton value for a given 2x2 matrix """ # Newton => x^(n+1) = x^n - J(x^n)F(xn) for i in range(0,max): # Setup Jacobi # J = ( dx/df1 dy/df1 ) # ( dx/df2 dy/df2 ) print 'x =',x,'y =',y f1v = f1(x,y) f2v = f2(x,y) f = [] f.append(f1v) f.append(f2v) print 'f =',f # Do I actually want this check in here? if abs(f1v) < self.epsilon or abs(f2v) < self.epsilon: print 'f1v or f2v below machine epsilon' return j = self.jacobi2x2(x,y,f1dx,f1dy,f2dx,f2dy) if printDetails: print 'j =',j # Get inverse of 2x2 Jacobi jdet = self.determinant2x2(j) jinv = self.inverse2x2(j,jdet) if printDetails: print 'jinv =',jinv negjinv = self.matrixScale(jinv,-1) if printDetails: print 'negjinv =',negjinv # solve for h h = self.multiplyAx(negjinv,f) if printDetails: print 'h =',h # x^n+1 = x^n - h x = x + h[0] y = y + h[1] def dot(self,v1,v2): """ Return the dot product of two vectors """ dotProd = sum([v1[i] * v2[i] for i in range(len(v1))]) if printDetails: print 'Dot product for two vectors is the sum of the product of the items' print 'v1 =',v1 print 'v2 =',v2 print 'v1 dot v2 =',dotProd return dotProd def vectorScale(self,v,s): """ Return a vector-constant product (a scale vector) """ scaled = [s * v[i] for i in range(len(v))] if printDetails: print 'Vector scaled by a constant' print 'v =',v print 's =',s print 'v*s =',scaled return scaled def vectorSubtract(self,v1,v2): """ Return the differenc of two vectors """ vsub = [v1[i] - v2[i] for i in range(len(v1))] if printDetails: print 'Vector subtraction' print 'v1 =',v1 print 'v2 =',v2 print 'v1 - v2 =',vsub return vsub def vectorAddition(self,v1,v2): """ Return the sum of two vectors """ vadd = [v1[i] + v2[i] for i in range(len(v1))] if printDetails: print 'Vector addition' print 'v1 =',v1 print 'v2 =',v2 print 'v1 + v2 =',vadd return vadd def conjugateGradient(self,x,a,b,max,delta=0.0): """ Solve Ax = b with conjugate gradient method """ print '\nSolving Ax = b with conjugate gradient method' if delta == 0.0: delta = self.epsilon # r = residual # r = b - Ax r = self.vectorSubtract(b,self.multiplyAx(a,x)) if printDetails: print 'r=',r v = list(r) if printDetails: print 'v=',v c = self.dot(r,r) if printDetails: print 'c=',c for k in range(1,max+1): if c < self.epsilon: print 'finish due to c < epsilon' break if math.sqrt(self.dot(v,v)) < delta: print 'finish due to sqrt(dot(v,v)) < delta' break # z = a*v z = self.multiplyAx(a,v) if printDetails: print 'z=',z t = c / self.dot(v,z) if printDetails: print 't=',t # x = x + tv x = self.vectorAddition(x,self.vectorScale(v,t)) if printDetails: print 'x=',x # r = r - tz r = self.vectorSubtract(r,self.vectorScale(z,t)) if printDetails: print 'r=',r d = self.dot(r,r) if printDetails: print 'd=',d # NOTE: I moved this check for d < self.epsilon to be # at the top of the function so that we still # output the last possible k,x,r # if (d < self.epsilon): # print 'd < epsilon' # break # v = r + (d/c)*v v = self.vectorAddition(r,self.vectorScale(v,d/c)) c = d print 'k=',k,'\nx=',x,'\nr=',r def solveHB(self,n,t,y): """ Solving for h and b """ h = [0.0 for i in range(0,n)] b = [0.0 for i in range(0,n)] # n... (actually n-1) for i in range(0,n): h[i] = t[i+1] - t[i] b[i] = 6.0*(y[i+1] - y[i]) / h[i] return h,b def solveUV(self,n,h,b): """ Solving for u and v """ u = [0 for i in range(0,n)] v = [0 for i in range(0,n)] u[1] = 2.0*(h[0]+h[1]) v[1] = b[1]-b[0] # n... (actually n-1) for i in range(2,n): u[i] = 2.0*(h[i]+h[i-1]) - pow(h[i-1],2)/u[i-1] v[i] = b[i] - b[i-1] - h[i-1]*v[i-1]/u[i-1] return u,v def solveZ(self,n,h,u,v): """ Solving for z in Cubic Spline """ z = [0 for i in range(0,n+1)] z[n] = 0 # 0... (actually 1) for i in range(n-1,0,-1): z[i] = (v[i] - h[i]*z[i+1])/u[i] z[0] = 0 return z def solveA(self,n,h,z): """ Solving for a in Cubic Spline """ return [((1.0/(6.0*h[i]))*(z[i+1]-z[i])) for i in range(0,n)] def solveB(self,n,z): """ Solving for b in Cubic Spline """ return [(z[i]/2.0) for i in range(0,n)] def solveC(self,n,h,z,y): """ Solving for c in Cubic Spline """ return [(-h[i]/6.0*z[i+1] - h[i]/3.0*z[i] + 1/h[i]*(y[i+1]-y[i])) for i in range(0,n)] def solveS(self,n,xlist,y,t,c,b,a): """ Solve for s in a Cubic Spline """ s = [0 for i in range(len(xlist))] for j,x in enumerate(xlist): for i in range(0,n): if t[i] <= x and x < t[i+1]: s[j] = (y[i] + (x-t[i])*(c[i] + (x-t[i])*(b[i] + (x-t[i])*a[i]))) return s def solveE(self,n,s,y): """ Solve for the error in a Cubic Spline """ return [abs(s[i]-y[i]) for i in range(0,n)] def cubicSpline(self,n,t,y,xlist,fx,m): """ Cubic Spline Algorithm """ print '\nPerforming Cubic Spline' h,b = self.solveHB(n,t,y) if printDetails: print 'h =',h,'\nb =',b u,v = self.solveUV(n,h,b) if printDetails: print 'u =',u,'\nv =',v z = self.solveZ(n,h,u,v) if printDetails: print 'z =',z a = self.solveA(n,h,z) if printDetails: print 'a =',a b = self.solveB(n,z) if printDetails: print 'b =',b c = self.solveC(n,h,z,y) if printDetails: print 'c =',c if printDetails: print 'x =',xlist s = self.solveS(n,xlist,y,t,c,b,a) if printDetails: print 's =',s e = self.solveE(m,s,fx) if printDetails: print 'e =',e # PRINT OUTPUT for i in range(0,m): text = 'i= %2d' % i text += ' x[i]= %10f' % xlist[i] text += ' s[i]= %10f' % s[i] text += ' f(x)= %10f' % fx[i] text += ' e[i]= %10f' % e[i] print text ######################################################## ## NEWTON METHOD TESTS ######################################################## def testF1(self,x,y): return x + y - 3 def testF1dx(self,x,y): return 1 def testF1dy(self,x,y): return 1 def testF2(self,x,y): return pow(x,2) + pow(y,2) - 9 def testF2dx(self,x,y): return 2*x def testF2dy(self,x,y): return 2*y def testNewton(self): """ Tests the Newton Method """ print "\nTesting the Newton Method (Test 1)" x = 1 y = 5 max = 3 self.newton(x,y,max,self.testF1,self.testF1dx,self.testF1dy, \ self.testF2,self.testF2dx,self.testF2dy) def test2F1(self,x,y): return pow(x,2) - 2*x - y + 0.5 def test2F1dx(self,x,y): return 2*x - 2 def test2F1dy(self,x,y): return -1 def test2F2(self,x,y): return pow(x,2) + 4*pow(y,2) - 4 def test2F2dx(self,x,y): return 2*x def test2F2dy(self,x,y): return 8*y def test2Newton(self): """ Tests the Newton Method http://math.fullerton.edu/mathews/numerical/n2.htm Exercise 1 """ print "\nTesting the Newton Method (Test 2)" x = 2.0 y = 0.25 max = 5 self.newton(x,y,max,self.test2F1,self.test2F1dx,self.test2F1dy, \ self.test2F2,self.test2F2dx,self.test2F2dy) ######################################################## ## Page 93, Computer Problem 14 ######################################################## # PART A def function14a1(self,x,y): """ f(x,y) = 4y^2 + 4y + 52x - 19 """ return 4*pow(y,2) + 4*y + 52*x - 19 def function14a1dx(self,x,y): """ f(x,y) = 4y2 + 4y + 52x -19 dx/df = 52 """ return 52 def function14a1dy(self,x,y): """ f(x,y) = 4y2 + 4y + 52x - 19 dy/df = 8y + 4 """ return 8*y + 4 def function14a2(self,x,y): """ f(x,y) = 169x^2 + 3y^2 + 111x - 10y - 10 """ return 169*pow(x,2) + 3*pow(y,2) + 111*x - 10*y - 10 def function14a2dx(self,x,y): """ f(x,y) = 169x^2 + 3y^2 + 111x - 10y - 10 dx/df = 338x + 111 """ return 338*x + 111 def function14a2dy(self,x,y): """ f(x,y) = 6y - 10 - 10 """ return 6*y - 10 # PART B def function14b1(self,x,y): """ f(x,y) = x + e^-1x + y^3 = 0 """ return x + math.exp(-1*x) + pow(y,3) def function14b1dx(self,x,y): """ f(x,y) = x + e^-1x + y^3 = 0 dx/df = 1 - e^-1x """ return 1 - math.exp(-1*x) def function14b1dy(self,x,y): """ f(x,y) = x + e^-1x + y^3 = 0 dy/df = 3y^2 """ return 3*pow(y,2) def function14b2(self,x,y): """ f(x,y) = x^2 + 2xy - y^2 + tan(x) """ return pow(x,2) + 2*x*y - pow(y,2) + math.tan(x) def function14b2dx(self,x,y): """ f(x,y) = x^2 + 2xy - y^2 + tan(x) dx/df = 2x + 2y + sec^2(x) = 2x + 2y + 1 + tan(x)**2 """ return 2*x + 2*y + 1 + math.tan(x)**2 def function14b2dy(self,x,y): """ f(x,y) = x^2 + 2xy - y^2 + tan(x) dy/df = 2x - 2y """ return 2*x - 2*y def problem93_14(self): """ Solves computer problem 14 on page 93 """ print '\nPage 93, Computer Problem 14' # GUESS FOR STARTING POSITION x = 0 y = 0 max = 10 print 'Part a)' self.newton(x,y,max,self.function14a1,self.function14a1dx,self.function14a1dy, \ self.function14a2,self.function14a2dx,self.function14a2dy) # GUESS FOR STARTING POSITION x = 1 y = 1 max = 10 print 'Part b)' self.newton(x,y,max,self.function14b1,self.function14b1dx,self.function14b1dy, \ self.function14b2,self.function14b2dx,self.function14b2dy) ######################################################## ## CONJUGATE GRADIENT METHOD TESTS ######################################################## def testConjugateGradient(self,a,b,x,max): """ Tests the conjugate gradient """ print 'Testing Conjugate Gradient' print 'Matrix A =',a print 'Vector b =',b print 'Vector x =',x print 'Answer should be x = [0.0909, 0.6364] (see below)' self.conjugateGradient(x,a,b,max) ######################################################## ## Page 245, Computer Problem 1 ######################################################## def problem245_1(self): """ Solves computer problem 1 on page 245 """ print '\nPage 245, Computer Problem 1' # setup hilbert matrix # n_elements = 5 = true number of elements in A # n_range = n_elements+1 = number used for Python's range function # aij = (i + j - 1)^-1 n_elements = 10 n_range = n_elements+1 a = [[(1.0/(row+col-1)) for col in range(1,n_range)] for row in range(1,n_range)] # Optional print Hilbert matrix if printDetails: print 'Hilbert',n_elements,'x',n_elements,'matrix A:' for i in range(0,n_elements): print a[i] # setup b-vector # bi = 1/3 (SUM j=1 to n of aij) b = [0 for row in range(1,n_range)] for i in range(1,n_range): sum = 0.0 for j in range(1,n_range): sum += a[i-1][j-1] b[i-1] = 1.0/3.0*sum # Optional print b vector if printDetails: print 'b vector:\n',b # initial x-vector # x = [0] x = [0 for i in range(1,n_range)] if printDetails: print 'x vector:\n',x # Solve via Conjugate Gradient max = 50 self.conjugateGradient(x,a,b,max) ######################################################## ## CUBIC SPLINE TESTS ######################################################## def testCubicSpline(self): """ Tests the Cubic Spline functions """ print '\nTesting Cubic Spline' # Setup Problem n = 10 nMinus = n - 1 t = [i/nMinus*2.25 for i in range(0,n+1)] y = [math.sqrt(t[i]) for i in range(0,n+1)] m = 37 xlist = [i/(m-1)*2.25 for i in range(0,m+1)] fx = [math.sqrt(xlist[i]) for i in range(0,m+1)] if printDetails: print 't =',t print 'y =',y print 'xlist =',xlist print 'fx =',fx # algorithm self.cubicSpline(n,t,y,xlist,fx,m) ######################################################## ## Page 365, Computer Problem 4 ######################################################## def problem365_4(self): """ Solves computer problem 4 on page 365 """ print '\nPage 365, Computer Problem 4' # Setup Problem n = 10 nMinus = n - 1 t = [i/nMinus*2.25 for i in range(0,n+1)] y = [math.sqrt(t[i]) for i in range(0,n+1)] m = 37 xlist = [i/(m-1)*2.25 for i in range(0,m+1)] fx = [math.sqrt(xlist[i]) for i in range(0,m+1)] if printDetails: print 't =',t print 'y =',y print 'xlist =',xlist print 'fx =',fx # algorithm self.cubicSpline(n,t,y,xlist,fx,m) ######################################################## ## PQ factorization ######################################################## def testPQ(self,n,a): """ Testing PQ decomposition """ print '\nTesting PQ factorization algorithm' p,q = self.pqdecomposition(n,a) return p,q def pqdecomposition(self,n,a): p = [[0 for j in range(0,n)] for i in range(0,n)] q = [[0 for j in range(0,n)] for i in range(0,n)] for k in range(0,n): # 1's in the Q matrix - diagonal for j in range(0,n): if k + j == n-1: q[k][j] = 1 # P matrix first for j in range(0,k+1): total = sum([p[k][n-s-1]*q[n-s-1][j] for s in range(0,k+1)]) p[k][n-1-j] = a[k][j] - total if printDetails: print 'SET p[',k,'][',n-1-j,'] =',p[k][n-1-j] # Q matrix second for j in range(n,k+1,-1): total = sum([p[k][n-s-1]*q[n-s-1][j-1] for s in range(0,k+1)]) q[n-k-1][j-1] = (a[k][j-1] - total) / p[k][n-k-1] if printDetails: print 'SET q[',n-k-1,'][',j-1,'] =',q[n-k-1][j-1] print 'a =',a,'\np =',p,'\nq =',q return p,q def solvePQxb(self,p,q,b): """ Return x in the equation PQx = b """ n = len(b) # first solve Pz = b z = self.solveAxb(p,b) # second solve Qx = z x = self.solveAxb(q,z) return x def solveAxb(self,a,b): """ Return x in the equation Ax = b """ n = len(b) x = [0 for i in range(n)] for i in range(0,n): total = sum([a[i][j]*x[j] for j in range(n)]) x[n-i-1] = (b[i] - total) / a[i][n-i-1] if printDetails: print 'Solving Ax = b for x' print 'A =',a print 'b =',b print 'x =',x return x performTests = True performProblems = True printDetails = False final = final() final.printHeader() if performTests: final.testFunctions() if performProblems: final.problem93_14() final.problem245_1() final.problem365_4()
true
b8a2bcec279d315338dc2692ead7f0135d4cb7f9
Python
BrachystochroneSD/machine_learning
/session1/a_star.py
UTF-8
6,637
3.640625
4
[]
no_license
# Based on the wiki page and pseudocode : https://en.wikipedia.org/wiki/A*_search_algorithm import matplotlib as mpl from matplotlib import pyplot import numpy as np class Node: # initialise an object NODE characterized by : # pos : position in the grid # statut : state, opened, blocked... (to know which color in the graph) # f : The f score of the node (set to infinity) check the wiki page # g : The g score of the node (also set to infinity) check the wiki page for the formulae # neighbor : the neighbors of that nodes def __init__(self,pos_): self.pos=pos_ self.statut='open' self.f=float('inf') self.g=float('inf') self.neighbors=[] def check_and_append(self,nb): # check if a nieghbor is open and append is so if nb.statut is 'open': self.neighbors.append(nb) def dist_between(node1,node2): # distance between 2 nodes, catesian way biatch x=abs(node1.pos[0]-node2.pos[0]) y=abs(node1.pos[1]-node2.pos[1]) return np.sqrt(pow(x,2)+pow(y,2)) class Grid: # Grid object composed of # grid : a matrix of integer (to show the color) # nodegrid :a matrix of node objects def __init__(self,_width,_height): self.width=_width self.height=_height self.grid=np.random.randint(1,size=(_width,_height)) # create a 2-D array of 0 self.nodegrid=[] print('New Grid created') def addobstacle(self,wh,pos): # input : wh : tuple of width and height that determine the block # pos : position of the block # add that block on the position of the main grid addgrid = np.random.randint(1,2,size=(wh[0],wh[1])) for i in range(len(addgrid)): for j in range(len(addgrid[i])): self.grid[i+pos[0]][j+pos[1]]=(self.grid[i+pos[0]][j+pos[1]]+addgrid[i][j])%2 print('Obstacle added') def cell_to_node(self): # Convert the grid on integer into a grid of node objects. # and set the status of the nodes for i in range(self.width): templist=[] for j in range(self.height): n=Node((i,j)) if self.grid[i][j]==1: n.statut='closed' templist.append(n) self.nodegrid.append(templist) print('Cells converted to nodes') def node_to_cell(self): # convert grid of nodes into grid of integer, to be "processable" # by pyplot that set each int value into a defined color print('Converting nodes to cell to show that beauty...') for liste in self.nodegrid: for node in liste: pos=node.pos if node.statut=='open': self.grid[pos[0]][pos[1]]=0 elif node.statut=='closed': self.grid[pos[0]][pos[1]]=1 elif node.statut=='checked': self.grid[pos[0]][pos[1]]=2 else: self.grid[pos[0]][pos[1]]=3 def set_neighbors(self): # link each nodes of a grid with is neighbor. # But only in the neighbor is 'opened' for i in range(self.width): for j in range(self.height): current=self.nodegrid[i][j] if not i == 0: current.check_and_append(self.nodegrid[i-1][j]) if not j == 0: current.check_and_append(self.nodegrid[i-1][j-1]) if not j == self.height-1: current.check_and_append(self.nodegrid[i-1][j+1]) if not i == self.width-1: current.check_and_append(self.nodegrid[i+1][j]) if not j == 0: current.check_and_append(self.nodegrid[i+1][j-1]) if not j == self.height-1: current.check_and_append(self.nodegrid[i+1][j+1]) if not j == 0: current.check_and_append(self.nodegrid[i][j-1]) if not j == self.height-1: current.check_and_append(self.nodegrid[i][j+1]) print('Neighbors of each nodes are set') def lowestfof(liste): # Return the node that have the lowest f score of an array res=None winner_score=float('inf') for node in liste: if node.f < winner_score: winner_score=node.f res=node return res def path_finder(node,cFrom): # Check which node come from and then reconstruct # the path by set the color of each nodes of that path in green while node in cFrom.keys(): node.statut='colored' node=cFrom[node] def A_Star(start,goal): # The A* algorythm. Check the pseudo code in the wiki page print('Finding path ...') cameFrom={} closedSet=[] openSet=[] start.g=0 start.f=dist_between(start,goal) openSet.append(start) while len(openSet)>0: current = lowestfof(openSet) if current == goal: path_finder(current,cameFrom) break openSet.remove(current) closedSet.append(current) for neighbor in current.neighbors: neighbor.statut='checked' if neighbor in closedSet: continue test_gscore = current.g + dist_between(current,neighbor) if neighbor not in openSet: openSet.append(neighbor) elif test_gscore >= neighbor.g: continue cameFrom[neighbor]=current neighbor.g=test_gscore neighbor.f=neighbor.g+dist_between(neighbor,goal) def show_graph(grid): # set pyplot and then show cmap = mpl.colors.ListedColormap(['white','black','red','green']) bounds=[0,0.5,1.5,2.5,3] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) img = pyplot.imshow(grid,interpolation='nearest', cmap = cmap,norm=norm) pyplot.xticks([]), pyplot.yticks([]) pyplot.show() # Create a grid and add obstacle into it grid=Grid(100,100) grid.addobstacle((10,30),(48,48)) grid.addobstacle((10,80),(15,0)) grid.addobstacle((10,80),(50,20)) grid.addobstacle((70,70),(20,20)) grid.addobstacle((50,50),(40,40)) grid.addobstacle((40,40),(50,50)) # Process the grid to become path findable grid.cell_to_node() grid.set_neighbors() # A* search algorythm A_Star(grid.nodegrid[0][0],grid.nodegrid[-1][-1]) # Convert the nodes to cells to be readable for pyplot then show grid.node_to_cell() show_graph(grid.grid)
true
4fb9fefea278dc4dd50c91d6e5e7f333622d8fbd
Python
akapkotel/introduction_to_algorithms
/sorting/sorting_algorithms.py
UTF-8
1,915
3.984375
4
[]
no_license
#!/usr/bin/env python from typing import List def insertion_sort(list_to_sort: List) -> List: list_to_sort = [e for e in list_to_sort] # to avoid sorting in place, comment this to change original list for j in range(1, len(list_to_sort)): sorted_element = list_to_sort[j] # print('sorted element:', sorted_element) i = j - 1 while i >= 0 and list_to_sort[i] > sorted_element: list_to_sort[i + 1] = list_to_sort[i] i -= 1 list_to_sort[i + 1] = sorted_element # print('list after insertion:', list_to_sort) return list_to_sort def reverse_sort(list_to_sort: List) -> List: """ The same as insertion_sort, but order is reversed. :param list_to_sort: List :return: List """ if len(list_to_sort) == 1: return list_to_sort list_to_sort = [e for e in list_to_sort] # to avoid sorting in place, comment this to change original list for j in range(len(list_to_sort) - 2, -1, -1): sorted_element = list_to_sort[j] # print('sorted element:', sorted_element) i = j + 1 while i < len(list_to_sort) and list_to_sort[i] > sorted_element: list_to_sort[i - 1] = list_to_sort[i] i += 1 list_to_sort[i - 1] = sorted_element # print('list after insertion:', list_to_sort) return list_to_sort def search_in_list(a_list: List, element: int) -> int: for i, x in enumerate(a_list): if x == element: return i def selection_sort(list_to_sort: List) -> List: sorted_list = [] # print(list_to_sort, sorted_list) while list_to_sort: smallest = 0 for i, elem in enumerate(list_to_sort): if elem < list_to_sort[smallest]: smallest = i sorted_list.append(list_to_sort.pop(smallest)) # print(list_to_sort, sorted_list) return sorted_list
true
7e8b43271c259460765d9b8496d61eec55702a15
Python
pratul2789/CS6360-database
/00-test-packing.py
UTF-8
524
2.515625
3
[]
no_license
from file.valuetype import * from binascii import hexlify import datetime dt = DateTime(0) ddt = Date(100000000000000) tm = Time(23, 1, 2, 103) tm2 = Time(4359084) yr = Year(2016) print(dt, ddt, tm, tm2) data = vpack([0, 1, 2, 3, 6, 10, 11, 9, 9, 8, 0xc], NULLVAL, 23, 267, 234524, 4.5654, dt, ddt, tm, tm2, yr, b'hello world!!!!') print('** DATA **************') for i in range(0, len(data), 8): print('%04x: %s' % (i, str(hexlify(data[i:i+8]), 'utf8'))) print('**********************') print(vunpack(data))
true
110b5a808833c6b315f851bc1c3ed3b00928791b
Python
ArturTask/Mathan6
/drawAnswer.py
UTF-8
518
3.28125
3
[]
no_license
import matplotlib.pyplot as plt def drawPls(answer,title): fig = plt.figure() axes = fig.add_subplot(111) plt.grid() x = [] y = [] for i in range(len(answer)): x.append(answer[i][1]) y.append(answer[i][2]) axes.plot(x,y,c="black",label="полученное решение") y = [] for i in range(len(answer)): y.append(answer[i][4]) axes.plot(x, y, c="red", label="точное решение") axes.legend() plt.title(title) plt.show()
true
df61a3fb43977f034dabad8eaa804ddd981f02dc
Python
gijswobben/pydow-2
/pydow/store/tiny.py
UTF-8
702
2.90625
3
[ "MIT" ]
permissive
from tinydb import TinyDB, Query class Store(object): def __init__(self: object, *args: list, **kwargs: dict) -> None: self._db = TinyDB("database.json") def getState(self: object, key: str, default=None, session_id: str = None, identifier: str = None): """ """ pass def setState(self: object, key: str, value, session_id: str = None, identifier: str = None) -> None: """ """ if session_id is not None: key = f"{session_id}_{key}" if identifier is not None: key = f"{identifier}_{key}" self._db.insert({key: value}) if __name__ == '__main__': store = Store() print(store._db)
true
5f8bc8bebfa3673348b3883ef5051b52683e280b
Python
acc-cosc-1336/cosc-1336-fall-2017-mmontemayor1
/frames/AboutFrame.py
UTF-8
266
3.34375
3
[ "MIT" ]
permissive
from tkinter import Frame, Label class AboutFrame(Frame): """Frame container for About screen""" def __init__(self, parent): Frame.__init__(self, parent) Label(self, text="About Frame").grid(row=0, column=0, sticky="w")
true
68c437b3dbcf305a82baebe00c4155887180e329
Python
kashewnuts/python-school-ja
/src/downloader.py
UTF-8
1,353
2.65625
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- """%prog url [, url [, ... ]] Download contents from given URL list. """ import logging import os import urllib from urlparse import urlparse # Check the document about version differences. # http://docs.python.org/library/urlparse.html#urlparse.parse_qs # New in version 2.6: Copied from the cgi module. try: from urlparse import parse_qs except ImportError: from cgi import parse_qs from pyschool.cmdline import parse_args def download(url): o = urlparse(url) # Check the document for return value attributes. # http://docs.python.org/library/urlparse.html#urlparse.urlparse # "index 2" means "path" attribute, Hierarchical path. path = o[2] fname = os.path.basename(path) if os.path.exists(fname): logging.warn("%s already exists, overwrite it.", fname) logging.info("Download: %s -> %s", url, fname) try: r = urllib.urlretrieve(url, fname) except IOError, e: logging.error(e) def main(): opts, args = parse_args() if not args: # Dirty code. This replacement should be in `parse_args()`. raise SystemExit(__doc__.replace("%prog", os.path.basename(__file__))) for url in args: download(url) if __name__ == '__main__': main() # vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
true
f3636acbbaa2781258954d99e9b762556fbd747a
Python
amanshuraikwar/pr-assignment-2
/code.py
UTF-8
14,489
2.671875
3
[]
no_license
import funcs import sys import math from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import random THRESHOLD=0.001 MAXITERATIONS=50 EMMAXITERATIONS=50 EMTHRESHOLD=0.1 TRAININGDATALIMIT=0.75 CURRENTNOOFCLUSTERS=2 def belongsToClusture(dataPoint,means): distances=[] for i in range(len(means)): distances.append(math.sqrt(math.pow(dataPoint[0][0]-means[i][0][0],2)+math.pow(dataPoint[1][0]-means[i][1][0],2))) return distances.index(min(distances)) def emCheckConvergence(oldl,newl,interationNo): for clsi in range(len(oldl)): if(math.fabs(oldl[clsi]-newl[clsi])<EMTHRESHOLD): print "" print "NOTE:DIFFERENCE CROSSED THRESHOLD FOR CONVERGENCE -- EM method" return True if(interationNo>EMMAXITERATIONS): print "" print "NOTE:MAX ITERATIONS REACHED FOR CONVERGENCE -- EM method" return True return False #to update def checkConvergence(old,new,interationNo): if(math.sqrt(math.pow(new[0][0][0]-old[0][0][0],2)+math.pow(new[0][1][0]-old[0][1][0],2))<THRESHOLD and math.sqrt(math.pow(new[1][0][0]-old[1][0][0],2)+math.pow(new[1][1][0]-old[1][1][0],2))<THRESHOLD): print "NOTE:DIFFERENCE CROSSED THRESHOLD FOR CONVERGENCE" return True if(interationNo>MAXITERATIONS): print "NOTE:MAX ITERATIONS REACHED FOR CONVERGENCE" return True return False #problem of two means assigning same value def kMeansClusture(k,data,minx,maxx,miny,maxy,datainclusters): #holding means curmeans=[] #holding data of different clusters #datainclusters=[] initialMeanIndex=[] i=0 while(i<k): randindex=random.randrange(int(len(data)*TRAININGDATALIMIT)) #checking for mean index repetitions try: initialMeanIndex.index(randindex) continue except: curmeans.append([[data[randindex][0][0]],[data[randindex][1][0]]]) initialMeanIndex.append(randindex) datainclusters.append([]) i+=1 interationNo=0 while(True): interationNo+=1 for i in range(k): datainclusters[i]=[] for i in range(int(len(data)*TRAININGDATALIMIT)): datainclusters[belongsToClusture(data[i],curmeans)].append(data[i]) newmeans=[] for i in range(len(datainclusters)): newmeans.append([[0],[0]]) for j in range(0,len(datainclusters[i])): newmeans[i]=funcs.addM([[datainclusters[i][j][0][0]],[datainclusters[i][j][1][0]]],newmeans[i]); #no data point classified in cluster -- hopefully never executes if(len(datainclusters[i])==0): print "error iteration no :",interationNo print "error cluster index :",i print "error cluster data array :",datainclusters[i] print "no data point in a clusture" print "TERMINATING" exit() newmeans[i]=funcs.divByConstM(newmeans[i],len(datainclusters[i])) if(checkConvergence(curmeans,newmeans,interationNo)): return newmeans[:] curmeans=newmeans[:] def calculateL(data,mean,covariance,piik): tempL=[] for clsi in range(len(data)): tempL.append(0) for datai in range(len(data[clsi])): tempSum=0.0 for clusi in range(len(mean[clsi])): temp=funcs.subM(data[clsi][datai],mean[clsi][clusi]) temp=funcs.mulM(funcs.mulM(funcs.transpose(temp),funcs.inverse(covariance[clsi][clusi])),temp) N=funcs.det(funcs.inverse(covariance[clsi][clusi]))*math.exp(-0.5*temp[0][0])/math.sqrt(2*3.14) tempSum+=piik[clsi][clusi]*N tempSum=math.log(tempSum) tempL[clsi]+=tempSum return tempL def NormalDist(data,mean,covariance): temp=funcs.subM(data,mean) temp=funcs.mulM(funcs.mulM(funcs.transpose(temp),funcs.inverse(covariance)),temp) N=math.exp(-0.5*temp[0][0])/(math.sqrt(2*3.14)*math.sqrt(funcs.det(covariance))) return N def confusionM(data,mean,covariance,pik): clsno=len(data) returnM=[] p=[] gx=[] for clsi in range(clsno): gx.append(0) p.append(0) for clsi in range(clsno): dtno=len(data[clsi]) for cli in range(clsno): p[cli]=0 for datai in range (int(math.floor(0.75*dtno)),dtno): for cli in range(clsno): temp=0.0 for clusi in range(len(mean[cli])): temp+=pik[cli][clusi]*NormalDist(data[clsi][datai],mean[cli][clusi],covariance[cli][clusi]) totalN=0 for xx in range(clsno): totalN+=len(data[xx]) temp*=float(len(data[cli]))/float(totalN) #hopefully this does not execute if(temp>1): temp=0.999999 # print pik[cli] # print "error probability :",temp # print "probability more that 1 error" # print "TERMINATING" # exit() temp=math.log(temp) gx[cli]=temp mgx=gx.index(max(gx)) p[mgx]+=1 returnM.append(p[:]) return returnM def accuracy(confmatrix,ntest): dmatrix=len(confmatrix) accu=0.0 for i in range (dmatrix): accu=accu+confmatrix[i][i] accu=accu/ntest return accu def per_accuracy(confmatrix,ntest): p_accu=accuracy(confmatrix,ntest) return p_accu*100 def precision(confmatrix): pre=[] dmatrix=len(confmatrix) for i in range (dmatrix): tp=0.0 for j in range (dmatrix): tp=tp+confmatrix[j][i] tc=confmatrix[i][i] if (tp==0): pre.append(-1) else: pre.append(tc/tp) return pre def mean_precision(confmatrix): pre=precision(confmatrix) temp=0.0 lenn=len(pre) for i in range(lenn): if(pre[i]==-1): lenn-=1 else: temp=temp+pre[i] return (temp/lenn) def recall(confmatrix): rec=[] dmatrix=len(confmatrix) for i in range(dmatrix): n=0.0 for j in range(dmatrix): n=n+confmatrix[i][j] tc=confmatrix[i][i] rec.append(tc/n) return rec def mean_recall(confmatrix): rec=recall(confmatrix) temp=0.0 for i in range (len(rec)): temp=temp+rec[i] return (temp/(len(rec))) def f_measure(confmatrix): f=[] pre=precision(confmatrix) rec=recall(confmatrix) temp=0.0 for i in range (len(confmatrix)): if (pre[i]==-1): f.append(-1) else: temp=pre[i]*rec[i]*2/(pre[i]+rec[i]) f.append(temp) return f def mean_f_measure(confmatrix): f=f_measure(confmatrix) temp=0.0 lenn=len(f) for i in range (lenn): if(f[i]==-1): lenn-=1 else: temp=temp+f[i] return (temp/(lenn)) #universal matrices data=[] mean=[] datainclusters=[] covariance=[] pik=[] oldL=[] newL=[] minx=0 miny=0 maxx=0 maxy=0 #reading files and storing data in data[] DATAVALUESEPARATOR=" " nooffiles=len(sys.argv)-2 PRINTSTEPSFLAG=int(sys.argv[len(sys.argv)-2]) CURRENTNOOFCLUSTERS=int(sys.argv[len(sys.argv)-1]) #for each file for filei in range(1,nooffiles): with open(sys.argv[filei]) as curFile: data.append([]) mean.append([]) datainclusters.append([]) covariance.append([]) pik.append([]) newL.append(0.0) oldL.append(0.0) content = curFile.read().splitlines() lineno=len(content); #for each line for linei in range(lineno): value=content[linei].split(DATAVALUESEPARATOR); data[filei-1].append([]) #for each data value in data point for valuei in range(len(value)): try: data[filei-1][linei].append([float(value[valuei])]) except ValueError: continue #endoffor #checking for ranges of data if(float(value[0])<minx): minx=float(value[0]) if(float(value[0])>maxx): maxx=float(value[0]) if(float(value[1])<miny): miny=float(value[1]) if(float(value[1])>maxy): maxy=float(value[1]) #endoffor #endofwith #endoffor #no of classes clsno=len(data) totaltestdatano=0 for i in range(clsno): mean[i]=kMeansClusture(CURRENTNOOFCLUSTERS,data[i],minx,maxx,miny,maxy,datainclusters[i]) totaltestdatano+=0.25*len(data[i]) #print mean for clsi in range(clsno): for clusi in range(CURRENTNOOFCLUSTERS): covariance[clsi].append([]) covariance[clsi][clusi]=[[0,0],[0,0]] for datai in range(len(datainclusters[clsi][clusi])): covariance[clsi][clusi]=funcs.addM(funcs.mulM(funcs.subM(datainclusters[clsi][clusi][datai],mean[clsi][clusi]),funcs.transpose(funcs.subM(datainclusters[clsi][clusi][datai],mean[clsi][clusi]))),covariance[clsi][clusi]) covariance[clsi][clusi]=funcs.divByConstM(covariance[clsi][clusi],len(datainclusters[clsi][clusi])) pik[clsi].append([]) pik[clsi][clusi]=float(len(datainclusters[clsi][clusi]))/float(len(data[clsi])) print "PIK CALCULATED" newL=calculateL(data,mean,covariance,pik) print "L CALCULATED" interationNo=0 clusterColors=[["#ffcdd2","#e57373","#f44336","#b71c1c","#f06292","#e91e63","#c2185b","#880e4f"],["#b2dfdb","#4db6ac","#009688","#00796b","#004d40","#a5d6a7","#66bb6a","#1b5e20"],["#303f9f","#1976d2","#0288d1","#0097a7","#64b5f6"]] while(True): interationNo+=1 bs='\b'*1000 print bs, print "\bITERATION :",interationNo, #E STEP oldL=newL[:] gammak=[] for clsi in range(clsno): gammak.append([]) for datai in range(int(len(data[clsi])*TRAININGDATALIMIT)): gammak[clsi].append([]) totalgamma=0; for clusi in range(CURRENTNOOFCLUSTERS): gammak[clsi][datai].append([]) temp=funcs.subM(data[clsi][datai],mean[clsi][clusi]) temp=funcs.mulM(funcs.mulM(funcs.transpose(temp),funcs.inverse(covariance[clsi][clusi])),temp) gammak[clsi][datai][clusi]=[funcs.det(funcs.inverse(covariance[clsi][clusi]))*math.exp(-0.5*temp[0][0])/math.sqrt(2*3.14)] gammak[clsi][datai][clusi][0]*=pik[clsi][clusi] totalgamma+=gammak[clsi][datai][clusi][0] if(len(gammak[clsi][datai])!=CURRENTNOOFCLUSTERS): print "error" gammak[clsi][datai]=funcs.divByConstM(gammak[clsi][datai],totalgamma) #M STEP NK=[] for clsi in range(clsno): NK.append([]) for clusi in range(CURRENTNOOFCLUSTERS): NK[clsi].append([]) NK[clsi][clusi]=0 for datai in range(int(len(data[clsi])*TRAININGDATALIMIT)): NK[clsi][clusi]+=gammak[clsi][datai][clusi][0] for clsi in range(clsno): for clusi in range(CURRENTNOOFCLUSTERS): pik[clsi][clusi]=NK[clsi][clusi]/len(data[clsi]) mean[clsi][clusi]=[[0],[0]] for datai in range(int(len(data[clsi])*TRAININGDATALIMIT)): mean[clsi][clusi]=funcs.addM(mean[clsi][clusi],funcs.mulByConstM(data[clsi][datai],gammak[clsi][datai][clusi][0])) mean[clsi][clusi]=funcs.divByConstM(mean[clsi][clusi],NK[clsi][clusi]) covariance[clsi][clusi]=[[0,0],[0,0]] for datai in range(int(len(data[clsi])*TRAININGDATALIMIT)): covariance[clsi][clusi]=funcs.addM(funcs.mulByConstM(funcs.mulM(funcs.subM(data[clsi][datai],mean[clsi][clusi]),funcs.transpose(funcs.subM(data[clsi][datai],mean[clsi][clusi]))),gammak[clsi][datai][clusi][0]),covariance[clsi][clusi]) covariance[clsi][clusi]=funcs.divByConstM(covariance[clsi][clusi],NK[clsi][clusi]) newL=calculateL(data,mean,covariance,pik) # print newL if(emCheckConvergence(oldL,newL,interationNo)): break datainclusters=[] if(PRINTSTEPSFLAG==1): fig=plt.figure() subplot=fig.add_subplot(111) subplot.set_title(str(interationNo)) for clsi in range(clsno): datainclusters.append([]) for clusi in range(CURRENTNOOFCLUSTERS): datainclusters[clsi].append([]) for datai in range(len(data[clsi])): clas=funcs.classify(data[clsi][datai],mean[clsi],covariance[clsi],pik[clsi]) subplot.plot(data[clsi][datai][0][0],data[clsi][datai][1][0],color=clusterColors[clsi][clas],marker="o") datainclusters[clsi][clas].append(data[clsi][datai]) plt.axis([minx,maxx,miny,maxy]) fig.savefig(str(interationNo)+".png") confM=confusionM(data,mean,covariance,pik) acc=accuracy(confM,totaltestdatano) prec=precision(confM) meprec=mean_precision(confM) rec=recall(confM) merec=mean_recall(confM) fmes=f_measure(confM) mefmes=mean_f_measure(confM) print confM print "accuracy : ",str(acc) print "precision : ",str(prec) print "mean precision : ",str(meprec) print "recall : ",str(rec) print "mean recall : ",str(merec) print "f measure : ",str(fmes) print "mean fmeasure",str(mefmes) print "THRESHOLD :",THRESHOLD print "MAXITERATIONS :",MAXITERATIONS print "EMMAXITERATIONS :",EMMAXITERATIONS print "EMTHRESHOLD :",EMTHRESHOLD print "TRAININGDATALIMIT :",TRAININGDATALIMIT print "CURRENTNOOFCLUSTERS :",CURRENTNOOFCLUSTERS fig=plt.figure() subplot=fig.add_subplot(111) color=["#F49292","#A9F5AF","#A1A4FF","#F3F3AF"] color1=["#E21818","#17E81F","#252BDF","#D2C81D"] xinc=(maxx-minx)/50 yinc=(maxy-miny)/50 #abcd gx=[] for clsi in range(clsno): gx.append(0) vecx=[] vecy=[] vecz=[] mingx=0 maxgx=0 yi=0 y=miny while(y<maxy): vecy.append(y) vecz.append([]) bs='\b'*1000 print bs, print "\bPLOTTING GRAPH :",round((y-miny)*100/(maxy-miny),2),"%", x=minx while(x<maxx): for clsi in range(clsno): temp=0.0 for clusi in range(len(mean[clsi])): temp+=pik[clsi][clusi]*NormalDist([[x],[y]],mean[clsi][clusi],covariance[clsi][clusi]) totalN=0 for xx in range(clsno): totalN+=len(data[xx]) temp*=float(len(data[clsi]))/float(totalN) #hopefully this does not execute if(temp>1): temp=0.999999 # pik[clsi] # print "error probability :",temp # print "probability more that 1 error" # print "TERMINATING" # exit() temp=math.log(temp) gx[clsi]=temp mgx=max(gx) vecz[yi].append(mgx) if(mingx>mgx): mingx=mgx if(maxgx<mgx): maxgx=mgx if(y==miny): vecx.append(x) if(x==minx): mingx=mgx maxgx=mingx clas=gx.index(mgx) subplot.plot(x,y,color=color[clas],marker="o",markeredgecolor=color[clas]) x+=xinc y+=yinc yi+=1 print "" plt.axis([minx,maxx,miny,maxy]) contourFig=plt.figure() contourSubPlot=contourFig.add_subplot(111) #CS = contourSubPlot.contour(vecx,vecy,vecz,zorder=2,level=funcs.generateGP(mingx,maxgx)) CS = contourSubPlot.contour(vecx,vecy,vecz,zorder=2,level=funcs.generateGP(mingx,maxgx)) contourSubPlot.clabel(CS, inline=1, fontsize=10) for clsi in range(clsno): for datai in range(int(TRAININGDATALIMIT*len(data[clsi]))): contourSubPlot.plot(data[clsi][datai][0][0],data[clsi][datai][1][0],color=color[clsi],marker="o",markeredgecolor=color[clsi],zorder=1) subplot.plot(data[clsi][datai][0][0],data[clsi][datai][1][0],color=color1[clsi],marker="o") plt.axis([minx,maxx,miny,maxy]) print "SAVING CONTOUR GRAPH" contourFig.savefig("contour-K-"+str(CURRENTNOOFCLUSTERS)+".png") print "SAVING BOUNDARIES GRAPH" fig.savefig("boundaries-K-"+str(CURRENTNOOFCLUSTERS)+".png") fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(vecx,vecy,vecz, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False) ax.set_zlim(-1.5,maxgx) fig.colorbar(surf, shrink=0.5, aspect=5) fig.savefig("3d-1.png") fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(vecx, vecy, vecz, rstride=4, cstride=4, color='b') ax.set_zlim(-1.5,maxgx) fig.savefig("3d-2.png")
true
53ba6f1fefa410fcf5c4c63ead11dcfc5091e74f
Python
patvdheyden/CvoDeVerdieping
/LesVariabelen.py
UTF-8
1,544
3.671875
4
[]
no_license
from termcolor import colored def avg(l): return sum(l, 0.0) / len(l) print ("Oefening 4.1") lijst = [15,26,36] print ("Het gemiddelde van " + str(lijst) + " is " + str("{:.2f}".format(avg(lijst)))) # afronden print 2 dec print("") print ("Oefening 4.2") straal = 5 PI = 3.14159 oppervlakte = (straal**2)*PI print ( "De oppervlakte van een cirkel met een straal van " + str(straal) + " is " + str("{:.2f}".format(oppervlakte)) ) print("") print ("Oefening 4.3") aantal_centen = 1287 resultaat_dollar = aantal_centen // 100 rest_dollar = aantal_centen % 100 resultaat_kwartjes = rest_dollar // 25 rest_kwartjes = rest_dollar % 25 resultaat_dubbeltjes = rest_kwartjes // 10 rest_dubbeltjes = rest_kwartjes % 10 resultaat_stuivers = rest_dubbeltjes // 5 resultaat_centjes = rest_dubbeltjes % 5 print ("In het bedrag " + str(aantal_centen)) print ("zitten er " + str(resultaat_dollar) +" dollars") print ("zitten er " + str(resultaat_kwartjes) + " kwartjes") print ("zitten er " + str(resultaat_dubbeltjes) + " dubbeltjes") print ("zitten er " + str(resultaat_stuivers) + " stuivers") print ("zitten er " + str(resultaat_centjes) + " centjes") print("") print ("Oefening 4.4") waarde1 = 45 waarde2 = 96 print ("waardes voor de switch", waarde1, waarde2) waarde1,waarde2 = waarde2,waarde1 print ("waardes na de switch", waarde1, waarde2) print("") print ("Oefening 4.5") fahrenheit = 50 celsius = (fahrenheit-32)/1.8 print (str(fahrenheit) +" graden fahrenheit = " +str(celsius) + " graden celsius") print (colored('test','red'))
true
9f88dd15317c38b6f3abda99e4ac61470c416a22
Python
soriapinnow/Python
/app_python/aula11.py
UTF-8
610
3.609375
4
[]
no_license
lista = [1, 10] try: arquivo = open('teste.txt', 'r') texto = arquivo.read() divisao = 10/1 numero = lista[1] #x = a except ZeroDivisionError: print('Não é possível realizar uma divisão por 0') except ArithmeticError: print('Houve um erro au realizar uma operação aritmética!') except IndexError: print ('Erro: índice inválido da lista!') except Exception as ex: print('Erro desconhecido. Erro: {}'.format(ex)) else: print('Executa quando não ocorre nenhuma exceção.') finally: print('Sempre executa!') print('Fechando arquivo') arquivo.close()
true
4f1c523d93299c39c8fad9e487e0478dd216cac1
Python
Laurox/ZealotBot
/requirements.py
UTF-8
2,994
2.640625
3
[]
no_license
import requests import util.uuid_util import leaderboard import util.converter import time from dotenv import load_dotenv import os load_dotenv() token = os.getenv('API_TOKEN') rq = requests.get("https://api.hypixel.net/guild?key=" + token + "&id=5d2e186677ce8415c3fd0074") c = 0 for member in rq.json()['guild']['members']: try: name = util.uuid_util.get_name_from_uuid(member['uuid']) profile = leaderboard.get_current_profile(member['uuid']) souls = profile['fairy_souls_collected'] farming_xp = profile['experience_skill_farming'] combat_xp = profile['experience_skill_combat'] foraging_xp = profile['experience_skill_foraging'] mining_xp = profile['experience_skill_mining'] fishing_xp = profile['experience_skill_fishing'] taming_xp = profile['experience_skill_taming'] alchemy_xp = profile['experience_skill_alchemy'] enchanting_xp = profile['experience_skill_enchanting'] total_xp = farming_xp + combat_xp + foraging_xp + mining_xp + fishing_xp + taming_xp + alchemy_xp + enchanting_xp average_xp = total_xp / 8 farming_lvl = util.converter.skill_exp_to_level(farming_xp) combat_lvl = util.converter.skill_exp_to_level(combat_xp) foraging_lvl = util.converter.skill_exp_to_level(foraging_xp) mining_lvl = util.converter.skill_exp_to_level(mining_xp) fishing_lvl = util.converter.skill_exp_to_level(fishing_xp) taming_lvl = util.converter.skill_exp_to_level(taming_xp) alchemy_lvl = util.converter.skill_exp_to_level(alchemy_xp) enchanting_lvl = util.converter.skill_exp_to_level(enchanting_xp) total_level = farming_lvl + combat_lvl + foraging_lvl + mining_lvl + fishing_xp + taming_lvl + alchemy_xp + enchanting_lvl average_lvl = total_level / 8 revenant_xp = profile['slayer_bosses']['zombie']['xp'] tarantula_xp = profile['slayer_bosses']['spider']['xp'] sven_xp = profile['slayer_bosses']['wolf']['xp'] total_slayer_xp = revenant_xp + tarantula_xp + sven_xp average_slayer_xp = total_slayer_xp / 3 revenant_lvl = util.converter.slayer_exp_to_level(revenant_xp) tarantula_lvl = util.converter.slayer_exp_to_level(tarantula_xp) sven_lvl = util.converter.slayer_exp_to_level(sven_xp) total_slayer_level = revenant_xp + tarantula_lvl + sven_lvl average_skayer_lvl = total_level / 3 # if not (souls >= 190): # print(name + " kennt TimeDeo nicht") # elif not (average_lvl >= 20.0): # print(name + " ist sehr schlecht") # elif not (total_slayer_level >= 13): # print(name + " selbst P2Go ist besser") # elif not (sven_lvl >= 6): # print(name + " wird vom Sven T1 gekillt") if not total_xp >= 20000000: print(name + " hat kack Skills") except: print(name + " ist nh bissle dumm") time.sleep(1)
true
d25689642e1f0ee1417a53314ea8e1bf1a176c54
Python
maxim5helopugin/Portfolio
/AntiBullying/src/preproc/emoji.py
UTF-8
868
3.484375
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
# -*- coding: utf-8 -*- """Module that contains utilities useful for dealing with emojis in text.""" KNOWN_EMOJIS = { ':)': 'smile', ':-)': 'smile', ':(': 'sad', ':-(': 'sad', '&lt;3': 'heart', '>:(': 'angry', '>:-(': 'angry', ':\'(': 'cry', } def replace_emojis(orig_text): """ Replace known emoji character combinations with words. Doing the replacement so that in later pre-processing stages, emojis are not suppressed as punctuation. note:: The transformation is **not** done in place. Input remains intact. :param orig_text: Original line of text to transform. :type orig_text: str :return: New line of text with transformation done. :rtype: str """ result = '{:s}'.format(orig_text) for emoji, subst in KNOWN_EMOJIS.items(): result = result.replace(emoji, subst) return result # vim: set ts=2 sw=2 expandtab:
true
58ab0735423d344d6a46b7181dc3e468520af777
Python
XihangJ/leetcode
/BFS/752_Open the Lock.py
UTF-8
1,720
3.625
4
[]
no_license
''' You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. ''' class Solution: #method 1. BFS. def openLock(self, deadends: List[str], target: str) -> int: if target == '0000': return 0 if '0000' in deadends: return -1 deadends = set(deadends) directions = [1, -1] visited = set(['0000']) queue = collections.deque(['0000']) count = 0 while queue: count += 1 for _ in range(len(queue)): curr = queue.popleft() for i in range(4): for direction in directions: tmp_list = [slot for slot in curr] tmp_list[i] = str((int(tmp_list[i]) + direction) % 10) end = ''.join(tmp_list) if end == target: return count elif end not in visited and end not in deadends: visited.add(end) queue.append(end) return -1
true
46717a02784fd4893462976ce74b4257e11fa949
Python
aliakatas/SKIRON_analysis_pack
/task_reader.py
UTF-8
14,526
2.65625
3
[ "MIT" ]
permissive
""" Module to define the Task class responsible for parsing the input of users. It performs sanity checks on what is asked from the application. """ import os import ntpath from dateutil.parser import parse from support_data import FILE, NODATA, VEC, SCAL, HISTO, SCATT, ROSE, HEAT, STATS, SERIES, SAVE, FTYPE, METEO, DPI, FIGSIZE, DATETIME, TIMEFROM, TIMETO, POS_ANS, FTYPES_ALLOWED from support_data import KEYS_bool, KEYS_mult_num, KEYS_mult_str, KEYS_num, KEYS_str, NOKEY, NOKEY_val def path_leaf(path): """ Separate the filename and the full path. """ head, tail = ntpath.split(path) return head, tail or ntpath.basename(head) def key_in_keys(key): """ Just a nice wrapper to check if key is in some the existing keys and get it back... """ if key in KEYS_bool: return KEYS_bool if key in KEYS_mult_num: return KEYS_mult_num if key in KEYS_mult_str: return KEYS_mult_str if key in KEYS_num: return KEYS_num if key in KEYS_str: return KEYS_str return {} def get_entry(line): """ Read an entry from the conf file. """ if not line.strip(): print('Empty line, ignoring...') return NOKEY, NOKEY_val # Parse field name from values words = line.split('=') if len(words) < 2: # Just mentioning the field or some other weird setup if len(words) == 1: key = words[0].strip().lower() my_key_dict = key_in_keys(key) if my_key_dict: print('Field {} has no value, will default to {}'.format(key, my_key_dict[key])) return key, my_key_dict[key] else: print('Field {} is not recognised and will be ignored.'.format(key)) return NOKEY, NOKEY_val else: print('Empty line, ignoring...') return NOKEY, NOKEY_val else: if len(words) > 2: print('Bad field combination: {}'.format(line.strip())) print('Line will be ignored...') return NOKEY, NOKEY_val key = words[0].strip().lower() my_key_dict = key_in_keys(key) if not my_key_dict: print('Field {} is not recognised and will be ignored.'.format(key)) return NOKEY, NOKEY_val values = words[1].strip() if ',' in values: mult_vals = values.split(',') else: mult_vals = values.split() mvals = [] for val in mult_vals: mvals.append(val.strip()) # if key == VEC and len(mult_vals) != 2: # print('Bad field combination: {}'.format(line.strip())) # print('Line will be ignored...') # return NOKEY, NOKEY_val # if key == SCAL and len(mult_vals) != 1: # print('Bad field combination: {}'.format(line.strip())) # print('Line will be ignored...') # return NOKEY, NOKEY_val return key, tuple(mvals) def get_headers(fname): """ Get the headers in the csv file. """ headers = [] with open(fname, 'r') as f: line = f.readline() words = line.split(',') for word in words: headers.append(word.strip().lower()) return headers ############################################################ class Task: def __init__(self, filename = None): """ Constructor - aborting if nothing is entered (ie no demo mode). """ self.ok = False print('') print('------> Entering Task creator...') if not filename: print('Error: no filename provided!') print('Please retry...') print('Exiting task. <------ ') return # Get the full path and name of the file in one string fullname = os.path.abspath(filename) print('For task: {}'.format(fullname)) # Check if the conf file exists if not os.path.exists(fullname): print('Error: The conf file does not exist!') print('Please retry...') print('Exiting task. <------') return # Store for later use self.fullname = fullname self.fpath, self.fname = path_leaf(fullname) # Initialise options dictionary self.init_opt_dict() # Read the conf file and extract info self.conf_reader() # Validate the input from the user ok = self.validate_conf() if not ok: print('Error: Some of the contents of ') print(' {}'.format(self.fullname)) print(' are not valid!') print('Please retry...') print('Exiting task. <------') return self.ok = True print('Task created OK. <------') return def init_opt_dict(self): """ Get the keys and default values to proceed with the task. """ self.opt_dict = {} for key in KEYS_bool.keys(): self.opt_dict[key] = KEYS_bool[key] for key in KEYS_mult_num.keys(): self.opt_dict[key] = KEYS_mult_num[key] for key in KEYS_mult_str.keys(): self.opt_dict[key] = KEYS_mult_str[key] for key in KEYS_num.keys(): self.opt_dict[key] = KEYS_num[key] for key in KEYS_str.keys(): self.opt_dict[key] = KEYS_str[key] return def dump(self): """ Just for debugging. Printing the dictionary. """ print('') print('--------------------------------------------') print(' Task Summary ') print('--------------------------------------------') print('Fullpath to conf file: {}'.format(self.fullname)) print('Path of conf file: {}'.format(self.fpath)) print('Name of conf file: {}'.format(self.fname)) print('*********************') print('(Key : Value) ') for kk in self.opt_dict.keys(): print('{:<9s} : {}'.format(kk, self.opt_dict[kk])) print('============================================') print('') return def set_value(self, key, val): """ Set the value to the field in an appropriate way. """ if isinstance(val, tuple): if key in KEYS_bool: uopt = val[0].lower() if uopt in POS_ANS: self.opt_dict[key] = True else: self.opt_dict[key] = False elif key in KEYS_str: self.opt_dict[key] = val[0] elif key in KEYS_num: try: self.opt_dict[key] = float(val[0]) except: print('Using default {}:{}'.format(key, KEYS_num[key])) self.opt_dict[key] = KEYS_num[key] elif key in KEYS_mult_str: self.opt_dict[key].append(val[0:]) elif key in KEYS_mult_num: temp_list = [] for item in val: try: temp_list.append(float(item)) except: print('Could not add {} to {}'.format(item, key)) self.opt_dict[key] = tuple(temp_list) elif isinstance(val, int) or isinstance(val, float): if key in KEYS_num: self.opt_dict[key] = val else: print('Could not associate {} with numeric fields...'.format(key)) elif isinstance(val, list): print('Unable to handle lists in task_reader.set_values()...') else: print('No method to handle {}:{}'.format(key, val)) return def conf_reader(self): """ Read the contents of the conf file. """ with open(self.fullname, 'r') as f: lines = f.readlines() for line in lines: key, vals = get_entry(line) if key != NOKEY: self.set_value(key, vals) return def validate_conf(self): """ Responsible for validating the contents of the conf file. """ if not self.opt_dict[FILE]: print('SKIRON csv filename is missing!') return False # Adjust the full name of the csv file temp_path = os.path.join(self.fpath, self.opt_dict[FILE]) if not os.path.exists(temp_path): print('SKIRON csv file does not exist: {}'.format(temp_path)) return False self.opt_dict[FILE] = temp_path # # Check for nodata value input and default to something... # if not self.opt_dict[NODATA]: # print('No user input for NODATA value.') # print('Default to {}'.format(KEYS_mult_str[NODATA])) # self.opt_dict[NODATA].append(KEYS_mult_str[NODATA]) # Get the headers of the csv headers = get_headers(self.opt_dict[FILE]) # Convert to lowercase the header input from the user # and count how many are valid. scount = 0 temp_list = self.opt_dict[SCAL] self.opt_dict[SCAL] = [] for item in temp_list: if len(item) != 1: print('Bad request for scalar field, will consider leftmost entry only from {}'.format(item)) item1 = item[0].lower() if item1 in headers: self.opt_dict[SCAL].append(item1) scount += 1 else: print('Removing {} because it is not in csv headers.'.format(item)) vcount = 0 temp_list = self.opt_dict[VEC] self.opt_dict[VEC] = [] for item in temp_list: if len(item) < 2: print('Ignoring {}'.format(item)) continue elif len(item) > 2: print('Bad request for vector field, will consider the first two different entries from {}'.format(item)) cc = 0 last = '' temp_tup = [] for subitem in item: current = subitem.lower() if cc != 0: if (current != last) and (current in headers): temp_tup.append(current) last = current cc += 1 else: if current in headers: temp_tup.append(current) last = current cc += 1 else: print('Removing {} because it is not in csv headers.'.format(current)) if cc == 2: self.opt_dict[VEC].append(tuple(temp_tup)) vcount += 1 continue if scount + vcount < 1: print('No valid header input found in the conf file!') return False # Get unique elements... if vcount > 0: self.opt_dict[VEC] = list(set(self.opt_dict[VEC])) if scount > 0: self.opt_dict[SCAL] = list(set(self.opt_dict[SCAL])) # Check if any output is actually requested outcount = 0 if self.opt_dict[HISTO]: outcount += 1 if self.opt_dict[SCATT]: outcount += 1 if self.opt_dict[ROSE]: outcount += 1 if self.opt_dict[HEAT]: outcount += 1 if self.opt_dict[SERIES]: outcount += 1 if self.opt_dict[STATS]: outcount += 1 if not outcount: print('No output is actually requested!') return False # Check if any folders need to be created for output temp_path = os.path.join(self.fpath, self.opt_dict[SAVE]) if not os.path.exists(temp_path): print('Output folder does not exist, but will attempt creating...') os.makedirs(temp_path) if not os.path.exists(temp_path): print('Output folder could NOT be created...') print('Possible cause: Lack of writing rights in some of the folders in the path.') return False self.opt_dict[SAVE] = temp_path # Check for valid output figure filetypes temp_list = self.opt_dict[FTYPE] for ftype in temp_list: if not (ftype in FTYPES_ALLOWED): self.opt_dict[FTYPE].remove(ftype) if len(self.opt_dict[FTYPE]) < 1: print('No valid output format given...') print('Default to {}'.format(KEYS_mult_str[FTYPE][0])) self.opt_dict[FTYPE] = KEYS_mult_str[FTYPE] # Check for the rest of options... self.opt_dict[DPI] = int(self.opt_dict[DPI]) if self.opt_dict[DPI] < 80 or self.opt_dict[DPI] > 350: print('Unusually small or large value for DPI detected...') print('Will default to {}'.format(KEYS_num[DPI])) self.opt_dict[DPI] = KEYS_num[DPI] # Ensure figsize has two values if isinstance(self.opt_dict[FIGSIZE], tuple): if len(self.opt_dict[FIGSIZE]) == 1: self.opt_dict[FIGSIZE] = tuple([self.opt_dict[FIGSIZE][0], self.opt_dict[FIGSIZE][0]]) elif len(self.opt_dict[FIGSIZE]) > 2: print('Bad format for figsize, will consider first two args only...') self.opt_dict[FIGSIZE] = tuple([self.opt_dict[FIGSIZE][0], self.opt_dict[FIGSIZE][1]]) else: print('Unknown format for figsize...') print('Will default to {}'.format(KEYS_mult_num[FIGSIZE])) self.opt_dict[FIGSIZE] = KEYS_mult_num[FIGSIZE] # Check that the string for limiting processing based on time # is actually a valid date-time format. if self.opt_dict[TIMETO] or self.opt_dict[TIMEFROM]: self.opt_dict[DATETIME] = KEYS_str[DATETIME] if self.opt_dict[TIMETO]: self.opt_dict[TIMETO] = parse(self.opt_dict[TIMETO]) if self.opt_dict[TIMEFROM]: self.opt_dict[TIMEFROM] = parse(self.opt_dict[TIMEFROM]) return True
true
8ff86d5c92b599240b7482adeb0d1cea895212a5
Python
Leoberium/CS
/stepik_data_structures/bst_feature.py
UTF-8
1,545
3.328125
3
[]
no_license
import sys def check_feature(bst: list): if not bst: return "CORRECT" stack = [] current = 0 # root key_previous = -sys.maxsize - 1 while True: if current != -1: stack.append(current) current = bst[current][1] # left child elif stack: current = stack.pop() if key_previous >= bst[current][0]: # compare keys return "INCORRECT" key_previous = bst[current][0] # update previous key current = bst[current][2] # right child else: break return "CORRECT" if __name__ == '__main__': t = [] for _ in range(int(sys.stdin.readline())): t.append(tuple(map(int, sys.stdin.readline().split()))) print(check_feature(t)) def test_check_feature(): assert check_feature([]) == "CORRECT" assert check_feature([ (2, 1, 2), (1, -1, -1), (3, -1, -1) ]) == "CORRECT" assert check_feature([ (1, 1, 2), (2, -1, -1), (3, -1, -1) ]) == "INCORRECT" assert check_feature([ (1, -1, 1), (2, -1, 2), (3, -1, 3), (4, -1, 4), (5, -1, -1) ]) == "CORRECT" assert check_feature([ (4, 1, 2), (2, 3, 4), (6, 5, 6), (1, -1, -1), (3, -1, -1), (5, -1, -1), (7, -1, -1) ]) == "CORRECT" assert check_feature([ (4, 1, -1), (2, 2, 3), (1, -1, -1), (5, -1, -1) ]) == "INCORRECT"
true
1943507ad7b39735d5f228073321a687c77cdb07
Python
abhishekgupta9807/GIES
/gies.py
UTF-8
50,852
2.515625
3
[]
no_license
#!/usr/bin/env python3 """" ******************************************************************** //File name: gies.py //Creator: Abhishek gupta //Stand alone GUI Desktop aplliction //Last chang: 05/08/2018 ******************************************************************** """ # importing external modules into our application from PyQt4 import QtCore,QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * import os,re,datetime,csv import pandas as pd import sys try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) # Making Main Window Class using PyQt4 class Ui_MainWindow(object): #init method to Creat Data Files when our application will run first time def __init__(self): if os.path.isfile("data_files/import.csv") != True: file = open("data_files/import.csv", 'w', newline='') write = csv.writer(file) write.writerow(['ITEM NAME', 'ITEM WEIGHT', 'ITEM PRICE', 'DATE']) file.close() if os.path.isfile("data_files/export.csv") != True: file = open("data_files/export.csv", 'w', newline='') write = csv.writer(file) write.writerow(["ITEM NAME", 'ITEM WEIGHT', 'ITEM PRICE', 'DATE', 'GST No.']) file.close() if os.path.isfile("data_files/stock.csv") != True: file= open("data_files/stock.csv",'w',newline='') write =csv.writer(file) write.writerow(['ITEM NAME','IMPORT WEIGHT','AVG IMPORT PRICE','EXPORT WEIGHT','AVG EXPORT PRICE','STOCK','profit']) file.close() # settingUp Window size and attributes Size,color, position,hight, width def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(777, 566) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("img/gies_logo.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setStyleSheet(_fromUtf8("")) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.horizontalBottomLayout = QtGui.QHBoxLayout() self.horizontalBottomLayout.setObjectName(_fromUtf8("horizontalBottomLayout")) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 2, 0, 1, 1) self.gstLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.gstLabel.sizePolicy().hasHeightForWidth()) self.gstLabel.setSizePolicy(sizePolicy) self.gstLabel.setObjectName(_fromUtf8("gstLabel")) self.gridLayout.addWidget(self.gstLabel, 0, 0, 1, 1) self.quitButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.quitButton.sizePolicy().hasHeightForWidth()) self.quitButton.setSizePolicy(sizePolicy) self.quitButton.setLayoutDirection(QtCore.Qt.LeftToRight) self.quitButton.setAutoFillBackground(False) self.quitButton.setStyleSheet(_fromUtf8("background-color: rgb(255, 0, 0);\n" "color: rgb(0, 0, 0);")) self.quitButton.setObjectName(_fromUtf8("quitButton")) self.gridLayout.addWidget(self.quitButton, 6, 3, 1, 1) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem1, 6, 2, 1, 1) self.ownerLabel = QtGui.QLabel(self.centralwidget) self.ownerLabel.setObjectName(_fromUtf8("ownerLabel")) self.gridLayout.addWidget(self.ownerLabel, 6, 0, 1, 1) spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem2, 2, 3, 1, 1) spacerItem3 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.gridLayout.addItem(spacerItem3, 6, 1, 1, 1) self.verticalLayout_6 = QtGui.QVBoxLayout() self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) self.shop_noLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.shop_noLabel.sizePolicy().hasHeightForWidth()) self.shop_noLabel.setSizePolicy(sizePolicy) self.shop_noLabel.setObjectName(_fromUtf8("shop_noLabel")) self.verticalLayout_6.addWidget(self.shop_noLabel) self.gridLayout.addLayout(self.verticalLayout_6, 1, 0, 1, 1) self.verticalLayout.addLayout(self.gridLayout) self.horizontalBottomLayout.addLayout(self.verticalLayout) self.gridLayout_2.addLayout(self.horizontalBottomLayout, 3, 0, 1, 1) self.horizonOptiontalLayout = QtGui.QHBoxLayout() self.horizonOptiontalLayout.setObjectName(_fromUtf8("horizonOptiontalLayout")) spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum) self.horizonOptiontalLayout.addItem(spacerItem4) self.line = QtGui.QFrame(self.centralwidget) self.line.setFrameShape(QtGui.QFrame.VLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8("line")) self.horizonOptiontalLayout.addWidget(self.line) self.importButton = QtGui.QPushButton(self.centralwidget) self.importButton.setStyleSheet(_fromUtf8("color: rgb(0, 0, 0);\n" "background-color: rgb(20, 255, 98);")) self.importButton.setObjectName(_fromUtf8("importButton")) self.horizonOptiontalLayout.addWidget(self.importButton) self.exportButton = QtGui.QPushButton(self.centralwidget) self.exportButton.setStyleSheet(_fromUtf8("background-color: rgb(51, 0, 255);\n" "background-color: rgb(255, 52, 26);\n" "color: rgb(0, 0, 0);")) self.exportButton.setObjectName(_fromUtf8("exportButton")) self.horizonOptiontalLayout.addWidget(self.exportButton) self.stockButton = QtGui.QPushButton(self.centralwidget) self.stockButton.setStyleSheet(_fromUtf8("background-color: rgb(0, 255, 0);\n" "color: rgb(0, 0, 0);")) self.stockButton.setObjectName(_fromUtf8("stockButton")) self.horizonOptiontalLayout.addWidget(self.stockButton) self.balanceSheetButton = QtGui.QPushButton(self.centralwidget) self.balanceSheetButton.setStyleSheet(_fromUtf8("background-color: rgb(21, 5, 255);\n" "color: rgb(0, 0, 0);")) self.balanceSheetButton.setObjectName(_fromUtf8("balanceSheetButton")) self.horizonOptiontalLayout.addWidget(self.balanceSheetButton) self.line_2 = QtGui.QFrame(self.centralwidget) self.line_2.setFrameShape(QtGui.QFrame.VLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName(_fromUtf8("line_2")) self.horizonOptiontalLayout.addWidget(self.line_2) spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum) self.horizonOptiontalLayout.addItem(spacerItem5) self.gridLayout_2.addLayout(self.horizonOptiontalLayout, 2, 0, 1, 1) self.systemTitleLabel = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily(_fromUtf8("Ubuntu")) font.setPointSize(26) font.setBold(True) font.setItalic(True) font.setWeight(75) self.systemTitleLabel.setFont(font) self.systemTitleLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.systemTitleLabel.setTextFormat(QtCore.Qt.AutoText) self.systemTitleLabel.setAlignment(QtCore.Qt.AlignCenter) self.systemTitleLabel.setObjectName(_fromUtf8("systemTitleLabel")) self.gridLayout_2.addWidget(self.systemTitleLabel, 1, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 777, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuHome = QtGui.QMenu(self.menubar) self.menuHome.setObjectName(_fromUtf8("menuHome")) self.menuView = QtGui.QMenu(self.menubar) self.menuView.setStyleSheet(_fromUtf8("")) self.menuView.setObjectName(_fromUtf8("menuView")) self.menuSetting = QtGui.QMenu(self.menubar) self.menuSetting.setObjectName(_fromUtf8("menuSetting")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.subMenuImport = QtGui.QAction(MainWindow) self.subMenuImport.setObjectName(_fromUtf8("subMenuImport")) self.subMenuExport = QtGui.QAction(MainWindow) self.subMenuExport.setObjectName(_fromUtf8("subMenuExport")) self.subMenuStock = QtGui.QAction(MainWindow) self.subMenuStock.setObjectName(_fromUtf8("subMenuStock")) self.subMenuBalanceSheet = QtGui.QAction(MainWindow) self.subMenuBalanceSheet.setObjectName(_fromUtf8("subMenuBalanceSheet")) self.menuHome.addAction(self.subMenuImport) self.menuHome.addAction(self.subMenuExport) self.menuHome.addAction(self.subMenuStock) self.menuHome.addAction(self.subMenuBalanceSheet) self.menubar.addAction(self.menuHome.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuSetting.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.subMenuImport.triggered.connect(self.importUI) self.subMenuExport.triggered.connect(self.exportUI) self.subMenuStock.triggered.connect(self.stock) self.importButton.clicked.connect(self.importUI) self.exportButton.clicked.connect(self.exportUI) self.stockButton.clicked.connect(self.stock) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "GIES", None)) self.gstLabel.setText(_translate("MainWindow", "GST No. :TIN00920", None)) self.quitButton.setText(_translate("MainWindow", "Quit", None)) self.ownerLabel.setText(_translate("MainWindow", "OWNER : XYZ", None)) self.shop_noLabel.setText(_translate("MainWindow", "SHOP No. : 1980", None)) self.importButton.setText(_translate("MainWindow", "Import", None)) self.exportButton.setText(_translate("MainWindow", "Export", None)) self.stockButton.setText(_translate("MainWindow", "Stock", None)) self.balanceSheetButton.setText(_translate("MainWindow", "BalanceSheet", None)) self.systemTitleLabel.setText(_translate("MainWindow", "Grain Import/Export System", None)) self.menuHome.setTitle(_translate("MainWindow", "Home", None)) self.menuView.setTitle(_translate("MainWindow", "View", None)) self.menuSetting.setTitle(_translate("MainWindow", "Setting", None)) self.menuHelp.setTitle(_translate("MainWindow", "Help", None)) self.subMenuImport.setText(_translate("MainWindow", "Import", None)) self.subMenuExport.setText(_translate("MainWindow", "Export", None)) self.subMenuStock.setText(_translate("MainWindow", "Stock", None)) self.subMenuBalanceSheet.setText(_translate("MainWindow", "BalanceSheet", None)) # On click event on menu def importUI(self): self.import_window=Ui_ImportWindow() self.import_window.setupUi(MainWindow) self.import_window.enterButton.clicked.connect(self.import_window.saveImportData) def exportUI(self): self.export_window=Ui_ExportWindow() self.export_window.setupUi(MainWindow) self.export_window.enterButton.clicked.connect(self.export_window.saveExportData) def stock(self): self.stock_window=Ui_StockWindow() self.stock_window.setupUi(MainWindow) # Making Import Window Class class Ui_ImportWindow(object): # SettingUp Window size ,elements ,color,height,width def setupUi(self, ImportWindow): ImportWindow.setObjectName(_fromUtf8("ImportWindow")) ImportWindow.resize(804, 526) self.centralwidget = QtGui.QWidget(ImportWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.shopLabel = QtGui.QLabel(self.centralwidget) self.shopLabel.setObjectName(_fromUtf8("shopLabel")) self.gridLayout_2.addWidget(self.shopLabel, 14, 0, 1, 1) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.dateEdit = QtGui.QDateEdit(self.centralwidget) self.dateEdit.setCalendarPopup(True) self.dateEdit.setObjectName(_fromUtf8("dateEdit")) self.gridLayout.addWidget(self.dateEdit, 4, 2, 1, 1) self.formLabel = QtGui.QLabel(self.centralwidget) self.formLabel.setObjectName(_fromUtf8("formLabel")) self.gridLayout.addWidget(self.formLabel, 0, 2, 1, 2) self.nameLineEdit = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.nameLineEdit.sizePolicy().hasHeightForWidth()) self.nameLineEdit.setSizePolicy(sizePolicy) self.nameLineEdit.setObjectName(_fromUtf8("nameLineEdit")) self.gridLayout.addWidget(self.nameLineEdit, 1, 2, 1, 1) self.priceLineEdit_3 = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.priceLineEdit_3.sizePolicy().hasHeightForWidth()) self.priceLineEdit_3.setSizePolicy(sizePolicy) self.priceLineEdit_3.setObjectName(_fromUtf8("priceLineEdit_3")) self.gridLayout.addWidget(self.priceLineEdit_3, 3, 2, 1, 1) self.itemWeightLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemWeightLabel.sizePolicy().hasHeightForWidth()) self.itemWeightLabel.setSizePolicy(sizePolicy) self.itemWeightLabel.setObjectName(_fromUtf8("itemWeightLabel")) self.gridLayout.addWidget(self.itemWeightLabel, 2, 1, 1, 1) spacerItem = QtGui.QSpacerItem(300, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 2, 0, 1, 1) self.priceLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.priceLabel.sizePolicy().hasHeightForWidth()) self.priceLabel.setSizePolicy(sizePolicy) self.priceLabel.setObjectName(_fromUtf8("priceLabel")) self.gridLayout.addWidget(self.priceLabel, 3, 1, 1, 1) self.itemNameLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemNameLabel.sizePolicy().hasHeightForWidth()) self.itemNameLabel.setSizePolicy(sizePolicy) self.itemNameLabel.setObjectName(_fromUtf8("itemNameLabel")) self.gridLayout.addWidget(self.itemNameLabel, 1, 1, 1, 1) self.dateLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dateLabel.sizePolicy().hasHeightForWidth()) self.dateLabel.setSizePolicy(sizePolicy) self.dateLabel.setObjectName(_fromUtf8("dateLabel")) self.gridLayout.addWidget(self.dateLabel, 4, 1, 1, 1) self.weightLineEdit_2 = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.weightLineEdit_2.sizePolicy().hasHeightForWidth()) self.weightLineEdit_2.setSizePolicy(sizePolicy) self.weightLineEdit_2.setObjectName(_fromUtf8("weightLineEdit_2")) self.gridLayout.addWidget(self.weightLineEdit_2, 2, 2, 1, 1) self.enterButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.enterButton.sizePolicy().hasHeightForWidth()) self.enterButton.setSizePolicy(sizePolicy) self.enterButton.setObjectName(_fromUtf8("enterButton")) self.gridLayout.addWidget(self.enterButton, 5, 2, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 6, 0, 1, 1) self.systemLabel = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(24) font.setBold(True) font.setItalic(True) font.setWeight(75) self.systemLabel.setFont(font) self.systemLabel.setAlignment(QtCore.Qt.AlignCenter) self.systemLabel.setObjectName(_fromUtf8("systemLabel")) self.gridLayout_2.addWidget(self.systemLabel, 1, 0, 2, 2) self.ownerLabel = QtGui.QLabel(self.centralwidget) self.ownerLabel.setObjectName(_fromUtf8("ownerLabel")) self.gridLayout_2.addWidget(self.ownerLabel, 16, 0, 1, 1) self.quitButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.quitButton.sizePolicy().hasHeightForWidth()) self.quitButton.setSizePolicy(sizePolicy) self.quitButton.setStyleSheet(_fromUtf8("background-color: rgb(255, 12, 24);\n" "color: rgb(0, 0, 0);")) self.quitButton.setObjectName(_fromUtf8("quitButton")) self.gridLayout_2.addWidget(self.quitButton, 16, 1, 1, 1) self.gstLabel = QtGui.QLabel(self.centralwidget) self.gstLabel.setObjectName(_fromUtf8("gstLabel")) self.gridLayout_2.addWidget(self.gstLabel, 13, 0, 1, 1) ImportWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(ImportWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 804, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuHome = QtGui.QMenu(self.menubar) self.menuHome.setObjectName(_fromUtf8("menuHome")) self.menuView = QtGui.QMenu(self.menubar) self.menuView.setObjectName(_fromUtf8("menuView")) self.menuSetting = QtGui.QMenu(self.menubar) self.menuSetting.setObjectName(_fromUtf8("menuSetting")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) ImportWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(ImportWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) ImportWindow.setStatusBar(self.statusbar) self.subMenuImport = QtGui.QAction(ImportWindow) self.subMenuImport.setObjectName(_fromUtf8("subMenuImport")) self.subMenuExport = QtGui.QAction(ImportWindow) self.subMenuExport.setObjectName(_fromUtf8("subMenuExport")) self.subMenuStock = QtGui.QAction(ImportWindow) self.subMenuStock.setObjectName(_fromUtf8("subMenuStock")) self.subMenuBalanceSheet = QtGui.QAction(ImportWindow) self.subMenuBalanceSheet.setObjectName(_fromUtf8("subMenuBalanceSheet")) self.menuHome.addAction(self.subMenuImport) self.menuHome.addAction(self.subMenuExport) self.menuHome.addAction(self.subMenuStock) self.menuHome.addAction(self.subMenuBalanceSheet) self.menubar.addAction(self.menuHome.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuSetting.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.subMenuExport.triggered.connect(self.exportUI) self.subMenuStock.triggered.connect(self.stock) #self.enterButton.clicked.connect(self.saveImportData) self.retranslateUi(ImportWindow) QtCore.QMetaObject.connectSlotsByName(ImportWindow) def retranslateUi(self, ImportWindow): ImportWindow.setWindowTitle(_translate("ImportWindow", "ImportWindow", None)) self.shopLabel.setText(_translate("ImportWindow", "Shop No. :1980", None)) self.formLabel.setText(_translate("ImportWindow", "Enter Details of Trancation", None)) self.itemWeightLabel.setText(_translate("ImportWindow", "Item Weight :", None)) self.priceLabel.setText(_translate("ImportWindow", "Price :", None)) self.itemNameLabel.setText(_translate("ImportWindow", "Item Name :", None)) self.dateLabel.setText(_translate("ImportWindow", "Date :", None)) self.enterButton.setText(_translate("ImportWindow", "Enter", None)) self.systemLabel.setText(_translate("ImportWindow", "Grain Import/Export System", None)) self.ownerLabel.setText(_translate("ImportWindow", "OWNER :XYZ", None)) self.quitButton.setText(_translate("ImportWindow", "Quit", None)) self.gstLabel.setText(_translate("ImportWindow", "GST No. :TIN0009293", None)) self.menuHome.setTitle(_translate("ImportWindow", "Home", None)) self.menuView.setTitle(_translate("ImportWindow", "View", None)) self.menuSetting.setTitle(_translate("ImportWindow", "Setting", None)) self.menuHelp.setTitle(_translate("ImportWindow", "Help", None)) self.subMenuImport.setText(_translate("ImportWindow", "Import", None)) self.subMenuExport.setText(_translate("ImportWindow", "Export", None)) self.subMenuStock.setText(_translate("ImportWindow", "Stock", None)) self.subMenuBalanceSheet.setText(_translate("ImportWindow", "BalanceSheet", None)) # funtion to Save imported Data into import.csv file def saveImportData(self): #retriving Data into the applicatiion date=datetime.datetime.now().date() self.todayDate=str(date.day)+'/'+str(date.month)+'/'+str(date.year) self.itemName=self.nameLineEdit.text().upper() try: if not self.itemName: raise ValueError() self.itemWeight=float(self.weightLineEdit_2.text()) self.itemPrice=float(self.priceLineEdit_3.text()) self.list=[self.itemName,self.itemWeight,self.itemPrice,self.todayDate] except ValueError: self.error() try: file=open("data_files/import.csv",'a',newline='') write=csv.writer(file) write.writerow(self.list) #updateStock() finally: file.close() self.statusbar.showMessage("SUCCESS!!\t PAYMENT={}$".format(self.itemWeight*self.itemPrice)) def error(self): # ERROR message on Wrong Input self.statusbar.showMessage("Something is going WRONG!! PLEASE enter correct details") # on click event def exportUI(self): self.export_window=Ui_ExportWindow() self.export_window.setupUi(MainWindow) self.export_window.enterButton.clicked.connect(self.export_window.saveExportData) def stock(self): self.stock_window=Ui_StockWindow() self.stock_window.setupUi(MainWindow) # Making Export Window class class Ui_ExportWindow(object): #SettingUp Window size, elements ,height, width color def setupUi(self, ExportWindow): ExportWindow.setObjectName(_fromUtf8("ExportWindow")) ExportWindow.resize(802, 525) font = QtGui.QFont() font.setItalic(False) ExportWindow.setFont(font) self.centralwidget = QtGui.QWidget(ExportWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.line = QtGui.QFrame(self.centralwidget) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8("line")) self.verticalLayout.addWidget(self.line) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.itemWeightLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemWeightLabel.sizePolicy().hasHeightForWidth()) self.itemWeightLabel.setSizePolicy(sizePolicy) self.itemWeightLabel.setObjectName(_fromUtf8("itemWeightLabel")) self.gridLayout.addWidget(self.itemWeightLabel, 3, 0, 1, 2) self.formLabel = QtGui.QLabel(self.centralwidget) self.formLabel.setObjectName(_fromUtf8("formLabel")) self.gridLayout.addWidget(self.formLabel, 0, 1, 1, 3) self.priceLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.priceLabel.sizePolicy().hasHeightForWidth()) self.priceLabel.setSizePolicy(sizePolicy) self.priceLabel.setObjectName(_fromUtf8("priceLabel")) self.gridLayout.addWidget(self.priceLabel, 4, 0, 1, 1) self.priceLineEdit = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.priceLineEdit.sizePolicy().hasHeightForWidth()) self.priceLineEdit.setSizePolicy(sizePolicy) self.priceLineEdit.setObjectName(_fromUtf8("priceLineEdit")) self.gridLayout.addWidget(self.priceLineEdit, 4, 3, 1, 1) self.shopNoLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.shopNoLabel.sizePolicy().hasHeightForWidth()) self.shopNoLabel.setSizePolicy(sizePolicy) self.shopNoLabel.setObjectName(_fromUtf8("shopNoLabel")) self.gridLayout.addWidget(self.shopNoLabel, 1, 0, 1, 3) self.shopLineEdit = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.shopLineEdit.sizePolicy().hasHeightForWidth()) self.shopLineEdit.setSizePolicy(sizePolicy) self.shopLineEdit.setObjectName(_fromUtf8("shopLineEdit")) self.gridLayout.addWidget(self.shopLineEdit, 1, 3, 1, 1) self.itemNameLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemNameLabel.sizePolicy().hasHeightForWidth()) self.itemNameLabel.setSizePolicy(sizePolicy) self.itemNameLabel.setObjectName(_fromUtf8("itemNameLabel")) self.gridLayout.addWidget(self.itemNameLabel, 2, 0, 1, 2) self.dateLabel = QtGui.QLabel(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dateLabel.sizePolicy().hasHeightForWidth()) self.dateLabel.setSizePolicy(sizePolicy) self.dateLabel.setObjectName(_fromUtf8("dateLabel")) self.gridLayout.addWidget(self.dateLabel, 5, 0, 1, 1) self.dateEdit = QtGui.QDateEdit(self.centralwidget) self.dateEdit.setCalendarPopup(True) self.dateEdit.setObjectName(_fromUtf8("dateEdit")) self.gridLayout.addWidget(self.dateEdit, 5, 3, 1, 1) self.itemNameLineEdit = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemNameLineEdit.sizePolicy().hasHeightForWidth()) self.itemNameLineEdit.setSizePolicy(sizePolicy) self.itemNameLineEdit.setObjectName(_fromUtf8("itemNameLineEdit")) self.gridLayout.addWidget(self.itemNameLineEdit, 2, 3, 1, 1) self.itemWeightLineEdit = QtGui.QLineEdit(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemWeightLineEdit.sizePolicy().hasHeightForWidth()) self.itemWeightLineEdit.setSizePolicy(sizePolicy) self.itemWeightLineEdit.setObjectName(_fromUtf8("itemWeightLineEdit")) self.gridLayout.addWidget(self.itemWeightLineEdit, 3, 3, 1, 1) self.enterButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.enterButton.sizePolicy().hasHeightForWidth()) self.enterButton.setSizePolicy(sizePolicy) self.enterButton.setObjectName(_fromUtf8("enterButton")) self.gridLayout.addWidget(self.enterButton, 6, 2, 1, 2) self.verticalLayout.addLayout(self.gridLayout) self.line_2 = QtGui.QFrame(self.centralwidget) self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName(_fromUtf8("line_2")) self.verticalLayout.addWidget(self.line_2) self.gridLayout_2.addLayout(self.verticalLayout, 1, 2, 1, 1) self.systemLabel = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(24) font.setBold(True) font.setWeight(75) self.systemLabel.setFont(font) self.systemLabel.setAlignment(QtCore.Qt.AlignCenter) self.systemLabel.setObjectName(_fromUtf8("systemLabel")) self.gridLayout_2.addWidget(self.systemLabel, 0, 0, 1, 5) self.line_3 = QtGui.QFrame(self.centralwidget) self.line_3.setFrameShape(QtGui.QFrame.VLine) self.line_3.setFrameShadow(QtGui.QFrame.Sunken) self.line_3.setObjectName(_fromUtf8("line_3")) self.gridLayout_2.addWidget(self.line_3, 1, 1, 1, 1) self.line_4 = QtGui.QFrame(self.centralwidget) self.line_4.setFrameShape(QtGui.QFrame.VLine) self.line_4.setFrameShadow(QtGui.QFrame.Sunken) self.line_4.setObjectName(_fromUtf8("line_4")) self.gridLayout_2.addWidget(self.line_4, 1, 3, 1, 1) self.shopLabel = QtGui.QLabel(self.centralwidget) self.shopLabel.setObjectName(_fromUtf8("shopLabel")) self.gridLayout_2.addWidget(self.shopLabel, 2, 0, 1, 3) self.gstLabel = QtGui.QLabel(self.centralwidget) self.gstLabel.setObjectName(_fromUtf8("gstLabel")) self.gridLayout_2.addWidget(self.gstLabel, 3, 0, 1, 3) self.ownerLabel = QtGui.QLabel(self.centralwidget) self.ownerLabel.setObjectName(_fromUtf8("ownerLabel")) self.gridLayout_2.addWidget(self.ownerLabel, 4, 0, 1, 1) self.quitButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.quitButton.sizePolicy().hasHeightForWidth()) self.quitButton.setSizePolicy(sizePolicy) self.quitButton.setStyleSheet(_fromUtf8("background-color: rgb(255, 10, 14);\n" "color: rgb(0, 0, 0);")) self.quitButton.setObjectName(_fromUtf8("quitButton")) self.gridLayout_2.addWidget(self.quitButton, 4, 3, 1, 1) ExportWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(ExportWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 802, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuHome = QtGui.QMenu(self.menubar) self.menuHome.setObjectName(_fromUtf8("menuHome")) self.menuView = QtGui.QMenu(self.menubar) self.menuView.setObjectName(_fromUtf8("menuView")) self.menuSetting = QtGui.QMenu(self.menubar) self.menuSetting.setObjectName(_fromUtf8("menuSetting")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) ExportWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(ExportWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) ExportWindow.setStatusBar(self.statusbar) self.subMenuImport = QtGui.QAction(ExportWindow) self.subMenuImport.setObjectName(_fromUtf8("subMenuImport")) self.subMenuExport = QtGui.QAction(ExportWindow) self.subMenuExport.setObjectName(_fromUtf8("subMenuExport")) self.subMenuStock = QtGui.QAction(ExportWindow) self.subMenuStock.setObjectName(_fromUtf8("subMenuStock")) self.subMenuBalanceShaeet = QtGui.QAction(ExportWindow) self.subMenuBalanceShaeet.setObjectName(_fromUtf8("subMenuBalanceShaeet")) self.menuHome.addAction(self.subMenuImport) self.menuHome.addAction(self.subMenuExport) self.menuHome.addAction(self.subMenuStock) self.menuHome.addAction(self.subMenuBalanceShaeet) self.menubar.addAction(self.menuHome.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuSetting.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.subMenuImport.triggered.connect(self.importUI) self.subMenuStock.triggered.connect(self.stock) #self.enterButton.clicked.connect(self.saveExportData) self.retranslateUi(ExportWindow) QtCore.QMetaObject.connectSlotsByName(ExportWindow) def retranslateUi(self, ExportWindow): ExportWindow.setWindowTitle(_translate("ExportWindow", "ExportWindow", None)) self.itemWeightLabel.setText(_translate("ExportWindow", "Item Weight :", None)) self.formLabel.setText(_translate("ExportWindow", "Enter Details Of Trancation", None)) self.priceLabel.setText(_translate("ExportWindow", "Price :", None)) self.shopNoLabel.setText(_translate("ExportWindow", "GST No. /Shop No. :", None)) self.itemNameLabel.setText(_translate("ExportWindow", "Item Name : ", None)) self.dateLabel.setText(_translate("ExportWindow", "Date :", None)) self.enterButton.setText(_translate("ExportWindow", "Enter", None)) self.systemLabel.setText(_translate("ExportWindow", "GRAIN IMPORT/EXPORT SYSTEM", None)) self.shopLabel.setText(_translate("ExportWindow", "Shop No. : 1980", None)) self.gstLabel.setText(_translate("ExportWindow", "GST No. :TIN00029938", None)) self.ownerLabel.setText(_translate("ExportWindow", "OWNER : XYZ", None)) self.quitButton.setText(_translate("ExportWindow", "Quit", None)) self.menuHome.setTitle(_translate("ExportWindow", "Home", None)) self.menuView.setTitle(_translate("ExportWindow", "View", None)) self.menuSetting.setTitle(_translate("ExportWindow", "Setting", None)) self.menuHelp.setTitle(_translate("ExportWindow", "Help", None)) self.subMenuImport.setText(_translate("ExportWindow", "Import", None)) self.subMenuExport.setText(_translate("ExportWindow", "Export", None)) self.subMenuStock.setText(_translate("ExportWindow", "Stock", None)) self.subMenuBalanceShaeet.setText(_translate("ExportWindow", "BalanceShaeet", None)) # function to save exported data into export.csv file def saveExportData(self): date = datetime.datetime.now().date() self.todayDate = str(date.day) + '/' + str(date.month) + '/' + str(date.year) self.itemName = str(self.itemNameLineEdit.text()).upper() self.shopName=str(self.shopLineEdit.text()).upper() #date = self.dateEdit.text() try: if not self.itemName: raise ValueError #if not self.shopName: # raise ValueError self.itemWeight = float(self.itemWeightLineEdit.text()) self.itemPrice = float(self.priceLineEdit.text()) self.list = [self.itemName,self.itemWeight,self.itemPrice, self.todayDate,self.shopName] except: self.error() try: file = open("data_files/export.csv", 'a', newline='') write = csv.writer(file) write.writerow(self.list) #updateStock() finally: file.close() self.statusbar.showMessage("SUCCESS!!!\t PAYMENT={}$".format(self.itemWeight*self.itemPrice)) def error(self): self.statusbar.showMessage("WARNING !!!Somthing is going wrong please enter valid details") def importUI(self): self.import_window=Ui_ImportWindow() self.import_window.setupUi(MainWindow) self.import_window.enterButton.clicked.connect(self.import_window.saveImportData) def stock(self): self.stock_window=Ui_StockWindow() self.stock_window.setupUi(MainWindow) # stock window class class Ui_StockWindow(object): #settingUp window size, elements, color def setupUi(self, StockWindow): StockWindow.setObjectName(_fromUtf8("StockWindow")) StockWindow.resize(810, 563) self.centralwidget = QtGui.QWidget(StockWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.Lsystemabel = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(24) font.setBold(True) font.setItalic(True) font.setWeight(75) self.Lsystemabel.setFont(font) self.Lsystemabel.setAlignment(QtCore.Qt.AlignCenter) self.Lsystemabel.setObjectName(_fromUtf8("Lsystemabel")) self.gridLayout.addWidget(self.Lsystemabel, 0, 0, 1, 1) self.stockTableView = QtGui.QTableWidget(self.centralwidget) self.stockTableView.setObjectName(_fromUtf8("stockTableView")) self.stockTableView.setRowCount(100) self.stockTableView.setColumnCount(7) self.stockTableView.setItem(0,0,QtGui.QTableWidgetItem("ITEM NAME")) self.stockTableView.setItem(0,1,QtGui.QTableWidgetItem("IMPORT WEIGHT")) self.stockTableView.setItem(0, 2, QtGui.QTableWidgetItem("AVG IMPORT PRICE")) self.stockTableView.setItem(0, 3, QtGui.QTableWidgetItem("EXPORT WEIGHT")) self.stockTableView.setItem(0,4,QtGui.QTableWidgetItem("AVG EXPORT PRICE")) self.stockTableView.setItem(0,5,QtGui.QTableWidgetItem("STOCK")) self.stockTableView.setItem(0, 6, QtGui.QTableWidgetItem("PROFIT/LOSS")) self.gridLayout.addWidget(self.stockTableView, 1, 0, 1, 2) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.gstLabel = QtGui.QLabel(self.centralwidget) self.gstLabel.setObjectName(_fromUtf8("gstLabel")) self.verticalLayout.addWidget(self.gstLabel) self.shopLabel = QtGui.QLabel(self.centralwidget) self.shopLabel.setObjectName(_fromUtf8("shopLabel")) self.verticalLayout.addWidget(self.shopLabel) self.userLabel = QtGui.QLabel(self.centralwidget) self.userLabel.setObjectName(_fromUtf8("userLabel")) self.verticalLayout.addWidget(self.userLabel) self.gridLayout.addLayout(self.verticalLayout, 2, 0, 1, 1) self.quitButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.quitButton.sizePolicy().hasHeightForWidth()) self.quitButton.setSizePolicy(sizePolicy) self.quitButton.setObjectName(_fromUtf8("quitButton")) self.gridLayout.addWidget(self.quitButton, 2, 1, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1) StockWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(StockWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 810, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuHome = QtGui.QMenu(self.menubar) self.menuHome.setObjectName(_fromUtf8("menuHome")) self.menuView = QtGui.QMenu(self.menubar) self.menuView.setObjectName(_fromUtf8("menuView")) self.menuSetting = QtGui.QMenu(self.menubar) self.menuSetting.setObjectName(_fromUtf8("menuSetting")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) StockWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(StockWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) StockWindow.setStatusBar(self.statusbar) self.toolBar = QtGui.QToolBar(StockWindow) self.toolBar.setObjectName(_fromUtf8("toolBar")) StockWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar_2 = QtGui.QToolBar(StockWindow) self.toolBar_2.setObjectName(_fromUtf8("toolBar_2")) StockWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar_2) self.subMenuImport = QtGui.QAction(StockWindow) self.subMenuImport.setObjectName(_fromUtf8("subMenuImport")) self.subMenuExport = QtGui.QAction(StockWindow) self.subMenuExport.setObjectName(_fromUtf8("subMenuExport")) self.subMenuStock = QtGui.QAction(StockWindow) self.subMenuStock.setObjectName(_fromUtf8("subMenuStock")) self.subMenuBalanceSheet = QtGui.QAction(StockWindow) self.subMenuBalanceSheet.setObjectName(_fromUtf8("subMenuBalanceSheet")) self.menuHome.addAction(self.subMenuImport) self.menuHome.addAction(self.subMenuExport) self.menuHome.addAction(self.subMenuStock) self.menuHome.addAction(self.subMenuBalanceSheet) self.menubar.addAction(self.menuHome.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuSetting.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.subMenuImport.triggered.connect(self.importUI) self.subMenuExport.triggered.connect(self.exportUI) self.loadValue() self.retranslateUi(StockWindow) QtCore.QMetaObject.connectSlotsByName(StockWindow) def retranslateUi(self, StockWindow): StockWindow.setWindowTitle(_translate("StockWindow", "StockWindow", None)) self.Lsystemabel.setText(_translate("StockWindow", "Grain Import/Export System", None)) self.gstLabel.setText(_translate("StockWindow", "GST No. : TIN000298982", None)) self.shopLabel.setText(_translate("StockWindow", "Shop No. : 1998", None)) self.userLabel.setText(_translate("StockWindow", "USER : XYZ", None)) self.quitButton.setText(_translate("StockWindow", "Quit", None)) self.menuHome.setTitle(_translate("StockWindow", "Home", None)) self.menuView.setTitle(_translate("StockWindow", "View", None)) self.menuSetting.setTitle(_translate("StockWindow", "Setting", None)) self.menuHelp.setTitle(_translate("StockWindow", "Help", None)) self.toolBar.setWindowTitle(_translate("StockWindow", "toolBar", None)) self.toolBar_2.setWindowTitle(_translate("StockWindow", "toolBar_2", None)) self.subMenuImport.setText(_translate("StockWindow", "Import", None)) self.subMenuExport.setText(_translate("StockWindow", "Export", None)) self.subMenuStock.setText(_translate("StockWindow", "Stock", None)) self.subMenuBalanceSheet.setText(_translate("StockWindow", "BalanceSheet", None)) #this fuction will read stock.csv file and load data into Stock Window def loadValue(self): string='' try: if os.path.isfile("data_files/stock.csv"): updateStock() self.stock=pd.read_csv('data_files/stock.csv') else: raise ValueError() except: self.error() for x in range(len(self.stock)): row=re.sub("\s+","$",self.stock.iloc[x][0]) list=[] row=row+'$' for y in row: if y=='$': list.append(string) string='' else: string=string+y count=0 for z in range(1,len(list)): self.stockTableView.setItem(x+1,count,QtGui.QTableWidgetItem(list[z])) count+=1 def error(self): self.statusbar.showMessage("Data not found") def importUI(self): self.import_window=Ui_ImportWindow() self.import_window.setupUi(MainWindow) self.import_window.enterButton.clicked.connect(self.import_window.saveImportData) def exportUI(self): self.export_window=Ui_ExportWindow() self.export_window.setupUi(MainWindow) self.export_window.enterButton.clicked.connect(self.export_window.saveExportData) ''' /*Update Stock function*/ / // # it will load all the transaction from both import/export.csv files and apply some logics to write available stocks into the stock.csv file ''' def updateStock(): #reading import.csv file into pandas dataframe import_data=pd.read_csv('data_files/import.csv') item_list=pd.Series(import_data['ITEM NAME']).unique() import_stock=[] for x in item_list: row=[] item=import_data[import_data['ITEM NAME']==x] avg_price=item['ITEM PRICE'].mean() item_weight=item['ITEM WEIGHT'].sum() item=str(x) row.append(item) row.append(item_weight) row.append(avg_price) import_stock.append(row) import_dataframe=pd.DataFrame(import_stock,columns=['ITEM NAME','IMPORT WEIGHT','AVG IMPORT PRICE']) # reading export.csv file into pandas dataframe export_data=pd.read_csv('data_files/export.csv') item_list=pd.Series(export_data['ITEM NAME']).unique() export_stock=[] for x in item_list: row=[] item=export_data[export_data['ITEM NAME']==x] avg_price=item['ITEM PRICE'].mean() item_weight=item['ITEM WEIGHT'].sum() item=str(x) row.append(item) row.append(item_weight) row.append(avg_price) export_stock.append(row) export_dataframe=pd.DataFrame(export_stock,columns=['ITEM NAME','EXPORT WEIGHT','AVG EXPORT PRICE']) # merging two dataframes stock=pd.merge(import_dataframe,export_dataframe,on='ITEM NAME',how="outer") stock['STOCK']=stock['IMPORT WEIGHT']-stock['EXPORT WEIGHT'] stock['profit']=stock['EXPORT WEIGHT']*stock['AVG EXPORT PRICE']-stock['EXPORT WEIGHT']*stock['AVG IMPORT PRICE'] # writing stock dataframe into stock.csv file. stock.to_csv('data_files/stock.csv',sep='\t') ''' Start of the Main program''' if __name__ == "__main__": app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) """ *********************************************************************** //EOF: gies.py *********************************************************************** """
true