def addRecord(data): """ The incoming 'data' paramater should be a tuple of two dictionaries in the following format: ("author":{"first_name":"John", "last_name":"Doe"}, "book":{"title":"Some book", "isbn":"1234567890", "publisher":"Packt"} ) """ # Create an instance of the Book and Person classes and populate them with the values # collected from the 'Add' dialog and passed in as the tuple of dictionaries. book = Book() book.title = data['book']['title'] book.isbn = data['book']['isbn'] book.publisher = data['book']['publisher'] author = Person() author.first_name = data['author']['first_name'] author.last_name = data['author']['last_name'] book.person = author # Create a session, connect to the database, commit and close the connection. session = connectToDatabase() session.add(book) session.commit() session.close
def validate(self, a_string): list_ = Validator.clean_input(a_string) id_, gender, age, sales, bmi, income = self.__unpack_list(list_) while not Validator.has_valid_id(id_): id_ = Validator.clean_id(self.request_new_value(id_, "A123", "id")) while not Validator.has_valid_gender(gender): gender = Validator.clean_gender(self.request_new_value(gender, "M", "gender")) while not Validator.has_valid_age(age): age = Validator.clean_age(self.request_new_value(age, "01", "age")) while not Validator.has_valid_sales(sales): sales = Validator.clean_sales(self.request_new_value(sales, "001", "sales")) while not Validator.has_valid_bmi(bmi): bmi = Validator.clean_bmi(self.request_new_value(bmi, "Normal, Overweight, Obesity, Underweight", "bmi")) while not Validator.has_valid_income(income): income = Validator.clean_income(self.request_new_value(income, "00-100", "income")) p = Person(Validator.clean_id(id_), Validator.clean_gender(gender), Validator.clean_age(age), Validator.clean_sales(sales), Validator.clean_bmi(bmi), Validator.clean_income(income)) self._good_data.update({p.get_id(): p}) self._raw_data.remove(a_string) return p
def is_stable(instance, matching): ''' 対象のマッチングが安定かどうか判定する。 ナイーブな実装のためO(n^2)の計算量を必要とする。 Parameters ---------- instance : Instance 安定結婚問題のインスタンスオブジェクト。 matching : Matching マッチングオブジェクト。 Returns ------- is_stable : bool 安定であればTrue。 pair : (Person, Person) マッチングが非安定であればブロッキングペア。 安定であれば無効値。 ''' for man in instance.men: for woman in instance.women: # 男性側に駆け落ちするインセンティブが存在 man_dissatisfaction = man.prefers(woman, matching.search_wife(man)) # 女性側に駆け落ちするインセンティブが存在 woman_dissatisfaction = woman.prefers(man, matching.search_husband(woman)) if man_dissatisfaction and woman_dissatisfaction: return False, (man, woman) return True, (Person(0, -1), Person(0, -1))
def submit_newcourse(): """ create new course """ #print_debug('submit_newcourse: {}'.format(request.form)) name = request.form['name'] # e.g. "Intro Programming" path = request.form[ 'path'] # should have form term/folder e.g. fall2018/cs1 copyfrom = request.form['copyfrom'] # e.g. "fall2017/cs1" startdate = path_to_startdate(path) title = name_to_htmltitle(name) print_debug(' submit_newcourse: name = "{}"'.format(name)) print_debug(' path = "{}"'.format(path)) print_debug(' copyfrom = "{}"'.format(copyfrom)) newcourse = Course.create_course(name, path, start=startdate, name_as_title=title, copyfrom=copyfrom) for name in request.form['faculty'].split(','): try: faculty = Person.get(username=name.strip()) except: faculty = None if not faculty: try: faculty = Person.get(username=name.strip()) except: faculty = None if faculty: today = str(Time())[:10] newcourse.enroll(faculty, 'faculty', today, create_work=False) return newcourse.url
def submit_newuser(): """ create new user """ username = request.form['username'] name = request.form['name'] email = request.form['email'] password = request.form['password'] print_debug(' create_person: ' + \ 'username={} name="{}" email={} password=""'.format( username, name, email, password)) Person.create_person(username, name, email, password) return url_base + '/sys/user?username=' + username
def submit_edituser(): """ edit existing user - admin only """ username = request.form['username'] name = request.form['name'] email = request.form['email'] password = request.form['password'] print_debug(' submit_edituser: '******'username={} name="{}" email={} password=""'.format( username, name, email, password)) Person.edit_person(username, name, email, password) return request.base_url + '?username=' + username
def test_two_people(person_a: Person, person_b: Person): if person_a.id == person_b.id: person_a.friends = (person_b.id, ) assert len(person_a.friends) == 0 else: person_a.friends = (person_b.id, ) person_b.friends = (person_a.id, ) diff = get_account_difference(people={ person_a.id: person_a, person_b.id: person_b }) assert diff[person_a.id] == diff[person_b.id] assert len(diff) == 2
def add_record(session, data): book = Book() book.title = data["book"]["title"] book.isbn = data["book"]["isbn"] book.publisher = data["book"]["publisher"] author = Person() author.first_name = data["author"]["first_name"] author.last_name = data["author"]["last_name"] book.person = author # try: session.add(book) session.commit()
def input_people(csvfilename): """ create users from a .csv file defining them """ with row in csv.DictReader(open(csvfilename)): username = name = row['name'] email = row.get('email', username+'@marlboro.edu') password = row.get('password', username+'*05344*') # CHANGEME Person.create_person( username = row['username'], name = row['name'] email = username+'@marlboro.edu' password = password ) coursepath = row['coursepath']
def post(self): # parse passed in data args = new_person_parser.parse_args() # create new person with passed in data new_person = Person(args['firstName'], args['lastName'], args['dateOfBirth'], args['zipCode']) # try to add new user to DB try: db.session.add(new_person) db.session.commit() return new_person.serialize() except Exception as e: return {"message": "Unknown error occured while adding new user"}
def calc_man_best_wife_pair(instance): ''' 各男性について、安定マッチングでマッチしうる女性のうち最も好みの女性を求める。 Parameters ---------- instance : Instance 安定結婚問題のインスタンス。 Returns ------- 該当女性とのペアのリスト。 ''' all_matching = SMUtil.create_all_matching(instance) best_wife_list = [Person(0, -1)] * instance.size # 無効値で初期化 for matching in all_matching: is_stable, _ = SMUtil.is_stable(instance, matching) if not is_stable: continue for pair in matching.pairs: man = pair[0] woman = pair[1] if best_wife_list[man.index].index == -1: best_wife_list[man.index] = woman continue if man.prefers(woman, best_wife_list[man.index]): best_wife_list[man.index] = woman best_pair_list = [(man_index, woman.index) for man_index, woman in enumerate(best_wife_list) ] best_pair_list.sort() return best_pair_list
def get_person(self, person_id): try: person = self.conference.persons[person_id] except KeyError: person = Person(person_id) self.conference.persons[person_id] = person return person
def get(self): viewer_id = self.request.get('viewer_id', '') if viewer_id.find('googlewave.com') > -1: gadget_key = viewer_id.split('@')[0] else: gadget_key = viewer_id viewer_name = self.request.get('viewer_name', '') viewer_thumbnail = self.request.get('viewer_thumbnail', '') # compress viewer latlng = self.request.get('latlng', '') country = self.request.get('country', '') wavelet = self._robot.fetch_wavelet('googlewave.com!w+0iIr7fEYA', "googlewave.com!conv+root") delta = {} delta[gadget_key] = latlng.replace(' ', '') + ',' + country wavelet.root_blip.first(element.Gadget).update_element(delta) self._robot.submit(wavelet) person = Person.get_or_insert(viewer_id) person.name = viewer_name person.thumbnail = viewer_thumbnail person.country = country logging.info(person.name) person.put() oldlocation = person.location coord_list = latlng.split(',') lat = float(coord_list[0]) lng = float(coord_list[1]) person.location = db.GeoPt(lat, lng) person.update_location() person.put()
def get(self): if self.config.search_auth_key_required and not ( self.auth and self.auth.search_permission): return self.error(403, 'Missing or invalid authorization key\n') pfif_version = pfif.PFIF_VERSIONS.get(self.params.version or '1.2') # Retrieve parameters and do some sanity checks on them. query_string = self.request.get("q") subdomain = self.request.get("subdomain") max_results = min(self.params.max_results or 100, HARD_MAX_RESULTS) if not query_string: return self.error(400, 'Missing q parameter') if not subdomain: return self.error(400, 'Missing subdomain parameter') # Perform the search. results = indexing.search(Person.all_in_subdomain(subdomain), TextQuery(query_string), max_results) records = [pfif_version.person_to_dict(result) for result in results] utils.optionally_filter_sensitive_fields(records, self.auth) # Define the function to retrieve notes for a person. def get_notes_for_person(person): notes = model.Note.get_by_person_record_id( self.subdomain, person['person_record_id']) records = map(pfif_version.note_to_dict, notes) utils.optionally_filter_sensitive_fields(records, self.auth) return records self.response.headers['Content-Type'] = 'application/xml' pfif_version.write_file(self.response.out, records, get_notes_for_person)
def get(self): if self.config.search_auth_key_required and not (self.auth and self.auth.search_permission): return self.error(403, "Missing or invalid authorization key\n") pfif_version = pfif.PFIF_VERSIONS.get(self.params.version or "1.2") # Retrieve parameters and do some sanity checks on them. query_string = self.request.get("q") subdomain = self.request.get("subdomain") max_results = min(self.params.max_results or 100, HARD_MAX_RESULTS) if not query_string: return self.error(400, "Missing q parameter") if not subdomain: return self.error(400, "Missing subdomain parameter") # Perform the search. results = indexing.search(Person.all_in_subdomain(subdomain), TextQuery(query_string), max_results) records = [pfif_version.person_to_dict(result) for result in results] utils.optionally_filter_sensitive_fields(records, self.auth) # Define the function to retrieve notes for a person. def get_notes_for_person(person): notes = model.Note.get_by_person_record_id(self.subdomain, person["person_record_id"]) records = map(pfif_version.note_to_dict, notes) utils.optionally_filter_sensitive_fields(records, self.auth) return records self.response.headers["Content-Type"] = "application/xml" pfif_version.write_file(self.response.out, records, get_notes_for_person)
def get_person(name): """ Page with details for a specific person. """ person = Person.select(graph, name).first() movies = [(movie.title, "Actor") for movie in person.acted_in] + \ [(movie.title, "Director") for movie in person.directed] return template("person", person=person, movies=movies)
def add_person(self, email, nickname=None, website=None, bio=None): """ Add a new Person to the database :type email: str :param email: This Person's email address :type nickname: str :param nickname: This Person's nickname :type website: str :param website: This Person's website :type website: str :param bio: This Person's bio """ if not self.person_exists(email=email): # If no nickname is specified, just use the first bit of their # email as a convenient default. if not nickname: nickname = email.split('@')[0] new_person = Person(email=email, nickname=nickname, website=website, bio=bio) self.session.add(new_person) self.session.flush() return email return False
def login(): form = LoginForm(request.form) if form.button_login.data and form.validate(): user_name = form.login.data role_name = form.user_type.data user = None class_map = Person.get_class_map() if not role_name: for clazz in class_map.values(): user = user or db.session.query(clazz).filter(clazz.login == user_name).one_or_none() elif role_name in class_map.keys(): clazz = class_map[role_name] user = user or db.session.query(clazz).filter(clazz.login == user_name).one_or_none() if user is not None: password = form.password.data if password_checker(user_name, password): login_user(user) return redirect(request.args.get("next") or url_for('index')) else: form.password.errors.append("Неверный пароль") else: form.login.errors.append("Пользователя с таким учётным именем не существует") return render_template('login.html', form=form)
def createStaff(): params = request.args name = params["name"] page = params["page"] phone = params.get("phone", "") email = params.get("email", "") photo = params.get("photo", "") address = params.get("address", "") newStaff = Person(name=name, page=page, phone=phone, email=email, photo=photo, address=address) return dumps(newStaff.toDict())
def calc_woman_worst_husband_pair(instance): ''' 各女性について、安定マッチングでマッチしうる男性のうち最も好みでない男性を求める。 Parameters ---------- instance : Instance 安定結婚問題のインスタンス。 Returns ------- 該当男性とのペアのリスト。 ''' all_matching = SMUtil.create_all_matching(instance) worst_husband_list = [Person(0, -1)] * instance.size # 無効値で初期化 for matching in all_matching: is_stable, _ = SMUtil.is_stable(instance, matching) if not is_stable: continue for pair in matching.pairs: man = pair[0] woman = pair[1] if worst_husband_list[woman.index].index == -1: worst_husband_list[woman.index] = man continue if woman.prefers(worst_husband_list[woman.index], man): worst_husband_list[woman.index] = man worst_pair_list = [(man.index, woman_index) for woman_index, man in enumerate(worst_husband_list)] worst_pair_list.sort() return worst_pair_list
def OK_btn(self): # 判断人脸是否存在 faceid = getFaceOf(self.faceEncode, self.channelDict["faceLib"]) if faceid != 0: QMessageBox.warning(self, '警告', '该人脸已存在!', QMessageBox.Yes) return elif self.ADD_name_edit.text() == "": QMessageBox.warning(self, '警告', '请输入信息!', QMessageBox.Yes) elif faceid == 0: PDI = person_dao_impl.PersonDaoImpl() # 获得personClass的ID personClassID = getKeyByValue(self.channelDict["personClass"], self.ADD_comboBox.currentText()) # 先添加人员 PDI.addPerson( Person(self.faceEncode, self.ADD_name_edit.text(), int(personClassID), "null")) # 获得最后一条记录 personID = int(self.PDI.getLastPersonID()) # 保存图片 然后获得图片路径 file_path = saveRGB2JPG( self.img, "person/{0}_{1}".format(personID, getCurDateTime())) # 再填充人员图片信息 PDI.setPersonPicPath(personID, file_path) # 实时更新人脸库 self.channelDict["DataGetThreadContent"].append("updateFaceLib") self.channelDict["DataGetThreadEvent"].set() QMessageBox.information(self, '恭喜', '注册成功!', QMessageBox.Yes) self.closeAll()
def testSecond(self): session.query(Event).delete() session.query(Person).delete() session.query(Place).delete() session.commit() place = Place('First place') place.address = 'Address' place.phone = 'Phone' place.site_url = 'http://localhost' persons_list = [] persons_list.append(Person('First', Person.MUSICIAN)) persons_list.append(Person('Second', Person.MUSICIAN)) e = Event(self.et) e.place = place for p in persons_list: e.persons.append(p) session.add(e) session.commit() session.flush() first_query = self.first_query all_first = first_query.all() self.assertEquals(len(all_first), 1) e = all_first[0] place = e.place self.assertEquals(place.address, 'Address') self.assertEquals(place.phone, 'Phone') self.assertEquals(place.site_url, 'http://localhost') person_names = [] for p in e.persons: person_names.append(p.name) self.assert_('First' in person_names) self.assert_('Second' in person_names) e = Event(EventType.findByName(session, 'live'), 'Live event') e.addEventStatus(EventStatus(EventStatus.LIVE_WANT)) e.addEventStatus(EventStatus(EventStatus.LIVE_BE_HERE)) session.add(e) session.commit() session.flush() events = self.live_query.all() self.assertEquals(len(events), 1) e = events[0] self.assertEquals(len(e.event_status_list), 2) self.assertEquals(e.last_status, EventStatus.LIVE_BE_HERE)
def OccupationSearch(self, occupation = None, **kw): occupations = [] if occupation: search = Person.select(Person.q.Occupation.contains(str(occupation)),distinct=True) #log.debug("Occupation results %d" % search.count()) for person in search: occupations.append(person.Occupation) # occupations = set(occupations) return dict(occupations=occupations)
def submit_enroll(): """ Enroll someone in this course. """ username = request.form['username'] rolename = request.form['submit_enroll'] print_debug(' submit_enroll: user={}, role={}'.format(username, rolename)) user = Person.by_username(username) request.page.course.enroll(user, rolename, create_work=(rolename == 'student')) return request.page.url
def get_by_name(cls, name): sql = """select * from person where name=?""" data = (name, ) rows = cls.db.query(sql, data) records = [] for row in rows: records.append( Person(row[0], row[1], row[2], row[3], dt.fromtimestamp(row[4]), dt.fromtimestamp(row[5]))) return records
def load_user(user_name): if "@" not in user_name: return None role_name, ulogin = user_name.split("@", 1) class_map = Person.get_class_map() user = None if role_name in class_map.keys(): clazz = class_map[role_name] user = user or db.session.query(clazz).filter(clazz.login == ulogin).one_or_none() return user
def make_courses(csvfilename='courses_jan2018.csv'): """ create courses from a .csv file defining them """ # csvfile : name, name_as_title, path, faculty for row in csv.DictReader(open(csvfilename)): course = Course.create_course(name=row['name'], name_as_title=row['name_as_title'], path=row['path'], start=term, copy_generic=True) faculty = Person.by_username(row['faculty']) course.enroll(faculty, 'faculty', spring2018)
def add_record(session, data): """ Data should be a dictionary of two dictionaries in the following format: {"author":{"first_name":"John", "last_name":"Doe"}, "book":{"title":"Some book", "isbn":"1234567890", "publisher":"Packt"} } """ book = Book() book.title = data["book"]["title"] book.isbn = data["book"]["isbn"] book.publisher = data["book"]["publisher"] author = Person() author.first_name = data["author"]["first_name"] author.last_name = data["author"]["last_name"] book.person = author session.add(book) session.commit()
class Test(unittest.TestCase): """ The basic class that inherits unittest.TestCase """ person = PersonClass.Person() # instantiate the Person Class user_id = [] # variable that stores obtained user_id user_name = [] # variable that stores person name # test case function to check the Person.set_name function def test_0_set_name(self): print("Start set_name test\n") """ Any method which starts with ``test_`` will considered as a test case. """ for i in range(4): # initialize a name name = 'name' + str(i) # store the name into the list variable self.user_name.append(name) # get the user id obtained from the function user_id = self.person.set_name(name) # check if the obtained user id is null or not self.assertIsNotNone(user_id) # null user id will fail the test # store the user id to the list self.user_id.append(user_id) print("user_id length = ", len(self.user_id)) print(self.user_id) print("user_name length = ", len(self.user_name)) print(self.user_name) print("\nFinish set_name test\n") # test case function to check the Person.get_name function def test_1_get_name(self): print("\nStart get_name test\n") """ Any method that starts with ``test_`` will be considered as a test case. """ length = len(self.user_id) # total number of stored user information print("user_id length = ", length) print("user_name length = ", len(self.user_name)) for i in range(6): # if i not exceed total length then verify the returned name if i < length: # if the two name not matches it will fail the test case self.assertEqual(self.user_name[i], self.person.get_name(self.user_id[i])) #self.assertEqual(self.user_name[i], 'banana') else: print("Testing for get_name no user test") # if length exceeds then check the 'no such user' type message self.assertEqual('There is no such user', self.person.get_name(i)) print("\nFinish get_name test\n")
def ReceiptSearch(self, PersonID=None, **kw): receipts = [] if PersonID: try: person = Person.get(int(PersonID)) customer = person.Customer[0] for receipt in customer.Receipts: receipts.append((receipt.id, '%d Items purchased on %s (%s)' % (receipt.CountPurchasedItems(), receipt.ModifyTime.strftime(DATE_FORMAT), receipt.StatusText()), receipt.TotalPaymentCalc())) except: log.debug("No receipts for person") return dict(headers = ['id','Description','Total'], rows=receipts)
def main(): currentdate=date.today(); creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('people', 'v1', credentials=creds) # Call the People API results = service.people().connections().list( resourceName='people/me', pageSize=500, personFields='names,birthdays,phoneNumbers,biographies').execute() connections = results.get('connections', []) birthday_people=[] #list [1,2,3,4] - unique #Dict[{"name":1,"rollno":2},{"name":2,"rollno:3"}] #set[1,2,3,4,4,] -- can contain same values for person in connections: names = person.get('names', []) birthdays = person.get('birthdays',[]) notes = person.get('biographies',[]) if names and birthdays: wish=None name = names[0].get('displayName') birthday = birthdays[0].get('date') if (currentdate.day == birthday['day'] and currentdate.month == birthday['month']): if notes: wish=notes[0].get('value') birthday_person=Person(name,wish) birthday_people.append(birthday_person) if birthday_people: sendTextMessage(birthday_people) else: print('no birthdays today!')
def before_request(): engine, DB = model.connect() g.db = DB() id = session.get('id', None) if id: g.me = g.db.query(Person).filter_by(id = id).first() else: g.me = Person() g.db.add(g.me) g.db.commit() session['id'] = g.me.id
def response(): action = cgi_get("action", choices=["register"]) if action == "register": z = getzip(cgi_get("zip")) p = Person() p.zipcode = z.key p.name = cgi_get("name", required=False) p.email = cgi_get("email", required=False) p.put() succeed(p.key.urlsafe())
def PaymentSearch(self, PersonID=None, **kw): payments = [] if PersonID: try: person = Person.get(int(PersonID)) customer = person.Customer[0] log.debug("Payments count %d" % len(customer.Payments)) for payment in customer.Payments: payments.append((payment.id, '%s on %s' % (payment.Type(), payment.DatePaid.strftime(DATE_FORMAT)), payment.Amount)) except: log.debug("No payments for person") return dict(payments=payments)
def get(self): participant_ids = self.request.get('participant_ids').split(',') info = [] for participant_id in participant_ids: if len(participant_id) > 3: if participant_id.find('@') < 0: participant_id = participant_id + '@googlewave.com' person = Person.get_by_key_name(participant_id) thumbnail = person.thumbnail if thumbnail and thumbnail.find('http') < 0: thumbnail = 'http:%s' % thumbnail info.append({'address': participant_id, 'name': person.name, 'thumbnail': thumbnail}) self.response.out.write(simplejson.dumps(info))
def job(name): global session print(f"id session:{id(session)}") person = Person(name='frank-' + name, mobile='111111', id_card_number='123456789') print(f"{name} person is add..") session.add(person) time.sleep(1) if name == 'job3': # 线程3 提交, 其他线程不提交. session.commit() session.close()
def addRecord(data): """ Data should be a tuple of two dictionaries in the following format: ("author":{"first_name":"John", "last_name":"Doe"}, "book":{"title":"Some book", "isbn":"1234567890", "publisher":"Packt"} ) """ book = Book() book.title = data["book"]["title"] book.isbn = data["book"]["isbn"] book.publisher = data["book"]["publisher"] author = Person() author.first_name = data["author"]["first_name"] author.last_name = data["author"]["last_name"] book.person = author # connect to session and commit data to database session = connectToDatabase() session.add(book) session.commit() session.close()
def post(self): # TODO: factor all this out somewhere shared person = Person.create_original( self.repo, entry_date=utils.get_utcnow(), family_name=self.params.family_name, given_name=self.params.given_name, age=self.params.age, sex=self.params.sex, home_city=self.params.home_city, home_state=self.params.home_state, home_country=self.params.home_country, ) if self.params.photo: p, photo_url = photo.create_photo(self.params.photo, self) p.put() person.photo = p person.photo_url = photo_url person.update_index(['old', 'new']) person.put_new() json = {'personId': person.record_id} self._return_json(json)
def init_data(): d = Person.create(name="doc1", social_number="1", address="calle 30", location="Yucatan", type="1") Person.create(name="Andres Vargas", social_number="2", address="calle 30", location="Yucatan", type="1") Person.create(name="Andres Vargas2", social_number="3", address="calle 30", location="Yucatan", type="1") p = Person.create(name="Andres Vargas3", social_number="4", address="calle 30", location="Yucatan", type="1") c = Consult.create(paciente=p, doctor=d, sintomas="niguno", diagnostico="ninguno", tratamiento="none", notas="" )
def post(self): if not (self.auth and self.auth.search_permission and self.auth.domain_write_permission == '*'): self.info( 403, message= '"key" URL parameter is either missing, invalid or ' 'lacks required permissions. The key\'s repo must be "*", ' 'search_permission must be True, and it must have write ' 'permission with domain name "*".', style='plain') return body = self.request.body_file.read() doc = xml.dom.minidom.parseString(body) message_text = self.get_element_text(doc, 'message_text') receiver_phone_number = self.get_element_text( doc, 'receiver_phone_number') if message_text is None: self.info( 400, message='message_text element is required.', style='plain') return if receiver_phone_number is None: self.info( 400, message='receiver_phone_number element is required.', style='plain') return repo = ( self.config.sms_number_to_repo and self.config.sms_number_to_repo.get(receiver_phone_number)) if not repo: self.info( 400, message= 'The given receiver_phone_number is not found in ' 'sms_number_to_repo config.', style='plain') return query_lang = None query_action = None match = None for lang, action, regex in HandleSMS.QUERY_PATTERNS: match = re.search(regex, message_text.strip(), re.I) if match: query_lang = lang query_action = action break if query_lang: # Use the language for the following calls of _(). django_setup.activate(query_lang) responses = [] if query_action == 'search': query_string = match.group(1).strip() query = TextQuery(query_string) persons = indexing.search(repo, query, HandleSMS.MAX_RESULTS) if persons: for person in persons: responses.append(self.render_person(person)) else: responses.append( _('No results found for: %(query)s') % {'query': query_string}) responses.append( _('More at: %(url)s') % {'url': 'google.org/personfinder/%s?ui=light' % repo}) responses.append( _('All data entered in Person Finder is available to the ' 'public and usable by anyone. Google does not review or ' 'verify the accuracy of this data ' 'google.org/personfinder/global/tos')) elif self.config.enable_sms_record_input and query_action == 'add': name_string = match.group(1).strip() person = Person.create_original( repo, entry_date=utils.get_utcnow(), full_name=name_string, family_name='', given_name='') person.update_index(['old', 'new']) note = Note.create_original( repo, entry_date=utils.get_utcnow(), source_date=utils.get_utcnow(), person_record_id=person.record_id, author_name=name_string, author_made_contact=True, status='is_note_author', text=message_text) db.put(note) model.UserActionLog.put_new('add', note, copy_properties=False) person.update_from_note(note) db.put(person) model.UserActionLog.put_new('add', person, copy_properties=False) responses.append(_('Added a record for: %(person_name)s') % {'person_name': name_string}) else: usage_str = 'Usage: "Search John"' if self.config.enable_sms_record_input: usage_str += ' OR "I am John"' responses.append(usage_str) # Convert the response into ASCII because the SMS pipeline doesn't # support UTF-8. # e.g., It removes diacritics such as "ú" -> "u". # This seems acceptable for Spanish, but may not be for other # languages. ascii_response = unidecode(u' ## '.join(responses)) self.response.headers['Content-Type'] = 'application/xml; charset=utf-8' self.write( '<?xml version="1.0" encoding="utf-8"?>\n' '<response>\n' ' <message_text>%s</message_text>\n' '</response>\n' % django.utils.html.escape(ascii_response))
break else: # personList에 있는 각 Person 객체에 해당 nickName이 없는 경우 usercomments['total']=float(lectureLine[idx+2].split(' : ')[1]) if usercomments['total'] < 3 : usercomments['grade_poor']=True elif usercomments['total'] < 5 : usercomments['grade_average']=True else : usercomments['grade_good']=True usercomments['difficulty']=float(lectureLine[idx+3].split(' : ')[1]) usercomments['studyTime']=float(lectureLine[idx+4].split(' : ')[1]) usercomments['attendance']=float(lectureLine[idx+5].split(' : ')[1]) usercomments['grade']=float(lectureLine[idx+6].split(' : ')[1]) usercomments['achievement']=float(lectureLine[idx+7].split(' : ')[1]) onePerson = Person() onePerson.nickName = nickName onePerson.total = float(lectureLine[idx+2].split(' : ')[1]) onePerson.difficulty = float(lectureLine[idx+3].split(' : ')[1]) onePerson.studyTime = float(lectureLine[idx+4].split(' : ')[1]) onePerson.attendance = float(lectureLine[idx+5].split(' : ')[1]) onePerson.grade = float(lectureLine[idx+6].split(' : ')[1]) onePerson.achievement = float(lectureLine[idx+7].split(' : ')[1]) onePerson.lectureList.append(lectureID) personList.append(onePerson) oneLecture.comments.append(usercomments) lectureList.append(oneLecture) # 생성한 oneLecture를 lectureList를 담음
def post(self): if not (self.auth and self.auth.search_permission and self.auth.domain_write_permission == '*'): self.info( 403, message= '"key" URL parameter is either missing, invalid or ' 'lacks required permissions. The key\'s repo must be "*", ' 'search_permission must be True, and it must have write ' 'permission.', style='plain') return body = self.request.body_file.read() doc = xml.dom.minidom.parseString(body) message_text = self.get_element_text(doc, 'message_text') receiver_phone_number = self.get_element_text( doc, 'receiver_phone_number') if message_text is None: self.info( 400, message='message_text element is required.', style='plain') return if receiver_phone_number is None: self.info( 400, message='receiver_phone_number element is required.', style='plain') return repo = ( self.config.sms_number_to_repo and self.config.sms_number_to_repo.get(receiver_phone_number)) if not repo: self.info( 400, message= 'The given receiver_phone_number is not found in ' 'sms_number_to_repo config.', style='plain') return responses = [] search_m = re.search(r'^search\s+(.+)$', message_text.strip(), re.I) add_self_m = re.search(r'^i am\s+(.+)$', message_text.strip(), re.I) if search_m: query_string = search_m.group(1).strip() query = TextQuery(query_string) persons = indexing.search(repo, query, HandleSMS.MAX_RESULTS) if persons: for person in persons: responses.append(self.render_person(person)) else: responses.append('No results found for: %s' % query_string) responses.append( 'More at: google.org/personfinder/%s?ui=light' % repo) responses.append( 'All data entered in Person Finder is available to the public ' 'and usable by anyone. Google does not review or verify the ' 'accuracy of this data google.org/personfinder/global/tos.html') elif self.config.enable_sms_record_input and add_self_m: name_string = add_self_m.group(1).strip() person = Person.create_original( repo, entry_date=utils.get_utcnow(), full_name=name_string, family_name='', given_name='') person.update_index(['old', 'new']) note = Note.create_original( repo, entry_date=utils.get_utcnow(), source_date=utils.get_utcnow(), person_record_id=person.record_id, author_name=name_string, author_made_contact=True, status='is_note_author', text=message_text) db.put(note) model.UserActionLog.put_new('add', note, copy_properties=False) person.update_from_note(note) db.put(person) model.UserActionLog.put_new('add', person, copy_properties=False) responses.append('Added record for found person: %s' % name_string) else: usage_str = 'Usage: "Search John"' if self.config.enable_sms_record_input: usage_str += ' OR "I am John"' responses.append(usage_str) self.response.headers['Content-Type'] = 'application/xml' self.write( '<?xml version="1.0" encoding="utf-8"?>\n' '<response>\n' ' <message_text>%s</message_text>\n' '</response>\n' % django.utils.html.escape(' ## '.join(responses)))
def add_people(): pjson = json.loads(request.data) person = Person(pjson.get('name')) person.save() return jsonify({'result': "Ok"})
def view(): # load Object data with open('objectData.pkl', 'rb') as input: lectureList = pickle.load(input) personList = pickle.load(input) # userId, userPw 받아옴 userId = request.form['userId'] userPw = request.form['userPw'] # ghost 모듈을 이용하여 crawling a = KuKlueCrawler(id=userId,pw=userPw) page, resource = a.openPage('http://klue.kr/myLectureEval.php') page, resource = a.ghost.evaluate("document.getElementsByClassName('mainContent');") page = unicode(page[PyQt4.QtCore.QString(u'0')][PyQt4.QtCore.QString(u'outerHTML')]).encode('utf-8') lec = BeautifulSoup(page) lecContent = lec.find('div',{'class':['lectureEvalList']}).findAll('div',{'class':['content']}) # 자신에 대한 Person 객체 생성 me = Person() me.nickName = lecContent[0].find('div',{'class':['wrInfo']}).a.text.encode('utf-8') # 자신이 평가한 항목에 대해 평균 점수를 매김 lectureCount = 0 for item in lecContent: try: me.difficulty += len(item.find('div',{'class':['e difficulty']}).find('div','center').findAll('span','active')) me.total += len(item.find('div',{'class':['e total']}).find('div','center').findAll('span','active')) me.studyTime += len(item.find('div',{'class':['e studyTime']}).find('div','center').findAll('span','active')) me.attendance += len(item.find('div',{'class':['e attendance']}).find('div','center').findAll('span','active')) me.grade += len(item.find('div',{'class':['e grade']}).find('div','center').findAll('span','active')) me.achievement += len(item.find('div',{'class':['e achievement']}).find('div','center').findAll('span','active')) lectureCount+=1 except: # except가 뜨는 부분은 신형 데이터를 읽었을 경우 me.difficulty /= lectureCount me.total /= lectureCount me.studyTime /= lectureCount me.attendance /= lectureCount me.grade /= lectureCount me.achievement /= lectureCount break # 유사도 계산 알고리즘에 넣고 결과값(유사한 사람) 반환 result = topMatches(personList,me) classList = [] # for calculating error totalCount = 0 Etotal = 0.0 Edifficulty = 0.0 EstudyTime = 0.0 Eattendance = 0.0 Egrade = 0.0 Eachievement = 0.0 # 결과값에 대한 강의 정리 for person in result: similarity = person[0] for lectureID in person[1].lectureList: for oneLecture in lectureList: if float(oneLecture.total)<2.5: continue if oneLecture.lectureID == lectureID: ##### for calculating error ##### Etotal += float(oneLecture.total) Edifficulty += float(oneLecture.difficulty) EstudyTime += float(oneLecture.studyTime) Eattendance += float(oneLecture.attendance) Egrade += float(oneLecture.grade) Eachievement += float(oneLecture.achievement) totalCount += 1 ################################# classList.append((similarity*float(oneLecture.total)/5,oneLecture)) break Etotal /= totalCount Edifficulty /= totalCount EstudyTime /= totalCount Eattendance /= totalCount Egrade /= totalCount Eachievement /= totalCount print print "Total Eval Error : " + str(me.total-Etotal) print "difficulty Error : " + str(me.difficulty - Edifficulty) print "studyTime Error : " + str(me.studyTime - EstudyTime) print "attendance Error : " + str(me.attendance - Eattendance) print "grade Error : " + str(me.grade - Egrade) print "achievement Error " + str(me.achievement - Eachievement) print classList.sort(reverse=True) classList = [lecture[1] for lecture in classList] # 유사도*total 점수 제거 # page rendering return render_template('ShowLectures.html',classList=classList)