def post(self): args = image_req_args.parse_args() if 'internals' in os.listdir(): shutil.rmtree('internals') if 'segmented' in os.listdir(): shutil.rmtree('segmented') os.mkdir('segmented') operation = BytesIO(base64.urlsafe_b64decode(args['image'])) print(operation) operation = main(operation) print("operation :", operation) print("solution :", calculate(operation)) os.mkdir('internals') shutil.move('segmented', 'internals') shutil.move('input.png', 'internals') if 'segmented_characters.csv' not in os.listdir(): return json.dumps({ 'Entered_equation': '', 'Formatted_equation': '', 'solution': '' }) shutil.move('segmented_characters.csv', 'internals') formatted_equation, solution = calculate(operation) # solution = " ".join(str(x) for x in solution) return json.dumps({ 'Entered_equation': operation, 'Formatted_equation': formatted_equation, 'solution': solution })
def test_divide_by_zero_fail(): # input a = 4 b = 0 operator = '/' # process and assert with pytest.raises(ZeroDivisionError): calc.calculate(a, b, operator)
def test_calculator_invalid_value(self, rf): rf.return_value = [ "add 100", "add 200", "add 300", "foo 400", "add bar", "apply 3", ] with self.assertRaises(ValueError): calculate(_)
def test_calculator_invalid_instructions(self, rf): rf.return_value = [ "add 100", "add 200", "apply 3", "add 300", "add 400", "add 500", ] with self.assertRaises(InvalidInstructions): calculate(_)
def menu(): print("") print("Calcule seu reajuste salarial") print(" ") salary = input("Digite o valor total do seu salário: ") if (calculator.validate(salary)): calculator.calculate(salary) else: print(" ") print("Valor inválido")
def calculate(*args): if not args or len(args) < 2: print ">>> You have to provide the path to the input data and the path to the top artists." elif len(args) > 2: print ">>> Invalid usage. This command takes exactly two arguments: path to the input data and path to top artists." else: path_data = args[0] path_artists = args[1] if not os.path.exists(path_data) or not os.path.isfile(path_data): print ">>> You did not provide a valid data input file path." elif not os.path.exists(path_artists) or not os.path.isfile(path_artists): print ">>> You did not provide a valid artists input file path." else: print ">>> Starting data analysis..." calculator.calculate(path_data, path_artists, talky=True)
def get_cmd_output(hostname, topic, request_options): digest = get_digest({'h': hostname, 't': topic, 'r': request_options}) cache_file = '%s/cache/%s' % (MYDIR, digest) if os.path.exists(cache_file): return open(cache_file).read().decode('utf-8') #elif hostname == 'rate.sx' and topic == ':firstpage' and os.path.exists(cache_file): # return open(cache_file).read().decode('utf-8') else: currency = hostname.lower() if currency.endswith('.rate.sx'): currency = currency[:-8].upper() if currency == 'COIN': return "Use YOUR COIN instead of COIN in the query: for example btg.rate.sx, xvg.rate.sx, eth.rate.sx and so on\nTry:\n curl btg.rate.sx\n curl xvg.rate.sx\n curl xrb.rate.sx\n" use_currency = currency if currency not in currencies_names.SUPPORTED_CURRENCIES \ and currency not in coins_names.COIN_NAMES_DICT and currency != 'coin': currency = 'USD' if topic != ':firstpage': try: answer = calculator.calculate(topic.upper(), currency) if answer: answer = 'text %s' % answer except ValueError as e: return "ERROR: %s\n" % e if answer is None: try: answer = draw.view(topic, use_currency=use_currency) except RuntimeError as e: return "ERROR: %s\n" % e if answer is not None: if request_options.get('no-terminal'): answer = remove_ansi(answer) open(cache_file, 'w').write(str(answer) + "\n") return "%s\n" % answer else: return "ERROR: Can't parse your query: %s\n" % topic cmd = [ "%s/ve/bin/python" % MYDIR, "%s/bin/show_data.py" % MYDIR, currency, topic ] config = request_options config['currency'] = currency answer = view.show(config) if config.get('no-terminal'): answer = remove_ansi(answer) open(cache_file, 'w').write(answer) #p = Popen(cmd, stdout=PIPE, stderr=PIPE) #answer = p.communicate()[0] return answer.decode('utf-8')
def handle(): form = GraphForm() if form.validate_on_submit(): flash('request parameters: p1={}, p2={}, p3={}, p4={}'.format( form.salary.data, form.span.data, form.rate.data, form.deposit.data)) Salary_year = 10000 * form.salary.data year = form.span.data rate = form.rate.data deposit = 10000 * form.deposit.data X, base, profit = calculator.calculate(Salary_year, year, rate, deposit=deposit) image_buffer = calculator.drawPlot(X, base, profit, salary=Salary_year, rate=rate, deposit=deposit) # app.logger.debug(image_buffer) # 使用form.form.para1.data就能取到para1的值,然后可以调用具体计算过程 # 使用flash(...) 是将数据绑定到前端的页面,你不需要绑定的话可以不flash # 你可以将生成的图片放入result.html中 return render_template('result.html', img_stream=image_buffer.decode())
def home(): form = WelcomeForm(request.form) calcform = CalcForm(request.form) if request.method == 'POST' and form.validate(): if request.form['stream']: name = form.name.data stream = config.STREAM_CODE[request.form['stream']] global syllabus syllabus = config.STREAM[stream] return render_template('calc.html', name=name, syllabus = syllabus, stream = stream, grades = grades, calc = calcform) else: form.errors['stream'] = 'Please select a stream' return render_template('home.html', form = form, streams = config.STREAM_CODE) elif request.method == 'POST' and request.form['submit'] == 'Calculate': return render_template('result.html', result = calculate(request.form, syllabus)) else: return render_template('home.html', form = form, streams = config.STREAM_CODE)
def get_cmd_output(hostname, topic, request_options): cache_file = '%s/data/last' % MYDIR if hostname == 'rate.sx' and topic == ':firstpage' and os.path.exists( cache_file): return open(cache_file).read().decode('utf-8') else: currency = hostname.lower() if currency.endswith('.rate.sx'): currency = currency[:-8].upper() if currency == 'COIN': return "Use YOUR COIN instead of COIN in the query: for example btg.rate.sx, xvg.rate.sx, eth.rate.sx and so on\nTry:\n curl btg.rate.sx\n curl xvg.rate.sx\n curl xrb.rate.sx\n" if currency not in currencies_names.SUPPORTED_CURRENCIES \ and currency not in currencies_names.CRYPTO_CURRENCIES + ['coin']: currency = 'USD' if topic != ':firstpage': answer = calculator.calculate(topic.upper(), currency) if answer is not None: return "%s\n" % answer else: return "ERROR: Can't parse your query: %s\n" % topic cmd = [ "%s/ve/bin/python" % MYDIR, "%s/bin/show_data.py" % MYDIR, currency, topic ] config = request_options config['currency'] = currency answer = view.show(config) #p = Popen(cmd, stdout=PIPE, stderr=PIPE) #answer = p.communicate()[0] return answer.decode('utf-8')
def get_cmd_output(hostname, topic, request_options): digest = get_digest({'h':hostname, 't': topic, 'r': request_options}) cache_file = '%s/cache/%s' % (MYDIR, digest) if os.path.exists(cache_file): return open(cache_file).read().decode('utf-8') #elif hostname == 'rate.sx' and topic == ':firstpage' and os.path.exists(cache_file): # return open(cache_file).read().decode('utf-8') else: currency = hostname.lower() if currency.endswith('.rate.sx'): currency = currency[:-8].upper() if currency == 'COIN': return "Use YOUR COIN instead of COIN in the query: for example btg.rate.sx, xvg.rate.sx, eth.rate.sx and so on\nTry:\n curl btg.rate.sx\n curl xvg.rate.sx\n curl xrb.rate.sx\n" if currency not in currencies_names.SUPPORTED_CURRENCIES \ and currency not in currencies_names.CRYPTO_CURRENCIES + ['coin']: currency = 'USD' if topic != ':firstpage': try: answer = calculator.calculate(topic.upper(), currency) except ValueError, e: return "ERROR: %s\n" % e if answer is not None: open(cache_file, 'w').write(str(answer)+"\n") return "%s\n" % answer else: return "ERROR: Can't parse your query: %s\n" % topic cmd = ["%s/ve/bin/python" % MYDIR, "%s/bin/show_data.py" % MYDIR, currency, topic]
def test_calculator_success(self, rf): rf.return_value = [ "add 2", "multiply 3", "apply 3", ] self.assertEqual(calculate(_), 15) rf.return_value = [ "divide 4", "multiply 2", "apply 3", ] self.assertEqual(calculate(_), 6) rf.return_value = [ "divide -4", "multiply 2", "subtract 10", "apply 3", ] self.assertEqual(calculate(_), -23) rf.return_value = [ "divide 44", "multiply -4", "subtract -10", "add 100", "multiply 6", "apply 3", ] self.assertEqual(calculate(_), 48) rf.return_value = [ "add 100", "add 200", "add 300", "add 400", "add 500", "apply 3", ] self.assertEqual(calculate(_), 1503)
def test_calculator_three_elements(self): self.assertEqual(36, calculate("(add 12 12 12)")) self.assertEqual(49, calculate("(add 12 12 12 13)")) self.assertEqual(24, calculate("(multiply 2 2 2 3)")) self.assertEqual(45, calculate("(multiply (add 2 3) 3 3)")) self.assertEqual(75, calculate("(multiply (add 2 3) (add 2 3) 3)")) self.assertEqual(125, calculate("(multiply (add 2 3) (add 2 3) (add 2 3))")) self.assertEqual(625, calculate("(multiply (add 2 3) (add 2 3) (add 2 3) (add 2 3))")) self.assertEqual(28, calculate("(add (multiply 2 3) (multiply 4 5) (multiply 1 2))"))
def post(self): x = self.request.get("no1") y = self.request.get("no2") oper = self.request.get("operator") result = calculate(x, y, oper) params = {"result": result} return self.render_template("index.html", params=params)
def test_calculator_whitespace_success(self, rf): rf.return_value = [ "add 2 ", "multiply 3", "divide 6", " apply 3", ] self.assertEqual(calculate(_), 10)
def test_multiplicate_two_numbers_success(): # input a = 5 b = 2 operator = '*' # process result = calc.calculate(a, b, operator) # assert assert result == 10
def doit(equation, expected, use_runtime=False): result = calculator.calculate(equation, tick_limit=TIMEOUT, use_runtime=use_runtime, trace=False) assert expected is Ignore \ or isinstance(result, calculator.functions.Glyph) and result.value == expected \ or check_string(result, expected) \ or result is None and expected is None \ or isinstance(result, sympy.boolalg.BooleanAtom) and bool(result) == expected \ or sympy.simplify(result - expected) == 0
def test_when_number_is_None(): # input a = None b = 4 operator = '-' # process result = calc.calculate(a, b, operator) # assert assert result is None
def test_sum_two_numbers_success(): # input value1 = 2 value2 = 3 operator = '+' # process result = calc.calculate(value1, value2, operator) # assert assert result == 5
def test_operation_with_empty_operator(): # input a = 1 b = 6 operator = '' # process result = calc.calculate(a, b, operator) # assert assert result is None
def press_equal(self, reciprocal=False, percent=False): text = self.lineEdit.text() if reciprocal: text = wrapper_inverse(text) try: result, equation = calculate(text, self.PRECISION, percent) self.lineEdit.setText(str(result)) self.update_history(equation) self._history.append(text) except Exception as e: self.lineEdit.setText(str(e))
def test_subtracting_two_numbers_success(): # input a = 30 b = 20 operator = '-' # process result = calc.calculate(a, b, operator) # assert assert result == 10
def post(self): try: first_number = float(self.request.get("first_number")) second_number = float(self.request.get("second_number")) operator = self.request.get("operator") full_result = "" full_result = calculator.calculate(first_number, second_number, operator) except Exception as e: full_result = "Please enter a whole number." params = {"full_result": full_result} return self.render_template("calculator.html", params=params)
def testNoneAsArg(self): with self.assertRaises(ValueError): calculate("+", None, "1") with self.assertRaises(ValueError): calculate("*", None, "4") with self.assertRaises(ValueError): calculate("/", "1", None)
def perform_condition(condition, inventory): """Processing of condition""" condition = str(condition) if condition == 'True': return True try: while True: a = condition.index('{') b = condition.index('}') part = changer_names(condition[a + 1:b], inventory) part = calculator.calculate(part) condition = condition[:a] + part + condition[b + 1:] except Exception: return calculator.truth(condition)
def step_that_we_will_enter_the_input_in_the_order_number1_number2_operator( self): r'that we will enter the input in the order number1, number2, operator' with self.assertRaises(ValueError): calculate('add', 5, 234) with self.assertRaises(ValueError): calculate(8, 'add', 234) with self.assertRaises(ValueError): calculate(8, 5, 8)
def val(self, message): """ Called when the values come back from the server Input: message """ values = message[1:] if self.ownValue in values: self.ownResult, self.ownTrace = calculate(values, self.maxNum) self.print(f'Your calculation: {self.ownResult}') message = compose(RESULT_HEADER, [self.ownResult], self.key) self.sock.sendall(message) else: self.showWarning('Value not present', f'Your value {self.ownValue} not present in {message}. The server has been notified.') msg = compose(ERROR_HEADER, [VALUE_OMITTED_ERROR, self.ownValue], self.key) self.sock.sendall(msg)
def recognize(self, task): doc = self.nlp(task) dependency_parser.print_doc(doc) # Find root of the calculation current = None for token in doc: if token.dep_ == "ROOT" and token._.operator != matcher.Term.NONE: current = token break if current is None: print("Could not find useable ROOT") return {"term": "Error: Could not find useable ROOT", "result": ""} return calculator.calculate(current)
def add_expression(expression_request: ExpressionRequest): res = calculate(expression_request.expression) new_expression = { "expression": expression_request.expression, "result": res } expressions.insert_one(new_expression) return { "status": "200", "message": "Expression added to db", "result": str(res) }
def test_unicode(): tokens = calculator.parser.tokenizer(';🐱', calculator.parser.TOKEN_SPEC) strings = list(map(lambda x: x['string'], tokens)) assert strings == ['', ';🐱', ''] result = calculator.calculate(';🐱') assert isinstance(result, calculator.functions.Glyph) assert result.value == '🐱' assert calculator.formatter.format(result) == '🐱' doformatted(';🐱', '🐱') doformatted(';🐶 : ;🦊 :[]', '"🐶🦊"') doformatted(';🐶 : ;🦊 :[]', '"🐶🦊"') doformatted('"🐶🦊"', '"🐶🦊"') doformatted('ord(;🐱)', '128049') doformatted('chr(ord(;🐱))', '🐱')
def accept(a, b, c): try: a=float(a.get()) b=float(b.get()) c=float(c.get()) result = calculator.calculate(a,b,c) if result == False: no_result() else: print(type(result)) x1 = result['x1'] x2 = result['x2'] result_screen(x1, x2) except ValueError as e: not_number_error(e)
def calculate_hands(): app.logger.info(request.get_json()) if not request.json: # or not 'player' in request.json: abort(400) # hand = { # 'player': request.json['player'], # 'hand': request.json['hand'], # # 'hand': request.json.get('hand', ""), # # 'done': False # } hand = request.json['hand'] app.logger.info(hand) # return jsonify({'hand': hand}), 201 # return jsonify({'hand': calculate(hand)}), 201 return jsonify({'hand': calculate(hand)}), 201
def test_calculator_success_blank_lines(self, rf): rf.return_value = [ "add 100", "", "", "", "add 200", "", "add 300", "", "", "", "add 400", "", "add 500", "", "apply 3", ] self.assertEqual(calculate(_), 1503)
def handler(conn): response_list = [] raw_message = recvall(conn) print('[info] Server received raw_message:', raw_message) exp_count = struct.unpack('>H', raw_message[0:2])[0] response_list.append(exp_count) start = 2 while exp_count > 0: exp_len = struct.unpack('>H', raw_message[start:start + 2])[0] start += 2 exp_content = raw_message[start:start + exp_len].decode('utf-8') exp_result = str(calculator.calculate(exp_content)) response_list.append(len(exp_result)) response_list.append(exp_result) start += exp_len exp_count -= 1 # send response print('[info] response list to send:', response_list) conn.sendall(build_message(response_list)) print('[info] message sent:', build_message(response_list)) conn.close()
def test_complex1(): assert_true_equal(calculator.calculate("12 - 2 * 3.0"), 6.0)
def test_divide2(): assert_true_equal(calculator.calculate("12 d 2 d 3.0"), 2.0)
def test_divide1(): assert_true_equal(calculator.calculate("6 d 2"), 3)
def test_calculator_raises_with_wrong_operation(self): with self.assertRaises(InvalidOperationException): calculate(3, 2, 'invalid')
def test_multiply_two_numbers(): assert calculator.calculate('2*4')==8
def calculateUnitTest(): assert calculate(3, 4, '*') == 12 assert calculate(5, 4, '#') == "OPERATION ERROR" assert calculate('5.3a', '4', '*') == "NUM ERROR" assert calculate('5', '4', '*') == 5.0 * 4.0 print "Testing of calculate passed successfully"
def test_subtract1(): assert_true_equal(calculator.calculate("123-103"), 20)
def test_add3(): assert_true_equal(calculator.calculate("123 + 123.0"), 246.0)
def test_add2(): assert_true_equal(calculator.calculate("123 + 123 + 4"), 250)
def test_add1(): assert_true_equal(calculator.calculate("123+123"), 246)
def test_calculator_adds_two_numbers(self): result = calculate(2, 3, 'add') self.assertEqual(result, 5)
def test_complex2(): assert_true_equal(calculator.calculate("-5 + 10 * 4 - 10 d 2.0"), 30.0)
def test_complex3(): assert_true_equal(calculator.calculate("-12 * 3.0 + 5"), -31.0)
def test_subtract_two_numbers(): assert calculator.calculate('12-10')==2
def test_bad_input(): assert calculator.calculate('foo')=="Invalid input"
def test_add_three_numbers(): assert calculator.calculate('3+4+5')==12
def test_subtract2(): assert_true_equal(calculator.calculate("123 + - 3 - + 20"), 100)
def test_calculator_raises_with_wrong_argument(self): with self.assertRaises(CalculatorException): calculate(3, "invalid", 'add')
def test_divide_two_numbers(): assert calculator.calculate('27/3')==9
def test_subtract3(): assert_true_equal(calculator.calculate("123+-3.0-+20"), 100.0)
def test_no_operator(): assert calculator.calculate('35')==35
def test_multiply1(): assert_true_equal(calculator.calculate("123*2"), 246)
def test_pemdas(): assert calculator.calculate('5+2*4')==13
def test_multiply2(): assert_true_equal(calculator.calculate("123*2 * 1.0"), 246.0)
def test_add_two_numbers(): assert calculator.calculate('5+2')==7
def test_calculator_multiplies_negative_numbers(self): result = calculate(3, -1, 'multiply') self.assertEqual(result, -3)