def test_get_property_should_return_value_for_property_if_already_answered( app): # Given obj_to_save = [] user = create_user(email='*****@*****.**', username='******', password='******') obj_to_save.append(user) property_obj = Property() property_obj.property_name = 'question_1' obj_to_save.append(property_obj) BaseObject.check_and_save(*obj_to_save) user_property_obj = UserProperty() user_property_obj.user_id = user.id user_property_obj.property_id = property_obj.id user_property_obj.value = float(0.5) BaseObject.check_and_save(user_property_obj) # When property_request = req_with_auth(email='*****@*****.**', password='******') \ .get(API_URL + '/property') # Then assert property_request.status_code == 200 content = property_request.json() assert 'question_1' in content assert content['question_1'] == 0.5
def test_save_property_set_value_if_property_and_user_property_exist(app): # Given obj_to_save = [] user = create_user(email='*****@*****.**', username='******', password='******') obj_to_save.append(user) property_obj = Property() property_obj.property_name = 'question_1' obj_to_save.append(property_obj) BaseObject.check_and_save(*obj_to_save) user_property_obj = UserProperty() user_property_obj.user_id = user.id user_property_obj.property_id = property_obj.id user_property_obj.value = float(12) BaseObject.check_and_save(user_property_obj) data = dict() data['question_1'] = "0.5" # When property_request = req_with_auth(email='*****@*****.**', password='******') \ .post(API_URL + '/property', json=data) # Then assert property_request.status_code == 200 user_property_obj = UserProperty.query. \ filter_by(user_id=user.id). \ filter_by(property_id=property_obj.id). \ first() assert user_property_obj is not None assert user_property_obj.value == 0.5
def get_property(property_id=None): from models import Property if property_id == None: user_id = request.args.get('user_id') if user_id == None: return Property.get_properties() return Property.get_user_properties(user_id) if request.method == 'DELETE': return Property.delete_property(property_id) return Property.get_property(property_id)
def setUp(self): prop_dict = { 'year': '2017', 'address': "13 Drews Ct, SC", 'property_pin': '4590501053', 'zip_code': '29403', 'property_value': '20000', 'status': 'DEED', 'acreage': 0 } prop = Property(**prop_dict) prop.save()
def post(self, **kwargs): page = int(self.request.POST['page']) newstatus = int(self.request.POST['newstatus']) keys = [] for key in self.request.POST: if key != 'page' and key != 'newstatus': keys.append(key) properties = [] for property in Property.get(keys): property.status = newstatus property.save(build_index=False) # Verifico que sean mias las propiedades que voy a borrar del indice if str(property.realestate.key()) != self.get_realestate_key(): self.abort(500) properties.append(property) # Salvamos y mandamos a remover del indice def savetxn(): for key in keys: taskqueue.add(url=self.url_for('property/update_index'), params={'key': key,'action':'need_remove'}, transactional=True) db.run_in_transaction(savetxn) self.set_ok('Las propiedades fueron %s correctamente' % ('recuperadas' if newstatus == Property._NOT_PUBLISHED else 'borradas') ) return self.redirect_to('property/listpage', page=page)
def post(self, this_id=None): this_property = Property.get_by_id(normalize_id(this_id)) if (self.request.get('_method') == 'DELETE'): return self.delete() data = self.handle_upload() result = {'files': data} s = simplejson.dumps(result, separators=(',', ':')) if this_property.images: this_property.images["files"].append(data[0]) else: this_property.images = result this_property.put() redirect = self.request.get('redirect') if redirect: return self.redirect(str( redirect.replace('%s', urllib.quote(s, ''), 1) )) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s)
def create_property_resource(id): resource = Resource.query.filter_by(id=id).first() """View for create properties""" if request.method == 'POST': p_name = request.form['name'] p_value = request.form['value'] p_description = request.form['description'] resource_id = resource.id error = None if not p_name or not p_value: error = 'No mandatory property is set.' if error is not None: flash(error) else: try: property_d = Property(name=p_name, value=p_value, description=p_description, resource_id=resource_id) db.session.add(property_d) db.session.commit() return redirect(url_for('device.resource_view', id=resource.id)) except OSError as e: flash("Creation of the directory %s failed" % e) except Exception as e: flash("DB Creation Failed") return render_template('device/create_property.html', resource=resource)
def post(self, **kwargs): self.request.charset = 'utf-8' editing = 'key' in self.request.POST and len(self.request.POST['key']) if not self.form.validate(): kwargs[ 'title'] = 'Editando Propiedad' if editing else 'Nueva Propiedad' kwargs['form'] = self.form kwargs['key'] = self.request.POST['key'] if editing else None kwargs['flash'] = { 'message': 'Verifique los datos ingresados', 'type': 'error' } return self.show_property_form(**kwargs) # Actualizo o creo el model property = self.mine_or_404( self.request.POST['key']) if editing else Property.new( db.Key(self.get_realestate_key())) self.form.update_object(property) # Updateamos y mandamos a rebuild el indice si es necesario # Solo lo hacemos si se require y la propiedad esta publicada # Si se modifica una propiedad BORRADA o DESACTIVADA no se toca el indice por que no existe friend_realestates_keys = property.realestate_friend_keys() if not editing: if not realestate_can_add_public_property( self.get_realestate_key(), self.plan_max_properties): status = Property._NOT_PUBLISHED else: status = Property._PUBLISHED on_public_property_added(self.get_realestate_key()) property.status = status def savetxn(): result = property.save( build_index=True, friends=friend_realestates_keys) if editing else property.put( friends=friend_realestates_keys) if result != 'nones' and property.status == Property._PUBLISHED: taskqueue.add(url=self.url_for('property/update_index'), params={ 'key': str(property.key()), 'action': result }, transactional=True) db.run_in_transaction(savetxn) if self.request.POST['goto'] == 'go': return self.redirect_to('property/images', key=str(property.key())) self.set_ok('La propiedad fue %s ' % ( 'modificada con exito.' if editing else u'creada con exito, sera visible en el mapa dentro de la próxima hora.' )) return self.redirect_to('property/listpage', page=1)
def get(self): properties = Property.query().fetch() self.tv["properties"] = [] for this_property in properties: self.tv["properties"].append(this_property.to_object()) self.tv["current_page"] = "DASHBOARD" self.render('frontend/dashboard.html')
def add_property(request): form = PropertyForm() if request.method == 'POST': form = PropertyForm(request.POST) if form.is_valid(): property_to_add = Property(form.cleaned_data) instance = form.save() return render_to_response('property/add.html', {'form': form}, context_instance = RequestContext(request))
def analyze(): data = request.get_json() nlp = spacy.load("en_core_web_md") try: doc = nlp(data["input"]) noun = data["noun"] verb = data["verb"] except KeyError: return jsonify({"error": "Wrong data parameters"}) except TypeError: return jsonify({"error": "Wrong data format"}) elements = [] for w in doc: if "nsubj" in w.dep_: concept = Concept(w.text) elements.append(concept) if "ROOT" == w.dep_: property_ = Property(w.text) elements.append(property_) for w1 in doc: # searching for branch verb and auxiliary verb if "cc" == w1.dep_ and w1.head.text == property_.name: property_.particle = w1.text if "conj" == w1.dep_ and w1.head.text == property_.name: property_.branch = w1.text # check if concept exist if "nsubj" in w.dep_: property_.concept = w1.text if "aux" == w.dep_: aspect = Aspect(w.text) elements.append(aspect) if "auxpass" == w.dep_: aspect.particle = w.text if "adv" in w.dep_: characteristic = Characteristic(w.text) elements.append(characteristic) visitor = NaturalLanguageTransformer(f"To {verb} {noun},") for element in elements: element.accept(visitor) return jsonify({"result": visitor.body})
def test_get_property_should_return_false_for_property_is_not_answered_already( app): # Given obj_to_save = [] user = create_user(email='*****@*****.**', username='******', password='******') obj_to_save.append(user) property_obj = Property() property_obj.property_name = 'question_1' obj_to_save.append(property_obj) BaseObject.check_and_save(*obj_to_save) # When property_request = req_with_auth(email='*****@*****.**', password='******')\ .get(API_URL + '/property') # Then assert property_request.status_code == 200 content = property_request.json() assert 'question_1' in content
def get(self, **kwargs): if 'key' in kwargs: kwargs['title'] = 'Editando Propiedad' kwargs['form'] = PropertyForm(obj=self.mine_or_404(kwargs['key'])) else: if len(Property.all().filter('realestate = ',db.Key(self.get_realestate_key())).fetch(10))>=1: self.set_error(u'Comuníquese con DirectoDueño si desea publicar más de una propiedad; por correo ([email protected]) o a través del <a href="%s">panel de ayuda</a>.' % self.uri_for('backend/help')) return self.redirect_to('property/list') kwargs['title'] = 'Nueva Propiedad' kwargs['form'] = self.form return self.show_property_form(**kwargs)
def test_read_file_query(self): filepath = './data-all.csv' reader = csv.DictReader(open(filepath, 'rb')) for test_line in list(reader)[0:5]: address = test_line['Parcel Address'] year = test_line['TaxYear'] location_obj = LocationFinder(address, year, 'SC') location_dict = location_obj.getCensusStats() property = Property.create(location_dict, test_line) self.assertEqual(test_line['Parcel Address'], property.address)
def new(request): if request.method == 'GET': query = request.GET['q'] property = Property() property.postcode = query return render(request, "leader.html", {'property':property, 'comments':[], 'title':'A property at ' + query}) elif request.method == 'POST': property = Property() property.address = request.POST['new_address'] property.postcode = request.POST['postcode'] property.description = request.POST['description'] property.save() return HttpResponseRedirect(reverse('reviews:property', args=(property.id,)))
def get(self, **kwargs): re = get_or_404(kwargs['key']) blobs = [] imgs = [] props = [] for img in ImageFile.all().filter('realestate', re.key()): blobs.append(img.file.key()) imgs.append(img.key()) blobstore.delete(blobs) db.delete(imgs) props = [] for prop in Property.all().filter('realestate', re.key()): props.append(prop.key()) db.delete(props) pis = [] for pi in PropertyIndex.all().filter('realestate', re.key()): pis.append(pi.key()) db.delete(pis) invs = [] pays = [] for inv in Invoice.all().filter('realestate', re.key()): invs.append(inv) if inv.payment: pays.append(inv.payment.key()) db.delete(invs) db.delete(pays) usrs = [] for usr in User.all().filter('realestate', re.key()): usrs.append(usr) db.delete(usrs) mRealEstateFriendship = [] for fr in RealEstateFriendship.all().filter('realestates', str(re.key())): mRealEstateFriendship.append(fr) db.delete(mRealEstateFriendship) re.delete() self.response.write('borrado %s' % kwargs['key'])
def add_property(name, source, url, localization, content, price): prop = Property(name=name, source=source, url=url, localization=localization, content=content, price=price) try: s.add(prop) s.commit() except Exception, e: s.rollback() print "[ERROR] Error (%s)" % e
async def listing(request): id = request.path_params['id'] doc = request.state.db.listingsAndReviews.find_one({'_id': id}) response = Property(doc['_id'], doc['name'], doc['summary'], doc['address']['street'], str(doc['price']), str(doc['cleaning_fee']), str(doc['accommodates']), doc['images']['picture_url'], doc['amenities']) return templates.TemplateResponse('listing.html', { 'request': request, 'property': response })
def getto(self, realestate, **kwargs): # Ponemos la pantalla de disabled si esta en NO_PAYMENT if realestate.status == RealEstate._NO_PAYMENT or realestate.plan.allow_website == 0: return self.render_response('realestate/disabled.html', realestate=realestate) kwargs['realestate'] = realestate kwargs['menu_item'] = 'index' kwargs['form'] = self.form kwargs['properties'] = Property.all().filter( ' location_geocells = ', RealEstate.get_realestate_sharing_key( None, realestate=realestate)).filter( ' status = ', Property._PUBLISHED).fetch( get_props_at_home(realestate.get_web_theme())) return self.render_response('realestate/index.html', **kwargs)
def sql_dump(self, location, **kwargs): """ returns an Item suitable for adding to the database """ league = self.data.get("league", getattr(self, "league", "Standard")) try: return Item( name=self.name, type=self.type, x=self.data.get("x", None), y=self.data.get("y", None), w=self.data["w"], h=self.data["h"], rarity=self.rarity, icon=self.data["icon"], num_sockets=self.num_sockets(), socket_str=self.socket_str, is_identified=self.data["identified"], is_corrupted=self.data["corrupted"], char_location=self.char_location(), full_text=db.func.to_tsvector(self.full_text()), league=league, mods=[Modifier(**m) for m in self.mods], requirements=[Requirement(**r) for r in self.requirements], properties=[Property(**p) for p in self.properties], socketed_items=[ ItemData(x, league=league).sql_dump(location) for x in self.data.get("socketedItems", []) ], location=location, **kwargs ) # show some debugging output except: raise pprint.pprint(self.data)
def post(self): """ Create a new Experiment (with Treatments and Properties) based on the POSTed form data. The format is as follows: exp_name = main Experiment name exp_description = main Experiment description exp_instructions = Instructions on how to test the treatments to be given to the participants exp_device = Which device(s) are allowed for this experiment treat##_name = the name of treatment ## treat##_prop##_name = the name of a property to be changed for treatment ## treat##_prop##_value = the value that property ## will be set to for treatment ## There can be any number of treatments/properties, but there can be no missing values, (ie: a property name without a value) or the creation will fail. """ experiment = self.parse() if not experiment: self.redirect('error') else: exp = Experiment() exp.name = experiment.get('name') exp.description = experiment.get('description') exp.instructions = experiment.get('instructions') exp.device = experiment.get('device') exp.owner = experiment.get('owner') exp.experiment_type = experiment.get('experiment_type') exp.put() # Adding each treatment in turn for treatment in experiment.get('treatments'): t = Treatment(parent=exp.key()) t.name = treatment.get('name') t.put() for property in treatment.get('properties'): p = Property(parent=t.key()) p.name = property.get('name') p.value = property.get('value') p.put() self.redirect('view?exp_key=%s' % exp.key())
def updateProperty(request): form = PropertyForm() try: if 'owner' not in request.POST: crrProp = Property() else: pid = request.POST.get('owner', '') crrProp = Property.objects.get(pk=pid) except Property.DoesNotExist: return HttpResponse("no prtoperty with this id") crrProp.ptype = request.POST['ptype'] crrProp.location = request.POST['location'] crrProp.price = request.POST['price'] crrProp.area = request.POST['area'] crrProp.nrooms = request.POST['nrooms'] crrProp.ntoilets = request.POST['ntoilets'] crrProp.lang = request.POST['long'] crrProp.latt = request.POST['lat'] # crrProp.lang = 70 # crrProp.latt = 40 SITE_ROOT = path.dirname(path.dirname(path.realpath(__file__))) user = Client.objects.get(pk=1) crrProp.owner = user crrProp.save() fname = request.FILES['fileToUpload'].name extension = fname.split(".")[-1] imgName = str(crrProp.id) + "." + extension imgPath = SITE_ROOT + "/aqarmap/static/img/" + imgName handle_uploaded_file(request.FILES['fileToUpload'], imgPath) # form = ModelFormWithFileField(request.POST, request.FILES) # if form.is_valid(): # form.save() crrProp.img = imgName crrProp.save() return render(request, 'add-property.html', {'form': form.as_p()})
def post(self): newproperty = Property() newproperty.title = self.request.get("title").strip() newproperty.description = self.request.get("description").strip() newproperty.location = self.request.get("location").strip() newproperty.sqft = self.request.get("size").strip() newproperty.price = self.request.get("price").strip() newproperty.kind = self.request.get("type").strip() developer_key = ndb.Key("Developer", normalize_id(self.request.get("developer").strip())) newproperty.developer = developer_key amenities = PROPERTY_AMENITIES.copy() new_amenities = PROPERTY_AMENITIES.copy() for key, value in amenities.items(): if self.request.get("amenities_"+key).strip(): new_val = self.request.get("amenities_"+key).strip() else: new_val = 0 new_amenities[key] = new_val newproperty.amenities = new_amenities newproperty.put() self.redirect("/upload/"+ str(newproperty.key.id()))
def extract(): if 'email' not in session: return redirect(url_for('login')) option_list = get_properties() option_list2 = list(option_list) listofchoices = list(zip(option_list, option_list2)) propertyform = ExtractForm() propertyform.search_property.choices = listofchoices useremail = session['email'] propertyindb = Property.query.with_entities( Property.search_property, Property.brand_queries).filter_by(email=useremail).all() if request.method == 'POST': if propertyform.validate() == False: flash('Form validation not passed') return render_template('extract.html', form=propertyform, option_list=option_list) else: # get the project and API key email = session['email'] propertyindb = Property.query.filter_by( search_property=propertyform.search_property.data).first() if propertyindb is None: # save the keys into database newautho = Property(propertyform.search_property.data, propertyform.brand_queries.data, email) db.session.add(newautho) db.session.commit() else: propertyindb.brand_queries = propertyform.brand_queries.data db.session.commit() # get the web property, start and end dates from form property_uri = propertyform.search_property.data start_date = propertyform.start_date.data end_date = propertyform.end_date.data # generate a request to searchanalytics to extract data query_response = generate_request(property_uri, start_date, end_date) if query_response: flash(query_response) propertyindb = Property.query.with_entities( Property.search_property, Property.brand_queries).filter_by(email=useremail).all() # return those results return render_template('extract.html', form=propertyform, option_list=option_list, query_response=query_response, branded_queries=propertyindb) elif request.method == 'GET': return render_template("extract.html", form=propertyform, option_list=option_list, branded_queries=propertyindb)
def get_or_create_compound(smiles, clean=False, inchi_standard=False): """ Will return the compound object if found in the database or will create a new one and return it. Also returned a boolean indicating whether or not it was created. If more than one Compound object returned, an exception is raised. If clean=True, input SMILES will be desalted and neutralized. If inchi_standard=True, INCHI will be used to determine if a compounds already exists in the databases. Since the standard INCHI canonicalized tautomers, you will see collisions between tautomers such as E/Z imines. """ config.do_chiral_sss = True if clean: smiles = desalt_neutralize(smiles, return_smiles=True) compounds = Compound.objects.filter(molecule__exact=smiles) if not compounds or len(compounds) == 0: mol = Chem.MolFromSmiles(smiles) inchi = Chem.MolToInchi(mol) if inchi_standard: inchi_check = Compound.objects.filter(inchi=inchi) if len(inchi_check) == 0: pass elif len(inchi_check) == 1: return inchi_check[0], False else: matched_smiles = " AND ".join([inchi_obj.smiles for inchi_obj in inchi_check]) raise MoleculeMatchException("Inchi from SMILES {} matched an Inchi existing in database with SMILES {}".format(smiles, matched_smiles)) property = Property(amw=Chem.rdMolDescriptors.CalcExactMolWt(mol), hba=Chem.rdMolDescriptors.CalcNumHBA(mol), hbd=Chem.rdMolDescriptors.CalcNumHBD(mol), tpsa=Chem.rdMolDescriptors.CalcTPSA(mol)) property.save() bfp = Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, 512) fingerprint = Fingerprint(bfp=bfp) fingerprint.save() inchi_key = Chem.InchiToInchiKey(inchi) compound = Compound(smiles=smiles, molecule=mol, inchi=inchi, inchi_key=inchi_key, ctab=Chem.MolToMolBlock(mol), fingerprint=fingerprint, property=property) compound.save() return compound, True elif len(compounds) == 1: if inchi_standard: mol = Chem.MolFromSmiles(smiles) inchi = Chem.MolToInchi(mol) inchi_check = Compound.objects.filter(inchi=inchi) if len(inchi_check) != 1: raise MoleculeMatchException("Inchi from SMILES {} did not match one Inchi existing in database".format(smiles)) return compounds[0], False else: raise MoleculeMatchException("Exact match search returned multiple molecules")
def create_property(step=None): # Import DB from models import Property # Import Genability Interface from services.genability import GenabilityApiInterface, auth GenabilityInterface = GenabilityApiInterface(auth["app_id"], auth["app_key"]) if step is not None: if step == "1": property_name = request.json['property_name'] address_line_1 = request.json['address_line_1'] address_line_2 = request.json['address_line_2'] city = request.json['city'] zipcode = request.json['zipcode'] customer_class = request.json['customer_class'] user_id = request.json['user_id'] ### Create a genability account new_account = GenabilityInterface.create_account( account_name=property_name, address1=address_line_1, address2=address_line_2, city=city, zipcode=zipcode, country="US", customer_class=customer_class, ) # new_account = GenabilityInterface.get_account(providerAccountId='49546fc5-7101-42d6-8ab4-539f855b4918') account = json.loads(new_account) provider_account_id = account["results"][0]["providerAccountId"] ### Store account information in the local database Property.create_property(property_name, address_line_1, address_line_2, city, zipcode, provider_account_id, user_id, customer_class) ### Retrieve and return utilities associated with the account utilities = GenabilityInterface.get_utilities(zipcode) return ({ "provider_account_id": provider_account_id, "utilities": utilities }) if step == "2": provider_account_id = request.json['provider_account_id'] lseId = request.json['lseId'] utility_name = request.json['utility_name'] ### UpdateGenability and the local db GenabilityInterface.set_utility( providerAccountId=provider_account_id, lseId=lseId) Property.set_utility(provider_account_id=provider_account_id, utility_id=lseId, utility_name=utility_name) ### Retrieve and return tariffs associated with the account tariffs = GenabilityInterface.get_tariffs( providerAccountId=provider_account_id) return tariffs if step == "3": provider_account_id = request.json['provider_account_id'] master_tariff_id = request.json['master_tariff_id'] tariff_name = request.json['tariff_name'] ### Update Genability and the local db response = GenabilityInterface.set_tariff( providerAccountId=provider_account_id, masterTariffId=master_tariff_id) Property.set_tariff(provider_account_id=provider_account_id, tariff_id=master_tariff_id, tariff_name=tariff_name) return response if step == "4": provider_account_id = request.json['provider_account_id'] month_1_usage = request.json['month_1_usage'] month_2_usage = request.json['month_2_usage'] month_3_usage = request.json['month_3_usage'] ### Update Genability and the local db response = GenabilityInterface.create_electricity_profile( providerAccountId=provider_account_id, bill_1=month_1_usage, bill_2=month_2_usage, bill_3=month_3_usage) data = json.loads(response) electricity_profile_id = data["results"][0]["providerProfileId"] Property.set_electricity_profile(provider_account_id, month_1_usage, month_2_usage, month_3_usage, electricity_profile_id) return response if step == "5": provider_account_id = request.json['provider_account_id'] solar_system_kw = request.json['solar_system_kw'] solar_system_dir = request.json['solar_system_dir'] solar_system_tilt = request.json['solar_system_tilt'] # Update Genability and the local db response = GenabilityInterface.create_solar_profile( provider_account_id, solar_system_dir, solar_system_kw, solar_system_tilt) data = json.loads(response) solar_profile_id = data["results"][0]["providerProfileId"] Property.set_solar_profile(provider_account_id, solar_system_dir, solar_system_kw, solar_system_tilt, solar_profile_id) return response if step == "6": # Select the battery system specifications [power (kw), capacity (kWh) storage_specifications = { '0': ['No storage', 'No storage'], '1': ['5', '10'], '2': ['5', '13.5'], '3': ['10', '20'], '4': ['10', '27'], '5': ['20', '50'], '6': ['40', '120'], '7': ['60', '240'] } provider_account_id = request.json['provider_account_id'] storage_system = request.json["storage_system"] storage_power_kw = storage_specifications[storage_system][0] storage_capacity_kwh = storage_specifications[storage_system][1] storage_profile_id = f'{provider_account_id}-storage' edited_property = Property.set_storage_profile( provider_account_id, storage_power_kw, storage_capacity_kwh, storage_profile_id) # Retrieve the electricity 8760 data and create a template for storage data e_response = GenabilityInterface.get_electricity_profile( edited_property.electricity_profile_id) e_data = json.loads(e_response) electricity_profile = [] storage_profile = [] for hour in e_data["results"][0]["intervals"]["list"]: electricity_profile.append(hour["kWh"]["quantityAmount"]) storage_profile.append({ "fromDateTime": hour["fromDateTime"], "quantityUnit": "kWh", "quantityValue": '', "toDateTime": hour["toDateTime"] }) # Retrieve the solar 8760 data s_response = GenabilityInterface.get_solar_profile( edited_property.solar_profile_id) s_data = json.loads(s_response) solar_profile = [] for hour in s_data["results"][0]["baselineMeasures"]: solar_profile.append(hour["v"]) # Call the OSESMO to return the 8760 data for storage from services.osesmo import main if storage_system != '0': # Solar plus storage [ storage_profile_data, storage_installed_cost, solar_installed_cost ] = main(electricity_profile, solar_profile, edited_property.customer_class, float(edited_property.solar_system_kw), float(edited_property.storage_power_kw), float(edited_property.storage_capacity_kwh)) # Send the storage profile to Genability for i in range(len(storage_profile)): storage_profile[i]["quantityValue"] = str( -1 * storage_profile_data[i]) GenabilityInterface.set_storage_profile( storage_profile, provider_account_id, storage_profile_id) # Analyze the solar plus torage savings using Genability analysis endpoint response = GenabilityInterface.analyze_solar_plus_storage( provider_account_id, edited_property.tariff, edited_property.electricity_profile_id, edited_property.solar_profile_id, edited_property.storage_profile_id) else: # Solar only customer_class_dict = { "residential": "Residential", "commercial": "Commercial and Industrial" } customer_class = customer_class_dict[ edited_property.customer_class] from services.OSESMO.Solar_Installed_Cost_per_kW_Calculator import Solar_Installed_Cost_per_kW_Calculator storage_installed_cost = 0.0 solar_installed_cost = Solar_Installed_Cost_per_kW_Calculator( customer_class, float(edited_property.solar_system_kw)) # Analyze the solar savings using Genability analysis endpoint response = GenabilityInterface.analyze_solar( provider_account_id, edited_property.tariff, edited_property.electricity_profile_id, edited_property.solar_profile_id) data = json.loads(response) yearly_savings = float( data["results"][0]["summary"]["netAvoidedCost"]) monthly_savings = yearly_savings / 12 payback_period = (storage_installed_cost + solar_installed_cost) / yearly_savings # Save the reuslts to the local db finished_property = Property.set_savings_profile( provider_account_id, solar_installed_cost, storage_installed_cost, monthly_savings, payback_period) return finished_property
def get_or_create_compound(smiles, clean=False, inchi_standard=False): """ Will return the compound object if found in the database or will create a new one and return it. Also returned a boolean indicating whether or not it was created. If more than one Compound object returned, an exception is raised. If clean=True, input SMILES will be desalted and neutralized. If inchi_standard=True, INCHI will be used to determine if a compounds already exists in the databases. Since the standard INCHI canonicalized tautomers, you will see collisions between tautomers such as E/Z imines. """ config.do_chiral_sss = True if clean: smiles = desalt_neutralize(smiles, return_smiles=True) compounds = Compound.objects.filter(molecule__exact=smiles) if not compounds or len(compounds) == 0: mol = Chem.MolFromSmiles(smiles) inchi = Chem.MolToInchi(mol) if inchi_standard: inchi_check = Compound.objects.filter(inchi=inchi) if len(inchi_check) == 0: pass elif len(inchi_check) == 1: return inchi_check[0], False else: matched_smiles = " AND ".join([inchi_obj.smiles for inchi_obj in inchi_check]) raise MoleculeMatchException( "Inchi from SMILES {} matched an Inchi existing in database with SMILES {}".format( smiles, matched_smiles ) ) property = Property( amw=Chem.rdMolDescriptors.CalcExactMolWt(mol), hba=Chem.rdMolDescriptors.CalcNumHBA(mol), hbd=Chem.rdMolDescriptors.CalcNumHBD(mol), tpsa=Chem.rdMolDescriptors.CalcTPSA(mol), ) property.save() bfp = Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, 512) fingerprint = Fingerprint(bfp=bfp) fingerprint.save() inchi_key = Chem.InchiToInchiKey(inchi) compound = Compound( smiles=smiles, molecule=mol, inchi=inchi, inchi_key=inchi_key, ctab=Chem.MolToMolBlock(mol), fingerprint=fingerprint, property=property, ) compound.save() return compound, True elif len(compounds) == 1: if inchi_standard: mol = Chem.MolFromSmiles(smiles) inchi = Chem.MolToInchi(mol) inchi_check = Compound.objects.filter(inchi=inchi) if len(inchi_check) != 1: raise MoleculeMatchException( "Inchi from SMILES {} did not match one Inchi existing in database".format(smiles) ) return compounds[0], False else: raise MoleculeMatchException("Exact match search returned multiple molecules")
def add_device_api(): body = request.get_json() if 'tag' not in body or 'name' not in body: error = {"Error": "No mandatory property is set."} return make_response(jsonify(error), 400) else: tag = body['tag'] name = body['name'] description = body.get('description', None) device_parent = body.get('device_parent', None) is_gateway = body.get('is_gateway', None) ipv4_address = body.get('ipv4_address', None) properties = body.get('properties', None) resources = body.get('resources', None) devices = Device.query.filter_by(tag=tag).first() if devices is not None: error = {"Error": "The device with this tag is already exist."} return make_response(jsonify(error), 400) if device_parent is not None: device = Device.query.filter_by(id=device_parent) if device is None: error = {"Error": "The parent device ID not exist."} return make_response(jsonify(error), 400) if properties: for proper in properties: keys_list = list(proper.keys()) if "name" not in keys_list or "value" not in keys_list: error = { "Error": "The properties doesn't have the mandatory attributes." } return make_response(jsonify(error), 400) if resources: for resource in resources: keys_list = list(resource.keys()) if "tag" not in keys_list or "name" not in keys_list or "resource_type" not in keys_list: error = { "Error": "The resources doesn't have the mandatory attributes." } return make_response(jsonify(error), 400) device = Device(tag=tag, name=name, description=description, ipv4_address=ipv4_address, is_gateway=is_gateway, device_parent=device_parent) db.session.add(device) db.session.commit() if properties: for proper in properties: if "description" not in list(proper.keys()): proper_d = Property(name=proper["name"], value=proper["value"], device_id=device.id) else: proper_d = Property(name=proper["name"], value=proper["value"], description=proper["description"], device_id=device.id) db.session.add(proper_d) if resources: for resource in resources: if "description" not in list(resource.keys()): resource_d = Resource( tag=resource["tag"], name=resource["name"], resource_type=resource["resource_type"], device_id=device.id) else: resource_d = Resource( tag=resource["tag"], name=resource["name"], description=resource["description"], resource_type=resource["resource_type"], device_id=device.id) db.session.add(resource_d) db.session.commit() return jsonify(device.serialize)
def update_device_api(tag): device = Device.query.filter_by(tag=tag).first() if device is not None: body = request.get_json() propers = [] resources_list = [] #Get properties from request name = body.get('name', None) description = body.get('description', None) device_parent = body.get('device_parent', None) is_gateway = body.get('is_gateway', None) ipv4_address = body.get('ipv4_address', None) properties = body.get('properties', None) resources = body.get('resources', None) #Set properties to model if name: device.name = name if description: device.description = description if device_parent: device.device_parent = device_parent if is_gateway is not None: device.is_gateway = is_gateway if ipv4_address: device.ipv4_address = ipv4_address if properties: for proper in properties: keys_list = list(proper.keys()) if "name" not in keys_list or "value" not in keys_list: error = { "Error": "The properties doesn't have the mandatory attributes." } return make_response(jsonify(error), 400) properti = Property(name=proper["name"], value=proper["value"], description=proper.get( "description", None)) propers.append(properti) if resources: for resource in resources: keys_list = list(resource.keys()) if "tag" not in keys_list or "name" not in keys_list or "resource_type" not in keys_list: error = { "Error": "The resources doesn't have the mandatory attributes." } return make_response(jsonify(error), 400) resource_i = Resource(tag=resource["tag"], name=resource.get("name", None), resource_type=resource.get( "resource_type", None)) resources_list.append(resource_i) db.session.add(device) db.session.commit() if len(propers) > 0: for new_proper in propers: proper = Property.query.filter_by( device_id=device.id, name=new_proper.name).first() if proper is not None: proper.value = new_proper.value proper.description = new_proper.description db.session.add(proper) else: new_proper.device_id = device.id db.session.add(new_proper) db.session.commit() if len(resources_list) > 0: for new_resource in resources_list: resource = Resource.query.filter_by( device_id=device.id, tag=new_resource.tag).first() if resource is not None: print("entro aquí") resource.name = new_resource.name resource.resource_type = new_resource.resource_type if new_resource.description: resource.description = new_resource.description db.session.add(resource) else: print("entro aca") new_resource.device_id = device.id db.session.add(new_resource) db.session.commit() return jsonify(device.serialize) else: error = {"Error": "The device doesn't exist."} return make_response(jsonify(error), 400)
async def homepage(request): try: filter = request.query_params['filter'] if filter == 'under-100': data = request.state.db.listingsAndReviews.find( { '$and': [{ 'cleaning_fee': { '$exists': True } }, { 'price': { '$lt': 100 } }] }, limit=15) elif filter == 'highly-rated': data = request.state.db.listingsAndReviews.find( { '$and': [{ 'cleaning_fee': { '$exists': True } }, { 'price': { '$lt': 100 } }, { 'review_scores.review_scores_rating': { '$gt': 90 } }] }, limit=15) elif filter == 'surprise': data = request.state.db.listingsAndReviews.find( { 'cleaning_fee': { '$exists': True }, 'amenities': { '$in': ["Pets allowed", "Patio or balcony", "Self check-in"] } }, limit=15) except KeyError: data = request.state.db.listingsAndReviews.find( {'cleaning_fee': { '$exists': True }}, limit=15) response = [] for doc in data: response.append( Property(doc['_id'], doc['name'], doc['summary'], doc['address']['street'], str(doc['price']), str(doc['cleaning_fee']), str(doc['accommodates']), doc['images']['picture_url'], doc['amenities'])) return templates.TemplateResponse('index.html', { 'request': request, 'response': response })
from google.appengine.ext import db from geo.geocell import compute, MAX_GEOCELL_RESOLUTION from geo.geotypes import Point from models import Property, PropertyIndex, RealEstate from search_helper import config_array, alphabet, calculate_price fout = open('propertybulked.csv', "w") csvout = csv.writer(fout, delimiter=',', quotechar='"', lineterminator='\n') # Atributos del objeto Propiedad para imprimir en el csv del bulker. attribute_headers = [u'key'] # Itero sobre el metodo 'public_attributes()' de propiedad para obtener los atributos del objeto y generar el csv del bulker. # Este metodo tambien es utilizado por la librería del 'service/search', pra generar el Json. for key in Property.public_attributes(): attribute_headers.append(u'%s' % unicode(key)) # Agrego atributo realestate (que no es retornado por el método 'public_attributes()') y el string location el cual agrego a mano para generar el csv. attribute_headers.append(u'realestate') attribute_headers.append(u'location') attribute_headers.append(u'location_geocells') attribute_headers.append(u'status') # Escribo el header de los atributos a bulkear en el csv. csvout.writerow(map(lambda x: x.encode('utf8'), attribute_headers)) # Arreglo que contiene los tipos de currency. currencies = {'US': 'USD', 'PE': 'ARS', '': ''} csvreader = csv.reader(open('normalized.csv', 'r'),
def doSearch(self, cursor_key, **kwargs): query_type = self.request["query_type"] if not query_type in ['proximity', 'bounds']: return _simple_error( 'El parámetro de búsqueda debe ser "proximity" o "bounds".', code=400) if query_type == 'proximity': try: center = geotypes.Point(float(self.request['lat']), float(self.request['lon'])) except ValueError: return _simple_error( 'lat and lon parameters must be valid latitude and longitude values.', code=400) elif query_type == 'bounds': try: bounds = geotypes.Box(float(self.request['north']), float(self.request['east']), float(self.request['south']), float(self.request['west'])) except ValueError: return _simple_error( 'north, south, east, and west parameters must be valid latitude/longitude values.', code=400) max_distance = 80000 # 80 km ~ 50 mi if self.request.has_key('max_distance'): max_distance = float(self.request['max_distance']) #---extirpado-- base_query, price_data = create_query_from_dict( self.request, PropertyIndex) #---extirpado-- max_results = MAX_QUERY_RESULTS if self.request.has_key('max_results'): max_results = int(self.request['max_results']) results, the_box, new_cursor_key = Property.bounding_box_fetch( base_query, bounds, max_results=max_results, cost_function=None, cursor_key=cursor_key) total_count = 'cientos' viewing_count = len(results) return { 'properties': results, 'total_count': total_count, 'viewing': viewing_count, 'the_box': '<br/>' + the_box + '<br/><br/>cursor_key:' + str(cursor_key), 'cursor_key': new_cursor_key, 'price_data': price_data }
def load_experiment(experiment_id): experiment = Experiment.gql('WHERE __key__ = KEY(:1)', experiment_id).get() treatments = Treatment.gql('WHERE ANCESTOR IS KEY(:1)', experiment_id) properties = Property.gql('WHERE ANCESTOR IS KEY(:1)', experiment_id) return (experiment, treatments, properties)
from geocell import compute, MAX_GEOCELL_RESOLUTION from geotypes import Point from models import Property, PropertyIndex from search_helper import config_array, alphabet, calculate_price f = codecs.open('propertybulked.csv', "w", "utf-8") # Atributos del objeto Propiedad para imprimir en el csv del bulker. attribute_headers = 'key,' # Atributos del objeto Propiedad para iterar en la instancia y generar el csv del bulker. attributes = [] # Itero sobre el metodo 'public_attributes()' de propiedad para obtener los atributos del objeto y generar el csv del bulker. # Este metodo tambien es utilizado por la librería del 'service/search', pra generar el Json. for key in Property.public_attributes(): attribute_headers += '%s,' % key attributes.append(key) # Agrego atributo realestate (que no es retornado por el método 'public_attributes()') y el string location el cual agrego a mano para generar el csv. attributes.append('realestate') attribute_headers += 'realestate,location\r\n' # Escribo el header de los atributos a bulkear en el csv. f.write(attribute_headers.encode('utf-8')) # Semilla para las KEY de Property (esta semilla es utilizada por el bulker de imagenes, para tener correspondencia). seed = 1001 # contadores para mostrar luego los max. max_geocell_len = 0