code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
printf('deleting genome (%s, %s)...' % (species, name))
conf.db.beginTransaction()
objs = []
allGood = True
try :
genome = Genome_Raba(name = name, species = species.lower())
objs.append(genome)
pBar = ProgressBar(label = 'preparing')
for typ in (Chromosome_Rab... | def deleteGenome(species, name) | Removes a genome from the database | 4.594939 | 4.559374 | 1.0078 |
"Serializes fastas into .dat files"
f = gzip.open(fastaFile)
header = f.readline()
strRes = f.read().upper().replace('\n', '').replace('\r', '')
f.close()
fn = '%s/chromosome%s.dat' % (targetDir, chromosome.number)
f = open(fn, 'w')
f.write(strRes)
f.close()
chromosome.dataFile... | def _importSequence(chromosome, fastaFile, targetDir) | Serializes fastas into .dat files | 4.104891 | 3.359848 | 1.221749 |
s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION)
f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w')
f.write(s)
f.close() | def createDefaultConfigFile() | Creates a default configuration file | 3.875232 | 3.71245 | 1.043848 |
parser = SafeConfigParser()
try :
parser.read(os.path.normpath(pyGeno_SETTINGS_DIR+'/config.ini'))
return parser.get('pyGeno_config', 'settings_dir')
except :
createDefaultConfigFile()
return getSettingsPath() | def getSettingsPath() | Returns the path where the settings are stored | 5.547441 | 5.418067 | 1.023878 |
global db, dbConf
global pyGeno_SETTINGS_PATH
global pyGeno_RABA_DBFILE
global pyGeno_DATA_PATH
if not checkPythonVersion() :
raise PythonVersionError("==> FATAL: pyGeno only works with python 2.7 and above, please upgrade your python version")
if not os.path.exists(pyGeno_SETTINGS_DIR) :
os.makedirs... | def pyGeno_init() | This function is automatically called at launch | 2.477837 | 2.473521 | 1.001745 |
e = copy.copy(self)
e.transcript = str(self.transcript)
return e | def pluck(self) | Returns a plucked object. Plucks the exon off the tree, set the value of self.transcript into str(self.transcript). This effectively disconnects the object and
makes it much more lighter in case you'd like to pickle it | 8.560386 | 3.270546 | 2.617418 |
if self.number == 0 :
return None
try :
return self.transcript.exons[self.number-1]
except IndexError :
return None | def previousExon(self) | Returns the previous exon of the transcript, or None if there is none | 3.594574 | 3.186618 | 1.128021 |
self.data = st.replace('\r', '\n')
self.data = self.data.replace('\n\n', '\n')
self.data = self.data.split('\n') | def parseStr(self, st) | Parses a string | 2.645848 | 2.646791 | 0.999644 |
i = li*4
self.__splitEntry(i)
return self.data[i] | def get(self, li) | returns the ith entry | 14.253011 | 10.596439 | 1.345075 |
e = FastqEntry()
self.data.append(e)
return e | def newEntry(self, ident = "", seq = "", plus = "", qual = "") | Appends an empty entry at the end of the CSV and returns it | 7.999414 | 5.475884 | 1.460844 |
loc = location + "/datawraps.json"
response = urllib2.urlopen(loc)
js = json.loads(response.read())
return js | def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) | Lists all the datawraps availabe from a remote a remote location. | 3.214079 | 3.054761 | 1.052154 |
l = listRemoteDatawraps(location)
printf("Available datawraps for bootstraping\n")
print json.dumps(l["Ordered"], sort_keys=True, indent=4, separators=(',', ': ')) | def printRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) | print all available datawraps from a remote location the location must have a datawraps.json in the following format::
{
"Ordered": {
"Reference genomes": {
"Human" : ["GRCh37.75", "GRCh38.78"],
"Mouse" : ["GRCm38.78"],
},
"SNPs":{
}
},
"Flat":{
"Reference genomes": {
"G... | 7.37662 | 4.85284 | 1.520062 |
try :
dw = listRemoteDatawraps()["Flat"]["Reference genomes"][name]
except AttributeError :
raise AttributeError("There's no remote genome datawrap by the name of: '%s'" % name)
finalFile = _DW(name, dw["url"])
PG.importGenome(finalFile, batchSize) | def importRemoteGenome(name, batchSize = 100) | Import a genome available from http://pygeno.iric.ca (might work). | 14.505974 | 14.905972 | 0.973165 |
try :
dw = listRemoteDatawraps()["Flat"]["SNPs"]
except AttributeError :
raise AttributeError("There's no remote genome datawrap by the name of: '%s'" % name)
finalFile = _DW(name, dw["url"])
PS.importSNPs(finalFile) | def importRemoteSNPs(name) | Import a SNP set available from http://pygeno.iric.ca (might work). | 16.560572 | 17.732056 | 0.933934 |
l = {"Genomes" : [], "SNPs" : []}
for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) :
if f.find(".tar.gz") > -1 :
l["Genomes"].append(f)
for f in os.listdir(os.path.join(this_dir, "bootstrap_data/SNPs")) :
if f.find(".tar.gz") > -1 :
l["SNPs"].append(f)
return l | def listDatawraps() | Lists all the datawraps pyGeno comes with | 2.574541 | 2.394891 | 1.075014 |
l = listDatawraps()
printf("Available datawraps for boostraping\n")
for k, v in l.iteritems() :
printf(k)
printf("~"*len(k) + "|")
for vv in v :
printf(" "*len(k) + "|" + "~~~:> " + vv)
printf('\n') | def printDatawraps() | print all available datawraps for bootstraping | 6.355529 | 5.10883 | 1.244028 |
path = os.path.join(this_dir, "bootstrap_data", "genomes/" + name)
PG.importGenome(path, batchSize) | def importGenome(name, batchSize = 100) | Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. | 7.277821 | 6.826577 | 1.066101 |
path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name)
PS.importSNPs(path) | def importSNPs(name) | Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. | 7.868304 | 7.412172 | 1.061538 |
self.logs['epochDuration'].append(self.lastEpochDuration)
self.logs['avg'].append(self.avg)
self.logs['runtime'].append(self.runtime)
self.logs['remtime'].append(self.remtime) | def log(self) | logs stats about the progression, without printing anything on screen | 5.457255 | 4.727558 | 1.15435 |
f = open(filename, 'wb')
cPickle.dump(self.logs, f)
f.close() | def saveLogs(self, filename) | dumps logs into a nice pickle | 2.47882 | 2.319371 | 1.068746 |
self.currEpoch += 1
tim = time.time()
if (tim - self.lastPrintTime > self.minRefeshTime) or forceRefresh :
self._update()
wheelState = self.wheel[self.currEpoch%len(self.wheel)]
if label == '' :
slabel = self.label
else :
slabel = label
if self.nbEpochs > 1 :
ratio = self... | def update(self, label = '', forceRefresh = False, log = False) | the function to be called at each iteration. Setting log = True is the same as calling log() just after update() | 3.221425 | 3.183755 | 1.011832 |
def appendAllele(alleles, sources, snp) :
pos = snp.start
if snp.alt[0] == '-' :
pass
# print warn % ('DELETION', snpSet, snp.start, snp.chromosomeNumber)
elif snp.ref[0] == '-' :
pass
# print warn % ('INSERTION', snpSet, snp.start, snp.chromosomeNumber)
else :
sources[snpSet] = snp... | def filter(self, chromosome, **kwargs) | The default filter mixes applied all SNPs and ignores Insertions and Deletions. | 4.937251 | 4.803338 | 1.027879 |
if childTree.x1 != None and childTree.x2 != None :
parentTree.insert(childTree.x1, childTree.x2, childTree.name, childTree.referedObject)
for c in childTree.children:
aux_insertTree(c, parentTree) | def aux_insertTree(childTree, parentTree) | This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree. | 3.220346 | 3.278065 | 0.982392 |
if tree.x1 != None and tree.x2 != None :
tree.x1, tree.x2 = tree.x1+offset, tree.x2+offset
for c in tree.children:
aux_moveTree(offset, c) | def aux_moveTree(offset, tree) | This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1 | 2.6113 | 2.516587 | 1.037635 |
if x1 > x2 :
xx1, xx2 = x2, x1
else :
xx1, xx2 = x1, x2
rt = None
insertId = None
childrenToRemove = []
for i in range(len(self.children)) :
if self.children[i].x1 == xx1 and xx2 == self.children[i].x2 :
self.children[i].name = self.children[i].name + ' U ' + name
self.children[i].re... | def insert(self, x1, x2, name = '', referedObject = []) | Insert the segment in it's right place and returns it.
If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the
referedObject will be appended to the already existing list | 1.865339 | 1.763523 | 1.057734 |
def condition(x1, x2, tree) :
#print self.id, tree.x1, tree.x2, x1, x2
if (tree.x1 != None and tree.x2 != None) and (tree.x1 <= x1 and x1 < tree.x2 or tree.x1 <= x2 and x2 < tree.x2) :
return True
return False
if x2 == None :
xx1, xx2 = x1, x1
elif x1 > x2 :
xx1, xx2 = x2, x1
else :... | def intersect(self, x1, x2 = None) | Returns a list of all segments intersected by [x1, x2] | 2.395727 | 2.331376 | 1.027602 |
"Radiates down: walks self.children downward until condition is no longer verifed or there's no childrens left "
ret = []
i = childId
while 0 <= i :
if condition(x1, x2, self.children[i]) :
ret.append(self.children[i])
else :
break
i -= 1
return ret | def __radiateDown(self, x1, x2, childId, condition) | Radiates down: walks self.children downward until condition is no longer verifed or there's no childrens left | 5.866875 | 2.280289 | 2.572865 |
"Radiates uo: walks self.children upward until condition is no longer verifed or there's no childrens left "
ret = []
i = childId
while i < len(self.children):
if condition(x1, x2, self.children[i]) :
ret.append(self.children[i])
else :
break
i += 1
return ret | def __radiateUp(self, x1, x2, childId, condition) | Radiates uo: walks self.children upward until condition is no longer verifed or there's no childrens left | 6.011822 | 2.053443 | 2.927679 |
for i in range(1, len(self.children)) :
if self.children[i].x1 > self.children[i-1].x2:
aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i]) | def removeGaps(self) | Remove all gaps between regions | 4.0892 | 3.921694 | 1.042713 |
if self.x1 != None and self.x2 != None:
return self.x2 - self.x1
else :
if len(self.children) == 0 :
return 0
else :
l = self.children[0].x2 - self.children[0].x1
for i in range(1, len(self.children)) :
l += self.children[i].x2 - self.children[i].x1 - max(0, self.children[i-1].x2 - self... | def getIndexedLength(self) | Returns the total length of indexed regions | 2.075112 | 1.979888 | 1.048096 |
res = []
if len(self.children) > 0 :
for c in self.children:
res.append((c.x1, c.x2))
else :
if self.x1 != None :
res = [(self.x1, self.x2)]
else :
res = None
return res | def getFirstLevel(self) | returns a list of couples (x1, x2) of all the first level indexed regions | 2.744329 | 2.333005 | 1.176306 |
if len(self.children) > 1 :
children = self.children
self.emptyChildren()
children[0].emptyChildren()
x1 = children[0].x1
x2 = children[0].x2
refObjs = [children[0].referedObject]
name = children[0].name
for i in range(1, len(children)) :
children[i].emptyChildren()
if child... | def flatten(self) | Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together | 2.209804 | 2.14486 | 1.030279 |
if self.x1 != None and self.x2 != None :
offset = newX1-self.x1
aux_moveTree(offset, self)
elif len(self.children) > 0 :
offset = newX1-self.children[0].x1
aux_moveTree(offset, self) | def move(self, newX1) | Moves tree to a new starting position, updates x1s of children | 3.563767 | 3.247253 | 1.097471 |
polymorphisms = []
defaultSequence = ''
binSequence = array.array(self.forma.typecode)
b = 0
i = 0
trueI = 0 #not inc in case if poly
poly = set()
while i < len(sequence)-1:
b = b | self.forma[self.charToBin[sequence[i]]]
if sequence[i+1] == '/' :
poly.add(sequence[i])
i += 2
els... | def encode(self, sequence) | Returns a tuple (binary reprensentation, default sequence, polymorphisms list) | 3.072352 | 2.758066 | 1.113952 |
arr = self.encode(strSeq)[0]
res = []
if not strict :
for i in range(len(arr)+len(self)) :
if i >= len(arr) or i > len(self) :
break
if arr[i] & self[i] == 0:
res.append(i)
else :
for i in range(len(arr)+len(self)) :
if i >= len(arr) or i > len(self) :
break
if arr[i] != ... | def findPolymorphisms(self, strSeq, strict = False) | Compares strSeq with self.sequence.
If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence | 2.183428 | 2.201773 | 0.991668 |
if polyStart < len(self.polymorphisms) and polyStart < polyStop:
sequence = copy.copy(listSequence)
ret = []
pk = self.polymorphisms[polyStart]
posInSequence = pk[0]-x1
if posInSequence < len(listSequence) :
for allele in pk[1] :
sequence[posInSequence] = allele
ret.extend(self._... | def __getSequenceVariants(self, x1, polyStart, polyStop, listSequence) | polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops | 3.192323 | 3.018174 | 1.0577 |
if x2 == -1 :
xx2 = len(self.defaultSequence)
else :
xx2 = x2
polyStart = None
nbP = 1
stopped = False
j = 0
for p in self.polymorphisms :
if p[0] >= xx2 :
break
if x1 <= p[0] :
if polyStart == None :
polyStart = j
nbP *= len(p[1])
if nbP > maxVariantNu... | def getSequenceVariants(self, x1 = 0, x2 = -1, maxVariantNumber = 128) | returns the sequences resulting from all combinaisons of all polymorphismes between x1 and x2. The results is a couple (bool, variants of sequence between x1 and x2), bool == true if there's more combinaisons than maxVariantNumber | 3.227529 | 2.824055 | 1.142871 |
if x2 == -1 :
xx2 = len(self.defaultSequence)
else :
xx2 = x2
nbP = 1
for p in self.polymorphisms:
if x1 <= p[0] and p[0] <= xx2 :
nbP *= len(p[1])
return nbP | def getNbVariants(self, x1, x2 = -1) | returns the nb of variants of sequences between x1 and x2 | 3.310198 | 2.941805 | 1.125227 |
if len(currHaystack) == 1 :
if (offset <= (len(self) - len(needle))) and (currHaystack[0] & needle[0]) > 0 and (self[offset+len(needle)-1] & needle[-1]) > 0 :
found = True
for i in xrange(1, len(needle)-1) :
if self[offset + i] & needle[i] == 0 :
found = False
break
if found :
... | def _dichFind(self, needle, currHaystack, offset, lst = None) | dichotomic search, if lst is None, will return the first position found. If it's a list, will return a list of all positions in lst. returns -1 or [] if no match found | 1.826787 | 1.783557 | 1.024238 |
next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP]
next[pattern[0]][0] = 1
restart_state = 0
for state in range(1, len(pattern)):
for input_token in self.ALPHABETA_KMP:
... | def _kmp_construct_next(self, pattern) | the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern. | 3.124397 | 2.858219 | 1.093127 |
input_sequence, pattern = pInput_sequence, [len(bin(e)) for e in pPattern]
n, m = len(input_sequence), len(pattern)
d = p = 0
next = self._kmp_construct_next(pattern)
while d < n and p < m:
p = next[... | def _kmp_search_first(self, pInput_sequence, pPattern) | use KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the occurence if found; otherwise, -1. | 3.96585 | 3.77633 | 1.050186 |
r = []
input_sequence, pattern = [len(bin(e)) for e in pInput_sequence], [len(bin(e)) for e in pPattern]
n, m = len(input_sequence), len(pattern)
d = p = 0
next = self._kmp_construct_next(pattern)
while d < ... | def _kmp_search_all(self, pInput_sequence, pPattern) | use KMP algorithm to search all occurrence in the input_sequence of the pattern. both arguments are integer arrays. return a list of the positions of the occurences if found; otherwise, []. | 3.51904 | 3.265257 | 1.077722 |
if lst != None: return self._kmp_search_all(haystack, needle)
else: return self._kmp_search_first(haystack, needle) | def _kmp_find(self, needle, haystack, lst = None) | find with KMP-searching. needle is an integer array, reprensenting a pattern. haystack is an integer array, reprensenting the input sequence. if lst is None, return the first position found or -1 if no match found. If it's a list, will return a list of all positions in lst. returns -1 or [] if no match found. | 4.158558 | 3.39152 | 1.226164 |
arr = self.encode(strSeq)
return self._dichFind(arr[0], self, 0, lst = None) | def findByBiSearch(self, strSeq) | returns the first occurence of strSeq in self. Takes polymorphisms into account | 19.639576 | 16.746027 | 1.17279 |
arr = self.encode(strSeq)
lst = []
self._dichFind(arr[0], self, 0, lst)
return lst | def findAllByBiSearch(self, strSeq) | Same as find but returns a list of all occurences | 9.775424 | 9.11988 | 1.071881 |
arr = self.encode(strSeq)
return self._kmp_find(arr[0], self) | def find(self, strSeq) | returns the first occurence of strSeq in self. Takes polymorphisms into account | 16.187521 | 15.643281 | 1.034791 |
arr = self.encode(strSeq)
lst = []
lst = self._kmp_find(arr[0], self, lst)
return lst | def findAll(self, strSeq) | Same as find but returns a list of all occurences | 11.784488 | 11.317902 | 1.041225 |
try:
binSeq = iter(binSequence[0])
except TypeError, te:
binSeq = binSequence
ret = ''
for b in binSeq :
ch = ''
for c in self.charToBin :
if b & self.forma[self.charToBin[c]] > 0 :
ch += c +'/'
if ch == '' :
raise KeyError('Key %d unkowom, bad format' % b)
ret += ch[:... | def decode(self, binSequence) | decodes a binary sequence to return a string | 5.631548 | 5.822131 | 0.967266 |
self.stream = stream
if gziped :
self.f = gzip.open(filename)
else :
self.f = open(filename)
self.filename = filename
self.gziped = gziped
lineId = 0
inLegend = True
while inLegend :
ll = self.f.readline()
l = ll.replace('\r', '\n').replace('\n', '')
if l[:2] == '##' :
eqP... | def parse(self, filename, gziped = False, stream = False) | opens a file | 2.89343 | 2.874767 | 1.006492 |
# UTF-8 Strings contain two lengths, as they might differ:
# 1) the UTF-16 length
str_len, skip = self._decode_length(offset, 1)
offset += skip
# 2) the utf-8 string length
encoded_bytes, skip = self._decode_length(offset, 1)
offset += skip
data... | def _decode8(self, offset) | Decode an UTF-8 String at the given offset
:param offset: offset of the string inside the data
:return: str | 4.944561 | 4.963875 | 0.996109 |
str_len, skip = self._decode_length(offset, 2)
offset += skip
# The len is the string len in utf-16 units
encoded_bytes = str_len * 2
data = self.m_charbuff[offset: offset + encoded_bytes]
assert self.m_charbuff[offset + encoded_bytes:offset + encoded_bytes + ... | def _decode16(self, offset) | Decode an UTF-16 String at the given offset
:param offset: offset of the string inside the data
:return: str | 4.789716 | 4.934497 | 0.970659 |
sizeof_2chars = sizeof_char << 1
fmt = "<2{}".format('B' if sizeof_char == 1 else 'H')
highbit = 0x80 << (8 * (sizeof_char - 1))
length1, length2 = unpack(fmt, self.m_charbuff[offset:(offset + sizeof_2chars)])
if (length1 & highbit) != 0:
length = ((length1... | def _decode_length(self, offset, sizeof_char) | Generic Length Decoding at offset of string
The method works for both 8 and 16 bit Strings.
Length checks are enforced:
* 8 bit strings: maximum of 0x7FFF bytes (See
http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692)
* 16 bit strings: maxi... | 3.054478 | 3.141036 | 0.972443 |
if not name[0].isalpha() and name[0] != "_":
log.warning("Invalid start for name '{}'".format(name))
self.packerwarning = True
name = "_{}".format(name)
if name.startswith("android:"):
# Seems be a common thing...
# Actually this means... | def _fix_name(self, name) | Apply some fixes to element named and attribute names.
Try to get conform to:
> Like element names, attribute names are case-sensitive and must start with a letter or underscore.
> The rest of the name can contain letters, digits, hyphens, underscores, and periods.
See: https://msdn.micr... | 4.650293 | 4.716294 | 0.986006 |
if not self.__charrange or not self.__replacement:
if sys.maxunicode == 0xFFFF:
# Fix for python 2.x, surrogate pairs does not match in regex
self.__charrange = re.compile(
u'^([\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD]|[\uD800-\uDBFF]... | def _fix_value(self, value) | Return a cleaned version of a value
according to the specification:
> Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
See https://www.w3.org/TR/xml/#charsets
:param value: a value to clean
:return: the cleaned value | 2.789472 | 2.778439 | 1.003971 |
i = "AndroidManifest.xml"
try:
manifest_data = self.zip.read(i)
except KeyError:
log.warning("Missing AndroidManifest.xml. Is this an APK file?")
else:
ap = AXMLPrinter(manifest_data)
if not ap.is_valid():
log.erro... | def _apk_analysis(self) | Run analysis on the APK file.
This method is usually called by __init__ except if skip_analysis is False.
It will then parse the AndroidManifest.xml and set all fields in the APK class which can be
extracted from the Manifest. | 2.397589 | 2.389848 | 1.003239 |
default = "Unknown"
ftype = None
try:
# Magic is optional
import magic
except ImportError:
return default
try:
# There are several implementations of magic,
# unfortunately all called magic
# We us... | def _get_file_magic_name(self, buffer) | Return the filetype guessed for a buffer
:param buffer: bytes
:return: str of filetype | 5.855521 | 6.189485 | 0.946043 |
if self._files == {}:
# Generate File Types / CRC List
for i in self.get_files():
buffer = self.zip.read(i)
self.files_crc32[i] = crc32(buffer)
# FIXME why not use the crc from the zipfile?
# should be validated as ... | def get_files_types(self) | Return the files inside the APK with their associated types (by using python-magic)
:rtype: a dictionnary | 6.937575 | 6.897068 | 1.005873 |
if ("Zip" in orig) or ('(JAR)' in orig):
val = is_android_raw(buffer)
if val == "APK":
return "Android application package file"
return orig | def _patch_magic(self, buffer, orig) | Overwrite some probably wrong detections by mime libraries
:param buffer: bytes of the file to detect
:param orig: guess by mime libary
:return: corrected guess | 18.929604 | 15.941483 | 1.187443 |
if self.files_crc32 == {}:
for i in self.get_files():
buffer = self.zip.read(i)
self.files_crc32[i] = crc32(buffer)
return self.files_crc32 | def get_files_crc32(self) | Calculates and returns a dictionary of filenames and CRC32
:return: dict of filename: CRC32 | 2.911304 | 3.212305 | 0.906298 |
dexre = re.compile("^classes(\d+)?.dex$")
return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1 | def is_multidex(self) | Test if the APK has multiple DEX files
:return: True if multiple dex found, otherwise False | 9.213256 | 8.029163 | 1.147474 |
for i in self.xml:
if self.xml[i] is None:
continue
for item in self.xml[i].findall('.//' + tag_name):
if with_namespace:
value = item.get(self._ns(attribute))
else:
value = item.get(attribut... | def get_elements(self, tag_name, attribute, with_namespace=True) | Deprecated: use `get_all_attribute_value()` instead
Return elements in xml files which match with the tag name and the specific attribute
:param tag_name: a string which specify the tag name
:param attribute: a string which specify the attribute | 3.402631 | 3.682676 | 0.923956 |
if len(value) > 0:
if value[0] == ".":
value = self.package + value
else:
v_dot = value.find(".")
if v_dot == 0:
value = self.package + "." + value
elif v_dot == -1:
value = s... | def _format_value(self, value) | Format a value with packagename, if not already set
:param value:
:return: | 2.980418 | 2.677941 | 1.112951 |
for i in self.xml:
if self.xml[i] is None:
continue
tag = self.xml[i].findall('.//' + tag_name)
if len(tag) == 0:
return None
for item in tag:
skip_this_item = False
for attr, val in list(att... | def get_element(self, tag_name, attribute, **attribute_filter) | :Deprecated: use `get_attribute_value()` instead
Return element in xml files which match with the tag name and the specific attribute
:param tag_name: specify the tag name
:type tag_name: string
:param attribute: specify the attribute
:type attribute: string
:rtype: strin... | 2.534776 | 2.579244 | 0.98276 |
if len(attribute_filter) <= 0:
return True
for attr, value in attribute_filter.items():
# TODO: figure out if both android:name and name tag exist which one to give preference
_value = tag.get(self._ns(attr))
if _value is None:
log... | def is_tag_matched(self, tag, **attribute_filter) | Return true if the attributes matches in attribute filter
:param tag: specify the tag element
:type tag: Element
:param attribute: specify the attribute
:type attribute: string | 5.817056 | 5.822118 | 0.999131 |
if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG):
return u''
return self.sb[self.m_name] | def name(self) | Return the String assosciated with the tag name | 6.553182 | 5.10218 | 1.284389 |
if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG):
return u''
# No Namespace
if self.m_namespaceUri == 0xFFFFFFFF:
return u''
return self.sb[self.m_namespaceUri] | def namespace(self) | Return the Namespace URI (if any) as a String for the current tag | 5.944936 | 4.81045 | 1.235838 |
if self.m_name == -1 or self.m_event != const.TEXT:
return u''
return self.sb[self.m_name] | def text(self) | Return the String assosicated with the current text | 11.693716 | 10.172173 | 1.149579 |
uri = self.getAttributeUri(index)
# No Namespace
if uri == 0xFFFFFFFF:
return u''
return self.sb[uri] | def getAttributeNamespace(self, index) | Return the Namespace URI (if any) for the attribute | 11.671692 | 11.086093 | 1.052823 |
offset = self._get_attribute_offset(index)
name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]
res = self.sb[name]
# If the result is a (null) string, we need to look it up.
if not res:
attr = self.m_resourceIDs[name]
if attr in public.SYS... | def getAttributeName(self, index) | Returns the String which represents the attribute name | 8.413796 | 8.234015 | 1.021834 |
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE] | def getAttributeValueType(self, index) | Return the type of the attribute at the given index
:param index: index of the attribute | 7.980068 | 9.774665 | 0.816403 |
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA] | def getAttributeValueData(self, index) | Return the data of the attribute at the given index
:param index: index of the attribute | 8.95523 | 10.510064 | 0.852062 |
headers = frozenset(request._p['header'].items())
path = frozenset(request._p['path'].items())
query = frozenset(request._p['query'])
return (request.url, headers, path, query) | def make_cache_key(request) | Generate a cache key from request object data | 4.814809 | 4.568112 | 1.054004 |
if isinstance(cache, BaseCache):
return cache
elif cache is False:
return DictCache()
elif cache is None:
return DummyCache()
else:
raise ValueError('Provided cache must implement BaseCache') | def check_cache(cache) | check if a cache fits esipy needs or not | 4.556696 | 4.264791 | 1.068445 |
epoch = datetime(1970, 1, 1)
# this date is ALWAYS in UTC (RFC 7231)
expire = (
datetime(
*parsedate(expires_header)[:6]
) - epoch
).total_seconds()
now = (datetime.utcnow() - epoch).total_seconds()
return int(expire) - int(now) | def get_cache_time_left(expires_header) | return the time left in second for an expires header | 3.63107 | 3.383923 | 1.073036 |
verifier = base64.urlsafe_b64encode(
os.urandom(n_bytes)
).rstrip(b'=').decode('utf-8')
# https://tools.ietf.org/html/rfc7636#section-4.1
# minimum length of 43 characters and a maximum length of 128 characters.
if len(verifier) < 43:
raise ValueError("Verifier too short. n_byt... | def generate_code_verifier(n_bytes=64) | source: https://github.com/openstack/deb-python-oauth2client
Generates a 'code_verifier' as described in section 4.1 of RFC 7636.
This is a 'high-entropy cryptographic random string' that will be
impractical for an attacker to guess.
Args:
n_bytes: integer between 31 and 96, inclusive. default: ... | 2.42514 | 2.365523 | 1.025202 |
digest = hashlib.sha256(verifier.encode('utf-8')).digest()
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('utf-8') | def generate_code_challenge(verifier) | source: https://github.com/openstack/deb-python-oauth2client
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
verifier: bytestring, representing a code_verifier as generated by
gene... | 2.040486 | 2.230679 | 0.914737 |
def add_receiver(self, receiver):
if not callable(receiver):
raise TypeError("receiver must be callable")
self.event_receivers.append(receiver) | Add a receiver to the list of receivers.
:param receiver: a callable variable | null | null | null | |
def remove_receiver(self, receiver):
if receiver in self.event_receivers:
self.event_receivers.remove(receiver) | Remove a receiver to the list of receivers.
:param receiver: a callable variable | null | null | null | |
def send_robust(self, **kwargs):
for receiver in self.event_receivers:
try:
receiver(**kwargs)
except Exception as err: # pylint: disable=W0703
if not hasattr(err, '__traceback__'):
LOGGER.error(sys.exc_info()[2])
... | Trigger all receiver and pass them the parameters
If an exception is raised it will be catched and displayed as error
in the logger (if defined).
:param kwargs: all arguments from the event. | null | null | null | |
headers = {"Accept": "application/json"}
app_url = '%s?datasource=%s' % (url, self.datasource)
cached = self.cache.get(cache_key, (None, None, 0))
if cached is None or len(cached) != 3:
self.cache.invalidate(cache_key)
cached_app, cached_headers, cached_... | def __get_or_create_app(self, url, cache_key) | Get the app from cache or generate a new one if required
Because app object doesn't have etag/expiry, we have to make
a head() call before, to have these informations first... | 3.417563 | 3.279542 | 1.042086 |
prefix = prefix if prefix is not None else self.cache_prefix
for endpoint in self.app.op.values():
cache_key = '%s:app:%s' % (prefix, endpoint.url)
self.cache.invalidate(cache_key)
self.cache.invalidate('%s:app:meta_swagger_url' % self.cache_prefix)
self.... | def clear_cached_endpoints(self, prefix=None) | Invalidate all cached endpoints, meta included
Loop over all meta endpoints to generate all cache key the
invalidate each of them. Doing it this way will prevent the
app not finding keys as the user may change its prefixes
Meta endpoint will be updated upon next call.
:param: pr... | 4.607919 | 4.578815 | 1.006356 |
def __get_jwks_key(self, jwks_uri, **kwargs):
jwks_key = kwargs.pop('jwks_key', None)
if not jwks_key:
res = self._session.get(jwks_uri)
res.raise_for_status()
jwks_key = res.json()
self.jwks_key_set = None
self.jwks_key = None
... | Get from jwks_ui all the JWK keys required to decode JWT Token.
Parameters
----------
jwks_uri : string
The URL where to gather JWKS key
kwargs : Dict
The constructor parameters | null | null | null | |
def __get_basic_auth_header(self):
if self.secret_key is None:
return {}
# encode/decode for py2/py3 compatibility
auth_b64 = "%s:%s" % (self.client_id, self.secret_key)
auth_b64 = base64.b64encode(auth_b64.encode('utf-8'))
auth_b64 = auth_b64.decode... | Return the Basic Authorization header for oauth if secret_key exists
Returns
-------
type
A dictionary that contains the Basic Authorization key/value,
or {} if secret_key is None | null | null | null | |
def __prepare_token_request(self, params, url=None):
if self.secret_key is None:
params['code_verifier'] = self.code_verifier
params['client_id'] = self.client_id
request_params = {
'headers': self.__get_basic_auth_header(),
'data': param... | Generate the request parameters to execute the POST call to
get or refresh a token.
Parameters
----------
params : dictionary
Contains the parameters that will be given as data to the oauth
endpoint
Returns
-------
type
... | null | null | null | |
def get_auth_uri(self, state, scopes=None, implicit=False):
if state is None or state == '':
raise AttributeError('"state" must be non empty, non None string')
scopes_list = [] if not scopes else scopes
response_type = 'code' if not implicit else 'token'
# ... | Constructs the full auth uri and returns it..
Parameters
----------
state : string
The state to pass through the auth process
scopes : list (optional)
The list of scope to have
implicit : Boolean (optional)
Activate or not the implici... | null | null | null | |
def get_refresh_token_params(self, scope_list=None):
if self.refresh_token is None:
raise AttributeError('No refresh token is defined.')
params = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
if scope_list... | Return the param object for the post() call to get the access_token
from the refresh_token
:param code: the refresh token
:return: a dict with the url, params and header | null | null | null | |
def update_token(self, response_json, **kwargs):
self.token_identifier = kwargs.pop(
'token_identifier',
self.token_identifier
)
self.access_token = response_json['access_token']
self.token_expiry = int(time.time()) + response_json['expires_in']
... | Update access_token, refresh_token and token_expiry from the
response body.
The response must be converted to a json object before being passed as
a parameter
:param response_json: the response body to use.
:param token_identifier: the user identifier for the token | null | null | null | |
def is_token_expired(self, offset=0):
if self.token_expiry is None:
return True
return int(time.time()) >= (self.token_expiry - offset) | Return true if the token is expired.
The offset can be used to change the expiry time:
- positive value decrease the time (sooner)
- negative value increase the time (later)
If the expiry is not set, always return True. This case allow the users
to define a security object... | null | null | null | |
def refresh(self, scope_list=None):
request_data = self.get_refresh_token_params(scope_list)
res = self._session.post(**request_data)
if res.status_code != 200:
raise APIException(
request_data['url'],
res.status_code,
... | Update the auth data (tokens) using the refresh token in auth. | null | null | null | |
def auth(self, code):
request_data = self.get_access_token_params(code)
res = self._session.post(**request_data)
if res.status_code != 200:
raise APIException(
request_data['url'],
res.status_code,
response=res.conten... | Request the token to the /oauth/token endpoint.
Update the security tokens.
:param code: the code you get from the auth process | null | null | null | |
def revoke(self):
if not self.refresh_token and not self.access_token:
raise AttributeError('No access/refresh token are defined.')
if self.refresh_token:
data = {
'token_type_hint': 'refresh_token',
'token': self.refresh_token,
... | Revoke the current tokens then empty all stored tokens
This returns nothing since the endpoint return HTTP/200
whatever the result is...
Currently not working with JWT, left here for compatibility. | null | null | null | |
def verify(self, kid='JWT-Signature-Key', options=None):
if self.access_token is None or self.access_token == "":
raise AttributeError('No access token are available at this time')
if options is None:
options = {}
if self.jwks_key_set is None:
... | Decode and verify the token and return the decoded informations
Parameters
----------
kid : string
The JWKS key id to identify the key to decode the token.
Default is 'JWT-Signature-Key'. Only change if CCP changes it.
options : Dict
The dicti... | null | null | null | |
def _retry_request(self, req_and_resp, _retry=0, **kwargs):
raise_on_error = kwargs.pop('raise_on_error', False)
if _retry:
# backoff delay loop in seconds: 0.01, 0.16, 0.81, 2.56, 6.25
time.sleep(_retry ** 4 / 100)
res = self._request(req_and_resp, **k... | Uses self._request in a sane retry loop (for 5xx level errors).
Do not use the _retry parameter, use the same params as _request
Used when ESIClient is initialized with retry_requests=True
if raise_on_error is True, this will only raise exception after
all retry have been done | null | null | null | |
def multi_request(self, reqs_and_resps, threads=20, **kwargs):
opt = kwargs.pop('opt', {})
raw_body_only = kwargs.pop('raw_body_only', self.raw_body_only)
# you shouldnt need more than 100, 20 is probably fine in most cases
threads = max(min(threads, 100), 1)
d... | Use a threadpool to send multiple requests in parallel.
:param reqs_and_resps: iterable of req_and_resp tuples
:param raw_body_only: applied to every request call
:param opt: applies to every request call
:param threads: number of concurrent workers to use
:return: a lis... | null | null | null | |
def _request(self, req_and_resp, **kwargs):
opt = kwargs.pop('opt', {})
# reset the request and response to reuse existing req_and_resp
req_and_resp[0].reset()
req_and_resp[1].reset()
# required because of inheritance
request, response = super(EsiCli... | Take a request_and_response object from pyswagger.App and
check auth, token, headers, prepare the actual request and fill the
response
Note on performance : if you need more performance (because you are
using this in a batch) you'd rather set raw_body_only=True, as parsed
... | null | null | null | |
def head(self, req_and_resp, **kwargs):
opt = kwargs.pop('opt', {})
# reset the request and response to reuse existing req_and_resp
req_and_resp[0].reset()
req_and_resp[1].reset()
# required because of inheritance
request, response = super(EsiClient,... | Take a request_and_response object from pyswagger.App, check
and prepare everything to make a valid HEAD request
:param req_and_resp: the request and response object from pyswagger.App
:param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144
:param raise_on_error: boolea... | null | null | null | |
def __cache_response(self, cache_key, res, method):
if ('expires' in res.headers
and method not in self.__uncached_methods__):
cache_timeout = get_cache_time_left(res.headers.get('expires'))
# Occasionally CCP swagger will return an outdated expire
... | cache the response
if method is one of self.__uncached_method__, don't cache anything | null | null | null | |
def __make_request(self, request, opt, cache_key=None, method=None):
# check expiration and etags
opt_headers = {}
cached_response = self.cache.get(cache_key, None)
if cached_response is not None:
# if we have expires cached, and still validd
expir... | Check cache, deal with expiration and etag, make the request and
return the response or cached response.
:param request: the pyswagger.io.Request object to prepare the request
:param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144
:param cache_key: the cache key used f... | null | null | null | |
def _hash(data):
hash_algo = hashlib.new('md5')
hash_algo.update(pickle.dumps(data))
# prefix allows possibility of multiple applications
# sharing same keyspace
return 'esi_' + hash_algo.hexdigest() | generate a hash from data object to be used as cache key | null | null | null | |
fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls)
self.fit(fvs, clsselected) | def fit_from_image(self, data, voxelsize, seeds, unique_cls) | This Method allows computes feature vector and train model.
:cls: list of index number of requested classes in seeds | 5.464994 | 5.042755 | 1.083732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.