Esempio n. 1
0
 def pms_fwk_modifydict_wrapper(f):
     lockname = "Framework.ModDict:" + key
     Thread.Lock(lockname, addToLog=False)
     dictitem = Dict.Get(key)
     f(dictitem)
     Dict.Set(key, dictitem, addToLog=False)
     Thread.Unlock(lockname, addToLog=False)
Esempio n. 2
0
def testSetStuff():
    dct1 = Dict.fromList(List.toElm([
        (1, 10),
        (2, 20),
        (3, 30),
    ]))

    dct2 = Dict.fromList(List.toElm([
        (3, 300),
        (4, 400),
        (5, 500),
    ]))

    print('union')
    assert list(Dict.keys(Dict.union(dct1, dct2))) == [1,2,3,4,5]

    print('intersect')
    assert list(Dict.keys(Dict.intersect(dct1, dct2))) == [3]

    print('diff')
    assert list(Dict.keys(Dict.diff(dct1, dct2))) == [1,2]

    print('merge')
    outList = Dict.merge(
        lambda k, v, lst: List.cons((k, v), lst),
        lambda k, v1, v2, lst: List.cons((k, v1, v2), lst),
        lambda k, v, lst: List.cons((v, k), lst),
        dct1,
        dct2,
        List.empty)
    assert list(outList) == [ (500, 5), (400, 4), (3, 30, 300), (2, 20), (1, 10) ]
Esempio n. 3
0
 def readdrug(self):
     work = xlrd.open_workbook(self.drug)
     sheet = work.sheet_by_index(0)
     nrows = sheet.nrows
     for row in range(1, nrows):
         rowvalue = sheet.row_values(row)
         if sheet.cell(row, 4).ctype == 0:
             ishaplotype = 'N'
         else:
             ishaplotype = 'H'
         Dict.addtodict5(self.drugdict, rowvalue[0], rowvalue[1],
                         rowvalue[2], rowvalue[3], ishaplotype, rowvalue[5])
Esempio n. 4
0
 def computlines(self):
     temp_chemsit = {}
     all_num_tex = {}
     for key1 in self.endchesite.keys():
         drug_lines = 0
         for key2 in self.endchesite[key1].keys():
             if key2 == 'N':
                 for key3 in self.endchesite[key1][key2].keys():
                     [basic, hploy, clinal,
                      conclusion] = self.endchesite[key1][key2][key3]
                     n_clinal = self.numlin(clinal, 35)
                     n_conclusion = self.numlin(conclusion, 3)
                     Dict.addtodict3(temp_chemsit, key1, key3, 'conclusion',
                                     n_conclusion)
                     Dict.addtodict3(temp_chemsit, key1, key3, 'clinal',
                                     n_clinal)
                     drug_lines = drug_lines + n_clinal * 0.7 + n_conclusion
             else:
                 key3list = list(self.endchesite[key1][key2].keys())
                 for key3 in self.endchesite[key1][key2].keys():
                     [basic, hploy, clinal,
                      conclusion] = self.endchesite[key1][key2][key3list[0]]
                     n_clinal = self.numlin(clinal, 35)
                     Dict.addtodict3(temp_chemsit, key1, key3, 'conclusion',
                                     len(key3list))
                     Dict.addtodict3(temp_chemsit, key1, key3, 'clinal',
                                     n_clinal)
                 drug_lines = drug_lines + len(key3list) + n_clinal * 0.7
         all_num_tex[key1] = int(drug_lines)
     return temp_chemsit, all_num_tex
def __checkFrameworkCompatibility():
  try:
    lastFrameworkVersion = Dict.Get("Framework.LastCompatibilityVersion")
    if lastFrameworkVersion != PMS.FrameworkCompatibilityVersion: raise
    return True
  except:
    PMS.Log("(Framework) Data stored by an earlier framework version has been removed due to incompatibilities.")
    if os.path.exists(Prefs.__prefsPath): os.unlink(Prefs.__prefsPath)
    if os.path.exists(Database.__databasePath): os.unlink(Database.__databasePath)
    shutil.rmtree(Data.__dataPath)
    os.makedirs(Data.__dataItemPath)
    Dict.__loadDefaults()
    Dict.__save(addToLog=False)
    return False
Esempio n. 6
0
    def readannofile(self):
        global rslist
        mutationrs = {}
        with open(self.annofile, 'r') as F:
            mark = None
            title = F.readline().strip().split('\t')
            for idx, value in enumerate(title):
                if 'snp13' in value:
                    mark = idx

            for line in F:
                lines = line.strip('\n').split('\t')
                if lines[mark] == 'rs2032582' and re.search(
                        r'^1/2:', lines[-1]):
                    Dict.addtodict(mutationrs, lines[mark], 'CT')
                elif lines[mark] == 'rs8175347':
                    [gt, fre] = self.percent(lines)
                    if gt == 'TT':
                        nlty = '(TA)6/(TA)6'
                    elif gt == 'TA':
                        nlty = '(TA)6/(TA)7'
                    elif gt == 'AA':
                        nlty = '(TA)7/(TA)7'
                    Dict.addtodict(mutationrs, lines[mark], nlty)
                elif lines[mark] in rslist:
                    [gt, fre] = self.percent(lines)
                    Dict.addtodict(mutationrs, lines[mark], gt)
                else:
                    pattern1 = re.compile(
                        'ABL1:NM_005157:exon\d+:c\.\w+:p\.(\w+)')
                    pattern2 = re.compile(
                        'IDH2:NM_002168:exon\d+:c\.\w+:p\.(\w+)')
                    for rsp in rslist:
                        if pattern1.search(lines[9]):
                            paa = pattern1.search(lines[9]).groups(1)
                            if rsp == paa:
                                [gt, fre] = self.percent(lines)
                                Dict.addtodict(mutationrs, rsp, fre)
                        elif pattern2.search(lines[9]):
                            paa = pattern2.search(lines[9]).group(1)
                            if rsp == paa:
                                [gt, fre] = self.percent(lines)
                                Dict.addtodict(mutationrs, rsp, fre)
                        else:
                            pass
                    # Dict.addtodict(mutationrs,'rs8175347','(TA)6/(TA)6')

        return mutationrs
Esempio n. 7
0
def __checkFrameworkCompatibility():
    try:
        lastFrameworkVersion = Dict.Get("Framework.LastCompatibilityVersion")
        if lastFrameworkVersion != PMS.FrameworkCompatibilityVersion: raise
        return True
    except:
        PMS.Log(
            "(Framework) Data stored by an earlier framework version has been removed due to incompatibilities."
        )
        if os.path.exists(Prefs.__prefsPath): os.unlink(Prefs.__prefsPath)
        if os.path.exists(Database.__databasePath):
            os.unlink(Database.__databasePath)
        shutil.rmtree(Data.__dataPath)
        os.makedirs(Data.__dataItemPath)
        Dict.__loadDefaults()
        Dict.__save(addToLog=False)
        return False
Esempio n. 8
0
 def readdrug(self):
     global rslist
     work = xlrd.open_workbook(self.drug)
     rslist = []
     sheet = work.sheet_by_index(0)
     nrows = sheet.nrows
     for row in range(1, nrows):
         rowvalue = sheet.row_values(row)
         if sheet.cell(row, 4).ctype == 0:
             ishaplotype = 'N'
         else:
             ishaplotype = 'H'
         cloc = rowvalue[2].replace('_', '\_')
         Dict.addtodict5(self.drugdict, rowvalue[9], rowvalue[0],
                         rowvalue[1], cloc + ':' + rowvalue[3], ishaplotype,
                         rowvalue[5])
         rslist.append(rowvalue[3])
Esempio n. 9
0
def buildQuery(s, tables):
    tokens = nltk.word_tokenize(s)
    Tagged = nltk.pos_tag(tokens)

    subjects = 0
    # joined = False
    for item in Tagged:
        if item[1] == 'NNS':
            subjects += 1
    if subjects >= 2:
        # joined = True
        s = join(s, tables)
    s = Dict.DoReplacing(s)
    # s = 'Show me when both Mario and Sonic first came out'
    s = s.strip()  # Remove Leading and Trailing Whitespace
    s = ReplaceNotFirst(s, 'where', 'and')
    s = s.replace('and and', 'and')

    # Remove generic database references
    if s.lower().find("from database") != -1:
        s = Dict.Replace(s, [" from database"], '')

    tokens = nltk.word_tokenize(s)
    # if there is no "from"
    if s.find('from') == -1 and s.find('select') != -1:
        temp = tokens[tokens.index('select') + 1]
        temps = singularize(temp)
        tempp = pluralize(temps)
        s = s.replace('select ' + temp, 'select ' + temps + ' from ' + tempp)

        tokens = nltk.word_tokenize(s)
        if tokens[tokens.index('from') + 1] not in tables:
            s = noTableName(s, tables, tokens[tokens.index('from') + 1])

    if s[-1] != ';':
        s = s + ';'
    tokens = s.split(' ')

    s = manageStringVars(s, tokens)
    # above func takes in string and list, looks for operator and if the following
    # string is not a digit, then the function will add quotes to it

    return s
Esempio n. 10
0
def noTableName(s, tables, BadName):
    print("Which of the following subjects is that most related to?")
    print(tables)
    validTable = False
    tableName = "INVALID"
    while validTable is False:
        tableName = input("Subject: ")
        if tableName not in tables:
            print(
                "\033[91mSorry, " + tableName +
                " is not in the list above. Please enter a subject from above.\033[0m"
            )
        else:
            validTable = True
    tableName = tableName.lower().capitalize()
    s = s.replace(BadName, tableName, 1)
    if tableName == "Systems":
        s = Dict.Replace(s, ["game"], "system")
        s = Dict.Replace(s, ["Publisher"], "Creator")
    return (s)
Esempio n. 11
0
 def readhaptype(self):
     work = xlrd.open_workbook(self.haplotype)
     sheet = work.sheet_by_index(0)
     nrows = sheet.nrows
     for row in range(1, nrows):
         rowvalue = sheet.row_values(row)
         drug = rowvalue[0]
         gene = rowvalue[1]
         genetype = str(rowvalue[2].replace(':', ':'))
         genetype = genetype.replace(' ', '')
         clinal = str(rowvalue[5]).replace('%', r'\%')
         clinal = clinal.replace('_', r'\_')
         conclusion = str(rowvalue[6]).replace('%', r'\%')
         conclusion = conclusion.replace('_', r'\_')
         if sheet.cell(row, 3).ctype == 0:
             basic = '-'
         else:
             basic = rowvalue[3]
         Dict.addtodict3(self.haplotypedict, drug, gene, genetype,
                         [basic, clinal, conclusion])
Esempio n. 12
0
    def readannofile(self):
        global rslist
        mutationrs = {}
        with open(self.annofile, 'r') as F:
            mark = None
            title = F.readline().strip().split('\t')
            for idx, value in enumerate(title):
                if 'snp13' in value:
                    mark = idx

            for line in F:
                lines = line.strip('\n').split('\t')
                if lines[mark] in rslist:
                    if lines[mark] == 'rs2032582' and re.search(
                            r'^1/2:', lines[-1]):
                        Dict.addtodict(mutationrs, lines[mark], 'CT')
                    else:
                        gt = self.percent(lines)
                        Dict.addtodict(mutationrs, lines[mark], gt)

        return mutationrs
Esempio n. 13
0
 def readhaptype(self):
     global rslist
     rslist = []
     work = xlrd.open_workbook(self.haplotype)
     sheet = work.sheet_by_index(0)
     nrows = sheet.nrows
     for row in range(1, nrows):
         rowvalue = sheet.row_values(row)
         drug = rowvalue[0]
         gene = rowvalue[1]
         genetype = rowvalue[2]
         clinal = str(rowvalue[5]).replace('%', r'\%')
         conclusion = str(rowvalue[6]).replace('%', r'\%')
         if sheet.cell(row, 3).ctype == 0:
             basic = '-'
         elif sheet.cell(row, 3).value == 'others':
             basic = '无'
         else:
             basic = rowvalue[3]
         Dict.addtodict3(self.haplotypedict, drug, gene, genetype,
                         [basic, clinal, conclusion])
         rslist.append(rowvalue[3])
Esempio n. 14
0
from bs4 import BeautifulSoup

import Dict

soup = BeautifulSoup(open('anki.html'))

# get wordList from anki.html

wordList = []

for item in soup.find_all('div', class_='back'):
    for content in item.contents:
        try:
            words = content.strip().split('\n')
            if words != ['']:
                wordList += words
        except:
            print content

# wordList = list(set(wordList))

print wordList
print len(wordList), 'words to update/add.'

# look up each word (and save locally)

localDict = Dict.Local()
for word in wordList:
    localDict.addEntry(word)
localDict.save()
Esempio n. 15
0
    def __init__(self):
        # Instância  a classe que irá ler os arquivos de entrada do programa como stop-word e tags
        inputFiles = ReadInputFiles.ReadInputFiles()

        # Instância da classe generateID  que gera os id para os registros a serem adicionados no banco
        generateID = GenerateID.GenerateID()

        # Chama o método que cria todas os dicionários com os valores.
        inputFiles.mountDicts()

        writeLogFile = WriteLogFile.WriteLogFile()

        #Cria uma instância da classe Bolsa DAO, a qual fica realizando as consultas no banco
        bolsa = BolsaDAO.BolsaDAO(writeLogFile)

        pool_sema = threading.BoundedSemaphore(value=1)

        self.generateID = GenerateID.GenerateID()

        dicionario = Dict.Dict(bolsa, pool_sema, writeLogFile)

        numberOfThread = 4

        #Pega a quantidade de linhas do banco de dados
        rowCount = bolsa.getTableRowCount()

        areaDeConhecimento = self.montaHashAreaCohecimento(bolsa)

        # A quantidade de registros que serão trazidos do banco de dados por vez.
        offset = 5000
        # realiza a quantidade de vez para que se rode o algoritmo no banco todo.
        cycles = math.ceil(rowCount / offset)

        i = inputFiles.readOnFileCycle()

        inputFiles.readOnFileHashWord(dicionario.wordDict)
        inputFiles.readOnFileHashStem(dicionario.stemDict)

        for i in range(0, cycles):
            #pegando as 1000 registros do banco de cada vez
            rows = bolsa.getBolsaOffsetLimit(offset, offset * i)
            threads = []
            k = 0
            while k < len(rows):
                for l in range(0, numberOfThread):
                    if k < len(rows):
                        thread = DataProcess.DataProcess(
                            inputFiles.stopWordBannedList,
                            inputFiles.stopWordConnectList,
                            inputFiles.tagTrigram, inputFiles.tagBigram, bolsa,
                            rows[k], pool_sema, self.generateID,
                            areaDeConhecimento, dicionario)
                        threads.append(thread)
                        thread.start()
                        k = k + 1
                for l in range(0, len(threads)):
                    threads[l].join()
                del threads[:]
            print("..::Já foram processadas ->" + str(offset * (i + 1)))
            bolsa.mysql.commit()
            if i > 0 and i % 10 == 0:
                dicionario.saveStemAndWordDict(i)
        #fechando os arquivos de log que contem os erros de insercao de cada tabela
        bolsa.fileSource.close()
        bolsa.fileWord.close()
        bolsa.fileStem.close()
        dicionario.saveStemAndWordDict(i)
Esempio n. 16
0
    def searchdrug(self):
        mutationrs = self.readannofile()
        for drug in self.drugdict.keys():
            for gene in self.drugdict[drug].keys():
                rscom = []
                rssite = {}
                for cloc in self.drugdict[drug][gene].keys():
                    for rsid in self.drugdict[drug][gene][cloc].keys():
                        for hap in self.drugdict[drug][gene][cloc][rsid].keys(
                        ):
                            genechem = gene + '(' + cloc + ')'
                            genetype = ''
                            if hap == 'N':
                                if rsid in mutationrs:
                                    genetype = rsid + ':' + mutationrs[rsid]
                                else:
                                    genetype = rsid + ':' + self.drugdict[
                                        drug][gene][cloc][rsid][hap]

                                if genetype in self.haplotypedict[drug][
                                        gene].keys():
                                    Dict.addtodict3(self.endchesite, drug, 'N',
                                                    genechem,
                                                    [genetype.split(':')[1]] +
                                                    self.haplotypedict[drug]
                                                    [gene][genetype])
                                else:
                                    print('strange genetype: ' + hap + ' ' +
                                          rsid + ' ' + gene + drug)
                            else:
                                if rsid in mutationrs:
                                    genetype = rsid + ':' + mutationrs[rsid]
                                    rssite[genetype] = [
                                        genechem, mutationrs[rsid]
                                    ]
                                else:
                                    genetype = rsid + ':' + self.drugdict[
                                        drug][gene][cloc][rsid][hap]
                                    rssite[genetype] = [
                                        genechem, self.drugdict[drug][gene]
                                        [cloc][rsid][hap]
                                    ]
                                rscom.append(genetype)
                if rscom:
                    combiners = self.comiter(rscom)
                    mark = 0
                    for coms in combiners:
                        if coms in self.haplotypedict[drug][gene].keys():
                            mark += 1
                            for site in coms.split(','):
                                if site in rssite:
                                    Dict.addtodict3(
                                        self.endchesite, drug, 'H',
                                        rssite[site][0], [rssite[site][1]] +
                                        self.haplotypedict[drug][gene][coms])
                                else:
                                    print('this rssite is not in list ' + site)
                        else:
                            pass
                    if mark == 0:
                        for site in rssite:
                            Dict.addtodict3(
                                self.endchesite, drug, 'H', rssite[site][0],
                                [rssite[site][1]] +
                                self.haplotypedict[drug][gene]['others'])
                    else:
                        print(gene + ' is haplotype')
Esempio n. 17
0
        NewValue = (((xory - oldMin) * NewRange) / OldRange) + newMin
        return NewValue
    else:
        return 0


controller = Leap.Controller()

while True:
    pw.Prepare()
    frame = controller.frame()  #frame grab
    handlist = frame.hands

    #database handle start
    if start:
        userName, database = Dict.init_database()
        startTime = timer()

        sorted_dict = sorted(
            database[userName]['correctAttempts'].items(),
            key=lambda kv: kv[1])[0]  # grab the lowest signed number
        number = int(sorted_dict[0][len('digit'):len('digit') + 1])
        type = GetMath(number)  #grab the math for this digit

        start = False

    if (len(handlist) > 0):
        Handle_Finger(frame)
        if correct == False:
            if number != 10:  #10 is equivalent to a void number
                rtnval = pw.Adjust_Hand(
Esempio n. 18
0
def join(s, tables):
    Query = "select "

    tokens = nltk.word_tokenize(s)
    tagged = nltk.pos_tag(tokens)

    Query = append(tagged, Query, 'NNS')

    tables = ['games', 'systems']
    for table in tables:
        Query = Query.replace(table, table + '.' + singularize(table))
        Query = Query.replace(' ' + singularize(table) + ' ',
                              ' ' + pluralize(table) + '.' + table + ' ')

    # From
    Query += 'from '
    for table in tables:
        Query += table
        Query += ', '
    Query = Query.strip(', ') + ' '

    # Actual Joining
    Query += 'where games.system = systems.system '  # Change later

    # Nintendo Systems ==> Systems made by Nintendo
    temp = False
    i = 0
    for row in tagged:
        if tagged[i][1] == 'NNP' and i + 1 < len(tagged):
            if tagged[i + 1][1] == 'NNPS':
                Query += tagged[i + 1][0]
                Query += '.made by '
                Query += tagged[i][0]
                Query += ' '
                tagged[i] = ((tagged[i][0]), ('X' + tagged[i][1]))
                tagged[i + 1] = ((tagged[i + 1][0]), ('X' + tagged[i + 1][1]))
                break

        i += 1

    i = 0
    flag = False
    for row in tagged:
        if tagged[i][1] == 'NNS':
            flag = True
        if flag:
            tagged[i] = ((tagged[i][0]), ('Z' + tagged[i][1]))
        i += 1

    i = 0
    flag = False
    for i in range(0, len(tagged)):
        if tagged[i][1][0] == 'Z':
            flag = True
        if flag:
            if tagged[i][1] == 'ZNNS':
                temp = tagged[i][0] + '.'
                Query += temp
            elif tagged[i][1] == 'ZNNP' and i + 1 < len(tagged):
                Query += tagged[i][0] + ' '
                Query += temp
            else:
                Query += tagged[i][0]
                Query += ' '

        i += 1
    Query = Dict.DoReplacing(Query)

    for table in tables:
        Query = Dict.Replace(Query, [table + '\.where '],
                             'where ' + table + '.')

    return Query
def __run(_bundlePath):
  #
  # Initializes the framework, verifies the plug-in & extracts information, then enters a
  # run loop for handling requests. 
  #
  global Identifier
  global Debug
  global __bundlePath  
  global __pluginModule
  global __logFilePath
  global __requestHandlers
  global LastPrefix
  
  FirstRun = False
  random.seed()
  
  # Set up the support file paths
  if sys.platform == "win32":
    if 'PLEXLOCALAPPDATA' in os.environ:
      key = 'PLEXLOCALAPPDATA'
    else:
      key = 'LOCALAPPDATA'
    pmsPath = os.path.join(os.environ[key], 'Plex Media Server')
    logFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Logs", "PMS Plugin Logs")
  else:
    pmsPath = "%s/Library/Application Support/Plex Media Server" % os.environ["HOME"]
    logFilesPath = "%s/Library/Logs/PMS Plugin Logs" % os.environ["HOME"]
  
  supportFilesPath = "%s/Plug-in Support" % pmsPath
  frameworkSupportFilesPath = "%s/Framework Support" % pmsPath
  
  # Make sure framework directories exist
  def checkpath(path):
    try:
      if not os.path.exists(path): os.makedirs(path)
    except:
      pass
  
  checkpath("%s/Preferences" % supportFilesPath)
  checkpath("%s/Databases" % supportFilesPath)
  checkpath(logFilesPath)
  checkpath(frameworkSupportFilesPath)
    
  # Set the bundle path
  __bundlePath = _bundlePath.rstrip('/')
  
  # Add the bundle path to the system path, including any libraries
  if os.path.isdir("%s/Contents" % __bundlePath):
    sys.path.append("%s/Contents" % __bundlePath)
    if os.path.isdir("%s/Contents/Libraries" % __bundlePath):
      sys.path.append("%s/Contents/Libraries" % __bundlePath)
  else:
    print "Couldn't find bundle directory"
    return None
  
  # Open the Info.plist file
  f = open("%s/Contents/Info.plist" % __bundlePath, "r")
  infoplist = XML.ElementFromString(f.read())
  f.close()
  if infoplist is None:
    print "Couldn't load Info.plist file from plug-in"
    return

  # Get the plug-in identifier
  Identifier = infoplist.xpath('//key[text()="CFBundleIdentifier"]//following-sibling::string/text()')[0]
  if Identifier is None:
    print "Invalid Info.plist file in plug-in"
    return None
    
  # Set up the log file
  __logFilePath = "%s/%s.log" % (logFilesPath, Identifier)
  if os.path.exists(__logFilePath):
    if os.path.exists("%s.old" % __logFilePath):
      os.remove("%s.old" % __logFilePath)
    os.rename(__logFilePath, "%s.old" % __logFilePath)
  
  # Now we can start logging
  PMS.Log("(Framework) Bundle verification complete", False)
  
  # Check whether debugging is enabled
  try:
    _debug = infoplist.xpath('//key[text()="PlexPluginDebug"]//following-sibling::string/text()')[0]
    if _debug == "1":
      Debug = True
      PMS.Log("(Framework) Debugging is enabled")
  except: pass

  # Log the system encoding (set during bootstrap)
  PMS.Log("(Framework) Default encoding is " + sys.getdefaultencoding())

  # Set up framework paths
  Prefs.__prefsPath = "%s/Preferences/%s.xml" % (supportFilesPath, Identifier)
  Data.__dataPath = "%s/Data/%s" % (supportFilesPath, Identifier)
  Data.__dataItemPath = "%s/DataItems" % Data.__dataPath
  if not os.path.isdir(Data.__dataItemPath):
    FirstRun = True
    os.makedirs(Data.__dataItemPath)
  Resource.__resourcePath = "%s/Contents/Resources" % __bundlePath
  Helper.__helperPath = "%s/Contents/Helpers" % __bundlePath
  Resource.__sharedResourcePath = "%s/Plug-ins/Framework.bundle/Contents/Resources/Versions/1/Resources" % pmsPath
  Database.__databasePath = "%s/Databases/%s.db" % (supportFilesPath, Identifier)
  os.chdir(Data.__dataItemPath)
  Locale.SetDefaultLocale()
  PMS.Log("(Framework) Configured framework modules")

  # Attempt to import the plug-in module - if debugging is enabled, don't catch exceptions
  if Debug:
    import Code as _plugin
    PMS.Log("(Framework) Imported plug-in module")
  else:
    try:
      import Code as _plugin
      PMS.Log("(Framework) Imported plug-in module")
    except ImportError:
      PMS.Log("(Framework) Couldn't import plug-in from bundle")
      __exit()
      return
      
  # Load the list of trusted plug-ins
  _trusted = []
  try:
    _trustedJSON = Resource.LoadShared("trust.json")
    if _trustedJSON:
      _trusted = JSON.ObjectFromString(_trustedJSON)
  except:
    pass

  # Populate the permission lists
  __setupPermissionLists()

  # Register the plug-in with the framework
  __pluginModule = _plugin

  # Check the imported module to make sure nothing untoward is happening!
  if Identifier in _trusted:
    PMS.Log("(Framework) Plug-in is trusted, skipping module check")
  else:
    __scanModules()
    _allowed = []
    for n in PMS.__dict__:
      if n[0] != "_":
        if type(PMS.__dict__[n]).__name__ == "module":
          _allowed.append(n)
    for n in __modWhitelist:
      _allowed.append(n)
    __checkModule(_plugin, _allowed)
    PMS.Log("(Framework) Checked module imports")

  # Initialize the framework modules
  Dict.__load()
  if not FirstRun:
    __checkFrameworkCompatibility()
  Prefs.__load()
  HTTP.__loadCookieJar()
  HTTP.__loadCache()
  if HTTP_TIMEOUT_VAR_NAME in os.environ:
    HTTP.SetTimeout(float(os.environ[HTTP_TIMEOUT_VAR_NAME]))
  else:
    HTTP.SetTimeout(HTTP_DEFAULT_TIMEOUT)
  PMS.Log("(Framework) Initialized framework modules")

  # Call the plug-in's Start method
  PMS.Log("(Framework) Attempting to start the plug-in...")
  __call(__pluginModule.Start)
  PMS.Log("(Framework) Plug-in started", False)

  # Start timers
  __startCacheManager(firstRun=FirstRun)
  
  PMS.Log("(Framework) Entering run loop")
  # Enter a run loop to handle requests
  while True:
    try:
      # Read the input
      path = raw_input()
      path = path.lstrip("GET ").strip()
      LastPrefix = None
      
      # Read headers
      headers = {}
      stop = False
      while stop == False:
        line = raw_input()
        if len(line) == 1:
          stop = True
        else:
          split = string.split(line.strip(), ":", maxsplit=1)
          if len(split) == 2:
            headers[split[0].strip()] = split[1].strip()

      # Set the locale
      if headers.has_key("X-Plex-Language"):
        loc = headers["X-Plex-Language"].lower()
        Locale.__loadLocale(loc)
        
      # Set the version
      if headers.has_key("X-Plex-Version"):
        Client.__setVersion(headers["X-Plex-Version"])

      PMS.Request.Headers.clear()
      PMS.Request.Headers.update(headers)
      
      req = urlparse.urlparse(path)
      path = req.path
      qs_args = cgi.parse_qs(req.query)
      kwargs = {}
      if 'function_args' in qs_args:
        try:
          unquoted_args = urllib.unquote(qs_args['function_args'][0])
          decoded_args = PMS.String.Decode(unquoted_args)
          kwargs = cerealizer.loads(decoded_args)
        except:
          PMS.Log(PMS.Plugin.Traceback())
          raise Exception("Unable to deserialize arguments")
      
      for arg_name in qs_args:
        if arg_name != 'function_args':
          kwargs[arg_name] = qs_args[arg_name][0]
      
      # First, try to match a connected route
      rpath = path
      for key in __prefixHandlers:
        if rpath.count(key, 0, len(key)) == 1:
          rpath = rpath[len(key):]
          break
      f, route_kwargs = MatchRoute(rpath)
      
      if f is not None:
        PMS.Log("(Framework) Handling route request :  %s" % path, False)
        route_kwargs.update(kwargs)
        result = f(**route_kwargs)

      # No route, fall back to other path handling methods
      else:
        mpath = path
        
        if mpath[-1] == "/":
          mpath = mpath[:-1]
        
        # Split the path into components and decode.
        pathNouns = path.split('/')
        pathNouns = [urllib.unquote(p) for p in pathNouns]
      
        # If no input was given, return an error
        if len(pathNouns) <= 1:
          __return("%s\r\n\r\n" % PMS.Error['BadRequest'])
        
        # Otherwise, attempt to handle the request
        else:
          result = None
          pathNouns.pop(0)
          count = len(pathNouns)
          if pathNouns[-1] == "":
            pathNouns.pop(len(pathNouns)-1)
          PMS.Log("(Framework) Handling request :  %s" % path, False)
        
          # Check for a management request
          if pathNouns[0] == ":":
            result = __handlePMSRequest(pathNouns, path, **kwargs)

          else:  
            handler = None
            isPrefixHandler = False
          
            # See if there's a prefix handler available
            for key in __prefixHandlers:
              if mpath.count(key, 0, len(key)) == 1:
                LastPrefix = key
            if mpath in __prefixHandlers:
              handler = __prefixHandlers[mpath]["handler"]
              isPrefixHandler = True
            
            else:
              # Check each request handler to see if it handles the current prefix
              popped = False
              for key in __requestHandlers:
                if handler is None:
                  if path.count(key, 0, len(key)) == 1:
                    # Remove the prefix from the path
                    keyNounCount = len(key.split('/')) - 1
                    for i in range(keyNounCount):
                      pathNouns.pop(0)
                    count = count - keyNounCount
                    # Find the request handler
                    handler = __requestHandlers[key]["handler"]
                    LastPrefix = key
                    popped = True
            
              # If no path request handler was found, make sure we still pop the prefix so internal requests work
              for key in __prefixHandlers:
                if popped == False:
                  if mpath.count(key, 0, len(key)) == 1:
                    keyNounCount = len(key.split('/')) - 1
                    for i in range(keyNounCount):
                      pathNouns.pop(0)
                    popped = True

            # Check whether we should handle the request internally
            handled = False
            if count > 0:
              if pathNouns[0] == ":":
                handled = True
                result = __handleInternalRequest(pathNouns, path, **kwargs)
    
          
            # Check if the App Store has flagged the plug-in as broken
            if os.path.exists(os.path.join(frameworkSupportFilesPath, "%s.broken" % Identifier)):
              #TODO: Localise this bit, use message from the App Store if available
              handled = True
              result = PMS.Objects.MessageContainer("Please try again later", "This plug-in is currently unavailable")
              PMS.Log("(Framework) Plug-in is flagged as broken")
          
            # If the request hasn't been handled, and we have a valid request handler, call it
            else:
              if not handled and handler is not None:
                if isPrefixHandler:
                  result = handler(**kwargs)
                else:
                  result = handler(pathNouns, path, **kwargs)
        
      response = None
      
      # If the request wasn't handled, return an error
      if result == None:
        PMS.Log("(Framework) Request not handled by plug-in", False)
        response = "%s\r\n\r\n" % PMS.Error['NotFound']
        
      # If the plugin returned an error, return it to PMS
      elif result in PMS.Error.values():
        PMS.Log("(Framework) Plug-in returned an error :  %s" % result, False)
        response = "%s\r\n\r\n" % result
        
      # Otherwise, check if a valid object was returned, and return the result
      elif __objectManager.ObjectHasBase(result, Objects.Object):
        resultStr = result.Content()
        resultStatus = result.Status()
        resultHeaders = result.Headers()
      
      elif isinstance(result, basestring):
        resultStr = result
        resultStatus = '200 OK'
        resultHeaders = "Content-type: text/plain\r\n"
      
      if resultStr is not None:
        PMS.Log("(Framework) Response OK")
        resultLen = len(resultStr)
        if resultLen > 0:
          resultHeaders += "Content-Length: %i\r\n" % resultLen
          resultStr = "\r\n"+resultStr
        
      else:
        resultStr = ""
        resultStatus = '500 Internal Server Error'
        resultHeaders = ''
        PMS.Log("(Framework) Unknown response type")
        
      if response == None:
        response = str("%s\r\n%s" % (resultStatus, resultHeaders)) + str(resultStr) + str("\r\n")
      
      #PMS.Log("\n---\n"+response+"---\n")
        
      __return(response)
    
    # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
    except KeyboardInterrupt:
      # Save data & exit
      __saveData()
      __exit()     
    
    except EOFError:
      # Save data & exit
      __saveData()
      __exit()
          
    # If another exception is raised, deal with the problem
    except:
      __except()
      __return("%s\r\n\r\n" % PMS.Error['InternalError'])
    
    # Make sure the plugin's data is saved
    finally:
      __saveData()
Esempio n. 20
0
 def test_key(self):
     d = Dict()
     d['key'] = 'value'
     self.assertEqual(d.key, 'value')
Esempio n. 21
0
 def test_init(self):
     d = Dict(a=1, b='test')
     self.assertEqual(d.a, 1)
     self.assertEqual(d.b, 'test')
     self.assertTrue(isinstance(d, dict))
Esempio n. 22
0
def testBasics():
    print('singleton')
    dct = Dict.singleton(5, 50)
    assert Dict.get(5, dct).val == 50

    print('empty')
    dct = Dict.empty
    print(toPy(dct))
    print('member', Dict.member(5, dct))
    print('get', Dict.get(5, dct))
    print('size', Dict.size(dct))
    print('empty', Dict.isEmpty(dct))

    print('\n\ninsert one...')
    dct = Dict.insert(5, 50, dct)
    print('member', Dict.member(5, dct))
    print('get', Dict.get(5, dct))
    keys = Dict.keys(dct)
    print('keys', keys)
    print('size', Dict.size(dct))
    print('empty', Dict.isEmpty(dct))
Esempio n. 23
0
def benchmark(n):
    def printRate(elapsed):
        if elapsed == 0:
            print('elapsed = 0')
            return
        print('rate', int(n * 1.0 / elapsed))
        print('\n')


    print('\n\ninsert many...')
    lst = list(range(n))
    random.shuffle(lst)

    dct = Dict.empty
    t = perf_counter()
    for i in lst:
        dct = Dict.insert(i, i*10, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)

    depth = maxDepth(dct)
    print('max depth', depth)
    threshold = 2 * math.log2(n)
    print('threshold', math.ceil(threshold))
    assert depth < threshold
    print()

    print('membership')
    t = perf_counter()
    for i in lst:
        assert Dict.member(i, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)


    print('get')
    t = perf_counter()
    for i in lst:
        assert Dict.get(i, dct).val == i * 10
    elapsed = perf_counter() - t
    printRate(elapsed)

    print('keys')
    t = perf_counter()
    keys = Dict.keys(dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(keys) == sorted(lst)

    print('values')
    t = perf_counter()
    values = Dict.values(dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(values) == sorted(10 * i for i in lst)


    print('update')
    t = perf_counter()

    for i in lst:
        dct = Dict.update(i, double, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)

    for i in lst:
        assert Dict.get(i, dct).val == i * 20

    assert Dict.size(dct) == n

    print('remove')
    t = perf_counter()
    for i in lst:
        dct = Dict.remove(i, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)

    assert Dict.size(dct) == 0

    print('fromList')
    tups = [(n, n * 2) for n in lst]
    elmLst = List.toElm(tups)
    t = perf_counter()
    dct = Dict.fromList(elmLst)
    elapsed = perf_counter() - t
    printRate(elapsed)

    assert Dict.size(dct) == n

    print('keys')
    t = perf_counter()
    keys = Dict.keys(dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(keys) == sorted(lst)

    print('toList')
    t = perf_counter()
    outLst = Dict.toList(dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(outLst) == sorted(tups)

    print('map')
    t = perf_counter()
    dct = Dict.map(add, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(Dict.values(dct)) == [
        3*i for i in sorted(lst)]

    print('foldl')
    t = perf_counter()
    bigSum = Dict.foldl(add3, 0, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert bigSum == 4 * n * (n-1) / 2

    accum = lambda k, v, accLst: List.cons((v, k), accLst)
    print('foldr')
    t = perf_counter()
    outLst = Dict.foldr(accum, List.empty, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    assert list(outLst) == [(n*3, n) for n in sorted(lst)]

    evenKey = lambda k, v: k % 2 == 0
    print('filter')
    t = perf_counter()
    filterDct = Dict.filter(evenKey, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    outLst = Dict.toList(filterDct)
    assert list(outLst) == [(n, n*3) for n in sorted(lst) if n % 2 == 0]

    evenKey = lambda k, v: k % 2 == 0
    print('partition')
    t = perf_counter()
    (goodDict, badDict) = Dict.partition(evenKey, dct)
    elapsed = perf_counter() - t
    printRate(elapsed)
    goodList = Dict.toList(goodDict)
    badList = Dict.toList(badDict)
    assert list(goodList) == [(n, n*3) for n in sorted(lst) if n % 2 == 0]
    assert list(badList) == [(n, n*3) for n in sorted(lst) if n % 2 != 0]
Esempio n. 24
0
 def test_attr(self):
     d = Dict()
     d.key = 'value'
     self.assertTrue('key' in d)
     self.assertEquals(d['key'], 'value')
Esempio n. 25
0
def __run(_bundlePath):
    #
    # Initializes the framework, verifies the plug-in & extracts information, then enters a
    # run loop for handling requests.
    #
    global Identifier
    global Debug
    global __bundlePath
    global __pluginModule
    global __logFilePath
    global __requestHandlers
    global LastPrefix

    FirstRun = False
    random.seed()

    # Set up the support file paths
    pmsPath = "%s/Library/Application Support/Plex Media Server" % os.environ[
        "HOME"]
    supportFilesPath = "%s/Plug-in Support" % pmsPath
    frameworkSupportFilesPath = "%s/Framework Support" % pmsPath
    logFilesPath = "%s/Library/Logs/PMS Plugin Logs" % os.environ["HOME"]

    # Make sure framework directories exist
    def checkpath(path):
        try:
            if not os.path.exists(path): os.makedirs(path)
        except:
            pass

    checkpath("%s/Preferences" % supportFilesPath)
    checkpath("%s/Databases" % supportFilesPath)
    checkpath(logFilesPath)
    checkpath(frameworkSupportFilesPath)

    # Set the bundle path
    __bundlePath = _bundlePath.rstrip('/')

    # Add the bundle path to the system path, including any libraries
    if os.path.isdir("%s/Contents" % __bundlePath):
        sys.path.append("%s/Contents" % __bundlePath)
        if os.path.isdir("%s/Contents/Libraries" % __bundlePath):
            sys.path.append("%s/Contents/Libraries" % __bundlePath)
    else:
        print "Couldn't find bundle directory"
        return None

    # Open the Info.plist file
    f = open("%s/Contents/Info.plist" % __bundlePath, "r")
    infoplist = XML.ElementFromString(f.read())
    f.close()
    if infoplist is None:
        print "Couldn't load Info.plist file from plug-in"
        return

    # Get the plug-in identifier
    Identifier = infoplist.xpath(
        '//key[text()="CFBundleIdentifier"]//following-sibling::string/text()'
    )[0]
    if Identifier is None:
        print "Invalid Info.plist file in plug-in"
        return None

    # Set up the log file
    __logFilePath = "%s/%s.log" % (logFilesPath, Identifier)
    if os.path.exists(__logFilePath):
        if os.path.exists("%s.old" % __logFilePath):
            os.remove("%s.old" % __logFilePath)
        os.rename(__logFilePath, "%s.old" % __logFilePath)

    # Now we can start logging
    PMS.Log("(Framework) Bundle verification complete", False)

    # Check whether debugging is enabled
    try:
        _debug = infoplist.xpath(
            '//key[text()="PlexPluginDebug"]//following-sibling::string/text()'
        )[0]
        if _debug == "1":
            Debug = True
            PMS.Log("(Framework) Debugging is enabled")
    except:
        pass

    # Log the system encoding (set during bootstrap)
    PMS.Log("(Framework) Default encoding is " + sys.getdefaultencoding())

    # Set up framework paths
    Prefs.__prefsPath = "%s/Preferences/%s.xml" % (supportFilesPath,
                                                   Identifier)
    Data.__dataPath = "%s/Data/%s" % (supportFilesPath, Identifier)
    Data.__dataItemPath = "%s/DataItems" % Data.__dataPath
    if not os.path.isdir(Data.__dataItemPath):
        FirstRun = True
        os.makedirs(Data.__dataItemPath)
    Resource.__resourcePath = "%s/Contents/Resources" % __bundlePath
    Helper.__helperPath = "%s/Contents/Helpers" % __bundlePath
    Resource.__sharedResourcePath = "%s/Plug-ins/Framework.bundle/Contents/Resources/Versions/1/Resources" % pmsPath
    Database.__databasePath = "%s/Databases/%s.db" % (supportFilesPath,
                                                      Identifier)
    os.chdir(Data.__dataItemPath)
    Locale.SetDefaultLocale()
    PMS.Log("(Framework) Configured framework modules")

    # Attempt to import the plug-in module - if debugging is enabled, don't catch exceptions
    if Debug:
        import Code as _plugin
        PMS.Log("(Framework) Imported plug-in module")
    else:
        try:
            import Code as _plugin
            PMS.Log("(Framework) Imported plug-in module")
        except ImportError:
            PMS.Log("(Framework) Couldn't import plug-in from bundle")
            __exit()
            return

    # Load the list of trusted plug-ins
    _trusted = []
    try:
        _trustedJSON = Resource.LoadShared("trust.json")
        if _trustedJSON:
            _trusted = JSON.ObjectFromString(_trustedJSON)
    except:
        pass

    # Populate the permission lists
    __setupPermissionLists()

    # Register the plug-in with the framework
    __pluginModule = _plugin

    # Check the imported module to make sure nothing untoward is happening!
    if Identifier in _trusted:
        PMS.Log("(Framework) Plug-in is trusted, skipping module check")
    else:
        __scanModules()
        _allowed = []
        for n in PMS.__dict__:
            if n[0] != "_":
                if type(PMS.__dict__[n]).__name__ == "module":
                    _allowed.append(n)
        for n in __modWhitelist:
            _allowed.append(n)
        __checkModule(_plugin, _allowed)
        PMS.Log("(Framework) Checked module imports")

    # Initialize the framework modules
    Dict.__load()
    if not FirstRun:
        __checkFrameworkCompatibility()
    Prefs.__load()
    HTTP.__loadCookieJar()
    HTTP.__loadCache()
    PMS.Log("(Framework) Initialized framework modules")

    # Call the plug-in's Start method
    PMS.Log("(Framework) Attempting to start the plug-in...")
    __call(__pluginModule.Start)
    PMS.Log("(Framework) Plug-in started", False)

    # Start timers
    __startCacheManager(firstRun=FirstRun)

    PMS.Log("(Framework) Entering run loop")
    # Enter a run loop to handle requests
    while True:
        try:
            # Read the input
            path = raw_input()
            path = path.lstrip("GET ").strip()
            LastPrefix = None

            # Read headers
            headers = {}
            stop = False
            while stop == False:
                line = raw_input()
                if len(line) == 1:
                    stop = True
                else:
                    split = string.split(line.strip(), ":", maxsplit=1)
                    if len(split) == 2:
                        headers[split[0].strip()] = split[1].strip()

            # Set the locale
            if headers.has_key("X-Plex-Language"):
                loc = headers["X-Plex-Language"].lower()
                Locale.__loadLocale(loc)

            # Set the version
            if headers.has_key("X-Plex-Version"):
                Client.__setVersion(headers["X-Plex-Version"])

            # Extract arguments
            kwargs = {}
            mpath = path
            if path.find("?") >= 0:
                parts = path.split("?")
                mpath = parts[0]
                args = parts[1].split("&")
                for arg in args:
                    kwarg = arg.split("=")
                    if len(kwarg) == 2:
                        name = urllib.unquote(kwarg[0])
                        value = urllib.unquote(kwarg[1])
                        kwargs[name] = value
            if mpath[-1] == "/":
                mpath = mpath[:-1]

            # Split the path into components and decode.
            pathNouns = path.split('/')
            pathNouns = [urllib.unquote(p) for p in pathNouns]

            # If no input was given, return an error
            if len(pathNouns) <= 1:
                __return("%s\r\n\r\n" % PMS.Error['BadRequest'])

            # Otherwise, attempt to handle the request
            else:
                result = None
                pathNouns.pop(0)
                count = len(pathNouns)
                if pathNouns[-1] == "":
                    pathNouns.pop(len(pathNouns) - 1)
                PMS.Log("(Framework) Handling request :  %s" % path, False)

                # Check for a management request
                if pathNouns[0] == ":":
                    result = __handlePMSRequest(pathNouns, path, **kwargs)

                else:
                    handler = None
                    isPrefixHandler = False

                    # See if there's a prefix handler available
                    for key in __prefixHandlers:
                        if mpath.count(key, 0, len(key)) == 1:
                            LastPrefix = key
                    if mpath in __prefixHandlers:
                        handler = __prefixHandlers[mpath]["handler"]
                        isPrefixHandler = True

                    else:
                        # Check each request handler to see if it handles the current prefix
                        popped = False
                        for key in __requestHandlers:
                            if handler is None:
                                if path.count(key, 0, len(key)) == 1:
                                    # Remove the prefix from the path
                                    keyNounCount = len(key.split('/')) - 1
                                    for i in range(keyNounCount):
                                        pathNouns.pop(0)
                                    count = count - keyNounCount
                                    # Find the request handler
                                    handler = __requestHandlers[key]["handler"]
                                    LastPrefix = key
                                    popped = True

                        # If no path request handler was found, make sure we still pop the prefix so internal requests work
                        for key in __prefixHandlers:
                            if popped == False:
                                if mpath.count(key, 0, len(key)) == 1:
                                    keyNounCount = len(key.split('/')) - 1
                                    for i in range(keyNounCount):
                                        pathNouns.pop(0)
                                    popped = True

                    # Check whether we should handle the request internally
                    handled = False
                    if count > 0:
                        if pathNouns[0] == ":":
                            handled = True
                            result = __handleInternalRequest(
                                pathNouns, path, **kwargs)

                    # Check if the App Store has flagged the plug-in as broken
                    if os.path.exists(
                            os.path.join(frameworkSupportFilesPath,
                                         "%s.broken" % Identifier)):
                        #TODO: Localise this bit, use message from the App Store if available
                        handled = True
                        result = PMS.Objects.MessageContainer(
                            "Please try again later",
                            "This plug-in is currently unavailable")
                        PMS.Log("(Framework) Plug-in is flagged as broken")

                    # If the request hasn't been handled, and we have a valid request handler, call it
                    else:
                        if not handled and handler is not None:
                            if isPrefixHandler:
                                result = handler(**kwargs)
                            else:
                                result = handler(pathNouns, path, **kwargs)

                # If the request wasn't handled, return an error
                if result == None:
                    PMS.Log("(Framework) Request not handled by plug-in",
                            False)
                    response = "%s\r\n\r\n" % PMS.Error['NotFound']

                # If the plugin returned an error, return it to PMS
                elif result in PMS.Error.values():
                    PMS.Log(
                        "(Framework) Plug-in returned an error :  %s" % result,
                        False)
                    response = "%s\r\n" % result

                # Otherwise, check if a valid object was returned, and return the result
                elif __objectManager.ObjectHasBase(result, Objects.Object):
                    PMS.Log("(Framework) Response OK")
                    resultStr = result.Content()
                    resultStatus = result.Status()
                    resultHeaders = result.Headers()
                    if resultStr is not None:
                        resultLen = len(resultStr)
                        if resultLen > 0:
                            resultHeaders += "Content-Length: %i\r\n" % resultLen
                        resultStr = "\r\n%s" % resultStr
                    else:
                        resultStr = ""
                    response = str("%s\r\n%s" %
                                   (resultStatus, resultHeaders)) + str(
                                       resultStr) + str("\r\n")

                __return(response)

        # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
        except KeyboardInterrupt:
            # Save data & exit
            __saveData()
            __exit()

        except EOFError:
            # Save data & exit
            __saveData()
            __exit()

        # If another exception is raised, deal with the problem
        except:
            __except()
            __return("%s\r\n\r\n" % PMS.Error['InternalError'])

        # Make sure the plugin's data is saved
        finally:
            __saveData()
Esempio n. 26
0
 def test_attrerror(self):
     d = Dict()
     with self.assertRaises(AttributeError):
         value = d.empty
Esempio n. 27
0
def Handle_Finger(finger):
    global x, y, xMin, xMax, yMin, yMax, testData, number, correct, database, startTime, lastNumber, end, topTimeSigned, predictedArray, checkN, type
    hand = frame.hands[0]
    fingers = hand.fingers
    k = 0
    for finger in fingers:
        for b in range(0, 4):
            w = 3
            if b == 0:
                bone = finger.bone(Leap.Bone.TYPE_METACARPAL)
            elif b == 1:
                bone = finger.bone(Leap.Bone.TYPE_PROXIMAL)
            elif b == 2:
                bone = finger.bone(Leap.Bone.TYPE_INTERMEDIATE)
                w = 2
            elif b == 3:
                bone = finger.bone(Leap.Bone.TYPE_DISTAL)
                w = 1

            tip = bone.next_joint
            xTip, yTip, zTip = tip[0], tip[1], tip[2]
            if ((b == 0) or (b == 3)):
                testData[0, k] = xTip
                testData[0, k + 1] = yTip
                testData[0, k + 2] = zTip
                k = k + 3

            Handle_Bone(bone, w)

    testData = CenterData(testData)
    predictedClass = clf.Predict(testData)
    end = timer()

    if end - startTime > max(
            10,
        (15 - database[userName]['correctAttempts']['digit' + str(number) +
                                                    'attempted']
         )):  #if the start time is over 20 then pick a new number
        database, topTimeSigned = Dict.update_database_time(
            userName, 'mean' + str(number) + 'time', end - startTime,
            'total' + str(number) + 'time',
            'digit' + str(number) + 'attempted')
        database = Dict.input_database_sign(
            userName, 'digit' + str(number) + 'attempted')
        number = randrange(10)
        type = GetMath(number)

        startTime = timer()

    predictedArray.append(number)
    checkN = []
    for i in range(0, 200):
        checkN.append(predictedClass)

    if checkN[0:50] == predictedArray[len(predictedArray) -
                                      50:len(predictedArray)]:
        predictedArray = []
        #show check mark
        pw.Prepare()
        image = pygame.image.load('images/iconmonstr-check-mark-1.png')
        pw.screen.blit(image, (pygameWindowWidth / 2 + 100, 150))
        pw.Reveal()
        pygame.display.update()

        #correct handle
        correct = True

        #find the time taken to sign
        timeTaken = end - startTime

        #increment the digit signed and start the timer for the next digit
        database = Dict.input_database_sign(
            userName, 'digit' + str(number) + 'attempted')
        database = Dict.input_correct_database_sign(
            userName, 'digit' + str(number) + 'attempted')
        database, topTimeSigned = Dict.update_database_time(
            userName, 'mean' + str(number) + 'time', timeTaken,
            'total' + str(number) + 'time',
            'digit' + str(number) + 'attempted')
        startTime = timer()
        lastNumber = number

        #if I've signed this one correct four times get a new number
        if database[userName][
                'digit' + str(number) +
                'attempted'] > 3:  #just making it faster change back to 3 later
            sorted_dict = sorted(
                database[userName]['correctAttempts'].items(),
                key=lambda kv: kv[1])[0]  #grab the lowest signed number
            number = int(sorted_dict[0][len('digit'):len('digit') + 1])
            print(sorted_dict)
            print("New number " + str(number))
            type = GetMath(number)
            lastNumber = number  #?

        number = 10  #disable number
Esempio n. 28
0
 def test_keyerror(self):
     d = Dict()
     with self.assertRaises(KeyError):
         value = d['empty']
Esempio n. 29
0
 def test_attr(self):
     d = Dict()
Esempio n. 30
0
    def searchdrug(self):
        mutationrs = self.readannofile()
        extern = self.readexternal()
        mutationrs.update(extern)
        abl_idh2 = {}
        for partone in self.drugdict.keys():
            #########如果按部分写####
            for drug in self.drugdict[partone].keys():
                for gene in self.drugdict[partone][drug].keys():
                    rscom = []
                    rssite = {}
                    for rsid_c in self.drugdict[partone][drug][gene].keys():
                        [caa, rsid] = str(rsid_c).split(':')
                        genesite = gene + '(' + caa + ')'
                        for hap in self.drugdict[partone][drug][gene][
                                rsid_c].keys():
                            genetype, genepaa_type, genepaa = '', '', ''
                            if hap == 'N':
                                if rsid in mutationrs and str(rsid).startswith(
                                        'rs'):
                                    genetype = rsid + ':' + mutationrs[rsid]
                                elif rsid in mutationrs and not str(
                                        rsid).startswith('rs'):
                                    genepaa = '阳性'
                                    genepaa_type = rsid + ':' + genepaa
                                elif not str(rsid).startswith('rs'):
                                    genepaa = '阴性'

                                else:
                                    genetype = rsid + ':' + self.drugdict[
                                        partone][drug][gene][rsid_c][hap]

                                if genetype in self.haplotypedict[drug][
                                        gene].keys():
                                    Dict.addtodict4(self.endchesite, drug,
                                                    gene, hap, genesite,
                                                    [genetype.split(':')[1]] +
                                                    self.haplotypedict[drug]
                                                    [gene][genetype])
                                elif genepaa == '阳性':
                                    Dict.addtodict4(abl_idh2, drug, gene,
                                                    genepaa, genesite,
                                                    [genepaa] +
                                                    self.haplotypedict[drug]
                                                    [gene][genepaa_type])
                                elif genepaa == '阴性':
                                    Dict.addtodict4(
                                        abl_idh2, drug, gene, genepaa,
                                        genesite, [genepaa] +
                                        self.haplotypedict[drug][gene][genepaa]
                                    )
                                else:
                                    print(
                                        'type is {} drug is {} gene is {} u do not think about'
                                        .format(genetype, drug, gene))

                            else:
                                if rsid in mutationrs:
                                    genetype = rsid + ':' + mutationrs[rsid]
                                    rssite[genetype] = [
                                        genesite, mutationrs[rsid]
                                    ]
                                else:
                                    genetype = rsid + ':' + self.drugdict[
                                        partone][drug][gene][rsid_c][hap]
                                    rssite[genetype] = [
                                        genesite, self.drugdict[partone][drug]
                                        [gene][rsid_c][hap]
                                    ]
                                rscom.append(genetype)
                    if rscom:
                        combiners = self.comiter(rscom)
                        # if drug=='柔红霉素':print(combiners)
                        mark = 0
                        for coms in combiners:
                            if coms in self.haplotypedict[drug][gene].keys():
                                mark += 1
                                for site in coms.split(','):
                                    if site in rssite:
                                        Dict.addtodict4(
                                            self.endchesite, drug, gene, 'H',
                                            rssite[site][0],
                                            [rssite[site][1]] +
                                            self.haplotypedict[drug][gene]
                                            [coms])
                                    else:
                                        print('this rssite is not in list ' +
                                              site)
                            else:
                                pass
                        if mark == 0:
                            for site in rssite:
                                if 'others' in self.haplotypedict[drug][gene]:
                                    Dict.addtodict4(self.endchesite, drug,
                                                    gene, 'H', rssite[site][0],
                                                    [rssite[site][1]] +
                                                    self.haplotypedict[drug]
                                                    [gene]['others'])
                                else:
                                    print(
                                        'this haplotype has not a other class'
                                        + drug)
                        else:
                            print(gene + ' is haplotype')
        return abl_idh2