Weather data record.

        Yields:
            dict
183579
def next(self):
        
        record = self.epw_data.next()
        local_time = _muck_w_date(record)
        record['datetime'] = local_time
        # does this fix a specific data set or a general issue?
        if self.DST:
            localdt = self.local_tz.localize(record['datetime'])
            record['utc_datetime'] = localdt.astimezone(pytz.UTC)
        else:
            record['utc_datetime'] = local_time - \
                datetime.timedelta(hours=self.TZ)

        return record
992727
def gen_WS_DF(df_WS_data):
    
    df_fs = gen_FS_DF(df_WS_data)

    list_index = [('mean', 'T2'), ('max', 'T2'), ('min', 'T2'),
                  ('mean', 'U10'), ('max', 'U10'), ('min', 'U10'),
                  ('mean', 'RH2'), ('max', 'RH2'), ('min', 'RH2'),
                  ('mean', 'Kdown')]

    list_const = [getattr(const, attr)
                  for attr in ['T_MEAN', 'T_MAX', 'T_MIN',
                               'WIND_MEAN', 'WIND_MAX', 'WIND_MIN',
                               'RH_MEAN', 'RH_MAX', 'RH_MIN',
                               'SOLAR_RADIATION_GLOBAL']]
    list_ws = [df_fs.loc[idx] * cst
               for idx, cst
               in zip(list_index, list_const)]
    df_ws = pd.concat(list_ws, axis=1).sum(axis=1).unstack().dropna()

    return df_ws
1328913
def coords(self) -> Iterator[Tuple[float, float, float]]:
        
        data = self.data[self.data.longitude.notnull()]
        yield from zip(data["longitude"], data["latitude"], data["altitude"])
917002
def current(place):
    """"""
    lat, lon = place
    url = "https://api.forecast.io/forecast/%s/%s,%s?solar" % (APIKEY, lat,
                                                               lon)
    w_data = json.loads(urllib2.urlopen(url).read())
    currently = w_data['currently']
    return mangle(currently)
907501
def _get_existing_records(cr, fp, module_name):
    """"""
    def yield_element(node, path=None):
        if node.tag not in ['openerp', 'odoo', 'data']:
            if node.tag == 'record':
                xmlid = node.attrib['id']
                if '.' not in xmlid:
                    module = module_name
                else:
                    module, xmlid = xmlid.split('.', 1)
                cr.execute(
                    'select id from ir_model_data where module=%s and name=%s',
                    (module, xmlid)
                )
                if not cr.rowcount:
                    return
            result = StringIO(etree.tostring(path, encoding='unicode'))
            result.name = None
            yield result
        else:
            for child in node:
                for value in yield_element(
                        child,
                        etree.SubElement(path, node.tag, node.attrib)
                        if path else etree.Element(node.tag, node.attrib)
                ):
                    yield value
    return yield_element(etree.parse(fp).getroot())
698488
def fetch_data(self):
        """"""
        # Get http session
        yield from self._get_httpsession()
        # Get login page
        login_url = yield from self._get_login_page()
        # Post login page
        yield from self._post_login_page(login_url)
        # Get p_p_id and contracts
        p_p_id, contracts = yield from self._get_p_p_id_and_contract()
        # If we don't have any contrats that means we have only
        # onecontract. Let's get it
        if contracts == {}:
            contracts = yield from self._get_lonely_contract()

        # Get balance
        balances = yield from self._get_balances()
        balances_len = len(balances)
        balance_id = 0
        # For all contracts
        for contract, contract_url in contracts.items():
            if contract_url:
                yield from self._load_contract_page(contract_url)

            # Get Hourly data
            try:
                yesterday = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)
                day_date = yesterday.strftime("%Y-%m-%d")
                hourly_data = yield from self._get_hourly_data(day_date, p_p_id)
                hourly_data = hourly_data['processed_hourly_data']
            except Exception:  # pylint: disable=W0703
                # We don't have hourly data for some reason
                hourly_data = {}

            # Get Annual data
            try:
                annual_data = yield from self._get_annual_data(p_p_id)
            except PyHydroQuebecAnnualError:
                # We don't have annual data, which is possible if your
                # contract is younger than 1 year
                annual_data = {}
            # Get Monthly data
            monthly_data = yield from self._get_monthly_data(p_p_id)
            monthly_data = monthly_data[0]
            # Get daily data
            start_date = monthly_data.get('dateDebutPeriode')
            end_date = monthly_data.get('dateFinPeriode')
            try:
                daily_data = yield from self._get_daily_data(p_p_id, start_date, end_date)
            except Exception:  # pylint: disable=W0703
                daily_data = []
            # We have to test daily_data because it's empty
            # At the end/starts of a period
            if daily_data:
                daily_data = daily_data[0]['courant']
            # format data
            contract_data = {"balance": balances[balance_id]}
            for key1, key2 in MONTHLY_MAP:
                contract_data[key1] = monthly_data[key2]
            for key1, key2 in ANNUAL_MAP:
                contract_data[key1] = annual_data.get(key2, "")
            # We have to test daily_data because it's empty
            # At the end/starts of a period
            if daily_data:
                for key1, key2 in DAILY_MAP:
                    contract_data[key1] = daily_data[key2]
            # Hourly
            if hourly_data:
                contract_data['yesterday_hourly_consumption'] = hourly_data
            # Add contract
            self._data[contract] = contract_data
            balance_count = balance_id + 1
            if balance_count < balances_len:
                balance_id += 1
696761
def records(self):
        
        first = True
        with as_handle(self._filename) as fp:
            for record in NCBIXML.parse(fp):
                if first:
                    self.params = self._convertBlastParamsToDict(record)
                    first = False
                yield record
58041
def __parse_fc_data(fc_data):
    """"""
    fc = []
    for day in fc_data:
        fcdata = {
            CONDITION: __cond_from_desc(
                __get_str(
                    day,
                    __WEATHERDESCRIPTION)
            ),
            TEMPERATURE: __get_float(day, __MAXTEMPERATURE),
            MIN_TEMP: __get_float(day, __MINTEMPERATURE),
            MAX_TEMP: __get_float(day, __MAXTEMPERATURE),
            SUN_CHANCE: __get_int(day, __SUNCHANCE),
            RAIN_CHANCE: __get_int(day, __RAINCHANCE),
            RAIN: __get_float(day, __MMRAINMAX),
            MIN_RAIN: __get_float(day, __MMRAINMIN),  # new
            MAX_RAIN: __get_float(day, __MMRAINMAX),  # new
            SNOW: 0,  # for compatibility
            WINDFORCE: __get_int(day, __WIND),
            WINDDIRECTION: __get_str(day, __WINDDIRECTION),      # new
            DATETIME: __to_localdatetime(__get_str(day, __DAY)),
        }
        fcdata[CONDITION][IMAGE] = day[__ICONURL]

        fc.append(fcdata)
    return fc
659519
def iteritems(self):
        ''''''
        for x in range(len(self.keys)):
            yield (self.keys[x], self.values[x])
1105680
def iteritems(self, multi=False):
        """"""
        for key, values in dict.iteritems(self):
            if multi:
                for value in values:
                    yield key, value
            else:
                yield key, values[0]
775259
async def weather_type_classe(self):
        """"""

        data = await self.retrieve(url=API_WEATHER_TYPE)

        self.weather_type = dict()

        for _type in data['data']:
            self.weather_type[_type['idWeatherType']] = _type['descIdWeatherTypePT']

        return self.weather_type
535449
def _get_all_forecast_from_api(api_result: dict) -> OrderedDict:
    """"""
    # Total time in hours since last forecast
    total_hours_last_forecast = 1.0

    # Last forecast time
    last_time = None

    # Need the ordered dict to get
    # the days in order in next stage
    forecasts_ordered = OrderedDict()

    # Get the parameters
    for forecast in api_result['timeSeries']:

        valid_time = datetime.strptime(
            forecast['validTime'], "%Y-%m-%dT%H:%M:%SZ")
        for param in forecast['parameters']:
            if param['name'] == 't':
                temperature = float(param['values'][0])  # Celcisus
            elif param['name'] == 'r':
                humidity = int(param['values'][0])  # Percent
            elif param['name'] == 'msl':
                pressure = int(param['values'][0])  # hPa
            elif param['name'] == 'tstm':
                thunder = int(param['values'][0])  # Percent
            elif param['name'] == 'tcc_mean':
                octa = int(param['values'][0])  # Cloudiness in octas
                if 0 <= octa <= 8:  # Between 0 -> 8
                    cloudiness = round(100*octa/8)  # Convert octas to percent
                else:
                    cloudiness = 100  # If not determined use 100%
            elif param['name'] == 'Wsymb2':
                symbol = int(param['values'][0])  # category
            elif param['name'] == 'pcat':
                precipitation = int(param['values'][0])  # percipitation
            elif param['name'] == 'pmean':
                mean_precipitation = float(
                    param['values'][0])  # mean_percipitation
            elif param['name'] == 'ws':
                wind_speed = float(param['values'][0])  # wind speed
            elif param['name'] == 'wd':
                wind_direction = int(param['values'][0])  # wind direction
            elif param['name'] == 'vis':
                horizontal_visibility = float(param['values'][0])  # Visibility
            elif param['name'] == 'gust':
                wind_gust = float(param['values'][0])  # wind gust speed

        roundedTemp = int(round(temperature))

        if last_time is not None:
            total_hours_last_forecast = (valid_time - last_time).seconds/60/60

        # Total precipitation, have to calculate with the nr of
        # hours since last forecast to get correct total value
        tp = round(mean_precipitation*total_hours_last_forecast, 2)

        forecast = \
            SmhiForecast(roundedTemp, roundedTemp, roundedTemp,
                         humidity, pressure, thunder, cloudiness,
                         precipitation, wind_direction, wind_speed,
                         horizontal_visibility, wind_gust,
                         round(mean_precipitation, 1), tp, symbol,
                         valid_time)

        if valid_time.day not in forecasts_ordered:
            # add a new list
            forecasts_ordered[valid_time.day] = []

        forecasts_ordered[valid_time.day].append(forecast)

        last_time = valid_time

    return forecasts_ordered
1284222
def iteritems(self):
        
        sorted_data = sorted(self.data.iteritems(), self.cmp, self.key,
                             self.reverse)
        for k,v in sorted_data:
            yield k,v
241431
def weather(query):
	

	print 'Identifying the location . . .'
	try:
		response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-ner",
	  		headers={
	    	"X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP",
	    	"Content-Type": "application/x-www-form-urlencoded"
	  			},
	  		params={
	    	"text": query
	  		}
		)
	except:
		print 'Unable to connect to internet'
		return
	location = ''
	for entity in response.body['result'].split():
		word,tag = entity.split('/')
		if(tag == 'LOCATION'):
			location += ' '+word
	if(location != ''):
		print 'Gathering weather information for'+location
		import urllib2, urllib, json
		baseurl = "https://query.yahooapis.com/v1/public/yql?"
		yql_query = "select * from weather.forecast where woeid in \
		(select woeid from geo.places(1) where text=\""+location+"\")"
		yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json"
		try:
			result = urllib2.urlopen(yql_url).read()
			data = json.loads(result)
			result = data['query']['results']['channel']
			print result['location']['city']+' '+result['location']['country']+' '+result['location']['region']
			print result['item']['condition']['date']
			print result['item']['condition']['text']
			print result['item']['condition']['temp']+' '+result['units']['temperature'] 
		except:
			print 'Unable to connect to internet'
	else:
		print 'Unable to get the location.'
7802
def temperatures(self):
        """"""
        self.location.status()

        if self.hotwater:
            yield {
                'thermostat': 'DOMESTIC_HOT_WATER',
                'id': self.hotwater.dhwId,
                'name': '',
                'temp': self.hotwater.temperatureStatus['temperature'],          # pylint: disable=no-member
                'setpoint': ''
            }

        for zone in self._zones:
            zone_info = {
                'thermostat': 'EMEA_ZONE',
                'id': zone.zoneId,
                'name': zone.name,
                'temp': None,
                'setpoint': zone.setpointStatus['targetHeatTemperature']
            }

            if zone.temperatureStatus['isAvailable']:
                zone_info['temp'] = zone.temperatureStatus['temperature']
            yield zone_info
1110803
def iterShapeRecords(self):
        """"""
        for shape, record in izip(self.iterShapes(), self.iterRecords()):
            yield ShapeRecord(shape=shape, record=record)
601037
def items(cls):
        
        return [
            cls.PRECIPITATION,
            cls.WIND,
            cls.TEMPERATURE,
            cls.PRESSURE
        ]