class HandleFoodTrucks(xml.sax.handler.ContentHandler): curr_name = "" curr_description = "" curr_position = Position(lat=0,lon=0) curr_id = 0 buff = "" def startElement(self, name, attrs): self.buff = "" if name == 'Placemark': self.curr_id = attrs.get("id") def characters(self, ch): self.buff = self.buff + ch ## YK def endElement(self, name): if name == 'Placemark': truck = FoodTruck(key=self.curr_id, name=self.curr_name, foodType=self.curr_description, position=self.curr_position) truck.save() print "saved: "+ str(truck); self.curr_name = "" self.curr_description = "" self.curr_position = Position(lat=0,lon=0) self.curr_id = 0 self.buff = "" elif name == 'name': self.curr_name = self.buff elif name == 'description': self.curr_description = self.buff elif name == 'coordinates': coords = self.buff.split(",") print "float(coords[0])" + str(coords[0]) + "float(coords[1])" + str(coords[1]) self.curr_position = Position(lat=float(coords[1]), lon=float(coords[0])) self.curr_position.save() self.buff = ""
def load(self, path): pgn = open(path) offsets = [] for offset, headers in chess.pgn.scan_headers(pgn): offsets.append(offset) for offset in offsets: pgn.seek(offset) game = chess.pgn.read_game(pgn) exporter = chess.pgn.StringExporter() pgn_string = game.accept(exporter) game_headers = self._get_headers_columns(game.headers) game_id = [x for x in (Game.insert(pgn=pgn_string, **game_headers).returning(Game.id)).execute()][0][0] node = game while not node.is_end(): next_node = node.variations[0] fen = node.board().fen() hash_key = hashlib.md5(fen.encode()).hexdigest() position_result = (Position.select().where(Position.hash == hash_key).execute()) if not position_result: position_id = [x for x in (Position.insert(hash=hash_key).returning(Position.id)).execute()][0][0] else: position_id = position_result[0].id PositionGame.insert(position_id=position_id, game_id=game_id).execute() node = next_node pgn.close()
def test_total_expected_earnings(self): position_1 = Position(stock=Stock('ticker', 'name', 20, 30), quantity=2) position_2 = Position(stock=Stock('ticker', 'name', 20, 40), quantity=2) portfolio = Portfolio(position_1, position_2) self.assertEqual(Decimal('1.5'), portfolio.total_expected_earnings)
def new_game(self, request): """This function creates a new game. Input: Two Usernames; Only The first is required, if the second is not given, the first player will be playing with an Automate (Computer)""" player = utils.get_by_username(request.player) if not request.opponent: opponent = Player.query(Player.username == "computer").get() else: opponent = utils.get_by_username(request.opponent) newgame = Game(player=player.key, opponent=opponent.key) newgame.put() # initialize players position Position(game=newgame.key, player=player.key, position=0).put() Position(game=newgame.key, player=opponent.key, position=0).put() # update score Score(game=newgame.key, player=player.key, score=0).put() Score(game=newgame.key, player=opponent.key, score=0).put() return NewGameForm(player=player.username, opponent=opponent.username, urlsafekey=newgame.key.urlsafe())
class TestOptionPos(TestCase): def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_options = test_raw_data['Options'] def tearDown(self): del self.raw_options def test_format_saves(self): ids = [] for raw_option in self.raw_options: # create new option position object op = OptionPos() # save into db op.save_raw_data(position=self.position, raw_option=raw_option) # get id ids.append(op.id) print 'Inserted IDs: %s\n' % ids print 'option row count in db: %d' % len(Option.objects.all()) print 'option position row count in db: %d\n' % len(OptionPos.objects.all()) print 'option rows:\n%s\n%s\n' % \ (Option.objects.get(id=1), Option.objects.get(id=2)) print 'option position rows:\n%s\n%s\n' % \ (OptionPos.objects.get(id=1), OptionPos.objects.get(id=2))
def test_save_raw_data(self): position = Position(symbol=test_symbol, company=test_company, date=test_date) position.save() print 'position row count in db: %d\n' % len(Position.objects.all()) self.assertEqual(len(Position.objects.all()), 1) print 'Position in db:' print Position.objects.all()
def post(self): title = self.request.get('title') position_query = Position.query(Position.title == title) positions = position_query.fetch() if (len(positions) > 0): self.response.write(False) else: new_position = Position(title=title) new_position.put() self.response.write(True)
def summary(): global symbols user = request.args.get('user') if user: if not current_user.is_admin(): return 'WTF?' if user: user = User.query_one({'_id': user}) else: user = current_user accounts = list(Account.query({'user_id': user._id})) ps = [p for p in Position.query({'user_id': user._id}, sort=[('date', 1)])] os = [o for o in Order.query({'user_id': user._id}, sort=[('date', 1)])] dates = list(reversed([p.date for p in ps])) total_profit = 0 for o in os: for oo in o.order_list: if oo.symbol in symbols: total_profit += oo.profit today = request.args.get('today') if today: today = datetime.strptime(today, '%Y-%m-%d %H:%M:%S') else: d = datetime.utcnow() + timedelta(hours=8) if d.hour == 9 and 20 <= d.minute <= 40: return '跌零时间段, 不可查看' if d.hour < 9: d -= timedelta(days=1) today = d.replace(hour=0, minute=0, second=0, microsecond=0) try: position_list = Position.query_one({ 'user_id': user._id, 'date': today }).position_list status_list = Status.query_one({ 'user_id': user._id, 'date': today }).status_list order_list = Order.query_one({ 'user_id': user._id, 'date': today }).order_list except: pass locals()['symbols'] = symbols return render_template('summary.html', **locals())
def summary(): global symbols user = request.args.get('user') if user: if not current_user.is_admin(): return 'WTF?' if user: user = User.query_one({'_id': user}) else: user = current_user accounts = list(Account.query({'user_id': user._id})) ps = [p for p in Position.query({'user_id': user._id}, sort=[('date', 1)])] os = [o for o in Order.query({'user_id': user._id}, sort=[('date', 1)])] dates = list(reversed([p.date for p in ps])) total_profit = 0 for o in os: for oo in o.order_list: if oo.symbol in symbols: total_profit += oo.profit today = request.args.get('today') if today: today = datetime.strptime(today, '%Y-%m-%d %H:%M:%S') else: d = datetime.utcnow() + timedelta(hours=8) if d.hour == 9 and 20 <= d.minute <= 40: return '跌零时间段, 不可查看' if d.hour < 9: d -= timedelta(days=1) today = d.replace(hour=0, minute=0, second=0, microsecond=0) try: position_list = Position.query_one({'user_id': user._id, 'date': today}).position_list status_list = Status.query_one({'user_id': user._id, 'date': today}).status_list order_list = Order.query_one({'user_id': user._id, 'date': today}).order_list except: pass locals()['symbols'] = symbols return render_template('summary.html', **locals())
def scrape_single_position_job(self, job: Job, job_element: WebElement): summary_element = self.find_summary_element(job_element, 'pv-entity__summary-info') job.company.name = self.canonize_company_name( summary_element.find_element_by_class_name( 'pv-entity__secondary-title').text) position = Position() position.title = summary_element.find_element_by_class_name( 't-16').text.strip() position.date_range = self.scrape_date_range(job_element) position.location = self.scrape_location(job_element) job.add_position(position)
def save_data_to_db(rssi_file, position_file, session_file): rssi_data = list(csv.reader(open(rssi_file, 'r'))) position_data = list(csv.reader(open(position_file, 'r'))) with open(session_file, 'r') as f: session_name, session_date = [x.rstrip() for x in f] with database.atomic(): sess = CaptureSession() sess.name = session_name sess.date = session_date sess.save() for row in rssi_data[1:]: rssi = RSSIValue() rssi.beacon_uuid = row[0] rssi.beacon_major = int(row[1]) rssi.beacon_minor = int(row[2]) rssi.rssi = int(row[3]) rssi.timestamp = int(row[4]) rssi.capture_session = sess rssi.save() for row in position_data[1:]: pos = Position() pos.x = float(row[0]) pos.y = float(row[1]) pos.timestamp = int(row[2]) pos.capture_session = sess pos.save()
def portfolio(): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE).execute() values = result.get('values', []) positions = [ Position(symbol=row[0], quantity=float(scrub(row[2]))) for row in values if len(row) > 1 ] return Portfolio(positions)
def from_db_object(self, db_object): return Position(mac=Mac(db_object['mac']), location=Location(x=db_object['location']['x'], y=db_object['location']['y'], z=db_object['location']['z']), created_at=Time(int(db_object['created_at'])), _id=db_object['_id'])
def new_position(): if "user_id" not in session: return redirect("/") if session["user_id"]["role"] != "org": return redirect("/logout") req_langs = request.form.getlist("pos_lang") for i in range(0, len(req_langs)): req_langs[i] = int(req_langs[i]) print("languages", req_langs) is_valid = True if not len(request.form["title"]) >= 2: is_valid = False flash("You Job Title must be at least 3 characters long") if not request.form["description"]: is_valid = False flash("You cannot post an empty job description.") if len(request.form["description"]) > 1000: flash("Job Description must be under 1000 characters.") is_valid = False if is_valid: new_position = Position(name=request.form["title"], description=request.form["description"], owner_id=session["user_id"]["id"]) db.session.add(new_position) db.session.commit() print(new_position.position_id) cur_pos = Position.query.get(new_position.position_id) for i in range(0, len(req_langs)): lang_to_add = Language.query.get(req_langs[i]) cur_pos.langs.append(lang_to_add) db.session.commit() return redirect("/org_landing") return redirect("/org_add_pos")
def post(self): if (self.request.get('username')): user = self.request.get('username') else: user = self.session['username'] employee_query = Employee.query(Employee.login_name == user) employee = employee_query.fetch()[0] timesheet_query = Timesheet.query(Timesheet.time_period == self.request.get('time_period'), Timesheet.worked_by == employee.key) timesheet = timesheet_query.fetch() currentPositions = [] for sheet in timesheet: currentPositions.append(sheet.position) for position in employee.positions: if position not in currentPositions: new_timesheet = Timesheet(worked_by=employee.key, position=position, time_period=self.request.get('time_period')) new_timesheet.put() timesheet.append(new_timesheet) jsonSheet = {'sheets': []} for t in timesheet: obj = { 'worked_by': Employee.query(Employee.key == t.worked_by).fetch()[0].login_name, 'position': Position.query(Position.key == t.position).fetch()[0].title, 'hours_worked': t.hours_worked, 'time_period': t.time_period, 'is_submitted': t.is_submitted, 'is_approved': t.is_approved } jsonSheet['sheets'].append(obj) self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(jsonSheet))
def add_position(): if request.method == "POST": position = Position(rank=request.form['rank'], title=request.form['title']) db.session.add(position) db.session.commit() return render_template('add_position.html')
def get_game_history(self, request): ''' returns the usual GameForm, plus all related positions and all moves ''' game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: return endpoints.NotFoundException("Game not found") game_key = game.key game = game.to_form("") ships = Ship.query(ancestor=game_key).order(-Ship.created).fetch() ship_forms = [] for s in ships: position_forms = [] positions = Position.query(ancestor=s.key).fetch() for p in positions: position_forms.append(XYMessage(x=p.x, y=p.y, hit=p.hit)) ship_forms.append( ShipMessage(player=s.player.get().name, ship=s.ship, created_date=s.created, positions=position_forms)) moves = Move.query(ancestor=game_key).order(-Move.created).fetch() move_forms = [] for m in moves: move_forms.append( MoveMessage(player=m.player.get().name, x=m.x, y=m.y, created_date=m.created)) form = FullGameInfo(game=game, ships=ship_forms, moves=move_forms) return form
def parse_portfolio_text(prtf_text): ''' Parse reconciliation text file which contains alternating position lists (portfolio states) and daily transaction lists. Returns dicts of positions, transactions keyed by day index where the value is the position or transaction list from that day ''' sections = prtf_text.split('\n\n') data = [s.strip().split('\n') for s in sections] header_pattern = re.compile(r'D(\d+)-(POS|TRN)') positions = {} transactions = {} for section in data: header_str = section[0].strip() day_idx, input_type = header_pattern.search(header_str).groups() day_idx = int(day_idx) if input_type == 'POS': positions[day_idx] = [ Position.from_text(s.strip()) for s in section[1:] ] elif input_type == 'TRN': transactions[day_idx] = [ Transaction.from_text(s.strip()) for s in section[1:] ] return positions, transactions
def insert(engine): fake = Faker('ru_RU') Session = sessionmaker(bind=engine) session = Session() for i in range(CANDIDATE_NUMBER): session.add( Candidate(id=i, fio=fake.name(), gender=random.choice(list(GenderEnum)), birth=fake.date_this_decade(), deputat=fake.pybool())) for i in range(POSITION_NUMBER): session.add(Position(id=i, name=fake.job())) session.add( PositionDetails(id=i, staff_cat=random.choice(list(StaffCatEnum)), salary=fake.pyint(), position_id=i)) for i in range(CANDIDATE_NUMBER * 2): session.add( Employee(id=i, tab_num=fake.isbn10(), candidate_id=(fake.pyint() % CANDIDATE_NUMBER), position_id=(fake.pyint() % POSITION_NUMBER))) session.commit()
def getTable(season, gamesPlayed): """Creates a table of team positions after all teams have played some number of games.""" matchDict, teamDict = readMatchData(season) positionDict = {} for team in teamDict.values(): positionDict[team] = Position(gamesPlayed, team, matchDict) for team in sorted(positionDict, key=positionDict.get, reverse=True): print(team)
def windows_save(request, house_id): Window.objects.filter(floor=int(request.POST['floor_id'])).delete(); s = house_id for i in range(int(request.POST['n'])): f = Window(); center = Position() center.x = request.POST['window_center_x' + str(i)] center.y = request.POST['window_center_y' + str(i)] center.save() f.center = center f.width = request.POST['window_width' + str(i)] f.orientation = request.POST['window_orientation' + str(i)] f.type = request.POST['window_type' + str(i)] f.height = request.POST['window_height' + str(i)] f.floor=Floor.objects.get(pk=int(request.POST['floor_id'])) f.save() return HttpResponse(s)
def super_triangle(poslist): xmin = MAX_INTEGER ymin = MAX_INTEGER xmax = None ymax = None for pos in poslist: if pos.x < xmin: xmin = pos.x if pos.x > xmax: xmax = pos.x if pos.y < ymin: ymin = pos.y if pos.y > ymax: ymax = pos.y o = Position.position(xmin, ymin) A = Position.position(xmin, ymax) B = Position.position(xmax, ymax) C = Position.position(xmax, ymin) D = Position.position((xmax - xmin) / 2, ymax) DO = vector(D, o) DC = vector(D, C) AD_length = abs(D.x - A.x) E = Position.position(o.x - AD_length, o.y) F = Position.position(C.x + AD_length, o.y) M_y = (D.y - o.y) * AD_length
def get_active_position(self): """ Get all of the active position associated with API_KEY - Requires authentication. @return Array <models.Position> """ endpoint = "auth/r/positions" raw_positions = self.post(endpoint) return [Position.from_raw_rest_position(rp) for rp in raw_positions]
def extract_position_of_item(item, data_row_dict): p_x = data_row_dict[item.name + '_p_x'] p_y = data_row_dict[item.name + '_p_y'] p_z = data_row_dict[item.name + '_p_z'] r_x = data_row_dict[item.name + '_r_x'] r_y = data_row_dict[item.name + '_r_y'] r_z = data_row_dict[item.name + '_r_z'] r_w = data_row_dict[item.name + '_r_w'] return Position(p_x, p_y, p_z, r_x, r_y, r_z, r_w)
def setUpClass(cls): print("Setting up") conn = mongoengine.connect(db=DB_NAME, host=DB_HOST) for n in range(1, 11): invoice = Invoice(x=n, invoice_number=2) position = Position(**POSITION).save() #invoice.positions = [InvoiceItem(position_id=str(position.id))] invoice.positions = [InvoiceItem(position=position)] invoice.save()
def handle_buy(request): if request.user.is_authenticated(): p = Portfolio.objects.get(user=request.user) else: return render_error(request, 'You don\'t seem to be logged in') symbol = request.POST["symbol"] stk = Stock.objects.get(symbol=symbol) try: share = int(request.POST['number_of_shares']) except: return render_error(request, 'Try entering a real number') if p.balance < share * stk.price: return render_error(request, "Insufficient funds deadbeat") o = Order(type='buy', amount=share, stock=stk) o.save() p.history.add(o) p.save() pos = p.positions.filter(stock=stk) if pos.count() == 1: pos = pos[0] pos.amount = pos.amount + share pos.value = pos.amount * stk.price pos.save() else: pos = Position(amount=share, stock=stk, value=share * stk.price) pos.save() p.positions.add(pos) p.save() p.value += share * stk.price p.balance -= share * stk.price p.save() return HttpResponseRedirect('/')
def test_loading_invoice_yaml_to_model(self): import yaml invoice_path = os.path.join("..", "documents", "invoice", "data", "data.yml") with open(invoice_path) as config_file: data = yaml.load(config_file.read()) for position in data['positions']: p = Position(**position) print(p)
class TestStockPos(TestCase): def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_stock = test_raw_data['Stock'] def tearDown(self): del self.raw_stock def test_save_data(self): sp = StockPos() sp.save_raw_data(position=self.position, raw_stock=self.raw_stock) print 'stock row count in db: %d\n' % len(StockPos.objects.all()) self.assertEqual(len(StockPos.objects.all()), 1) print 'Stock Position in db:' print StockPos.objects.get(id=1)
class TestInstrumentPos(TestCase): def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_instrument = test_raw_data['Instrument'] def tearDown(self): del self.raw_instrument def test_save_raw_data(self): ip = InstrumentPos() ip.save_raw_data(position=self.position, raw_instrument=self.raw_instrument) print 'instrument row count in db: %d\n' % len(InstrumentPos.objects.all()) self.assertEqual(len(InstrumentPos.objects.all()), 1) print 'Instrument Position in db:' print InstrumentPos.objects.get(id=1)
def save_position(self): """ save all into db """ instrument_count = 0 option_count = 0 # now import all symbol position in files into db for symbol, items in self.position.items(): instrument = items["Instrument"] stock = items["Stock"] options = items["Options"] # get company name company = stock["name"] # leg_identify insert position position = Position(symbol=symbol, company=company, date=self.date) position.save() # second insert instrument instrument_pos = InstrumentPos() instrument_pos.save_raw_data(position=position, raw_instrument=instrument) # third insert stock stock_pos = StockPos() stock_pos.save_raw_data(position=position, raw_stock=stock) # fourth and final insert option for option in options: option_pos = OptionPos() option_pos.save_raw_data(position=position, raw_option=option) option_count += 1 # update insert count instrument_count += 1 # after finish clear data self.position = None return instrument_count, option_count
def ranPos(min, max, count): i = 0 rans = list() while(i < count): ranx = randrange(start=min, stop=max, step=1) rany = randrange(start=min, stop=max, step=1) pos = Position.position(x=ranx, y=rany) rans.append(pos) i = i + 1 return rans
def mutate(root, info, **input): pb = Position(currency_pair=input['currency_pair'], held_currency=input['held_currency'], amount=input['amount'], date=input['date'], full_info=input['full_info'], type=input['type']) user = User.objects(id=input['user_id']).first() user.balance.append(pb).save() return AddPosition(position=pb)
def set_firstPlayer(self, request): """ This function sets the first player of a given game. Input: game safe url key, player username""" game = utils.get_by_urlsafe(request.game_urlsafekey, Game) player = utils.get_by_username(request.player) position = Position.query(Position.game == game.key, Position.player == player.key).get() position.isPlayingNow = True position.put() message = "Player %s token is set %s" % (player.username, "True") return MessageForm(message=message)
def walls_save(request, house_id): Wall.objects.filter(floor=int(request.POST['floor_id'])).delete(); s = house_id for i in range(int(request.POST['n'])): f = Wall(); start = Position() start.x = request.POST['wall_start_x' + str(i)] start.y = request.POST['wall_start_y' + str(i)] start.save() f.start = start end = Position() end.x = request.POST['wall_end_x' + str(i)] end.y = request.POST['wall_end_y' + str(i)] end.save() f.end = end f.insulating_size = request.POST['wall_insulating_size' + str(i)] f.wall_size = request.POST['wall_wall_size' + str(i)] f.floor=Floor.objects.get(pk=int(request.POST['floor_id'])) f.save() return HttpResponse(s)
def endElement(self, name): if name == 'Placemark': truck = FoodTruck(key=self.curr_id, name=self.curr_name, foodType=self.curr_description, position=self.curr_position) truck.save() print "saved: "+ str(truck); self.curr_name = "" self.curr_description = "" self.curr_position = Position(lat=0,lon=0) self.curr_id = 0 self.buff = "" elif name == 'name': self.curr_name = self.buff elif name == 'description': self.curr_description = self.buff elif name == 'coordinates': coords = self.buff.split(",") print "float(coords[0])" + str(coords[0]) + "float(coords[1])" + str(coords[1]) self.curr_position = Position(lat=float(coords[1]), lon=float(coords[0])) self.curr_position.save() self.buff = ""
def crypto_tokens(): """ Crypto currency tokens """ try: with open('crypto.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') positions = [Position(symbol=row[0], quantity=row[1]) for row in reader] return Portfolio(positions) except IOError: return Portfolio()
def saveRowAsTruck(worksheet, row_index): if (isValidTruck(worksheet, row_index)): flat = worksheet.cell_value(row_index, 6) flon = worksheet.cell_value(row_index, 7) floc = worksheet.cell_value(row_index, 4) p = Position(lat=float(flat), lon=float(flon)) p.save() if (worksheet.cell_type(row_index, 3) is not 1): fname = "Food Cart" else: fname = worksheet.cell_value(row_index, 3) if (worksheet.cell_type(row_index, 5) is not 1): fdescription = "Mystery Food" else: fdescription = worksheet.cell_value(row_index, 5) fkey = worksheet.cell_value(row_index, 0) t = FoodTruck(key=fkey, name=fname, foodType=fdescription, position=p, location=floc) t.save()
def appliances_save(request, house_id): appliances_list = ApplianceLink.objects.filter( floor=int(request.POST['floor_id'])) appliances = [] for appliance in appliances_list: appliances.append(appliance.pk) for i in range(int(request.POST['n'])): if (long(request.POST.get('appliance_link_pk' + str(i), 0)) > 0): f = ApplianceLink(pk=long(request.POST['appliance_link_pk' + str(i)])) appliances.remove(f.pk) else: f = ApplianceLink() center = Position() center.x = request.POST['appliance_link_center_x' + str(i)] center.y = request.POST['appliance_link_center_y' + str(i)] center.save() f.center = center f.appliance = ApplianceType.objects.get( pk=request.POST['appliance_link_appliance_pk' + str(i)]) f.floor = Floor.objects.get(pk=int(request.POST['floor_id'])) f.save() for appliance in appliances: ApplianceLink(pk=appliance).delete() return HttpResponse('')
def portfolio(): """ Stock market portfolio """ try: with open('portfolio.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') positions = [Position(symbol=row[0], quantity=row[2]) for row in reader ] return Portfolio(positions) except IOError as err: return Portfolio()
def _factory_election_data(websafe_election_key): """ Factory database with data from settings.py """ # create or update election if websafe_election_key is not None: election_key = ndb.Key(urlsafe=websafe_election_key) election = election_key.get() else: election = Election() election.populate(**ELECTION_DATA) election_key = election.put() for pos_data_orig in POSITION_DATA: # avoid directly delete on setting objects pos_data = pos_data_orig.copy() position_data = pos_data['data'] del pos_data['data'] position_name = pos_data['name'] position = Position.query(ancestor=election_key).\ filter(Position.name == position_name).get() if position is None: logger.debug('creating new position entity') position_id = ndb.Model.allocate_ids( size=1, parent=election_key)[0] position_key = ndb.Key(Position, position_id, parent=election_key) position = Position(key=position_key) position.populate(**pos_data) position_key = position.put() # remove all roles under position ndb.delete_multi(position.candidate_keys) # create all roles from data candidates = [] for index, data_dict in enumerate(position_data): candidate_id = ndb.Model.allocate_ids( size=1, parent=position_key)[0] candidate_key = ndb.Key( Candidate, candidate_id, parent=position_key) candidate = Candidate(key=candidate_key) data_dict['voting_index'] = index candidate.populate(**data_dict) candidates.append(candidate) position.candidate_keys = ndb.put_multi(candidates) position.put() return "update all data successfully"
def load_position(position_data, comments, parties): """Return a new position instance for position_data.""" party_data = parties[position_data["party"]] party = party_instances[party_data["name"]] party.name = party_data["name"] party.long_name = party_data["longname"] # Im Datensatz werden Antworten mit einem Schlüssel in answer.json # kodiert. Da Metawahl davon ausgeht, dass Antworten immer zustimmend, # ablehnend oder neutral sind, wird der Schlüssel hier hart kodiert, assert position_data["answer"] in [0, 1, 2] value = {0: 1, 1: -1, 2: 0}[position_data["answer"]] position = Position(value=value, party=party) comment_id = position_data["comment"] if comment_id and comments[comment_id]["text"] not in INVALID_POSITION_TEXTS: raw_text = comments[comment_id]["text"] raw_text = raw_text[1:-1] if raw_text.startswith('"') else raw_text position.text = raw_text return position
def generate_demo_csv(): position_a = Position(quantity=2, ticker='AA', name='A & A', current_value=20, expected_value=30) position_b = Position(quantity=3, ticker='BB', name='B & B', current_value=30, expected_value=40) position_c = Position(quantity=4, ticker='CC', name='C & C', current_value=40, expected_value=50) position_d = Position(quantity=5, ticker='DD', name='D & D', current_value=50, expected_value=60) portfolio = Portfolio(position_a, position_b, position_c, position_d) portfolio.write_to_file(os.path.join(PORTFOLIO_DIR, 'demo.csv'))
def post(self): employee_query = Employee.query(Employee.login_name == self.request.get('username')) employee = employee_query.fetch()[0] position_query = Position.query(Position.title == self.request.get('position')) position = position_query.fetch()[0] employee.positions.remove(position.key) employee.put() position_query = Position.query() positions = position_query.fetch() notUserTitles = [] userTitles = [] for position in positions: if position.key in employee.positions: userTitles.append(position.title) else: notUserTitles.append(position.title) titles = [notUserTitles, userTitles] self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(titles))
def appliances_save(request, house_id): appliances_list = ApplianceLink.objects.filter(floor=int(request.POST['floor_id'])) appliances = [] for appliance in appliances_list: appliances.append(appliance.pk) for i in range(int(request.POST['n'])): if (long(request.POST.get('appliance_link_pk' + str(i),0)) > 0): f = ApplianceLink(pk = long(request.POST['appliance_link_pk' + str(i)])); appliances.remove(f.pk) else: f = ApplianceLink() center = Position() center.x = request.POST['appliance_link_center_x' + str(i)] center.y = request.POST['appliance_link_center_y' + str(i)] center.save() f.center = center f.appliance = ApplianceType.objects.get(pk=request.POST['appliance_link_appliance_pk' + str(i)]) f.floor=Floor.objects.get(pk=int(request.POST['floor_id'])) f.save() for appliance in appliances: ApplianceLink(pk=appliance).delete() return HttpResponse('')
def locate(self): start = time.perf_counter() measures = self.fetch_measures() end = time.perf_counter() print("{} measures fetched in {}s".format(len(measures), end - start)) for device_mac, measure in measures.items(): if len(measure) >= 3: start = time.perf_counter() res = self.engine.locate(measure) end = time.perf_counter() print("engine localised {} in {}s".format( device_mac, end - start)) self.publisher.publish({ "mac": device_mac, "location": res.to_db_object() }) self.position_dao.save(Position(Mac(device_mac), res))
def post(self): employee_query = Employee.query(Employee.login_name == self.session['username']) employee = employee_query.fetch()[0] data = self.request.get_all('hours') data = [data[i:i+8] for i in range(0, len(data), 8)] for i in range(0, len(data)): position_query = Position.query(Position.title == data[i][0]) position = position_query.fetch()[0] timesheet_query = Timesheet.query(Timesheet.time_period == self.request.get('week'), Timesheet.worked_by == employee.key, Timesheet.position == position.key) timesheet = timesheet_query.fetch()[0] del data[i][0] timesheet.hours_worked = map(int, data[i]) timesheet.put()
def get(self): employee_query = Employee.query(Employee.login_name != self.session.get('username')) employee_list = employee_query.fetch() position_query = Position.query() position_list = position_query.fetch() admin_values = { 'username': self.session.get('username'), 'first_name': self.session.get('first_name'), 'last_name': self.session.get('last_name'), 'is_admin': self.session.get('is_admin'), 'positions': self.session.get('positions'), 'employee_list': employee_list, 'position_list': position_list } template = jinja_env.get_template("templates/admin_edit.html") self.response.write(template.render(admin_values))
def contribute_post(): stripped_ctags = [ tag.split(' - ', 1)[1] for tag in request.form.getlist('ctags') ] current_user.dtags = DemogTag.query.filter( DemogTag.label.in_(request.form.getlist('dtags'))).all() new_post = Post( author=current_user, category=Category.query.filter( Category.label == request.form.get('category')).first(), ctags=ContentTag.query.filter( ContentTag.label.in_(stripped_ctags)).all(), q_name=request.form.get('q_name'), q_about=request.form.get('q_about'), q_interest=request.form.get('q_interest'), q_challenges=request.form.get('q_challenges'), q_change=request.form.get('q_change'), q_helpful=request.form.get('q_helpful'), q_other=request.form.get('q_other')) for r in range(3): role, org = request.form.get('role' + str(r)), request.form.get('org' + str(r)) if not (role == '' and org == ''): check_pos = Position.query.filter(Position.title == role, Position.org == org) try: pos = check_pos.first() pos.users.append(current_user) pos.posts.append(new_post) except: Position(title=role, org=org, users=[current_user], posts=[new_post]) db.session.add(new_post) db.session.commit() flash('Thank you for your contribution!') return render_template('contribute.html', categories=category_dict, demographics=demog_tags, sample=sample, roles=3)
def save_portfolio(self, portfolio, name, date): #NOTE ndict annoying stuff session = self.manager.db.Session() # Cleaning session.execute( "delete from Positions where Positions.PortfolioName = '{}'". format(name)) #session.execute("delete from Portfolios where Portfolios.Name = '{}'".format(name)) pf_object = Portfolio(name=name, date=date.strftime(format='%Y-%m-%d %H:%M'), startdate=portfolio.start_date, cash=portfolio.cash, startingcash=portfolio.starting_cash, returns=portfolio.returns, capital=portfolio.capital_used, pnl=portfolio.pnl, portvalue=portfolio.portfolio_value, posvalue=portfolio.positions_value) positions = json.loads( str(portfolio.positions).replace('Position(', '').replace(')', '').replace("'", '"')) assert isinstance(positions, dict) #FIXME In remote mode with lot of portfolios: make it crash ! for ticker in positions: positions[ticker]['name'] = name positions[ticker]['date'] = date session.add(Position(**positions[ticker])) #NOTE bug: 'not list-like object', but not an issue ? #pf_object.Positions = Position(**positions[ticker]) #name=name, #ticker='pouet', #amount=0, #last_sale_price=0, #cost_basis=0) session.add(pf_object) session.commit() session.close()
# This Python file uses the following encoding: utf-8 import os, sys import datetime from models import Position p = Position(title = u'网站开发工程师', department = u'R&D', responsibility = u'开发基于Python/Javascript的网站应用;负责相应模块的设计,开发,单元测试和文档编写;参与相关领域的创新和探索性研究。', requirement = u'计算机专业或相关领域本科学历(及以上);三年以上网站开发工作经验;精通Python/Cheerypy开发,熟悉相关平台;精通Javascript/JQuery开发,熟悉Json/Ajax/XML/REST等技术;熟悉各种浏览器特性和开发;为人开朗,有良好的团队合作精神。', preference = u'熟悉Flash/ActionScript开发,并有相关工作背景视为额外优势;熟悉网络构架,网络协议,有网络监控或者协议分析相关工作背景视为额外优势。', pub_date=datetime.datetime.now()); p.save();
def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_instrument = test_raw_data['Instrument']
def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_stock = test_raw_data['Stock']
def setUp(self): self.position = Position(symbol=test_symbol, company=test_company, date=test_date) self.position.save() self.raw_options = test_raw_data['Options']