def get(self): mbid=self.request.get('mbid') #data=memcache.get("albumpage %s"%mbid) data=None if data is None: album_name,x=album.get_album_mb(mbid) artist_name=x[0] artist_mbid=x[1] bg=image.get_image(artist_mbid,artist_name,'bg') tracks=track.get_tracks_mb(mbid) videos=[] for t in tracks: videos.append([t.video, (t.track_mbid,t.song)]) taskqueue.add(url='/worker', params={'f':'track.check_hottness("%s","%s")'%(t.track_mbid,t.hottness)}) logo=image.get_image(artist_mbid,artist_name,'artist') data={"artist":artist_name,"artist_mbid":artist_mbid,"album":album_name,"tracks":videos,"album_id":mbid,"bg":bg,"logo":logo} #memcache.set("albumpage %s"%mbid,data) self.render_album(**data)
def mouse_interaction_commands( self) -> List[Tuple[pygame.Surface, Callable, Text]]: return [ (img.get_image(self.empire).BARRACK, self.build_barrack, 'build barrack'), (img.get_image(self.empire).WALL, self.build_wall, 'build wall'), (img.get_image(self.empire).MINE, self.build_mine, 'build mine') ]
def no_interaction_commands( self) -> List[Tuple[pygame.Surface, Callable, Text]]: return [(img.get_image(self.empire).SCOUT, self.create_scout, 'create scout'), (img.get_image(self.empire).BUILDER, self.create_builder, 'create builder'), (img.get_image(self.empire).WARRIOR, self.create_warrior, 'create warrior'), (img.get_image().UPGRADE, self.upgrade, 'Upgrade'), (img.get_image().REMOVE, self.delete, 'Remove')]
def get_artist_albums(artist_mbid): logging.error("START OF Artist_ALBUMS") url=tools.get_url("musicbrainz","artist_mbid",artist_mbid) xml=tools.get_xml(url) artist_name= xml.getElementsByTagName("name")[0].childNodes[0].nodeValue logo=image.get_image(artist_mbid," ",'artist') background=image.get_image(artist_mbid,"artist_name",'bg') artist=Artists(artist_name=artist_name, artist_mbid=artist_mbid,disambiguation=" ",letter=artist_name[0], key=ndb.Key('Artists',artist_mbid)) artist.logo=logo artist.background=background artist_key=artist.put() logging.error(artist) releases=xml.getElementsByTagName("release-group") albums=[] for rg in releases: try: if rg.getElementsByTagName("primary-type")[0].childNodes[0].nodeValue != "Album": continue error=rg.getElementsByTagName("secondary-type")[0] continue except: try: if rg.attributes.get("type").value == "Album": album_mbid=rg.attributes.get("id").value b=Albums(key=ndb.Key(Albums,album_mbid,parent=ndb.Key(Artist,artist_mbid))) b.album_mbid=album_mbid b.album_name=rg.getElementsByTagName("title")[0].childNodes[0].nodeValue b.album_date=rg.getElementsByTagName("first-release-date")[0].childNodes[0].nodeValue b.album_image=image.get_image(album_mbid,b.album_name,key="album") albums.append(b) logging.error(b) except: continue albums.sort(key=lambda tup: tup.album_date) test=ndb.put_multi(albums) logging.error("END OF Artist_ALBUMS") return artist,albums
def get(self): mbid=self.request.get('mbid') data=memcache.get("bandpage %s"%mbid) if data is None: artist_mbid=mbid artist_data,album_data=artist.get_artist_albums(mbid) ancestor_key=ndb.Key(Artists,artist_mbid) logging.error(ancestor_key) #qry=Albums.query().ancestor(ancestor_key) #logging.error(qry.get()) for i in Albums.query().iter(): x=i.key logging.error(dir(x)) logging.error(x.parent()) similar=artist.get_similar(artist_mbid) similar_mbid=[] for s in similar: mbid=s[1] s_name=s[0] logo=image.get_image(mbid,s[0],'artist') similar_mbid.append((mbid,logo,s_name)) im=image.get_image(artist_data.artist_mbid," ",'artist') bg=image.get_image(artist_mbid,"artist_name",'bg') for a in album_data: pass #taskqueue.add(url='/worker', params={'f':'track.get_tracks_mb("%s",key="worker")'%a[0]}) data={"artist":artist_data,"albums":album_data,"similar":similar_mbid, "image":im,"bg":bg} logging.error(data) """ data={ artist=Artists albums=[Albums] similar=[Artists] images=[background, logo] """ #memcache.set("bandpage %s"%artist_mbid, data) self.render_band(**data)
def get(self): c=self.request.cookies artists=[] nologo=[] for i in c: if i[0:11]!='yourlastube': pass else: name,disambiguation=c[i].split(":::") name=name.replace("_"," ") logging.error(i) mbid=i[11:] im=image.get_image(mbid,name,key='artist') logging.error("DISAMBI") logging.error(im) if im != []: ar=[mbid,name,disambiguation,im] artists.append(ar) taskqueue.add(url='/worker', params={'f':'artist.get_artist_mb("%s")'%mbid}) taskqueue.add(url='/worker', params={'f':'album.get_albums_mb("%s")'%mbid}) else: ar=[mbid,name,disambiguation,im] nologo.append(ar) self.response.headers.add_header("Set-Cookie", "%s=deleted; Expires=Thu, 01-Jan-1970 00:00:00 GMT"%str(i)) if len(artists)==1: self.redirect("/artist?mbid=%s"%artists[0][0]) if len(artists)==0: artists=nologo self.render_disam(artists)
def on_btn_Recognize_Clicked(self): save_path = "./written_digit.jpg" self.__paintBoard.GetContentAsQImage().save(save_path) ans, pred = image.predict(model=self.model, image=image.get_image(save_path)) QMessageBox.question(self, u"识别结果", u"手写数字识别为:" + str(ans), QMessageBox.Yes)
def build_mine(self) -> mine.Mine: return mine.Mine(health=10, reload=60, cost=configs.MINE_COST, empire=self.empire, image=img.get_image(self.empire).MINE, size=configs.MINE_SIZE)
async def fact(ctx): embed = discord.Embed(title=":thinking: Monkey Fact:", description=random.choice(monkey_facts), colour=discord.Colour.dark_orange()) embed.set_footer(text='MonkeBot') queries = ["thinking monkey", "monkey thinking"] embed.set_image(url=get_image(queries, 10)) await ctx.send(embed=embed)
def __init__(self, empire, health: int, speed: int): Unit.__init__(self, empire=empire, health=health, speed=speed, size=configs.BUILDER_SIZE, image=img.get_image(empire).BUILDER, cost=configs.BUILDER_COST)
def img(image_id=None): if image_id == None: img_response = image.get_latest_image() image_id ='' else: img_response = image.get_image(image_id) return flask.render_template('image.html', image_id=image_id, image_name=img_response[1], image_description=img_response[2])
def image(request, board_id, marked=False, voted=False): bingo_board = get_object_or_404(BingoBoard, board_id=board_id, game__site=get_current_site(request)) response = HttpResponse(content_type="image/png") filename = _get_image_name(board_id, marked, voted) + ".png" response['Content-Disposition'] = 'filename={0}'.format(filename) im = image_module.get_image(request.get_host(), bingo_board, marked, voted) im.save(response, "png") return response
def on_open_file(self, event): wildcard = "All files(*.*)|*.*" dialog = wx.FileDialog(None, "select", os.getcwd(), "", wildcard) if dialog.ShowModal() == wx.ID_OK: self.file_name.SetValue(dialog.GetPath()) dialog.Destroy() self.image_wx = wx.Image(self.file_name.GetValue(), wx.BITMAP_TYPE_JPEG) self.image_pil = image.get_image(self.file_name.GetValue()) self.show()
def image(request, board_id, marked=False, voted=False): bingo_board = get_object_or_404( BingoBoard, board_id=board_id, game__site=get_current_site(request)) response = HttpResponse(content_type="image/png") filename = _get_image_name(board_id, marked, voted) + ".png" response['Content-Disposition'] = 'filename={0}'.format(filename) im = image_module.get_image(request.get_host(), bingo_board, marked, voted) im.save(response, "png") return response
def __init__(self, empire, health: int, speed: int, damage: int): AttackUnit.__init__(self, empire=empire, health=health, speed=speed, damage=damage, fight_distance=400, size=configs.SCOUT_SIZE, image=img.get_image(empire).SCOUT, cost=configs.SCOUT_COST)
def image_raw(image_id=None): if image_id == None: img_data = image.get_latest_image() else: img_data = image.get_image(image_id) response = flask.make_response(img_data[0]) # print img_data[3] response.headers['Content-Type'] = img_data[3] return response
def __init__(self, imageNames, screen): self.screen = screen # screen sur lequelle background est affiché self.images = [] for imageName in imageNames: currentImage = pygame.transform.scale(img.get_image(imageName), (1024, 768)) self.images.append(currentImage) self.lengthX = 0 # X de la largeur cumulé des images de images[] for image in self.images: self.lengthX += image.get_size()[0] self.firstImageX = 0 self.mooveSpeed = 3
def image_decode(uid): try: image = get_image(uid) data = Blend(image).decode() birr = [int(i) for i in data.split(',')[:-1]] str_birr = bytearray_to_str(birr) decoded_data = shuffle_text(str_birr, 1) if decoded_data.isalnum(): return decoded_data else: return None except: return None
def __init__(self, race, name: str = 'DefaultEmpireName', start_resources: int = 100): self.race = race self.name = name self.resources = start_resources self.icon = img.get_image(self).EMPIRE_ICON self.army = army.Army(empire=self) self.objects = pygame.sprite.Group() self.friends = pygame.sprite.Group() self.enemies = pygame.sprite.Group() self.cities = pygame.sprite.Group()
def test_attack(self): other_unit = warrior.ElfWarrior(empire=self.empire, cost=1, health=1, speed=1, damage=2, fight_distance=300, size=(100, 100), image=image.get_image( self.empire).WARRIOR) other_unit.rect.center = (1000, 50) self.warrior.attack_target.add(other_unit) self.warrior.update() self.assertEqual(self.warrior.rect.center, (60, 50))
def setUp(self) -> None: self.empire = empire.Empire(races.DWARFS) self.other_empire = empire.Empire(races.ELVES) Interface(self.empire, self.other_empire) Game(self.empire, self.other_empire) self.warrior = warrior.OrcWarrior(empire=self.empire, cost=10, health=11, speed=10, damage=20, fight_distance=300, size=(100, 100), image=image.get_image( self.empire).WARRIOR)
def set_city(self, name: str, cost: int = 50): for city_ in self.cities: if city_.name == name: raise EmpireError(f'City {name} has already exists in {self.name} cities') # If city is first (default), it is free. if len(self.cities) == 0: cost = 0 city_ = city.City(empire=self, name=name, cost=cost, image=img.get_image(self).CITY, size=(200, 200), health=30) self.cities.add(city_) return city_
def bot(): print("get mention") last_id = get_last_id() mentions = api.mentions_timeline(last_id['last_seen_id']) for mention in reversed(mentions): try: uname = '@' + str(mention.in_reply_to_screen_name) print('=============================================') print(mention.in_reply_to_status_id_str + " - " + uname) except TypeError as e: print("Unknown username", e) uname = "@uknown" # debug(mention._json) if (mention.in_reply_to_status_id): mainStatus = get_status(mention.in_reply_to_status_id_str) if (check(mention)): print(mainStatus.full_text) status = remove_mention( remove_media(mainStatus.full_text), len(mention.entities["user_mentions"]) - 2) # status=remove_media(mainStatus.full_text) img = json.loads(get_image()) desc = ' by ' + img['user']['username'] + \ ' from unsplash ' + img['links']['html'] print(desc) try: upload(img) generate(status, uname) media_ids = api.media_upload('temp.jpg') api.update_status(status='@' + mention.user.screen_name + desc, media_ids=[media_ids.media_id], in_reply_to_status_id=mention.id) except Exception as e: print("------error: " + str(e)) store_last_id(mention.id) else: print("No hashtag") store_last_id(mention.id) print('=============================================')
async def player_roll(ctx): # determine that the player who !rolled is actually playing roller_ID = format(ctx.author.id) for player in current_games[ctx.message.guild.id]['player_list']: if player.name == roller_ID and player.is_my_turn: #set that player as the current player print(f"{ctx.author}'s turn.") embed_var = discord.Embed(description=f"<@{player.name}>'s turn.") roll1 = pig_roll.pig_roll() roll2 = pig_roll.pig_roll() roll = score.scoring( roll1, roll2 ) # roll two pigs and return a name and a score for the roll image.get_image(roll1, roll2) file = discord.File('images/rollimage.png', filename='rollimage.png') embed_var.set_image(url='attachment://rollimage.png') # Player rolls a Pig Out if roll['name'] == 'Pig Out': player.is_my_turn = False # end the player's turn player.current_score = 0 # reset the player's score for that turn embed_var.add_field( name=f"{roll['name']}", value=f"Total score: {player.total_score} points") # move to the next player if current_games[ctx.message.guild.id]['current_player'] == ( len(current_games[ctx.message.guild.id]['player_list']) - 1): current_games[ctx.message.guild.id]['current_player'] = 0 else: current_games[ctx.message.guild.id]['current_player'] += 1 current_games[ctx.message.guild.id]['player_list'][ current_games[ctx.message.guild.id] ['current_player']].is_my_turn = True # set the next player's turn embed_var.add_field( name='Next player:', value= f"<@{current_games[ctx.message.guild.id]['player_list'][current_games[ctx.message.guild.id]['current_player']].name}>", inline=False) # Player rolls an Oinker elif roll['name'] == 'Oinker': player.is_my_turn = False # end the player's turn player.current_score = 0 # reset the player's score for that turn player.total_score = 0 # reset the player's score for the entire game embed_var.add_field( name=f"{roll['name']}", value=f"Total score: {player.total_score} points") # move to the next player if current_games[ctx.message.guild.id]['current_player'] == ( len(current_games[ctx.message.guild.id]['player_list']) - 1): current_games[ctx.message.guild.id]['current_player'] = 0 else: current_games[ctx.message.guild.id]['current_player'] += 1 current_games[ctx.message.guild.id]['player_list'][ current_games[ctx.message.guild.id] ['current_player']].is_my_turn = True # set the next player's turn embed_var.add_field( name='Next player:', value= f"<@{current_games[ctx.message.guild.id]['player_list'][current_games[ctx.message.guild.id]['current_player']].name}>", inline=False) # Player rolls anything else else: player.current_score += roll[ 'score'] # add the score from the roll embed_var.add_field( name=f"{roll['name']} [+ {roll['score']} points]", value= f"Score this turn: {player.current_score} points\nTotal score: {player.total_score + player.current_score} points" ) if player.current_score + player.total_score >= 100: # check if player has won the game embed_var.add_field( name='You win!', value='Use **!huckthehogs** to play again.', inline=False) # reset game variables current_games[ctx.message.guild.id]['current_player'] = 0 current_games[ctx.message.guild.id]['joinable'] = False current_games[ctx.message.guild.id]['game_init'] = False current_games[ctx.message.guild.id]['game_on'] = False current_games[ctx.message.guild.id]['player_list'] = [] else: embed_var.add_field( name='\u200b', # prompt the player for their next action value= 'Use **!roll** to roll again or **!pass** to move to the next player.', inline=False) await ctx.send(file=file, embed=embed_var)
import cv2 import sys import datetime import time from image import get_image, ImageCaptured from circular_buffer import Circular if __name__ == "__main__": storage = sys.argv[1] port = sys.argv[2] ramp_frames = sys.argv[3] camera = cv2.VideoCapture(int(port)) circular = Circular() while (cv2.waitKey(1) & 0xFF != ord('q')): time.sleep(1) image_data = get_image(camera, int(ramp_frames)) time_now = time.time() image = ImageCaptured(image_data, time_now, storage) image.filename_from_time() image.save_image() circular.check_and_clean()
def build_wall(self) -> wall.Wall: return wall.Wall(health=10, cost=configs.WALL_COST, empire=self.empire, image=img.get_image(self.empire).WALL, size=configs.WALL_SIZE)
def build_barrack(self) -> barrack.Barrack: return barrack.DwarfsBarrack(health=30, cost=configs.BARRACK_COST, empire=self.empire, image=img.get_image(self.empire).BARRACK, size=configs.BARRACK_SIZE)
import torch import image IMAGE_PATH = "./digit.jpg" model = torch.load("./model.pkl") ans, pred = image.predict(model=model, image=image.get_image(image_path=IMAGE_PATH)) print(ans)
for obj in Game().objects: if obj in Game().objects: obj.update() # Make place of camera location visible. SCREEN.blit(Map().image, (-Interface().camera.x, -Interface().camera.y)) place_objects_on_display() Interface().draw_interface(SCREEN) # Show screen. pygame.display.update() # Cap the framerate. CLOCK.tick(50) if __name__ == '__main__': # pygame initialization. pygame.init() tmp = pygame.display.set_mode(configs.SCR_SIZE) pygame.display.set_caption("the Lord of the Strategy") pygame.display.set_icon(img.get_image().ICON) if not pygame.font.get_init(): raise SystemExit("Fonts are out-of-service") # Global variables initilization. SCREEN = tmp CLOCK = pygame.time.Clock() play_game()
async def pog(ctx): queries = [ "spider monkey mouth open", "monkey open mouth", "howler monkey mouth" ] link = get_image(queries, 10) await ctx.send(link)
async def angry(ctx): queries = ["angry monkey", "mad monkey"] link = get_image(queries, 10) await ctx.send(link)
def convert(dicom_data_sets, dtype): """ Convert a list of dicom data sets into Nfiti :param dicom_data_sets: list of dicom data sets to convert :param dtype: type to use when coverting images """ nifti_data = [] stacks = get_stacks(dicom_data_sets) logger.info( "Found {} stack{}".format(len(stacks), "s" if len(stacks) > 1 else "")) # Set up progress information stacks_count = {} stacks_converted = {} for key, data_sets_frame_idx in stacks.items(): series_instance_uid = data_sets_frame_idx[0][0].as_string( odil.registry.SeriesInstanceUID)[0] stacks_count.setdefault(series_instance_uid, 0) stacks_count[series_instance_uid] += 1 stacks_converted[series_instance_uid] = 0 def get_element(data_set, tag): value = odil_getter._default_getter(data_set, tag) return value[0] if value is not None else None meta_data_cache = {} pixel_data_cache = {} # Try to preserve the original stacks order (multi-frame) stacks = sorted( stacks.items(), key=lambda item: numpy.min([x[1] for x in item[1]]) ) for stack_index, (keys, data_sets_frame_idx) in enumerate(stacks): data_set = data_sets_frame_idx[0][0] study = [ get_element(data_set, odil.registry.StudyID), get_element(data_set, odil.registry.StudyDescription)] study = [unicode(x) for x in study if x is not None] series = [ get_element(data_set, odil.registry.SeriesNumber), get_element(data_set, odil.registry.SeriesDescription)] series = [unicode(x) for x in series if x is not None] series_instance_uid = data_set.as_string( odil.registry.SeriesInstanceUID)[0] if stacks_count[series_instance_uid] > 1: stack_info = " (stack {}/{})".format( 1 + stacks_converted[series_instance_uid], stacks_count[series_instance_uid]) else: stack_info = "" if stack_index == 0: logger.info( u"Converting {} / {}".format( "-".join(study), "-".join(series))) if stack_info: logger.debug( u"Converting {} / {}{}".format( "-".join(study), "-".join(series), stack_info)) stacks_converted[series_instance_uid] += 1 sort(keys, data_sets_frame_idx) nifti_img = image.get_image( data_sets_frame_idx, dtype, pixel_data_cache) nifti_meta_data = meta_data.get_meta_data( data_sets_frame_idx, meta_data_cache) nifti_data.append((nifti_img, nifti_meta_data)) # Try to preserve the original stacks order (single-frame) nifti_data.sort( key=lambda x: numpy.ravel(x[1].get("InstanceNumber", [None])).min()) for nifti_img, nifti_meta_data in nifti_data: meta_data.cleanup(nifti_meta_data) series = {} for nitfi_img, nifti_meta_data in nifti_data: series.setdefault(nifti_meta_data["SeriesInstanceUID"][0], []).append( (nitfi_img, nifti_meta_data)) merged_stacks = [] for stacks in series.values(): # Use OrderedDict to keep the relative order mergeable = collections.OrderedDict() for nifti_img, nifti_meta_data in stacks: geometry = nifti_img.shape + \ tuple(nifti_img.qform.ravel().tolist()) dt = nifti_img.datatype mergeable.setdefault((geometry, dt), []).append( (nifti_img, nifti_meta_data)) for _, stack in mergeable.items(): if len(stack) > 1: logger.info( "Merging {} stack{}".format( len(stack), "s" if len(stack) > 1 else "")) merged = merge_images_and_meta_data(stack) merged_stacks.append(merged) else: merged_stacks.append(stack[0]) return merged_stacks
def add_fleet(self, fleet): nm = '' if 'arrival_turn' in fleet: nm = '[%d] '%(fleet['arrival_turn'] - store.max_turn(),) nm += fleet['name'] cp = wx.CollapsiblePane(self, label=nm, style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE) self.sizer.Add(cp) pane = cp.GetPane() u = store.get_user(fleet['user_id']) if u: owner_name = u['name'] else: owner_name = '<unknown>' sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(wx.StaticText(pane, label='owner: %s'%(owner_name,)), 1, wx.EXPAND) speed, rng = store.get_fleet_speed_range(fleet['fleet_id']) if speed and rng: sizer.Add(wx.StaticText(pane, label='%0.2f / %0.2f'%(speed, rng)), 1, wx.EXPAND) #can we contrl the fleet? is_controlled = 'login' in u and u['login'] in config.users if is_controlled and rng >= 1 and (not 'in_transit' in fleet or fleet['in_transit']==0): jump_button = wx.ToggleButton(pane, label='jump') jump_button.fleet_id = fleet['fleet_id'] sizer.Add(jump_button, 1, wx.EXPAND) self.Bind(wx.EVT_TOGGLEBUTTON, self.on_jump, jump_button) #else: # print 'user %s not controllable'%(u,) for unit in store.get_fleet_units(fleet['fleet_id']): hbox = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(hbox, 1, wx.EXPAND) proto = store.get_object('proto', {'proto_id':unit['proto_id']}) if not proto: print 'Prototype not found for %s'%(unit,) continue obj_carp = int(unit['proto_id']), int(proto['carapace']), int(proto['color']) if is_controlled: planet = store.get_object('planet', {'x':self.coord[0], 'y':self.coord[1]}) inhabited = False if planet and planet['user_id'] and int(planet['user_id']) > 0: inhabited = True # get unit actions ( colony, kill-people ) if not inhabited: for action_type in [action.Action.COLONY_COLONISE, action.Action.ARC_COLONISE, action.Action.OUTPOST_COLONISE]: action_colonize = store.get_object('proto_action', {'proto_id':proto['proto_id'], 'proto_action_id':action_type}) if action_colonize: c_action = store.get_object('action', {'unit_id':unit['unit_id']}) if c_action: # already colonizing cancel_button = wx.Button(pane, label='Cancel colonize %s'%(action.get_colony_population(action_type))) cancel_button.cancel_action = u['user_id'], unit['unit_id'], c_action['cancel_id'] self.Bind(wx.EVT_BUTTON, self.on_cancel_action, cancel_button) sizer.Add( cancel_button , 1, wx.EXPAND ) else: colonize_button = wx.Button(pane, label='Colonize %s'%(action.get_colony_population(action_type))) colonize_button.action = action_type, unit['unit_id'], fleet['fleet_id'], self.coord, u['user_id'] self.Bind(wx.EVT_BUTTON, self.on_store_action, colonize_button) sizer.Add( colonize_button , 1, wx.EXPAND ) if inhabited and planet['user_id'] != u['user_id']: #TODO: check if our mult, or ally, and notify user about it action_kill_people = store.get_object('proto_action', {'proto_id':proto['proto_id'], 'proto_action_id':action.Action.KILL_PEOPLE}) if action_kill_people: c_action = store.get_object('action', {'unit_id':unit['unit_id']}) if c_action: # already colonizing cancel_button = wx.Button(pane, label='Cancel kill people') cancel_button.cancel_action = u['user_id'], unit['unit_id'], c_action['cancel_id'] self.Bind(wx.EVT_BUTTON, self.on_cancel_action, cancel_button) sizer.Add( cancel_button , 1, wx.EXPAND ) else: colonize_button = wx.Button(pane, label='Kill people') colonize_button.action = action.Action.KILL_PEOPLE, unit['unit_id'], fleet['fleet_id'], self.coord, u['user_id'] self.Bind(wx.EVT_BUTTON, self.on_store_action, colonize_button) sizer.Add( colonize_button , 1, wx.EXPAND ) img = image.get_image( int(unit['proto_id']), int(proto['carapace']), int(proto['color']) ) if img: bitmap = wx.StaticBitmap(pane) bitmap.SetBitmap(img) hbox.Add(bitmap, 1, wx.EXPAND) #else: # print 'image not found for unit %s, bc %s, carp %s, color %s'%(unit['unit_id'], int(unit['proto_id']), int(proto['carapace']), int(proto['color']) ) name = proto['name'] if not name: name = get_unit_name(int(proto['carapace'])) hbox.Add(wx.StaticText(pane, label=name), 1, wx.EXPAND) border = wx.BoxSizer() border.Add(sizer, 1, wx.EXPAND|wx.ALL) pane.SetSizer(border) self.sizer.Layout() self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged, cp) cp.Expand() cp.Bind(wx.EVT_LEFT_DOWN, self.onFleetSelect) self.fleets[cp] = fleet
from text import reverse_hebrew, annoying_text from image import get_image, resize_and_caption import time if __name__ == '__main__': filename = 'output/{}.jpg'.format(int(time.time())) get_image(filename) resize_and_caption(filename, reverse_hebrew(annoying_text(time.localtime())), filename)
def create_vm_from_image(token, flavor): if ide.validate_token(token): image = img.get_image(flavor) cpt.create_vm(image)
from image import get_image from generate import gen from encrypt import encrypt_blob from cloud_deploy import dep import cv2 # get the secret image and save it images = get_image() cv2.imwrite("gallery/c_im.jpg", images[0]) # generate the private and public key gen() # loading public key fd = open("public_key.pem", "rb") public_key = fd.read() fd.close() #loading image fd = open("gallery/c_im.jpg", "rb") unencrypted_blob = fd.read() fd.close() # encryption encrypted_blob = encrypt_blob(unencrypted_blob, public_key) #storing encrypted data fd = open("gallery/encrypted_img.jpg", "wb") fd.write(encrypted_blob) fd.close()
def default_commands(self) -> List[Tuple[pygame.Surface, Callable, Text]]: """ Returns list of default commands. Every game object has default commands: `remove` and `upgrade`. """ return [(img.get_image().UPGRADE, self.upgrade, 'Upgrade'), (img.get_image().REMOVE, self.delete, 'Remove')]
def play_game(): # pygame initialization start pygame.init() screen = pygame.display.set_mode(configs.SCR_SIZE) pygame.display.set_caption("the Lord of the Strategy") icon_surf = img.get_image().ICON pygame.display.set_icon(icon_surf) clock = pygame.time.Clock() if not pygame.font.get_init(): raise SystemExit("Fonts are out-of-service") # pygame initialization finish # game objects initialization start player_empire = empire.Empire(user_configs.EMPIRE_RACE, name=user_configs.EMPIRE_NAME, start_resources=1000) enemy_empire = empire.Empire(races.DWARFS, name='Durden', start_resources=1000) game = Game(player_empire, enemy_empire) interface = Interface(player_empire, enemy_empire) player_empire.set_city("Nevborn") player_default_city = player_empire.get_city("Nevborn") player_default_city.rect.x = 500 player_default_city.rect.centery = world_map.Map().rect.centery enemy_empire.set_city("Nuhen") enemy_default_city = enemy_empire.get_city("Nuhen") enemy_default_city.rect.right = world_map.Map().rect.right - 700 enemy_default_city.rect.centery = world_map.Map().rect.centery StressAI(enemy_empire) # game objects initialization start rendered = None while True: mouse_pressed = False for event in pygame.event.get(): if event.type == pygame.QUIT or \ event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: mouse_pressed = True key = pygame.key.get_pressed() mouse_pos = pygame.mouse.get_pos() if mouse_pressed: handled = False # check if any of interface windows can handle click if interface.handle_interface_click(mouse_pos): handled = True else: for obj in game.objects: # check if any of game objects can handle click if obj.handle_click(get_global_mouse_pos(mouse_pos)): handled = True if not handled: interface.handle_empty_click(mouse_pos) # AI is singleton, which has initialized before StressAI().play_step() # If any of empires is out of cities, finish the game if not player_empire.alive() or not enemy_empire.alive(): return interface.move_view(key, mouse_pos) # place objects on map if rendered is not None: game.objects.clear(world_map.Map().image, clear_callback) game.objects.update() rendered = game.objects.draw(world_map.Map().image) interface.draw_interface(screen) # show screen pygame.display.flip() # cap the framerate clock.tick(50)