def get_faces():
    """
    This API searches an image for faces and returns the location of each face
    ---
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: formData
        name: upfile
        type: file
        required: true
        description: Image file to analyse
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    #logger=logging.getLogger(__name__)
    #logger.info("Calling prediction data for /people")
    response = None
    model = People()
    query_class = request.args.get('class')
    iFile = request.files.getlist('upfile')[0]
    img = load_image(iFile)
    img = rotate_image(img, iFile)
    img = limit_size_image(img)
    response = model.get_tags_coords(img, query_class)
    return jsonify(response)
예제 #2
0
파일: friend.py 프로젝트: topicus/musily
class Friend(object):
  def __init__(self, people_path, friendships_path):
    friendships_file = open(friendships_path, 'r')
    self.___people = People(people_path)
    self.friendships_reader = csv.DictReader(friendships_file, delimiter='|')
    self.__friendships = []
    self.load()

  def load(self):
    for f in self.friendships_reader:
      self.__friendships.append(f)

  def people(self):
    return self.___people.all()    
  
  def friendships(self):
    return self.__friendships
  
  def filter(self, filters):
    people = self.___people.filter(filters)
    people_set = set(people)
    return people, [f for f in self.__friendships if self.people_exists(f, people_set)]

  def people_exists(self, friendship, people):
    f = friendship
    return f['usuario_1'] in people and f['usuario_2'] in people
예제 #3
0
 def __init__(self, x, y, board):
     shape = [[MARIO_CHAR] * 3] * 3
     People.__init__(self, Point(x, y), 1, shape, Dimension(3, 3), board)
     self.state = 0
     self.air = 0
     self.board.mario = self
     self.update()
예제 #4
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Pick the stars")

    people = People(ai_settings, screen)
    stars = Stars(ai_settings, screen)
    alien = Alien(ai_settings, screen)
    bullets = Group()
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    play_button = Button(ai_settings, screen, "Play")

    while True:
        gf.check_events(ai_settings, stats, sb, people, alien, bullets,
                        play_button)
        bullets.update()
        for bullet in bullets.copy():
            if bullet.rect.bottom >= ai_settings.screen_height:
                bullets.remove(bullet)
        if stats.game_active:
            people.update()
            gf.update_alien(alien)
            gf.update_stars(ai_settings, stats, sb, people, stars)
            if alien.rect.x % 120 == 0:
                gf.update_bullet(ai_settings, stats, screen, people, alien,
                                 bullets)

        gf.update_screen(ai_settings, stats, sb, screen, people, stars, alien,
                         bullets, play_button)
def cycle(person_info, sms_cycle):
    new_people = shelve.open('new_people')
    options = ['30', '60', '90', '180', '365', '1095']

    person_number = person_info.keys()[0]

    valid = sms_cycle in options

    if not valid:
        # Send Text 'The cycle you sent was not valid. pls send it again.
        # Your options are '30', '60', '90', '180', '365', '1095'
        new_people.close()
        return "Send Text 'The cycle you sent was not valid. pls send it again.  " \
               "Your options are '30', '60', '90', '180', '365', '1095'"
    else:
        new_people[person_number]['cycle'] = sms_cycle
        tmp_new_person = new_people[person_number]
        peaps.append(tmp_new_person)
        del new_people[person_number]
        #
        #
        # add this person to the db: new_people[person_number])
        #
        #
    return "Your all set up %(username)s. Your in %(position)s" \
           " and will be notified of any change" % {
             'username': tmp_new_person['username'],
             'position': '1'
            }
예제 #6
0
def rungame():
	#初始化
	pygame.init()
	al_setting = Settings()
	#创建窗口
	screen = pygame.display.set_mode((al_setting.screen_width,
	al_setting.screen_height))
	pygame.display.set_caption("catch the ball")
	stats = Stats(al_setting)
	#创建角色
	people = People(al_setting,screen)
	#创建球组
	balls = Group()
	#创建角色组
	peoples = Group()
	peoples.add(people)
	while True:
		#鼠标键盘相应事件
		gf.check_event(people)
		if stats.game_active:	
			#更新角色位置
			people.update()
			#更新球的位置
			gf.ball_update(al_setting,screen,balls,peoples,stats)
			#刷新界面
		gf.screen_update(al_setting,screen,balls,people)
예제 #7
0
 def self_move(self, unit):
     if 20 > self.point.y - self.board.mario.point.y > 0:
         if not self.move_left(2 * unit):
             self.move_right(2 * unit)
     elif 20 > self.board.mario.point.y - self.point.y > 0:
         if not self.move_right(2 * unit):
             self.move_left(2 * unit)
     else:
         People.self_move(self, 2 * unit)
예제 #8
0
    def __init__(self, school, name, age):
        self.school = school
        #注意:这里必须传入self,否则无法构造成功
        #这里相当于用类来调用了实例方法,是一个普通的调用,因此需要像
        #普通函数调用一样,传self
        People.__init__(self, name, age)

        #但是上面这样的构造方式并不推荐,开闭原则,比方说我们更换父类,那么派生类中
        #可能要修改很多地方,这不可取,而是应该采用下面这个方法
        super(Student, self).__init__(name, age)
예제 #9
0
def main():
    """set-up applcation and send love"""
    api = get_handle()
    markov = Markov(get_corpus())
    people = People(api)

    love = markov.generate_markov_text(random.randrange(15, 20))
    to_email = people.get_random()
    print to_email
    print love
    if api.send_love(to_email, love):
        return 0
    else:
        return -1
예제 #10
0
def load_main_file(filename, main_dic):

    wb = openpyxl.load_workbook(filename)
    sheet = wb.get_sheet_by_name(wb.sheetnames[0])
    line_number = len(sheet["A"])
    print "Filename: ", filename, "Lines: ", line_number

    racker_name_list = []
    contractor_name_list = []

    for row in range(9, line_number + 1):
        combi_name = sheet['A' + str(row)].value.encode(
            'ascii', 'ignore').lower().strip()
        status = sheet['C' + str(row)].value.encode('ascii',
                                                    'ignore').lower().strip()
        company = sheet['J' + str(row)].value.encode('ascii',
                                                     'ignore').lower().strip()
        time = sheet['D' + str(row)].value
        active_status = sheet['K' + str(row)].value.encode(
            'ascii', 'ignore').lower().strip()

        if status != "completed":
            status = "incompleted"
        if company != "contractor":
            company = "rackspace"

        if time > datetime.datetime(2017, 1, 1) and active_status == "active":
            if combi_name not in main_dic:
                people = People(combi_name)
                people.status = status
                people.company = company

                main_dic[combi_name] = people

            #name duplicate
            else:
                if status == "completed":
                    main_dic[combi_name].status = status

            last_name, first_name = combi_name.split(",")
            last_name = last_name.strip()
            first_name = first_name.strip()
            if company == "rackspace" and (first_name,
                                           last_name) not in racker_name_list:
                racker_name_list.append((first_name, last_name))
            if company != "rackspace" and (
                    first_name, last_name) not in contractor_name_list:
                contractor_name_list.append((first_name, last_name))

    print "Active registered in 2017: ", len(main_dic.keys())
예제 #11
0
 def __init__(self,
              lastname,
              middlename,
              name,
              gender,
              age,
              parents,
              subject=None):
     People.__init__(self, lastname, middlename, name, gender, age)
     self.parents = parents
     if subject:
         self.subject = subject
     else:
         self.subject = []
예제 #12
0
def create_people():
    """
    sample request body:{
                            "First":"Zhe",
                            "Last":"Chen",
                            "Age":"31",
                            "GithubAcct":"zchen1007",
                            "Date of 3rd Grade Graduation":"3/04/98"
                        }
    not recommending using id as one of the key in the json
    :return: json object response
    """
    input = request.json
    people = People(profile=input)
    is_valid, msg = people.is_data_valid()
    if not is_valid:
        return jsonify({"err": msg}), 400
    has_all_req, msg = people.contains_all_keys()
    if not has_all_req:
        return jsonify({"err": msg}), 400
    con_cur = Database.get_connection()
    if 'ID' in people.profile:
        app.logger.warning(
            "manually input ID has the risk of conflicting with existing, if conflicts records will be ignored"
        )
        people.insert_with_id(con_cur)
    else:
        people.insert_no_id(con_cur)
    con_cur.commit()
    con_cur.close()
    return getPeople()
예제 #13
0
 def getPeople(self):
     self.category = 'people'
     result_d = json.loads(
         SwapiService.getSwapi(self.category, self.getId()))
     self.people = People(result_d['name'], result_d['height'])
     print("Name: {} Height: {}cm".format(self.people.name,
                                          self.people.height))
예제 #14
0
파일: grid.py 프로젝트: Lawlietgit/COVID_19
 def __init__(self, size, n_p):
     """
     :param size: int, size of the grid
     :param n_p: (4,) numpy array, [# of ppl of each status]
     """
     self.size = size
     self.all_p = []
     self.total_p = sum(
         n_p)  # sum of the n_p list, indicating total number of ppl
     self.steps = 1000  # this is the total number of steps you simulate
     for status, n in enumerate(n_p):
         gc = 0 if status == 0 else n_p[status - 1]
         cur_list = [
             People(i + gc,
                    np.random.randint(self.size, size=2),
                    size,
                    age=0,
                    status=status) for i in range(n)
         ]
         self.all_p.extend(cur_list)
     self.to_pos_array()
     self.stream = self.data_stream()
     # Setup the figure and axes...
     self.fig, self.ax = plt.subplots()
     # Then setup FuncAnimation.
     self.ani = anime.FuncAnimation(
         self.fig,
         self.update,
         interval=200,
         # interval it is the time between your snapshots in ms
         init_func=self.setup_plot,
         blit=True)
예제 #15
0
 def __init__(self, num, city, BROAD_RATE, PROTECTION_RATE, DEATH_RATE, EXPOSED_TIME, IMMUNED_TIME, \
   HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST, u, FLUCTUATION, can_exposed_infect, recovered_included):
     # self.city = city
     self.num = num
     self.peoples = np.array([])
     self.BROAD_RATE = BROAD_RATE
     self.PROTECTION_RATE = PROTECTION_RATE
     self.DEATH_RATE = DEATH_RATE
     self.EXPOSED_TIME = EXPOSED_TIME
     self.HOSPITAL_RECEIVE_TIME = HOSPITAL_RECEIVE_TIME
     self.CURE_TIME = CURE_TIME
     self.IMMUNED_TIME = IMMUNED_TIME
     self.SAFETY_DIST = SAFETY_DIST
     self.FLUCTUATION = FLUCTUATION
     self.SCALE = 1000
     self.u = np.exp(u)
     self.can_exposed_infect = can_exposed_infect
     self.recovered_included = recovered_included
     self.Tg = []
     self.Te = []
     self.Ti = []
     self.in_touch = 0
     if can_exposed_infect == True:
         self.can_infect_status = [1, 2]
     else:
         self.can_infect_status = [2]
     for i in range(num):
         x = self.SCALE * np.random.normal(0, 1) + city.centerX
         y = self.SCALE * np.random.normal(0, 1) + city.centerY
         self.peoples = np.append(self.peoples, People(x, y))
예제 #16
0
    def __init__(self, slug, api_key):
        super(NationBuilder, self).__init__()

        self.people = People(slug, api_key)
        self.tags = NBTags(slug, api_key)
        self.lists = Lists(slug, api_key)
        self.contacts = Contacts(slug, api_key)
예제 #17
0
 def wrapper_load_people_from_json_file(original_people):
     """Loads a list of people from a json file"""
     if storage_method == "json":
         with open("people_subset.json") as file:
             #return json.load(file, object_hook=decode_person)
             people_from_json = People.from_json(json.load(file))
         value = func(original_people, people_from_json)
         return value
예제 #18
0
def sortPeopleByAge():
    '''
    Returns Json block containing a list of people sorted by age youngest to oldest
    '''
    # TODO
    con_cur = Database.get_connection()
    result = jsonify(People.get_all_users(con_cur, order_by='age'))
    con_cur.close()
    return result
예제 #19
0
def getPeople():
    '''
    Return a standard JSON block of people in any order of format. Must be valid JSON
    '''
    # TODO
    con_cur = Database.get_connection()
    result = jsonify(People.get_all_users(con_cur))
    con_cur.close()
    return result
예제 #20
0
def main(student_file, volunteer_file, output_file):

    workbook = xlsxwriter.Workbook(
        '/Users/Ingrid.Pacheco/Desktop/match-output.xlsx')
    worksheet = workbook.add_worksheet()
    headers = [
        'nome MENTOR', 'email MENTOR', 'numero MENTOR', 'graduacao MENTOR',
        'disciplinas MENTOR', 'idade MENTOR', 'estado MENTOR', 'nome ALUNO',
        'email ALUNO', 'numero ALUNO', 'graduacao ALUNO', 'disciplinas ALUNO',
        'idade ALUNO', 'estado ALUNO', 'dificuldades', 'interesse'
    ]
    worksheet = add_headers(worksheet, headers)
    matches = Match(worksheet, len(headers))
    students = People()
    mentors = People()
    with pd.ExcelFile(student_file) as firstxls:
        df1 = pd.read_excel(firstxls, 0)

        f1 = File(student_file, df1.columns, df1.values.tolist(), df1)
        f1.set_properties('student')

        with pd.ExcelFile(volunteer_file) as secondxls:
            df2 = pd.read_excel(secondxls, 0)

            f2 = File(volunteer_file, df2.columns, df2.values.tolist(), df2)
            f2.set_properties('mentor')

            hours = df2.get(
                'Quantas horas por semana você terá para dedicar para a mentoria (não esqueça de levar em consideração o tempo que você já dedica a outras atividades, e eventualmente outros projetos do ExplicaEnem que você é parte).  Dessa maneira, de acordo com sua disponibilidade, poderemos te conectar com a quantidade de mentorados.'
            ).tolist()
            for idx_mentor, val_mentor in enumerate(f2.get_values()):

                vital_properties = f2.get_properties(idx_mentor, 'mentor')
                mentor = Person(
                    f2.get_name(idx_mentor), f2.get_email(idx_mentor),
                    f2.get_phone(idx_mentor), vital_properties, val_mentor,
                    int(hours[idx_mentor].split('(')[1].split(' ')[0]))
                mentors.add_person(mentor)

                for idx_student, val_student in enumerate(f1.get_values()):

                    student_vital_properties = f1.get_properties(
                        idx_student, 'student')
                    student = Person(f1.get_name(idx_student),
                                     f1.get_email(idx_student),
                                     f1.get_phone(idx_student),
                                     student_vital_properties, val_student, 0,
                                     f1.get_additional_properties(idx_student))
                    students.add_person(student)

                    matches.get_match(student, mentor)

    find_matches(matches, students, mentors)
    workbook.close()
예제 #21
0
def getIdsByLastName(lastname):
    '''
    Returns Json block of ids found for the given last name
    Using path params
    '''
    # TODO
    con_cur = Database.get_connection()
    result = jsonify(People.get_user_by_lname(con_cur, lastname))
    con_cur.close()
    return result
예제 #22
0
def Cellular_Automata(Total_People):

    UI = GUI()

    # Total_People = 200
    P = People(Total_People, myMap)

    UI.Show_People(P.list)

    Time_Start = time.time()
    Eva_Number = 0
    Time_Pass = 0
    Time_Step = 1
    while Eva_Number < Total_People:
        Eva_Number = P.run()

        UI.Update_People(P.list)

        # time.sleep(random.uniform(0.015, 0.025))

        UI.canvas.update()
        UI.root.update()

        Time_Pass += Time_Step
        UI.label_time['text'] = "Time = " + "%.2f" % Time_Pass + "s"
        UI.label_evac['text'] = "Evacution People: " + str(Eva_Number)
        # print("%.2fs" % (Time_Pass) + " 已疏散人数:" +str(Eva_Number))

    # Time_Pass = time.time()-Time_Start
    UI.label_time['text'] = "Time = " + "%.2f" % Time_Pass + "s"
    UI.label_evac['text'] = "Evacution People: " + str(Eva_Number)

    # 热力图
    sns.heatmap(P.thmap.T, cmap='Reds')
    # for i in range(0, 100):
    # 	for j in range(0, 60):
    # 		if P.thmap[i][j] != 0:
    # 			print(P.thmap[i][j])
    plt.axis('equal')
    plt.show()

    UI.root.mainloop()
예제 #23
0
def write_arch(name, age, weight, height):
    last = 0
    people = People(name, int(age), float(weight), float(height))
    print(last_id())
    last += int(last_id())
    final_str = get_all()
    final_str += f"{(last)+1} - {people.get_name()}#{people.get_age()}#{people.get_weight():.2f}#{people.get_height():.2f}\n"
    with open(abs_file_path, 'w') as archive:
        archive.write(final_str)

    clear()
    print("Pessoa adicionada com sucesso")
def set_person_name(repo, personid, name):
    """
    This API allows you to set the name of a person group in the DB for a repo
    ---
    paths:
      /people/{repo}/{personid}/{name}
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: path
        name: repo
        schema:
          type: integer
        required: true
      - in: path
        name: personid 
        schema:
          type: integer
        required: true
      - in: path
        name: name 
        schema:
          type: string
        required: true
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    logger = logging.getLogger(__name__)
    logger.info("Calling prediction data for /people/<repo>/<personid>/<name>")
    model = People(repo)
    query_class = request.args.get('class')
    response = model.set_name(repo, personid, name)
    return jsonify(response)
예제 #25
0
def grasp_ball():
    pygame.init()

    settings = Settings()

    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption(settings.screen_caption)
    stats = GameStats(settings)

    people = People(settings, screen)

    balls = Group()

    gbf.create_ball(settings, screen, balls)

    while True:
        gbf.check_events(people)

        if stats.game_active:
            gbf.update_ball(settings, stats, screen, people, balls)

        else:
            balls.empty()
            settings.people_image = './images/game_over.bmp'
            people = People(settings, screen)
            people.rect.centerx = screen.get_rect().centerx
            people.rect.centery = screen.get_rect().centery
            people.draw_people()

        gbf.update_screen(settings, screen, people, balls)
def get_face_id(repo):
    """
    This API searches an image for faces and returns the person face grouop the name of a face group in the DB for a repo.
    ---
    paths:
      /people/{repo}
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: formData
        name: upfile
        type: file
        required: true
        description: Image file to analyse
      - in: path
        name: repo
        schema:
          type: integer
        required: true
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    #logger=logging.getLogger(__name__)
    #logger.info("Calling prediction data for /faces")
    response = None
    model = People(repo)
    query_class = request.args.get('class')
    iFile = request.files.getlist('upfile')[0]
    img = load_image(iFile)
    img = rotate_image(img, iFile)
    img = limit_size_image(img)
    response = model.get_tags_face(img, query_class)
    return jsonify(response)
예제 #27
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
예제 #28
0
파일: main.py 프로젝트: jfxugithub/python
def app():

    laoLiu = People("老刘")
    laoWan = People("老王")
    laoLin = People("老林")

    peopleList = [laoLiu, laoWan, laoLin]
    nu = 1  # 记录回合数
    """随机获取一名要敌人"""
    def get_enemy(gunerName):
        while True:
            enemy = random.choice(peopleList)
            if enemy.name != gunerName:
                return enemy

    #每个人开一枪,看谁活到最后
    while True:
        print("=" * 10 + ("第%d回合" % nu) + "=" * 10)

        if laoWan.blood > 0:
            print("%s:" % laoWan.name)
            enemy = get_enemy(laoWan.name)
            if laoWan.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if laoLiu.blood > 0:
            print("%s:" % laoLiu.name)
            enemy = get_enemy(laoLiu.name)
            if laoLiu.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if laoLin.blood > 0:
            print("%s:" % laoLin.name)
            enemy = get_enemy(laoLin.name)
            if laoLin.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if len(peopleList) == 1:
            print("最终的赢家是:", peopleList[0].name)
            break

        nu += 1
예제 #29
0
	def __init__(self, num, city, BROAD_RATE, DEATH_RATE, SHADOW_TIME, \
			HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST, u, FLUCTUATION):
		# self.city = city
		self.peoples = np.array([])
		self.BROAD_RATE = BROAD_RATE
		self.DEATH_RATE = DEATH_RATE
		self.SHADOW_TIME = SHADOW_TIME
		self.HOSPITAL_RECEIVE_TIME = HOSPITAL_RECEIVE_TIME
		self.CURE_TIME = CURE_TIME
		self.SAFETY_DIST = SAFETY_DIST
		self.FLUCTUATION = FLUCTUATION
		self.SCALE = 1000
		self.u = u
		for i in range(num):
			x = self.SCALE*np.random.normal(0, 1) + city.centerX
			y = self.SCALE*np.random.normal(0, 1) + city.centerY
			self.peoples = np.append(self.peoples, People(x, y))
예제 #30
0
def ini():
    # create a bunch of particles
    num_people = 40
    vec_v = np.array([0, 0])
    r = 0.25  # in meters
    #random initial position and check overlap
    overlap= False 
    p_list=[]
    while len(p_list)<num_people:
        P=People(np.random.rand(2) * 10, vec_v, r,np.random.rand(2),screen)
        for p_j in p_list:
            if p_j.overlap(P):
                overlap= True 
                break
            overlap= False 
        if overlap== False:
            p_list.append(P)
    return p_list
 def initPeople(self, n):
     global MAX_LIKE_LEVEL
     #(self,id,egoMax,initMax,sex):
     ncore = 10  # n/10
     for i in range(0, n):
         p = People(i, r.randint(0, self.egoMax),
                    r.randint(0, self.initMax), r.randint(0, 1))
         p.initLike0(n)
         if (len(self.people) > 0):
             for j in range(0, min(ncore, len(self.people))):
                 lover = r.randint(0, len(self.people) - 1)
                 p.like[lover] = r.randint(
                     MAX_LIKE_LEVEL - MAX_LIKE_LEVEL / 20, MAX_LIKE_LEVEL)
                 self.people[
                     lover].nice = self.people[lover].nice + p.like[lover]
         p.initUndefinedLike()
         self.people.append(p)
예제 #32
0
def run_game():
    #初始化一个游戏并创建一个屏幕对象
    pygame.init()
    ai_settings=Settings()
    screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #创建一艘飞船
    ship=Ship(screen)
    people=People(screen)

    #开始游戏的主循环
    while True:

        #监视屏幕和鼠标和键盘事件
        gf.check_events(ship)
        ship.update()
        #更新屏幕上的图像,并切换到新图像
        gf.update_screen(ai_settings,screen,ship,people)
예제 #33
0
def test_get_all_people():
    response = requests.get("https://swapi.co/api/people/")
    next_is_available = True
    while (next_is_available):
        assert response.status_code == 200
        response_json = response.json()
        for response_person in response_json["results"]:
            person = People()
            person.set_fields(response_person)
            person.assert_people()
        if response_json["next"] is not None:
            response = requests.get(response_json["next"])
        else:
            next_is_available = False
예제 #34
0
def test_history(test_data):
    people = People.people()

    def ned_then(year):
        ned = people.get("ned", datetime.datetime(year, 1, 1))
        return ned['institution']

    assert ned_then(2015) == "edX"
    assert ned_then(2014) == "edX"
    assert ned_then(2013) == "edX"
    assert ned_then(2012) == "freelance"
    assert ned_then(2011) == "freelance"
    assert ned_then(2010) == "Hewlett Packard"
    assert ned_then(2009) == "Hewlett Packard"
    assert ned_then(2008) == "Hewlett Packard"
    assert ned_then(2007) == "Tabblo"
    assert ned_then(2006) == "Kubi Software"
    assert ned_then(2005) == "Kubi Software"
    assert ned_then(2004) == "Kubi Software"
    assert ned_then(2003) == "Kubi Software"
    assert ned_then(2002) == "Kubi Software"
    assert ned_then(2001) == "Blue Ripple"
    assert ned_then(2000) == "Blue Ripple"
예제 #35
0
    def test_history(self):
        people = People.from_string(SAMPLE_PEOPLE)

        def ned_then(year):
            ned = people.get("ned", datetime.datetime(year, 1, 1))
            return ned["institution"]

        self.assertEqual(ned_then(2015), "edX")
        self.assertEqual(ned_then(2014), "edX")
        self.assertEqual(ned_then(2013), "edX")
        self.assertEqual(ned_then(2012), "freelance")
        self.assertEqual(ned_then(2011), "freelance")
        self.assertEqual(ned_then(2010), "Hewlett Packard")
        self.assertEqual(ned_then(2009), "Hewlett Packard")
        self.assertEqual(ned_then(2008), "Hewlett Packard")
        self.assertEqual(ned_then(2007), "Tabblo")
        self.assertEqual(ned_then(2006), "Kubi Software")
        self.assertEqual(ned_then(2005), "Kubi Software")
        self.assertEqual(ned_then(2004), "Kubi Software")
        self.assertEqual(ned_then(2003), "Kubi Software")
        self.assertEqual(ned_then(2002), "Kubi Software")
        self.assertEqual(ned_then(2001), "Blue Ripple")
        self.assertEqual(ned_then(2000), "Blue Ripple")
예제 #36
0
 def org(self):
     people = People.people()
     user_info = people.get(self.user_login, self.created_at)
     return user_info.get("institution", "other")
예제 #37
0
파일: room.py 프로젝트: ssami/python
	def __init__(self, player, end=False, good=False):
		"""
			The end paramter denotes whether or not this room is the end. 
			If it's the end, the player just needs to pass whatever scenario is here and then exit successfully
			If not the end, the room will spawn other connected rooms and continue
			If "good" is false, this room will have bad things in it
		"""

		import random
		from scenery import SceneDescriptors
		from monster import Monster
		from bestiary import Bestiary
		from angel import Angel
		from host import Host
		from people import People
		from player import Player

		self._description = SceneDescriptors.getScene(good)
		if good: 
			self._creature = Angel()
			print "The angel", self._creature.name, "appears before you. It is", self._creature.description, ". It", Host.getRequest()
			print "Your choices are: "
			resp = People.getResponses()
			for key, val in enumerate(resp):
				print key, ".", resp[val]

			print "Now, what will you do? Select a number"
			
			choice = ''
			invalid = True
			while invalid:
				choice = raw_input("-->")
				if int(choice) > len(resp)-1:
					print "That number is invalid! Try again"
				elif int(choice) < 0:
					print "That number isn't even a positive number! Try again"
				else:
					print "You selected", choice
					invalid = False

			choiceType = resp.keys()[int(choice)]
			choiceText = resp[choiceType]		# always prints only one from each good, bad, wierd list anyway
			typeMap = {
				'good': True, 
				'bad': False, 
				'weird': False
			}

			if typeMap[choiceType]:
				print "The angel bestows upon you", self._creature.pointsGiven, "health and", self._creature.disappears
				player.changeHealth(self._creature.pointsGiven)

			else: 
				print "The angel is annoyed. It smites you and takes away", self._creature.pointsGiven, "health"
				player.changeHealth(-1 * self._creature.pointsGiven)
				
			print "You now have", player.health, "health left"

		else: 
			self._creature = Monster()
			print "The monster", self._creature.name, "appears before you. It is", self._creature.description
			print "Your choices are: "
			resp = People.getDefenses()

			for key, val in enumerate(resp):
				print key, ".", resp[val]

			print "Now, how will you defend yourself? Select a number"
			
			choice = ''
			invalid = True
			while invalid:
				choice = raw_input("-->")
				if int(choice) > len(resp)-1:
					print "That number is invalid! Try again"
				elif int(choice) < 0:
					print "That number isn't even a positive number! Try again"
				else:
					print "You selected", choice
					invalid = False

			choiceType = resp.keys()[int(choice)]
			choiceText = resp[choiceType]		# always prints only one from each good, bad, wierd list anyway
			typeMap = {
				'good': True, 
				'bad': False, 
				'weird': False
			}

			if typeMap[choiceType]:
				print "The monster", self._creature.death

			else: 
				print "The monster", self._creature.attack, "and you lose", self._creature.pointsTaken
				player.changeHealth(self._creature.pointsTaken)
				
			print "You now have", player.health, "health left"
예제 #38
0
 def test_main_singleton_is_a_singleton(self):
     p1 = People.people()
     p2 = People.people()
     self.assertIs(p1, p2)
예제 #39
0
def test_main_singleton_is_a_singleton(test_data):
    p1 = People.people()
    p2 = People.people()
    assert p1 is p2
예제 #40
0
    if i in starts:
        rows.append(prettify.merged_row('Conversation {} -->'.format(starts[i]), 3, colors['dialogStartStop'][0]))
    if i in stops:
        rows.append(prettify.merged_row('<-- End {}'.format(stops[i]), 3, colors['dialogStartStop'][1]))
    style = colors[p_type][i%2]
    rows.append(prettify.content_comment_row(i, p, p_type, style=style))
    
table = prettify.table('\n'.join(rows))
html = prettify.html(table)
f_out = open('www/dialogs.html','w')
f_out.write(html.encode('utf8'))
f_out.close()    
   
#%% 3a. Export numbered paragraphs with dialog AND named entity detection
print 'Pass 1: Character Learning'
ppl = People(train_set=txt, min_count=3, use_postag=use_postag)

print 'Pass 2: Character Detection'
in_conversation = False
rows = [prettify.content_comment_row('Number', 'Original text','Comments')]
interactions = np.zeros((ppl.num(), ppl.num()))
for i,(p,p_type) in enumerate(zip(paragraphs, p_types)):
    if (i+1)%10==0:
        print 'Processing paragraph {}/{}'.format(i+1, len(paragraphs))
    if i in starts: # start of conversation
        rows.append(prettify.merged_row('Conversation {} -->'.format(starts[i]), 3, colors['dialogStartStop'][0]))
        characters = set()
        in_conversation = True
    if in_conversation: # middle of conversation
        current_characters = ppl.predict(p)
        characters = characters.union(current_characters)
예제 #41
0
def test_get_institution(test_data):
    people = People.people()
    assert people.get("ned")['institution'] == "edX"
    assert people.get("db")['institution'] == "Optimists United"
예제 #42
0
def test_get_non_person(test_data):
    people = People.people()
    ghost = people.get("ghost")
    assert ghost['institution'] == "unsigned"
    assert ghost['agreement'] == "none"
예제 #43
0
파일: friend.py 프로젝트: topicus/musily
 def __init__(self, people_path, friendships_path):
   friendships_file = open(friendships_path, 'r')
   self.___people = People(people_path)
   self.friendships_reader = csv.DictReader(friendships_file, delimiter='|')
   self.__friendships = []
   self.load()
예제 #44
0
 def test_get_non_person(self):
     people = People.from_string(SAMPLE_PEOPLE)
     ghost = people.get("ghost")
     self.assertEqual(ghost["institution"], "unsigned")
     self.assertEqual(ghost["agreement"], "none")
예제 #45
0
 def test_get_institution(self):
     people = People.from_string(SAMPLE_PEOPLE)
     self.assertEqual(people.get("ned")["institution"], "edX")
     self.assertEqual(people.get("db")["institution"], "Optimists United")
예제 #46
0
 def __init__(self, name, age):
     People.__init__(self, name, age)
예제 #47
0
파일: student.py 프로젝트: kai0200/PythonST
 def __init__(self, n, a, w, c, s):
     People.__init__(self, n, a, w)
     self.s_class = c
     self.school_number = s