def formula(nr): response.set_header('X-XSS-Protection', '0') try: if '.' in nr: text = formula_details(*nr.split('formulae')[1].split('.')) result, good_input = calc('', text) outp, logp, memory, known, linespace = result result = outp, logp, memory, known, linespace return newform( result, '', '', action=None, button2='', otherbuttons='', actualpref= "\n\nClick on formulas to make commands appear here (and then copy into calculator)\n" ) else: text = show_formulae(int(nr.split('formulae')[1])) except ZeroDivisionError: text = 'No data' result, good_input = calc('', text) return newform( result, '', '', action=None, button2='', otherbuttons='', show_top=True, actualpref= "\n\nClick on formulas to make commands appear here (and then copy into calculator)\n" )
def test_bad_input(self): with self.assertRaises(ValueError): calc("gun", 1, "+") calc(1, "gun", "+") with self.assertRaises(TypeError): calc(1, 2, 1) calc(1, 2, "gun") calc(1, 2, float)
def menu(): now = datetime.datetime.now() print(now.strftime("[%H:%M]"), 3 * "-", "Control Center", 10 * "-") choice = input(""" 1: Ip weergave | 5: Networkscan | 9: calculator 2: PasswordGen | 6: System update en upgrade | 10: Computer management 3: System info | 7: Portscan 4: Install openvpn | 8: gpio Choose the option you like: """) if choice == "1": ifConfig.ip() print("\n") restart() elif choice == "2": passwordgen.passwordgenerator() print("\n") restart() elif choice == "3": systemInfo.sysinfo() print("\n") restart() elif choice == "4": install.installvpn() print("\n") restart() elif choice == "5": c=2 elif choice == "6": updateSystem.updatesystem() print("\n") restart() elif choice == "7": portscan.port() print("\n") restart() elif choice == "8": gpioPin.pinout() restart() elif choice == "9": calculator.calc() print("\n") restart() elif choice == "10": compman.com_mana() print("\n") restart() else: print(29 * "-") print("|You must only select option|") print("|Please try again |") print(29 * "-") menu()
def POST(self): """ Load quantities defined previously by the user, process current commands and output results. """ web.header('Content-Type', 'text/html; charset=utf-8', unique=True) browser = web.ctx.env['HTTP_USER_AGENT'].lower() mobile = ("ipad" in browser or "iphone" in browser or "nexus" in browser) if "ipod" in browser or "iphone" in browser or "android" in browser: mobile = "ipod" try: state = web.input() if state['sub'] == "reset": return newform("", "", "", "", "", mobile, False, "") except: return newform("", "", "", "", "", mobile, False, "") oldsymbols = state['memory'] logbook = state['logbook'] inputlog = state['inputlog'] if state['sub'] == "export": allsymbols = State(oldsymbols, mobile) return printableLog(allsymbols, logbook, inputlog) if state['sub'] == "help": return helpform(mobile) commands = state['commands'] outp, logp, mem, known, oneline, good_input,linespace = calc(oldsymbols, commands, mobile) inputlog = inputlog + "\n" + good_input return newform(outp, logp, mem, known, logbook, mobile, oneline, inputlog, linespace=linespace)
def index_post(): # response.set_header('Content-Type', 'text/html; charset=utf-8') response.set_header('X-XSS-Protection', '0') browser = request.environ.get('HTTP_USER_AGENT').lower() if request.forms.get('sub') == "reset": return newform(('', '', '', '', ''), '', '', browser=browser) oldmemory = request.forms.get('memory') if request.forms.get('sub') == "help": return helpform() oldinputlog = request.forms.get('inputlog') oldlogbook = request.forms.get('logbook') if request.forms.get('sub') == "export": return printableLog(State(oldmemory), oldlogbook, oldinputlog) commands = request.forms.get('commands') result, newinputlog = calc(oldmemory, commands) # verboselog, brieflog, memory, known, linespace = result inputlog = oldinputlog + newinputlog if request.forms.get('sub') == " Save ": with open('logfile.txt', 'a', encoding='utf-8') as logfile: print(inputlog, file=logfile) print(inputlog) return helpform() return newform(result, oldlogbook, inputlog)
def generator(begin, end, step, EPS): if EPS <= 0 or begin > end or step <= 0: raise ValueError("Bad input") cur = begin while cur < end: yield calc(cur, EPS) cur += step
def show_calc_dialog(dest_val, components, error_msg=None): global DIALOG_FLAG DIALOG_FLAG = True # 用户输入的表达式 message = DIALOG_MSG.replace('_REPLACE_0_', str(components)).replace('_REPLACE_1_', str(dest_val)) DIALOG_FLAG = False if error_msg: message += '\n' + error_msg expression = easygui.enterbox(message, DIALOG_TITLE) # 用户没输入,点了取消 if expression is None: CHESSBOARD.CURRENT_SELECTED_CHESSMAN = None # 用户输入了,进行计算 else: expression_valid = check_expression(components, expression) if not expression_valid: show_calc_dialog(dest_val, components, '表达式有误,请重新输入') else: result = calc(expression) # 输入的表达式格式 if result is None: show_calc_dialog(dest_val, components, '表达式有误,请重新输入') # 输入的表达式计算出来的结果不为0 elif result != dest_val: show_calc_dialog(dest_val, components, '结果不正确,请重新输入') # 正确,跳特么的 else: CHESSBOARD.jump()
def __next__(self): if self.begin < self.end: cur = calc(self.begin, self.EPS) self.begin += self.step return cur else: raise StopIteration
def handler(conn, addr): print('Server connected by', addr) while True: exp_generator = calculator.zfp_decode(conn, bufsize) res = [str(calculator.calc(exp)) for exp in exp_generator] if res == []: conn.close() print("Connection closed by client.") break else: print("Result send: {0}, waiting for next request.".format(res)) conn.sendall(calculator.zfp_encode(res))
def thickness_calc(request): result = None if request.method == "POST": form = ThicknessForm(request.POST) if form.is_valid(): form = form.save(commit=False) angle = form.angle dhthick = form.dhthick result = calc(angle,dhthick) return render(request, 'blog/truewidthans.html', {'form':form, 'result': result}) else: form = ThicknessForm() return render(request, 'blog/truewidth.html', {'form': form})
def adder_page(): errors = "" if request.method == "POST": a = None d = None try: a = float(request.form["a"]) except: errors += "<p>{!r} is not a number.</p>\n".format( request.form["a"]) try: d = float(request.form["d"]) except: errors += "<p>{!r} is not a number.</p>\n".format( request.form["d"]) if a is not None and d is not None: result = calc(a, d) return ''' <html> <body> <p>The result is {result}</p> <p><a href="/">Click here to calculate again</a> </body> </html> '''.format(result=result) return ''' <html> <head> <title>LuckytheDog</title> </head> <body> {errors} <h1>True Thickness Calculator</h1> <p>Angle to core axis: <form method="post" action="."> <p><input name="a" /></p> <p>Downhole thickness: <p><input name="d" /></p> <p><input type="submit" value="Calculate" /></p> </form> </body> </html> '''.format(errors=errors)
def GET(self): web.header('Content-Type', 'text/html; charset=utf-8', unique=True) browser = web.ctx.env['HTTP_USER_AGENT'].lower() mobile = ("ipad" in browser or "iphone" in browser or "nexus" in browser) if "ipod" in browser or "iphone" in browser or "android" in browser: mobile = "ipod" try: state = web.input(switch="") if state['switch'] == "": return newform("", "", "", "", "", mobile, False) except: return newform("", "", "", "", "", mobile, False) oldsymbols = "" logbook = "" commands = "\n".join(["__%s__ = 1" % switch for switch in state['switch'].split("*")]) outp, logp, mem, known, oneline, good_input,linespace = calc(oldsymbols, commands, mobile) return newform(outp, logp, mem, known, logbook, mobile, oneline, "", linespace=linespace)
def workedexample(nr): """ Presents a worked example. """ response.set_header('X-XSS-Protection', '0') browser = request.environ.get('HTTP_USER_AGENT').lower() prefill = nr.split('example')[1] text = exdict[prefill][:-2] if '<h4>Answer:</h4>' in text: text = text.split('<h4>Answer:</h4>')[0] result, good_input = calc('', text) logbook = '' pref = '\n'.join(extract_knowns('='.join(text.split('\n')[1:]))) + '\n' print(pref) print(text) return newform(result, logbook, good_input, browser=browser, actualpref=pref)
def __init__(self, uuid): Budgie.Applet.__init__(self) self.uuid = uuid # applet appearance self.icon = Gtk.Image() self.icon.set_from_icon_name("gnome-calculator", Gtk.IconSize.MENU) self.box = Gtk.EventBox() self.box.add(self.icon) self.add(self.box) self.popover = Budgie.Popover.new(self.box) self.calc = calc() self.popover.add(self.calc) self.box.show_all() self.popover.show_all() self.show_all() self.box.connect("button-press-event", self.on_press)
def hw(hwid): global hints hints = None question = get_example(hwid[2:]) if not question: return "waah, does not exist" if '@@' in question: question, pref = question.split('@@', 1) else: pref = '' answer, followup = get_answer(hwid[2:]) #rint('question', question) result, good_input = calc('', question) inputlog = good_input logbook = '' if hwid.endswith('b'): outp, logp, memory, known, linespace = result outp = '<span style="font-size: 12pt; color: maroon;">' + outp + '</span><br>' logp = '<span style="font-size: 12pt; color: maroon;">' + logp + '</span><br>' outp = outp.replace('color: navy', 'color: indigo') logp = logp.replace('color: navy', 'color: indigo') if followup: outp = outp + '<hr>' + '<span title="%s">Think about it...</span>' % followup.splitlines( )[0].split('Think about it:')[1] result = outp, logp, memory, known, linespace return newform(result, logbook, inputlog, action=hwid, button2='submit', otherbuttons=('export', ), actualpref=pref) return newform(result, logbook, inputlog, action=hwid, button2='', otherbuttons='', show_top=True)
def cookie_post(): oldsymbols = request.forms.get('memory') logbook = request.forms.get('logbook') inputlog = request.forms.get('inputlog') if request.forms.get('sub') == "export": allsymbols = State(oldsymbols, False) return printableLog(allsymbols, logbook, inputlog) if request.forms.get('sub') == "help": return helpform(False) commands = request.forms.get('commands') result, good_input = calc(oldsymbols, commands, False) inputlog = inputlog + good_input enc = inputlog.encode('utf-8') enc = repr(enc[-3000:]) response.set_cookie("visited", enc) if request.forms.get('sub') == " save ": with open('logfile.txt', 'a', encoding='utf-8') as logfile: print(inputlog, file=logfile) print(inputlog) return helpform(False) return newform(result, logbook, inputlog, action='./cookie')
def index_post(): # response.set_header('Content-Type', 'text/html; charset=utf-8') # response.set_header('X-XSS-Protection', '0') browser = request.environ.get('HTTP_USER_AGENT').lower() mobile = ("ipad" in browser or "iphone" in browser or "nexus" in browser) if "ipod" in browser or "iphone" in browser or "android" in browser: mobile = "ipod" try: if request.forms.get('sub') == "reset": return newform("", "", "", "", "", mobile, False, "") except: return newform("", "", "", "", "", mobile, False, "") oldsymbols = request.forms.get('memory') logbook = request.forms.get('logbook') inputlog = request.forms.get('inputlog') if request.forms.get('sub') == "export": allsymbols = State(oldsymbols, mobile) return printableLog(allsymbols, logbook, inputlog) if request.forms.get('sub') == "help": return helpform(mobile) commands = request.forms.get('commands') outp, logp, mem, known, oneline, good_input, linespace = calc(oldsymbols, commands, mobile) inputlog = inputlog + "\n" + good_input return newform(outp, logp, mem, known, logbook, mobile, oneline, inputlog, linespace=linespace)
def test_complex_expression(self): self.assertEqual(calc("2 PLUS 5 MINUS 1 PLUS 4"), 10)
def testSigned(self): self.assertEquals(calc('-4-+2'), Decimal('-6')) self.assertEquals(calc('|+6|'), Decimal('6'))
def testSub2(self): self.assertEquals(calc('0.3-0.1'), Decimal('0.2'))
def testMult2(self): self.assertEquals(calc('12*0.1'), Decimal('1.2'))
def test_calc_substraction(): assert calculator.calc(16, 3, '-') == 13 assert calculator.calc(23, 58, '-') == -35 assert calculator.calc(9, 7, '-') == 2
from calculator import calc print(f"This is Module 1. The name of this module is {__name__}") calc(5,6,"-")
def testDiv2(self): self.assertEquals(calc('0.3/0.1'), Decimal('3'))
def testFloatForms(self): self.assertEquals(calc('1.+.2'), Decimal('1.2'))
def test_calc1(self): result = calc("(33+4)*5/6-99") print result self.assertEqual(-68.16666666666667, result)
def test_calc(self): result = calc("33+4*5/6-99") print result self.assertEqual(-62.666666666666664, result)
def testMult(self): self.assertEquals(calc('2*1.5'), Decimal('3'))
def testSpaces(self): self.assertEquals(calc(' 20 * - 1.5 '), Decimal('-30')) self.assertRaises(ValueError, calc, '2 0 *-1.5') self.assertEquals(calc(' | - 10 | '), Decimal('10')) self.assertRaises(ValueError, calc, '|-1 0|')
def test_number(self): self.assertEqual(calc("5"), 5)
def testLeftZero(self): self.assertEquals(calc('0100 + 04'), Decimal('104')) self.assertEquals(calc('|-01.1|'), Decimal('1.1'))
def Calc(self, request, context): result = c.calc(request.number_1, request.number_2, request.operation) if result is None: return calculator_pb2.CalcReply(res='None') else: return calculator_pb2.CalcReply(res=str(result))
def testAbs(self): self.assertEquals(calc('|10|'), Decimal('10')) self.assertEquals(calc('|-1.1|'), Decimal('1.1'))
import greet from custom_datetime import get_date as date from custom_datetime import get_time as time import calculator import game #main greet.greeting() print("\nwhat you want to do:\n1)check date.\n2)check time.\n3)to open calculator.\n4)to play stone,paper,scissor.\n5)to play number guess game.") c_1 = int(input("\nenter our choice:")) if c_1 == 1: date() elif c_1 == 2: time() elif c_1 == 3: calculator.calc() elif c_1 == 4: game.spc() elif c_1 == 5: game.nog() else: print("bye bye") del c_1 input("\npress enter to exit") #add unit converter #min and max in calculator is still left
def testAdd2(self): self.assertEquals(calc('0.1+0.2'), Decimal('0.3'))
def test_calc_addition(): assert calculator.calc(16, 3, '+') == 19 assert calculator.calc(23, 58, '+') == 81 assert calculator.calc(9, 7, '+') == 16
def test_decline_str(self): self.assertEqual(calculator.calc("words", "ints"), math.inf)
def test_calc_wrong_operation(): assert calculator.calc(16, 3, '?') == None assert calculator.calc(16, 3, 'hello') == None assert calculator.calc(16, 3, '') == None
def test_operations(self): self.assertEqual(calculator.calc(5, 10), (15, -5, 50, 0.5))
def testSub(self): self.assertEquals(calc('401-1'), Decimal('400'))
def test_simple_expression(self): self.assertEqual(calc("1 PLUS 2"), 3)
def test_neg_div_0(self): self.assertEqual(calculator.calc(-10, 0), (-10, -10, 0, -math.inf))
def testAdd(self): self.assertEquals(calc('101+202'), Decimal('303'))
def hw_post(hwid): oldsymbols = request.forms.get('memory') logbook = request.forms.get('logbook') inputlog = request.forms.get('inputlog') oldstuff = len(inputlog.splitlines()) hints = request.forms.get('hints') if hints: hints = json.loads(unescape(hints)) print(oldstuff, inputlog) if request.forms.get('sub') == "export": allsymbols = State(oldsymbols) return printableLog(allsymbols, logbook, inputlog) commands = request.forms.get('commands') result, good_input, = calc(oldsymbols, commands) if commands: inputlog = inputlog + "\n" + good_input outp, logp, memory, known, linespace = result answer, followup = get_answer(hwid[2:]) question = get_example(hwid[2:]) student_answer = inputlog[:] for q in question.splitlines(): student_answer = student_answer.replace(q + '\r\n', '') if request.forms.get('sub') == "submit": grade = grade_answer(student_answer, answer, question, hwid) if followup: fu = followup.splitlines() followup = fu[ 0] + '<ul style="list-style-type:none"><li>' + '</li><br><li>'.join( (f if f[1] != '*' else f[:1] + f[2:]) for f in fu[1:]) + '</li></ul>' result, good_input, = calc('', followup) outp, logp, memory, known, linespace = result return newform((grade + outp, logp, '', '', ''), logbook, inputlog, actualpref='The answer is: ', button2='extra credit?', action='yipee') return newform((grade, logp, '', '', ''), logbook, inputlog, otherbuttons=('export', )) if not commands: if '__tutor__' in inputlog: outp = 'Tutor says: Please input commands. I will comment but give no hints' else: if not hints: print("Hints for:", hwid) print("Student answer:", student_answer) hints = generate_hints(hwid, student_answer, answer, question) for h in hints: pass #rint(h) print('done with hints') outp = hints.pop(0) if not hints: hints = [outp] hints = json.dumps(hints) return newform((outp, '', memory, known, linespace), logbook, inputlog, action=hwid, button2='submit', otherbuttons=('export', ), hints=hints) else: if '__tutor__' in inputlog and '__tutor__' not in commands: feedback = generate_tutor_comments(hwid, inputlog, oldstuff, answer, question) outp, logp, memory, known, linespace = result return newform((outp + feedback, logp, memory, known, linespace), logbook, inputlog, action=hwid, button2='submit', otherbuttons=('export', )) return newform(result, logbook, inputlog, action=hwid, button2='submit', otherbuttons=('export', ))
def test_accept_str_int(self): self.assertEqual(calculator.calc("5", "10"), (15, -5, 50, 0.5))
from calculator import calc if __name__ == '__main__': while True: try: p = raw_input('enter expression or press enter to exit:') if p == '': break print 'answer is: ' + str(calc(p)) except ZeroDivisionError: print 'cannot divide by zero' except (ValueError, IndexError): print 'invalid expression'
def testDiv(self): self.assertEquals(calc('3/1.5'), Decimal('2'))
def calculator(): return calc()
def test_pos_div_0(self): self.assertEqual(calculator.calc(10, 0), (10, 10, 0, math.inf))