def savedKeys(): # Initalise the saved key array savedKeys = [] # Loop through the directory for the public keys for fileName in os.listdir('keys/public/'): # Check that it is a csv file if os.path.isfile('keys/public/' + fileName) and fileName.endswith('.csv'): # Deduce the name of the key from the filename name = fileName.replace('.csv', '') # Set the public key file path publicKeyFile = 'keys/public/' + name + '.csv' # Read the public key file publicKeyFileContents = file.read(publicKeyFile) # Split the file into an array of values publicKeyFileValues = publicKeyFileContents.split(',') # Set the public key publicKey = crypto.PublicKey(publicKeyFileValues[0], publicKeyFileValues[1]) # Check if a corresponding private key exists and set the flag if os.path.isfile('keys/private/' + fileName): # Set the private key file path privateKeyFile = 'keys/private/' + name + '.csv' # Read the private key file privateKeyFileContents = file.read(privateKeyFile) # Split the file into an array of values privateKeyFileValues = privateKeyFileContents.split(',') # Set the private key privateKey = crypto.PrivateKey(privateKeyFileValues[0], privateKeyFileValues[1], privateKeyFileValues[2]) # Create a new saved key object with the private key and add it to the return array savedKeys.append(SavedKey(name, publicKey, privateKey)) else: # Create a new saved key object without the private key and add it to the return array savedKeys.append(SavedKey(name, publicKey)) # Return the array of saved keys return savedKeys
def courseq(): courses = read('courses.csv') questions = read('questions.csv') if authentic: if request.method == "POST": survey_name = request.form["survey"] question = request.form.getlist("question") return redirect( url_for('.surveys', survey_name=survey_name, question=question)) return render_template("select.html", all_questions=questions, all_courses=courses) else: return redirect("/")
def __init__(self, iterate, **kwargs): self.iterate = iterate self.startState = file.read() self.neighbor = Neighbor(self.startState) self.update_states = None if "update_states" in kwargs: self.update_states = True
def update_detekt_config(properties_info): try: open_checker_list = [] skip_checker_list = [] checker_options = {} if 'OPEN_CHECKERS' in properties_info: open_checker_list = properties_info['OPEN_CHECKERS'].split(';') if 'SKIP_FILTERS' in properties_info: skip_checker_list = properties_info['SKIP_FILTERS'].split(';') if 'CHECKER_OPTIONS' in properties_info: checker_options = json.loads(properties_info['CHECKER_OPTIONS']) config_file_path = properties_info["CONFIG_PATH"] with open(config_file_path, 'r', encoding='utf-8') as file: config_dict = yaml.load(file.read()) for rule_set_key, rule_set_value in config_dict.items(): if is_valid_detekt_rule_set(rule_set_key): for checker in rule_set_value.keys(): if re.match("([A-Z][a-z]+)+", checker): if checker in open_checker_list: config_dict[rule_set_key][checker]['active'] = True else: config_dict[rule_set_key][checker][ 'active'] = False for rule_key, rule_value in checker_options.items(): if rule_key in open_checker_list and rule_key in rule_set_value: for option_key, option_value in json.loads( rule_value).items(): config_dict[rule_set_key][rule_key][ option_key] = option_value with open(config_file_path, 'w', encoding='utf-8') as file: yaml.dump(config_dict, file, default_flow_style=False) except Exception as e: raise Exception(e)
def initialize(self, path): self.pbm = File.read(path) dimen = self.pbm[2].split() self.width, self.height = [int(x) for x in dimen] pixels = self.pbm[3:] filtered_pixels = Util.filterData(pixels) self.matrix = Matrix(self.width, self.height, filtered_pixels)
def get_data(self, fname): if file.exists(fname) == 1: cfg = file.read(fname) return data.build_config(cfg) else: print "Utilizando configuracion predeterminado" return None
def export(key, includePrivateKey=True): # Add the key name to the export content = key.name # Add the public key to the export content += "," + file.read('keys/public/' + key.name + '.csv') # Check if there is a corresponding private key and the user wanted to include it if includePrivateKey: # Add the private key to the export content += "," + file.read('keys/private/' + key.name + '.csv') # Save the export file.save(key.name + ' Export.csv', content)
def file_db_for(): file_paht = 'D:\\\\vscode\\python\\src\\study\\chinese-xinhua\\data\\\\word.json' with open(file_paht, 'r', encoding='UTF-8') as file: words = file.read() values = [] for i in json.loads(words): value = (i['word'], i['oldword'], i['strokes'], i['pinyin'], i['radicals'], i['explanation'], i['more']) values.append(value)
def importKey(filePath): # Read the key file at the given path keyCsv = file.read(filePath) # Get the data from the csv keyName, publicKey, privateKey = extractKeyFileData(keyCsv) # Save the key saveKey(keyName, publicKey, privateKey)
def importBallot(filePath): # Read the ballot file at the given path ballotFile = file.read(filePath) # Get the data from the csv title, address = extractBallotFileData(ballotFile) # Save the ballot saveBallot(title, address)
def file_db_kv1(): file_paht = 'D:\\\\vscode\\python\\src\\study\\chinese-xinhua\\data\\\\word.json' with open(file_paht, 'r', encoding='UTF-8') as file: words = file.read() values = [] value = [] for word in json.loads(words): for k, v in word.items(): value.append(v) values.append(value)
def initialize(self, path): mask_file = File.read(path) dimen = mask_file[0].split() self.width, self.height = [int(x) for x in dimen] self.a = int((self.width - 1) / 2) self.b = int((self.height - 1) / 2) data = mask_file[1:] filtered_data = list(map(toInt, data)) self.matrix = Matrix(self.width, self.height, filtered_data) self.mask = self.matrix.getMatrixData() self.weight = self.width * self.height
def contentMd5(self): with open(self.path, mode = 'rb') as file: md5 = hashlib.md5() while True: data = file.read(MD5_BUFFER_SIZE) if not data: break md5.update(data) return md5.hexdigest()
def __init__(self, iterate, maxDis, maxSuc, alpha, startTemp, **kwargs): self.iterate = iterate self.maxDis = maxDis self.maxSuc = maxSuc self.alpha = alpha self.startState = file.read() self.neighbor = Neighbor(self.startState) self.startTemp = startTemp self.state_update = None if 'state_update' in kwargs: self.state_update = True
def file_xiehouyu_db(): file_path = 'D:\\vscode\\python\\src\\study\\chinese-xinhua\\data\\xiehouyu.json' with open(file_path, 'r', encoding='UTF-8') as file: words = file.read() values = [] for word in json.loads(words): value = (word['riddle'], word['answer']) values.append(value) sql = 'INSERT INTO xiehouyu (riddle,answer) values (%s,%s)' ms = mysql.MysqlPool() count = ms.insert_many(sql, values) print('insert into xiehouyu db influence %s rows' % count)
def update_nn(): games = file.read() boards = [] outputs = [] for game in games: winner = game[-1] winner_turn = 1 if winner != "N" else 0.5 game = game[:-1] while game: next_move = int(game[-1]) game = game[:-1] board = [0] * 18 for index, move in enumerate(game): board[(index % 2) * 9 + int(move)] = 1 board = [1 if str(i) not in game else 0 for i in range(9)] + board output = [0.5] * 9 output[next_move] = winner_turn boards.append(board) outputs.append(output) winner_turn = 1 - winner_turn if games: X = np.array(boards) Y = np.array(outputs) # initialize weights randomly with mean 0 np.random.seed(4) global syn0 syn0 = 2 * np.random.random((27, 9)) - 1 l1 = None for i in range(20000): # forward propagation l0 = X l1 = nonlin(np.dot(l0, syn0)) # how much did we miss? l1_error = Y - l1 # multiply how much we missed by the # slope of the sigmoid at the values in l1 l1_delta = l1_error * nonlin(l1, True) # update weights syn0 += np.dot(l0.T, l1_delta) print(l1) print("updated")
def get_devices_from_file(filename): """ Reads in a list of devices from a plain text file and returns the list. :param filename: The name of a file containing device names or IP addresses. :return: A populated list of device names and/or IP addresses. """ full_filename = file.get_full_path(filename) devices = [] if file.exists(full_filename): devices = file.read(full_filename) return devices
def cleanup(textfile): print('') print('Reading ' + textfile + '...') txt = file.read(textfile, 0) i = 0 print('Found ' + str(len(txt)) + ' items:') while i < len(txt): print(txt[i]) i += 1 i = 0 print('') print('Finding problems...') print('') newnewtxt = [''] while i < len(txt): test = findthing(txt[i], ':') test = test and findthing(txt[i], '[') test = test and findthing(txt[i], ']') test = test and findthing(txt[i], '"') if test: print('No problem found with ' + txt[i]) newnewtxt.append(txt[i]) elif not test: print('Problem found with ' + txt[i] + '. Cleaning...') i += 1 del newnewtxt[0] print('Checking complete.') print('') print('Opening for write...') newtxt = file.openforwrite(textfile) i = 0 print('') print('New file being created:') print('') while i < len(newnewtxt): string = newnewtxt[i] string = string.replace('invalid', '') string = string.replace('valid', '') string = string.replace('[True]', '') string = string.replace('[False]', '') string = string.replace('[Valid]', '') string = string.replace('[Invalid]', '') string = string.rstrip() print(string) file.write(newtxt, string) i += 1 print('') print('Done') file.closeafterwrite(newtxt) return
def file_idiom_db(): file_path = 'D:\\vscode\python\src\study\chinese-xinhua\data\idiom.json' with open(file_path, 'r', encoding='UTF-8') as file: words = file.read() values = [] for word in json.loads(words): value = (word['word'], word['abbreviation'], word['pinyin'], word['explanation'], word['example'], word['derivation']) values.append(value) sql = 'INSERT INTO idiom (word,abbreviation,spell,explanation,example,derivation) values (%s,%s,%s,%s,%s,%s)' ms = mysql.MysqlPool() count = ms.insert_many(sql, values) print('insert into idiom db influence %s rows' % count)
def read(args, config): address = None if args.list: if config.api_key: print('Default location: {}'.format(file.read(config.save_file))) return if args.key: if args.address: key = [parse_address(args.address)] loc = config.default_location config.save(key[0], loc) print('API key stored') return if config.api_key: print("To change API, use: -k <api-key>") return if args.address: address = parse_address(args.address) if not address: return else: if file.exists(config.save_file): data = file.read_json(config.save_file) if (data): address = data['default_location'] if args.default: if args.address: key = config.api_key loc = address config.save(key, loc) print('Saving {} as default location'.format(address)) return if args.save: if args.address: key = config.api_key loc = address config.save(key, loc) print('Saving {} as default location'.format(address)) else: if config.api_key: print('No location specified') return return address
def readLocalCardInfo(name, set): content = file.read(STORED_LOOk_UPS) snippets = content.split('###') for snippet in snippets: if snippet == '': continue if snippet.split('$$$')[0] != name or snippet.split('$$$')[1] != set: continue return { 'name': name, 'set': set, 'correctedName': snippet.split('$$$')[2], 'reprint': int(snippet.split('$$$')[3]) } return None
def generateState(self): pChange = [] # Posicao de mudanca das rainhas # nChange = len(self.state) / random.randint(1, len(self.state) - 1) # numero de linhas que mudarao nChange = (len(self.state)/2) - 1 # numero de linhas que mudarao # nChange = (len(self.state)/2) # numero de linhas que mudarao for col in range(nChange): pChange.append(random.randint(0, len(self.state) - 1)) for col in range(len(pChange)): self.qP[pChange[col]] = random.randint(0, len(self.state) - 1) self.createBoard() file.write(self.qP, self.baseBoard) return file.read('./resource/newBoard.txt')
def read_map(filename, HDU=0, field=0, nest=False): """Read Healpix map all columns of the specified HDU are read into a compound numpy MASKED array if nest is not None, the map is converted if need to NEST or RING ordering. this function requires healpy""" m, h = read(filename, HDU=HDU, return_header=True) try: m = m[field] except exceptions.KeyError: m = m.values()[field] nside = healpy.npix2nside(m.size) if not nest is None: if h.get('ORDERING', False): if h['ORDERING'] == 'NESTED' and not nest: idx = healpy.ring2nest(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] elif h['ORDERING'] == 'RING' and nest: idx = healpy.nest2ring(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] return healpy.ma(m)
def update_occheck_config(properties_info): try: open_checker_str = "" checker_options = {} if 'OPEN_CHECKERS' in properties_info: open_checker_str = properties_info['OPEN_CHECKERS'].replace( ";", ",") if 'CHECKER_OPTIONS' in properties_info: checker_options = json.loads(properties_info['CHECKER_OPTIONS']) config_file_path = properties_info["CONFIG_PATH"] config_dict = {} with open(config_file_path, 'r', encoding='utf-8') as file: config_dict = yaml.load(file.read()) config_dict["Checks"] = "-*" if open_checker_str: config_dict[ "Checks"] = config_dict["Checks"] + "," + open_checker_str checker_option_list = [] if "CheckOptions" in config_dict and len( config_dict["CheckOptions"]) > 0: checker_option_list = config_dict["CheckOptions"][:] for rule_key, rule_value in checker_options.items(): for option_key, option_value in json.loads(rule_value).items(): checker_option = {} checker_option["key"] = rule_key + "." + option_key checker_option["value"] = option_value for exist_option in config_dict["CheckOptions"]: if exist_option["key"] == checker_option["key"]: checker_option_list.remove(exist_option) checker_option_list.append(checker_option) break else: checker_option_list.append(checker_option) config_dict["CheckOptions"] = checker_option_list with open(config_file_path, 'w', encoding='utf-8') as file: yaml.dump(config_dict, file, default_flow_style=False) except Exception as e: raise Exception(e)
def checktopleveldomain(email): domain = email.split('@')[-1] toplevel = domain.split('.')[1:] i = 0 tld = file.read('tlds-alpha-by-domain.txt', 0) tld = tld[1:] tld.append('WA') returnvar = True while i < len(toplevel): ii = 0 testtld = 0 while ii < len(tld): if toplevel[i] == tld[ii].lower(): testtld += 1 else: testtld += 0 ii += 1 if testtld == 1: returnvar = returnvar and True else: returnvar = returnvar and False i += 1 return ['checktopleveldomain', returnvar]
def savedBallots(): # Initalise the saved ballots array savedBallots = [] # Loop through the directory for the saved ballots for fileName in os.listdir('ballots/'): # Check that it is a csv file if os.path.isfile('ballots/' + fileName) and fileName.endswith('.ballot'): # Deduce the ballot title from the filename title = fileName.replace('.ballot', '') # Get the ballot address from the file address = file.read('ballots/' + fileName) # Create a new saved ballot object and add it to the return array savedBallots.append(Ballot(title, address)) # Return the array of saved ballots return savedBallots
def main(argv): if len(argv) < 2: print('Please enter input and output files as arguments!') sys.exit(0) # first arg is input path input_path = argv[0] # second arg is output path output_path = argv[1] direction = 'asc' # if they specified ascending or descending if len(argv) == 3: if argv[2] == 'desc': direction = 'desc' # reading the file and parsing the names name_list = file.read(input_path) # sorting the names sorted_name_list = sort_names.sort_by_len_alpha(name_list, direction) # write the sorted names to the output file file.write(output_path, sorted_name_list)
import operator, functools, itertools, string, file, enable1 text = tuple(map(int, file.read('p059_cipher.txt').split(','))) s = max(map(''.join, itertools.product(string.ascii_lowercase, repeat=3)), key=lambda s: sum(1 for x in ''.join(itertools.starmap(lambda i, y: chr(int(y) ^ ord(s[i % 3])), enumerate(text))).split() if enable1.isword(x))) print(sum(itertools.starmap(lambda i, y: int(y) ^ ord(s[i % 3]), enumerate(text))))
import file input = file.read('inputs/day03.txt') paths = input.split('\n') path_1 = paths[0].split(',') path_2 = paths[1].split(',') def calcPoints(path): x = 0 y = 0 step = 0 directions = {'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1)} points = {} for segment in path: dx, dy = directions[segment[0]] for _ in range(int(segment[1:])): x += dx y += dy step += 1 if (x, y) not in points: points[(x, y)] = step return points def partOne(): points_1 = calcPoints(path_1) points_2 = calcPoints(path_2)
import file content = file.read('file Test.txt') print(content) file.write('file Test.txt',content + '\n\nFooter') content = file.read('file Test.txt') print(content) file.append('file Test.txt','\nLegal|Copyright') content = file.read('file Test.txt') print(content)
#Wesbert J Edouard #U73502535 #September 13, 2019 #Fall 2019 - Data Structures and Algorithms from file import read newlist = read() print(newlist) def increasetrendpoints(): v = (len(newlist) - 1) x = 0 y = 1 boolean = 0 while x < v: if (newlist[x] - newlist[y]) < 0: #print("\nincreasing trend at position", x, "to", y, end=" ") if (y + 1) <= v: x = y y += 1 if (newlist[x] - newlist[y]) > 0: boolean += 1 if boolean < 2: print("\ntrend change point is value: ", newlist[y], "at position: ", y) else: exit() def decreasetrendpoints(): v = (len(newlist) - 1) x = 0
import file content = file.read('file Test.txt') print(content) file.write('file Test.txt', content + '\n\nFooter') content = file.read('file Test.txt') print(content) file.append('file Test.txt', '\nLegal|Copyright') content = file.read('file Test.txt') print(content)
import file instructions = file.read('inputs/day05.txt').split(',') def getParams(intcode, pointer, modes): mode_a = modes.pop() if len(modes) > 0 else 0 mode_b = modes.pop() if len(modes) > 0 else 0 a = intcode[pointer + 1] if mode_a == 1 else intcode[intcode[pointer + 1]] b = intcode[pointer + 2] if mode_b == 1 else intcode[intcode[pointer + 2]] c = intcode[pointer + 3] if pointer + 3 < len(intcode) else None return (a, b, c) def runTest(intcode, input): pointer = 0 output = [] while intcode[pointer] != 99: instruction = str(intcode[pointer]) opcode, modes = int(instruction[-2:]), list(map(int, instruction[:-2])) if opcode == 1: a, b, c = getParams(intcode, pointer, modes) intcode[c] = a + b elif opcode == 2: a, b, c = getParams(intcode, pointer, modes) intcode[c] = a * b elif opcode == 3: inputPosition = intcode[pointer + 1]
def crawl_saved_files(dir): for f in file.list_files(dir): html = file.read(f) table_rows = parser.table(html) save_table(table_rows)
def save_table(table_rows): table_list = [ 'https:http://%s:%s' % (i['IP Address'], i['Port']) for i in table_rows if 'IP Address' in i ] file.save_list('proxies', table_list, 'a') """Accepts a file directory name and returns all table data in all of its HTML files.""" def crawl_saved_files(dir): for f in file.list_files(dir): html = file.read(f) table_rows = parser.table(html) save_table(table_rows) def peakpmm(): html = crawler.crawl_one('https://www.peakpmm.com') soup = bs4.BeautifulSoup(html, "html.parser") print(soup.find('h1')) html = file.read('colors.html') for table in parser.all_tables(html): table_rows = parser.table_no_headers(table) file.save_list('colors.csv', table_rows, 'a')