code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
bgwrite_chunk - Chunk up the data into even #chunkSize blocks, and then pass it onto #bgwrite.
Use this to break up a block of data into smaller segments that can be written and flushed.
The smaller the chunks, the more interactive (recipient gets data quicker, iowait goes down f... | def bgwrite_chunk(fileObj, data, chunkSize, closeWhenFinished=False, chainAfter=None, ioPrio=4) | bgwrite_chunk - Chunk up the data into even #chunkSize blocks, and then pass it onto #bgwrite.
Use this to break up a block of data into smaller segments that can be written and flushed.
The smaller the chunks, the more interactive (recipient gets data quicker, iowait goes down for you) at cost ... | 13.173327 | 1.532422 | 8.596411 |
'''
chunk_data - Chunks a string/bytes into a list of string/bytes, each member up to #chunkSize in length.
e.x. chunk_data("123456789", 2) = ["12", "34", "56", "78", "9"]
'''
chunkSize = int(chunkSize)
return [data[i : i + chunkSize] for i in range(0, len(data), chunkSize)] | def chunk_data(data, chunkSize) | chunk_data - Chunks a string/bytes into a list of string/bytes, each member up to #chunkSize in length.
e.x. chunk_data("123456789", 2) = ["12", "34", "56", "78", "9"] | 3.561641 | 1.593486 | 2.235126 |
nsdict = NAMESPACES
#.xpath() always returns a list, so we need to select the first element
try:
return element.xpath('@xsi:type', namespaces=nsdict)[0]
except IndexError: # xpath result is empty
raise ValueError("The '{0}' element has no 'xsi:type' but has these "
... | def get_xsi_type(element) | returns the type of an element of the XML tree (incl. its namespace),
i.e. nodes, edges, layers etc.), raises an exception if the element has no
'xsi:type' attribute. | 5.887469 | 5.823607 | 1.010966 |
for key, count in sorted(counter.items(), key=itemgetter(1), reverse=True):
print "{0}{1} - {2}".format('\t'*tab, key, count) | def print_sorted_counter(counter, tab=1) | print all elements of a counter in descending order | 2.501626 | 2.402432 | 1.041289 |
for key, count in counter.most_common(number):
print "{0}{1} - {2}".format('\t'*tab, key, count) | def print_most_common(counter, number=5, tab=1) | print the most common elements of a counter | 2.89673 | 2.833291 | 1.022391 |
print "Node statistics\n==============="
layer_counts = Counter()
attrib_counts = Counter()
for node_id, node_attrs in docgraph.nodes_iter(data=True):
for layer in node_attrs['layers']:
layer_counts[layer] += 1
for attrib in node_attrs:
attrib_counts[attrib] ... | def node_statistics(docgraph) | print basic statistics about a node, e.g. layer/attribute counts | 2.677094 | 2.334893 | 1.14656 |
print "Edge statistics\n==============="
layer_counts = Counter()
attrib_counts = Counter()
source_counts = Counter()
target_counts = Counter()
for source, target, edge_attrs in docgraph.edges_iter(data=True):
for layer in edge_attrs['layers']:
layer_counts[layer] += 1
... | def edge_statistics(docgraph) | print basic statistics about an edge, e.g. layer/attribute counts | 2.223361 | 2.026423 | 1.097185 |
print networkx.info(docgraph), '\n'
node_statistics(docgraph)
print
edge_statistics(docgraph) | def info(docgraph) | print node and edge statistics of a document graph | 7.512898 | 6.072407 | 1.237219 |
return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens)) | def _sum_cycles_from_tokens(self, tokens: List[str]) -> int | Sum the total number of cycles over a list of tokens. | 16.156511 | 9.919616 | 1.628744 |
return sum((int(re.sub(r'\D', '', op)) for op in self.template_tokens)) | def template_cycles(self) -> int | The number of cycles dedicated to template. | 12.552024 | 9.926138 | 1.264543 |
return sum((int(re.sub(r'\D', '', op)) for op in self.skip_tokens)) | def skip_cycles(self) -> int | The number of cycles dedicated to skips. | 13.338805 | 10.451834 | 1.276217 |
return sum((int(re.sub(r'\D', '', op)) for op in self.umi_tokens)) | def umi_cycles(self) -> int | The number of cycles dedicated to UMI. | 12.84691 | 10.286761 | 1.248878 |
return sum((int(re.sub(r'\D', '', op)) for op in self.tokens)) | def total_cycles(self) -> int | The number of total number of cycles in the structure. | 12.080605 | 10.873312 | 1.111033 |
return {str(x): str(y) for x, y in self.items()} | def to_json(self) -> Mapping | Return the properties of this :class:`Sample` as JSON serializable. | 6.247904 | 4.745445 | 1.316611 |
section_name = self._whitespace_re.sub('_', section_name)
self._sections.append(section_name)
setattr(self, section_name, Section()) | def add_section(self, section_name: str) -> None | Add a section to the :class:`SampleSheet`. | 4.778862 | 3.894409 | 1.227109 |
all_keys: List[str] = []
for key in chain.from_iterable([sample.keys() for sample in self]):
if key not in all_keys:
all_keys.append(key)
return all_keys | def all_sample_keys(self) -> List[str] | Return the unique keys of all samples in this :class:`SampleSheet`.
The keys are discovered first by the order of samples and second by
the order of keys upon those samples. | 2.457652 | 2.683748 | 0.915754 |
if not self.samples:
raise ValueError('No samples in sample sheet')
markdown = tabulate(
[[getattr(s, h, '') for h in DESIGN_HEADER] for s in self.samples],
headers=DESIGN_HEADER,
tablefmt='pipe',
)
return maybe_render_markdown(m... | def experimental_design(self) -> Any | Return a markdown summary of the samples on this sample sheet.
This property supports displaying rendered markdown only when running
within an IPython interpreter. If we are not running in an IPython
interpreter, then print out a nicely formatted ASCII table.
Returns:
Markd... | 5.479862 | 4.088629 | 1.340269 |
for sample in samples:
self.add_sample(sample) | def add_samples(self, samples: Iterable[Sample]) -> None | Add samples in an iterable to this :class:`SampleSheet`. | 6.011055 | 2.879462 | 2.087562 |
content = {
'Header': dict(self.Header),
'Reads': self.Reads,
'Settings': dict(self.Settings),
'Data': [sample.to_json() for sample in self.samples],
**{title: dict(getattr(self, title)) for title in self._sections},
}
return j... | def to_json(self, **kwargs: Mapping) -> str | Write this :class:`SampleSheet` to JSON.
Returns:
str: The JSON dump of all entries in this sample sheet. | 4.679863 | 3.601041 | 1.299586 |
if not isinstance(blank_lines, int) or blank_lines <= 0:
raise ValueError('Number of blank lines must be a positive int.')
writer = csv.writer(handle)
csv_width: int = max([len(self.all_sample_keys), 2])
section_order = ['Header', 'Reads'] + self._sections + ['Sett... | def write(self, handle: TextIO, blank_lines: int = 1) -> None | Write this :class:`SampleSheet` to a file-like object.
Args:
handle: Object to wrap by csv.writer.
blank_lines: Number of blank lines to write between sections. | 2.634655 | 2.45723 | 1.072205 |
header_description = ['Sample_ID', 'Description']
header_samples = [
'Sample_ID',
'Sample_Name',
'Library_ID',
'index',
'index2',
]
header = SingleTable([], 'Header')
setting = SingleTable([], 'Settings')
... | def _repr_tty_(self) -> str | Return a summary of this sample sheet in a TTY compatible codec. | 3.399337 | 3.192056 | 1.064937 |
# pylint: disable=newstyle
super(TimeZoneField, self).validate(
value=self.get_prep_value(value),
model_instance=model_instance
)
# Insure the value is can be converted to a timezone
self.to_python(value) | def validate(self, value, model_instance) | Validates value and throws ValidationError. Subclasses should override
this to provide validation logic. | 7.318854 | 6.882862 | 1.063345 |
# pylint: disable=newstyle
value = super(TimeZoneField, self).get_prep_value(value)
if isinstance(value, tzinfo):
return value.zone
return value | def get_prep_value(self, value) | Converts timezone instances to strings for db storage. | 5.982069 | 4.836371 | 1.236892 |
# pylint: disable=newstyle
value = super(TimeZoneField, self).to_python(value)
if not value:
return value
try:
return pytz.timezone(str(value))
except pytz.UnknownTimeZoneError:
raise ValidationError(
message=self.err... | def to_python(self, value) | Returns a datetime.tzinfo instance for the value. | 3.121732 | 2.905056 | 1.074586 |
defaults = {'form_class': forms.TimeZoneField}
defaults.update(**kwargs)
return super(TimeZoneField, self).formfield(**defaults) | def formfield(self, **kwargs) | Returns a custom form field for the TimeZoneField. | 3.946621 | 2.643983 | 1.49268 |
def check(self, **kwargs): # pragma: no cover
errors = super(TimeZoneField, self).check(**kwargs)
errors.extend(self._check_timezone_max_length_attribute())
errors.extend(self._check_choices_attribute())
return errors | Calls the TimeZoneField's custom checks. | null | null | null | |
def _check_timezone_max_length_attribute(self): # pragma: no cover
# Retrieve the maximum possible length for the time zone string
possible_max_length = max(map(len, pytz.all_timezones))
# Make sure that the max_length attribute will handle the longest time
# zone string... | Checks that the `max_length` attribute covers all possible pytz
timezone lengths. | null | null | null | |
warning_params = {
'msg': (
"'choices' contains an invalid time zone value '{value}' "
"which was not found as a supported time zone by pytz "
"{version}."
),
'hint': "Values must be found in pytz.all... | def _check_choices_attribute(self): # pragma: no cover
if self.choices | Checks to make sure that choices contains valid timezone choices. | 3.057094 | 2.851049 | 1.07227 |
# pylint: disable=newstyle
value = super(LinkedTZDateTimeField, self).to_python(value)
if not value:
return value
return value.astimezone(self.timezone) | def to_python(self, value) | Convert the value to the appropriate timezone. | 8.978313 | 7.710268 | 1.164462 |
# pylint: disable=newstyle
# Retrieve the currently entered datetime
value = super(
LinkedTZDateTimeField,
self
).pre_save(
model_instance=model_instance,
add=add
)
# Convert the value to the correct time/timezone
... | def pre_save(self, model_instance, add) | Converts the value being saved based on `populate_from` and
`time_override` | 5.294812 | 4.995659 | 1.059883 |
# Since populate_from requires a model instance and Django does
# not allow lambda, we hope that we have been provided a
# function that can be parsed
kwargs['populate_from'] = self.populate_from
# Only include kwarg if it's not the default
if self.ti... | def deconstruct(self): # pragma: no cover
# pylint: disable=newstyle
name, path, args, kwargs = super(
LinkedTZDateTimeField,
self
).deconstruct()
# Only include kwarg if it's not the default
if self.populate_from is not None | Add our custom keyword arguments for migrations. | 4.976398 | 4.256876 | 1.169026 |
if hasattr(self.populate_from, '__call__'):
tz = self.populate_from(model_instance)
else:
from_attr = getattr(model_instance, self.populate_from)
tz = callable(from_attr) and from_attr() or from_attr
try:
tz = pytz.timezone(str(tz))
... | def _get_populate_from(self, model_instance) | Retrieves the timezone or None from the `populate_from` attribute. | 4.477349 | 3.666439 | 1.221171 |
if callable(self.time_override):
time_override = self.time_override()
else:
time_override = self.time_override
if not isinstance(time_override, datetime_time):
raise ValueError(
'Invalid type. Must be a datetime.time instance.'
... | def _get_time_override(self) | Retrieves the datetime.time or None from the `time_override` attribute. | 3.153269 | 2.472717 | 1.275224 |
if not value:
return value
# Retrieve the default timezone as the default
tz = get_default_timezone()
# If populate_from exists, override the default timezone
if self.populate_from is not None:
tz = self._get_populate_from(model_instance)
... | def _convert_value(self, value, model_instance, add) | Converts the value to the appropriate timezone and time as declared by
the `time_override` and `populate_from` attributes. | 3.909135 | 3.399302 | 1.149981 |
if isinstance(tree, (RSTTree, nltk.tree.Tree)):
if tree.label() in ('N', 'S'):
return tree.label()
else:
return 'relation'
elif isinstance(tree, basestring):
return 'edu'
else:
raise ValueError("Unknown tree/node type: {}".format(type(tree))) | def get_node_type(tree) | Returns the type of the root node of the given RST tree
(one of 'N', 'S', 'relation' or 'edu'.) | 4.231224 | 2.544996 | 1.662566 |
assert len(elements) == 2 and len(nuc_types) == 2, \
"A nucsat relation must have two elements."
assert set(nuc_types) == set(['N', 'S']), \
"A nucsat relation must consist of one nucleus and one satellite."
result = "\dirrel"
for i, nuc_type in enumerate(nuc_types):
if nu... | def make_nucsat(relname, nuc_types, elements) | Creates a rst.sty Latex string representation of a standard RST relation
(one nucleus, one satellite). | 3.368494 | 3.058016 | 1.101529 |
nuc_strings = []
for nucleus in nucleii:
nuc_strings.append( MULTINUC_ELEMENT_TEMPLATE.substitute(nucleus=nucleus) )
nucleii_string = "\n\t" + "\n\t".join(nuc_strings)
return MULTINUC_TEMPLATE.substitute(relation=relname, nucleus_segments=nucleii_string) | def make_multinuc(relname, nucleii) | Creates a rst.sty Latex string representation of a multi-nuclear RST relation. | 3.149724 | 2.926288 | 1.076354 |
nucsat_tuples = [tup for tup in nucsat_tuples] # unpack the iterable, so we can check its length
assert len(nucsat_tuples) > 1, \
"A multisat relation bundle must contain more than one relation"
result = "\dirrel\n\t"
first_relation, remaining_relations = nucsat_tuples[0], nucsat_tuples[1... | def make_multisat(nucsat_tuples) | Creates a rst.sty Latex string representation of a multi-satellite RST subtree
(i.e. a set of nucleus-satellite relations that share the same nucleus. | 3.139873 | 2.990723 | 1.049871 |
padding = amount * ch
return ''.join(padding+line for line in text.splitlines(True)) | def indent(text, amount, ch=' ') | Indents a string by the given amount of characters. | 3.517097 | 3.586218 | 0.980726 |
matches = [PCC_DOCID_RE.match(os.path.basename(fname))
for fname in pcc.tokenization]
return sorted(match.groups()[0] for match in matches) | def document_ids(self) | returns a list of document IDs used in the PCC | 11.868861 | 9.394609 | 1.263369 |
layer_graphs = []
for layer_name in self.layers:
layer_files, read_function = self.layers[layer_name]
for layer_file in layer_files:
if fnmatch.fnmatch(layer_file, '*{}.*'.format(doc_id)):
layer_graphs.append(read_function(layer_file))... | def get_document(self, doc_id) | given a document ID, returns a merged document graph containng all
available annotation layers. | 2.924898 | 2.605766 | 1.122472 |
layer_path = os.path.join(self.path, layer_name)
return list(dg.find_files(layer_path, file_pattern)) | def get_files_by_layer(self, layer_name, file_pattern='*') | returns a list of all files with the given filename pattern in the
given PCC annotation layer | 3.9625 | 3.967746 | 0.998678 |
assert isinstance(document_id, basestring), \
"The document ID must be given as a string, e.g. 'maz-1423'"
return list(dg.find_files(self._all_files, '*{}.*'.format(document_id))) | def get_files_by_document_id(self, document_id) | returns a list of all files (from all available annotation layers)
with the given document ID. | 9.245394 | 8.07725 | 1.144621 |
if is_ipython_interpreter(): # pragma: no cover
from IPython.display import Markdown # type: ignore # noqa: E501
return Markdown(string)
else:
return string | def maybe_render_markdown(string: str) -> Any | Render a string as Markdown only if in an IPython interpreter. | 4.567033 | 3.051404 | 1.496699 |
parser = argparse.ArgumentParser()
parser.add_argument('input_file',
help='{} file to be converted'.format(file_descriptor))
parser.add_argument('output_file', nargs='?', default=sys.stdout)
args = parser.parse_args(sys.argv[1:])
assert os.path.isfile(args.input_file), ... | def generic_converter_cli(docgraph_class, file_descriptor='') | generic command line interface for importers. Will convert the file
specified on the command line into a dot representation of the
corresponding DiscourseDocumentGraph and write the output to stdout
or a file specified on the command line.
Parameters
----------
docgraph_class : class
a ... | 2.227854 | 2.169836 | 1.026739 |
for node_id in discoursegraph:
discoursegraph.node[node_id]['layers'] = \
list(discoursegraph.node[node_id]['layers'])
for (from_id, to_id) in discoursegraph.edges_iter():
# there might be multiple edges between 2 nodes
edge_dict = discoursegraph.edge[from_id][to_id]
... | def layerset2list(discoursegraph) | typecasts all `layers` sets to lists to make the graph
exportable (e.g. into the `geoff` format).
Parameters
----------
discoursegraph : DiscourseDocumentGraph | 2.346025 | 2.461044 | 0.953264 |
for node_id in discoursegraph:
discoursegraph.node[node_id]['layers'] = \
str(discoursegraph.node[node_id]['layers'])
for (from_id, to_id) in discoursegraph.edges_iter():
# there might be multiple edges between 2 nodes
edge_dict = discoursegraph.edge[from_id][to_id]
... | def layerset2str(discoursegraph) | typecasts all `layers` from sets of strings into a single string to make
the graph exportable (e.g. into the `gexf` and `graphml` formats).
Parameters
----------
discoursegraph : DiscourseDocumentGraph | 2.343623 | 2.524265 | 0.928438 |
for node_id in discoursegraph:
node_dict = discoursegraph.node[node_id]
for attrib in node_dict:
if isinstance(node_dict[attrib], list):
node_dict[attrib] = str(node_dict[attrib])
for (from_id, to_id) in discoursegraph.edges_iter():
# there might be multi... | def attriblist2str(discoursegraph) | converts all node/edge attributes whose values are lists into string
values (e.g. to export them into the `gexf` and `graphml` formats).
WARNING: This function iterates over all nodes and edges! You can speed up
conversion by writing a custom function that only fixes those attributes
that have lists (o... | 2.007865 | 1.963832 | 1.022422 |
docgraph.node[docgraph.root].pop('metadata', None)
# delete metadata from the generic root node (which probably only exists
# when we merge graphs on the command line, cf. issue #89
if 'discoursegraph:root_node' in docgraph.node:
docgraph.node['discoursegraph:root_node'].pop('metadata', Non... | def remove_root_metadata(docgraph) | removes the ``metadata`` attribute of the root node of a document graph.
this is necessary for some exporters, as the attribute may contain
(nested) dictionaries. | 5.097068 | 5.074659 | 1.004416 |
prefix_err = "All tokens must share the same prefix: {0} vs. {1}"
tokens = []
if not span_string:
return tokens
spans = span_string.split(',')
for span in spans:
span_elements = span.split('..')
if len(span_elements) == 1:
tokens.append(span_elements[0])
... | def convert_spanstring(span_string) | converts a span of tokens (str, e.g. 'word_88..word_91')
into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']
Note: Please don't use this function directly, use spanstring2tokens()
instead, which checks for non-existing tokens!
Examples
--------
>>> convert_spanstring('w... | 2.325747 | 2.397333 | 0.970139 |
print("~ dumping contents of memory on {}".format(self.sensor.computer_name))
local_file = remote_file = "{}.memdmp".format(self.sensor.computer_name)
if not self.lr_session:
self.go_live()
try:
if cb_compress and auto_collect_result:
log... | def dump_sensor_memory(self, cb_compress=False, custom_compress=False, custom_compress_file=None, auto_collect_result=False) | Customized function for dumping sensor memory.
:arguments cb_compress: If True, use CarbonBlack's built-in compression.
:arguments custom_compress_file: Supply path to lr_tools/compress_file.bat to fork powershell compression
:collect_mem_file: If True, wait for memdump + and compression to com... | 3.302349 | 3.160923 | 1.044742 |
self.go_live()
print("~ dumping memory where pid={} for {}".format(pid, self.sensor.computer_name))
# need to make sure procdump.exe is on the sensor
procdump_host_path = None
dir_output = self.lr_session.list_directory(working_dir)
for dir_item in dir_output:
... | def dump_process_memory(self, pid, working_dir="c:\\windows\\carbonblack\\", path_to_procdump=None) | Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default
behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer.
:requires: SysInternals ProcDump v9.0 included with cbinterface==1.1.0
:arguments pid: Process... | 3.484394 | 3.497118 | 0.996361 |
return {rel.attrib['name']: rel.attrib['type']
for rel in urml_xml_tree.iterfind('//header/reltypes/rel')
if 'type' in rel.attrib} | def extract_relationtypes(urml_xml_tree) | extracts the allowed RST relation names and relation types from
an URML XML file.
Parameters
----------
urml_xml_tree : lxml.etree._ElementTree
lxml ElementTree representation of an URML XML file
Returns
-------
relations : dict of (str, str)
Returns a dictionary with RST r... | 4.436442 | 5.652604 | 0.784849 |
segment_types = \
{namespace+':'+seg.attrib['id']: seg.tag
for seg in urml_document_element.iter('nucleus', 'satellite')}
for seg in urml_document_element.iter('segment'):
seg_id = namespace+':'+seg.attrib['id']
if seg_id not in segment_types:
segment_types[seg... | def extract_segment_types(urml_document_element, namespace) | Return a map from segment node IDs to their segment type
('nucleus', 'satellite' or 'isolated'). | 3.791447 | 2.628583 | 1.442392 |
self.__context = etree.iterparse(self.urml_file, events=('end',),
tag='document', recover=False) | def _reset_corpus_iterator(self) | create an iterator over all documents in the file (i.e. all
<text> elements).
Once you have iterated over all documents, call this method again
if you want to iterate over them again. | 13.78214 | 12.668046 | 1.087945 |
'''
counts the number of documents in an URML file.
adapted from Listing 2 on
http://www.ibm.com/developerworks/library/x-hiperfparse/
'''
parser = etree.XMLParser(target=XMLElementCountTarget('document'))
# When iterated over, 'results' will contain the output fr... | def _get_num_of_documents(self) | counts the number of documents in an URML file.
adapted from Listing 2 on
http://www.ibm.com/developerworks/library/x-hiperfparse/ | 8.209105 | 3.944137 | 2.081344 |
for _event, elem in context:
if not self.debug:
yield URMLDocumentGraph(elem, tokenize=self.tokenize,
precedence=self.precedence)
else:
yield elem
# removes element (and references to it) from me... | def document_iter(self, context) | Iterates over all the elements in an iterparse context
(here: <document> elements) and yields an URMLDocumentGraph instance
for each of them. For efficiency, the elements are removed from the
DOM / main memory after processing them.
If ``self.debug`` is set to ``True`` (in the ``__init_... | 8.830467 | 4.938617 | 1.788045 |
for segment in document_elem.iter('segment'):
self.__add_segment(segment)
for relation in document_elem.iter('parRelation', 'hypRelation'):
self.__add_relation(relation)
# each discourse docgraphs has a default root node, but we will
# overwrite it here
... | def __urml2graph(self, document_elem) | Reads an RST tree (from an ElementTree representation of an URML
XML file) and adds all segments (nodes representing text) and
relations (nonterminal nodes in an RST tree as well as the
relationships that hold between them) to this
URMLDocumentGraph.
Parameters
---------... | 5.077973 | 4.947121 | 1.02645 |
segment_id = self.ns+':'+segment.attrib['id']
self.edus.append(segment_id) # store RST segment in list of EDUs
# A URML file can be tokenized, partially tokenized or not tokenized
# at all. The "tokenized tokens" in the URML file will always be added
# to the graph as ... | def __add_segment(self, segment) | add attributes to segment nodes, as well as edges to/from other
segments/groups. add segment to list of EDUs.
Parameters
----------
segment : ??? etree Element | 4.064025 | 3.917827 | 1.037316 |
rel_id = self.ns + ':' + relation.attrib['id']
rel_name = relation.attrib['type']
rel_type = relation.tag
self.add_node(rel_id, layers={self.ns, self.ns+':relation'},
attr_dict={self.ns+':rel_name': rel_name,
self.ns+':rel_t... | def __add_relation(self, relation) | <parRelation id="maz3377.1000" type="sequential">
<nucleus id="maz3377.1"/>
<nucleus id="maz3377.2"/>
</parRelation> | 2.674882 | 2.562068 | 1.044033 |
@wraps(func)
def inner(request, *args, **kwargs):
if not request.is_sudo():
return redirect_to_sudo(request.get_full_path())
return func(request, *args, **kwargs)
return inner | def sudo_required(func) | Enforces a view to have elevated privileges.
Should likely be paired with ``@login_required``.
>>> @sudo_required
>>> def secure_page(request):
>>> ... | 2.229264 | 2.418078 | 0.921916 |
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(dis_string)
temp.close()
dis_tree = cls(dis_filepath=temp.name)
os.unlink(temp.name)
return dis_tree | def fromstring(cls, dis_string) | Create a DisRSTTree instance from a string containing a *.dis parse. | 2.998642 | 2.404734 | 1.246975 |
if self._filters is None:
self._filters, self._attributes = self._fetch_configuration()
return self._filters | def filters(self) | List of filters available for the dataset. | 7.224568 | 6.38625 | 1.131269 |
if self._attributes is None:
self._filters, self._attributes = self._fetch_configuration()
return self._attributes | def attributes(self) | List of attributes available for the dataset (cached). | 7.469074 | 6.063296 | 1.23185 |
if self._default_attributes is None:
self._default_attributes = {
name: attr
for name, attr in self.attributes.items()
if attr.default is True
}
return self._default_attributes | def default_attributes(self) | List of default attributes for the dataset. | 2.865453 | 2.710878 | 1.05702 |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name, attr.description)
return pd.DataFrame.from_records(
_row_gen(self.attributes),
columns=['name', 'display_name', 'description']) | def list_attributes(self) | Lists available attributes in a readable DataFrame format.
Returns:
pd.DataFrame: Frame listing available attributes. | 3.75694 | 3.449517 | 1.089121 |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.type, attr.description)
return pd.DataFrame.from_records(
_row_gen(self.filters), columns=['name', 'type', 'description']) | def list_filters(self) | Lists available filters in a readable DataFrame format.
Returns:
pd.DataFrame: Frame listing available filters. | 4.879533 | 4.11329 | 1.186285 |
# Example query from Ensembl biomart:
#
# <?xml version="1.0" encoding="UTF-8"?>
# <!DOCTYPE Query>
# <Query virtualSchemaName = "default" formatter = "TSV" header = "0"
# uniqueRows = "0" count = "" datasetConfigVersion = "0.6" >
# <Dataset name = "... | def query(self,
attributes=None,
filters=None,
only_unique=True,
use_attr_names=False,
dtypes = None
) | Queries the dataset to retrieve the contained data.
Args:
attributes (list[str]): Names of attributes to fetch in query.
Attribute names must correspond to valid attributes. See
the attributes property for a list of valid attributes.
filters (dict[str,any... | 2.324475 | 2.296795 | 1.012052 |
filter_el = ElementTree.SubElement(root, 'Filter')
filter_el.set('name', filter_.name)
# Set filter value depending on type.
if filter_.type == 'boolean':
# Boolean case.
if value is True or value.lower() in {'included', 'only'}:
filter_e... | def _add_filter_node(root, filter_, value) | Adds filter xml node to root. | 2.712429 | 2.575782 | 1.053051 |
# we can't rely on the .ns attribute of a merged graph
if layer:
namespace = dg.layer2namespace(layer)
else:
namespace = docgraph.ns
ret_str = u''
pointing_chains = dg.get_pointing_chains(docgraph, layer=layer)
# a token can be part of 1+ markable(s)
first_token2markab... | def brat_output(docgraph, layer=None, show_relations=True) | converts a document graph with pointing chains into a string representation
of a brat *.ann file.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which might contain pointing chains (e.g. coreference links)
layer : str or None
the name of the layer that cont... | 3.018096 | 2.869782 | 1.051681 |
num_of_entities = len(pointing_chains)
mapsize = max(3, min(12, num_of_entities)) # 3 <= mapsize <= 12
colormap = brewer2mpl.get_map(name='Paired', map_type='Qualitative', number=mapsize)
colors = range(mapsize) * int(math.ceil(num_of_entities / float(mapsize)))
# recycle colors if we need more... | def create_visual_conf(docgraph, pointing_chains) | creates a visual.conf file (as a string)
for the given document graph. | 5.194606 | 5.194643 | 0.999993 |
tokens = convert_spanstring(span_string)
existing_nodes = set(docgraph.nodes())
existing_tokens = []
for tok in tokens:
if tok in existing_nodes:
existing_tokens.append(tok)
else: # we're trying to catch all token IDs that have been
# renamed during mergin... | def spanstring2tokens(docgraph, span_string) | Converts a span string (e.g. 'word_88..word_91') into a list of token
IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']. Token IDs that
do not occur in the given document graph will be filtered out.
Q: Why are some token IDs missing in a document graph?
A: They either have been removed manually (e... | 6.577487 | 6.166163 | 1.066706 |
token_node_ids = spanstring2tokens(docgraph, span_string)
return u' '.join(docgraph.node[tok_node_id][docgraph.ns+':token']
for tok_node_id in token_node_ids) | def spanstring2text(docgraph, span_string) | converts a span of tokens (str, e.g. 'word_88..word_91') into a string
that contains the tokens itself. | 4.43094 | 4.546684 | 0.974543 |
def sentence_sort_key(sentence_token_tuple):
return natural_sort_key(sentence_token_tuple[1][0])
sentence_token_tuples = zip(sentence_root_nodes, token_nodes)
return sorted(sentence_token_tuples, key=sentence_sort_key) | def sort_sentences_by_token_order(sentence_root_nodes, token_nodes) | Given a list of sentence markables (i.e. sentence root nodes) and a list of
lists of token markables (one list per sentence), returns a list of
(sentence root node, token nodes) tuples. The result is sorted by the
order in which the tokens occur in the text.
Parameters
----------
sentence_root_... | 3.226515 | 3.486928 | 0.925318 |
potential_markables = []
for node_id, nattr in dg.select_nodes_by_layer(docgraph, 'tiger:syntax', data=True):
if nattr['tiger:cat'] == 'NP':
# if an NP is embedded into a PP, only print the PP
pp_parent = False
for source, target in docgraph.in_edges(node_id):
... | def get_potential_markables(docgraph) | returns a list of all NPs and PPs in the given docgraph.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph that (at least) contains syntax trees
(imported from Tiger XML files)
Returns
-------
potential_markables : list of str or int
Node IDs of a... | 3.579452 | 3.310236 | 1.081328 |
common_paths_file = os.path.join(project_path, 'common_paths.xml')
tree = etree.parse(common_paths_file)
paths = {}
path_vars = ['basedata', 'scheme', 'style', 'style', 'customization',
'markable']
for path_var in path_vars:
specific_pat... | def _parse_common_paths_file(project_path) | Parses a common_paths.xml file and returns a dictionary of paths,
a dictionary of annotation level descriptions and the filename
of the style file.
Parameters
----------
project_path : str
path to the root directory of the MMAX project
Returns
------... | 3.764216 | 2.683039 | 1.402967 |
token_nodes = []
# if sentence annotations were ignored during MMAXDocumentGraph
# construction, we need to extract sentence/token node IDs manually
if self.ignore_sentence_annotations:
mp = self.mmax_project
layer_dict = mp.annotations['sentence']
... | def get_sentences_and_token_nodes(self) | Returns a list of sentence root node IDs and a list of sentences,
where each list contains the token node IDs of that sentence.
Both lists will be empty if sentences were not annotated in the original
MMAX2 data.
TODO: Refactor this! There's code overlap with
self.add_annotation... | 3.627928 | 3.362114 | 1.079061 |
return spanstring2tokens(self, self.node[sentence_root_node][self.ns+':span']) | def get_token_nodes_from_sentence(self, sentence_root_node) | returns a list of token node IDs belonging to the given sentence | 26.14304 | 19.593948 | 1.334241 |
return os.path.join(self.mmax_project.paths['project_path'],
self.mmax_project.paths['basedata'],
etree.parse(mmax_base_file).find('//words').text) | def get_word_file(self, mmax_base_file) | parses an MMAX base file (``*.mmax``) and returns the path
to the corresponding ``_words.xml`` file (which contains
the tokens of the document). | 5.678802 | 6.133169 | 0.925916 |
for word in etree.parse(words_file).iterfind('//word'):
token_node_id = word.attrib['id']
self.tokens.append(token_node_id)
token_str = ensure_unicode(word.text)
self.add_node(token_node_id,
layers={self.ns, self.ns+':token'},
... | def add_token_layer(self, words_file, connected) | parses a _words.xml file, adds every token to the document graph
and adds an edge from the MMAX root node to it.
Parameters
----------
connected : bool
Make the graph connected, i.e. add an edge from root to each
token. | 3.283216 | 3.154879 | 1.040679 |
assert os.path.isfile(annotation_file), \
"Annotation file doesn't exist: {}".format(annotation_file)
tree = etree.parse(annotation_file)
root = tree.getroot()
default_layers = {self.ns, self.ns+':markable', self.ns+':'+layer_name}
# avoids eml.org namespac... | def add_annotation_layer(self, annotation_file, layer_name) | adds all markables from the given annotation layer to the discourse
graph. | 4.46034 | 4.366963 | 1.021383 |
assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree)
edu_str = u' '.join(word for word in text_subtree.leaves())
return re.sub('_!(.*?)_!', '\g<1>', edu_str) | def get_edu_text(text_subtree) | return the text of the given EDU subtree, with '_!'-delimiters removed. | 4.245837 | 3.566729 | 1.190401 |
tree_type = tree.label()
assert tree_type in SUBTREE_TYPES, "tree_type: {}".format(tree_type)
return tree_type | def get_tree_type(tree) | returns the type of the (sub)tree: Root, Nucleus or Satellite
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it) | 3.800139 | 4.281123 | 0.88765 |
node_type = tree[0].label()
assert node_type in NODE_TYPES, "node_type: {}".format(node_type)
return node_type | def get_node_type(tree) | returns the node type (leaf or span) of a subtree (i.e. Nucleus or Satellite)
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it) | 3.538542 | 5.02749 | 0.703839 |
node_type = get_node_type(nuc_or_sat)
if node_type == 'leaf':
leaf_id = nuc_or_sat[0].leaves()[0]
if namespace is not None:
return '{0}:{1}'.format(namespace, leaf_id)
else:
return string(leaf_id)
#else: node_type == 'span'
span_start = nuc_or_sat[0]... | def get_node_id(nuc_or_sat, namespace=None) | return the node ID of the given nucleus or satellite | 2.102641 | 2.113844 | 0.9947 |
'''
This converts '(' and ')' brackets the EDUs of the RST into PTB-style
tokens (e.g., -LRB-) to escape them for nltk.
'''
def replace_brackets(matchobj):
edu = matchobj.group(0)
for (br, br_repl) in DIS_ESCAPES:
edu = re.sub("\{}".format(br), br_repl, edu)
retur... | def convert_parens_in_rst_tree_str(rst_tree_str) | This converts '(' and ')' brackets the EDUs of the RST into PTB-style
tokens (e.g., -LRB-) to escape them for nltk. | 8.158556 | 3.461774 | 2.356756 |
'''
nonblock_read - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines.
@param stream <object> - A stream (like a file object or a socket)
@param limit <None/int> - Max number of bytes to read. If None or 0, will read as much ... | def nonblock_read(stream, limit=None, forceMode=None) | nonblock_read - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines.
@param stream <object> - A stream (like a file object or a socket)
@param limit <None/int> - Max number of bytes to read. If None or 0, will read as much data is availabl... | 4.361212 | 2.331811 | 1.870311 |
if self._datasets is None:
self._datasets = self._fetch_datasets()
return self._datasets | def datasets(self) | List of datasets in this mart. | 3.8269 | 3.484504 | 1.098262 |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name)
return pd.DataFrame.from_records(
_row_gen(self.datasets),
columns=['name', 'display_name']) | def list_datasets(self) | Lists available datasets in a readable DataFrame format.
Returns:
pd.DataFrame: Frame listing available datasets. | 4.597829 | 4.595492 | 1.000509 |
return {rel.attrib['name']: rel.attrib['type']
for rel in rs3_xml_tree.iter('rel')
if 'type' in rel.attrib} | def extract_relationtypes(rs3_xml_tree) | extracts the allowed RST relation names and relation types from
an RS3 XML file.
Parameters
----------
rs3_xml_tree : lxml.etree._ElementTree
lxml ElementTree representation of an RS3 XML file
Returns
-------
relations : dict of (str, str)
Returns a dictionary with RST rela... | 3.199707 | 4.192486 | 0.763201 |
assert node_type in ('source', 'target')
_, node_id_str = edge.attrib[node_type].split('.') # e.g. //@nodes.251
return int(node_id_str) | def get_node_id(edge, node_type) | returns the source or target node id of an edge, depending on the
node_type given. | 6.212173 | 6.067077 | 1.023915 |
onset_label = edge.find('labels[@name="SSTART"]')
onset_str = onset_label.xpath('@valueString')[0]
return int(onset_str) | def get_string_onset(edge) | return the onset (int) of a string | 7.999518 | 8.441616 | 0.947629 |
onset_label = edge.find('labels[@name="SEND"]')
onset_str = onset_label.xpath('@valueString')[0]
return int(onset_str) | def get_string_offset(edge) | return the offset (int) of a string | 9.568884 | 10.645694 | 0.89885 |
ins = SaltElement.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
ins.__class__ = SaltEdge.mro()[0] # convert SaltElement into SaltEdge
ins.layers = get_layer_ids(etree_element)
ins.source = get_node_id(etree_element, 'source')
... | def from_etree(cls, etree_element) | creates a ``SaltEdge`` instance from the etree representation of an
<edges> element from a SaltXMI file. | 5.398808 | 4.54157 | 1.188754 |
layers_attrib_val = ' '.join('//@layers.{}'.format(layer_id)
for layer_id in self.layers)
attribs = {
'{{{pre}}}type'.format(pre=NAMESPACES['xsi']): self.xsi_type,
'source': "//@nodes.{}".format(self.source),
'target': "/... | def to_etree(self) | creates an etree element of a ``SaltEdge`` that mimicks a SaltXMI
<edges> element | 4.75514 | 4.310293 | 1.103206 |
ins = SaltEdge.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert SaltEdge into TextualRelation
ins.__class__ = TextualRelation.mro()[0]
ins.onset = get_string_onset(etree_element)
ins.offset = get_string_offset(etree_el... | def from_etree(cls, etree_element) | create a ``TextualRelation`` instance from an etree element
representing an <edges> element with xsi:type
'sDocumentStructure:STextualRelation'. | 8.116209 | 6.045885 | 1.342435 |
ins = SaltEdge.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert SaltEdge into DominanceRelation
ins.__class__ = DominanceRelation.mro()[0]
ins.features = get_annotations(etree_element)
return ins | def from_etree(cls, etree_element) | create a ``DominanceRelation`` instance from an etree element
representing an <edges> element with xsi:type
'sDocumentStructure:SDominanceRelation'. | 13.265475 | 8.961476 | 1.480278 |
# there's only one, but we're in a multidigraph
source, target = docgraph.in_edges(node_id)[0]
traverse_attr = node_attr if node_attr else docgraph.lemma_attr
attrib_value = docgraph.node[source].get(traverse_attr)
if attrib_value:
yield attrib_value
if istoken(docgraph, source) i... | def traverse_dependencies_up(docgraph, node_id, node_attr=None) | starting from the given node, traverse ingoing edges up to the root element
of the sentence. return the given node attribute from all the nodes visited
along the way. | 4.691921 | 4.868207 | 0.963788 |
if markable_layer is None:
markable_layer = docgraph.ns+':markable'
conll_file = Conll2009File(docgraph,
coreference_layer=coreference_layer,
markable_layer=markable_layer)
assert isinstance(output_file, (str, file))
if isinstanc... | def write_conll(docgraph, output_file, coreference_layer=None,
markable_layer=None) | converts a DiscourseDocumentGraph into a tab-separated CoNLL 2009 file and
writes it to the given file (or file path). | 2.32678 | 2.288408 | 1.016768 |
assert self.conll_format in ('2009', '2010'), \
"We only support CoNLL2009 and CoNLL2010 format."
if self.conll_format == '2009':
word_class = Conll2009Word
else:
word_class = Conll2010Word
def parse_conll_file(conll_file, encoding=None):
... | def _parse_conll(self, conll_filepath) | parses a CoNLL2009/2010 file into a multidigraph. | 2.233898 | 2.167397 | 1.030682 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.