def test_relative_time(self): # test开头的方法会被自动调用 test_cases = [ # N minutes ("0m abc", (time.mktime(time.localtime()) + 60 * 0, "abc")), ("5m 中文", (time.mktime(time.localtime()) + 60 * 5, "中文")), ("5 onlynum中文", (time.mktime(time.localtime()) + 60 * 5, "onlynum中文")), ( "5", # 匿名事件 (time.mktime(time.localtime()) + 60 * 5, "")), ( "abc 99m", # 顺序 (time.mktime(time.localtime()) + 60 * 99, "abc")), ("中文 空格 99m", (time.mktime(time.localtime()) + 60 * 99, "中文 空格")), # N days ("0d abc space", (time.mktime(time.localtime()) + 24 * 60 * 60 * 0, "abc space")), ("9d abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 9, "abc")), ("100d abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100, "abc")), ("100day abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100, "abc")), ("100days abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100, "abc")), ("abc 100day", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100, "abc")) ] parser = InputParser() for test_case in test_cases: (due_timestamp, thing) = parser.parse_textline(test_case[0]) self.assertEqual(test_case[1], (due_timestamp, thing))
def test_parse_user_tracks(self): tracklist = [ { 'name': 'Track 1', 'start': '00:00' }, { 'name': 'Track 2', 'start': '01:00' }, { 'name': 'Track 3', 'start': '05:30' }, ] parsed = InputParser().parse_user_tracks(tracklist) expected = [{ 'name': 'Track 1', 'start': '00:00', 'duration': '0:01:00' }, { 'name': 'Track 2', 'start': '01:00', 'duration': '0:04:30' }, { 'name': 'Track 3', 'start': '05:30', 'duration': None }] self.assertListEqual(expected, parsed)
def execute_input(input_array): input_parser = InputParser(input_array) board, statement = input_parser.get_board(), input_parser.get_statement() if statement == "occupied?": point = input_parser.get_point() return board.occupied(point) elif statement == "occupies?": stone_type, point = input_parser.get_stone_and_point() return board.occupies(stone_type, point) elif statement == "reachable?": point, stone_type = input_parser.get_point_and_stone() return board.reachable(point, stone_type) elif statement == "place": stone_type, point = input_parser.get_stone_and_point() return format_board_if_valid(board.place_stone(stone_type, point)) elif statement == "remove": stone_type, point = input_parser.get_stone_and_point() return format_board_if_valid(board.remove_stone(stone_type, point)) elif statement == "get-points": stone_type = input_parser.get_stone() return format_points(board.get_points(stone_type))
def main(): f = Figlet(font='slant') print(f.renderText(' ')) print(f.renderText(' openAA:')) print(" 'h' for help, 'q' to quit \n") print(f.renderText(' ')) openAA = OpenAA() inputparser = InputParser(openAA) while True: cmd = input('$$$: ') if cmd == "q": break elif cmd == "h": print("\n -List of commands: -----------\n") print("1. load_data (load datasets)") print("2. load_json (load settings from json file)") print("3. setup_model (set GANN and training parameters)") print("4. visualize (set visualization modes)") print("5. run_model (build the GANN and train it)") print("6. view_model (view GANN and training paramters)") print( "7. predict (run some cases through the trained GANN and look at the predictions)" ) print( "\n For now you will have to read through the code to see how these are used.\n Might add DOCS and better help-instructions here later" ) elif cmd == "": continue else: inputparser.evaluator(cmd)
def fit_linear(file_path): input_parser = InputParser(file_path=file_path) file_input = input_parser.start() linear_calc = FitLinearCalculator(file_input) linear_calc.calculate() linear_calc.print_output() linear_calc.plot(save_plot_name=config.LINEAR_PLOT_FILE_NAME)
def add_flow_chart(self, path, x, y): y += self.tm flow_chart = FlowChart("RGB", (x, y), color="white") with open(path) as file: input_parser = InputParser(file) input_parser.instruct(flow_chart) self.im.paste(flow_chart.im, (0, self.tm))
def search_best_parameter(file_path): input_parser = InputParser(file_path=file_path, contains_ab_values=True) file_input = input_parser.start() linear_calc = FitLinearCalculator(file_input) linear_calc.calculate(chose_ab=True) linear_calc.print_output() linear_calc.plot(save_plot_name=config.LINEAR_PLOT_FILE_NAME) linear_calc.create_and_plot_a_chosing_plot( save_plot_name=config.A_PLOT_FILE_NAME)
def test_parse_input(self): with open('test_data/input.json') as f: input_data = json.load(f) with open('test_data/output.json', 'r') as f: expected = json.load(f) parsed = InputParser().parse_input([input_data])[0] self.assertDictEqual(expected, parsed)
def __init__(self): self.musicdata = [] self.ydl_options = { 'format': 'bestaudio', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', }] } self.dataparser = InputParser()
def parse_input(options): """ validate and parse input high-level description file""" from input_parser import InputParser if options.createmud: log.info("Create MUD file(s) from flow rules in path: %s" % (options.createmud[0])) try: InputParser().create_mud_files(options.createmud[0]) except BaseException, e: log.error('%s' % e.message)
def test_parse_tracks_from_video(self): ip = InputParser() url = 'https://www.youtube.com/watch?v=ldwg3eXiISM' vdata = ip.get_video_info(url) tracks = ip.get_track_list(vdata) self.assertEqual(False, tracks is None) parsed = ip.parse_tracks_from_video(tracks) with open('test_data\\parsed_tracks.json', 'r') as f: expected = json.load(f) self.assertListEqual(expected, parsed)
def main(): flow_chart = FlowChart("RGB", (2480, 3508), color="white") try: fp = sys.stdin if "-f" in sys.argv: file_path = sys.argv[sys.argv.index("-f")+1] fp = open(file_path) input_parser = InputParser(fp) input_parser.instruct(flow_chart) finally: fp.close() return flow_chart
def __init__(self, parent=None): super(CaminoProgrammer, self).__init__(parent) self.setupUi(self) self.actionExit.triggered.connect(QtGui.qApp.quit) self.actionConnect.triggered.connect(self.connectCamino) self.actionDisconnect.triggered.connect(self.disconnectCamino) self.pushButtonConfigureDevice.clicked.connect(self.programCamino) self.pushButtonReadDevice.clicked.connect(self.readCamino) self.inputParser = InputParser(self) # Instance of the settings device self.settings = Settings(self) self.actionSettings.triggered.connect(self.settings.show)
def encrypt_sentence(self, sentence): ''' encrypt the whole sentence ''' words = InputParser().parse(sentence) if self.log_steps: print(f'Phrase: {" ".join([word for word in words])}') encrypted_words = self.encrypt_words(words) if self.log_steps: print(f"Encrypted pass 1: {' '.join(str(w) for w in encrypted_words)}") return self.distil_sentence(encrypted_words, 2)
def start_process(input_file, output_file): handler = FileHandler(input_file, output_file) info = handler.read_file() error_msgs = info['error_msgs'] if len(info['ref_words']) > 0: parser = InputParser(DEFAULT_ANSWER) result = parser.process_info(info['ref_words'], info['price_msgs']) if result: error_msgs.extend(result) answers = parser.answer_questions(info['questions']) handler.write_file(answers, error_msgs) else: handler.error_output("No correct inputs found.")
def main(): # YOUR MAIN CODE GOES HERE st_dict = {} exist_node = {} # sample code to read from stdin. # make sure to remove all spurious print statements as required # by the assignment while True: line = sys.stdin.readline() if line.rstrip().strip() == '': break else: #print('read a line:', line) # parse the input line i_p = InputParser(line, st_dict, exist_node) i_p.parseInput() #print('Finished reading input') # return exit code 0 on successful termination sys.exit(0)
def test_parse_video(self): self.maxDiff = None video = { "url": "https://www.youtube.com/watch?v=ldwg3eXiISM", "tracklist": [{ "name": "ALEX - Insert Soul", "start": "00:00" }, { "name": "Tokyo Rose - The Pact (feat. WVLFPAKT)", "start": "01:47" }, { "name": "ALEX - Ritual", "start": "05:16" }] } parsed = InputParser().parse_video(video) expected = { 'url': 'https://www.youtube.com/watch?v=ldwg3eXiISM', 'filename': 'ALEX & Tokyo Rose - AKUMA [Full Album] 2017-ldwg3eXiISM', 'output_dir': 'ALEX & Tokyo Rose - AKUMA [Full Album] 2017', 'tracklist': [{ 'name': 'ALEX - Insert Soul', 'start': '00:00', 'duration': '0:01:47' }, { 'name': 'Tokyo Rose - The Pact (feat. WVLFPAKT)', 'start': '01:47', 'duration': '0:03:29' }, { 'name': 'ALEX - Ritual', 'start': '05:16', 'duration': None }] } self.assertDictEqual(expected, parsed)
def test_absolute_time_without_date(self): year = time.localtime().tm_year month = time.localtime().tm_mon day = time.localtime().tm_mday today_timestamp = time.mktime( time.strptime(str(year) + str(month) + str(day), "%Y%m%d")) tomorrow_timestamp = time.mktime( time.strptime(str(year) + str(month) + str(day + 1), "%Y%m%d")) # 如果现在过了2点,那么指的是第二天的2点,否则指的是今天的2点 if time.localtime().tm_hour > 2 or (time.localtime().tm_hour == 2 and time.localtime().tm_minute > 0): timestamp_for_2 = tomorrow_timestamp else: timestamp_for_2 = today_timestamp # 如果现在过了23点,那么指的是第二天的23点,否则指的是今天的23点 if time.localtime().tm_hour > 23 or (time.localtime().tm_hour == 23 and time.localtime().tm_minute > 0): timestamp_for_23 = tomorrow_timestamp else: timestamp_for_23 = today_timestamp test_cases = [ ("23:00 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")), ("23am 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")), ("11pm 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")), ("2am 中文", (timestamp_for_2 + 2 * 60 * 60, "中文")) # failed now #( # "中文abc 2:00 中文", # (timestamp_for_2+2*60*60, "中文abc 中文") #) ] parser = InputParser() for test_case in test_cases: (due_timestamp, thing) = parser.parse_textline(test_case[0]) #tmp = parser.parse_textline(test_case[0]) #print tmp self.assertEqual(test_case[1], (due_timestamp, thing))
def test_absolute_time_with_date(self): year = time.localtime().tm_year month = time.localtime().tm_mon day = time.localtime().tm_mday today_timestamp = time.mktime( time.strptime(str(year) + str(month) + str(day), "%Y%m%d")) test_cases = [ ( "2014-11-1 abc1", # 默认是早上8点提醒 (1414800000.0, "abc1")), ("11-1 abc", (1414800000.0, "abc")), ("abc 11-1", (1414800000.0, "abc")), ("2014-11-1 16:30 中文", (1414830600.0, "中文")), ("11-1 16:30 中文", (1414830600.0, "中文")), ("中文 11-1 11pm", (1414854000.0, "中文")), ("中文 11-1 23am", (1414854000.0, "中文")), ("中文 11-1 2am", (1414778400.0, "中文")) ] parser = InputParser() for test_case in test_cases: (due_timestamp, thing) = parser.parse_textline(test_case[0]) self.assertEqual(test_case[1], (due_timestamp, thing))
class Main(Wox): """Class that works with the Wox API.""" parser = InputParser() generator = ResultGenerator() manager = VolumeManager() def query(self, parameters): """ Returns list of results based on provided parameters. Parameters are provided as string stripped from plugin keyword, if any. For instance, input of "v 50 whatever" (assuming plugin keyword is v) will set parameters to "50 whatever". """ if not self.manager.init_success: return [ self.generator.generate_error(), ] value = self.parser.parse(parameters) if value is None: return [] result = self.generator.generate_valid_result(value) return [ result, ] def perform_action(self, value): """Method that reroutes user-defined value to VolumeManager.""" self.manager.perform_action(value) def open_url(self, url): """Opens provided URL as a new tab in default browser.""" # new=2 is a way of saying "new tab please, um, if that's possible" webbrowser.open(url, new=2)
from input_parser import InputParser from docker_runner import DockerRunner if __name__ == "__main__": user_info = InputParser() docker_runner = DockerRunner() docker_runner.run(user_info.get_name(), user_info.get_age())
def parse_input(options): """ validate and parse input high-level description file""" from input_parser import InputParser if options.createmud: log.info("Create MUD file(s) from flow rules in path: %s" % (options.createmud[0])) try: InputParser().create_mud_files(options.createmud[0]) except BaseException, e: log.error('%s' % e.message) if options.checkmud: log.info("Check MUD file consistency using metagraphs") try: InputParser().check_mud_consistency(options.checkmud[0]) except BaseException, e: log.error('%s' % e.message) if options.bpcompare: log.info("Check best practice compliance of MUD policy: %s" % (options.bpcompare[0])) try: InputParser().check_bp_compliance(options.bpcompare[0]) except BaseException, e: log.error('%s' % e.message) # !! The main function are only here for debug. The real compiler don't need this`!! if __name__ == '__main__': import sys
print('farmer2 hand:{}'.format( sorted(self.board_state.get_hands(FARMER_TWO)))) def start_game(self): print('***GAME START***') while not self.board_state.is_terminal: turn = self.board_state.turn action = None if turn == FARMER_ONE: action = self._farmer_one.get_action(self.board_state) print('farmer1 plays {0}'.format(action)) if turn == FARMER_TWO: action = self._farmer_two.get_action(self.board_state) print('farmer2 plays {0}'.format(action)) if turn == LANDLORD: action = self._landlord.get_action(self.board_state) print('landlord plays {0}'.format(action)) self.board_state = self.board_state.next_state(action) # print('hands left landlord: {0}'.format(sorted(self.board_state.hands[LANDLORD]))) # print('hands left farmer one: {0}'.format(sorted(self.board_state.hands[FARMER_ONE]))) # print('hands left farmer two: {0}'.format(sorted(self.board_state.hands[FARMER_TWO]))) print('*** GAME OVER, {0} WIN ***'.format(self.board_state.winner)) if __name__ == '__main__': parser = InputParser() parser.parse_input() game = FightingWithLandlordGame() game.setup(parser) game.start_game()
] options = available_options if len(sys.argv) > 1: options = sys.argv[1:] if '-t' in options: filename = '../res/one_tenth_semeval_twitter_data.txt' else: filename = '../res/semeval_twitter_data.txt' if '-a' in options: options = available_options parser = InputParser(filename) tweet_list = parser.parse() #All preprocessing necessary print('Started preprocessing') analyzer = Analyzer(constants.ESCAPE_SEQUENCE) uFeatureParser = UnigramSWNFeatureParser() for data in tweet_list: tokens = analyzer.analyze(data.tweet_string) for term in tokens: term = term.encode('utf_8').decode('ascii', 'ignore') data.set_tokens(tokens)
scores[i, j] = (row | col) elif x in available: available.remove(x) # ! ---------------------------------------- for i, x in scores: scores[i, x] = available.difference(scores[i, x]) return scores @staticmethod def recursive_fill_fields(scores, sudoku): pass @staticmethod def fill_cell(row, col, n, scores, sudoku: list): sudoku[row][col] = n return scores[row, col].remove(n) parser_obj = InputParser('test1') ret = parser_obj.get_input() matrix = parser_obj.get_square(3, 0) # return generator # for i in matrix: # print(i) scores = SudokuAnalyzer.analyze(matrix, parser_obj, 3, 0) pprint(scores) # SudokuAnalyzer.recursive_fill_fields(scores, ret)
def test_parse_file(self): parser = InputParser() self.assertEqual(parser.parse_file("./input_parser_test_data.txt"), [-1, 0, -1, -1])
available.remove(x) # ! ---------------------------------------- for i, x in scores: scores[i, x] = available.difference(scores[i, x]) return scores @staticmethod def recursive_fill_fields(scores): pass @staticmethod def fill_cell(cell_row, cell_col, field_row, field_col, n, sudoku: list): sudoku[cell_row][cell_col][field_row][field_col] = n parser_obj = InputParser('../test1') parser_obj.cell_length = 3 parser_obj.side_length = 3 # analyzer = SudokuAnalyzer() ret = parser_obj.get_input() # print(*ret, sep='\n') matrix = parser_obj.get_square(0, 0) ret2 = SudokuAnalyzer.analyze(matrix, parser_obj) # SudokuAnalyzer.fill_cell(0, 0, 0, 0, 4, ret) # print(sud) print(ret2)
def parse_input(options): """ validate and parse input high-level description file""" if options.config: log.info("Parsing device configuration files located in : %s" % (options.config)) InputParser().ParseDeviceConfigurations(options.config)
def main(): logging.info("Starting...") training_parser = InputParser( '/Users/skobovm/repos/csep517/hmm/data/twt.train.json') dev_parser = InputParser( '/Users/skobovm/repos/csep517/hmm/data/twt.dev.json') test_parser = InputParser( '/Users/skobovm/repos/csep517/hmm/data/twt.test.json') # First, count the words! counter = WordCounter() for parsed_sentence in training_parser.get_tokenized_sentences(): if parsed_sentence: for i in range(1, len(parsed_sentence) - 1): counter.add_word(parsed_sentence[i][0]) # Finalize counter and separate high frequency from low frequency counter.finalize() # Initialize the models bigram = BigramHMM() trigram = TrigramHMM() for parsed_sentence in training_parser.get_tokenized_sentences(): if parsed_sentence: # Convert the low frequency words to classes counter.classify_sentence(parsed_sentence) bigram.add_sentence(parsed_sentence) trigram.add_sentence(parsed_sentence) # Models have been initialized at this point, finalize the distributions #bigram.finalize() trigram.finalize() # PICK THE PARSER HERE parser = dev_parser # Iterate over data and try to predict num_correct_bigram = 0 num_correct_trigram = 0 total_words = 0 for parsed_sentence in parser.get_tokenized_sentences(): if parsed_sentence: original_sentence = copy.deepcopy(parsed_sentence) # Convert the low frequency words to classes counter.classify_sentence(parsed_sentence) # Bigram lattice #lattice = Lattice(bigram, parsed_sentence) # Trigram lattice tri_lattice = TrigramLattice(trigram, parsed_sentence) # Calculate best POS using viterbi #pos_list_bigram = lattice.get_pos() pos_list_trigram = tri_lattice.get_pos() # Determine how many were correct #num_correct_bigram += get_num_correct(parsed_sentence, pos_list_bigram, lattice) num_correct_trigram += get_num_correct(parsed_sentence, pos_list_trigram, tri_lattice, original_sentence, counter) # Remove the START and STOP chars total_words += (len(parsed_sentence) - 2) print("Accuracy: %s" % (num_correct_trigram / total_words)) else: print('ERROR! Couldnt parse sentence') print("Bigram HMM Accuracy: %s/%s - %s" % (num_correct_bigram, total_words, (num_correct_bigram / total_words))) print("Trigram HMM Accuracy: %s/%s - %s" % (num_correct_trigram, total_words, (num_correct_trigram / total_words)))
def test_get_hand_from_line(self): parser = InputParser() self.assertEqual(parser.get_hand_from_line("2C 2H 3H 4C 4H"), PokerHand(["2C", "2H", "3H", "4C", "4H"]))