Ejemplo n.º 1
0
 def _check_write(self, thread_name, socket):
     event = self._write_access[thread_name]
     if event.is_set():
         socket.send(
             self._write_cmd % (_randint(-100, 0), _randint(0, 100)))
         event.result = socket.recv(1024)
         event.clear()
Ejemplo n.º 2
0
def checkReadWithParams(scpiObj):
    _printHeader("Attribute read with parameters after the '?'")
    try:
        cmd = 'reader:with:parameters'
        longTest = ArrayTest(100)
        scpiObj.addCommand(cmd, readcb=longTest.readRange)
        answer = _send2Input(scpiObj, "DataFormat ASCII")
        if answer is None or len(answer) == 0:
            raise ValueError("Empty string")
        for i in range(10):
            bar, foo = _randint(0, 100), _randint(0, 100)
            start = min(bar, foo)
            end = max(bar, foo)
            # introduce a ' ' (write separator) after the '?' (read separator)
            cmdWithParams = "%s?%3s,%s" % (cmd, start, end)
            answer = _send2Input(scpiObj, cmdWithParams)
            print("\tRequest %s \n\tAnswer: %r (len %d)" % (cmdWithParams,
                                                            answer,
                                                            len(answer)))
            if answer is None or len(answer) == 0:
                raise ValueError("Empty string")
        cmdWithParams = "%s?%s,%s" % (cmd, start, end)
        result = True, "Read with parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Read with parameters test FAILED"
    _printFooter(result[1])
    return result
Ejemplo n.º 3
0
 def __fsanitation(self):
     # private! This method should not be called independently. Otherwise
     # the program will be stuck in a permanent loop
     """A target method for threading.Thread
     
     Drops sanitation with max interval being SANITATION_DROP_INTERVAL. If
     sanitation value is 0, the score is dropped every maximum ticks of 
     SCOREDROP_SANITATION_COUNT.
     """
     SCOREDROPCOUNT = SCOREDROP_SANITATION_COUNT
     # To add more randomness, uncomment following:
     SCOREDROPCOUNT = _randint(0, SCOREDROP_SANITATION_COUNT)
     while True:
         #_sleep(SANITATION_DROP_INTERVAL)
         # To add more randomness, uncomment following:
         _sleep(_randint(1, SANITATION_DROP_INTERVAL))
         self._setsanitation(self._sanitation - 1)
         if self._sanitation is 0:
             SCOREDROPCOUNT -= 1
             if SCOREDROPCOUNT <= 0:
                 #SCOREDROPCOUNT = SCOREDROP_SANITATION_COUNT
                 # To add more randomness, uncomment following:
                 SCOREDROPCOUNT = _randint(1, SCOREDROP_SANITATION_COUNT)
                 self.addscore(SANITATION_SCOREDROP,
                               'Low sanitation. Use a water tap nearby.')
Ejemplo n.º 4
0
 def insert(self, z : SearchTreeNode):
     '''
     插入元素,时间复杂度`O(h)` `h`为树的高度
     '''
     y = None
     x = self.root
     while x != None:
         y = x
         if z.key < x.key:
             x = x.left
         elif z.key > x.key:
             x = x.right
         else:
             # 处理相同结点的方式,随机分配左右结点
             if _randint(0, 1) == 0:
                 x = x.left
             else:
                 x = x.right
     z.p = y
     if y == None:
         self.root = z
     elif z.key < y.key:
         y.left = z
     elif z.key > y.key:
         y.right = z
     else:
         # 处理相同结点的方式,随机分配左右结点
         if _randint(0, 1) == 0:
             y.left = z
         else:
             y.right = z
     self.nodes.append(z) 
     self.lastnode = z
Ejemplo n.º 5
0
def joystick_summary_status():
    # returns [x, y] for summary position
    if JOYSTICKS_CONNECTED:  # case of joysticks actually connected
        # Sum of states; TBC
        pass
    else:  # No joysticks; random data
        return [_randint(-10, 10), _randint(-10, 10)]
Ejemplo n.º 6
0
def checkReadWithParams(scpiObj):
    _printHeader("Attribute read with parameters after the '?'")
    try:
        cmd = 'reader:with:parameters'
        longTest = ArrayTest(100)
        scpiObj.addCommand(cmd, readcb=longTest.readRange)
        answer = _send2Input(scpiObj, "DataFormat ASCII")
        if answer is None or len(answer) == 0:
            raise ValueError("Empty string")
        for i in range(10):
            bar, foo = _randint(0, 100), _randint(0, 100)
            start = min(bar, foo)
            end = max(bar, foo)
            # introduce a ' ' (write separator) after the '?' (read separator)
            cmdWithParams = "%s?%3s,%s" % (cmd, start, end)
            answer = _send2Input(scpiObj, cmdWithParams)
            print("\tRequest %s \n\tAnswer: %r (len %d)" %
                  (cmdWithParams, answer, len(answer)))
            if answer is None or len(answer) == 0:
                raise ValueError("Empty string")
        cmdWithParams = "%s?%s,%s" % (cmd, start, end)
        result = True, "Read with parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Read with parameters test FAILED"
    _printFooter(result[1])
    return result
Ejemplo n.º 7
0
def joystick_summary_status():
    # returns [x, y] for summary position
    if JOYSTICKS_CONNECTED: # case of joysticks actually connected
        # Sum of states; TBC
        pass
    else: # No joysticks; random data
        return [_randint(-10, 10), _randint(-10, 10)]
Ejemplo n.º 8
0
def rnd_dim(maxdim):
    """when plotting multidimensional graphs we need to reduce the dimensions to
	two"""
    if maxdim < 2:
        return 0, 0

    if maxdim == 2:
        return 0, 1

    f = _randint(0, maxdim - 1)
    s = f
    while s == f:
        s = _randint(0, maxdim - 1)
    return f, s
Ejemplo n.º 9
0
def _channelCmds_readCheck(scpiObj, pre, inner, post, nCh, value=None):
    rCmd = ''.join("%s%s:%s?;" % (pre, str(ch).zfill(2), post)
                   for ch in range(1, nCh+1))
    answer = _send2Input(scpiObj, "%s" % rCmd)
    if type(inner) is list:
        toCheck = {}
        for i in inner:
            toCheck[i] = answer.strip().split(';')[i-1]
    else:
        toCheck = {inner: answer.strip().split(';')[inner-1]}
        if value is None:
            value = _randint(-1000, 1000)
            while value == int(toCheck[inner]):
                value = _randint(-1000, 1000)
    return answer, toCheck, value
Ejemplo n.º 10
0
def _channel_cmds_read_check(scpi_obj, pre, inner, post, n_ch, value=None):
    r_cmd = ''.join("{0}{1}:{2}?;".format(pre, str(ch).zfill(2), post)
                    for ch in range(1, n_ch+1))
    answer = _send2input(scpi_obj, "{0}".format(r_cmd))
    if type(inner) is list:
        to_check = {}
        for i in inner:
            to_check[i] = answer.strip().split(';')[i-1]
    else:
        to_check = {inner: answer.strip().split(';')[inner-1]}
        if value is None:
            value = _randint(-1000, 1000)
            while value == int(to_check[inner]):
                value = _randint(-1000, 1000)
    return answer, to_check, value
Ejemplo n.º 11
0
def _channelCmds_readCheck(scpiObj, pre, inner, post, nCh, value=None):
    rCmd = ''.join("%s%s:%s?;" % (pre, str(ch).zfill(2), post)
                   for ch in range(1, nCh + 1))
    answer = _send2Input(scpiObj, "%s" % rCmd)
    if type(inner) is list:
        toCheck = {}
        for i in inner:
            toCheck[i] = answer.strip().split(';')[i - 1]
    else:
        toCheck = {inner: answer.strip().split(';')[inner - 1]}
        if value is None:
            value = _randint(-1000, 1000)
            while value == int(toCheck[inner]):
                value = _randint(-1000, 1000)
    return answer, toCheck, value
Ejemplo n.º 12
0
def encrypt(v, k):
    """
    Encrypt Message follow QQ's rule.
    用QQ的规则加密消息
    参数 v 是被加密的明文, k是密钥
    >>> en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    >>> decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    """
    END_CHAR = '\0'
    FILL_N_OR = 0xF8
    vl = len(v)
    filln = (8-(vl+2))%8 + 2
    fills = ''
    for i in xrange(filln):
        fills = fills + chr(_randint(0, 0xff))
    v = ( chr((filln -2)|FILL_N_OR) + fills + v + END_CHAR * 7 )
    tr = '\0'*8
    to = '\0'*8
    r = ''
    o = '\0' * 8
    for i in xrange(0, len(v), 8):
        o = xor(v[i:i+8], tr)
        tr = xor( encipher(o, k), to)
        to = o
        r += tr
    return r
Ejemplo n.º 13
0
    def add(self, parent_id: int, tag: str, text: str = '', **attrib) -> int:
        """
        Adds an element to a parent

        Args:
            parent_id: ID of the parent element
            tag: Tag / name of the new element
            text: Text of the new element
            **attrib: Attributes of the new element

        Returns:
            The id of the new created element

        """
        if parent_id == 0:
            element = _ET.Element(tag, **attrib)
            element.text = text
            self.root.append(element)
        elif parent_id in self.elements.keys():
            element = _ET.SubElement(self.elements[parent_id], tag, **attrib)
            element.text = text
        else:
            raise IndexError('The parent element does not exist')

        while True:  # do while would be nice
            elem_id = _randint(111111111, 999999999)
            if elem_id not in self.elements:
                break
        self.elements[elem_id] = element

        return elem_id
Ejemplo n.º 14
0
 def chooseBooster(self):
     probs = _randint(0, 4)
     if probs != 0:
         return
     bst = _choice(['add_bomb', 'add_explosion_range', 'add_speed'])
     booster = Booster(bst, gameObjectGroup)
     booster.rect.center = self.rect.center
Ejemplo n.º 15
0
def _buildCommand2Test():
    baseCmds = ['SOURce', 'BASIcloop', 'ITERative', 'CHANnel']
    subCmds = ['CURRent', 'VOLTage']
    attrs = ['UPPEr', 'LOWEr', 'VALUe']
    baseCmd = _randomchoice(baseCmds)
    if baseCmd in ['CHANnel']:
        baseCmd = "%s%s" % (baseCmd, str(_randint(1, nChannels)).zfill(2))
        if _randint(0, 1):
            baseCmd = "%s:MEAS:FUNC%s" % (
                baseCmd, str(_randint(1, nSubchannels)).zfill(2))
    subCmd = _randomchoice(subCmds)
    if baseCmd in ['SOURce']:
        attr = _randomchoice(attrs + ['BUFFer'])
    else:
        attr = _randomchoice(attrs)
    return "%s:%s:%s?" % (baseCmd, subCmd, attr)
Ejemplo n.º 16
0
def elect_key_with_modifier(target, preference, multiplier=10):
    """Chooses a pseudo-random key in dictionary, affected by preference
    
    *target* is the value in *preference* that we are trying to get electors
    for
    
    *preference* is a dictionary containing *target*'s preference for the
    result. The format is:
    {<key>: <target name>, ...}
    
    *multiplier* is a modifier for prioritizing the whole preferences.
    Defaults to 10 as it is the supposed optimum value, yielding approx. 70%
    election chance. Value of 1 makes all keys to have equal probabilities,
    regardless of their preferences.
    
    Returns elected key.
    """
    assert isinstance(preference, dict), '*preference* should be a dictionary'

    candidate = []
    for key in preference.keys():
        if preference[key] is target:
            candidate.extend([key] * multiplier)
        else:
            candidate.append(key)
    return candidate[_randint(0, len(candidate) - 1)]
Ejemplo n.º 17
0
def is_prime_miller(n):
    primelist = all_prime(1000)
    if n < 2:
        return False
    for i in primelist:
        if n == i:
            return True
        if n % i == 0:
            return False
    k = 0
    q = n - 1
    while q % 2 == 0 and q > 0:
        q >>= 1
        k += 1
    T = 15
    while T:
        a = _randint(3, n - 1)
        if gcd(a, n) > 1:
            return False
        a = my_pow(a, q, n)
        if a != 1:
            for i in range(k):
                if a == n - 1:
                    break
                if a == 1:
                    return False
                a = pow(a, 2, n)
        if a != 1 and a != n - 1:
            return False
        T -= 1
    return True
Ejemplo n.º 18
0
def encrypt(v, k):
    """
    Encrypt Message follow QQ's rule.
    用QQ的规则加密消息
    参数 v 是被加密的明文, k是密钥
    >>> en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    >>> decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    """
    END_CHAR = '\0'
    FILL_N_OR = 0xF8
    vl = len(v)
    filln = (8 - (vl + 2)) % 8 + 2
    fills = ''
    for i in xrange(filln):
        fills = fills + chr(_randint(0, 0xff))
    v = (chr((filln - 2) | FILL_N_OR) + fills + v + END_CHAR * 7)
    tr = '\0' * 8
    to = '\0' * 8
    r = ''
    o = '\0' * 8
    for i in xrange(0, len(v), 8):
        o = xor(v[i:i + 8], tr)
        tr = xor(encipher(o, k), to)
        to = o
        r += tr
    return r
Ejemplo n.º 19
0
    def permute_by_cyclic(self, array):
        '''
        随机打乱排列一个数组

        Args
        =
        array : 随机排列前的数组

        Return:
        =
        random_array : 随机排列后的数组

        Example 
        =
        >>> Chapter5_3().permute_by_cyclic([1, 2, 3, 4])
        '''
        A = _deepcopy(array)
        n = len(array)
        offset = _randint(0, n - 1)
        A = _deepcopy(array)
        for i in range(n):
            dest = i + offset
            if dest >= n:
                dest = dest - n
            A[dest] = array[i]
        return A
Ejemplo n.º 20
0
 def __init__(self, name, job=None):
     """Class initialization.
     
     *name* is the name of the player.
     
     *job* is a DGProfession instance
     
     Note: *name* must be changed to Player object when implemented in
     DetectiveGame420 java plugin.
     """
     self._name = name
     self._job = job
     self._iskiller = False
     self._score = 0
     self._sanitation = _randint(SANITATION_LOWEST_INITVALUE, 99)
     self._soaked = False
     self._invisible = False
     self._breath = 0
     self._bloody = False
     self._alive = True
     # this variable must have no other means of setting its value to False
     self._bloody_once = False
     # sanitation drop start
     self.__sanitation_fall_thread = _Thread(target=self.__fsanitation)
     self.__sanitation_fall_thread.setDaemon(True)
     self.__sanitation_fall_thread.start()
     self.__initialized = True
Ejemplo n.º 21
0
def reiniciar():
    """
    Reinicia as variáveis de estado que controlam o jogo.
    """
    _.ativo = False
    _.morto = False
    _.flappy_x = _.largura_tela // 3
    _.flappy_y = _.altura_tela // 2
    _.velocidade = 0
    distancia_canos = 80
    cano1 = _.largura_tela + distancia_canos * 0, -10 * _randint(1, 8)
    cano2 = _.largura_tela + distancia_canos * 1, -10 * _randint(1, 8)
    cano3 = _.largura_tela + distancia_canos * 2, -10 * _randint(1, 8)
    cano4 = _.largura_tela + distancia_canos * 3, -10 * _randint(1, 8)
    _.canos = [cano1, cano2, cano3, cano4]
    _.score = 0
 def randomized_partition(self, A: list, p: int, r: int):
     '''
     快速排序随机分堆子过程
     '''
     i = _randint(p, r)
     A[r], A[i] = A[i], A[r]
     return self.partition(A, p, r)
Ejemplo n.º 23
0
def initkey():
    i=0
    fills=''
    while i < 16:
        fills = fills + chr(_randint(0, 0xff))
        i += 1
    return fills
Ejemplo n.º 24
0
def _doWriteCommand(scpiObj, cmd, value=None):
    # first read ---
    answer1 = _send2Input(scpiObj, "%s?" % cmd)
    print("\tRequested %s initial value: %r" % (cmd, answer1))
    # then write ---
    if value is None:
        value = _randint(-1000, 1000)
        while value == int(answer1.strip()):
            value = _randint(-1000, 1000)
    answer2 = _send2Input(scpiObj, "%s %s" % (cmd, value))
    print("\tWrite %r value: %r, answer: %r" % (cmd, value, answer2))
    # read again ---
    answer3 = _send2Input(scpiObj, "%s?" % cmd)
    print("\tRequested %r again value: %r\n" % (cmd, answer3))
    if answer2 != answer3:
        raise AssertionError("Didn't change after write (%r, %r, %r)"
                             % (answer1, answer2, answer3))
Ejemplo n.º 25
0
def _buildCommand2Test():
    baseCmds = ['SOURce', 'BASIcloop', 'ITERative', 'CHANnel']
    subCmds = ['CURRent', 'VOLTage']
    attrs = ['UPPEr', 'LOWEr', 'VALUe']
    baseCmd = _randomchoice(baseCmds)
    if baseCmd in ['CHANnel']:
        baseCmd = "%s%s" % (baseCmd, str(_randint(1, nChannels)).zfill(2))
        if _randint(0, 1):
            baseCmd = "%s:MEAS:FUNC%s" % (baseCmd,
                                          str(_randint(1,
                                                       nSubchannels)).zfill(2))
    subCmd = _randomchoice(subCmds)
    if baseCmd in ['SOURce']:
        attr = _randomchoice(attrs + ['BUFFer'])
    else:
        attr = _randomchoice(attrs)
    return "%s:%s:%s?" % (baseCmd, subCmd, attr)
Ejemplo n.º 26
0
def _doWriteCommand(scpiObj, cmd, value=None):
    # first read ---
    answer1 = _send2Input(scpiObj, "%s?" % cmd)
    print("\tRequested %s initial value: %r" % (cmd, answer1))
    # then write ---
    if value is None:
        value = _randint(-1000, 1000)
        while value == int(answer1.strip()):
            value = _randint(-1000, 1000)
    answer2 = _send2Input(scpiObj, "%s %s" % (cmd, value))
    print("\tWrite %r value: %r, answer: %r" % (cmd, value, answer2))
    # read again ---
    answer3 = _send2Input(scpiObj, "%s?" % cmd)
    print("\tRequested %r again value: %r\n" % (cmd, answer3))
    if answer2 != answer3:
        raise AssertionError("Didn't change after write (%r, %r, %r)" %
                             (answer1, answer2, answer3))
Ejemplo n.º 27
0
def _do_write_command(scpi_obj, cmd, value=None):
    # first read ---
    answer1 = _send2input(scpi_obj, "{0}?".format(cmd))
    print("\tRequested {0} initial value: {1!r}".format(cmd, answer1))
    # then write ---
    if value is None:
        value = _randint(-1000, 1000)
        while value == int(answer1.strip()):
            value = _randint(-1000, 1000)
    _send2input(scpi_obj, "{0} {1}".format(cmd, value), check_answer=False)
    print("\tWrite {0!r} value: {1!r}".format(cmd, value))
    # read again ---
    answer2 = _send2input(scpi_obj, "{0}?".format(cmd))
    print("\tRequested {0!r} again value: {1!r}\n".format(cmd, answer2))
    if answer1 == answer2:
        raise AssertionError(
            "Didn't change after write ({0!r}, {1!r})".format(
                answer1, answer2))
Ejemplo n.º 28
0
def _build_command2test():
    base_cmds = ['SOURce', 'BASIcloop', 'ITERative', 'CHANnel']
    sub_cmds = ['CURRent', 'VOLTage']
    attrs = ['UPPEr', 'LOWEr', 'VALUe']
    base_cmd = _random_choice(base_cmds)
    if base_cmd in ['CHANnel']:
        base_cmd = "{0}{1}".format(
            base_cmd, str(_randint(1, n_channels)).zfill(2))
        if _randint(0, 1):
            base_cmd = "{0}:MEAS:FUNC{1}" \
                       "".format(base_cmd,
                                 str(_randint(1, n_subchannels)).zfill(2))
    sub_cmd = _random_choice(sub_cmds)
    if base_cmd in ['SOURce']:
        attr = _random_choice(attrs + ['BUFFer'])
    else:
        attr = _random_choice(attrs)
    return "{0}:{1}:{2}?".format(base_cmd, sub_cmd, attr)
Ejemplo n.º 29
0
    def build(self):
        # Building the main window widget
        game = GameWidget()
        # c1, c2, c3 to split the ASTEROID_COUNT into three
        c1 = ASTEROID_COUNT // 3
        c2 = c1 * 2
        # Adding asteroids; three various classes to have three different images
        for i in range(c1):
            game.add_widget(Asteroid1(), i)
        for i in range(c1, c2):
            game.add_widget(Asteroid2(), i)
        for i in range(c2, ASTEROID_COUNT):
            game.add_widget(Asteroid3(), i)
        # Generate random positions for all asteroids (type 1, 2, and 3)
        for i in range(ASTEROID_COUNT):
            while True:
                xpos = _randint(0, XSIZE)
                ypos = _randint(0, YSIZE)
                # ...until being reasonably far from the center,
                # to avoid an immediate collsion with the rocket
                if abs(xpos - XSIZE // 2) > 50:
                    if abs(ypos - YSIZE // 2) > 50:
                        break
            # Set the asteroid actual location
            game.children[i].pos = (xpos, ypos)
            # Set the asteroid location attributes;
            # These are separate to accumulate computed movement
            game.children[i].pos_x = xpos
            game.children[i].pos_y = ypos
            # Set the asteroid velocity attributes
            game.children[i].vel_x = MAX_ASTEROID_SPEED / (_randint(-3, 3) +
                                                           0.5)
            game.children[i].vel_y = MAX_ASTEROID_SPEED / (_randint(-3, 3) +
                                                           0.5)

        # Adding resources as next items on the widget list
        for i in range(ASTEROID_COUNT, ASTEROID_COUNT + RESOURCE_COUNT):
            # Resource index starts after the ASTEROID_COUNT
            game.add_widget(Resource(), i)  # Adding i-th resource
            xpos = _randint(0, XSIZE)
            ypos = _randint(0, YSIZE)
            # Set the resource location
            game.children[i].pos = (xpos, ypos)
            # Set the resource location attributes, float
            game.children[i].pos_x = xpos
            game.children[i].pos_y = ypos
            # Set the resource velocity; float
            game.children[i].vel_x = MAX_RESOURCE_SPEED / (_randint(-3, 3) +
                                                           0.5)
            game.children[i].vel_y = MAX_RESOURCE_SPEED / (_randint(-3, 3) +
                                                           0.5)

        Clock.schedule_interval(game.update, TIME_STEP)
        return game
Ejemplo n.º 30
0
def test(n, pause):
    is_conn = tosdb.connected()
    if not is_conn:
        print("*** COULD NOT CONNECT... exiting ***\n")
        exit(1)

    print("-- CREATE BLOCK --\n")
    b1 = tosdb.TOSDB_DataBlock(BSIZE, True, BTIMEOUT)

    for _ in range(n):
        nt = _randint(1, MAX_ADD)
        ni = _randint(1, MAX_ADD)
        topics = choice_without_replace(T_TOPICS, nt)
        items = choice_without_replace(T_ITEMS, ni)
        print('ADD ITEMS: ', str(items))
        b1.add_items(*items)
        print('ADD TOPICS: ', str(topics))
        b1.add_topics(*topics)

        _sleep(pause)
        print()
        print(b1)
        _sleep(pause)

        items = b1.items()
        ni = len(items)
        if ni > 1:
            ni = _randint(1, ni - 1)
            items = choice_without_replace(items, ni)
            print('REMOVE ITEMS: ', str(items))
            b1.remove_items(*items)

        topics = b1.topics()
        nt = len(topics)
        if nt > 1:
            nt = _randint(1, nt - 1)
            topics = choice_without_replace(topics, nt)
            print('REMOVE TOPICS: ', str(topics))
            b1.remove_topics(*topics)

        _sleep(pause)
        print()
        print(b1)
        _sleep(pause)
Ejemplo n.º 31
0
def test(n,pause):   
    is_conn = tosdb.connected()
    if not is_conn:
        print("*** COULD NOT CONNECT... exiting ***\n")
        exit(1)
        
    print("-- CREATE BLOCK --\n")
    b1 = tosdb.TOSDB_DataBlock(BSIZE,True,BTIMEOUT)

    for _ in range(n):
        nt = _randint(1,MAX_ADD)
        ni = _randint(1,MAX_ADD)
        topics = choice_without_replace(T_TOPICS, nt)
        items = choice_without_replace(T_ITEMS, ni)
        print('ADD ITEMS: ', str(items))        
        b1.add_items(*items)
        print('ADD TOPICS: ', str(topics))
        b1.add_topics(*topics)
        
        _sleep(pause)
        print()
        print(b1)
        _sleep(pause)                
        
        items = b1.items()
        ni = len(items)
        if ni > 1:
            ni = _randint(1,ni-1)
            items = choice_without_replace(items, ni)
            print('REMOVE ITEMS: ', str(items))
            b1.remove_items(*items)
            
        topics = b1.topics()
        nt = len(topics)
        if nt > 1:
            nt = _randint(1, nt-1)
            topics = choice_without_replace(topics, nt)
            print('REMOVE TOPICS: ', str(topics))
            b1.remove_topics(*topics)
        
        _sleep(pause)
        print()
        print(b1)
        _sleep(pause)
Ejemplo n.º 32
0
	def encrypt(self, v):
		"""
		Encrypt Message follow QQ's rule.
		v is the message to encrypt, k is the key
		fill char is some random numbers (in old QQ is 0xAD)
		fill n char's n = (8 - (len(v)+2)) %8 + 2
		( obviously, n is 2 at least, n is 2-9)

		then insert (n - 2)|0xF8 in the front of the fill chars
		to record the number of fill chars.
		append 7 '\0' in the end of the message.
		
		thus the lenght of the message become filln + 8 + len(v),
		and it == 0 (mod 8)

		Encrypt the message .
		Per 8 bytes,
		the result is:
		
		r = encipher( v ^ tr, key) ^ to   (*)

		code is the QQ's TEA function.
		v is 8 bytes data to encrypt.
		tr is the result in preceding round.
		to is the data coded in perceding round, is v_pre ^ r_pre_pre

		For the first 8 bytes 'tr' and 'to' is zero.
		
		loop and loop, 
		that's end.
		
		>>> en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
		>>> decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
		''
		"""
		END_CHAR = '\0'
		FILL_N_OR = 0xF8
		vl = len(v)
		filln = (8-(vl+2))%8 + 2;
		fills = ''
		for i in xrange(filln):
			fills = fills + chr(_randint(0, 0xff))
		v = ( chr((filln -2)|FILL_N_OR)
			  + fills
			  + v
			  + END_CHAR * 7)
		tr = '\0'*8
		to = '\0'*8
		r = ''
		o = '\0' * 8
		for i in xrange(0, len(v), 8):
			o = xor(v[i:i+8], tr)
			tr = xor( self.encipher(o), to)
			to = o
			r += tr
		return r
Ejemplo n.º 33
0
 def _generate_genotype_for_trial(self, target_index, mutagen_indices,
                                  dimensions):
     target = self.population[target_index]
     D = _randint(0, dimensions - 1)
     return [
         self._calculate_mutagen_value(mutagen_indices, genotype_index)
         if _random() < self.CR or genotype_index == D else
         target.genotype[genotype_index]
         for genotype_index in range(dimensions)
     ]
Ejemplo n.º 34
0
def get_prime(bit_length = 2048, strong = False):
	while True:
		x = _randint(2 ** (bit_length - 1) + 1, 2 ** bit_length - 1)
		x += 1 - (x & 1)
		if _is_prime_miller(x):
			if strong == False:
				break
			if _is_prime_miller((x - 1) // 2):
				break
	return x
Ejemplo n.º 35
0
def encrypt(v, k):
    """
    Encrypt Message follow QQ's rule.

    v is the message to encrypt, k is the key
    fill char is some random numbers (in old QQ is 0xAD)
    fill n char's n = (8 - (len(v)+2)) %8 + 2
    ( obviously, n is 2 at least, n is 2-9)

    then insert (n - 2)|0xF8 in the front of the fill chars
    to record the number of fill chars.
    append 7 '\0' in the end of the message.

    thus the lenght of the message become filln + 8 + len(v),
    and it == 0 (mod 8)

    Encrypt the message .
    Per 8 bytes,
    the result is:

    r = code( v ^ tr, key) ^ to   (*)

    code is the QQ's TEA function.
    v is 8 bytes data to encrypt.
    tr is the result in preceding round.
    to is the massage coded in perceding round, is v_pre ^ r_pre_pre

    For the first 8 bytes 'tr' and 'to' is zero.
    
    loop and loop, 
    that's end.
    >>> en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    >>> decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    ''
    """
    ##FILL_CHAR = chr(0xAD)
    END_CHAR = '\0'
    FILL_N_OR = 0xF8
    vl = len(v)
    filln = (8 - (vl + 2)) % 8 + 2
    fills = ''
    for i in xrange(filln):
        fills = fills + chr(_randint(0, 0xff))
    v = (chr((filln - 2) | FILL_N_OR) + fills + v + END_CHAR * 7)
    tr = '\0' * 8
    to = '\0' * 8
    r = ''
    o = '\0' * 8
    #print 'len(v)=', len(v)
    for i in xrange(0, len(v), 8):
        o = xor(v[i:i + 8], tr)
        tr = xor(code(o, k), to)
        to = o
        r += tr
    return r
Ejemplo n.º 36
0
def _get_random_reader():
    global _random_reader, _random_init
    if not _random_init:
        try:
            import random
            try:
                _random_reader = open("/dev/urandom","rb").read
            except:
                _random_reader = os.fdopen(os.open("/dev/random",os.O_RDONLY|os.O_NONBLOCK),"rb").read
            sec,usec = _gettimeofday()
            random.seed((os.getpid() << 16) ^ os.getuid() ^ sec ^ usec)
        except:
            pass
        _random_init = True
    sec,usec = _gettimeofday()
    i = (sec ^ usec) & 0x1F
    while i>0:
        _randint(0,_maxint)
        i -= 1
    return _random_reader
Ejemplo n.º 37
0
    def update(self, dt):
        # One step game status update
        
        # Move the rocket by the speed vector
        self.rocket.move()
        
        # Decrease the timer; it will display automatically
        self.timer = self.timer - dt

        # Move the freely floating objects, i.e. asteroids & resources
        # It's aplicable to all these objects with the same algorithm
        # Then there is no separate 'move' function for each class
        for i in range(ASTEROID_COUNT + RESOURCE_COUNT):
            new_x = self.children[i].pos_x + self.children[i].vel_x
            new_y = self.children[i].pos_y + self.children[i].vel_y
            # Wrap up if out of the window
            if new_x < -MARGIN:
                new_x = XSIZE + MARGIN
            if new_x > XSIZE + MARGIN:
                new_x = -MARGIN
            if new_y < -MARGIN:
                new_y = YSIZE + MARGIN
            if new_y > YSIZE + MARGIN:
                new_y = -MARGIN
            self.children[i].pos_x = new_x
            self.children[i].pos_y = new_y
            # Using float due to sub-unit steps; then rounding is needed
            self.children[i].pos = (round(new_x), round(new_y))

        # Check for a rocket collision with the window frame
        if ((self.rocket.y < 0) or
           (self.rocket.top > self.height) or
           (self.rocket.x < 0) or
           (self.rocket.right > self.width)):
            self.collision()
        
        # Check for a rocket collision with an asteroid
        for i in range(ASTEROID_COUNT):
            if self.rocket.collide_widget(self.children[i]):
                self.collision()

        # Check for a rocket meeting with a resource
        for i in range(ASTEROID_COUNT, ASTEROID_COUNT + RESOURCE_COUNT):
            if self.rocket.collide_widget(self.children[i]):
                # Score increases by 1
                self.score = self.score + 1
                # The resource disappears; actually it gets new coordinates,
                # So it immediately translates far away. Then there's no need
                # to destroy and recreate the object.
                xpos = _randint(0, XSIZE)
                ypos = -MARGIN # To avoid resources popping out within the window
                self.children[i].pos = (xpos, ypos)
                self.children[i].pos_x = xpos
                self.children[i].pos_y = ypos
Ejemplo n.º 38
0
 def __new__(cls, *arg, **kw):
     c = cls._klass
     c._group, c._field = cls._group, cls
     # make new class if automagic on to avoid attribute property overlap
     if arg[2]:
         c = type(
             _md5.new(str(_randint(0, _maxint))).digest(),
             (c,),
             dict(c.__dict__)
         )
     return c(*arg, **kw)
Ejemplo n.º 39
0
 def DrawSpecs(self, excludeMelody=False, enforceMelody=False):
     # might be better to enforce desired behaviour from outside
     from random import randint as _randint
     drawnSpecs = [
         _randint(*self[field]) for field in
         ["NbMelodies", "NbAccompaniments", "NbBass", "NbDrums"]
     ]
     if enforceMelody:
         drawnSpecs[0] = max(1, drawnSpecs[0])
     elif excludeMelody:
         drawnSpecs[0] = 0
     return drawnSpecs
Ejemplo n.º 40
0
    def collision(self):
        # Called if the rocket collides with an obstacle
        # i.e. the window frame, or an asteroid

        # Penalty by decreasing available time;
        # Maybe I'll put an explosion animation here
        _sleep(2)

        # Rocket is then moved to a collision-safe place
        rocket_is_safe = False
        while not rocket_is_safe:
            # Select a new random position
            xpos = _randint(100, XSIZE - 100)
            ypos = _randint(100, YSIZE - 100)
            self.rocket.center = (xpos, ypos)
            # ...until not colliding with any asteroid
            for i in range(ASTEROID_COUNT):
                if self.rocket.collide_widget(self.children[i]):
                    break
            else:
                rocket_is_safe = True
Ejemplo n.º 41
0
 def collision(self):
     # Called if the rocket collides with an obstacle
     # i.e. the window frame, or an asteroid
     
     # Penalty by decreasing available time;
     # Maybe I'll put an explosion animation here
     _sleep(2)
     
     # Rocket is then moved to a collision-safe place
     rocket_is_safe = False
     while not rocket_is_safe:
         # Select a new random position
         xpos = _randint(100, XSIZE - 100)
         ypos = _randint(100, YSIZE - 100)
         self.rocket.center = (xpos, ypos)
         # ...until not colliding with any asteroid
         for i in range(ASTEROID_COUNT):
             if self.rocket.collide_widget(self.children[i]):
                 break
         else:
             rocket_is_safe = True
Ejemplo n.º 42
0
    def build(self):
        # Building the main window widget
        game = GameWidget()
        # c1, c2, c3 to split the ASTEROID_COUNT into three
        c1 = ASTEROID_COUNT // 3
        c2 = c1 * 2
        # Adding asteroids; three various classes to have three different images
        for i in range(c1):
            game.add_widget(Asteroid1(), i)
        for i in range(c1, c2):
            game.add_widget(Asteroid2(), i)
        for i in range(c2, ASTEROID_COUNT):
            game.add_widget(Asteroid3(), i)
        # Generate random positions for all asteroids (type 1, 2, and 3)
        for i in range(ASTEROID_COUNT):
            while True:
                xpos = _randint(0, XSIZE)
                ypos = _randint(0, YSIZE)
                # ...until being reasonably far from the center,
                # to avoid an immediate collsion with the rocket
                if abs(xpos - XSIZE//2) > 50:
                    if abs(ypos - YSIZE//2) > 50:
                        break
            # Set the asteroid actual location
            game.children[i].pos = (xpos, ypos)
            # Set the asteroid location attributes;
            # These are separate to accumulate computed movement
            game.children[i].pos_x = xpos
            game.children[i].pos_y = ypos
            # Set the asteroid velocity attributes
            game.children[i].vel_x = MAX_ASTEROID_SPEED / (_randint(-3, 3) + 0.5)
            game.children[i].vel_y = MAX_ASTEROID_SPEED / (_randint(-3, 3) + 0.5)
            
        # Adding resources as next items on the widget list
        for i in range(ASTEROID_COUNT, ASTEROID_COUNT + RESOURCE_COUNT):
            # Resource index starts after the ASTEROID_COUNT
            game.add_widget(Resource(), i) # Adding i-th resource
            xpos = _randint(0, XSIZE)
            ypos = _randint(0, YSIZE)
            # Set the resource location
            game.children[i].pos = (xpos, ypos)
            # Set the resource location attributes, float
            game.children[i].pos_x = xpos
            game.children[i].pos_y = ypos
            # Set the resource velocity; float
            game.children[i].vel_x = MAX_RESOURCE_SPEED / (_randint(-3, 3) + 0.5)
            game.children[i].vel_y = MAX_RESOURCE_SPEED / (_randint(-3, 3) + 0.5)

        Clock.schedule_interval(game.update, TIME_STEP)
        return game
Ejemplo n.º 43
0
    def update(self, dt):
        # One step game status update

        # Move the rocket by the speed vector
        self.rocket.move()

        # Decrease the timer; it will display automatically
        self.timer = self.timer - dt

        # Move the freely floating objects, i.e. asteroids & resources
        # It's aplicable to all these objects with the same algorithm
        # Then there is no separate 'move' function for each class
        for i in range(ASTEROID_COUNT + RESOURCE_COUNT):
            new_x = self.children[i].pos_x + self.children[i].vel_x
            new_y = self.children[i].pos_y + self.children[i].vel_y
            # Wrap up if out of the window
            if new_x < -MARGIN:
                new_x = XSIZE + MARGIN
            if new_x > XSIZE + MARGIN:
                new_x = -MARGIN
            if new_y < -MARGIN:
                new_y = YSIZE + MARGIN
            if new_y > YSIZE + MARGIN:
                new_y = -MARGIN
            self.children[i].pos_x = new_x
            self.children[i].pos_y = new_y
            # Using float due to sub-unit steps; then rounding is needed
            self.children[i].pos = (round(new_x), round(new_y))

        # Check for a rocket collision with the window frame
        if ((self.rocket.y < 0) or (self.rocket.top > self.height)
                or (self.rocket.x < 0) or (self.rocket.right > self.width)):
            self.collision()

        # Check for a rocket collision with an asteroid
        for i in range(ASTEROID_COUNT):
            if self.rocket.collide_widget(self.children[i]):
                self.collision()

        # Check for a rocket meeting with a resource
        for i in range(ASTEROID_COUNT, ASTEROID_COUNT + RESOURCE_COUNT):
            if self.rocket.collide_widget(self.children[i]):
                # Score increases by 1
                self.score = self.score + 1
                # The resource disappears; actually it gets new coordinates,
                # So it immediately translates far away. Then there's no need
                # to destroy and recreate the object.
                xpos = _randint(0, XSIZE)
                ypos = -MARGIN  # To avoid resources popping out within the window
                self.children[i].pos = (xpos, ypos)
                self.children[i].pos_x = xpos
                self.children[i].pos_y = ypos
Ejemplo n.º 44
0
def test_marker_func(fname, *args):
    block = tosdb.TOSDB_DataBlock(N,True)
    block.add_items(*ITEMS)
    block.add_topics(*TOPICS)   
    topics = list(TOPICS)    
    _shuffle(topics)
    for topic in topics:
        item = _choice(ITEMS)
        date_time = _choice([True,False])        
        passes = _randint(3,10)
        wait = int(MAX_SEC_PER_TEST/passes)
        print("+ TEST", fname, str((item,topic,date_time,passes,wait)))
        test(fname, block, (item, topic, date_time) + args, passes, wait)
    block.close()    
Ejemplo n.º 45
0
    def __init__(self, meta='meta.json', verbose=True):

        super().__init__()

        self.__verbose = verbose
        self.__meta = {
            'header': {
                'ident': '%s-%4X' % (IDENT, _randint(0x1000, 0xffff)),
                'initialized': get_timestamp(),
                'verbose': verbose
            },
            'import': dict(),
            'log': dict()
        }
        self.__lock = Lock()
        self.stage(meta, clean=True)
Ejemplo n.º 46
0
	def __reCluster(self,trainingSet):
		#Choose k random means from the trainingSet
		for i in range(self.k):
			if self.means[i] == None:
				self.means[i] = (trainingSet[ _randint(0,len(trainingSet) - 1 ) ] )
		
		clusteredExamples = {}
		#for every example int the training set figure out which cluster is belongs to
		for example in trainingSet:
			newCluster = self.__findCluster(example)
			try:
				clusteredExamples[newCluster].append(example)
			except KeyError:
				clusteredExamples[newCluster] = [ example ]
				
		return clusteredExamples
Ejemplo n.º 47
0
def encrypt(v, k):
    END_CHAR = '\0'
    FILL_N_OR = 0xF8
    vl = len(v)
    filln = ((8 - (vl + 2)) % 8) + 2
    fills = ''
    for i in xrange(filln):
        fills += chr(_randint(0, 0xff))
    v = (chr((filln - 2) | FILL_N_OR)
         + fills
         + v
         + END_CHAR * 7)
    tr = '\0' * 8
    to = '\0' * 8
    r = ''
    o = '\0' * 8
    for i in xrange(0, len(v), 8):
        o = xor(v[i:i + 8], tr)
        tr = xor(code(o, k), to)
        to = o
        r += tr
    return r
Ejemplo n.º 48
0
def encrypt(v, k):
    """
    Encrypt Message follow QQ's rule.
    用QQ的规则加密消息
    v is the message to encrypt, k is the key
    参数 v 是被加密的明文, k是密钥
    fill char is some random numbers (in old QQ is 0xAD)
    填充字符数是随机数, (老的QQ使用0xAD)
    fill n char's n = (8 - (len(v)+2)) %8 + 2
    填充字符的个数 n = (8 - (len(v)+2)) %8 + 2
    ( obviously, n is 2 at least, n is 2-9)
    ( 显然, n至少为2, 取2到9之间)
    then insert (n - 2)|0xF8 in the front of the fill chars
    然后在填充字符前部插入1字节, 值为 ((n - 2)|0xF8)
    to record the number of fill chars.
    以便标记填充字符的个数.
    append 7 '\0' in the end of the message.
    在消息尾部添加7字节'\0'

    thus the lenght of the message become filln + 8 + len(v),
    因此消息总长变为 filln + 8 + len(v),
    and it == 0 (mod 8)
    他模8余0(被8整除)
    Encrypt the message .
    加密这段消息
    Per 8 bytes,
    每8字节,
    the result is:
    规则是

    r = code( v ^ tr, key) ^ to   (*)
    code is the QQ's TEA function.
    code函数就是QQ 的TEA加密函数.
    v is 8 bytes data to encrypt.
    v是被加密的8字节数据
    tr is the result in preceding round.
    tr是前次加密的结果
    to is the data coded in perceding round, is v_pre ^ r_pre_pre
    to是前次被加密的数据, 等于 v_pre ^ r_pre_pre
    For the first 8 bytes 'tr' and 'to' is zero.
    对头8字节, 'tr' 和 'to' 设为零

    loop and loop,
    不断循环,
    that's end.
    结束.

    >>> en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    >>> decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
    ''
    """
    ##FILL_CHAR = chr(0xAD)
    END_CHAR = '\0'
    FILL_N_OR = 0xF8
    vl = len(v)
    filln = (8-(vl+2))%8 + 2;
    fills = ''
    for i in range(filln):
        fills = fills + chr(_randint(0, 0xff))
    v = ( chr((filln -2)|FILL_N_OR)
          + fills
          + v
          + END_CHAR * 7)
    tr = '\0'*8
    to = '\0'*8
    r = ''
    o = '\0' * 8
    #print 'len(v)=', len(v)
    for i in range(0, len(v), 8):
        o = xor(v[i:i+8], tr)
        tr = xor( code(o, k), to)
        to = o
        r += tr
    return r
Ejemplo n.º 49
0
def _randomize_byte(b):
    return b ^ ((_randint(0,_maxint) >> 7) & 0xFF)
Ejemplo n.º 50
0
 def _checkWrite(self, threadName, socket):
     event = self._writeAccess[threadName]
     if event.isSet():
         socket.send(self._writeCmd % (_randint(-100, 0), _randint(0, 100)))
         event.result = socket.recv(1024)
         event.clear()
Ejemplo n.º 51
0
def new_seed():
    result = _array('c',str(_now()))
    for i in range(0,_randint(10,20)):
        result.append(chr(_randint(0,255)))
    return _MD5(result.tostring()).hexdigest().lower()
Ejemplo n.º 52
0
def checkCommandWrites(scpiObj):
    _printHeader("Testing to command writes")
    try:
        # simple commands ---
        currentConfObj = WattrTest()
        scpiObj.addCommand('source:current:configure',
                           readcb=currentConfObj.readTest,
                           writecb=currentConfObj.writeTest)
        voltageConfObj = WattrTest()
        scpiObj.addCommand('source:voltage:configure',
                           readcb=voltageConfObj.readTest,
                           writecb=voltageConfObj.writeTest)
        for inner in ['current', 'voltage']:
            _doWriteCommand(scpiObj, "source:%s:configure" % (inner))
        _wait(1)  # FIXME: remove
        # channel commands ---
        _printHeader("Testing to channel command writes")
        baseCmd = 'writable'
        wObj = scpiObj.addComponent(baseCmd, scpiObj._commandTree)
        chCmd = 'channel'
        chObj = scpiObj.addChannel(chCmd, nChannels, wObj)
        chCurrentObj = WchannelTest(nChannels)
        chVoltageObj = WchannelTest(nChannels)
        for (subcomponent, subCmdObj) in [('current', chCurrentObj),
                                          ('voltage', chVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, chObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    if attrName == 'value':
                        attrObj = scpiObj.addAttribute(attrName,
                                                       subcomponentObj,
                                                       readcb=subCmdObj.
                                                       readTest,
                                                       writecb=subCmdObj.
                                                       writeTest,
                                                       default=True)
                    else:
                        cbFunc = getattr(subCmdObj, attrFunc)
                        attrObj = scpiObj.addAttribute(attrName,
                                                       subcomponentObj, cbFunc)
        print("\nChecking one write multiple reads\n")
        for i in range(nChannels):
            rndCh = _randint(1, nChannels)
            element = _randomchoice(['current', 'voltage'])
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndCh,
                                   element, nChannels)
            _interTestWait()
        print("\nChecking multile writes multiple reads\n")
        for i in range(nChannels):
            testNwrites = _randint(2, nChannels)
            rndChs = []
            while len(rndChs) < testNwrites:
                rndCh = _randint(1, nChannels)
                while rndCh in rndChs:
                    rndCh = _randint(1, nChannels)
                rndChs.append(rndCh)
            element = _randomchoice(['current', 'voltage'])
            values = [_randint(-1000, 1000)]*testNwrites
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndChs,
                                   element, nChannels, values)
            _interTestWait()
        print("\nChecking write with allowed values limitation\n")
        selectionCmd = 'source:selection'
        selectionObj = WattrTest()
        selectionObj.writeTest(False)
        scpiObj.addCommand(selectionCmd, readcb=selectionObj.readTest,
                           writecb=selectionObj.writeTest,
                           allowedArgins=[True, False])
        _doWriteCommand(scpiObj, selectionCmd, True)
        # _doWriteCommand(scpiObj, selectionCmd, 'Fals')
        # _doWriteCommand(scpiObj, selectionCmd, 'True')
        try:
            _doWriteCommand(scpiObj, selectionCmd, 0)
        except:
            print("\tLimitation values succeed because it raises an exception "
                  "as expected")
        else:
            raise AssertionError("It has been write a value that "
                                 "should not be allowed")
        _interTestWait()
        result = True, "Command writes test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Command writes test FAILED"
    _printFooter(result[1])
    return result
Ejemplo n.º 53
0
def randint(a, b = None):
    if b is None:
        b = a
        a = 0
    return _randint(a, b)
Ejemplo n.º 54
0
def randint(A, B=None):
    """Random da A a B che funziona con valori long."""
    if B is None:
        return _randint(0, A-1)
    return _randint(A, B-1)