from notify_run import Notify  #pip install notify_run
import time
import json

#getting config parameter from 'products.json' file
with open('products.json', 'r') as file:
    settings = json.load(file)
    file.close()

#get configuration parameters
items = settings['items']  #list of items
repeateTime = settings['repeat_after']  #ping time
notificationChanel = settings['notification_channel']  #notification channel
userAgetString = settings['user_agent']  #useragent string
#creating notification object with created notification channel.
notify = Notify(endpoint=notificationChanel)

if items is None:
    print("No product urls found.")
    exit(0)

# Google "My User Agent" And Replace It
headers = {"User-Agent": userAgetString}
cookies = {}


def CheckPrice(url, price):
    try:
        page = requests.get(url, headers=headers, cookies=cookies)
    except requests.ConnectionError:
        print(
Example #2
0
def send_notification(message):
    notify = Notify()
    notify.send(message)
Example #3
0
        image_folder = video.split('.')[0]
        extract_frames(join(videos_path, video), join(images_path,
                                                      image_folder))


if __name__ == '__main__':
    p = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    p.add_argument('--data_path', type=str)
    p.add_argument('--dataset',
                   '-d',
                   type=str,
                   choices=list(DATASET_PATHS.keys()) + ['all'],
                   default='all')
    p.add_argument('--compression',
                   '-c',
                   type=str,
                   choices=COMPRESSION,
                   default='c0')
    args = p.parse_args()

    if args.dataset == 'all':
        for dataset in DATASET_PATHS.keys():
            args.dataset = dataset
            extract_method_videos(**vars(args))
    else:
        extract_method_videos(**vars(args))

    notify = Notify(endpoint="https://notify.run/Dbnkja3hR3rG7MuV")
    notify.send(" ".join(sys.argv) + " done")
Example #4
0
def main():
	change_settings = False

	main_window, load_data_popup, settings = None, None, load_settings(SETTINGS_FILE, DEFAULT_SETTINGS)
	DEBUG_MODE = settings['debug']

	while True:
		if main_window is None:
			main_window = create_main_window(settings)
			#gc.collect()

		if load_data_popup is None:
			load_data_popup = create_load_data_popup(settings)
			#gc.collect()

		event, values = main_window.read()
		#print('event: %s\nvalues: %s' % (event, values))
		
		if event == ('Exit'):
			main_window.close()
			main_window = None
			#gc.collect()
			break

		if event in ('Settings'):
			# close main window
			main_window.close()
			main_window = None
			#gc.collect()

			settings_window = create_settings_window(settings)

			while True:
				event, values = settings_window.read()
				print(event)
				print(values)

				if event in (None, 'Quit', 'Cancel'):
					settings_window.close()
					settings_window = None
					#gc.collect()
					break
					# break

				# if event in ('Cancel'): 
				# 	settings_window.close()

				if event == 'Default Settings':
					settings_window.close()
					##gc.collect()

					# default settings
					default_settings(SETTINGS_FILE)
					settings = load_settings(SETTINGS_FILE, DEFAULT_SETTINGS)

				
				if event == 'Save':
					
					# for some reason values does not contain the key for Text elements
					values['-NOTIFYLINK-'] = settings_window['-NOTIFYLINK-'].DisplayText

					settings_window.close()
					settings_window = None
					#gc.collect()

					save_settings(SETTINGS_FILE, settings, values, popup=True)
					
					change_settings = True
					
					break

				print(load_setting(SETTINGS_FILE, 'notify'))

				if event == '-NOTIFY-': # register using notify-run
					if values['-NOTIFY-'] and not load_setting(SETTINGS_FILE, 'notify'):
						notify = Notify()
						endpointinfo = notify.register()

						endpointlink = str(endpointinfo).split('\n')[0][10:]

						settings_window['-NOTIFYLINK-'].Update(endpointlink)
					else:
						settings_window['-NOTIFYLINK-'].Update('N/A')

				if event == '-NOTIFYLINK-' and values['-NOTIFY-']: # clicked on link
					import webbrowser

					link = settings_window['-NOTIFYLINK-'].DisplayText

					# send a welcome message
					notify = Notify()
					notify.send('Notifications will appear here.')

					webbrowser.open_new(link)

			continue


		###################################
		####### CREATE DATASET FLOW #######
		###################################
		if event in ('Create Dataset'):
			folder_path = sg.popup_get_folder("Please select the folder of flooded scalogram files", title="Select Folder for dataset")

			sg.popup('Creating dataset...Please wait')
			
			Dataset(folder_path)

			sg.popup('Dataset Created!')

		#########################
		####### GAN FLOW ########
		#########################
		if event in ('GAN'):
			main_window.close()
			main_window = None

			gan_window = None

			while True:
				
				if gan_window is None:
					gan_window = create_gan_window()
				else:
					break
				
				gan_event, gan_values = gan_window.read()

				if gan_event in (None, 'Quit', 'Cancel'):
					gan_window.close()
					break

				if gan_event.startswith('Generate'): # generate images
					gan_window.close()

					modelname = sg.popup_get_file("Please select a trained GAN model", title="Generate images from GAN model")

					if modelname in (None, 'Cancel'):
						gan_window = None
						continue

					plt_window = create_plt_window(modelname)
					fig = generate_images_grid(modelname)
					fig_canvas_agg = draw_figure(plt_window['-CANVAS-'].TKCanvas, fig)

					while True:
						plt_event, plt_values = plt_window.read()

						if plt_event in (None, 'Quit', 'Cancel', 'Ok'):
							plt_window.close()
							plt_window = None
							break


						if plt_event in ('New'):
							fig = generate_images_grid(modelname)
							fig_canvas_agg.get_tk_widget().pack_forget()
							fig_canvas_agg = draw_figure(plt_window['-CANVAS-'].TKCanvas, fig)
							_, _ = plt_window.read(timeout=10)
							continue


						if plt_event in ('Save'):
							namefile = sg.PopupGetFile('Enter filename', save_as=True)

							if namefile:
								try:
									fig.savefig(namefile)
									# plt_window.close()
									# plt_window = None
									sg.popup_quick_message('Image saved!', keep_on_top=True, auto_close_duration=2)
									time.sleep(2)
								except Exception as e:
									sg.popup('Error saving figure')
										

				if gan_event.startswith('Train'): # train new models
					gan_window.close()

					# select dataset file
					dataset = sg.popup_get_file("Please select a .npz dataset file", title="Train new GAN model: Load Dataset")

					if dataset in (None, 'Cancel'): 
						gan_window = None
						continue

					gan_train_window = create_gan_train_window()

					gan_train_started = False
					thread = None

					while True:
						gt_event, gt_values = gan_train_window.read(timeout=10)

						if gt_event in (None, 'Quit', 'Cancel'):
							if gan_train_started: thread.join()
							gan_train_window.close()
							gan_train_window = None
							gan_train_started = False

							sg.popup_quick_message('Cancelled. Returning to main menu.', keep_on_top=True, auto_close_duration=2)
							time.sleep(2)

							break

						if gt_event in ('Start') and not gan_train_started:
							gan_train_main(dataset)
							gan_train_started = True

						# if gt_event in ('Start') and not gan_train_started:
						# 	try:
						# 		thread = threading.Thread(target=gan_train_main, args=(dataset,), daemon=True)
						# 		thread.start()
						# 		gan_train_started = True
						# 	except Exception as e:
						# 		print('Error starting thread: ', e)

		if event in ('Process Data'):
			main_window.close() # close main menu
			main_window = None
			#gc.collect()

			# boolean for showing warning message in load data layout
			select_folder_warning = False
			wav_only_warning = False

			load_data_popup = None

			while True: 
				#pop up load window

				if load_data_popup is None:
					load_data_popup = create_load_data_popup(settings, wav_only_warning, select_folder_warning)
				else:
					break

				
				ld_event, ld_values = load_data_popup.read()
				#print('ld_event: %s\nld_values: %s' % (ld_event, ld_values))

				if ld_event == 'Cancel':
					load_data_popup.close()
					# load_data_popup = None
					#gc.collect()
					break
			
				if ld_event in ('OK'): 	# clicked OK without selecting folder
					if ld_values['_FILES_']=='':
						load_data_popup.close()
						load_data_popup = None
						#gc.collect()
						select_folder_warning = True
						continue

					select_folder_warning = False
					
					# close load_data_popup
					load_data_popup.close()
					# load_data_popup = None
					#gc.collect()

					# print(ld_values)


					wave_dir = ld_values['_FILES_'].split(';')[0]

					print('### SELECTED FOLDER ###')
					print(wave_dir)

					print('### SELECTED FILES ###')
					# for file_name in os.listdir(wave_dir):
					# 	if file_name.endswith(".wav"):
					# 		print(file_name)
					
					# check for non .wav files in selected folder
					total_num_files = len(os.listdir(wave_dir))
					total_num_wavs = len(glob.glob1(wave_dir, '*.wav'))
					# if non .wav files exist, warn user and return to load_data window
					wav_only_warning = total_num_files != total_num_wavs

					if not wav_only_warning:

						#create file storing wav file transformations
						if not os.path.exists('./png_scalogram'):
							os.mkdir('./png_scalogram')

						if not os.path.exists('./wav_transform'):
							os.mkdir('./wav_transform')

						png_sav_dir = './png_scalogram'
						wave_sav_dir = './wav_transform'


						###########################################################
						### PASS FILES TO DATA PIPELINE						 ###
						###########################################################

						# print('SPLITTING\n')

						# org_wav = os.stat(wave_dir + "/test.wav")
						# print(f'File size in Bytes is {org_wav.st_size}')


						start = time.time()
						#TODO: add option to split wav files from GUI
						split_wav = True
						if (split_wav):
							WavPipeline.split(wave_dir, wave_sav_dir)
						stop = time.time()

						time_split= stop-start



						listwavs = os.listdir(wave_sav_dir)
						totalwavs = len(glob.glob1(wave_sav_dir, '*.wav'))
						i=1



						size_wav = 0
						size_scl = 0
						size_png = 0


						time_wavToScl = 0
						time_sclToPng = 0
						time_flood = 0

						total_files = 0

						try:
							for splitwav in listwavs:
								total_files += 1
						except:
							print('################## CANNOT FIND FILES ################')
							exit(-1)

						
						pg_window = create_prog_bar_popup(settings, total_files)
						# create communicate queue if debug mode
						gui_queue = queue.Queue()

						# pg_window = sg.Window('File Processing').Layout(pg_layout)
						progress_bar = pg_window['progressbar_f']
						process_count = pg_window['progressbar_p']

						pg_window.read(timeout=10)

						process_count.UpdateBar(0)
						progress_bar.UpdateBar(0)

						pg_window['file_c'].update('(0/%d)' % total_files)
						pg_window['proc_c'].update('(0/%d)' % (total_files*3))

						pg_window.read(timeout=10)

						# progress bar event loop
						started = False
						if multithreaded:
							print('MODE: MULTITHREADED')
							# multithreaded -- gui is responsive but may (will most definitely) crash 				
							while True:
								event, values = pg_window.read(timeout=100)

								if event in (None, 'Exit', 'Cancel'):
									print('CANCELLED, EXITING')
									pg_window.close()
									pg_window = None
									sg.popup_quick_message('Cancelled. Returning to main menu.', keep_on_top=True, auto_close_duration=1)
									time.sleep(1)
									break

								elif event.startswith('Start') and not started: # check for thread already spun up
									try:
										print('STARTING THREAD')
										thread = threading.Thread(target=main_op_thread, 
															args=(listwavs, totalwavs, wave_sav_dir, png_sav_dir, total_files, gui_queue), 
															daemon=True)
										thread.start()
										
										started = True
									except Exception as e:
										print('Error starting work thread')
								# elif event == 'Check responsive':
								# 	print('GUI is responsive')

								# check for incoming messages from thread
								try:
									message = gui_queue.get_nowait()
								except queue.Empty:
									message = None
								
								# check if message exists
								if message:
									# CHECK FOR SPECIFIC MESSAGES TO UPDATE PROGRESS BAR VALUES
									if isinstance(message, int) and message==42: 
										thread.join()
										print('thread joined')
										pg_window.close()
										pg_window = None
										sg.popup_quick_message("Data Processing Complete", keep_on_top=True, auto_close_duration=2)
										time.sleep(2)
										break
									elif isinstance(message, str): # if string instance print it
										print(message)
									else: # otherwise, it is an opcode to update the progress bar
										print(message)
										proc_c_text = message[0]
										file_c_text = message[1]
										
										p_c = message[2]
										f_c = message[3]

										# update text
										pg_window['proc_c'].update(proc_c_text)
										pg_window['file_c'].update(file_c_text)

										# update bar
										process_count.UpdateBar(p_c)
										progress_bar.UpdateBar(f_c)

						else:
							print('MODE: SINGLETHREADED')
							# single threaded -- gui will not be responsive until each step is complete.
							event, values = pg_window.read()

							if event in (None, 'Exit', 'Cancel'):
								print('CANCELLED, EXITING')
								pg_window.close()
								pg_window = None
								sg.popup_quick_message('Cancelled. Returning to main menu.', keep_on_top=True, auto_close_duration=1)
								time.sleep(1)
								break

							elif event.startswith('Start') and not started:
								started = True

								# execute single-threaded processing pipeline 
								main_data_process(listwavs, totalwavs, wave_sav_dir, png_sav_dir, total_files, pg_window)

								pg_window.close()
								pg_window = None

								sg.popup('Completion window', 'The provided data has successfully been processed!\nFind the results in your local directory.')


						# TODO: SEPARATELY CALL EACH FUNCTION IN THE PIPELINE
						# TODO: UPDATE THE GUI AND THE USER ON THE PROCESS OF EACH FUNCTION CALL
						# TODO: UPSCALE THE GUI SIZE SO IT IS NOT TIGHTLY FIT TO THE CURRENT GUI ELEMENTS -> MAKE IT MORE USER-FRIENDLY AND NAVIGABLE

						if ld_event in (None, 'Cancel'):
							load_data_popup.close()
							load_data_popup = None
							#gc.collect()
							break
					else:
						print('non .wav files detected')
						load_data_popup = None
						#gc.collect()

				if event in (None, 'Exit'):
					main_window.close()
					main_window = None
import os, time, bs4, requests  # We will use the 'os' module to clear screen later
from notify_run import Notify

# Here we're declaring a variable for notification function
notify = Notify()


def getTime(url):

    timeRes = requests.get(url)
    timeRes.raise_for_status()
    timeSoup = bs4.BeautifulSoup(timeRes.text, 'html.parser')
    timeElems = timeSoup.select('#ct')
    return (timeElems[0].text)


def getTheValue(url):

    ethRes = requests.get(url)

    ethRes.raise_for_status()

    ethSoup = bs4.BeautifulSoup(ethRes.text, 'html.parser')

    ethElems = ethSoup.select(
        'html body div.container.main-section div.row div.col-lg-10.padding-top-1x div.details-panel.flex-container.bottom-margin-2x div.details-panel-item--header.flex-container div.details-panel-item--price.bottom-margin-1x span#quote_price span.h2.text-semi-bold.details-panel-item--price__value'
    )

    return (ethElems[0].text)

Example #6
0
def helper():

    # To notify the user
    os.system('notify-run register')
    notify = Notify()

    # Eyes and mouth threshold value
    eyeThresh = 0.25
    mouthThresh = 0.60

    # frame to check
    frame_check_eye = 10
    frame_check_mouth = 7

    # Initializing the Face Detector object
    detect = dlib.get_frontal_face_detector()

    # Loading the trained model
    predict = dlib.shape_predictor(
        "model/shape_predictor_68_face_landmarks.dat")

    # Getting the eyes and mouth index
    (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["left_eye"]
    (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["right_eye"]
    (mStart, mEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["mouth"]

    # Initializing the Video capturing object
    cap = cv2.VideoCapture(0)

    # Initializing the flags for eyes and mouth
    flag_eye = 0
    flag_mouth = 0

    # Calculating the Euclidean distance between facial landmark points in the Eye Aspect Ratio (EAR)
    while True:
        ret, frame = cap.read()
        frame = imutils.resize(frame, width=450)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        subjects = detect(gray, 0)
        for subject in subjects:
            shape = predict(gray, subject)
            shape = face_utils.shape_to_np(shape)  #converting to NumPy Array
            leftEye = shape[lStart:lEnd]
            rightEye = shape[rStart:rEnd]
            mouth = shape[mStart:mEnd]
            leftEAR = eye_aspect_ratio(leftEye)
            rightEAR = eye_aspect_ratio(rightEye)
            ear = (leftEAR + rightEAR) / 2.0
            leftEyeHull = cv2.convexHull(leftEye)
            rightEyeHull = cv2.convexHull(rightEye)
            mar = yawning(mouth)
            mouthHull = cv2.convexHull(mouth)

            # Drawing the overlay on the face
            cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
            cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)
            cv2.drawContours(frame, [mouth], -1, (255, 0, 0), 1)

            # Comparing threshold value of Mouth Aspect Ratio (MAR)
            if mar > mouthThresh:
                flag_mouth += 1
                if flag_mouth >= frame_check_mouth:
                    cv2.putText(frame,
                                "**************** YAWNING ****************",
                                (10, 300), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
                                (0, 0, 255), 2)
                    notify.send('Yawning While Driving')
            else:
                flag_mouth = 0

            # Comparing threshold value of Eye Aspect Ratio (EAR)
            if ear < eyeThresh:
                flag_eye += 1
                if flag_eye >= frame_check_eye:
                    cv2.putText(frame,
                                "**************** SLEEPING ***************",
                                (10, 325), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
                                (0, 0, 255), 2)
                    notify.send('Sleeping While Driving')
            else:
                flag_eye = 0

        # Plotting the frame
        cv2.imshow("Frame", frame)

        # Waiting for exit key
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break

    # Destroying all windows
    cv2.destroyAllWindows()
    cap.stop()
Example #7
0
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import requests
import tqdm
import re
from tqdm import tqdm
from notify_run import Notify
import csv
from csv import writer

notify = Notify()
notify.register()

url_names = 'https://www.maxpreps.com/rankings/football-fall-17/{}/state/texas.htm'
url_scores = 'https://www.maxpreps.com/high-schools/{})/football-fall-17/schedule.htm'
url_contact_info = 'https://www.maxpreps.com/high-schools/{})/home.htm'
#state_set = {'texas'}
state_set = [
    'delaware', 'hawaii', 'kansas', 'louisiana', 'massachusetts', 'michigan',
    'pennsylvania', 'utah', 'wisconsin', 'wyoming'
]

for x in tqdm(range(0, 50, 1)):
    names = url_names.format(x)
    r = requests.get(names)
    sopa = BeautifulSoup(r.text, 'html.parser')
    for item in sopa.find_all('tr'):
        try:
            school_name.append(
                item.find('th', attrs={
Example #8
0
import praw
import time
from notify_run import Notify
notify = Notify()

reddit = praw.Reddit(client_id='',
                     client_secret='',
                     username='',
                     password='',
                     user_agent='reputation bot by hacksorskill')
subreddit = reddit.subreddit('giftcardexchange')

while True:
    try:
        for submission in subreddit.stream.submissions(pause_after=-1):

            if submission is None:
                break
            else:

                now = time.time()
                if (now - submission.created_utc <
                        700) and submission.id not in map(
                            str.strip, open("gcxall.txt")):

                    notify.send(
                        submission.title + " by u/" + str(submission.author),
                        submission.url)
                    with open("gcxall.txt", "a+") as f:
                        f.write(submission.id + "\n")
Example #9
0
def notify():
    notify = Notify()
    notify.send('Bigbasket may be available. check it out NOW !!!')
Example #10
0
import gym
import gym_LoL

from stable_baselines.common.policies import MlpLstmPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import PPO2

from notify_run import Notify

if __name__ == "__main__":
    notify = Notify(endpoint='https://notify.run/1GQn88vSML1rmxdz')
    model = None
    model_path = 'ppo_lol'
    try:
        env = DummyVecEnv([lambda: gym.make('LoL-v0')])
        try:
            model = PPO2.load(model_path, env)
        except ValueError:
            model = PPO2(MlpLstmPolicy, env, verbose=1, nminibatches=1)
        for i in range(100):
            model.learn(total_timesteps=2500)
            model.save(model_path)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        model.save(model_path)
        notify.send('Training Failed for LoL-v0')
        raise
    else:
        notify.send('Training Completed for LoL-v0')
        #losslogger = checkpoint['losslogger']
        print("=> loaded checkpoint '{}' (epoch {})".format(
            filename, checkpoint['epoch']))
    else:
        print("=> no checkpoint found at '{}'".format(filename))

    return model, optimizer, start_epoch  #, losslogger


m = XorNet()
loss_fn = nn.MSELoss()
optimizer = optim.Adam(m.parameters(), lr=1e-5)
f = open("gap_ML90.dat", "w+")
training_epochs = 6000
minibatch_size = 64
notify = Notify()
#notify.register()

#
#pairs = [np.asarray([x1,x2]), [y]]
# input-output pairs
# pairs = [(np.asarray([4.0,0.85]), [0.072]),
#           (np.asarray([6.0,0.75]), [0.1]),
#           (np.asarray([8.0,0.65]), [0.15]),
#           (np.asarray([10.0,0.55]), [0.312]),
#           (np.asarray([3.0,0.8]), [0.068])]
f0 = open("orderparn85U8t1tl0.4v0q.dat", "r")
f1 = open("orderparn85U8t1tl0.4v01q.dat", "r")
f2 = open("dorderparn85U8t1tl0.4v02q.dat", "r")
f3 = open("dorderparn85U8t1tl0.4v03q.dat", "r")
f4 = open("dorderparn85U8t1tl0.4v04q.dat", "r")
Example #12
0
        clean_t = clean_tweet(tweet_details['tweet'])  # Gets rid of hyperlinks
        tweet_details['tweet'] = clean_t
        print(tweet_details)
        data.append(tweet_details)
        counter += 1
        if counter == 100:  # Api.search only runs 100 times so add a loop
            break
        else:
            pass
    with open('data/{}.json'.format(search_term), 'a') as f:
        json.dump(data, f)
    print('done!')


if __name__ == "__main__":
    notify = Notify()
    notify.send('Starting stream')
    print('Starting to stream...')
    counter = 0
    try:
        while counter != 10:  # Infinite loop
            for search_term in search_terms1:
                stream_tweets(search_term)
                print('finished!')
                counter += 1
    except:
        notify.send('Eoghan your twitter scraping program has failed'
                    )  # Send me an android notification
    finally:
        notify.send('Eoghan your twitter scraping program has finally failed'
                    )  # Send me an android notification
Example #13
0
						vs = analyzer.polarity_scores(tweet)
						latitude = location.latitude
						longitude = location.longitude
						sentiment = vs['compound']
						df = pd.DataFrame({'date': [time_ms],'tweet':[tweet], 'sentiment':[sentiment],'latitude':[latitude],'longitude':[longitude]})
						df['date'] = pd.to_datetime(df['date'], unit='ms')
						df['date'] = df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')
						df['date'] = df['date'].astype('datetime64[ns]')
						df.to_sql('sentiment_tweets', con = database_connection, if_exists = 'append', index = False)
					else:
						pass
				else:
					pass
			else:
				pass
		except Exception as e:
			with open('errors.txt','a') as f:
				print(str(e))
				f.write(str(e))
				f.write('\n')

auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_KEY_SECRET)
auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET)
notify = Notify()

twitterStream = Stream(auth, listener())
try:
	twitterStream.filter( languages =['en'], locations = [-140.99778, 18.91619, -66.96466,  83.23324],stall_warnings = True)
except:
	notify.send('App stopped')
print(rem_data_mb)
print(today)

# # used_data_mb = '35100.55'
# # rem_data_mb = '5000.45'
used_data = convert_MBtoGB(used_data_mb)
rem_data = convert_MBtoGB(rem_data_mb)

web.go_to('??.in/signout')

# # log_file_df = pd.read_csv("log.csv")
# # log_file_df['usage(GB)'] = log_file_df['usage(GB)'].apply(lambda x: int(x))
# # total_usage = sum(log_file_df['usage(GB)'].tolist())

f1 = open('prev_usage.txt', 'r')
prev_usage = convert_MBtoGB(f1.read())
# print(prev_usage)

daily_usage = used_data - prev_usage
if daily_usage < 0:
    msg = "Renewed ?? GB"
else:
    msg = "Todays Usage : " + str(daily_usage) + " GB  |  Remaining : " + str(rem_data)+" GB"
print(msg)

f1 = open('prev_usage.txt', 'w')
f1.write(str(used_data_mb))

notify = Notify()
notify.send(msg)
    p = os.popen("df -h /")
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i == 2:
            return (line.split()[1:5])


if __name__ == "__main__":
    RAM_stas = getRAMinfo()
    RAM_free = round(int(RAM_stas[1]) / 1000, 1)
    # RAM_free = 900
    DISK_stats = getDiskSpace()
    DISK_free = DISK_stats[2]
    notify = Notify()
    count = 0

    while True:
        count += 1
        print("CONTINOUSLY RUNNING {}".format(count))
        print("FREE DISK SPACE: {} and FREE RAM SIZE: {}".format(
            DISK_free, RAM_free))
        if int(DISK_free.split('G')[0]) < 5:
            notify.send(
                "!!! CRITICAL CRITICAL !!!! Please check the server right now. The Disk size is lower than {}"
                .format(DISK_free))

        if RAM_free < 1000:
            notify.send(
                "Whooops ! The Free ram size is available around {}MB".format(
from lxml import html
import requests
from notify_run import Notify
import sys
import time

notify = Notify()

print(sys.argv[1])

while True:
    page = requests.get('https://coursebook.utdallas.edu/'
                        '' + sys.argv[1].split()[0].lower() + '/'
                        '' + sys.argv[1].split()[1] + '/term_19f?')
    tree = html.fromstring(page.content)

    status = tree.xpath('//*[@id="r-1"]/td[1]/span')
    course = tree.xpath('//*[@id="r-1"]/td[2]/a')

    for i in range(len(status)):
        status[i] = status[i].text_content()
    for i in range(len(course)):
        course[i] = course[i].text_content()

    print('status: ', status)
    print('course: ', course)

    for i in range(len(status)):
        if status[i] == 'Open':
            if course[i][:course[i].find('.')] == sys.argv[1]:
                notify.send('available')
Example #17
0
import os
from time import strftime, sleep
from notify_run import Notify
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime
from pytz import timezone

# multiple status, containing key value=> key used to refer in code, value will be the value which will be saved in DB/logs
statusMap = {'ONLINE': 'online', 'OFFLINE': 'offline'}

#getting indian timezone
indian_timezone = timezone('Asia/Kolkata')

# getting notify for notification
notify = Notify()

# target_name that needs to be tracked
target_name = "Nazma"


def getCurrentTime():
    return datetime.now(indian_timezone).strftime("%Y-%m-%d %I:%M:%S %p")


def sendNotification(message):
    print(message)
    notify.send(message)


def handleStatusChange(status, time_stamp, target_name):
Example #18
0
def push_notification():
    notify = Notify()
    pnmsg = "Your emails are being deleted"
    notify.send(pnmsg)

    return 1
Example #19
0
 def __init__(self, notify=None, action=None):
     if notify is None:
         notify = Notify()
     self.notify = notify
     self._format_pair = '{}: {:.5f}'
     self.action = action
Example #20
0
import hashlib
from notify_run import Notify
import time
import datetime
import urllib
notify=Notify()

url = "http://www.dota2.com/news/updates/"   #Your URL here

sleeptime = 300    #sleeptime
def getHash():
    r = urllib.request.urlopen(url)
    the_page = r.read()
    return hashlib.sha224(the_page).hexdigest()
current_hash = getHash()      # much update needed here

while 1:
    if getHash() == current_hash:
        print('Nothing')
    else:
        notify.send(f"New Patch Out at {datetime.datetime.now()}")
        break
    time.sleep(sleeptime)
Example #21
0
def main_data_process(listwavs, totalwavs, wave_sav_dir, png_sav_dir, total_files, pg_window):
	"""
	Single-threaded version of data processing pipeline
	"""

	i=0
	
	notify = Notify()

	for splitwav in listwavs:
		if splitwav.endswith('.wav'):

			notify.send('Processing file: (%d/%d)' % (i+1,total_files))
			
			print('\nInitiating data processing pipeline')

			p = (i*3)

			wavname = os.path.join(wave_sav_dir, splitwav)			  # .wav file with full path
			fname = splitwav[:splitwav.rfind('.')]					  # remove .wav extension
			scalname = os.path.join(png_sav_dir , '%s.scal' % fname)	# .scal file with full path
			scalgzname = scalname + '.gz'							   # .scal.gz file
			mp3name = os.path.join(wave_sav_dir, fname + '.mp3')		# .mp3 name


			###################
			### WAV -> SCAL ###
			###################
			
			## message
			print('\nwavname: %s\nfname: %s\nscalname: %s\nscalgzname: %s\nmp3name: %s' % (wavname, fname, scalname, scalgzname, mp3name)) 
			print('\nStarting Operation: WAV TO SCAL')
			pg_window.read(timeout=10)

			time.sleep(2)

			WavPipeline.wavToScl(wavname, scalname, scalgzname, mp3name)

			print('Complete: WAV TO SCAL')

			## pb update  -- finished wav -> scal
			update_text = ['(%d/%d)' % (p+1,(total_files*3)), '(%d/%d)' % (i,total_files),p+1,i]

			# update text
			pg_window['proc_c'].update(update_text[0])
			pg_window['file_c'].update(update_text[1])

			# update bar
			pg_window['progressbar_p'].UpdateBar(update_text[2])
			pg_window['progressbar_f'].UpdateBar(update_text[3])
			pg_window.read(timeout=10)



			###################
			### SCAL -> PNG ###
			###################

			## message
			print('\nStarting Operation: SCAL TO PNG')
			pg_window.read(timeout=10)

			time.sleep(2)
			
			WavPipeline.scalToPng(fname,scalname,scalgzname, png_sav_dir)

			print('Complete: SCAL TO PNG')


			## pb update  -- finished scal -> png
			update_text = ['(%d/%d)' % (p+2,(total_files*3)), '(%d/%d)' % (i,total_files),p+2,i]
			
			# update text
			pg_window['proc_c'].update(update_text[0])
			pg_window['file_c'].update(update_text[1])

			# update bar
			pg_window['progressbar_p'].UpdateBar(update_text[2])
			pg_window['progressbar_f'].UpdateBar(update_text[3])
			pg_window.read(timeout=10)


			###################
			###  FLOOD PNG  ###
			###################

			## message
			print('\nStarting Operation: PNG FLOOD-FILL')
			pg_window.read(timeout=10)

			time.sleep(2)

			#gc.collect()
			WavPipeline.flood_png(fname, png_sav_dir)

			print('Complete: PNG FLOOD-FILL')
			
			i+=1
			
			## pb update signal -- finished flooding png
			update_text = ['(%d/%d)' % (p+3,(total_files*3)), '(%d/%d)' % (i,total_files),p+3,i]
			
			# update text
			pg_window['proc_c'].update(update_text[0])
			pg_window['file_c'].update(update_text[1])

			# update bar
			pg_window['progressbar_p'].UpdateBar(update_text[2])
			pg_window['progressbar_f'].UpdateBar(update_text[3])
			pg_window.read(timeout=10)

	
	notify.send('Data processing complete')
Example #22
0
        "items")[0].get("_embedded")
    total_slots = 0
    for day in data.get("deliveryDates"):
        date = datetime.strptime(day['date'], "%Y-%m-%d")
        if date.isocalendar()[1] == cur_week:
            r = 0
            for slot in day['deliveryTimeSlots']:
                if slot['state'] != "full":
                    r += 1
            total_slots += r

    if total_slots > 0:
        notify = Notify()
        if notify.config_file_exists:
            notify.read_config()
        else:
            print(notify.register())
            notify.write_config()
        print("[" + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
              "] Notifying about " + str(total_slots) + " available slots")
        notify.send("AH Bezorg slots beschikbaar", "https://www.ah.nl")


if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == "info":
        notify = Notify()
        notify.read_config()
        print(notify.info())
    else:
        find_slots("7513DB")
Example #23
0
def init():
    global lastCheckL, lastCheckM, cycle
    global pi, DHTSensors, fan, light, servos, mSensor, notify, logFileDHT, logFileM, heatpad

    print("Initializing...")

    # create pigpio instance
    pi = gpio.pi()

    # init Notify
    notify = Notify()

    # open logFiles
    file_exists = os.path.isfile(DHT_LOG)
    logFileDHT = open(DHT_LOG, "a+", buffering=1)
    if not file_exists:
        logFileDHT.write(
            "time, tempLeft, tempRight, tempLight, avgTemp, RHLeft, RHRight, RHLight\n"
        )

    file_exists = os.path.isfile(MOISTURE_LOG)
    logFileM = open(MOISTURE_LOG, "a+", buffering=1)
    if not file_exists:
        logFileM.write(
            "time, potLeft, rawLeft, potMid, rawMid, potRight, rawRight\n")

    # init Sensors
    pi.set_mode(5, gpio.OUTPUT)
    pi.write(5, 1)
    DHTSensors = DHTC(pi, DHT)

    # init Fan
    fan = fanC(pi, FAN_PIN)

    # init ADC for moisture sensor
    mSensor = ADS1115C(pi, 0x48, INSTALLED_MOISTURE_SENSORS)
    mData = mSensor.readAll()
    logSoilData(cTime.nowf(), mData)
    #ADS1115C.checkData(mData, notify, SOIL_THRESH)
    lastCheckM = cTime.now()

    # init Servos
    servos = servosC(pi, SERVOS, fan)

    # init Smartplug
    light = smartplugC(PLUG_ADDR)
    lastCheckL = cTime.now()

    heatpad = smartstripC(HEATPAD_ADDR, HEATPAD_ID)

    # init State
    lastState = -1
    if cTime.between(cTime.nowf(), runTime):
        cycle = 1
        light.set(ON)
    else:
        cycle = 0
        light.set(OFF)

    fan.set(OFF)
    servos.all(OFF)
Example #24
0
def push_notification(pnmsg):
  notify = Notify()
  notify.send(pnmsg)
Example #25
0
from notify_run import Notify
notify = Notify()
notify.send('The system. Is down.')
def push_notification():
    notify = Notify()
    notify.send(pnmsg)
    print("HEY Anurag, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY.")

    print("Check again after an hour.")
Example #27
0
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from selenium.webdriver.firefox.options import Options
from notify_run import Notify
import numpy as np
import pandas as pd
from csv import writer
import time
import csv
import players as pl
import helpers as hp
import sys
import instasignin as inst

# print(sys.argv[0], sys.argv[1], sys.argv[2])

notify = Notify()
notify.register()
print(notify.info())

opts = Options()
opts.headless = True
driver = webdriver.Firefox(options=opts)


def start_scrapping(driver, start, end, player_links):
    dest_cols = {
        "./Scrapped_Data/Players.csv": [
            'Id', 'tm_Id', 'Name', 'Team', 'Nationality', 'Date of Birth',
            'Height', 'Strong Foot', 'Position', 'Joined', 'Contract Expires',
            'Followers'
        ],
Example #28
0
    for size in sizes:
        option = soup.find('option', {'value': re.compile(size + '_')})
        try:
            id = option.get('value').split(size + '_')[1]
            session.post(
                post_url + id, data={'serviceType': 'product-details', 'sku': id})
            if id:
                print("Found size {} id...".format(size))
                print("Carted in", time.time() - cart_time)
        except AttributeError:
            print("Size {} sold out!".format(size))
            pass


if __name__ == "__main__":
    notify = Notify()
    notify.send('Script Started!')
    session = IncapSession()
    session.headers.update(
        {'User-Agent': '"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"'}
    )
    get_product_page_url()
    driver = webdriver.Chrome(
        r'C:\Users\athit\Desktop\deadstock-bot\windows_chromedriver.exe')
    print("Navigating to dummy url to add cookies in browser...")
    dummy_url = '/404error'
    driver.get(base_url + dummy_url)
    for cookie in session.cookies:
        driver.add_cookie({'name': cookie.name, 'value': cookie.value})
    print("Navigating to cart...")
    driver.get(base_url + '/shopping-bag')
Example #29
0
# get data from database
def get_data():
	sql_con=MySQLdb.connect(
	    host='127.0.0.1',
	    port= 3306,
	    user='******',
	    passwd='XXXXXX',
	    db='Hackthon2019',
	    use_unicode=True,
	    charset="utf8"
	)
	sql_cur=sql_con.cursor()
	sql_cur.execute("SELECT using FROM training_data")
	using=sql_con.commit()
	sql_cur.execute("SELECT pnexts FROM training_data")
	pre_nexts=sql_con.commit()

	return (using, pre_nexts)

# train model
training()

model = joblib.load(model_name)

now_using = "photoshop"
result = model.predict(now_using)

# send message to windows computer
notify = Notify()
notify.register()
notify.send("Also open "+str(result)+"?") # should be picture
    notification.notify(
        title=title,
        message=message,
        app_icon="C:/Users/hp/COVID19_Cases_Notification_System/COVID_icon.ico",
        timeout=15)


def getData(url):
    req = requests.get(url)
    return req.text


if __name__ == "__main__":
    while True:
        # notifyAlert("COVID 19 Disease", "Stay Safe !")
        notify = Notify(
        )  # To notify through web push notifications to android mobile phones
        htmlData = getData('https://www.mohfw.gov.in/')

        soup = BeautifulSoup(htmlData, 'html.parser')
        # print(soup.prettify())
        cases = ""
        for tr in soup.find_all('tbody')[0].find_all('tr'):
            cases = cases + tr.get_text()
        cases = cases[1:]
        caselist = cases.split("\n\n")
        states = [
            "Uttar Pradesh", "Madhya Pradesh", "Maharashtra", "Delhi",
            "Rajasthan", "Bihar"
        ]
        statewiseCases = []
        for item in caselist: