def test_getTotalRows(self): data = self.getData() script = Script() expectedResult = 1 result = script.get_total_rows(data) self.assertEqual(expectedResult, result)
def do_POST(self): self.send_response(200) self.send_header('Access-Control-Allow-Origin', '*') self.end_headers() parsed_path = urlparse.urlparse(self.path) params = urlparse.parse_qs(parsed_path.query) ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} print parsed_path if parsed_path.path == '/heartbeat' : returnJson = {'status': 'ok'} elif parsed_path.path == '/completions': script = Script(postvars) script.display() returnJson = prophet.speak(script) else: returnJson = {'error': 'command ' + parsed_path.path + ' does not exist'} print "Returning", len(returnJson), "items" print self.wfile.write(json.dumps(returnJson, encoding = 'latin1'))
def setup_test(self): script = Script() script_config = ScriptConfig() when(script_config).get_location().thenReturn("./testFiles/") script.script_config = script_config return script
def test_getFileExtension(self): data = self.getData() script = Script() expectedResult = "py" result = script.get_file_extension(data) self.assertEqual(expectedResult, result)
def __init__(self, prev_tx, prev_index, script_sig=None, sequence=0xffffffff): self.prev_tx = prev_tx self.prev_index = prev_index if script_sig is None: # <1> self.script_sig = Script() else: self.script_sig = script_sig self.sequence = sequence
def test_getEigenschap(self): data = self.getData() script = Script() expectedResult = "Tokenize.py" result = script.get_property_from_data(data) self.assertEqual(expectedResult, result)
def initializePopulation(self, size, depth): list1 = [] for i in range(size): choose = random.randint(1, 5) Try = DSL() OK = Script(Try.initializeNumerous(choose, depth), i) list1.append(OK) OK.saveFile(path) return list1
def initializePopulation(size, generation, depth): list1 = [] # The following line is the directory on Rohan's computer, change # this to the directory where you would like to store your scripts. for i in range(size): choose = random.randint(1, 5) Try = DSL() OK = Script(Try.initializeNumerous(choose, depth), i) list1.append(OK) OK.saveFile(path) return list1
def loadScripts(self, dir): import sys sys.path.insert(0, "./scripts") from Script import Script s = Script(self, "test") from loading import Loading l = Loading(self.segments[0]) self.scripts.append(l) from TheaterChase import TheaterChase t = TheaterChase(self.segments[0]) self.scripts.append(t) from rainbow import Rainbow r = Rainbow(self.segments[0]) self.scripts.append(r) from LeftToRightRandom import LeftToRightRandom lr = LeftToRightRandom(self.segments[0]) self.scripts.append(lr) from RandomLed import RandomLed r = RandomLed(self.segments[0]) self.scripts.append(r) from Light import Light self.scripts.append(Light(self.segments[0])) from Test import Test self.scripts.append(Test(self.segments[0])) from Cycle import Cycle self.scripts.append(Cycle(self.segments[0])) from SingleColor import SingleColor self.scripts.append(SingleColor(self.segments[0]))
def script(self, **kwds): from Script import Script script = Script(**kwds) self.contents.append(script) return script
def sign_input(self, input_index, private_key): z = self.sig_hash(input_index) der = private_key.sign(z).der() sig = der + SIGHASH_ALL.to_bytes(1, 'big') sec = private_key.point.sec() self.tx_ins[input_index].script_sig = Script([sig, sec]) return self.verify_input(input_index)
def verify_input(self, input_index): # '''Returns whether the input has a valid signature''' # get the relevant input tx_in = self.tx_ins[input_index] # grab the previous ScriptPubKey script_pubkey = tx_in.script_pubkey(testnet=self.testnet) # check to see if the ScriptPubkey is a p2sh if script_pubkey.is_p2sh_script_pubkey(): # the last cmd has to be the RedeemScript to trigger cmd = tx_in.script_sig.cmds[-1] # parse the RedeemScript raw_redeem = int_to_little_endian(len(cmd), 1) + cmd redeem_script = Script.parse(BytesIO(raw_redeem)) # the RedeemScript might be p2wpkh or p2wsh if redeem_script.is_p2wpkh_script_pubkey(): z = self.sig_hash_bip143(input_index, redeem_script) witness = tx_in.witness elif redeem_script.is_p2wsh_script_pubkey(): cmd = tx_in.witness[-1] raw_witness = encode_varint(len(cmd)) + cmd witness_script = Script.parse(BytesIO(raw_witness)) z = self.sig_hash_bip143(input_index, witness_script=witness_script) witness = tx_in.witness else: z = self.sig_hash(input_index, redeem_script) witness = None else: # ScriptPubkey might be a p2wpkh or p2wsh if script_pubkey.is_p2wpkh_script_pubkey(): z = self.sig_hash_bip143(input_index) witness = tx_in.witness elif script_pubkey.is_p2wsh_script_pubkey(): cmd = tx_in.witness[-1] raw_witness = encode_varint(len(cmd)) + cmd witness_script = Script.parse(BytesIO(raw_witness)) z = self.sig_hash_bip143(input_index, witness_script=witness_script) witness = tx_in.witness else: z = self.sig_hash(input_index) witness = None # combine the current ScriptSig and the previous ScriptPubKey combined = tx_in.script_sig + script_pubkey # evaluate the combined script return combined.evaluate(z, witness)
def continue_saved_game(self): f = open("save.dat") data = f.read().split("\n") f.close() self.scripts = [Script(self, data[0])] if len(data) > 1: self.main.music.load_music(data[1]) self.main.music.begin() self.main.music.cue(int(data[2]), True) self.main.music.play_next()
def parse(cls, s): #Takes a byte stream and parses the tx_output at the start #return a TxOut object # amount is an integer in 8 bytes, little endian amount = little_endian_to_int(s.read(8)) # use Script.parse to get the ScriptPubKey script_pubkey = Script.parse(s) # return an instance of the class (see __init__ for args) return cls(amount, script_pubkey)
def mutate(script, j): Try = DSL() new = [] for i in range(len(script._strategies)): if random.randint(0, 1) == 0: new.append(Try.initialize('S', 3)) if random.randint(0, 1) == 0: new.append(Try.initialize('S', 3)) else: new.append(script._strategies[i]) if random.randint(0, 1) == 0: new.append(Try.initialize('S', 3)) # print('p') # print(new) Ok = Script(new, script._id + j) Ok.saveFile(path) return Ok
def runConverting(): tup = dialog.getPaths() folder = dialog.getFolderName() # Удаляем сообщения если есть lb.clearMessages() lb.destroyLables() # Проверяем выбран ли файлы if len(tup) == 0: return messagebox.showerror("Ошибка", "Необходимо выбрать файлы") script = Script(tup, folder) filename = script.run() # Удаляем сообщения об успешном выполнении и выводим сообщение об успешном завершении процесса lb.destroyLables() lb.addMessageToList( f'{filename} готов.\n Если в консоле нет ошибок, то все ок.', 6) lb.createLables(background='#2e8b57')
def main(): VERSION = '1.0.0/0213' if len(sys.argv) == 1 : consoleMode() else : outFile = None inFile = None for i in xrange(1,len(sys.argv)) : if sys.argv[i] == '-i' : inFile = Script(sys.argv[i+1],True) elif sys.argv[i] == '-o' : try: outFile = open(sys.argv[i+1],'w') except Exception as e : sys.stderr.write('ERROR I cannot open: ' + sys.argv[i+1] + '\nThe error was:\n') sys.stderr.write(str(e) + '\n') return elif sys.argv[i] == '--help' : sys.stdout.write( "1D5 Version: " + VERSION + "\n" + "The scriptable dice roller.\n"+ "Usage: python onedeefive.py [options]\n\n"+ "Options:\n"+ "-i <file name>\n"+ "\tRead input from the specified file.\n\n"+ "-o <file name>\n"+ "\twrite output to the specified file.\n\n"+ "--help\n"+ "\tPrint this message.\n" ) if not outFile is None : setOutput(outFile) if inFile is None : consoleMode() else : inFile.execute()
def consoleMode(): # initialize variables reading = False line = '' stack = list() context = dict() # read from the console while True: if reading: # we are reading a multi-line segment cur = sys.stdin.readline() if re.match(ENDREAD_STRING, cur) : reading = False script = Script(line) script.execute(stack,context) else : line = line + cur + '\n' else : # execute the single line we just read line = sys.stdin.readline() if re.match(READ_STRING,line) : reading = True line = '' elif re.match(EXIT_STRING,line): return else : script = Script(line) script.execute(stack,context)
class TxIn: def __init__(self, prev_tx, prev_index, script_sig=None, sequence=0xffffffff): self.prev_tx = prev_tx self.prev_index = prev_index if script_sig is None: self.script_sig = Script() else: self.script_sig = script_sig self.sequence = sequence def fetch_tx(self, testnet=False): return TxFetcher.fetch(self.prev_tx.hex(), testnet=testnet) def serialize(self): # Returns the byte serialization of the transaction input # serialize prev_tx, little endian result = self.prev_tx[::-1] # serialize prev_index, 4 bytes, little endian result += int_to_little_endian(self.prev_index, 4) # serialize the script_sig result += self.script_sig.serialize() # serialize sequence, 4 bytes, little endian result += int_to_little_endian(self.sequence, 4) return result def script_pubkey(self, testnet=False): # Get the ScriptPubKey by looking up the tx hash Returns a Script object # use self.fetch_tx to get the transaction tx = self.fetch_tx(testnet=testnet) # get the output at self.prev_index # return the script_pubkey property return tx.tx_outs[self.prev_index].script_pubkey @classmethod def parse(cls, s): # Takes a byte stream and parses the tx_input at the start. return a TxIn object # prev_tx is 32 bytes, little endian prev_tx = s.read(32)[::-1] # prev_index is an integer in 4 bytes, little endian prev_index = little_endian_to_int(s.read(4)) # use Script.parse to get the ScriptSig script_sig = Script.parse(s) # sequence is an integer in 4 bytes, little-endian sequence = little_endian_to_int(s.read(4)) # return an instance of the class (see __init__ for args) return cls(prev_tx, prev_index, script_sig, sequence)
def parse(cls, s): # Takes a byte stream and parses the tx_input at the start. return a TxIn object # prev_tx is 32 bytes, little endian prev_tx = s.read(32)[::-1] # prev_index is an integer in 4 bytes, little endian prev_index = little_endian_to_int(s.read(4)) # use Script.parse to get the ScriptSig script_sig = Script.parse(s) # sequence is an integer in 4 bytes, little-endian sequence = little_endian_to_int(s.read(4)) # return an instance of the class (see __init__ for args) return cls(prev_tx, prev_index, script_sig, sequence)
def parse(cls, s): '''Takes a byte stream and parses the tx_input at the start return a TxIn object ''' # prev_tx is 32 bytes, little endian # prev_index is an integer in 4 bytes, little endian # use Script.parse to get the ScriptSig # sequence is an integer in 4 bytes, little-endian # return an instance of the class (see __init__ for args) # raise NotImplementedError prev_tx = s.read(32)[::-1] prev_index = little_endian_to_int(s.read(4)) script_sig = Script.parse(s) sequence = little_endian_to_int(s.read(4)) return cls(prev_tx, prev_index, script_sig, sequence)
def __init__(self, file): self._script = Script(file) self._segment = self._script.getCurrentSegment() self._ruleString = self._segment.getNextRule() self._cursor = database.connect() self._repeat = 0 self._songcounter = -1 self._ruleNew = 1 timelist = time.localtime() if 'repeat' in self._ruleString: self._repeat = 1 print "Current Day: "+str(timelist[6])
class VisualizeVariablesController(object): file = File() script = Script() def load(self, path): return self.file.load(path) def get_criteria(self): return self.file.get_filter_criteria() def filter(self, levels_and_variables): return self.file.filter(json.loads(levels_and_variables)) def get_properties(self): return self.script.get_properties() def execute(self, data): return self.script.execute(data)
def __init__(self, glob): self.glob = glob self.symbols = { # Use one globalId for global vars. # 'globalId': glob.get_id_mgr(), # These keywords have run method to handle exec calls. # 'import' : Import(self.glob), 'script' : Script(self.glob), 'exec' : Exec(self.glob), 'replace': Replace(self.glob) } # Assign keywords for items in the table. # for key, value in self.symbols.iteritems(): value.assign_keyword(key)
def __init__(self,main): Script.__init__(self,main,"Test")
def __init__(self, main, name, updatesPerSecond): Script.__init__(self, main,name) self.updatesPerSecond = updatesPerSecond self.last = self.getTime()
def __init__(self,main): Script.__init__(self, main,"loading")
def __init__(self, main): Script.__init__(self, main, "Test")
def __init__(self, main): Script.__init__(self, main, "SingleColor") self.options.append( ScriptOption("color", "colorpicker", "150,0,150", []))
interaction.interact(lcond, lcons) interactionQ.remove(interaction) gp = piece.gridposition() piece.position = piece.space.grid.g[gp[X]][gp[Y]].center() if ((piece.gridposition()[Y] == WHITEEDGE and piece.team.name == 'blacks') or (piece.gridposition()[Y] == BLACKEDGE and piece.team.name == 'whites')): piece.promotion() piece.latency = (max(piece.latency - 1, 0) if piece.latency != -1 else -1) p = piece.gridposition() lp = piece.lastgridposition if p != lp: GameObject.game.space.grid.g[lp[X]][lp[Y]].removeObject(piece) GameObject.game.space.grid.g[p[X]][p[Y]].addObject(piece) piece.lastgridposition = p def onInteraction(piece, interaction): if interaction.interactionid in piece.interactiondomain: piece.addInteraction(interaction, None, piece, piece) return True return False piecebehavior = lambda owner: Script(owner, onCreate, onUpdate, onCollision, onInteraction)
def __init__(self, main): Script.__init__(self, main,"TheaterChase")
def __init__(self, main): Script.__init__(self, main, "TheaterChase")
def __init__(self, main): Script.__init__(self, main, "Cycle") self.j = 0
def __init__(self, main): Script.__init__(self, main, "Light")
def __init__(self, main): Script.__init__(self, main,"Rainbow")
def __init__(self, main): Script.__init__(self, main, "SingleColor") self.options.append(ScriptOption("color", "colorpicker","150,0,150",[]))
class TxIn: def __init__(self, prev_tx, prev_index, script_sig=None, sequence=0xffffffff): self.prev_tx = prev_tx self.prev_index = prev_index if script_sig is None: # <1> self.script_sig = Script() else: self.script_sig = script_sig self.sequence = sequence def __repr__(self): return '{}:{}'.format( self.prev_tx.hex(), self.prev_index, ) # end::source2[] @classmethod def parse(cls, s): '''Takes a byte stream and parses the tx_input at the start return a TxIn object ''' # prev_tx is 32 bytes, little endian # prev_index is an integer in 4 bytes, little endian # use Script.parse to get the ScriptSig # sequence is an integer in 4 bytes, little-endian # return an instance of the class (see __init__ for args) # raise NotImplementedError prev_tx = s.read(32)[::-1] prev_index = little_endian_to_int(s.read(4)) script_sig = Script.parse(s) sequence = little_endian_to_int(s.read(4)) return cls(prev_tx, prev_index, script_sig, sequence) # tag::source5[] def serialize(self): '''Returns the byte serialization of the transaction input''' result = self.prev_tx[::-1] result += int_to_little_endian(self.prev_index, 4) result += self.script_sig.serialize() result += int_to_little_endian(self.sequence, 4) return result # end::source5[] # tag::source8[] def fetch_tx(self, testnet=False): return TxFetcher.fetch(self.prev_tx.hex(), testnet=testnet) def value(self, testnet=False): '''Get the output value by looking up the tx hash. Returns the amount in satoshi. ''' tx = self.fetch_tx(testnet=testnet) return tx.tx_outs[self.prev_index].amount def script_pubkey(self, testnet=False): '''Get the ScriptPubKey by looking up the tx hash. Returns a Script object. ''' tx = self.fetch_tx(testnet=testnet) return tx.tx_outs[self.prev_index].script_pubkey
def __init__(self, main): Script.__init__(self, main,"Cycle") self.j = 0
def start_new_game(self): self.scripts.insert(0, Script(self, "level1/main_script"))
def __init__(self, main): Script.__init__(self, main, "Rainbow")
def __init__(self, main): Script.__init__(self, main,"LeftToRightRandom") self.colors = []#[PColor(main,Color(255,0,0))]
def __init__(self, main): Script.__init__(self, main,"Random")
import sys import r2pipe from Script import Script r2 = r2pipe.open("./a.out") display = "variables" analysis = Script() analysis.analyzeFile(r2, display)
class Scheduler: def __init__(self, file): self._script = Script(file) self._segment = self._script.getCurrentSegment() self._ruleString = self._segment.getNextRule() self._cursor = database.connect() self._repeat = 0 self._songcounter = -1 self._ruleNew = 1 timelist = time.localtime() if 'repeat' in self._ruleString: self._repeat = 1 print "Current Day: "+str(timelist[6]) def getNextFile(self): while 1: #print "getting file" #Check for stopped status while 1: self._cursor.execute('select switch from commands where type="1"') result = self._cursor.fetchone() if result["switch"] == "0": time.sleep(1) else: break #Check to see if any time left in segment if self._segment.getTimeLeft() <= 0: #No time left, go to next segment self._repeat = 0 self._songcounter = 0 self._segment = self._script.getNextSegment() self._ruleString = self._segment.getNextRule() self._ruleNew = 1 else: #time left if self._repeat == 0 and self._songcounter == 0: #no repeating, just get next rule self._ruleString = self._segment.getNextRule() self._ruleNew = 1 print "Got Next Rule: "+self._ruleString elif self._songcounter > 0: #song counter, drop it down one print "Song Counter Minus: ", self._songcounter -= 1 print self._songcounter #Now we have to interprate the rule if 'repeat' in self._ruleString: self._repeat = 1 self._songcounter = 0 self._ruleNew = 0 rule = self._ruleString.split('"') parameter = rule[-2:] #print parameter if self._ruleNew == 1: print "Set counter" if parameter[-1] != '' and self._repeat != 1: self._songcounter = int(parameter[-1])-1 print "Sound counter Set: "+str(self._songcounter) else: self._songcounter = 0 self._ruleNew = 0 del parameter[-1] del rule[-2:] rule = rule[0].split() import sys if rule[0] == 'random': print "Random Rule" if rule[1] == 'genre': print "Genre: "+str(parameter[0]) print "Counter: "+str(self._songcounter) sql = 'select f.path,f.title,f.artist from files f, genres g where f.id = g.id and g.genre = "'+parameter[0]+'"and f.length <= "'+str(self._segment.getTimeLeft())+'" ORDER BY RAND() LIMIT 1' print sql self._cursor.execute(sql) if self._cursor.rowcount == 0: print "No song: "+parameter[0] #No song can fit into our timeframe, goto next segment self._repeat = 0 self._songcounter = -1 self._segment = self._script.getNextSegment() self._ruleString = self._segment.getNextRule() self._ruleNew = 1 continue #Get our row row = self._cursor.fetchone() #log our song log.addLog(row["artist"],row["title"],self._cursor) return row["path"] if rule[1] == 'comment': print "Comment" sql = 'select path,title,artist from files where comment = "'+parameter[0]+'"and length <= "'+str(self._segment.getTimeLeft())+'" ORDER BY RAND() LIMIT 1' print sql self._cursor.execute(sql) if self._cursor.rowcount == 0: print "No song: "+parameter[0] #No song can fit into our timeframe, goto next segment self._repeat = 0 self._songcounter = -1 self._segment = self._script.getNextSegment() self._ruleString = self._segment.getNextRule() self._ruleNew = 1 continue #Get our row row = self._cursor.fetchone() #log our song log.addLog(row["artist"],row["title"],self._cursor) return row["path"] elif rule[0] == 'title': print "Title" sql = 'select path,title,artist from files where title = "'+parameter[0]+'"' print sql self._cursor.execute(sql) if self._cursor.rowcount == 0: print "Why" print "No song: "+parameter[0] #No song found self._repeat = 0 self._songcounter = -1 self._segment = self._script.getNextSegment() self._ruleString = self._segment.getNextRule() self._ruleNew = 1 continue #Get our row row = self._cursor.fetchone() #log our song log.addLog(row["artist"],row["title"],self._cursor) return row["path"] elif rule[0] == 'filelist': pass def changeScript(self): pass