Ejemplo n.º 1
0
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

        self.w = weather.Weather()
    def amb_temp(self, timestep):
        """ambient temperature surrounding tank

        # if location of storage is inside
        # then a 15 deg ambient condition is assumed
        # elif location is outside then outdoor temperature is used

        Arguments:
            timestep {int} --

        Returns:
            float -- ambient temp surrounding tank degC
        """
        if self.location == 'Outside':

            w = weather.Weather(
                air_temperature=self.air_temperature).hot_water_tank()
            ambient_temp = w['air_temperature']['air_temperature'][timestep]

        elif self.location == 'Inside ':
            ambient_temp = 15.0

        else:
            print('Error in location definition')
        return ambient_temp
Ejemplo n.º 3
0
    def bot_reply(self):
        if '!! about' in self.user_message:
            return "Big fella! you not been talkin to me enough big fella, I am the teenage chatbot here to assist you. To see my commands type '!! help'"

        if '!! help' in self.user_message:
            return """
    	    (!! about): gives you a description of who I am\n
    	    (!! help): gives you the list of all the commands\n
    	    (!! say)<something>: I will say anything you tell me to following that command\n
    	    (!! dior): I will recite the first bar of pop smokes song dior #RIPpopSmoke\n
    	    (!! me)<something>: I will say whatever you tell me to followed by "yea thatss meee!"\n
    	    (!! weather man weather man): Gives the current weather report in baltimore\n
    	    """
        if '!! dior' in self.user_message:
            return """Said I'm never lackin', always pistol packing
            With them automatics, we gon' send him to heaven
            Wait, wait, wait, wait, aye, aye, woo (aw, s**t), huh (ha ha)
            Oh you feelin' sturdy, huh? (you feelin' sturdy, man)
            Shake some
            Shake it huh, shake it huh, shake it huh"""

        if '!! say' in self.user_message:
            replyIndex = 6 + self.user_message.find('!! say')
            return self.user_message[replyIndex:]

        if '!! me' in self.user_message:
            replyIndex = 5 + self.user_message.find('!! me')
            return self.user_message[replyIndex:] + " yea thatss meee!"

        if '!! weather man weather man' in self.user_message:
            w = weather.Weather()
            return "yea thass mee!\n" + w.get_weather()

        if '!!' in self.user_message:
            return "I noticed your message contained '!!' You're either really excited or.. you want to use a command. To see the commands type in '!! help'"
Ejemplo n.º 4
0
 def weather_label(self):
     value_str = str()
     wea_dic = dict()
     self.weastr = tkinter.StringVar()
     with open("data/user_info.json", "r") as file:
         data = json.loads(file.read())
     if not data["city"]:
         city = "成都"
     else:
         city = data["city"]
     try:
         wea_obj = weather.Weather(city)
         wea_dic = wea_obj.get_weather()
     except:
         value_str = "网络出错, 天气无法显示."
     wea_lab = tkinter.Label(self.chat_screen,
                             textvariable=self.weastr,
                             width=88,
                             height=1,
                             bg="white",
                             anchor="w")
     if wea_dic is None:
         value_str = "网络出错, 天气无法显示."
     else:
         for x in wea_dic.items():
             if x[0] in ("今日天气", "平均温度", "最高温度", "最低温度", "PM2.5", "空气质量",
                         "风力"):
                 value_str += str(x[0]) + ": " + str(x[1]) + " "
     self.weastr.set(value_str)
     wea_lab.place(x=155, y=10)
Ejemplo n.º 5
0
    def heat_resource(self):
        """accessing the heat resource

        takes the hp resource from the weather class

        Returns:
            dataframe -- ambient temperature for heat source of heat pump
        """

        HP_resource = weather.Weather(
            air_temperature=self.hp_ambient_temp['air_temperature'],
            water_temperature=self.hp_ambient_temp['water_temperature']
        ).heatpump()

        if self.hp_type == 'ASHP':

            HP_resource = HP_resource.rename(
                columns={'air_temperature': 'ambient_temp'})
            return HP_resource[['ambient_temp']]

        elif self.hp_type == 'WSHP':

            HP_resource = HP_resource.rename(
                columns={'water_temperature': 'ambient_temp'})
            return HP_resource[['ambient_temp']]

        else:
            print('ERROR invalid heat pump type')
Ejemplo n.º 6
0
def main():

    logging.basicConfig(filename=LOG_FILE,
                        level=logging.INFO,
                        format='%(asctime)s %(message)s')
    logging.info("Bustimes starting")

    with open('config.yaml') as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
    weather_api_key = config['weather']['api_key']
    lat = config['weather']['latitude']
    lng = config['weather']['longitude']
    logging.info('Weather API: %s', weather_api_key)
    logging.info('Weather latitude: %s', lat)
    logging.info('Weather longitude: %s', lng)
    weather_service = weather.Weather(weather_api_key, lat, lng)
    bus_api_key = config['bus']['api_key']
    bus_api_base_url = config['bus']['api_base_url']
    bus_data_feed = config['bus']['data_feed']
    logging.info('Bus API: %s', bus_api_key)
    logging.info("Bus API base URL: %s", bus_api_base_url)
    logging.info("Bus API data feed: %s", bus_data_feed)
    bus_service = bus.Bus(bus_api_key, bus_api_base_url, bus_data_feed)

    window = tk.Tk()

    app = BusTimes(window, bus_service, weather_service, config)

    window.mainloop()

    logging.info("Bustimes exiting")
Ejemplo n.º 7
0
    def __init__(self, team1, team2, length=None):
        self.over = False
        self.random_weather_flag = False
        self.teams = {"away": team1, "home": team2}
        self.archetypes = {
            team1.name: team1.archetypes,
            team2.name: team2.archetypes
        }
        self.offense_archetypes = {}
        self.defense_archetypes = {}
        self.inning = 1
        self.outs = 0
        self.top_of_inning = True
        self.last_update = ({}, 0)  #this is a ({outcome}, runs) tuple
        self.play_has_begun = False
        self.owner = None
        self.victory_lap = False
        if length is not None:
            self.max_innings = length
        else:
            self.max_innings = config()["default_length"]
        self.bases = {1: None, 2: None, 3: None}
        self.weather = weather.Weather(self)
        self.voice = None
        self.current_batter = None

        for this_team in [team1, team2]:
            for this_player in this_team.lineup + this_team.rotation:
                if this_player.name in this_team.archetypes.keys():
                    this_team.archetypes[this_player.name].modify_player_stats(
                        this_player)
Ejemplo n.º 8
0
    def __init__(self, master, config, *args, **kwargs):
        self.config = config
        self.f = tkinter.Frame(master, *args, **kwargs)
        self.make_month_table()
        self.make_day_table()
        lat, lon = self.config.get('general', 'weather_location').split(',')
        self.w = weather.Weather(
            lat, lon, self.config.getint('general', 'weather_update_interval'))
        self.city = geodata.get_town(lat, lon)
        self.c = calendarevents.CalendarEvents('calendar.csv')
        ok_widgets = ('time', 'date', 'week', 'temp', 'weekday', 'spacer',
                      'percipitation', 'wind', 'weather', 'smhi', 'headline',
                      'calendar', 'sunrise', 'sunset')
        widgets = [
            w.strip()
            for w in self.config.get('sidebar', 'widget_order').split(',')
        ]
        self.atributes = [{
            'name':
            w,
            'text_size':
            self.config.get(w, 'fontsize'),
            'font':
            self.config.get(w, 'font'),
            'orientation':
            self.config.get(w, 'orientation'),
            'anchor':
            self.config.get(w, 'anchor', fallback='center')
        } for w in widgets if w in ok_widgets]

        self.build_content_window()
        l = logging.getLogger(__name__)
        l.debug('INIT DONE')
Ejemplo n.º 9
0
def handle_start_help(message):
    my_bot.busy = True
    my_bot.weather = True
    my_bot.answer = ""
    try:
        my_bot.bot.send_message(message.chat.id, "Conntecting...")
        weather_checker = weather.Weather()
        my_bot.bot.send_message(message.chat.id, config.weather_intro)
        while my_bot.answer == "":
            pass
        location = my_bot.answer.split(" ")
        if my_bot.answer != config.stop_weather_request.lower():
            result = weather_checker.getWeather(location[0], location[1])
            my_bot.bot.send_message(message.chat.id, u"В городе " + location[1] +
                                                     u" сейчас " + result[1] +
                                                     u". Температура составляет " +
                                                     result[0] + u" градус(а) по Цельсию.")
        else:
            my_bot.bot.send_message(message.chat.id, config.stop_weather_answer)
    except LookupError:
        if len(location) != 2:
            my_bot.bot.send_message(message.chat.id, 
                                    config.ERROR_invalid_parameter)
        else:
            my_bot.bot.send_message(message.chat.id, 
                                    config.ERROR_invalid_city_country)
    except urllib2.URLError:
        my_bot.bot.send_message(message.chat.id, config.ERROR_connection_failed)
    finally:
        my_bot.busy = False
        my_bot.weather = False
        my_bot.answer = ""
Ejemplo n.º 10
0
def reply():
    body = request.values.get('Body', None)
    number = request.values.get('From', None)
    print("Sender Number: " + number)
    command = base_command.Command(body).command
    return_text = ''
    print("Command: " + command)
    if command == "help":
        response = helps.Help(body)
        return_text = response.exec()
    elif command == "stock":
        response = stock.Stock(body)
        return_text = response.exec()
    elif command == "mail":
        response = mail.Mail(body)
        return_text = response.exec()
    elif command == "weather":
        response = weather.Weather(body)
        return_text = response.exec()
    elif command == "translate":
        response = translate.Translate(body)
        return_text = response.exec()
    elif command == "movie":
        response = movies.Movie(body)
        return_text = response.exec()

    if return_text == '':
        send_message("please type !help for response", number)
    else:
        print("RETURN MESSAGE:", return_text)
        send_message(return_text, number)
    return str(return_text)
Ejemplo n.º 11
0
def main(logger):
    envse = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_NAME', 'DISCORDBOT_TOKEN']
    envsc = [
        'LOCATION', 'XRAIN_ZOOM', 'MANET', 'GOOGLE_MAPS_API_KEY',
        'DARK_SKY_API_KEY', 'CADVISOR', 'CONTAINERS', 'MORNING', 'EVENING',
        'XRAIN_LAT', 'XRAIN_LON', 'PORT'
    ]

    f = util.environ(envse, 'error')
    util.environ(envsc, 'warning')
    if f:
        logger.error('error: some environment variables are not set. exiting.')
        sys.exit(1)

    sendqueue = queue.Queue()

    httploop = asyncio.new_event_loop()
    ap = api.API(httploop, sendqueue, logger,
                 os.environ.get('DISCORDBOT_TOKEN'))
    threading.Thread(target=ap.run, name='api', daemon=True).start()

    wea = weather.Weather(sendqueue, logger)
    mon = monitoring.Monitoring(sendqueue, logger)
    scheduleloop = asyncio.new_event_loop()
    sched = Scheduler(sendqueue, wea, mon, logger, scheduleloop)
    threading.Thread(target=sched.run, name='scheduler', daemon=True).start()

    logger.debug('launch discord client')
    client = discordbot.DiscordClient(os.environ.get('DISCORD_CHANNEL_NAME'),
                                      sendqueue, wea, mon, logger)
    client.run(os.environ.get('DISCORD_TOKEN'))
Ejemplo n.º 12
0
def Weather(count):
    import gtts, weather, playsound, os
    weather = weather.Weather()

    location = weather.lookup_by_location("College Station")

    forecast_high = int(location.forecast()[0].high()) * 9 / 5 + 32
    forecast_low = int(location.forecast()[0].low()) * 9 / 5 + 32

    condition = location.condition().text()

    message = "The high for today is " + str(
        forecast_high) + " Fahrenheit, and the low is " + str(
            forecast_low) + " Fahrenheit. The condition should be " + condition

    tts = gtts.gTTS(text=message, lang="en")
    try:
        tts.save("Weather" + str(count) + ".mp3")
    except:
        pass

    try:
        playsound.playsound("Weather" + str(count) + ".mp3", True)
    except:
        pass

    os.remove("Weather" + str(count) + ".mp3")
Ejemplo n.º 13
0
 def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict]:
     print("----In submit")
     location = tracker.get_slot("location")
     w = weather.Weather()
     weather_report = w.get_current_weather(location)
     dispatcher.utter_message(w.format_weather(weather_report, location))
     dispatcher.utter_template("utter_submit", tracker)
     def test(self):
         weather_handle = weather.Weather()
         location = self.weather_handle.lookup_by_location(self.metropolis)
         condition = location.condition()
         print(condition['text'])
 
          # Get weather forecasts for the upcoming 5 days.
         forecastslist = location.forecast()[:5]
Ejemplo n.º 15
0
def print_weather(message):
    try:
        result = translator.translate(message.text)
        wet = weather.Weather(result.text)
        temperature = wet.load_weather()
        bot.send_message(message.chat.id, temperature)
    except Exception as e:
        bot.send_message(message.from_user.id, 'Город не найден')
 def compute_stats(self):
     weather_handle = weather.Weather()
     self.dates = []
     self.high_temperatures = []
     self.low_temperatures = []
     self.rainy_days_index = []
     self.current_condition = ""
     location = self.weather_handle.lookup_by_location(self.metropolis)
     condition = location.condition()
Ejemplo n.º 17
0
def wind_weather():

    i = inputs.weather()
    wind_weather = weather.Weather(
        wind_speed_10=i['wind_speed_10'],
        wind_speed_50=i['wind_speed_50'],
        roughness_length=i['roughness_length'],
        pressure=i['pressure'],
        air_temperature=i['air_temperature']).wind_turbine()
    print wind_weather
Ejemplo n.º 18
0
 async def on_message(self, message):
     # print('Message from {0.author}: {0.content}'.format(message))
     msg = message.content
     if '심심' in msg:
         await message.channel.send("$Game_Blackjack")
     if '날씨' in msg:
         # await message.channel.send("$weather 안산")
         weather.Weather()
     if '덥다' in msg:
         await message.channel.send("$weather 안산")
Ejemplo n.º 19
0
def second_level_commands():
    recognised_speech = speech.recognition()
    if recognised_speech:
        if 'weather' in recognised_speech:
            weather = forecast.Weather()
            speech.synthesis(weather.get_weather_string())
        elif any(news in recognised_speech for news in ['news', 'headline']):
            news_url = config.get('news', 'news_audio_url')
            news_file = urllib.URLopener()
            news_file.retrieve(news_url, 'news.mp3')
            audio_helper.play_audio('news.mp3')
Ejemplo n.º 20
0
 def __init__(self, logger, datadir):
     self.logger = logger
     self.weather = weather.Weather(self.logger, os.environ['OWM_API_KEY'],
                                    'default', os.environ['LAT'],
                                    os.environ['LON'],
                                    os.environ['KISHODAI'],
                                    os.environ['CITY'], datadir)
     self.monitor = monitor.Monitor(self.logger, self.weather,
                                    os.environ.get('DARK') is not None,
                                    datadir)
     self.weather.update()
     self.monitor.clear()
Ejemplo n.º 21
0
def go():
    print('Starting ... Toolkit/Yahoo_Weather')

    my = wea.Weather(unit=wea.Unit.CELSIUS)

    run = True
    while run:
        print('')
        query = cli.InputBox('Which city you want to check w/ Yahoo Weather?',
                             '[Q] ', 'Name of city (q for Quit): ')
        if query in {'0', 'q', 'bye', 'quit', 'exit'}:
            run = False
            print('')
        else:
            try:
                print('    ' + 'OK, searching ' + c_p + query + c_n + ' ...\n')
                loc = my.lookup_by_location(query)

                print('\n=== Current Weather===')
                title = loc.title
                atmosphere = loc.atmosphere
                wind = loc.wind
                astronomy = loc.astronomy
                condition = loc.condition

                print(title)
                print(condition.date)
                print('')

                print('Weather    : ', condition.text)
                print('Temp       : ', condition.temp, 'Celsius')
                print('Pressure   : ', atmosphere['pressure'],
                      '(Issue Here! psi/mb?)')
                print('Humidity   : ', atmosphere['humidity'], '%')
                print('Visibility : ', atmosphere['visibility'], 'km')
                print('Wind SPD   : ', wind.speed, 'km/h')
                print('Wind DIR   : ', wind.direction, 'DegreesNorth')
                print('Sunrise    : ', astronomy['sunrise'])
                print('Sunset     : ', astronomy['sunset'])

                print('\n=== Forecast ===')
                ruler = '%15s%8s%8s%8s%30s'
                print(ruler % ('Date', 'Day', 'Tmax', 'Tmin', 'Weather'))

                forecasts = loc.forecast
                for i in forecasts:
                    print(ruler % (i.date, i.day, i.high, i.low, i.text))

            except:
                print(
                    '\nSorry, cannot successfully retrieve data for %s from Yahoo Weather.'
                    % (c_red + query + c_n))
    return
Ejemplo n.º 22
0
def getWeatherInfo(loc, location):
    a = weather.Weather(weather.Unit.CELSIUS)
    result = ''
    for i in loc:
        if i['country'].upper() == "INDIA" and i['name'].upper(
        ) == location.upper():
            try:
                climate = a.lookup(i['woeid'])
                result = '☁ ' + result + i[
                    'name'] + ' : ' + climate.condition.text + '\n'
            except Exception:
                pass
    return result
    def test(self):
        weather_handle = weather.Weather()
        location = self.weather_handle.lookup_by_location(self.metropolis)
        condition = location.condition()
        print(condition['text'])

         # Get weather forecasts for the upcoming 10 days.
        forecastslist = location.forecast()[:5]
        for forecasts in forecastslist:
            print(forecasts['text'])
            print(forecasts['date'])
            print(forecasts['high'])
            print(forecasts['low'])
Ejemplo n.º 24
0
 def jobs(self):
     data = weather.Weather().getWeather()
     result = itchat.search_friends(remarkName="小仙女")
     wea = data['wea']
     temp1 = data['tem1']  # 最高温度
     temp2 = data['tem2']
     win_meter = data['win_meter']
     air_level = data['air_level']
     air_tips = data['air_tips']
     date = data['date']
     msg = '早上好,今天是{}\n天气:{}\n 最低温度:{},最高温度:{}\n 风速:{}\n空气质量:{}\n 来自亲亲的提示:{}' \
     .format(date, wea, temp2, temp1, win_meter, air_level, air_tips)
     itchat.send_msg(msg, result[0]['UserName'])
Ejemplo n.º 25
0
def regio(regio, datum_str='vandaag'):
    # Does the regio exist?
    regio = weather.Regio.by_id(regio.lower())
    if not regio:
        return flask.abort(404)

    # Change input to real date object
    datum = helpers.datums(datum_str)

    weer = weather.Weather().from_gae(regio=regio, datum=datum)
    return flask.render_template('regio.jinja',
                                 weer=weer,
                                 regio=regio,
                                 datum=datum)
Ejemplo n.º 26
0
def provincie(provincie, datum_str='vandaag'):
    # Does the provincie exist?
    provincie = weather.Provincie.by_id(provincie.lower())
    if not provincie:
        return flask.abort(404)

    # Change input to real date object
    datum = helpers.datums(datum_str)

    weer = weather.Weather().from_gae(provincie=provincie, datum=datum)
    return flask.render_template('provincie.jinja',
                                 weer=weer,
                                 provincie=provincie,
                                 datum=datum)
Ejemplo n.º 27
0
 def pogoda(self, thread_id):
     weather_obj = weather.Weather()
     location = weather_obj.lookup_by_location(CITY)
     forecasts = location.forecast()
     for forecast in forecasts[:3]:
         min = round(far2cel(int(forecast.low())))
         max = round(far2cel(int(forecast.high())))
         text = forecast.text()
         date = forecast.date()
         msg = Message(
             text=f'Pogoda na {date}: Od {min} do {max} stopni, {text}')
         self.send(msg,
                   thread_id=self.thread_id_,
                   thread_type=ThreadType.GROUP)
Ejemplo n.º 28
0
def main():
    try:
        log.info("<--------------START----------------->")

        log.info("Get Address based on Latitude and Longitude.")
        location_res = getlocation()
        _places_list = []
        city = location_res.get_cityname()
        state = location_res.get_statecode()
        if not city or not state:
            raise (errors.InputError().message, errors.InputError().expression)
        log.info(
            "Address extracted based on latitude and longitude => '%s,%s'" %
            (city, state))
        origin = ('%s %s' % (city, state))
        _places_list.append(origin)
        destination = ('%s %s' % (__destination_city__, __destination_state__))
        log.info("Now get the distance between %s and %s" %
                 (origin, destination))
        dist_req = distance_request.DistanceRequest(origin, destination)
        dist_res = distance_response.DistanceResponse()
        distance.Distance(dist_req, dist_res)
        _distance = dist_res.get_distance()
        _duration = dist_res.get_duration()
        if not _distance or not _duration:
            raise errors.Error(
                "Could not get distance or duration for the given destination.",
                "%s,%s" % (_distance, _duration))
        else:
            _places_list.append(destination)
        log.info(" Distance and duration between %s and %s is %s and %s" %
                 (origin, destination, _distance, _duration))
        weather_url = weather.get_weatherurl()
        output_format = weather.get_weatheroutputformat()
        log.info(_places_list)
        for place in _places_list:
            log.info("Invoke weather API for location %s" %
                     (place.split(",")[0]))
            weather_req = weather_request.WeatherRequest()
            weather_req.set_url(weather_url)
            weather_req.set_city(place.rsplit(" ", maxsplit=1)[0])
            weather_req.set_state(place.rsplit(" ", maxsplit=1)[1])
            weather_req.set_format(output_format)
            weather_res = weather_response.WeatherResponse()
            weather.Weather(weather_req, weather_res)
            _weatherResponse(weather_res)

        log.info("<---------------END------------------>")
    except errors.Error as err:
        print("%s %s" % (err.message, err.expression))
Ejemplo n.º 29
0
def test_PV_weather():

    i = inputs.weather()
    PV_weather = weather.Weather(
        DHI=i['DHI'],
        GHI=i['GHI'],
        DNI=i['DNI'],
        wind_speed_10=i['wind_speed_10'],
        wind_speed_50=i['wind_speed_50'],
        roughness_length=i['roughness_length'],
        pressure=i['pressure'],
        air_temperature=i['air_temperature'],
        air_density=i['air_density'],
        water_temperature=i['water_temperature']).PV()
    print PV_weather
Ejemplo n.º 30
0
    def weather_data(self):
        """gets PV weather data

        gets weather data from the excel sheet for the PV

        Returns:
            df -- dhi, ghi, dni, wind_speed, temp_air
        """
        PV_weather = weather.Weather(
            DHI=self.weather_input['DHI'],
            GHI=self.weather_input['GHI'],
            DNI=self.weather_input['DNI'],
            wind_speed_10=self.weather_input['wind_speed_10'],
            air_temperature=self.weather_input['air_temperature']).PV()
        return PV_weather