Example #1
0
 def __init__(self, white, black):
     self.__white = white
     self.__black = black
     self.__winner = Participant()
     self.__loser = Participant()
     self.link = None
     self.status = 'pending'
 def test_draw_winners_test_less_prizes_then_participants(self):
     file_content = [
         Participant(1, "Aaa", "Bbb"),
         Participant(1, "Aaa", "Bbb")
     ]
     prizes = [Prize("1", "Annual Vim subscription")]
     assert len(draw_winners(file_content, prizes)) == 1
Example #3
0
    def read_by_location(self):
        """
        Read the file and create Participant objects
        Group participants into 3 groups based on location
            - far
            - near
            - inda (because they are in da hood, sorry, 'in' is reserved)
        :return: dict with 3 fields, each holding a list of Participant objects
        """

        far = []
        near = []
        inda = []
        with open(self.file) as csv_file:
            rdr = csv.reader(csv_file, delimiter=self.delimiter)
            hdr = next(rdr, None)
            self.check_header(hdr, location=True)
            for row in rdr:
                if row[3] == "Far":
                    far.append(Participant(row[0], row[1], row[2]))
                elif row[3] == "Near":
                    near.append(Participant(row[0], row[1], row[2]))
                else:
                    inda.append(Participant(row[0], row[1], row[2]))
        if (len(inda) + len(far) + len(near)) < 18:
            print("Currently you need to have at least 18 participants!")
            sys.exit()
        participants = {"near": near, "far": far, "inda": inda}

        return participants
Example #4
0
def index():
    if request.method == 'GET':
        alert = ""
        return render_template('index.html', alert=alert)

    name = request.form.get("name")
    surname = request.form.get("surname")
    email = request.form.get("email")
    passport = request.form.get("passport")
    address = request.form.get("address")
    profession = request.form.get("profession")
    participant = Participant(firstname=name,
                              lastname=surname,
                              email=email,
                              passport=passport,
                              address=address,
                              profession=profession)
    db.session.add(participant)
    db.session.commit()
    alert = f"Դուք Գրանցված եք!! Ստուգեք ձեր էլեկտրոնային հասցեն {email}"

    msg = Message('Confirm Email',
                  sender='*****@*****.**',
                  recipients=[email])
    msg.body = f"Հարգելի {name}, \n\nՁեր հայտը ընդունված է: \nԽնդրում եմ ստորև ստուգեք ձեր տվյալները;\n\nԱնձնագիր- {passport}\nՀասցե- {address} \n\nՎճարում կատարելու համար 1 օրվա ընթացքում կատարել փոխանցում հետևյալ հաշվեհամարին՝ Հայէկոնոմբանկ Սպանդարյանի մասնաճյուղ, 163048123489, Անհատ ձեռնարկատեր Սերոբ Խաչատրյան։ Վճարման նպատակը՝ դասընթացի մասնակցության մուտքավճար։\n\nԼավագnւյն Մաղթանքներով,\nՍերոբ"
    mail.send(msg)

    return render_template('index.html', alert=alert)
Example #5
0
def parseLog(file):
    participant = Participant()

    print("%-25s %s" % ("Parsing log:", file))
    f = open(file, "r", encoding=my_utils.getFileEncoding(file))

    for line in f:
        line_split = line.split()
        try:
            if len(line_split) == 0:
                pass
            elif line_split[0] == "CALLSIGN:":
                participant.callsign = line_split[1].upper()
            elif line_split[0] == "NAME:":
                participant.name = " ".join(line_split[1:])
            elif line_split[0] == "CATEGORY:":
                participant.category = " ".join(line_split[1:])
            elif line_split[0] == "QSO:":
                participant.log.append(Qso(line_split))
        except:
            print("Error in line: " + line)
            pass  # empty line

    if len(participant.callsign):
        print("Success!")
    else:
        print("Error!")

    return participant
Example #6
0
def first_contact():
  json = request.get_json()
  userid = json['userid']
  rows[userid] = Participant(userid)
  if 'features' in json:
    features = json['features']
    rows[userid].features.update(json['features'])
  return jsonify(initial_argument())
Example #7
0
def loadParticipants(trials, names):
    outParticipants = []

    for trial in trials:
        for name in names:
            p = Participant(date, name, trial, fileType='.mat')
            outParticipants.append(p)

    return outParticipants
Example #8
0
 def from_list(cls, attrs):
     print(attrs)
     return cls(
         posted_by=Participant(attrs[0]),
         stock_symbol=attrs[1],
         direction=attrs[2],
         amount=int(attrs[3]),
         price=float(attrs[4]),
     )
	def createSide(self, side):
		print "creating side", side.id
		side_node = self.rootNode.createChildSceneNode("%s_node" % side.id)
		i = 0
		cur_pos = 0
		for entity in side.entities:
			i += 1
			print "creating", entity.name, entity.type
			node = side_node.createChildSceneNode("%s_node" % entity.id)
			media = self.media[entity.type]
			mesh = "%s.mesh" % media[0]
			entity_object = self.sceneManager.createEntity("%s" % entity.id, mesh)
			#entity_object.setNormaliseNormals(True)
			if entity.type == 'planet':
				entity_object.setMaterialName("Starmap/Planet/Terran")
				node.position = [-media[1] / 2 - media[1], 0, 0]
				#node.yaw(ogre.Radian(1.57))
				userObject = Participant(entity_object, entity)
			else:
				cur_pos += media[1]*2+1
				node.position = [0, cur_pos, 0]
				node.yaw(ogre.Radian(1.57))
				node.roll(ogre.Radian(1.57))

				# orient ships to face each other
				node.yaw(ogre.Radian(3.13 * len(self.sides)))
				#node.pitch(ogre.Radian(3.14))
				# Create the engine particle system
				engine = self.sceneManager.createParticleSystem(entity.name + "/Engine", "%s/Engine" % entity.type)
				userObject = Participant(entity_object, entity, engine=engine)
				engine_node = node.createChildSceneNode("%s_engine_node" % entity.id)
				engine_node.attachObject(engine)
			self.initial_positions.append((entity.id, node.position))
			obj_scale = media[1] / entity_object.mesh.boundingSphereRadius
			entity_object.setUserObject(userObject)
			self.wfl.registerEntity(entity_object, node)
			self.mfl.registerEntity(entity_object, node)
			node.attachObject(entity_object)
			node.setScale(ogre.Vector3(obj_scale, obj_scale, obj_scale))
			entity_object.setVisible(False)
			self.userobjects[entity.id] = userObject
			self.nodes[entity.id] = node

		self.sides.append(side_node)
Example #10
0
    def parse_file(path):
        """This method takes the directory path and returns a list\nwith the mapped contents"""
        pathfile = open(str(path), 'r')
        reader = csv.reader(pathfile)
        lista = []
        for row in reader:
            #print(row)
            lista.append(Participant(row[0], row[1]))

        return lista
Example #11
0
 def __init__(self):
     self.participants = []
     f = open(self.fileName(), 'r')
     lines = f.readlines()
     f.close()
     for line in lines:
         participant = Participant()
         participant.setFromLine(line)
         self.participants.append(participant)
     self.sort()
Example #12
0
def solo():
    """ Only one participant, its too few. """
    try:
        _ = participants_shuffler([Participant("", "")])
    except AssertionError:
        print('Exception catched. Great')
        return 1, 1
    else:
        print('Error: Exception not catched')
        return 0, 1
 def __init__(self, fileNameString='./participants.txt'):
     self.fileName = fileNameString
     self.participants = []
     f = open(self.fileName, 'r')
     lines = f.readlines()
     f.close()
     for line in lines:
         participant = Participant()
         participant.setFromLine(line)
         self.participants.append(participant)
     self.sort()
Example #14
0
def read_participants():
    participants = []
    raw_data = str(read_data(Path("participants.txt"))).strip("\n")
    raw_participants = raw_data.split("\n")
    for raw_participant in raw_participants:
        raw_participant = raw_participant.split(",")
        participants.append(
            Participant(
                raw_participant[0], raw_participant[1],
                Address(raw_participant[2], raw_participant[3],
                        raw_participant[4], raw_participant[5])))
    return participants
 def _extract_participants(self, participant_data, read_state,
                           user_phone_number, self_gaia_id):
     # Builds a dictionary of the participants in a conversation/thread
     participant_list = {}
     for participant in participant_data:
         # Create a new participant and store its properties
         current_participant = Participant()
         current_participant.name = getattr(participant, "fallback_name",
                                            None)
         participant_id = getattr(participant, "id", None)
         current_participant.chat_id = self._try_int_attribute(
             participant_id, "chat_id")
         current_participant.gaia_id = self._try_int_attribute(
             participant_id, "gaia_id")
         current_participant.type = getattr(participant, "participant_type",
                                            None)
         # Parse participant phone details
         phone_number = getattr(participant, "phone_number", None)
         if phone_number is not None:
             current_participant.e164_number = getattr(
                 phone_number, "e164", None)
             i18n_data = getattr(phone_number, "i18n_data", None)
             if i18n_data is not None:
                 current_participant.country_code = getattr(
                     i18n_data, "country_code", None)
                 current_participant.international_number = getattr(
                     i18n_data, "international_number", None)
                 current_participant.national_number = getattr(
                     i18n_data, "national_number", None)
                 current_participant.region_code = getattr(
                     i18n_data, "region_code", None)
         # Sometimes the phone number is missing...
         # This only seems to happen for the user, not others
         if (current_participant.gaia_id is not None
                 and current_participant.gaia_id == self_gaia_id
                 and (current_participant.e164_number is None
                      and current_participant.international_number is None
                      and current_participant.national_number is None)):
             current_participant.e164_number = user_phone_number
             current_participant.international_number = user_phone_number
         participant_list[current_participant.gaia_id] = current_participant
     # Parse read_state to get latest_read_timestamp for each participant
     if read_state is not None:
         for participant_read_state in read_state:
             participant_id = getattr(participant_read_state,
                                      "participant_id", None)
             gaia_id = self._try_int_attribute(participant_id, "gaia_id")
             latest_read_timestamp = self._try_int_attribute(
                 participant_read_state, "latest_read_timestamp")
             if gaia_id in participant_list.keys():
                 participant_list[
                     gaia_id].latest_read_timestamp = latest_read_timestamp
     return participant_list
Example #16
0
def registerUser():
    global confirm
    global registerAnother
    confirm = input("Papel: " + str(role) + " Nível: " + str(level) +
                    ". Podemos confirmar sua inscrição ? (s/n) ")
    if confirm == "S" or confirm == "s":
        participantsList.append(Participant(name, role, level))
        print("Inscrição confirmada com sucesso!")
        print(participantsList)
        registerAnother = input("Deseja registrar outro usuário? (s/n)")
    else:
        print("Inscrição cancelada!")
        registerAnother = input("Deseja registrar outro usuário? (s/n)")
Example #17
0
def main(argv):

    #set url for serverRequests
    url = ridertrackUrl

    participants = []
    
    if(len(argv) >= 1):
        eventId = argv

    f = open('users.txt','r')

    startingLine = True
    counting = 0
    while (True):
        l = f.readline().strip()
        if (startingLine  == True):
            startingLine = False
            continue
    
        if counting > 5:
            break

        line = l.split(',')
        user = Participant(line[0],line[1],line[2],line[3])
        participants.append(user)
        print (user.email)
        counting = counting + 1
    f.close()

    for p in participants:
        #login or register
        tupleTokenId = ()
        try:
            tupleTokenId = serverRequests.login(url,p.email,p.password)
        except:
            tupleTokenId = serverRequests.register(url,p.name,p.surname,p.email,p.password)
        p.token = tupleTokenId[0]
        p.userId = tupleTokenId[1]
        #enroll users
        serverRequests.enroll(url,p.token,p.userId,eventId)

    #get route
    print ("Enrollment part finished")
    coordinates = serverRequests.getRoute(url,eventId)
    print (coordinates)
    r = Route(coordinates)
    #simulate
    simulator.simulate(url,eventId,participants,r)
Example #18
0
def info_input(participants):
    participant_number = 0
    # loop for information input
    for numParticipant in range(0, MAXPARTICIPANT + 1):

        name = input("What is the name?\n")
        paid = input("How much did %s pay in total?\n" % (name))
        # insert into the participants list
        temp = Participant(name, float(paid))
        participants.append(temp)
        repeat = input("Add another participant? ")
        participant_number = participant_number + 1
        if repeat != "y" and repeat != "Y":
            break
    return participant_number
Example #19
0
    def load_participants(self):
        """create instances of storage node for participants in this cluster"""
        self._participants = {}

        try:
            instances = self.functions.get_instances(self.cluster)
            for instance in instances:
                ident = instance["id"]
                enabled = instance["simpleFields"]["HELIX_ENABLED"]
                alive = instance["simpleFields"]["Alive"]
                data = instance
                participant = Participant(ident, alive, enabled, data)
                self._participants[instance["id"]] = participant
        except HelixException:
            pass
Example #20
0
    def handle_stream(self, stream, address):
        """
        When a new incoming connection is found, this function is called. Wrap
        the incoming connection in a Participant, then make it the most recent
        connection. Tell the oldest connection to use the new one as its
        write target.
        """
        r = Participant(stream, self.db)

        if self.last_connection is not None:
            self.last_connection.add_destination(r)

        self.last_connection = r

        r.wait_for_headers()
def open_file(path):

    reader = csv.reader(open(path, 'r'), delimiter=',', dialect='excel')
    participants = []
    participant = None
    rownum = 0
    for row in reader:
        participant_id = None
        marathon_date = None
        marathon_name = None
        marathon_type = None
        marathon_time = None
        marathon_category = None
        #participant.append(row)
        if rownum == 0:
            header = row
        else:
            colnum = 0
            for col in row:
                if header[colnum] == "PARTICIPANT ID":
                    participant_id = col
                    participant = Participant(col)
                elif header[colnum] == "EVENT DATE":
                    marathon_date = col
                elif header[colnum] == "EVENT NAME":
                    marathon_name = col
                elif header[colnum] == "EVENT TYPE":
                    marathon_type = col
                elif header[colnum] == "TIME":
                    marathon_time = col
                    if marathon_time == "-1":
                        participant.failed_times += 1
                elif header[colnum] == "CATEGORY":
                    marathon_category = col
                    participant.total_marathons += 1
                    participant.add_marathon(marathon_date, marathon_name,
                                             marathon_type, marathon_time,
                                             marathon_category)
                else:
                    print("Exception!")

                colnum += 1

        participants.append(participant)

        rownum += 1

    return participants
Example #22
0
def parseLogs(logs_dir):
    """
    Reads all the logs in the supplied directory and parses the data into dictionary that is returned

    :param logs_dir: Directory where the log files are located
    :return: Dictonary of particpants. {callsign, participant object}
    :rtype: dict
    """
    participants = {}

    for filename in glob.glob(os.path.join(logs_dir, "*.*")):

        participant = Participant()

        logger.info("parsing log: " + filename)
        logfile = open(filename,
                       "r",
                       encoding=my_utils.getFileEncoding(filename))

        try:
            for line in logfile:
                line_split = line.split()
                try:
                    if len(line_split) == 0:
                        pass
                    elif line_split[0] == "CALLSIGN:":
                        participant.callsign = line_split[1].upper()
                    elif line_split[0] == "NAME:":
                        participant.name = " ".join(line_split[1:])
                    elif line_split[0] == "CATEGORY:":
                        participant.category = " ".join(line_split[1:])
                    elif line_split[0] == "QSO:":
                        participant.log.append(Qso(line_split))
                except:
                    logger.warning("Error in line (will be ignored): " + line)
                    pass  # empty line
        except Exception as e:
            logger.warning("Error in file (will be ignored): " + filename)
            logger.warning("Error: " + str(e))
            pass

        if len(participant.callsign):
            participants[participant.callsign] = participant
            logger.info("Parsed log for: " + participant.callsign + "\n")
        else:
            logger.error("Couldn't parse the file: " + filename + "\n")

    return participants
Example #23
0
File: bridge.py Project: Armael/xib
    def add_participant(self, from_protocol, nickname, real_jid=None):
        """Add a participant to the bridge."""
        if (from_protocol == 'irc' and nickname == self.bot.nickname) or (
                from_protocol == 'xmpp' and nickname == self.bot.nickname):
            return
        try:
            p = self.get_participant(nickname)
            if p.protocol != from_protocol:
                if from_protocol == 'irc' and isinstance(
                        p.irc_connection, irclib.ServerConnection
                ) and p.irc_connection.channels.has_key(
                        self.irc_room
                ) and p.irc_connection.channels[
                        self.
                        irc_room].state >= irclib.JOINING or from_protocol == 'xmpp' and isinstance(
                            p.muc, xmpp.muc) and p.muc.state >= p.muc.JOINING:
                    return p
                p.set_both_sides()
            return p
        except self.NoSuchParticipantException:
            pass

        if nickname == 'ChanServ' and from_protocol == 'irc':
            return

        self.bot.error(3,
                       'adding participant "' + nickname + '" from "' +
                       from_protocol + '" to bridge "' + str(self) + '"',
                       debug=True)
        try:
            p = Participant(self, from_protocol, nickname, real_jid=real_jid)
        except:
            self.bot.error(
                say_levels.debug, 'unknown error while adding participant "' +
                nickname + '" from "' + from_protocol + '" to bridge "' +
                str(self) + '"\n' + traceback.format_exc())
            return
        self.lock.acquire()
        self.participants.append(p)
        self.lock.release()
        if self.mode not in ['normal', 'bypass']:
            if from_protocol == 'xmpp':
                self.show_participants_list_on(protocols=['irc'])
            elif self.mode == 'minimal' and from_protocol == 'irc':
                self.show_participants_list_on(protocols=['xmpp'])
        return p
    def __init__(self, strategies, rounds, round_player_count):
        """
    Creates a new round-robin tournament.

    Parameters:
     strategies: array of participating strategies
     rounds: number of rounds to play in each match
     round_player_count: number of duplicated representatives of each strategy in matches

    Fields:
     result_matrix: dictionary where key is pair of participants and value is average_payoff of the first in match
    """

        self._participants = [Participant(strategy) for strategy in strategies]
        self._rounds = rounds
        self._round_player_count = round_player_count
        self._result_matrix = {}
Example #25
0
    def read_simple(self):
        """
        Read the file and create Participant objects without grouping
        :return: list of Participant objects
        """

        participants = []
        with open(self.file) as csv_file:
            rdr = csv.reader(csv_file, delimiter=self.delimiter)
            hdr = next(rdr, None)
            self.check_header(hdr, location=False)
            for row in rdr:
                participants.append(Participant(row[0], row[1], row[2]))
        if len(participants) < 18:
            print("Currently you need to have at least 18 participants!")
            sys.exit()
        return participants
Example #26
0
 def select_lucky_winner(self):
     winner = None
     with open("participants.csv") as peeps:
         reader = csv.reader(peeps)
         next(reader)  # skip header
         choices = list(reader)
         chore_log = pandas.read_csv("chore_log.csv")
         filtered_by_chore = chore_log[chore_log['chore_type'] ==
                                       self.state.chore_type]
         if len(filtered_by_chore.index) >= 2:
             recent_winners = self.get_recent_winners(
                 self.state.chore_type, 2)
             choices = [x for x in choices if x not in recent_winners]
         winner = random.choice(choices)
         winner = Participant(winner[0], winner[1])
         print("winner")
         print(winner)
     return winner
Example #27
0
    def post(self):
		user = users.get_current_user()
		if user:
			name = self.request.get('name')
			email = self.request.get('email')

			participant = Participant(id=email, name=name, email=email)
			participant.put()

			participants_query = Participant.query().order(-Participant.date)
			participants = participants_query.fetch()

			template_values = {
				'participants': participants
	    	}

			utils.fillTemplate(self.response, 'joined.html', template_values)
		else:
			self.redirect(users.create_login_url(self.request.uri))
Example #28
0
    def generate_web(self, template, dst):
        timetable_headings, timetables = TimeTable(self.timetable_source_file).gen_tables()
        abst_headings, abst_tables = AbstTable(self.timetable_source_file).gen_tables()
        room_headings, room_tables = Room(self.room_source_file).gen_room_table_t()

        env = Environment(loader=FileSystemLoader('./', encoding='utf-8'))
        tmpl = env.get_template(template)
        v = {
            'timetables': timetables,
            'timetable_headings': timetable_headings,
            'abst_headings': abst_headings,
            'abst_tables': abst_tables,
            'info': self.md_converter('info'),
            'room_headings': room_headings,
            'room_tables': room_tables,
            'sponsor': self.gen_sponsor_table(self.sponsor_source_file),
            'ryokan': self.md_converter('ryokan'),
            'participant_table': Participant(self.participant_source_file).gen_table()
        }
        with open(dst, 'w') as f:
            f.write(tmpl.render(v))
Example #29
0
    def assign_data_to_participants(self):

        for i in range(self.num_of_participants):
            self.participants.append(
                Participant(self, self.X_train[i], self.y_train[i],
                            self.upload_percentage))
 def addNewParticipantNamed(self, nameString) -> None:
     if not self.hasParticipantNamed(nameString):
         participant = Participant()
         participant.name = nameString
         self.participants.append(participant)
     self.sort()