def setUp(self):
     self.r = Room('Anvil', 'office')
     self.l = Room('Ruby', 'living space')
     self.f = Person.make_person('Jane', 'fellow',
                                 sex='F',
                                 has_expr_interest=True)
     self.s = Person.make_person('Mark', 'staff')
示例#2
0
def dummy_network():
    n = Network()
    pic1 = Picture('famille.png')
    pic2 = Picture('annif.png')
    pic3 = Picture('fete.png')
    pic4 = Picture('soiree')

    per1 = Person('Jesus')
    per2 = Person('Juda')
    per3 = Person('Moise')
    per4 = Person('Charlie')
    per5 = Person('Antoine')

    n.add_person_to_picture(per1, pic1)
    n.add_person_to_picture(per2, pic1)
    n.add_person_to_picture(per3, pic1)

    n.add_person_to_picture(per3, pic2)
    n.add_person_to_picture(per4, pic2)
    n.add_person_to_picture(per5, pic2)

    n.add_person_to_picture(per1, pic3)
    n.add_person_to_picture(per5, pic3)

    n.add_person_to_picture(per1, pic4)
    n.add_person_to_picture(per5, pic4)

    return n
示例#3
0
def read(id=None):
    """
    This function responds to a request for /api/people
    with the complete lists of people

    :return:        sorted list of people
    """

    # Create the list of people from our data
    with client() as mcl:

        # Database
        ppldb = mcl.ppldb
        # collection (kind of like a table)
        pplclxn = ppldb.people
        log.debug(pplclxn)

        if id is None:
            ppl = [Person(p) for p in pplclxn.find()]
            log.debug(ppl)
        else:
            p = pplclxn.find_one({'lname': id})
            return Person(p)

    return ppl
示例#4
0
 def test_job(self):
   j = FakeJob()
   j2 = FakeJob()
   p = Person()
   self.assertEqual(p.job,None)
   #TODO: replace FakeJob with a real mock and check calls
   p.setJob(j)
   self.assertEqual(p.job,j)
   p.setJob(j2)
   self.assertEqual(p.job,j2)
示例#5
0
    def test_output(self):
        p = Person()
        p.body = 1
        p.strength = 2
        p.dex = 3
        p.intelligence = 4
        p.charisma = 5
        p.will = 6

        out = StringIO()
        p.print_stats(out=out)
        output = out.getvalue().strip()
        self.assertEqual(output, '1:2:3:4:5:6')
示例#6
0
    def execute(self):
        while True:
            me = Person(api.get_me())
            if any([p(me) for p in self.halt_predicates]):
                print "Halt predicate triggered! Exiting!"
                break
            time.sleep(0.500)
            feed = self.fetch_feed()
            for person_data in feed:
                person = Person(person_data)
                if all(p(person) for p in self.trade_predicates):
                    self._try_buy(person)

            time.sleep(self.buy_interval/1000)
示例#7
0
class HtmlConvener(Convener):
	
	def __init__(self,content,session):
		super(HtmlConvener,self).__init__()
		self.session = session
		convenerInfo = [s.strip() for s in content.split(",")]
		self.name = convenerInfo[0]
		organization = Organization(", ".join(convenerInfo[1:]))
		organization.convenerships.append(self)
		self.affiliations = [organization]
		self.person = Person(self.name)
		self.person.convenerships.append(self)
	
	def _conflate_organization(self,location):
		existingOrganization = organizationLookup.get(location)
		if existingOrganization != None:
			self.affiliations = [existingOrganization]
		else:
			organization = Organization(location)
			organizationLookup.add(organization)
			self.affiliations = [organization]
	
	def _conflate_person(self):
		self.person = Person(self.name)
		self.person.convenerships.append(self)
		existingPerson = personLookup.get(self.person.uri())
		if existingPerson == None:
			personLookup.add(self.person)
		else:
			self.person = existingPerson
			self.person.convenerships.append(self)
示例#8
0
def gen_profile(vect=None):
    '''
    Input lifestyle vector return person obj with income, expenditure,
    purchase amount by category.
    '''
    sav_rating = determine_saving_rating()
    gender = random.choice(['male', 'female'])
    username = gen.generate_name().lower()
    if not vect:
        if gender == 'male':
            vect = gc.generate_test_cases(1)[0]
        else:
            vect = gc.generate_test_cases(1)[1]
    trans_hist = create_transaction_history(vect)
    income, saving = determine_inv_sav(trans_hist, sav_rating)
    email = gen.generate_email(username)
    age = str(random.choice(list(range(16, 81))))
    rent = determine_rent()
    category = str(predict(vect))
    utilities = determine_utility(rent)
    Location = random.choice(
        ['Toronto', 'Calgary', 'Vancover', 'Montreal', 'Edmonton'])
    password = "******"
    return Person(category, username, gender, password, email, age, income,
                  saving, rent, utilities, trans_hist)
示例#9
0
def generate_random_students(fname: list, lname: list,
                             number_of_students: int) -> list:
    """creates a list of persons with random names"""
    lst = []
    for _ in range(0, number_of_students):
        lst.append(Person(random_string(fname), random_string(lname)))
    return lst
示例#10
0
def load_people():
    f = open('people.cfg')
    data = ''
    people = []
    mode = 0
    p = None
    v1 = ''
    v2 = ''
    for char in f.read():
        if char not in ';{}=':
            data += char
            continue
        elif char == '{' and mode == 0:
            p = Person(data.strip())
            people.append(p)
            mode = 1
        elif char == '=' and mode == 1:
            v1 = data.strip()
        elif char == ';' and mode == 1:
            v2 = data.strip()
            setattr(p, v1, float(v2))
        elif char == '}' and mode == 1:
            mode = 0
        data = ''

    return people
示例#11
0
    def extract_data(self, datatag: bs4.element.ResultSet,
                     category: str) -> None:
        host = 'https://ru.wikipedia.org'
        categories = {
            "Отец": 'parent',
            "Мать": 'parent',
            "Супруга": 'wifehusband',
            "Супруг": 'wifehusband',
            "Дети": 'child'
        }
        for _tag in datatag:
            if _tag.has_attr('href') and not _tag.has_attr('title'):
                continue

            name = _tag.text.strip()
            if self.check_name(name):
                continue
            uri = '{}{}'.format(host,
                                _tag['href']) if _tag.has_attr('href') else ''
            sex = self.check_sex(category)

            number_person = self.people.count()
            by_person = self.people.current()
            person = Person(id=number_person,
                            name=name,
                            category=categories[category],
                            uri=uri,
                            relation_id=by_person,
                            sex=sex)
            self.people.append(person)
示例#12
0
def createList(famous_list):
    #lsit for all the people
    all_people = []
    for i in range(len(famous_list)):
        #splits the string by either capitals, commas or spaces to
        split_spaces = re.split('   |, |  | ', famous_list[i])
        split_comma = re.split(',', famous_list[i])
        split_capitals = re.findall('[A-Z]\w+', split_comma[0])
        print(split_comma)
        birthdate = split_spaces[0]
        try:
            name = split_capitals[0]

            for z in range(len(split_capitals) - 1):
                z += 1
                name += ' ' + split_capitals[z]
        except Exception:
            name = re.findall('[a-zA-Z].*', split_comma[0])
            print("Special Name is ----------------------------------------------------------------------->  " + name[0])

        try:
            information = split_comma[1]
        except Exception:
            information = 'No information on this person'

        all_people.append(Person(name,birthdate,information))
        print(all_people[i].get_information())

    sorted_list = set_index(all_people)
    return sorted_list
示例#13
0
  def test_output(self):
      p = Person()
      p.body = 1
      p.strength = 2
      p.dex = 3
      p.intelligence = 4
      p.charisma = 5
      p.will = 6

      out = StringIO()
      p.print_stats(out=out)
      output = out.getvalue().strip()
      self.assertEqual(output,'1:2:3:4:5:6')
示例#14
0
	def _conflate_person(self):
		self.person = Person(self.name)
		self.person.convenerships.append(self)
		existingPerson = personLookup.get(self.person.uri())
		if existingPerson == None:
			personLookup.add(self.person)
		else:
			self.person = existingPerson
			self.person.convenerships.append(self)
示例#15
0
	def __init__(self,content,session):
		super(HtmlConvener,self).__init__()
		self.session = session
		convenerInfo = [s.strip() for s in content.split(",")]
		self.name = convenerInfo[0]
		organization = Organization(", ".join(convenerInfo[1:]))
		organization.convenerships.append(self)
		self.affiliations = [organization]
		self.person = Person(self.name)
		self.person.convenerships.append(self)
示例#16
0
def generate_population(n):
    population = []

    with click.progressbar(range(n), label='populating...') as n:
        for i in n:
            agent = Person.generate(START_DATE.year)
            population.append(agent)

    social_net = social_network(population, base_prob=0.4)
    for i, person in enumerate(population):
        person.friends = [population[j] for _, j in social_net.edges(i)]
    print('avg n of friends', sum(len(p.friends) for p in population)/len(population))
    return population
示例#17
0
 def test_simple_gen(self):
     with patch('random.randint', return_value=2) as mock_randint:
         population = [Person() for _ in xrange(32)]
         out = StringIO()
         nextPop = simple_next_gen(population, out=out)
         expectedPeople = 32
         actualPeople = len(nextPop)
         output = out.getvalue().strip()
         self.assertEqual(
             "We had %d folks die off at birth and %d new kids" %
             (expectedPeople - actualPeople, actualPeople), output)
         for p in nextPop:
             self.assertTrue(p.viable())
示例#18
0
def generate_people(age_max, no_of_people, filename):
    """Reads a list of names from a file then selects a random number of them configured
    by no_of_people and assigns them ages up to age_max
    """
    try:
        people = []
        with open(filename) as myfile:
            for line in myfile:
                person = Person(line.rstrip('\n'), randint(1, age_max))
                people.append(person)
        people = random.sample(people, no_of_people)
        return People(people)
    except (FileNotFoundError, ValueError):
        raise
示例#19
0
    def common_courting(self, nm, nw):
        men = [Person() for _ in xrange(nm)]
        women = [Person() for _ in xrange(nw)]
        biggest = max(nm, nw) + 10
        for i in xrange(nm):
            men[i].gender = "M"
            for a in attribNames:
                men[i].__dict__[a] = biggest - i
        for i in xrange(nw):
            women[i].gender = "F"
            for a in attribNames:
                women[i].__dict__[a] = biggest - i

        court(men, women)
        for i in xrange(min(nm, nw)):
            self.assertEqual(men[i].spouse, women[i])
            self.assertEqual(women[i].spouse, men[i])
        if nm > nw:
            extra = men
        else:
            extra = women
        for i in xrange(min(nm, nw), max(nm, nw)):
            self.assertEqual(extra[i].spouse, None)
示例#20
0
def generate_population(n):
    population = []

    with click.progressbar(range(n), label='populating...') as n:
        for i in n:
            agent = Person.generate(START_DATE.year)
            population.append(agent)

    social_net = social_network(population, base_prob=0.4)
    for i, person in enumerate(population):
        person.friends = [population[j] for _, j in social_net.edges(i)]
    print('avg n of friends',
          sum(len(p.friends) for p in population) / len(population))
    return population
示例#21
0
def obtain_tied_preferences(raw_players):

    players_dict = {}

    for raw_player in raw_players:
        player_name = raw_player[1]
        new_player = Person(player_name)

        players_dict[player_name] = new_player

    for raw_player in raw_players:
        player_name = raw_player[1]
        players_dict[player_name] = get_tied_preferences(raw_player)

    return players_dict
示例#22
0
    def _try_buy(self, person):
        trial_counts = 0
        while (trial_counts < self.trade_trial_counts):
            print "Trying to buy {} for: {}".format(person.username, person.display_price)
            me = Person(api.get_me())
            time.sleep(0.500)
            person = Person(api.get_person(person.id))
            if not all(p(person) for p in self.trade_predicates):
                break

            if any([p(me) for p in self.halt_predicates]):
                break
            if  me.balance > person.display_price:
                try:
                    api.buy(person.id, person.purchase_uuid)
                except InvalidRequest as ex:
                    trial_counts += 1
                    continue
                else:
                    break # Buy successful
            else:
                print "Display price {} higher than balance {}".format(person.display_price, me.balance)
                break
            trial_count += 1
示例#23
0
def obtain_players(players_names, preferences):

    players = []
    players_dict = {}

    for player_name in players_names:
        new_player = Person(player_name)

        players_dict[player_name] = new_player
        players.append(new_player)

    for players_name in players_names:
        set_preferences_for_player(players_name, preferences, players_dict)

    return players
示例#24
0
    def __init__(self, city, u, people_num, BROAD_RATE, SHADOW_TIME,
                 HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST):
        self.u = u
        self.people = np.array([])
        self.BROAD_RATE = BROAD_RATE
        self.SHADOW_TIME = SHADOW_TIME
        self.HOSPITAL_RECEIVE_TIME = HOSPITAL_RECEIVE_TIME
        self.CURE_TIME = CURE_TIME
        self.SAFETY_DIST = SAFETY_DIST

        for i in range(people_num):
            x = 1000 * np.random.normal(0, 1) + city.x
            y = 1000 * np.random.normal(0, 1) + city.y
            person = Person(x, y)
            self.people = np.append(self.people, person)
示例#25
0
 def test_job(self):
     j = FakeJob()
     j2 = FakeJob()
     p = Person()
     self.assertEqual(p.job, None)
     #TODO: replace FakeJob with a real mock and check calls
     p.setJob(j)
     self.assertEqual(p.job, j)
     p.setJob(j2)
     self.assertEqual(p.job, j2)
示例#26
0
def load_population(path):
    raw = json.load(open(path, 'r'))
    pop = [Person(**p) for p in raw]

    # update ids
    for p, p_raw in zip(pop, raw):
        p.id = p_raw['id']
        p.friends = p_raw['friends']

    # setup friends
    for p in pop:
        friends = []
        for f in p.friends:
            friend = next(p_ for p_ in pop if p_.id == f)
            friends.append(friend)
        p.friends = friends
    return pop
    def test_can_raise_exception(self):
        names = ['DAMIAN RICK', 'CHARLES WILLIAM',
                 'BRAD WILSON', 'WILSON DAMIAN',
                 'JACK BAUER', 'JASON STATHAM']

        persons = [Person.make_person(name, 'Fellow',
                                      has_expr_interest=True)
                   for name in names]

        def assign_all(room_name):
            for person in persons:
                Manager.assign_to_room(person, room_name)

        # raise Exception(Amity.room_collection)
        self.assertRaises(OutOfOfficeException,
                          assign_all, 'Room 1')
        self.assertRaises(OutOfLivingSpaceException,
                          assign_all, 'Room 11')
示例#28
0
    def start(self, start_uri: str) -> None:
        number_person = self.people.count()
        start_person = Person(id=number_person, name='Name', uri=start_uri)
        self.people.append(start_person)
        _n = 0
        while self.people.is_have:
            self.pause()
            self.parse()

            if self.people.ready_tosend():
                json_data = self.people.json_tosend()
                self.send(json_data)

            _n = _n + 1
            if _n == 50:
                break

            print('{} iteration'.format(_n))
        print('Done!')
示例#29
0
 def __init__(self, size: list):
     self.people = []
     self.people.append(Person('John', 20 * 52, '45', 'M'))
     self.people.append(Person('Josh', 20 * 52, '45', 'M'))
     self.people.append(Person('Jacob', 20 * 52, '45', 'M'))
     self.people.append(Person('Jessica', 20 * 52, '45', 'F'))
     self.people.append(Person('Jane', 20 * 52, '45', 'F'))
     self.people.append(Person('Jackyln', 20 * 52, '45', 'F'))
     self.resources = Resources(100000, 100000, 100000, 100000, 100000, 100000, 100000)
     self.plants = {}
     self.map = Map(size[0], size[1])  # CONSTANT
     self.map.initialize()
     self.victory = False
     self.buildings = []
     self.ded = []
     self.food = Food()
示例#30
0
def extractPeople(root, tag):
	people = []
	for p in root.findall(tag):
		name = p.text
		email = p.get('email')
		hid_email = None

		try: hid_email = re.search(r'([\w.-]+)@([\w.]+)', name).group()
		except: pass

		if name != None and name != '': 
			person = Person(name.strip())
		elif email != None and email != '': 
			person = Person(email)
		else: 
			continue # No name, no email, move on

		if email != None and email != '': person.addEmail(email)
		if hid_email != None and hid_email != '': person.addEmail(hid_email)

		people.append(person)
	
	return people
示例#31
0
]


class Philosopher(Person):
    pass

class Plato(Philosopher, Human):
    gender = Male

class Socrates(Philosopher, Human):
    gender = Male

class Spock(Philosopher, Vulcan):
    pass

if __name__ == '__main__':

    from events import Kick
    from __init__ import *

    socrates = Socrates()
    plato = Plato()
    me = Person()

    narrate = socrates.narrate(me).narrate_event
    print narrate(Kick(socrates, me))

    narrate = me.narrate(me).narrate_event
    print narrate(Kick(plato, socrates))

示例#32
0
文件: test.py 项目: levinsamuel/rand
 def test_marshal(self):
     pdict = {'fname': 'me', 'lname': 'meme', 'unused': 'nothing'}
     person = Person(pdict)
     pstr = people.marshal(person)
     self.assertTrue('{"fname": "me", "lname": "meme"' in pstr)
示例#33
0
def person(request):
    from people import Person
    p = Person(request.param[0], request.param[1])
    return p
示例#34
0
 def test_json(self):
   p = Person()
   x = p.json()
   pass
示例#35
0
 def test_marriage(self):
   m = Person()
   f = Person()
   m2 = Person()
   m.gender = "M"
   m2.gender = "M"
   f.gender = "F"
   m.marry(f)
   self.assertEqual(m.spouse,f)
   self.assertEqual(f.spouse,m)
   m.divorce()
   self.assertEqual(m.spouse,None)
   self.assertEqual(f.spouse,None)
   m.marry(m2) #not dealing with it
   self.assertEqual(m.spouse,None)
   self.assertEqual(m2.spouse,None)
   f.marry(m2)
   m.marry(f)
   self.assertEqual(m.spouse,None)
   self.assertEqual(m2.spouse,f)
   self.assertEqual(f.spouse,m2)
示例#36
0
 def setUp(self):
     print("setUp method runs at begining of each test")
     self.person_1 = Person("Muzi", "Xaba", 32)
     self.person_2 = Person("Nkanyezi", "Xaba", 3)
示例#37
0
文件: town.py 项目: jillson/simtown
 def __init__(self, name):
     self.name = name
     self.pop = reaper([Person() for _ in xrange(64)])
     self.pickInitialJobs()
示例#38
0
#!/usr/bin/python
# -*- coding: latin-1 -*-
from __future__ import unicode_literals
from people import Person
import random


cosette = Person('Cosette', '', 'F')

########## HOUSEHOLD

valjean = Person('Valjean', '', 'M', ' Somehow he had seemed much more relaxed since June, although he wouldn\'t explain why.')
marius = Person('Marius', '', 'M')
toussaint = Person('Toussaint', '', 'F')

#these are Cosette's household

household = [valjean, marius, toussaint]

######### SEAMSTRESSES

musichetta = Person('Musichetta', '', 'F')
laughingmistress= Person('Charlotte', '', 'F', ' Her merry laugh was infectious.')
#these are the people who can make clothes
seamstresses = [musichetta, laughingmistress]


def name_laughingmistress(lm):
    frenchgirlnames = ['Inès','Lola','Camille','Sarah','Louise','Lilou',u'Maëlys',
                       'Clara','Eva','Lina',u'Anaïs','Louna','Romane','Juliette','Lucie',
                       'Ambre','Alice','Lou','Lisa',u'Clémence','Jeanne','Louane',
示例#39
0

townfile = open("town.txt","r")
for aline in townfile.readlines():
    values = aline.split()
    Town(values[1], values[3:]) # create Town objects

busfile = open("bus.txt","r")
for aline in busfile.readlines():
    values = aline.split()
    Bus(values) # create Bus objects

personfile = open("person.txt","r")
for aline in personfile.readlines():
    values = aline.split()
    Person(values[0], values[1], values[2]) # create Person objects


# Town Info Display
print(">>> There are twelve towns in this system... \n")
for town in Town.all:
    print(town.getName()+", which is connected to",town.getNeighbor())
print(" ")
print(" ")


# Bus Info Display
for bus in Bus.all:
    print(bus)
print(" ")
print(" ")
def person():
    print("\nPrint!!!!")
    return Person(name="Bob", age=1)
示例#41
0
 def to_person(self):
     return Person({
         'fname': self.fname,
         'lname': self.lname,
         'timestamp': self.createtime
     })
示例#42
0
from people import Person, Kid

john = Person('John', 'Doe', 103)
jane = Person('Jane', 'Doe', 104)

johnny = Kid('johnny', 'doe', 12)

john.update_age(104)
Person.update_age(johnny, 13)
johnny.set_hair("blonde")
print(johnny.get_hair())
johnny.update_age(11)
print(johnny.get_age())

示例#43
0
 def test_viable(self):
     p = Person()
     p.body = 0
     self.assertFalse(p.viable())
     p.body = 1
     p.strength = 1
     p.intelligence = 1
     p.charisma = 1
     p.will = 1
     p.dex = 1
     self.assertTrue(p.viable())
     for dstat in ["body","strength","intelligence","charisma","will","dex"]:
         p.__dict__[dstat] = 0
         self.assertFalse(p.viable())
         p.__dict__[dstat] = 1