Ejemplo n.º 1
0
    def test_output(self):
        today = DayForecast()

        # go and get bbc data, update the day forecast
        today.bbc = Forecast();
        today.bbc.rainfallHourly = {
            7: 10,
            8: 11
        }
        today.bbc.tempHourly = {
            7: 15,
            8: 16
        }

        # go and get met data, update the day forecast
        today.met = Forecast();
        today.met.rainfallHourly = {
            7: 8,
            8: 9
        }
        today.met.tempHourly = {
            7: 13,
            8: 14
        }

        self.assertEqual(today.bbc.rainfallHourly[7], 10)
        self.assertEqual(today.bbc.tempHourly[7], 15)
        self.assertEqual(today.met.rainfallHourly[7], 8)
        self.assertEqual(today.met.tempHourly[7], 13)

        # eventually, get the actual forecast
        today.actual.rainfallHourly = {
            7: 0,
            8: 0
        }
Ejemplo n.º 2
0
    def set_weather(self):
        """ Reads weather data and sets it in UI classes """

        self.util.set_url()
        weather = self.util.load_json()
        self.components.clear()

        dark_light = self.util.weather_config[COLOR_DARK_LIGHT]
        semi_transparent_color = (dark_light[0], dark_light[1], dark_light[2],
                                  210)

        today_bgr = self.images[0]
        self.today = Today(self.util, today_bgr, semi_transparent_color)
        self.today.set_weather(weather)
        self.today.draw_weather()
        self.today.set_visible(False)

        if len(self.images) > 1:
            forecast_bgr = self.images[1]
        else:
            forecast_bgr = self.images[0]
        self.forecast = Forecast(self.util, forecast_bgr,
                                 semi_transparent_color)
        self.forecast.set_weather(weather)
        self.forecast.draw_weather()
        self.forecast.set_visible(True)

        self.add_component(self.today)
        self.add_component(self.forecast)
Ejemplo n.º 3
0
def weather_outfit(req):
    """Returns a string containing text with a response to the user
    with a indication if the outfit provided is appropriate for the
    current weather or a prompt for more information

    Takes a city, outfit and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the outfits listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Validate that there are the required parameters to retrieve a forecast
    if not forecast_params['outfit']:
        return 'What are you planning on wearing?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    return forecast.get_outfit_response()
Ejemplo n.º 4
0
def weather_temperature(req):
    """Returns a string containing text with a response to the user
    with a indication if temperature provided is consisting with the
    current weather or a prompt for more information

    Takes a city, temperature and (optional) dates.  Temperature ranges for
    hot, cold, chilly and warm can be configured in config.py
    uses the template responses found in weather_responses.py as templates
    """

    parameters = req['queryResult']['parameters']

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(parameters)
    if error:
        return error

    # If the user didn't specify a temperature, get the weather for them
    if not forecast_params['temperature']:
        return weather(req)

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    return forecast.get_temperature_response()
    def setup_community(self,
                        community_config,
                        global_config,
                        i_dir=None,
                        scalers=None):
        """
        
        """
        diag = diagnostics()

        if i_dir is None:
            com_dir = community.replace(' ', '_').split('+')[0]
            i_dir = os.path.join(self.inputs_dir, com_dir)

        try:
            cd = CommunityData(community_config, global_config, diag, scalers)
        except IOError as e:
            raise RuntimeError, \
                ("A Fatal Error Has occurred, ("+ str(e) +")")
        try:
            fc = Forecast(cd, diag, scalers)
        except RuntimeError as e:
            raise RuntimeError, \
                    ("A Fatal Error Has occurred, ("+ str(e) +")")

        return cd, fc, diag
Ejemplo n.º 6
0
def weather_condition(req):
    """Returns a string containing a human-readable response to the user
    with the probability of the provided weather condition occurring
    or a prompt for more information

    Takes a city, condition and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the conditions listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Check to make sure there is a activity, if not return an error
    if not forecast_params['condition']:
        return 'What weather condition would you like to check?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    # get the response
    return forecast.get_condition_response()
Ejemplo n.º 7
0
def weather_activity(req):
    """Returns a string containing text with a response to the user
    with a indication if the activity provided is appropriate for the
    current weather or a prompt for more information

    Takes a city, activity and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the activities listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Check to make sure there is a activity, if not return an error
    if not forecast_params['activity']:
        return 'What activity were you thinking of doing?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    # get the response
    return forecast.get_activity_response()
Ejemplo n.º 8
0
def get_currently_forecast():
    city = request.args.get('city')

    response = DarkSkyWeather.currently(city=city)
    forecast_data = Forecast(timestamp=response["currently"]["time"],
                             temperature=response["currently"]["temperature"])
    return str(forecast_data)
Ejemplo n.º 9
0
def main():
    data_processor = ProcessData()
    forecast_util = Forecast()
    series,train, test = data_processor.read_data('shampoo-sales.csv')

    forecasts = forecast_util.make_forecasts(train,test, 1, 3)
    forecast_util.evaluate_forecasts(test, forecasts, 1, 3)
    forecast_util.plot_forecasts(series, forecasts, 12)
Ejemplo n.º 10
0
def start(sharename, sharenum):

    a = Spider(sharename)
    a.writeDoc()
    print("调用spider结束")
    b = PrintWordCloud(sharename, sharenum)
    b.drawWordCloud()
    print("生成词云图结束")
    print("开始调用Forecast")
    c = Forecast(sharename, sharenum)
    c.useModel()
Ejemplo n.º 11
0
def forecast():

    forecaster = Forecast()
    forecaster.hello()

    if request.method == 'POST':
        args = []
        args.append(request.form['firstname'])
        args.append(request.form['lastname'])
        return render_template('forecast.html', args=args)
    else:
        return render_template('forecast.html')
Ejemplo n.º 12
0
def parse_forecast(html, zone=None):
    html_root = BeautifulSoup(html, 'html.parser')
    forecast_root = html_root.find(id="avalanche-forecast")

    zone = zone.name if zone is not None else None
    date = parse_forecast_date(forecast_root)
    description = parse_forecast_description(forecast_root)
    problems = parse_all_problems(forecast_root)
    warnings = parse_all_warnings(html_root)
    dangers = parse_all_dangers(forecast_root)

    return Forecast(zone, date, description, problems, warnings, dangers)
Ejemplo n.º 13
0
    def __forecast(self, soup, num_of_days_of_forecast):
        keys = [
            "Date/Month:", "Wind:", "Weather:", "Temp range:", "R.H. range:"
        ]
        l = soup.get_text().split('\n')
        forecast_list = []
        # b = []
        # for a in l:
        date = ""
        wind = ""
        weather = ""
        temp = ""
        rh = ""
        last_date = ""
        is_first_date = True
        for i in range(0, len(l)):
            s = l[i].strip()
            if i + 2 < len(l):
                if s == keys[0]:
                    date = l[i + 1].strip()
                elif s == keys[1]:
                    wind = l[i + 1].strip()
                elif s == keys[3]:
                    temp = l[i + 1].strip() + " " + l[i + 2].strip()
                elif s == keys[4]:
                    rh = l[i + 1].strip() + " " + l[i + 2].strip()
                elif s == keys[2]:
                    weather = l[i + 1].strip()
                if len(
                    [x for x in [date, wind, weather, temp, rh]
                     if len(x) > 0]) == 5:
                    f = Forecast(date, wind, weather, temp, rh)
                    forecast_list.append(f.dict())
                    date = ""
                    wind = ""
                    weather = ""
                    temp = ""
                    rh = ""

        return {
            "general_situation": l[0].split(":")[1],
            "forecast": forecast_list[0:num_of_days_of_forecast]
        }
Ejemplo n.º 14
0
def main():
    sender, password = get_email_credentials()
    receivers = get_receivers()

    gmail = Gmail(sender, password)

    for locationName, emails in receivers.items():
        location = Location(locationName)

        if location.get_local_time().hour == SEND_EMAIL_HOUR:
            forecast = Forecast(location)

            if forecast.rain_today():
                message = forecast.get_forecast_message()

                for email in emails:
                    send_forecast_message(gmail, email, message)

    print('INFO: Done.')
Ejemplo n.º 15
0
def expected_positive_increase( current: pd.DataFrame, history: pd.DataFrame,
                                log: ResultLog, context: str, config: QCConfig=None):
    """
    Fit state-level daily positives data to an exponential and a linear curve.
    Get expected vs actual case increase to determine if current positives
    are within the expected ranges.

    The exponential is used as the upper bound. The linear is used as the lower bound.

    TODO: Eventually these curves will NOT be exp (perhaps logistic?)
          Useful to know which curves have been "leveled" but from a
          data quality perspective, this check would become annoying
    """

    if not config: config = QCConfig()

    forecast_date = current.lastUpdateEt.to_pydatetime().strftime('%Y%m%d')
    history = history.loc[history["date"].astype(str) != forecast_date]

    forecast = Forecast()
    forecast.fit(history)
    forecast.project(current)

    if config.save_results:
        save_forecast_hd5(forecast, config.results_dir)
    elif config.plot_models:
        plot_to_file(forecast, f"{config.images_dir}/{context}", FIT_THRESHOLDS)

    state = forecast.state
    date = forecast.date
    actual_value, expected_linear, expected_exp = forecast.results

    min_value = int(FIT_THRESHOLDS[0] * expected_linear)
    max_value = int(FIT_THRESHOLDS[1] * expected_exp)

    if not (min_value <= actual_value <=  max_value):
        direction = "increase"
        if actual_value < expected_linear:
            direction = "drop"

        log.error(state, f"unexpected {direction} in positive cases ({actual_value:,}) for {date}, expected between {min_value:,} and {max_value:,}")
Ejemplo n.º 16
0
def weather(req):
    """Returns a string containing text with a response to the user
    with the weather forecast or a prompt for more information

    Takes the city for the forecast and (optional) dates
    uses the template responses found in weather_responses.py as templates
    """
    parameters = req['queryResult']['parameters']

    print('Dialogflow Parameters:')
    print(json.dumps(parameters, indent=4))

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(parameters)
    if error:
        print(error, forecast_params)
        return str(error)

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        print('Forecast error')
        print(error, forecast_params)
        return str(error)

    # If the user requests a datetime period (a date/time range), get the
    # response
    if forecast.datetime_start and forecast.datetime_end:
        response = forecast.get_datetime_period_response()
    # If the user requests a specific datetime, get the response
    elif forecast.datetime_start:
        response = forecast.get_datetime_response()
    # If the user doesn't request a date in the request get current conditions
    else:
        response = forecast.get_current_response()

    return response
Ejemplo n.º 17
0
def main():
    if len(argv) < 2:
        return
    try:
        ingredients = argv[1:]
        alt_names = {
            'cream': 'milk',
            'yam': 'sweet potato',
            'scallion': 'green onion',
            'armagnac': 'cognac',
            'stew': 'soup',
            'butterscotch': 'caramel',
            'jelly': 'jam'
        }
        ingredients, indeces = np.unique(np.array(
            [alt_names.get(n, n) for n in ingredients]),
                                         return_index=True)
        ingredients = ingredients[indeces.argsort()]
        names = np.loadtxt('data/names.csv', dtype='object', delimiter=',')
        for ing in ingredients:
            if ing not in names:
                print(f"""Ingredient '{ing}' not found in base.
Sorry forecast cannot be done, please try again""")
                exit()
        print('I. OUR FORECAST')
        fcst = Forecast(ingredients)
        print(fcst.predict_rating_category()[1])
        print('\n')
        print('II. NUTRITION FACTS')
        nf = NutritionFacts(ingredients)
        nf.retrieve()
        print(nf.filter(['Protein', 'Total Carbohydrate', 'Total Fat'], 30))
        print('\n')
        print('III. TOP-3 SIMILAR RECIPES')
        sr = SimilarRecipes(ingredients)
        print(sr.top_similar(3))
    except Exception:
        print('An error occured while executing, please reinstall the app')
Ejemplo n.º 18
0
        start += datetime.timedelta(days=1)
    return data


if __name__ == '__main__':
    data = eval(open(os.path.join('data', 'data')).read())
    testdata = eval(open(os.path.join('data', 'testdata')).read())

    #forecast = Forecast(data, testdata, scale = [7.0, 10.0, 2.0, 12.0, 5.0, 8.0, 16.0, 5.0, 6.0, 8.0, 1, 11.0, 3.0])
    #forecast = Forecast(data, testdata, scale = [42.0, 30.0, 0.0, 108.0, 60.0, 56.0, 144.0, 70.0, 42.0, 128.0, 20.0, 220.0, 36.0])
    #print forecast.annealing([(0, 20) for i in range(len(testdata.values()[0]['input']))], trial = 30)

    scale = dict([(-1 * i, []) for i in range(5)])
    veclen = len(testdata.values()[0]['input'])

    try:
        for vector in eval(open('../output').read()):
            forecast = Forecast(data, testdata, scale=vector)
            result = forecast.validation(trial=100)

            if result in scale:
                scale[result].append(vector)
            elif sorted(scale.keys(), reverse=True)[-1] < result:
                del scale[sorted(scale.keys(), reverse=True)[-1]]
                scale[result] = [vector]
            print vector, result
    except:
        pass

    print scale
Ejemplo n.º 19
0
    if planet is None:
        raise ValueError(
            "You must indicate a planet contained on the solar system. Valid "
            "ones: %s" % available_planets)

    db = database.connect()

    if args.db_clean:
        db.flushall()

    total_days = args.days + planet.days_in_year() * args.years
    db.set('total', total_days)
    print("> Total days to calculate: %d (from %s point of view)" %
          (total_days, planet.name))

    fc = Forecast()
    totalized = {
        'total': total_days,
        'max_rain': {
            'day': None,
            'perimeter': 0
        }
    }

    for day in range(total_days):
        coords = solar.positions(day)
        prediction = fc.predict(coords)
        totalized.setdefault(prediction['name'], 0)
        totalized[prediction['name']] += 1

        db.set('%s%d' % (config.DB_DAY_PREFIX, day), json.dumps(prediction))
Ejemplo n.º 20
0
from forecast import Forecast
from real_environment import real_environment
import yopy
import json
import utils

# environment
renv = real_environment.RealEnvironment()

# forecast 
forecast = Forecast()

# register your func
functions_to_be_run = {
    'trend_by_perc': forecast.trend_by_perc,
    'trend_by_weekdays': forecast.trend_by_weekdays
}

# read weight json file. if not exist, redefine all weights
try:
    weight = utils.read_file(
        'weight_' + renv.get_env_or_default("coin_name", "bitcoin") + '.json')
except FileNotFoundError:
    weight = {}
    for key, value in functions_to_be_run.items():
        weight[key]=100/len(functions_to_be_run) # give a percantage value
    utils.write_file(
        'weight_' + renv.get_env_or_default("coin_name", "bitcoin") + '.json', weight)

# prophecy is old forecast. read prophecy data and update weights. escobar will smarter.
try:
Ejemplo n.º 21
0
def main():
    """
  - Parse user-specified data from YaML
  - Check to see that the needed graphics are available. If not, get them.
  - Get the radar imagery, complete with warnings graphics
  - Get today's hazardous weather outlook statement and parse it
  - Check for FTM outage notifications
  - Get, parse, and write out current weather conditions to specified locations.
  - TODO: should run the getweather.sh shell script, that overlays/composites
    the weather graphics. At present, that shell script calls this script
    and runs the overlays with -bash-.
  - Check for and acquire current multi-band GOES-x imagery of a given resolution.
  """
    if os.path.exists('weatherwidget.log'):
        os.remove('weatherwidget.log')
    logging.basicConfig(
        filename='weatherwidget.log',
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s %(threadName)-10s %(message)s',
    )

    data = wf.load_settings_and_defaults(SETTINGS_DIR, 'settings.yml',
                                         'defaults.yml')
    if not data:
        logging.error('Unable to load settings files. These are required.')
        sys.exit(
            'settings files are required and could not be loaded successfully.'
        )

    logging.info('Checking for radar outage.')
    wf.outage_check(data)

    logging.info('Retrieving current weather observations.')
    right_now = Observation(data)
    right_now.get_current_conditions()
    right_now.get_backup_obs(use_json=False)
    right_now.merge_good_observations()
    logging.debug('Merged current conditions: %s', right_now.con1.obs)
    sum_con = right_now.conditions_summary()

    if right_now.con1.obs and sum_con:
        text_conditions, nice_con = right_now.format_current_conditions()
        logging.debug('Current conditions from primary source: %s', nice_con)
        wf.write_json(some_dict=nice_con,
                      outputdir=data['output_dir'],
                      filename='current_conditions.json')
    else:
        logging.error(
            'Something went wrong getting the current conditions. Halting.')
        return 1

    wf.write_text(os.path.join(data['output_dir'], 'current_conditions.txt'),
                  text_conditions)

    # Get radar image:
    current_radar = Radar(data)
    current_radar.check_assets()
    current_radar.get_radar()
    current_radar.get_warnings_box()
    if current_radar.problem:
        logging.error('Unable to retrieve weather radar image. Halting now.')

    # Hazardous Weather Outlook and alerts:
    today_alerts = Alerts(data)
    today_alerts.get_alerts()

    # Get hydrograph image.
    if wf.get_hydrograph(abbr=data['river_gauge_abbr'],
                         hydro_url=data['defaults']['water_url'],
                         outputdir=data['output_dir']).ok:
        logging.info('Requesting hydrograph for station %s, gauge "%s".',
                     data['radar_station'], data['river_gauge_abbr'])
    else:
        logging.error('Failed to get hydrograph information.')
        return 1

    forecast_obj = Forecast(data=data)
    logging.debug('Getting the forecasts.')
    forecast_obj.get_forecast()
    forecastdict = forecast_obj.parse_forecast()
    if forecastdict is None:
        logging.error('Unable to parse forecast!')
        return 1
    forecast_obj.write_forecast(outputdir=data['output_dir'])
    logging.debug('Getting area forecast discussion.')
    forecast_obj.get_afd()

    logging.debug('Getting zone forecast.')
    zoneforecast = ZoneForecast(data)
    zoneforecast.get()

    wf.write_json(some_dict=forecastdict,
                  outputdir=data['output_dir'],
                  filename='forecast.json')
    wsvg.make_forecast_icons(forecastdict, outputdir=data['output_dir'])

    # Satellite imagery:
    current_image = Imagery(band='GEOCOLOR', data=data)
    current_image.get_all()

    logging.info('Finished program run.')

    return 0
Ejemplo n.º 22
0
def _forecast(net, temp):
    return None if net is None else Forecast(net, temp)
    def run(self,
            community_config,
            global_config=None,
            tag='',
            scalers=None,
            alt_save_name=None):
        """
        run the model for a community
        
        inputs:
            community: the community <string>
            c_config: (optional, default: none) alternate community config 
                file <string>
            g_config: (optional, default: none) alternat global confing 
                file <string>
            tag: (optional) tag for results dir <string>
            
        outputs:
            the model is run for a community/project/assigned 'name'
            
        preconditions:
            see invariants
            
        postconditions:
            None
        """
        #~ print community_config

        if scalers is None:
            scalers = default_scalers

        #~ if name is None:
        #~ name = community

        temp = tag
        #~ if img_dir is None:
        #~ if temp != '':
        #~ temp = '_' + tag
        #~ img_dir = os.path.join(self.model_root, 'results' + temp, 'plots')

        #~ cd, fc, diag = self.setup_community(community, i_dir, c_config,
        #~ g_config, c_mult, scalers)

        diagnostics = Diagnostics()
        community_data = CommunityData(community_config, global_config,
                                       diagnostics, scalers)
        name = community_data.get_item('community', 'file id')
        #~ print name
        forecast = Forecast(community_data, diagnostics, scalers)

        comps_used = self.run_components(community_data, forecast, diagnostics,
                                         scalers)

        #~ name = community_data.get_item('community', 'file id')
        self.save_components_output(comps_used,
                                    name,
                                    forecast,
                                    tag,
                                    alt_name=alt_save_name)
        #~ self.save_forecast_output(forecast, name, img_dir, plot, tag)
        self.save_input_files(community_data,
                              name,
                              tag,
                              alt_name=alt_save_name)
        self.save_diagnostics(diagnostics, name, tag, alt_name=alt_save_name)

        comps_used['community data'] = community_data
        comps_used['forecast'] = forecast

        #~ print name
        #~ print 'rb', alt_save_name
        self.store_results(comps_used, tag, name=alt_save_name)
Ejemplo n.º 24
0
def main(cla):

    # Load the user-defined settings, and script settings
    # ----------------------------------------------------
    user_config = cla.user_config

    print(f"user config: {user_config}")
    script_config = cla.script_config
    print(f"script config: {script_config}")
    if not script_config:
        ushdir = os.path.join(user_config['paths']['homerrfs'], 'configs')
        script_config = checks.load_config_file(
            os.path.join(ushdir, 'fv3_script.yml'))

    # Update script config with user-supplied config file
    # ----------------------------------------------------
    utils.update_dict(script_config, user_config, quiet=cla.quiet)

    # Create Namespace of config for easier syntax
    # ---------------------------------------------
    config = argparse.Namespace()
    utils.namespace(config, script_config)

    # Now config and script_config contain identical information in Namespace
    # and dict formats, respectively.

    # Load each of the standard YAML config files
    # --------------------------------------------
    #
    # Reminder:
    # checks.load_config_section(arg) takes a two-element list as it's input.
    #    arg = [file_name, section_name(s)]
    #
    grid = cla.grid_config
    if not grid:
        grid = checks.load_config_section([
            config.paths.grid.format(n=config),
            [config.grid_name, config.grid_gen_method],
        ])

    machine = cla.machine_config
    if not machine:
        machine_path = config.paths.machine.format(n=config)
        machine = checks.load_config_section([
            machine_path,
            config.machine,
        ])

    namelist = cla.nml_config
    if not namelist:
        namelist = checks.load_config_section([
            config.paths.namelist.format(n=config),
            config.phys_pkg,
        ])

    # Update each of the provided configure files with user-supplied settings
    # ------------------------------------------------------------------------
    for cfg in ['grid', 'machine', 'namelist']:
        utils.update_dict(locals()[cfg][0],
                          script_config.get(cfg),
                          quiet=cla.quiet)

    # Set up a kwargs dict for Forecast object
    # -----------------------------------------
    fcst_kwargs = {
        'grid': grid[0],
        'nml': namelist[0],
        'overwrite': cla.overwrite,
    }

    # Create the Forecast object
    # ---------------------------
    fcst = Forecast(
        config=script_config,
        machine=machine[0],
        starttime=cla.start_date,
        **fcst_kwargs,
    )

    # Run the forecast job
    # ---------------------
    fcst.run(dry_run=cla.dry_run)
Ejemplo n.º 25
0
    time.sleep_ms(1000)
    now = time.ticks_ms()
    while True:
      if wifi.ifconfig()[0] != '0.0.0.0':
        print("Connected, IP: {}".format(wifi.ifconfig()[0]))
        break
      if time.ticks_ms() - now > timeout:
        break
  return wifi

wifi = init_wifi("signalhuset", "signal+huset2017")
# wifi = init_wifi("HomeBox-10E0_5G", "a6cfdf567")
# wifi = init_wifi("AndroidAPAD82", "odon3187")

status, header, data = curl.get('api.openweathermap.org/data/2.5/onecall?lat=55.6761&lon=12.5683&exclude=minutely,hourly,current&&units=metric&appid=4641ad3e90202b3e5b93bb82490ca04f')
weather = Forecast(json.loads(data)['daily'])

servo = machine.PWM(machine.Pin(17), freq=50)
pin_r = machine.PWM(machine.Pin(27))
pin_g = machine.PWM(machine.Pin(26))
pin_b = machine.PWM(machine.Pin(25))

def on_data(temp):
    print(temp[2])
    today = json.loads(data)['daily'][0]['weather'][0]
    print(today['main'])
    if today['main'] == 'Clear':
        servo.duty(7)
    elif today['main'] == 'Clouds':
        servo.duty(11)
    elif today['main'] == 'Rain':
Ejemplo n.º 26
0
# import libraries
from argument_parser import args
try:
    from config import app_id, default_country_code
except ImportError as import_error:
    print("An error ocurred while trying to import the config file: ")
    print(import_error)

from forecast import Forecast

country_code = default_country_code
if args.country is not None:
    country_code = args.country

weather = Forecast(args.city, country_code, app_id)
weather.get_tomorrow()
Ejemplo n.º 27
0
# Call create table functions with the SQL queries
create_table(create_query_forecasts)
create_table(create_query_history)

# call getForecast function from Wunder_api.py to get the current 10 day forecast
forecastValues = getForecast()
# unpack the variables from the tuple
dates = forecastValues[0]
highs = forecastValues[1]
lows = forecastValues[2]

# insert all days of the forecast into the forecasts table
count = 0
for days in dates:
	fore = Forecast('Weather Underground', dates[0],dates[count],highs[count],lows[count])
	insert_forecast(fore)
	
	count = count + 1

# This section determines which dates to request from the historic weather API
# by checking the rows in the history table against the rows in the forecasts table	
# also checks date to make sure that it comes before todays date

# select all rows from history table and populate a list with the dates
records_in_historic = select_historic()
# create a list and extract dates from records_in_historic
dates_in_history = []
count = 0
for rows in records_in_historic:
	currentRow = records_in_historic[count]
Ejemplo n.º 28
0
    def __init__(self, fullname: str, version: str, description: str,
                 shortname: str):
        """
        :param fullname: program name
        :param version: program version
        :param description: short description
        :param shortname: short name, mainly for logs
        """

        self.NAME = fullname
        self.SHORTNAME = shortname
        self.VERSION = version
        self.DESCRIPTION = description

        self.STATION_NAME = None
        self.ELEVATION = None
        self.P_INITIAL = None

        self.start_console()

        # starts logging
        self.LOG_FILENAME = self.SHORTNAME + ".log"
        logging.basicConfig(
            filename=self.LOG_FILENAME,
            level=logging.INFO,
            filemode="w",
            format="%(asctime)s %(levelname)s : %(message)s",
            datefmt="%Y-%m-%d %H:%M",
        )

        self.result = PredictionTable()
        self.forecast = Forecast()
        self.slack = slack.WebClient(token=environ["SLACK_API_TOKEN"])

        # reads configuration file and recreates missing values
        self.CONFIG_FILENAME = "config.ini"
        self.CS = "USER SETTINGS"
        self.cfg = ConfigParser()
        self.cfg.read(self.CONFIG_FILENAME)

        if self.CS not in self.cfg.sections():
            print80(_("Regenerating {}").format(self.CONFIG_FILENAME))
            print()
            self.cfg.add_section(self.CS)

        self.TIMEOUT_T = "short timeout"
        self.TIMEOUT = int(self.cfg.get(self.CS, self.TIMEOUT_T, fallback="5"))

        self.TIMEOUT_LONG_T = "long timeout"
        self.TIMEOUT_LONG = int(
            self.cfg.get(self.CS, self.TIMEOUT_LONG_T, fallback="10"))

        self.GEOLOCATION_ALWAYS_ON_T = "geolocation always on"
        self.GEOLOCATION_ALWAYS_ON = bool(
            int(
                self.cfg.get(self.CS,
                             self.GEOLOCATION_ALWAYS_ON_T,
                             fallback="0")))

        self.WAIT_FOR_KEY_T = "press any key"
        self.WAIT_FOR_KEY = bool(
            int(self.cfg.get(self.CS, self.WAIT_FOR_KEY_T, fallback="1")))
        self.PAUSE = (not args.no_key) and self.WAIT_FOR_KEY

        self.OVERRIDE_URL_T = "override url"
        self.OVERRIDE_URL_ = self.cfg.get(self.CS,
                                          self.OVERRIDE_URL_T,
                                          fallback="")
        if args.override_url is not None:
            self.OVERRIDE_URL = args.override_url
        else:
            self.OVERRIDE_URL = self.OVERRIDE_URL_

        self.OVERRIDE_URL_EXISTS = self.OVERRIDE_URL is not None and self.OVERRIDE_URL.startswith(
            "https://www.wunderground.com/hourly/")

        self.ANY_HTTPS_PAGE_T = "https page"
        self.ANY_HTTPS_PAGE = self.cfg.get(self.CS,
                                           self.ANY_HTTPS_PAGE_T,
                                           fallback="https://blank.org")

        self.GEOLOCATED_URL_T = "wunderground hourly url"
        self.GEOLOCATED_URL = self.cfg.get(
            self.CS,
            self.GEOLOCATED_URL_T,
            fallback="https://www.wunderground.com/hourly/ca/location/",
        )

        self.GRAPH_FILENAME_T = "autosave png-pdf-eps filename"
        self.GRAPH_FILENAME = self.cfg.get(self.CS,
                                           self.GRAPH_FILENAME_T,
                                           fallback="graph.png")

        self.GRAPH_DPI_T = "autosave dpi"
        self.GRAPH_DPI = int(
            self.cfg.get(self.CS, self.GRAPH_DPI_T, fallback="600"))

        self.GRAPH_ORIENTATION_T = "autosave orientation"
        self.GRAPH_ORIENTATION = self.cfg.get(self.CS,
                                              self.GRAPH_ORIENTATION_T,
                                              fallback="landscape")

        self.GRAPH_PAPERTYPE_T = "autosave papertype"
        self.GRAPH_PAPERTYPE = self.cfg.get(self.CS,
                                            self.GRAPH_PAPERTYPE_T,
                                            fallback="letter")

        self.VERBOSE_T = "verbose"
        self.VERBOSE_ = bool(
            int(self.cfg.get(self.CS, self.VERBOSE_T, fallback="0")))
        self.VERBOSE = self.VERBOSE_ or args.verbose

        self.SHOW_X_HOURS_T = "display x hours"
        self.SHOW_X_HOURS = max(
            int(self.cfg.get(self.CS, self.SHOW_X_HOURS_T, fallback="6")), 1)

        self.MIN_HOURS_T = "minimum hours"
        self.MIN_HOURS = max(
            int(self.cfg.get(self.CS, self.MIN_HOURS_T, fallback="8")),
            self.SHOW_X_HOURS,
        )

        self.save_ini()  # save immediately to renew all required values

        # optional values that can be missing
        self.LATITUDE_T = "latitude"
        self.LONGITUDE_T = "longitude"
        self.LATITUDE = None
        self.LONGITUDE = None

        if args.latitude is not None:
            self.LATITUDE = args.latitude
        elif self.cfg.has_option(self.CS, self.LATITUDE_T):
            self.LATITUDE = float(self.cfg.get(self.CS, self.LATITUDE_T))

        if args.longitude is not None:
            self.LONGITUDE = args.longitude
        elif self.cfg.has_option(self.CS, self.LONGITUDE_T):
            self.LONGITUDE = float(self.cfg.get(self.CS, self.LONGITUDE_T))

        self.MISSING_LATLONG = self.LATITUDE is None or self.LONGITUDE is None

        self.browser = ChromeBrowser()
Ejemplo n.º 29
0
 def init(self):
     self.__forecast = Forecast().forecast(Forecast.TODAY)
     self.setHasConfigurationInterface(False)
     self.resize(125, 125)
     self.setAspectRatioMode(Plasma.Square)
Ejemplo n.º 30
0
 def __init__(self):
     self._id = datetime.today().strftime('%Y-%m-%d')
     self.bbc = Forecast()
     self.met = Forecast()
     self.actual = Forecast()