def main(): fileName = input('Enter file name : ') # Used variables pawnAmountBW = {'WHITE': 0, 'BLACK': 0} # number of pawns for each side dataSplitted = [] readFile(fileName, dataSplitted) # parse user's input into array # Algorithms option print("Choose Algorithm By Input The Number :") print("1. Hill Climbing") print("2. Simulated Annealing") print("3. Genetic Algorithm") chosenAlgo = int(input("Choose : ")) while (chosenAlgo > 3 or chosenAlgo < 1): print("Choose The Correct Number Please...") chosenAlgo = int(input("Choose : ")) # Execute the chosen algorithm if (chosenAlgo == 1): state = parseState(dataSplitted, pawnAmountBW) # generate an initial state result = hillClimbing(state, pawnAmountBW) elif (chosenAlgo == 2): temperature = int(input('Temperature: ')) decreaseRate = int(input('Decrease Rate: ')) iteration = int(input('Maximum Iteration: ')) state = parseState(dataSplitted, pawnAmountBW) # generate an initial state result = simulatedAnnealing(state, pawnAmountBW, temperature, decreaseRate, iteration) elif (chosenAlgo == 3): populationAmount = int(input('Number Of Population: ')) limit = int(input('Maximum generation: ')) listOfStates = createListOfStates(dataSplitted, pawnAmountBW, populationAmount) result = geneticAlgorithm(listOfStates, pawnAmountBW, populationAmount, limit) # Print the result attackNum = countAtack( result) # Get the number of attack from the result state printBoard(result) print(attackNum['friend'], end='') print(' ', end='') print(attackNum['enemy'])
def sipEnumerator(): conf.verb = 0 client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr'] client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask'] print("\033[33m[!] Client Interface: {0}".format(str( conf.iface))) + "\033[0m" print("\033[33m[!] Client IP: {0} ".format(str(client_ip))) + "\033[0m" print "\033[94m[!] Enumeration process started. \033[0m" user_list = utilities.readFile(options.from_user) user_list = user_list.split("\n") if len(user_list) <= 1: print "\033[1;31;40m Error: From user not found. Please enter a valid From User list.\033[0m" exit(0) content = utilities.readFile("ip_list.txt") content = content.split(";") if len(content[0]) <= 1: print "\033[1;31;40m Error: Target IP not found. Please run SIP-NES first for detect the target IPs.\033[0m" exit(0) content = content[0].split(";") ext_counter = 0 for user_id in user_list: sip = sip_packet.sip_packet("register", content[0].strip(), options.dest_port, client_ip, from_user=user_id.strip(), to_user=user_id.strip(), protocol="socket", wait=True) result = sip.generate_packet() if result["status"]: if result["response"]['code'] == 200: print "\033[1;32m[+] New SIP Extension Found : " + user_id + ",\033[0m \033[1;31mAuthentication not required!\033[0m" ext_counter = ext_counter + 1 if result["response"]['code'] == 401: print "\033[1;32m[+] New SIP Extension Found : " + user_id + ", Authentication required.\033[0m" ext_counter = ext_counter + 1 print "[!] " + str(ext_counter) + " SIP Extension Found."
import utilities kmers = utilities.readFile('stepik\dataset_198_10.txt') def insert(d, k, v): if k not in d: d[k] = [v] else: d[k].append(v) def overlap_graph(kmers): prefixes = {} for kmer in kmers: prefix = kmer[0:-1] insert(prefixes, prefix, kmer) output = '' for kmer in kmers: suffix = kmer[1:] if suffix in prefixes: output += kmer + ' -> ' + ','.join(prefixes[suffix]) + '\n' return output f = open('stepik/output.txt', 'w') f.write(overlap_graph(kmers)) f.close()
import utilities lines = utilities.readFile('stepik/dataset_197_3.txt') k, text = lines #k = 5 #text = 'CAATCCAAC' k = (int)(k) def composition_k(k, text): comps = [] if k > len(text): return comps for i in range(len(text) - k + 1): s = text[i:i + k] comps.append(s) return comps output = "\n".join(composition_k(k, text)) f = open('stepik/output.txt', 'w') f.write(output) f.close()
__author__ = 'SAMARTH' import os import utilities as util filepath = os.path.join(".", "..", "DATA", "facebook.txt") edgeSet = set() edgesTS, number_days, number_nodes, trial_new_node_dict = util.readFile(filepath) #UPDATING edgesTS # OLD call # edgesTS = util.updateEdgesTS(edgesTS, new_nodeDictionary, number_nodes, trial_new_node_ids, trial_new_node_dict) # NEW call edgesTS = util.updateEdgesTS(edgesTS, number_nodes, trial_new_node_dict) ##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ##++++++++++++++++++ NEW CODE STARTS HERE ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #N is the hash table (Dictionary) which stores the neighborhoods of all the nodes. N = {} # d = no. of hops+++++ j and _j are iterators. d = 1 j = 1 _j = 1 for i in range(number_nodes): for t in range(number_days): index = (t * number_nodes) + i #adding the node itself N[index] = [index] #computes neighborhood in a SINGLE time-slice
from utilities import readFile from structures import dominant_phenotype_prob alleles = ["AA-AA", "AA-Aa", "AA-aa", "Aa-Aa", "Aa-aa", "aa-aa"] pairs = list(map(int, readFile("test_data/rosalind_iev.txt")[0].split(' '))) result = 0 for i in range(len(alleles)): allele = alleles[i] #print(allele, dominant_phenotype_prob[allele]) result += dominant_phenotype_prob[allele] * pairs[i] * 2 print(result)
from DNAToolkit import * from utilities import readFile lines = readFile("test_data/rosalind_prot.txt") #print(lines) #RNA = "AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA" RNA = lines[0] DNA = reverse_transcription(RNA) print("".join(translate_seq(DNA))[0:-1])
import utilities, functions k, text = utilities.readFile('stepik\input.txt') def insert(d, k, v): if k not in d: d[k] = [v] else: d[k].append(v) def overlap_graph(kmers): prefixes = {} for kmer in kmers: prefix = kmer[0:-1] insert(prefixes, prefix, kmer) output = '' for kmer in kmers: suffix = kmer[1:] if suffix in prefixes: output += kmer + ' -> ' + ','.join(prefixes[suffix]) + '\n' return output def de_bruijn(k, text): k = int(k) kcomp = functions.composition_k(k, text) graph = {}
def sipEnumerator(): value_errors = [] conf.verb = 0 try: client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr'] except ValueError: value_errors.append( 'Please specify a valid interface name with --if option.') message_type = options.message_type.lower( ) if options.message_type else "subscribe" user_list = [ userName for userName in utilities.readFile(options.from_user).split("\n") if userName.isalnum() ] if len(user_list) <= 1: value_errors.append( "Error: From user not found. Please enter a valid From User list.") if options.target_network: target_networks = [options.target_network] else: content = utilities.readFile("ip_list.txt").split(";") if len(content[0]) <= 1: value_errors.append( "Error: Target IP not found. Please run SIP-NES first for detect the target IPs." ) with open('ip_list.txt', 'r') as f: target_networks = [line.split(';')[0] for line in f.readlines()] utilities.check_value_errors(value_errors) utilities.printInital("Enumeration", conf.iface, client_ip) # combination of all target_networks with user_IDs target_network__user_id = [(target_network, user_id) for target_network, user_id in itertools.product(target_networks, user_list)] global counter global workQueue run_event = threading.Event() thread_join_time = 0.001 print("running with {} threads".format(len(threadList))) for _ in threadList: thread = threading.Thread(target=sipenum_worker, args=(run_event, message_type, options.dest_port, client_ip)) thread.daemon = True threads.append(thread) _prompt_new = "\33[38;5;6m{} user IDs will be checked for {} target networks.\nThere will be {} packages generated. Do you want to continue? (y/n)\33[0m\n" try: continue_flag = raw_input( _prompt_new.format(len(user_list), len(target_networks), len(target_network__user_id))) except EOFError: print("STDIN is unavailable. Accepting answer as yes.") continue_flag = 'y' if continue_flag == 'y': for tn_ui in target_network__user_id: workQueue.put(tn_ui) for thread in threads: thread.start() # invoke the 'run()' function in the class try: while not workQueue.empty(): pass # Wait for queue to empty< except KeyboardInterrupt: print("\nCTRL+C pressed, terminating SIP-ENUM gracefully") run_event.set() run_event.clear() try: for t in threads: t.join(thread_join_time) except KeyboardInterrupt: print( "\nCTRL+C pressed, but Mr. SIP is already trying to terminate SIP-ENUM gracefully. Please be patient." ) for t in threads: t.join(thread_join_time) # call the threads, finish elif continue_flag == 'n': print("\33[38;5;6mTerminating by user input\33[0m") run_event.set() run_event.clear() exit(0) else: print("\33[38;5;6mAnswer not understood. Please answer y/n.\33[0m") run_event.set() run_event.clear() exit(0) print(("[!] " + str(counter) + " SIP Extension Found."))
import utilities kmers = utilities.readFile('stepik/dataset_198_3.txt') def string_reconstruction(kmers): s = list(kmers[0]) for i in range(1, len(kmers)): s.append(kmers[i][-1]) return ''.join(s) print(string_reconstruction(kmers))
) + '","' + target[i].strip() + '","' + action[i].strip() + '"\n' return result if __name__ == '__main__': #argv[1] -> input file, argv[2] -> output file if len(sys.argv) == 3: input_filename = str(sys.argv[1]) output_filename = str(sys.argv[2]) signals = utilities.read_by_line("./2018/analogy_signals.txt") count = 0 sentences = utilities.readFile(input_filename) result = "" #goes to output file for next_sent in sentences: print(next_sent) base, target, action = extract_base_and_target(next_sent, signals) print("BASE: ", base, "TARGET: ", target, "ACTION: ", action) #convert the following lists into strings. next_lines = produce_next_lines(count, base, target, action) result += next_lines count += 1 utilities.writeCSVFile(result, output_filename)
from utilities import readFile from string import split data = readFile('data2.csv') lines = split(data, '\n') # Function that splits the line up into an array of items # separated by tabs def csvParse(line): return split(line, '\t') # Apply the csvParse function to all the elements of the # lines array linesOfTokens = map(csvParse, lines) print(linesOfTokens)
import utilities, functions kmers = utilities.readFile('stepik\dataset_200_8.txt') def de_bruijn_kmers(kmers): graph = {} for kmer in kmers: prefix = kmer[0:-1] suffix = kmer[1:] functions.insert(graph, prefix, suffix) output = '' keys = list(graph.keys()) keys.sort() for key in keys: l = ','.join(graph[key]) output += key + ' -> ' + l + '\n' return output #print(de_bruijn_kmers(kmers)) utilities.writeFile('stepik\output.txt', de_bruijn_kmers(kmers))
""" Created on Thu Aug 23 15:19:29 2018 @author: amrit.patel """ from jira.client import GreenHopper import utilities section_name = 'JIRA_CONNECTION_DETAILS' #########################JIRA Connection################ con_credentials = utilities.readProperties(section_name) JIRA_SERVER = con_credentials.get('JIRA_SERVER') CONSUMER_KEY = con_credentials.get('CONSUMER_KEY') RSA_KEY = utilities.readFile('rsa.pem') def getJiraClient(): jira = GreenHopper(options={'server': JIRA_SERVER}, oauth={ 'access_token': con_credentials.get('ACCESS_TOKEN'), 'access_token_secret': con_credentials.get('ACCESS_TOKEN_SECRET'), 'consumer_key': CONSUMER_KEY, 'key_cert': RSA_KEY }) return jira
from DNAToolkit import gc_content from utilities import readFile import math contents = readFile("test_data/rosalind_prob.txt") seq = contents[0] A = [float(x) for x in contents[1].split(' ')] #print(seq, A) gc = A[0] res = 1 B = [] for gc in A: res = 1 for bp in seq: if bp in "GC": res *= (gc / 2.0) else: res *= ((1 - gc) / 2.0) B.append(round(math.log10(res), 3)) print(" ".join(map(str, B)))
def networkScanner(): value_errors = [] conf.verb = 0 global counter try: client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr'] except ValueError: value_errors.append( 'Please specify a valid interface name with --if option.') message_type = options.message_type.lower( ) if options.message_type else "options" if options.target_network == None: value_errors.append( 'Please specify a valid target network with --tn option.') if 'txt' in options.from_user: from_user = [ userName for userName in utilities.readFile(options.from_user).split("\n") if userName.isalnum() ] else: from_user = [options.from_user] if 'txt' in options.to_user: to_user = [ userName for userName in utilities.readFile(options.to_user).split("\n") if userName.isalnum() ] else: to_user = [options.to_user] if message_type == 'invite' or message_type == 'options': pass # both fromUser and toUser should be accepted. elif message_type == 'register' or message_type == 'subscribe': to_user = [''] # toUser should be omitted if 'txt' in options.from_user or '.txt' in options.to_user: print( "\033[33m\nYou gave a list of user names ('{}', '{}') for SIP-NES. This is yet an experimental feature. (WIP) \033[0m" .format(options.from_user, options.to_user)) print( "\033[33mIf this was not what you wanted, specify user names with '--to' and '--from' arguments \033[0m \n" ) utilities.check_value_errors(value_errors) if "-" in options.target_network: host_range = options.target_network.split("-") host, last = ipaddress.IPv4Address(unicode( host_range[0])), ipaddress.IPv4Address(unicode(host_range[1])) if ipaddress.IPv4Address(host) > ipaddress.IPv4Address(last): value_errors.append( "Error: Second IP address ({}) must bigger than first IP address ({})." .format(ipaddress.IPv4Address(host), ipaddress.IPv4Address(last))) else: target_networks = [ utilities.decimal_to_octets(host) for host in range(int(ipaddress.IPv4Address(host)), int(ipaddress.IPv4Address(last) + 1)) ] target_network__fromUser__toUser = [ (tn, fu, tu) for tn, fu, tu in itertools.product( target_networks, from_user, to_user) ] elif "/" in options.target_network: target_networks = [ host for host in ipaddress.IPv4Network(unicode(options.target_network), strict=False).hosts() ] target_network__fromUser__toUser = [ (tn, fu, tu) for tn, fu, tu in itertools.product( target_networks, from_user, to_user) ] elif len(from_user) > 1 or len(to_user) > 1: print( "\033[33mCalculating all permutations of target network ('{}'), from user name list ('{}') and to user name list ('{}').\033[0m" .format(options.target_network, options.from_user, options.to_user)) print( "\033[33mDepending on the list sizes, this might take a long time.\033[0m \n" ) target_network__fromUser__toUser = [ (tn, fu, tu) for tn, fu, tu in itertools.product( [options.target_network], from_user, to_user) ] utilities.check_value_errors(value_errors) utilities.printInital("Network scan :", conf.iface, client_ip) thread_join_time = 0.01 if '-' in options.target_network or '/' in options.target_network or ( len(from_user) > 1 or len(to_user) > 1): # Create new threads run_event = threading.Event() for _ in threadList: thread = threading.Thread(target=sipnes_worker, args=(run_event, message_type, options.dest_port, client_ip)) thread.daemon = True threads.append(thread) _prompt_new = "\33[38;5;6m{} User names (to and from) will be checked for {} target networks.\nThere will be {} packages generated. Do you want to continue? (y/n)\33[0m\n" try: continue_flag = raw_input( _prompt_new.format( len(from_user) + len(to_user), len(target_networks), len(target_network__fromUser__toUser))) except EOFError: print("STDIN is unavailable. Accepting answer as yes.") continue_flag = 'y' if continue_flag == 'n': print("\33[38;5;6mTerminating by user input\33[0m") run_event.clear() exit(0) elif continue_flag != 'y' and continue_flag != 'n': print("\33[38;5;6mAnswer not understood. Please answer y/n.\33[0m") run_event.clear() exit(0) for tn_fu_tu in target_network__fromUser__toUser: workQueue.put(tn_fu_tu) for thread in threads: thread.start() try: while not workQueue.empty(): pass except KeyboardInterrupt: print("\nCTRL+C pressed, terminating SIP-NES gracefully") run_event.set() run_event.clear() try: for t in threads: t.join(thread_join_time) except KeyboardInterrupt: print( "\nCTRL+C pressed, but Mr. SIP is already trying to terminate SIP-NES gracefully. Please be patient." ) for t in threads: t.join(thread_join_time) # call the threads, finish else: if len(from_user) == 1 and len(to_user) == 1: host = options.target_network sip = sip_packet.sip_packet(message_type, host, options.dest_port, client_ip, from_user=from_user[0], to_user=to_user[0], protocol="socket", wait=True) result = sip.generate_packet() if result["status"]: # and result["response"]['code'] == 200: utilities.printResult(result, host, options.ip_list) counter += 1 print(( "\033[31m[!] Network scan process finished and {0} live IP address(s) found.\033[0m" .format(str(counter))))
def sipEnumerator(): conf.verb = 0 client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr'] client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask'] printInital("Enumeration", conf.iface, client_ip) dos_method = options.dos_method if options.dos_method else "subscribe" user_list = utilities.readFile(options.from_user).split("\n") if len(user_list) <= 1: print( "\033[1;31;40m Error: From user not found. Please enter a valid From User list.\033[0m" ) exit(0) # TODO: input validation for --tn ... if options.target_network: target_networks = [options.target_network] else: content = utilities.readFile("ip_list.txt").split(";") if len(content[0]) <= 1: print( "\033[1;31;40m Error: Target IP not found. Please run SIP-NES first for detect the target IPs.\033[0m" ) exit(0) with open('ip_list.txt', 'r') as f: target_networks = [line.split(';')[0] for line in f.readlines()] # combination of all target_networks with user_IDs target_network__user_id = [(target_network, user_id) for target_network, user_id in itertools.product(target_networks, user_list)] global counter global timeToExit global workQueue # global prog_bar_counter # global len_total counter = 0 # extension counter # prog_bar_counter = 0 # len_total = len(target_network__user_id) print("running with {} threads".format(len(threadList))) threadID = 0 for threadName in threadList: thread = ThreadSIPENUM(threadID, threadName, dos_method, options.dest_port, client_ip) thread.start() # invoke the 'run()' function in the class threads.append(thread) threadID += 1 _prompt_new = "{} user IDs will be checked for {} target networks.\nThere will be {} packages generated. Do you want to continue? (y/n) \n" isContinue = raw_input( _prompt_new.format(len(user_list), len(target_networks), len(target_network__user_id))) if isContinue == 'y': for tn_ui in target_network__user_id: workQueue.put(tn_ui) while not workQueue.empty(): pass # Wait for queue to empty elif isContinue == 'n': timeToExit = 1 print("Terminating by user input") for t in threads: t.join() # Wait for all threads to complete exit(0) else: timeToExit = 1 for t in threads: t.join() print("Answer not understood. Please answer y/n.") exit(0) timeToExit = 1 for t in threads: t.join() print("[!] " + str(counter) + " SIP Extension Found.")
import urllib.request import re from utilities import readFile FASTA_dict = {} protein_id_list = readFile("test_data/rosalind_mprt.txt") #protein_id_list = ["P07204_TRBM_HUMAN"] for protein in protein_id_list: url = "https://www.uniprot.org/uniprot/" + protein + ".fasta" FASTA_page = urllib.request.urlopen(url) FASTA_str = FASTA_page.read().decode("utf-8") FASTA_list = FASTA_str.split("\n") for line in FASTA_list: if '>' in line: #print("LABEL: ", line) #FASTALabel = line[1:].rstrip() FASTA_dict[protein] = "" else: #print("ELSE: ", line) FASTA_dict[protein] += line.rstrip() FASTA_keys = sorted(list(FASTA_dict.keys())) #print(FASTA_keys) for key in FASTA_keys: #result = re.findall("N[^P][ST][^P]", seq). seq = FASTA_dict[key] p = re.compile("(?=(N[^P][ST][^P]))")
__author__ = 'SAMARTH' import os import utilities as util filepath = os.path.join(".", "..", "DATA", "facebook.txt") edgeSet = set() edgesTS, number_days, number_nodes, trial_new_node_dict = util.readFile( filepath) #UPDATING edgesTS # OLD call # edgesTS = util.updateEdgesTS(edgesTS, new_nodeDictionary, number_nodes, trial_new_node_ids, trial_new_node_dict) # NEW call edgesTS = util.updateEdgesTS(edgesTS, number_nodes, trial_new_node_dict) ##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ##++++++++++++++++++ NEW CODE STARTS HERE ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #N is the hash table (Dictionary) which stores the neighborhoods of all the nodes. N = {} # d = no. of hops+++++ j and _j are iterators. d = 1 j = 1 _j = 1 for i in range(number_nodes): for t in range(number_days): index = (t * number_nodes) + i #adding the node itself N[index] = [index]