def variable_assignments( self, *, ontology: Ontology, object_variables: AbstractSet["TemplateObjectVariable"], property_variables: AbstractSet["TemplatePropertyVariable"], action_variables: AbstractSet["TemplateActionTypeVariable"], chooser: SequenceChooser, # pylint: disable=unused-argument ) -> Iterable[TemplateVariableAssignment]: # TODO: fix hard-coded rng # https://github.com/isi-vista/adam/issues/123 rng = Random() rng.seed(0) for object_combination in self._all_combinations(object_variables, ontology=ontology, rng=rng): for property_combination in self._all_combinations( property_variables, ontology=ontology, rng=rng): for action_combination in self._all_combinations( action_variables, ontology=ontology, rng=rng): yield TemplateVariableAssignment( object_variables_to_fillers=object_combination, property_variables_to_fillers=property_combination, action_variables_to_fillers=action_combination, )
def __init__(self, seed): mt = [0] * 624 mt[0] = p = seed & 0xffffffff for mti in six.moves.range(1, 624): mt[mti] = p = (1812433253 * (p ^ (p >> 30)) + mti) & 0xffffffff mt.append(624) self.random = Random() self.random.setstate(tuple(mt))
def manufactureLists(): # for i in range(0,Player.moveB.len()): # Player.moveB.(i) = MoveEntry.MoveEntry(move=i,points = 100) rand = Random() for i in range (0,len(Player.moveArray)): tempL = Player.moveArray[i] for j in range(0,len(tempL)): tempL[j] = MoveEntry(move=tempL[j], points = 100*rand.random())
class MT19937(object): def __init__(self, seed): mt = [0] * 624 mt[0] = p = seed & 0xffffffff for mti in six.moves.range(1, 624): mt[mti] = p = (1812433253 * (p ^ (p >> 30)) + mti) & 0xffffffff mt.append(624) self.random = Random() self.random.setstate(tuple(mt)) def __call__(self): return self.random.getrandbits(32)
def assignList (self): if len(Player.usedMoveArrayIndices) == 4: Player.usedMoveArrayIndices.clear() rand = Random() randomValue = int(rand.random() * 4) while Player.usedMoveArrayIndices.__contains__(randomValue): randomValue = int(rand.random() * 4) Player.usedMoveArrayIndices.add(randomValue) self.moves = Player.moveArray[randomValue]
def gen_keys(): r = Random() min_p = (10**4) * (1 + 100 * r.random()) min_q = (10**4) * (1 + 100 * r.random()) p = first_prime_after(min_p) q = first_prime_after(min_q) T = (p - 1) * (q - 1) N = p * q E = 65537 #mcd(E,T)==1 and E < T D = modinv(E, T) #D*E = 1 (mod T) return dict(public=[E, N], private=[D, N])
def makeRandomSequence(): '''Genera una sequenza casuale di 3 bit e la memorizza nell'attributo app.sequence.''' tmp = bin(Random().getrandbits(3))[2:] while len(tmp) < 3: tmp = "0" + tmp print(tmp) app.sequence = list(tmp)
def build(field_model_l: [FieldModel], constraint_l: [ConstraintModel], rng=None) -> RandInfo: if rng is None: rng = Random() builder = RandInfoBuilder(rng) # First, collect all the fields builder._pass = 0 for fm in field_model_l: fm.accept(builder) # Now, build the randset builder._pass = 1 builder._used_rand = True # Visit the field objects passed in, as well # as their constraints for fm in field_model_l: fm.accept(builder) # Visit standalone constraints passed to the function for c in constraint_l: c.accept(builder) # for rs in builder._randset_s: # print("RS: " + str(rs)) # for c in rs.constraint_s: # print("RS Constraint: " + str(c)) return RandInfo(list(builder._randset_s), list(builder._field_s))
def setUp(self): self._rand = Random(self._defaultSeed) if self.rtl_simulator_cls is not None: # if the simulator is not compiled it is expected # that it will be compiled in the test and this functio # will be called later self.restartSim()
def __init__(self, classifierName, classifierArgs, numFolds=10, parallel=1, metric='roc_auc', getCV=None, preDispatch='2*n_jobs', classifyHidden=False, steps=10, seed=2): super(LearningCurve, self).__init__(classifierName, classifierArgs, numFolds, parallel, metric, getCV, preDispatch, classifyHidden) self.steps = steps self.random = Random(seed) self.thresholds = None self.currentCutoff = None self.saveExtra = False
def addBunnies(self, num=500): data = {"components":[ { "type":"Sprite", "file":u"images/wabbit_alpha.png", "x": 0, "y": 0 }, ]} r = Random() for x in range(0,num): bunny = Entity.create(id = 'bunny %d' % x, scene=self, **data) if self.firstBunny is None: self.firstBunny = bunny if self.lastBunny is not None: self.lastBunny.nextBunny = bunny bunny.x = r.random()*self.size['width'] bunny.y = self.size['height'] bunny.speedx = int(r.random()*70.0) - 35 bunny.speedy = int(r.random()*70.0) bunny.angle = 90 - r.random() * 90 bunny.z = int(r.random()*100) bunny.nextBunny = None self.lastBunny = bunny self.entities[bunny.id] = bunny Gilbert().startEntity(bunny) self.nBunnies+=num fps = self.getComponent("fps") if fps != None: fps.text = str(self.nBunnies)
def simpleRandomizationProcess(tc: SimTestCase, agent, timeQuantum=CLK_PERIOD): seed = tc._rand.getrandbits(64) random = Random(seed) def randomEnProc(): # small space at start to modify agents when they are inactive yield Timer(timeQuantum / 4) while True: en = random.random() < 0.5 if agent.getEnable() != en: agent.setEnable(en) delay = int(random.random() * 2) * timeQuantum yield Timer(delay) return randomEnProc
def simpleRandomizationProcess(self, agent): seed = self._rand.getrandbits(64) random = Random(seed) timeQuantum = 10 * Time.ns # default clk period def randomEnProc(sim): # small space at start to modify agents when they are inactive yield sim.wait(timeQuantum / 4) while True: en = random.random() < 0.5 if agent.getEnable() != en: agent.setEnable(en, sim) delay = int(random.random() * 2) * timeQuantum yield sim.wait(delay) return randomEnProc
class LearningCurve(Classification): def __init__(self, classifierName, classifierArgs, numFolds=10, parallel=1, metric='roc_auc', getCV=None, preDispatch='2*n_jobs', classifyHidden=False, steps=10, seed=2): super(LearningCurve, self).__init__(classifierName, classifierArgs, numFolds, parallel, metric, getCV, preDispatch, classifyHidden) self.steps = steps self.random = Random(seed) self.thresholds = None self.currentCutoff = None self.saveExtra = False def subsample(self, array, thresholds, cutoff): indices = [] assert array.shape[0] == len(thresholds) for i in range(len(thresholds)): if thresholds[i] < cutoff: indices.append(i) return array[indices] def _getResult(self, setName, classifier, cv, params, score=None, fold=None, mean_score=None, scores=None, extra=None): result = super(LearningCurve, self)._getResult(setName=setName, classifier=classifier, cv=cv, params=params, score=score, fold=fold, mean_score=mean_score, scores=scores, extra=extra) result["cutoff"] = self.currentCutoff result["step"] = self.currentStep return result def _insert(self, tableName, rows): if tableName == "result": tableName = "learning_curve" super(LearningCurve, self)._insert(tableName, rows) def classify(self): self.indices, X_train, X_hidden, y_train, y_hidden = self._splitData() thresholds = [self.random.random() for x in y_train] for i in range(self.steps): print "----------------------", "Learning curve step", i + 1, "----------------------" self.currentCutoff = float(i + 1) / self.steps self.currentStep = i print "Cutoff", self.currentCutoff y_sample = self.subsample(y_train, thresholds, self.currentCutoff) X_sample = self.subsample(X_train, thresholds, self.currentCutoff) if "class" in self.meta.db.tables: print "Classes y_sample = ", countUnique(y_sample) search = self._crossValidate(y_sample, X_sample, self.classifyHidden and (X_hidden.shape[0] > 0)) if self.classifyHidden: self._predictHidden(y_hidden, X_hidden, search, y_sample.shape[0]) self.currentCutoff = None self.indices = None
def build( field_model_l : [FieldModel], constraint_l : [ConstraintModel], rng=None) ->RandInfo: if rng is None: rng = Random() builder = RandInfoBuilder(rng) # First, collect all the fields builder._pass = 0 for fm in field_model_l: fm.accept(builder) builder._randset_s.clear() builder._randset_field_m.clear() # Create rand sets around explicitly-ordered fields for i,o in enumerate(builder._order_l): s = RandSet(i) s.field_s.add(o) builder._randset_s.add(s) builder._randset_field_m[o] = s # Now, build the randset builder._pass = 1 builder._used_rand = True # Visit the field objects passed in, as well # as their constraints for fm in field_model_l: fm.accept(builder) # Visit standalone constraints passed to the function for c in constraint_l: c.accept(builder) # for rs in builder._randset_s: # print("RS: " + str(rs)) # for c in rs.constraint_s: # print("RS Constraint: " + str(c)) randset_l = list(builder._randset_s) randset_l.sort(key=lambda e:e.order) return RandInfo(randset_l, list(builder._field_s))
def __init__(self,x, y, vx, vy): self.rand=None self.model = {"walls" : {"left":0, "top":0, "right": 500, "bottom": 300}, "elastity" : -0.2, "ballRadius" : 26, "maxSpeed" : 3.0 } # default provisioning self.rand=Random() if (x == None) : Threading.Thread.Sleep(15) x = (self.model["walls"]["right"] - self.model["walls"]["left"] - 2*self.model["ballRadius"])* self.rand.random() y = (self.model["walls"]["bottom"] - self.model["walls"]["top"] - 2*self.model["ballRadius"])* self.rand.random() vx = 2*self.model["maxSpeed"]* self.rand.random() - self.model["maxSpeed"] vy = 2*self.model["maxSpeed"]* self.rand.random() - self.model["maxSpeed"] self._x = x self._y = y self._vx = vx self._vy = vy self._r = self.model["ballRadius"] # d = 52 px self._d = 2*self._r self._d2 = self._d*self._d
return key[0] def num(x): r = 0 for i in x: r *= 16 r += int(i, 4) return r def v(a, b): return int(a, 4) * 16 + int(b, 4) r = Random() rand = r.getrandbits stack = [] carry = 0 labels = {} ints = [] idx = 0 for x in data: if x: ints.append(x[0]) if x[0] == "10": labels[num(x[1:])] = idx else:
def predict(self, x_test): randObj = Random() retArr = [] for _ in range(0,len(x_test)): retArr.append(int(randObj.random()*3)) return numpy.asarray(retArr)
''' Exception |- ScriptError |- LoadError |- SyntaxError |- StandardError |- IOError |- TyperError |- ZeroDivisionError |- RuntimeError |- MyStdError |- MyException ''' from _random import Random rnd = Random() def randomly_choose(l): if l: return l[int(rnd.random() * len(l))] else: return None class Ex: def __init__(self, name): self.name = name self.children = [] self.parent = None def add_child(self, ex): self.children.append(ex)
''' Modified on Apr 28, 2018 In questo programma si assume che lo studente NON sappia usare le funzioni di Flask per leggere i dati del request. Questo programma FUNZIONA solo con un giocatore alla volta! @author: posenato ''' from _random import Random from flask import Flask app = Flask("Gioco") # Alcune variabili dell'applicazione per rappresentare lo stato e le costanti del gioco. app.rnd = Random() app.rnd.seed() app.sequence = [0, 0, 0] app.seqMaxIndex = 2 app.index = 0 app.moves = 0 app.maxAllowedMoves = 10 # Le seguenti variabili (in realtà costanti stringa) sono per scrivere pezzi di codice HTML in modo semplice # Sono variabili di MODULO! head = """<!DOCTYPE html> <html> <head> <title>Piccolo gioco</title> <style type="text/css"> form, input { padding: 2px; width: auto;
def setUp(self): self._rand = Random(self._defaultSeed)
class SimTestCase(unittest.TestCase): """ This is TestCase class contains methods which are usually used during hdl simulation. :attention: self.model, self.procs has to be specified before running doSim (you can use prepareUnit method) """ _defaultSeed = 317 _rand = Random(_defaultSeed) def getTestName(self): className, testName = self.id().split(".")[-2:] return "%s_%s" % (className, testName) def doSim(self, time): outputFileName = "tmp/" + self.getTestName() + ".vcd" d = os.path.dirname(outputFileName) if d: os.makedirs(d, exist_ok=True) with open(outputFileName, 'w') as outputFile: # return _simUnitVcd(simModel, stimulFunctions, outputFile=f, time=time) sim = HdlSimulator() # configure simulator to log in vcd sim.config = VcdHdlSimConfig(outputFile) # run simulation, stimul processes are register after initial initialization sim.simUnit(self.model, time=time, extraProcesses=self.procs) return sim def dumpHdlTestbench(self, time, file=None): if file: outputFileName = file else: outputFileName = "tmp/" + self.getTestName() + "_tb.vhd" d = os.path.dirname(outputFileName) if d: os.makedirs(d, exist_ok=True) with open(outputFileName, 'w') as outputFile: # return _simUnitVcd(simModel, stimulFunctions, outputFile=f, time=time) sim = HdlSimulator() # configure simulator to log in vcd sim.config = HdlSimConfigVhdlTestbench(self.u) # run simulation, stimul processes are register after initial initialization sim.simUnit(self.model, time=time, extraProcesses=self.procs) sim.config.dump(outputFile) return sim def assertValEqual(self, first, second, msg=None): if isinstance(first, SimSignal): first = first._val if not isinstance(first, int) and first is not None: first = valToInt(first) return unittest.TestCase.assertEqual(self, first, second, msg=msg) def assertEmpty(self, val, msg=None): return unittest.TestCase.assertEqual(self, len(val), 0, msg=msg) def assertValSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """ An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: :param seq1: can contain instance of values or nested list of them :param seq2: items are not converted :param seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. :param msg: Optional message to use on failure instead of a list of differences. """ seq1 = allValuesToInts(seq1) if seq_type is not None: seq_type_name = seq_type.__name__ if not isinstance(seq1, seq_type): raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))) if not isinstance(seq2, seq_type): raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2))) else: seq_type_name = "sequence" differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = 'First %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = 'Second %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: if seq1 == seq2: return differing = '%ss differ: %s != %s\n' % ( (seq_type_name.capitalize(), ) + _common_shorten_repr(seq1, seq2)) for i in range(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ( '\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ( '\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if item1 != item2: differing += ('\nFirst differing element %d:\n%s\n%s\n' % ((i, ) + _common_shorten_repr(item1, item2))) break else: if (len1 == len2 and seq_type is None and type(seq1) != type(seq2)): # The sequences are the same, but have differing types. return if len1 > len2: differing += ('\nFirst %s contains %d additional ' 'elements.\n' % (seq_type_name, len1 - len2)) try: differing += ('First extra element %d:\n%s\n' % (len2, safe_repr(seq1[len2]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of first %s\n' % (len2, seq_type_name)) elif len1 < len2: differing += ('\nSecond %s contains %d additional ' 'elements.\n' % (seq_type_name, len2 - len1)) try: differing += ('First extra element %d:\n%s\n' % (len1, safe_repr(seq2[len1]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = '\n' + '\n'.join( difflib.ndiff( pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def randomize(self, intf): """ Randomly disable and enable interface for testing purposes """ self.procs.append( agent_randomize(intf._ag, 50 * Time.ns, seed=self._rand.getrandbits(64))) def prepareUnit(self, unit, modelCls=None, dumpModelIn=None, onAfterToRtl=None): """ Create simulation model and connect it with interfaces of original unit and decorate it with agents and collect all simulation processes :param unit: interface level unit which you wont prepare for simulation :param modelCls: class of rtl simulation model to run simulation on, if is None rtl sim model will be generated from unit :param dumpModelIn: folder to where put sim model files (if is None sim model will be constructed only in memory) :param onAfterToRtl: callback fn(unit) which will be called unit after it will be synthesised to rtl """ self.u, self.model, self.procs = simPrepare(unit, modelCls=modelCls, dumpModelIn=dumpModelIn, onAfterToRtl=onAfterToRtl) def setUp(self): self._rand.seed(self._defaultSeed)
class testUtil: m_instantiated = False m_random = Random() m_ref_array_count = 16 # arbitrary number m_ref_array_index = 0 m_ref_array_list = [] m_patterned_not_random_arrays = True m_page_size = 256 # eeprom page size (universal) m_trace_buffer = [] m_trace_protect_index = 0 m_detail_trace = False m_display_trace = False m_detail_echo = False m_display_echo = False m_trace_echo = False m_log_file = None m_log_to_file = False m_log_to_file = False m_file_log_buffer_depth = 0 m_file_log_buffer_lines = 0 m_trace_enabled = False m_page_arrays_built = False _instance = None def __new__(cls): if cls._instance is None: print('Creating the testUtil object') cls._instance = super(testUtil, cls).__new__(cls) cls.m_random = random.Random() cls.m_random.seed(2000) cls.m_page_arrays_built = False return cls._instance def fatalError(self, reason): fatal_msg = "Fatal : " + reason if self.traceEnabled(): self.bufferTraceInfo(fatal_msg) self.dumpTraceBuffer() else: print(fatal_msg) sys.exit(-1) def flushLogfileBuffer(self): if len(self.m_file_log_buffer) > 0: for line in self.m_file_log_buffer: self.m_log_file.write(line + "\n") self.m_file_log_buffer = [] self.m_file_log_buffer_lines = 0 def openLogfile(self, file_path): datetime_string = time.strftime("%Y%m%d-%H%M%S") file_name = "SpiReadTest_%s.log" % datetime_string file_pathname = file_path + "/" + file_name self.m_log_file = open(file_pathname, "w+") self.m_file_log_buffer_depth = 200 self.m_file_log_buffer_lines = 0 self.initLogfileBuffer(200) self.bufferLogfileLine("SPI EEPROM Read Test Log: " + file_name) self.flushLogfileBuffer() return self.m_log_file ''' except IOError as e: print("Open or Write Failure to %s: %s" %(file_pathname, e)) self.fatalError("File I/O Error") finally: return ''' def closeLogFile(self): self.flushLogfileBuffer() self.m_log_file.close() def enableLogfile(self): if self.m_log_file != None: self.m_log_to_file = True def disableLogfile(self): if self.m_log_file != None: self.m_log_to_file = False def initLogfileBuffer(self, buffer_depth=None): if buffer_depth != None: self.m_file_log_buffer_depth = buffer_depth self.m_file_log_buffer = [] def bufferLogfileLine(self, string_info): self.m_file_log_buffer.append(string_info) self.m_file_log_buffer_lines += 1 if self.m_file_log_buffer_lines == self.m_file_log_buffer_depth: self.flushLogfileBuffer() self.m_file_log_buffer_lines = 0 def traceEnabled(self): return self.m_trace_enabled def setTraceBufferDepth(self, trace_depth): self.m_trace_depth = trace_depth def initTraceBuffer(self, trace_depth=0): self.m_trace_buffer = [] self.m_trace_enabled = True self.m_trace_depth = trace_depth self.m_trace_protect_depth = 0 ''' protectTraceBuffer locks the initial contents into the Trace Buffer sets the flush index data in the trace buffer when this function is called will NEVER be flushed until initTraceBuffer. The Trace Depth is measured from the end of the protect index. ''' def protectTraceBuffer(self): if self.m_trace_enabled: self.m_trace_protect_depth = self.m_trace_depth def disableTrace(self): self.m_trace_enabled = False def detailTraceOff(self): if self.m_trace_enabled: self.m_detail_trace = False def displayTraceOff(self): if self.m_trace_enabled: self.m_display_trace = False def detailTraceOn(self): if self.m_trace_enabled: self.m_detail_trace = True def displayTraceOn(self): if self.m_trace_enabled: self.m_display_trace = True def bufferDisplayInfo(self, string_info, echo=True): if self.m_display_trace: self.bufferTraceInfo(string_info, echo or self.m_display_echo) def bufferDetailInfo(self, string_info, echo=False): if self.m_detail_trace: self.bufferTraceInfo(string_info, echo or self.m_detail_echo) def bufferTraceInfo(self, string_info, echo=False): if self.m_trace_enabled: if self.m_trace_depth > 0: if len(self.m_trace_buffer) >= (self.m_trace_depth + self.m_trace_protect_depth): self.m_trace_buffer.pop(self.m_trace_protect_depth) if self.m_trace_echo or echo: print(string_info) self.m_trace_buffer.append(string_info) if self.m_log_to_file: self.bufferLogfileLine(string_info) def flushTraceBuffer(self): if self.m_trace_enabled: self.m_trace_buffer = self.m_trace_buffer[:self. m_trace_protect_depth] def traceEchoOn(self): self.m_trace_echo = True def traceEchoOff(self): self.m_trace_echo = False def detailEchoOn(self): self.m_detail_echo = True def detailEchoOff(self): self.m_detail_echo = False def dumpTraceBuffer(self): if self.m_trace_enabled: if len(self.m_trace_buffer) > 0: print("******TRACE BUFFER DUMP ******") index = 0 for entry in self.m_trace_buffer: print("%04d %s" % (index, entry)) index += 1 return True return False def ipString(self, ip_integer): integer = ip_integer ipString_buf = "" for index in range(0, 4): if index > 0: ipString_buf = "." + ipString_buf octet = int((ip_integer >> ((3 - index) * 8)) & 0xff) integer >>= 8 octet_string = format(octet, "d") ipString_buf = octet_string + ipString_buf return ipString_buf def zeroedArray(self, array_size): zero_array = array_u08(array_size) return zero_array def randomizeList(self, reference_list): element_count = len(reference_list) if element_count <= 1: # NULL and Single Item List already Randomized return reference_list ordinals = [None] * element_count reorder_indices = [] for index in range(element_count): test_index = self.m_random.randint(0, element_count) if ordinals[test_index] == test_index: continue else: ordinals[test_index] = test_index reorder_indices.append[test_index] if len(reorder_indices) == element_count: break reordered_list = [None] * element_count for index in reordered_list: reordered_list[index] = reference_list[reorder_indices[index]] return reordered_list pass class pagePatternGenerator(object): m_index = None m_recurrence_page = None m_page_size = None m_max_value = None m_max_index = None m_frequency_1 = None m_frequency_2 = None def __init__(self, recurrence_page, page_size, max_value): self.m_index = 0 self.m_recurrence_page = recurrence_page self.m_page_size = page_size self.m_max_value = max_value self.m_max_index = page_size * recurrence_page self.m_frequency_1 = 1 / self.m_max_index self.m_frequency_2 = 10 / page_size def initPatternNumber(self): self.m_pattern_index = 0 def incrementIndex(self): self.m_index += 1 if self.m_index == self.m_max_index: self.m_index = 0 def nextPatternNumber(self): sin_1 = math.sin(2 * self.m_index * math.pi * self.m_frequency_1) sin_2 = math.sin(2 * self.m_index * math.pi * self.m_frequency_2) self.incrementIndex() num = math.sqrt(math.fabs(sin_1 + sin_2) / 2) num = num * self.m_max_value return int(num) m_pattern_generator = None class referenceArraySequence(object): def __init__(self, array_list): self.m_max_index = len(array_list) - 1 self.m_base_index = 0 self.m_reference_index = 0 self.m_array_size = len(array_list[0]) self.m_array_count = len(array_list) self.m_array_list = array_list self.m_sequence_byte_length = self.m_array_size * self.m_array_count def firstIndex(self): self.m_reference_index = self.m_base_index return self.m_reference_index def currentIndex(self): return self.m_reference_index def nextIndex(self): self.m_reference_index += 1 if self.m_reference_index > self.m_max_index: self.m_reference_index = self.m_base_index def pageSize(self): return self.m_array_size def firstAddress(self): return self.m_array_size * self.firstIndex() def currentAddress(self): return self.m_reference_index * self.m_array_size def nextAddress(self): return self.m_array_size * self.nextIndex() def indexOfAddress(self, array_address): return array_address // self.m_array_size def arrayAtIndex(self, index): return self.m_array_list[index] def arrayAtAddress(self, array_address): modaddress = array_address % self.m_sequence_byte_length return self.m_array_list[self.indexOfAddress(modaddress)] def firstArray(self): return self.arrayAtIndex(self.firstIndex()) def currentArray(self): return self.arrayAtIndex(self.currentIndex()) def nextArray(self): return self.arrayAtIndex(self.nextIndex()) def addressForArrayIndex(self, index): modindex = index % self.m_array_count return modindex * self.m_array_size def setIndex(self, index): self.m_reference_index = index def setIndexByAddress(self, address): self.m_reference_index = self.indexOfAddress(address) ''' referenceArrayIndex() the reference array set is finite in page-array length it is written recurrently throughout the memory space compute the page array index matching a memory page start address ''' def referenceArrayIndex(self, start_address): if start_address % 256 != 0: self.fatalError( "referenceArrayIndex: start_address not on page boundary") return (start_address // 256) % self.m_ref_array_count def generatePatternedArray(self, array_size): if self.m_pattern_generator == None: self.m_pattern_generator = self.pagePatternGenerator( self.m_ref_array_count, 256, 255) patterned_array = array_u08(array_size) for index in range(array_size): patterned_array[ index] = self.m_pattern_generator.nextPatternNumber() return patterned_array def generateRandomArray(self, array_size): rand_array = array_u08(array_size) for index in range(array_size): rand_array[index] = random.randint(0, 255) return rand_array def refArrayCount(self): return self.m_ref_array_count def buildPageArrays(self): self.m_ref_array_list = [] for _index in range(self.m_ref_array_count): if self.m_patterned_not_random_arrays: this_array = self.generatePatternedArray(self.m_page_size) else: this_array = self.generateRandomArray(self.m_page_size, self.m_page_size) self.m_ref_array_list.append(this_array) self.m_page_arrays_built = True # array_label = "Reference Page Array #%02X:" % index # self.printArrayHexDump(array_label, self.m_ref_array_list[index]) def nthReferencePageArray(self, index): index = index % self.m_ref_array_count return self.m_ref_array_list[index] def firstReferencePageArray(self): self.m_ref_array_index = 0 return self.m_ref_array_list[0] def nextReferencePageArray(self): self.m_ref_array_index = (self.m_ref_array_index + 1) % self.m_ref_array_count return self.m_ref_array_list[self.m_ref_array_index] def printArrayHexDump(self, label, data_array=None, echo_to_display=False): if not type(data_array) == array.ArrayType or len(data_array) == 0: self.bufferDetailInfo("Hexdump: array is empty") return bytes_per_line = 32 array_size = len(data_array) array_lines = (array_size + bytes_per_line - 1) // bytes_per_line dump_bytes = array_size dump_index = 0 self.bufferDetailInfo("%s [ 0x%x bytes ]" % (label, array_size), echo_to_display) for line in range(array_lines): linestart = line * bytes_per_line linestring = " %02X : " % linestart if dump_bytes >= bytes_per_line: line_bytes = bytes_per_line else: line_bytes = dump_bytes for dump_index in range(dump_index, dump_index + line_bytes): value = data_array[dump_index] linestring = linestring + " %02X" % value self.bufferDetailInfo(linestring, echo_to_display) ''' printArrayHexDumpWithErrors Dump an array in rows of fixed length. Include between rows of array_a, annotated values of array_b where they differ with array_a. ''' def printArrayHexDumpWithErrors(self, label, data_array, pattern_array, echo_to_display=False): ''' diffLine compares two arrays if equal, returns True and Null String else, returns False and Text with Annotated differing hex values ''' def printDiffLine(array_a, array_b): diff_indices = [] if len(array_a) == len(array_b): for index in range(len(array_a)): if array_a[index] == array_b[index]: continue else: diff_indices.append(index) if len(diff_indices) > 0: diff_text = [ ' ', ] * len(array_a) last_index = -2 for index in diff_indices: reference = array_b[index] if index == last_index + 1: diff_text[index] = "-%02x" % reference else: diff_text[index] = ">%02x" % reference last_index = index self.bufferDetailInfo(' ' + ''.join(diff_text), echo_to_display) return False else: return True, '' if not type(data_array) == array.ArrayType or len(data_array) == 0: self.bufferDetailInfo("Hexdump: array is empty", echo_to_display) return bytes_per_line = 32 array_size = len(data_array) array_lines = (array_size + bytes_per_line - 1) // bytes_per_line dump_bytes = array_size dump_index = 0 self.bufferDetailInfo("%s [ 0x%x bytes ]" % (label, array_size), echo_to_display) for line in range(array_lines): line_start = line * bytes_per_line line_string = " %02X : " % line_start if dump_bytes >= bytes_per_line: line_bytes = bytes_per_line else: line_bytes = dump_bytes line_end = line_start + bytes_per_line data_sub_array = data_array[line_start:line_end] pattern_sub_array = pattern_array[line_start:line_end] pattern_match, _errors = self.arraysMatch(data_sub_array, pattern_sub_array) if not pattern_match: self.bufferDetailInfo("", echo_to_display) for dump_index in range(dump_index, dump_index + line_bytes): value = data_array[dump_index] line_string = line_string + " %02X" % value self.bufferDetailInfo(line_string, echo_to_display) if not pattern_match: printDiffLine(data_array[line_start:line_end], pattern_array[line_start:line_end]) pass def arraySingleValued(self, array_a, value=None): if value != None and array_a[0] != value: return False byte_0 = array_a[0] match_count = 0 for item in array_a: if item != byte_0: break match_count += 1 return match_count == len(array_a), match_count def arraysMatch(self, array_a, array_b): errors = 0 if len(array_a) == len(array_b): for index in range(len(array_a)): if array_a[index] == array_b[index]: continue else: errors += 1 continue if errors >= 250: errors += 0 return errors == 0, errors pass def logReferenceArrays(self): for index in range(self.refArrayCount()): this_array = self.nthReferencePageArray(index) label = "Reference Array %02d" % index self.printArrayHexDump(label, this_array, True)
def test_argsort_random(self): from numpy import array from _random import Random rnd = Random(1) a = array([rnd.random() for i in range(512*2)]).reshape(512,2) a.argsort()
class Ball : def __init__(self,x, y, vx, vy): self.rand=None self.model = {"walls" : {"left":0, "top":0, "right": 500, "bottom": 300}, "elastity" : -0.2, "ballRadius" : 26, "maxSpeed" : 3.0 } # default provisioning self.rand=Random() if (x == None) : Threading.Thread.Sleep(15) x = (self.model["walls"]["right"] - self.model["walls"]["left"] - 2*self.model["ballRadius"])* self.rand.random() y = (self.model["walls"]["bottom"] - self.model["walls"]["top"] - 2*self.model["ballRadius"])* self.rand.random() vx = 2*self.model["maxSpeed"]* self.rand.random() - self.model["maxSpeed"] vy = 2*self.model["maxSpeed"]* self.rand.random() - self.model["maxSpeed"] self._x = x self._y = y self._vx = vx self._vy = vy self._r = self.model["ballRadius"] # d = 52 px self._d = 2*self._r self._d2 = self._d*self._d def Ballmove(self): self._x +=self._vx self._y += self._vy if (self._x < self.model["walls"]["left"] and self._vx<0): #self._vx += (self._x - walls.left)*elastity self._vx = -self._vx # top if (self._y < self.model["walls"]["top"] and self._vy<0): #self._vy += (self._y - walls.top)*elastity self._vy = -self._vy # left if (self._x > self.model["walls"]["right"] - self._d and self._vx>0): #self._vx += (self._x - walls.right + self._d)*elastity self._vx = -self._vx # top if (self._y > self.model["walls"]["bottom"] - self._d and self._vy>0) : #self._vy += (self._y - walls.bottom + self._d)*elastity self._vy = -self._vy def doCollide(self,b): dx = self._x - b._x dy = self._y - b._y dvx = self._vx - b._vx dvy = self._vy - b._vy distance2 = dx*dx + dy*dy if (Math.Abs(dx) > self._d or Math.Abs(dy) > self._d): return False if (distance2 > self._d2): return False # make absolutely elastic collision mag = dvx*dx + dvy*dy # test that balls move towards each other if (mag > 0): return False mag /= distance2 delta_vx = dx*mag delta_vy = dy*mag self._vx -= delta_vx self._vy -= delta_vy b._vx += delta_vx b._vy += delta_vy return True