def __init__(self, name, command, positions, verbose): Thread.__init__(self) self._name = name self._positions = positions self._verbose = verbose command = command + " --logfile-name=" + name + ".log" self._program = Program(command, verbose)
def send_program(): json_data = request.args.get('json_data') print("======>>>json_data" + json_data) program = Program(json_data) prog_name = program.send_program() print("send program:" + prog_name) return {"code": "200", "program_name": prog_name}
def P15(): p = Program(num_prog_inputs=2) p.create_add_component() p.create_and_component() p.create_xor_component() p.create_bitshiftright_component(1) return ProgramSynthesis(p, BVT.P15, 'P15')
def main(): print("Start") #The first 2 parameters are msg_id, sig_name by which to filter the display of real-time data #The next 2 params are the paths of the file containing the dbc definition file (in json) and the data trace program = Program('c000003', 'TSC1EMSTECU_EngReqTrq_HR', 'data/convereted_dbc_to_json.json', "data/trace.asc") program.plot()
def test_detach(self): vert = VertexShader("A") frag = FragmentShader("B") program = Program(vert, frag) program.detach(frag) assert len(program.shaders) == 1 assert program.shaders[0].code == "A"
def __init__(self, settings=None): # self.settings = settings Program.__init__(self, settings) Driver.__init__(self, settings) print("initializing viewer") self.settings = settings if self.settings["verbose"]: print() print("Settings:") print() print( pformat([f"{k}: {v}" for k, v in settings.items() ]).lstrip('[').rstrip(']')) print() self.env = Environment(DEFAULT_VARS) # programs should be loaded from a directory located by a configuration file setting self.programs = list() self.fig = plt.figure() self.ax = self.fig.add_subplot(111, projection='3d', xlim=(0, 6), ylim=(0, 6)) # self.ax.plot([0.0, 1.0], [0.2, 0.7], 0.4) self.current_position = Point() plt.show() self.current_program = NCProgram()
def main(): root = tkinter.Tk() from libs import painter #import pdb;pdb.set_trace() program = Program(painter) try: fileToLoad = sys.argv[1] except IndexError: print("Ne file specified, opening first.lsa") fileToLoad = "first.lsa" program.load_file(fileToLoad) #Create the gui widgets menuBar = gui.MenuBar(root, program) stepChanger = gui.StepChanger(root, program) text = gui.TextInput(root, program) contextShower = painter.ContextShower(root) activeStateShower = gui.ActiveStateShower(root, program, contextShower) stepOutput = gui.StepOutput(root, text, program) textHelp = gui.TextHelp(root, text, program) help = gui.HelpShower(root, program) #Place them in the rigth order root['menu'] = menuBar root.grid_propagate(True) stepChanger.grid(row=0, column=0, columnspan=50, sticky="nesw") vScrollbar = tkinter.Scrollbar(root, orient=tkinter.VERTICAL) vScrollbar.grid(row=1, column=0, sticky="nesw") text.grid(row=1, column=10, sticky="nesw") textHelp.grid(row=1, column=11, sticky="nesw") stepOutput.grid(row=1, column=12, sticky="nesw") activeStateShower.grid(row=1, column=13, sticky="nesw") help.grid(row=2, column=0, columnspan=50, sticky="nesw") root.columnconfigure(0, weight=0) root.columnconfigure(10, weight=2) root.columnconfigure(11, weight=1) root.columnconfigure(12, weight=2) root.columnconfigure(13, weight=0) root.rowconfigure(0, weight=0) root.rowconfigure(1, weight=1) root.rowconfigure(2, weight=0) def proxy_yview(*args, **kwords): text.yview(*args, **kwords) textHelp.on_activeStep_changed() stepOutput.on_steps_changed() def proxy_set(*args, **kwords): vScrollbar.set(*args, **kwords) textHelp.on_activeStep_changed() stepOutput.on_steps_changed() text['yscrollcommand'] = proxy_set vScrollbar['command'] = proxy_yview # create the interpretor and go, go, go interpretor = interpreter.Interpreter(program) root.after(500, lambda : program.event("source_changed")()) root.mainloop()
def main(argv=None, syslog=syslog): if argv is None: argv = sys.argv[1:] program = Program(__version__, __updated__, argv, syslog) program.mainLoop() program.logFinish()
def message_wylio(self, event): global program try: log("WylioServer message wylio received") print event['wylio'] if event['wylio']['run']: #print "run in wylio" code = event['wylio']['run'] file = open('received_program.py', 'w') file.write(code) file.close() if program != None: program.stop() program = Program(1,'received_program.py') try: thread.start_new_thread(program.run,(self,event['from'])) print "created thread" except: traceback.print_exc() log("Error creating thread") if event['wylio']['value']: signal = event['wylio']['value']['signal'] value = event['wylio']['value']['value'] if program != None: program.sendSensorInput(signal,value) except: traceback.print_exc()
def jumpleq(state: Program, address1: int, address2: int, address3: int): """If Value in Address 1 <= Value in Address 2, Jump to Address 3 Args: state: the program state address1: address 1 address2: address 2 address3: the address to jump to Notes: Rules for legal argument ranges and syntactical correctness: Jumps may lead to any address in the dynamic range [Min, Max + 1] """ address1 = state.read(state, address1) if state.halt is not None: return address2 = state.read(state, address2) if state.halt is not None: return if address1 <= address2: Primitives.jump(state, address3) if state.halt is not None: return else: state.jumped = False
def run_mem(savedstate=""): with zipfile.ZipFile(os.path.join("source", "challenge.zip"), 'r') as zip: machine = zip.read('challenge.bin') program = Program() program.load_bytes(machine) show_all = False if len(savedstate): program.deserialize(savedstate) memory = [] while True: program.run(abort_on_input=True) if len(memory) == 0: memory = program.memory[:] else: for i in range(len(memory)): if memory[i] != program.memory[i]: if show_all or i == 2732: print(f"{i} => {memory[i]} != {program.memory[i]}") temp = input("Step? ") if temp.startswith("all"): show_all = not show_all elif temp.startswith("room "): temp = temp[4:] program.memory[2732] = int(temp) elif temp.startswith("mem "): temp = temp[4:].split(' ') program.memory[int(temp[0])] = int(temp[1]) elif temp == "reset": memory = program.memory[:] else: program.input_buffer += temp + "\n"
def free(state: Program, address1: int): # No more than 5 work tape cells may be Allocated or Freed at a time. if address1 > 5 or address1 <= 0 or (state.min + address1) > 0: state.halt = HaltingCode.ERROR_FREE_OUT_BOUNDS return state.free(address1)
def search_next(cur, program, fo_remain, ho_remain, target_len): if len(program) == target_len: p = Program() for s in program: p.append_step(Step(*s)) PROGRAMs.append(p) # print p return else: valid_fo_funcs = filter(lambda x: FUNCs['FO'][x][1][0] == cur[2] \ if len(FUNCs['FO'][x][1]) == 1 \ else FUNCs['FO'][x][1][1] == cur[2], fo_remain) # len(FUNCs['HO'][x][1]) == 2 \ and valid_ho_funcs = filter(lambda x: FUNCs['HO'][x][1][1] == cur[2], ho_remain) for func in valid_fo_funcs: search_next(FUNCs['FO'][func], \ program+[(func,)], \ filter(lambda x: x!=func, valid_fo_funcs), \ valid_ho_funcs, \ target_len) for func in valid_ho_funcs: for lambs in filter(lambda x: (Lambdas[x][3], Lambdas[x][2])\ ==FUNCs['HO'][func][1][0], \ [l for l in Lambdas]): search_next(FUNCs['HO'][func], \ program+[(func, lambs)], \ valid_fo_funcs, \ filter(lambda x: x!=func, valid_ho_funcs), \ target_len)
def main(): app = None try: from program import Program app = Program() app.run() except Exception as exc: traceback.print_exc(file=open(ERROR_LOG, "w")) class Error(App): theme_cls = kivymd.theming.ThemeManager() def report_callback(self, *args): try: import webbrowser webbrowser.open(PROJ_REPO + "/issues/new?body=" + str(exc)) except Exception: traceback.print_exc(file=open(ERROR_LOG, "w")) sys.exit(1) def build(self): return BugReporter(report_callback=self.report_callback) Error().run()
def main(): INSTRUCTION = """ 0 - exit 1 - sort by name in non-decreasing order 2 - sort by name in non-increasing order 3 - sort by destination in non-decreasing order 4 - sort by destination in non-increasing order 5 - sort by flight number in non-decreasing order 6 - sort by flight number in non-increasing order 7 - sort by price in non-decreasing order 8 - sort by price in non-increasing order 9 - find aeroflots with provided destination 10 - find aeroflots with provided name 11 - find aeroflots with provided departure day 12 - add new aeroflot 13 - delete aeroflot by index 14 - edit aeroflot(enter index and field which you want to change) 15 - print aeroflots """ print(INSTRUCTION) path_read = input("enter path_read: ") path_write = input("enter path_write: ") reader = ReadFromFile(path_read) file = FileEditor(path_write) collection = reader.read() menu = Program(collection) while True: try: menu.menu(file) except Exception as s: print(s)
def main(): logging.basicConfig(level=logging.DEBUG) logging.info('Started') lv = LoadValues() lines = lv.strip_lines() instr = get_instructions(lines) prog = Program(instr) (_, ip, acc) = prog.does_terminate() print("Star 1 : ", acc) finished = None for (i, cur_instr) in enumerate(instr): if cur_instr[0] == 'nop' or cur_instr[0] == 'jmp': instr2 = instr.copy() if cur_instr[0] == 'nop': instr2[i] = ('jmp', cur_instr[1]) else: instr2[i] = ('nop', cur_instr[1]) (res, ip, acc) = Program(instr2).does_terminate() if res: finished = (ip, acc) break print("Star 2 : ", acc) logging.info('Finished')
def execute(self, program: Program): variable = program.var_get('SETCHAR', self.args[0]) index = program.get_symb('SETCHAR', self.args[1]) toModify = program.get_symb('SETCHAR', self.args[2]) if variable is None: exit_app(exitCodes.UNDEFINED_VALUE, 'SETCHAR\nUndefined variable.', True) if not index.is_int() or not variable.is_string() or\ not toModify.is_string(): exit_app(exitCodes.INVALID_DATA_TYPE, 'SETCHAR\nExpected: string variable, int, string', True) if len(toModify.value) == 0 or index.value >= len(variable.value): exit_app(exitCodes.INVALID_STRING_OPERATION, 'SETCHAR\nZero length of to modify characters.', True) try: result = "{}{}{}".format(variable.value[:index.value], toModify.value[0], variable.value[index.value + 1:]) program.var_set('SETCHAR', self.args[0], Symbol(DataTypes.STRING, result)) except IndexError: exit_app(exitCodes.INVALID_STRING_OPERATION, 'SETCHAR\nIndex is out of range.', True)
def __parse_program(): if Parser.tokens.current is None: raise ValueError("File cannot be empty") if Parser.tokens.current.type == "PROGRAM": Parser.tokens.next() if Parser.tokens.current.type == "IDENTIFIER": Parser.tokens.next() if Parser.tokens.current.type == "SEMICOLON": Parser.tokens.next() node = Program() node.set_child(Parser.__parse_block()) if Parser.tokens.current is None or \ Parser.tokens.current.type != "DOT": raise ValueError( f"Expecting final dot (.). Got: {Parser.tokens.current.type}" ) else: raise ValueError( f"Fatal: Syntax error, \";\" expected" + f" but \"{Parser.tokens.current.type}\" found") else: raise ValueError( f"Fatal: Syntax error, \"IDENTIFIER\" expected" + f" but \"{Parser.tokens.current.type}\" found") else: raise ValueError(f"Fatal: Syntax error, \"PROGRAM\" expected" + f" but \"{Parser.tokens.current.type}" + f" {Parser.tokens.current.value}\" found") return node
def process_phase_sequence(self, phase_sequence): program_a = Program(self.program, default_inputs=[phase_sequence[0], 0]) program_b = Program(self.program, default_inputs=[phase_sequence[1], program_a.outputs.pop()]) program_c = Program(self.program, default_inputs=[phase_sequence[2], program_b.outputs.pop()]) program_d = Program(self.program, default_inputs=[phase_sequence[3], program_c.outputs.pop()]) program_e = Program(self.program, default_inputs=[phase_sequence[4], program_d.outputs.pop()]) return program_e.outputs.pop()
def test_allocation_get_channel(): program = Program([Push(0), Pop(0), Push(1), Push(2), Pop(2)]) assert program.get_channel_for_port_key(0, KEY_CKS_DATA) == 0 assert program.get_channel_for_port_key(0, KEY_CKS_CONTROL) == 3 assert program.get_channel_for_port_key(1, KEY_CKR_DATA) is None assert program.get_channel_for_port_key(2, KEY_CKS_DATA) == 2
def display(): glClearColor(20 / 255, 20 / 255, 20 / 255, 1) ShadowProgram.use() glClear(GL_DEPTH_BUFFER_BIT) if not Display._show_shadow_map: glBindFramebuffer(GL_FRAMEBUFFER, ShadowMap.depth_buffer) glViewport(0, 0, ShadowMap.width, ShadowMap.height) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnableClientState(GL_VERTEX_ARRAY) glBindBuffer(GL_ARRAY_BUFFER, Model.vbo) glVertexPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) glDrawArrays(GL_TRIANGLES, 0, len(vertices)) glDisableClientState(GL_VERTEX_ARRAY) if glCheckFramebufferStatus( GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: exit(1) Display._check_map() ShadowProgram.disable() if Display._show_shadow_map: glutSwapBuffers() glutPostRedisplay() return Program.use() glBindFramebuffer(GL_FRAMEBUFFER, 0) glClearDepth(1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glViewport(0, 0, Config.width, Config.height) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, ShadowMap.depth_texture) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glBindBuffer(GL_ARRAY_BUFFER, Model.vbo) glVertexPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, Model.tbo) glTexCoordPointer(2, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, Model.nbo) glNormalPointer(GL_FLOAT, 0, None) glDrawArrays(GL_TRIANGLES, 0, len(vertices)) glBindBuffer(GL_ARRAY_BUFFER, 0) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) Program.disable() glutSwapBuffers() glutPostRedisplay()
def move(state: Program, address1: int, address2: int): address1 = state.read(state, address1) if state.halt is not None: return state.write(state, address2, address1) if state.halt is not None: return
def reshape(width, height): Program.use() glViewport(0, 0, width, height) gluPerspective(100, width / height, 0.1, 50) gluLookAt(*(10, 10, 10), *(0, 0, 0), *(0, 1, 0)) Display.width = width Display.height = height return
def decrement(state: Program, address1: int): v1 = state.read(state, address1) if state.halt is not None: return state.write(state, address1, v1 - 1) if state.halt is not None: return
def execute(self, program: Program): symb1 = program.get_symb(self.opcode, self.args[1]) symb2 = program.get_symb(self.opcode, self.args[2]) validate_math_symbols(self.opcode, symb1, symb2) result = self.compute(symb1, symb2) program.var_set(self.opcode, self.args[0], result)
def execute(self, program: Program): if len(program.data_stack) == 0: exit_app( exitCodes.UNDEFINED_VALUE, 'POPS\nInstruction {}. Data Stack is empty.'.format( self.opcode), True) program.var_set('POPS', self.args[0], program.pop_stack(1)[0])
def test_P15(): print('P15 program, floor of average of inputs, with debug printing:') p = Program(num_prog_inputs=2) p.create_add_component() p.create_and_component() p.create_xor_component() p.create_bitshiftright_component(1) timed_synthesis(p, BVT.P15, 100000, True)
def execute(self, program: Program): symb = program.get_symb('TYPE', self.args[1], False) if symb is None: program.var_set('TYPE', self.args[0], Symbol(DataTypes.STRING, '')) else: program.var_set('TYPE', self.args[0], Symbol(DataTypes.STRING, symb.data_type.value))
def test_attach(self): vert = VertexShader("A") frag = FragmentShader("B") program = Program(vert) program.attach(frag) assert len(program.shaders) == 2 assert program.shaders[0].code == "A" assert program.shaders[1].code == "B"
def P16(): p = Program(num_prog_inputs=2) p.create_xor_component() p.create_xor_component() p.create_negate_component() p.create_and_component() p.create_ule_component() return ProgramSynthesis(p, BVT.P16, 'P16')
def initgl(self): glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.program = Program.load(in_module('glsl/flat.glsl')) self.program_ms = Program.load(in_module('glsl/flat_ms.glsl')) self.use_program(self.resolution) self.stream = BufferStream(Vertex, GL_TRIANGLES)
def execute(self, program: Program): arg = self.args[0] if program.var_exists(arg): exit_app(exitCodes.SEMANTIC_ERROR, 'DEFVAR\nVariable {} now exists. Cannot redefine.', True) program.var_set('DEFVAR', arg, None, True)
def main(): parser = argparse.ArgumentParser(description='You started a proxy-script.' ' Enter your port to use ' 'this') parser.add_argument('-p', '--port', help='This will be your port') port = parser.parse_args().port prog = Program(port) prog.process()
def handle_program_status(): """ Expose the program status """ logging.debug("program_status") prog = Program("") if app.prog: prog = app.prog return json.dumps({'name': prog.name, "running": prog.is_running(), "log": app.prog_engine.get_log()})
class Commander(object): def __init__(self, program): self.program = Program(program) self.army = list() self.enemies = list() self.army_name = self.find_army_name() def find_army_name(self): try: name = self.do_find_army_name() except Exception: # If program fails to implement -n properly, just choose # a random name. name = 'army-%d'% random.randint(1,10000000) return name def do_find_army_name(self): arguments = ProgramArguments() reader = FileReader(self) output_filename = FileUtils.get_new_filename() arguments.add('-n') arguments.add('-o', output_filename) self.program.execute(arguments) name = reader.read_name(output_filename) FileUtils.remove_file(output_filename) return name def get_army_name(self): return self.army_name def get_army(self): return self.army def set_army(self, soldiers): map(self.set_army_on_soldier, soldiers) self.army = soldiers def set_army_on_soldier(self, soldier): army_name = self.get_army_name() soldier.set_army_name(army_name) def add_enemies(self, enemies): self.enemies.extend(enemies) def read_file_or_raise(self, filename, writer, context): reader = FileReader(context) try: data = reader.read(filename) except IOError: raise MissingFileException(self.army_name, self.program, writer.get_filename()) except ParsingException, e: e.set_army_name(self.army_name) raise e else:
def eval(self, text): """Respond to text entered by the user. :param text: the user's input """ program = Program(text, echo=self.echo, transforms=self.transforms) tokens = program.gen_tokens() for sentence in program.gen_sentences(tokens, self.aliases): if self.echo: self.terminal.debug(str(sentence)) program.interpret(sentence, self.commands)
def launch_f2c(self): is_running = False for p in psutil.process_iter(): try: if p.name() == "FlowchartToCode.exe": print "Flowchart To Code is already running" is_running = True except psutil.error: pass if not is_running: f2c = Program(self.f2c_path) f2c.start() print "program {} started".format(self.f2c_path)
def launch_dia(self): is_running = False for p in psutil.process_iter(): try: if p.name() == "dia.exe": print "Dia is already running" is_running = True except psutil.error: pass if not is_running: dia = Program(self.dia_path) dia.start() print "program {} started".format(self.dia_path)
def launch_intellij(self): is_running = False for p in psutil.process_iter(): try: if p.name() == "idea.exe": print "IntelliJ IDEA is already running" is_running = True except psutil.error: pass if not is_running: intellij = Program(self.intellij_path) intellij.start() print "program {} started".format(self.intellij_path)
class programTest(unittest.TestCase): def setUp(self): self.fixture = Program(1, 1, "-d 1".split(' '), FakeSyslog()) def test_default_options_are_set(self): fixture = self.fixture self.assertEqual('1', fixture.opts.keyid) self.assertEqual(None, fixture.opts.verbose) self.assertEqual('0000', fixture.opts.pin) self.assertEqual('/usr/lib/opensc-pkcs11.so', fixture.opts.module) self.assertEqual(None, fixture.opts.environment) self.assertEqual('localhost', fixture.opts.host) self.assertEqual(256, fixture.opts.inputlength) self.assertEqual(256, fixture.opts.outputlength) self.assertEqual('SHA512-RSA-PKCS', fixture.opts.mechanism) self.assertEqual(9999, fixture.opts.port) def test_keyid_can_be_given_with_d(self): self.fixture.parseArgs("-d 2222".split(' ')) self.assertEqual('2222', self.fixture.opts.keyid) def test_verbose_can_be_set_with_v(self): self.fixture.parseArgs("-d 1 -v".split(' ')) self.assertEqual(1, self.fixture.opts.verbose) def test_verbose_level_is_increased_with_all_v(self): self.fixture.parseArgs("-d 1 -vvvv".split(' ')) self.assertEqual(4, self.fixture.opts.verbose) def test_outputlength_is_set_by_o(self): self.fixture.parseArgs("-d 1 -o 511".split(' ')) self.assertEqual(511, self.fixture.opts.outputlength)
def execute_file(fname): program = Program(fname) state = ExecutionState() done = False try: while not done: pc = state.read_program_cntr() state.write_program_cntr(pc + 1) cmd = program.fetch(pc) if DEBUG_MODE: print "Executing: '"+str(cmd)+"'" done = cmd.execute(state) except Exception as e: print e finally: print "Stack:", str(state)
def load_programs_from_xml(xml_root, exercise_type_dict): program_dict = {} programs_node = xml_root.find("programs") for program_node in programs_node: program_name = program_node.get("name") program_description = program_node.get("description") program = Program(program_name, program_description) for action_node in program_node: action_exercise_name = action_node.get("exercise") action_exercise_type = exercise_type_dict[action_exercise_name] action_nb_series = int(action_node.get("nbSeries")) action_rest = int(action_node.get("rest")) action_min = int(action_node.get("min")) action_goal = int(action_node.get("goal")) program.add_action(action_exercise_type, action_nb_series, action_rest, action_min, action_goal) program_dict[program_name] = program return program_dict
class agent: def __init__(self, exe): self.exe = exe self.program = Program(self.exe, True) self.name = self.program.sendCommand("name").strip() self.lock = threading.Lock() def sendCommand(self, command): self.lock.acquire() answer = self.program.sendCommand(command) self.lock.release() return answer def reconnect(self): self.program.terminate() self.program = Program(self.exe,True) self.lock = threading.Lock()
def __init__(self, output, default_font, program=None): self.output = output self.default_font = default_font self.stream = VertexStream(fmt) self.textures = TextureCache() if program is None: self.program = Program.load(in_module('shaders/flat.glsl')) else: self.program = program
def create_program(self): self.command = 0 self.program = Program(self.display) self.program.add_command("^", "Forward", self.wheels.forwards, self.wheels.stop) self.program.add_command("v", "Backward", self.wheels.backwards, self.wheels.stop) self.program.add_command("<", "Left", self.wheels.left, self.wheels.stop) self.program.add_command(">", "Right", self.wheels.right, self.wheels.stop) self.program.add_command("{", "Slow Left", self.wheels.slow_left, self.wheels.stop) self.program.add_command("}", "Slow Right", self.wheels.slow_right, self.wheels.stop) self.add_component("Program", self.program)
def main(): app = None try: from program import Program # основной класс программы # Запуск приложения. app = Program() app.run() except Exception as exc: print(traceback.format_exc()) traceback.print_exc(file=open("{}/error.log".format( os.path.split(os.path.abspath(sys.argv[0]))[0]), "w")) if app: # очищаем экран приложения от всех виджетов app.start_screen.clear_widgets() class Error(App): """Выводит экран с текстом ошибки.""" def callback_report(self, *args): """Функция отправки баг-репорта""" try: import webbrowser import six.moves.urllib txt = six.moves.urllib.parse.quote( self.win_report.txt_traceback.text.encode( "utf-8")) url = "https://github.com/HeaTTheatR/KivyCleanMasterDemo" \ "/issues/new?body=" + txt webbrowser.open(url) except Exception: sys.exit(1) def build(self): self.win_report = BugReporter( callback_report=self.callback_report, txt_report=str(exc), icon_background="Data/Images/logo.png") return self.win_report Error().run()
class WrapperAgent(object): def __init__(self, executable, verbose=False): self.executable=executable self.program=Program(self.executable, verbose) self.name=self.program.sendCommand("name").strip() self.lock=threading.Lock() def sendCommand(self, command): self.lock.acquire() answer=self.program.sendCommand(command) self.lock.release() return answer def reconnect(self): self.program.terminate() self.program=Program(self.executable, True) self.lock=threading.Lock() def play_black(self, move): self.sendCommand("play black "+move) def play_white(self, move): self.sendCommand("play white "+move) def genmove_black(self): return self.sendCommand("genmove black").strip() def genmove_white(self): return self.sendCommand("genmove white").strip() def clear_board(self): self.sendCommand("clear_board") def set_board_size(self, size): self.sendCommand("boardsize "+repr(size)) def play_move_seq(self, moves_seq): turn=0 for m in moves_seq: self.play_black(m) if turn==0 else self.play_white(m) turn = (turn+1)%2
def mutate(self, programs_population): """ Generates mutation chances and mutate the team if it is a valid mutation. """ if Config.USER['advanced_training_parameters']['use_agressive_mutations']: mutation_chance = 1 while (mutation_chance > random.random() and len(self.programs) > Config.USER['training_parameters']['team_size']['min']): self._randomly_remove_program() mutation_chance = mutation_chance * Config.USER['training_parameters']['mutation']['team']['remove_program'] mutation_chance = 1 while (mutation_chance > random.random() and len(self.programs) < Config.USER['training_parameters']['team_size']['max']): self._randomly_add_program(programs_population) mutation_chance = mutation_chance * Config.USER['training_parameters']['mutation']['team']['add_program'] else: if len(self.programs) > Config.USER['training_parameters']['team_size']['min']: mutation_chance = random.random() if mutation_chance <= Config.USER['training_parameters']['mutation']['team']['remove_program']: self._randomly_remove_program() if len(self.programs) < Config.USER['training_parameters']['team_size']['max']: mutation_chance = random.random() if mutation_chance <= Config.USER['training_parameters']['mutation']['team']['add_program']: self._randomly_add_program(programs_population) to_mutate = [] while len(to_mutate) == 0: for program in self.programs: mutation_chance = random.random() if mutation_chance <= Config.USER['training_parameters']['mutation']['team']['mutate_program']: to_mutate.append(program) for program in to_mutate: clone = Program(self.generation, copy.deepcopy(program.instructions), program.action) clone.mutate() self._add_program(clone) programs_population.append(clone) if self._is_ok_to_remove(program): self.remove_program(program) return programs_population
def __init__(self): self.program = Program() self.vao = GLuint(0) self.vbuf = None self.ibuf = None self.vertices = [] self.normals = [] self.indices = [] self.uvs = [] # we should really be getting the camera not creating a new instance.. self.camera = Camera(800, 600) GameObject.__init__(self)
def test_failed_build(self): vert = VertexShader("A") frag = FragmentShader("B") program = Program(verts = vert) with self.assertRaises(ProgramException): program.build() program = Program(frags = frag) with self.assertRaises(ProgramException): program.build()
def test_failed_build(self): vert = VertexShader("A") frag = FragmentShader("B") program = Program(verts = vert) with self.assertRaises(ValueError): program.activate() program = Program(frags = frag) with self.assertRaises(ValueError): program.activate()
def loadProgram(self, fileName): """ Load the program in memory @param filename: file containing the code to execute @type filename: string """ try: self.program = Program() self.program.load(fileName, self) self.chip.setEndProgram(False) return True except MemError as e: e.display() return False except ProgramError: return False
def import_data(cls): filenm ='kegiatan.csv' with open(filenm, 'rb') as csvfile: reader = csv.DictReader(csvfile, delimiter=';', quotechar='"') for row in reader: print row kode = row['kode'].strip() data = cls.get_by_kode(kode) if not data: data=cls() data.kode = kode data.created = datetime.now() data.create_uid = 1 #data.tahun = data.created.year #data.level_id = data.kode.count('.')+1 #data.parent_id = DBSession.query(Rekening.id).filter(Rekening.kode==data.kode[:data.kode.rfind('.')]).scalar() data.disabled = 0 #data.defsign = 1 data.program_id=Program.get_by_kode(''.join([row['urusankd'].strip(),'.',row['programkd'].strip()])).id data.nama = row['nama'].strip() DBSession.add(data) DBSession.flush() DBSession.commit()
print "At least one of %s is alive" % GR_PROG_BIN result = True return result #### -------------- MAIN start ----------------#### # create the program processor. This # 1. accepts and process the command line options # 2. creates XML processing engine, that in turn # a) validates the XML file # b) extracts the DOM object tree # c) populates the GINI network class library # d) performs some semantic/syntax checkings on # the extracted specification myProg = Program(sys.argv[0], SRC_FILENAME) if (not myProg.processOptions(sys.argv[1:])): sys.exit(1) options = myProg.options # set the UML directory if is not given via -u option if (not options.umlDir): # set it to the directory pointed by the $UML_DIR env # if no such env variable, set the uml dir to curr dir if (os.environ.has_key("UML_DIR")): options.umlDir = os.environ["UML_DIR"] else: options.umlDir = "." # get the binaries binDir = options.binDir
from base import * from rekening import Rekening from rekening_hukum import DasarHukum from urusan import Urusan from fungsi import Fungsi from fungsi_urusan import FungsiUrusan from unit import Unit from program import Program from kegiatan import Kegiatan if __name__ == '__main__': Rekening.import_data() DasarHukum.import_data() Urusan.import_data() Fungsi.import_data() FungsiUrusan.import_data() Unit.import_data() Program.import_data() Kegiatan.import_data()
def __init__(self, app=None, name = "default"): info("Creating script") self.extension = "scr" Program.__init__(self, None) DictObj.__init__(self, "script", app, name) self.repr_blacklist += ["exit", "sleep_event", "freeze_event", "next_event_in"]
help="human plays first (if not present default to second)") parser.add_argument("--boardsize", "-b", type=int, help="side length of (square) board") parser.add_argument("--time", "-t", type=int, help="total time allowed for each move in seconds") args = parser.parse_args() if args.boardsize: boardsize = args.boardsize else: boardsize = 11 if args.time: time = args.time else: time = 10 agent = Program(args.program, False) agent.sendCommand("boardsize "+str(boardsize)) agent.sendCommand("set_time "+str(time)) human_game = gamestate(boardsize) game = gamestate(boardsize) winner = None moves = [] while(True): if(args.first): moves.append(get_human_move(game, human_game, "black")) if(game.winner() != game.PLAYERS["none"]): winner = game.winner() break print("waiting for opponent...")