Exemplo n.º 1
0
def getNextPos(currentPos, playground, area, avId = None):
    if avId != None:
        if estateIndexes.has_key(avId):
            unusedI = estateIndexes[avId][0][area]
            usedI = estateIndexes[avId][1][area]
        else:
            return (ButterflyPoints[playground][area][0], 0, 4.0)
    else:
        unusedI = unusedIndexes[playground][area]
        usedI = usedIndexes[playground][area]
    nextPos = currentPos
    while nextPos == currentPos:
        if len(unusedI) == 0:
            index = whrandom.choice(usedI)
            nextPos = ButterflyPoints[playground][area][index]
        else:
            index = whrandom.choice(unusedI)
            nextPos = ButterflyPoints[playground][area][index]
            if nextPos != currentPos:
                unusedI.remove(index)
                usedI.append(index)
            
    dist = Vec3(nextPos - currentPos).length()
    time = dist / BUTTERFLY_SPEED + BUTTERFLY_TAKEOFF[playground] + BUTTERFLY_LANDING[playground]
    return (nextPos, index, time)
Exemplo n.º 2
0
def getNextPos(currentPos, playground, area, avId=None):
    if avId != None:
        if estateIndexes.has_key(avId):
            unusedI = estateIndexes[avId][0][area]
            usedI = estateIndexes[avId][1][area]
        else:
            return (
             ButterflyPoints[playground][area][0], 0, 4.0)
    else:
        unusedI = unusedIndexes[playground][area]
        usedI = usedIndexes[playground][area]
    nextPos = currentPos
    while nextPos == currentPos:
        if len(unusedI) == 0:
            index = whrandom.choice(usedI)
            nextPos = ButterflyPoints[playground][area][index]
        else:
            index = whrandom.choice(unusedI)
            nextPos = ButterflyPoints[playground][area][index]
            if nextPos != currentPos:
                unusedI.remove(index)
                usedI.append(index)

    dist = Vec3(nextPos - currentPos).length()
    time = dist / BUTTERFLY_SPEED + BUTTERFLY_TAKEOFF[playground] + BUTTERFLY_LANDING[playground]
    return (
     nextPos, index, time)
    return
Exemplo n.º 3
0
def testConfig():
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]
    loggers = ['', 'area1', 'area2']
    for i in xrange(1000):
        logger = logging.getLogger(choice(loggers))
        level = choice(levels)
        logger.log(level, "Message number %d", i)
    def enter(self, toon, shopsVisited=[]):
        base.disableMouse()
        self.toon = toon
        self.dna = toon.getStyle()
        colorList = self.getGenderColorList(self.dna)
        if COLORSHOP not in shopsVisited:
            self.headChoice = whrandom.choice(colorList)
            self.armChoice = self.headChoice
            self.legChoice = self.headChoice
            self.startColor = self.headChoice
            self._ColorShop__swapHeadColor(0)
            self._ColorShop__swapArmColor(0)
            self._ColorShop__swapLegColor(0)
            self.allLButton['state'] = DISABLED
            self.headLButton['state'] = DISABLED
            self.armLButton['state'] = DISABLED
            self.legLButton['state'] = DISABLED
        else:

            try:
                self.headChoice = colorList.index(self.dna.headColor)
                self.armChoice = colorList.index(self.dna.armColor)
                self.legChoice = colorList.index(self.dna.legColor)
            except:
                self.headChoice = whrandom.choice(colorList)
                self.armChoice = self.headChoice
                self.legChoice = self.headChoice
                self._ColorShop__swapHeadColor(0)
                self._ColorShop__swapArmColor(0)
                self._ColorShop__swapLegColor(0)

        self.acceptOnce('last', self._ColorShop__handleBackward)
        self.acceptOnce('next', self._ColorShop__handleForward)
        return None
Exemplo n.º 5
0
    def enter(self, toon, shopsVisited = []):
        base.disableMouse()
        self.toon = toon
        self.dna = toon.getStyle()
        colorList = self.getGenderColorList(self.dna)
        if COLORSHOP not in shopsVisited:
            self.headChoice = whrandom.choice(colorList)
            self.armChoice = self.headChoice
            self.legChoice = self.headChoice
            self.startColor = self.headChoice
            self._ColorShop__swapHeadColor(0)
            self._ColorShop__swapArmColor(0)
            self._ColorShop__swapLegColor(0)
            self.allLButton['state'] = DISABLED
            self.headLButton['state'] = DISABLED
            self.armLButton['state'] = DISABLED
            self.legLButton['state'] = DISABLED
        else:
            
            try:
                self.headChoice = colorList.index(self.dna.headColor)
                self.armChoice = colorList.index(self.dna.armColor)
                self.legChoice = colorList.index(self.dna.legColor)
            except:
                self.headChoice = whrandom.choice(colorList)
                self.armChoice = self.headChoice
                self.legChoice = self.headChoice
                self._ColorShop__swapHeadColor(0)
                self._ColorShop__swapArmColor(0)
                self._ColorShop__swapLegColor(0)

        self.acceptOnce('last', self._ColorShop__handleBackward)
        self.acceptOnce('next', self._ColorShop__handleForward)
        return None
Exemplo n.º 6
0
def createTestCases(n):
	n=int(n)
	g1 = [[0] * n for i in range(n)]
	for i in range(0,rand.choice(range(n))*rand.choice(range(n))):
    		j=rand.choice(range(n))
    		k=rand.choice(range(n))
		g1[j][k]=g1[k][j]=1
	pi_orig = get_random_isomorphism (len(g1))
	gP = get_isomorphic_graph(g1, pi_orig)
	
	g2 = get_isomorphic_graph(g1, pi_orig)
	si={};
	si["VD"]=[];
	
	for i in range(0,rand.choice(range(n))):
    		j=rand.choice(range(n))
		si["VD"].append(j)
	si["VD"] = list(set(si["VD"]))
	si["VD"].sort(reverse=False);
	for i in si["VD"]:
		g2.insert(i,[0]*len(g2))
		for elements in g2:
			elements.insert(i,0)
			
	si["ER"]=[];
	
	for i in range(0,rand.choice(range(len(g2)))*rand.choice(range(len(g2)))):
    		j=rand.choice(range(len(g2)))
    		k=rand.choice(range(len(g2)))
		if (g2[j][k]==0):
			g2[j][k]=g2[k][j]=1
			si["ER"].append([j,k])
	
        
	fname = "../data/commonInput_%d.txt"%(n)
	fp = open(fname, 'w')
	gname = "../data/proverInput_%d.txt"%(n)
	gp = open(gname, 'w')
 	fp.write("%d\n"%len(g1))
	fp.write(commit.prettyPrintMatrixSpc(g1)+"\n")
 	fp.write("%d\n"%len(g2))
	fp.write(commit.prettyPrintMatrixSpc(g2)+"\n")

	gp.write("ER ")
	for elements in si["ER"]:
		gp.write(str(elements[0])+","+str(elements[1])+" ")
	gp.write("\n")
	gp.write("VD " + " ".join(map(str,si["VD"])) + "\n")
	gp.write(" ".join(map(str,pi_orig.values()))+"\n")

	gp1=get_subgraph(si, g2);
	gp2=get_isomorphic_graph(g1, pi_orig);

	print commit.prettyPrintMatrix(gp1)+"\n"
	print commit.prettyPrintMatrix(gp2)+"\n"
	print commit.prettyPrintMatrix(gP)+"\n"

	return g1,g2,pi_orig,si,gP
Exemplo n.º 7
0
def testConfig():
    levels = [
        logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
        logging.CRITICAL
    ]
    loggers = ['', 'area1', 'area2']
    for i in xrange(1000):
        logger = logging.getLogger(choice(loggers))
        level = choice(levels)
        logger.log(level, "Message number %d", i)
Exemplo n.º 8
0
 def getRandomCongratsPair(self, toon):
     congratsStrings = Localizer.RewardPanelCongratsStrings
     numStrings = len(congratsStrings)
     indexList = range(numStrings)
     index1 = whrandom.choice(indexList)
     indexList.remove(index1)
     index2 = whrandom.choice(indexList)
     string1 = congratsStrings[index1]
     string2 = congratsStrings[index2]
     return (string1, string2)
Exemplo n.º 9
0
    def set (self, password, isCrypted = 0):
	if isCrypted:
	    self.crypt = password
	    self.pure = None
	else:
            salt = (whrandom.choice (string.letters +
                                     string.digits + './') + 
                    whrandom.choice (string.letters +
                                     string.digits + './'))
            self.crypt = crypt.crypt (password, salt)
	    self.pure = password
Exemplo n.º 10
0
def passcrypt(passwd, salt=None, method='md5', magic='$1$'):
    """Encrypt a string according to rules in crypt(3)."""

    if method.lower() == 'des':
        if not salt:
            salt = str(whrandom.choice(DES_SALT)) + \
              str(whrandom.choice(DES_SALT))

        return crypt.crypt(passwd, salt)
    elif method.lower() == 'md5':
        return passcrypt_md5(passwd, salt, magic)
    elif method.lower() == 'clear':
        return passwd
Exemplo n.º 11
0
def passcrypt(passwd, salt=None, method='md5', magic='$1$'):
    """Encrypt a string according to rules in crypt(3)."""
    
    if method.lower() == 'des':
	if not salt:
	    salt = str(whrandom.choice(DES_SALT)) + \
	      str(whrandom.choice(DES_SALT))

	return crypt.crypt(passwd, salt)
    elif method.lower() == 'md5':
	return passcrypt_md5(passwd, salt, magic)
    elif method.lower() == 'clear':
        return passwd
Exemplo n.º 12
0
def __healToon(toon, hp, ineffective):
    notify.debug('healToon() - toon: %d hp: %d ineffective: %d' % (toon.doId, hp, ineffective))
    if ineffective == 1:
        laughter = whrandom.choice(Localizer.MovieHealLaughterMisses)
    else:
        maxDam = AvPropDamage[0][1][0][1]
        if hp >= maxDam - 1:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits2)
        else:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits1)
    toon.setChatAbsolute(laughter, CFSpeech | CFTimeout)
    if hp > 0 and toon.hp != None:
        toon.setHp(min(toon.maxHp, toon.hp + hp))
    else:
        notify.debug('__healToon() - toon: %d hp: %d' % (toon.doId, hp))
 def remoteButtonPressed(self, avId, index, wrong):
     if not self.gameFSM.getCurrentState().getName() in [
             'getUserInput', 'waitForPlayerPatterns'
     ]:
         return
     if avId != self.localAvId:
         if self.animTracks[avId]:
             self.animTracks[avId].finish()
         av = self.getAvatar(avId)
         if wrong:
             acts = ['slip-forward', 'slip-backward']
             ag = whrandom.choice(acts)
             self.arrowDict[avId][0].hide()
             self.animTracks[avId] = Sequence(
                 Func(self.showX, avId),
                 Func(self.colorStatusBall, avId,
                      self.__otherToonIndex[avId], 0),
                 ActorInterval(actor=av, animName=ag, duration=2.35),
                 Func(av.loop, 'neutral'), Func(self.hideX, avId))
         else:
             self.colorStatusBall(avId, self.__otherToonIndex[avId], 1)
             arrowTrack = self.getDanceArrowAnimTrack(avId, [index], 1)
             potTrack = self.getDanceSequenceAnimTrack(av, [index])
             self.animTracks[avId] = Parallel(potTrack, arrowTrack)
         self.__otherToonIndex[avId] += 1
         self.animTracks[avId].start()
 def __buttonPressed(self, index):
     if len(self.__localPattern) >= len(self.__serverPattern):
         return
     if self.animTracks[self.localAvId]:
         self.animTracks[self.localAvId].finish()
     badd = 0
     if index != self.__serverPattern[len(self.__localPattern)]:
         badd = 1
         acts = ['slip-forward', 'slip-backward']
         ag = whrandom.choice(acts)
         self.animTracks[self.localAvId] = Sequence(
             Func(self.showX, 'lt'),
             Func(self.colorStatusBall, 'lt', len(self.__localPattern), 0),
             ActorInterval(actor=self.lt, animName=ag, duration=2.35),
             Func(self.lt.loop, 'neutral'), Func(self.hideX, 'lt'))
         self.arrowDict['lt'][0].hide()
         base.playSfx(self.fallSound)
     else:
         self.colorStatusBall('lt', len(self.__localPattern), 1)
         base.playSfx(self.__getButtonSound(index))
         arrowTrack = self.getDanceArrowAnimTrack('lt', [index], 1)
         potTrack = self.getDanceSequenceAnimTrack(self.lt, [index])
         self.animTracks[self.localAvId] = Parallel(potTrack, arrowTrack)
     self.sendUpdate('reportButtonPress', [index, badd])
     self.animTracks[self.localAvId].start()
     self.__localPattern.append(index)
     if len(self.__localPattern) == len(self.__serverPattern) or badd:
         self.__doneGettingInput(self.__localPattern)
Exemplo n.º 15
0
    def gotoNode(self, node):
        possiblePoints = (Point3(3, 6, 0), Point3(-3, 6, 0), Point3(6, 6, 0),
                          Point3(-6, 6, 0), Point3(3, 9, 0), Point3(-3, 9, 0),
                          Point3(6, 9, 0), Point3(-6, 9, 0), Point3(9, 9, 0),
                          Point3(-9, 9, 0), Point3(6, 0, 0), Point3(-6, 0, 0),
                          Point3(6, 3, 0), Point3(-6, 3, 0), Point3(9, 9, 0),
                          Point3(-9, 9, 0), Point3(0, 12, 0), Point3(3, 12, 0),
                          Point3(-3, 12, 0), Point3(6, 12,
                                                    0), Point3(-6, 12, 0),
                          Point3(9, 12, 0), Point3(-9, 12,
                                                   0), Point3(0, -6, 0),
                          Point3(-3, -6, 0), Point3(0, -9,
                                                    0), Point3(-6, -9, 0))
        for point in possiblePoints:
            pos = self.positionExaminer.consider(node, point)
            if pos:
                self.setPos(node, pos)
                self.lookAt(node)
                self.setHpr(self.getH() + whrandom.choice((-10, 10)), 0, 0)
                base.drive.node().setPos(self.getPos())
                base.drive.node().setHpr(self.getHpr())
                return

        self.setPos(node, 0, 0, 0)
        base.drive.node().setPos(self.getPos())
        base.drive.node().setHpr(self.getHpr())
Exemplo n.º 16
0
 def _DistributedPatternGame__buttonPressed(self, index):
     if len(self._DistributedPatternGame__localPattern) >= len(self._DistributedPatternGame__serverPattern):
         return None
     
     if self.animTracks[self.localAvId]:
         self.animTracks[self.localAvId].finish()
     
     badd = 0
     if index != self._DistributedPatternGame__serverPattern[len(self._DistributedPatternGame__localPattern)]:
         badd = 1
         acts = [
             'slip-forward',
             'slip-backward']
         ag = whrandom.choice(acts)
         self.animTracks[self.localAvId] = Sequence(Func(self.showX, 'lt'), Func(self.colorStatusBall, 'lt', len(self._DistributedPatternGame__localPattern), 0), ActorInterval(actor = self.lt, animName = ag, duration = 2.3500000000000001), Func(self.lt.loop, 'neutral'), Func(self.hideX, 'lt'))
         self.arrowDict['lt'][0].hide()
         base.playSfx(self.fallSound)
     else:
         self.colorStatusBall('lt', len(self._DistributedPatternGame__localPattern), 1)
         base.playSfx(self._DistributedPatternGame__getButtonSound(index))
         arrowTrack = self.getDanceArrowAnimTrack('lt', [
             index], 1)
         potTrack = self.getDanceSequenceAnimTrack(self.lt, [
             index])
         self.animTracks[self.localAvId] = Parallel(potTrack, arrowTrack)
     self.sendUpdate('reportButtonPress', [
         index,
         badd])
     self.animTracks[self.localAvId].start()
     self._DistributedPatternGame__localPattern.append(index)
     if len(self._DistributedPatternGame__localPattern) == len(self._DistributedPatternGame__serverPattern) or badd:
         self._DistributedPatternGame__doneGettingInput(self._DistributedPatternGame__localPattern)
Exemplo n.º 17
0
def chooseHealOpenShot(heals, attackDuration):
    numHeals = len(heals)
    av = None
    duration = 2.7999999999999998
    shotChoices = [toonGroupShot]
    track = apply(whrandom.choice(shotChoices), [av, duration])
    return track
Exemplo n.º 18
0
 def get_drop_point(self, drop_point_list):
     if self.dbg_drop_mode == 0:
         return whrandom.choice(drop_point_list)
     else:
         droppnt = self.current_drop_point % len(drop_point_list)
         self.current_drop_point = (self.current_drop_point + 1) % len(drop_point_list)
         return drop_point_list[droppnt]
Exemplo n.º 19
0
def invent_passwd(length=6):
    """Invent a password. Not industry-strenght but good enough for us"""
    ok = "abcdefghijkmnopqrstuvwxyz023456789"
    rv = ''
    for i in range(length):
        rv = rv + whrandom.choice(ok)
    return rv
Exemplo n.º 20
0
 def grab(self, n):
     retval = []
     for i in range(min(n, len(self.list))):
         c = whrandom.choice(self.list)
         self.list.remove(c)
         retval.append(c)
     return retval
Exemplo n.º 21
0
def chooseSOSShot(av, duration):
    shotChoices = [
        avatarCloseUpThreeQuarterRightShot, avatarBehindShot,
        avatarBehindHighShot, suitGroupThreeQuarterLeftBehindShot
    ]
    track = apply(whrandom.choice(shotChoices), [av, duration])
    return track
Exemplo n.º 22
0
 def remoteButtonPressed(self, avId, index, wrong):
     if not (self.gameFSM.getCurrentState().getName() in [
         'getUserInput',
         'waitForPlayerPatterns']):
         return None
     
     if avId != self.localAvId:
         if self.animTracks[avId]:
             self.animTracks[avId].finish()
         
         av = self.getAvatar(avId)
         if wrong:
             acts = [
                 'slip-forward',
                 'slip-backward']
             ag = whrandom.choice(acts)
             self.arrowDict[avId][0].hide()
             self.animTracks[avId] = Sequence(Func(self.showX, avId), Func(self.colorStatusBall, avId, self._DistributedPatternGame__otherToonIndex[avId], 0), ActorInterval(actor = av, animName = ag, duration = 2.3500000000000001), Func(av.loop, 'neutral'), Func(self.hideX, avId))
         else:
             self.colorStatusBall(avId, self._DistributedPatternGame__otherToonIndex[avId], 1)
             arrowTrack = self.getDanceArrowAnimTrack(avId, [
                 index], 1)
             potTrack = self.getDanceSequenceAnimTrack(av, [
                 index])
             self.animTracks[avId] = Parallel(potTrack, arrowTrack)
         self._DistributedPatternGame__otherToonIndex[avId] += 1
         self.animTracks[avId].start()
Exemplo n.º 23
0
def chooseLureOpenShot(lures, attackDuration):
    numLures = len(lures)
    av = None
    duration = 3.0
    shotChoices = [allGroupLowShot]
    track = apply(whrandom.choice(shotChoices), [av, duration])
    return track
Exemplo n.º 24
0
def nonRedundantSet(d, threshold, distanceMatrix=1):
    """
    returns an array consisting of entries having
    a maximum similarity (or distance) of 'threshold'.
    distanceMatrix <> None means matrix elemens are similarities.

    Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417

    gives somehow weired results.
    """
    import whrandom  #@UnresolvedImport

    d = Numeric.array(d).astype(Float32)
    if not distanceMatrix: d = less(d, threshold)
    else: d = greater(d, threshold)

    s = shape(d)
    d = Numeric.concatenate((reshape(range(s[0]), (-1, 1)), d), 1)

    ok = 1

    while ok:
        nNeighbours = Numeric.sum(d)
        if len(nNeighbours) <= 1: break
        maxx = max(nNeighbours[1:])
        others = Numeric.nonzero(equal(nNeighbours[1:], maxx)) + 1
        candidate = whrandom.choice(others)
        ok = nNeighbours[candidate]
        if ok: d = deleteRowAndColumn(d, candidate - 1, candidate)
    # end while

    return d[:, 0]
Exemplo n.º 25
0
def login(req, username, password):

    user = dms.username.get_by_id(username)
    if user and user.username==username:
        if user.password == password:
            if not sessions.has_key(username):
                sessions.add(username, req.connection.remote_addr[0])
    
            # establish random 20 character session_id.
            # 
            chars = string.letters + string.digits
            session_id = ''
            for x in range(20):
                session_id += whrandom.choice(chars)
            user.session_id = session_id
            user.save()
                    
            log(3, 'setting cookie')
            req.headers_out['Set-Cookie']='lampadas=' + session_id + '; path=/; expires=Wed, 09-Nov-2030 23:59:00 GMT'
            uri = URI('home' + referer_lang_ext(req))
            uri.base = '../../'
            return page_factory.page(uri)
        else:
            return "Wrong password"
    else:
        return "User not found"
Exemplo n.º 26
0
def nonRedundantSet(d, threshold, distanceMatrix = 1):
    """
    returns an array consisting of entries having
    a maximum similarity (or distance) of 'threshold'.
    distanceMatrix <> None means matrix elemens are similarities.

    Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417

    gives somehow weired results.
    """
    import whrandom #@UnresolvedImport

    d = Numeric.array(d).astype(Float32)
    if not distanceMatrix: d = less(d, threshold)
    else: d = greater(d, threshold)

    s = shape(d)
    d = Numeric.concatenate((reshape(range(s[0]),(-1,1)),d),1)

    ok = 1

    while ok:
        nNeighbours = Numeric.sum(d)
        if len(nNeighbours) <= 1: break
        maxx = max(nNeighbours[1:])
        others = Numeric.nonzero(equal(nNeighbours[1:], maxx))+1
        candidate = whrandom.choice(others)
        ok = nNeighbours[candidate]
        if ok: d = deleteRowAndColumn(d, candidate-1, candidate)
    # end while
    
    return d[:,0]
def __healToon(toon, hp, ineffective):
    notify.debug('healToon() - toon: %d hp: %d ineffective: %d' %
                 (toon.doId, hp, ineffective))
    if ineffective == 1:
        laughter = whrandom.choice(Localizer.MovieHealLaughterMisses)
    else:
        maxDam = AvPropDamage[0][1][0][1]
        if hp >= maxDam - 1:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits2)
        else:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits1)
    toon.setChatAbsolute(laughter, CFSpeech | CFTimeout)
    if hp > 0 and toon.hp != None:
        toon.setHp(min(toon.maxHp, toon.hp + hp))
    else:
        notify.debug('__healToon() - toon: %d hp: %d' % (toon.doId, hp))
Exemplo n.º 28
0
    def warp_password(self):
        """Warps around the chars in the password."""
        import string

        warps = {}
        # add the alphabet to the warplist
        for x in xrange(ord('a'), ord('z')+1):
            x = chr(x)
            warps[x] = [x, x.upper()]

        # add some specials
        specialchars = (("a", ["@", "4"]),
                        ("e", ["3"]),
                        ("g", ["6"]),
                        ("i", ["1", "|", "!"]),
                        ("l", ["1", "|", "!"]),
                        ("o", ["0"]),
                        ("s", ["5", "z", "Z"]),
                        ("t", ["+", "7"]),
                        ("z", ["s", "S", "2"]))

        for (a,b) in specialchars:
            warps[a] += b

        randoms = 0
        warped_password = ""
        # warp the chars in the password
        for i in self.password:
            if i in warps.keys():
                # 75% probability
                if randint(0, 3):
                    warped_password += choice(warps[i])
                else:
                    warped_password += i
            else:
                warped_password += i

            # add a random character (max two)
            if randint(0, 5) == 0 and randoms < 2:
                warped_password += choice("\/_.,!;:'+-=")
                randoms += 1

#        print "unwarped pass = "******"warped pass   = ", warped_password

        return warped_password
Exemplo n.º 29
0
 def genName(
     self
 ):  #Name is generated here, 1-15 chars from the full alphanumeric range
     chars = string.letters + string.digits
     name = ''
     for i in range(random.randint(1, 15)):
         name += choice(chars)
     return name
Exemplo n.º 30
0
 def get_drop_point(self, drop_point_list):
     if self.dbg_drop_mode == 0:
         return whrandom.choice(drop_point_list)
     else:
         droppnt = self.current_drop_point % len(drop_point_list)
         self.current_drop_point = (self.current_drop_point +
                                    1) % len(drop_point_list)
         return drop_point_list[droppnt]
Exemplo n.º 31
0
def challengeSend(f, password):
	cList = []
	for i in range(16):
		cList.append(whrandom.choice(CharSet))
	challenge = string.join(cList, '')
	f.write('%s\n' % x509.RC4(password, challenge, 0, len(challenge)))
	f.flush()
	return challenge
def challengeSend(f, password):
    cList = []
    for i in range(16):
        cList.append(whrandom.choice(CharSet))
    challenge = string.join(cList, '')
    f.write('%s\n' % x509.RC4(password, challenge, 0, len(challenge)))
    f.flush()
    return challenge
Exemplo n.º 33
0
def response( char, args, target ):
	if not char:
		return False

	if skills.skilltable[ HEALING ][ skills.UNHIDE ] and char.hidden:
		char.removefromview()
		char.hidden = False
		char.update()

	if not target.char:
		char.socket.clilocmessage( 500970, "", 0x3b2, 3 )
		return True
	# will be added : a golem would not healed by bandages

	# count bandage
	if not char.countresource( 0x0e21 ):
		return True

	anatomy = char.skill[ ANATOMY ]
	healing = char.skill[ HEALING ]

	# dead char : res it
	if target.char.dead:
		# you cannot res yourself
		if char == target.char:
			#char.socket.clilocmessage()
			return True
		if healing >= RES_HEALING and anatomy >= RES_ANATOMY:
			res_char( char, target.char, healing, anatomy )
		else:
			char.socket.clilocmessage( 1049656, "", 0x3b2, 3 )
		return True
	if target.char.poisoned:
		if healing >= CURE_HEALING and anatomy >= CURE_ANATOMY:
			cure_char( char, target.char, healing, anatomy )
		#else:
			#char.socket.clilocmessage()
		return True

	# calc total heal amount : used formula from UOSS
	heal_min = 3 + ( char.skill[ ANATOMY ] + char.skill[ HEALING ] ) / 50
	heal_max = 10 + char.skill[ ANATOMY ] / 50 + char.skill[ HEALING ] / 20
	heal_amount = whrandom.choice( range( heal_min, heal_max ) )
	if not heal_amount:
		heal_amount = 1

	# calc total delay : used formula from UOSS
	if char == target.char:
		delay = 9400 + 60 * ( 120 - char.dexterity )
	else:
		delay = HEAL_OTHER_DELAY

	char.socket.clilocmessage( 500956, "", 0x3b2, 3 )
	# loop
	start_time = wolfpack.time.servertime()
	end_time = start_time + delay
	chance = 1
	char.addtimer( CHECK_DELAY, "skills.healing.delay_check", [ resto.serial, chance, start_time, end_time, heal_amount + 2 ] )
Exemplo n.º 34
0
def test():
    print "Running Test Vectors"
    print "--------------------"
    # (plaintext, key, ciphertext)
    vectors = [("AAAAAAAAAAAAAAA", "", "EXKYIZSGEHUNTIQ"),
               ("AAAAAAAAAAAAAAA", "f", "XYIUQBMHKKJBEGY"),
               ("AAAAAAAAAAAAAAA", "foo", "ITHZUJIWGRFARMW"),
               ("AAAAAAAAAAAAAAA", "a", "XODALGSCULIQNSC"),
               ("AAAAAAAAAAAAAAA", "aa", "OHGWMXXCAIMCIQP"),
               ("AAAAAAAAAAAAAAA", "aaa", "DCSQYHBQZNGDRUT"),
               ("AAAAAAAAAAAAAAA", "b", "XQEEMOITLZVDSQS"),
               ("AAAAAAAAAAAAAAA", "bc", "QNGRKQIHCLGWSCE"),
               ("AAAAAAAAAAAAAAA", "bcd", "FMUBYBMAXHNQXCJ"),
               ("AAAAAAAAAAAAAAAAAAAAAAAAA", "cryptonomicon",
                "SUGSRSXSWQRMXOHIPBFPXARYQ"),
               ("SOLITAIRE", "cryptonomicon", "KIRAKSFJAN")]
    for i in vectors:
        s = SolitaireCipher()
        s.KeyDeck(i[1])
        ciphertext = s.Encrypt(i[0])
        if (ciphertext == i[2]):
            print "passed!"
        else:
            print "FAILED!"
        print "plaintext           = " + i[0]
        print "key                 = " + i[1]
        print "expected ciphertext =",
        PrintInFives(i[2])
        print "got ciphertext      =",
        PrintInFives(ciphertext)
        print
    print "Test bijectivity (i.e. make sure that D(E(m)) == m"
    print "--------------------------------------------------"
    from whrandom import choice, randint
    from string import uppercase
    for i in range(0, 5):
        p = ""
        for i in range(0, randint(10, 25)):
            p = p + choice(uppercase)
        s = SolitaireCipher()
        s.KeyDeck("SECRETKEY")
        c = s.Encrypt(p)
        s = SolitaireCipher()
        s.KeyDeck("SECRETKEY")
        r = s.Decrypt(c)
        if (r[:len(p)] == p):
            print "passed!"
        else:
            print "FAILED!"
        print "Random plaintext =",
        PrintInFives(p)
        print "ciphertext       =",
        PrintInFives(c)
        print "decrypt          =",
        PrintInFives(r[:len(p)])

        print
Exemplo n.º 35
0
def get_random_isomorphism(n):
    s = range(n)
    isomorphism = {}
    for i in range(n):
        element = rand.choice(s)
        isomorphism[i] = element
        s.remove(element)

    return isomorphism
def __getCurrentPos(playground, area, avId=None):
    if avId != None:
        if estateIndexes.has_key(avId):
            unusedI = estateIndexes[avId][0][area]
            usedI = estateIndexes[avId][1][area]
        else:
            return (ButterflyPoints[playground][area][0], 0)
    else:
        unusedI = unusedIndexes[playground][area]
        usedI = usedIndexes[playground][area]
    if len(unusedI) == 0:
        index = whrandom.choice(usedI)
        return (ButterflyPoints[playground][area][index], index)

    index = whrandom.choice(unusedI)
    unusedI.remove(index)
    usedI.append(index)
    return (ButterflyPoints[playground][area][index], index)
Exemplo n.º 37
0
def chooseHealCloseShot(heals, openDuration, openName, attackDuration):
    av = None
    duration = attackDuration - openDuration
    shotChoices = [
        toonGroupShot]
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    return track
Exemplo n.º 38
0
 def chooseRewardShotNow(av):
     if av.playingAnim == 'victory':
         shotChoices = [
             (0, 8, av.getHeight() * 0.66000000000000003, 179, 15, 0),
             (5.2000000000000002, 5.4500000000000002, av.getHeight() * 0.66000000000000003, 131.5, 3.6000000000000001, 0)]
         shot = whrandom.choice(shotChoices)
         camera.setPosHpr(av, *shot)
     else:
         camera.setPosHpr(10, 0, 10, 115, -30, 0)
Exemplo n.º 39
0
def __getCurrentPos(playground, area, avId = None):
    if avId != None:
        if estateIndexes.has_key(avId):
            unusedI = estateIndexes[avId][0][area]
            usedI = estateIndexes[avId][1][area]
        else:
            return (ButterflyPoints[playground][area][0], 0)
    else:
        unusedI = unusedIndexes[playground][area]
        usedI = usedIndexes[playground][area]
    if len(unusedI) == 0:
        index = whrandom.choice(usedI)
        return (ButterflyPoints[playground][area][index], index)
    
    index = whrandom.choice(unusedI)
    unusedI.remove(index)
    usedI.append(index)
    return (ButterflyPoints[playground][area][index], index)
Exemplo n.º 40
0
def chooseTrapCloseShot(traps, openDuration, openName, attackDuration):
    av = None
    duration = attackDuration - openDuration
    shotChoices = [
        allGroupLowShot]
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    return track
Exemplo n.º 41
0
    def fetch_word_from_dictionary(self, min_chars):
        """Get a word from a dictionary with minimum [min_chars] characters."""
        word  = ""
        words = open(dictionary_file, "r").readlines()
        while len(word) < min_chars:
            word = choice(words)

        word = word.lower().strip()
        return word
Exemplo n.º 42
0
    def fetch_word_from_dictionary(self, min_chars):
        """Get a word from a dictionary with minimum [min_chars] characters."""
        word = ""
        words = open(dictionary_file, "r").readlines()
        while len(word) < min_chars:
            word = choice(words)

        word = word.lower().strip()
        return word
Exemplo n.º 43
0
def chooseSOSShot(av, duration):
    shotChoices = [
        avatarCloseUpThreeQuarterRightShot,
        avatarBehindShot,
        avatarBehindHighShot,
        suitGroupThreeQuarterLeftBehindShot]
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    return track
Exemplo n.º 44
0
def chooseHealOpenShot(heals, attackDuration):
    numHeals = len(heals)
    av = None
    duration = 2.7999999999999998
    shotChoices = [
        toonGroupShot]
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    return track
Exemplo n.º 45
0
def chooseLureOpenShot(lures, attackDuration):
    numLures = len(lures)
    av = None
    duration = 3.0
    shotChoices = [
        allGroupLowShot]
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    return track
Exemplo n.º 46
0
    def warp_password(self):
        """Warps around the chars in the password."""
        import string

        warps = {}
        # add the alphabet to the warplist
        for x in xrange(ord('a'), ord('z') + 1):
            x = chr(x)
            warps[x] = [x, x.upper()]

        # add some specials
        specialchars = (("a", ["@", "4"]), ("e", ["3"]), ("g", ["6"]),
                        ("i", ["1", "|", "!"]), ("l", ["1", "|",
                                                       "!"]), ("o", ["0"]),
                        ("s", ["5", "z",
                               "Z"]), ("t", ["+", "7"]), ("z", ["s", "S",
                                                                "2"]))

        for (a, b) in specialchars:
            warps[a] += b

        randoms = 0
        warped_password = ""
        # warp the chars in the password
        for i in self.password:
            if i in warps.keys():
                # 75% probability
                if randint(0, 3):
                    warped_password += choice(warps[i])
                else:
                    warped_password += i
            else:
                warped_password += i

            # add a random character (max two)
            if randint(0, 5) == 0 and randoms < 2:
                warped_password += choice("\/_.,!;:'+-=")
                randoms += 1

#        print "unwarped pass = "******"warped pass   = ", warped_password

        return warped_password
 def getLookAtPosition(self, toonHead, toonidx):
     lookAtChoice = whrandom.random()
     if len(self.used_panel_indexs) == 1:
         lookFwdPercent = 0.33000000000000002
         lookAtOthersPercent = 0
     else:
         lookFwdPercent = 0.20000000000000001
         if len(self.used_panel_indexs) == 2:
             lookAtOthersPercent = 0.40000000000000002
         else:
             lookAtOthersPercent = 0.65000000000000002
     lookRandomPercent = 1.0 - lookFwdPercent - lookAtOthersPercent
     if lookAtChoice < lookFwdPercent:
         self.IsLookingAt[toonidx] = 'f'
         return Vec3(0, 1.5, 0)
     elif lookAtChoice < lookRandomPercent + lookFwdPercent or len(self.used_panel_indexs) == 1:
         self.IsLookingAt[toonidx] = 'r'
         return toonHead.getRandomForwardLookAtPoint()
     else:
         other_toon_idxs = []
         for i in range(len(self.IsLookingAt)):
             if self.IsLookingAt[i] == toonidx:
                 other_toon_idxs.append(i)
             
         
         if len(other_toon_idxs) == 1:
             IgnoreStarersPercent = 0.40000000000000002
         else:
             IgnoreStarersPercent = 0.20000000000000001
         NoticeStarersPercent = 0.5
         bStareTargetTurnsToMe = 0
         if len(other_toon_idxs) == 0 or whrandom.random() < IgnoreStarersPercent:
             other_toon_idxs = []
             for i in self.used_panel_indexs:
                 if i != toonidx:
                     other_toon_idxs.append(i)
                 
             
             if whrandom.random() < NoticeStarersPercent:
                 bStareTargetTurnsToMe = 1
             
         
         lookingAtIdx = whrandom.choice(other_toon_idxs)
         if bStareTargetTurnsToMe:
             self.IsLookingAt[lookingAtIdx] = toonidx
             otherToonHead = None
             for panel in self.panelList:
                 if panel.position == lookingAtIdx:
                     otherToonHead = panel.headModel
                 
             
             otherToonHead.doLookAroundToStareAt(otherToonHead, self.getLookAtToPosVec(lookingAtIdx, toonidx))
         
         self.IsLookingAt[toonidx] = lookingAtIdx
         return self.getLookAtToPosVec(toonidx, lookingAtIdx)
Exemplo n.º 48
0
def chooseSuitCloseShot(attack, openDuration, openName, attackDuration):
    av = None
    duration = attackDuration - openDuration
    if duration < 0:
        duration = 9.9999999999999995e-007
    
    groupStatus = attack['group']
    diedTrack = None
    if groupStatus == ATK_TGT_SINGLE:
        av = attack['target']['toon']
        shotChoices = [
            avatarCloseUpThreeQuarterRightShot,
            suitGroupThreeQuarterLeftBehindShot]
        died = attack['target']['died']
        if died != 0:
            pbpText = attack['playByPlayText']
            diedText = av.getName() + ' was defeated!'
            diedTextList = [
                diedText]
            diedTrack = pbpText.getToonsDiedInterval(diedTextList, duration)
        
    elif groupStatus == ATK_TGT_GROUP:
        av = None
        shotChoices = [
            allGroupLowShot,
            suitGroupThreeQuarterLeftBehindShot]
        deadToons = []
        targetDicts = attack['target']
        for targetDict in targetDicts:
            died = targetDict['died']
            if died != 0:
                deadToons.append(targetDict['toon'])
            
        
        if len(deadToons) > 0:
            pbpText = attack['playByPlayText']
            diedTextList = []
            for toon in deadToons:
                pbpText = attack['playByPlayText']
                diedTextList.append(toon.getName() + ' was defeated!')
            
            diedTrack = pbpText.getToonsDiedInterval(diedTextList, duration)
        
    else:
        notify.error('Bad groupStatus: %s' % groupStatus)
    track = apply(whrandom.choice(shotChoices), [
        av,
        duration])
    if diedTrack == None:
        return track
    else:
        mtrack = MultiTrack([
            track,
            diedTrack])
        return mtrack
Exemplo n.º 49
0
    def reply(self, sentence):
        keywords = []
	for k in self.parse(sentence):
	    if k[0] in string.letters and k not in \
	        STOPLIST:
		try: k = SWAPLIST[k]
		except KeyError: pass
		if k not in keywords: keywords.append(k)
	    
        keys = self.markov.keys()
	candidates = []
	for keyword in keywords:
	    seeds = filter(lambda s, k=keyword: s[3] == k, keys)
	    if seeds:
	        # generate 10 replies per keyword
	        for i in range(10):
	            candidate = self.generate_sentence(list(whrandom.choice(seeds)))
		    # Calculate the probability of each keywords' appearing
		    # in its position
		    # This is a total hack.
		    total_logprob = 0
		    num_keywords = 0
		    key = [None, None, None, None]
		    for symbol in candidate:
		        if symbol in keywords:
			    total_logprob = total_logprob - \
			        log(self.markov[tuple(key)][1].prob(symbol))
			    num_keywords = num_keywords + 1

			del key[0]
			key.append(symbol)

		    # Insert them in random order.
		    candidates.insert(whrandom.randint(0, len(candidates)), (total_logprob/num_keywords, candidate))


	if not candidates:
	    return 0.0, ''.join(self.generate_sentence(list(whrandom.choice(keys)))).capitalize()

	candidates.sort(lambda a, b: cmp(a[0], b[0]))
	avg_logprob, sentence = candidates[-1]
	return avg_logprob, ''.join(sentence).capitalize()
Exemplo n.º 50
0
 def chooseRewardShotNow(av):
     if av.playingAnim == 'victory':
         shotChoices = [(0, 8, av.getHeight() * 0.66000000000000003, 179,
                         15, 0),
                        (5.2000000000000002, 5.4500000000000002,
                         av.getHeight() * 0.66000000000000003, 131.5,
                         3.6000000000000001, 0)]
         shot = whrandom.choice(shotChoices)
         camera.setPosHpr(av, *shot)
     else:
         camera.setPosHpr(10, 0, 10, 115, -30, 0)
Exemplo n.º 51
0
def random_string(length):
    """
    Returns a string of random alphanumeric characters.
    It is intended for password generation, although it can
    be used for other purposes as well.
    """
    
    chars = string.letters + string.digits
    password = ''
    for x in range(length):
        password += whrandom.choice(chars)
    return password
Exemplo n.º 52
0
Arquivo: test.py Projeto: jeske/netcon
    def test_addData(self):
        ndb = self.ndb
        datamanager = nc_datamgr.NCDataManager(ndb)    

        # add some new data
        datamanager.handleRawData("t1","disk/size:total","t4","sda1",24232920)

        datamanager.handleRawData("t1","disk/size:cur","t4","sda1",100)
        datamanager.handleRawData("t1","disk/size:cur","t4","sda1",200)

        curdisk = [1,1,1,1,1,1,1,1,1,1,1,5,5]
        datamanager.handleRawData("t5","disk/size:cur","t5","sda1",whrandom.choice(curdisk))
Exemplo n.º 53
0
def generatePassword(minlen=5, maxlen=10):
 chars = string.letters + string.digits
 passwd = ""
 
 # determine password size (randomly, but between the given range)
 passwd_size = whrandom.randint(minlen, maxlen)

 for x in range(passwd_size):
  # choose a random alpha-numeric character
  passwd += whrandom.choice(chars)

 return passwd
Exemplo n.º 54
0
def generatePassword(minlen=5, maxlen=10):
    chars = string.letters + string.digits
    passwd = ""

    # determine password size (randomly, but between the given range)
    passwd_size = whrandom.randint(minlen, maxlen)

    for x in range(passwd_size):
        # choose a random alpha-numeric character
        passwd += whrandom.choice(chars)

    return passwd
    def newSuitRandom(self, level=None, dept=None):
        self.type = 's'
        if level == None:
            level = whrandom.choice(range(1, len(suitsPerLevel)))
        elif level < 0 or level > len(suitsPerLevel):
            notify.error('Invalid suit level: %d' % level)

        if dept == None:
            dept = whrandom.choice(suitDepts)

        self.dept = dept
        index = suitDepts.index(dept)
        base = index * suitsPerDept
        offset = 0
        if level > 1:
            for i in range(1, level):
                offset = offset + suitsPerLevel[i - 1]

        bottom = base + offset
        top = bottom + suitsPerLevel[level - 1]
        self.name = suitHeadTypes[whrandom.choice(range(bottom, top))]
        self.body = getSuitBodyType(self.name)
Exemplo n.º 56
0
def cryptPassword(password, useMD5):
    if useMD5:
	salt = "$1$"
	saltLen = 8
    else:
	salt = ""
	saltLen = 2

    for i in range(saltLen):
	salt = salt + whrandom.choice (string.letters +
                                       string.digits + './')

    return crypt.crypt (password, salt)
def getAttackTaunt(attackName, index = None):
    if SuitAttackTaunts.has_key(attackName):
        taunts = SuitAttackTaunts[attackName]
    else:
        taunts = Localizer.SuitAttackDefaultTaunts
    if index != None:
        if index >= len(taunts):
            notify.warning('index exceeds length of taunts list in getAttackTaunt')
            return Localizer.SuitAttackDefaultTaunts[0]
        
        return taunts[index]
    else:
        return whrandom.choice(taunts)