def selectMenu(): userSelect = 0 while userSelect == 0: userSelectM = input("请选择功能>>>>>:") if str(userSelectM) == '1': print("=" * 20 + "记事本" + "=" * 20) N.note() elif str(userSelectM) == '2': print("=" * 20 + "天气预报" + "=" * 20) W.get_weather() elif str(userSelectM) == '3': print("=" * 20 + "音乐解析" + "=" * 20) M.showMusicHtml() elif str(userSelectM) == '4': print("=" * 20 + "图片下载" + "=" * 20) I.imgMain() elif str(userSelectM) == "5": print("=" * 20 + "表情包生成" "" + "=" * 20) word = input("请输入你在表情包上生成的字>>>>>>>>>:") E.genImage(word) elif str(userSelectM) == '6': print("=" * 20 + "表情包生成" "" + "=" * 20) A.aMain() elif str(userSelectM) == '7': userSelect = 1 else: print("请选上面有的") userSelect == 0
def SYNTHESISonHit(pokemon): if (weather.get_weather() in [weather.SUNNYDAY, weather.DESOLATELAND]): pokemon.heal(pokemon.max_hp * 0.667) elif (weather.get_weather() in [weather.RAINDANCE, weather.PRIMORDIALSEA, weather.SANDSTORM, weather.HAIL]): pokemon.heal(pokemon.max_hp * 0.25) else: pokemon.heal(pokemon.max_hp * 0.5)
def do(self): if self.get_type() == "joke": joke.get_joke_text() elif self.get_type() == "weather": weather.get_weather() elif self.get_type() == "play": if music.channel1.get_queue() == None: for song in os.listdir('./music'): print song music.add_song_to_queue(song) elif self.get_type() == "pause": music.pause_song() elif self.get_type() == "resume": music.resume_song() elif self.get_type() == "skip": music.next_song() elif self.get_type() == "stop": music.stop_song() elif self.get_type() == "name": name.do() elif self.get_type() == "created": creators.do() elif self.get_type() == "mood": having_date.do() elif self.get_type() == "security": return security.toggle_security() elif self.get_type() == "selfie": camera_util.selfie() return False;
def alarm_end(alarm_time: datetime.datetime, alarm: dict, news_call: bool, weather_call: bool) -> None: """ This function runs when an alarm has gone off. The notification and log dictionaries are created including the necessary alarm data. If the user has checked news and weather checkboxes then news and weather information will be played. Covid Data Nwews will be plaayed on every alarm """ # Alarm Go off notification created alarm_notification = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'Alarm', 'title': ' Alarm scheduled for ' + str(alarm_time) + ' has gone off.', 'description': '' }) alarm_log = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'alarm', 'description': 'Alarm scheduled for ' + str(alarm_time) + ' has gone off.', 'error': '' }) new_notification(alarm_notification) info_log(alarm_log) tts("Alarm " + str(alarm_time) + "has gone off") if news_call == True: get_news(True) if weather_call == True: get_weather(True) get_covid_data(True)
def on_search(data): '''Will fetch zipcode from DB and return local weather''' zipcode = data["zipcode"] if check_zip(zipcode): data["weather"] = get_weather(zipcode) else: data["weather"] = get_weather("10001") SOCKETIO.emit('forecast', data, broadcast=False, include_self=True)
def test_get_weather_exception(self, get_mock: Mock, json_mock: Mock): """Test that get_weather raises WeatherError when no weather results.""" get_mock.return_value = requests.Response() json_mock.return_value = {} with self.app_context: location = LocationCoords(lat=100, long=200) with self.assertRaises(WeatherError): get_weather(location)
def on_forecast(data): '''Will fetch zipcode from DB and return local weather''' user = DB.session.query( models.Person).filter_by(email=data["email"]).first() zipcode = user.zipcode if check_zip(zipcode): data["weather"] = get_weather(zipcode) else: data["weather"] = get_weather( "10001" ) # Default for now. Will update when we can fetch the zipcode. SOCKETIO.emit('forecast', data, broadcast=False, include_self=True)
def get_response(message, sender): if message[0].lower() in ['hi', 'hey', 'hello']: return ("Hello %s" % get_user_name(sender)) elif message[0].lower() in ['shutdown']: return ("Just what do you think you're doing, %s?" % get_user_name(sender)) elif message[0].lower() in ['weather']: if message[1].lower() == 'in': return weather.get_weather(' '.join(message[2:])) else: return weather.get_weather(' '.join(message[1:])) elif message[0].lower() in ['quote']: return (quote.get_quote_of_the_day()) else: return ("I'm sorry %s, I'm afraid I can't do that." % get_user_name(sender))
def get_processingHumid(): with open("us_state_capitals.json", "r") as f: data = json.load(f) #data = list(data.values()) # print(data) states = list(data.keys()) reds = [] greens = [] blues = [] for state in states: item = data[state] w = weather.get_weather(lat=item['lat'], lon=item['lon']) #print(w) temp = float(w['temp']) humidity = str(w['humidity']) blue = int(humidity) * 2 if blue < 0: blue = 0 if blue > 255: blue = 255 blues.append(blue) greens.append(128) reds.append(100) return render_template("processingHumid.html", states=states, reds=reds, greens=greens, blues=blues)
def index(): #name = request.values.get('name') address = request.values.get('address') forecast = None if address: forecast = weather.get_weather(address) return render_template('index.html', forecast=forecast)
def get_weather(): """ Returns a line ready for the LCD with outside weather conditions """ weather_dict = weather.get_weather() return "It feels {}".format(weather_dict['out_feel'])
def test(): return render_template("test.html", weather = weather.get_weather(), quote = quote.format_quote(quote.get_quote()), food = food.get_food_master(), bus_bcc = bus.get_predictions_for("Busch Campus Center"), bus_hill = bus.get_predictions_for("Hill Center"))
def notify(): icon_path = "/home/dushyant/Desktop/Github/Weather-Notifier/weathernotifier/Weather-icon.png" place = get_location() resp = get_weather(place) print resp result = '' result += "Place : " + str(resp[0]["Place"]) result += "\nStatus : " + str(resp[6]) result += "\nCurrent Temperature (Celcius) : " + str(resp[1]["temp"]) result += "\nMax Temperature (Celcius) : " + str(resp[1]["temp_max"]) result += "\nMin Temperature (Celcius) : " + str(resp[1]["temp_min"]) result += "\nWind Speed (m/s) : " + str(resp[2]["speed"]) result += "\nHumidity (%) : " + str(resp[3]) result += "\nPressure (hpa) : " + str(resp[4]["press"]) result += "\nCloud Cover (%) : " + str(resp[5]) # print result # Notification Tool notify2.init("Weather Notifier") n = notify2.Notification("Weather Details", icon=icon_path) n.update("Weather Details", result) n.show()
def weather_forecast(request): city = 'raipur' print("City detected : ", city) results = get_weather(city) forecast = [] for i in range(0, 10): entry = {} entry['high'] = results['query']['results']['channel'][i]['item'][ 'forecast']['high'] entry['low'] = results['query']['results']['channel'][i]['item'][ 'forecast']['low'] entry['text'] = results['query']['results']['channel'][i]['item'][ 'forecast']['text'] entry['day'] = results['query']['results']['channel'][i]['item'][ 'forecast']['day'] entry['date'] = results['query']['results']['channel'][i]['item'][ 'forecast']['date'] text = results['query']['results']['channel'][i]['item']['forecast'][ 'text'] try: weather_img = Weather.objects.get(type=text) except: print("not for : ", text) entry['image'] = weather_img.image forecast.append(entry) #print(forecast) return render(request, 'user_panel/weather_forecast.html', {'forecast': forecast})
def handle_today(message): list = weather.get_weather(); l = list[0] response = '' emoji = weather.get_weatherEmoji(l[4]) response += '\U0001F4C5<b>{}</b> {} {},{}\n{}{}\n'.format(datetime.datetime.now().strftime("%d.%m.%Y %H:%M"),l[1],l[2],l[3],emoji,l[4]) JBot.send_message(message.chat.id, response, parse_mode='HTML')
def index(): name = request.values.get('name') location = request.values.get('location') forecast = None if location: forecast = weather.get_weather(location) return render_template('index.html', location=location, forecast=forecast)
def increment_day(self): """moves us 1 day ahead on the calender. Also eats food and and updates the daily weather. no return.""" cal = [('January', 31), ('February', 28), ('March', 31), ('April', 30), ('May', 31), ('June', 30), ('July', 31), ('August', 31), ('September', 30), ('October', 31), ('November', 30), ('December', 31)] self.day += 1 month = 0 for i in range(len(cal)): if cal[i][0] == self.month: month = i if self.day > cal[month][1]: self.day = 1 self.month = cal[(month + 1) % 12][0] if self.month == 'January': self.year += 1 self.consume_rations() self.weather = get_weather(self.miles_from_missouri, self.month) output = "" i = 0 for player in self.party: if player.health < 1: self.party.pop(i) disease = '' if player.sick: disease = player.sick[0] else: disease = "exhaustion" output += f"\nObituary alert!!! {player.name} has died of {disease}.\n" i += 1 if output: input(colored(output, 'red'))
def main(): lcd=LCD.LCD() lcd.blight(1) while(True): try: home_conditions = DHT.requestData() line1 = "{0:0.1f} C and {1:0.1f}%".format(home_conditions['temp'], home_conditions['hum']) weather_dict = weather.get_weather() line2 = "Outside feels %d" % (int(weather_dict['out_feel'])) line3 = "Rpi " + commands.getoutput('vcgencmd measure_temp') lcd.sendText(1, line1) lcd.sendText(2, line2) time.sleep(10) lcd.sendText(1, line1) lcd.sendText(2, line3) time.sleep(10) except Exception,e: print e lcd._cleanUp() quit() except KeyboardInterrupt: print 'User interrupted' lcd._cleanUp() quit()
def get_processing3(): with open("us_state_capitals.json", "r") as f: data = json.load(f) #data = list(data.values()) print(data) states = list(data.keys()) reds = [] greens = [] blues = [] for state in states: item = data[state] w = weather.get_weather(lat=item['lat'], lon=item['lon']) print(w) temp = float(w['temp']) humidity = str(w['humidity']) red = int(temp * 5) if red < 0: red = 0 if red > 255: red = 255 reds.append(red) greens.append(128) blues.append(128) return render_template("processing3.html", states=states, reds=reds, greens=greens, blues=blues)
def update_twitter_name(consumer_key, consumer_secret, access_token, access_token_secret, cityid, appid, name): ''' Update your Twitter name :param consumer_key: Twitter app consumer key :param consumer_secret: Twitter app consumer secret :param access_token: Twitter app access token :param access_token_secret: Twitter app access token secret :param cityid: Your city ID :param appid: Your OpenWeatherMap API key :param name: Your Twitter name (replace "-weather-" to emoji) :return: ''' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) weather_data = get_weather(cityid, appid) emoji = weather_emoji(weather_data) twitter_name = name.replace("-weather-", emoji) return api.update_profile(name=twitter_name)
def read_weather(): # Currently, weather will be a dictionary with a comment, temp, and max. location = settings.get_preference('location') w = get_weather(location) say('The weather for %s includes %s' %(location, w['comment'])) say('It is currently %d. Expect it to get %.2f degrees warmer' %(w['temp'], w['max'] - w['temp']))
def pipeline(df_city, df_metadata): # Kopia wybranych kolumn z oryginalnego zbioru print('Kopiowanie danych') working_city = df_city[['dataid', 'local_15min', 'grid']].copy() # Usunięcie wsyzstkich wierszy zawierających NA (odpada 0,005% zbioru) print('Usuwanie "NA"') working_city = working_city.dropna() # Stworzenie kolumny 'city' na podstawie zbioru metadanych print("Tworzenie kolumny 'city'") working_city['city'] = working_city.apply( lambda row: df_metadata.loc[df_metadata['dataid'] == row['dataid'], 'city'], axis=1) # Stworzenie kolumny 'state' na podstawie zbioru metadanych print("Tworzenie kolumny 'state'") working_city['state'] = working_city.apply( lambda row: df_metadata.loc[df_metadata['dataid'] == row['dataid'], 'state'], axis=1) # Poprawienie wartosci czasu, a nastepnie zmiana typu danych na timestamp print("Poprawienie czasu") working_city.local_15min = working_city.local_15min.apply(trim_time) working_city.local_15min = pd.to_datetime(working_city.local_15min) # Pobranie stacji pogodowych i danych geolokalizacyjnych dla każdego miasta print("Pobieranie danych geolokalizacyjnych") cities_meta = get_location_and_station_per_dataid(df_metadata, working_city) print(cities_meta) # Stworzenie kolumn i pobranie wartości 'station_id', 'latitude', 'longitude' print("Tworzenie kolumn ze stacja i lokalizacja") location_frame = working_city.apply( lambda x: pd.Series( location_and_station_per_dataid(str(x['local_15min'].date()),cities_meta), index=['station_id', 'latitude', 'longitude']), axis=1, result_type='expand') working_city = pd.concat([working_city, location_frame], axis=1) print(working_city) # Stworznenie kolumn i pobranie wartości tempAvg, windspeedAvg, pressureMax, humidityAvg, winddirAvg print("Tworzenie kolumn z danymi pogodowymi") weather_frame = working_city.apply( lambda x: pd.Series( get_weather(x['local_15min'], x['station_id']), index=['temp_avg', 'wind_speed_avg', 'wind_dir_avg', 'pressure_max', 'humidity_avg']), axis=1, result_type='expand') working_city = pd.concat([working_city, weather_frame], axis=1) # Dodanie kolumny, która sprawdza czy dzień był wolny od pracy (weekendy i święta) working_city['holiday'] = working_city.apply( lambda row: check_if_holiday(row.local_15min.date(), STATES.get(row.state)), axis=1) print("Koniec") return working_city
def send_message(location): client = Client(account, token) weather_message = get_weather(location) message = client.messages.create(from_='+12085475915', to='+8615990184749', body=weather_message) print(message.sid)
def handle_allActions(sender, action, ai_reply): if action == 'action.getNews': smart_object = qr.get_news_quick_reply() page.send(recipient_id=sender, message='Choose any one of these sources:', quick_replies=smart_object) elif action == 'smalltalk.greetings.hello': quickreply_mini = [ QuickReply(title='news', payload='news_hello'), QuickReply(title='weather', payload='weather') ] message_ai = ai_reply['result']['fulfillment']['speech'] page.send( recipient_id=sender, message=message_ai + '! Click on the button below, or you can simply text What is the news? For info on weather tap on weather', quick_replies=quickreply_mini) elif action == 'action.getWeather': if 'cityName' in ai_reply['result']['parameters']: city = ai_reply['result']['parameters']['cityName'] page.send(recipient_id=sender, message=w.get_weather(city)) else: reply = ai_reply['result']['fulfillment']['speech'] if reply is None or reply == "": reply = "Okay" page.send(recipient_id=sender, message=reply)
def read_weather(): # Currently, weather will be a dictionary with a comment, temp, and max. location = settings.get_preference('location') w = get_weather(location) say('The weather for %s includes %s' % (location, w['comment'])) say('It is currently %d. Expect it to get %.2f degrees warmer' % (w['temp'], w['max'] - w['temp']))
def process_chat_message(msg): text = msg['text'] chat_id = str(msg['from']['id']) print(chat_id + ': ' + text) if text == 'Установить город': reply = 'Отправь мне свой город' waiting_for_cities[chat_id] = True elif text == 'Узнать погоду': # если бот уже запомнил город человека - узнаем погоду в этом городе. # иначе просим установить город if chat_id in cities: city = cities[chat_id] reply = get_weather(city) else: reply = 'Сначала установи город.' else: # если бот ждет от пользователя город - то сохраняем пользовательский ввод. # иначе говорим, что не поняли пользователя if chat_id in waiting_for_cities and waiting_for_cities[ chat_id] == True: cities[chat_id] = text waiting_for_cities[chat_id] = False reply = 'Устанавливаю город ' + text else: reply = 'Я еще совсем маленький и не понимаю человеческую речь. Воспользуйся кнопками, пожалуйста.' buttons = [['Установить город', 'Узнать погоду']] return reply, buttons
def weather(self, channel, user, command): from weather import get_weather from location import get_woeid class WeatherOptions(object): def __init__(self, metric=False, forecast=1): self.metric = metric self.forecast = forecast try: location = command.split('.weather')[1].strip() woeid = None try: woeid = get_woeid(location) except: woeid = location results = get_weather(woeid, WeatherOptions()) msg = 'It is %(current_condition)s in %(city)s with a high of %(high)s and low of %(low)s, the current temperature is %(current_temp)s %(units)s' % dict( current_condition=str(results['current_condition']).lower(), city=str(results['city']), current_temp=str(results['current_temp']), units=str(results['units']), high=str(results['forecasts'][0]['high']), low=str(results['forecasts'][0]['low']), ) except: msg = 'Please provide a valid postal code' self.msg(channel, msg) self.logger.log("<%s> %s" % (self.factory.nickname, msg))
def get_weather(update, context): ''' Inform user about the weather ''' import weather myCity = "Pato Branco" temperature, temperature_feelslike, humidity, skyCondition, uvi = weather.get_weather( myCity) if skyCondition == "Clear": skyCondition = "limpo" if uvi < 5.9: msg = "Temperatura: " + '{:02.2f}'.format( temperature ) + "ºC\nEstado do Céu: " + skyCondition + '\nRaios UV estão seguros!\nUmidade: ' + str( humidity) elif (uvi > 5.9) and (uvi <= 7.9): msg = "Temperatura: " + '{:02.2f}'.format( temperature ) + "ºC\nEstado do Céu: " + skyCondition + '\nRaios UV estão no nível Laranja (' + str( uvi) + '), ou seja, muito altos!\nUmidade: ' + str(humidity) elif uvi > 7.9: msg = "Temperatura: " + '{:02.2f}'.format( temperature ) + "ºC\nEstado do Céu: " + skyCondition + "! " + '\nRaios UV estão no nível Vermelho (' + str( uvi) + '), então não saia no sol\nUmidade: ' + str(humidity) update.message.reply_text(msg)
def dailyDigest(config): print("Sending daily digest.") to = config["email"]["admin"] #Get the date. lt = time.localtime() d = date() #Get the weather. location = config["Weather"]["default_location"] json_data = weather.get_weather(location) forecast = weather.digestable(json_data) #Get upcoming calendar events, if there are any. events = "" upcoming = calendarLib.getUpcomingEvents(config["calendar"]["url"], config["calendar"]["timezone"]) for event in upcoming: if event.date[0] == lt[0] and event.date[1] == lt[1] and event.date[ 2] == lt[2]: events += event.prettyPrint(False) + "\n" if events != "": events = "Today's events: \n" + events else: events = "You have no events today!\n" output = "Good morning! It is " + d + ". " + forecast + "\n" + events + "Hope you have a great day!" print("Sending: ") print(output) send_text(config, to, output) print("Getting top reddit post.") d = reddit.digestable(config) print("Sending: " + d["title"]) t = "Top post on /r/" + config["reddit"]["sub"] + ": " + d["title"] if d["is_photo"]: send_attachment(config, to, t, d["location"]) else: send_text(config, to, t + " @ " + d["url"])
def first_callback(bot, update): call = update.callback_query message = call.message chat_id = message.chat_id if call.data == 'yes': bot.edit_message_text(chat_id=chat_id, message_id=message.message_id, text='Главная страница', reply_markup=menu_markup) elif call.data == 'weather': bot.edit_message_text(chat_id=chat_id, message_id=message.message_id, text=weather.get_weather(town[0]), reply_markup=menu_markup) elif call.data == 'stock': bot.edit_message_text(chat_id=chat_id, message_id=message.message_id, text='Выберете нужное', reply_markup=first_stock_markup) elif call.data == 'crypto': bot.edit_message_text(chat_id=chat_id, message_id=message.message_id, text='Выберете нужное', reply_markup=crypto_markup) elif call.data == 'btcusd' or call.data == 'ethusd' or call.data == 'etpeth' or call.data == 'xmrusd': x = crypto.BitFinex(call.data) mid = x.mid() bot.edit_message_text(chat_id=chat_id, message_id=message.message_id, text='PRICE - ' + mid, reply_markup=crypto_markup)
def outdoor(): """ Shows outdoor conditions """ return render_template('outdoor.html', today=get_weather(), forecast=get_forecast(1))
def ehco_message(message): if message.chat.type == 'private': if message.text == 'Случайное число': bot.send_message(message.chat.id, str(random.randint(0, 100))) elif message.text == 'Погода': bot.send_message( message.chat.id, "Погода в {} {}".format(location, get_weather(location))) elif message.text == 'Установить город': msg = bot.reply_to(message, "Введите свой город") bot.register_next_step_handler(msg, set_location) elif message.text == 'Курс $': bot.send_message(message.chat.id, currency_chech('USD')) elif message.text == 'Курс €': bot.send_message(message.chat.id, currency_chech('EUR')) elif message.text == 'Узнать новости': news_res = news_check() for i in range(0, 3, 2): message_news = '' for i, j in zip(news_res[i], news_res[i + 1]): message_news += i message_news += '\n' message_news += j message_news += '\n\n' bot.send_message(message.chat.id, message_news) if message.text in hello_list: bot.send_sticker(message.chat.id, hi_optimus) elif message.text in bye_list: bot.send_sticker(message.chat.id, bye_optimus)
def place(): """Displays The place page defaulting in GET to ask the user for input then swapping to post to display the required information. """ data = '' image = '' error = '' if request.method == 'POST': place = request.form.get('place_name') data = places.find_place(place) try: image = places.get_photo_request( data['candidates'][0]['photos'][0]['photo_reference']) except IndexError: pass if image: pass else: data = '' image = '' error = 'Place Not Found Try Again' return render_template('place.html', title='Places', data=data, image=image, weather_icon=weather.get_weather(), error=error)
def main(city): con = db.connect() db.create_table(con) response = weather.get_weather(city) record = weather.format_response(response) db.insert_record(con, record) con.close()
def main(): dic_weather = { '晴れ': 'sunny', '曇り': 'cloud', '雨': 'rain_cloud', '雪': 'snow_cloud', '曇時々晴': 'barely_sunny', } dic_date = {'今日': 0, '明日': 1, '明後日': 2} w = weather.get_weather(130010) t = w['forecasts'][dic_date['今日']] telop = t['telop'] # 辞書にない天気が来たら絵文字に空文字を設定する if telop in dic_weather: emoji = ':' + dic_weather[telop] + ':' else: emoji = "" # テキストファイル読み込み f = open('../token.txt', 'r') token = f.read() # print(token) # APIトークンを設定する slack = Slacker(token) # Slackにメッセージを送信する slack.chat.post_message('agenda-bot-test', '今日の天気は%sです%s' % (telop, emoji), as_user=True)
def index(): address = request.values.get('address') forecast = None #will only pass through function if there is an address if address: forecast = weather.get_weather(address) return render_template('index.html', forecast=forecast)
def check(): img = ["grass.jpg", "drygrass.jpg", "hddesert.jpg"] zips = [65733, 95616, 94133] dataw = [] datat = [] for z in zips[:]: weather.get_weather(z) dataw.append(weather.get_sky(z)) datat.append(weather.get_temp(z)) print dataw print datat for z in zips[:]: for i in img[:]: for t in datat[:]: main_color(i, t, z)
def get_all(): # Zimmerli #lat = 40.4991876 #lon = -74.4473217 lat = request.args.get("lat") lon = request.args.get("lon") return flask.jsonify({"bus": bus.get_nearby(lat, lon), "events": events.get_nearby(lat, lon), "sports": sports.get_scores(), "weather": weather.get_weather(lat, lon)})
def turn_on_if_above_threshold(): lat = request.args.get('lat') lon = request.args.get('lon') threshold = request.args.get('threshold') current_weather = weather.get_weather(lat, lon) if current_weather >= threshold: turn_on() return "turning on. weather is %s threshold is %s" % (current_weather, threshold) return "not turning on. weather is %s threshold is %s" % (current_weather, threshold)
def get_city(state, city): weather = get_weather(city, state) temperature = weather['temperature_string'] lat = weather['display_location']['latitude'] longi = weather['display_location']['longitude'] photos = get_photos(lat, longi) return render_template('city.html', city=city.capitalize(), state=state.upper(), weather=temperature, photos=photos)
def get_weather(): # Hill Center #lat = 40.5220011 #lon = -74.46236700000001 lat = request.args.get("lat") lon = request.args.get("lon") return flask.jsonify(weather.get_weather(lat, lon))
def connect_feature(file_name1, file_name2): file1 = open(file_name1) file2 = open(file_name2, 'w+') weather_feature = weather.get_weather() line = file1.readline() features = list() while line: temp_list = list() line_list = line.strip().split(',') temp_list.append(line_list[3]) #if line_list[0] == '10': # temp_list.append('1') #else: # temp_list.append('2') day = int(line_list[1]) holiday = isHoliday(day) if holiday == 2: temp_list.append(str(2)) if day == 43 or day == 66 or day == 67 or day == 158: temp_list.append(str(8)) elif day == 68 or day == 69 or day == 70 or day == 159: temp_list.append(str(9)) elif day == 44 or day == 71 or day == 72 or day == 160: temp_list.append(str(10)) elif holiday == 3: if day == 161: temp_list.append(str(1)) temp_list.append(str(1)) elif day == 76: temp_list.append(str(1)) temp_list.append(str(5)) elif holiday == 1: temp_list.append(str(1)) temp_list.append(str(day%7 + 1)) elif holiday == 4: if day %7 > 0 and day %7 < 6: temp_list.append(str(1)) temp_list.append(str(day%7)) elif day % 7 == 0: temp_list.append(str(2)) temp_list.append(str(7)) elif day %7 == 6: temp_list.append(str(2)) temp_list.append(str(6)) #temp_list[1] = (str(day%7 + 1)) #temp_list[2] = (str(isHoliday(day))) temp_list.append(str(int(line_list[2]))) #print weather_feature[str(day)] temp_list.extend(weather_feature[str(day)][1:]) features.append(','.join(temp_list)) file2.write(','.join(temp_list) + '\n') line = file1.readline() file1.close() file2.close() return features
def get(self): humidity, temperature = get_weather() data = {'data': {'temperature': '', 'humidity': ''}} if humidity is not None: data['data']['humidity'] = str(int(humidity)) if temperature is not None: data['data']['temperature'] = str(int(temperature)) data['data']['timestamp'] = datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%M:%S') return data
def aweather(self): try: res = weather.get_weather('daxx0002') return 'Temp: %sC, Today: %s [%s:%s] Tommorow: %s [%s:%s]' % ( res['current_temp'], res['forecasts'][0]['condition'], res['forecasts'][0]['high'], res['forecasts'][0]['low'], res['forecasts'][1]['condition'], res['forecasts'][1]['high'], res['forecasts'][1]['low']) except: pass
def explore(): #Zimmerli #lat = 40.4991876 #lon = -74.4473217 lat = float(request.args.get("lat")) lon = float(request.args.get("lon")) return render_template("explore.html", bus = bus.get_nearby(lat, lon), events = events.get_nearby(lat, lon), sports = sports.get_scores(), weather = weather.get_weather(lat, lon))
def SOLARBEAMonTry(attacker, defender, move): if (attacker.remove_volatile(status.TWOTURNMOVE)): # return (True,) return True if (weather.get_weather() in [weather.SUNNYDAY, weather.DESOLATELAND]): # return (True,) return True attacker.add_volatile(status.TWOTURNMOVE, "SOLARBEAM") log.message(attacker.template.species + " is gathering light") # return (False, " is gathering sunlight") return False
def loop(): weather.get_weather() newpacket.packet() f=open("../../data/packet.dat","r") lines = f.readlines() f.close() weatherData=lines[0].split(",") lon=weatherData[0] lat=weatherData[1] time_packet = getTime(lat,lon) client.publish ("/topic/0", time_packet) #***************WEATHER******************* weather_packet = '' for i in range(2, len(weatherData) - 1): #Creating a # separated string for sending. weather_packet += weatherData[i] + '#' client.publish ("/topic/1", weather_packet) #***************REMINDER******************* f = open("../../data/reminder.txt", "r") reminder = f.readlines() reminder_packet = reminder [0] client.publish ("/topic/2", reminder_packet) f.close #***************TO-DO******************* f = open("../../data/TODO.txt", "r") for todo in f: client.publish("/topic/3", todo) f.close #***************RSS******************* f = open("../../data/rss","r") for headline in f: client.publish("/topic/4",headline) f.close time.sleep(9) return
def weather(location_code): # Create the command line parser. cli_parser = create_cli_parser() # Get the options and arguments. args = cli_parser.parse_args([location_code]) weather_stats = get_weather(location_code,args) print weather_stats return jsonify({"data": weather_stats})
def notify_weather(droid): """Display the weather at the current location in a notification.""" # print 'Finding ZIP code.' location = droid.getLastKnownLocation().result if 'gps' in location: location = location['gps'] else: location = location['network'] print 'Location: ', location['latitude'], location['longitude'] result = weather.get_weather(location['latitude'], location['longitude']) msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result droid.notify('Weather Report', msg)
def say_weather(droid): """Speak the weather at the current location.""" location = droid.getLastKnownLocation().result if 'gps' in location: location = location['gps'] else: location = location['network'] print 'Location: ', location['latitude'], location['longitude'] result = weather.get_weather(location['latitude'], location['longitude']) msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result # droid.notify('Weather Report', msg) droid.ttsSpeak(msg)
def echo(bot, update): message = update.message.text.lower() if message.find(u'погода') != -1 or message.find(u'температура') != -1: weather = get_weather() # generate_img('{}'.format(weather['temp']), weather['description'], update.message.chat_id) # file_name = 'answers/weather-{}.png'.format(update.message.chat_id) # path = os.path.join(os.path.dirname(os.path.dirname(__file__)), file_name) # img_file = open(file_name, 'rb') bot.sendMessage(update.message.chat_id, text=u'Сейчас {}, {}°'.format(weather['description'], weather['temp'])) elif message.startswith(u'можно'): img_file = open('answers/answer{}.png'.format(random.randint(1, 21)), 'rb') bot.sendPhoto(update.message.chat_id, photo=img_file) else: img_file = open('answers/answer{}.png'.format(random.randint(1, 20)), 'rb') bot.sendPhoto(update.message.chat_id, photo=img_file)
def all_weather(): # Create the command line parser. cli_parser = create_cli_parser() all = [] # Get the options and arguments. for location_code in ["95131", "10001", "95035", "95132"]: args = cli_parser.parse_args([location_code]) weather_stats = get_weather(location_code,args) all.append(weather_stats) print all return jsonify({"data": all})
def handle_msg(xml_recv, from_user, to_user): content = xml_recv.find('Content').text # 天气 if content == 'tq': city = '武汉' weather = get_weather(city, from_user, to_user) print weather return weather # 帮助 elif content == u'h' or content == u"帮助": reply_msg = config.STR_HELP # 星座 elif content in config.STAR_INFO: reply_msg = get_astro(content) else: reply_msg = u'谢谢你的回复与关注!小姻会在后台看到你的消息,欢迎注册缘分社区,在那寻求你的另一半,有疑问可以加QQ:2118892572咨询[调皮]~~' reply_msg = config.MSG_TXT % (from_user, to_user, str(int(time.time())), reply_msg) return reply_msg
def get_weather(request): town = request.matchdict.get('town', 'Paris') temp_per = Temperature.get_by(city=town) temp = 0 if temp_per: temp = temp_per.temperature else: d = weather.get_weather(town) temp = d[u'data'][u'current_condition'][0][u'temp_C'] temp_per = Temperature(city=town, temperature=temp) temp_per.save() return Response(""" <div style="text-align: center"> <div style="font-size: 72px">{}</div> <div style="font-size: 144px">{}°C</div> <div style="font-size: 24px">Current temperature</div> </div>"""\ .format(town, temp))
def handle_event(xml_recv, from_user, to_user): event_type = xml_recv.find("Event").text # 关注事件 if event_type == "subscribe": content = config.STR_SUB # 取消关注 elif event_type == "unsubscribe": content = "" elif event_type == "CLICK": event_key = xml_recv.find("EventKey").text # 天气 if event_key == "WEATHER": city = "武汉" weather = get_weather(city, from_user, to_user) return weather # 帮助 elif event_key == "HELP": content = config.STR_HELP # 往期回顾 elif event_key == "REVIEW": header = config.MSG_IMG_TXT_HEADER % (from_user, to_user, "1") item = config.MSG_IMG_TXT_ITEM % ( "往期回顾", "往期的各种丰富的线下同城活动……", "http://mmbiz.qpic.cn/mmbiz/68j2HjK6ejAmhTiahhZSyxzicOiaDicmbs8OQDRGgnhkWg8lbFOfVPSBHrQfTGDYQQM6GwENic7FLyaYf1qta0rMChg/0?tp=webp", "http://mp.weixin.qq.com/s?sn=e9058cab7bc308136b38e6aad910ce35&mid=202381233&idx=1&plg_auth=1&__biz=MzA3NDE4NzU3NQ%3D%3D#rd", ) foot = config.MSG_IMG_TXT_FOOT % "0" return header + item + foot elif event_key == "STAR": content = config.STR_STAR else: content = "" else: content = "" reply_msg = config.MSG_TXT % (from_user, to_user, str(int(time.time())), content) return reply_msg
def current_weather(): lat = request.args.get('lat') lon = request.args.get('lon') return weather.get_weather(lat, lon)
def chat(): # keyword conditions condnext = False condweather = False condtime = False condlocation = False condtemp = False condkey = False condresponse = False foundinfo = False condtrain = False condcountry = False condspellcheck = True # global variables conversation = [] location = '' prevlocation = location time = 'today' key = '' keytemplate = [] fulltime = '' numdays = '' logstr = '' printstr = '' responsedict = {} # Dictionary to hold all inputs without predefined responses. This dictionary will be written into predefined_responses.txt before exiting the program. # read data files citylist = readfile.readfile('cities.txt') keylist = readfile.readfile('keywords.txt') timelist = readfile.readfile('time.txt') condlist = readfile.readfile('conditions.txt') numlist = readfile.readfile('numbers.txt') countrylist = readfile.readfile('countries.txt') exitlist = ['exit', 'quit', 'bye', 'ok'] # Greeting message printstr = 'Hello! You can ask me questions about the weather in any major city in the world. What would you like to know?' print printstr logstr += '\n\n' + printstr # Start main loop while True : foundinfo = False condtrain = False condcountry = False # read input from user input = raw_input('\nMe > ') logstr += '\nMe > ' + input + '\nBot > ' if input in exitlist: if input == 'ok': exitans = raw_input("Do you want to quit? (y/n)") if exitans in ('y','Y','Yes','YES','yes'): break else: continue break if input == 'disable spellcheck': condspellcheck = False continue if input == 'enable spellcheck': condspellcheck = True continue condcorrected = False if condspellcheck: corrected_input = '' for i in input.split(): str = spellcheck.correct(i) if str != i: condcorrected = True corrected_input += str + ' ' if condcorrected: print 'did you mean: \"' + corrected_input + '\"?' input = corrected_input currentstring = input.split() conversation.append(currentstring) # Start searching input for each of the keywords if input == 'train': condtrain = True printstr = 'Entering training mode. Enter input and response seperated by a "|": input|response. Type "exit" to quit training mode' print printstr logstr += '\n' + printstr + '\n' while True: traininput = raw_input('>') if traininput == 'exit': break if traininput.find('|') < 0: printstr = 'Format error: use input|response' print printstr logstr += '\n' + printstr + '\n' continue traininput = traininput.split('|') responsedict[traininput[0]] = traininput[1] if condtrain: continue for i in countrylist: for j in currentstring: if lower(i[0]) == lower(j): printstr = 'Which city in ' + i[0] + '?' condcountry = True foundinfo = True break if condcountry: print printstr logstr += printstr continue if 'next' in input: foundinfo = True condnext = True condtime = False numdays = currentstring[currentstring.index('next') + 1] for i in numlist: if numdays == i[0]: numdays = i[1] break if re.match('[0-9]*$',numdays): numdays = int(numdays) else: numdays = '' if 'weather' in input: foundinfo = True condweather = True condkey = False condtemp = False key = '' keytemplate = [] # get key from input for i in keylist: if i[0] in input: if 'sunday' in lower(input) and i[0] == 'sun': break else: foundinfo = True condkey = True condweather = False condtemp = False key = i[0] keytemplate = i break # get time from input for i in timelist: if lower(i[0]) in input: foundinfo = True condtime = True numdays = '' if lower(i[0]) != 'today' and lower(i[0]) != 'tomorrow': time = i[1] fulltime = i[0] break else: time = i[0] fulltime = time break if fulltime == '': fulltime = time if numdays != '': condtime = True if numdays > 4: printstr = 'Forecast is available only for the next 4 days.' print printstr logstr += '\n' + printstr + '\n' else: time = '' fulltime = '' count = numdays # get location from input for i in citylist: if lower(i[0]) in input: foundinfo = True condlocation = True location = i[0] break # find if a new location has been mentioned. if not, don't fetch data again if location != prevlocation: newlocation = True condlocation = True prevlocation = location else: newlocation = False if location is '': if prevlocation is '': condlocation = False else: location = prevlocation newlocation = False location = location.replace(' ','-') #Google requires a '-' in 2-word city names result = False # get temperature from input if 'temperature' in input: foundinfo = True condtemp = True # User gave no infomation about weather. Switching to general predefined response based chat if not foundinfo: response = predefined_responses.respond(input, responsedict) if response == '': printstr = "I don't know what that means. If I asked you the same question, what would you reply?" print printstr logstr += printstr responseinput = raw_input('Me > ') logstr += '\nMe > ' + responseinput if not responseinput in ('exit', 'quit'): responsedict[input] = responseinput print 'response learnt' else: printstr = response print printstr logstr += printstr continue if condlocation: if newlocation: #If location hasn't changed, don't fetch data again. It's already available printstr = 'Fetching weather information from Google...' print printstr logstr += printstr # Call Google weather to get current weather conditions google_result = weather.get_weather(location) if google_result == {}: print 'Could not get data from google.' continue # We have a valid location. Get further information # User has asked about temperature. Return temperature information and continue if condtemp: printstr = temperature.temperature(google_result, time) print printstr logstr += printstr continue # User has asked about a specific weather condition. Print information. There are 2 possibilities: # 1. Find the condition in the next n days # 2. Find the condition in a specified day if condkey: # 1. User has asked about a specific condition in the 'next x days'. Return appropriate response printstr = '' timecounter = 0 day_of_week = '' condition = '' if numdays != '': for i in google_result['forecasts']: count -= 1 if count < 0: break if key in lower(i['condition']): result = True day_of_week = i['day_of_week'] condition = i['condition'] break for i in timelist: if i[0] != 'today' and i[0] != 'tomorrow': if i[1] == day_of_week: fulltime = i[0] break if result: printstr = keytemplate[3] + keytemplate[0] + ' on ' + fulltime else: printstr = keytemplate[4] + keytemplate[0] + ' in the next ' + str(numdays) + ' days.' print printstr logstr += printstr continue # 2. User has asked about a particular condition on a particular day. Return appropriate response if time != 'today' and time != 'tomorrow': for i in google_result['forecasts']: if i['day_of_week'] == time: if key in lower(i['condition']): printstr = keytemplate[3] + keytemplate[0] + ' on' else: printstr = keytemplate[4] + keytemplate[0] + ' on' elif time == 'today': fulltime = time if key in lower(google_result['current_conditions']['condition']): printstr = keytemplate[1] + keytemplate[0] else: printstr = keytemplate[2] + keytemplate[0] elif time == 'tomorrow': fulltime = time if key in lower(google_result['forecasts'][1]['condition']): printstr = keytemplate[3] + keytemplate[0] else: printstr = keytemplate[4] + keytemplate[0] printstr = printstr + ' ' + fulltime print printstr logstr += printstr continue # User is asking about today's weather. Print details elif time == '' or time == 'today' : printstr = sentence.sentence(google_result['current_conditions']['condition'], time) printstr += ' ' + fulltime + '. ' + google_result['current_conditions']['humidity'] + ' ' if google_result['current_conditions'].has_key('wind_condition'): printstr += google_result['current_conditions']['wind_condition'] print printstr logstr += printstr continue # User is asking about weather of a particular day. Print details elif time == 'tomorrow': printstr = sentence.sentence(google_result['forecasts'][1]['condition'], time) printstr += ' ' + fulltime print printstr logstr += printstr else: found = False for i in range(4): if google_result['forecasts'][i]['day_of_week'] == time: printstr = sentence.sentence(google_result['forecasts'][i]['condition'], time) printstr += " on" + ' ' + fulltime print printstr logstr += printstr found = True if not found: printstr = "Forecast for " + time + " is not available currently." print printstr logstr += printstr continue else: printstr = 'What\'s the location?' print printstr logstr += printstr # End of outermost while loop. # Print message before exiting program dictcount = 0 for i in responsedict: dictcount += 1 if dictcount > 0: printstr = 'Writing new entries to database...' print printstr logstr += printstr datafile = file('predefined_responses.txt', 'a') for i in responsedict.keys(): trimmedi = re.sub('[^a-zA-Z0-9 ]+','', i) string = trimmedi + '|' + responsedict[i] + '\n' datafile.write(string) log.log(logstr) print 'Ending the program...' print 'Bye!' # End of function chat()
def pollutionAPi(lat, lon, offset): return predictPollution(*weather.get_weather(lat, lon, offset))
def bot(): conversation = [] location = '' time = 'today' key = '' keytemplate = [] fulltime = '' numdays = '' citylist = readfile.readfile('cities.txt') keylist = readfile.readfile('keywords.txt') timelist = readfile.readfile('time.txt') condlist = readfile.readfile('conditions.txt') numlist = readfile.readfile('numbers.txt') exitlist = ['exit', 'quit', 'bye', 'ok'] print 'Hello! You can ask me questions about the weather in any major city in the world. What would you like to know?' while True : input = raw_input('Me > ') if input in exitlist: break currentstring = input.split() conversation.append(currentstring) if 'next' in currentstring: numdays = currentstring[currentstring.index('next') + 1] for i in numlist: if numdays == i[0]: numdays = i[1] break if re.match('[0-9]*$',numdays): numdays = int(numdays) else: numdays = '' if 'weather' in currentstring: key = '' keytemplate = [] # get key from input for i in keylist: if i[0] in input: key = i[0] keytemplate = i break # get time from input for i in timelist: if lower(i[0]) in input: numdays = '' if lower(i[0]) != 'today' and lower(i[0]) != 'tomorrow': time = i[1] fulltime = i[0] break else: time = i[0] fulltime = time break if fulltime == '': fulltime = time if numdays != '': if numdays > 4: print 'Forecast is available only for the next 4 days.' else: time = '' fulltime = '' count = numdays prevlocation = location #We store previous location to avoid re-fetching data if the location hasn't been changed # Below, we check if any token in the input matches a city name, and if so, set location to that city newlocation = False # get location from input foundLocation = False for i in citylist: if lower(i[0]) in input: location = i[0] foundLocation = True break #if not foundLocation: #if location != '': #print "I didn't find any city name in your input. I'll get you information about " + location # find if a new location has been mentioned. if not, don't fetch data again if location is not prevlocation: newlocation = True if location is '': if prevlocation is '': print 'City not found' else: location = prevlocation newlocation = False location = location.replace(' ','-') #Google requires a '-' in 2-word city names result = False if location is not '': if newlocation: #If location hasn't changed, don't fetch data again. It's already available print 'Fetching weather information from Google...' # Call Google weather to get current weather conditions google_result = weather.get_weather(location) if 'temperature' in currentstring: print temperature.temperature(google_result, time) continue printed = False if key is not '': printstring = '' timecounter = 0 day_of_week = '' condition = '' if numdays != '': for i in google_result['forecasts']: count -= 1 if count < 0: break if key in lower(i['condition']): result = True day_of_week = i['day_of_week'] condition = i['condition'] break for i in timelist: if i[0] != 'today' and i[0] != 'tomorrow': if i[1] == day_of_week: fulltime = i[0] break if result: printstring = keytemplate[3] + keytemplate[0] + ' on ' + fulltime else: printstring = keytemplate[4] + keytemplate[0] + ' in the next ' + str(numdays) + ' days.' print printstring printed = True if not printed: if time != 'today' and time != 'tomorrow': for i in google_result['forecasts']: if i['day_of_week'] == time: if key in lower(i['condition']): printstring = keytemplate[3] + keytemplate[0] + ' on' else: printstring = keytemplate[4] + keytemplate[0] + ' on' elif time == 'today': fulltime = time if key in lower(google_result['current_conditions']['condition']): printstring = keytemplate[1] + keytemplate[0] else: printstring = keytemplate[2] + keytemplate[0] elif time == 'tomorrow': fulltime = time if key in lower(google_result['forecasts'][1]['condition']): printstring = keytemplate[3] + keytemplate[0] else: printstring = keytemplate[4] + keytemplate[0] print printstring, fulltime elif time == '' or time == 'today' : printstring = sentence.sentence(google_result['current_conditions']['condition'], time) print printstring, fulltime, google_result['current_conditions']['humidity'], google_result['current_conditions']['wind_condition'] else : if time == 'tomorrow': printstring = sentence.sentence(google_result['forecasts'][1]['condition'], time) print printstring, fulltime else: found = False for i in range(4): if google_result['forecasts'][i]['day_of_week'] == time: printstring = sentence.sentence(google_result['forecasts'][i]['condition'], time) print printstring, "on", fulltime found = True if not found: print "Forecast for " + time + " is not available currently." else: print 'What\'s the location?' #end of outermost while loop print 'ending the program...' print 'bye!'