def entity_search_genres_engine(entity: Entity, values: list, search: SearchParams) -> str: """ Genres criteria :param entity: entity to search :param values: values for criteria :param search: search parameters for advanced search """ genre_term = f'{fq_column(GENRES_TABLE, "name")}' idx = search.entities.index(entity) if len(search.genre_aliases) > idx: if search.genre_aliases[idx] is not None: genre_term = f'{search.genre_aliases[idx]}.name' terms = [f'{genre_term} = \'{g}\'' for g in values] # ((inner join 'entity table' and 'genre link table') # inner join 'genres table') search.customisation = \ join_engine( join_engine(entity.eng_table, entity.eng_genre_link_table, entity.fq_genre_link(), entity.fq_id()), GENRES_TABLE, fq_column(entity.eng_genre_link_table, "genre_id"), fq_column(GENRES_TABLE, "id")) return conjunction_op_engine(OR_CONJUNC, *terms)
def create_entities(name_to_info): """Create the entities from the list of names. Returns the dict to map names indices to the Mongo Entity ID Args: * name_to_info: dict {name: {'id': index, 'image_url': image_url, 'twitter': <twitter_account>, ...}, ...} Returns: * index_to_id: dict {name_index: entity.id} """ index_to_id = {} for name, attr in name_to_info.items(): kwargs = {} # We may not have the image if 'image_url' in attr: kwargs['image_url'] = attr['image_url'] # Social media accounts kwargs['accounts'] = { k: attr[k] for k in attr if k not in ['id', 'image_url'] } ent = Entity(name=name, **kwargs) ent.save() # Store the indices to link the index from the timecode and the Mongo index index = attr['id'] index_to_id[index] = ent.id return index_to_id
def get(self, profile_to_get=None): template_values = get_template_values(self) user = users.get_current_user() if user: if not profile_to_get or profile_to_get == user.user_id(): entity_query = Entity.query( Entity.id == user.user_id()).fetch() else: entity_query = Entity.query( Entity.id == profile_to_get).fetch() if len(entity_query) < 1: entity_query = Entity.query( Entity.display_name == profile_to_get).order( -Entity.created).fetch() if len(entity_query) < 1: self.redirect('/') return entity = entity_query[0] if len(entity_query) > 0: if user.user_id() == entity.id: template_values['this_user'] = True template_values = add_entity_to_template( template_values, entity, self.request) path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'profile.html')) self.response.out.write(template.render(path, template_values)) return self.redirect('/') return
def get(self, profile_to_get=None): template_values = get_template_values( self ) user = users.get_current_user() if user: if not profile_to_get or profile_to_get == user.user_id(): entity_query = Entity.query( Entity.id == user.user_id() ).fetch() else: entity_query = Entity.query( Entity.id == profile_to_get ).fetch() if len(entity_query) < 1: entity_query = Entity.query( Entity.display_name == profile_to_get ).order(-Entity.created).fetch() if len(entity_query) < 1: self.redirect('/') return entity = entity_query[0] if len(entity_query) > 0: if user.user_id() == entity.id: template_values['this_user'] = True template_values = add_entity_to_template(template_values, entity, self.request) path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'profile.html' ) ) self.response.out.write( template.render( path, template_values )) return self.redirect('/') return
def load_dictionary(self, source, language, dict_path): counter, start_at = 0, int(time.time()) print("\nLoading entity_dictionary from: {}".format(dict_path)) with open(dict_path, "r", encoding="utf-8") as rf: for line in rf: line_arr = line.strip().split("\t\t") if len(line_arr) != 4: continue title, sub_title, uris, entity_id = line_arr uris = uris.split("::;") counter += 1 entity = Entity(entity_id, title, sub_title, source, language) for uri in uris: self._uri_2_id[uri] = entity_id self._fulltitle_2_id[entity.get_full_title()] = entity_id title_mention = self.get_mention_from_title( entity.get_full_title()) if self._mention_2_ids.get(title_mention) is None: self._mention_2_ids[title_mention] = dict() self._mention_2_ids[title_mention][entity_id] = None self.entity_dict[entity_id] = entity print("Loaded, #{}, time: {}.".format( counter, str(datetime.timedelta(seconds=int(time.time()) - start_at))))
def post(self): test_id = self.request.get( 'test_id' ) author_id = self.request.get( 'author_id' ) user = users.get_current_user() if user: test = Test.query( Test.id == test_id ).get() mark_query = Mark.query( ancestor = ndb.Key("Entity", user.user_id() ) ) mark_query = mark_query.filter( Mark.test.id == test.id ) this_mark = mark_query.get() if this_mark == None: print "IndexError" this_mark = Mark( parent = ndb.Key("Entity", user.user_id() ) ) this_mark.test = test this_mark.created = datetime.datetime.now() this_mark.mark = None this_mark.rated = False this_mark.rating = 0 test.times_taken += 1 test.put() this_mark.response = self.request.get( 'response' ) this_mark.complete = False this_mark.modified = datetime.datetime.now() this_mark.id = test_id + user.user_id() this_mark.marker_entity = Entity.query( Entity.id == author_id ).get() this_mark.taker_entity = Entity.query( Entity.id == user.user_id() ).get() send_email( this_mark.marker_entity.user.email() , test, "Test-Answer") this_mark.put() self.redirect( '/t/%s' % test_id ) return
def analyse_sentiment(id, text, posted_at): document = types.Document(content=text, type=enums.Document.Type.PLAIN_TEXT) # Detect the entities in the text try: entities = nl_api_client.analyze_entity_sentiment( document=document, encoding_type='UTF8').entities # Build up our entities object to insert into the table entities_object = [] for e in entities: entity = Entity( name=e.name, \ type=e.type, \ wikipedia_url=e.metadata['wikipedia_url'], \ mid=e.metadata['mid'], \ salience=e.salience, \ sentiment_score=e.sentiment.score, \ sentiment_magnitude=e.sentiment.magnitude, \ posted_at=posted_at, \ remote_post_id=id ) entity.mentions = create_entity_mentions(e.mentions) entities_object.append(entity) except InvalidArgument as err: print(err) return False # Insert entities and mentions into the database session.add_all(entities_object)
def get(self, test_to_get=None): template_values = get_template_values( self ) user = users.get_current_user() if not test_to_get: self.logger.debug("No test was provided for lookup") self.redirect('/') return else: try: test = Test.query( Test.id == test_to_get).fetch(1)[0] except IndexError: self.logger.debug("Invalid Test ID") self.redirect('/') else: if user: template_values = add_entity_to_template( template_values, Entity.query( Entity.id == user.user_id() ).fetch(1)[0] ) user_level = get_user_group_level( get_grouped_marks( user.user_id() ), test.group ) if user_level == None: user_level = 1 template_values['user_level'] = user_level if user_level < test.level: template_values['locked'] = True try: mark_query = Mark.query( ancestor = ndb.Key("Entity", user.user_id() ) ) mark = mark_query.filter( Mark.test.id == test.id ).fetch(1)[0] template_values = add_mark_to_template( template_values, mark ) if (datetime.datetime.now() - mark.modified) < datetime.timedelta(hours=24) or mark.complete: template_values['locked'] = True except IndexError: self.logger.debug( "No mark found" ) template_values = add_test_to_template( template_values, test ) finally: if test.author_id == user.user_id(): template_values['is_test_marker'] = True template_values['locked'] = True test_marker = Entity.query( Entity.id == user.user_id() ).get() template_values['to_be_marked'] = get_to_be_marked( test_marker, test ) template_values['name'] = test_marker.display_name template_values['current_user'] = user.user_id() else: template_values['locked'] = True template_values['visitor'] = True logging.warning("User not found!") template_values = add_test_to_template( template_values, test ) finally: path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'test_detail.html') ) self.response.out.write( template.render( path, template_values) ) return
def index(request): try: companies = ['Abar Automation', 'ABB', 'Accuworx', 'Adept Technology', 'Advanced Coating Robotics', 'Advanced Robotic Technology', 'Aerotech', 'Aetnagroup SpA', 'AIDA Engineering (JP)', 'Alaark Robotics, Inc.', 'Alfa Automation Technology Ltd', 'Alpha Robotics', 'American Robot', 'American Robot Sales', 'Antenen Research', 'Apex Automation & Robotics', 'Applied Controls Technology', 'ARC Specialities, Inc.', 'Asic Robotics AG', 'Aspect Automation', 'ASS End of Arm Tooling', 'Atlas Copco AB', 'ATM Automation Ltd.', 'ATS Automation Tooling Systems', 'Aurotek Corp', 'Austong Intelligent Robot Technology (CN)', 'Automatted Motion', 'AVN Gruppen', 'AWL Techniek (NV)', 'Axium, Inc.', 'Baumann Automation', 'Bila A/S', 'BL Autotec, Ltd.', 'Bleichert, Inc.', 'Bosch', 'Braas Co', 'Brokk AB', 'Chad Industries', 'Chariot Robotics', 'CIM Systems, Inc.', 'Cimcorp Oy', 'Cloos Schweisstechnik Robotic', 'CMA Robotics', 'Columbia/Okura, LLC', 'Comau', 'Conair Group', 'Creative Automation', 'CT Pack Srl (IT)', 'Daewoo Shipbuilding & Marine Engr', 'Daihen Corp.', 'DanRob', 'Daum + Partner GmbH', 'Dematic GmbH', 'Denso-Wave Robotics', 'DiFacto Robotics & Automation', 'Dong-Hyun Systems (DHS)', 'Dongbu Robot (prev DasaRobot) (KR)', 'Dover Corp (DE-STA-CO)', 'Duepi Automazioni Industriali', 'Durr Systems', 'Dynamic Motion Technology', 'Dynax (JP)', 'Egemin Automation', 'Electroimpact Inc.', 'Electtric80 (IT)', 'Ellison Technologies Automation', 'ENGEL Austria GmbH', 'Erowa Technology', 'EWAB Engineering', 'Fanuc', 'Farr Automation, Inc.', 'Fatronik Technalia', 'FerRobotics GmbH', 'FIPA GmbH', 'FleetwoodGoldcoWyard', 'Flexilane (WIKA Systems) (Denmark)', 'FlexLink', 'Fronius IG', 'Fuji Yusoki Kogyou', 'Gema Switzerland GmbH', 'Gerhard Schubert GmbH', 'GHS Automation', 'Gibotech A/S', 'Glama Engineering', 'GM Global Tech Ops', 'Gotting KG', 'Gudel Robotics', 'H.A.P. GmbH', 'Harly Robotic-Arm Co., Ltd.', 'Harmo (JP)', 'Hitachi Kokusai Electric Inc.', 'Hon Hai Precision (Foxconn)', 'Honeywell', 'Huaxing Machinery Corp', 'Hyundai Heavy Industries (KR)', 'I&J Fisnar', 'IAI America', 'IGM Robotic Systems AG', 'IHI Group', 'Industrial Control Repair'] for company in companies: entity = Entity(name=company) entity.save() except: pass context = RequestContext(request, {'categories': [i.category for i in CategoryOrder.objects.all().order_by('order')], 'companies': Entity.objects.all()}) return render_to_response('market/index.html', context)
def post(self, in_test_id): path = urlparse.urlsplit(self.request.referrer).path author_id = self.request.get("author_id") test_id = self.request.get("test_id") mark_id = self.request.get("mark_id") address = self.request.get("mark_address") comment = self.request.get("comment") mark = self.request.get("mark") author_entity = Entity.query(Entity.id == author_id).get() test_entity = Test.query(Test.id == test_id).get() mark_entity = Mark.query(ancestor=ndb.Key("Entity", mark_id)) mark_entity = mark_entity.filter(Mark.test.id == test_id).get() mark_entity.marker_entity = author_entity mark_entity.test = test_entity mark_entity.comment = comment mark_entity.mark = int(mark) test_entity.total_score += mark_entity.mark test_entity.num_marked += 1 mark_entity.modified = datetime.datetime.now() mark_entity.complete = True mark_entity.put() send_email(address, test_entity, "Answer-Response") test_entity.put() self.redirect(path) return
def network(): entities = Entity.query().order(Entity.name) result = list() for e in entities: result.extend(e.get_json()) return render_template('network.html', result=result)
def set(): data = request.get_json() key = data['key'] value = data['value'] # check empty one of below if key and value: query = db.session.query(Entity).filter( Entity.key == key, Entity.user_id == session['owner']).first() if query is not None: # check the same value exist if query.value == value: flash('key/value already exist', 'warning') return json.dumps({'status': 'key/value already exist'}) # change only value query.value = value db.session.commit() else: # full query db.session.add( Entity(key=key, value=value, user_id=session['owner'])) db.session.commit() message = ('').join(("Set ", key, "/", value)) flash(message) else: flash('Not correct data!', 'error') return json.dumps({'status': 'Not correct data!'}) return json.dumps({'status': 'OK'})
def __init__(self): # Default Rectangle for Hero self.hero_start_x = 20 self.hero_start_y = settings.WINDOW_HEIGHT/2 self.hero_size = 50 # in pixels self.hero_rect = pygame.Rect(self.hero_start_x, self.hero_start_y, self.hero_size, self.hero_size) Entity.__init__(self, self.hero_rect, ["HERO", ["HERO", "HERO"]]) self.hit_points = 3 self.base_speed = 5 # Default speed self.is_firing_laser = False self.laser = None self.ok2shoot = True self.laser_equipped = False self.fire_time = -1
def add_test_to_template(template_values, in_test): """Combines Test object properties into template_values""" template_values['test_id'] = in_test.id template_values['title'] = in_test.title template_values['description'] = in_test.description template_values['group'] = in_test.group template_values['level'] = in_test.level template_values['test_created'] = in_test.created template_values['test_modified'] = in_test.modified template_values['author_id'] = in_test.author_id template_values['author_name'] = Entity.query( Entity.id == in_test.author_id).get().display_name template_values['times_taken'] = in_test.times_taken template_values['total_score'] = in_test.total_score template_values['num_marked'] = in_test.num_marked template_values['open'] = in_test.open if in_test.num_marked > 0: template_values['average_mark'] = template_values[ 'total_score'] / template_values['num_marked'] mark_list = Mark.query(Mark.test.id == in_test.id).filter( Mark.rating > -1).fetch() template_values['num_ratings'] = len(mark_list) if template_values['num_ratings'] > 0: template_values['average_rating'] = sum( [mark.rating for mark in mark_list]) / template_values['num_ratings'] if template_values['average_rating'] is not in_test.average_rating: save_average_rating(in_test.id, template_values['average_rating']) return template_values
def post( self, in_test_id ): path = urlparse.urlsplit(self.request.referrer).path author_id = self.request.get("author_id") test_id = self.request.get("test_id") mark_id = self.request.get("mark_id") address = self.request.get("mark_address") comment = self.request.get("comment") mark = self.request.get("mark") author_entity = Entity.query( Entity.id == author_id ).get() test_entity = Test.query( Test.id == test_id ).get() mark_entity = Mark.query( ancestor = ndb.Key("Entity", mark_id) ) mark_entity = mark_entity.filter( Mark.test.id == test_id ).get() mark_entity.marker_entity = author_entity mark_entity.test = test_entity mark_entity.comment = comment mark_entity.mark = int(mark) test_entity.total_score += mark_entity.mark test_entity.num_marked += 1 mark_entity.modified = datetime.datetime.now() mark_entity.complete = True mark_entity.put() send_email( address, test_entity, "Answer-Response") test_entity.put() self.redirect( path ) return
def get_query(self,id): lines = [] if ALL_DIGITS.match(id) is not None: lines = Entity.query(Entity.id==id).fetch(1) else: lines = Entity.query(Entity.name==id).fetch(1) if len(lines)>0: ret = lines[0].to_dict() id = ret['id'] logging.debug('entity-api: id='+id) supports = SupportLine.query(SupportLine.entity_id==id).order(-SupportLine.year).fetch(1000) ret['supports'] = [x.to_dict() for x in supports] exemptions = MRExemptionRecord.query(MRExemptionRecord.entity_id==id).order(-MRExemptionRecord.start_date).fetch(1000) ret['exemptions'] = [x.to_dict() for x in exemptions] return ret else: return {}
def entity_browser_body(self, *args): country_key = args[0] entity_list = None if country_key: entity_list = Entity.gql("where country=:country_key", country_key=country_key) else: member = self.current_member() country = Country.gql("WHERE name = :country_name", country_name=member.country).get() entity_list = Entity.gql("where country=:country_key", country_key=country.key()) param = self.render_parameters() param["entity_list"] = entity_list param["country_list"] = Country.all() return self.render("entity_browser_body", param)
def network(): entities = Entity.query().order(Entity.name) result = list() for e in entities: result.extend(e.get_json()) last_posts = Post.get_lastest() return render_template('network.html', last_posts=last_posts, result=result)
def team_put(request): dbsession = DBSession() entity = Entity() entity.name = clean_matchdict_value(request, 'team') entity.entityType_id = getTeamTypeID() entity.group_id = clean_param_value(request, 'group_id') entity.parent_id = None entity.price = 100 entity.touched = False entity.timestamp = get_timestamp() dbsession.add(entity) transaction.commit() return {'status': 'success'}
def get(self, in_test_id=None): template_values = get_template_values(self) user = users.get_current_user() try: entity = Entity.query(Entity.id == user.user_id()).get() if not entity.display_name: # It's only slightly possible to have a user with no display_name self.redirect('/login') except: self.redirect('/login') else: test_query = Test.query(ancestor=ndb.Key('Entity', user.user_id())) if len(test_query.fetch()) > 0: if in_test_id: in_query = test_query.filter( Test.id == in_test_id).fetch(1) try: # The test exists template_values = add_test_to_template( template_values, in_query[0]) except IndexError: # The test does not exist self.redirect("/") potential_groups = set( itertools.chain(entity.test_groups, default_groups)) print potential_groups grouped_marks = get_grouped_marks(entity.id) # Add groups with levels for level dropdown template_values['user_levels'] = json.dumps(grouped_marks) # Add list of groups for group dropdown template_values['user_groups'] = [] for group in grouped_marks: group_test_query = Test.query( Test.group == group['group']).order(-Test.level).fetch() try: threshold = group_test_query[0] except: threshold = 0 print threshold for mark in grouped_marks: potential_groups = potential_groups - set(group['group']) if mark['group'] == group and mark["level"] >= threshold: template_values['user_groups'].append(group) for group in potential_groups: template_values['user_groups'].append(group) if template_values["user_groups"] == []: template_values[ 'error'] = "You may only create a test in a new category." path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'create.html')) self.response.out.write(template.render(path, template_values)) return
def get_query(self, id): lines = [] if ALL_DIGITS.match(id) is not None: lines = Entity.query(Entity.id == id).fetch(1) else: lines = Entity.query(Entity.name == id).fetch(1) if len(lines) > 0: ret = lines[0].to_dict() id = ret['id'] logging.debug('entity-api: id=' + id) supports = SupportLine.query(SupportLine.entity_id == id).order( -SupportLine.year).fetch(1000) ret['supports'] = [x.to_dict() for x in supports] exemptions = MRExemptionRecord.query( MRExemptionRecord.entity_id == id).order( -MRExemptionRecord.start_date).fetch(1000) ret['exemptions'] = [x.to_dict() for x in exemptions] return ret else: return {}
def update_to_supergroup(bot, update): old_id = update.message.migrate_from_chat_id new_id = update.message.chat_id user_id = update.message.from_user.id if old_id: UserStat.update(user_id, old_id, {'cid': new_id}) Entity.update_all(old_id, {'cid': new_id}) Chat.update(old_id, {'cid': new_id}) # Update all rows in chat_stats for c in db.query(ChatStat)\ .filter(ChatStat.cid == old_id)\ .all(): c.cid = new_id db.commit() bot.sendMessage(new_id, 'Group was updated to supergroup') cache.delete('last_{}'.format(old_id)) logger.info('Group {} was updated to supergroup {}'.format( old_id, new_id))
def add_entities(session): added = False for entity_value in ENTITIES: entity = session.query(Entity).filter(Entity.label == entity_value) if not entity.count(): added = True session.add(Entity(label=entity_value)) else: entity_records[entity_value] = entity.first() if added: session.commit()
def entity_post(request): """ Create a new Entity with optional predefined GUID. If Entity with given GUID already exists, it will be replaced with new data. Parameters can be separate parameters in request.POST or JSON encoded in a singe "data" parameter. Currently successful creation returns always 201 Created. """ try: request_data = json.loads(request.POST.get('data', '')) except ValueError: request_data = {} if not request_data: # json data did not exist request_data['name'] = request.POST.get('name', '') try: lat = float(request.POST.get('lat')) lon = float(request.POST.get('lon')) request_data['geography'] = Point(lon, lat) except TypeError: data, message = {}, u'No "lat" or "lon" parameters found.' return False, data, message guid = request.POST.get('guid') if guid: request_data['guid'] = request.POST.get('guid') try: # to get existing Entity from the database ent = Entity.objects.get(guid=guid) ent.geography = request_data['geography'] # update location if 'name' in request_data and request_data['name']: ent.name = request_data['name'] except Entity.DoesNotExist: # if it fails, create a new one ent = Entity(**request_data) #try: # ent.validate_unique() #except ValidationError, e: # data, message = {}, u'Entity with uid "%s" already exists.' % (ent.uid) # return False, data, message ent.save() data, message = {'guid': ent.guid}, u'201 Created' return True, data, message
async def init_db(): from models import Department, Employee, Role, User, Entity Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create Fixture for Users user1 = User(name='user1') db_session.add(user1) user2 = User(name='user2') db_session.add(user2) # Create Fixture for Profiles entity1 = Entity(user=user1, provider="email", data={"email": "*****@*****.**"}) db_session.add(entity1) entity2 = Entity(user=user1, provider="facebook", data={"token": "blablabla"}) db_session.add(entity2) entity3 = Entity(user=user2, provider="email", data={"email": "*****@*****.**"}) db_session.add(entity3) # Insert seed data into database db_session.commit() print('committed!')
def post(self): template_values = get_template_values(self) user = users.get_current_user() try: entity_query = Entity.query(Entity.id == user.user_id()).fetch() entity = entity_query[0] except IndexError: # This user must not exist yet, so create one entity = Entity( user=user, id=user.user_id(), created=datetime.datetime.now(), test_groups=[], ) if not entity.display_name: posted_name = self.request.get('display_name') else: posted_name = entity.display_name # Show an error if the name isn't formatted properly. if re.match('^[a-z0-9]{3,16}$', posted_name) is None: template_values[ 'error'] = "Usernames must be 16 or fewer alphanumeric characters [a-z0-9]." path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) return users_with_name = Entity.query( Entity.display_name == posted_name).count() if users_with_name == 0 or entity.display_name == posted_name: # Update values entity.display_name = posted_name if posted_name else entity.display_name entity.bio = self.request.get('bio') if len( self.request.get('bio')) > 0 else "I am mysterious." # Save and visit entity.put() time.sleep( 0.1 ) # The user doesn't exist for a short period of time after put() self.redirect('/u/%s' % entity.display_name) else: template_values[ 'error'] = "That username is in use. Please choose again." path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) return
def update_entity(): tree = Tree() all_nodes = tree.build('./post/entity.txt', False) for node in all_nodes: node = tree.get_or_create(node) entity = Entity.query(Entity.name == node.entity).get() print '-----------------------' print node.get_parent() print node.entity print node.get_children() print node.get_ref() if entity: entity.from_entity = node.get_parent() entity.to_entity = node.get_children() entity.ref_entity = node.get_ref() entity.put() else: Entity( name=node.entity, from_entity=node.get_parent(), to_entity=node.get_children(), ref_entity=node.get_ref(), ).put()
def post(self): group_name = self.request.get('group_name') user = users.get_current_user() entity = Entity.query(Entity.id == user.user_id()).get() try: assert re.match('^[a-z0-9_]{2,16}$', group_name) is not None except: self.redirect('/preferences') else: if group_name not in entity.test_groups: entity.test_groups.append(group_name) entity.put() time.sleep(0.1) # Need some time to ensure consistency. self.redirect('/preferences')
def get(self): template_values = get_template_values( self ) user = users.get_current_user() try: entity = Entity.query( Entity.id == user.user_id() ).fetch()[0] if not entity.display_name: path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'register.html' ) ) self.response.out.write( template.render( path, template_values )) else: self.redirect('/u') except IndexError: path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'register.html' ) ) self.response.out.write( template.render( path, template_values )) return
def get(self, in_test_id=None): template_values = get_template_values( self ) user = users.get_current_user() try: entity = Entity.query( Entity.id == user.user_id() ).get() if not entity.display_name: # It's only slightly possible to have a user with no display_name self.redirect('/login') except: self.redirect('/login') else: test_query = Test.query( ancestor = ndb.Key('Entity', user.user_id() ) ) if len(test_query.fetch()) > 0: if in_test_id: in_query = test_query.filter( Test.id == in_test_id ).fetch(1) try: # The test exists template_values = add_test_to_template( template_values, in_query[0] ) except IndexError: # The test does not exist self.redirect("/") potential_groups = set( itertools.chain( entity.test_groups, default_groups ) ) print potential_groups grouped_marks = get_grouped_marks( entity.id ) # Add groups with levels for level dropdown template_values['user_levels'] = json.dumps( grouped_marks ) # Add list of groups for group dropdown template_values['user_groups'] = [] for group in grouped_marks: group_test_query = Test.query( Test.group == group['group'] ).order(-Test.level).fetch() try: threshold = group_test_query[0] except: threshold = 0 print threshold for mark in grouped_marks: potential_groups = potential_groups - set(group['group']) if mark['group'] == group and mark["level"] >= threshold: template_values['user_groups'].append( group ) for group in potential_groups: template_values['user_groups'].append( group ) if template_values["user_groups"] == []: template_values['error'] = "You may only create a test in a new category." path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'create.html' ) ) self.response.out.write( template.render( path, template_values )) return
def post(self): group_name = self.request.get('group_name') user = users.get_current_user() entity = Entity.query( Entity.id == user.user_id() ).get() try: assert re.match('^[a-z0-9_]{2,16}$', group_name ) is not None except: self.redirect('/preferences') else: if group_name not in entity.test_groups: entity.test_groups.append(group_name) entity.put() time.sleep(0.1) # Need some time to ensure consistency. self.redirect('/preferences')
def post(self): test_id = self.request.get('test_id') author_id = self.request.get('author_id') user = users.get_current_user() if user: test = Test.query(Test.id == test_id).get() mark_query = Mark.query(ancestor=ndb.Key("Entity", user.user_id())) mark_query = mark_query.filter(Mark.test.id == test.id) this_mark = mark_query.get() if this_mark == None: print "IndexError" this_mark = Mark(parent=ndb.Key("Entity", user.user_id())) this_mark.test = test this_mark.created = datetime.datetime.now() this_mark.mark = None this_mark.rated = False this_mark.rating = 0 test.times_taken += 1 test.put() this_mark.response = self.request.get('response') this_mark.complete = False this_mark.modified = datetime.datetime.now() this_mark.id = test_id + user.user_id() this_mark.marker_entity = Entity.query( Entity.id == author_id).get() this_mark.taker_entity = Entity.query( Entity.id == user.user_id()).get() send_email(this_mark.marker_entity.user.email(), test, "Test-Answer") this_mark.put() self.redirect('/t/%s' % test_id) return
def _handle_entities(self, tweet, tweet_data): for category in tweet_data.entities: for entity_data in tweet_data.entities[category]: content = '' if category == 'urls': content = entity_data['expanded_url'] if category == 'hashtags': content = entity_data['text'] if category == 'user_mentions': content = entity_data['screen_name'] entity = Entity(category=category, tweet=tweet, content=content) self.session.add(entity)
def get_grouped_marks(entity_id): """Returns a list of summary of the marks in each group This list will return all available lgroups, even if the level is 0. """ grouped_marks = [] groups = set() mark_list = Mark.query(ancestor=ndb.Key("Entity", entity_id)).filter( Mark.complete == True).order(-Mark.created).fetch() entity = Entity.query(Entity.id == entity_id).fetch()[0] group_list = [] for mark in mark_list: groups_length = len(groups) groups.update(mark.test.group) if groups_length < len(groups): # If the set of groups got longer, add a new dict to the list grouped_marks.append({ 'group': mark.test.group, 'level': mark.test.level, 'level_progress': 0, 'tests_taken': 0, 'total_score': 0, }) else: for group in grouped_marks: if group['group'] == mark.test.group: group['tests_taken'] += 1 group['total_score'] += mark.mark * mark.test.level group_list.append(mark.test.group) for group in grouped_marks: if group['total_score'] is not None and group['total_score'] > 0: group['level'] = math.floor( math.log(float(group['total_score']), 2)) group['level_progress'] = (math.log(group['total_score'], 2) - group['level']) * 100 else: group['total_score'] = 0 group['level'] = 1 group['level_progress'] = 0 unused_defaults = set(itertools.chain( entity.test_groups, default_groups)) - set( [group['group'] for group in grouped_marks]) for group in unused_defaults: grouped_marks.append({'group': group, 'level': 1, 'level_progress': 0}) return grouped_marks
def get(self): template_values = get_template_values(self) user = users.get_current_user() try: entity = Entity.query(Entity.id == user.user_id()).fetch()[0] if not entity.display_name: path = os.path.join( os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) else: self.redirect('/u') except IndexError: path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) return
def entity(noun=None): entity = Entity.query(Entity.name==noun).get() post = Post.query(Post.title==noun).get() if not post: return redirect(url_for("idonotknow", noun=noun)) posts = Post.query().filter(Post.category.IN([noun])) content, toc = md2html(post.content) txt = noTag(noTag(toc, 'div'), 'ul') toc = toc if txt.strip() else '' return render_template('entity.html', entity=entity, post=post, posts=posts, toc=toc, content=content)
def get_grouped_marks( entity_id ): """Returns a list of summary of the marks in each group This list will return all available lgroups, even if the level is 0. """ grouped_marks = [] groups = set() mark_list = Mark.query( ancestor = ndb.Key( "Entity", entity_id )).filter( Mark.complete == True ).order( -Mark.created ).fetch() entity = Entity.query( Entity.id == entity_id).fetch()[0] group_list = [] for mark in mark_list: groups_length = len(groups) groups.update( mark.test.group ) if groups_length < len(groups): # If the set of groups got longer, add a new dict to the list grouped_marks.append({ 'group' : mark.test.group, 'level' : mark.test.level, 'level_progress' : 0, 'tests_taken' : 0, 'total_score' : 0, }) else: for group in grouped_marks: if group['group'] == mark.test.group: group['tests_taken'] += 1 group['total_score'] += mark.mark * mark.test.level group_list.append( mark.test.group ) for group in grouped_marks: if group['total_score'] is not None and group['total_score'] > 0: group['level'] = math.floor( math.log( float(group['total_score']),2 ) ) group['level_progress'] = (math.log( group['total_score'],2 ) - group['level']) * 100 else: group['total_score'] = 0 group['level'] = 1 group['level_progress'] = 0 unused_defaults = set( itertools.chain( entity.test_groups, default_groups )) - set( [ group['group'] for group in grouped_marks ] ) for group in unused_defaults: grouped_marks.append( {'group':group,'level':1,'level_progress':0} ) return grouped_marks
def entity_browser_entity_part(self, *args): country_name = args[0] country = Country.get_by_name(country_name) entity_result = Entity.gql("where country=:country_key", country_key=country.key()) param = self.render_parameters() entity_lc = [] entity_mc = None entity_ai = None for entity in entity_result: if entity.type.name == "MEMBER COMMITTEE": entity_mc = entity elif entity.type.name == "AIESEC INTERNATIONAL": entity_ai = entity else: entity_lc.append(entity) param["entity_lc_list"] = entity_lc param["entity_mc"] = entity_mc param["entity_ai"] = entity_ai param["flag_url"] = country.get_flag_url() return self.render("entity_browser_entity_part", param)
def update_entity(): tree = Tree() all_nodes = tree.build('./post/entity.txt', False) for node in all_nodes: node = tree.get_or_create(node) entity = Entity.query(Entity.name==node.entity).get() print '-----------------------' print node.get_parent() print node.entity print node.get_children() print node.get_ref() if entity: entity.from_entity = node.get_parent() entity.to_entity = node.get_children() entity.ref_entity = node.get_ref() entity.put() else: Entity(name=node.entity, from_entity=node.get_parent(), to_entity=node.get_children(), ref_entity=node.get_ref(), ).put()
def entity(noun=None): entity = Entity.query(Entity.name==noun).get() post = Post.query(Post.title==noun).get() if not post: return redirect(url_for("idonotknow", noun=noun)) posts = Post.query().filter(Post.category.IN([noun])).order(-Post.date) tagged_posts = Post.get_tagged_post(noun) content, toc = md2html(post.content) txt = noTag(noTag(toc, 'div'), 'ul') toc = toc if txt.strip() else '' last_posts = Post.get_lastest() return render_template('entity.html', entity=entity, post=post, posts=posts, tagged_posts=tagged_posts, last_posts=last_posts, toc=toc, content=content)
def get_template_values( self ): """Constructs and returns a dict of common values needed by all or nearly all templates""" user = users.get_current_user() template_values= { 'date' : datetime.datetime.now(), 'nav_urls' : get_navigation_urls( self, user ), } if user: try: entity = Entity.query( Entity.id == user.user_id() ).fetch()[0] template_values['user_name'] = entity.display_name template_values['bio'] = entity.bio except: # User isn't an entity yet pass template_values['user'] = user template_values['user_id'] = user.user_id() template_values['nav_grav'] = "http://www.gravatar.com/avatar/" + hashlib.md5(user.email().lower()).hexdigest() + "?s=36" else: template_values['user'] = False return template_values
def post(self): template_values = get_template_values( self ) user = users.get_current_user() try: entity_query = Entity.query( Entity.id == user.user_id() ).fetch() entity = entity_query[0] except IndexError: # This user must not exist yet, so create one entity = Entity( user = user, id = user.user_id(), created = datetime.datetime.now(), test_groups = [], ) if not entity.display_name: posted_name = self.request.get( 'display_name' ) else: posted_name = entity.display_name # Show an error if the name isn't formatted properly. if re.match('^[a-z0-9]{3,16}$', posted_name) is None: template_values['error'] = "Usernames must be 16 or fewer alphanumeric characters [a-z0-9]." path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'register.html' ) ) self.response.out.write( template.render( path, template_values )) return users_with_name = Entity.query( Entity.display_name == posted_name ).count() if users_with_name == 0 or entity.display_name == posted_name: # Update values entity.display_name = posted_name if posted_name else entity.display_name entity.bio = self.request.get( 'bio' ) if len(self.request.get( 'bio' )) > 0 else "I am mysterious." # Save and visit entity.put() time.sleep(0.1) # The user doesn't exist for a short period of time after put() self.redirect('/u/%s' % entity.display_name ) else: template_values['error'] = "That username is in use. Please choose again." path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'register.html' ) ) self.response.out.write( template.render( path, template_values )) return
def get_template_values(self): """Constructs and returns a dict of common values needed by all or nearly all templates""" user = users.get_current_user() template_values = { 'date': datetime.datetime.now(), 'nav_urls': get_navigation_urls(self, user), } if user: try: entity = Entity.query(Entity.id == user.user_id()).fetch()[0] template_values['user_name'] = entity.display_name template_values['bio'] = entity.bio except: # User isn't an entity yet pass template_values['user'] = user template_values['user_id'] = user.user_id() template_values[ 'nav_grav'] = "http://www.gravatar.com/avatar/" + hashlib.md5( user.email().lower()).hexdigest() + "?s=36" else: template_values['user'] = False return template_values
def add_test_to_template( template_values, in_test ): """Combines Test object properties into template_values""" template_values['test_id'] = in_test.id template_values['title'] = in_test.title template_values['description'] = in_test.description template_values['group'] = in_test.group template_values['level'] = in_test.level template_values['test_created'] = in_test.created template_values['test_modified'] = in_test.modified template_values['author_id'] = in_test.author_id template_values['author_name'] = Entity.query( Entity.id == in_test.author_id ).get().display_name template_values['times_taken'] = in_test.times_taken template_values['total_score'] = in_test.total_score template_values['num_marked'] = in_test.num_marked template_values['open'] = in_test.open if in_test.num_marked > 0: template_values['average_mark'] = template_values['total_score'] / template_values['num_marked'] mark_list = Mark.query( Mark.test.id == in_test.id ).filter( Mark.rating > -1 ).fetch() template_values['num_ratings'] = len(mark_list) if template_values['num_ratings'] > 0: template_values['average_rating'] = sum([mark.rating for mark in mark_list]) / template_values['num_ratings'] if template_values['average_rating'] is not in_test.average_rating: save_average_rating( in_test.id, template_values['average_rating']) return template_values
DBSession.add(new_lex) paradigm_lexes[str(entity.parent_client_id) + '_' + str(entity.parent_object_id) + '_' + str( json.loads(entity.additional_metadata)['row_id'])] = {'client_id': new_lex.client_id, 'object_id': new_lex.object_id} link_ids.append((old_parent_ids, {'client_id': new_lex.client_id, 'object_id': new_lex.object_id})) parent_ids = { 'client_id': new_lex.client_id, 'object_id': new_lex.object_id} new_entity = Entity(client_id=entity.client_id, content=entity.content, locale_id=entity.locale_id, marked_for_deletion=entity.marked_for_deletion, field_client_id=fields[entity.entity_type]['client_id'], field_object_id=fields[entity.entity_type]['object_id'], parent_client_id=parent_ids['client_id'], parent_object_id=parent_ids['object_id'], created_at=entity.created_at ) if entity.additional_metadata: new_entity.additional_metadata = json.loads(entity.additional_metadata) DBSession.add(new_entity) l1entity_ids[str(entity.client_id) + '_' + str(entity.object_id)] = { 'client_id': new_entity.client_id, 'object_id': new_entity.object_id} pub_ent = old_DBSession.query(old_publ1entity).filter_by(entity=entity).first() if pub_ent and not pub_ent.marked_for_deletion: new_entity.publishingentity.published = True DBSession.flush()
import nltk import spacy en = spacy.load('en_core_web_lg') #nltk.download('reuters') from nltk.corpus import reuters import json from models import Entity from models import Document docDict = {} from tqdm import tqdm for fid in tqdm(reuters.fileids()): # set each key in the dictionary to be the fileid... # then the value will be an empty instance of the Document class docDict[fid] = {'Doc': Document(), 'ents': []} docDict[fid]['Doc'].text = reuters.raw(fid) nlpTemp = en(docDict[fid]['Doc'].text) raw_ents = [[m.start_char, m.end_char, m.label_, m.text] for m in nlpTemp.ents] if len(nlpTemp.ents) > 0: [ docDict[fid]['ents'].append(Entity()) for x in range(len(nlpTemp.ents)) ] for x in range(len(nlpTemp.ents)): docDict[fid]['ents'][x].setOffsets(raw_ents[x][0], raw_ents[x][1]) docDict[fid]['ents'][x].setLabel(raw_ents[x][2]) docDict[fid]['ents'][x].setText(raw_ents[x][3]) docDict[fid]['Doc'].addEntity(docDict[fid]['ents'][x])
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 mouse_pos = pygame.mouse.get_pos( ) # получение координат указателя мыши ## ОБРАБОТКА НАЖАТИЙ КЛАВИАТУРЫ И МЫШИ ## for event in pygame.event.get( ): # добавляем свой функционал в цикл получения сообщений от мыши и клавиатуры if event.type == MOUSEBUTTONDOWN: # если произошло событие - нажатие кнопки мыши #mouse_pos = event.pos # Получаем x,y координаты мыши на экране игры for cur_obj in gameObjectList: # Для всех объектов проверяем попадение курсора мыши в этот объект pos_in_mask = mouse_pos[0] - cur_obj.img_rect.x, mouse_pos[ 1] - cur_obj.img_rect.y # вычисление позиции курсора относительно координат маски прозрачности объекта if cur_obj.img_rect.collidepoint( mouse_pos ) and cur_obj.img_mask.get_at( pos_in_mask ) == 1: # проверяем, находится ли мышь на каком-то объекте, и прозрачен ли пиксель, на котором находится указатель мыши cur_obj_name = 'unnamed' ### имя объекта, по-умолчанию безымянный if 'ObjectName' in cur_obj.obj_props: ### если в словаре есть свойство ИмяОбъекта cur_obj_name = cur_obj.obj_props[ "ObjectName"] ### создаем надпись с этим именем new_text_obj = models.TextObject( [mouse_pos[0], mouse_pos[1]], cur_obj_name, white_color, 1500 ) # Создаем текстовый объект с координатами указателя мыши, текстом, равным имени объекта под мышкой, белым цветом шрифтаwhite_color и временем существования 1500 миллисеукнд new_text_obj.time1 = time.time( ) # в свойство текстового объекта time1 заносим время, когда этот текст создан if pygame.mouse.get_pressed( )[2]: ### если нажата ПРАВАЯ кнопка мыши textObjectList.append( new_text_obj ) # Добавляем новую надпись(текстовый объект) в список всех надписей else: ### если нажата ЛЕВАЯ кнопка мыши, захватываем объект cur_obj.follow_mouse = True # устанавливаем флаг следования за мышкой(захватываем объект мышкой) cur_obj.follow_mouse_offset = [ mouse_pos[0] - cur_obj.pos[0], mouse_pos[1] - cur_obj.pos[1] ] # смещение мышки относительно нулевых координат области объекта break # после первого найденного объекта под мышкой, выходим из цикла, чтобы не появлялось несколько надписей в одном месте elif event.type == pygame.KEYUP: if event.key == pygame.K_e: ### Если на клавитуре нажата клавиша 'e' if World.edit_mode == None: ### Включаеv режим EDIT(Редактирования объектов) mode_text_obj = models.TextObject( [10, 10], "EDIT", white_color, -1, 40) ### создаем надпись слева вверху textObjectList.append( mode_text_obj ) ### Добавляем надпись в список всех текстовых объектов World.edit_mode = textObjectList[len(textObjectList) - 1] else: ### Если режим Редактирования уже включен, textObjectList.remove( World.edit_mode) ### Удаляем надпись World.edit_mode = None ### Отменяем режим Редактирования(EDIT) ## При выключении режима редактирования, выводим в консоль все объекты all_objects_dict = [] ###список со всеми объектами for i in range(len(gameObjectList) - 1): ### Для всех оюъектов в игре cur_obj = gameObjectList[i] ###текущий объект new_obj_dict = { 'obj_props': cur_obj. obj_props, ### все свойства объекта заносим во вложенный словарь 'posX': cur_obj.pos[0], ### Позиция X 'posY': cur_obj.pos[1], ### Позиция Y 'width': cur_obj.img_rect.w, ### Ширина картинки 'height': cur_obj.img_rect.h ### Высота картинки } all_objects_dict.append( new_obj_dict ) ### добавляем новый объект с описанием в список всех объектов json_dump = json.dumps( all_objects_dict ) ### выгружаем описание всех объектов игры в json-формате print(json.dumps( json_dump)) ### выводим полученный json в консоль elif event.key == pygame.K_r: ### Постоянное отображение рамок все объектов if World.show_rects: ### Если включено World.show_rects = False ### выключаем режим else: ### включаем, если отключено World.show_rects = True elif event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) ## ОТРИСОВКА ОБЪЕКТОВ ## player_pos = (player.x + player.offsetX, player.y + player.offsetY ) #позиция игрока на карте x,y for indx, _ in enumerate( gameObjectList): #в массиве всех созданным нами объектов cur_obj = gameObjectList[indx] if cur_obj.follow_mouse: # Если установлен флаг следования за мышкой (объект взят) if World.edit_mode != None or ( 'CanMove' in cur_obj.obj_props and cur_obj.obj_props['CanMove'] == 'True' ): ### Если включен режим редактирования(EDIT) # получение состояния нажатия всех кнопок мыши if pygame.mouse.get_pressed( )[0]: # проверяем, нажата ли ЛЕВАЯ кнопка мыши newPosX = mouse_pos[0] - cur_obj.follow_mouse_offset[ 0] # высчитываем новую позицию с учетом смещения X-координату newPosY = mouse_pos[1] - cur_obj.follow_mouse_offset[ 1] # Y-координату cur_obj.set_position( [newPosX, newPosY] ) # при зажатой кнопке мыши, переносим объект на текущую позицию мыши else: # если левая кнопка отпущена, бросаем предмет cur_obj.follow_mouse = False # отключаем следование за мышью(бросаем объект) gameObjectList.sort( key=lambda x: x.pos[1] + x.lowestY ) # снова сортируем объекты в правильном порядке по самому нижнему пикселю screen.blit( cur_obj.img, cur_obj.pos ) #рисуем картинку каждого объекта на поверхность игрового экрана if World.show_rects or ( World.edit_mode != None and cur_obj.follow_mouse ): ### Если включен режим Редактирования(EDIT), рисуем прямоугольники, очерчивающие непрозрачную область объекта и прямоугольник для коллизий opq_rect = pygame.Rect( cur_obj.pos[0] + cur_obj.opaq_rect[0], cur_obj.pos[1] + cur_obj.opaq_rect[1], cur_obj.opaq_rect[2], cur_obj.opaq_rect[3] ) ### расчет прямоугольника для отображения на игровом экране pygame.draw.rect(screen, white_color, opq_rect, 1) ### рисуем рамку объекта col_rect = pygame.Rect(cur_obj.pos[0] + cur_obj.coll_rect[0], cur_obj.pos[1] + cur_obj.coll_rect[1], cur_obj.coll_rect[2], cur_obj.coll_rect[3]) pygame.draw.rect( screen, (100, 255, 0), col_rect, 2 ) ### зеленым цветом рисуем область коллизий данного объекта if (player_pos[1] + player.rect[3]) >= ( cur_obj.pos[1] + cur_obj.lowestY ): #если самая нижняя точка игрока объекта выше игрока screen.blit(player.image, player_pos) #рисуем игрока поверх объекта if World.edit_mode != None: ### Если режим EDIT player_rect = pygame.Rect( player_pos[0], player_pos[1], player.rect[2], player.rect[3]) ### Расчитываем прямоугольник вокруг игрока pygame.draw.rect(screen, (0, 0, 255), player_rect, 2) ### рисуем рамку игрока ## ОТРИСОВКА ТЕКСТОВЫХ ОБЪЕКТОВ ## for indx, _ in enumerate( textObjectList ): # перечисляем все надписи(текстовые объекты из их общего списка) text_obj = textObjectList[ indx] # работаем с самим объектом, а не копией, как в случае просто for цикла, чтобы не тратить лишнюю память if text_obj.text_visible == False: # Если в объекте указана невидимость continue # пропускаем этот объект text_surface = pygame.font.SysFont( text_obj.font_name, text_obj.font_size).render( text_obj.text_str, False, text_obj.text_color ) # рисуем текст(создаем поверхность Surface с текстом) screen.blit( text_surface, text_obj.pos ) # накладываем поверхность с нарисованным текстом на поверхность экрана, выводя текст на игровой экран if text_obj.exist_time != -1: # если у надписи указано время существования(exist_time) elapsed = ( time.time() - text_obj.time1 ) * 1000 #проверяем сколько миллисекунд прошло со времени создания надписи if elapsed > text_obj.exist_time: # если прошло больше времени, чем указано во времени существования (exist_time) textObjectList.pop( indx) # удаляем объект из списка надписей pygame.display.flip()
def __init__(self, enemy_rect, sign=None, w=1.0): Entity.__init__(self, enemy_rect, sign, w) self.bar = Enemy_Bar(self.stats, (self.centerx, self.centery))
def post(self): user = users.get_current_user() entity = Entity.query( Entity.id == user.user_id() ).get() test_query = Test.query( ancestor = ndb.Key('Entity', entity.id ) ) test_query = test_query.filter( Test.id == self.request.get( 'id' ) ).fetch() if len(test_query) > 0: test = test_query[0] test.modified = datetime.datetime.now() else: test = Test( parent = ndb.Key('Entity', entity.id ) ) test.created = datetime.datetime.now() test.times_taken = 0 test.total_score = 0 test.num_marked = 0 test.average_rating = 0 test.open = True test.author_id = user.user_id() test.title = self.request.get( 'title' ) test.description = self.request.get( 'description' ) test.group = self.request.get( 'group' ) test.level = int(self.request.get( 'level' )) # Define rules for what is and isn't a valid group try: assert re.match('^[a-z0-9_]{2,16}$', self.request.get( 'group' )) is not None except: # If the group is invalid, try again template_values = get_template_values( self ) template_values['error'] = """There was an error with the group entered. Please ensure it uses only lowercase letters, numbers, and underscores.""" template_values['user_groups'] = set( itertools.chain( entity.test_groups, default_groups ) ) template_values['user_levels'] = json.dumps( get_grouped_marks( ndb.Key( "Entity", entity.id ) )) template_values = add_test_to_template(template_values, test) path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'create.html' ) ) self.response.out.write( template.render( path, template_values )) return # Define rules for what is and isn't a valid level for the user to be posting in. user_level = get_user_group_level( get_grouped_marks( entity.id ), test.group ) max_test_query = Test.query( Test.group == test.group ).order(-Test.level).fetch() print max_test_query try: max_test_level = max_test_query[0].level / 2 except IndexError: max_test_level = 0 if user_level < max_test_level or user_level < test.level: # User level is not high enough. template_values = get_template_values( self ) if user_level < max_test_level: template_values['error'] = "You must be at least level %d in %s to create a test." \ "You are only level %d." \ % ( math.floor(max_test_level), test.group, user_level) elif user_level < test.level: template_values['error'] = """You must be at least level %d in %s to create a level %d test .""" \ % ( test.level, test.group, test.level) template_values['user_groups'] = set( itertools.chain( entity.test_groups, default_groups ) ) template_values['user_levels'] = json.dumps( get_grouped_marks( entity_id=entity.id ) ) template_values = add_test_to_template(template_values, test) path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'create.html' ) ) self.response.out.write( template.render( path, template_values )) return # Create an id and save the test if the group is valid #test.id = str( test.put().id() ) test.id = ''.join(random.choice(string.digits+string.ascii_lowercase) for x in range(20)) test.put() # Keep track of which test groups a user has used if test.group not in entity.test_groups: entity.test_groups.append(test.group) entity.put() # Add/Alter this test's Document in the search index test_as_document = search.Document( doc_id = test.id, fields = [ search.AtomField( name="group", value=test.group ), search.TextField( name="title", value=test.title ), search.NumberField( name="times_taken", value=test.times_taken ), search.DateField( name="date", value=test.created ), search.NumberField( name="level", value=test.level ), search.NumberField( name="rating", value=test.average_rating ), ] ) try: index = search.Index(name="tests") index.put( test_as_document ) except search.Error: logging.info("Index put failed") self.redirect('/t/%s' % test.id ) return
def message(bot, update): chat_id = update.message.chat_id user_id = update.message.from_user.id msg = update.message.text username = update.message.from_user.username fullname = " ".join([ update.message.from_user.first_name, update.message.from_user.last_name ]) chat_type = update.message.chat.type chat_title = update.message.chat.title # If message from group if chat_type == 'group' or chat_type == 'supergroup': # Add chat and user to DB User().add(user_id, username, fullname) Chat().add(chat_id, chat_title, bot.getChat(chat_id).username) if update.message.photo: Entity().add(chat_id, 'photo', None) if update.message.video: Entity().add(chat_id, 'video', None) if update.message.audio: Entity().add(chat_id, 'audio', None) if update.message.voice: Entity().add(chat_id, 'voice', None) if update.message.document: Entity().add(chat_id, 'document', None) for entity in update.message.entities: # http://link.com if entity['type'] == 'url': link = msg[entity['offset']:entity['offset'] + entity['length']] link = re.sub('(.*)://', '', link) link = link.split('/')[0] Entity().add(cid=chat_id, type='url', title=link) # /command if entity['type'] == 'bot_command': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='bot_command', title=title) # #hashtag if entity['type'] == 'hashtag': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='hashtag', title=title) # @username if entity['type'] == 'mention': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='mention', title=title) user_stat = UserStat.get(user_id, chat_id) # If user already in group if user_stat: today = datetime.today().day last_activity = datetime.fromtimestamp( timestamp=user_stat.last_activity).day # If last activity was not today if (timedelta(today).days - timedelta(last_activity).days) != 0: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 1}) else: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 0}) else: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 1}) # Update user messages count UserStat().add(user_id, chat_id) else: # If message from user pass
def archives(): entities = Entity.query().order(Entity.name) return render_template('archives.html', entities=entities)
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 for event in pygame.event.get(): if event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) pygame.display.flip()
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 for event in pygame.event.get(): if event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit(level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit(level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit(player.image, (player.x + player.offsetX, player.y + player.offsetY)) pygame.display.flip()
def archives(): entities = Entity.query().order(Entity.name) last_posts = Post.get_lastest() return render_template('archives.html', last_posts=last_posts, entities=entities)