def update_weather(self): # 基本天气 weather = Weather.Weather('beijing').getWeather()['HeWeather5'] city = weather[0]['basic']['city'] cond = weather[0]['now']['cond']['txt'] cond_code = weather[0]['now']['cond']['code'] tmp = weather[0]['now']['tmp'] + '℃' # 空气指数 aqi = weather[0]['aqi']['city']['aqi'] qlty = weather[0]['aqi']['city']['qlty'] pm25 = weather[0]['aqi']['city']['pm25'] # 生活指数 cw_brf = weather[0]['suggestion']['cw']['brf'] cw_txt = weather[0]['suggestion']['cw']['txt'] drsg_brf = weather[0]['suggestion']['drsg']['brf'] drsg_txt = weather[0]['suggestion']['drsg']['txt'] # print(type(weather[0]['daily_forecast']['tmp']['max'])) # print(weather) self.root.ids.label_weather1.text = city + ' ' + cond + ' ' + tmp self.root.ids.label_weather2.text = '空气指数 : ' + \ aqi + '\n空气质量 : ' + qlty + '\npm25浓度 : ' + pm25 self.root.ids.label_weather3.text = '\n人体感觉 : ' + drsg_brf + '\n穿衣指数 : ' + drsg_txt self.root.ids.image_weather.source = 'data/images/' + cond_code + '.png'
def main(): while True: try: # ———— CREATE OBJECTS ———— # print("Creating Objects...", end="") #TESTING calendar = GoogleCalendar.GoogleCalendar(CREDENTIAL_PATH, PICKLE_PATH, SCOPES, 600) current_time = CustomTime.CurrentTime(24) ip_checkers = create_ip_checkers() hue_room = HueRoom.HueRoom(HUE_LIGHTS) weather = Weather.Weather(API_key, 76133, 600) # print("DONE") #TESTING # ———— START OBJECT THREADS ———— # print("Starting threaded programs...", end="") #TESTING calendar.start() current_time.start() weather.start() for x in range(len(ip_checkers)): ip_checkers[x].start() # print("DONE") #TESTING sleep(4) # give objects time to retreive data update_screen_loop(ip_checkers, calendar, current_time, hue_room, weather) except Exception as error: try: ErrorWriter.write_error(error) except: print("BAD") sleep(2)
def initiate_warp_flowers(self, center_pos): self.weather.append(Weather.Weather('Warp_Flower', -1, (-1, -1, -1, -1), (self.width, self.height))) angle_frac = math.pi/8 true_pos = center_pos[0] * GC.TILEWIDTH + GC.TILEWIDTH//2, center_pos[1] * GC.TILEHEIGHT + GC.TILEHEIGHT//2 for speed in (2.0, 2.5): for num in range(0, 16): angle = num*angle_frac + angle_frac/2 self.weather[-1].particles.append(Weather.WarpFlower(true_pos, speed, angle))
def register_all(): if led_cube is not None: led_cube.register(Snake.Snake(api.cubeSize, frame_size), Pong.Pong(api.cubeSize, frame_size), PongMulti.PongMulti(api.cubeSize, frame_size), Weather.Weather(api.cubeSize, frame_size), FFT.AudioVis(api.cubeSize, frame_size), Exit.Exit(api.cubeSize, frame_size))
def main(): weather = Weather.Weather( "http://tj.nineton.cn/Heart/index/all?city=CHSN000000") content = weather.getData() mp3 = MP3.MP3('IEqP5sQIhGSiVGyzGy6FjnwZ', 'nWeh0xWjaUBFPILiAqB3PZDqmK4uWDOr', content) if (mp3.getMP3()): mp3.playmusic()
def __init__(self): self.weather = Weather.Weather() self.recipe = Recipe.Recipe() self.customerCounter = 0 self.dailyServed = 0 self.dailySatisfied = 0 self.price = 0 self.potentialCustomers = 0
def __init__(self,our_tm,enemy_tm): self.our_tm=our_tm self.enemy_tm=enemy_tm self.our_skill=None self.enemy_skill=None self.our_life_line=True self.enemy_life_line=True self.weather=Weather() self.first=True self.ml=music_list()
def main(): """Shows basic usage of the Gmail API. Lists the user's Gmail labels. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('gmail', 'v1', credentials=creds) #Class calls email = Email(service) inbox = email.batchEmails() #list school = School() assignments = school.getAssignments() #list weather = Weather() today = weather.getWeather() #list # ----------------------------- # TKINTER CODE BELOW THIS POINT # ----------------------------- window = tk.Tk() #window.geometry('1280x1024') window.attributes('-fullscreen', True) window.configure(bg='black') #Close on escape key def close(event): window.withdraw() # if you want to bring it back sys.exit() # if you want to exit the entire thing window.bind('<Escape>', close) window.mainloop()
def fetch_weather_data(): # get parameters cityName = aux.cityName APIKey = aux.APIKey apiEndpoint = aux.weatherEndpoint # send request response = requests.get(apiEndpoint) # throw exception if respone code is different than 200 if response.status_code != 200: raise APIError(f"GET {apiEndpoint} status={response.status_code}") # handle json response data jsonData = response.json() generalWeather = jsonData["weather"][0] weather = Weather.Weather(generalWeather["id"], generalWeather["main"], generalWeather["description"]) print()
def start(self): clock = ClockThread.ClockThread() clock.setDaemon(True) clock.start() musicPlayer = MusicPlayer.MusicPlayer() textToSpeech = TextToSpeech.TextToSpeech() weather = Weather.Weather() segmentDimmer = SegmentDimmerThread.SegmentDimmerThread(clock, weather) segmentDimmer.setDaemon(True) segmentDimmer.start() gCalendar = GCalendar.GCalendar() volumeController = VolumeControllerThread.VolumeControllerThread() volumeController.setDaemon(True) volumeController.start() sleep(1) # Wait one second so clock's hour and minute values get filled ready for when alarm needs them alarm = AlarmThread.AlarmThread(musicPlayer, textToSpeech, weather, clock, gCalendar) alarm.setDaemon(True) # DEFAULT WAKEUP TIME - 6:00AM alarm.setAlarm(6,0) alarm.start() internalCommServer = InternalCommServer.InternalCommServer(alarm, musicPlayer, textToSpeech) internalCommServer.setDaemon(True) internalCommServer.start() try: while (self.ended == False): sleep(1) except (KeyboardInterrupt, SystemExit): logger.warn("Interrupted") logger.warn("Main powering off process beginning") clock.end() alarm.end() segmentDimmer.end() volumeController.end() internalCommServer.end() sleep(2) logger.info("Main powering off process finished")
def main(): """Gathers the data and refreshes every 20mins""" while True: currentTime = datetime.datetime.today() print( "Gathering weather information for your location... at: {}".format( currentTime.strftime('%I:%M%p'))) zip = Weather.geolocate() Data = Weather.getWeatherData(zip) weather = Weather.Weather(Data) print(weather) time.sleep(1200) # Refreshes ever 20mins print("\n")
def add_weather(self, weather): if weather == "Rain": bounds = (-self.height*GC.TILEHEIGHT//4, self.width*GC.TILEWIDTH, -16, -8) self.weather.append(Weather.Weather('Rain', .1, bounds, (self.width, self.height))) elif weather == "Snow": bounds = (-self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, -16, -8) self.weather.append(Weather.Weather('Snow', .125, bounds, (self.width, self.height))) elif weather == "Sand": bounds = (-2*self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, self.height*GC.TILEHEIGHT+16, self.height*GC.TILEHEIGHT+32) self.weather.append(Weather.Weather('Sand', .075, bounds, (self.width, self.height))) elif weather == "Smoke": bounds = (-self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, self.height*GC.TILEHEIGHT, self.height*GC.TILEHEIGHT+16) self.weather.append(Weather.Weather('Smoke', .075, bounds, (self.width, self.height))) elif weather == "Light": bounds = (0, self.width*GC.TILEWIDTH, 0, self.height*GC.TILEHEIGHT) self.weather.append(Weather.Weather('Light', .04, bounds, (self.width, self.height))) elif weather == "Dark": bounds = (0, self.width*GC.TILEWIDTH, 0, self.height*GC.TILEHEIGHT) self.weather.append(Weather.Weather('Dark', .04, bounds, (self.width, self.height))) elif weather == "Fire": bounds = (0, GC.WINWIDTH, GC.WINHEIGHT, GC.WINHEIGHT+16) self.weather.append(Weather.Weather('Fire', .05, bounds, (GC.TILEX, GC.TILEY)))
fh.close() return chars def skewTime(h, m, s): return (h,m,s) # main loop chars = parseChars("clock_chars.txt") colon = chars[":"] display = Display() # load messenger module messenger = Messenger.Messenger(display) weather = Weather.Weather(messenger) #weather.showToday() #messenger.showNews() prev_min = 0 next_pos = 1 + (int)(random.random() * 10) counter = 0 off_x = 0 off_y = 0 while(1): counter = counter + 1 if counter == next_pos: if counter % 3 == 0: weather.showTemperature()
# ''' This will be the main script to run, it will call the other scripts from here and do the layout''' # Import packages from tkinter import * from PIL import Image, ImageTk import os # Import scripts import Weather import DateTime import Location # Classes location = Location.Location() weather = Weather.Weather() date_time = DateTime.Date_Time() # tries to get the location, if it can't it'll return [None, None] lat_long = location.geo_location() # weather_currently = weather.get_weather(lat_long[0], lat_long[1])#if weather can't be fetched, return will be 'unknown' # print(weather_currently) print(date_time.get_date_time()) # text sizes xlarge_text_size = 94 large_text_size = 48 medium_text_size = 28 small_text_size = 18 # Colours
# houses pipe houses_pipes = [multiprocessing.Pipe() for i in range(numberOfHouses)] ###MAIN choice = input( "If you want to follow the evolution of all the houses during the simulation, type y.\n>" ) marketProcess = Market.Market(externalFactors, lockExternal, globalNeed, lockGlobalNeed, payableEnergyBank, lockPayable, clocker, weather, market_conn) print("Starting market") marketProcess.start() weatherProcess = Weather.Weather(weather, clocker, day) print("Starting weather") weatherProcess.start() houses = [ House.House(i, clocker, weather, lockHouse, houses_pipes[i][1]) for i in range(numberOfHouses) ] print("Starting every Houses") for k in houses: k.start() tickProcess = Clock.Clock(clocker) print("Starting the clock") tickProcess.start()
def __init__(self): self.weather = Weather.Weather() self.musicPlayer = PlayMusic.PlayMusic() self.speaker = TextToSpeech.TextToSpeech() self.help = Help.Help()
# TODO: add description # TODO: add unittest logging.info('Deleting completed tasks') tasks.delete_completed_tasks(1) if __name__ == "__main__": # init logging logging.basicConfig(filename=LOG_FILE_PATH, level=logging.DEBUG) logging.info("Start Screen Program") # init date and time dt = DateAndTime.DateAndTime() # init weather weather_obj = Weather.Weather() # init tasks tasks = Tasks.Tasks() # init the fonts font18 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 18) font24 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 24) font35 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 35) font68 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 68) schedule.every(1).minutes.do(update_screen, dt=dt, weather=weather_obj.weather_dict, tasks=tasks) schedule.every(1).minutes.do(update_weather, weather_obj=weather_obj)
def assistant(command): "if statements for executing commands" if 'open reddit' in command: reg_ex = re.search('open reddit (.*)', command) url = 'https://www.reddit.com/' if reg_ex: subreddit = reg_ex.group(1) url = url + 'r/' + subreddit webbrowser.open(url) print('Done!') elif 'open website' in command: reg_ex = re.search('open website (.+)', command) if reg_ex: domain = reg_ex.group(1) url = 'https://www.' + domain webbrowser.open(url) print('Done!') else: pass elif 'what\'s up' in command: talkToMe('Just doing my thing') elif 'joke' in command: res = requests.get( 'https://icanhazdadjoke.com/', headers={"Accept":"application/json"} ) if res.status_code == requests.codes.ok: talkToMe(str(res.json()['joke'])) else: talkToMe('oops!I ran out of jokes') elif 'current weather in' in command: reg_ex = re.search('current weather in (.*)', command) if reg_ex: city = reg_ex.group(1) weather = Weather() location = weather.lookup_by_location(city) condition = location.condition() talkToMe('The Current weather in %s is %s The tempeture is %.1f degree' % (city, condition.text(), (int(condition.temp())-32)/1.8)) elif 'weather forecast in' in command: reg_ex = re.search('weather forecast in (.*)', command) if reg_ex: city = reg_ex.group(1) weather = Weather() location = weather.lookup_by_location(city) forecasts = location.forecast() for i in range(0,3): talkToMe('On %s will it %s. The maximum temperture will be %.1f degree.' 'The lowest temperature will be %.1f degrees.' % (forecasts[i].date(), forecasts[i].text(), (int(forecasts[i].high())-32)/1.8, (int(forecasts[i].low())-32)/1.8)) elif 'email' in command: talkToMe('Who is the recipient?') recipient = myCommand() if 'John' in recipient: talkToMe('What should I say?') content = myCommand() #init gmail SMTP mail = smtplib.SMTP('smtp.gmail.com', 587) #identify to server mail.ehlo() #encrypt session mail.starttls() #login mail.login('username', 'password') #send message mail.sendmail('John Fisher', '*****@*****.**', content) #end mail connection mail.close() talkToMe('Email sent.') elif 'open youtube' in command: webbrowser.open("youtube.com") elif 'exit program' in command: talkToMe('Goodbye, I am shutting down.') sys.exit() else: talkToMe('I don\'t know what you mean!')
import subprocess as sp import random import os import Weather import datetime # test t_delta = datetime.timedelta(hours=9) JST = datetime.timezone(t_delta, 'JST') now = datetime.datetime.now(JST) print(now) # print('直近の天気を調べるね') order = 0 wd = Weather.Weather() Say = wd.getLocation()+'の'+wd.getDate(order)+'の天気は['+wd.getWeathers(order)+']だよ' if(wd.getDate(0)=='None' or wd.getWeathers(order)=='None'): Say = '何もみえないよ。' #Say = '天気予報機能は現在メンテナンス中だよ' Num = str(random.randint(0,1)) #Python3;.9~ #dirname=os.path.dirname(__file__) #Python~3.8 dirname=os.path.dirname(os.path.abspath(__file__)) shellpath=dirname+'/ShikimiShellArt.sh' sp.Popen([shellpath,Num,Say],cwd=dirname)
import datetime import mraa import time import json #outfit chooser from Outfit import * #weather finder from Weather import * #email import emailBot w = Weather("toronto", "canada") wDict = w.getDict() print(wDict) o = Outfit(wDict) print(o.outfit) buzz = mraa.Gpio(31) button = mraa.Gpio(29) buzz.dir(mraa.DIR_OUT) button.dir(mraa.DIR_IN) buzz.write(0)
import MealInfo, ClassInfo, EventInfo, Weather import datetime, time, os, time, sys, traceback data = io.open('config.json', mode='r', encoding='utf-8').read() conf = json.loads(data) mod_mealinfo = MealInfo.MealInfo(conf['Open-NEIS-API']['KEY'], conf['Open-NEIS-API']['SD_SCHUL_CODE'], conf['Open-NEIS-API']['ATPT_OFCDC_SC_CODE']) mod_classinfo = ClassInfo.ClassInfo( conf['Open-NEIS-API']['KEY'], conf['Open-NEIS-API']['SD_SCHUL_CODE'], conf['Open-NEIS-API']['ATPT_OFCDC_SC_CODE']) mod_eventinfo = EventInfo.EventInfo( conf['Open-NEIS-API']['KEY'], conf['Open-NEIS-API']['SD_SCHUL_CODE'], conf['Open-NEIS-API']['ATPT_OFCDC_SC_CODE']) mod_weather = Weather.Weather(conf['KMA-Weather-Api']['ZoneID']) while True: print('1. get EventInfo') print('2. get ClassInfo') print('3. get WeatherInfo') print('4. get MealInfo') comm = input('') if comm == '1': #Event Info print('=========EventInfo========') try: mod_eventinfo.load() event_list = mod_eventinfo.get(2019, 12, 10, 3) # 2019년 12월 10일부터 최대 3개의 일정을 불러옴 for event in event_list: print('일시: ', event['AA_YMD'])
def __init__(self, root: tk.Tk): self.owm = Weather() font = "Segoe UI Semilight" bg_color = "#408ab4" text_fg_color = "#c5f0a4" accent_color = "#fff8a6" root.title("Weather App") root.state("zoomed") root.config(bg=bg_color) # ---- MENU ---- menu = tk.Menu(root) root.config(menu=menu) degree_menu = tk.Menu(menu, tearoff=0) self.degree_option = tk.IntVar() menu.add_cascade(label="Degree Unit", menu=degree_menu) degree_menu.add_radiobutton(label="Fahrenheit", var=self.degree_option, value=1, command=self.change_degree_unit) degree_menu.add_radiobutton(label="Celsius", var=self.degree_option, value=2, command=self.change_degree_unit) exit_menu = tk.Menu(menu, tearoff=0) menu.add_cascade(label="Exit", menu=exit_menu) exit_menu.add_command(label="Quit", command=root.quit) # ---- MAIN FRAMES ---- weather_frame = tk.Frame(root, bg=bg_color) forecast_frame = tk.Frame(root, bg=bg_color) weather_frame.grid(row=0, column=1, sticky="nsew") forecast_frame.grid(row=0, column=2, ipadx=50, sticky="nsew") root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1, uniform="side") root.columnconfigure(1, weight=2, uniform="main") root.columnconfigure(2, weight=2, uniform="main") root.columnconfigure(3, weight=1, uniform="side") # ---- WEATHER_FRAME ---- # create frames entry_frame = tk.Frame(weather_frame, width=450, height=50, bg=bg_color) entry_frame.grid_propagate(0) temp_frame = tk.Frame(weather_frame, height=100, width=200, bg=bg_color) temp_frame.grid_propagate(0) features_frame = tk.Frame(weather_frame, bg=bg_color) # layout frames entry_frame.grid(row=0, pady=(20, 0)) temp_frame.grid(row=4) features_frame.grid(row=6, ipadx=115, padx=15, pady=(0, 20)) # create widgets for entry_frame self.entry = tk.Entry(entry_frame, font=(font, 12), width=40) self.entry.insert(0, "Enter a city name.") self.entry.config(fg="gray", state=tk.DISABLED) self.entry.bind("<Button-1>", self.focus_entry) self.entry.bind("<Return>", self.change_city) search_button = tk.Button(entry_frame, text="Search", font=(font, 10), bg=accent_color, activebackground="#d4cd76", command=self.change_city) self.error_label = tk.Label(entry_frame, text="Invalid city name.", font=(font, 9), fg="#d54040", bg=bg_color) # layout widgets for entry_frame self.entry.grid(row=0, column=1, padx=5) search_button.grid(row=0, column=2, padx=5) # layout entry_frame entry_frame.columnconfigure(0, weight=1) entry_frame.columnconfigure(3, weight=1) # create widgets for temp_frame self.temp_label = tk.Label(temp_frame, font=(font, 65), compound=tk.LEFT, fg=text_fg_color, bg=bg_color) self.display_image("icons/thermometer.png", self.temp_label, True, (40, 80)) # layout widgets for temp_frame self.temp_label.grid(row=0, column=1) # layout temp_frame temp_frame.rowconfigure(1, weight=1) temp_frame.columnconfigure(0, weight=1) temp_frame.columnconfigure(2, weight=1) # create widgets for features_frame humidity_icon = tk.Label(features_frame, bg=bg_color, height=50, width=50) self.display_image("icons/humidity.png", humidity_icon, False) wind_icon = tk.Label(features_frame, bg=bg_color, height=50, width=50) self.display_image("icons/wind.png", wind_icon, False) pressure_icon = tk.Label(features_frame, bg=bg_color, height=50, width=50) self.display_image("icons/pressure.png", pressure_icon, False) self.humidity_label = tk.Label(features_frame, font=(font, 12), fg=accent_color, bg=bg_color) self.wind_label = tk.Label(features_frame, font=(font, 12), fg=accent_color, bg=bg_color) self.pressure_label = tk.Label(features_frame, font=(font, 12), fg=accent_color, bg=bg_color) # layout widgets for features_frame humidity_icon.grid(row=0, column=0) wind_icon.grid(row=0, column=1) pressure_icon.grid(row=0, column=2) self.humidity_label.grid(row=1, column=0) self.wind_label.grid(row=1, column=1) self.pressure_label.grid(row=1, column=2) # layout features_frame features_frame.columnconfigure(0, weight=1, uniform="features") features_frame.columnconfigure(1, weight=1, uniform="features") features_frame.columnconfigure(2, weight=1, uniform="features") # create widgets for weather_frame self.loc_label = tk.Label(weather_frame, font=(font, 25), fg=text_fg_color, bg=bg_color) self.weather_label = tk.Label(weather_frame, font=(font, 14), fg=accent_color, bg=bg_color) self.weather_icon = tk.Label(weather_frame, bg=bg_color, height=160, width=170) self.hilo_temp_label = tk.Label(weather_frame, font=(font, 15), fg=accent_color, bg=bg_color) # layout widgets for weather_frame self.loc_label.grid(row=1) self.weather_label.grid(row=2, pady=(0, 10)) self.weather_icon.grid(row=3) self.hilo_temp_label.grid(row=5, pady=5) # layout weather_frame weather_frame.rowconfigure(0, weight=1) weather_frame.rowconfigure(6, weight=1) weather_frame.columnconfigure(0, weight=1) # ---- FORECAST_FRAME ---- # create frames day1_frame = tk.Frame(forecast_frame, height=170, width=170, highlightbackground="white", highlightcolor="white", highlightthickness=3, bd=0, bg=bg_color) day1_frame.grid_propagate(0) day2_frame = tk.Frame(forecast_frame, height=170, width=170, highlightbackground="white", highlightcolor="white", highlightthickness=3, bd=0, bg=bg_color) day2_frame.grid_propagate(0) day3_frame = tk.Frame(forecast_frame, height=170, width=170, highlightbackground="white", highlightcolor="white", highlightthickness=3, bd=0, bg=bg_color) day3_frame.grid_propagate(0) day4_frame = tk.Frame(forecast_frame, height=170, width=170, highlightbackground="white", highlightcolor="white", highlightthickness=3, bd=0, bg=bg_color) day4_frame.grid_propagate(0) day5_frame = tk.Frame(forecast_frame, height=170, width=170, highlightbackground="white", highlightcolor="white", highlightthickness=3, bd=0, bg=bg_color) day5_frame.grid_propagate(0) # layout frames day1_frame.grid(row=1, column=0) day2_frame.grid(row=1, column=1) day3_frame.grid(row=2, column=0) day4_frame.grid(row=2, column=1) day5_frame.grid(row=3, column=0, columnspan=2) day1_frame.rowconfigure(0, weight=1) day1_frame.rowconfigure(1, weight=2) day1_frame.rowconfigure(2, weight=1) day1_frame.columnconfigure(0, weight=1) day2_frame.rowconfigure(0, weight=1) day2_frame.rowconfigure(1, weight=2) day2_frame.rowconfigure(2, weight=1) day2_frame.columnconfigure(0, weight=1) day3_frame.rowconfigure(0, weight=1) day3_frame.rowconfigure(1, weight=2) day3_frame.rowconfigure(2, weight=1) day3_frame.columnconfigure(0, weight=1) day4_frame.rowconfigure(0, weight=1) day4_frame.rowconfigure(1, weight=2) day4_frame.rowconfigure(2, weight=1) day4_frame.columnconfigure(0, weight=1) day5_frame.rowconfigure(0, weight=1) day5_frame.rowconfigure(1, weight=2) day5_frame.rowconfigure(2, weight=1) day5_frame.columnconfigure(0, weight=1) # day1 widgets self.weekday1_label = tk.Label(day1_frame, font=(font, 20), fg=text_fg_color, bg=bg_color) self.icon1_label = tk.Label(day1_frame, bg=bg_color) self.temp1_label = tk.Label(day1_frame, font=(font, 22), fg=accent_color, bg=bg_color) self.weekday1_label.grid(row=0) self.icon1_label.grid(row=1) self.temp1_label.grid(row=2) # day2 widgets self.weekday2_label = tk.Label(day2_frame, font=(font, 20), fg=text_fg_color, bg=bg_color) self.icon2_label = tk.Label(day2_frame, bg=bg_color) self.temp2_label = tk.Label(day2_frame, font=(font, 22), fg=accent_color, bg=bg_color) self.weekday2_label.grid(row=0) self.icon2_label.grid(row=1) self.temp2_label.grid(row=2) # day3 widgets self.weekday3_label = tk.Label(day3_frame, font=(font, 20), fg=text_fg_color, bg=bg_color) self.icon3_label = tk.Label(day3_frame, bg=bg_color) self.temp3_label = tk.Label(day3_frame, font=(font, 22), fg=accent_color, bg=bg_color) self.weekday3_label.grid(row=0) self.icon3_label.grid(row=1) self.temp3_label.grid(row=2) # day4 widgets self.weekday4_label = tk.Label(day4_frame, font=(font, 20), fg=text_fg_color, bg=bg_color) self.icon4_label = tk.Label(day4_frame, bg=bg_color) self.temp4_label = tk.Label(day4_frame, font=(font, 22), fg=accent_color, bg=bg_color) self.weekday4_label.grid(row=0) self.icon4_label.grid(row=1) self.temp4_label.grid(row=2) # day5 widgets self.weekday5_label = tk.Label(day5_frame, font=(font, 20), fg=text_fg_color, bg=bg_color) self.icon5_label = tk.Label(day5_frame, bg=bg_color) self.temp5_label = tk.Label(day5_frame, font=(font, 22), fg=accent_color, bg=bg_color) self.weekday5_label.grid(row=0) self.icon5_label.grid(row=1) self.temp5_label.grid(row=2) # layout forecast_frame forecast_frame.rowconfigure(0, weight=1) forecast_frame.rowconfigure(1, weight=1) forecast_frame.rowconfigure(2, weight=1) forecast_frame.rowconfigure(3, weight=1) forecast_frame.rowconfigure(4, weight=1) forecast_frame.columnconfigure(0, weight=1, uniform="forecast") forecast_frame.columnconfigure(1, weight=1, uniform="forecast") # ---- FILL INFO ---- self.update_weather("London")
import sys import weather from Weather api="https://github.com/stevob21/weather-api" weather=Weather() x = None current_max = 0 y = None for line in sys.stdin: line = line.strip() y, temp = line.rsplit('\t', 1) try: temp = float(temp) except ValueError: continue if temp > current_max: current_max = temp x = y print() lookup=weather.lookup() condition=lookup() print(condition['text']
search = '' imagesPath = '/home/godys/Pictures/Unsplash/' images = [] #Erase Previous Images images = getImages(imagesPath) if len(images) > 0: for image in images: if (os.path.exists(image)): os.remove(image) #Set Browser Config ch_options = getPrefs() drive = None #Set API variables current_weather = Weather() response = {} API_KEY, CITY = API.getAPIdata() #Search for Today's Events mx_holidays = holidays.Mexico() today = str(datetime.datetime.today()).split()[0] today_holiday = mx_holidays.get(today) if (today_holiday): #If event exists search = today_holiday search.replace(' ', '-') else: #Otherwise get the current weather mainPage = '' req = requests.get( "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(
import sys import tkinter as tk import weather as Weather w = Weather() avg_temp = lambda: w.query("SELECT AVG(temp) FROM weather")[0][0] min_temp = lambda: w.query("SELECT MIN(temp) FROM weather")[0][0] max_temp = lambda: w.query("SELECT MAX(temp) FROM weather")[0][0] all_temp = lambda: w.query("SELECT temp FROM weather") def gui(): root = tk.Tk() w.get_forecast_plot(root) avgL = tk.Label(root) avgL.pack() minL = tk.Label(root) minL.pack() maxL = tk.Label(root) maxL.pack() def set_labels(): avgL.config(text=f"Averge temperature: {avg_temp():.2f}") minL.config(text=f"Minimum temperature: {min_temp():.2f}") maxL.config(text=f"Maximum temperature: {max_temp():.2f}") def on_request_click():
import Weather import sys args = sys.argv areacode = args[1] order = 0 wd = Weather.Weather(areacode) Say = wd.getLocation() + 'の' + wd.getDate(order) + 'の天気は[' + wd.getWeathers( order) + ']だよ' if (wd.getDate(0) == 'None' or wd.getWeathers(order) == 'None'): Say = '何もみえないよ。' print(Say) sys.exit(1) print(Say) sys.exit(0)
- Example routines to add new secondary features to the observation list """ # Weather data is accessed through an instantation of the provided `Weather` class. from Weather import * # Create a new object (e.g. `weather`) of type `Weather`. # # As part of the instantiation provide: # - weatherFile: The filename (either basic.txt or advanced.txt) # - fileSlice: The number of lines to read from the chosen input file (0 is all) # # Use the fileSlice to limit the sample size for early evaluation weatherFile = 'data/sample.txt' fileSlice = 0 weather = Weather(weatherFile, fileSlice) # Recovering Incomplete Data # # Some of the observation values have a value of `-99999` # This is a default value I inserted to indicate that the feature data was either not collected # at the time of the observation or had a null value. # # Any data points that contain null observations need to be corrected to avoid problems # with subsequent filtering and modifications. # # In some cases null values can either be interpolated or set to a default value. # # The large majority of null data is from the `Gust` measurement. # Here I assume than no observation is the same as a zero value
csv_path = './data/darksky_weather.csv' ################################################################ if __name__ == "__main__": config_path = locate_config(sys.argv) config = ConfigParser() config.read(config_path) api_key = config.get('Darksky', 'key') for c in city_names: city = City.City(c, state_name) forecast_handle = Weather.Weather(api_key) weather_forecast = forecast_handle.get_hourly_weather( city, start_date, end_date, True) if not os.path.isfile( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv' ): weather_forecast.to_csv( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv', index=None, header=True) else: weather_forecast.to_csv( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv', mode='a', header=False)
def getReport(self): newWeather = Weather.Weather() self.weather = newWeather.getWeather() self.precipitation = newWeather.getPrecipitation() self.temperature = newWeather.getTemperature() del newWeather
def search(): if request.method == 'POST': active = Database.ActiveUser() id = active.getActiveUser() logstate = "" if id == "None": logstate = False else: logstate = True location = request.form['search'] value = request.form['Gender'] geocode = Geocoding.Geocoding() latlon = geocode.getLocation(location) lat = str(latlon["lat"]) long = str(latlon["lng"]) weather = Weather.Weather() weather.getAllInfo(lat, long) day = datetime.datetime.now().strftime("%A") t = datetime.datetime.now().time().strftime("%I:%M %p") date = str(day) + " " + str(t) description = weather.getDescription() # "Mostly Cloudy" description_list = description.split(" ") new_description = "" for word in description_list: word = word[0:1].upper() + word[1:] new_description = new_description + word + " " description = new_description current = weather.getCurrent() high = weather.getHigh() # "58 F" low = weather.getLow() # "39 F" humidity = weather.getHumidity() # "55%" wind = weather.getWind() # "20 mph" icon = weather.getIcon() if value == "Men": alchemy = AlchemyOutlook.Alchemy(location, value) pictures = alchemy.getPictures() return render_template("search.html", location=location.upper(), date=date, description=description, current=current, high=high, low=low, humidity=humidity, wind=wind, icon=icon, pictures=pictures, logstate=logstate) elif value == "Women": alchemy = AlchemyOutlook.Alchemy(location, value) pictures = alchemy.getPictures() return render_template("search.html", location=location.upper(), date=date, description=description, current=current, high=high, low=low, humidity=humidity, wind=wind, icon=icon, pictures=pictures, logstate=logstate) else: return render_template("search.html", test=value, t=t)