Exemple #1
0
def do_init():

    # position everyone randomly about the canvas
    (x_min, y_min, x_max, y_max) = agentsim.gui.get_canvas_coords()

    # because we create additional zombies, we want to remove them 
    # from the simulation before we start.  We might as well remove all
    # the persons and start fresh.

    for p in Person.get_all_instances():
       Person.del_instance(p) 

    # create all the new people at the party
    create_persons(init_num_normals, init_num_defenders, init_num_zombies)

    # position them randomly about
    for p in Person.get_all_instances():
        i = 3
        while not position_randomly(p, x_min, x_max, y_min, y_max) and i > 0 :
            i -= 1

        # if after 3 tries we could not position p, then make it leave the party
        if i <= 0:
            print("Could not position {} into random spot".format(p.get_name()))
            p.leave()

    # have all the people arrive at the simulation before we start
    for p in Person.get_all_instances():
        p.arrive()
Exemple #2
0
def modifier(file_name):
    u"""Основная функция ДЗ"""
    input_file = open(file_name, 'rb')
    reader = csv.DictReader(input_file)
    field_names = reader.fieldnames
    data_list = []
    for row in reader:
        data_list.append(row)
        var_class = Person(
            data_list[-1]['surname'],
            data_list[-1]['name'],
            data_list[-1]['birthdate'],
            data_list[-1]['nickname'])

        data_list[-1]['fullname'] = var_class.get_fullname()
        data_list[-1]['age'] = var_class.get_age()
    field_names.append('fullname')
    field_names.append('age')
    input_file.close()
    output_file = open(file_name, 'wb')
    writer = csv.DictWriter(output_file, field_names)
    writer.writeheader()
    for str_data in data_list:
        writer.writerow(str_data)
    output_file.close()
Exemple #3
0
	def test_sort_2(self):
		'Sort orders activities with the same start, but different end dates with oldest end date activity last'
		person_test = Person(self.ID, self.Name)
		person_test.add_activity(self.activity_1)
		person_test.add_activity(self.activity_end_before_activity_1)
		self.assertEqual(person_test.activities[0], self.activity_end_before_activity_1)
		self.assertEqual(person_test.activities[1], self.activity_1)
 def __init__(self, x, y, score=0, life=3):
     '''Initialise The Player'''
     Person.__init__(self, x, y)
     self.coins = 0
     self.life = life
     self.score = score
     self.alive = True
Exemple #5
0
 def reset(self,entity):
     Person.reset(self,entity)
     self.status['health'].set(self.status['health'].maximum)
     self.status['stamina'].set(self.status['stamina'].maximum)
     self.dead = False
     self.add_physics()
     self.add_parkour()
Exemple #6
0
    def testPersonWithAtLeastOneOnlineDeviceIsHome(self):
        d1 = Device('a', 'abcdefgh', True, ONLINE)
        d2 = Device('b', 'zzzzzzzz', True, OFFLINE)
        d3 = Device('c', 'xxxxxxxx', True, OFFLINE)
        p = Person('A', [d1, d2, d3])

        self.assertTrue(p.is_home())
Exemple #7
0
    def csv(self, outputFileName):
        ''' Build out put'''
        html = self.htmlFetch()
        soup = BeautifulSoup(html)
        code = soup.find('code', attrs={'id': 'voltron_srp_main-content'})
        if code != None:
            data = unicodeHandle(code.text)
            data = data.replace(":\u002d1,", ":\"\u002d1\",")
            jdata = json.loads(data)
            results = jdata["content"]["page"]["voltron_unified_search_json"]["search"]["results"]

            print(",".join(csvHeader()))
            list_persons_csv = []
            for person in results:
                personProfile = person.get("person", None)
                personProfile = personProfile.get("link_nprofile_view_headless", None) if personProfile != None else None
                if personProfile != None:
                    personHtml = self.htmlFetchPerson(personProfile)
                    personObject = Person(personHtml)
                    list_persons_csv.append(personObject.csv())
                    print(",".join(personObject.csv()))
        
            if outputFileName != None:
                with open(outputFileName, 'wb') as csvfile:
                    writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_ALL)
                    writer.writerow(csvHeader())
                    writer.writerows(list_persons_csv)
        else:
            print "upss no content!!! - Probably something change or cookie old"
	def __init__(self,surface,x,y,dir):
		self.__surface=surface
		Person.__init__(self,x,y)
#		self.__donk_y=donk_y
#		self.__donk_x=donk_x
		self.__surface[self.x][self.y]='D'
		self.__donk_dir=dir
class TestPerson(unittest.TestCase):
  def setUp(self):
    Person.objects = {}
    self.person = Person('Oswaldo')

  def test_initial_attributes(self):
    self.person.name |should| equal_to('Oswaldo')
    self.person.id   |should| equal_to(1)

  def test_persistence(self):
    Person.objects |should| equal_to({ 'Oswaldo': self.person })

  def test_credit_cards(self):
    with Stub() as first_credit_card:
      first_credit_card.person_id >> self.person.id
      first_credit_card.id >> 1

    # Another person credit card
    with Stub() as second_credit_card:
      second_credit_card.person_id >> 'another-id'
      second_credit_card.id >> 2

    from credit_card import CreditCard
    CreditCard.objects = { 1: first_credit_card, 2: second_credit_card }

    self.person.credit_cards() |should| equal_to([first_credit_card])
    def save_person_capture(cls, max_faces=100):
        """ save person with video capture.
        """
        nickname, last_name, first_name, company = \
            cls.ask_personality()
        cls.say("{}さんのことを覚えたいので5秒ほどビデオを撮りますね。".format(nickname))
        cls.say("はい。とりまーす!")
        def face_yield(face, faces):
            if len(faces) > cls.PERSON_IMAGES_NUM:
                yield face
            yield face

        all_face_imgs = face_capture.FaceCapture.capture(
            loop_func=lambda **kwargs: True,
            continue_condition_func=lambda **kwargs: len(
            kwargs.get('face_positions')) > 1,
            break_condition_func=lambda **kwargs:
                len(kwargs.get('all_face_imgs')) > cls.PERSON_IMAGES_NUM)
        person_obj = Person(
            nickname=nickname,
            last_name=last_name,
            first_name=first_name,
            company=company,
        )
        person_obj.set_face_imgs(all_face_imgs, cls.SAVE_IMAGE_SIZE)
        cls.say("今{}さんのこと覚えてます。1分くらいかかるかもしれません。".format(
            nickname))
        # cls.say("たぶん大丈夫ですが、僕はロボットなのでデータの保存に失敗すると"
        #         "全て忘れてしまうので...")
        person_obj.save()
        cls.say("{}さんのことバッチリ覚えました!またお会いしましょう。".format(
            nickname))
Exemple #11
0
 def __init__(self,pos,level):
     Enemy.__init__(self,pos,level)
     self.kill()
     self.animation_set = data.Boss()
     Person.__init__(self,level)
     self.rect.center = pos
     level.enemies.add(self)
Exemple #12
0
	def test_two_non_concurrent_activities(self):
		'''Two non concurrent activities result in consecutive start and end equal to 
		start and end of second activity'''
		person_test = Person(self.ID, self.Name)
		person_test.add_activity(self.activity_1)
		person_test.add_activity(self.activity_3)
		self.assertEqual(person_test.consecutive_start, self.activity_3.start_date)
		self.assertEqual(person_test.consecutive_end, self.activity_3.end_date)
Exemple #13
0
    def testDeviceStatusUpdate(self):
        d = Device('a', 'abcdefgh', True, OFFLINE)
        p = Person('A', [d])

        self.assertFalse(p.is_home())

        d.status = ONLINE
        self.assertTrue(p.is_home())
Exemple #14
0
 def __init__(self, first_name, last_name):
     """
     Extends from Person.__init__() to store common data of a person
     first_name and last_name are string type and storep the first name and last name of a director
     """
     Person.__init__(self, first_name, last_name)
     self._filmography = []
     """Store the movies instances in filmography list"""
def get_recent_gravatars(num):
    # get recently edited profiles
    recent = recently_edited(num)
    recent_gravatars = {}
    for uid in recent:
        person = Person(uid)
        recent_gravatars[uid] = person.gravatar(50)
    return recent_gravatars
 def test_age_calculation(self):
     p = Person('Ian','Skidmore')
     p.DateOfBirth = datetime.date(1964,9,29)
     self.assertEqual(p.Age(),51)
     
     p = Person('Adam','Skidmore')
     p.DateOfBirth = datetime.date(2002,2,18)
     self.assertEqual(p.Age(),14)       
Exemple #17
0
 def __init__(self,spawn_x=100,spawn_y=100,entity = []):
     Person.__init__(self,spawn_x,spawn_y,'0.png', 'player\\default')
     self.inputhandler = InputHandler()
     self.admin = self.physics = self.parkour = False
     self.add_basic_movement()
     self.add_physics()
     self.add_parkour()
     self.add_stats(entity)
def loadPeopleFromGEUVADISHeader(cls,header):
    people = People()
    for i,text in enumerate(header):
        if i > GFTF.COORD:
            person = Person()
            person.id = text
            people.addPerson(person)
    return people
    def get(self, uid):
        if self.current_user and self.current_user == uid:
            self.redirect('/edit')
            return
        db = settings['db']
        # generate a one-time hash. these are stored in the database
        # as uuid --> uid key-value pairs, so that the uuid is an
        # index which returns the uid which the user is logging into
        # as.
        if not 'edit_requests' in db:
            db['edit_requests'] = {}
        edit_requests = db['edit_requests']
        onetime_uuid = str(uuid.uuid4())
        edit_requests[onetime_uuid] = uid
        db['edit_requests'] = edit_requests
        user = Person(uid)
        email = user.email()
        if not email:
            message = "This user does not have any email addresses, so we cannot verify your identity. You should update your official x500 information. If this isn't possible, email [email protected] and we can help you work it out."
            self.render('templates/email_notify.html', message=message)
            return

        # construct and send the email
        base = 'http://'+settings['domain']
        if settings['port'] != 80:
            base += ':'+str(settings['port'])
        edit_url = base+'/login/'+onetime_uuid
        text = '''Please click the following link to update your information:\n%s''' % edit_url
        html = '''<html><p>Welcome! People.openNASA is the open
        extension to the NASA x500 system. We hope that you will find
        this a useful way to share information about your skills, work
        and interests. If you have any trouble or questions, check out
        the <a href="http://people.opennasa.com/faq">FAQ</a>, or email
        us at <a href="mailto:[email protected]">
        [email protected]</a>.</p> <p>Happy collaborating!</p>'''
        html += '''<p>Follow this link to update your information:<br><a href="%s">%s</a></p></html>''' % (edit_url, edit_url)
        part1 = MIMEText(text, 'text')
        part2 = MIMEText(html, 'html')
        msg = MIMEMultipart('alternative')
        msg.attach(part1)
        msg.attach(part2)
        msg['Subject'] = '[openNASA Profiles] Update your Information'
        msg['From'] = '*****@*****.**'
        msg['To'] = email
        if settings['email_enabled']:
            s = smtplib.SMTP('smtp.gmail.com')
            s.starttls()
            s.login(settings['smtp_user'], settings['smtp_pass'] )
            s.sendmail(msg['From'], msg['To'], msg.as_string())
            s.quit()
            message = 'An email with one-time login has been sent to your email address at %s. (You can change your primary email address when you log in to edit your profile)' % email
            print 'One-time login sent'
        elif settings['debug']:
            # careful with this! it will allow anyone to log into any
            # profile to edit its fields.
            message = 'Click <a href="%s">here</a> to log in.' % edit_url
        self.render('templates/email_notify.html', message=message)
        return
Exemple #20
0
	def test_sort_1(self):
		'Sort orders each activity oldest to newest by start date'
		person_test = Person(self.ID, self.Name)
		person_test.add_activity(self.activity_1)
		person_test.add_activity(self.activity_3)
		person_test.add_activity(self.activity_2)
		self.assertEqual(person_test.activities[0], self.activity_1)
		self.assertEqual(person_test.activities[1], self.activity_2)
		self.assertEqual(person_test.activities[2], self.activity_3)
Exemple #21
0
	def test_three_activities_one_break(self):
		'''When adding three activities with a break after second, consecutive dates are 
		equal to third activity start end dates'''
		person_test = Person(self.ID, self.Name)
		person_test.add_activity(self.activity_1)
		person_test.add_activity(self.activity_2)
		person_test.add_activity(self.activity_3)
		self.assertEqual(person_test.consecutive_start, self.activity_3.start_date)
		self.assertEqual(person_test.consecutive_end, self.activity_3.end_date)
 def __del__(self):
     class_name = self.__class__.__name__
     print(class_name, "destroyed")
     Person.__del__(self)
    
     
 
 
     
 def __init__(self,name,age,id,loc,desg):
     print('Employee Constructor called') 
     self.id = id
     print(self.id)
     self.loc = loc
     print(self.loc)
     self.desg = desg
     print(self.desg)
     Person.__init__(self, name, age)
def loadPeopleFromPDBSampleFile(cls,sample_file_name):
    people = People()
    with open(sample_file_name, 'rb') as samples:
        reader = csv.reader(samples, delimiter='\t', quotechar='"')
        for row in reader:
            person = Person()
            person.loadFromPDBRow(row)
            people.addPerson(person)
    return people
Exemple #25
0
def do_step():
    # Buffer all the move_by calls and do at once.

    # Note that this does not buffer other state changes made in objects,
    # such as a teleport - we really should have that facility for a proper
    # simulation of a time step

    # we should also enforce the restriction on the move limit for each
    # type of object.  At the moment, you can get around this limit by calling
    # move_by in the compute_next_move method!

    moves = [ ]

    # give the defenders a chance to tell the normals what to do
    # and try to teleport any zombies

    for p in Defender.get_all_present_instances():
        moves.append( (p,) + p.compute_next_move() )

    # then give the normals a chance
    for p in Normal.get_all_present_instances():
        moves.append( (p,) + p.compute_next_move() )

    # and finally the zombies, which may have been teleported to new positions
    for p in Zombie.get_all_present_instances():
        moves.append( (p,) + p.compute_next_move() )

    # then execute the moves, even though other state may have been changed
    # earlier
    for (p, delta_x, delta_y) in moves:
        p.move_by(delta_x, delta_y)

    # then convert normals into zombies if the zombies are close enough

    # Warning: z - number of zombies, n - number of normals, then the
    # time complexity of this is O( z n )

    for z in Zombie.get_all_present_instances():
        for n in Normal.get_all_present_instances():
            d_e_e = z.distances_to(n)[3]
            d_touch = z.get_touching_threshold()

            # print(z.get_name(), n.get_name(), d_e_e, d_touch)

            if d_e_e <= d_touch:

                x = n.get_xpos()
                y = n.get_ypos()

                new_z = Zombie(size=n.get_size(), haircolor='green', 
                    xpos = x, ypos = y, move_limit=person_move_limit)

                new_z.arrive()
                n.leave()

                Person.del_instance(n)
Exemple #26
0
 def parse_tsv(self, string):
     lines = iter(string.splitlines())
     r = csv.DictReader(lines, delimiter='\t')
     for row in r:
         person = Person(row)
         template = os.environ.get('PHOTO_URL_TEMPLATE')
         if template:
             person.photo_url = str.replace(os.environ.get('PHOTO_URL_TEMPLATE'), '%NAME%', person.photo)
         self.add(person)
     return self
 def get(self, uid): 
     db = settings['db']
     try:
         person = Person(uid)
         self.render('templates/person.html', title=person.display_name(), 
                     person=person, map=helper.map, mailing=helper.mailing, 
                     category=helper.category, category_sm=helper.category_sm)
     except:
         user_message = "There is no profile with that ID. Please try again."
         self.render('templates/results.html', title='Search Results', results=None, message=user_message)
Exemple #28
0
 def __init__(self, board):
     '''Creates the player. Player takes board as input for ease of
     updaating information on the board directly
     '''
     #Inherit from Person
     Person.__init__(self, 1, 1)
     #Print onto Board initial location
     board.board[1][1] = "Player"
     self.board = board.board
     self.bombs = 1
def main():



    p = Person("Charlotte Smith", 45, 55555555)
    s = Student("Kyle Smith", 24, 7777777, 12345641464, ['CS-332L', 'CS-312', 'CS-386'])
    print(p.get_name())
    print(s.get_name())

    print(isinstance(s, Person))
	def __init__(self,surface,x,y):
		self.__surface=surface
		Person.__init__(self,x,y)
		self.__start_x=x
		self.__start_y=y
#		self.__pos_x=x
#		self.__pos_y=y
		self.prev_dir=[0,0]
		self.cur_dir=[0,0]
		self.__surface[x][y]='P'
import shelve
from person import Person
from manager import Manager
bob = Person("Bob Smith", 42, 30000, "software")
sue = Person("Sue Jones", 45, 40000, "hardware")
tom = Manager("Tom Doe", 50, 50000)
db = shelve.open("class-shelve")
db["bob"] = bob
db["sue"] = sue
db["tom"] = tom
db.close()
Exemple #32
0
input_details = model.get_input_details()
output_details = model.get_output_details()
floating_model = input_details[0]['dtype'] == np.float32

for file in os.scandir('photos/sitting'):
    img = cv.imread(file.path)
    print(file.path, "original shape: ", img.shape)
    img2 = cv.resize(img, (257, 257), interpolation=cv.INTER_LINEAR)
    img = tf.reshape(tf.image.resize(img, [257, 257]), [1, 257, 257, 3])
    if floating_model:
        img = (np.float32(img) - 127.5) / 127.5
    # print('input shape: {}, img shape: {}'.format(input_details[0]['shape'], img.shape))
    model.set_tensor(input_details[0]['index'], img)
    model.invoke()

    output_data = np.squeeze(
        model.get_tensor(
            output_details[0]['index']))  # o()
    offset_data = np.squeeze(model.get_tensor(output_details[1]['index']))
    p = Person(output_data, offset_data)

    img = draw(p, img2)
    cv.imshow("{}".format(p.confidence()), img2)
    cv.waitKey(0)
    cv.destroyAllWindows()
# print(p.to_string())
# results = np.squeeze(output_data)
# offsets_results = np.squeeze(offset_data)
# print("output shape: {}".format(output_data.shape))
# np.savez('sample3.npz', results, offsets_results)
 def getAddress(self):
     return Person.getAddress(self)
 def test_init(self):
     p = Person('Hanmeimei', 20)
     self.assertEqual(p.name, 'Hanmeimei', '属性赋值有误')
Exemple #35
0
 def __init__(self, name, age, pay):
     Person.__init__(self, name, age, pay, 'manager')
 def setUp(self):
     print('Test start.')
     self.p1 = Person('Bill', 'Gates', 15)
     self.p2 = Person('Steve', 'Jobs', 25)
Exemple #37
0
    def start_game(self):
        # Uses the list of player names to make a list of player objects
        for x in self.player_name_list:  # may need to be a while loop to get 'id's
            y = Player(x, x[0:2:1], self.player_name_list.index(x))
            self.player_list.append(y)

        # Makes the people instances from the list of players
        # PROP OBSOLETE DO TO ABOVE FUNCTION
        # for name in player_name_list:
        #     name_being_added_to_people_list = Person("meh" player, life_number_for_player, name, parent):)
        #     name_being_added_to_people_list.name = person
        #     people_list.append(name_being_added_to_people_list)

        # intro
        print("\nHere's everyone's numbers:")
        i = 0
        while i < len(self.player_name_list) - 1:
            print(f'{str(i + 1)}: {self.player_name_list[i]}')
            i += 1

        # main code
        date = 1
        while True:
            while True:
                entered_id_or_initials = (input('\nEnter your number and hit enter to sign in/out as alive/dead:\n\n'))
                entered_id = None
                entered_initials = None

                # did they enter letters?
                try:
                    entered_id = int(entered_id_or_initials)
                except ValueError:
                    entered_initials = entered_id_or_initials[0:2:1]

                # If the user entered their initials, convert to id
                if entered_initials is not None:
                    for x in self.player_list:
                        if x.initials.lower() == entered_initials.lower():
                            entered_id = x.id

                if entered_id is not None:
                    if entered_id > 0:

                        # find out which player is trying to sign in/out
                        player_signing_in_or_out = None
                        for x in self.player_list:
                            if x.id == entered_id:
                                player_signing_in_or_out = x
                                break

                        # if alive, die
                        self.refresh_string_of_living_people()
                        if player_signing_in_or_out.name in string_of_living:  # there's gotta be a better way... todo
                            for person in self.living_people_list:
                                if person.player.name == player_signing_in_or_out.name:
                                    person.die()

                        # else dead, so be birthed!
                        else:
                            # find out if there are are no fertile people who can birth the player back into the game
                            if len(baby_wait_list) == 0:
                                if len(self.living_people_list) == 0:
                                    print(
                                        f'\nWelcome, {player_signing_in_or_out.name}. Looks like you\'ll be the Adam/Eve of this world! No pressure. Oh, and don\'t let your kids fight like Cain and Abel...\n')
                                    baby = Person(player_signing_in_or_out, 1, None)
                                    break
                                # if there are other people but no one ready to have a baby, then they need to wait!
                                else:
                                    print(
                                        f'\n\nSorry, {player_signing_in_or_out.name}. Looks like there\'re no available parents for you yet. Back to Heaven, now!\n')

                            else:
                                # find out what life number the player will be on when born this time
                                name_of_guy_that_is_being_birthed = player_signing_in_or_out.name
                                life_number_for_player_that_will_soon_be_born = None
                                for x in self.player_list:
                                    if x.name == name_of_guy_that_is_being_birthed:
                                        life_number_for_player_that_will_soon_be_born = x.times_played + 1
                                        baby = Person(x, life_number_for_player_that_will_soon_be_born,
                                                      next_parent_in_line_to_have_a_baby)
                                        try:
                                            self.pop_parent_off_of_baby_wait_list(baby)
                                        except NameError:
                                            print(f'you did not have a parent')
                                        if len(baby_wait_list) == 0:
                                            print(f'\nNO MORE BABIES CAN BE BORN THIS TURN\n')
                                        break
                    else:
                        break  # because I must be trying to end turn manually

            # Next turn because I entered 0
            if entered_id > -1:
                # age people
                for x in self.living_people_list:
                    x.age += 1
                # kill old people
                for x in self.living_people_list:
                    if x.age > self.lifespan:
                        x.die()
                        x = input(f'\nHit enter:\n')
                self.make_new_baby_wait_list()
                print(
                    f'TURN {date + 1}:\nStats:\n\t{len(self.living_people_list)} -> Pop\n\t{len(baby_wait_list)} -> Fertile pop\n\t{len(self.people_list)} -> Total people ever lived\n')  # todo add stats here: pop, total people ever lived, total fertile players
                date += 1
            else:
                x = input(f'What turns would you like printed? not implemented')
                self.print_family_tree()
Exemple #38
0
персонаж реагирует только на верхнюю часть платформы,
но ничего не мешает добавить остальные стороны,
прыжок был вырезан из-за незнания, как правильно реализовать его анимацию
'''

py.init()

width = 1000
height = 600
window = py.display.set_mode([width, height])
rect = window.get_rect()
window.fill((255, 255, 255))

clock = py.time.Clock()

person = Person(width, height)
person.yPos = 530

level = level(window)

objects = []
for i in range(len(level.platforms)):
    objects.append(level.platforms[i].rect)

run = True
while run:
    clock.tick(50)
    for event in py.event.get():
        if event.type == py.QUIT:
            run = False
Exemple #39
0
@author: nesko

My first Flask app
"""

# Importera relevanta moduler
import traceback
from flask import Flask, render_template
from person import Person

app = Flask(__name__)

person_json_path = "static/me.json"

me = Person(person_json_path)


@app.route("/")
def main():
    """ Main route """
    return render_template("index.html",
                           firstname=me.firstname,
                           familyname=me.familyname,
                           picture=me.picture,
                           course=me.course)


@app.route("/about")
def about():
    """ About route """
Exemple #40
0
    def run(self):
        try:
            self.login()
        except ValueError as ve:
            print(ve)
            sys.exit(0)
        else:
            print(Fore.GREEN + 'Logged In' + Style.RESET_ALL)
            self.sleep(1.0, 3.0)

        if self.potential is None:
            print(Fore.RED + 'Q is None' + Style.RESET_ALL)
            sys.exit(0)

        if not self.potential.first():
            self.reset()

        while self.potential.first():
            current_message = self.potential.first()
            self.potential.remove(current_message)
            current_id = current_message.get_body()

            self.visit(self.root_url + current_id)

            if not self.scroll():
                print(Fore.YELLOW + current_id + ' Waste' + Style.RESET_ALL)
                # self.potential.remove(current_message)
                continue

            showMoreButtons = self.browser.find_elements_by_css_selector(
                "section[id='experience-section'] button.pv-profile-section__see-more-inline"
            )
            while showMoreButtons:
                print(Fore.YELLOW + str(len(showMoreButtons)) + ' show alls' +
                      Style.RESET_ALL)
                for button in showMoreButtons:
                    ActionChains(
                        self.browser).move_to_element(button).perform()
                    scroll = self.partial_scroll + "-2));"
                    self.browser.execute_script(scroll)
                    button.click()
                    print(Fore.BLUE + 'Clicked: ' + Style.RESET_ALL)
                    self.sleep(1.0, 2.0)

                showMoreButtons = self.browser.find_elements_by_css_selector(
                    "section[id='experience-section'] button.pv-profile-section__see-more-inline"
                )

            soup = BeautifulSoup(
                self.browser.page_source.encode('utf-8').decode(
                    'ascii', 'ignore'), 'html.parser')

            if self.session.query(User).filter_by(id=current_id).first():
                print(Fore.YELLOW + current_id + ' Already in DB' +
                      Style.RESET_ALL)
                # self.potential.remove(current_message)
                continue
            person = Person(soup, current_id)
            if person.shouldScrape():
                self.visited[current_id] = person
                # for url in person.also_viewed_urls:
                #     if url not in self.visited and not self.is_in_checked_user(url):
                #         self.potential.add(url)

                self.write_to_db(person)
                print(person)
                print(
                    '------------------------------------------------------------------------'
                )
                print('Stats:')
                print('\t' + 'Queue Length:', self.potential.count())
                print('\t' + 'Visited:', len(self.visited))
                print('\t' + 'Elapsed time:', datetime.now() - self.starttime)
                print(
                    '------------------------------------------------------------------------'
                )
                # self.potential.remove(current_message)
            else:
                print(Fore.BLUE + 'Skipped:' + Style.RESET_ALL, current_id)
                # self.potential.remove(current_message)

        self.sleep(5.0, 10.0)
        self.browser.quit()
Exemple #41
0
import shelve
from person import Person
from manager import Manager

bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jones', 45, 40000, 'hardware')
tom = Manager('Tom Doe', 50, 50000)

db = shelve.open('class-shelve')
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
db.close()
Exemple #42
0
def show():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    id = session['id']
    users = Person.select().where(Person.owner == id)
    return render_template('show.html', users=users)
Exemple #43
0
	def giveRaise(self, percent, bonus=0.1):
#		self.pay *= (1.0 + percent + bonus)
		Person.giveRaise(self, 1.0 + percent + bonus)
Exemple #44
0
import socket
import pickle
from person import Person

SERVER = ('127.0.0.1', 61100)
TCP_PROTO = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCP_PROTO.connect(SERVER)

while True:
    name = input('Name: ')
    age = input('Age: ')
    sex = input('Sex: ')
    msg = pickle.dumps(Person(name, age, sex),
                       protocol=pickle.HIGHEST_PROTOCOL)
    TCP_PROTO.send(msg)
    resp = TCP_PROTO.recv(1024)
    print(resp.decode('utf-8'))

    if input('Press 0 to exit or Enter to continue') == '0':
        break
Exemple #45
0
        print("4. Eliminar persona")
        return int(input("Elija una opción: "))


if __name__ == '__main__':
    app = App()
    personService = PersonService()
    while True:
        opcion_person = app.menu_person()
        if opcion_person == 1:
            listPerson = personService.get_personList()
            for key in listPerson:
                print("legajo: %s -> %s" % (key, listPerson[key]))

        if opcion_person == 2:
            p = Person()
            p.name = input("Ingrese Nombre: ")
            p.surname = input("Ingrese apellido: ")
            p.age = int(input("Ingrese edad: "))
            personService.add_person(p)

        if opcion_person == 3:
            key = int(input("Ingrese legajo de la persona: "))
            p = Person()
            p.name = input("Ingrese Nombre: ")
            p.surname = input("Ingrese apellido: ")
            p.age = int(input("Ingrese edad: "))
            personService.update_person(key, p)

        if opcion_person == 4:
            p = Person()
    # Aufbauen der Population
    for i in range(params.popsize):
        is_isolated = False
        is_infected = False
        is_immune = False
        is_heavy = False
        is_superspread = False
        temp = randint(1, params.popsize)
        if temp < params.isolation:
            is_isolated = True  # Mit einer gewählten Wahrscheinlichkeit ist die Person isoliert.
        if temp < params.infected:
            is_infected = True  # Mit einer gewählten Wahrscheinlichkeit ist die Person infiziert.
        if temp < params.superspreader:
            is_superspread = True  # Mit einer gewählten Wahrscheinlichkeit ist die Person superspreader.
        new_person = Person(
            is_isolated, is_infected, is_immune, is_heavy, is_infected,
            is_superspread
        )  #Erstellen eines Objekts Person mit den oben genannten Eigenschaften
        params.end_dist['Age'][i] = new_person.age
        new_person.ps = new_person.ps.move(
            new_person.left * 10,
            new_person.top * 10)  # Setzen der Personen auf das Spielfeld
        population.append(new_person)

    people_infected[0] = params.infected / params.popsize
    start = timer()
    figure()  #erstellt das Figure aus der drawnow-Bibliothek für Liveplot
    # Creating the Simulation
    while sim_continue(population):

        count += 1
 def getDOB(self):
     return Person.getDOB(self)
from person import Person
from virus import Virus
from logger import Logger
from simulation import Simulation

import pytest

# TODO: Create a function that initializes virus and person to use
# on all testing funtions
ebola = Virus('ebola', 0.7, 2.5)
person = Person(1, True, ebola)
person2 = Person(2, True)


# -----Person file-----
def test_init_Person():
    # ebola = Virus('ebola', 0.7)
    # person = Person(1, True, ebola)
    # person2 = Person(2, True)
    assert person._id == 1
    assert person.is_vaccinated == True
    assert person.infected == ebola
    assert person2.infected == None


def test_did_survive_infection():
    person = Person(3, False, ebola)
    assert person.did_survive_infection() == False


# -----Logger file-----
Exemple #49
0
from house import House, SmallHouse
from person import Person
from realtor import Realtor

if __name__ == "__main__":
    mansion = House(78000.0, 120)
    cottage = House(19000.0, 33)
    forestHouse = SmallHouse(10000.0)
    mountHouse = SmallHouse(33000.0)
    lakeHouse = House(45600.0, 66)

    print('Input name, age and budget of person:')
    humanFirst = Person(input(), input(), float(input()), [lakeHouse])
    humanFirst.provide_inform()

    print('Input name of realtor and available discounts:')
    realtorFirst = Realtor(input(), float(input()), [mansion, mountHouse])
    realtorFirst.provide_info_all_houses()

    humanFirst.buy_house(mountHouse, realtorFirst)
    humanFirst.make_money(14450.0)
    realtorFirst.offer_discount(mountHouse)
    humanFirst.buy_house(mountHouse, realtorFirst)

    humanFirst.provide_inform()
    realtorFirst.provide_info_all_houses()
def test_did_survive_infection():
    person = Person(3, False, ebola)
    assert person.did_survive_infection() == False
Exemple #51
0
 def giveRaise(self, percent, bonus=0.1):
     Person.giveRaise(self, percent + bonus)
Exemple #52
0
    load_settings("settings.json")
    read_map('maps/map2.txt')

    get_antennas()
    get_walls()

    start_time = time.time()

    # tries to load a pre saved RSSI map
    RSSI_MATRIX = read_saved_matrix()

    tt = time.time() - start_time

    print(f'Setup took {tt} ms')

    PERSONS.append(Person())
    sched.start()

    def init():
        """
        Creates the window and loads the map visually
        It also adds all the buttons
        """

        root = Tk()
        root.geometry(f'{SCREEN_W + 40}x{SCREEN_H + 100}')
        root.title('RSSI localization simulator')
        root.config(bg='#233043')

        global FRAME
        FRAME = Test(master=root)
 def test_getAge(self):
     p = Person('Hanmeimei', 22)
     self.assertEqual(p.getAge(), p.age, 'getAge函数有误')
Exemple #54
0
from person import Person, Manager

bob = Person('Bob Smith')
sue = Person('Sue Jones', job='dev', pay=100000)
tom = Manager('Tom Jones', pay=50000)

import shelve

db = shelve.open('persondb')
for obj in (bob, sue, tom):
	db[obj.name] = obj
db.close()
 def getName(self):
     return Person.getName(self)
Exemple #56
0
 def __init__(self, x=1, y=1):
     Person.__init__(self, x, y)
     self.bombs = 0
     # To check condition so that person can not plant more than 1 bomb
     b.game[x][y] = 'P'
from person import Person

fieldnames = ('name', 'age', 'job', 'pay')
db = shelve.open('class-shelve')

while True:
    key = input('\nKey? => ')
    # 回车退出循环
    if not key:
        break
    # 如果元组(人员信息表)中有该人员,读取信息
    if key in db:
        record = db[key]
    # 如果没有该人员则新建一个对象,并传入参数
    else:
        record = Person(name=key, age='?')
    # 对待改人员的各项信息进行遍历,修改
    for field in fieldnames:
        currval = getattr(record, field)
        # 显示的打印出待改人员的待改信息,并输入新的信息
        newtext = input('\t[%s]=%s\n\t\tnew?=>' % (field, currval))
        if newtext:
            print('\t\t\t修改后的信息:\n\t\t\t[{}]={}'.format(field, newtext))
            c = input('\t\t\t请再次确认您是否要进行修改\n\t\t\t\t(y/n)')
            if c == 'y':
                # 为record对象的field属性赋值为eval(newtext)
                if field == 'job':
                    setattr(record, field, newtext)
                else:
                    setattr(record, field, eval(newtext))
    db[key] = record
import shelve

from person import Person
from manager import Manager

filednames = ('name', 'age', 'job', 'pay')

db = shelve.open('class-shelve')

while True:

    key = input('\nKey? \t=>\t ')

    if not key: break

    if key in db:
        record = db[key]
    else:
        record = Person(name='?', age='?')

    for field in filednames:
        currval = getattr(record, field)
        newtext = input('\t[%s] = %s \n \t\tnew? =>' % (field, currval))
        if newtext:
            setattr(record, field, eval(newtext))
    db[key] = record
db.close()
Exemple #59
0
print(family["Smith"]["emily"]["kid_names"][0])

print("=============================")

from person import Person


class Athlete(Person):
    speed = 0

    def __init__(self, speed, hair_color, eye_color, body_type):
        self.speed = speed
        super().__init__(hair_color, eye_color, body_type)

    def run(self, distance):
        print(
            f"I am {self.body_type} and have {self.speed} speed for {distance} meters!"
        )


joe = Person("brown", "blue", "thin")
joe.talk()

sarah = Person("black", "green", "chubby")
sarah.run()
print(sarah.eye_color)

michael = Athlete(10, "brown", "blue", "thin")
michael.run(400)
michael.walk()
import csv
import sys
import Pyro4
import Pyro4.util
from person import Person

sys.excepthook = Pyro4.util.excepthook

warehouse = Pyro4.Proxy("PYRONAME:example.warehouse")

employee = Person("kangqi")

employee.visit(warehouse)