def __init__(self, name): self.name = name self.customers = hashtable.Hashtable() self.classicals = binarysearchtree.BinarySearchTree() self.rocks = binarysearchtree.BinarySearchTree() self.metals = binarysearchtree.BinarySearchTree() self.fact = factory.Factory()
def Factory(): global _factory # One-time init if _factory == None: _factory = SynchronizedObject(factory.Factory()) return _factory
def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_key = "bullet" #Get these from xml self.image_size = (10, 4) self.speed_x = 10 self.speed_y = 0 #Probably shouldn't touch these self.image = factory.Factory().get_sprite_data(self.image_key) self.rect = self.image.get_rect() self.screen = factory.Factory().get_screen() self.screenRect = self.screen.get_rect() self.on_screen = False self.x = 0 self.y = 0
def __init__(self): """ """ #the factory to create the instances objFactory=factory.Factory() #get the instances self._gdcm=objFactory.get_gdClient_man() self._gdam=objFactory.get_gdActions_man() self._confMan=objFactory.get_configuration_man() self._accMan=objFactory.get_account_man()
def load_images(self): """ Loads the frames of an image from a single file """ img_master = factory.Factory().get_sprite_data(self.image_file) offset = [] for i in range(self.frames): offset.append((i * self.image_size[0], 0)) tmp_img = pygame.Surface(self.image_size) tmp_img.blit(img_master, (0, 0), (offset[i], self.image_size)) trans_color = tmp_img.get_at((0, 0)) tmp_img.set_colorkey(trans_color) self.img_list.append(tmp_img)
def start_game(): while True: user_choice = options_to_choose.OptionsToChoose().offering_options( fighting_game_types.FightingGames) game = factory.Factory().create(user_choice, fighting_game_types.FightingGames) if game == None: continue elif game == False: print("Goodby!") break
def __init__(self): #Loads the files that contains all components with open('data/components.json') as component_files: components = json.load(component_files) self.WORLD = {} self.COMPS = {} self.COMPS['none'] = 1 << 0 iterator = 1 for key in components: self.WORLD[key] = {} self.COMPS[key] = 1 << iterator iterator += 1 self.entity_id_max = 2500 self.factory = factory.Factory(self)
def execute(self, iterable): list_iterator = factory.Factory().create(iterable, type(self)) while True: iteratoion_over_iterable = input( "If you want the next fighting style type N\n" "If you want the previous fighting style type P\n" "If you want the current fighting style type C: ") fighting_style_with_iteration = factory.FactoryForAttackMainClass( ).create(iteratoion_over_iterable, self.command_to_iterator, list_iterator) if fighting_style_with_iteration == None: continue else: return fighting_style_with_iteration()
def main(): for path in paths: path = '/home/srv/development/crm/pdf_for_tests/' + path fact = factory.Factory(path) show_lead_time(fact._convert)() show_lead_time(fact._recognize)() show_lead_time(fact.find_title)() show_lead_time(fact.find_tu)() show_lead_time(fact.find_length)() show_lead_time(fact.find_res)() show_lead_time(fact.find_type)() show_lead_time(fact.find_adress)() print('\n' + path +'\n\n')
def cycle(margs): """Runs a single game cycle. Broken out of the run function to allow multiprocessing support. Takes the factory as an argument. Returns the dataset from the cycle. """ # Retrieve the important bits, now with bake your own factory fact = factory.Factory(margs) (engine, manager) = fact.createHeadless() # Prepare game dataset state = manager.copyState() gameData = {'turn' : 0, 'winner' : None, 'players' : {}} for key in state.players: gameData['players'][key] = [] # Do the game done = False while not done: # Prepare data-gathering while manager.copyState().GMState < manager.GMStates['resolve']: if engine.update(): # Run the game up to resolution done = True break # Break the loop if someone has already won if done: gameData['winner'] = state.winner break # No more collections while manager.copyState().GMState == manager.GMStates['resolve']: if engine.update(): # Finish the resolution step done = True break # Game is over, time to collect data # Collect data for the turn state = manager.copyState() for key in state.players: gameData['players'][key].append( state.getPlayer(key).ship.getPos()) gameData['winner'] = state.winner if not done: gameData['turn'] += 1 # End return gameData
def place_obj_by_index(self, index, x, y): o = None if index == game.OBJ['factory']: # Factory o = factory.Factory(x, y) self.factories.append(o) self.game_group.add(o) self.animatedsprites.append(o) if index == game.OBJ['cityhall']: # City Hall o = cityhall.CityHall(x, y) self.cityhalls.append(o) self.game_group.add(o) self.animatedsprites.append(o) elif index == game.OBJ['police']: # Police o = police.Police(x, y) self.game_group.add(o) self.animatedsprites.append(o) o.set_starting_dir(self.road_grid) elif index == game.OBJ['soldier']: # Soldier o = soldier.Soldier(x, y) self.game_group.add(o) self.animatedsprites.append(o) o.set_starting_dir(self.road_grid) elif index == game.OBJ['start']: #Starting tile o = starttile.StartTile(x, y) self.game_group.add(o) self.animatedsprites.append(o) elif index == game.OBJ['celltower']: o = celltower.CellTower(x, y) self.game_group.add(o) self.animatedsprites.append(o) elif index == game.OBJ['tank']: o = tank.Tank(x, y) self.game_group.add(o) self.animatedsprites.append(o) self.tanks.append(o) o.set_starting_dir(self.road_grid) self.object_grid[y][x] = o
def __init__(self, screen): self.screen = screen self.ticks = pygame.time.get_ticks() pygame.mouse.set_visible(False) self.elapsed = 0 self.delay = 5 self.cur_ticks = pygame.time.get_ticks() self.keys = pygame.key.get_pressed() self.frames = 0 self.first_run = True #These need to be changeable through options menu eventually self.player_key_up = pygame.K_UP self.player_key_shoot = pygame.K_SPACE self.factory = factory.Factory(screen, ("player", "player_star.png"), ("bullet", "bullet.png"), ("mine", "brown_mine.png")) self.background = parallax.ParallaxSurface((640, 480)) self.background.add("images/background_far.png", 2) self.background.add("images/background_close.png", 1) self.explosions = [] self.player = player.Player() #Bullet stuffs (with pooling) self.bullets = [] self.bullet_delay = 300 self.bullet_cur_ticks = self.cur_ticks self.bullet_elapsed = 0 #Enemy creation self.enemy_group = pygame.sprite.Group() self.num_enemies = 0 while self.num_enemies < random.randint(20, 40): self.num_enemies += 1 self.enemy_group.add( mine.Mine(random.randint(960, 1560), random.randint(20, 460), random.randint(-7, -3), 0))
def from_file_name(cls, filename): match = cls.file_regex.match(filename) if len(match) < 5: logging.error(f"Cannot convert {filename} to FetchedFile") return None try: provider = factory.Factory().get_provider_cls(match[1])() except: logging.error(f"Cannot find provider {match[1]}") return None dataset = provider.get_dataset(match[2]) if not dataset: logging.error( f"Provider {provider.name} has no dataset {match[2]}") try: event_date = datetime.datetime.strptime(match[3], "%Y%m%d").date() created_at = datetime.datetime.strptime(match[4], "%Y%m%d%H%M%S") except: logging.error(f"Cannot get timestamps from {filename}") return None return cls(provider, dataset, event_date, created_at)
def __init__(self, x, y, speed_x, speed_y): pygame.sprite.Sprite.__init__(self) self.image_file = "mine" #Get these from xml self.image_size = (40, 40) self.frames = 2 self.speed_x = speed_x self.speed_y = speed_y #Probably shouldn't touch these self.img_list = [] self.load_images() self.image = self.img_list[0] self.rect = self.image.get_rect() self.screen = factory.Factory().get_screen() self.screenRect = self.screen.get_rect() self.on_screen = False self.cur_ticks = pygame.time.get_ticks() self.delay = 0 self.index = 0 self.x = x self.y = y
from prettytable import PrettyTable import factory import neh import read x = read.Reader() y = neh.Neh() z = factory.Factory() neh_sequence = [] neh_c_max = 0 neh_time = 0 johnson_sequence = [] johnson_c_max = 0 johnson_time = 0 list_of_files = [ "ta000.txt", "ta001.txt", "ta002.txt", "ta004.txt", "ta003.txt" ] t = PrettyTable(['NEH C_max', 'Johnsons C_max', 'NEH Time', 'Johnsons Time']) for file in list_of_files: x.read(file) neh_sequence, neh_c_max, neh_time = y.sum_times(x.my_data, x.cols, x.rows) johnson_sequence, johnson_c_max, johnson_time = z.johnson( x.my_data, x.cols, x.rows) t.add_row([neh_c_max, johnson_c_max, neh_time, johnson_time]) print(t)
# the python script import factory factoryObj = factory.Factory() person = factoryObj.getPerson('Visakh', 'male') person.getGender()
break # No more collections while manager.copyState().GMState == manager.GMStates['resolve']: if engine.update(): # Finish the resolution step done = True break # Game is over, time to collect data # Collect winnerData state = manager.copyState() winner = state.winner # increase count of the most recent winner if winner in data: data[winner] += 1 else: data[winner] = 0 print(data) # Runtime bit if __name__ == "__main__": # Do the parsering args = parser.parse_args() # Do the other parsering margs = main.parser.parse_args( ['-c', args.config, '--headless', '-l', '0']) # Factorize the factory fact = factory.Factory(margs) # Launch the run run(args.cycles, fact)
import factory from song import Song import instructions import re from os import system, name def clear_screen(): if name == 'nt': _ = system('cls') else: _ = system('clear') chord_factory = factory.Factory() song = Song(chord_factory) #chord factory object is being injected into song clear_screen() print(str(instructions.instructions)) while True: user_song_input = input( "\nEnter a chord progression (Q to Quit; I for instructions): ") if re.search(r'Q', user_song_input, re.I): break if re.match(r'\s*I', user_song_input, re.I): clear_screen() print(str(instructions.instructions)) continue
import factory fac = factory.Factory('config.json') fac.print()
def getDB(self): """ @return DB connector instance """ return factory.Factory().getDB()
def setUp(self): self.factory = factory.Factory({ "x": lambda: [1, 2, 3], "y": lambda: [4, 5, 6], })
for note in state.notes: for i in range(0, 8): index = note + i * 12 if index < len(semitones) - 1: bins += [index] if len(bins) > 0: power = 0.0 for index in bins: power += semitones[index] total_power = 0.0 for i in range(min(bins), max(bins)): total_power += semitones[i] return 1 - power / total_power else: return 0.8 def post_process(self, costs): logging.log(str(costs[:, 0])) logging.log(str(costs[:, 1])) pass #for t in range(0,np.size(costs,0)-1): #for i in range(0, np.size(costs,1)): #costs[t,i] = costs[t+1,i] - costs[t,i] factory = factory.Factory({ "poisson": lambda: PoissonLikelihoodProcessor(), "spectra": lambda: SpectragramLikelihoodProcessor(), "psd": lambda: PSDLikelihoodProcessor(), })
if y > 0: prob = V[t-u, y-1] else: prob = 0.0 prob += self.duration(u, score.states[y].duration * frame_rate) for v in range(0, u+1): prob -= costs[t-v, y] if prob >= max_prob: max_prob = prob max_u = u V[t][y] = max_prob path = np.zeros(T) t = T-1 i = N-1 path[t] = i while i > 0 and t>0: if V[t-1, i-1] > V[t-1, i]: i -= 1 t -= 1 path[t] = i return path def duration(self, u, d): prob = np.log(norm.sf(u-d, d/self.width)) return prob factory = factory.Factory({ "dtw": lambda:DTWPathFinder(), "hmm": lambda:HMMPathFinder(), "hsmm": lambda:HSMMPathFinder(), })
# The contents of this file are subject to the Mozilla Public License Version
dir=st.RIGHT) list_ops[name[num]] = (self._get_unit_id(f'C{j+1}T{i}'), self._get_unit_id(f'M{j}T{i}')) num += 1 # link conveyors to right-side machines for j in [2, 4]: for i in range(3, 5 + 1): conveyor = f'C{j}T{i}' # machine_belt = f'C{j}T{i}' machine = f'M{j+1}T{i}' # make it so you can't go back to the # conveyor, avoid congestion? # TODO: see if this restriction # is necessary in practice self._add_weighted_edge_unid(conveyor, machine, dir=st.RIGHT) return list_ops f = None g = None if __name__ == "__main__": import factory f = factory.Factory('io.csv') g = Graph(f)
def main(): Dlina = 500 # сколько пикселей экран Dlmatr = 1000 # сколько пикселей карта rasst = 100 # хуйня ебаная ненужная changed = False # надо чтоб проверять, сдвинулась ли карта, чтоб лишний раз не перерисовывать mm = mapmatrix(Dlmatr) # хуярим основную карту с биомами pm = politmm(Dlmatr) # политическую карту im = ironmm(Dlmatr) # карту с железом gm = grainmm(Dlmatr) # карту с зерном state1 = state.State('Pidronija', (100, 0, 0)) # тестовое государство 1 state2 = state.State('Lochonija', (0, 0, 100)) # 2 serf, worker, soldier, schoolers = stra.Existing_Strat( ) # назначаем страты населения bolvan = po.Pops( 15, 100, serf, 1, 100, 1.00, False ) # болванчик для того, чтоб создать город (он привязывается к населению) # но такое у меня чувство, что я эту механику уберу city = stl.Settlement(state1, (50, 60), mm, 'Govnovodsk', bolvan, schoolers) # тестовые города town = stl.Settlement(state1, (60, 70), mm, 'Pidrozhopsk', bolvan, schoolers) city1 = stl.Settlement(state1, (55, 60), mm, 'Muchosransk', bolvan, schoolers) town1 = stl.Settlement(state1, (65, 70), mm, 'Jobozadsk', bolvan, schoolers) stl.Settlement(state1, (50, 65), mm, 'Gorojobsk', bolvan, schoolers) stl.Settlement(state1, (70, 70), mm, 'Zernochujsk', bolvan, schoolers) grain, fertilizer, fish, whool, fabric, iron = gds.existing_goods( ) # назначаем производимые товары po.Pops(stl.Settlement.slovar['Zernochujsk'], 100, serf, 1, 100, 1) # назначаем попы - pop - экземпляр "единицы" населения po.Pops(stl.Settlement.slovar['Govnovodsk'], 100, serf, 1, 100, 1) po.Pops(stl.Settlement.slovar['Pidrozhopsk'], 100, serf, 1, 100, 1) po.Pops(stl.Settlement.slovar['Muchosransk'], 100, serf, 1, 100, 1) po.Pops(stl.Settlement.slovar['Jobozadsk'], 100, serf, 1, 100, 1) po.Pops(stl.Settlement.slovar['Gorojobsk'], 100, worker, 1, 100, 1) fct.Factory(stl.Settlement.slovar['Zernochujsk'], serf, grain, 200, 1, 1000, 0, True) # назначаем заводы fct.Factory(stl.Settlement.slovar['Govnovodsk'], serf, grain, 200, 1, 1000, 0, True) fct.Factory(stl.Settlement.slovar['Pidrozhopsk'], serf, fertilizer, 100, 1, 1000) fct.Factory(stl.Settlement.slovar['Muchosransk'], serf, fish, 200, 1, 1000, 0, True) fct.Factory(stl.Settlement.slovar['Jobozadsk'], serf, fertilizer, 100, 1, 1000) fct.Factory(stl.Settlement.slovar['Gorojobsk'], worker, iron, 100, 1, 1000) pg.init() sc = pg.display.set_mode((Dlina, Dlina)) background = pg.Surface((Dlmatr, Dlmatr)) background.fill((0, 0, 150)) politbg = pg.Surface((Dlmatr, Dlmatr), flags=pg.SRCALPHA) pbg = pg.Surface((Dlmatr, Dlmatr), flags=pg.SRCALPHA) pbg.set_alpha(100) for i in range(Dlmatr): for j in range(Dlmatr): if mm[i, j] == 1: background.set_at((i, j), (0, 90, 0)) elif mm[i, j] == 2: background.set_at((i, j), (150, 150, 150)) elif mm[i, j] == 3: background.set_at((i, j), (50, 50, 50)) elif mm[i, j] == 4: background.set_at((i, j), (0, 0, 0)) ironbackground = pg.Surface.copy(background) imm = np.array(mm, copy=True) for i in range(Dlmatr): for j in range(Dlmatr): if im[i, j] > 20: ironbackground.set_at((i, j), (im[i, j], 0, 255 - im[i, j])) imm[i, j] = im[i, j] bg = pg.Surface((Dlmatr, Dlmatr)) bg.fill((0, 0, 150)) for i in range(Dlmatr): for j in range(Dlmatr): for k in state.State.statenumberdict: if pm[i, j] == k: politbg.set_at((i, j), state.State.statenumberdict[k].colour) politbg.set_alpha(100) xb = 0 yb = 0 sc.blit(background, (xb, yb)) pg.display.update() xe, ye = xb, yb xg, yg = 0, 0 sur = background pribl = 1 f1 = pg.font.Font(None, 26) xt = 0 but1 = pg.Rect(50, 0, 50, 30) but2 = pg.Rect(150, 0, 50, 30) weekdistribution = 0 # все эти хуйни недельные - это для распределения нагрузки в течение дня/недели weekproduction = 0 # и так далее. тип утром распределились на работу, днём произвели товар, вечером потрах... скорректировали население weekconsumption = 0 weekbuying = 0 weekpricechanging = 0 weekcorrections = 0 mapmode = 0 pause = False while 1: """всё хуярится через вайл""" #print('СДЕЛАТЬ МИГРАЦИЮ И ПОИСК НОВОЙ РАБОТЫ, А ПОТОМ ЦЕНООБРАЗОВАНИЕ И БЛЯ ЕЩЁ ЧТО-ТО') #print('НЕ ПОКУПКА УСИЛИТЕЛЯ, ЕСЛИ КОНЕЧНАЯ ЦЕНА ПРОДУКТА СЛИШКОМ НИЗКАЯ') for i in pg.event.get(): """обрабатывается нажатие клавиш клавиатуры с pygame""" if i.type == pg.QUIT: exit() elif i.type == pg.KEYUP: if i.key == pg.K_BACKSPACE: pribl = pribl // 10 if pribl == 1: sur = background elif i.type == pg.MOUSEBUTTONUP: if i.button == 1: if pg.Rect.collidepoint(but1, pos): if mapmode != 1: mapmode = 1 else: mapmode = 0 if pg.Rect.collidepoint(but2, pos): if mapmode != 2: mapmode = 2 else: mapmode = 0 if i.button == 3: xg, yg = i.pos[0], i.pos[1] print(pos, xe, ye) pribl = pribl * 10 bg = pg.Surface((Dlina, Dlina)) risov(xe, xg, ye, yg, rasst, pribl, Dlina, mm, bg) sur = bg if xt // 100 - weekdistribution > 0: """распределение по работе попов""" print('distribution') weekdistribution += 1 for i in stl.Settlement.slovar: # по каждому городу в общем словаре городов for j in stl.Settlement.slovar[ i].pops: # для каждого попа в этом городе if stl.Settlement.slovar[i].pops[ j].unemployed == 1: # была тема, стала костылём, но хз пока, стоит ли убирать if stl.Settlement.slovar[i].pops[ j].num != 0: # ежели есть кто из работяг в попе stl.Settlement.summakubow( stl.Settlement.slovar[i], j ) # считаем нормировку для коэффициентов распределения попов по заводам for k in stl.Settlement.slovar[ i].factories: # распределяем по этим заводам, которые все находятся в этом городе if k.work_type == j.strata: # проверка, подходит ли завод типу попа. ибо священники на заводах не въёбывают fct.Factory.coef( stl.Settlement.slovar[i].factories[k] ) # считаем коэффициенты po.Pops.facsearch( j ) # непосредственно распределяем население попа в соответствии с коэффициентами if (xt - 25) // 100 - weekbuying > 0: """покупка всего и вся""" print('production') weekbuying += 1 treck = {} trecksell = {} for i in stl.Settlement.slovar: # по всем городам for j in stl.Settlement.slovar[ i].factories: # и заводам в этих городах fct.Factory.factbuy(j) # завод покупает нужные ресурсы fct.Factory.factboostbuy( j) # и бустеры (типа удобрения для С/Х) if stl.Settlement.slovar[i].factories[ j].type == 1: # эта херня на попозже. чтоб учесть, что крестьяне работают на себя а не барина #fct.Factory.serf_winter(stl.Settlement.slovar[i].factories[j]) print() for j in stl.Settlement.slovar[i].pops: # теперь для попов po.Pops.popbuy(j) # покупают жрачку и т.д. if (xt - 30) // 100 - weekpricechanging > 0: """корректировка цен""" print('price') weekpricechanging += 1 for i in stl.Settlement.slovar: for j in stl.Settlement.slovar[i].factories: if j.type: # отдаю деньги и жратву крестьянам. fct.Factory.givefoodmoney(j) if 1 in j.price_changed.values(): fct.Factory.pricechangeagain(j) elif 2 in j.price_changed.values(): fct.Factory.pricechangeagain(j) else: fct.Factory.pricechange(j) if (xt - 50) // 100 - weekproduction > 0: """производство""" print('production') weekproduction += 1 #print(grain.prices.values()) for i in stl.Settlement.slovar: for j in stl.Settlement.slovar[i].factories: if stl.Settlement.slovar[i].factories[ j].good.name == 'Grain': #print('GRAIN',stl.Settlement.slovar[i].factories[j].sell, stl.Settlement.slovar[i].factories[j].money) print() fct.Factory.create(stl.Settlement.slovar[i].factories[j]) if (xt - 75) // 100 - weekconsumption > 0: """потребление""" print('consumption') weekconsumption += 1 for i in stl.Settlement.slovar: for j in stl.Settlement.slovar[i].pops: if j.num != 0: po.Pops.consume_food(stl.Settlement.slovar[i].pops[j]) if (xt - 95) // 100 - weekcorrections > 0: """корректировка населения. смерть-рождение""" print('corrections') weekcorrections += 1 for i in stl.Settlement.slovar: for j in stl.Settlement.slovar[i].pops: po.Pops.popchange(j) stl.Settlement.stlpopul(stl.Settlement.slovar[i]) stl.Settlement.city_growth(stl.Settlement.slovar[i], mm) keys = pg.key.get_pressed( ) # при нажатии на кнопку меняется координата исходного полотна - сдвиг карты if keys[pg.K_LEFT]: xe += 10 changed = True if keys[pg.K_RIGHT]: xe -= 10 changed = True if keys[pg.K_UP]: ye += 10 changed = True if keys[pg.K_DOWN]: ye -= 10 changed = True if changed: if pribl > 1: if mapmode == 0: risov(xe, xg, ye, yg, rasst, pribl, Dlina, mm, bg) elif mapmode == 1: risov(xe, xg, ye, yg, rasst, pribl, Dlina, mm, bg) politrisov(xe, xg, ye, yg, rasst, pribl, Dlina, pm, pbg) elif mapmode == 2: risov(xe, xg, ye, yg, rasst, pribl, Dlina, imm, bg) changed = False pressed = pg.mouse.get_pressed() pos = pg.mouse.get_pos() if pressed[0]: xa, ya = pos xe = xe + (xa - xg) ye = ye + (ya - yg) if pribl > 1: sc.blit(sur, (0, 0)) if mapmode == 1: sc.blit(pbg, (0, 0)) #elif mapmode == 2: else: sc.blit(sur, (xe, ye)) if mapmode == 1: sc.blit(politbg, (xe, ye)) elif mapmode == 2: sc.blit(ironbackground, (xe, ye)) text1 = f1.render(str(xt // 10), 0, (0, 0, 0)) # кнопочки и другой текст sc.blit(text1, (0, 0)) text2 = f1.render('Political', 0, (0, 0, 0)) sc.blit(text2, (50, 0)) text3 = f1.render('Resource', 0, (0, 0, 0)) sc.blit(text3, (150, 0)) q1 = 0 for q in stl.Settlement.slovar: if pg.Rect.collidepoint(stl.Settlement.arry[q1][0], (pos[0] - xe, pos[1] - ye)): citytext = f1.render(stl.Settlement.slovar[q].name, 0, (0, 0, 0)) citytext1 = f1.render(str(stl.Settlement.slovar[q].population), 0, (0, 0, 0)) if (pos[1] - 50) < 0: minus = -1 else: minus = 1 sc.blit(citytext, (pos[0], pos[1] - 50 * minus)) sc.blit(citytext1, (pos[0], pos[1] - 30 * minus)) q1 += 1 pg.display.update() if pressed[0]: xg, yg = pos pg.time.delay(1) if not pause: xt += 1 # счётчик времени