def register(self, request: Request): ip, port = request.connection if isinstance(request.body, dict): nickname = request.body.get("nickname") if nickname != None: player = Player(ip, port, nickname) # Block if the gamming is running if self.game_running or self.last_question != None: return Response(code=codes.IS_RUNNING, body="Gamming is running") if len(self.players) == self.max_players: return Response(code=codes.FULL, body="The room is full") # Check if user is not already registred elif player in self.players: return Response(code=codes.ALREADY_EXISTS, body="Already exists") # Add new player print("[*] Player Registred!", str(player)) self.players.append(player) return Response(code=codes.REGISTRED, body="OK") # Return invalid parameters return Response(code=codes.INVALID_PARAMETERS, body="Invalid params")
def update(db_conn, user, card, response): """ Update the card's parameters (and its parents') when given a response. """ # TODO-3 split up into smaller methods if not card.has_assessment(): return { 'response': Response({}), 'feedback': '', } errors = card.validate_response(response) if errors: return {'errors': errors} score, feedback = card.score_response(response) response = Response({ 'user_id': user['id'], 'card_id': card['entity_id'], 'unit_id': card['unit_id'], 'response': response, 'score': score, }) card_parameters = CardParameters.get(db_conn, entity_id=card['entity_id']) if not card_parameters: card_parameters = CardParameters({ 'entity_id': card['entity_id'] }) previous_response = Response.get_latest(db_conn, user_id=user['id'], unit_id=card['unit_id']) now = time() time_delta = now - (int(previous_response['created'].strftime("%s")) if previous_response else now) learned = (previous_response['learned'] if previous_response else init_learned) guess_distribution = card_parameters.get_distribution('guess') slip_distribution = card_parameters.get_distribution('slip') updates = formula_update(score, time_delta, learned, guess_distribution, slip_distribution) response['learned'] = updates['learned'] response, errors = response.save(db_conn) if errors: return {'errors': errors, 'feedback': feedback} card_parameters.set_distribution('guess', updates['guess_distribution']) card_parameters.set_distribution('slip', updates['slip_distribution']) card_parameters, errors = card_parameters.save(db_conn) if errors: return {'errors': errors, 'feedback': feedback} return {'response': response, 'feedback': feedback}
async def execute_head(self, request): file_data = self.get_file_info(request) if file_data == 403: # forbidden error return Response(status=ALLOWED_CODES.get(403), protocol=request.protocol, connection='') elif file_data == 404: # not found error return Response(status=ALLOWED_CODES.get(404), protocol=request.protocol, connection='') else: return Response(status=ALLOWED_CODES.get(200), protocol=request.protocol, connection='closed', content_length=file_data.get('content_length'), content_type=file_data.get('content_type'))
def update(user, card, response): """ Update the card's parameters (and its parents') when given a response. """ # TODO-3 split up into smaller methods if not card.has_assessment(): return { 'response': Response({}), 'feedback': '', } errors = card.validate_response(response) if errors: return {'errors': errors} score, feedback = card.score_response(response) response = Response({ 'user_id': user['id'], 'card_id': card['entity_id'], 'unit_id': card['unit_id'], 'response': response, 'score': score, }) card_parameters = CardParameters.get(entity_id=card['entity_id']) previous_response = Response.get_latest(user_id=user['id'], unit_id=card['unit_id']) now = time() time_delta = now - (int(previous_response['created'].strftime("%s")) if previous_response else now) learned = (previous_response['learned'] if previous_response else init_learned) guess_distribution = card_parameters.get_distribution('guess') slip_distribution = card_parameters.get_distribution('slip') updates = formula_update(score, time_delta, learned, guess_distribution, slip_distribution) response['learned'] = updates['learned'] response, errors = response.save() if errors: return {'errors': errors, 'feedback': feedback} card_parameters.set_distribution('guess', updates['guess_distribution']) card_parameters.set_distribution('slip', updates['slip_distribution']) card_parameters, errors = card_parameters.save() if errors: return {'errors': errors, 'feedback': feedback} return {'response': response, 'feedback': feedback}
def create_prospect(self, prospect): try: message = self.xstream_service.create_message( FunctionTypes.CREATE_PROSPECT.value, prospect=prospect) service_response = self.xstream_service.process_message(message) api_response_body = self.xstream_service.process_response( service_response, ResponseType.PROSPECT) api_response = Response(api_response_body, status_code=200) except Exception as e: print('Error: create_prospect failed - {}'.format(e)) api_response = Response(ErrorResponses.INTERNAL_SERVER_ERROR.value, status_code=500) return api_response
async def _execute_head_request(self, request: Request) -> Response: try: resource = self._build_resource(request) except ForbiddenError: return Response(status_code=StatusCodes.FORBIDDEN, protocol=request.protocol) except NotFoundError: return Response(status_code=StatusCodes.NOT_FOUND, protocol=request.protocol) return Response(status_code=StatusCodes.OK, protocol=request.protocol, content_length=resource.size, content_type=resource.content_type.value, body=b'')
def execute_head(self, request): try: file = self.get_file_info(request) content_length = self.get_file_content_length(file.file_path) return Response(status_code=Response.OK, protocol=request.protocol, connection=request.connection, content_type=file.content_type.value, content_length=content_length) except (BadFilePathException, FileNotFoundError): return Response(status_code=Response.NOT_FOUND, protocol=request.protocol, connection=request.connection)
def judge(unit, user): """ Given a unit and a user, pass judgement on which bucket to file it under. """ response = Response.get_latest(user_id=user['id'], unit_id=unit['entity_id']) if response: learned = response['learned'] now = time() time_delta = now - (int(response['created'].strftime("%s")) if response else now) belief = calculate_belief(learned, time_delta) else: learned = 0 belief = 0 if learned >= max_learned: if belief > max_belief: return "done" if belief <= max_belief: return "review" if belief > diag_belief: return "learn" return "diagnose"
def status(self, request: Request): return Response(code=codes.SUCCESS, body={ "total": self.max_players, "actual": len(self.players), 'running': self.running })
def test_created(db_conn, responses_table): """ Expect to have a created date. """ response = Response({ 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'response': 42, 'score': 0.9, 'learned': 0.9, }) del response['created'] # should be set to default anywho response, errors = response.save(db_conn) assert len(errors) == 0
async def execute_head(self, request): try: file = self.get_file_info(request) except ForbidenError: return Response(status=Response.FORBIDDEN, protocol=request.protocol, connection='') except NotFoundError: return Response(status=Response.NOT_FOUND, protocol=request.protocol, connection='') return Response(status=Response.OK, protocol=request.protocol, connection='closed', content_length=file.content_length, content_type=file.content_type)
def judge(db_conn, unit, user): """ Given a unit and a user, pass judgement on which bucket to file it under. """ response = Response.get_latest( db_conn, user_id=user['id'], unit_id=unit['entity_id'] ) if response: learned = response['learned'] now = time() time_delta = now - (int(response['created'].strftime("%s")) if response else now) belief = calculate_belief(learned, time_delta) else: learned = 0 belief = 0 if learned >= max_learned: if belief > max_belief: return "done" if belief <= max_belief: return "review" if belief > diag_belief: return "learn" return "diagnose"
def test_created(db_conn, responses_table): """ Expect to have a created date. """ response = Response({ 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'response': 42, 'score': 0.9, 'learned': 0.9, }) del response['created'] # should be set to default anywho response, errors = response.save() assert len(errors) == 0
def register(self, request: Request): ip, port = request.connection p = Player(ip, port) if len(self.room.players) == self.room.max_players: return Response(code=codes.SUCCESS, body="the game is full, await some minutes") elif (p in self.room.players): return Response(code=codes.SUCCESS, body="you're already registred") # Add into a virtual database self.room.players.append(p) print("[*] Player Registred!", str(p)) return Response(code=codes.SUCCESS, body="ok")
def delete(self, cls, slug=None): session = self.backend.get_session() response = Response() cls_obj = getattr(sys.modules[__name__], cls) if inspect.isclass(cls_obj): try: if slug: session.query(cls_obj).filter(cls_obj.id == slug).delete() session.commit() response.add_data('Deleted') else: response.add_error_message('Missing %s id' % cls) except: response.add_error_message('Exception while fetching cards') else: response.add_error_message('No such class %s' % cls) self.write(response.as_dict())
async def execute(self, request): if request.get_method() not in [b'GET', b'HEAD']: return Response(Response.METHOD_NOT_ALLOWED, request.get_protocol(), request.get_connection()) elif request.get_method() == b'HEAD': return await self.execute_head(request) else: return await self.execute_get(request)
async def _execute_get_request(self, request: Request) -> Response: try: resource = self._build_resource(request) except ForbiddenError: return Response(status_code=StatusCodes.FORBIDDEN, protocol=request.protocol) except NotFoundError: if request.url[-1:] == '/': return Response(status_code=StatusCodes.FORBIDDEN, protocol=request.protocol) else: return Response(status_code=StatusCodes.NOT_FOUND, protocol=request.protocol) try: body = await self._reader.read(resource.filename) except FileNotFoundError: if request.url[-1:] == '/': return Response(status_code=StatusCodes.FORBIDDEN, protocol=request.protocol) else: return Response(status_code=StatusCodes.NOT_FOUND, protocol=request.protocol) except NotADirectoryError: return Response(status_code=StatusCodes.NOT_FOUND, protocol=request.protocol) return Response(status_code=StatusCodes.OK, protocol=request.protocol, content_type=resource.content_type.value, content_length=resource.size, body=body)
async def execute_get(self, request): try: file = self.get_file_info(request) body = await self.read_file(file.filename) return Response(status=Response.OK, protocol=request.protocol, connection='closed', content_type=file.content_type, content_length=file.content_length, body=body) except ForbiddenError: return Response(status=Response.FORBIDDEN, protocol=request.protocol, connection='') except NotFoundError: return Response(status=Response.NOT_FOUND, protocol=request.protocol, connection='')
async def execute_get(self, request): try: file = self.get_file_info(request) body = await self.read_file(file.file_path, request.url) return Response(status_code=Response.OK, protocol=request.protocol, connection=request.connection, content_type=file.content_type.value, content_length=len(body), body=body) except (BadFilePathException, FileNotFoundError): return Response(status_code=Response.NOT_FOUND, protocol=request.protocol, connection=request.connection) except ForbiddenException: return Response(status_code=Response.FORBIDDEN, protocol=request.protocol, connection=request.connection)
async def execute(self, request): if request.method not in [b'GET', b'HEAD']: return Response(Response.METHOD_NOT_ALLOWED, request.protocol, connection=request.connection) elif request.method == b'HEAD': return await self.execute_head(request) else: return await self.execute_get(request)
def choose_card(user, unit): """ Given a user and a unit, choose an appropriate card. Return a card instance. """ # TODO-3 simplify this method unit_id = unit['entity_id'] query = (Card.start_accepted_query() .filter({'unit_id': unit_id}) .sample(10)) # TODO-2 index # TODO-3 does this belong as a model method? # TODO-2 is the sample value decent? # TODO-2 has the learner seen this card recently? cards = [Card(d) for d in query.run(database.db_conn)] if not len(cards): return None previous_response = Response.get_latest(user_id=user['id'], unit_id=unit_id) if previous_response: learned = previous_response['learned'] # Don't allow the previous card as the next card cards = [ card for card in cards if card['entity_id'] != previous_response['card_id'] ] else: learned = init_learned shuffle(cards) assessment, nonassessment = partition(cards, lambda c: c.has_assessment()) choose_assessment = random() < p_assessment_map[floor(learned * 10)] if choose_assessment: if not len(assessment): return nonassessment[0] for card in assessment: params = CardParameters.get(entity_id=card['entity_id']) guess = params.get_distribution('guess').get_value() slip = params.get_distribution('slip').get_value() correct = calculate_correct(guess, slip, learned) if 0.25 < correct < 0.75: return card return assessment[0] if len(nonassessment): return nonassessment[0] if len(assessment): return assessment[0] return None
async def execute(self, request): if request.get_method == ALLOWED_METHODS.get('HEAD'): # print('Request: HEAD') return await self.execute_head(request) elif request.get_method == ALLOWED_METHODS.get('GET'): # print('Request: GET') return await self.execute_get(request) else: # print('Request: Unknown') return Response(ALLOWED_CODES.get(405), request.get_protocol, request.get_connection)
async def execute(self, request: Request) -> Optional[Response]: if request.method not in ('GET', 'HEAD'): return Response(status_code=StatusCodes.NOT_ALLOWED, protocol=request.protocol) if request.method == 'HEAD': return await self._execute_head_request(request=request) elif request.method == 'GET': return await self._execute_get_request(request=request)
def main(): url = 'https://www.westerncalendar.uwo.ca/Courses.cfm?Subject=COMPSCI&SelectedCalendar=Live' scraper = Scraper(url) course_headers = scraper.get_course_headers_list() course_details = scraper.get_course_details_list() response = Response( transformer.generate_course_summary_list(course_headers, course_details)) json_response = json.dumps(vars(response), default=lambda x: x.__dict__, indent=4) print(json_response)
def open_connection(socket, client_conn, data, router): request = None try: payload = json.loads(data) request = Request(**payload) request.connection = client_conn try: response = router.resolve(request) if response != None: socket.sendto(response.encode(), client_conn) except Exception as e: print(e) socket.sendto( Response(code=codes.INTERNAL_ERROR, body="Internal error").encode(), client_conn) except Exception as e: print(e) socket.sendto( Response(code=codes.BAD_REQUEST, body="Invalid request").encode(), client_conn)
def get(self): session = self.backend.get_session() response = Response() try: username = self.get_argument('username', None, True) password = self.get_argument('password', None, True) user = session.query(User).filter(User.username == username).one() if user.check_password(password): session.query(UserToken).filter(UserToken.user_id == user.id).delete() token = UserToken.generate_token_for_user(user) session.add(token) session.commit() response.add_data(token.as_dict()) else: raise NoResultFound except NoResultFound: response.add_error_message('User does not exist') except IntegrityError: response.add_error_message('Token already exists. Retry') except Exception: response.add_error_message('Exception while generating a token') finally: session.rollback() self.write(response.as_dict())
def get(self): session = self.backend.get_session() response = Response() try: username = self.get_argument('username', None, True) password = self.get_argument('password', None, True) user = User.register({'username': username, 'password': password}) session.add(user) session.commit() response.add_data(user.as_dict()) except IntegrityError: response.add_error_message('Username already exists') except Exception: response.add_error_message('Exception while adding a new user') finally: session.rollback() self.write(response.as_dict())
def post(self, cls, slug=None): session = self.backend.get_session() response = Response() cls_obj = getattr(sys.modules[__name__], cls) if inspect.isclass(cls_obj): try: obj = cls_obj() obj.update(self.request.arguments) session.add(obj) session.commit() response.add_data(obj.as_dict()) except: session.rollback() response.add_error_message('Exception while fetching cards') else: response.add_error_message('No such class %s' % cls) self.write(response.as_dict())
def new_session(user, message, response): sms_session = Session(user_id=user.id, interval_id=user.interval.id) models.storage.new(sms_session) models.storage.save() if message.strip().lower() == user.predictor.name: sms_response = Response(session_id=sms_session.id, predictor_id=user.predictor.id, user_id=user.id, message=message, twilio_json="{}") models.storage.new(sms_response) models.storage.save() else: response.message('This should be the predictor.')
def test_response(db_conn, responses_table): """ Expect to record the user's response. """ response, errors = Response.insert(db_conn, { 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'score': 0.9, 'learned': 0.9, }) assert len(errors) == 1 response['response'] = 42 response, errors = response.save(db_conn) assert len(errors) == 0
def test_unit(db_conn, responses_table): """ Expect to require a unit ID. """ response, errors = Response.insert(db_conn, { 'user_id': 'A', 'card_id': 'BC', 'response': 42, 'score': 0.9, 'learned': 0.9, }) assert len(errors) == 1 response['unit_id'] = 'A24JLD' response, errors = response.save(db_conn) assert len(errors) == 0
def test_card(db_conn, responses_table): """ Expect to require a card ID. """ response, errors = Response.insert({ 'user_id': 'A', 'unit_id': 'RM', 'response': 42, 'score': 0.9, 'learned': 0.9, }) assert len(errors) == 1 response['card_id'] = 'AFJ' response, errors = response.save() assert len(errors) == 0
def test_unit(db_conn, responses_table): """ Expect to require a unit ID. """ response, errors = Response.insert({ 'user_id': 'A', 'card_id': 'BC', 'response': 42, 'score': 0.9, 'learned': 0.9, }) assert len(errors) == 1 response['unit_id'] = 'A24JLD' response, errors = response.save() assert len(errors) == 0
def test_response(db_conn, responses_table): """ Expect to record the user's response. """ response, errors = Response.insert({ 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'score': 0.9, 'learned': 0.9, }) assert len(errors) == 1 response['response'] = 42 response, errors = response.save() assert len(errors) == 0
def handler(event, context): prospect = json.loads(event['body']) print(event) # todo move jwt functionality into a service class to keep things dry try: # todo make jwt secret an env var jwt.decode(event['headers']['Authorization'], 'paigeleah1') except Exception as e: print('Error: jwt did not decode correctly - {}'.format(e)) # todo refactor Response, it ain't pretty atm return Response(ErrorResponses.NOT_AUTHORIZED.value, status_code=401).to_json() prospect_service = ProspectService() api_response = prospect_service.create_prospect(prospect) return api_response.to_json()
def test_get_latest(db_conn, responses_table): """ Expect to get the latest response by user and unit. """ responses_table.insert([{ 'id': 'A', 'user_id': 'abcd1234', 'unit_id': 'apple', 'created': r.now(), 'modified': r.now(), }, { 'id': 'B', 'user_id': 'abcd1234', 'unit_id': 'banana', 'created': r.now(), 'modified': r.now(), }]).run(db_conn) assert Response.get_latest(db_conn, 'abcd1234', 'apple')['id'] == 'A'
def test_get_latest(db_conn, responses_table): """ Expect to get the latest response by user and unit. """ responses_table.insert([{ 'id': 'A', 'user_id': 'abcd1234', 'unit_id': 'apple', 'created': r.now(), 'modified': r.now(), }, { 'id': 'B', 'user_id': 'abcd1234', 'unit_id': 'banana', 'created': r.now(), 'modified': r.now(), }]).run(db_conn) assert Response.get_latest('abcd1234', 'apple')['id'] == 'A'
def test_score(db_conn, responses_table): """ Expect to have a score between 0 and 1 (including). """ response, errors = Response.insert(db_conn, { 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'response': 42, 'learned': 0.9, }) assert len(errors) == 1 response['score'] = 1.1 response, errors = response.save(db_conn) assert len(errors) == 1 response['score'] = 0 response, errors = response.save(db_conn) assert len(errors) == 0 response['score'] = 1 response, errors = response.save(db_conn) assert len(errors) == 0
def test_score(db_conn, responses_table): """ Expect to have a score between 0 and 1 (including). """ response, errors = Response.insert({ 'user_id': 'A', 'card_id': 'BC', 'unit_id': 'RM', 'response': 42, 'learned': 0.9, }) assert len(errors) == 1 response['score'] = 1.1 response, errors = response.save() assert len(errors) == 1 response['score'] = 0 response, errors = response.save() assert len(errors) == 0 response['score'] = 1 response, errors = response.save() assert len(errors) == 0
def answer(self, request: Request): ip, port = request.connection p = Player(ip, port, "") result = [player for player in self.players if p == player] if len(result) == 0: return Response(code=codes.NOT_ALLOWED, body="You aren't in this room") elif not self.running and self.last_question == None: return Response(code=codes.NOT_RUNNING, body="Game ins't started yet") elif self.round_hit: return Response(code=codes.ALREADY_EXISTS, body="Someone alrady won") player = result[0] for ans in self.last_question.answers: if ans.player == player: return Response(code=codes.ALREADY_EXISTS, body="You already answered") if isinstance(request.body, dict): answer_obj = request.body.get("answer") if answer_obj: # Add new answer in actual question self.last_question.answers.append( Answer(player, answer_obj, answer_obj == self.last_question.correct_code)) if answer_obj == self.last_question.correct_code: self.round_hit = True return Response(code=codes.SUCCESS, body="OK") # Return invalid parameters return Response(code=codes.INVALID_PARAMETERS, body="Invalid params")
def put(self, cls, slug=None): session = self.backend.get_session() response = Response() cls_obj = getattr(sys.modules[__name__], cls) if inspect.isclass(cls_obj): try: if slug: obj = session.query(cls_obj).filter(cls_obj.id == slug).one() obj.update(self.request.arguments) session.add(obj) session.commit() response.add_data(obj.as_dict()) else: response.add_error_message('Missing %s id' % cls) except NoResultFound: response.add_error_message('Missing %s' % cls) except: response.add_error_message('Exception while fetching %s' % cls) finally: session.rollback() else: response.add_error_message('No such class %s' % cls) self.write(response.as_dict())
def get(self, cls, slug=None): session = self.backend.get_session() response = Response() cls_obj = getattr(sys.modules[__name__], cls) if inspect.isclass(cls_obj): try: objs = session.query(cls_obj) if slug: obj = objs.filter(cls_obj.id == slug).one() response.add_data(obj.as_dict()) else: response.add_data([obj.as_dict() for obj in objs]) except NoResultFound: response.add_error_message('No such %s' % cls) except: response.add_error_message('Exception while fetching %s' % cls) else: response.add_error_message('No such class %s' % cls) self.write(response.as_dict())
def resolve(self, request) -> Response: for route in self.routes: if route.route == request.route and request.method in route.methods: return route.callback(request) return Response(code=codes.NOT_FOUND, body=f"Not found {request.route}")
def sms(): session, counter, consent, name_req = get_session() response = MessagingResponse() phone_number = request.form['From'] message = request.form['Body'] user = find_user_by_phone(phone_number) if user: if not user.predictor and not user.outcome: response.message( "Hi {}. You need to set up your variables first: {}".format( user.username, SITE_URL)) elif message.strip().lower() != user.predictor.name and message.strip( ).lower() != user.outcome.name: response.message('That does not match your variables. Try again.') else: user.sessions.sort(key=lambda sess: sess.updated_at, reverse=True) if message.strip().lower() == user.predictor.name: if len(user.sessions ) == 0 or user.sessions[0].complete is True: new_session(user, message, response) elif user.sessions[0].complete is False: if session_expired(user.sessions[0].created_at, user.sessions[0].interval.duration): user.sessions[0].complete = True new_session(user, message, response) else: response.message( 'We were expecting outcome: {}'.format( user.outcome.name)) elif message.strip().lower() == user.outcome.name: if len(user.sessions ) == 0 or user.sessions[0].complete is True: response.message('We were expecting predictor: {}'.format( user.predictor.name)) elif user.sessions[0].complete is False: if session_expired(user.sessions[0].created_at, user.sessions[0].interval.duration): user.sessions[0].complete = True response.message( 'We were expecting predictor: {}'.format( user.predictor.name)) else: sms_response = Response(session_id=user.sessions[0].id, outcome_id=user.outcome.id, user_id=user.id, message=message, twilio_json="{}") models.storage.new(sms_response) user.sessions[0].complete = True models.storage.save() elif consent is True and name_req is True: access_code = binascii.hexlify(os.urandom(8)).decode() session['access-code'] = access_code user = User() user.username = message.strip() user.phone_number = phone_number user.access_code = access_code models.storage.new(user) models.storage.save() session['user-id'] = user.id response.message( "Welcome {}! Please go to: {}/register/?access-code={}".format( user.username, SITE_URL, access_code)) elif consent is True and name_req is False: session['name_req'] = True if message.strip().lower() == 'yes': session['consent'] = True response.message("What's your name?") elif message.strip().lower() == 'no': response.message("Sorry to hear that. Bye.") else: response.message("Would you like to enroll in rel8? [Yes, No]") session['consent'] = True return str(response)