示例#1
0
    def test_model_eq(self):
        resource1 = Resource(ID=1, name="Resource1", resource_type="ROOM")
        resource2 = Resource(ID=1, name="Resource1", resource_type="ROOM")
        resource3 = Resource(ID=1, name="Resource3", resource_type="ROOM")
        self.assertEqual(resource1, resource2)
        self.assertNotEqual(resource1, resource3)

        date = QtCore.QDate.currentDate()
        start_time = QtCore.QTime(8, 0)
        end_time = QtCore.QTime(9, 0)
        start = QtCore.QDateTime(date, start_time)
        end = QtCore.QDateTime(date, end_time)
        reservation1 = Reservation(ID=1,
                                   resource=resource1,
                                   start=start,
                                   end=end)
        reservation2 = Reservation(ID=1,
                                   resource=resource2,
                                   start=start,
                                   end=end)
        reservation3 = Reservation(ID=1,
                                   resource=resource3,
                                   start=start,
                                   end=end)
        self.assertEqual(reservation1, reservation2)
        self.assertNotEqual(reservation1, reservation3)
示例#2
0
def store_scene_json():
    from models import Resource
    from docs import Blob
    from application import db

    json_data = json.loads(request.data)
    data = json_data['scene']
    name = json_data['name']
    type = 'scene'
    tags = 'scene json plain'
    blob_key = Blob(json.dumps(data)).save()
    resource = Resource(name=name, type=type, blob_key=blob_key, tags=tags)
    db.session.add(resource)
    db.session.commit()
    resource_url = url_for('resource.get_by_name', resource_name=name)
    resource_url_base64 = base64.encodestring(resource_url)
    view_url = url_for('player', path=resource_url_base64)
    result = json.dumps({
        "success": True,
        "data": {
            "resource_url": resource_url,
            "base64_resource_url": resource_url_base64,
            "resource_id": resource.id,
            "view_url": view_url
        }
    })
    return result
示例#3
0
文件: views.py 项目: sgml/simpledav
    def put(self):
        """Uploads a file."""
        path = self.request_path
        parent_path = os.path.dirname(path)

        # anything at this path already?
        existing_resource = Resource.get_by_path(path)

        if existing_resource:
            existing_resource.delete_recursive()

        # fetch parent
        if parent_path:
            parent = Resource.get_by_path(parent_path)
            if not parent or not parent.is_collection:
                return self.response.set_status(
                    409, "Conflict")  # must create parent folder first
        else:
            parent = Resource.root()

        logging.info("Creating resource at %s" % path)
        data = ResourceData(blob=self.request.body)
        data.put()

        resource = Resource(path=path, parent_resource=parent, data=data)
        resource.content_length = len(self.request.body)
        resource.put()

        self.response.set_status(201, 'Created')
示例#4
0
 def test_get_reservations(self):
     customer = Customer(name='Teemu Teekkari',
                         email='teemu.teekkari@aalto fi')
     service1 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     service2 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     self.db.save(service1)
     self.db.save(service2)
     added_reservations = []
     date = QtCore.QDate.currentDate()
     resource = Resource(name="Resource1", resource_type="ROOM")
     for x in range(8, 19):
         start_time = QtCore.QTime(x, 0)
         end_time = QtCore.QTime(x, 59)
         start = QtCore.QDateTime(date, start_time)
         end = QtCore.QDateTime(date, end_time)
         new_reservation = Reservation(customer=customer,
                                       resource=resource,
                                       start=start,
                                       end=end,
                                       services=[service1, service2])
         self.db.save(new_reservation)
         added_reservations.append(new_reservation)
     reservations = self.db.get_reservations()
     for i in range(len(reservations)):
         self.assertEqual(reservations[i], added_reservations[i])
示例#5
0
def add_resource():
    if request.method == 'GET':
        return render_template("form.html",
                               action="Add",
                               resource={},
                               tag="",
                               message="")
    data = request.form.to_dict(flat=True)
    data['owner_id'] = current_user.id
    #print data
    message = valid_resource_time(data['available_start'],
                                  data['available_end'])
    if len(data['name']) == 0:
        message = "name can't be empty"
    if message != "":
        return render_template("form.html",
                               action="Add",
                               resource={},
                               tag="",
                               message=message)
    resource = Resource()
    resource.deserialize(data)
    tag_list = data['tag'].split()
    for tag_name in tag_list:
        tag = db.session.query(Tag).filter_by(value=tag_name.lower()).first()
        if not tag:
            tag = Tag(tag_name.lower())
            db.session.add(tag)
        resource.tags.append(tag)
    db.session.add(resource)
    try:
        db.session.commit()
    except:
        db.session.rollback()
    return redirect(url_for('.get_resources', id=resource.id))
示例#6
0
文件: views.py 项目: sgml/simpledav
    def mkcol(self):
        """Creates a subdirectory, given an absolute path."""
        path = self.request_path
        parent_path = os.path.dirname(path)

        # check for duplicate
        if Resource.exists_with_path(path):
            return self.response.set_status(405, "Method Not Allowed")

        # fetch parent
        if parent_path:
            parent = Resource.get_by_path(parent_path)
            if not parent:
                return self.response.set_status(
                    409, "Conflict")  # must create parent folder first
        else:
            parent = Resource.root()

        logging.info("Creating dir at %s" % path)
        collection = Resource(path=path,
                              parent_resource=parent,
                              is_collection=True)
        collection.put()

        self.response.set_status(201, 'Created')
示例#7
0
def add():
    if not g.user.is_authenticated():
        return render_template('add.html')
    if request.method == 'GET':
        return render_template('add.html')

    resource_type = request.form['resource_type']
    url = request.form['url'].strip()
    resource = Resource.query.filter_by(resource_type=resource_type,
                                        url=url).first()
    if resource is not None:
        flash('service already registered (%s, %s)' % (resource_type, url),
              'danger')
        if 'resource_type' in request.args:
            rtype = request.args.get('resource_type')
            return redirect(url_for('add', resource_type=rtype))
        return redirect(url_for('add'))

    [title, success, response_time, message,
     start_time] = run_test_resource(resource_type, url)

    resource_to_add = Resource(current_user, resource_type, title, url)
    run_to_add = Run(resource_to_add, success, response_time, message,
                     start_time)

    DB.session.add(resource_to_add)
    DB.session.add(run_to_add)
    try:
        DB.session.commit()
        flash('service registered (%s, %s)' % (resource_type, url), 'success')
    except Exception, err:
        DB.session.rollback()
        flash(str(err), 'danger')
示例#8
0
    def payoutResources(camps):
        """ Grabs all of the camp type structures and gives resources to owners."""
        # TODO: If this starts to become costly, look into optimizing this via
        # Keys-only queries.

        logging.info('called it')

        # map the players that need to updated into a cache.
        players_to_update = {}
        # Map the resources that need to be updated into a cache.
        resources_to_update = {}

        for camp in camps:
            logging.info('camp: ' + str(camp))
            # TODO: Add some contested area checking.
            # TODO: Add error checking on all of this.
            # Get the player who owns camp, first from the cache, then the store.
            owner_key = camp.owner_key
            owner = None
            if owner_key in players_to_update:
                owner = players_to_update[owner_key]
            else:
                owner = camp.owner_key.get()
            tile_resource = camp.harvesting_camp_data.tile_resource_key.get()
            template_key = tile_resource.resource_template

            # If the player already has the resource, up the quantity.
            for resource_key in owner.resources:
                # Get the resource from the cache first, otherwise get it from store.
                resource = None
                if resource_key in resources_to_update:
                    logging.info('getting resource from dict')
                    resource = resources_to_update[resource_key]
                else:
                    logging.info('getting resource from resource_key: ' +
                                 str(resource_key))
                    resource = resource_key.get()
                if not resource:
                    logging.error('Resource is None. Key is: ' +
                                  str(resource_key))
                    continue
                if resource.resource_template == template_key:
                    resource.quantity += determineHarvestRate(tile_resource)
                    resources_to_update[resource_key] = resource
                    # In python, if you break a for loop, the else does not trigger.
                    # This is the for/else logic...
                    # http://book.pythontips.com/en/latest/for_-_else.html
                    break
            # If the player doesn't already have the resource, create one.
            else:
                # TODO: Find out if there is a way to put_multi this resource.
                owner.resources.append(
                    Resource(
                        resource_template=template_key,
                        quantity=determineHarvestRate(tile_resource)).put())
                players_to_update[owner_key] = owner
        # Now all of the resources and players to update should be ready to be put.
        entities_to_put = players_to_update.values(
        ) + resources_to_update.values()
        ndb.put_multi(entities_to_put)
示例#9
0
    def fetch(self, msg):
        qres = msg.get('qres')
        keep_file = msg.get('keep_file')
        keep_tempfile = msg.get('keep_tempfile')

        request = Request(self,
                          qres.url,
                          keep_file=keep_file,
                          keep_tempfile=keep_tempfile)
        request.fetch()

        res = Resource(
            url=qres.url,
            level=qres.level,
            context=qres.context,
            status_code=request.status_code,
            content_type=request.content_type,
            content_length=request.content_length,
        )
        msg = {
            'qres': qres,
            'res': res,
            'filepath': request.tempfile,
        }
        self.fetch_results.put(msg)
示例#10
0
    def to_rdf(self):
        g = Graph()
        r = Resource(g, self.uri)
        r.set(RDF.type, self.get_type())
        label = self.build_label()
        r.set(RDFS.label, Literal(label))
        r.set(CONVERIS.converisId, Literal(self.cid))

        if hasattr(self, 'url'):
            r.set(FHD.url, Literal(self.url))

        g += self.get_awardee()
        #g += self.get_awarded_by()
        #g += self.get_date_statements("award", self._v("awardedon"))

        if hasattr(self, 'awardedon'):
            start = self.awardedon
        else:
            start = None

        if hasattr(self, "endedon"):
            end = self.endedon
        else:
            end = None
        # Add datetime interval
        try:
            dti_uri, dti_g = self._dti(start, end)
            g += dti_g
            r.set(VIVO.dateTimeInterval, dti_uri)
        except TypeError:
            pass

        return g
示例#11
0
    def post(self, request):
        self.query_dict = {'classgroup': request.DATA.get('classgroup')}

        self.verify_membership()

        resource_type = request.DATA.get('resource_type')

        if resource_type != "vertical":
            raise Http404

        resource = Resource(resource_type=resource_type,
                            user=request.user,
                            classgroup=self.cg)
        resource.save()

        renderer = ResourceRenderer(resource,
                                    user=request.user,
                                    static_data={
                                        'request':
                                        request,
                                        'author_post_link':
                                        '/api/resources/author/'
                                    })

        html = renderer.author_view().get_html()

        return Response({'html': html, 'display_name': resource.display_name})
示例#12
0
def add_from_csv(txt_file):
    f = open(txt_file, 'r')
    content = f.readlines()
    f.close()

    print len(content)

    # read each line in the tab-separated txt file and add the a resource for that line
    for line in content:
        line = line.strip().split('\t')

        if line[10]:
            description = line[10]
        else:
            description = "No description available"

        resource = Resource(subject=line[0],
                            topic=line[1],
                            name=line[2],
                            link=line[3],
                            instructor=line[4],
                            college=line[5],
                            lecture_notes=line[6] == "TRUE",
                            videos=line[7] == "TRUE",
                            assignments=line[8] == "TRUE",
                            book=line[9] == "TRUE",
                            description=description)

        db.session.add(resource)

    db.session.commit()
示例#13
0
 def get_all(self):
     resources = []
     self.cursor.execute('SELECT * FROM resources ORDER BY name COLLATE NOCASE')
     rows = self.cursor.fetchall()
     for row in rows:
         resources.append(Resource(row=row))
     return resources
示例#14
0
 def accept(self):
     name = self.name.text()
     resource_type = self.resource_type.text()
     if name:
         if self.resource:
             resource = Resource(ID=self.resource.ID, name=name, resource_type=resource_type)
         else:
             resource = Resource(name=name, resource_type=resource_type)
         self.database.save(resource)
         self.information = MessageDialog("Resource added", icon=QtWidgets.QMessageBox.Information)
         self.information.show()
         self.close()
         self.parent.update()
     else:
         self.information = MessageDialog("Please fill in name.")
         self.information.show()
示例#15
0
def workspace_test():
	print_data('workspaces objects', br=False)

	for index in range(3):
		w = Workspace()
		w.name = 'New workspace name'
		w.description = 'Some new description'
		w.save()

	workspaces = Workspace.all()
	print_data('new objects -> model.all()', workspaces)

	w.name = 'Updated name'
	w.save()

	workspaces = Workspace.all()
	print_data('UPDATED -> model.all()', workspaces)

	workspaces = Workspace.get(id=w.id, name=w.name)
	print_data('GET -> model.get()', [workspaces])

	workspaces = Workspace.filter(name='New workspace name')
	print_data('FILTER -> model.filter()', workspaces)

	for index in range(2):
		o = Application()
		o.workspace_id = w.guid
		o.save()

	a = View()
	a.application_id = o.guid
	a.save()

	a = Resource()
	a.application_id = o.guid
	a.save()

	for index in range(3):
		o = Widget()
		o.workspace_id = w.guid
		o.save()

	for index in range(3):
		o = DataSource()
		o.workspace_id = w.guid
		o.save()

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('All objects in db', objects)

#	[w.delete() for w in Workspace.all()]
	workspaces = Workspace.all()
	print_data('cleaned', workspaces)

	workspaces = Workspace.filter(include_deleted=True)
	print_data('cleaned with deleted if exists', workspaces)

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('no objects left', objects)
示例#16
0
    def save(self, data: Dict):
        self.validate(data)

        try:
            resource = Resource(data)
            resource.save()
        except ValueError as err:
            raise ValidationError(message=str(err))
示例#17
0
def add_resource():
    form = AddResourceForm()
    new_resource = Resource(form.resource_name.data,
                            form.resource_content.data,
                            form.resource_source.data, 0,
                            form.lection_name.data, current_user.student_email)
    db.session.add(new_resource)
    db.session.commit()
    return redirect(url_for('main.my_resources'))
示例#18
0
def submit_resource():

    title = request.json['title']
    url = request.json['url']

    new_resource = Resource(title=title, url=url)

    db.session.add(new_resource)
    db.session.commit()

    return '200'
示例#19
0
 def create_resource(self, body):
     resource = Resource(
         name=body['name'],
         ip=body['ip'],
         in_use=body.get('in_use') or False,
         project=body['project'],
         private=body.get('private') or False,
         usable=body.get('usable') or False
     )
     db.session.add(resource)
     db.session.commit()
示例#20
0
def move_file_to_store(data, name, type, tags):
	from application import db
	from flask import url_for
	from docs import Blob
	from models import Resource

	blob_key = Blob(data).save()
	resource = Resource(name=name, type=type, blob_key=blob_key, tags=tags)
	db.session.add(resource)
	db.session.commit()
	return url_for('resource.get_by_name', resource_name=name)
示例#21
0
 def instance_by_path(self, path, underlying=None):
     if not path.startswith(self.root.path):
         return None
     rel_path = self.rel_path(path)
     if len(rel_path) == 0:
         return self.root
     names = rel_path.split('/')
     current = self.root
     for idx in range(0, len(names)):
         current = Resource(parent=current, name=names[idx], helper=self, underlying=underlying)
     return current
示例#22
0
def populate_resources():
    resourceJSON = settings.get('plugin-GoogleCalendar', 'Resources')
    resources = json.loads(resourceJSON)
    # print(resources)
    for res in resources:
        # print(res)
        if not Resource.query.filter_by(name=res['resourceName']).first():
            print(f"Adding new resource: {res['resourceName']}")
            new_resource = Resource(name=res['resourceName'],
                                    email=res['resourceEmail'])
            db.session.add(new_resource)
            db.session.commit()
示例#23
0
def _create_user(sess, username, buildings, resources):
    new_user = GameUser(username=username)
    sess.add(new_user)
    sess.flush()
    for resource, amount in resources.items():
        new_resource = Resource(user_id=new_user.id,
                                resource_type=resource,
                                amount=amount)
        sess.add(new_resource)
    for building in buildings:
        new_building = get_building_with_specs(
            new_user.id, building, config.BUILDING_CONFIG[building])
        sess.add(new_building)
示例#24
0
def serve(request, resource):
    verb = request.method

    if verb == "GET":
        try:
            entry = Resource.objects.get(key=resource)
            return HttpResponse("<p> " + str(entry.value) + "</p>" + out)
        except Resource.DoesNotExist:
            return HttpResponseNotFound("ERROR: Entrada no disponible")
    elif verb == "PUT":
        entry = Resource(key=resource, value=request.body)
        entry.save()
        return HttpResponse("Entrada insertada correctamente")
示例#25
0
def testGivePlayerResource(player_key_string):
    player = ndb.Key(urlsafe=player_key_string).get()
    player.resources.append(
        Resource(resource_template=ResourceTemplate(
            resource_type=2,
            leather_properties=LeatherProperties(
                durability=200,
                flexibility=400,
                smoothness=600,
            ),
            name='testLeather').put(),
                 quantity=150).put())
    player.put()
示例#26
0
文件: views.py 项目: cnwalker/savesun
def decrement_resources(request):
    if len(Resource.objects.all()) == 0:
        active_resource = Resource(amount=10000)
        active_resource.save()
    active_resource = Resource.objects.all()[0]

    if request.method == "GET":
        return HttpResponse(json.dumps({'value': active_resource.amount}))

    if request.method == "POST":
        data = json.loads(request.body)
        active_resource.amount -= int(data.get('decrementBy'))
        active_resource.save()
        return HttpResponse(json.dumps({'value': active_resource.amount}))
def add_contributed_resource(form):
    params = [
        'title', 'link', 'institution', 'categories', 'description',
        'submitter', 'ia', 'resource_type'
    ]
    inputs = {}
    for param in params:
        inputs[param] = form[param]

    date_added = datetime.utcnow()
    new_resource = Resource(title=inputs['title'],
                            institution=inputs['institution'],
                            description=inputs['description'],
                            link=inputs['link'],
                            submitter=inputs['submitter'],
                            iped_ad=inputs['ia'],
                            resource_type=inputs['resource_type'],
                            date_added=date_added,
                            show=False)
    categories = ast.literal_eval(inputs['categories'])
    for category in categories:
        cat = category['value']
        cat_exists = db.session.query(
            Category.id).filter_by(name=cat).scalar() is not None

        ## adding to database
        if not cat_exists:
            print('adding to database')
            new_category = Category(name=cat,
                                    slug=cat.lower().replace(' ', '_'))
            db.session.add(new_category)
            db.session.commit()
        else:
            print('cat exists')
            new_category = Category.query.get(
                db.session.query(Category.id).filter_by(name=cat).all()[0])

        new_resource.categories.append(new_category)

    ## check for duplicate resource
    error_message = 'Thank you! Your submission has been submitted for review.'
    try:
        db.session.add(new_resource)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        error_message = 'Duplicate already exists in the database. Resource not saved. Please ensure that the title and link you submit are unique.'
        print('ERROR: Duplicate resource')

    return new_resource, error_message
示例#28
0
def handle_create(request, resource_type):
    '''
    handle FHIR create operation
    '''
    correctible = (request.format == 'xml')
    valid, search_elements = fhir_parser.parse_resource(
        resource_type, request.data, correctible)
    if not valid:
        return fhir_error.inform_bad_request()

    resource = Resource(resource_type, request.data, owner_id=request.authorizer.email)
    index_resource(resource, search_elements)

    return resource.as_response(request, created=True)
示例#29
0
 def test_is_free(self):  # change resources.is_free to reservations.is_free
     customer = Customer(name='Teemu Teekkari',
                         email='teemu.teekkari@aalto fi')
     resource = Resource(name="Resource1", resource_type="ROOM")
     date = QtCore.QDate(2018, 3, 8)
     start_time = QtCore.QTime(10, 0)
     end_time = QtCore.QTime(11, 0)
     start = QtCore.QDateTime(date, start_time)
     end = QtCore.QDateTime(date, end_time)
     reservation = Reservation(customer=customer,
                               resource=resource,
                               start=start,
                               end=end)
     self.db.save(reservation)
     self.assertEqual(
         self.db.reservations.is_free(2, '2018-03-08 10:00',
                                      '2018-03-08 11:00'), True)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-07 10:00',
                                      '2018-03-07 11:00'), True)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 09:00',
                                      '2018-03-08 09:59'), True)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 11:01',
                                      '2018-03-08 12:00'), True)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 10:00',
                                      '2018-03-08 11:00'), False)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 09:00',
                                      '2018-03-08 11:00'), False)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 09:00',
                                      '2018-03-08 10:30'), False)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 10:30',
                                      '2018-03-08 12:00'), False)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 09:00',
                                      '2018-03-08 14:00'), False)
     self.assertEqual(
         self.db.reservations.is_free(1, '2018-03-08 10:30',
                                      '2018-03-08 10:59'), False)
     self.assertEqual(
         self.db.reservations.is_free(
             reservation.resource.ID,
             reservation.start.toString('yyyy-MM-dd hh:mm'),
             reservation.end.toString('yyyy-MM-dd hh:mm'),
             reservationID=reservation.ID), True)
示例#30
0
 def __init__(self, root=None, acls=None, tags=None, logger=None,
              enable_access_log=True, enable_operation_log=False):
     if root is None:
         root = Resource(name='', rid='ROOT',
                         owner=constants.SECURITY_IDENTITY_ROLE_PREFIX + constants.ROLE_NAME_ADMIN,
                         group=constants.SECURITY_IDENTITY_ROLE_PREFIX + constants.ROLE_NAME_LOGIN_USER,
                         mode=0o740, children=[], ctime=0, mtime=0, atime=0, links=[], blocks=[],
                         helper=self)
     self.root = root
     self.root.loaded = True
     self.acls = acls
     self.tags = tags
     self.logger = logger
     self.enable_access_log = enable_access_log
     self.enable_operation_log = enable_operation_log