def runAlgorithm(listOfStocks, forecast): clear() print("Running Predictive Pricing of", listOfStocks, "Stocks At A", forecast, "Day Forecast") loading = animation.Wait() loading.start() algMain(listOfStocks, forecast) loading.stop()
def main(): file_name = "" output_dir = "" peaks = False if len(sys.argv) == 1: print("input a file to browse waveforms") return None if len(sys.argv) == 2: file_name = sys.argv[1] peaks = True if len(sys.argv) >= 3: file_name = sys.argv[1] output_dir = sys.argv[2] peaks = True wait = animation.Wait(text="Loading File: " + file_name + " ") print(" ") wait.start() digitizer1 = digitizers.CAENDT5730(df_data=file_name) digitizer1.v_range = 2.0 digitizer1.e_cal = 2.0e-15 waves_data = digitizer1.format_data(waves=True) print(" ") wait.stop() retry = True again = False min_distance = 0 min_height = 0 width = 0 heights = [] while retry: if peaks: min_distance = float( input("guess minimum distance between peaks ")) min_height = float(input("guess minimum peak height ")) width = float(input("guess peak widths ")) sipm_plt.waveform_plots(waves_data, get_peaks=peaks, min_dist=min_distance, min_height=min_height, width=width) plt.show() again = input("do it again! y/n ") else: sipm_plt.waveform_plots(waves_data, get_peaks=peaks) plt.show() again = input("do it again! y/n ") if again == "y": retry = True elif again == "n": retry = False else: break
def main(): # Enter shares shares = [raw_input('Enter your share: ')] while True: questions = [ inquirer.List( 'share', message='Enter next share', choices=['OK', 'I don\'t have another one'], ), ] answer = inquirer.prompt(questions)['share'] if answer != 'OK': break shares.append(raw_input('Enter your share: ')) # Recover wait = animation.Wait('spinner', 'Generating randomness.. It may take a while.. ') wait.start() message = PlaintextToHexSecretSharer.recover_secret(shares) wait.stop() print('Original message:\n' + message)
import itertools import warnings import pandas as pd import networkx as nx import animation import glob warnings.simplefilter(action='ignore', category=FutureWarning) currentProblem = {} wait = animation.Wait() def readFile(filename): currentProblem['filename'] = (filename.split('\\')[1]).split('.')[0] dataProblem = {} # Dictionary key,value ==> examCode, [array of students] fileHandle = open(filename, "r") lineList = fileHandle.read().splitlines() fileHandle.close() for student in range(len(lineList)): examsList = lineList[student].rstrip().split() for examcode in examsList: if examcode not in dataProblem.keys(): dataProblem[str(examcode)] = [ student + 1 ] # Επειδή η αρίθμηση ξεκινάει απο 0 προσθέτουμε + 1 για να δείχνουμε σωστά την θέση του φοιτητή else: dataProblem[str(examcode)].append( student + 1 ) # Επειδή η αρίθμηση ξεκινάει απο 0 προσθέτουμε + 1 για να δείχνουμε σωστά την θέση του φοιτητή currentProblem['dataProblem'] = dataProblem
#basestr = str(ordered_bases[i-1]) try: if str(ordered_bases[i-1]).startswith('{0}_'.format(i)) is False: #if re.match('^{0}_'.format(i),ordered_bases[i-1]) is None: ordered_bases = np.insert(ordered_bases, i-1, missing_base_dict.get(i)) except IndexError: ordered_bases = np.append(ordered_bases, missing_base_dict.get(i)) for base in range(len(ordered_bases)): ordered_bases[base] = re.sub("\d+_","",ordered_bases[base]) seq = ''.join(ordered_bases) return seq ''' print("\n----------\n") wait = animation.Wait(text='Remapping data') wait.start() start = time.time() sequences = np.apply_along_axis(mapping, axis=1, arr=X_test).reshape(-1, 1) print("\nSequences mapped") crisprs = np.apply_along_axis(seq_to_crispr, axis=1, arr=sequences).reshape(-1, 1) print("Crisprs found") end = time.time() lapse = end - start wait.stop() print('\nRemapping execution time: {0:.2f} seconds'.format(lapse)) print("\n----------\n") ''' old_start = time.time() sequences = np.apply_along_axis( old_mapping, axis=1, arr=X_test).reshape(-1,1)
def main(): # Select number of shares questions = [ inquirer.List( 'parties', message='How many shares do you want?', choices=['2', '3', '4', 'other'], ), ] answer = inquirer.prompt(questions) if answer['parties'] == 'other': parties = int(raw_input('Type a number: ')) while parties < 2: parties = int(raw_input('Type a number greater than 1: ')) else: parties = int(answer['parties']) # Select revealing threshold if parties > 2: min_threshold = 2 max_threshold = parties thresholds = [x for x in range(min_threshold, max_threshold + 1)] questions = [ inquirer.List( 'threshold', message= 'How many shares should be enough for decryption? (Most secure: ' + str(max_threshold) + ')', choices=thresholds, ), ] answer = inquirer.prompt(questions) threshold = int(answer['threshold']) else: threshold = parties # Select type of shares output questions = [ inquirer.List( 'format', message='Select the format of output images', choices=['png', 'svg', 'terminal'], ), ] format = inquirer.prompt(questions)['format'] # Select size of shares output if format != 'terminal': questions = [ inquirer.List( 'scale', message='Size of output images', choices=['Small', 'Medium', 'Large'], ), ] answers = inquirer.prompt(questions) if answers['scale'] == 'Small': scale = 2 elif answers['scale'] == 'Medium': scale = 4 elif answers['scale'] == 'Large': scale = 8 secret = raw_input('Enter your message: ') wait = animation.Wait('spinner', 'Generating randomness.. It may take a while.. ') wait.start() # Secret-share the message using Shamir's secret sharing scheme. shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, parties) wait.stop() print(shares) for share in shares: # Create png for each share img = pyqrcode.create(share) if format == 'png': img.png(share[0] + '.png', scale=scale) elif format == 'svg': img.svg(share[0] + '.svg', scale=scale) elif format == 'terminal': print(img.terminal())
poses = yaml.load(open(map_path + 'amcl_poses.yaml', 'rb')) map_params = yaml.load(open(map_path + 'map.yaml', 'rb')) origin = map_params['origin'] res = map_params['resolution'] #meters per pixel I = Image.open(map_path + 'map.pgm') w, h = I.size im_w = int(w / step) im_h = int(h / step) files = glob.glob(data_path + '*.p') tqdm.write("Extracting Data") im = extract_data(im_w, im_h, origin, res, files) wait = animation.Wait(text='Skeletonizing\n') wait.start() mask = make_bmap(im, im_w, im_h, 0) skel, distance = medial_axis(mask, return_distance=True) dist_on_skel = distance * skel wait.stop() dist_on_skel_filter = ndimage.filters.gaussian_filter(dist_on_skel, 6) # plt.imshow(dist_on_skel_filter, cmap=plt.cm.nipy_spectral, interpolation='nearest') # plt.show() wait = animation.Wait(text='Skeletonizing again\n') wait.start() mask2 = make_bmap(dist_on_skel_filter, im_w, im_h, 90) # plt.imshow(mask2, cmap=plt.cm.nipy_spectral, interpolation='nearest') # plt.show()
def main(): input_path = "" file_name = "" output_path = "" if len(sys.argv) == 4: file_name = sys.argv[1] input_path = os.path.abspath(sys.argv[2]) output_path = os.path.abspath(sys.argv[3]) elif len(sys.argv) == 3: file_name = sys.argv[1] output_path = os.path.abspath(sys.argv[2]) input_path = os.getcwd() else: print("Specify <file_name> <output_path>!") if not os.path.isfile(file_name): raise FileNotFoundError("File: " + str(file_name) + " not found!") wait = animation.Wait(text="Loading File: " + file_name + " ") print(" ") wait.start() digitizer = digitizers.CAENDT5730(df_data=file_name) digitizer.v_range = 2.0 digitizer.e_cal = 5.0e-15 params_data = digitizer.format_data(waves=False) waves_data = digitizer.format_data(waves=True) wait.stop() print(" ") pulse_charge_peaks = locate_spectrum_peaks(params_data["ENERGY"], 1, file_name, output_path) pulse_height_peaks = locate_triggered_peaks(waves_data) pk.dump([pulse_charge_peaks, pulse_height_peaks], open(input_path + "/" + file_name[:-3] + ".pk", "wb")) norm_proc = Processor() norm_proc.add( fun_name="normalize_waves", settings={"peak_locs": unumpy.nominal_values(pulse_height_peaks)}) # norm_proc.add(fun_name="baseline_subtract", settings={}) norm_proc.add(fun_name="normalize_energy", settings={ "pc_peaks": unumpy.nominal_values(pulse_charge_peaks), "label": "ENERGY" }) t1_file = file_name t1_path = input_path include_other_files = input("Include other files to process? y/n? ") file_list = [t1_file] if include_other_files == "y": what_files = input("Provide file names: ") for file in what_files.split(" "): file_list.append(file) process_data(t1_path, file_list, norm_proc, digitizer, output_dir=output_path, overwrite=False, write_size=5)
import keras, animation import numpy as np from keras.layers import * from keras.models import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from sklearn.model_selection import train_test_split import matplotlib.pylab as plt from unet_fork import * from liveHistCallback import * batch_size = 10 epochs = 75 wait = animation.Wait('spinner', text='Loading data\n') wait.start() in_data = np.load("indata.npy") img_x, img_y = in_data[0].shape in_data = in_data.reshape(in_data.shape[0], img_x, img_y, 1) out_data = np.load("outdata.npy") wait.stop() seed = 7 np.random.seed(seed) x_train, x_test, y_train, y_test = train_test_split(in_data, out_data, test_size=.15, random_state=seed)
def __init__(self, ip="127.0.0.1"): wait = animation.Wait(text="Looking for local FakerNet server") wait.start() self.mm = ModuleManager(ip=ip) error = self.mm.load() wait.stop() if error is not None: self.mm = ModuleManager(ip=ip, https=True, https_ignore=True) error = self.mm.load() wait.stop() if error is not None: if ip == "127.0.0.1": print_formatted_text( HTML('\n\n<ansired>{}</ansired>'.format(error))) wait = animation.Wait(text="FakerNet console is starting") wait.start() self.mm = ModuleManager() self.mm.load() wait.stop() self.mm['init'].check() self.host = "local" else: print_formatted_text( HTML( '<ansired>Failed to connect to the server at {}</ansired>' .format(ip))) sys.exit(1) else: self.host = self.mm.ip else: self.host = self.mm.ip file_history = FileHistory(".fnhistory") self.session = PromptSession(history=file_history) self.global_vars = {"AUTO_ADD": False} self.completer = CommandCompleter(self.mm, self.global_vars) if self.mm.ip == None: err, _ = self.mm['init'].run("verify_permissions") if err is not None: print_formatted_text(HTML('<ansired>{}</ansired>'.format(err))) sys.exit(1) print_formatted_text(HTML( '<ansigreen>{}</ansigreen>'.format(ASCIIART))) print_formatted_text(HTML('<skyblue>Internet-in-a-box\n</skyblue>')) if self.mm.ip == None: print_formatted_text( HTML('<ansigreen>NOTE: In non-server mode!</ansigreen>')) if self.mm['init'].init_needed: self.setup_prompts() else: print_formatted_text( HTML('<ansigreen>Connected to {}</ansigreen>'.format( self.mm.ip))) self.running = True self.current_command = None self.mm.logger.info("Started console")
def main(): wait = animation.Wait('spinner') projectName = input('Enter project name : ') projectStructure = [ 'scenes', 'navigations', 'components', 'styles', 'assets', 'actions', 'constants', 'reducers', 'stores', 'utils' ] navigations = ['app','auth','tab'] try: print('\nCreating a new react-native project!') wait.start() initProject = subprocess.Popen(['npx', 'react-native', 'init', projectName], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = initProject.communicate() wait.stop() if stdout != '': print('[ Project ] - ' + projectName + 'Created') # Create project structure container for i in range(len(projectStructure)): os.makedirs(projectName + '/src/' + projectStructure[i]) path = projectName + '/src/' + projectStructure[i] + '/' + 'index.js' open(path, 'w').close() for i in range(len(navigations)): os.makedirs(projectName + '/src/Navigations/' + navigations[i]) subprocess.check_call('tree ' + projectName + '/src', shell=True) rnative_base = input('Do you want to install native-base? (YES/NO) : ').lower() if rnative_base == 'y' or rnative_base == 'yes': print('Installing native-base . . . .') inative_base = subprocess.Popen(['yarn', '--cwd', projectName, 'add', 'native-base'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = inative_base.communicate() print('[ Native Base ] Successfully installed') rnavigation = input('Do you want to install react-navigation? (YES/NO) : ').lower() if rnavigation == 'y' or rnavigation == 'yes': print('Installing react-navigation . . . .') wait.start() # Installing react navigation native irnavigationative = subprocess.Popen(['yarn', '--cwd', projectName, 'add', '@react-navigation/native'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = irnavigationative.communicate() # Installing dependencies into a bare React Native project irnavigationdependencies = subprocess.Popen(['yarn', '--cwd', projectName, 'add', 'react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = irnavigationdependencies.communicate() # Installing react navigation stack irnavigationstack = subprocess.Popen(['yarn', '--cwd', projectName, 'add', '@react-navigation/native'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = irnavigationstack.communicate() wait.stop() print('[ @react-navigation/native ] Successfully installed') print('[ @react-navigation/stack ] Successfully installed') print('[ react navigation dependencies ] Successfully installed') except FileExistsError: print("Project " , projectName , " already exists")
def main(): downloaded_count = 0 unique_list = [] init(autoreset=True) # initialize the colours printed in terminal load_config() # create \tmp directory in the project folder if it does not exist temp_download_location = os.path.abspath(os.curdir) + r"\tmp" if not os.path.exists(temp_download_location): os.makedirs(temp_download_location) wait = animation.Wait() wait.text = "{0}[{1}] Retrieving all the video links from the youtube playlist. Please wait ".format( Fore.LIGHTWHITE_EX, datetime.now()) wait.start() r = requests.get(youtube_playlist_url) # Get the play list from youtube soup = BeautifulSoup(r.text, "lxml") tgt_list = [ a['href'] for a in soup.find_all('a', href=True) if re.search('watch', a['href']) ] for n in tgt_list: if "v=" in n and "list=" in n and "index=" in n: index = int([ indx.replace("index=", "") for indx in n.split("&") if "index=" in indx ][0]) if index >= 1 and index <= top_n: # top n songs if n not in unique_list: unique_list.append('https://www.youtube.com' + n) wait.stop() print(" ") ## database to keep track of downloaded songs if os.path.isfile(downloaded_history_file_location): downloaded_music = np.load(downloaded_history_file_location, allow_pickle=True).item() else: downloaded_music = {} total_count = len(unique_list) for link in unique_list: try: id = link[link.find("=") + 1:link.find("&")] if id in downloaded_music: print("{0}[{1}] {2} has already been downloaded.".format( Fore.LIGHTWHITE_EX, datetime.now(), downloaded_music[id])) downloaded_count += 1 else: y = YouTube(link, on_progress_callback=on_progress) id = y.video_id file_name_mp3 = "{0}.mp3".format(get_valid_filename(y.title)) downloaded_music[id] = file_name_mp3 print("{0}[{1}] Downloading {2} ...".format( Fore.LIGHTWHITE_EX, datetime.now(), file_name_mp3)) t = y.streams.filter(only_audio=True).first() t.download(output_path=temp_download_location) print(" ") default_filename = t.default_filename subprocess.run([ 'ffmpeg', '-n', '-i', os.path.join(temp_download_location, default_filename), os.path.join(mp3_download_location, file_name_mp3) ]) print("{0}[{1}] Downloading {2} completed.".format( Fore.LIGHTGREEN_EX, datetime.now(), file_name_mp3)) np.save(downloaded_history_file_location, downloaded_music) downloaded_count += 1 # delete mp4 file from tmp folder os.unlink( os.path.join(temp_download_location, default_filename)) print("{0}[{1}] {2}/{3} downloaded.".format( Fore.LIGHTWHITE_EX, datetime.now(), downloaded_count, total_count)) except Exception as ex: print("{0}[{1}] Exception: {2}".format(Fore.LIGHTRED_EX, datetime.now(), str(ex))) continue np.save(downloaded_history_file_location, downloaded_music)
#def f(): classifier.fit(X_train, Y_train, callbacks=switch_case_callbacks(x=True)) # return # mem_usage = memory_usage(f, max_usage=True) # print('Maximum memory usage: %s' % max(mem_usage)) end = time.time() time_completion = (end - start) / 60 print('Model completion time: {0:.2f} minutes'.format(time_completion)) else: # To get input and output dimensions for model with open(sample, 'rt') as x, open(encoded_output, 'rt') as y: waiting = animation.Wait( text="Retriving input and output dimensions for the model") waiting.start() # Row count takes a while row_count = sum(1 for row in open( sample)) # Needed for steps_per_epoch in fit.generator input_reader = csv.reader(x) output_reader = csv.reader(y) first_input = next(input_reader) first_output = next(output_reader) input_dim = len(first_input) y_categories = len(first_output) waiting.stop() # https://keras.io/models/sequential/#fit_generator def generator(encoded_input, encoded_output): while True:
#!/usr/bin/env python3 #General Packages import imageio import os import re import glob from tqdm import tqdm import animation path = os.getcwd() + '/gif_imgs/' files = sorted(glob.glob(os.path.join(path, '*.png')), key=lambda x: float(re.findall("([0-9]+?)\.png", x)[0])) # files = sorted(glob.glob( path),key=lambda x:float(path.basename(x).split("_")[3])) seq = [] tqdm.write("Generating frame sequence") for file in tqdm(files): seq.append(imageio.imread(file)) wait = animation.Wait('spinner', text='Writing gif ') wait.start() imageio.mimwrite('voronoi_expansion_anim.gif', seq, duration=.02) wait.stop()
with open('./Obama-SOTU-2015.txt', 'r') as o2015: obama2015 = o2015.read().decode('ascii', 'ignore').replace('\r', '') with open('./Obama-SOTU-2016.txt', 'r') as o2016: obama2016 = o2016.read().decode('ascii', 'ignore').replace('\r', '') obama = { 'obama2015': { 'fullText': obama2015 }, 'obama2016': { 'fullText': obama2016 } } wait = animation.Wait('spinner') print "Extracting features" wait.start() for key, obiwan in obama.iteritems(): sents = sent_tokenize(obiwan['fullText']) obiwan['sentCount'] = len(sents) words = word_tokenize(obiwan['fullText']) obiwan['wordCount'] = len(words) obiwan['averageWPS'] = obiwan['wordCount'] / obiwan['sentCount'] # obiwan['POSTagged'], obiwan['POSCount'], obiwan['ratingStats'] = posAndRate(sents) obiwan['POSStats'] = splitStats(sents) obama[key] = obiwan wait.stop() for key, value in obama.iteritems(): print '---------'