def post(self): """Post position""" # properties = ["id_", "created_at", "title", "location", "type_", "description", # "how_to_apply", "company", "company_url", "company_logo"] parser = reqparse.RequestParser() args = parser.parse_args() position_db = Position ( title = request.json['title'], location = request.json['location'], type_ = request.json['type_'], description = request.json['description'], how_to_apply = request.json['how_to_apply'], company = request.json['company'], company_url = request.json['company_url'], company_logo = request.json['company_logo'] ) position_db.put() position = position_db.to_dict(include=Position.get_public_properties()) # positions_db = [u.to_dict(include=Position.get_public_properties()) for u in positions_db] # g.model_db.put() return position, 201
def test_move_rovers_return_value(self): expectedResult = [ Rover(position=Position(1, 3), orientation=Orientation.NORTH), Rover(position=Position(5, 1), orientation=Orientation.EAST) ] result = self.controller.move_rovers(instructions=self.instructions) self.assertEqual(result, expectedResult)
def test_calculate_next_position_is_called_with_params(self): with patch.object(target=Controller, attribute='clean_data') as mocked_clean_data: rover = self.northRover cleanInstructions = [Position(4, 4), [rover, 'M']] mocked_clean_data.return_value = cleanInstructions with patch.object(target=Controller, attribute='calculate_next_position' ) as mocked_calculate_next_position: mocked_calculate_next_position.return_value = Position(5, 4) self.controller.move_rovers(instructions=self.instructions) mocked_calculate_next_position.assert_called_once_with( rover=rover)
def get(self): parser = reqparse.RequestParser() parser.add_argument('cursor', type=ArgumentValidator.create('cursor')) args = parser.parse_args() positions_future = Position.query() \ .order(-Position.created) \ .fetch_page_async(10, start_cursor=args.cursor) total_count_future = Position.query().count_async(keys_only=True) positions, next_cursor, more = positions_future.get_result() positions = [u.to_dict(include=Position.get_public_properties()) for u in positions] return make_list_response(positions, next_cursor, more, total_count_future.get_result())
def clean_data(self, instructions): # We check that the file contains at least 3 lines, otherwise it means that it is incomplete if len(instructions) < 2: raise DataErrorException(message='File in incomplete') # We create a list which will contain the top right position as the first element, and then each other elements will a list of 2 elements: the initial position and orientation of each rover cleanedInstructions = [] topSquareData = instructions[0].strip().split(' ') # We check that the first line is composed of 2 positive integers separated by a space. If so, we create the top square position and save it in the cleaned instructions list. if len(topSquareData) == 2 and topSquareData[0].isdigit( ) and topSquareData[1].isdigit(): topSquare = Position(int(topSquareData[0]), int(topSquareData[1])) cleanedInstructions.append(topSquare) # We look for every two lines, which correspond to each rover initial position and commands. # For the first line, we check that the initial position is composed of 2 positive integers and a letter among N, E, S or W, separated by a space. # If so, we create a Rover containing its original position and orientation for lineNumber in range(1, len(instructions), 2): roverData = instructions[lineNumber].strip().split(' ') if len(roverData) == 3 and roverData[0].isdigit( ) and roverData[1].isdigit( ) and roverData[2] in Orientation.ALL: rover = Rover( Position(int(roverData[0]), int(roverData[1])), roverData[2]) # For the second line, we check that the string is composed only of L, M or R. # If so, we save a list containing the initial position of the rover and its commands to be executed. try: commands = instructions[lineNumber + 1].strip() except: raise DataErrorException( message='There is no command for this rover') if set(commands).issubset(Command.ALL): cleanedInstructions.append([rover, commands]) else: # We raise an error specifying that there is a mistake in the commands raise DataErrorException( message= f'Rover n°{int((lineNumber + 1) / 2)} commands contain error, please correct it in the file to proceed' ) else: # We raise an error specifying that there is a mistake in the position raise DataErrorException( message= f'Rover n°{int((lineNumber + 1) / 2)} initial position contains error, please correct it in the file to proceed' ) # We return the cleaned instructions list. return cleanedInstructions # We raise an error specifying that there is a mistake in the top right position raise DataErrorException( message= 'The upper-right coordinates of the plateau contain error, please correct the file to proceed' )
def test_next_position_is_correct(self): expectedResult = [ Position(3, 4), Position(4, 3), Position(3, 2), Position(2, 3) ] result = [ self.controller.calculate_next_position(rover=self.northRover), self.controller.calculate_next_position(rover=self.eastRover), self.controller.calculate_next_position(rover=self.southRover), self.controller.calculate_next_position(rover=self.westRover) ] self.assertEqual(result, expectedResult)
def decodeMsg(str, left, IDs, pointmap): tmpstr = left + str tmpIds = [] # pointmap = {} if tmpstr.startswith('%'): fields = tmpstr[1:-1].split('%') idstr = fields[0] tmpstr = fields[1] ids = idstr.split(',') for uid in ids: tmpIds.append(uid) fields = tmpstr[1:].split('#') left = fields[len(fields) - 1] for fi in range(len(fields) - 1): field = fields[fi] lines = field.split(';') ts = lines[0] if ts not in pointmap: pointmap[ts] = [] points = [] for i in range(1, len(lines)): linefields = lines[i].split(',') # print(fields) uid = linefields[0] x = float(linefields[1]) / 1000 y = float(linefields[2]) / 1000 p = Position(uid, x, y, 0.0, 0.0, 0.0, 0.0) points.append(p) pointmap[ts] = points if len(tmpIds) == 0: tmpIds = IDs return tmpIds, pointmap, left
def search_positions(): user_id = session.get('current_user') user = User.get_user_by_user_id(user_id) position = Position.get_position_by_user_id(user_id) return render_template('salarysearch.html', user=user, position=position)
def test_next_position_is_available(self): nextPosition = Position(2, 3) self.assertTrue( self.controller.check_position_available( position=nextPosition, occupiedPositions=self.occupiedPositions, topSquare=self.topSquare))
def post(self): position_to_insert = request.get_json() print position_to_insert position = Position( created_at = str(datetime.now()), title = position_to_insert["title"], location = position_to_insert["location"], type = position_to_insert["type"], description = position_to_insert["description"], how_to_apply = position_to_insert["how_to_apply"], company = position_to_insert["company"], company_url = position_to_insert["company_url"], company_logo = position_to_insert["company_logo"], ) position.put() return position.to_json(), 201
def test_next_position_is_outside(self): nextPosition = Position(7, 1) self.assertFalse( self.controller.check_position_available( position=nextPosition, occupiedPositions=self.occupiedPositions, topSquare=self.topSquare))
def post(self): parser = reqparse.RequestParser() parser.add_argument('created_at') parser.add_argument('title') parser.add_argument('location') parser.add_argument('type_') parser.add_argument('description') parser.add_argument('how_to_apply') parser.add_argument('company') parser.add_argument('company_url') parser.add_argument('company_logo') parser.add_argument('url') args = parser.parse_args() position_db = model.Position( created_at=args.created_at, title=args.title, location=args.location, type_=args.type_, description=args.description, how_to_apply=args.how_to_apply, company=args.company, company_url=args.company_url, company_logo=args.company_logo, url=args.url ) position_db.put() return position_db.to_dict(include=Position.get_public_properties()), 201
def get(self): parser = reqparse.RequestParser() parser.add_argument('cursor', type=ArgumentValidator.create('cursor')) parser.add_argument('page') parser.add_argument('keyword') parser.add_argument('location') args = parser.parse_args() keyw = args.get('keyword') loc = args.get('location') page = args.get('page') if not keyw: keyw = "" if not loc: loc = "" if not page: page=0 else: page=int(page) positions_future = Position.query() \ .order(-Position.created) \ .fetch_page_async(10000, start_cursor=args.get('cursor')) total_count_future = Position.query().count_async(keys_only=True) positions, next_cursor, more = positions_future.get_result() positions = [p.to_dict(include=Position.get_public_properties()) for p in positions] pos = [] pos = [elem for elem in positions if (elem["title"].find(keyw) != -1 or elem["description"].find(keyw) != -1) and elem["location"].find(loc) != -1] ipage=10 until=((page+1)*ipage) if until > len(pos): until=len(pos) npos = pos[page*ipage:until] pages=math.ceil(len(pos)/float(ipage)) # for x in range(0,len(positions)): # if positions[x]["title"].find(keyw) != -1: # pos.append(positions[x]) return make_new_list_response(npos, pages, len(npos), len(pos), page*ipage)
def get(self): parser = reqparse.RequestParser() parser.add_argument('cursor', type=ArgumentValidator.create('cursor')) parser.add_argument('description') parser.add_argument('location') args = parser.parse_args() positions_future = Position.query() \ .order(-Position.created) \ .fetch_page_async(10, start_cursor=args.cursor) total_count_future = Position.query().count_async(keys_only=True) positions, next_cursor, more = positions_future.get_result() positions = [p.to_json() for p in positions] positions = [p for p in positions if args.description.lower() in p["description"].lower()] positions = [p for p in positions if args.location.lower() in p["location"].lower()] return make_list_response(positions, next_cursor, more, total_count_future.get_result())
def calculate_next_position(self, rover): # By knowing the current position and orientation of the rover, we increase or decrease of 1 the abcissa or the ordinate of the position, depending of the orientation and we return the new position. initialPosition = rover.position orientation = rover.orientation if orientation == Orientation.NORTH: nextPosition = Position(initialPosition.abscissa, initialPosition.ordinate + 1) elif orientation == Orientation.EAST: nextPosition = Position(initialPosition.abscissa + 1, initialPosition.ordinate) elif orientation == Orientation.SOUTH: nextPosition = Position(initialPosition.abscissa, initialPosition.ordinate - 1) elif orientation == Orientation.WEST: nextPosition = Position(initialPosition.abscissa - 1, initialPosition.ordinate) return nextPosition
def test_data_is_correctly_cleaned(self): instructions = [ '5 5\n', '1 2 N\n', 'LMLMLMLMM\n', '3 3 E\n', 'MMRMMRMRRM\n' ] expectedResult = [ Position(5, 5), [ Rover(position=Position(1, 2), orientation=Orientation.NORTH), 'LMLMLMLMM' ], [ Rover(position=Position(3, 3), orientation=Orientation.EAST), 'MMRMMRMRRM' ] ] result = self.controller.clean_data(instructions=instructions) self.assertEqual(result, expectedResult)
def setUp(self): self.controller = Controller() self.position = Position(3, 3) self.northRover = Rover(position=self.position, orientation=Orientation.NORTH) self.eastRover = Rover(position=self.position, orientation=Orientation.EAST) self.southRover = Rover(position=self.position, orientation=Orientation.SOUTH) self.westRover = Rover(position=self.position, orientation=Orientation.WEST)
def process_user_info(): user_id = session['current_user'] first_name = request.form.get('first_name') last_name = request.form.get('last_name') headline = request.form.get('headline') location = request.form.get('form') gender = request.form.get('gender') industry = request.form.get('industry') salary = int(request.form.get('salary')) company = request.form.get('company') title = request.form.get('title') start_date_month = request.form.get('start_date_month') start_date_year = request.form.get('start_date_year') user = User.get_user_by_user_id(user_id) user.update_user_profile(first_name=first_name, last_name=last_name, headline=headline, location=location, gender=gender, industry=industry) position = Position.get_position_by_user_id(user_id) if position: position.update_position(company=company, title=title, start_date_year=start_date_year, start_date_month=start_date_month, salary=salary) else: Position.create(user_id=user_id, company=company, title=title, start_date_year=start_date_year, start_date_month=start_date_month, salary=salary) flash("Your profile has been updated") return render_template('salarysearch.html')
def dashboard(): """renders the dashboard template""" user_id = session['current_user'] first_name = request.form.get('first_name') last_name = request.form.get('last_name') headline = request.form.get('headline') location = request.form.get('form') industry = request.form.get('industry') company = request.form.get('company') title = request.form.get('title') start_date_month = request.form.get('start_date_month') start_date_year = request.form.get('start_date_year') user = User.get_user_by_user_id(user_id) user.update_user_profile(first_name=first_name, last_name=last_name, headline=headline, location=location, industry=industry) position = Position.get_position_by_user_id(user_id) if position: position.update_position( company=company, title=title, start_date_year=start_date_year, start_date_month=start_date_month, ) else: Position.create( user_id=user_id, company=company, title=title, start_date_year=start_date_year, start_date_month=start_date_month, ) return render_template('dashboard.html')
def test_calculate_next_position_is_called_with_params(self): with patch.object(target=Controller, attribute='clean_data') as mocked_clean_data: rover = self.northRover cleanInstructions = [Position(4, 4), [rover, 'LR']] mocked_clean_data.return_value = cleanInstructions with patch.object(target=Controller, attribute='rotate_rover') as mocked_rotate_rover: calls = [ call(rover=rover, command='L'), call(rover=rover, command='R') ] self.controller.move_rovers(instructions=self.instructions) mocked_rotate_rover.assert_has_calls(calls=calls)
def put(self, id): position_to_insert = request.get_json() position = Position.get_by_id(id) position.title = position_to_insert["title"] position.location = position_to_insert["location"] position.type = position_to_insert["type"] position.description = position_to_insert["description"] position.how_to_apply = position_to_insert["how_to_apply"] position.company = position_to_insert["company"] position.company_url = position_to_insert["company_url"] position.company_logo = position_to_insert["company_logo"] position.url = position_to_insert["url"] position.put() return position.to_json()
def readOriginFile(filepath): pointmatrix = {} IDs = [] csv_data = csv.reader(open(filepath, 'r'), delimiter=',') for row in csv_data: ts = row[0] if ts not in pointmatrix: pointmatrix[ts] = [] uid = row[1] if uid not in IDs: IDs.append(uid) p = Position(uid, float(row[2]) / 1000, float(row[3]) / 1000, float(row[4]) / 1000, float(row[5]) / 1000, row[6], row[7]) pointmatrix[ts].append(p) return pointmatrix,IDs
def dePositionMsg(str): tmpstr = str[1:-1] lines = tmpstr.split(';') ts = lines[0] points = [] for i in range(1, len(lines)): fields = lines[i].split(',') # print(fields) uid = fields[0] x = float(fields[1]) / 1000 y = float(fields[2]) / 1000 p = Position(uid, x, y, 0.0, 0.0, 0.0, 0.0) # p = Position(fields[0], float(fields[1])/1000, float(fields[2])/1000, float(fields[3])/1000, float(fields[4])/1000, # fields[5], fields[6]) points.append(p) return ts, points
def _get_position(self, path): ret_code = 0 ret_value = [] error_msg = '' try: f = open(path, 'r') for line in f: if len(line) < 10: continue raw_data = json.loads(line.strip()) ret_value.append(Position(raw_data)) f.close() except IOError: ret_code = 1 error_msg = traceback.format_exc() except: ret_code = 2 error_msg = traceback.format_exc() return (ret_code, ret_value, error_msg, self.local_log_path)
def make_positions(): # LOL that's what she said """ Positions """ print 'Making Positions...' # Since I like to run this file over and over again: Position.query.delete() position_dict = {'01-SM': 'Store Manager', '02-AM': 'Assistant Manager', '03-SS': 'Sales Associate', '10-DM': 'District Manager', '99-HQ': 'Corporate Admin'} for position in position_dict: pos_id = position title = position_dict[position] position_obj = Position(pos_id=pos_id, title=title) db.session.add(position_obj) db.session.commit()
def get(self, key): return g.model_db.to_dict(include=Position.get_public_properties())
row[6], row[7]) pointmatrix[ts].append(p) return pointmatrix,IDs "读取原始数据" filepath = PATH + 'data\\process_ATC_1_1200_1.csv' pointmatrix = {} csv_data = csv.reader(open(filepath,'r'), delimiter=',') for row in csv_data: ts = row[0] if ts not in pointmatrix: pointmatrix[ts] = [] p = Position(row[1], float(row[2])/1000, float(row[3])/1000, float(row[4])/1000, float(row[5])/1000, row[6], row[7]) pointmatrix[ts].append(p) "获得参与人员" IDs = [] groupfile = open(PATH+'data\\group.txt','r') lines = groupfile.readlines() for line in lines: fields = line.split(' ') for i in range(len(fields)): pi = int(fields[i]) if pi not in IDs: IDs.append(str(pi)) "初始值设置" act_flocks = []
def get(self, id): position = Position.get_by_id(id) if position is None: return {}, 404 return position.to_json()
def setUp(self): super().setUp() self.occupiedPositions = [self.position] self.topSquare = Position(4, 4)
def sync_position(position_dict: Dict, position: model.Position = None) -> model.Position: if not position: position = model.Position() position.future = position_dict['future_symbol'] position.future_price = position_dict['future_price'] position.spot = position_dict['spot_symbol'] position.spot_price = position_dict['spot_price'] position.direct_ratio = position_dict['direct_ratio'] position.hours = position_dict['hours'] position.hour_ratio = position_dict['hour_ratio'] position.days = position_dict['days'] position.year_ratio = position_dict['year_ratio'] position.contract_size = position_dict['contract_size'] position.contract_qty = position_dict['contract_qty'] position.buy_per_contract = position_dict['buy_per_contract'] position.tick_size = position_dict['tick_size'] position.base_asset = position_dict['base_asset'] position.state = position_dict['state'] return position
def delete(self, id): position = Position.get_by_id(id) position.key.delete() return "", 204
def authorized(): resp = linkedin.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description']) session['linkedin_token'] = (resp['access_token'], '') me = linkedin.get( 'people/~:(id,first-name,last-name,headline,picture-url,positions,location,industry,specialties,public-profile-url)?format=json' ) user_data = me.data print "user data: ", user_data first_name = user_data.get('firstName', None) last_name = user_data.get('lastName', None) id = user_data.get('id', None) headline = user_data.get('headline', None) industry = user_data.get('industry', None) location = user_data.get('location', None) profile_pic = user_data.get('pictureUrl', None) location_name = None if location: location_name = location['name'] check_user = User.get_user_by_linkedin_id( id) #check to see if the user exists already print check_user, "this is check_user" if not check_user: user = User.create(first_name=first_name, last_name=last_name, linkedin_id=id, headline=headline, industry=industry, location=location_name, profile_pic=profile_pic) else: user = check_user print user, "this is the user" user_id = user.user_id session['current_user'] = user_id positions = user_data.get('positions', None) if positions and positions.get('values', None): position_info = positions.get('values')[0] position_company = None position_start_date_month = None position_start_date_year = None position_title = None if position_info.get('company', None): position_company = position_info.get('company', None)['name'] if position_info.get('startDate', None): position_start_date_month = position_info['startDate']['month'] position_start_date_year = position_info['startDate']['year'] if position_info.get('title', None): position_title = position_info['title'] position = Position.create(user_id=user_id, company=position_company, start_date_month=position_start_date_month, start_date_year=position_start_date_year, title=position_title) else: position = None # return render_template('test.html', user=user, position=position) return redirect(url_for('search_positions'))