Ejemplo n.º 1
0
    def test_job_model():
        j = Job('title', '1000', 'only weeks', 'major001', datetime.now(),
                'url')
        db.session.add(j)
        db.session.commit()

        assert j in db.session
Ejemplo n.º 2
0
def create_job(
        template,
        notification_count=1,
        created_at=None,
        job_status='pending',
        scheduled_for=None,
        processing_started=None,
        original_file_name='some.csv',
        archived=False
):
    data = {
        'id': uuid.uuid4(),
        'service_id': template.service_id,
        'service': template.service,
        'template_id': template.id,
        'template_version': template.version,
        'original_file_name': original_file_name,
        'notification_count': notification_count,
        'created_at': created_at or datetime.utcnow(),
        'created_by': template.created_by,
        'job_status': job_status,
        'scheduled_for': scheduled_for,
        'processing_started': processing_started,
        'archived': archived
    }
    job = Job(**data)
    dao_create_job(job)
    return job
def save_city_given_list_of_posts(posts, month, year):
    all_cities = { city : id for (city, id) in db.session.query(City.name, City.id).all() }
    unmatched_jobs = []
    # posts is a list of tuples (html_post, plain_post, hackernews_hd)
    for post in posts:
        at_least_one_match = False
        (html_post, plain_post, hn_id) = post
        for city in all_cities:
            maybe_city = plain_post.find(city)
            if maybe_city != -1:
                if re.match(city + '([^a-z]|$)', plain_post[maybe_city:]):
                    newJob = Job(unicode(html_post), month, year, hn_id, all_cities[city])
                    db.session.add(newJob)
                    at_least_one_match = True
        if not at_least_one_match:
            unmatched_jobs.append((plain_post, hn_id))
    db.session.commit()
    db.session.close()

    if not os.path.exists('debug'):
        os.makedirs('debug')
    with open('debug/no_matches-{0}-{1}.txt'.format(month, year), 'w') as f:
        for (job, hn_id) in unmatched_jobs:
            f.write(hn_id)
            f.write(job.encode('utf-8'))
Ejemplo n.º 4
0
def list_jobs():
    if request.method == 'POST':



        # print(request.data)
        # print(type(request.data))
        data_dict = json.loads(request.data)
        # print(data_dict)
        # print(type(data_dict))
        job_object = Job(events=data_dict.get('events'), name=data_dict.get('name'),
                         out_dir=data_dict.get('out_dir'), log_dir=data_dict.get('log_dir'),
                         new_file=data_dict.get('new_file'))

        job_object.save()

        if data_dict.get('start') is True:
            job_object.start()
            started = True
        else:
            started = False

        return jsonify({'job_id': str(job_object.job_id),
                        'started': started})

    else:
        # Needs testing, potentially bad practice.
        # print([job.get() for job in Job.objects()])
        return jsonify({"jobs": [job.get() for job in Job.objects()]})
Ejemplo n.º 5
0
def sample_job(
    notify_db,
    notify_db_session,
    service=None,
    template=None,
    notification_count=1,
    created_at=None,
    job_status="pending",
    scheduled_for=None,
    processing_started=None,
    original_file_name="some.csv",
    archived=False,
):
    if service is None:
        service = create_service(check_if_service_exists=True)
    if template is None:
        template = create_template(service=service)
    data = {
        "id": uuid.uuid4(),
        "service_id": service.id,
        "service": service,
        "template_id": template.id,
        "template_version": template.version,
        "original_file_name": original_file_name,
        "notification_count": notification_count,
        "created_at": created_at or datetime.utcnow(),
        "created_by": service.created_by,
        "job_status": job_status,
        "scheduled_for": scheduled_for,
        "processing_started": processing_started,
        "archived": archived,
    }
    job = Job(**data)
    dao_create_job(job)
    return job
Ejemplo n.º 6
0
def add_job():
    user = User.query.filter_by(email=request.args.get("email")).first()
    job = Job(title=request.args.get("jobTitle"),description=request.args.get("jobDes"))
    job.users.append(user.profile)
    db.session.add(job)
    db.session.commit()
    return jsonify({'result':True})
Ejemplo n.º 7
0
def test_should_reject_notification_if_job_id_not_on_service(notify_api, notify_db, notify_db_session, notify_config):
    service = Service(
        id=1000,
        name="unrelated service",
        created_at=datetime.now(),
        active=True,
        restricted=True,
        limit=100
    )
    job = Job(id=1000, name="job test", created_at=datetime.now())
    job.service = service
    db.session.add(service)
    db.session.add(job)
    db.session.commit()
    response = notify_api.test_client().post(
        '/sms/notification',
        headers={
            'Authorization': 'Bearer 1234'
        },
        data=json.dumps({
            "notification": {
                "to": "+441234512345",
                "message": "Some message",
                "jobId": 1000
            }
        }),
        content_type='application/json'
    )

    data = json.loads(response.get_data())
    assert response.status_code == 400
    assert data['error'] == 'Invalid job id for these credentials'
Ejemplo n.º 8
0
 def test_new_tag(self):
     job = Job(uuid='uuidtest')
     tag = job.new_tag(name="Tag1")
     db.session.add(job)
     db.session.commit()
     self.assertTrue(job.tags.all()[0].name == "Tag1")
     self.assertTrue(tag.job == job)
Ejemplo n.º 9
0
def edit_job(id):
    job = Job().query.filter_by(id=id).first()
    form = EmployerPostForm()
    if form.validate_on_submit():
        if form.maxWorker.data:
            job.maxWorker = form.maxWorker.data
        job.title = form.title.data
        job.description = form.description.data
        job.jobType = form.job_type.data
        job.location = form.location.data
        job.salary = form.salary.data
        db.session.commit()
        flash('Successfully Edited Job', category='success')
        return redirect(
            url_for('users.home',
                    username=current_user.username,
                    post_page=1,
                    hired_page=1,
                    history_page=1))
    else:
        if job.maxWorker is not None:
            form.maxWorker.data = job.maxWorker
        form.title.data = job.title
        form.description.data = job.description
        form.job_type.data = job.jobType
        form.location.data = job.location
        form.salary.data = job.salary
        return render_template('edit_job.html', form=form, title='Edit Job')
Ejemplo n.º 10
0
    def launch_workflow(self):
        from .job import Job

        body = self.json

        jobs = []
        for i, node in body["nodes"].items():
            j = Job(uuid=i, workflow=self, dependencies_met=False)
            j.json = node
            j.save()
            jobs.append(j)

            # temporary property
            j.has_no_dependencies = True

        for j in jobs:
            node = body["nodes"][j.pk]
            for _, inp in node["inputs"].items():
                for c in inp["connections"]:
                    dep = Job.objects.get(pk=c["node"])
                    j.dependencies.add(dep)
                    j.has_no_dependencies = False
            j.save()

        for j in filter(lambda j: j.has_no_dependencies, jobs):
            j.dependencies_met = True
            j.save()
Ejemplo n.º 11
0
def sample_email_job(notify_db,
                     notify_db_session,
                     service=None,
                     template=None):
    if service is None:
        service = sample_service(notify_db, notify_db_session)
    if template is None:
        template = sample_email_template(
            notify_db,
            notify_db_session,
            service=service)
    job_id = uuid.uuid4()
    data = {
        'id': job_id,
        'service_id': service.id,
        'service': service,
        'template_id': template.id,
        'template_version': template.version,
        'original_file_name': 'some.csv',
        'notification_count': 1,
        'created_by': service.created_by
    }
    job = Job(**data)
    dao_create_job(job)
    return job
Ejemplo n.º 12
0
def job(id=None):
	if request.method == 'POST':
		data = request.get_json()
		# print(data)

		if 'secret' not in data or 'url' not in data or 'dom' not in data:
			print('POST to /job/ expects \'url\', \'dom\' and \'secret\'; at least one missing')
			return json.dumps({'success': False}), 400, {'ContentType': 'application/json'}
		
		# print(data['secret'])
		secret_user = User.query.filter_by(secret=data['secret']).first()
		if secret_user == None:
			print('Could not find any user associated with secret phrase:', data['secret'])
			return json.dumps({'success': False}), 400, {'ContentType': 'application/json'}

		job = Job(url=data['url'], dom=data['dom'])
		job.extracted_job_data = job_data_extractor(data['url'], data['dom'])
		job.user_id = secret_user.id
		db.session.add(job)
		db.session.commit()
		return json.dumps({'success': True}), 200, {'ContentType':'application/json'}

	else:
		job = Job.query.get(id)
		return json.dumps(job), 200, {'ContentType':'application/json'}
Ejemplo n.º 13
0
def create_job(
    template,
    notification_count=1,
    created_at=None,
    job_status="pending",
    scheduled_for=None,
    processing_started=None,
    original_file_name="some.csv",
    archived=False,
    sender_id=None,
):
    data = {
        "id": uuid.uuid4(),
        "service_id": template.service_id,
        "service": template.service,
        "template_id": template.id,
        "template_version": template.version,
        "original_file_name": original_file_name,
        "notification_count": notification_count,
        "created_at": created_at or datetime.utcnow(),
        "created_by": template.created_by,
        "job_status": job_status,
        "scheduled_for": scheduled_for,
        "processing_started": processing_started,
        "archived": archived,
        "sender_id": sender_id,
    }
    job = Job(**data)
    dao_create_job(job)
    return job
Ejemplo n.º 14
0
    def test_questions_evaluated_correctly(self):
        s = self.client.session
        newUser = AppUser(100000, "*****@*****.**", "notapassword", "Applicant", False, "Firstname", "Lastname")
        newUser.save()
        s.update({
            "id": 100000,
        })
        s.save()
        data = dict()
        testML = MLModel(1, "TestModel")
        testML.save()
        testOrganisation = Organisation(1, "TestOrg", True, "*****@*****.**", "01234567890")
        testOrganisation.save()
        testJob = Job(1, 1, 1, "TestJob", "TestDesc", "2019-03-15")
        testJob.save()

        testCV = CV(1, 1, '{"Name": "Bill", "Degree Qualification": "Computer Science BSc", "Degree Level": "1st", "University Attended": "University of Warwick", "Skills": [{"Skill": "Server setup", "Expertise": 10}, {"Skill": "Database Management", "Expertise": 10}], "Languages Known": [{"Language": "Python", "Expertise": 10}, {"Language": "Java", "Expertise": 10}, {"Language": "C#", "Expertise": 10}], "Hobbies": [{"Name": "Gaming", "Interest": 10}], "A-Level Qualifications": [{"Subject": "Computer Science", "Grade": "A"}, {"Subject": "Chemistry", "Grade": "A"}], "Previous Employment": [{"Company": "Microsoft", "Position": "CEO", "Length of Employment": 120}]}')
        test_question_one = TestQuestions(1, "What is 5 + 3?", "8", 1)
        test_question_one.save()
        test_question_two = TestQuestions(2, "What is 9 + 5?", "14", 1)
        test_question_two.save()
        test_question_three = TestQuestions(3, "What is 12 + 4?", "16", 1)
        test_question_three.save()
        test_question_four = TestQuestions(4, "What is 15 + 16?", "31", 1)
        test_question_four.save()
        data['extra_questionfield_0'] = "8"
        data['extra_questionfield_1'] = "14"
        data['extra_questionfield_2'] = "16"
        data['extra_questionfield_3'] = "73"
        response = self.client.post('/applicant/test/1/', data)
        self.assertEqual(200, response.status_code)
        newApplication = Application.objects.get(id=1)
        self.assertEqual(75.0, newApplication.answer_percent)
Ejemplo n.º 15
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('name',
                         help='The name field cannot be blank',
                         required=True)
     parser.add_argument('category_id',
                         help='The category id field cannot be blank',
                         required=True)
     parser.add_argument('employer_id',
                         help='The employer id field cannot be blank',
                         required=True)
     parser.add_argument('title',
                         help='The title field cannot be blank',
                         required=True)
     parser.add_argument('description',
                         help='The description field cannot be blank',
                         required=True)
     parser.add_argument(
         'application_deadline',
         help='The application deadline field cannot be blank',
         required=True)
     data = parser.parse_args()
     json_data = request.get_json(force=True)
     job = Job(name=json_data['name'],
               date_created=str(datetime.now()),
               category_id=json_data['category_id'],
               employer_id=json_data['employer_id'],
               title=json_data['title'],
               description=json_data['description'],
               application_deadline=json_data['application_deadline'])
     job.save()
     response = json.loads(json.dumps(job.json_dump()))
     return {"status": "success", "data": response}, 201
Ejemplo n.º 16
0
def sample_job(notify_db,
               notify_db_session,
               service=None,
               template=None,
               notification_count=1,
               created_at=None,
               job_status='pending',
               scheduled_for=None,
               processing_started=None,
               original_file_name='some.csv',
               archived=False):
    if service is None:
        service = create_service(check_if_service_exists=True)
    if template is None:
        template = create_template(service=service)
    data = {
        'id': uuid.uuid4(),
        'service_id': service.id,
        'service': service,
        'template_id': template.id,
        'template_version': template.version,
        'original_file_name': original_file_name,
        'notification_count': notification_count,
        'created_at': created_at or datetime.utcnow(),
        'created_by': service.created_by,
        'job_status': job_status,
        'scheduled_for': scheduled_for,
        'processing_started': processing_started,
        'archived': archived
    }
    job = Job(**data)
    dao_create_job(job)
    return job
Ejemplo n.º 17
0
def new_job_posting(company_name):
    company = Startup.query.filter_by(company_name=company_name).first_or_404()
    is_admin = (current_user.startup.first() == company)
    if not current_user.is_authenticated or not is_admin:
        abort(404)
    form = PostNewJobForm()
    if form.validate_on_submit():
        kwargs = {
            'name': form.name.data,
            'job_description': form.job_description.data,
            'offer_price': form.offer_price.data,
            'job_type': form.job_type.data,
            'estimated_developement_time':
            form.estimated_developement_time.data,
            'equity_job': form.equity_job.data
        }
        job = Job(**kwargs)
        job.post_job_time()
        db.session.add(job)
        company.create_job(job)
        db.session.commit()
        flash(_('Successfully created new job'))
        return redirect(url_for('employer.company', company_name=company_name))
    return render_template('new_job_listing.html',
                           title='Create new job listing',
                           form=form)
Ejemplo n.º 18
0
    def _transaction(
        self,
        project_uuid: str,
        pipeline_uuid: str,
        pipeline_name: str,
        job_name: str,
        draft: bool,
    ) -> Job:

        job_uuid = str(uuid.uuid4())
        pipeline_path = pipeline_uuid_to_path(pipeline_uuid, project_uuid)

        new_ex = Job(
            uuid=job_uuid,
            name=job_name,
            pipeline_uuid=pipeline_uuid,
            project_uuid=project_uuid,
            pipeline_name=pipeline_name,
            pipeline_path=pipeline_path,
            strategy_json="{}",
            draft=draft,
        )

        db.session.add(new_ex)

        self.collateral_kwargs["job_uuid"] = job_uuid
        self.collateral_kwargs["pipeline_uuid"] = pipeline_uuid
        self.collateral_kwargs["project_uuid"] = project_uuid

        return new_ex
Ejemplo n.º 19
0
def test_create_job_without_finished_auto_fills_field_to_false():
    test_user = test_utils.create_user("test user", "test_password")
    job = Job(config="This is a config",
              catalog_link="abc.com",
              user=test_user)

    assert not job.finished
Ejemplo n.º 20
0
def create_job(test_user, config, catalog_link, finished=False):
    job = Job(finished=finished,
              config=config,
              catalog_link=catalog_link,
              user=test_user)
    job.save()
    return job
Ejemplo n.º 21
0
def new_job():

    form = JobForm()
    form.customer_name.choices = [("", "Select Name")] + [
        (c.id, c.name) for c in Customer.query.order_by('name')
    ]
    form.project_number.choices = [("", "Select Number")] + [
        (p.id, p.number) for p in Project.query.order_by('number')
    ]
    form.project_name.choices = [("", "Select Name")] + [
        (p.id, p.name) for p in Project.query.order_by('name')
    ]

    if form.validate_on_submit():
        job = Job(project_id=form.project_name.data,
                  phase=form.phase.data,
                  job_type=form.job_type.data)
        db.session.add(job)
        db.session.commit()
        flash(
            f'Job {job.project_name()} {job.phase} {job.job_type} has been added to the database.'
        )
        return redirect(url_for('main.index'))

    return render_template('new_job.html', title='New Job', form=form)
Ejemplo n.º 22
0
def create_and_start_job(sim_id, form, extra_file=None):
    job_attrs = dict()
    data = {
        'simulator': sim_id,
        'status': 'created',
        'user_id': current_user.id,
        'attrs': job_attrs
    }
    for name, value in form.data.items():
        if name == 'name':
            data['name'] = value
        elif name == 'privacy':
            data['privacy'] = value
        elif name == 'sequence_identifier':
            # NOTE: sequence identifier is for artificialfastqgenerator where
            # this field must be the header to a sequence and it must start with >
            job_attrs[name] = str(value)[1:]
        elif isinstance(value, bool):
            # NOTE: let 1 equal true and 0 false
            job_attrs[name] = '1' if value else '0'
        elif name != 'csrf_token' and name != 'file' and name != 'submit':
            job_attrs[name] = str(value)

    if extra_file is not None:
        job_attrs['extra_file'] = 'extra_file'

    # Apply the job's tags to the dictionary to be stored in the database.
    for key in ['ref_db', 'genomics', 'tech', 'variants']:
        data[key] = SIMULATORS[sim_id][key]

    job = Job(**data)
    job.save()

    # If there is no job name, then set the job id as the job name.
    if job.name == '':
        job.name = str(job.id)
        job.save()

    client = arc.Client('newriver1.arc.vt.edu', arc.ARC_USER)
    remote_path = arc.get_remote_path(job.id)
    client.run('mkdir {}'.format(remote_path))

    # The path where all output files are written to is the project's directory.
    # NOTE: not all simulators have an input file (ex. xs)
    if hasattr(form, 'file'):
        project_dir = os.path.join(arc.ARC_DIR, str(job.id))
        filename = form.file.data.filename
        tmp_path = os.path.join('/tmp', filename)
        form.file.data.save(tmp_path)

        client.put_file(tmp_path, os.path.join(remote_path, 'input.fasta'))

    if extra_file is not None:
        tmp_path = os.path.join('/tmp', 'extra_file')
        extra_file.data.save(tmp_path)
        client.put_file(tmp_path, os.path.join(remote_path, 'extra_file'))

    client.close()
    start_job.apply_async(args=[str(job.id)])
Ejemplo n.º 23
0
def test_create_job_without_user_raises_integrity_error():
    test_user = test_utils.create_user("test user", "test_password")
    job = Job(finished=False,
              config="this is a config.",
              catalog_link="abc.com")

    with pytest.raises(django.db.utils.IntegrityError):
        job.save()
Ejemplo n.º 24
0
    def storage(self, job_dict, tag):

        for key in job_dict:
            job_dict[key] = self.switch_str(job_dict[key])
        job = Job()
        try:
            job.companyId = job_dict['companyId']
            job.positionName = job_dict['positionName']
            job.workYear = job_dict['workYear']
            job.education = job_dict['education']
            job.jobNature = job_dict['jobNature']
            job.companyLogo = job_dict['companyLogo']
            job.salary = job_dict['salary']
            job.city = job_dict['city']
            job.financeStage = job_dict['financeStage']
            job.industryField = job_dict['industryField']
            job.positionId = job_dict['positionId']
            job.approve = job_dict['approve']
            job.createTime = job_dict['createTime']
            job.positionAdvantage = job_dict['positionAdvantage']
            job.companySize = job_dict['companySize']
            job.companyLabelList = job_dict['companyLabelList']
            job.publisherId = job_dict['publisherId']
            job.score = job_dict['score']
            job.district = job_dict['district']
            job.companyShortName = job_dict['companyShortName']
            job.positionLables = job_dict['positionLables']
            job.industryLables = job_dict['industryLables']
            job.businessZones = job_dict['businessZones']
            job.longitude = job_dict['longitude']
            job.latitude = job_dict['latitude']
            job.adWord = job_dict['adWord']
            job.formatCreateTime = job_dict['formatCreateTime']
            job.hitags = job_dict['hitags']
            job.resumeProcessRate = job_dict['resumeProcessRate']
            job.resumeProcessDay = job_dict['resumeProcessDay']
            job.companyFullName = job_dict['companyFullName']
            job.imState = job_dict['imState']
            job.lastLogin = job_dict['lastLogin']
            job.explain = job_dict['explain']
            job.plus = job_dict['plus']
            job.pcShow = job_dict['pcShow']
            job.appShow = job_dict['appShow']
            job.deliver = job_dict['deliver']
            job.gradeDescription = job_dict['gradeDescription']
            job.promotionScoreExplain = job_dict['promotionScoreExplain']
            job.firstType = job_dict['firstType']
            job.secondType = job_dict['secondType']
            job.isSchoolJob = job_dict['isSchoolJob']
            job.subwayline = job_dict['subwayline']
            job.stationname = job_dict['stationname']
            job.linestaion = job_dict['linestaion']
            job.job_type = tag
        except Exception as e:
            self.logger.warning('存储失败', e)
            self.logger.warning(job_dict['publisherId'])
        self.safe_commit(job)
Ejemplo n.º 25
0
def notify_db_session(request):

    meta = MetaData(bind=db.engine, reflect=True)

    # Set up dummy org, with a service and a job
    org = Organisation(id=1234, name="org test")
    token = Token(id=1234, token="1234", type='admin')
    service = Service(
        id=1234,
        name="service test",
        created_at=datetime.utcnow(),
        token=token,
        active=True,
        restricted=False,
        limit=100
    )
    job = Job(id=1234, name="job test", created_at=datetime.utcnow(), service=service)
    notification = Notification(
        id=1234,
        to="phone-number",
        message="this is a message",
        job=job,
        status="created",
        method="sms",
        created_at=datetime.utcnow()
    )

    # Setup a dummy user for tests
    user = User(
        id=1234,
        email_address="*****@*****.**",
        mobile_number="+449999234234",
        password=generate_password_hash('valid-password'),
        active=True,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow(),
        password_changed_at=datetime.utcnow(),
        role='admin'
    )

    service.users.append(user)

    db.session.add(token)
    db.session.add(org)
    db.session.add(service)
    db.session.add(notification)
    db.session.add(job)
    db.session.add(user)
    db.session.commit()

    def teardown():
        db.session.remove()
        for tbl in reversed(meta.sorted_tables):
            db.engine.execute(tbl.delete())

    request.addfinalizer(teardown)
Ejemplo n.º 26
0
def importComments(_fileList):

    # load all cities in a dict for faster lookup
    dd = {
        city: id
        for (city, id) in db.session.query(City.name, City.id).all()
    }

    s = bs(open(os.path.join('hn-pages', _fileList)))
    t = s.title.get_text()
    title = t[t.index('(') + 1:t.index(')')].split(' ')
    month = monthify(title[0])
    year = title[1]

    # let's dig through this thing
    hnmain = s.find('table')
    outerTable = hnmain.findAll('tr')[3]
    innerTable = outerTable.findAll('table')[1]

    # inside innerTable, every <tr> is a post,
    # but the actual stuff in nested in yet another <tr> (wtf?)
    posts = innerTable.findAll('tr', recursive=False)

    with open('hn-pages/debug-{0}-{1}.txt'.format(year, month), 'w') as f:
        for p in posts:
            c = p.find('tr')
            # if the post is not a reply, process it
            if c.find(
                    lambda tag: tag.name == 'img' and int(tag['width']) == 0):
                content = c.find('span', class_='comment')
                plain = content.get_text()
                found_flag = False
                for city in dd:
                    position = plain.find(city)
                    if position != -1:
                        found_flag = True
                        if re.match(city + '([^a-z]|$)', plain[position:]):
                            # get the original HN id and push the new job
                            hn_id = c.findAll('a')[2]['href'].split('=')[1]
                            newJob = Job(unicode(content), month, year, hn_id,
                                         dd[city])
                            db.session.add(newJob)
                        else:
                            f.write('--DITCHED BY REGEX--\n')
                            f.write(plain[position:position +
                                          50].encode('utf-8'))
                            f.write('\n\n\n')
                if not found_flag:
                    f.write('--NO CITY FOUND FOR--\n')
                    f.write(plain.encode('utf-8'))
                    f.write('\n\n\n')
        # end of for p in posts
        f.write('Imported successfully!')
        db.session.commit()
        db.session.close()
Ejemplo n.º 27
0
def test_create_job_entry():
    test_user = test_utils.create_user("test user", "test_password")
    job = Job(
        finished=False,
        config="this is a config.",
        catalog_link="abc.com",
        user=test_user,
    )

    job.save()

    assert len(Job.objects.all()) == 1
Ejemplo n.º 28
0
    def __create_job_from_config(self, config):
        job = Job()
        job.number = self.__get_number_of_last_job() + 1

        job.environment = choice(config.environment)
        job.random_seed = choice(config.random_seed)
        job.number_generations = choice(config.number_generations)
        job.use_worker_processes = config.use_worker_processes

        job.optimizer_type = choice(config.optimizer_type)
        job.optimizer_population_size = choice(
            config.optimizer_population_size)
        job.optimizer_sigma = choice(config.optimizer_sigma)
        job.optimizer_checkpoint_frequency = choice(
            config.optimizer_checkpoint_frequency)
        job.optimizer_hof_size = choice(config.optimizer_hof_size)

        job.brain_type = choice(config.brain_type)
        job.brain_number_neurons = choice(config.brain_number_neurons)
        job.brain_use_bias = config.brain_use_bias
        job.brain_delta_t = choice(config.brain_delta_t)
        job.brain_neuron_activation = choice(config.brain_neuron_activation)
        job.brain_neuron_activation_inplace = config.brain_neuron_activation_inplace
        job.brain_normalize_input = config.brain_normalize_input
        job.brain_normalize_input_target = choice(
            config.brain_normalize_input_target)
        job.brain_optimize_state_boundaries = choice(
            config.brain_optimize_state_boundaries)
        job.brain_clipping_range_max = choice(config.brain_clipping_range_max)
        job.brain_clipping_range_min = choice(config.brain_clipping_range_min)
        job.brain_optimize_y0 = config.brain_optimize_y0
        job.brain_set_principle_diagonal_elements_of_W_negative = config.brain_set_principle_diagonal_elements_of_W_negative
        job.brain_w_mask = choice(config.brain_w_mask)
        job.brain_w_mask_param = choice(config.brain_w_mask_param)
        job.brain_v_mask = choice(config.brain_v_mask)
        job.brain_v_mask_param = choice(config.brain_v_mask_param)
        job.brain_t_mask = choice(config.brain_t_mask)
        job.brain_t_mask_param = choice(config.brain_t_mask_param)
        job.brain_parameter_perturbations = choice(
            config.brain_parameter_perturbations)

        job.episode_runner_type = choice(config.episode_runner_type)
        job.episode_runner_keep_env_seed_fixed_during_generation = config.episode_runner_keep_env_seed_fixed_during_generation
        job.episode_runner_number_fitness_runs = choice(
            config.episode_runner_number_fitness_runs)
        job.episode_runner_reuse_env = config.episode_runner_reuse_env
        job.episode_runner_max_steps_per_run = choice(
            config.episode_runner_max_steps_per_run)
        job.episode_runner_max_steps_penalty = choice(
            config.episode_runner_max_steps_penalty)

        return job
Ejemplo n.º 29
0
def save():
    try:
        # get headers first
        # save through headers
        # jobtitle = request.headers.get('jobtitle')
        # company = request.headers.get('company')
        # city = request.headers.get('city')
        # state = request.headers.get('state')
        # zip = request.headers.get('zip')
        # descr = request.headers.get('descr')
        # jstatus = request.headers.get('jstatus')
        # link = request.headers.get('link')
        # duties = request.headers.get('duties')
        # requi = request.headers.get('requi')
        # post_date = request.headers.get('post_date')

        # save through parameters
        jobtitle = request.args.get('jobtitle')
        company = request.args.get('company')
        city = request.args.get('city')
        state = request.args.get('state')
        zip = request.args.get('zip')
        descr = request.args.get('descr')
        jstatus = request.args.get('jstatus')
        link = request.args.get('link')
        duties = request.args.get('duties')
        requi = request.args.get('requi')
        post_date = request.args.get('post_date')

        if not jobtitle and not company and not city and not state and not zip and not descr and not jstatus and not link and not duties and not requi and not post_date:
            return jsonify({'error #301': 'Invalid params'})

        # create an event
        job = Job(jobtitle=jobtitle,
                  company=company,
                  city=city,
                  state=state,
                  zip=zip,
                  descr=descr,
                  jstatus=jstatus,
                  link=link,
                  duties=duties,
                  requi=requi,
                  post_date=post_date)

        # add to stage and commit to db
        db.session.add(job)
        db.session.commit()

        return jsonify({'success': 'job saved'})
    except:
        return jsonify({'error #303': 'job could not be saved'})
Ejemplo n.º 30
0
 def test_subcat_cat(self):
     cat = Cat(name='Web Developement')
     sub = Sub(name='Frontend')
     job = Job(name='A')
     db.session.add_all([cat, sub, job])
     db.session.commit()
     job.add_cat(cat)
     cat.assign_sub_cat(sub)
     db.session.commit()
     job.add_sub_cat(sub)
     db.session.commit()
     check = (sub in job.subs)
     self.assertTrue(check)