示例#1
0
    def put(self):
        user = current_user()

        if not user or not user.is_admin:
            return '', 403

        prize = dbi.find_one(Prize, {'id': api.payload['id']})

        if not prize:
            return 'Can\'t find prize to update :/', 500

        sponsor = dbi.find_one(Sponsor, {'id': api.payload['sponsorId']})

        if not sponsor:
            return 'Sponsor required to update prize', 500

        dbi.update(
            prize, {
                'sponsor': sponsor,
                'name': api.payload['name'],
                'count': api.payload['count'] or 1
            })

        prizes = format_prizes(prize.challenge.active_prizes())

        return prizes, 200
示例#2
0
    def put(self):
        user = current_user()

        if not user:
            return '', 403

        payload = api.payload or {}

        check_in_id = payload.get('id')
        if not check_in_id:
            return 'CheckInId required to save user\'s answers', 500

        questions = payload.get('questions') or []
        if not questions:
            return 'Questions list required to save user\'s answers', 500

        check_in = dbi.find_one(CheckIn, {'id': check_in_id})

        if not check_in:
            logger.error('No CheckIn for id: {}'.format(check_in_id))
            return 'CheckIn Not Found', 500

        for q in questions:
            question = q.get('question')
            answer = q.get('answer')

            if not question or not answer or \
              not question.get('id') or not question.get('text') or 'text' not in answer:
                return 'Invalid question/answer format', 500

            answer_id = answer.get('id')

            # If answer already has been created, find and update it
            if answer_id:
                check_in_answer = dbi.find_one(CheckInAnswer,
                                               {'id': answer_id})

                if not check_in_answer:
                    logger.error(
                        'No CheckInAnswer for id: {}'.format(answer_id))
                    return 'Answer doesn\'t exist', 500

                dbi.update(check_in_answer, {'text': answer['text']})

            else:  # otherwise, create a new answer
                dbi.create(
                    CheckInAnswer, {
                        'user': user,
                        'check_in_question_id': question['id'],
                        'text': answer['text']
                    })

        questions = format_questions(check_in, user)

        return questions
示例#3
0
    def put(self):
        user = current_user()

        if not user or not user.is_admin:
            return '', 403

        try:
            start_date = datetime.strptime(api.payload['startDate'],
                                           '%m/%d/%y')
        except:
            return 'Invalid start date', 500

        challenge_slugs = [c['slug'] for c in api.payload['challenges']]

        school = user.school

        challenges = dbi.find_all(Challenge, {
            'school': user.school,
            'slug': challenge_slugs
        })

        i = 0
        for slug in challenge_slugs:
            challenge = [c for c in challenges if c.slug == slug][0]

            if i > 0:
                start_date = start_date + timedelta(days=7)

            end_date = start_date + timedelta(days=6)

            dbi.update(challenge, {
                'start_date': start_date,
                'end_date': end_date
            })

            i += 1

        challenges = sorted(school.active_challenges(),
                            key=attrgetter('start_date'))

        curr_week_num = current_week_num(challenges)

        challenges_data = format_challenges(challenges,
                                            user,
                                            curr_week_num=curr_week_num)

        resp = {'weekNum': curr_week_num, 'challenges': challenges_data}

        return resp
示例#4
0
  def post(self):
    user = dbi.find_one(User, {'id': api.payload['userId']})

    if not user or not user.reset_pw_secret:
      return '', 401

    provided_token = decode_url_encoded_str(api.payload['token'])

    if not auth_util.verify_secret(provided_token, user.reset_pw_secret):
      return '', 401

    user = dbi.update(user, {'reset_pw_secret': None})

    secret = auth_util.fresh_secret()
    token = dbi.create(Token, {'user': user, 'secret': secret})
    school = user.school

    response_data = {
      'user': {
        'name': user.name,
        'email': user.email,
        'isAdmin': user.is_admin
      },
      'school': {
        'name': school.name,
        'slug': school.slug
      }
    }

    return response_data, 200, {'quokka-user': auth_util.serialize_token(token.id, secret)}
示例#5
0
    def put(self):
        user = current_user()

        if not user or not user.is_admin:
            return '', 403

        challenge = dbi.find_one(Challenge, {'id': api.payload['id']})

        if not challenge:
            logger.error('No challenge found for id: {}'.format(
                api.payload['id']))
            return 'Challenge required to update text and points', 500

        dbi.update(challenge, {'suggestions': api.payload['suggestions']})

        return {'suggestions': challenge.suggestions}
示例#6
0
  def put(self):
    user = current_user()

    if not user:
      return '', 403

    updates = {
      'hashed_pw': auth_util.hash_pw(api.payload['password'])
    }

    if user.school.slug == 'rice-university' and api.payload.get('dorm'):
      updates['meta'] = {'dorm': api.payload['dorm']}

    dbi.update(user, updates)

    return '', 200
示例#7
0
def perform(repo):
    logger.info('Creating project: {}...'.format(repo))

    # Create new Project for repo
    project = dbi.create(Project, {'repo': repo})

    logger.info('Cloning repo...')

    # Clone the repo locally to access its files
    tmp_repo_dir = '{}/{}'.format(tmp_dir, project.uid)
    os.system('git clone {} {}'.format(repo, tmp_repo_dir))

    # Get a Config model instance from the project's .gab.yml file
    config_path = '{}/{}'.format(tmp_repo_dir, GAB_FILE)
    config = config_from_file.perform(config_path, project)

    logger.info('Determining volume size...')

    # Figure out which size volume you will need to hold the dataset
    dataset_size = gb2gib(get_file_size(config.dataset_loc))  # in GiB
    vol_size = int(math.ceil(dataset_size)) + 1  # adding extra GiB in volume

    # Create EC2 Volume and DB representation
    volume = create_volume.perform(project, vol_size)

    # Create EC2 API Instance and DB representation
    instance = create_instance.perform(project,
                                       image_id=API_AMI_ID,
                                       role=roles.API)

    # Wait until instance is running
    aws_instance = watch_instance_until_running.perform(instance)

    logger.info('Setting instance\'s IP...')

    # Update instance's IP
    instance = dbi.update(instance, {'ip': aws_instance.public_ip_address})

    logger.info('Attaching volume to API instance...')

    # Attach Volume to API Instance
    aws_instance.attach_volume(Device=VOLUME_DEVICE,
                               VolumeId=volume.aws_volume_id)

    # Initialize the newly attached volume on the instance
    init_attached_volume.perform(instance, config)

    logger.info('Dettaching volume from API instance...')

    # Detach the volume
    aws_instance.detach_volume(Device=VOLUME_DEVICE,
                               VolumeId=volume.aws_volume_id)

    remote_exec(instance.ip, 'git clone {} project'.format(repo))
示例#8
0
  def post(self):
    email = api.payload['email']
    user = dbi.find_one(User, {'email': email})

    if not user:
      return '', 400

    # Give user a reset password token
    user = dbi.update(user, {'reset_pw_secret': auth_util.fresh_secret()})

    # Send user an email with a link to reset pw
    user_mailer.reset_password(user)

    return '', 200
示例#9
0
  def post(self):

    email = api.payload['email'].lower()

    # Find the school they selected
    school = dbi.find_one(School, {'slug': api.payload['school']})

    # user_validation_error = user_validation.validate_user(email, school)

    # # Return user-validation error if one exists
    # if user_validation_error:
    #   return dict(error=user_validation_error), 400

    user = dbi.find_one(User, {'email': email})

    challenges = sorted(school.active_challenges(), key=attrgetter('start_date'))
    launched = len(challenges) > 0 and date.today() >= challenges[0].start_date.date() and school.launchable

    # If user doesn't exist yet, create him
    if not user:
      logger.info('Adding {} to database...'.format(api.payload['gender']))
      user = dbi.create(User, {
        'email': email,
        'name': api.payload['name'],
        'age': api.payload['age'],
        'gender': api.payload['gender'],
        'school': school
      })

      if launched:
        email_sent = user_mailer.complete_account(user)

        if email_sent:
          dbi.update(user, {'email_verification_sent': True})

    return {'launched': launched}, 201
示例#10
0
def perform(project):
    # Get the trainer instance for this project
    instance = dbi.find_one(Instance, {
        'project': project,
        'role': roles.TRAINER
    })

    if instance:
        aws_instance = ec2.Instance(instance.aws_instance_id)
    else:
        # Create instance if not there
        instance = create_instance.perform(project,
                                           image_id=TRAINER_AMI_ID,
                                           role=roles.TRAINER)

        # Wait for it to start running...
        aws_instance = watch_instance_until_running.perform(instance)

        logger.info('Setting instance\'s IP...')

        # Update the IP
        instance = dbi.update(instance, {'ip': aws_instance.public_ip_address})

    # Attach volume to trainer instance (if not already attached)
    attached_vol_ids = [v.id for v in aws_instance.volumes.all()]
    project_vol_id = project.volume.aws_volume_id

    if project_vol_id not in attached_vol_ids:
        logger.info('Attaching volume to trainer instance...')

        aws_instance.attach_volume(Device=VOLUME_DEVICE,
                                   VolumeId=project_vol_id)

    out, err = remote_exec(instance.ip, 'ls -l /usr/local/bin | grep init_vol')

    # if init_vol script doesn't exist yet, run init_attached_vol
    if not out:
        remote_exec(instance.ip, 'init_attached_vol', sudo=True)

    # Run the rest of the volume initialization scripts
    remote_exec(instance.ip, 'yes Yes | sudo init_vol')
    remote_exec(instance.ip, 'mount_dsetvol', sudo=True)

    out, err = remote_exec(instance.ip, 'ls -l | grep {}'.format(project.uid))

    # Clone the project onto the instance if not already there
    if not out:
        remote_exec(instance.ip,
                    'git clone {}.git {}'.format(project.repo, project.uid))

        # Add the files to the project that you need:
        # api.py and watcher.py

        # Add/update config vars for project (however you plan to go about doing this)

        # Remove tensorflow or tensorflow-gpu from requirements.txt if there

        remote_exec(
            instance.ip,
            'cd {} && source venv/bin/activate && pip install -r requirements.txt && pip install tensorflow-gpu'
            .format(project.uid))

    # Run train command(s) on trainer instance
    for cmd in project.config.train:
        remote_exec(instance.ip, cmd)

    # Move model from trainer instance to API instance
    api_instance = dbi.find_one(Instance, {
        'project': project,
        'role': roles.API
    })
    transfer_model.perform(instance, api_instance)

    logger.info('Stopping trainer instance...')

    # Spin down instance
    instance.stop()
示例#11
0
        print('No school named {}.'.format(args.school))
        exit(0)

    print('Finding user, {}...'.format(args.email))

    user = dbi.find_one(User, {'school': school, 'email': args.email})

    if not user:
        print('No user for that email yet...creating new user...')

        if validate_user(args.email, school):
            print('Invalid email for school')
            exit(0)

        user = dbi.create(User, {
            'school': school,
            'name': args.name,
            'email': args.email
        })

    print('Updating name and password for user...')

    hashed_pw = hash_pw(args.password)

    dbi.update(user, {
        'name': args.name,
        'hashed_pw': hashed_pw,
        'is_admin': bool(args.admin)
    })

    print('Successfully upserted user!'.format(args.email))
示例#12
0
            'A name is required for the new school. Use the --name argument.')
        exit(0)

    school = find_one(School, {'name': args.name})

    domains = None
    if args.domains:
        domains = [
            d.strip() for d in args.domains.split(',') if d.strip() != ''
        ]

    if school:
        print('School named {} already exists.'.format(args.name))

        if domains:
            school = update(school, {'domains': domains})
    else:
        # NOTE: Since most schools added to the DB early on were added manually without a created_at,
        # this will probably blow up with an error saying there's an issue with primary_key not being unique...
        # This is because it somehow doesn't "see" the other school records that were manually added and then
        # tries to create this record with a primary_id of 1, which obviously won't work. Options at this point:
        # (1) See if adding fake created_at datetimes for the schools that don't have them will fix this.
        # (2) Add the school with a SQL INSERT before running this script
        print('Creating school, {}...'.format(args.name))

        if not domains:
            print(
                'Domains are required to create a new school. Use the --domains argument.'
            )
            exit(0)