예제 #1
0
 def post(self):
     dao = Dao()
     self.response.out.write(dao.put_linha(id = self.request.get("id"),
                                           deleted = self.request.get("deleted"),
                                           info = self.request.get("info"),
                                           pontos = self.request.get("pontos"),
                                           hashes = self.request.get("hashes")))
예제 #2
0
    def test_init_with_invalid_region(self):
        # create a dao with an existing region
        Dao('norcal', self.mongo_client, database_name=DATABASE_NAME)

        # create a dao with a non existant region, should return none
        self.assertIsNone(
            Dao('newregion', self.mongo_client, database_name=DATABASE_NAME))
예제 #3
0
def import_tournament(type, path, bracket, region, name):
    config = Config()
    mongo_client = MongoClient(host=config.get_mongo_url())

    if type == 'tio':
        scraper = TioScraper(path, bracket)
    elif type =='challonge':
        scraper = ChallongeScraper(path)
    else:
        click.echo("Illegal type")

    dao = Dao(region, mongo_client=mongo_client)

    player_map = get_player_alias_to_id_map(scraper, dao)

    # TODO pass in a map of overrides for specific players
    tournament = Tournament.from_scraper(type, scraper, player_map, region)
    if name:
        tournament.name = name

    dao.insert_tournament(tournament)

    click.echo("Generating new ranking...")
    rankings.generate_ranking(dao)

    click.echo("Done!")
예제 #4
0
파일: server.py 프로젝트: garsh0p/garpr
    def get(self, region):
        dao = Dao(region, mongo_client=mongo_client)
        if not dao:
            return 'Dao not found', 404
        user = get_user_from_request(request, dao)

        if not user:
            return 'Permission denied', 403
        if not user.admin_regions:
            return "user is not an admin", 403

        return_dict = {}
        return_dict['merges'] = [m.dump(context='web')
                                 for m in dao.get_all_merges()]

        for merge in return_dict['merges']:
            # TODO: store names in merge object
            source_player = dao.get_player_by_id(merge['source_player_obj_id'])
            target_player = dao.get_player_by_id(merge['target_player_obj_id'])

            if source_player is not None and target_player is not None:
                merge['source_player_name'] = source_player.name
                merge['target_player_name'] = target_player.name
                merge['requester_name'] = user.username

        return return_dict
예제 #5
0
파일: server.py 프로젝트: acoulon99/garpr
    def put(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        player = dao.get_player_by_id(ObjectId(id))

        if not player:
            return "No player found with that region/id.", 400

        # TODO auth for this needs to be different, otherwise an admin can tag with their region and then edit everything
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_regions(user, player.regions):
            return 'Permission denied', 403

        args = player_put_parser.parse_args()

        if args['name']:
            player.name = args['name']
        if args['aliases']:
            for a in args['aliases']:
                if not isinstance(a, unicode):
                    return "each alias must be a string", 400
            new_aliases = [a.lower() for a in args['aliases']]
            if player.name.lower() not in new_aliases:
                return "aliases must contain the players name!", 400
            player.aliases = new_aliases
        if args['regions']:
            for a in args['regions']:
                if not isinstance(a, unicode):
                    return "each region must be a string", 400
            player.regions = args['regions']

        dao.update_player(player)
예제 #6
0
def handleFileUpload():
    if (not d.isResourceInDb(conn, request.form['file'])):
        if 'file' in request.files:
            photo = request.files['file']
            print(photo.filename)
            extension = photo.filename.split(".")[-1]
            photo.save("./static/" + request.form['title'] + "." + extension)
            bucket.upload_local_file(
                local_file="./static/" + request.form['title'] + "." +
                extension,
                file_name=request.form['title'] + "." + extension,
                file_infos={"mood": "smile"},
            )
            os.remove("./static/" + request.form['title'] + "." + extension)
            global author
            print("keywords")
            print(request.form['keywords'])
            i = ""
            keywords = ""
            for j in request.form['keywords']:
                keywords += i
            d.addResource(conn, request.form['title'] + "." + extension,
                          request.form['keywords'], author)
        return render_template("startPage.html")
    else:
        return render_template("addResource.html",
                               error="Choose unique title fo your file")
예제 #7
0
def readings():
    dao=Dao()
    if(request.method=='POST'):
        _name = request.form.get('buildingName')
        info=dao.getDocumentsByName(_name)
        json_readings = [reading.to_json() for reading in info]
        return jsonify(json_readings)
예제 #8
0
 def __init__(self):
     self.view = ViewRoot()
     self.dao = Dao()
     self.controller_container = ControllerMainContainer()
     self.model_root = ModelRoot(
         self.controller_container.get_associated_container())
     self.controller_information = ControllerInformation(self.model_root)
예제 #9
0
    def test_dao(self):
        lista = []
        lista.append([1, 2, 3, 4])
        dao = Dao("/Users/MeteOro/codigo/larva/")
        ahora = datetime.now()

        dao.save(lista, "prueba", ahora)
예제 #10
0
파일: server.py 프로젝트: garsh0p/garpr
    def put(self, region):
        dao = Dao(region, mongo_client=mongo_client)
        args = rankings_criteria_get_parser.parse_args()

        try:
            ranking_num_tourneys_attended = int(args['ranking_num_tourneys_attended'])
            ranking_activity_day_limit = int(args['ranking_activity_day_limit'])
            tournament_qualified_day_limit = int(args['tournament_qualified_day_limit'])
        except Exception as e:
            return 'Error parsing Ranking Criteria, please try again: ' + str(e), 400

        print ranking_num_tourneys_attended
        print ranking_activity_day_limit

        if not dao:
            return 'Dao not found', 404
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_region(user, region):
            return 'Permission denied', 403

        try:
            # TODO Update rankings and store criteria in db
            dao.update_region_ranking_criteria(region,
                                               ranking_num_tourneys_attended=ranking_num_tourneys_attended,
                                               ranking_activity_day_limit=ranking_activity_day_limit,
                                               tournament_qualified_day_limit=tournament_qualified_day_limit)
        except Exception as e:
            print str(e)
            return 'There was an error updating the region rankings criteria', 400

        return dao.get_region_ranking_criteria(region)
예제 #11
0
파일: server.py 프로젝트: acoulon99/garpr
    def get(self, region):
        args = player_list_get_parser.parse_args()
        dao = Dao(region, mongo_client=mongo_client)
        return_dict = {}

        # single player matching alias within region
        if args['alias'] is not None:
            return_dict['players'] = []
            db_player = dao.get_player_by_alias(args['alias'])
            if db_player:
                return_dict['players'].append(db_player.get_json_dict())
        # search multiple players by name across all regions
        elif args['query'] is not None:
            all_players = dao.get_all_players(all_regions=True)
            return_dict['players'] = [p.get_json_dict() for p in self._get_players_matching_query(all_players, args['query'])]
        # all players within region
        else:
            return_dict['players'] = [p.get_json_dict() for p in dao.get_all_players()]

        convert_object_id_list(return_dict['players'])

        # remove extra fields
        for player in return_dict['players']:
            del player['regions']
            del player['aliases']
            del player['ratings']

        return return_dict
예제 #12
0
def bulk_alias_merge(path, region):
    config = parse_config()
    username = config.get('database', 'user')
    host = config.get('database', 'host')
    auth_db = config.get('database', 'auth_db')
    password = getpass.getpass()

    mongo_client = MongoClient(host='mongodb://%s:%s@%s/%s' % (username, password, host, auth_db))
    dao = Dao(region, mongo_client=mongo_client)

    with open(path) as f:
        reader = csv.reader(f)
        for row in reader:
            target_alias = row[0]
            db_target = dao.get_player_by_alias(target_alias)
            if db_target is None:
                print '%s is not a valid alias' % target_alias
                continue

            for source_alias in row[1:]:
                source_alias = source_alias.strip()
                if source_alias:
                    db_source = dao.get_player_by_alias(source_alias)
                    if db_source is None:
                        print '%s is not a valid alias' % source_alias
                        continue

                    print source_alias, '->', target_alias
                    dao.merge_players(source=db_source, target=db_target)
예제 #13
0
def grab(interval):
    coeffprovider = CoeffProvider()
    dao = Dao()
    coeffs = coeffprovider.get_coeff_list()
    dao.save_new_data(coeffs)
    print(time.ctime())
    threading.Timer(interval, grab, [interval]).start()
예제 #14
0
 def post(self, region):
     dao = Dao(region, mongo_client=mongo_client)
     requesting_user = get_user_from_access_token(request.headers, dao)
     if not requesting_user.admin_regions:  #wow, such auth
         return "user is not an admin", 403
     args = merges_put_parser.parse_args()  #parse args
     try:
         base_player_id = ObjectId(args['base_player_id'])
         to_be_merged_player_id = ObjectId(args['to_be_merged_player_id'])
     except:
         return "invalid ids, that wasn't an ObjectID", 400
     # the above should validate that we have real objectIDs
     # now lets validate that both of those players exist
     if not dao.get_player_by_id(base_player_id):
         return "base_player not found", 400
     if not dao.get_player_by_id(to_be_merged_player_id):
         return "to_be_merged_player not found", 400
     #get curr time
     now = datetime.now()
     #create a new merge object
     the_merge = Merge(requesting_user.id, base_player_id,
                       to_be_merged_player_id, now)
     #store it in the dao
     merge_id = dao.insert_pending_merge(the_merge)
     string_rep = str(merge_id)
     return_dict = {'id': string_rep}
     return return_dict, 200
예제 #15
0
파일: server.py 프로젝트: garsh0p/garpr
    def put(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        user = get_user_from_request(request, dao)

        args = tournament_details_add_match_parser.parse_args()
        tournament = dao.get_tournament_by_id(ObjectId(id))

        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_regions(user, tournament.regions):
            return 'Permission denied', 403

        winner_id = args['winner_id']
        loser_id = args['loser_id']

        if winner_id is None or loser_id is None:
            print "winner and loser IDs not present. Cannot continue"
            return "winner and loser IDs not present. Cannot continue", 400

        try:
            dao.add_match_by_tournament_id(ObjectId(id), ObjectId(winner_id), ObjectId(loser_id))
            return 'Successful addition', 200
        except Exception as e:
            print 'error adding match to tournament: ' + str(e)
            return 'error adding match to tournament: ' + str(e), 400
예제 #16
0
    def test_init_with_invalid_region(self):
        # create a dao with an existing region
        Dao('norcal', self.mongo_client, database_name=DATABASE_NAME)

        # create a dao with a new region
        with self.assertRaises(RegionNotFoundException):
            Dao('newregion', self.mongo_client, database_name=DATABASE_NAME)
예제 #17
0
파일: server.py 프로젝트: acoulon99/garpr
    def delete(self, region, id):
        """ Deletes a pending tournament.
            If a (non-pending) tournament with this id exists, tell the user they can't do that.
            Route restricted to admins for this region. """
        dao = Dao(region, mongo_client=mongo_client)

        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403

        pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))

        if not pending_tournament:
            tournament = dao.get_tournament_by_id(ObjectId(id))
            if not tournament:
                return "No pending tournament found with that id.", 400
            else:
                if not is_user_admin_for_regions(user, tournament.regions):
                    return 'Permission denied', 403
                else:
                    return "Cannot delete a finalized tournament.", 400

        if not is_user_admin_for_regions(user, pending_tournament.regions):
            return 'Permission denied', 403

        dao.delete_pending_tournament(pending_tournament)
        return {"success": True}
예제 #18
0
def add_sale():
    email = raw_input("Enter your email address:")
    password = getpass.getpass(stream=sys.stderr)

    seller_id = Dao.get_user_id(email, password)
    if seller_id == None:
        return

    startdate = datetime.now().date()
    enddate_input = raw_input("Please enter end date time in correct format mm/dd/yyyy: ")
    try:
        enddate = datetime.strptime(enddate_input, "%m/%d/%Y").date()
    except ValueError:
        print "Please enter date in the format mm/dd/yyyy"
        return

    address_line_one = raw_input("Enter address line one:")
    address_line_two = raw_input("Enter address line two:")
    city = raw_input("Enter city:")
    state = raw_input("Enter state:")
    country = raw_input("Enter country:")
    pincode = raw_input("Enter pincode:")
    match = re.match('^\\d{5}(-\\d{4})?$', pincode)

    if not match:
        print "\nInvalid pincode %s. It should be in the format xxxxxx-xxxx" % pincode
        return
    start_price = raw_input("Enter start price:")

    sale = Sale(seller_id, startdate, enddate, address_line_one, address_line_two, city, state, country, pincode,
                start_price)
    Dao.sale_by_user(sale)
예제 #19
0
def import_tournament(type, path, bracket, region, name):
    config = Config()
    mongo_client = MongoClient(host=config.get_mongo_url())

    if type == 'tio':
        scraper = TioScraper.from_file(path, bracket)
    elif type == 'challonge':
        scraper = ChallongeScraper(path)
    else:
        click.echo("Illegal type")

    dao = Dao(region, mongo_client=mongo_client)

    player_map = get_player_alias_to_id_map(scraper, dao)

    # TODO pass in a map of overrides for specific players
    tournament = Tournament.from_scraper(type, scraper, player_map, region)
    if name:
        tournament.name = name

    dao.insert_tournament(tournament)

    click.echo("Generating new ranking...")
    rankings.generate_ranking(dao)

    click.echo("Done!")
예제 #20
0
파일: server.py 프로젝트: MrMonacle/garpr
 def post(self, region):
     dao = Dao(region, mongo_client=mongo_client)
     requesting_user = get_user_from_access_token(request.headers, dao)
     if not requesting_user.admin_regions: #wow, such auth
         return "user is not an admin", 403
     args = merges_put_parser.parse_args() #parse args
     try:
         base_player_id = ObjectId(args['base_player_id'])
         to_be_merged_player_id = ObjectId(args['to_be_merged_player_id'])
     except:
         return "invalid ids, that wasn't an ObjectID", 400
     # the above should validate that we have real objectIDs
     # now lets validate that both of those players exist
     if not dao.get_player_by_id(base_player_id):
         return "base_player not found", 400
     if not dao.get_player_by_id(to_be_merged_player_id):
         return "to_be_merged_player not found", 400
     #get curr time
     now = datetime.now()
     #create a new merge object
     the_merge = Merge(requesting_user.id, base_player_id, to_be_merged_player_id, now)
     #store it in the dao
     merge_id = dao.insert_pending_merge(the_merge)
     string_rep = str(merge_id)
     return_dict = {'id': string_rep}
     return return_dict, 200
예제 #21
0
def olympic_marathoners():
    year = request.args['year']
    sex = request.args['sex']
    dao = Dao()
    results = dao.marathoners_in_year(year, sex)
    dao.close()
    return render_template('marathoners.html', results=results)
예제 #22
0
def import_tournament(type, path, bracket, region, name):
    config = parse_config()
    username = config.get('database', 'user')
    host = config.get('database', 'host')
    auth_db = config.get('database', 'auth_db')
    password = getpass.getpass()

    mongo_client = MongoClient(host='mongodb://%s:%s@%s/%s' % (username, password, host, auth_db))

    if type == 'tio':
        scraper = TioScraper(path, bracket)
    elif type =='challonge':
        scraper = ChallongeScraper(path)
    else:
        click.echo("Illegal type")

    dao = Dao(region, mongo_client=mongo_client)

    import_players(scraper, dao)

    tournament = Tournament.from_scraper(type, scraper, dao)
    if name:
        tournament.name = name

    dao.insert_tournament(tournament)

    click.echo("Generating new ranking...")
    rankings.generate_ranking(dao)

    click.echo("Done!")
예제 #23
0
def withdraw_my_sales():
    email = raw_input("Enter your email address:")
    password = getpass.getpass(stream=sys.stderr)

    seller_id = Dao.get_user_id(email, password)
    if seller_id == None:
        return

    sales_dict = Dao.my_active_sale_details(seller_id)

    if not sales_dict:
        print "No sales found"
        return

    for sale_id in sales_dict:
        print "Sale id: %s" % sale_id
        pretty_print(sales_dict[sale_id])

    with_draw_sale_id = raw_input("Please enter sale id to withdraw: ")
    if int(with_draw_sale_id) not in sales_dict:
        print "Invalid sale id entered to withdraw"
        return

    Dao.withdraw_sale(with_draw_sale_id)
    print "Sale withdrawn successfully"
    pretty_print(sales_dict[int(with_draw_sale_id)])

    return sales_dict
예제 #24
0
파일: server.py 프로젝트: garsh0p/garpr
    def get(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        if not dao:
            return 'Dao not found', 404
        response = None
        tournament = None
        try:
            tournament = dao.get_tournament_by_id(ObjectId(id))
        except:
            return 'Invalid ObjectID', 400
        if tournament is not None:
            response = convert_tournament_to_response(tournament, dao)
        else:
            user = get_user_from_request(request, dao)
            # this usage is safe, if the ID was fake, we would have already
            # blown the coop above
            pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
            if not pending_tournament:
                return 'Not found!', 404
            if not user:
                return 'Permission denied', 403
            if not is_user_admin_for_regions(user, pending_tournament.regions):
                return 'Permission denied', 403
            response = pending_tournament.dump(context='web')

        return response
예제 #25
0
def view_my_sales():
    email = raw_input("Enter your email address:")
    password = getpass.getpass(stream=sys.stderr)

    seller_id = Dao.get_user_id(email, password)
    if seller_id == None:
        return

    '''
       {
           1 : salesObj1,
           2 : salesObj2,
           4 : saledObj3
       }
    '''
    sales_dict = Dao.get_sale_details(seller_id)

    if not sales_dict:
        print "No sales found"
        return

    for sale_id in sales_dict:
        print "Sale id: %s" % sale_id
        pretty_print(sales_dict[sale_id])

    return sales_dict
예제 #26
0
파일: server.py 프로젝트: acoulon99/garpr
 def delete(self):
     args = session_delete_parser.parse_args()
     dao = Dao('norcal', mongo_client=mongo_client) # lol this doesn't matter, b/c we're just trying to log a user
     logout_success = dao.logout_user_or_none(args['session_id'])
     if not logout_success:
         return 'who is you', 404
     return 'logout success', 200, {'Set-Cookie': "session_id=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"}
예제 #27
0
파일: server.py 프로젝트: garsh0p/garpr
    def put(self):
        dao = Dao(None, mongo_client=mongo_client)

        if not dao:
            return 'Dao not found', 404
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        #if not is_user_admin_for_region(user, region='*'):
        #    return 'Permission denied', 403

        args = admin_functions_parser.parse_args()

        function_type = args['function_type']
        if function_type == 'region':
            region_name = args['new_region']

            #Execute region addition
            config = Config()
            if dao.create_region(region_name):
                print("region created:" + region_name)

        elif function_type == 'user':
            uname = args['new_user_name']
            upass = args['new_user_pass']
            uperm = args['new_user_permissions']
            uregions = args['new_user_regions']

            #Execute user addition
            dao = Dao(None, mongo_client)
            if dao.create_user(uname, upass, uregions):
                print("user created:" + uname)
예제 #28
0
	def __init__(self):
		self.robot = Robot()
		self.basic = Basic()
		self.material = Material()
		self.dao  = Dao()
		self.dao.connect()
		self.spider = Spider()
예제 #29
0
파일: server.py 프로젝트: jschnei/garpr
    def get(self, region):
        args = player_list_get_parser.parse_args()
        dao = Dao(region, mongo_client=mongo_client)
        return_dict = {}

        # single player matching alias within region
        if args['alias'] is not None:
            return_dict['players'] = []
            db_player = dao.get_player_by_alias(args['alias'])
            if db_player:
                return_dict['players'].append(db_player.get_json_dict())
        # search multiple players by name across all regions
        elif args['query'] is not None:
            all_players = dao.get_all_players(all_regions=True)
            return_dict['players'] = [
                p.get_json_dict() for p in self._get_players_matching_query(
                    all_players, args['query'])
            ]
        # all players within region
        else:
            return_dict['players'] = [
                p.get_json_dict() for p in dao.get_all_players()
            ]

        convert_object_id_list(return_dict['players'])

        # remove extra fields
        for player in return_dict['players']:
            del player['regions']
            del player['aliases']
            del player['ratings']

        return return_dict
def home():
    str = "Vol"
    li = [230, 2, 3, 4]
    rand1 = random.randint(220, 250)
    rand2 = random.randint(0, 10)
    #print(random.randint(0,99))
    da = Dao()
    power_data = PowerPara()
    #power_data.vol = str(data)
    #power_data.cur = "123"
    #power_data.power = "22"
    str2 = da.findData(power_data, 2, 3)
    # return db find data
    #print(str2)
    vol = random.randint(220, 240)
    cur = random.randint(0, 20)
    pwr = random.randint(0, 2)
    tmp = random.randint(0, 40)
    rssi = random.randint(0, 80)
    #print(str1)
    return render_template('general_parameters.html',
                           vol=vol,
                           cur=cur,
                           pwr=pwr,
                           tmp=tmp,
                           rssi=rssi)
예제 #31
0
def get_candles(market, start_date, end_date):
    df_candles = None
    try:
        df_candles = pd.read_csv('../candles/{}.csv'.format(market),
                                 index_col='date_time',
                                 parse_dates=True)
    except FileNotFoundError:
        db = Dao()
        candles = db.get_candles(market=market)
        df_candles = pd.DataFrame(candles,
                                  columns=[
                                      'market', 'date_time', 'open', 'high',
                                      'low', 'close', 'volume'
                                  ])
        df_candles.drop(columns='market', inplace=True)
        df_candles['date_time'] = pd.to_datetime(df_candles['date_time'])
        df_candles.set_index('date_time', inplace=True)
        df_candles.to_csv('../candles/{}.csv'.format(market))
    if start_date:
        start_dt = datetime.strptime(start_date, '%Y-%m-%d')
        df_candles = df_candles[df_candles.index >= start_dt]
    if end_date:
        end_dt = datetime.strptime(end_date, '%Y-%m-%d')
        df_candles = df_candles[df_candles.index <= end_dt]
    return df_candles
예제 #32
0
파일: server.py 프로젝트: jschnei/garpr
    def put(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        player = dao.get_player_by_id(ObjectId(id))

        if not player:
            return "No player found with that region/id.", 400

        # TODO auth for this needs to be different, otherwise an admin can tag with their region and then edit everything
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_regions(user, player.regions):
            return 'Permission denied', 403

        args = player_put_parser.parse_args()

        if args['name']:
            player.name = args['name']
        if args['aliases']:
            for a in args['aliases']:
                if not isinstance(a, unicode):
                    return "each alias must be a string", 400
            new_aliases = [a.lower() for a in args['aliases']]
            if player.name.lower() not in new_aliases:
                return "aliases must contain the players name!", 400
            player.aliases = new_aliases
        if args['regions']:
            for a in args['regions']:
                if not isinstance(a, unicode):
                    return "each region must be a string", 400
            player.regions = args['regions']

        dao.update_player(player)
예제 #33
0
def olympic_marathoners_json():
    year = request.args['year']
    sex = request.args['sex']
    dao = Dao()
    results = dao.marathoners_in_year(year, sex)
    dao.close()
    jstr = json.dumps(results, sort_keys=False, indent=2)
    return Response(jstr, mimetype='application/json')
예제 #34
0
class InsertTest(object):
    def __init__(self):
        self.powerpara = PowerPara()
        self.dao = Dao()

    def test(self):
        self.powerpara.vol = "220v"
        self.dao.insertData(self.powerpara)
예제 #35
0
파일: server.py 프로젝트: acoulon99/garpr
    def get(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        player = dao.get_player_by_id(ObjectId(id))

        return_dict = player.get_json_dict()
        convert_object_id(return_dict)

        return return_dict
예제 #36
0
def update_possible_error_rows(learning_logic_code, plain_logic_code):
    """
    Once both the logic are extracted. Learning agent logic & plain parsing logic.
    Both are compared if there is a mismatch in the values and given manual_check column
    is marked if there is a mismatch.
    """
    dao = Dao()
    dao.update_manual_check_work(learning_logic_code, plain_logic_code)
예제 #37
0
def calculate():
    dao = Dao()
    elo = Elo(k_factor=ELO_K_FACTOR, rating_class=float, initial=DEFAULT_RATING, beta=ELO_BETA)
    calculator = PreCalculation(DEFAULT_RATING, elo)
    dataframe = dao.get_past()
    dataframe = calculator.prepare_subtype(dataframe)
    rating = calculator.replay_elo(dataframe)
    print rating
예제 #38
0
파일: server.py 프로젝트: jschnei/garpr
    def get(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        player = dao.get_player_by_id(ObjectId(id))

        return_dict = player.get_json_dict()
        convert_object_id(return_dict)

        return return_dict
예제 #39
0
    def test_init_with_invalid_region(self):
        print Dao.get_all_regions(mongo_client=self.mongo_client)
        # create a dao with an existing region
        Dao(self.region, mongo_client=self.mongo_client, new=False)

        # create a dao with a new region
        with self.assertRaises(RegionNotFoundException):
            Dao('newregion', mongo_client=self.mongo_client, new=False)
예제 #40
0
    def setUp(self):
        self.maxDiff = None

        self.player_1_id = ObjectId()
        self.player_2_id = ObjectId()
        self.player_3_id = ObjectId()
        self.player_4_id = ObjectId()
        self.player_5_id = ObjectId()
        self.player_1 = Player(name='gaR',
                               aliases=['gar', 'garr'],
                               ratings={
                                   'norcal': Rating(),
                                   'texas': Rating()
                               },
                               regions=['norcal', 'texas'],
                               id=self.player_1_id)
        self.player_2 = Player(name='sfat',
                               aliases=['sfat', 'miom | sfat'],
                               ratings={'norcal': Rating()},
                               regions=['norcal'],
                               id=self.player_2_id)
        self.player_3 = Player(name='mango',
                               aliases=['mango', 'gar'],
                               ratings={'norcal': Rating(mu=2, sigma=3)},
                               regions=['socal'],
                               id=self.player_3_id)
        self.player_4 = Player(name='garpr|gar',
                               aliases=['garpr|gar'],
                               ratings={'norcal': Rating(mu=2, sigma=3)},
                               regions=['norcal'],
                               id=self.player_4_id)

        self.players = [
            self.player_1, self.player_2, self.player_3, self.player_4
        ]

        self.user_id_1 = 'abc123'
        self.user_admin_regions_1 = ['norcal']
        self.username1 = 'Full Name'
        #    def __init__(self, id, admin_regions, username, salt, hashed_password):
        self.user_1 = User(id=self.user_id_1,
                           admin_regions=self.user_admin_regions_1,
                           username=self.username1,
                           salt='nacl',
                           hashed_password='******')

        self.users = [self.user_1]

        self.region_1 = Region(id='norcal', display_name='Norcal')
        Dao.insert_region(self.region_1,
                          self.mongo_client,
                          database_name=DATABASE_NAME)
        self.norcal_dao = Dao('norcal',
                              self.mongo_client,
                              database_name=DATABASE_NAME)

        for player in self.players:
            self.norcal_dao.insert_player(player)
예제 #41
0
    def __init__(self, conf={}):
        if any(conf) == False:
            self.conf = util.loadConfig()
            logger.setLevel(
                logging.getLevelName(self.conf['logLevel'][moduleName]))

        else:
            self.conf = conf
        self.dao = Dao(self.conf)
예제 #42
0
파일: server.py 프로젝트: acoulon99/garpr
 def put(self): 
     args = session_put_parser.parse_args() #parse args
     dao = Dao('norcal', mongo_client=mongo_client) # lol this doesn't matter, b/c we're just trying to log a user
     session_id = dao.check_creds_and_get_session_id_or_none(args['username'], args['password'])
     if not session_id:
         return 'Permission denied', 403
     resp = jsonify({"status": "connected"})
     resp.set_cookie('session_id', session_id)
     return resp
예제 #43
0
파일: server.py 프로젝트: garsh0p/garpr
 def delete(self):
     args = session_delete_parser.parse_args()
     dao = Dao(None, mongo_client=mongo_client)
     if not dao:
         return 'Dao not found', 404
     logout_success = dao.logout_user_or_none(args['session_id'])
     if not logout_success:
         return 'who is you', 404
     return ('logout success', 200,
             {'Set-Cookie': "session_id=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"})
예제 #44
0
파일: test_dao.py 프로젝트: MrMonacle/garpr
    def test_get_all_regions(self):
        # add another region
        region = Region('newregion', 'New Region')
        Dao.insert_region(region, self.mongo_client, database_name=DATABASE_NAME)

        regions = Dao.get_all_regions(self.mongo_client, database_name=DATABASE_NAME)
        self.assertEquals(len(regions), 3)
        self.assertEquals(regions[0], region)
        self.assertEquals(regions[1], self.region_1)
        self.assertEquals(regions[2], self.region_2)
예제 #45
0
파일: server.py 프로젝트: jschnei/garpr
 def delete(self):
     args = session_delete_parser.parse_args()
     dao = Dao(None, mongo_client=mongo_client)
     logout_success = dao.logout_user_or_none(args['session_id'])
     if not logout_success:
         return 'who is you', 404
     return 'logout success', 200, {
         'Set-Cookie':
         "session_id=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"
     }
    def __init__(self, conf = {}):
        if any(conf) == False:
            self.conf = util.loadConfig()
            logger.setLevel(logging.getLevelName(self.conf['logLevel'][moduleName]))
        else:
            self.conf = conf

        self.dao = Dao(self.conf)
        self.templateEnv = Environment(loader=PackageLoader('jnpr.openclos', junosTemplateLocation))
        self.templateEnv.keep_trailing_newline = True
예제 #47
0
파일: server.py 프로젝트: jschnei/garpr
 def put(self):
     args = session_put_parser.parse_args()  #parse args
     dao = Dao(None, mongo_client=mongo_client)
     session_id = dao.check_creds_and_get_session_id_or_none(
         args['username'], args['password'])
     if not session_id:
         return 'Permission denied', 403
     resp = jsonify({"status": "connected"})
     resp.set_cookie('session_id', session_id)
     return resp
예제 #48
0
파일: server.py 프로젝트: garsh0p/garpr
    def post(self, region, id):
        print "finalize tournament post"
        dao = Dao(region, mongo_client=mongo_client)
        if not dao:
            return 'Dao not found', 404
        pending_tournament = None
        try:
            pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
        except:
            return 'Invalid ObjectID', 400
        if not pending_tournament:
            return 'No pending tournament found with that id.', 400
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_regions(user, pending_tournament.regions):
            return 'Permission denied', 403

        # Make sure multiple player aliases don't map to a single player ID.
        player_ids = set()
        for mapping in pending_tournament.alias_to_id_map:
            if mapping.player_id is not None:
                if mapping.player_id in player_ids:
                    return "Player id %s is already mapped" % mapping.player_id, 400
                else:
                    player_ids.add(mapping.player_id)

        new_player_names = []
        for mapping in pending_tournament.alias_to_id_map:
            if mapping.player_id is None:
                new_player_names.append(mapping.player_alias)

        for player_name in new_player_names:
            player = M.Player.create_with_default_values(player_name, region)
            player_id = dao.insert_player(player)
            pending_tournament.set_alias_id_mapping(player_name, player_id)

        # validate players in this tournament
        for mapping in pending_tournament.alias_to_id_map:
            try:
                player_id = mapping.player_id
                # TODO: reduce queries to DB by batching
                player = dao.get_player_by_id(player_id)
                if player.merged:
                    return "Player {} has already been merged".format(player.name), 400
            except:
                return "Not all player ids are valid", 400

        try:
            dao.update_pending_tournament(pending_tournament)
            tournament = M.Tournament.from_pending_tournament(
                pending_tournament)
            tournament_id = dao.insert_tournament(tournament)
            dao.delete_pending_tournament(pending_tournament)
            return {"success": True, "tournament_id": str(tournament_id)}
        except ValueError as e:
            print e
            return 'Not all player aliases in this pending tournament have been mapped to player ids.', 400
        except:
            return 'Dao threw an error somewhere', 400
예제 #49
0
파일: server.py 프로젝트: jschnei/garpr
    def post(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)

        pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
        if not pending_tournament:
            return 'No pending tournament found with that id.', 400
        user = get_user_from_request(request, dao)
        if not user:
            return 'Permission denied', 403
        if not is_user_admin_for_regions(user, pending_tournament.regions):
            return 'Permission denied', 403

        new_player_names = []
        for mapping in pending_tournament.alias_to_id_map:
            if mapping["player_id"] == None:
                new_player_names.append(mapping["player_alias"])

        for player_name in new_player_names:
            player = Player.create_with_default_values(player_name, region)
            player_id = dao.insert_player(player)
            pending_tournament.set_alias_id_mapping(player_name, player_id)

        dao.update_pending_tournament(pending_tournament)

        try:
            tournament = Tournament.from_pending_tournament(pending_tournament)
            tournament_id = dao.insert_tournament(tournament)
            dao.delete_pending_tournament(pending_tournament)
            return {"success": True, "tournament_id": str(tournament_id)}
        except ValueError:
            return 'Not all player aliases in this pending tournament have been mapped to player ids.', 400
예제 #50
0
 def get(self):
     self.response.headers['Content-Type'] = 'application/json'
     key = self.request.get("key")
     dao = Dao()
     pontos = json.loads(dao.get_pontos_linha(key))["util"]["ida"]
     pontos_json = json.dumps([[float(ponto[0]) / 1000000, float(ponto[1]) / 1000000]
                               for ponto in pontos], separators=(',',':'))
     callback = self.request.get("callback");
     if callback:
         pontos_json = callback + "(" + pontos_json + ");"            
     self.response.out.write(pontos_json) 
예제 #51
0
def update_orders(event=None):
    """
    poll queue and update database
    """
    client = boto3.client('sqs')

    response = client.receive_message(QueueUrl=Queue.URL,
                                      AttributeNames=['All'],
                                      WaitTimeSeconds=Queue.WAIT_TIME_S,
                                      MaxNumberOfMessages=Queue.MAX_MESSAGES)

    if 'Messages' not in response:
        return

    # process messages
    messages = response['Messages']
    processed_messages = list()

    for message in messages:
        payload = json.loads(message['Body'])
        order_update = json.loads(payload['Message'])

        try:
            order_id = order_update['order_id']
            redirect_url = order_update['order_url']
            uid = order_update['uid']

            item = {
                'order_id': order_id,
                'uid': uid,
                'redirect_url': redirect_url
            }

            # overwrite items
            Dao.update_item(item)

            # append to processed list
            _processed = {
                'Id': message['MessageId'],
                'ReceiptHandle': message['ReceiptHandle']
            }

            processed_messages.append(_processed)

        except UnknownDbException as err:
            print(err)
        except Exception as err:
            # try upto 3 times and then reject
            print(err)

    #batch delete all messages
    if len(processed_messages) > 0:
        client.delete_message_batch(QueueUrl=Queue.URL,
                                    Entries=processed_messages)
예제 #52
0
    def setUp(self):
        self.maxDiff = None

        self.player_1_id = ObjectId()
        self.player_2_id = ObjectId()
        self.player_3_id = ObjectId()
        self.player_4_id = ObjectId()
        self.player_5_id = ObjectId()
        self.player_1 = Player(
                name='gaR',
                aliases=['gar', 'garr'],
                ratings={'norcal': Rating(), 'texas': Rating()},
                regions=['norcal', 'texas'],
                id=self.player_1_id)
        self.player_2 = Player(
                name='sfat',
                aliases=['sfat', 'miom | sfat'],
                ratings={'norcal': Rating()},
                regions=['norcal'],
                id=self.player_2_id)
        self.player_3 = Player(
                name='mango',
                aliases=['mango', 'gar'],
                ratings={'norcal': Rating(mu=2, sigma=3)},
                regions=['socal'],
                id=self.player_3_id)
        self.player_4 = Player(
                name='garpr|gar',
                aliases=['garpr|gar'],
                ratings={'norcal': Rating(mu=2, sigma=3)},
                regions=['norcal'],
                id=self.player_4_id)

        self.players = [self.player_1, self.player_2, self.player_3, self.player_4]

        self.user_id_1 = 'abc123'
        self.user_admin_regions_1 = ['norcal']
        self.username1 = 'Full Name'
        #    def __init__(self, id, admin_regions, username, salt, hashed_password):
        self.user_1 = User(id=self.user_id_1,
                           admin_regions=self.user_admin_regions_1,
                           username=self.username1,
                           salt='nacl',
                           hashed_password='******')

        self.users = [self.user_1]

        self.region_1 = Region(id='norcal', display_name='Norcal')
        Dao.insert_region(self.region_1, self.mongo_client, database_name=DATABASE_NAME)
        self.norcal_dao = Dao('norcal', self.mongo_client, database_name=DATABASE_NAME)

        for player in self.players:
            self.norcal_dao.insert_player(player)
예제 #53
0
파일: server.py 프로젝트: MrMonacle/garpr
    def delete(self, region, id, region_to_change):
        dao = Dao(region, mongo_client=mongo_client)
        user = get_user_from_access_token(request.headers, dao)
        if not is_user_admin_for_region(user, region_to_change):
            return 'Permission denied', 403

        tournament = dao.get_tournament_by_id(ObjectId(id))
        if region_to_change in tournament.regions:
            tournament.regions.remove(region_to_change)
            dao.update_tournament(tournament)

        return convert_tournament_to_response(dao.get_tournament_by_id(tournament.id), dao)
예제 #54
0
파일: server.py 프로젝트: acoulon99/garpr
    def get(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        response = None

        tournament = dao.get_tournament_by_id(ObjectId(id))
        if tournament is not None:
            response = convert_tournament_to_response(tournament, dao)
        else:
            pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
            response = convert_pending_tournament_to_response(pending_tournament, dao)
            
        return response
예제 #55
0
파일: server.py 프로젝트: garsh0p/garpr
 def put(self):
     args = session_put_parser.parse_args()  # parse args
     dao = Dao(None, mongo_client=mongo_client)
     if not dao:
         return 'Dao not found', 404
     session_id = dao.check_creds_and_get_session_id_or_none(
         args['username'], args['password'])
     if not session_id:
         return 'Permission denied', 403
     resp = jsonify({"status": "connected"})
     resp.set_cookie('session_id', session_id)
     return resp
예제 #56
0
    def setUp(self):
        self.maxDiff = None
        self.mongo_client = MongoClient()

        self.player_1_id = ObjectId()
        self.player_2_id = ObjectId()
        self.player_3_id = ObjectId()
        self.player_4_id = ObjectId()
        self.player_5_id = ObjectId()
        self.player_1 = Player(
                'gaR', 
                ['gar', 'garr'], 
                {'norcal': TrueskillRating(), 'texas': TrueskillRating()}, 
                ['norcal', 'texas'], 
                id=self.player_1_id)
        self.player_2 = Player(
                'sfat', 
                ['sfat', 'miom | sfat'], 
                {'norcal': TrueskillRating()}, 
                ['norcal'], 
                id=self.player_2_id)
        self.player_3 = Player(
                'mango', 
                ['mango', 'gar'], 
                {'norcal': TrueskillRating(trueskill_rating=trueskill.Rating(mu=2, sigma=3))}, 
                ['socal'], 
                id=self.player_3_id)
        self.player_4 = Player(
                'garpr|gar', 
                ['garpr|gar'], 
                {'norcal': TrueskillRating(trueskill_rating=trueskill.Rating(mu=2, sigma=3))}, 
                ['norcal'], 
                id=self.player_4_id)

        self.players = [self.player_1, self.player_2, self.player_3, self.player_4]

        self.user_id_1 = 'abc123'
        self.user_full_name_1 = 'Full Name'
        self.user_admin_regions_1 = ['norcal']
        self.user_1 = User(self.user_id_1, self.user_admin_regions_1, full_name=self.user_full_name_1)

        self.users = [self.user_1]

        self.region_1 = Region('norcal', 'Norcal')
        Dao.insert_region(self.region_1, self.mongo_client, database_name=DATABASE_NAME)
        self.norcal_dao = Dao('norcal', self.mongo_client, database_name=DATABASE_NAME)

        for player in self.players:
            self.norcal_dao.insert_player(player)

        for user in self.users:
            self.norcal_dao.insert_user(user)
예제 #57
0
파일: server.py 프로젝트: garsh0p/garpr
    def get(self, region, id):
        dao = Dao(region, mongo_client=mongo_client)
        if not dao:
            return 'Dao not found', 404
        player = None
        try:
            player = dao.get_player_by_id(ObjectId(id))
        except:
            return 'Invalid ObjectID', 400
        if not player:
            return 'Player not found', 404

        return player.dump(context='web')
예제 #58
0
    def setUp(self):
        self.mongo_client_patcher = patch('server.mongo_client', new=mongomock.MongoClient())
        self.mongo_client = self.mongo_client_patcher.start()

        server.app.config['TESTING'] = True
        self.app = server.app.test_client()

        self.norcal_dao = Dao(NORCAL_REGION_NAME, mongo_client=self.mongo_client, new=True)
        self.texas_dao = Dao(TEXAS_REGION_NAME, mongo_client=self.mongo_client, new=True)

        self._import_files()
        rankings.generate_ranking(self.norcal_dao)
        rankings.generate_ranking(self.texas_dao)