def create_people(self, arrivals_per_hour, max_arrivals=None, quanta_emission_rate=None, inhalation_rate=None): """ Create a method of generating people """ is_someone_infected = False generated_people = 0 while True: infection_status_label = DiseaseProgression.valid_state( 'susceptible' ) if is_someone_infected else DiseaseProgression.valid_state( 'infected') is_someone_infected = True generated_people += 1 person = Person(self.simulation_params, starting_node_id='start', person_type='visitor', infection_status_label=infection_status_label, quanta_emission_rate=quanta_emission_rate, inhalation_rate=inhalation_rate) # self.create_routing(person, duration=duration) self.env.process(person.run()) time_to_next_person = 60 / arrivals_per_hour yield self.env.timeout(time_to_next_person) # If we have generated enough people then stop if max_arrivals and (generated_people >= max_arrivals): break
def addPerson(self, admin=False): array = ["", "", "", "", admin] PersonList = ['First name', 'last name', 'username', 'password'] for i in range(len(array)): while array[i] == "": try: array[i] = str(input("What's the " + PersonList[i] + "? ")) except: print("something went wrong.") try: userId = int(self.__Users[-1].getUserId()) + 1 except: userId = 0 self.__Users.append( Person(userId, array[0], array[1], array[2], array[3], array[4])) with open('Person.csv', mode='w') as csv_file: fieldnames = [ 'userId', 'firstName', 'lastName', 'username', 'password', 'admin' ] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for i in self.__Users: writer.writerow({ 'userId': i.getUserId(), 'firstName': i.getFirstName(), 'lastName': i.getLastName(), 'username': i.getUsername(), 'password': i.getPassword(), 'admin': i.isAdmin() })
def checkAndAdd(personList, newPerson): for persons in personList: if newPerson["user"]["fbid"] == persons.id: try: persons.parseConvDict(newPerson["messaging"]) return personList except Exception as e: print("-----------------------------") print("ERROR PARSING JSON") print("Exception: " + str(e)) print("Json:") print(newPerson) print("-----------------------------") # If the person is not already in the list add him by calling the Person constructor and passing the user parameters try: personList.append( Person(convDict=newPerson["messaging"], personDict=newPerson["user"])) except Exception as e: print("-----------------------------") print("ERROR PARSING JSON") print("Exception: " + str(e)) print("Json:") print(newPerson) print("-----------------------------") return personList
def readInContacts(): """ Read in the default contact list file """ file = open('contacts.txt', 'r') for line in file: fields = line.split(',') peep = Person(fields[0].strip(), fields[1].strip(), fields[2].strip()) contactList.addPerson(peep)
def signup(self, user_id, text): if user_id not in self.signupdb.keys(): self.signupdb[user_id] = [None, None, None] self.vk.messages.send(peer_id=user_id, random_id=get_random_id(), message=u'Отправьте имя') elif self.signupdb[user_id][0] is None: self.signupdb[user_id][0] = text self.vk.messages.send(peer_id=user_id, random_id=get_random_id(), message=u'Отправьте фамилию') elif self.signupdb[user_id][1] is None: self.signupdb[user_id][1] = text self.vk.messages.send(peer_id=user_id, random_id=get_random_id(), message=u'Отправь комнату в виде: 401б') elif self.signupdb[user_id][2] is None: self.signupdb[user_id][2] = text try: self.db.add_person( Person(self.signupdb[user_id][0], self.signupdb[user_id][1], self.signupdb[user_id][2], user_id)) self.send_laundress_keyboard(user_id) except pymysql.err.DataError: self.vk.messages.send( peer_id=user_id, random_id=get_random_id(), message= u'Ты что-то ввёл неправильно, попробуй ещё раз\n(Напиши мне снова)' ) finally: self.signupdb.pop(user_id)
def run(self): print("Esperando DNI...") fileName = "data.txt" startTime = time.time() maxWaitInSeconds = 30 while fileName not in os.listdir("Temp"): waitTime = time.time() - startTime if waitTime > maxWaitInSeconds: # Se agotó el tiempo de espera de colocación del DNI event = "LecturaDNIEsperaAgotada" self.queue.put([event]) return time.sleep(1) with open(os.path.join("Temp",fileName)) as f: data = f.read().replace("\n", "") print(data) person = Person(dataString=data) os.remove(os.path.join("Temp",fileName)) if not person.valid: event = "LecturaDNIQrInvalido" else: self.enroller.enroll(data) event = "LecturaDNITerminada" self.queue.put([event, person])
def CheckForArrivals(self, arrivalRate): if self.clock == arrivalRate: if random.random() * 100 <= 64: person = Person( int(numpy.random.normal(self.rateOfTransaction, 13)), "bowl") self.putInLine(True, self.numberOfLines, person, self.splitLines) else: person = Person( int(numpy.random.normal(self.rateOfTransaction, 13)), "burrito") self.putInLine(False, self.numberOfLines, person, self.splitLines) return -1 return arrivalRate
def main(filename, second): p = Person() lst = [] with open(filename) as f: for l in f.readlines(): for d in l.split(","): print "\n" dd = d.strip() turn = dd[0] moves = int(dd[1:]) print "Turn %s while facing %s moving %d" % (turn, p.cardinal, moves) p.turn(turn) xyL = p.move(moves) print xyL if second: for xy in xyL: if xy in lst: print lst print "Second answer:" print "%d, %d" % (xy[0], xy[1]) print "\nSecond Answer: %d" % (abs(xy[0]) + abs(xy[1])) sys.exit(0) lst.append(xy) if second: print "\nDidn't find an answer" sys.exit(-1) print "%d, %d" % (p.x, p.y) print lst print "\nAnswer: %d" % (abs(p.x) + abs(p.y))
def read_people_from_file(file_name): people_list = [] input_workbook = xlrd.open_workbook(file_name) input_worksheet = input_workbook.sheet_by_name("calculator") # print(input_worksheet.nrows) for i in range(1, input_worksheet.nrows): ID = int(input_worksheet.cell_value(i, 0)) # print(ID) age = int(input_worksheet.cell_value(i, 1)) gender = int(input_worksheet.cell_value(i, 2)) smkyears = int(input_worksheet.cell_value(i, 3)) cpd = int(input_worksheet.cell_value(i, 5)) race = int(input_worksheet.cell_value(i, 6)) emp = int(input_worksheet.cell_value(i, 7)) fam_lung_trend = int(input_worksheet.cell_value(i, 8)) bmi = input_worksheet.cell_value(i, 9) edu6 = input_worksheet.cell_value(i, 10) qtyears = int(input_worksheet.cell_value(i, 11)) pkyr_cat = input_worksheet.cell_value(i, 12) # print(pkyr_cat) LCRAT_1mon_risk = input_worksheet.cell_value(i, 19) p = Person(age, gender, smkyears, qtyears, cpd, race, emp, fam_lung_trend, bmi, edu6, ID, pkyr_cat, LCRAT_1mon_risk) # print(p.ID) people_list.append(p) # print(people_list[0].ID) return people_list
def __init__(self, config_places, config_crowd, config_isolation, config_preventions, medicalModel): self.config_places = config_places self.config_crowd = config_crowd self.config_isolation = dict(config_isolation.items()) self.enableIsolation = self.config_isolation['enable'] if not self.enableIsolation: self.config_isolation['agreeIsolationRate'] = 0 self.config_preventions = config_preventions self.medicalModel = medicalModel self.flexPlaces = {} self.day = 0 # step 1: create citizens self.crowd = [] for config in config_crowd: for i in range(config['number']): healthStage = self.medicalModel.initIllnessStage if i < config[ 'patient'] else self.medicalModel.healthStage prevention = [ preventionType for preventionType, config in config_preventions.items() if random.random() < config['applicationRatio'] ] newPerson = Person( config, healthStage, prevention, random.random() < config_isolation['agreeIsolationRate'], config_isolation['selfDiscipline']) self.crowd.append(newPerson) self.population = self.crowd.copy() random.shuffle(self.crowd) # step 2: create (fixed) locations self.fixedPlaces = {} for config in config_places: if config['number'] is None: continue self.fixedPlaces[config['type']] = [ Place(config) for i in range(config['number']) ] # step 3: randomly link people with fixed locations according to the 'fixedActivity' allPossibleDefaultPlaceTypes = [ person.defaultActivity for person in self.crowd ] allPossibleFixedPlaceTypes = itertools.chain( *[person.fixedActivityTypes() for person in self.crowd], allPossibleDefaultPlaceTypes) allPossibleFixedPlaceTypes = set(allPossibleFixedPlaceTypes) for placeType in allPossibleFixedPlaceTypes: people = [ person for person in self.crowd if placeType in person.fixedActivityTypes() or placeType == person.defaultActivity ] places = [place for place in self.fixedPlaces[placeType]] # randomly link the remaining people with places allocation = self.randomlyAllocate(people, places) for place, person in allocation: person.linkedPlace[placeType] = place place.linkedPeople.append(person)
def create_population(self): '''Creates the population (a list of Person objects) consisting of initial infected people, initial healthy non-vaccinated people, and initial healthy vaccinated people. Adds them to the population list''' for i in range(self.initial_infected): person = Person(False, virus) self.population.append(person) for i in range(self.initial_healthy): person = Person(False, None) self.population.append(person) for i in range(self.initial_vaccinated): person = Person(True, None) self.population.append(person)
def get_img_emb_name_lastest(json_file): data_json = json.loads(open(json_file).read().decode('utf-8')) list_image_face = [] list_image_cmt=[] list_person = [] if len(data_json['face_data']) != 0: for i in range(len(data_json['face_data'])): data = data_json['face_data'] data_image = data[i]['image'] list_image_one_person = [] list_image_one_person_cmt = [] for j in range(len(data_image)): image = Image_Face(data_image[j]["name"],data_image[j]["type"],data_image[j]["path_image"],data_image[j]["vector"],data_image[j]["date"],data_image[j]["location_transaction"]) if data_image[j]["type"] != 0: list_image_one_person.append(image) else: list_image_one_person_cmt.append(image) print("93") print (len(list_image_one_person)) print (len(list_image_one_person_cmt)) try: list_image_face.append(list_image_one_person[getImageLastestElementInList(list_image_one_person)]) except: pass try: list_image_cmt.append(list_image_one_person_cmt[getImageLastestElementInList(list_image_one_person_cmt)]) except: pass person_info = Person(data[i]["id_cmt"],data[i]["name"],data[i]["address"],data[i]["age"],data[i]["job"],data[i]["phone_number"],data[i]["last_address_transaction"],data[i]["first_address_transaction"],[], data[i]["firtdate_transaction"],data[i]["lastdate_transaction"]) list_person.append(person_info) return list_image_face,list_person,list_image_cmt
def __init__(self): self.sum = 0 self.changedby = '' # the following only works because Person is in a separate module # that is also available to the client: self.person = Person("Irmen de Jong", "30")
def LoginButtonfunction(): User = Person() User.Username = UsernameField.get("1.0", END) User.Password = passwordField.get("1.0", END) if len(User.Username) - 1 != 0 and len(User.Password) - 1 != 0: Data = User.Login(User.Username, User.Password) if Data[0] and Data[1].Authorize: if not Data[1].Admin: User = Users() else: User = Admin() User.Username = Data[1].Username User.Password = Data[1].Password User.Folderpath = Data[1].Folderpath User.Authorize = Data[1].Authorize User.Admin = Data[1].Admin if not User.Admin: root.destroy() root.quit() from Dashboard import Dashboard next = Dashboard(User) else: pass # الى هيعمل ال admin else: tkinter.messagebox.showinfo(" Invalid Credintial", "User Doesnot exist thank you :)") root.destroy() root.quit() else: tkinter.messagebox.showinfo("Empty fields", "Do net leave any field empty ")
def simulate_natality(self): try: self.natality_distribution except AttributeError: print("ERROR: No natality data loaded") exit(1) births = self.predictor.predict_natality(self.get_population_size()) newborns_places = [] mothers_ages = [] mothers_age_ranges = self.natality_distribution.Random(n = births) for age_range in mothers_age_ranges: (min_age, max_age) = BIRTH_RANGES[age_range] mother = self.get_random_person_in_age_range(min_age, max_age) mother_place = mother.get_origin() newborns_places.append(mother_place) mothers_ages.append(mother.get_age()) person = Person(mother_place, person_class = PersonClass.CLASS1, age = 0) self.add_person(person) self.stats.add_natality_stats(self.step_num, {'places': newborns_places, 'ages': mothers_ages}) print("Step {} - {} persons were born".format(self.step_num, len(mothers_age_ranges)))
def __init__(self, N=10, width=None, height=None): """ Neighborhood: a neighborhood containing people Parameters ---------- N: number of people in the neighborhood width: width of the (rectangular) neighborhood area height: height of the (rectangular) neighborhood area """ super().__init__() self.num_agents = N self.width = width or min(N, 100) self.height = height or min(N, 100) self.grid = MultiGrid(self.width, self.height, True) self.schedule = RandomActivation(self) # Create agents for i in range(self.num_agents): rand = random.random() infection = rand >= (N-N**.5)/N print(i, rand, (N-N**.5)/N) a = Person(i, self, level_of_infection=int(infection)) print(a, a.level_of_infection) self.schedule.add(a) # adding the agent to a random position in the neighborhood (x, y) = random.random() * self.width, random.random() * self.height self.grid.place_agent(a, (int(x), int(y)))
def simulate_migrations(self): num_persons_out = self.predictor.predict_migrations(self.get_population_size()) num_persons_out_abs = abs(num_persons_out) migration_age_ranges = self.migrations_distribution.Random(n=num_persons_out_abs) age_ranges = Parser.get_age_ranges() outcome_ages = [] for i in range(len(migration_age_ranges)): age_range = migration_age_ranges[i] if age_range >= len(age_ranges): migration_age_ranges[i] = self.migrations_distribution.Random(n=1)[0] age_range = migration_age_ranges[i] (a, b) = age_ranges[age_range] if num_persons_out < 0: person = self.get_random_person_in_age_range(a, b) outcome_ages.append(person.get_age()) self.remove_person(person) elif num_persons_out > 0: age = randint(a, b) (zones, probabilites) = self.get_age_group_zone_distribution(a, b) zone = random.choices(zones, weights=probabilites, k = 1)[0] person = Person(origin=zone, age=age) self.add_person(person) self.stats.add_migration_stats(self.step_num, outcome_ages) if num_persons_out < 0: print("Step {} - {} persons left".format(self.step_num, num_persons_out_abs)) elif num_persons_out > 0: print("Step {} - {} persons entered".format(self.step_num, num_persons_out_abs))
def populate_community(): """ Run only at the beginning of the Simulation Create instances of the Person for the simulation """ for i in range(1,11): Simulation.community["person"+str(i)] = Person("person"+str(i))
def test_is_marriage_fourteen_years_after_parents_birth(self): wife = Person() wife.set_birthday("1 JAN 1910") wife.name = "Kim" husband = Person() husband.set_birthday("1 JAN 1910") husband.name = "Joe" family = Family("1") family.husband = husband family.wife = wife family.set_marriage_date("1 JAN 1923") self.assertFalse( family.is_marriage_fourteen_years_after_parents_birth()) family.set_marriage_date("1 JAN 1925") self.assertTrue( family.is_marriage_fourteen_years_after_parents_birth())
def addPerson(self, Id): ''' adds a new person to the repository list input the id ''' person = Person(Id, "nonvaccinated", "healty") self.__repo.append(person)
def main(): s1 = UG('Christopher Kennedy', 2018) s2 = UG('Stephanie Herrera', 2018) s3 = UG('Gianca Devina', 2019) s4 = Grad('Matt Damon') studentList = [s1, s2, s3, s4] print(s1) print(s1.getClass()) # print(s1.speak('where is the quiz?')) # print(s2.speak('I have no clue!')) # print(s4.speak('I am not sure why I am here.')) for student in studentList: print(student.speak('today is cold.')) print(isStudent(s1)) p1 = Person('Taylor Swift') print(isStudent(p1))
def generate_score_for_patients() -> tuple: """ This function calculate the aggregate of the scores for a person according to the variables associated with person class and virus class. Then, it further increases the count of the person in the red_zone and return the results. Since the doctest here depends on the user input for population size, and it varies according to the input the user gives, it is not possible to write doctests here. :return aggregate_score, red_zone, total_count """ aggregate_score_list = [] red_zone = 0 total_count = 0 for i in range(1, population_size): person1 = Person() virus1 = virus(virus_type) #aggregate score is calculated as the sum of the patient's total score plus #the score based on the virus he is infected with. aggregate_score = person1.get_total_score() + virus1.get_type_score() #If the aggregate score exceeds a threshold level the patient is considered in red-zone. if aggregate_score >= 300: red_zone = red_zone + 1 total_count = total_count + 1 aggregate_score_list.append(aggregate_score) return (aggregate_score, red_zone, total_count)
def create_order(self, address_book): ''' Create new item in "address_book" :param address_book: list of contacts ''' name = input('Введите имя человека: ').capitalize() familyname = input('Введите фамилию человека: ').capitalize() lastname = input('Введите отчество человека: ').capitalize() address = input('Введите адрес человека: ').title() phone = input('Введите телефон человека(89009998877): ') phone_re = phone[0] + '-(' + phone[1:4] + ')-' + phone[ 4:7] + '-' + phone[7:9] + '-' + phone[9:11] date_create = datetime.datetime.now().strftime("%d-%m-%Y") date_modify = datetime.datetime.now().strftime("%d-%m-%Y") if isinstance(address_book[-1], tuple): last_item = dict(zip(self.params, list(address_book[-1]))) ID = last_item['id'] + 1 else: if (len(address_book) > 1): ID = int(address_book[-1]['id']) + 1 else: ID = 1 p = Person(ID, name, familyname, lastname, address, phone_re, date_create, date_modify) address_book.append(p.__dict__) self.address_book_for_bd.append( (p.id, p.name, p.familyname, p.lastname, p.address, p.phone, p.datecreate, p.datemodify))
def test(): # init reading data table life_table1 = read_life_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") local_cancer2 = read_LC_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") regional_cancer3 = read_regional_cancer_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") distant_cancer4 = read_distant_cancer_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") p1 = Person(72, 1, 42, 6, 24, 2, 0, 2, 27, 5, 50.4, 0.000983915, 4) p2 = Person(80, 0, 0, 0, 0, 0, 0, 0, 24.62, 0) print( get_years_remain_screening(p2, life_table1, local_cancer2, regional_cancer3, distant_cancer4, False))
def fillUsers(self): with open('Person.csv', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: self.__Users.append( Person(row["userId"], row["firstName"], row["lastName"], row["username"], row["password"], row["admin"]))
def test_move_north(): p = Person() err = "Incorrect %s when testing moving %s" p.move(2) assert p.x == 0, err % ('x', p.cardinal) assert p.y == 2, err % ('y', p.cardinal)
def add(self): print("Fill form please!") name = '' while name == '': name = input("Your Name: ") if not name in self.data_dict.keys(): phone = str(input('Phone: ')) adress = input('Adress: ') email = str(input('Email: ')) telegram = input('Telegram: ') whatsapp = str(input('Whatsapp: ')) self.data_dict.update({ name: Person(name=name, phone=phone, adress=adress, email=email, telegram=telegram, whatsapp=whatsapp) }) else: print('Contact with name: {} already exists!'.format(name)) answer = input("Change this contacts? ('Y/n') ") if answer.lower() == 'y': self.change(name)
def test_move_east(): p = Person() p.turn('R') err = "Incorrect %s when testing moving %s" p.move(2) assert p.x == 2, err % ('x', p.cardinal) assert p.y == 0, err % ('y', p.cardinal)
def Create(): per = Person() per.FirstName = input("Lütfen Kişinin Adını Giriniz: ") per.LastName = input("Lütfen Kişinin Soyadını Giriniz: ") per.Phone = input("Lütfen Kişinin Telefon Numarasını Giriniz: ") per.Mail = input("Lütfen Kişinin Mail AdresiniGiriniz: ") return per
def main(): # with open('test.txt','w') as file: # file.write("==================\n") start = Node(position=[0, 0]) end = Node(position=[50, 75]) kevin = Person(x=20, y=25, velocity=0, direction=0) #john = Person(x=2,y=7,velocity=0,direction=0) #am = Person(x=80,y=20,velocity=0,direction=0) # mike = Person(x=10,y=-20,velocity=0,direction=0) adjacencyList, listOfShape = createAdjacencyList_new(nodes=[start, end], people=[kevin]) for i, j in adjacencyList.items(): i.cost += calculateWeight(end, i) # plotAllPath(adjacencyList, listOfShape) listOfPath = a_star(start, end, adjacencyList, listOfShape) listOfPath.reverse() for i in listOfPath: print("{} to {}".format(i[0], i[1])) plot(listOfPath, adjacencyList)