def __init__(self): input_reader = InputReader() self.state = input_reader.read(0) self.output_writer = OutputWriter('naive') self.num_rows = self.state['numRows'] self.num_cols = self.state['numCols'] self.num_drones = self.state['numDrones'] self.num_turns = self.state['numTurns'] self.max_payload = self.state['maxPayload'] self.num_product_types = self.state['numProductTypes'] self.product_weights = self.state['productWeights'] self.num_warehouses = self.state['numWarehouses'] # warehouse: liste auf dicts: x, y, items -> itemstock self.warehouse_data = self.state['warehousesData'] # order data: liste auf dicts: x, y, numorders, items self.order_data = self.state['orderData'] # get list of items self.item_lists = numpy.zeros( (len(self.order_data), len(self.product_weights)), dtype=int) self.turns_used = numpy.zeros(self.num_drones) self.drone_location = numpy.zeros((self.num_drones, 2)) for order_idx in numpy.arange(len(self.order_data)): for item in self.order_data[order_idx]['items']: self.item_lists[order_idx][item] += 1 for n in numpy.arange(self.num_drones): self.drone_location[n] = [0, 0]
def read_match_list(self, reader: InputReader) -> None: """ Reads both the match list and replacement list from the console, and set them in the correct properties :param reader: The reader object to read the user input :return: None """ self.match_from_list = reader.read_yesno( "Match this value from a list and apply another value ?") if self.match_from_list: if self.value_by_logic: self.match_source_column = reader.read_val( "Specify the source column name to use as match value: ") print( "Type in the list of values to match this column, one per line. Empty Enter to Exit" ) self.match_values = [] self.match_replacements = [] val = "some text" while val != "": val = reader.read_val() self.match_values.append(val) print( "Now type in the same amount of lines for each of the replacement values, in the same order as " "the previous list. Empty Enter to Exit") val = "some text" while val != "": val = reader.read_val() self.match_replacements.append(val) self.match_replacement_default = reader.read_val( "Type in the value to apply if no match is found: ")
def test_block_correct_call(): r = InputReader() a = r.add_block_key(str('red')) assert a.name == 'red' assert a._end == 'end' assert not a._case assert not a._ignoreunknown
def read_nullable_info(self, reader: InputReader) -> None: """ Reads the nullable related info from the terminal to this objects properties The afected properties are: nullable, increment_if_null, null_replacement_value :param reader: The reader object to read the user input :return: None """ self.nullable = reader.read_yesno("Is this column nullable ?") if self.nullable: self.increment_if_null = reader.read_yesno( "Generate incrementing number if this column is null ?") if self.increment_if_null: self.increment_rule = reader.read_val( "Type in the extra rule for applying increment where 'val' " "refers to the value(Ex: val <= 100).Press Enter to have none" ) else: use_replacement = reader.read_yesno( "Use a replacement value for null ?") if use_replacement: self.null_replacement_value = reader.read_val( "Type in the null replacement value with double or" " single quotations for strings or dates") else: self.null_replacement_value = None
def test_unterminated_block(): r = InputReader(ignoreunknown=True) a = r.add_block_key('red') a.add_boolean_key('rose') with raises(ReaderError) as e: r.read_input(['red', 'rose']) assert search('Unterminated block', str(e.value))
def test_case_sensitivity_at_class_level(): ir = InputReader(case=True) assert ir._case l = ir.add_line_key('RED') assert l._case with raises(ValueError): ir2 = InputReader(case='True')
def test_regex_case_definition(): r = InputReader() a = r.add_regex_line('red', r'funny\d+DOG') assert a.name == 'red' assert a._regex.pattern == r'funny\d+DOG' if sys.version_info.major == 3: assert a._regex.flags == (re.IGNORECASE | re.UNICODE) else: assert a._regex.flags == re.IGNORECASE regex = re.compile(r'funny\d+dog', re.IGNORECASE) b = r.add_regex_line('blue', regex) assert b.name == 'blue' assert b._regex == regex c = r.add_regex_line('green', r'funny\d+DOG', case=True) assert c.name == 'green' assert c._regex.pattern == r'funny\d+DOG' if sys.version_info.major == 3: assert c._regex.flags == re.UNICODE else: assert c._regex.flags == 0 regex = re.compile(r'funny\d+dog', re.IGNORECASE) # Case is ignored if a regex flag is given d = r.add_regex_line('gray', regex, case=True) assert d.name == 'gray' assert d._regex == regex
def test_block_case_definition(): r = InputReader() a = r.add_block_key('red', case=True) assert a._case with raises(ValueError) as e: r.add_block_key('blue', case='True') assert 'case must be bool' in str(e.value)
def __init__(self): input_reader = InputReader() self.state = input_reader.read(0) self.output_writer = OutputWriter('naive') self.num_rows = self.state['numRows'] self.num_cols = self.state['numCols'] self.num_drones = self.state['numDrones'] self.num_turns = self.state['numTurns'] self.max_payload = self.state['maxPayload'] self.num_product_types = self.state['numProductTypes'] self.product_weights = self.state['productWeights'] self.num_warehouses = self.state['numWarehouses'] # warehouse: liste auf dicts: x, y, items -> itemstock self.warehouse_data = self.state['warehousesData'] # order data: liste auf dicts: x, y, numorders, items self.order_data = self.state['orderData'] # get list of items self.item_lists = numpy.zeros((len(self.order_data), len(self.product_weights)), dtype=int) self.turns_used = numpy.zeros(self.num_drones) self.drone_location = numpy.zeros((self.num_drones, 2)) for order_idx in numpy.arange(len(self.order_data)): for item in self.order_data[order_idx]['items']: self.item_lists[order_idx][item] += 1 for n in numpy.arange(self.num_drones): self.drone_location[n] = [0, 0]
def test_block_repeat_in_definition(): # You cannot repeat keys r = InputReader() r.add_block_key('red') with raises(ReaderError) as e: r.add_block_key('red') assert search(r'The keyname "\w+" has been defined twice', str(e.value))
def test_block_ignoreunknown_definition(): r = InputReader() a = r.add_block_key('red', ignoreunknown=True) assert a._ignoreunknown with raises(ValueError) as e: b = r.add_block_key('blue', ignoreunknown='True') assert 'ignoreunknown must be bool' in str(e.value)
def __init__(self): """ Default constructor for the Arith helper class """ self.reader = InputReader() self.parser = None self.interpreter = None self.nodes = []
def test_regex_repeat_in_definition(): # You cannot repeat keys r = InputReader() r.add_regex_line('red', r'test') with raises(ReaderError) as e: r.add_regex_line('red', r'tax') regex = r'The handle "\w+" has been defined twice' assert search(regex, str(e.value))
def test_block_read_end(): r = InputReader() a = r.add_block_key('red', end='subend') a.add_boolean_key('rose', default=False) inp = r.read_input(['red', 'rose', 'subend']) assert inp.red.rose inp = r.read_input(['red', 'subend']) assert not inp.red.rose
def test_block_end_definition(): r = InputReader() a = r.add_block_key('red', end='subend') assert a._end == 'subend' a = r.add_block_key('green', end=str('subending')) assert a._end == 'subending' with raises(ValueError) as e: r.add_block_key('blue', end=23) assert 'end must be str' in str(e.value)
def test_regex_correct_call_Str(): r = InputReader() a = r.add_regex_line(str('red'), str(r'funny\d+dog')) assert a.name == 'red' assert a._regex.pattern == r'funny\d+dog' regex = re.compile(str(r'funny\d+dog')) b = r.add_regex_line(str('blue'), regex) assert b.name == 'blue' assert b._regex == regex
def test_mutex_correct_call(): r = InputReader() meg = r.add_mutually_exclusive_group() a = meg.add_boolean_key('red') assert a.name == 'red' assert a._action assert not a._default meg.add_boolean_key('blue') with raises(ReaderError): meg.add_boolean_key('red')
def test_read_mutex_set_dest_set_required(): r = InputReader() meg = r.add_mutually_exclusive_group(required=True, dest='color') meg.add_boolean_key('red') meg.add_boolean_key('blue') meg.add_boolean_key('green') r.add_boolean_key('cyan') with raises(ReaderError) as e: inp = r.read_input(['cyan']) assert search(r'One and only one of .* must be included', str(e.value))
def test_regex_correct_call(): r = InputReader() a = r.add_regex_line('red', r'funny\d+dog') assert a.name == 'red' assert a._regex.pattern == r'funny\d+dog' assert not a._case regex = re.compile(r'funny\d+dog') b = r.add_regex_line('blue', regex) assert b.name == 'blue' assert b._regex == regex assert not b._case
def test_block_read_ignoreunknown(): r = InputReader() a = r.add_block_key('red', ignoreunknown=False) a.add_boolean_key('rose') with raises(ReaderError) as e: inp = r.read_input(['red', 'rose', 'rider', 'end']) assert 'Unrecognized key' in str(e.value) b = r.add_block_key('blue', ignoreunknown=True) b.add_boolean_key('rose') inp = r.read_input(['blue', 'rose', 'rider', 'end']) assert inp.blue.rose assert 'rider' not in inp.blue
def test_block_read_case_sensitive(): r = InputReader() a = r.add_block_key('red', case=True, end='END') a.add_boolean_key('ROSE') inp = r.read_input(['RED', 'ROSE', 'END']) assert 'rose' not in inp.red assert inp.red.ROSE b = r.add_block_key('pink', case=False) b.add_boolean_key('ROSE') inp = r.read_input(['PINK', 'ROSE', 'END']) assert 'ROSE' not in inp.pink assert inp.pink.rose
def test_block_read_subblocks(): r = InputReader() a = r.add_block_key('red') b = a.add_block_key('blue') b.add_boolean_key('egg') inp = r.read_input(['red', 'blue', 'egg', 'end', 'end']) assert inp.red.blue.egg c = r.add_block_key('pink') d = c.add_block_key('blue', end='subend') d.add_boolean_key('egg') inp = r.read_input(['pink', 'blue', 'egg', 'subend', 'end']) assert inp.pink.blue.egg
def test_mutex_custom_options(): r = InputReader() meg = r.add_mutually_exclusive_group(dest='rainbow', default='cloudy', required=True) assert meg._dest == 'rainbow' assert meg._default == 'cloudy' assert meg._required with raises(ValueError) as e: meg = r.add_mutually_exclusive_group(dest=23) assert 'dest must be a str, given' in str(e.value) with raises(ValueError) as e: meg = r.add_mutually_exclusive_group(required='True') assert 'required value must be a bool, given' in str(e.value)
def read_logic(self, reader: InputReader) -> None: """ Reads the logic info for this column, which affects the properties value_by_logic and logic_expression :param reader: The reader object to read the user input :return: None """ self.value_by_logic = reader.read_yesno( "Use a specific logic for this column values ?") if self.value_by_logic: print("Type whatever code you want to build this new column.") print("Other columns are referable as {colname}") self.logic_expression = reader.read_val( "Ex: {price} * {tax} / 100")
def test_comments_are_handled_correctly(setup): parse_string = setup[-1] reader = InputReader(comment='#') reader.add_boolean_key('red') reader.add_boolean_key('blue') reader.add_line_key('path') with raises(ReaderError) as e: reader.read_input(parse_string) regex = r'expected \d+ arguments, got \d+' assert search(regex, str(e.value))
def test_block_missing_keyname(): r = InputReader() with raises(TypeError): r.add_block_key() with raises(TypeError): r.add_block_key(end='subend') with raises(TypeError): r.add_block_key(ignoreunknown=True) with raises(TypeError): r.add_block_key(case=False)
def test_read_mutex_set_required(): r = InputReader() meg = r.add_mutually_exclusive_group(required=True) meg.add_boolean_key('red') meg.add_boolean_key('blue') meg.add_boolean_key('green') inp = r.read_input(['blue']) assert inp.blue assert not inp.red assert not inp.green with raises(ReaderError) as e: inp = r.read_input([]) assert search(r'One and only one of .* must be included', str(e.value))
def main(): rules_and_words = InputReader.fetch_input_lines() rules, words = seperate_rules_from_words(rules_and_words) rules = format_rules(rules) sol = "^" + build_regex(rules, "0", {}) + "$" print(sol) result = sum([1 for word in words if regex.match(sol, word)]) print(result)
def main(): parens = InputReader.fetch_input() floor = 0 for index, paren in enumerate(parens): floor += 1 if paren == "(" else -1 if floor == -1: print(index + 1) break
def test_line_read_case_sensitive(): r = InputReader() r.add_line_key('blue', type=str) inp = r.read_input(['blue HeLLo']) assert inp.blue == 'hello' r.add_line_key('red', type=str, case=True) inp = r.read_input(['red HeLLo']) assert inp.red == 'HeLLo'
def set_black_tiles(rounds): tiles = InputReader.fetch_input_lines() black_tiles = find_black_tiles(tiles) grid = initalize_grid(rounds) for black_tile in black_tiles: x_offset, y_offset = key_to_coords(black_tile) x = (2 * rounds) + x_offset y = (2 * rounds) + y_offset grid[x][y] = True return grid
def main(): ribbon_length = 0 dimension_sets = InputReader.fetch_input_lines() for dimensions in dimension_sets: x, y, z = parse_dimensions(dimensions) xy = (2 * x) + (2 * y) xz = (2 * x) + (2 * z) yz = (2 * y) + (2 * z) ribbon_length += (x * y * z) + min(xy, xz, yz) print(ribbon_length)
def test_read_mutex(): r = InputReader() meg = r.add_mutually_exclusive_group() meg.add_boolean_key('red') meg.add_boolean_key('blue') meg.add_boolean_key('green') inp = r.read_input(['red']) assert inp.red assert not inp.blue assert not inp.green with raises(ReaderError) as e: inp = r.read_input(['red', 'blue']) assert search(r'Only one of .* may be included', str(e.value)) # Unfortunately we cannot detect duplicate groups in different meg's meg2 = r.add_mutually_exclusive_group() meg2.add_boolean_key('red')
def main(): input_path, output_filename, cache_path, img_version, verbose,\ set_delimiter, collector_delimiter = parse_arguments() if verbose: logging.basicConfig(level=logging.INFO) info("Starting program") api = Scryfall(cache_path, img_version) input_reader = InputReader(set_delimiter, collector_delimiter) decklist = input_reader.get_decklist(input_path) if download_cards_from_decklist(decklist, api) > 0: error("Something went wrong when downloading") return 1 pdf_file = MtgPrinter(output_filename) if print_decklist(decklist, api, pdf_file) > 0: error("Something went wrong when doing the pdf") return 1 return 0
def test_unknown_keys_cause_failure(setup): # Don't ignore unknown keys parse_string = setup[-1] reader = InputReader(comment='//', ignoreunknown=False) reader.add_boolean_key('red') reader.add_line_key('path') with raises(ReaderError) as e: reader.read_input(parse_string) assert 'Unrecognized key' in str(e.value)
def open_column_menu(reader: InputReader, col: Column) -> None: """ Shows a menu of all possible options to this specific column. Each option applies a specific action to the column, by altering its properties, that are then interpreted in the SQL generation :param reader: The reader class object that reads values in specific ways :param col: The column to which the menu is going to work on :return: None """ option = "" while option != "e": clear_screen() col.show_full() # options menu print("\nOptions:") print("1 - Change Name") print("2 - Change type") print("3 - Discard column") print("4 - Merge with another column") print("5 - Nullable") print("6 - Match value from list") print("7 - Value by given logic") print("e - Exit menu") option = reader.read_val() if option == "1": col.name = reader.read_val("Type in the new name for the column") elif option == "2": col.type = reader.read_from_options("Select the new type", ["number", "bool", "str", "date"]) if col.type == "bool": col.invert = reader.read_yesno("Invert the value ?") elif option == "3": col.discard = not col.discard elif option == "4": col.read_merge_info(reader) elif option == "5": col.read_nullable_info(reader) elif option == "6": col.read_match_list(reader) elif option == "7": col.read_logic(reader)
def test_read_mutex_set_dest(): r = InputReader() # This is the best way to use meg's meg = r.add_mutually_exclusive_group(dest='color') meg.add_boolean_key('red', action='red') meg.add_boolean_key('blue', action='blue') meg.add_boolean_key('green', action='green') meg.add_boolean_key('pink', action='pink') meg.add_boolean_key('gray', action='pink') meg.add_boolean_key('cyan', action='cyan') r.add_boolean_key('white') inp = r.read_input(['cyan', 'white']) assert inp.color == 'cyan' assert inp.white assert 'red' not in inp assert 'blue' not in inp assert 'green' not in inp assert 'pink' not in inp assert 'gray' not in inp assert 'cyan' not in inp
def main(): sq_feet_wrapping_paper = 0 dimension_sets = InputReader.fetch_input_lines() for dimensions in dimension_sets: x, y, z = parse_dimensions(dimensions) xy = x * y xz = x * z yz = y * z sq_feet_wrapping_paper += (2 * xy) + (2 * xz) + (2 * yz) + min( xy, xz, yz) print(sq_feet_wrapping_paper)
def test_regex_read(): r = InputReader() # Remember it's case-insensitive r.add_regex_line('red', r'funny(\d+)DOG\s*(kitty)?') inp = r.read_input(['funny14dog']) assert inp.red.group(0) == 'funny14dog' assert inp.red.group(1) == '14' inp = r.read_input(['funny12DOG kitty']) # Regex won't lowercase for you assert inp.red.group(0) == 'funny12DOG kitty' assert inp.red.group(1) == '12' assert inp.red.group(2) == 'kitty' r.add_regex_line('blue', r'(SILLY|ODD)\s*(goose|duck)', case=True) inp = r.read_input(['SILLY goose']) assert inp.blue.group(0) == 'SILLY goose' inp = r.read_input(['ODD duck']) assert inp.blue.group(0) == 'ODD duck'
def test_block_name_definition(): r = InputReader() with raises(ValueError) as e: r.add_block_key(23) assert 'keyname must be str' in str(e.value) with raises(ValueError) as e: r.add_block_key('hello goodbye') assert 'String cannot contain spaces' in str(e.value) with raises(ValueError) as e: r.add_block_key('') assert 'String cannot be of zero length' in str(e.value)
def main(): secret_key = InputReader.fetch_input() done = False num = 0 while not done: value_to_hash = secret_key + str(num) hex_value = md5(value_to_hash.encode()).hexdigest() first_5 = str(hex_value)[0:6] if first_5 == "00000": done = True else: num += 1 print(num)
def test_regex_handle_definition(): r = InputReader() with raises(ValueError) as e: r.add_regex_line(23, r'test') assert 'handle must be str' in str(e.value) with raises(ValueError) as e: r.add_regex_line('hello goodbye', r'test') assert 'String cannot contain spaces' in str(e.value) with raises(ValueError) as e: r.add_regex_line('', r'test') assert 'String cannot be of zero length' in str(e.value)
class Arith: """ Arith class used to run the arith expression tokening language """ def __init__(self): """ Default constructor for the Arith helper class """ self.reader = InputReader() self.parser = None self.interpreter = None self.nodes = [] def create_nodes(self, tokens): self.nodes = [] for token in tokens: if token in OPERATORS_LIST: current_node = ASTOperator('', '', token) else: current_node = ASTInteger(token) self.nodes.append(current_node) def run(self): """ Function used to run the program, which prompts user to enter an expression and returns a abstract syntax tree if input is valid for the arith language :return None: """ while True: try: # get expression from user self.reader.get_expression() # check if expression has all valid characters if self.reader.decrypt_expression(): # create AST nodes self.create_nodes(self.reader.get_tokens()) # attempt to parse, meaning creating AST self.parser = Parser(self.nodes) root = self.parser.parse() # interpret the AST and return value self.interpreter = Interpreter(root) value = self.interpreter.traverse_ast() print('{0}'.format(value)) except Exception as e: print(e.args[0]) except KeyboardInterrupt: print("\nGracefully shutting down...") try: sys.exit(0) except SystemExit: os._exit(0) self.reader.reset_reader() sys.exit(0)
def main(): santa_x = 0 santa_y = 0 robo_x = 0 robo_y = 0 visited = {coord_to_key(0, 0)} directions = InputReader.fetch_input() for index, direction in enumerate(directions): if index % 2 == 0: santa_x, santa_y = update_coord(santa_x, santa_y, direction, visited) else: robo_x, robo_y = update_coord(robo_x, robo_y, direction, visited) print(len(visited))
def test_ignoreunknown_actually_ignores_unknown(setup): # Ignore unknown keys parse_string = setup[-1] reader = InputReader(comment='//', ignoreunknown=True) reader.add_boolean_key('red') reader.add_line_key('path') inp = reader.read_input(parse_string) with raises(AttributeError): inp.blue
def open_main_menu(reader: InputReader, import_settings:ImportSettings) -> None: """ Main entry menu, where the user can select, add or delete columns, as well as proceed to the SQL generation :param reader: The reader class object that reads values in specific ways :param import_settings: All the import settings including interpreted and added columns :return: None """ option = "" while option != "g": clear_screen() show_column_definitions(import_settings.columns) # options menu print("\nOptions:") print("n - new column") print("d - delete column") print("g - Generate SQL") print("column number - Change column") option = reader.read_val() if option == "n": col_index = len(import_settings.columns) import_settings.columns.append(Column("col{}".format(col_index+1), col_index, "str", "Example Data", True)) elif option == "d": delete_info = input_reader.read_val("What is the number of the column to delete ? You use ranges like 1-5") try: if delete_info.isdigit(): del_index = int(delete_info) - 1 import_settings.columns = list(filter(lambda col: col.index != del_index, import_settings.columns)) else: start, end = map(lambda val: int(val.strip()) - 1, delete_info.split("-")) import_settings.columns = list(filter( lambda col: col.index < start or col.index > end, import_settings.columns )) except Exception: print("Incorrect delete information") elif option == "g": pass else: try: option_number = int(option) if option_number < 0: print("There is no column with number {}".format(option_number)) else: column = import_settings.get_column_by_original_index(option_number) open_column_menu(reader, column) except Exception: print("Invalid column number")
def main(): print("Reading Input") (reviews, targets) = InputReader.run() # Uncomment this for faster testing. #(reviews, targets) = (reviews[:100], targets[:100]) print("Building Vocabulary") vocabulary = Vocabulary(reviews, targets) print(f"Vocab size: {vocabulary.num_words}") print("Converting inputs") inputs = vocabulary.featurize(reviews) print("Beginning Training") runner = Runner(inputs, targets) for epoch in range(100): runner.run_epoch()
def main(): x = 0 y = 0 presents = 1 visited = {coord_to_key(0, 0)} directions = InputReader.fetch_input() for direction in directions: if direction == "^": y += 1 elif direction == "v": y -= 1 elif direction == ">": x += 1 else: x -= 1 if not coord_to_key(x, y) in visited: presents += 1 visited.add(coord_to_key(x, y)) print(presents)
def main(): rules_and_words = InputReader.fetch_input_lines() rules, words = seperate_rules_from_words(rules_and_words) rules = format_rules(rules) mem_42 = build_regex(rules, "42", {}) mem_31 = build_regex(rules, "31", {}) solution_set = set() max_word_size = 0 for word in words: max_word_size = max(max_word_size, len(word)) for x in range(1, max_word_size): memo = {} memo["8"] = mem_42 + "+" memo["11"] = "(" + mem_42 + "){" + str( x) + "}" + "(" + mem_31 + "){" + str(x) + "}" sol = "^" + build_regex(rules, "0", memo) + "$" results = [word for word in words if regex.match(sol, word)] for result in results: solution_set.add(result) for blah in solution_set: print(blah) print(len(solution_set))
def read_merge_info(self, reader: InputReader) -> None: """ Reads the merging information as well as the padding for the merged column :param reader: The reader object to read the user input :return: None """ self.merge = reader.read_yesno("Merge this column with another one ?") if self.merge: self.merge_index = reader.read_int( "Type the number of the column to merge: ") - 1 self.merge_char = reader.read_val( "Type the text that separates both merged columns: ") self.pad = reader.read_yesno("Pad the merging column ? ") if self.pad: self.pad_char = reader.read_val("Select the pad char: ") self.pad_total_count = reader.read_int( "What is the total amount of chars the padded column will have ? " )
def main(): final_result = 0 problems = InputReader.fetch_input_lines() reworked_problems = [shunting_yard(problem) for problem in problems] results = [evaluate(problem) for problem in reworked_problems] print(sum(results))
def read_downloaded_images(): input_reader = InputReader(INPUT_PARQUETS) input_reader.read_parquet_files_as_row_groups(callback=process_dataframe)
import struct from input_reader import InputReader, list_cameras from tracker import Tracker target_ip = args.ip target_port = args.port if args.faces >= 40: print( "Transmission of tracking data over network is not supported with 40 or more faces." ) fps = 0 if os.name == 'nt': fps = args.fps input_reader = InputReader(args.capture, args.raw_rgb, args.width, args.height, fps) log = None out = None first = True height = 0 width = 0 tracker = None sock = None tracking_time = 0.0 tracking_frames = 0 frame_count = 0 features = [ "eye_l", "eye_r", "eyebrow_steepness_l", "eyebrow_updown_l", "eyebrow_quirk_l", "eyebrow_steepness_r", "eyebrow_updown_r",
return None def stemming(self, text): return None def auxillary_preprocess(self, text_with_rating): func_list = [ self.convert_lower_case, self.ignore_punctuation, self.tokenize, self.ignore_stopwords ] inp = text_with_rating[0] for func in func_list: inp = func(inp) return (inp, text_with_rating[1]) def process_text(self, text_generator, correct_spell=False, stem=False): for batch in text_generator: print batch yield map(self.auxillary_preprocess, batch) if __name__ == "__main__": from input_reader import InputReader input_reader = InputReader(1, 10) input_dir = "/home/rohittulu/Documents/aclImdb/train/pos/" text_generator = input_reader.get_batches(input_dir) text_processor = Textpreprocessor() for processed_batch in text_processor.process_text(text_generator): print processed_batch
def start_convergence(self, convParm, startVal, step): """ Run convergence study with the specified parameter, its initial value, and increment size convParam: string, convergence is determined w.r.t. this variable eg. 'kpoints', 'ke cutoff' startVal: list, initial value for convParam eg. 'kpoints' - [4,4,4], 'ke cutoff' - [10] step: list, increment for convParam between two runs eg. 'kpoints' = [2,2,2], 'ke cutoff' - [1] """ # check if convergence parameter is valid string self.convergeParam = str(convParm) if (self.convergeParam != 'kpoints'): raise Exception('Currently, only \'kpoints\' is supported') else: # set initial values for the k-point grid # TO DO: check for non-integer in array self.startValue = np.array(startVal) self.startValue = self.startValue.astype(int) if (len(self.startValue) != 3): raise Exception('k-point grid is input as [x,y,z]') if (any(i < 0 for i in self.startValue)): raise Exception('k-point grid value must be greater than 0') # set step size for k-point grid # TO DO: check for non-integer values self.stepSize = np.array(step) self.stepSize = self.stepSize.astype(int) if (len(self.stepSize) != 3): raise Exception('k-point grid step is input as [x,y,z]') if (any(i < 0 for i in self.stepSize)): raise Exception('k-point grid step must be greater than 0') # read sample inputfile qeInput = InputReader(self.inputFile) qeInput.read_file() linesList = qeInput.get_lines_file() lineNum = qeInput.find_line_number(self.convergeParam) # modify k-point input card # TO DO: make it generic if (self.convergeParam == 'kpoints'): modLinesList = self.modify_kpoint_card(linesList, lineNum) while self._notConverged: # create input file for job # for each value, a separate folder is created and all the files # relevant to the run are stored in it jobStr = self.convergeParam + '_' + \ np.array2string(self.startValue,separator='_')[1:-1] workDir = os.getcwd() jobPath = workDir + '/' + jobStr inpFile = 'in.' + jobStr outFile = 'out.' + jobStr # create job directory if not os.path.exists(jobPath): os.makedirs(jobPath) os.chdir(jobPath) # change convParam value if (self.convergeParam == 'kpoints'): modLinesList[lineNum+1] = \ np.array2string(self.startValue,separator=' ')[1:-1] + \ ' 0 0 0\n' # create new input files with changed convParam newInput = InputWriter(inpFile, modLinesList) newInput.write_lines_to_file() # launch task task = JobLauncher('mpirun -np 16 pw.x', inpFile, outFile) task.job_run() # parse output file after job finishes and update results readOut = OutputParser(self.dftPackage) readOut.parse_op_file(outFile) # store output in results array # TO DO: retrieve the relevant convergeParam (make generic) self._results.append([readOut.get_kpoints(), \ readOut.get_totenergy()]) # check convergence if(len(self._results) >= 2): deltaTotEnergy = abs(self._results[-1][1] - \ self._results[-2][1]) if (deltaTotEnergy <= self.tolerance): # total energy has converged self._notConverged = False else: # update convParam and set up new calculation os.chdir(workDir) self.startValue += self.stepSize # print, plot result print('Convergence test completed!') if (self.convergeParam == 'kpoints'): print('K-point grid needed for convergence: ' + self.startValue) self.plot_results()
sys.exit(0) target_ip = args.ip target_port = args.port if args.faces >= 40: print("Transmission of tracking data over network is not supported with 40 or more faces.") fps = 0 dcap = None use_dshowcapture_flag = False if os.name == 'nt': fps = args.fps dcap = args.dcap use_dshowcapture_flag = True if args.use_dshowcapture == 1 else False input_reader = InputReader(args.capture, args.raw_rgb, args.width, args.height, fps, use_dshowcapture=use_dshowcapture_flag, dcap=dcap) if args.dcap == -1 and type(input_reader) == DShowCaptureReader: fps = min(fps, input_reader.device.get_fps()) else: input_reader = InputReader(args.capture, args.raw_rgb, args.width, args.height, fps, use_dshowcapture=use_dshowcapture_flag) if type(input_reader.reader) == VideoReader: fps = 0 log = None out = None first = True height = 0 width = 0 tracker = None sock = None total_tracking_time = 0.0
def read_band(filename): '''Reads a formatted input file.''' from input_reader import InputReader import sys from pyscf import gto, dft, pbc from pyscf.pbc import gto as pbcgto, dft as pbcdft, df as pbcdf, scf as pbcscf import numpy as np from mole import concatenate_cells # initialize reader for a pySCF input reader = InputReader(comment=['!', '#', '::', '//'], case=False, ignoreunknown=True) # define "band" block rband = reader.add_block_key('band', required=True) rband.add_line_key('npoints', type=int, required=True) rband.add_regex_line('points', '\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)', repeat=True) # read the input file inp = reader.read_input(filename) inp.nskpts = len(inp.band.points) # get each special k-point skpts = np.zeros((inp.nskpts, 3)) for i in range(inp.nskpts): skpts[i][0] = inp.band.points[i].group(1) skpts[i][1] = inp.band.points[i].group(2) skpts[i][2] = inp.band.points[i].group(3) # get distance between spcial kpoints dkpts = np.zeros((inp.nskpts - 1)) for i in range(inp.nskpts - 1): temp = skpts[i + 1] - skpts[i] dkpts[i] = np.sqrt(np.dot(temp, temp)) # kpoints spacing kspace = dkpts.sum() / float(inp.band.npoints) # get kpoint coordinates x = np.array([], dtype=float) for i in range(inp.nskpts - 1): vec = skpts[i + 1] - skpts[i] lvec = np.sqrt(np.dot(vec, vec)) temp = np.arange(0, lvec, kspace) / lvec temp = np.outer(temp, vec) + skpts[i] x = np.append(x, temp.flatten()) x = np.array(x).flatten() lx = len(x) x = x.reshape(int(lx / 3.), 3) if not (x[-1] == skpts[-1]).all(): x = np.append(x, [skpts[-1]], axis=0) # replace all 1's with zeros ix = np.where(x == 1.) x[ix] = 0. inp.kpts = np.copy(x) return inp
def main(): foods = InputReader.fetch_input_lines() alergen_to_words = map_alergens_to_words(foods) alergen_to_word = match_alergen_to_word(alergen_to_words) print_canonical_list(alergen_to_word)
def main(): lines = InputReader.fetch_input_seperated_by_empty_lines() player1_cards, player2_cards = initalize_decks(lines) winning_deck = combat(player1_cards, player2_cards) print(calcualte_score(winning_deck))
target_ip = args.ip target_port = args.port if args.faces >= 40: print( "Transmission of tracking data over network is not supported with 40 or more faces." ) fps = 0 if os.name == 'nt': fps = args.fps use_escapi_flag = True if args.use_escapi == 1 else False input_reader = InputReader(args.capture, args.raw_rgb, args.width, args.height, fps, use_escapi=use_escapi_flag) else: input_reader = InputReader(args.capture, args.raw_rgb, args.width, args.height, fps, use_escapi=False) if type(input_reader.reader) == VideoReader: fps = 0 log = None out = None first = True