def __init__(self, image_in, region): # param self.hp, self.evaluation, self.run, self.env, self.design = parse_arguments( ) self.final_score_sz = 273 # init network self.siam = SiameseNet("SiamFC") pretrained = 'models/SiamFC.pth' load_net(pretrained, self.siam) self.siam.cuda() # init bbox bbox = convert_bbox_format(region, 'center-based') self.pos_x, self.pos_y, self.target_w, self.target_h = bbox.x, bbox.y, bbox.width, bbox.height # init scale factor, penalty self.scale_factors = self.hp.scale_step**np.linspace( -np.ceil(self.hp.scale_num / 2), np.ceil(self.hp.scale_num / 2), self.hp.scale_num) hann_1d = np.expand_dims(np.hanning(self.final_score_sz), axis=0) self.penalty = np.transpose(hann_1d) * hann_1d self.penalty = self.penalty / np.sum(self.penalty) context = self.design.context * (self.target_w + self.target_h) self.z_sz = np.sqrt( np.prod((self.target_w + context) * (self.target_h + context))) self.x_sz = float( self.design.search_sz) / self.design.exemplar_sz * self.z_sz image_, self.templates_z_ = self.siam.get_template_z_new( self.pos_x, self.pos_y, self.z_sz, image_in, self.design)
def test_user_argument_passes_multiple_users(self): filters = parse_arguments(['script_name.py', '--users', 'A User', 'B User']) self.assertEquals(1, len(filters)) self.assertFalse(filters[0](Changeset(user='******'))) self.assertTrue(filters[0](Changeset(user='******'))) self.assertTrue(filters[0](Changeset(user='******')))
def test_parse_arguments1(): args = [] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.logging_level == logging.ERROR assert parsed_args.group_size == defaults.DEFAULT_GRPSIZE assert parsed_args.students_file == defaults.DEFAULT_CSVFILE assert (parsed_args.grouping_method == group_random) is False
def test_parse_arguments3(): """Testing when a file is specified and the --confidential argument is given. To ensure proper output, we assert that the program passes the "confidential" argument""" args = ['--file', 'data.csv', '--confidential'] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.confidential
def test_handles_multiple_arguments(self): filters = parse_arguments(['script_name.py', '--users', 'A User', '--afterDate', '1980-10-2']) self.assertEquals(2, len(filters)) self.assertFalse(filters[0](Changeset(epochTime=self.OCT_2_1980_EPOCH))) self.assertTrue(filters[0](Changeset(epochTime=self.OCT_3_1980_EPOCH))) self.assertFalse(filters[1](Changeset(user='******'))) self.assertTrue(filters[1](Changeset(user='******')))
def test_parse_arguments2(): """Testing for appropriate output when a file is specified and the --debug argument is given. To ensure proper output, we assert that the program parses the correct file and that the logging function being used is the logging.DEBUG function""" args = ['--file', 'data.csv', '--debug'] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.file == 'data.csv' assert parsed_args.logging_level == logging.DEBUG
def main(): obj = MaturaResults('Liczba_matur.csv') args = parse_arguments( available_territories=obj.get_available_territories()) if args.method != 'compare_territories': getattr(obj, args.method)(year=int(args.year or 2018), territory=args.territory or 'Polska') else: obj.compare_territories(args.territory_1, args.territory_2)
def main(): args = parse_arguments(path.basename(__file__)) tunnel_graph = TunnelGraph(tunnel_log=args.tunnel_log, throughput_graph=args.throughput_graph, delay_graph=args.delay_graph, ms_per_bin=args.ms_per_bin) tunnel_results = tunnel_graph.run() sys.stderr.write(tunnel_results['stats'])
def main(): args = parse_arguments(path.basename(__file__)) tunnel_graph = TunnelGraph( tunnel_log=args.tunnel_log, throughput_graph=args.throughput_graph, delay_graph=args.delay_graph, ms_per_bin=args.ms_per_bin) tunnel_results = tunnel_graph.run() sys.stderr.write(tunnel_results['stats'])
def main(): args = parse_arguments(path.basename(__file__)) try: run_tests(args) except: # intended to catch all exceptions # dump traceback ahead in case pkill kills the program sys.stderr.write(traceback.format_exc()) if args.pkill_cleanup: pkill(args) sys.exit('Error in tests!') else: sys.stderr.write('All tests done!\n')
def main(): if not os.geteuid() == 0: print >> sys.stderr, ("You need to run experms with root privileges." "\nAborting.") sys.exit(1) set_procname("experms") args = parse_arguments() try: if os.environ["SYSTEMD_LOG_LEVEL"] == "debug": args.debug = True except KeyError: pass if args.version: print "Experms v" + version sys.exit(0) if args.restore: if args.debug: debug_message() config = configfile.main.Check(args.config, args.debug) restore(config, args.debug) sys.exit(0) if args.total: if args.debug: debug_message() config = configfile.main.Check(args.config, args.debug) print ("Directories configured for watching:\n%s" % len(collect(config)[0])) with open("/proc/sys/fs/inotify/max_user_watches", "r") as inotifyconf: inotifyconfig = inotifyconf.read().strip() print ("Directories allowed to watch with inotify:\n%s" % inotifyconfig) sys.exit(0) if args.debug: debug_message() config = configfile.main.Check(args.config, args.debug) if config.restore: if args.debug: print >> sys.stderr, ("[debug] Starting restore") restore(config, args.debug) start_pyinotify(config, args.debug) sys.exit(0)
def main(): # TODO(sjv): This needs to be refactored - this is dirty but gets the job done # NOTE(sjv): { "paramName": (IsThisRequired, NextArgSetToThis) } valid_args = { "--in": (True, True), "--out": (False, True), "--print": (False, False) } success, options = pa.parse_arguments(valid_args) if not success: print(options) print(print_command_line_options()) else: print(options)
def main(): args = parse_arguments(path.basename(__file__)) try: run_tests(args) except: # intended to catch all exceptions # dump traceback ahead in case pkill kills the program sys.stderr.write(traceback.format_exc()) if args.pkill_cleanup: pkill(args) sys.exit('Error in tests!') else: sys.stderr.write('All tests done!\n')
def print_metrics(repo): if repo.is_empty(): print('The repository is empty') return additional_filters = parse_arguments(sys.argv) numerator_filters = additional_filters + [on_default, is_tdded] denominator_filters = additional_filters + [on_default] (percentage, numerator, denominator) = get_commit_percent(repo, numerator_filters, denominator_filters) if denominator == 0: print('There are no changesets meeting the criteria') return print('%d percent of commits have tests' % percentage)
def main(): args = parse_arguments(path.basename(__file__)) analysis_dir = path.join(project_root.DIR, 'analysis') plot = path.join(analysis_dir, 'plot.py') report = path.join(analysis_dir, 'report.py') plot_cmd = ['python', plot] report_cmd = ['python', report] for cmd in [plot_cmd, report_cmd]: if args.data_dir: cmd += ['--data-dir', args.data_dir] if args.schemes: cmd += ['--schemes', args.schemes] if args.include_acklink: cmd += ['--include-acklink'] check_call(plot_cmd) check_call(report_cmd)
def main(): """ Main function for aliFreeFoldMulti :return: None """ input_file_name, method_name, output_folder_path, is_centroids, \ is_subopt, is_verbose = parse_arguments() initial_time = time() # == ALIFREEFOLD FOR CENTROID == print("Running aliFreeFoldMulti ...") run_alifreefold_using_centroid(input_file_name, output_folder_path, is_verbose) # == STEMS ALIGNMENT == if method_name == "all": for method in ALL_METHODS: run_stems_alignment(method, output_folder_path, is_verbose) else: run_stems_alignment(method_name, output_folder_path, is_verbose) # == ALIFREEFOLD FOR SUBOPTS == if method_name == "all": for method in ALL_METHODS: run_alifreefold_using_subopts(method, output_folder_path, is_verbose) else: run_alifreefold_using_subopts(method_name, output_folder_path, is_verbose) # == COMPUTE TIME == total_time = time() - initial_time # == POSTPROCESSING FILES == replace_files_name(output_folder_path) remove_files(output_folder_path, is_centroids, is_subopt) # == END == print("Total time: {}s".format(total_time))
def main(): args = parse_arguments() if args.create: create_tournament() if args.list: tournaments_list() if args.backup: tournament_backup() if args.restore: restore_tournament(args.restore) if args.active: active_tournament_info() if args.results: enter_results() if args.next: next_tour() if args.scores: tournament_score() if args.editranks: update_players_ranks() if args.sortedbyrank: sorted_by_rank() if args.sortedbynames: sorted_by_names()
def test_parse_arguments2(): args = ['--debug', '--students-file', 'students.csv', '--random'] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.logging_level == logging.DEBUG assert parsed_args.students_file == 'students.csv' assert parsed_args.grouping_method == 'random'
def test_parse_arguments5(): args = ["--num-group", "3"] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.num_group == 3
def test_user_argument_returns_a_filter(self): filters = parse_arguments(['script_name.py', '--users', 'A User']) self.assertEquals(1, len(filters)) self.assertFalse(filters[0](Changeset(user='******'))) self.assertTrue(filters[0](Changeset(user='******')))
def main(): args = parse_arguments(path.basename(__file__)) setup(args)
def main(): args = parse_arguments(path.basename(__file__)) Plot(args).run()
def test_parse_arguments1(): """Testing the program when the user does not enter any arguments""" args = [] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.logging_level == logging.ERROR
def test_parse_arguments_v_logging_level(): args = ['--v'] parsed_arguments = parse_arguments.parse_arguments(args) assert parsed_arguments.logging_level == logging.INFO
def test_parse_arguments_no_arguments(): args = [] parsed_arguments = parse_arguments.parse_arguments(args) assert parsed_arguments.logging_level == logging.ERROR
def main(): args = parse_arguments(path.basename(__file__)) PlotThroughputTime(args).run()
def test_parse_arguments_d_logging_level(): args = ['--d'] parsed_arguments = parse_arguments.parse_arguments(args) assert parsed_arguments.logging_level == logging.DEBUG
def test_file_extension_argument_returns_a_filter(self): filters = parse_arguments(['script_name.py', '--extensions', '.cpp']) self.assertEquals(1, len(filters)) self.assertFalse(filters[0](Changeset(filepaths=['bob.txt']))) self.assertTrue(filters[0](Changeset(filepaths=['bob.cpp'])))
def test_parse_arguments4(): args = ['--absentees', 'maria', '--round-robin', '--group-size', '3'] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.group_size == 3 assert parsed_args.grouping_method == 'rrobin' assert parsed_args.absentees == ['maria']
def test_parse_arguments5(): args = ['--num-group', '3'] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.num_group == 3
def test_no_arguments_returns_no_filters(self): filters = parse_arguments(['script_name.py']) self.assertEquals([], filters)
import sys import logging import parse_arguments import remove_absent_students import defaults import read_student_file import group_rrobin import group_random import display if __name__ == "__main__": # parse the arguments and display welcome message GG_ARGUMENTS = parse_arguments.parse_arguments(sys.argv[1:]) display.display_welcome_message() logging.info("Configuration of GatorGrouper:") logging.debug(GG_ARGUMENTS) # read in the student identifiers from the specified file print(GG_ARGUMENTS.students_file) STUDENT_IDENTIFIERS = remove_absent_students.remove_absent_students( GG_ARGUMENTS.absentees, read_student_file.read_student_file(GG_ARGUMENTS.students_file), ) logging.info("GatorGrouper will group these students:") logging.info("\n %s", display.create_escaped_string_from_list(STUDENT_IDENTIFIERS)) # shuffle the student identifiers SHUFFLED_STUDENT_IDENTIFIERS = group_random.shuffle_students(STUDENT_IDENTIFIERS)
def main(): # PiTFT init################# os.putenv('SDL_VIDEODRIVER','fbcon') os.putenv('SDL_FBDEV','/dev/fb1') os.putenv('SDL_MOUSEDRV','TSLIB') os.putenv('SDL_MOUSEDEV','/dev/input/touchscreen') # Wifi port init################# wifi.init() UDP_IP = "192.168.4.9" UDP_PORT = 9008 MESSAGE = "w" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(("192.168.4.1",8080)) # GPIO init################# volume.volumechange(100) GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(5,GPIO.BOTH,callback=GPIOinput.GPIO5_both) GPIO.add_event_detect(6,GPIO.BOTH,callback=GPIOinput.GPIO6_both) GPIO.add_event_detect(12,GPIO.BOTH,callback=GPIOinput.GPIO12_both) GPIO.add_event_detect(13,GPIO.BOTH,callback=GPIOinput.GPIO13_both) GPIO.add_event_detect(16,GPIO.BOTH,callback=GPIOinput.GPIO16_both) GPIO.add_event_detect(17,GPIO.BOTH,callback=GPIOinput.GPIO17_both) GPIO.add_event_detect(18,GPIO.BOTH,callback=GPIOinput.GPIO18_both) GPIO.add_event_detect(19,GPIO.BOTH,callback=GPIOinput.GPIO19_both) GPIO.add_event_detect(20,GPIO.BOTH,callback=GPIOinput.GPIO20_both) GPIO.add_event_detect(21,GPIO.BOTH,callback=GPIOinput.GPIO21_both) GPIO.add_event_detect(22,GPIO.BOTH,callback=GPIOinput.GPIO22_both) GPIO.add_event_detect(23,GPIO.BOTH,callback=GPIOinput.GPIO23_both) GPIO.add_event_detect(26,GPIO.BOTH,callback=GPIOinput.GPIO26_both) GPIO.add_event_detect(27,GPIO.BOTH,callback=GPIOinput.GPIO27_both) # Parse command line arguments (args, parser) = parse_arguments.parse_arguments() if not args.verbose: warnings.simplefilter('ignore') # Generate sound ################# fps, sound = wavfile.read(piano.wav) tones = range(-24, -12) tones_all = range(-48, 12) sys.stdout.write('Ready for the computation.. ') sys.stdout.flush() transposed_sounds = [shift_pitch.shift_pitch(sound, n) for n in tones] pygame.mixer.init(fps, -16, 1, 2048) # Pygame display init############################################################################ screen = pygame.display.set_mode((320,240)) keys = args.keyboard.read().split('\n') sounds = map(pygame.sndarray.make_sound, transposed_sounds) key_sound = dict(zip(keys, sounds)) keys_all = args.keyall.read().split('\n') transposed_sounds_all = [shift_pitch.shift_pitch(sound, n) for n in tones_all] sounds_all = map(pygame.sndarray.make_sound, transposed_sounds_all) key_sound_all = dict(zip(keys_all, sounds_all)) print(keys) playing = {k: 0 for k in keys} note_duration = 0 former_duration = 0 rest_duration = 0 note_length = 0 tune_length = 0 pygame.init() pygame.mouse.set_visible(False) WHITE = 255,255,255 BLACK = 0,0,0 GPIO.setmode(GPIO.BCM) a = 0 a_rest = 0 b = 0 b_rest = 0 start = 0 current_status = 0 KEYDOWN = 99 KEYUP = 100 genrestflag = 0 needtogenerate = 1 needtogenrest = 1 # Program starts here################ while (welcome.welcomeinit() == 0): a = time.time() b = time.time() #print(1) #print ('Virtual Piano') screen.fill(WHITE) display.displaykey(screen) #timer = threading.Timer(1,listenbutton) #timer.start() #print (a,b,keys) # main loop ################ while True: key = str(globalname.n[1]) event = globalname.n[0] pygame.display.flip() # detect virtual button press ################ if event == KEYDOWN: if (key in key_sound.keys()) and (playing[key] == 0): # Use UDP signal to change volume ################ sock.sendto(MESSAGE, (UDP_IP,UDP_PORT)) data, addr = sock.recvfrom(100) globalname.mainlocation = int(data) % 10 - 2 if (globalname.mainlocation == 3): pygame.quit() vol = int(data) / 10 if vol > 100: sound_vol = 100 elif vol > 40: sound_vol = 90 elif vol > 20: sound_vol = 80 else: sound_vol = 70 volume.volumechange(sound_vol) # generate note sound ################ if (globalname.mainlocation >= 0): sear = (globalname.mainlocation*100 + int(key) ) else: sear = (globalname.mainlocation*100 - int(key) ) key_sound_all[str(sear)].play(fade_ms=50) playing[key] = 1 # calculate rest duration ################ b = time.time() note_duration = b - a a = time.time() current_status = 1 # detect virtual button release ################ elif event == KEYUP and key in key_sound.keys(): # generate note fade out ################ if (globalname.mainlocation >= 0): sear = (globalname.mainlocation*100 + int(key) ) else: sear = (globalname.mainlocation*100 - int(key) ) key_sound_all[str(sear)].fadeout(50) # calculate note duration ################ playing[key] = 0 b = time.time() note_duration = b - a a = time.time() start = 1 globalname.n[0] = 0 current_status = 0 # append a note/rest to the note list ################ if ( former_duration != note_duration ): if (current_status == 0): display.appendnote(key,note_duration,keys) else: display.appendrest(note_duration) # display all things ################ screen.fill(WHITE) if (current_status == 0): display.displaykey(screen) else: display.displaykeyboard(key,keys,screen) display.displaybase(screen) if (start) : display.displaynote(screen) former_duration = note_duration
def main(): args = parse_arguments(path.basename(__file__)) setup(args)
def main(): args = parse_arguments(path.basename(__file__)) Plot(args).run()
# writer = FFMpegWriter(fps=new_vid['fps'], codec=new_vid['codec'], bitrate=new_vid['bitrate'], metadata=metadata) ani.save('temp_video.mp4', writer=writer, dpi=new_vid['dpi']) # # ADD THE SOUND # print('converting wav to mp3 ...') cmd = 'ffmpeg -y -i {} -shortest temp_audio.mp3'.format(audio['filename']) call(cmd, shell=True) print('combining video and audio ...') # -filter:a "volume={}" ... audio['volume'], cmd = 'ffmpeg -y -i temp_video.mp4 -i temp_audio.mp3 -c:v {} -c:a {} -b:a {} -shortest {}'.format( new_vid['codec'], audio['codec'], audio['bitrate'], new_vid['filename']) call(cmd, shell=False) os.remove('temp_audio.mp3') os.remove('temp_video.mp4') # END OF FUNCTIONS ------------------------------------------ # RUN audio, bkg_filename, au_plot, new_vid, metadata, text_p = parse_arguments( sys.argv[1:]) podcast_promo_maker(audio, bkg_filename, au_plot, new_vid, metadata, text_p)
from excel2yaml import excel2yaml from parse_arguments import parse_arguments from parse_arguments import __version__ def main(args): if args.to_excel: to_excel(args.output_path, args.input_path) else: excel2yaml(args.output_path, args.input_path) if __name__ == "__main__": # Parse Arguments ARGS = parse_arguments(sys.argv[1:]) # Setup Logging logging.basicConfig(level=getattr(logging, ARGS.log_level), format='%(message)s') # Log Header logging.info('YAML/Excel Converter v%s', __version__) logging.info(' Input: %s' % ARGS.input_path) logging.info(' Output: %s' % ARGS.output_path) # Write Output main(ARGS) # Log Footer logging.info('Conversion completed successfully')
def test_parse_gatorgrouper_arguments3(): args = ["--verbose", "--round-robin"] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.logging_level == logging.INFO assert parsed_args.grouping_method == "rrobin"
def main(): args = parse_arguments(path.basename(__file__)) PlotThroughputTime(args).run()
def test_parse_arguments4(): args = ["--absentees", "maria", "--round-robin", "--group-size", "3"] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.group_size == 3 assert parsed_args.grouping_method == "rrobin" assert parsed_args.absentees == ["maria"]
def test_parse_arguments2(): args = ["--debug", "--students-file", "students.csv", "--random"] parsed_args = parse_arguments.parse_arguments(args) assert parsed_args.logging_level == logging.DEBUG assert parsed_args.students_file == "students.csv" assert parsed_args.grouping_method == "random"
def test_date_argument_returns_a_filter(self): filters = parse_arguments(['script_name.py', '--afterDate', '1980-10-2']) self.assertEquals(1, len(filters)) self.assertFalse(filters[0](Changeset(epochTime=self.OCT_2_1980_EPOCH))) self.assertTrue(filters[0](Changeset(epochTime=self.OCT_3_1980_EPOCH)))