def generate(pw_lenght, randomLenght, source): # print ("reading...") source = source.split(".")[0] dict_path = os.path.join(os.path.abspath(".") + r"/dict/") words = words_import(dict_path) if os.path.isfile(dict_path + source + ".pickle"): counts = text_import(dict_path, source) else: calc.calculate(source + ".txt") counts = defaultdict(dd) counts = text_import(dict_path, source) # print(counts) # print(type(counts)) # print("counts") # print(counts) # print ("generating...") for i in range(50000): madeup_word = makeup(counts, n).lower() # break if (madeup_word not in words.lower() and madeup_word.isalpha()): if bool(randomLenght): return madeup_word elif (not bool(randomLenght) and len(madeup_word) == pw_lenght): return madeup_word # print(" " + str(i + 1) + "-crap: " + madeup_word) print("Sorry this one took to long") return ("Sorry this one took to long")
def calculate(self): if ('before' in self.image_paths and 'after' in self.image_paths): current_method = str(self.choose_method.currentText()) calc.calculate(self.image_paths['before'], self.image_paths['after'], current_method) else: error_dialog = self.create_error_dialog( 'Необходимо добавить оба изображения!') error_dialog.exec_()
def main_loop(): try: while True: request = raw_input("This program can calculate basic binary operations(*/+-) as well as factorial\nExmaples:\n-1+1\n1--2\n5!\nCtrl+D or Ctrl+C to quit\n") print calc.calculate(request) except KeyboardInterrupt: print "Bye!" except EOFError: print "See you!"
def check_answer(x, y, op, result, user_choice): if calculate(x, y, op) == result: if user_choice == True: return True elif user_choice == False: return False elif calculate(x, y, op) != result: if user_choice == True: return False elif user_choice == False: return True
def repeat(): new_cal = input( ''' Do you want to perform another calculation?\n Please enter Y for YES and N for NO: ''' ) if new_cal.upper() == 'Y': from calc import calculate calculate() elif new_cal.upper() == 'N': print('Thanks and see u later ') else: repeat()
def main(): _content = sys.stdin.read().strip() # do necessary data parsing here? content = list(map(int, _content.strip().split("\n"))) result = calc.calculate(content) print(result)
def generate_quiz(): # Hint: Return [x, y, op, result] dif = randint(-1, 1) x = randint(0,9) y = randint(0,9) op = choice(["+","-","*","/"]) result = calculate(x, y, op) + dif return [x, y, op, result]
def parse(self, msg): """ example: "one plus two minus three" """ text = msg.utterance.decode('utf-8').lower() try: self.ans = calculate(text) return True except: return False
def test_large() : large = [x for x in range(0,15001)] start = time() slow = calculate(large) end = time() elapsed = end - start print 'slow took: ',elapsed start = time() fast = f_calc(large) end = time() elapsed = end - start print 'fast took: ',elapsed assert slow == fast
def generate_scratch(): #af = calc.load_index(os.path.join(INDEX_PATH, "pitts_file_index.mat")) #""" af = load("raw/Pitts250/groundtruth") # remove 12 rows every other 12 rows (removing pitch2) alt = np.empty(af.shape[0] / 12) alt[::2] = 0 alt[1::2] = 1 row12 = np.repeat(alt, 12, axis=0) * (np.array(range(af.shape[0])) + 1) af = np.delete(af, np.nonzero(row12), axis=0) # Filter dark_thres, std_thres = constants.FILTERING_STREETVIEW_PARAMETERS["pitts"] af = calc.filter_darks(af, "raw/Pitts250/data", dark_thres, std_thres) calc.save_index(af, os.path.join(INDEX_PATH, "pitts_file_index.mat")) index, ind, dist, nz = calc.calculate(af[:, 1:3].astype(float)) return index, ind, dist, nz, af[:, 0]
def calculate(self, tableWidget): loadLFI = self.combo.currentText() == "Load LFI" # launch calculation [pipe_distance, Vp_final, diagnostics ] = calc.calculate(loadLFI, mutual_impedance_formula=self. mutual_impedance_selection.currentIndex()) # clear diagnostics log and refresh with matrices from latest calculation self.main_window.diagnostics_clear() for (title, data) in diagnostics: self.main_window.diagnostics_matrix(title=title, data=data) # Populate table of results in calc if loadLFI: data = np.transpose(np.array([pipe_distance, Vp_final])) else: # Convert kV to V for fault LFI cases data = np.transpose(np.array([pipe_distance, Vp_final * 1000])) self.results_table.fill_table(data, readOnly=True) self.results_table.show() # Unhide export button self.export_button.show() # Plot results if loadLFI: ylabel = "Pipeline-to-earth touch voltage (V)" title = "Load LFI Voltages" else: ylabel = "Pipeline-to-earth touch voltage (kV)" title = "Fault LFI Voltages" if self.plot is not None: self.plot.close() self.plot = PlotWindow(pipe_distance, Vp_final, "Distance along pipeline (m)", ylabel, title) self.plot.show()
def main(): af = load("raw/Pitts250/groundtruth") # remove 12 rows every other 12 rows (removing pitch2) alt = np.empty(af.shape[0] / 12) alt[::2] = 0 alt[1::2] = 1 row12 = np.repeat(alt, 12, axis=0) * (np.array(range(af.shape[0])) + 1) af = np.delete(af, np.nonzero(row12), axis=0) af = calc.filter_darks(af, "raw/Pitts250/data", 17, 12) calc.save_index(af, os.path.join(INDEX_PATH, "pitts_file_index.mat")) #af = calc.load_index(os.path.join(INDEX_PATH, "pitts_file_index.mat")) #load or do calculations index, ind, dist, nz = calc.calculate(af[:, 1:3].astype(float)) calc.save(index, ind, dist, nz, af[:, 0], os.path.join(INDEX_PATH, "pitts_calc.mat")) index, ind, dist, nz, af = calc.load_calculations( os.path.join(INDEX_PATH, "pitts_calc.mat")) calc.test(index, ind, dist, af, nz, "raw/Pitts250/data")
def resultant(Output_list): O = Output_list l = len(O) ans = 0 print(O) for i in range(0, l - 1): if i == 0: ans = O[0] if i % 2 != 0: n1 = ans n2 = O[i + 1] op = O[i] #print("%d s d" %n1)# %op %n2) ans = calc.calculate(n1, n2, op) return ans #X=[5, '-', 2, '-', 4, 'x', 5, 'x', 3, 'x', 5, '-', 1] #res=resultant(X) #print(res)
def update(): del eventList[:] now = datetime.datetime.now() one_month_ago = now - datetime.timedelta(days=31) two_months_ago = now - datetime.timedelta(days=60) current = (one_month_ago, now) previous = (two_months_ago, one_month_ago) apiQueue.put(current) apiQueue.put(previous) for i in range(2): thread = apiThread(apiQueue) thread.setDaemon(True) thread.start() apiQueue.join() # clear out the cache clear_session() return calculate(eventList)
def Count(self): operating = self.Entry.get() op = '' if calc.isoperator(operating[0]) or operating[0] == '^': #继续计算功能 op += (str(self.Answer.get()) + operating) for i in range(len(operating)): #一对中空括号表示内部装着上一次运算的结果。 if operating[i] == '(' and operating[i + 1] == ')': op += ('(' + str(self.Answer.get())) else: op += operating[i] try: s = calc.calculate(op) if s == None: self.Answer.set('Error--Syntax Error.') else: self.Answer.set(s) self.Outtry.delete(0, END) self.Outtry.insert(END, self.Answer.get()) except: self.Answer.set('Error--Syntax Error.') self.Outtry.delete(0, END) self.Outtry.insert(END, self.Answer.get())
def test_versions() : iterations = 10 length = 1000 max_size = 50 for i in range(0,iterations) : l = [] for j in range(0,length) : l.append(randint(1,max_size)) start = time() naive = calculate(l) end = time() elapsed = end - start print 'naive took: ', elapsed start = time() optimized = f_calc(l) end = time() elapsed = end - start print 'optimized took: ', elapsed try : assert naive == optimized except : print 'failed on: ',l raise Exception ('Failed test versions') print 'passes!'
def testSumFloatNum(self): self.assertEqual(calculate('+', 0.1, 0.2), 0.3)
def testSubNotNumInverce(self): self.assertEqual(calculate('-', 1, 'abc'), 'Error: It works just only with numbers')
def testDevisionByZero(self): self.assertEqual(calculate('/', 2, 0), 'Error: Wow, wow. You are not God to do so things! (Divide on zero)')
def testPowFloatMore1(self): self.assertEqual(calculate('^', 10.1, 2), 102.01)
def testPowNumInverce(self): self.assertEqual(calculate('^', 3, 2), 9)
def testPowInt(self): self.assertEqual(calculate('^', 2, 3), 8)
def test_simple_sub_eq(): assert (calculate('3-2') == 1.0)
def testSubNegative(self): self.assertEqual(calculate('-', 10, -1), 11)
def testSubFloatNumInverce(self): self.assertEqual(calculate('-', 0.2, 0.1), 0.1)
def testSubFloatNum(self): self.assertEqual(calculate('-', 0.1, 0.2), -0.1)
def testSubInt(self): self.assertEqual(calculate('-', 2, 4), -2)
def testSumNegative(self): self.assertEqual(calculate('+', -10, 1), -9)
def testNoneInverce(self): self.assertEqual(calculate('/', 1, None), 'Error: It works just only with numbers')
def testDevFloatMore1(self): self.assertEqual(calculate('/', 10.1, 0.1), 101.0)
def test_simple_div_eq(): assert (calculate('1/2') == 0.5)
def testPowFloatNum(self): self.assertEqual(calculate('^', 0.1, 2), 0.01)
def test_complicated_eq(): with unittest.mock.patch("random.randint", lambda x, y: 0): assert (calculate("1.3+2*3-2^3-5/2+R") == -3.2)
def testPowNegative(self): self.assertEqual(calculate('^', 10, -1), 0.1)
def test_not_supported_variable(): with pytest.raises(ValueError): calculate("Z+5")
def testPowZero(self): self.assertEqual(calculate('^', 15, 0), 1)
def test_valid_operator_at_the_beginning(): assert (calculate("-5+3") == -2.0)
def testUnknownOperator(self): self.assertEqual(calculate('@', 1, 1), 'Error: It is useless calculator, and it do not know this operator((')
def test_invalid_operator_at_the_end(): with pytest.raises(ValueError): calculate("5+3+")
def test_invalid_input_data(): with pytest.raises(ValueError): calculate("")
def test_simple_eq(): tmp = calculate(foo()) print(tmp, "really?") assert (tmp == 7) assert (calculate(foo()) == 6)
def testMultiplyInt(self): self.assertEqual(calculate('*', 2, 4), 8)
def testSumInt(self): self.assertEqual(calculate('+', 2, 4), 6)
def test_simple_mul_eq(): assert (calculate('2*2') == 4.0)
def testMultiplyFloatNum(self): self.assertEqual(calculate('*', 0.1, 0.2), 0.02)
def test_simple_power_eq(): assert (calculate('2^3') == 8.0)
def testMultiplyFloatNumInverce(self): self.assertEqual(calculate('*', 0.2, 0.1), 0.02)
def test_supported_variables(): with unittest.mock.patch("random.randint", lambda x, y: 0): assert (calculate("R+G") == 9.81)
def testMultiplyNegative(self): self.assertEqual(calculate('*', 10, -1), -10)
def test_validate_eq(): with pytest.raises(ValueError): calculate('3+-5+RR')
def testMultiplyFloatMore1(self): self.assertEqual(calculate('*', 10.1, 0.1), 1.01)
def test_invalid_operator_at_the_beginning(): with pytest.raises(ValueError): calculate("*5+3")
def testDevInt(self): self.assertEqual(calculate('/', 2, 4), 0.5)
def test_invalid_combination(): with pytest.raises(ValueError): calculate("5+-3")
def testDevFloatNum(self): self.assertEqual(calculate('/', 0.1, 0.2), 0.5)
def test_simple_add_eq(): assert (calculate('1+2') == 3.0)
def testDevFloatNumInverce(self): self.assertEqual(calculate('/', 0.2, 0.1), 2.0)
def test_variables(): with unittest.mock.patch("random.randint", lambda x, y: 0): assert (calculate("R+0") == 0)
def testDevNegative(self): self.assertEqual(calculate('/', 10, -1), -10)