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 P_tab_check_btn_click(self, row): # 判断文字 if self.P_table_widget_list[row]["check_btn"].text() == "修改": self.P_table_widget_list[row]["check_btn"].setText("保存") self.P_tab_set_enabled_true(row) else: self.P_table_widget_list[row]["check_btn"].setText("稍等") #取出值 class_id = getKeyByValue( self.channelDict["personClass"], self.P_table_widget_list[row] ["person_clz_combox"].currentText()) dorm = getKeyByValue( self.channelDict["addr_dorm"], self.P_table_widget_list[row] ["person_dorm_combox"].currentText()) grade = getKeyByValue( self.channelDict["addr_class"], self.P_table_widget_list[row] ["person_class_combox"].currentText()) # 更新表 # 判断图像是否更新 if self.P_table_widget_list[row]["imageChange"]: # 如果全部更新 # 取出编码 enc = self.P_table_widget_list[row]["imageEncode"] # 存入照片 path = self.P_table_widget_list[row]["imagePath"] person = Person( enc, self.P_table_widget_list[row] ["person_name_lineEdit"].text(), class_id, path) person.id = int( self.P_table_widget_list[row]["person_id_lineEdit"].text()) self.PDI.updatePerson(person, int(dorm), int(grade)) # 清空数据 self.P_table_widget_list[row]["imageEncode"] = None self.P_table_widget_list[row]["imagePath"] = "" self.P_table_widget_list[row]["imageChange"] = False # 更新图片 person_img = QImage(path) size = QSize(20, 20) self.P_table_widget_list[row]["imageLabel"].setPixmap( QPixmap.fromImage(person_img.scaled(size))) # 实时更新人脸库 self.channelDict["DataGetThreadContent"].append( "updateFaceLib") self.channelDict["DataGetThreadEvent"].set() else: # 更新数据 person = Person( None, self.P_table_widget_list[row] ["person_name_lineEdit"].text(), class_id, None) person.id = int( self.P_table_widget_list[row]["person_id_lineEdit"].text()) self.PDI.updatePerson(person, int(dorm), int(grade)) self.P_table_widget_list[row]["check_btn"].setText("修改") self.P_tab_set_enabled_false(row)
def submit_all(): result = askquestion(title="Confirmation", message= "Do you want to process?") if result == "yes": person = Person() person.lname = input_lastname.get(1.0, "end-1c") person.fname = input_firstname.get(1.0, "end-1c") person.birthday = datetime.date(birthYear.get(), months.index(birthMonth.get()) + 1, birthDay.get()) person.nationality = selected_nationality.get() person.gender = selected_gender.get() person.streetNumber = str(input_houseNo.get(1.0, "end-1c")) + str(input_houseNo2.get(1.0, "end-1c")) person.streetname = input_street.get(1.0, "end-1c") person.city = input_city.get(1.0, "end-1c") person.postalCode = str(input_postal.get(1.0, "end-1c")) + str(input_postal2.get(1.0, "end-1c")) person.phone = input_phoneNumber.get(1.0, "end-1c") person.email = input_email.get(1.0, "end-1c") person.insert() student = Student() student.personID = person.personID student.studentID = int(input_studentID.get(1.0, "end-1c")) student.startYear = datetime.date(startYear.get(), 1, 1) student.enrolled = selected_study.get() counseler_index = counsellornames.index(selected_counsellor.get()) student.studyCouncelor = counsellors[counseler_index].teacherID student.insert() person.userName = (person.lname + str(student.studentID)) person.userPass = "******" person.update() ui.AdminWindowStudents.admin_window_students(window, return_function) #avoid circular import
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 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 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 generatePerson(): person = Person() person.gender = random.choice(['M', 'F', 'O']) if (person.gender == 'F'): person.fname = random.choice(female_name) else: person.fname = random.choice(male_name) person.lname = random.choice(last_name) domain = ["gmail.com", "hotmail.com", "yahoo.com"] person.email = person.lname + "_" + person.fname + "@" + random.choice( domain) person.phone = "0" + str(random.randint(600000000, 699999999)) person.birthday = getRandomDate(1980, 2004) person.nationality = random.choice(nationality) alphabets = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ] person.streetname = ''.join(random.choice(alphabets) for _ in range(6)) person.streetNumber = random.randint(1, 99) person.city = random.choice(city_name) person.postalCode = str(random.randint(1111, 9999)) + str(''.join( random.choice(alphabets) for _ in range(2))).upper() person.insert() return person
def submit_all(): result = askquestion(title="Confirmation", message= "Do you want to process?") if result == "yes": person = Person() person.lname = input_lastname.get(1.0, "end-1c") person.fname = input_firstname.get(1.0, "end-1c") person.birthday = datetime.date(birthYear.get(), months.index(birthMonth.get()) + 1, birthDay.get()) person.nationality = selected_nationality.get() person.gender = selected_gender.get() person.streetNumber = str(input_houseNo.get(1.0, "end-1c")) + str(input_houseNo2.get(1.0, "end-1c")) person.streetname = input_street.get(1.0, "end-1c") person.city = input_city.get(1.0, "end-1c") person.postalCode = str(input_postal.get(1.0, "end-1c")) + str(input_postal2.get(1.0, "end-1c")) person.phone = input_phoneNumber.get(1.0, "end-1c") person.email = input_email.get(1.0, "end-1c") person.insert() teacher = Teacher() teacher.personID = person.personID teacher.salary = input_salary.get(1.0, "end-1c") person.userName = (person.lname + str(teacher.teacherID)) person.userPass = "******" person.update() get_counsellor = selected_counsellor.get() if (get_counsellor == "Yes"): teacher.studycouncelor = 'Y' else: teacher.studycouncelor = 'N' teacher.insert() ui.AdminWindowTeachers.admin_window_teachers(window, return_function) #avoid circular import
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 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 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 person(email, pw, pod=None): p = Person() p.firstName = min(email.split(".")[0], email.split("@")[0]) p.email = email p.active = True p.put() p.password = db.hashpass(pw, p.created) p.onjoin() pod and p.enroll(pod) return p
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
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 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 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 post(self): form = self.form_loader() if not self.form_validate(form): return user = Person( name=form.name.data, password=form.password.data, email=form.email.data, ) session.add(user) session.commit() self.login(user) self.redirect()
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 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 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 get_all_by_page(cls, page, size): # records = [ # Person(0, "TEST1","男","000000000000000000", dt.now(), dt.now()), # Person(1, "TEST2","女","000000000000000001", dt.now(), dt.now()), # Person(2, "TEST3","男","000000000000000002", dt.now(), dt.now()) # ] sql = "select * from person LIMIT {} OFFSET {}".format( size, (page - 1) * size) rows = cls.db.query_all(sql) records = [] for row in rows: print(row) records.append( Person(row[0], row[1], row[2], row[3], dt.fromtimestamp(row[4]), dt.fromtimestamp(row[5]))) return records
def register(): if request.method == "POST": email = request.form['email'] passw = request.form['passw'] fname = request.form['fname'] lname = request.form['lname'] register = Person(email=email, password=passw, fname=fname, lname=lname) db.session.add(register) db.session.commit() flash("You've registered. Please login.") return redirect("/login") return render_template("register.html")
def show(self): window = self.window while True: event, values = window.read() print(event, values) if event == "submit": self.person = Person(None, values['name'], values['sex'], values['idcard'], None, None) self.update() sg.popup_ok("提交成功") break elif event == "cancel": window.Element("name").Update(value="") window.Element("sex").Update(value="") window.Element("idcard").Update(value="") else: break window.Close()
def load_person(filename): Person.query.delete() for line in open(filename): email, pw, fname, lname, zipcode = line.rstrip().split(',') print(email, pw, fname, lname, zipcode) iuser = Person(email=email, password=pw, fname=fname, lname=lname, home_zipcode=zipcode) db.session.add(iuser) print(iuser) db.session.commit() print("person db session commit")
def process_faces(collection_id): photos_faces_dict = get_face_id_image_info_dict(collection_id) faces_list = photos_faces_dict.keys() # List to store the processed FaceId's processed_ids = [] # Iterate through each FaceId and update the database for face in faces_list: if face not in processed_ids: # Match the FaceId with other faces # Get all the FaceId's that belong to the same person face_ids_of_same_person = search_faces(collection_id, face) person = Person(collection_id=collection_id) # Connect the person obejct with all its photo objects for matched_face in face_ids_of_same_person: matched_face_properties = photos_faces_dict[matched_face] photo = Photo.query.get(matched_face_properties['photo_id']) (face_width, face_height, face_top, face_left ) = get_bounding_box_info_from_dict(matched_face_properties) photo_byte_string = photo.byte_string photo_width = photo.width photo_height = photo.height image_bytes = make_cropped_face_image(photo_byte_string, photo_width, photo_height, face_width, face_height, face_top, face_left) person_photo = PersonPhoto(person=person, photo=photo, face_width_percentage=face_width, face_height_percentage=face_height, face_top_percentage=face_top, face_left_percentage=face_left, cropped_face_image=image_bytes) person.person_photo.append(person_photo) db.session.add(person) processed_ids = processed_ids + face_ids_of_same_person
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()
def test_note_content_escaped(self): db.put(Person( key_name='haiti:test.google.com/person.123', repo='haiti', author_name='_test1_author_name', entry_date=ServerTestsBase.TEST_DATETIME, full_name='_test1_full_name', sex='male', date_of_birth='1970-01-01', age='50-60', latest_status='believed_missing' )) self.go('/haiti/view?id=test.google.com/person.123&lang=en') self.s.submit(self.s.doc.cssselect_one('input.add-note')) note_form = self.s.doc.cssselect_one('form') params = {'own_info': 'no', 'given_name': InputEscapingTests.SCRIPT_CONTENT, 'family_name': InputEscapingTests.SCRIPT_CONTENT, 'author_name': InputEscapingTests.SCRIPT_CONTENT, 'text': InputEscapingTests.SCRIPT_CONTENT} details_page = self.s.submit(note_form, **params)