当前位置: 首页>>代码示例>>Python>>正文


Python HelperFunctions类代码示例

本文整理汇总了Python中HelperFunctions的典型用法代码示例。如果您正苦于以下问题:Python HelperFunctions类的具体用法?Python HelperFunctions怎么用?Python HelperFunctions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HelperFunctions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: gatherContributions

def gatherContributions(aminoSeqList):
    """ Takes a list of amino acids and returns a list of dictionaries where every entry in the dictionary
     is the base and the contribution of that base to the information for that position
    Args:
        aminoSeqList (string): List of amino acids
    Returns:
        Dictionary: List of Dictionaries
    """
    countsList = HelperFunctions.gatherCounts(aminoSeqList)

    listOfDicts = [0 for x in range(len(countsList))]
    index = 0

    for oneCountList in countsList:
        probabilityPerCount = HelperFunctions.calcProbs(oneCountList)
        probabilityList = [value for key, value in probabilityPerCount.items()]

        entropy = HelperFunctions.entropy(probabilityList)
        info = HelperFunctions.information(entropy, 4)

        for key, value in probabilityPerCount.items():
            if (probabilityPerCount[key] == value):
                probabilityPerCount[key] = value * info

        listOfDicts[index] = probabilityPerCount
        index = index + 1

    return listOfDicts
开发者ID:bressan3,项目名称:Bioinformatics-1,代码行数:28,代码来源:TransmembraneFinder.py

示例2: __init__

    def __init__(self, gameSettings = None):

        ### --------- initialise pygame and set up the window
        pygame.init()
        pygame.display.set_caption(Config.PAGE_TITLE)
        Config.screen.fill(Config.BACKGROUND_COLOUR)


        self.gameScore = 0

        self.userEscape = False  # User ends game by ESC
        self.gameOver = False  # Game over by death

        self.freezeActiveBallsTimer = 0

        self.clock = pygame.time.Clock()

        ### --------- Generate the snake

        self.snake = Snake_Module.Snake()

        self.snakeSprite = pygame.sprite.Group()
        self.snakeSprite.add(self.snake.get_sections())

        

        # needed for clear/draw
        self.snakeSections = self.snake.get_sections()
        


        ### --------- Initial food

        self.foodGroup  = pygame.sprite.Group()
        # config['food']['standard']['initial']
        for n in range(Config.INITIAL_FOOD_NUM):
            self.foodGroup.add(Food_Module.make_food(self.snake))

        for n in range(Config.INITIAL_FOOD_SUPER_NUM):
            self.foodGroup.add(Food_Module.make_food(self.snake,'FoodSuper'))

        for n in range(Config.INITIAL_FOOD_MYSTERIOUS_NUM):
            self.foodGroup.add(Food_Module.make_food(self.snake, 'FoodMysterious'))

        for n in range(Config.INITIAL_FOOD_CURSE_NUM):
            self.foodGroup.add(Food_Module.make_food(self.snake, 'FoodCurse'))


        ### --------- Initial balls

        self.ballGroup  = pygame.sprite.Group()

        for n in range(Config.INITIAL_BALL_NUM):
            self.ballGroup.add(Ball_Module.BallStandard(HelperFunctions.generateSafeXY(self.snake, self.ballGroup, None, self.foodGroup)))

        self.ballKillerGroup = pygame.sprite.Group()
        if Config.INITIAL_BALL_KILLER_NUM != 0:
            self.ballKillerGroup.add(Ball_Module.BallKiller(HelperFunctions.generateSafeXY(self.snake, self.ballGroup, None, self.foodGroup)))            
开发者ID:jamietanna,项目名称:PySnake,代码行数:58,代码来源:Game_Module.py

示例3: handleRandoms

    def handleRandoms(self):
        time = pygame.time.get_ticks()

        if ((time % Config.RANDOM_FOOD_MYSTERIOUS_CHANCE) == 0):
            print "Random Melon of Mystery generated"
            self.foodGroup.add(Food_Module.FoodMysterious(None, None, None, HelperFunctions.generateSafeXY(self.snake, self.ballGroup, self.ballKillerGroup, self.foodGroup)))
        
        if ((time % Config.RANDOM_FOOD_CURSE_CHANCE) == 0):
            print "Random Berries of Bane generated"
            self.foodGroup.add(Food_Module.FoodCurse(None, None, None, HelperFunctions.generateSafeXY(self.snake, self.ballGroup, self.ballKillerGroup, self.foodGroup)))
开发者ID:jamietanna,项目名称:PySnake,代码行数:10,代码来源:Game_Module.py

示例4: testChoke

 def testChoke(self):
     self.connection._GitHubConnection__choke()
     alpha = HelperFunctions.millitimestamp()
     self.connection._GitHubConnection__choke()
     delta = HelperFunctions.millitimestamp()
     self.assertGreater(
         delta,
         alpha + 79,
         "The choke delay is less than 0.08 seconds: " + str((delta - alpha) / 1000) + " (" + str(delta) + ")",
     )
     self.assertLess(
         delta,
         alpha + 90,
         "The choke delay is too much over 0.08 seconds: " + str((delta - alpha) / 1000) + " (" + str(delta) + ")",
     )
开发者ID:tomibgt,项目名称:GitHubResearchDataMiner,代码行数:15,代码来源:ConnectedTests.py

示例5: __init__

    def __init__(self, colour=None, size=None, position=None):
        pygame.sprite.Sprite.__init__(self)
        # Make sure snake valid parameters
        if colour == None:
            colour = Snake._DEFAULT_COLOUR
        if size == None:
            size = Snake._DEFAULT_SIZE
        #if size[0] != size[1]:
        #    raise Exception('Invalid tile size. Width and height must be equal.')
        if position == None:
            position = Snake._DEFAULT_POSITION

        self.color = colour
        self.size = size
        #self.head = Snake._SnakeHead(colour, size, position)
        self.segments.append(Snake._SnakeSegment(colour, size, position))

        self.head = self.segments[0]
        #self.tail = Snake._SnakeTail()

        self.curseTail = 0

        self.direction = Snake.SnakeMove.UP


        print "TODO: make this use self.adjust_tail_size()"

        for x in range(1, Config.INITIAL_LENGTH): # Initial Length
            tailposition = [(position[0] - x*size[0]), position[1]]
            # self.tail.add_tail_section(colour, size, tailposition)
            self.segments.append(Snake._SnakeSegment(HelperFunctions.random_rgb(), size, tailposition))
开发者ID:jamietanna,项目名称:PySnake,代码行数:31,代码来源:Snake_Module.py

示例6: adjust_tail_size

    def adjust_tail_size(self, number):
        size = self.size[0]

        current_direction = self.direction

        if number > 0:
            for count in range(number):
            # ### TODO - randomly generate from the colour of the food eaten
                if self.curseTail > 0:
                    colour = Config.BACKGROUND_COLOUR
                else:
                    colour = HelperFunctions.random_rgb()
                # Randomise colour of new tail section

                lastindex = len(self.segments) - 1
                X = self.segments[lastindex].rect.topleft[0]
                Y = self.segments[lastindex].rect.topleft[1]
                
                # New tail section position
                if current_direction == Snake.SnakeMove.RIGHT:
                    X = X - size + (count*size)
                elif current_direction == Snake.SnakeMove.LEFT:
                    X = X + size + (count*size)
                elif current_direction == Snake.SnakeMove.UP:
                    Y = Y - size + (count*size)
                elif current_direction == Snake.SnakeMove.DOWN:
                    Y = Y + size + (count*size)

                self.segments.append(Snake._SnakeSegment(colour, self.size, [X, Y]))
        else:
            for count in range(abs(number)):
                # leave at least the head
                if(len(self.segments) > 1):
                    del self.segments[-1]
开发者ID:jamietanna,项目名称:PySnake,代码行数:34,代码来源:Snake_Module.py

示例7: curse_tail

    def curse_tail(self):

        self.randomize_snake_colour()
        
        
        self.curseTail = Config.FOOD_CURSE_TIME_TO_WEAR_OFF * Config.FPS
        for (idx, s) in enumerate(self.segments):
            if idx > 0:
                s.set_colour(Config.BACKGROUND_COLOUR)
            else:
                s.set_colour(HelperFunctions.random_rgb())
开发者ID:jamietanna,项目名称:PySnake,代码行数:11,代码来源:Snake_Module.py

示例8: __init__

 def __init__(self, config):
     self.config = config
     self.stringSanitizer = StringSanitizer()
     self.gitHubUserName = config.user
     self.gitHubRepoName = config.repo
     self.github = Github(config.get('authentication', 'ghusername'), config.get('authentication', 'ghpassword'))
     try: # Try to open the repository
         self.repo = self.github.get_repo(config.user+"/"+config.repo)
     except UnknownObjectException:
         print "Repository "+config.user+"/"+config.repo+" not found."
         GitHubResearchDataMiner.printHowToUse()
         sys.exit()
     self.requestRateTimer = HelperFunctions.millitimestamp()
开发者ID:tomibgt,项目名称:GitHubResearchDataMiner,代码行数:13,代码来源:GitHubConnection.py

示例9: addOfflineChallenge

 def addOfflineChallenge(self , fromUser, toUid , challengeData, offlineChallengeId=None):
     toUser = self.getUserByUid(toUid)
     
     offlineChallenge = OfflineChallenge()
     if(offlineChallengeId!=None):
         offlineChallenge.offlineChallengeId = offlineChallengeId
     else:
         offlineChallenge.offlineChallengeId = HelperFunctions.generateKey(10)
     offlineChallenge.fromUid_userChallengeIndex = fromUser.uid+"_"+str(fromUser.userChallengesIndex.index) # yeah , its a little bit funny too # fuck you , i was not funny , that was over optimization for an unreleased app !!!
     offlineChallenge.toUid_userChallengeIndex = toUid+"_"+str(toUser.userChallengesIndex.getAndIncrement(toUser).index)
     offlineChallenge.challengeData = challengeData
     offlineChallenge.save()
     return offlineChallenge
开发者ID:abhinavabcd,项目名称:QuizApp_server,代码行数:13,代码来源:Db.py

示例10: addOfflineChallenge

 def addOfflineChallenge(self , fromUser, toUid , challengeData, offlineChallengeId=None):
     toUser = self.getUserByUid(toUid)
     
     offlineChallenge = OfflineChallenge()
     if(offlineChallengeId!=None):
         offlineChallenge.offlineChallengeId = offlineChallengeId
     else:
         offlineChallenge.offlineChallengeId = HelperFunctions.generateKey(10)
     offlineChallenge.fromUid_userChallengeIndex = fromUser.uid+"_"+str(fromUser.userChallengesIndex.index) # yeah , its a little bit funny too
     offlineChallenge.toUid_userChallengeIndex = toUid+"_"+str(toUser.userChallengesIndex.getAndIncrement(toUser).index)
     offlineChallenge.challengeData = challengeData
     offlineChallenge.save()
     return offlineChallenge
开发者ID:shalintripathi,项目名称:QuizApp_server,代码行数:13,代码来源:Db.py

示例11: publishFeedToUser

 def publishFeedToUser(self,fromUid ,  user, _type, message, message2):
     f = Feed()
     f.fromUid = fromUid
     f.type = _type
     f.message = message
     if(message2!=None):
         f.message2 = message2
     f.timestamp = HelperFunctions.toUtcTimestamp(datetime.datetime.now())
     f.save()
     
     userFeed = UserFeed()
     userFeed.uidFeedIndex= user.uid+"_"+str(user.userFeedIndex.getAndIncrement(user).index)
     userFeed.feedMessage = f
     userFeed.save()
开发者ID:shalintripathi,项目名称:QuizApp_server,代码行数:14,代码来源:Db.py

示例12: check_high_t

def check_high_t(T=6000, metal=0.0, vsini=10):
    filenames = [f for f in os.listdir("./") if f.endswith("smoothed.fits") and f.startswith("H")]
    corrdir = "Cross_correlations/"
    logg = 4.5
    HelperFunctions.ensure_dir("Figures/")

    for rootfile in sorted(filenames):
        corrfile = "{0:s}{1:s}.{2:d}kps_{3:.1f}K{4:+.1f}{5:+.1f}".format(corrdir,
                                                                         rootfile.split(".fits")[0],
                                                                         vsini,
                                                                         T,
                                                                         logg,
                                                                         metal)
        print corrfile
        try:
            vel, corr = np.loadtxt(corrfile, unpack=True)
        except IOError:
            continue

        plt.plot(vel, corr, 'k-')
        plt.xlabel("Velocity")
        plt.ylabel("CCF")
        plt.title(rootfile.split(".fits")[0])
        plt.show()
开发者ID:kgullikson88,项目名称:Chiron-Scripts,代码行数:24,代码来源:CheckCCFs.py

示例13: detectFacesInImage

def detectFacesInImage(cvImage, detectionDebug=False): 
  logger = logging.getLogger('ELIME.OpenCVFunctions.detectFacesInImage')
  width, height = cv.GetSize(cvImage)
  
  minDimension = min(width, height)
  
#   scale_factor = 1.1
#   min_neighbors = 3
#   flags = 0
#   min_size = (20,20)
  
  arguments = [(1.1, 3, 0, (20, 20)),
              (1.1, 3, 0, (int(1.0 * minDimension), int(1.0 * minDimension))),
              (1.1, 3, 0, (int(0.7 * minDimension), int(0.7 * minDimension))),
              (1.1, 3, 0, (int(0.4 * minDimension), int(0.4 * minDimension))),
              (1.1, 3, 0, (int(0.1 * minDimension), int(0.1 * minDimension))),
              (1.1, 3, 0, (int(0.01 * minDimension), int(0.01 * minDimension)))]
              
  path = os.path.join(PATHTOCASCADES, 'haarcascade_frontalface_default.xml')
  path = HelperFunctions.checkFile(path)
 
  if path is None:
    logger.critical("Path to opencv haarcascades is wrong: %s", PATHTOCASCADES)
    sys.exit(1)

  print path    
  faceCascade = cv.Load(path)
  
  storage = cv.CreateMemStorage()
  
  returnFaces = set()
  
  for (scale_factor, min_neighbors, flags, min_size) in arguments:
    
    detectedFaces = cv.HaarDetectObjects(cvImage, faceCascade, storage, scale_factor, min_neighbors, flags, min_size)
    debugString = '{0:d} faces found, args: {1} {2} {3} {4}'.format(len(detectedFaces), str(scale_factor), str(min_neighbors), str(flags), str(min_size))
    logger.debug(debugString)
    for face,n in detectedFaces:
      returnFaces.add(face)
    
    if detectionDebug:
      debugFaces = []
      for face,n in detectedFaces:
        debugFaces.append((face, cv.RGB(0, 0, 255)))
      UiFunctions.displayColoredRects(cvImage, debugString, debugFaces)
      
  logger.debug("returning Faces: %s", returnFaces)     
  return returnFaces
开发者ID:stahlfabrik,项目名称:ELIME,代码行数:48,代码来源:OpenCvFunctions.py

示例14: publishFeed

 def publishFeed(self, user, _type ,  message, message2=None):
     f = Feed()
     f.fromUid = user.uid
     f.message = message
     f.type = _type
     if(message2!=None):
         f.message2 = message2
     f.timestamp = HelperFunctions.toUtcTimestamp(datetime.datetime.now())
     f.save()
     #### move to tasks other server if possible
     for uid in user.subscribers:
         user = self.getUserByUid(uid)
         userFeed = UserFeed()
         userFeed.uidFeedIndex = uid+"_"+str(user.userFeedIndex.getAndIncrement(user).index)
         userFeed.feedMessage = f
         userFeed.save()
开发者ID:shalintripathi,项目名称:QuizApp_server,代码行数:16,代码来源:Db.py

示例15: getAllUpdates

def getAllUpdates(response, user=None):
    isLogin = response.get_argument("isLogin",False)
    isFistLogin =  response.get_argument("isFirstLogin",False)
    lastOfflineChallengeIndex = int(response.get_argument("lastOfflineChallengeIndex",0));
    retObj = {"messageType":OK_UPDATES,
                               "payload7":user.toJson(),
                               "payload3":"["+','.join(map(lambda x:x.to_json(),dbUtils.getRecentUserFeed(user)))+"]",
                               "payload5":"["+','.join(map(lambda x:x.to_json(),dbUtils.getUserChallenges(user , fromIndex=lastOfflineChallengeIndex)))+"]"
                               }
    if(isLogin):
        quizzes = None
        categories= None
        badges = None
        userMaxQuizTimestamp = response.get_argument("maxQuizTimestamp",None)
        if(userMaxQuizTimestamp):
            userMaxQuizTimestamp = datetime.datetime.utcfromtimestamp(float(userMaxQuizTimestamp)+1)
            quizzes = dbUtils.getAllQuizzes(userMaxQuizTimestamp)
            categories = dbUtils.getAllCategories(userMaxQuizTimestamp)
            retObj["payload"]="["+','.join(map(lambda x:x.toJson() , quizzes ))+"]"
            retObj["payload1"] ="["+','.join(map(lambda x:x.toJson() , categories ))+"]"
            
        userMaxBadgesTimestamp = response.get_argument("maxBadgesTimestamp",None)
        if(userMaxBadgesTimestamp):
            userMaxBadgesTimestamp = datetime.datetime.utcfromtimestamp(max(0,float(userMaxBadgesTimestamp)+1))
            badges = dbUtils.getNewBadges(userMaxBadgesTimestamp)
            retObj["payload2"] = "["+",".join(map(lambda x:x.toJson(),badges))+"]"

        retObj["payload6"]=json.dumps({server.serverId : server.addr for server in routerServer.servers.values()})#id:serveraddr
     
    if(isFistLogin):
        retObj["payload8"]= json.dumps(dbUtils.getPeopleWithWhomUserConversed(user))
    
    
    recentMessages = None
    lastSeenTimestamp = response.get_argument("lastSeenTimestamp",None)
    if(lastSeenTimestamp):
        lastSeenTimestamp = datetime.datetime.utcfromtimestamp(float(lastSeenTimestamp))
        recentMessages = "["+','.join(map(lambda x:x.to_json(),dbUtils.getRecentMessagesIfAny(user, lastSeenTimestamp)))+"]"
        retObj["payload4"] = recentMessages #unseen messages if any
        
    retObj["payload10"] = json.dumps({"serverTime":HelperFunctions.toUtcTimestamp(datetime.datetime.now())})
    responseFinish(response, retObj)
    if(isLogin):
        #every time user logs in lets increment the index
        dbUtils.incrementLoginIndex(user)
开发者ID:abhinavabcd,项目名称:QuizApp_server,代码行数:45,代码来源:server.py


注:本文中的HelperFunctions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。