Exemple #1
0
 def test_length(self):
     self.assertEqual(length('1234'), 4)
     self.assertEqual(length([1, 2, 3, 4]), 4)
     self.assertEqual(length_is([], 0), True)
     self.assertEqual(length_is([], 1), False)
     self.assertEqual(length_is('a', 1), True)
     self.assertEqual(length_is('a', 10), False)
Exemple #2
0
 def test_length(self):
     self.assertEqual(length('1234'), 4)
     self.assertEqual(length([1, 2, 3, 4]), 4)
     self.assertEqual(length_is([], 0), True)
     self.assertEqual(length_is([], 1), False)
     self.assertEqual(length_is('a', 1), True)
     self.assertEqual(length_is('a', 10), False)
Exemple #3
0
def top5_films(request):
    filmsWithRating = []
    films = Pelicula.objects.all()
    top5 = []
    for film in films:
        total = 0.0
        ratings = Puntuacion.objects.filter(peliculaID=film.peliculaID)
        for rating in ratings:
            #top5.append(rating)
            total += float(rating.puntuacion)
        if length(ratings) != 0:
            filmsWithRating.append((film.titulo, total / length(ratings)))
    top5 = sorted(filmsWithRating, key=lambda x: -x[1])[:500]
    return render(request, 'top5.html', {'top5': top5})
Exemple #4
0
    def __getPropertyValues(self, transList1, transList2, i):
        _transfer1 = self.__getTransferText(transList1, transList2, i)
        _railway1 = self.__getRailwayText(transList2, i)
        _station1 = self.__getRailwayStationText(transList2, i)
        _railwayWalkMinute1Str = self.__getRailwayWalkText(transList1[i + 1])
        if length(_railwayWalkMinute1Str) > 0:
            _railwayWalkMinute1 = int(_railwayWalkMinute1Str)
        _busStation1 = self.__getBusStationText(transList1[i + 1])
        _busWalkMinute1Str = self.__getBusWalkText(transList1[i + 1])
        _busWalkMinute1 = 0
        if length(_busWalkMinute1Str) > 0:
            _busWalkMinute1 = int(_busWalkMinute1Str)

        return _transfer1, _railway1, _station1, _railwayWalkMinute1, _railwayWalkMinute1, _busStation1, _busWalkMinute1Str, _busWalkMinute1
Exemple #5
0
    def get_summary(request_id):
        
#         global_summary = ( {
#                             "name_of_sequence1" : 
#                             ( 
#                              { "album11":("plan111","plan112") },
#                              { "album12":("plan121","plan122") } 
#                             )
#                          },
#                           {
#                             "name_of_sequence2" : 
#                             ( 
#                              { "album21":("plan211","plan212") },
#                              { "album22":("plan221","plan222") } 
#                             )
#                           }               
#                            
#                            ) 
         
        request_object = Request.objects.get(id=request_id)
        sequences = Sequence.objects.filter(request=request_object) 
         
        
        global_summary = []
        aux = []
#         message = ('Void',)
#         for seq in sequences:
#             
#             for alb in Album.objects.filter(sequence=seq):
#                 
#                 global_summary = ( { seq.name : ( { alb : Plan.objects.filter(album=alb)} ) } )

        if length(sequences) != 0:
            for seq in sequences:
                albums = Album.objects.filter(sequence=seq)
                for album in albums:
                    plans = Plan.objects.filter(album=album)
                    aux.append( {album : plans} )
                global_summary.append({ seq : aux } )
       
        
#         x = {}
# 
#         for row in sequences:
#            x[row.name] = {} # derive this from something.
#            for idx, col in enumerate(row):
#                x[row.name][idx] = col
       
#         print "["+str(datetime.datetime.now())+"]"+global_summary[0].itervalues()
       
        return global_summary
Exemple #6
0
def intervalrefresh(request):
#	calculateDashboardData()
	print '========   Get data from ElectricityDashboard : start  ======='
	
	getvalues = request.POST
	siteUrl = getvalues.get('siteUrl', False)
	queryString = urlparse(getvalues["siteUrl"]).query     
	queryList = parse_qs(queryString)
	if length(queryList) > 0:
		site_name = queryList["siteid"][0]
	else:
		site_name = Site.objects.filter(id=1).values("name")[0]["name"]
        
	site_id = Site.objects.filter(name=site_name).values('id')[0]["id"]
	
	dataSet = ElectricityDashboard.objects.filter(site_id=site_id)
	
	dbLatestTime = dataSet.filter(field='lastTime').values('date_time')[0]['date_time']
	
	localTime = datetime.datetime.now()
	deltaSeconds = (localTime - dbLatestTime).total_seconds()
	deltaMinutes = deltaSeconds // 60
	
	realTimeCO2 = dataSet.filter(field='realTimeCO2').values('value')[0]['value']
	realTimeEfficiency = dataSet.filter(field='realTimeEfficiency').values('value')[0]['value']
	realTimeLoad = dataSet.filter(field='realTimeLoad').values('value')[0]['value']
	realTimePUE = dataSet.filter(field='realTimePUE').values('value')[0]['value']
	siteAbsoluteLoad = dataSet.filter(field='siteAbsoluteLoad').values('value')[0]['value']

	alarm_color = dataSet.filter(field='alarm_color').values('value')[0]['value']
	
	efficiencyTable = dataSet.filter(field='efficiencyTable').values('value')[0]['value']
	PUETable = dataSet.filter(field='PUETable').values('value')[0]['value']
	loadTable = dataSet.filter(field='loadTable').values('value')[0]['value']
	status_flag = dataSet.filter(field='status_flag').values('value')[0]['value']
	alarm_details = dataSet.filter(field='alarm_details').values('value')[0]['value']
	alarm_logs = dataSet.filter(field='alarm_logs').values('value')[0]['value']
 	
 	PUETable = json.loads(PUETable)
 	efficiencyTable = json.loads(efficiencyTable)
 	loadTable = json.loads(loadTable)
 	status_flag = json.loads(status_flag)
 	alarm_details = json.loads(alarm_details)
 	alarm_logs = json.loads(alarm_logs)
	alarm_color = json.loads(alarm_color)
	print '========   Get data from ElectricityDashboard : Finish ======='

	
	return HttpResponse(json.dumps({"PUETable": PUETable, "alarm_logs": alarm_logs, "deltaMinutes": deltaMinutes, "realTimePUE": realTimePUE, "realTimeEfficiency": realTimeEfficiency, "realTimeCO2": realTimeCO2, "realTimeLoad": realTimeLoad, "siteAbsoluteLoad": siteAbsoluteLoad, "efficiencyTable": efficiencyTable, "loadTable": loadTable, "status_flag": status_flag, "alarm_details": alarm_details, "alarm_color": alarm_color}))
    def test_check_expressions(self):
        
        expression1 = {
            'name': 'Sum',
            'type': 'float',
            'formula': 'a+b',
            'decimal_places': 3
        }
        
        expression2 = {
            'name': 'expr2',
            'type': 'float',
            'formula': 'foo(a)',
            'decimal_places': 3
        }
        
        expression3 = {
            'name': 'expr3',
            'type': 'float',
            'formula': 'a',
            'decimal_places': 3
        }

        expression4 = {
            'name': 'expr4',
            'type': 'float',
            'formula': 'log(a + 1',
            'decimal_places': 3
        }
        
        expressions = {}
        expressions[expression1['name']] = expression1
        expressions[expression2['name']] = expression2
        expressions[expression3['name']] = expression3
        expressions[expression4['name']] = expression4
        
        
        check_result = formula_service.check_expressions(expressions)
        self.assertTrue(length(check_result) == 1)
        self.assertTrue('expr4' in check_result)
Exemple #8
0
 def test_string(self):
     self.assertEqual(length("1234"), 4)
Exemple #9
0
 def test_list(self):
     self.assertEqual(length([1, 2, 3, 4]), 4)
Exemple #10
0
 def test_string(self):
     self.assertEqual(length('1234'), 4)
Exemple #11
0
 def test_safestring(self):
     self.assertEqual(length(mark_safe('1234')), 4)
Exemple #12
0
 def test_safestring(self):
     self.assertEqual(length(mark_safe('1234')), 4)
Exemple #13
0
 def test_list(self):
     self.assertEqual(length([1, 2, 3, 4]), 4)
Exemple #14
0
 def test_string(self):
     self.assertEqual(length('1234'), 4)
Exemple #15
0
 def validate(self, data):
     if length(data['content']) < 10:
         raise serializers.ValidationError("질문이 너무 짧습니다. 10자 이상 작성해주세요.")
     return data
Exemple #16
0
    def parsePropertyDetailPage(self, url):
        response = self.getResponseBs(url)
        item = SumifuMansion()

        item.pageUrl = url
        item.propertyName = response.find_all(
            "div", id="bukkenNameBlockIcon")[0].find_all("h2")[0].find_all(
                "span")[1].contents[0]
        # item.propertyName = response.xpath('//div[@id="bukkenNameBlockIcon"]/h2/span[2]/text()')[0]
        item.priceStr = response.find_all(
            "dl", id="s_summaryPrice")[0].find_all("dd")[0].find_all(
                "p")[0].find_all("em")[0].contents[0]
        # item.priceStr = response.xpath('//*[@id="s_summaryPrice"]/dd/p[1]/em/text()')[0]

        priceWork = item.priceStr.replace(',', '')
        oku = 0
        man = 0
        if u"億" in item.priceStr:
            priceArr = priceWork.split("億")
            oku = int(priceArr[0]) * 10000
            if length(priceArr[1]) != 0:
                man = int(priceArr[1])
        else:
            man = int(priceWork)
        price = oku + man
        item.price = price

        item.madori = response.find_all(
            "dl",
            id="s_summaryMadori")[0].find_all("dd")[0].find_all("em")[0].string
        # item.madori = response.xpath('//*[@id="s_summaryMadori"]/dd/em/text()')[0]
        item.senyuMensekiStr = response.find_all(
            "dl", id="s_summarySenyuMenseki")[0].find_all("dd")[0].contents[0]
        # item.senyuMensekiStr = response.xpath('//*[@id="s_summarySenyuMenseki"]/dd/text()[1]')[0]
        senyuMensekiWork = item.senyuMensekiStr.replace('m', '')
        item.senyuMenseki = Decimal(senyuMensekiWork)
        item.floorType = response.find_all(
            "dl", id="s_summaryFloor")[0].find_all("dd")[0].contents[0]
        # item.floorType = response.xpath('//*[@id="s_summaryFloor"]/dd/text()')[0]
        item.chikunengetsuStr = response.find_all(
            "dl", id="s_summaryChikunengetsu")[0].find_all("dd")[0].contents[0]
        # item.chikunengetsuStr = response.xpath('//*[@id="s_summaryChikunengetsu"]/dd/text()')[0]
        nen = int(item.chikunengetsuStr.split(u"年")[0])
        tsuki = int(item.chikunengetsuStr.split(u"年")[1].split(u"月")[0])
        item.chikunengetsu = datetime.date(nen, tsuki, 1)
        item.address = response.find_all(
            "div", id="bukkenDetailBlock")[0].find_all("div")[1].find_all(
                "dl")[5].find_all("dd")[0].contents[0]
        # item.address = response.xpath('//*[@id="bukkenDetailBlock"]/div[2]/dl[6]/dd/text()')[0]
        transList1 = []
        transList1.append(
            response.find_all("dd", id="s_summaryTransfer")[0].contents[1])
        transList1.append(
            response.find_all("dd", id="s_summaryTransfer")[0].contents[3])
        # transList1 = response.xpath('//dd[@id="s_summaryTransfer"]/text()')
        transList2 = []
        transList2.append(
            response.find_all(
                "dd", id="s_summaryTransfer")[0].contents[0].contents[0])
        transList2.append(
            response.find_all(
                "dd", id="s_summaryTransfer")[0].contents[2].contents[0])
        # transList2 = response.xpath('//dd[@id="s_summaryTransfer"]/a/text()')

        item.transfer1 = ""
        item.railway1 = ""
        item.station1 = ""
        item.railwayWalkMinute1Str = ""
        item.railwayWalkMinute1 = 0
        item.busStation1 = ""
        item.busWalkMinute1Str = ""
        item.busWalkMinute1 = 0

        item.transfer2 = ""
        item.railway2 = ""
        item.station2 = ""
        item.railwayWalkMinute2Str = ""
        item.railwayWalkMinute2 = 0
        item.busStation2 = ""
        item.busWalkMinute2Str = ""
        item.busWalkMinute2 = 0

        item.transfer3 = ""
        item.railway3 = ""
        item.station3 = ""
        item.railwayWalkMinute3Str = ""
        item.railwayWalkMinute3 = 0
        item.busStation3 = ""
        item.busWalkMinute3Str = ""
        item.busWalkMinute3 = 0

        item.transfer4 = ""
        item.railway4 = ""
        item.station4 = ""
        item.railwayWalkMinute4Str = ""
        item.railwayWalkMinute4 = 0
        item.busStation4 = ""
        item.busWalkMinute4Str = ""
        item.busWalkMinute4 = 0

        item.transfer5 = ""
        item.railway5 = ""
        item.station5 = ""
        item.railwayWalkMinute5Str = ""
        item.railwayWalkMinute5 = 0
        item.busStation5 = ""
        item.busWalkMinute5Str = ""
        item.busWalkMinute5 = 0

        for i in range(len(transList1)):
            if i == 0:
                item.transfer1, item.railway1, item.station1, item.railwayWalkMinute1Str, item.railwayWalkMinute1, item.busStation1, item.busWalkMinute1Str, item.busWalkMinute1 = self.__getPropertyValues(
                    transList1, transList2, i)
            if i == 2:
                item.transfer2, item.railway2, item.station2, item.railwayWalkMinute2Str, item.railwayWalkMinute2, item.busStation2, item.busWalkMinute2Str, item.busWalkMinute2 = self.__getPropertyValues(
                    transList1, transList2, i)
            if i == 4:
                item.transfer3, item.railway3, item.station3, item.railwayWalkMinute3Str, item.railwayWalkMinute3, item.busStation3, item.busWalkMinute3Str, item.busWalkMinute3 = self.__getPropertyValues(
                    transList1, transList2, i)
            if i == 6:
                item.transfer4, item.railway4, item.station4, item.railwayWalkMinute4Str, item.railwayWalkMinute4, item.busStation4, item.busWalkMinute4Str, item.busWalkMinute4 = self.__getPropertyValues(
                    transList1, transList2, i)
            if i == 8:
                item.transfer5, item.railway5, item.station5, item.railwayWalkMinute5Str, item.railwayWalkMinute5, item.busStation5, item.busWalkMinute5Str, item.busWalkMinute5 = self.__getPropertyValues(
                    transList1, transList2, i)

        for i, tr in enumerate(
                response.find_all("div", id="detailBlock")[0].find_all("tr")):
            for j, th in enumerate(tr.find_all("th")):
                thTitle = th.contents[0]
                tdValue = tr.find_all("td")[j].contents[0]
                if thTitle == "バルコニー面積":
                    item.barukoniMenseki = tdValue
                if thTitle == "採光方向":
                    item.saikouKadobeya = tdValue
                    temp = item.saikouKadobeya.split(u"/")
                    if len(temp) == 1:
                        item.saikou = item.saikouKadobeya
                        item.kadobeya = ""
                    else:
                        item.saikou = temp[0]
                        item.kadobeya = temp[1]
                if thTitle == "総戸数":
                    item.soukosuStr = tdValue
                    item.soukosu = int(
                        item.soukosuStr.replace(u"戸", "").strip())
                if thTitle == "管理方式/管理会社":
                    item.kanriKeitaiKaisya = tdValue
                    temp = item.kanriKeitaiKaisya.split(u"/")
                    if len(temp) == 1:
                        item.kanriKeitai = temp[0]
                        item.kanriKaisya = ""
                    else:
                        item.kanriKeitai = temp[0]
                        item.kanriKaisya = temp[1]
                if thTitle == "管理費(月額)":
                    item.kanrihiStr = tdValue
                    if "-" in item.kanrihiStr:
                        item.kanrihi = 0
                    else:
                        item.kanrihi = int(
                            item.kanrihiStr.replace(",", "").replace(u"円", ""))
                if thTitle == "修繕積立金(月額)":
                    item.syuzenTsumitateStr = tdValue
                    if "-" in item.syuzenTsumitateStr:
                        item.syuzenTsumitate = 0
                    else:
                        item.syuzenTsumitate = int(
                            item.syuzenTsumitateStr.replace(",", "").replace(
                                u"円", ""))
                if thTitle == "引渡時期":
                    item.hikiwatashi = tdValue
                if thTitle == "現況":
                    item.genkyo = tdValue
                if thTitle == "駐車場":
                    item.tyusyajo = tdValue
                if thTitle == "土地権利":
                    item.tochikenri = tdValue
        return item
Exemple #17
0
def getReport(request):
    #use to store upload data
    sitedata = {} 
    print 'start report selection==============', datetime.datetime.now()

    #Get Query String from dashboard page
    getvalues = request.POST
    # Initialize the selectors    

    queryString = urlparse(getvalues["siteUrl"]).query     
    queryList = parse_qs(queryString)
    site = queryList["siteid"][0]
    print queryList, length(queryList)
    
    if length(queryList) > 1:        

        #Set Query String from dashboard page to Report page
        fromdate = queryList["sdate"]
#        fromdate = fromdate.strftime('%m/%d/%Y')
        todate = queryList["edate"]
#        todate = todate.strftime('%m/%d/%Y')
        reportlist = queryList["type"]
        print fromdate, todate
        boxlist = selectorView.boxlist + selectorView.reportlist
        print boxlist
        reportlist = [str(i) for i in reportlist]
        print reportlist
        [boxlist.remove(i) for i in reportlist]

    else:
        #if only siteID, initialize the selectors here
        fromdate, todate, reportlist, boxlist = selectorView.dataInit(request)
        # below: validate the end date "todate" is not more than 'today'
        datepicker = getvalues.get('date', False)     # format: 08/18/2015 - 09/01/2015 
        if datepicker:
            tempdate = datepicker.split(' - ')
            fromdate = str(tempdate[0])
            todate = str(tempdate[1])
            fromdate = datetime.datetime.strptime(fromdate, '%m/%d/%Y')  # date type: datetime
            todate =  datetime.datetime.strptime(todate, '%m/%d/%Y')
            nowDate = datetime.datetime.now().date()
            if fromdate.date() > nowDate:
                fromdate = nowDate           # data type: datetime
            if todate.date() > nowDate:
                todate = nowDate
            fromdate = fromdate.strftime('%m/%d/%Y')     # data type: str
            todate = todate.strftime('%m/%d/%Y')            
                
    objIni = {"fromdate" : fromdate, "todate":todate, "reportlist":reportlist, "boxlist":boxlist}
    sitedata.update(objIni)

    # Get the values from selector

    date_new = getvalues.get('date', False)
    #click button 'go'
    if date_new:  
        print "test point"
        starttime, endtime, reportfields, data, allAlarmData = selectorView.dataSelector(request, -1, -1, [], site) # Rita added one more return item: data2 

    elif length(queryList) > 1:
        starttime, endtime, reportfields, data, allAlarmData = selectorView.dataSelector(request, datetime.datetime.strptime(fromdate[0], ISOTIMEFORMAT), datetime.datetime.strptime(todate[0], ISOTIMEFORMAT), reportlist, site)
        
    else:
        # Initialize the default data: most recent 14 days
        starttime, endtime, reportfields, data, allAlarmData = \
        selectorView.dataSelector(request, datetime.datetime.now() - datetime.timedelta(days=14), datetime.datetime.now(), selectorView.reportlist, site )

        
    objdefault = {"starttime" : starttime, "endtime":endtime, "reportfields":reportfields}
    sitedata.update(objdefault)
    
    # Views from Jason
    #calculate default report value here
    print 'start report calculate===============', datetime.datetime.now()
    print 'including following report:%s'%reportfields
    print 'selected report time is from %s to %s.'%(starttime,endtime)
    [reportviewdata, recordedEndtime]=reportViews.getFourReportData(request, starttime, endtime, data, reportfields)  # Rita added one more return item: recordedEndtime
    #print 'all data',reportviewdata
    obj = {'reportviewdata': reportviewdata}
    sitedata.update(obj)
    
    # Rita modified 
    # Calulate the Energy distribution to the current time 
    
    #obj_energy4pie=reportViews.calculateEnergy4PieChart(request, data, starttime, recordedEndtime)   # Rita modified. original: endtime
    #reportviewdata['obj_energy4pie']=obj_energy4pie
    
    '''
    objAll = {}
    for temp in reportfields:

        objname, errors = componentsview.View.Precent_View(starttime, endtime, data, temp)
        obj = { temp : {'obj' : objname, 'errors' : errors}}

        objAll.update(obj)
    '''
        
    
    # Views from Vicky
    if 'DC Efficiency' in reportfields:
        print 'DC==============', datetime.datetime.now()
        obj_dceff, errors = componentsview.View.Precent_View(starttime, recordedEndtime, data, 'DC Efficiency', site)              # Rita modified: original: endtime
        obj = {"obj_dceff" : obj_dceff}
        sitedata.update(obj)
    if 'Active Device Efficiency' in reportfields:
        print 'AD==============', datetime.datetime.now()
        obj_adeff, errors = componentsview.View.Precent_View(starttime, recordedEndtime, data, 'Active Device Efficiency', site)   # Rita modified: original: endtime
        obj = {"obj_adeff" : obj_adeff}
        sitedata.update(obj)
    if 'DC Load Rate' in reportfields: 
        print 'LOAD============', datetime.datetime.now()
        obj_dcload, errors = componentsview.View.Precent_View(starttime, recordedEndtime, data, 'DC Load Rate', site)              # Rita modified: original: endtime
        obj = {"obj_dcload" : obj_dcload}
        sitedata.update(obj)
    if 'Total Energy Consumption' in reportfields: 
        print 'TC=============', datetime.datetime.now()
        obj_tc, errors = componentsview.View.Precent_View(starttime, recordedEndtime, data, 'Total Energy Consumption', site)      # Rita modified: original: endtime
        obj = {"obj_tc" : obj_tc}
        sitedata.update(obj)

    #for alarm
    if 'Historical Event' in reportfields:
        alarmData = componentsview.View.alarm_View(allAlarmData)
        obj = {"alarmData" : alarmData}
        sitedata.update(obj)
    
    if '23:59:00' in recordedEndtime:
        recordedEndtime = datetime.datetime.strptime(recordedEndtime, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(seconds=60)
        recordedEndtime = str(recordedEndtime)
    sitedata["recordedEndtime"] = recordedEndtime
        
    print 'Finish report calculate==============', datetime.datetime.now()
    print sitedata       
    
    return HttpResponse(json.dumps(sitedata))
Exemple #18
0
 def clean_Password(self):
     Password = self.cleaned_data['Password']
     num_words = length(Password)
     if num_words < 6:
         raise forms.ValidationError("Not enough words!" +str(num_words)+Password)
     return Password