code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
METADATA_TABLE.select().where(
METADATA_TABLE.c.job_id == job_id)).fetchall()
metadata = {}
for row in results:
value = row['va... | def _get_metadata(job_id) | Return any metadata for the given job_id from the metadata table. | 3.912828 | 3.779264 | 1.035341 |
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall()
results = [dict(result) for result in results]
for result in results:
... | def _get_logs(job_id) | Return any logs for the given job_id from the logs table. | 4.953092 | 4.451789 | 1.112607 |
for attribute_name in attributes:
attribute = node.get(attribute_name)
if attribute is not None and pattern.search(attribute):
return True
return False | def check_node_attributes(pattern, node, *attributes) | Searches match in attributes against given pattern and if
finds the match against any of them returns True. | 2.83297 | 2.683291 | 1.055782 |
try:
content = tostring(node)
except Exception:
logger.exception("Generating of hash failed")
content = to_bytes(repr(node))
hash_id = md5(content).hexdigest()
return hash_id[:8] | def generate_hash_id(node) | Generates a hash_id for the node in question.
:param node: lxml etree node | 5.262272 | 6.504983 | 0.80896 |
if node_text is None:
node_text = node.text_content()
node_text = normalize_whitespace(node_text.strip())
text_length = len(node_text)
if text_length == 0:
return 0.0
links_length = sum(map(_get_normalized_text_length, node.findall(".//a")))
# Give 50 bonus chars worth of ... | def get_link_density(node, node_text=None) | Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text:
Text content of given node if it was obtained ... | 4.677298 | 5.02178 | 0.931402 |
weight = 0
if check_node_attributes(CLS_WEIGHT_NEGATIVE, node, "class"):
weight -= 25
if check_node_attributes(CLS_WEIGHT_POSITIVE, node, "class"):
weight += 25
if check_node_attributes(CLS_WEIGHT_NEGATIVE, node, "id"):
weight -= 25
if check_node_attributes(CLS_WEIGHT_... | def get_class_weight(node) | Computes weight of element according to its class/id.
We're using sets to help efficiently check for existence of matches. | 2.563582 | 2.389158 | 1.073007 |
unlikely = check_node_attributes(CLS_UNLIKELY, node, "class", "id")
maybe = check_node_attributes(CLS_MAYBE, node, "class", "id")
return bool(unlikely and not maybe and node.tag != "body") | def is_unlikely_node(node) | Short helper for checking unlikely status.
If the class or id are in the unlikely list, and there's not also a
class/id in the likely list then it might need to be removed. | 7.147107 | 6.700489 | 1.066655 |
MIN_HIT_LENTH = 25
candidates = {}
for node in nodes:
logger.debug("* Scoring candidate %s %r", node.tag, node.attrib)
# if the node has no parent it knows of then it ends up creating a
# body & html tag to parent the html fragment
parent = node.getparent()
if ... | def score_candidates(nodes) | Given a list of potential nodes, find some initial scores to start | 3.114265 | 3.139309 | 0.992023 |
doctype = None
#
# XML da NF-e
#
if '</NFe>' in xml:
doctype = '<!DOCTYPE NFe [<!ATTLIST infNFe Id ID #IMPLIED>]>'
elif '</cancNFe>' in xml:
doctype = '<!DOCTYPE cancNFe [<!ATTLIST infCanc Id ID #IMPLIED>]>'
elif '</inutNFe>' in x... | def _obtem_doctype(self, xml) | Obtém DOCTYPE do XML
Determina o tipo de arquivo que vai ser assinado, procurando pela tag
correspondente. | 2.315656 | 2.256036 | 1.026427 |
def decorator(self):
key = "_cached_property_" + getter.__name__
if not hasattr(self, key):
setattr(self, key, getter(self))
return getattr(self, key)
decorator.__name__ = getter.__name__
decorator.__module__ = getter.__module__
decorator.__doc__ = getter.__do... | def cached_property(getter) | Decorator that converts a method into memoized property.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties. | 2.064817 | 2.619966 | 0.788109 |
self.filename = ''
self.filehandler = 0
# Station name, identification and revision year:
self.station_name = ''
self.rec_dev_id = ''
self.rev_year = 0000
# Number and type of channels:
self.TT = 0
self.A = 0 # Number of analog channels.
... | def clear(self) | Clear the internal (private) variables of the class. | 4.579769 | 4.455375 | 1.02792 |
T = 1/float(self.samp[self.nrates-1])
endtime = self.endsamp[self.nrates-1] * T
t = numpy.linspace(0,endtime,self.endsamp[self.nrates-1])
return t | def getTime(self) | Actually, this function creates a time stamp vector
based on the number of samples and sample rate. | 5.965075 | 4.54207 | 1.313294 |
listidx = self.An.index(num) # Get the position of the channel number.
return self.Ach_id[listidx] | def getAnalogID(self,num) | Returns the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header. | 17.515972 | 12.430271 | 1.409138 |
listidx = self.Dn.index(num) # Get the position of the channel number.
return self.Dch_id[listidx] | def getDigitalID(self,num) | Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header. | 15.893029 | 10.598696 | 1.499527 |
listidx = self.An.index(num)
unit = self.uu[listidx]
if unit == 'kV' or unit == 'V':
return 'V'
elif unit == 'A' or unit == 'kA':
return 'I'
else:
print 'Unknown channel type'
return 0 | def getAnalogType(self,num) | Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel. | 5.302619 | 3.964726 | 1.337449 |
listidx = self.An.index(num) # Get the position of the channel number.
return self.uu[listidx] | def getAnalogUnit(self,num) | Returns the COMTRADE channel unit (e.g., kV, V, kA, A)
of a given channel number.
The number to be given is the same of the COMTRADE header. | 18.114254 | 11.216846 | 1.614915 |
if os.path.isfile(self.filename[0:-4] + '.dat'):
filename = self.filename[0:-4] + '.dat'
elif os.path.isfile(self.filename[0:-4] + '.DAT'):
filename = self.filename[0:-4] + '.DAT'
else:
print "Data file File not found."
retur... | def ReadDataFile(self) | Reads the contents of the Comtrade .dat file and store them in a
private variable.
For accessing a specific channel data, see methods getAnalogData and
getDigitalData. | 3.672 | 3.606456 | 1.018174 |
if not self.DatFileContent:
print "No data file content. Use the method ReadDataFile first"
return 0
if (ChNumber > self.A):
print "Channel number greater than the total number of channels."
return 0
# Fomating strin... | def getAnalogChannelData(self,ChNumber) | Returns an array of numbers containing the data values of the channel
number "ChNumber".
ChNumber is the number of the channal as in .cfg file. | 5.82063 | 5.855499 | 0.994045 |
if not self.DatFileContent:
print "No data file content. Use the method ReadDataFile first"
return 0
if (ChNumber > self.D):
print "Digital channel number greater than the total number of channels."
return 0
# Fomati... | def getDigitalChannelData(self,ChNumber) | Returns an array of numbers (0 or 1) containing the values of the
digital channel status.
ChNumber: digital channel number. | 6.41896 | 6.463966 | 0.993037 |
"Connect to a host on a given (SSL) port."
#
# source_address é atributo incluído na versão 2.7 do Python
# Verificando a existência para funcionar em versões anteriores à 2.7
#
if hasattr(self, 'source_address'):
sock = socket.create_connection((self.host, s... | def connect(self) | Connect to a host on a given (SSL) port. | 2.428503 | 2.288211 | 1.061311 |
'''
This code taken from Matt's Suspenders for initializing a logger
'''
global logger
logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(mess... | def initLogger() | This code taken from Matt's Suspenders for initializing a logger | 2.742956 | 1.693257 | 1.619929 |
#first, store the uniform size in our offsets file
offsets = np.lib.format.open_memmap(offsetFN, 'w+', '<u8', (1,))
offsets[0] = uniformLength
#define a constant character map for now
d = {'$':0, 'A':1, 'C':2, 'G':3, 'N':4, 'T':5}
dArr = np.add(np.zeros(dtype='<u... | def writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength):
'''
This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list o... | This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list of '$'-terminated strings to be saved
@param fnPrefix - the prefix for the temporar... | 2.707234 | 2.746986 | 0.985529 |
'''
During compression, each available process will calculate a subportion of the BWT independently using this
function. This process takes the chunk and rewrites it into a given filename using the technique described
in the compressBWT(...) function header
'''
#pull the tuple info
inputFN... | def compressBWTPoolProcess(tup) | During compression, each available process will calculate a subportion of the BWT independently using this
function. This process takes the chunk and rewrites it into a given filename using the technique described
in the compressBWT(...) function header | 4.367946 | 3.37051 | 1.29593 |
'''
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
@param outputFN - the directory for the output decompre... | def decompressBWT(inputDir, outputDir, numProcs, logger) | This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
@param outputFN - the directory for the output decompressed BWT, it... | 3.924125 | 2.320229 | 1.691266 |
'''
Individual process for decompression
'''
(inputDir, outputDir, startIndex, endIndex) = tup
if startIndex == endIndex:
return True
#load the thing we'll be extracting from
msbwt = MultiStringBWT.CompressedMSBWT()
msbwt.loadMsbwt(inputDir, None)
#open our out... | def decompressBWTPoolProcess(tup) | Individual process for decompression | 8.048764 | 7.478053 | 1.076318 |
'''
This function removes auxiliary files associated with a given filename
'''
if dirName != None:
if os.path.exists(dirName+'/auxiliary.npy'):
os.remove(dirName+'/auxiliary.npy')
if os.path.exists(dirName+'/totalCounts.p'):
os.remove(dirName+'/totalCount... | def clearAuxiliaryData(dirName) | This function removes auxiliary files associated with a given filename | 2.151329 | 1.956682 | 1.099478 |
good_keywords = ('youtube', 'blip.tv', 'vimeo')
node_str = tounicode(node)
for key in good_keywords:
if key in node_str:
return True
return False | def ok_embedded_video(node) | Check if this embed/video is an ok one to count. | 5.519604 | 4.90485 | 1.125336 |
body_element = dom.find(".//body")
if body_element is None:
fragment = fragment_fromstring('<div id="readabilityBody"/>')
fragment.append(dom)
else:
body_element.tag = "div"
body_element.set("id", "readabilityBody")
fragment = body_element
return document_f... | def build_base_document(dom, return_fragment=True) | Builds a base document with the body as root.
:param dom: Parsed lxml tree (Document Object Model).
:param bool return_fragment: If True only <div> fragment is returned.
Otherwise full HTML document is returned. | 3.295568 | 3.652309 | 0.902325 |
candidate_css = candidate_node.node.get("class")
potential_target = candidate_node.content_score * 0.2
sibling_target_score = potential_target if potential_target > 10 else 10
parent = candidate_node.node.getparent()
siblings = parent.getchildren() if parent is not None else []
for sibling... | def check_siblings(candidate_node, candidate_list) | Looks through siblings for content that might also be related.
Things like preambles, content split by ads that we removed, etc. | 3.854225 | 3.790171 | 1.0169 |
if node is None or len(node) == 0:
return None
logger.debug("\n\n-------------- CLEANING DOCUMENT -----------------")
to_drop = []
for n in node.iter():
# clean out any in-line style properties
if "style" in n.attrib:
n.set("style", "")
# remove embend... | def clean_document(node) | Cleans up the final document we return as the readable article. | 4.121604 | 4.134547 | 0.996869 |
if node.tag not in ('form', 'table', 'ul', 'div', 'p'):
return # this is not the tag we are looking for
weight = get_class_weight(node)
# content_score = LOOK up the content score for this node we found
# before else default to 0
content_score = 0
if weight + content_score < 0:
... | def clean_conditionally(node) | Remove the clean_el if it looks like bad content based on rules. | 3.930229 | 3.810322 | 1.031469 |
nodes_to_score = set()
should_remove = set()
for node in document.iter():
if is_unlikely_node(node):
logger.debug(
"We should drop unlikely: %s %r", node.tag, node.attrib)
should_remove.add(node)
elif is_bad_link(node):
logger.debug(
... | def find_candidates(document) | Finds cadidate nodes for the readable version of the article.
Here's we're going to remove unlikely nodes, find scores on the rest,
clean up and return the final best match. | 3.106148 | 2.845314 | 1.091672 |
if node.tag != "a":
return False
name = node.get("name")
href = node.get("href")
if name and not href:
return True
if href:
href_parts = href.split("#")
if len(href_parts) == 2 and len(href_parts[1]) > 25:
return True
return False | def is_bad_link(node) | Helper to determine if the node is link that is useless.
We've hit articles with many multiple links that should be cleaned out
because they're just there to pollute the space. See tests for examples. | 2.566668 | 2.512836 | 1.021423 |
for element in document.iter(tag="div"):
child_tags = tuple(n.tag for n in element.getchildren())
if "div" not in child_tags and "p" not in child_tags:
logger.debug(
"Changing leaf block element <%s> into <p>", element.tag)
element.tag = "p"
return d... | def leaf_div_elements_into_paragraphs(document) | Turn some block elements that don't have children block level
elements into <p> elements.
Since we can't change the tree as we iterate over it, we must do this
before we process our document. | 4.22888 | 3.749748 | 1.127777 |
try:
dom = self._original_document.dom
# cleaning doesn't return, just wipes in place
html_cleaner(dom)
return leaf_div_elements_into_paragraphs(dom)
except ValueError:
return None | def dom(self) | Parsed lxml tree (Document Object Model) of the given html. | 19.04311 | 17.936672 | 1.061686 |
dom = self.dom
if dom is None or len(dom) == 0:
return None
candidates, unlikely_candidates = find_candidates(dom)
drop_nodes_with_parents(unlikely_candidates)
return candidates | def candidates(self) | Generates list of candidates from the DOM. | 8.255636 | 6.634843 | 1.244285 |
if not self.candidates:
logger.info("No candidates found in document.")
return self._handle_no_candidates()
# right now we return the highest scoring candidate content
best_candidates = sorted(
(c for c in self.candidates.values()),
key=a... | def _readable(self) | The readable parsed article | 6.764127 | 6.394259 | 1.057844 |
# since we've not found a good candidate we're should help this
if self.dom is not None and len(self.dom):
dom = prep_article(self.dom)
dom = build_base_document(dom, self._return_fragment)
return self._remove_orphans(
dom.get_element_by_id("r... | def _handle_no_candidates(self) | If we fail to find a good candidate we need to find something else. | 11.161167 | 9.869361 | 1.130891 |
handler = cls()
saxify(dom, handler)
return handler.content | def parse(cls, dom) | Converts DOM into paragraphs. | 11.856868 | 11.325124 | 1.046953 |
'''
Iterator that yields tuples containing a sequence label and the sequence itself
@param fastaFN - the FASTA filename to open and parse
@return - an iterator yielding tuples of the form (label, sequence) from the FASTA file
'''
if fastaFN[len(fastaFN)-3:] == '.gz':
fp = gzip.open(fasta... | def fastaIterator(fastaFN) | Iterator that yields tuples containing a sequence label and the sequence itself
@param fastaFN - the FASTA filename to open and parse
@return - an iterator yielding tuples of the form (label, sequence) from the FASTA file | 2.418337 | 1.830723 | 1.320974 |
'''
Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression
and assign the appropriate class preferring the decompressed version if both exist.
@return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated
'''
... | def loadBWT(bwtDir, logger=None) | Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression
and assign the appropriate class preferring the decompressed version if both exist.
@return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated | 5.222626 | 1.953674 | 2.673233 |
'''
This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
@param seqArray - a list of '$'-terminated sequences to be in the MSBWT
@param mergedFN - the final destination filename for the BWT
@param numProcs - the number of processes it's allowed to use
... | def createMSBWTFromSeqs(seqArray, mergedDir, numProcs, areUniform, logger) | This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
@param seqArray - a list of '$'-terminated sequences to be in the MSBWT
@param mergedFN - the final destination filename for the BWT
@param numProcs - the number of processes it's allowed to use | 7.060702 | 4.095522 | 1.724005 |
'''
This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading
all string prior to computation
@param fastqFNs - a list of fastq filenames to extract sequences from
@param outputDir - the directory for all of the bwt related data
@param numPr... | def createMSBWTFromFastq(fastqFNs, outputDir, numProcs, areUniform, logger) | This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading
all string prior to computation
@param fastqFNs - a list of fastq filenames to extract sequences from
@param outputDir - the directory for all of the bwt related data
@param numProcs - the nu... | 7.642989 | 3.147484 | 2.428285 |
'''
This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory for all of the bwt related data
@param numProcs - the number of process... | def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger) | This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory for all of the bwt related data
@param numProcs - the number of processes it's allo... | 6.762137 | 3.113034 | 2.172201 |
'''
This function takes a series of sequences and creates a big BWT by merging the smaller ones
Mostly a test function, no real purpose to the tool as of now
@param seqArray - a list of '$'-terminated strings to be placed into the array
@param mergedFN - the final destination filename for the merge... | def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger) | This function takes a series of sequences and creates a big BWT by merging the smaller ones
Mostly a test function, no real purpose to the tool as of now
@param seqArray - a list of '$'-terminated strings to be placed into the array
@param mergedFN - the final destination filename for the merged BWT
@p... | 4.01206 | 2.25083 | 1.78248 |
'''
This function takes two kmer profiles and compare them for similarity.
@param profileFN1 - the first kmer-profile to compare to
@param profileFN2 - the second kmer-profile to compare to
@return - a tuple of the form (1-norm, 2-norm, sum of differences, normalized Dot product)
'''
fp1 = o... | def compareKmerProfiles(profileFN1, profileFN2) | This function takes two kmer profiles and compare them for similarity.
@param profileFN1 - the first kmer-profile to compare to
@param profileFN2 - the second kmer-profile to compare to
@return - a tuple of the form (1-norm, 2-norm, sum of differences, normalized Dot product) | 2.119921 | 1.720519 | 1.23214 |
'''
Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int)
'''
nextLine = fp.readline()
if nextLine == None or nextLine == '':
return (None, None)
else:
pieces = nextLine.strip('\n').split(',... | def parseProfileLine(fp) | Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int) | 3.930622 | 1.954028 | 2.011548 |
'''
Helper function for generating reverse-complements
'''
revComp = ''
complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'}
for c in reversed(seq):
revComp += complement[c]
return revComp | def reverseComplement(seq) | Helper function for generating reverse-complements | 2.913661 | 2.394785 | 1.216669 |
'''
This helper function calculates the start and end index for each character in the BWT. Basically, the information
generated here is for quickly finding offsets. This is run AFTER self.constructTotalCounts(...)
'''
#mark starts and ends of key elements
self.startInde... | def constructIndexing(self) | This helper function calculates the start and end index for each character in the BWT. Basically, the information
generated here is for quickly finding offsets. This is run AFTER self.constructTotalCounts(...) | 7.865699 | 2.89645 | 2.715634 |
'''
This function counts the number of occurrences of the given sequence
@param seq - the sequence to search for
@param givenRange - the range to start from (if a partial search has already been run), default=whole range
@return - an integer count of the number of times seq occur... | def countOccurrencesOfSeq(self, seq, givenRange=None) | This function counts the number of occurrences of the given sequence
@param seq - the sequence to search for
@param givenRange - the range to start from (if a partial search has already been run), default=whole range
@return - an integer count of the number of times seq occurred in this BWT | 4.405748 | 3.032432 | 1.452876 |
'''
This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is
associated with this read
@param strIndex - the index of the character to start with
@return - an integer indicating the dollar ID of the string the given character belongs... | def getSequenceDollarID(self, strIndex, returnOffset=False) | This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is
associated with this read
@param strIndex - the index of the character to start with
@return - an integer indicating the dollar ID of the string the given character belongs to | 5.261335 | 2.643373 | 1.990387 |
'''
This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index
'''
retNums = []
indices = []
#figure out the first hop ... | def recoverString(self, strIndex, withIndex=False) | This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index | 4.418334 | 3.475877 | 1.271142 |
'''
This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file
'''
self.totalSize = self.bwt.shape[0]
abtFN = self.dirName+'/totalCounts.... | def constructTotalCounts(self, logger) | This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file | 4.076758 | 2.710028 | 1.504323 |
'''
This function iterates through the BWT and counts the letters as it goes to create the FM index. For example, the string 'ACC$' would have BWT
'C$CA'. The FM index would iterate over this and count the occurence of the letter it found so you'd end up with this:
BWT FM-index
... | def constructFMIndex(self, logger) | This function iterates through the BWT and counts the letters as it goes to create the FM index. For example, the string 'ACC$' would have BWT
'C$CA'. The FM index would iterate over this and count the occurence of the letter it found so you'd end up with this:
BWT FM-index
C 0 0 0... | 6.331476 | 2.369526 | 2.672044 |
'''
This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of occurrences of char before the specified index
... | def getOccurrenceOfCharAtIndex(self, sym, index) | This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of occurrences of char before the specified index | 8.603366 | 4.598578 | 1.870875 |
'''
This function creates a complete FM-index for a specific position in the BWT. Example using the above example:
BWT Full FM-index
$ A C G T
C 0 1 2 4 4
$ 0 1 3 4 4
C 1 1 3 4 4
A 1 1 4 4 4
1 2 4 4... | def getFullFMAtIndex(self, index) | This function creates a complete FM-index for a specific position in the BWT. Example using the above example:
BWT Full FM-index
$ A C G T
C 0 1 2 4 4
$ 0 1 3 4 4
C 1 1 3 4 4
A 1 1 4 4 4
1 2 4 4 4
@return -... | 8.262965 | 2.217927 | 3.725535 |
'''
TODO: this method is oldddddd, needs to be ported into BasicBWT AND reworked to do this better
@param k - the length of the k-mers to profile
@param profileCsvFN - the filename of the csv to create
'''
searches = [('', 0, self.bwt.shape[0])]
normTotal = 0
... | def createKmerProfile(self, k, profileCsvFN) | TODO: this method is oldddddd, needs to be ported into BasicBWT AND reworked to do this better
@param k - the length of the k-mers to profile
@param profileCsvFN - the filename of the csv to create | 4.637892 | 3.015389 | 1.538074 |
'''
This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail
'''
#open the file with our BWT in it
self.dirNam... | def loadMsbwt(self, dirName, logger) | This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail | 12.797818 | 2.873663 | 4.453486 |
'''
This function constructs the total count for each valid character in the array and stores it under '<DIR>/totalCounts.p'
since these values are independent of compression
'''
self.letterBits = 3
self.numberBits = 8-self.letterBits
self.numPower = 2**self.numbe... | def constructTotalCounts(self, logger) | This function constructs the total count for each valid character in the array and stores it under '<DIR>/totalCounts.p'
since these values are independent of compression | 4.20366 | 3.428749 | 1.226004 |
'''
Used for searching, this function masks the complexity behind retrieving a specific character at a specific index
in our compressed BWT.
@param index - the index to retrieve the character from
@param return - return the character in our BWT that's at a particular index (integ... | def getCharAtIndex(self, index) | Used for searching, this function masks the complexity behind retrieving a specific character at a specific index
in our compressed BWT.
@param index - the index to retrieve the character from
@param return - return the character in our BWT that's at a particular index (integer format) | 6.186933 | 4.176787 | 1.481266 |
'''
This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
@return - a range of integers ... | def getBWTRange(self, start, end) | This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
@return - a range of integers representing the cha... | 8.3666 | 3.237083 | 2.584611 |
'''
This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in
decompression
@param startBlock - the index of the start block we will decode
@param endBlock - the index of the final block we will decode, if they are the same, we... | def decompressBlocks(self, startBlock, endBlock) | This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in
decompression
@param startBlock - the index of the start block we will decode
@param endBlock - the index of the final block we will decode, if they are the same, we decode one block
... | 4.834671 | 3.16716 | 1.5265 |
'''
This function creates a complete FM-index for a specific position in the BWT. Example using the above example:
BWT Full FM-index
$ A C G T
C 0 1 2 4 4
$ 0 1 3 4 4
C 1 1 3 4 4
A 1 1 4 4 4
1 2 4 4... | def getFullFMAtIndex(self, index) | This function creates a complete FM-index for a specific position in the BWT. Example using the above example:
BWT Full FM-index
$ A C G T
C 0 1 2 4 4
$ 0 1 3 4 4
C 1 1 3 4 4
A 1 1 4 4 4
1 2 4 4 4
@return -... | 5.07681 | 3.143234 | 1.615155 |
if isinstance(html, unicode):
return html
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_encoding = match.group(1).decode("ASCII")
# proceed unknown encoding as if it wasn't found at all
with ignored(LookupError):
return html.decode(declare... | def decode_html(html) | Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library. | 4.205169 | 4.002654 | 1.050595 |
assert html_content is not None
if isinstance(html_content, unicode):
html_content = html_content.encode("utf8", "xmlcharrefreplace")
try:
document = document_fromstring(html_content, parser=UTF8_PARSER)
except (ParserError, XMLSyntaxError):
raise ValueError("Failed to par... | def build_document(html_content, base_href=None) | Requires that the `html_content` not be None | 2.702728 | 2.620797 | 1.031262 |
props_dict = self.data.get('properties', {})
for prop_name in self.KNOWN_PROPERTIES:
if prop_name in props_dict:
setattr(self, prop_name, props_dict.get(prop_name))
else:
setattr(self, prop_name, None) | def _parse_properties(self) | Nodes have properties, which are facts like the
name, description, url etc.
Loop through each of them and set it as attributes on this company so
that we can make calls like
company.name
person.description | 2.560328 | 2.454686 | 1.043037 |
rs_dict = self.data.get('relationships', {})
for rs_name in self.KNOWN_RELATIONSHIPS:
if rs_name in rs_dict:
setattr(
self, rs_name, Relationship(rs_name, rs_dict.get(rs_name)))
else:
# fill in other relationships with ... | def _parse_relationship(self) | Nodes have Relationships, and similarly to properties,
we set it as an attribute on the Organization so we can make calls like
company.current_team
person.degrees | 4.885629 | 4.551919 | 1.073312 |
self.startTime = datetime.datetime.now()
self.offset = 0
return self | def open(self) | Reset time and counts. | 7.800074 | 5.733671 | 1.360398 |
self.offset = sent
now = datetime.datetime.now()
elapsed = (now - self.startTime).total_seconds()
if elapsed > 0:
mbps = (sent * 8 / (10 ** 6)) / elapsed
else:
mbps = None
self._display(sent, now, self.name, mbps) | def update(self, sent) | Update self and parent with intermediate progress. | 4.293421 | 3.961005 | 1.083922 |
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent <= self.total:
eta = (self.total - sent) * elapsed.total_seconds() / ... | def _display(self, sent, now, chunk, mbps) | Display intermediate progress. | 3.275215 | 3.132653 | 1.045509 |
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
self.output.write("\n")
self.output.flush() | def close(self) | Stop overwriting display, or update parent. | 5.594909 | 4.237194 | 1.320428 |
try:
chunkSize = receiveContext.chunkSize
except AttributeError:
pass
if sendContext is not None and receiveContext is not None:
with receiveContext as writer:
# Open reader after writer,
# so any raised errors will abort write before writer closes.
... | def transfer(sendContext, receiveContext, chunkSize) | Transfer (large) data from sender to receiver. | 4.019071 | 3.966545 | 1.013242 |
try:
return obj.display(detail=detail)
except AttributeError:
return str(obj) | def display(obj, detail='phrase') | Friendly string for volume, using sink paths. | 3.473829 | 3.318141 | 1.04692 |
if not isinstance(detail, int):
detail = detailNum[detail]
if detail > detailNum['word']:
return uuid
if uuid is None:
return None
return "%s...%s" % (uuid[:4], uuid[-4:]) | def _printUUID(uuid, detail='word') | Return friendly abbreviated string for uuid. | 4.933748 | 4.633965 | 1.064693 |
# This is an undocumented "feature" of logging module:
# logging.log() requires a numeric level
# logging.getLevelName() maps names to numbers
if not isinstance(level, int):
level = logging.getLevelName(level)
return (
functools.partial(_logDryRun, logger, level) if dryRun
... | def skipDryRun(logger, dryRun, level=logging.DEBUG) | Return logging function.
When logging function called, will return True if action should be skipped.
Log will indicate if skipped because of dry run. | 5.288683 | 5.530864 | 0.956213 |
vols = list(self.listVolumes())
vols.sort(key=lambda v: self.getSendPath(v))
return [vol.display(self, detail="line") for vol in vols] | def listContents(self) | Return list of volumes or diffs in this Store's selected directory. | 10.485916 | 8.843521 | 1.185717 |
for (vol, paths) in self.paths.items():
for path in paths:
if path.startswith('/'):
continue
if path == '.':
continue
if self.userVolume is not None and os.path.basename(path) != self.userVolume:
... | def listVolumes(self) | Return list of all volumes in this Store's selected directory. | 4.199184 | 4.014466 | 1.046013 |
try:
return self._fullPath(next(iter(self.getPaths(volume))))
except StopIteration:
return None | def getSendPath(self, volume) | Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store. | 6.890942 | 7.351102 | 0.937403 |
logger.debug("%s", paths)
if not paths:
path = os.path.basename(self.userPath) + '/Anon'
try:
# Relative paths are preferred
path = [p for p in paths if not p.startswith("/")][0]
except IndexError:
# If no relative path, just use... | def selectReceivePath(self, paths) | From a set of source paths, recommend a destination path.
The paths are relative or absolute, in a source Store.
The result will be absolute, suitable for this destination Store. | 5.362428 | 5.195515 | 1.032126 |
if fullPath is None:
return None
assert fullPath.startswith("/"), fullPath
path = os.path.relpath(fullPath, self.userPath)
if not path.startswith("../"):
return path
elif self.ignoreExtraVolumes:
return None
else:
... | def _relativePath(self, fullPath) | Return fullPath relative to Store directory.
Return fullPath if fullPath is not inside directory.
Return None if fullPath is outside our scope. | 4.931733 | 4.910581 | 1.004307 |
self._size = size
self._sizeIsEstimated = sizeIsEstimated
if self.fromVol is not None and size is not None and not sizeIsEstimated:
Diff.theKnownSizes[self.toUUID][self.fromUUID] = size | def setSize(self, size, sizeIsEstimated) | Update size. | 7.797984 | 7.112893 | 1.096317 |
vol = self.toVol
paths = self.sink.getPaths(vol)
if self.sink == dest:
logger.info("Keep: %s", self)
self.sink.keep(self)
else:
# Log, but don't skip yet, so we can log more detailed skipped actions later
skipDryRun(logger, dest.d... | def sendTo(self, dest, chunkSize) | Send this difference to the dest Store. | 8.844103 | 8.605385 | 1.027741 |
if size is None or fromUUID is None:
return
if not isinstance(size, int):
logger.warning("Bad size: %s", size)
return
stream.write(str("%s\t%s\t%d\n" % (
self.uuid,
fromUUID,
size,
))) | def writeInfoLine(self, stream, fromUUID, size) | Write one line of diff information. | 3.283283 | 3.181149 | 1.032106 |
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size) | def writeInfo(self, stream) | Write information about diffs into a file stream for use later. | 18.252058 | 14.483069 | 1.260234 |
count = len([None
for (fromUUID, size)
in Diff.theKnownSizes[self.uuid].iteritems()
if size is not None and fromUUID is not None
])
return count > 0 | def hasInfo(self) | Will have information to write. | 18.724756 | 16.926998 | 1.106207 |
try:
for line in stream:
(toUUID, fromUUID, size) = line.split()
try:
size = int(size)
except Exception:
logger.warning("Bad size: %s", size)
continue
logger.debug("di... | def readInfo(stream) | Read previously-written information about diffs. | 5.442976 | 5.069689 | 1.073631 |
if not isinstance(detail, int):
detail = detailNum[detail]
if detail >= detailNum['line'] and self.size is not None:
size = " (%s%s)" % (
humanize(self.size),
"" if self.exclusiveSize is None else (
" %s exclusive" % (... | def display(self, sink=None, detail='phrase') | Friendly string for volume, using sink paths. | 6.794796 | 6.082711 | 1.117067 |
if isinstance(vol, cls):
return vol
elif vol is None:
return None
else:
return cls(vol, None) | def make(cls, vol) | Convert uuid to Volume, if necessary. | 3.465339 | 3.031277 | 1.143194 |
self.diffs = collections.defaultdict((lambda: []))
self.extraKeys = {}
for key in self.bucket.list():
if key.name.startswith(theTrashPrefix):
continue
keyInfo = self._parseKeyName(key.name)
if keyInfo is None:
if key... | def _fillVolumesAndPaths(self, paths) | Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]} | 4.338514 | 4.298002 | 1.009426 |
items = list(self.extraKeys.items())
items.sort(key=lambda t: t[1])
(count, size) = (0, 0)
for (diff, path) in items:
if path.startswith("/"):
continue
yield str(diff)
count += 1
size += diff.size
yield "... | def listContents(self) | Return list of volumes or diffs in this Store's selected directory. | 4.895123 | 4.504405 | 1.086742 |
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]] | def hasEdge(self, diff) | Test whether edge is in this sink. | 11.378263 | 10.82111 | 1.051488 |
path = self.selectReceivePath(paths)
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
if self._skipDryRun(logger)("receive %s in %s", keyName, self):
return None
progress = _BotoProgress(diff.size) if self.showProgress is True else None
return _Upl... | def receive(self, diff, paths) | Return Context Manager for a file-like (stream) object to store a diff. | 12.788125 | 11.924351 | 1.072438 |
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if self._skipDryRun(logger)("receive info in '%s'", path):
return None
return _Uploader(self.bucket, path, bufferSize=theInfoBufferSize) | def receiveVolumeInfo(self, paths) | Return Context Manager for a file-like (stream) object to store volume info. | 38.095818 | 28.352287 | 1.343659 |
if name.endswith(Store.theInfoExtension):
return {'type': 'info'}
match = self.keyPattern.match(name)
if not match:
return None
match = match.groupdict()
match.update(type='diff')
return match | def _parseKeyName(self, name) | Returns dict with fullpath, to, from. | 7.468647 | 6.916442 | 1.079839 |
path = self._fullPath(self.extraKeys[diff])
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
key = self.bucket.get_key(keyName)
if self._skipDryRun(logger)("send %s in %s", keyName, self):
return None
progress = _BotoProgress(diff.size) if self.sho... | def send(self, diff) | Write the diff (toVol from fromVol) to the stream context manager. | 11.028664 | 10.291982 | 1.071578 |
path = self.extraKeys[diff]
if not path.startswith("/"):
logger.debug("Keeping %s", path)
del self.extraKeys[diff]
return
# Copy into self.userPath, if not there already
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
newP... | def keep(self, diff) | Mark this diff (or volume) to be kept in path. | 4.760877 | 4.578444 | 1.039846 |
(count, size) = (0, 0)
for (diff, path) in self.extraKeys.items():
if path.startswith("/"):
continue
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
count += 1
size += diff.size
if self._skipDryRun(logger,... | def deleteUnused(self) | Delete any old snapshots in path, if not kept. | 4.15783 | 4.025684 | 1.032826 |
args = command.parse_args()
with btrfs.FileSystem(args.dir) as mount:
# mount.rescanSizes()
fInfo = mount.FS_INFO()
pprint.pprint(fInfo)
vols = mount.subvolumes
# for dev in mount.devices:
# pprint.pprint(dev)
for vol in vols:
pri... | def main() | Main program. | 7.620748 | 7.188564 | 1.060121 |
# units = ('bytes', 'KB', 'MB', 'GB', 'TB')
# base = 1000
units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB')
base = 1024
if number is None:
return None
pow = int(math.log(number, base)) if number > 0 else 0
pow = min(pow, len(units) - 1)
mantissa = number / (base ** pow)
retu... | def humanize(number) | Return a human-readable string for number. | 2.18309 | 2.114385 | 1.032494 |
directory = os.path.dirname(path)
cmd = ["btrfs", "receive", "-e", directory]
if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd):
return None
if not os.path.exists(directory):
os.makedirs(directory)
process = subprocess.Popen(
... | def receive(self, path, diff, showProgress=True) | Return a context manager for stream that will store a diff. | 5.744333 | 5.386038 | 1.066523 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.