def _handle_schedule(schedule_id): schedule = Schedule.get(Schedule.id == schedule_id) if not schedule: logger.warn("Schedule is invalid. ID = %s" % schedule_id) return to_mails = schedule.recipients.split(",") attachments = Attachment.gets_by_schedule(schedule_id) atta_dicts = [a.to_mandrill_dict() for a in attachments] rs = send_mail( subject=schedule.subject, from_mail=SEND_ADDRESS, to_mails=to_mails, html=schedule.content, attachments=atta_dicts, ) if not rs: logger.warn("Schedule send fail. ID = %s" % schedule_id) schedule.fail() return if schedule.repeat_strategy: schedule.wait(schedule.repeat_strategy.get_next_time()) else: schedule.send() for r in rs: logger.info(r) now = datetime.utcnow() History.create( recipient=r.get("email"), send_id=r.get("_id", ""), schedule_id=schedule.id, status=r.get("status"), reason=r.get("reject_reason") or "", send_time=now, update_time=now, )
def handle(self): self.possible_responses = { 'login': self.login, 'logout': self.logout, 'msg': self.msg, 'names': self.names, 'help': self.help, 'history': self.history } self.logged_in = False self.name = None self.history_mod = History("messages.json") self.names_mod = Names('db.json') self.ip = self.client_address[0] self.port = self.client_address[1] self.connection = self.request threads.append(self) # Loop that listens for messages from the client while True: received_string = self.connection.recv(4096) payload = json.loads(received_string.decode()) if payload['request'] in self.possible_responses: self.possible_responses[payload['request']](payload) else: self.error("Illegal request {}".format(payload['request']))
def history_delete(id): user_id = get_jwt_identity() history = History.get_by_id(id) if history.delete_instance(): history_obj = History.select().where(History.user_id == user_id) history_arr = [] if history_obj: for history in history_obj: history_list = { 'mall': Mall.get_by_id(Floor.get_by_id(Parking.get_by_id(history.parking_id).floor_id).mall_id).outlet, 'floor': Floor.get_by_id(Parking.get_by_id(history.parking_id).floor_id).floor, 'parking': Parking.get_by_id(history.parking_id).parking_num, 'date': history.created_at.strftime('%A %d %b %Y'), 'time': history.created_at.strftime('%X %p'), 'id': history.id } history_arr.append(history_list) responseObj= { 'status': 'success', 'message': 'Successfully deleted parking history!', 'history': history_arr } return jsonify(responseObj), 200 else: responseObj = { 'status': 'failed', 'message': 'Failed to delete history!' } return jsonify(responseObj), 400
def add_history(): auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] else: responseObject = { 'status': 'failed', 'message': 'No authorization header found' } return make_response(jsonify(responseObject)), 401 user_id = User.decode_auth_token(auth_token) user = User.get_by_id(user_id) # save link that has been clicked on clicked_link = request.get_json('link') history = History(link=clicked_link, user_id=user.id) history.save() # sendgrid send email to user.email send_email(email)
def history_add_multiple(): user_id = get_jwt_identity() parking_id = [1,2,3,4,5,6,7,8] for parking in parking_id: history_inst = History(user_id = user_id, parking_id = parking) history_inst.save()
def post(self): mandrill_events = self.request.POST.get("mandrill_events", "") if mandrill_events: events = json.loads(mandrill_events) for e in events: status = e.get("event") send_id = e.get("_id") logger.info("[event arrival] %s %s" % (send_id, status)) if send_id and status: History.update_status(send_id, status)
def display_score(): if session.get('score') != None: current_user.total_score += session.get('score') current_user.update_user_info() score = session.pop('score') History.find_and_update(userID=current_user._id, score=score) return render_template('final_score.html', score=score) else: flash('You haven\'t played the Quiz yet!') return redirect('/')
def getHistory(): h = History() res = [] els = h.find() for el in els: res.append({'code': el['code'], 'action': el['action'], 'timestamp': el['timestamp'], 'data': el['data']}) return jsonify({'results': res})
def test_db_upsert(db): history = [ History(datetime.datetime(2016, 12, 31, 23, 59, 59), "mozillo1"), History(datetime.datetime(2015, 11, 30, 22, 58, 59), "mozillo2") ] session = [ Session(datetime.datetime(2016, 12, 31, 23, 59, 59), "mozillo1", "192.0.0.1", "msk") ] user = User(1, "test_user", history, session) db.upsert_user(user) return
def post(self): json_data = request.get_json() current_user = get_jwt_identity() try: data = history_schema.load(data=json_data) except ValidationError as errors: return {'message': 'Validation errors', 'errors': errors.messages}, HTTPStatus.BAD_REQUEST history = History(**data) history.user_id = current_user history.save() return history_schema.dump(history), HTTPStatus.CREATED
def match_pair(cls, game, pair_1, pair_2): """Match a pair and update game state""" game.attempts += 1 game.put() card_1 = Card.query(Card.game == game.key).filter(Card.index == pair_1).get() card_2 = Card.query(Card.game == game.key).filter(Card.index == pair_2).get() if card_1.matched or card_2.matched: raise RuntimeError('Could not rematch a matched card') form = MatchResultForm() if card_1.value == card_2.value: card_1.matched = True card_1.put() card_2.matched = True card_2.put() game.matched += 2 game.put() form.message = 'Success' else: form.message = 'Fail' # Construct return info form form.card_1 = card_1.to_form() form.card_2 = card_2.to_form() form.matched_count = game.matched if game.matched == 52: game.game_over = True game.put() Card.delete_cards_for_game(game) # Update average attempts of user user = game.user.get() games = Game.get_user_finished_games(user) count = len(games) if user.average_attempts == float('inf'): user.average_attempts = 0 user.average_attempts = ((count - 1) * user.average_attempts + game.attempts) / count user.put() score = Score(user=game.user, date=date.today(), attempts=game.attempts) score.put() form.message = 'Win' # Create history log History.create_history(game=game, card_1=card_1, card_2=card_2, message=form.message) return form
def get(self): page = self.request.GET.get('page', "1") try: page = int(page) except: self.abort(400, 'page is invalid') page = max(1, page) count = History.count() start = (page - 1) * PAGE_SIZE historys = History.gets_all(start, PAGE_SIZE) self.render_response('/history.html', historys=historys, page = page, page_count = -(-count / PAGE_SIZE))
def create_statistics(cls, user_id, stat_date): histories = History.get_by_user_id(user_id, stat_date) pomos = [0] * 24 breaks = [0] * 24 total_pomos = 0 total_breaks = 0 interruptions = 0 day_start = datetime.strptime(stat_date, '%Y%m%d') for history in histories: start_time = history.start end_time = history.end index = ((start_time - day_start).seconds + history.utc_offset * 60) // 3600 minutes = (end_time - start_time).seconds // 60 if history.type == 'Pomodoro': pomos[index] += minutes total_pomos += minutes if history.status == 'Interrupted': interruptions += 1 else: breaks[index] += minutes total_breaks += minutes stat = Stat(stat_key=stat_date, pomos=json.dumps(pomos), breaks=json.dumps(breaks), totalPomos=total_pomos, totalBreaks=total_breaks, interruptions=interruptions, user_id=user_id) stat.save() return stat
def post(self): """새로운 댓글 분석 요청 :return: {'status': 'success', 'unknown error'} """ parser = reqparse.RequestParser() parser.add_argument('userId', required=True, type=str) parser.add_argument('keyword', required=True, type=bool) parser.add_argument('sentiment', required=True, type=bool) parser.add_argument('url', required=True, type=str) parser.add_argument('slang', required=True, type=bool) args = parser.parse_args(strict=True) try: history = History(userId=args['userId'], keyword=args['keyword'], sentiment=args['sentiment'], url=args['url'], slang=args['slang']) db.session.add(history) db.session.commit() return {'status': 'success'} except: return {'status': 'unknown error'}
def make_game_easier(cls, game, hint_num): cards = Card.get_cards_for_game(game) unmatched_cards = filter(lambda c: not c.matched, cards) hint_histories = [] while game.matched != 52 and hint_num > 0: card_1 = unmatched_cards[0] card_2 = filter(lambda c: c != card_1 and c.value == card_1.value, unmatched_cards)[0] # Update game state card_1.matched = True card_2.matched = True game.matched += 2 game.attempts += 1 hint_num -= 1 # Update card state unmatched card list unmatched_cards.remove(card_1) unmatched_cards.remove(card_2) card_1.put() card_2.put() # Create history log history = History.create_history(game=game, card_1=card_1, card_2=card_2, message='Hint Match') hint_histories.append(history) game.put() return hint_histories
def history(): user_id = get_jwt_identity() current_user = User.get_by_id(user_id) history_obj = History.select().where(History.user_id == current_user.id).order_by(History.id.desc()) history_arr = [] if history_obj: for history in history_obj: history_list = { 'mall': Mall.get_by_id(Floor.get_by_id(Parking.get_by_id(history.parking_id).floor_id).mall_id).outlet, 'floor': Floor.get_by_id(Parking.get_by_id(history.parking_id).floor_id).floor, 'parking': Parking.get_by_id(history.parking_id).parking_num, 'date': history.created_at.strftime('%A %d %b %Y'), 'time': history.created_at.strftime('%X %p'), 'id': history.id } history_arr.append(history_list) responseObj = { 'status': 'success', 'history': history_arr } return jsonify(responseObj), 200 else: responseObj = { 'status': 'success', 'history': history_arr } return jsonify(responseObj), 200
def find(): user_id = get_jwt_identity() history = History.select().where(History.user_id == user_id).order_by(History.id.desc()) if history: latest = history[0] responseObj = { 'status': 'success', 'mall': Mall.get_by_id(Floor.get_by_id(Parking.get_by_id(latest.parking_id).floor_id).mall_id).outlet, 'floor': Floor.get_by_id(Parking.get_by_id(latest.parking_id).floor_id).floor, 'parking': Parking.get_by_id(latest.parking_id).parking_num, 'date': latest.created_at.strftime('%A %d %b %Y'), 'time': latest.created_at.strftime('%X %p'), 'id': latest.id } return jsonify(responseObj), 200 else: responseObj = { 'status': 'success', 'message': 'No parking information!', 'mall': 'N/A', 'floor': 'N/A', 'parking': 'N/A', 'date': 'N/A', 'time': 'N/A', 'id': 'N/A' } return jsonify(responseObj), 200
def main(): args = get_args() history = History(calc_ops) if args.history_file_path: with open(args.history_file_path) as history_file: history.from_json(history_file.read()) command = "noop" while command: log_command(command) command_fn = app_commands.get(command, command_unknown) command_fn(history) command = get_command()
def add_history(): clicked_link = request.get_json() auth_header = request.headers.get('Authorization') if not auth_header: responseObject = { 'status': 'failed', 'message': 'No JWT in Authorization Header' } return make_response(jsonify(responseObject)), 401 # decode the auth_token to get the user_id auth_token = auth_header.split(" ")[1] user_id = User.decode_auth_token(auth_token) current_user = User.get_by_id(user_id) # save link that has been clicked on if current_user and clicked_link: email = current_user.email name = current_user.name # sendgrid send email to user.email send_email(email) history = History( link=clicked_link['link'], user_id=current_user.id) if history.save(): responseObject = { 'status': 'success' } return make_response(jsonify(responseObject)), 201 else: responseObject = { 'status': 'failed', 'message': 'History not saved' } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'failed', 'message': 'No authorization header found' } return make_response(jsonify(responseObject)), 401
def get_game_history(self, request): """Return the guess history of given game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') histories = History.get_game_history(game) return HistoryForms(items=[h.to_form() for h in histories])
def get_user_by_id(user_id): user = User.get_by_id(user_id) if user: payload = user.get_view("public") if request.args.get('with_images'): user_images = Image.get_user_images(user.id) payload['images'] = [] if user_images: payload['images'] = [{ "src": i.image_src, "id": i.id } for i in user_images] if request.args.get('with_like'): has_like = Like.is_liked(g.current_user.id, user_id) likes_me = Like.is_liked(user_id, g.current_user.id) payload['has_like'] = has_like payload['likes_me'] = likes_me # If I blocked this user [blocked, blocker] if User.user_is_blocked(user_id, g.current_user.id): u_is_blocked = True else: u_is_blocked = False if request.args.get('with_block'): payload['is_blocked'] = u_is_blocked # If user didn't block me [blocked, blocker] # Send notification if not User.user_is_blocked(g.current_user.id, user_id): if g.current_user.id != user_id: text = Notification.notification_text('view', g.current_user) notification = Notification.from_dict({ "user_id": user_id, "text": text, "type": "view" }) notification.create() # View history if g.current_user.id != user_id: History.add_to_history(g.current_user.id, user_id) return jsonify(user=payload) abort(404)
class Simulator: def __init__(self, state): self._state = state self._history = History() def step(self): current_state = self._state self._history.store(current_state) next_state = copy.deepcopy(current_state) next_state.step(self._history) self._state = next_state def get_state(self): return self._state def extract_series(self): return self._state.extract_series(self._history)
def make_move(request): game = get_by_urlsafe(request.urlsafe_game_key, Game) game.number_of_guess += 1 word = Word.query(Word.key == game.word).get() split_word = list(word.word) guess = request.guess game_history = History.query(History.game == game.key) letters_guessed_so_far = [] for history in game_history.iter(): letters_guessed_so_far.append(history.guess) if game.game_over is True: msg = 'Game already over!' elif guess == '' or guess.isdigit() or len(guess) > 1: msg = "Please enter a single alpha character only" elif guess in letters_guessed_so_far: msg = "You have already used that letter" elif guess not in split_word: msg = "letter isn't in word" game.guesses_remaining -= 1 save_history(game.key, game.number_of_guess, guess, False) else: msg = "Letter is in word!" save_history(game.key, game.number_of_guess, guess, True) # Added in a sleep because of latency writing to the datastore. # http://stackoverflow.com/questions/9137214/writing-then-reading-entity-does-not-fetch-entity-from-datastore time.sleep(0.1) count_of_success = History.query(History.status == True).filter(History.game == game.key).count() if len(word.word) == count_of_success: msg = "You've won! The word was {}".format(word.word) game.end_game(True) elif game.guesses_remaining == 0: msg = 'You have run out of guesses! The word was {}'.format(word.word) game.end_game() taskqueue.add(url='/tasks/cache_average_attempts') game.put() return game, msg
def upload_files(): if request.method == 'POST': file = request.files['data'] # history_id = request.form['id'] if file and allowed_file(file.filename): history = History(request.form.to_dict(), file.filename) history.insert() user = User(request.form.to_dict()) user.insert() filename = secure_filename(file.filename) print(os.path.join(UPLOAD_FOLDER, filename)) file.save(os.path.join(UPLOAD_FOLDER, filename)) print(jsonify(filename=filename)) return jsonify(filename=filename) return jsonify(status='error'), 500 # show upload page. return render_template('upload.html', get_histories=get_histories)
def xpath_user_history(self, content): tree = html.fromstring(content) logging.debug("DOM created...") tmp = ' '.join( str(x) for x in tree.xpath( '//div[contains(@class, "light_blue")]/text()')) if "Здесь вы сможете проверить, не заходил ли кто-то чужой под вашим ником!" in tmp: logging.error("History protection (admin?)") return [] hist_raw_list = tree.xpath( '//div[contains(@class,"list_item")]/span/following-sibling::text()[1]' ) hist_list = [] logging.debug("List items: " + str(len(hist_raw_list))) l = len(hist_raw_list) for i in range(0, l, 2): device = "" logging.debug(str(i) + " // Date raw: " + hist_raw_list[i]) date = self.spac_date.get_python_time(hist_raw_list[i]) logging.debug("RawTime: " + str(date)) logging.debug(str(i + 1) + " // UA raw: " + hist_raw_list[i + 1]) ua = hist_raw_list[i + 1].strip() logging.debug("UA: " + ua) if l == i + 3 and l % 2 == 1: device = hist_raw_list[i + 2] logging.debug("Device: " + device) hist_list.append(History(date, ua, device)) return hist_list hist_list.append(History(date, ua, device)) return hist_list
def history_add(): user_id = get_jwt_identity() user_inst = User.get_by_id(user_id) parking_id = request.json.get('parking_id') parking_inst = Parking.get_by_id(parking_id) floor_inst = Floor.get_by_id(parking_inst.floor_id) mall_inst = Mall.get_by_id(floor_inst.mall_id) history_inst = History(user_id = user_id, parking_id = parking_id) if history_inst.save(): responseData = client.send_message({ 'from': 'Nexmo', 'to': user_inst.hp_number, 'text': 'RM0.00 EzPark: Your car is parked in Mall: [' + mall_inst.outlet + '], at Floor: [' + floor_inst.floor + '], in Parking Bay: [' + parking_inst.parking_num + ']///' }) # if responseData["messages"][0]["status"] == "0": responseObj = { 'status': 'success', 'message': 'Successfully saved your parking!' } return jsonify(responseObj), 200 # else: # responseObj = { # 'status': 'failed', # 'message': 'Message sent failed' # } # return jsonify(responseObj), 400 else: responseObj = { 'status': 'failed', 'message': 'Parking failed to save!' } return jsonify(responseObj), 400
def my_account(): user_data = session.get('user_data', None) user = json.loads(user_data) username = user['username'] history = History.select_user_history(connection, username) if history: return render_template( "module_account/my_account.html", history=history, logged_in=True, user=json.loads(user_data) if user_data else None) else: return render_template( "module_account/my_account.html", history=None, logged_in=True, user=json.loads(user_data) if user_data else None)
def history_db(): with open('histories.csv', mode='r') as his_file: hist_reader = csv.reader(his_file) line_count = 0 for row in hist_reader: if line_count == 0: line_count += 1 else: his = History(car_id=row[0], lat=row[1], long=row[2], fuel_level=row[3], dtc=row[4], timestamp=datetime.strptime( row[5], '%d-%m-%y %H:%M:%S'), engine_temp=row[6], oil_temp=row[7], odometer=row[8]) db.session.add(his)
def history(self): q = History.query(ancestor=self.key) q = q.order(-History.creation_time) return [h.get() for h in q.iter(limit=10, keys_only=True)]
def testHistoryLengthAndMovement(self): history = History(2) history.add_log(['1', '2', '3', '4']) # we only the last 2 one self.assertEqual(['3', '4'], history.get_log()) history.increase_cursor() # if we want to the next line do nothing self.assertEquals(['3', '4'], history.get_log()) history.decrease_cursor() self.assertEquals(['2', '3'], history.get_log()) # the increase work history.increase_cursor() self.assertEquals(['3', '4'], history.get_log()) history.go_to_the_top() self.assertEquals(['1', '2'], history.get_log())
def testHistoryLengthOnlyOneData(self): history = History(2) history.add_log(['1']) # if only one entry you can do more or less nothing.. self.assertEqual(['1'], history.get_log()) history.increase_cursor() self.assertEquals(['1'], history.get_log()) history.decrease_cursor() self.assertEquals(['1'], history.get_log()) history.increase_cursor() self.assertEquals(['1'], history.get_log()) history.go_to_the_top() self.assertEquals(['1'], history.get_log())
def inject_stage_and_region(): return dict(enumerate=enumerate, leaderboard=History.show_history())
def leaderboard(): if not History.show_history(): flash('No Player Data is available at the moment') return redirect('/') return render_template('leaderboard.html')
def testConstructor(self): history = History(5) self.assertEquals([], history.get_log()) history.add_log(['1', '2', '3', '4', '5']) self.assertEquals(['1', '2', '3', '4', '5'], history.get_log())
def get_game_history(self, request): """Get history for a game""" game = get_game(request) return HistoryForms(game=[history.to_form() for history in History.query(History.game == game.key)])
def remove_player(pid): player = User.get_user_info(pid) player.delete_user() History.delete_history(userID=player._id)
def get(self, txn_date): current_user = get_jwt_identity() histories = History.get_by_user_id(current_user, txn_date) result = history_list_schema.dump(histories) return result, HTTPStatus.OK
def __init__(self, state): self._state = state self._history = History()
def save_history(game_key, round, guess, status): history = History(game=game_key, round=round, guess=guess, status=status) history.put()