def __init__(self, x, y, image_path): Entity.__init__(self) self.image = pygame.image.load(image_path+"/plate.png") self.image = pygame.transform.scale(self.image, (32, 32)) self.image.convert() self.rect = Rect(x, y, 32, 32)
def __init__(self, x, y, image_path): Entity.__init__(self) self.image = pygame.image.load(image_path+"/ground.png") self.image = pygame.transform.scale(self.image, (64*6, 64)) self.image.convert() self.rect = Rect(x, y, 64*6, 64)
def __init__(self, a): Entity.__init__(self, a) self.name = 'MouseEntity' self.mouse_pos = Vect2([0.0, 0.0]) self.origImage = pygame.image.load('data/mousePlayer.png') self.image = self.origImage self.imgState = 0 self.image1 = pygame.image.load('data/mousePlayer_1.png') self.image2 = pygame.image.load('data/mousePlayer_2.png') self.image3 = pygame.image.load('data/mousePlayer_3.png') self.grabsound = pygame.mixer.Sound('data/grab.wav') self.dropsound = pygame.mixer.Sound('data/drop.wav') self.image = self.origImage self.radius = self.image.get_rect().width/2 print self.radius self.rotate = 0 self.radius = float(self.image.get_width()) / 2.0 self.maxSpeed = 100 self.grabbing = False self.grabDist = 60 # pixel distance within which you can grab something self.grabbedEntity = None
def _Render(self, renderWindow, windowView): """Here we render the contained entities onto the screen. (This happens once per program loop!)""" Entity._Render(self, renderWindow, windowView) for indx in xrange(len(self._pqEntities)): self._pqEntities[indx]._Render(renderWindow, windowView)
def __init__(self): Entity.__init__(self) self.type = 0 self.rage = False self.health = 1 self.dead = False self.facingRight = True
def update(self,t=0): Entity.update(self,t) #print t, self.rect.topleft, self._speed if self.jumping: # if the jumping flag is true, # call the jump function self.setSpeed('x',-14.0) self.jumping = False else: self.can_jump = True self.setSpeed('x',self._speed[1]+t/50.0) if self.rect.top >= 230: self.setSpeed('x',0.0) # limit duration of post damage invincibility (2500 ms) if self._invincible == True: if self._invincible_time < 2500: self._invincible_time += t if ((self._invincible_time /100)%2) == 0: self.image = self._invisible_pic else: self.image = self._images[0] else: self._invincible = False self._invincible_time = 0
def __init__(self): Entity.__init__(self) self.lastfm = pylast.LastFMNetwork(api_key=params.LASTFM_API_KEY, api_secret=params.LASTFM_API_SECRET, username=USERNAME, password_hash=pylast.md5(PASSWORD)) config.ECHO_NEST_API_KEY = params.ECHONEST_API_KEY
def __init__(self, id, name, numberOfUnits=1, parentBatch=None, parentBatchName=None, parentBatchId=None, remainingProcessingTime=0, currentStation=None, unitsToProcess=0,receiver=None,**kw): Entity.__init__(self, name=name, id=id, remainingProcessingTime=remainingProcessingTime, currentStation=currentStation) self.numberOfUnits=int(numberOfUnits) self.parentBatch=parentBatch self.unitsToProcess=int(float(unitsToProcess)) # if the parent batch was not given find it or create it if not self.parentBatch: # check if the parent batch is already created. If not, then create it batch=None from Batch import Batch from Globals import G for b in G.EntityList: if b.id==parentBatchId: batch=b if batch: #if the parent batch was found add the number of units of current sub-batch batch.numberOfUnits+=self.numberOfUnits else: #if the parent batch was not found create it batch=Batch(parentBatchId,parentBatchName,numberOfUnits) G.EntityList.append(batch) self.parentBatch=batch self.batchId=self.parentBatch.id import Globals self.receiver=Globals.findObjectById(receiver) self.parentBatch.subBatchList.append(self)
def update(self,t=0): Entity.update(self,t) #print t, self.rect.topleft, self._speed if self.jumping: # if the jumping flag is true, # call the jump function self.setSpeed('x',-14.0) self.jumping = False else: self.setSpeed('x',self._speed[1]+t/50.0) if self.rect.top >= 230: # if you hit the top, reset the vel so it self.setSpeed('x',0.0) # doesn't get stuck up at the top # limit duration of post damage invincibility (2500 ms) if self._invincible_time > 0: self._invincible_time -= t # On average, turn invisible for every other frame if ((self._invincible_time /100)%2) == 0: self.image = self._invisible_pic else: self.image = self._images[0] if self.rect.left < 0: self.rect.left = 0 elif self.rect.right > 930: self.rect.right = 930
def __init__(self, x, y, imageName=None, colorkey=None, coordsName=None, numImages=None, magicNumbers=(0, 0, 0, 0, 0, 0, 0, 0), director=None, *args): Entity.__init__(self, x, y, imageName, colorkey, coordsName, numImages) self.director = None self.speedX = 0 self.speedY = 0 self.controller = None self.equippedWpn = None self.attacking = False self.atk_delay_reset = 1.0 # Character dependent delay time self.atk_delay = self.atk_delay_reset # Starts with cooldown. Trust me, it's better. self.hp = 40 self.atk = 10 # To what point is the character trying to attack? Useful for ranged # weapons. self.atkX = 0 self.atkY = 0 self.just_attacked = False if not imageName: self.rect = pygame.Rect(x, y, 15, 25) # Needed for a better weapon placement self.magicNumbers = magicNumbers self.atk_speed = PLAYER_ATTACK_SPEED
def __init__(self, id): """ Arguments: o id - int """ self.level="M" Entity.__init__(self, id)
def entity_data(request): """ """ site = request.matchdict['code'] claims, site = verify_access(request, site=site) e = Entity(request) summnote, fullnote = e.data() return { 'summnote': summnote, 'fullnote': fullnote }
def __init__(self, x, y): Entity.__init__(self) self.image = pygame.image.load("files/Platforms/Bad_Platform.png") self.image = pygame.transform.scale(self.image, (128, 32)) self.image.convert() self.rect = Rect(x, y+10, 128, 32) #Платформата се извежда "вкопана"
def update(*args): self = args[0] width = args[1] height = args[2] Entity.update(self, width, height) self.animate() self.changed = False
def __init__(self, x, y): Entity.__init__(self, x, y, "explosion.png", -1, "coordExplosion.txt", [25]) self.rect.centerx = x + 2 self.rect.bottom = y + 12 sound = load_sound("explosion.wav") sound.set_volume(0.25) sound.play()
def tick(self, dt): Entity.tick(self, dt) if self.thrusting: thurst() else: resetThrust() self.currFireRate = self.currFireRate - 1 return False
def onLand(self): """ Called when the player lands on ground of some sort """ Entity.onLand(self) self.isJumping = False self.isFlying = False self.flyCounter = 0
def __init__(self, pos, radius, numVertices): Entity.__init__(self, radius, pos) if numVertices < 3: numVertices = 3 self.numVertices = numVertices self.verts = [(0,0)]*numVertices self.recalcVerts()
def __init__(self, id=None, name=None): Entity.__init__(self,id=id,name = name) self.Res=Resource(self.capacity) #dimension data self.width=2.0 self.height=2.0 self.lenght=2.0
def __init__(self, pos): Entity.__init__(self, pos, 0.5, 2) self.stats = Stats() self.input = InputController(self) self.motion = MotionController(self) self.action = ActionController(self) self.color = 0xAA0077 self.net = -1
def __init__(self, id, name, numberOfUnits=1, currentStation=None, remainingProcessingTime=0, unitsToProcess=0, **kw): Entity.__init__(self, name=name, id=id, remainingProcessingTime=remainingProcessingTime, currentStation=currentStation) self.numberOfUnits=int(numberOfUnits) self.numberOfSubBatches=1 #integer that shows in how many sub batches is the batch broken self.subBatchList=[] #list that contains the sub-batches that this batch has been broken into self.unitsToProcess=int(float(unitsToProcess))
def update(self,t=0): Entity.update(self,t) if self.rect.right < 0: self._wrap_count += 2 self.rect.left = 1024 self.rect.top = 300*random() self.setSpeed(-8.0*random()-10.0-self._wrap_count*random(),0.0) print self._speed
def entity_build(request): """ """ site = request.matchdict['code'] eid = request.matchdict['id'] claims, site = verify_access(request, site=site) e = Entity(request) e.build() return { 'started': True, 'name': site['name'], 'entity': eid }
def Assemble_Text_Box(sEntityName, sEntityType, iDrawPriority, attribDict): """This assembles a box with text in it!""" entity = Entity(sEntityName, sEntityType, iDrawPriority, {}) #The first argument represents the ID of the component with respect to its type (multiple components of a single type need to have different IDs.) entity._Add_Component(getClass("Box")({'componentID': '0', 'x': attribDict['x'], 'y': attribDict['y'], 'width': attribDict['width'], 'height': attribDict['height']})) entity._Add_Component(getClass("Text_Line")({'componentID': "0", 'x': attribDict['x'], 'y': attribDict['y'], 'width': attribDict['width'], 'height': attribDict['height'], 'text': attribDict['text'], 'font': attribDict["Font"]["Asman"]})) return entity
def __init__(self): Entity.__init__(self) self.weapon = Pistol() self.playerCharacter = 0 self.onGround = True self.facingRight = True self.jumping= False self.jumpStart = 0 self.keysDown = []
def initialize(self): Entity.initialize(self) self.shouldMove=False from Globals import G # find the project that the capacity entity is part of for project in G.CapacityProjectList: if project.id==self.capacityProjectId: self.capacityProject=project break
def __init__(self, id=None, name=None, capacityProjectId=None, requiredCapacity=10, priority=0, dueDate=0, orderDate=0, currentStation=None, isCritical=False, **kw): Entity.__init__(self, id, name, priority, dueDate, orderDate, isCritical, currentStation=currentStation) self.capacityProjectId=capacityProjectId # the project id hat the capacity Entity is part of self.capacityProject=None # the project that the capacity Entity is part of. It is defined in initialize self.requiredCapacity=requiredCapacity # the capacity that the capacity entity requires from the following station self.shouldMove=False from Globals import G G.CapacityEntityList.append(self)
def update(self, session): if self.impactDestroy: collisions = Entity.update(self, session.worlds[session.activeWorld]) for i in collisions: if i: session.worlds[session.activeWorld].projectiles.remove(self) return collisions else: return Entity.update(self, session.worlds[session.activeWorld])
def update(self, world): if self.impactDestroy: collisions = Entity.update(self, world) for i in collisions: if i: world.projectiles.remove(self) return collisions else: return Entity.update(self, world)
def __init__(self, r_name, r_id, x_off, y_off, theta_off): self.current_load = 0 self.firstLaserReading = [] self.treesLeft = True self.disableSideLaser = False Entity.__init__(self, r_name, r_id,x_off,y_off, theta_off)
def __init__(self, engine): self.engine = engine self.entity_list = [] self.screen = Entity() self.screen.x = 0 self.screen.y = 0 self.screen.width = self.engine.screen_width self.screen.height = self.engine.screen_height self.tracked_entity = None # View offset for the camera to facilitate scrolling # These are added to the x and y value of each entity when rendered # default white background self.background = QImage(self.screen.width, self.screen.height, QImage.Format_RGB32) self.background.fill(QColor(255, 255, 255))
def createHelmet(self): angle = self.rotation + 90 helmet = Entity( self.world, self.x + Utility.lengthDirXDegrees(self.sprite.height / 4, angle), self.y + Utility.lengthDirYDegrees(self.sprite.height / 4, angle), self.world.assetLoader.spaceguyDieHead, 0) helmet.hSpeed = Utility.lengthDirXDegrees(1, angle) helmet.vSpeed = Utility.lengthDirYDegrees(1, angle) helmet.rotationSpeed = 1 helmet.rotation = self.rotation self.world.addEntity(helmet)
def testSample(self): testSystem = TestSystem() world = World([testSystem], []) testEntity = Entity() testEntity.id = 0 world.entities.append(testEntity) testEntity2 = Entity() testEntity2.id = "This id should print too" world.entities.append(testEntity2) world.processSystems()
def getGroups(self): # получаю все названия групп groupsite = "https://uspu.ru/education/eios/schedule" grouplist = requests.get(groupsite) soup = BS(grouplist.content, 'html.parser') groups = soup.find('select', { 'name': 'group_name' }).findAll('option', value=True) listGroups = [] for group in groups: url = 'https://uspu.ru/education/eios/schedule/?group_name=%s' % ( group.text) name = group.text entity = Entity(name, url, 'group', None) listGroups.append(entity) return listGroups
def firing(self, isFiring): """ Starts/Stops the player's weapon. """ self.isFiring = isFiring if self.fireDelay > 0: self.fireDelay -= 1 if self.isFiring: if self.fireDelay <= 0: self.fireDelay = Player.FireDelay projectile = Entity( ObjectType.ObjectTypes['laser'], position=[ self.position[0] + (-5 if self.flipped else 5), self.position[1] + 5 ], velocity=[-15 if self.flipped else 15, 0], acceleration=[0, -Game.Game.Gravity], projectile=True)
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, player: Entity, ) -> GameMap: """Generate a new dungeon map""" dungeon = GameMap(map_width, map_height) rooms: List[RectangularRoom] = [] for _ in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # "RectangularRoom" class makes rectangles easier to work with new_room = RectangularRoom(x, y, room_width, room_height) # Run through the other rooms and see if they intersect with this one if any(new_room.intersects(other_room) for other_room in rooms): continue # this room intersects, so go to the next attempt # If there are no intersections, then the room is valid # Dig out this room's inner area dungeon.tiles[new_room.inner] = Tile_Types.floor if len(rooms) == 0: # The first room, where the player starts player.x, player.y = new_room.center else: # All rooms after the first. # Dig out a tunnel between this room and the previous one for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = Tile_Types.floor # Finally, append the new room to the list rooms.append(new_room) return dungeon
def execute(self, queue): controller = Controller.get_controller() if self.busy_until > controller.time: #print("Ativivity %s is buisy at time %d" % (self.name, controller.time)) controller.register_event( Event( self.busy_until, self, queue) ) return entity = queue.get_entity() delta = self.distribution(*self.parameters) * entity.get_kg() next_element = choice(self.connections, p=self.transitions) self.busy_until = controller.time + delta #print("Processing %.2f kg in %s at time %d until time %d" % (entity.get_kg(), self.name, controller.time, self.busy_until)) self.kg_processed += entity.get_kg() for next_element, probability in zip(self.connections, self.transitions): new_entity = Entity(entity.get_kg() * probability, entity.get_creation()) controller.register_event( Event(self.busy_until, next_element, new_entity) )
def averagePositions(entityList): positionList = [] for entity in entityList: positionList.append(entity.position) if(positionList): posXAvg = 0.0 posYAvg = 0.0 for position in positionList: posXAvg += position[0] posYAvg += position[1] posXAvg = posXAvg / len(positionList) posYAvg = posYAvg / len(positionList) averagePosition = [posXAvg, posYAvg] return [Entity(entityList[0].category, averagePosition)] else: return None
def getGroups(self): # получает списки групп listGroups = [] groupsite = "http://kml.vvsu.ru/map/getTimeTableInst.php" jsonGroups = requests.get(groupsite).json() for jsonInstitute in jsonGroups: jsonGroupInInstitutes = jsonInstitute['group'] for jsonGroup in jsonGroupInInstitutes: url = 'http://it.vvsu.ru/RTFReport/default.aspx?report=419210&Params=@pInstID=%d/;@pGroupID=%d' % ( int(jsonInstitute['id_inst']), int(jsonGroup['id'])) name = jsonGroup['name_group'] entity = Entity(name, url, 'group', None) listGroups.append(entity) return listGroups
def crawl(all_papers, max_count): while True: if len(all_papers) >= max_count: return try: page = requests.get(source_page) except requests.exceptions.Timeout: time.sleep(60) continue except requests.exceptions.RequestException as e: write_log('./error.log', e, datetime.now()) time.sleep(60) continue if page.status_code != 200: time.sleep(60) continue soup = BeautifulSoup(page.content, 'html.parser') res = soup.find_all( 'table', class_='table table-hover table-striped table-bordered') for r in res: #print type(r) papers = list(r.children)[3] for p in papers: if type(p) is bs4.element.Tag: url_title = p.find('a') title = url_title.get_text() url = url_title['href'] authors = p.find('small').get_text().split( 'Author(s): ')[-1] e = Entity(title, url, authors) all_papers.append(e) if len(all_papers) >= max_count: return break
def parse_entities_file(): """ This function parse the entities file and creates set of entities objects. The file must contain a column named id :return: """ file_name = './entities.csv' with open(file_name, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) if 'id' not in csv_reader.fieldnames: sys.exit( "Error! Start time can't be equal to end time! please change KLC code" ) for row in csv_reader: properties = dict() for prop in csv_reader.fieldnames: if prop == 'id': entityId = row[prop].rstrip() else: properties[prop] = row[prop].rstrip() entity = Entity(entityId=entityId, properties=properties) entities[entityId] = entity
def crawl_search_results(self): search_results = [] self.driver.switch_to.window(self.driver.window_handles[-1]) self.driver.maximize_window() while True: try: self.wait.until( ec.presence_of_element_located( (By.CLASS_NAME, 'result-cont'))) except TimeoutException: CustomLogging.log_to_file('东方财富网搜索页面加载失败', LogType.ERROR) break try: result_articles = self.driver.find_elements_by_class_name( 'result-article') for each_article in result_articles: item = Entity() item.title = each_article.find_element_by_tag_name( 'a').text item.url = each_article.find_element_by_tag_name( 'a').get_attribute('href') item.short_description = each_article.find_element_by_class_name( 'des').text item.publish_date = each_article.find_element_by_class_name( 'g').text threading.Thread(target=self.download_and_save_item, args=(each_article, )).start() except NoSuchElementException: print('没有搜索结果') break try: next_page = self.driver.find_element_by_xpath( '//div[@class="pagination pagination-centered"]//a[contains(text(), "下一页")]' ) self.driver.get(next_page.get_attribute('href')) # next_page.click() except NoSuchElementException: print('已经是最后一页') break return search_results
def crawl_search_results(self): exit_flag = 0 index = 0 while True: try: self.wait.until(ec.presence_of_element_located((By.CLASS_NAME, 'fr'))) except TimeoutException: CustomLogging.log_to_file('人民网搜索结果页面加载失败', LogType.ERROR) CustomLogging.log_to_file(traceback.format_exc(), LogType.ERROR) break try: result_articles = self.driver.find_elements_by_xpath('//div[@class="fr w800"]//ul') for each_article in result_articles: item = Entity() pub_date = each_article.find_elements_by_tag_name('li')[2].text item.publish_date = re.search(re.compile( '[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d'), pub_date).group() if not in_date_range(conv_pub_date(item.publish_date, 'peoplecn'), self.year_range): exit_flag = 1 # 跳出for循环 break item.title = each_article.find_element_by_tag_name('a').text item.short_description = each_article.find_elements_by_tag_name('li')[1].text if self.keyword not in item.short_description and self.keyword not in item.title: continue item.url = each_article.find_element_by_tag_name('a').get_attribute('href') threading.Thread(target=self.download_and_save_item, args=(item,)).start() except NoSuchElementException: break if exit_flag == 1: break try: next_page = self.driver.find_element_by_xpath( '//div[@class="show_nav_bar"]//a[contains(text(), "下一页")]') next_page.click() time.sleep(2) except NoSuchElementException: break
def str_to_entities(string): test_str = format_entities(string) fullRange = r'\{.*?\}' regex = r"((\".*?\").?(\".*?\"))" list_of_text_entities = [] entities_list = [] matchesFR = re.finditer(fullRange, test_str, re.MULTILINE | re.DOTALL) for match in matchesFR: list_of_text_entities.append("{match}".format(match=match.group())) for i in list_of_text_entities: matches = re.finditer(regex, i, re.DOTALL) attr = [] for match in matches: if 'classname' in match.group(): class_name = match.group(3).strip('"') continue attr.append([match.group(2).strip('"'), match.group(3).strip('"')]) entities_list.append(Entity(class_name, attr)) return entities_list
def init(): # Create entities for i in range(Params.population_size): ent_one = Entity() ent_one.x = Params.TEAM_ONE_SPAWN[0] ent_one.y = Params.TEAM_ONE_SPAWN[1] pop_one.append(ent_one) ent_two = Entity() ent_two.x = Params.TEAM_TWO_SPAWN[0] ent_two.y = Params.TEAM_TWO_SPAWN[1] pop_two.append(ent_two) # Determine fight sequence global pop_one_fight_sequence global pop_two_fight_sequence for i in range(Params.population_size): for j in range(Params.MATCHES_PER_FIGHTER): pop_one_fight_sequence.append(i) pop_two_fight_sequence.append(i) random.shuffle(pop_one_fight_sequence) random.shuffle(pop_two_fight_sequence)
def getGroups(self): url = "https://www.tsuab.ru/schedule/api/groups.php" arrayOfchar = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'э', 'ю', 'я', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] filterGroups = [] groupList = [] for char in arrayOfchar: querystring = {"q": char} response = requests.request("GET", url, params=querystring) response.encoding = 'utf-8' for group in response.json()['items']: groupList.append([group['value'], group['id']]) for group in groupList: if not group in filterGroups: filterGroups.append(group) filterGroups.sort() groupList = [] nowWeek = getNowWeek() nextWeek = getNextWeek() for group in filterGroups: urlnow = 'https://www.tsuab.ru/schedule/?q={}&type={}&dt={}&df={}&wid=11&text={}'.format(group[1], 'group', nowWeek[1], nowWeek[0], group[0]) url = urlnow name = group entity = Entity(name, url, 'group', None) groupList.append(entity) return groupList
def getTeachers(self): url = "https://tsuab.ru/schedule/api/teachers.php" arrayOfchar = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'э', 'ю', 'я'] nowWeek = getNowWeek() nextWeek = getNextWeek() teacherList = [] for char in arrayOfchar: querystring = {"q": char} response = requests.request("GET", url, params=querystring) response.encoding = 'utf-8' for teacher in response.json()['items']: teacherList.append([teacher['value'], teacher['id']]) filterTeachers = [] for teacher in teacherList: if not teacher in filterTeachers: filterTeachers.append(teacher) filterTeachers.sort() teacherList = [] for teacher in filterTeachers: urlnow = 'https://www.tsuab.ru/schedule/?q={}&type={}&dt={}&df={}&wid=11&text={}'.format(teacher[1], 'teacher', nowWeek[1], nowWeek[0], teacher[0]) url = urlnow name = teacher entity = Entity(name, url, 'teacher', None) teacherList.append(entity) return teacherList
def _extract(params, data): train_batches, dev_batches, test_batches, vocabs, embedding = data hate_train_batches = [train for train in train_batches if train["labels"] == 1] hate_dev_batches = [dev for dev in dev_batches if dev["labels"] == 1] hate_test_batches = [test for test in test_batches if test["labels"] == 1] t_weights = np.array([1 - (Counter([train["target_label"] for train in hate_train_batches])[i] / len(hate_train_batches)) for i in range(8)]) a_weights = np.array([1 - (Counter([train["action_label"] for train in hate_train_batches])[i] / len(hate_train_batches)) for i in range(4)]) entity = Entity(params, vocabs, embedding) entity.build() if args.goal == "train": entity.run_model(BatchIt(hate_train_batches, params["batch_size"], vocabs), BatchIt(hate_dev_batches, params["batch_size"], vocabs), BatchIt(hate_test_batches, params["batch_size"], vocabs), (t_weights, a_weights)) elif args.goal == "predict": unlabeled_batches = _load_unlabeled(params, args, vocabs) target, action = entity.predict(unlabeled_batches, (t_weights, a_weights)) pickle.dump(target, open("Data/" + args.dataset + "/targets.pkl", "wb")) pickle.dump(action, open("Data/" + args.dataset + "/actions.pkl", "wb"))
def extract_quantified_entities(self, to_create_transfer_entity, transfer_entity_relation): if self.m_cardinal != None: if self.m_owner_entity != None: temp_quantified_entity = QuantifiedEntity( self.m_cardinal, 'dobj', self.m_dobj, False) temp_quantified_entity.set_owner_entity(self.m_owner_entity) merge_entities = self.get_or_merge_entity( temp_quantified_entity) self.m_quantified_entity = temp_quantified_entity if merge_entities == True else None if to_create_transfer_entity and self.m_transfer_entity != None: print 'creating transfer entity' print -self.m_cardinal temp_transfer_quantified_entity = QuantifiedEntity( -self.m_cardinal, transfer_entity_relation, self.m_dobj, True) temp_transfer_quantified_entity.set_owner_entity( self.m_transfer_entity) to_merge_transfer_entity = self.get_or_merge_entity( temp_transfer_quantified_entity) self.m_transfer_quantified_entity = temp_transfer_quantified_entity if to_merge_transfer_entity == True else None else: self.m_object_entity = Entity('dobj', self.m_dobj)
def getTeachers(self): teachersite = 'https://uspu.ru/education/eios/schedule/' teacherlist = requests.get(teachersite) soup = BS(teacherlist.content, 'html.parser') teacherList = [] teachers = soup.find('select', { 'name': 'teacher_search' }).find_all('option', value=True) fio = soup.find('select', { 'name': 'teacher_search' }).find_all(text=True) porNumber = 3 for teacher in teachers: url = 'https://uspu.ru/education/eios/schedule/?teacher_name=%s' % ( teacher.text) name = fio[porNumber] entity = Entity(name, url, 'group', None) teacherList.append(entity) porNumber = porNumber + 2 return teacherList
def create_entities(self, unused_observation_ids, observations): for unused_observation_id in unused_observation_ids: self.tracked_objects[self.n_observed_entities] = Entity( initial_observations=observations[unused_observation_id]) self.n_observed_entities += 1
def __init__(self, image): Entity.__init__(self, image)
def __init__(self, level, entId): Entity.__init__(self, level, entId) self.initProps()
def destroy(self): self.destroyProps() Entity.destroy(self)
def Assemble_Chunk(sEntityName, sEntityType, iDrawPriority, attribDict): entity = Entity(sEntityName, sEntityType, iDrawPriority, {}) dMeshData = {"componentID": "0"} #Iterating through the attribDict items for (attribName, attrib) in attribDict.items(): #This checks to see if the current item is # for the Mesh component. if attribName[0:9] == "TileAtlas": #This will add in the Texture objects # defined by SFMl. This Texture object # points to a Texture object within # the AssetManager. dMeshData[attribName] = attrib entity._Add_Component(getClass("Mesh")(dMeshData)) entity._Add_Component(getClass("Position")({"componentID":"WorldPos", \ "positionX":attribDict['WorldPos'].split(',')[0], \ "positionY":attribDict['WorldPos'].split(',')[1]})) entity._Add_Component(getClass("Position")({"componentID":"WindowPos", \ "positionX":attribDict['WindowPos'].split(',')[0], \ "positionY":attribDict['WindowPos'].split(',')[1]})) entity._Add_Component( getClass("Flag")({ "componentID": "IsEmpty", "flag": True })) entity._Add_Component( getClass("Flag")({ "componentID": "IsLoaded", "flag": False })) List = getClass("List") Tile = getClass("Tile") tileList = List({"componentID": "Tiles"}) for row in xrange(config.CHUNK_TILES_HIGH): #Adds in a list for each row of the tiles tileList._Add(List({"componentID": "Tiles"})) for col in xrange(config.CHUNK_TILES_WIDE): #Adds in a list for each col of the tiles tileList[row]._Add(List({"componentID": "Tiles"})) for depth in xrange(config.CHUNK_LAYERS): #Then adds in a tile, for each layer that exists, into # each 2d tile position in this chunk. tileList[row][col]._Add( Tile({"componentID": "%d,%d,%d" % (row, col, depth)})) entity._Add_Component(tileList) return entity
def makeShot(self): shot = Entity(self.x, self.y, 0, -1.25, "img/shot.png", self.gameWidth, self.gameHeight) return shot
def crawl_search_results(self): search_results = [] self.driver.switch_to.window(self.driver.window_handles[-1]) self.driver.maximize_window() exit_flag = 0 while True: try: self.wait.until( ec.presence_of_all_elements_located( (By.CLASS_NAME, 'r-info'))) except TimeoutException: CustomLogging.log_to_file('搜索结果为空', LogType.ERROR) result_articles = self.driver.find_elements_by_class_name('r-info') for each_article in result_articles: item = Entity() try: pub_date = each_article.find_element_by_class_name( 'fgray_time').text except NoSuchElementException: continue item.publish_date = re.search( re.compile( '[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d' ), pub_date).group() # 判断文章是否在指定年限内,如果不在指定年限则退出 if not in_date_range(conv_pub_date(item.publish_date, 'sina'), self.year_range): exit_flag = 1 # 跳出for循环 break item.short_description = each_article.find_element_by_class_name( 'content').text item.title = each_article.find_element_by_tag_name('h2').text # 关键字过滤,如果关键在在文章标题和简述里都没出现,则判断下一条 if self.keyword not in item.short_description and self.keyword not in item.title: continue if item.title in self.titles: continue else: self.titles.append(item.title) item.url = each_article.find_element_by_xpath( './/h2/a').get_attribute('href') threading.Thread(target=self.download_and_save_item, args=(item, )).start() # 跳出while循环 if exit_flag == 1: break try: next_page = self.driver.find_element_by_xpath( '//div[@class="pagebox"]/a[@title="下一页"]') # next_page.click() self.driver.get(next_page.get_attribute('href')) # time.sleep(2) except NoSuchElementException: # print('已经是最后一页') break return search_results
def __init__(self, id): self.level = "C" Entity.__init__(self, id)
def mangle_entity(self, node): e = Entity(node) self.entities[e.get_id()] = e
class Chef(threading.Thread): ## Constructor Function # Has all the necessary arguments with a default value # This includes the communication port, the special ID and the default port to enter the Token Ring def __init__(self, port=5002, ide=COOK, init_port=5000): threading.Thread.__init__(self) ## Node in the Ring that will establish the communication self.node_entity = Entity(ide, ('localhost', port), 'Chef', ('localhost', init_port)) self.node_entity.start() ##Logger to print out information throughout the simulation self.logger = logging.getLogger("Chef") ##List of requests received self.req = [] ##List of foods to prepare self.to_do = [] ##Completed Function # Check if the cook has finished the first request in line ## @param req: a record of all the different foods currently done def completed(self, req): if len(self.req) <= 0: return False temp = self.req[0][1] for food in req: if req[food] < temp[food]: return False return True ##Add to_do Function # Add a list of foods to the to_do list of the cook, for him to prepare ## @param args: a dictionary with what food to make and in what quantities def add_to_do(self, args): for key, val in args.items(): for i in range(val): self.to_do.append(key) return self.to_do[0] ## Run Function # Starts the thread run: # When a requests comes from the Receptionist, it will add it to the request's list and the to_do list; # Once it has items on the to_do list, it will start confectionating these items, having to ask # for permission to use the needed cookingware from the Restaurant # To simulate the cooking process, the Chef has a sleep function builtin to it # After it finishes cooking anything, it will check if the first order has been completed: if so, it will be sent to the waiter, if not it will simply move on # It will also send a request for the next food item on the to_do list, to check if the cookingware is available def run(self): food_done = dict.fromkeys(['hamburger', 'fries', 'drink'], 0) cooking_item = False item_index = 0 while True: o = self.node_entity.queue_out.get() self.logger.info("O: %s", o) if o['method'] == 'SEND_ORDER': self.req.append((o['ticket'], o['args'])) self.add_to_do(o['args']) if o['method'] == 'USE_FRIES': if not o['args']: self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'USING_FRY' }) work(5, 0.5) self.to_do.pop(item_index) item_index = 0 food_done['fries'] += 1 self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'STOPPED_FRY' }) else: item_index += 1 cooking_item = False if o['method'] == 'USE_GRILL': if not o['args']: self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'USING_GRILL' }) work(3, 0.5) self.to_do.pop(item_index) item_index = 0 food_done['hamburger'] += 1 self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'STOPPED_GRILL' }) else: item_index += 1 cooking_item = False if o['method'] == 'USE_DRINK': if not o['args']: self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'USING_DRINK' }) work(1, 0.5) self.to_do.pop(item_index) item_index = 0 food_done['drink'] += 1 self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'STOPPED_DRINK' }) else: item_index += 1 cooking_item = False if self.completed(food_done): ticket, completed_req = self.req.pop() for key in food_done: food_done[key] -= completed_req[key] self.node_entity.queue_in.put({ 'entity': 'Waiter', 'method': 'COMPLETED_REQ', 'args': completed_req, 'ticket': ticket }) if not cooking_item: if len(self.to_do) > 0: item = self.to_do[item_index] cooking_item = True self.node_entity.queue_in.put({ 'entity': 'Restaurant', 'args': None, 'method': 'ask_' + item })