Esempio n. 1
0
	def get_analysis_id(self,options):
		selections=""; where_clause=""
		if options["INSTRUMENT"]:
			firstpart, secondpart = add_parameters.selections_conditions("INSTRUMENT", options["INSTRUMENT"], selections); selections="," + firstpart; where_clause+=" and " +secondpart
		if options["PAIR"]:
			firstpart, secondpart = add_parameters.selections_conditions("PAIR", options["PAIR"], selections); selections="," + firstpart; where_clause+=" and " +secondpart
		if options["LANE"]:
			firstpart, secondpart = add_parameters.selections_conditions("LANE", options["LANE"], selections); selections="," + firstpart; where_clause+=" and " +secondpart
		if options["BARCODE"]:
			if os.path.exists(options["BARCODE"]):
				list_of_barcodes=read_file.read_file(options["BARCODE"])
			else:
				list_of_barcodes=options["BARCODE"]
			firstpart, secondpart = add_parameters.selections_conditions("BARCODE", list_of_barcodes, selections); selections="," + firstpart; where_clause+=" and " +secondpart
		if options["SAMPLE_NAME"]:
			if os.path.exists(options["SAMPLE_NAME"]):
				list_of_samplenames=read_file.read_file(options["SAMPLE_NAME"])
			else:
				list_of_samplenames=options["SAMPLE_NAME"]
			firstpart, secondpart = add_parameters.selections_conditions("SAMPLE_NAME", list_of_samplenames, selections); selections="," + firstpart; where_clause+=" and " +secondpart
		statement =  "SELECT analysis_id FROM run WHERE " + where_clause[5:]

		
		statement = statement + " GROUP BY analysis_id"
		return self.execute_and_return(statement)
 def test_output_1(self):
     out_file = 'D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB5\\out\\out1'
     array = read_file('D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB5\\data\\data1')[1]
     word_num = read_file('D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB5\\data\\data1')[0]
     paths = {}
     self.assertEqual(find_max(array, paths, out_file, word_num), 6, 'An error occurred while processing your '
                                                                      'request')
Esempio n. 3
0
 def test_output_1(self):
     graph = read_file(
         "D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB3\\resources\\data1"
     )[0]
     vertex_num = read_file(
         "D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB3\\resources\\data1"
     )[1]
     self.assertEqual(check_cycle(graph, vertex_num, 0), [0, 5, 10],
                      'An error occurred while processing your '
                      'request')
Esempio n. 4
0
 def test_output_3(self):
     graph = read_file(
         "D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB3\\resources\\data3"
     )[0]
     vertex_num = read_file(
         "D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB3\\resources\\data3"
     )[1]
     self.assertEqual(check_cycle(graph, vertex_num, 20),
                      [20, 127, 131, 154, 46, 70, 73, 163, 125, 98],
                      'An error occurred while processing your '
                      'request')
Esempio n. 5
0
def main(argv):
    C = read_file.read_file(argv[0])
    C.pop(0)
    C = sp.array(C,float)
    density,natoms,molmass = read_file.read_file(argv[1])[0]
    density = float(density)  # kg/m**3
    natoms = int(natoms)
    molmass = float(molmass)  # kg/mol
    integral = spherical_integral(C,density)  # (s/m)**3
    mean_vel = (integral/12./sp.pi)**(-1/3.)
    debeye_temp = PLANCKCONST/BOLTZCONST*(3.*natoms*AVONUM*
                      density/4./sp.pi/molmass)**(1/3.)*mean_vel
    print debeye_temp,mean_vel
Esempio n. 6
0
def main(argv):
    C = read_file.read_file(argv[0])
    C.pop(0)
    C = sp.array(C, float)
    density, natoms, molmass = read_file.read_file(argv[1])[0]
    density = float(density)  # kg/m**3
    natoms = int(natoms)
    molmass = float(molmass)  # kg/mol
    integral = spherical_integral(C, density)  # (s/m)**3
    mean_vel = (integral / 12. / sp.pi)**(-1 / 3.)
    debeye_temp = PLANCKCONST / BOLTZCONST * (3. * natoms * AVONUM * density /
                                              4. / sp.pi /
                                              molmass)**(1 / 3.) * mean_vel
    print debeye_temp, mean_vel
Esempio n. 7
0
def render_page():

    my_list = read_file('tintern_abbey.txt')
    chain = MarkovChain(my_list)
    num_words = int(10) - 1
    my_sentence = chain.walk(num_words)

    my_list2 = read_file("the_rime.txt")
    chain2 = MarkovChain(my_list2)
    num_words2 = int(10) - 1
    my_sentence2 = chain2.walk(num_words2)

    return render_template('index.html',
                           sentence=my_sentence,
                           sentence2=my_sentence2)
Esempio n. 8
0
def requests_file():
    r = read_file()
    urls_list = r.read_urls_from_file()
    i = 1
    for url in urls_list:
        r = requests.get(url,
                         allow_redirects=True,
                         stream=True,
                         headers={'User-agent': 'Mozilla/5.0'})

        filename = str(r.headers['Content-Disposition'][22:-1])

        if r.status_code == 200:
            print('downloading ', filename, '...')

            with open(filename, "wb") as f:
                dl = 0
                total_length = int(r.headers.get('content-length'))
                for data in r.iter_content(chunk_size=4096):
                    dl += len(data)
                    f.write(data)
                    done = int(100 * dl / total_length)
                    sys.stdout.write("\r[%s%s] %.2f/%.2f MB" %
                                     ('=' * done, ' ' * (100 - done), dl /
                                      (1024 * 1024), total_length /
                                      (1024 * 1024)))
                    sys.stdout.flush()

            print('\nfile', filename, 'saved successfully!')

            print('waiting for 1 second....')
            time.sleep(10)
            i = i + 1
def change_password(ls):

    old_password = ls[2]

    flag = verify_old_password(old_password)

    if flag == '0':
        new_password = input("\nEnter the new password: "******"Out of range of try ... press Enter")
Esempio n. 10
0
 def test_minhash_with_testdata(self):
     sets = read_file('testdata.csv')
     similarity = similarity_matrix(sets, minhash_similarity)
     self.assertEqual(recommendations(1, sets, similarity, 0.75), {42})
     self.assertFalse(recommendations(3, sets, similarity, 0.75))
     self.assertEqual(recommendations(1, sets, similarity, 0.15),
                      (sets[2] | sets[3]) - sets[1])
Esempio n. 11
0
    def get_post_by_date(self):
        content = self.text.get("1.0", tk.END)
        dateFormat = re.compile(r"\d\d\d\d.\d\d.\d\d")
        try:
            result = dateFormat.search(content).group()
        except:
            result = "xxxx.xx.xx"
        #print("date in text box:", result)

        diaryContent = "".join(read_file(self.name, False))
        try:
            datesIn = dateFormat.findall(diaryContent)
        except:
            datesIn = []
        datesIn = list(set(datesIn))    #remove duplicates
        datesIn.sort()
        startPoint = len(diaryContent)
        stopPoint = len(diaryContent)
        #print("result:", result)
        if result in datesIn:
            startPoint = diaryContent.find(result)
            if not datesIn[-1] == result:
                nextDate = datesIn[datesIn.index(result)+1]    #if no duplicates and sorted it should be greater than result
                stopPoint = diaryContent.find(nextDate)   #-6 if colored
            chosenDay = diaryContent[startPoint:stopPoint]    #-6 if colored
            #print(chosenDay)
            self.text.delete("1.0", tk.END)
            self.text.insert("1.0", chosenDay)
        else:
            #print("No such date. These are availabe:\n", ", ".join(datesIn))
            textData = "Available dates:\n" + ", ".join(datesIn) + "\n"
            self.text.delete("1.0", tk.END)
            self.text.insert("1.0", textData)
Esempio n. 12
0
def shan_chu():
    '''
	删除学生条目
	'''
    l = Rf.read_file()
    #	print(l)
    sc = input('输入需要删除的学生的姓名:')

    for i in l:
        if i['姓名'] == sc:
            print('您要删除的是:', i['姓名'], '请确认(y/n)')
            qr = input()
            if qr == 'y':
                shan_chu = l.pop(l.index(i))
                print('删除了:', shan_chu)
                #				from imp import reload
                #				reload(get_path)
                Wf.write_file(l, 'w')
                return
            else:
                print('已放弃操作')
                ts.tishi('即将返回目录', 4)
                return
    print('没有此人')
    ts.tishi('返回目录', 5)
Esempio n. 13
0
 def test_recommendations_with_zero_cutoff_returns_all_other_products(self):
     sets = read_file('testdata.csv')
     similarity = similarity_matrix(sets)
     for i in sets.keys():
         self.assertEqual(
             recommendations(i, sets, similarity, 0),
             reduce(lambda a, b: a | b, sets.values(), set()) - sets[i])
Esempio n. 14
0
def field_to_str():
    '''(list) -> (str)
    Converts list into str and writes it in a file
    0 is for ' ' 1 is for  '*' 2 s for 'X'
    '''
    board = read_file.read_file('field.txt')
    board_str1 = ""
    board_str = []
    for i in board:
        if 0 in i:
            board_str1 += " "
        elif 1 in i:
            board_str1 += "*"
        elif 2 in i:
            board_str1 += "X"
    for i in range(0, 91, 10):
        board_str.append(board_str1[i:i + 10])
    print('Do you want to see a field here', end='')
    print(' or you want to write it in a file field1.txt?')
    control = int(input('Print 1 to see a field or 2 to write in a file '))
    if control == 1:
        for i in board_str:
            print(i)
    elif control == 2:
        with open('field1.txt', 'w') as file:
            for i in board_str:
                file.write(i + '\n')
    else:
        print('You are cheating!')
Esempio n. 15
0
def withdraw(ls):

    current_balance = int(ls[3])

    print('Your current balance: ' + ls[3])

    withdraw_amount = int(input('Enter withdraw amount: '))

    if withdraw_amount > current_balance:
        print("ERROR: You can't withdraw more than your current balance")
    else:
        current_balance -= abs(withdraw_amount)

    file_name = ls[0] + '.txt'
    process_list = read_file.read_file(file_name)
    id_file = open(file_name, 'a')

    if len(process_list) == 0:

        last_id = 1
    else:
        last_id = int(process_list[len(process_list) - 1][0]) + 1

    id_file.write('{0}\twithdraw\t\t\t{1}\t{2}\t{3}\n'.format(
        str(last_id), str(time.ctime()), ls[3], str(current_balance)))

    id_file.close()
    ls[3] = str(current_balance)
    print('Your current balance: ' + ls[3])

    return ls
Esempio n. 16
0
def jia_zai():

    jia_zai_f = tkinter.filedialog.askopenfilename(title='选择加载的文件',
                                                   filetypes=[('TXT格式', '.txt')
                                                              ])
    if jia_zai_f == ():
        print('已取消')
    else:
        fn = os.path.basename(jia_zai_f)  #截取文件名
        r_path = os.path.dirname(jia_zai_f)  #截取文件所在文件夹名称
        local_path = os.getcwd()  #获取本地文件夹
        f_local = fn + local_path

        print(jia_zai_f)
        Tisi.tishi('读入中', 1)
        sfp.safe_file_path(fn, r_path)

        from imp import reload
        reload(read_file)
        ld = read_file.read_file(jia_zai_f)
        if ld is None:
            return
        else:
            print('数据文件切换成功!即将退出系统,请重新进入系统查看和删改!')
            Tisi.tishi('正在关闭系统...', 2)
            sys.exit()
def change_password(ls):
    # Get the old password
    old_password = ls[2]

    # Ask to old password to enter new one
    flag = gate_x(old_password)
    # Security flag get the output flag
    if flag == '0':
        new_password = input("\nEnter the new password: "******"Out of range of try ... press Enter")
Esempio n. 18
0
def get_bands():
    control_raw, patient_raw, channel_names = read_file.read_file()
    control_res = []
    count = 0
    for (eid, raw) in control_raw.items():
        temp = handle_raw(raw)
        if temp is None:
            print('too large')
            continue
        control_res.append(temp)
        print('control: ' + str(count))
        count += 1

    patient_res = []
    count = 0
    for (eid, raw) in patient_raw.items():
        temp = handle_raw(raw)
        if temp is None:
            print('too large')
            continue
        patient_res.append(temp)
        print('patient: ' + str(count))
        count += 1

    return control_res, patient_res
def deposit(ls):

    current_balance = int(ls[3])

    print('Your current balance: ' + ls[3])
    deposit_amount = int(input('Enter the amount to deposit: '))

    current_balance += abs(deposit_amount)

    file_name = ls[0] + '.txt'
    process_list = read_file.read_file(file_name)
    id_file = open(file_name, 'ab')

    if len(process_list) == 0:
        last_id = 1
    else:
        last_id = int(process_list[len(process_list) - 1][0]) + 1

    id_file.write(('{0}\tdeposit\t\t\t\t{1}\t{2}\t{3}\n'.format(str(last_id), str(time.ctime()), ls[3], str(current_balance))).encode('utf-8'))

    id_file.close()
    ls[3] = str(current_balance)
    print('Your current balance: ' + ls[3])

    return ls
Esempio n. 20
0
def deposit(ls):
    # ls is a list of the information of the account
    # ls elements are of type string
    # ls[0] id
    # ls[1] name
    # ls[2] password
    # ls[3] balance
    current_balance = int(
        ls[3])  # make changes to another variable to keep the previous balance
    # to print it later, then save ls[3] = current_balance
    print('Your current balance: ' + ls[3])
    deposit_amount = int(input('Enter deposit amount: '))

    current_balance += abs(deposit_amount)  # to guarantee the entered value

    file_name = ls[0] + '.txt'
    process_list = read_file.read_file(file_name)
    id_file = open(file_name, 'a')

    if len(process_list) == 0:  # if there are no processes in the file
        last_id = 1
    else:
        last_id = int(process_list[len(process_list) -
                                   1][0]) + 1  # get last id and increment it

    id_file.write('{0}\tdeposit\t\t\t\t{1}\t{2}\t{3}\n'.format(
        str(last_id), str(time.ctime()), ls[3], str(current_balance)))
    # write->   process_id    process_name    process_date_and_time    before_process    after_process
    id_file.close()
    ls[3] = str(current_balance)
    print('Your current balance: ' + ls[3])

    return ls
 def test_output_2(self):
     order_list = []
     graph = read_file("D:\\Projects\\Data-Structures-and-Algorithms-Uni\\LAB4\\resources\\data2")
     visited = {k: False for k in graph}
     self.assertEqual(dfs("visa", graph, visited, order_list), ['foreignpassport', 'visa'],
                      'An error occurred while processing your '
                      'request')
Esempio n. 22
0
def main():
    positions_file = "Positions - Performance.txt"
    image_filepath = "C:\\Users\\Joshua\\Documents\\Development\\FIFAStats\\Pictures - Performance\\Mason.jpg"

    image = Image.open(image_filepath)
    scores = read_file(positions_file)

    indi_image(image, scores)
Esempio n. 23
0
 def test_asymmetric_similarity_returns_superset_of_jaccard(self):
     sets = read_file('testdata.csv')
     similarity1 = similarity_matrix(sets)
     similarity2 = similarity_matrix(sets, asymmetric_similarity)
     for i in sets.keys():
         self.assertTrue(
             recommendations(i, sets, similarity1, 0.25).issubset(
                 recommendations(i, sets, similarity2, 0.25)))
Esempio n. 24
0
    def __init__(self, word_list):
        self.histogram = {}
        self.text = read_file("tintern_abbey.txt")
        self.word_list = word_list

        self.dictionary_histogram = self.build_dictogram()

        self.tokens = sum(self.dictionary_histogram.values())
        self.types = self.unique_words()
Esempio n. 25
0
    def load(self):
        """
        Load data from mongodb.

        INPUT: None.
        OUTPUT: None.
        """
        #self.df = read_file("../data/yelp_academic_dataset_user.json")  #Full Data.
        self.df = read_file("../data/user300.json")  #For local machine.
def main():
    """
	主函数

	"""
    info = read_file.read_file("mission.txt")
    currency = translate_to_roman_numerals.translate_to_roman_numerals(info)
    get_price = price.cal_unit_price(info, currency)
    answers.get_answers(info, currency, get_price)
def main():
	"""
	主函数

	"""
	info = read_file.read_file("mission.txt")
	currency = translate_to_roman_numerals.translate_to_roman_numerals(info)
	get_price = price.cal_unit_price(info, currency)
	answers.get_answers(info,currency,get_price)
Esempio n. 28
0
def map(fi_name):
    matrix = read_file(fi_name)
    print('start mapping...')
    print('...')
    map_matrix = {}
    for e in matrix:
        map_matrix[e] = exp_map(matrix[e])
    print('mapping finished.')
    return map_matrix
Esempio n. 29
0
    def train(self, training_data_file):

        self.train_file_str = read_file(training_data_file)
        self.train_pfs = preprocess_line(self.train_file_str)
        self.train_counts = count_ngrams(3, self.train_pfs)

        self.train_discounts = gt_discount(self.train_counts)
        self.train_probs = estimate_probs(self.train_discounts)

        write_file(self.train_probs)
Esempio n. 30
0
def generate_sentence():
    my_file = read_file("tintern_abbey.txt")
    my_histogram = histogram(my_file.split("\n"))

    sentence = ""
    num_words = 10
    for i in range(num_words):
        word = random_word(my_histogram)
        sentence += " " + word
    return sentence
Esempio n. 31
0
def calculate_library_weight_main():
    final_list = []
    meta_data = read_file("input/d_tough_choices.txt")
    scanned_books = {}
    libraries = meta_data[4]
    num_days = meta_data[2]
    while libraries and num_days:
        libraries, num_days, final_list = calculate_scores(libraries, num_days, final_list)
        
    return final_list
Esempio n. 32
0
def main():
	content = read_file()
	bn = BayesNet(content)
	# for node in bn.nodes:
	# 	print(node)
	# X = 'G'
	# e = {'O': True, 'A': True, 'X':True, 'N': True, 'H':True}
 #    # print(markov_blanket_sample(X, e, bn))
	# print(gibbs_ask(X, e, bn, 100))
	print(bn.markov_blanket('A'))
def read_table(current_path):
    # Input File

    input_file_path = os.path.join(current_path, "TableA.txt")
    print(input_file_path)

    # Read File

    name, f = read_file(input_file_path)
    return name, f
Esempio n. 34
0
    def get_analysis_id(self, options):
        selections = ""
        where_clause = ""
        if options["INSTRUMENT"]:
            firstpart, secondpart = add_parameters.selections_conditions(
                "INSTRUMENT", options["INSTRUMENT"], selections)
            selections = "," + firstpart
            where_clause += " and " + secondpart
        if options["PAIR"]:
            firstpart, secondpart = add_parameters.selections_conditions(
                "PAIR", options["PAIR"], selections)
            selections = "," + firstpart
            where_clause += " and " + secondpart
        if options["LANE"]:
            firstpart, secondpart = add_parameters.selections_conditions(
                "LANE", options["LANE"], selections)
            selections = "," + firstpart
            where_clause += " and " + secondpart
        if options["BARCODE"]:
            if os.path.exists(options["BARCODE"]):
                list_of_barcodes = read_file.read_file(options["BARCODE"])
            else:
                list_of_barcodes = options["BARCODE"]
            firstpart, secondpart = add_parameters.selections_conditions(
                "BARCODE", list_of_barcodes, selections)
            selections = "," + firstpart
            where_clause += " and " + secondpart
        if options["SAMPLE_NAME"]:
            if os.path.exists(options["SAMPLE_NAME"]):
                list_of_samplenames = read_file.read_file(
                    options["SAMPLE_NAME"])
            else:
                list_of_samplenames = options["SAMPLE_NAME"]
            firstpart, secondpart = add_parameters.selections_conditions(
                "SAMPLE_NAME", list_of_samplenames, selections)
            selections = "," + firstpart
            where_clause += " and " + secondpart
        statement = "SELECT analysis_id FROM run WHERE " + where_clause[5:]

        statement = statement + " GROUP BY analysis_id"
        return self.execute_and_return(statement)
Esempio n. 35
0
    def train(self, training_data_file):

        self.train_file_str = read_file(training_data_file)
        self.train_pfs = preprocess_line(self.train_file_str)
        self.train_counts = count_trigrams(3, self.train_pfs)

        ans = raw_input("Smooth the counts? [y/n]")
        if ans.lower() == 'y':
            self.train_discounts = gt_discount(self.train_counts)
            self.train_probs = estimate_probs(self.train_discounts)
        else:
            self.train_probs = estimate_probs(self.train_counts)

        write_file(self.train_probs)
Esempio n. 36
0
def glitch_1(input_path, output_path="test_folder"):
    files = read_file(output_path, input_path, True)
    f = files[0]
    new_f = files[1]

    count = 0
    for line in f:
        temp = line

        if count > 20 and count % 20 == 0 and random.randint(1, 10) > 9:
            if random.randint(1, 10) < 8:
                temp += temp
            else:
                temp = temp[random.randint(0, len(temp)):random.randint(0, len(temp))]

        new_f.write(temp)
        count += 1
Esempio n. 37
0
def process_des(filename, key, encryption):
	input_blocks = read_file(filename, encryption)
	
	# Return error if file is empty
	if not input_blocks:
		return 'file_empty_error'

	if input_blocks == 'not_encrypted_file':
		return 'not_encrypted_file'

	keys = keygen(key)

	if encryption:
		# Convert each block to binary if operation is encryption.
		input_blocks = [string_to_bin(x) for x in input_blocks]

		# Pad zeroes to the end, if last block has less than 64 bits.
		if len(input_blocks[-1]) < 64:
			input_blocks[-1] += '0' * (64 - len(input_blocks[-1]))

	if not encryption:
		# Reverse the key schedule if operation is decryption.
		keys = list(reversed(keys))

	encoded_text = ''
	for block in input_blocks:
		encoded_text += fiestel(block, keys)

	if encryption:
		# Return cipher text as binary.
		return encoded_text
	else:
		# Remove padded zeroes if any.
		for i in range(64, 0, -8):
			if encoded_text[-8:] == '0' * 8:
				encoded_text = encoded_text[:-8]
			else:
				break

		# Convert binary to normal string.
		return bin_to_string(encoded_text)
Esempio n. 38
0
		for each in check_list:
			args.append(options[each])
		reports = Reports.Reports(config);tables=reports.get_samples_from_run_lane_barcode(args); display_outputs(tables)
	else:
		print "You have not supplied one of the option parameter. Make sure you supplied parameters for all of these : ", ",".join(check_list)
		exit(1)
	
elif options["get_analysis_id"]:
	check_list=["INSTRUMENT", "RUN", "LANE", "PAIR", "SAMPLE_NAME", "BARCODE"]	#supply at least one or all of these options
	reports = Reports.Reports(config);tables=reports.get_analysis_id(options); display_outputs(tables)
	
	
elif options["get_properties_for_analysis_ids"]:
	if options["ids"]:
		if os.path.exists(options["ids"]):
			list_of_ids=read_file.read_file(options["ids"])
		else:
			list_of_ids=options["ids"]
		reports = Reports.Reports(config);tables=reports.get_properties_for_analysis_ids(list_of_ids); display_outputs(tables); reports.disconnect()
	else:
		print "Please provide a list of analysis ids which you wish to get the properties"
		exit(1)

elif options["get_barcodes_for_sample_name"]:
	if options["SAMPLE_NAME"]:
		if os.path.exists(options["SAMPLE_NAME"]):
			#read the file
			list_of_samplenames=read_file.read_file(options["SAMPLE_NAME"])
			selections, where_clause=add_parameters.selections_conditions("sample_name", list_of_samplenames, "")
		else:
			selections, where_clause=add_parameters.selections_conditions("sample_name", options["SAMPLE_NAME"], "")
Esempio n. 39
0
    def test(self, test_data_file):

        self.test_file_str = read_file(test_data_file)
        self.test_pfs = preprocess_line(self.test_file_str)
        self.test_counts = count_trigrams(3, self.test_pfs)
        self.perplexity = calc_perplexity(self.test_counts, self.train_probs)
Esempio n. 40
0
	parser.add_argument("--softening",type=int,default=0,
						help="softening constant")
	# parser.add_argument("-o","--outfile",type=argparse.FileType('w'),
						# help="save results to file, '-' is stdout")
	parser.add_argument("--energy",action="store_const",const=Energy(),
						help="calculate and plot the energy of the system")
	parser.add_argument("--period",type=int,metavar="i",nargs="?",const=1,
						help="calculate and output the orbtal period of body i")
	parser.add_argument("--maxpoints",type=int,
						help="maximum plotted line length in data points")
	parser.add_argument("file",nargs="+",
						help="files containing the mass,"
						" initial position and velocity of the bodies")
	args = parser.parse_args()

	m,x,v,names,styles = read_file(args.file)
	# change the position and velocity of the Sun so that
	# the centre of mass is stationary and at the origin
	x[0] = -numpy.sum(x[1:]*m[1:,numpy.newaxis],axis=0)/m[0]
	v[0] = -numpy.sum(v[1:]*m[1:,numpy.newaxis],axis=0)/m[0]
	solar_system = N_bodies(m,x,v,args.dt,args.softening)
	v = solar_system.v_correction()

	dt = args.dt
	t = args.time
	
	pr = None
	# pr = printer() # for solar velocity print out

	if args.graph:
		plot = Plotter(dict(zip(names,styles)),axis=[-9e11,9e11,-9e11,9e11],position=111)
def translate_to_roman_numerals(info):
	"""
		转义为罗马数字模块

		提取输入信息中对星际货币与罗马数字的转换信息


	"""
	translate_to_roman=[[],[],[],[],[],[],[]]
	currency={}


	for key,value in info.items():
		if(key=='condition_roman'):
			for index,number in enumerate(value):
				translate_to_roman[index]=number.split()


	for i in translate_to_roman:
		if i:
			currency[i[0]]=i[2]
	return currency





if __name__ == "__main__":

	info = read_file.read_file()
	translate_to_roman_numerals(info)
Esempio n. 42
0
def test_read_file():
    """Assert the correct return value from the function read_file()."""
    assert read_file('test_read_file.txt') == """ABCDEFGHIJKLMNOPQRSTUVWXYZ?
from Problem import Problem
from solver_vertical_motion import Solver
from read_file import read_file
from scitools.std import plot
from numpy import linspace, array, zeros
import sys

v0 = 0
T = 100
dt = 0.01
N = int(T/float(dt))

parameters = read_file(sys.argv[1:])
problem = Problem(parameters)
problem.set_initial_condition(v0);

c = Solver(problem)
c.set_timestep(dt)
v = c.solve(T)

v = array(v)
F_d = zeros(N)
for i in range(N):
        F_d[i] = problem.get_drag_force(v[i])

F_g = zeros(N) + problem.get_gravity_force()
F_b = zeros(N) + problem.get_buoyancy_force()

time = linspace(0,dt*N,N);

plot(time,F_d,time,F_g,time,F_b, legend=['drag','gravity','buoyancy'])
Esempio n. 44
0
    """
    S_vib = 4*debye_func(thetaD/T)-3*sp.log(1-sp.exp(-thetaD/T))
    S_vib = natoms*BOLTZCONST*S_vib
    return S_vib

def debye_C_V(T,thetaD,natoms):
    """
    Returns the heat capacity at constant volume, C_V, of the Debeye model at a
    given temperature, T, in meV/atom/K.
    """
    C_V = 4*debye_func(thetaD/T)-3*(thetaD/T)/(sp.exp(thetaD/T)-1.)
    C_V = 3*natoms*BOLTZCONST*C_V
    return C_V

if __name__ == "__main__":
    thetaD,natoms = read_file.read_file(sys.argv[1])[0]
    thetaD = float(thetaD)
    natoms = int(natoms)
    temp = sp.linspace(0,2000,201)
    temp[0] = 1.0
    #reduced_temp = thetaD/temp
    E_zp = 9*natoms*BOLTZCONST*thetaD/8.
    #E_zp = 9*BOLTZCONST*thetaD/8.
    E_vib = sp.array([])
    S_vib = sp.array([])
    C_V = sp.array([])
    for T in temp:
        D = debye_func(thetaD/T)
        E_vib = sp.append(E_vib,natoms*BOLTZCONST*(E_zp + 3*T*D))
        #E_vib = sp.append(E_vib,BOLTZCONST*(E_zp + 3*T*D))
        S_vib = sp.append(S_vib,natoms*BOLTZCONST*(4*D - 
Esempio n. 45
0
#!/usr/bin/env python
import read_file
import parse_prop
import get_snpcount
import add_seq
import append
import integrate
import add_to_db
import run_struct
import get_sites

file = integrate.integrate()
df = read_file.read_file(file)
new_df = parse_prop.parse_prop(df)
#kage = get_snpcount.enough_info(file)
str = append.append(new_df)
sites, indices = get_sites.get_sites(new_df)
#add_to_db.add_to_base(kage,df)
run_struct.call_structure(sites, indices)