Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def Exponential(rate: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().ExponentialVertex, label, cast_to_double_vertex(rate)) | [
"\n One to one constructor for mapping some shape of rate to matching shaped exponential.\n \n :param rate: the rate of the Exponential with either the same shape as specified for this vertex or scalar\n "
] |
Please provide a description of the function:def Gamma(theta: vertex_constructor_param_types, k: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().GammaVertex, label, cast_to_double_vertex(theta), cast_to_double_vertex(k)) | [
"\n One to one constructor for mapping some shape of theta and k to matching shaped gamma.\n \n :param theta: the theta (scale) of the Gamma with either the same shape as specified for this vertex\n :param k: the k (shape) of the Gamma with either the same shape as specified for this vertex\n "
] |
Please provide a description of the function:def InverseGamma(alpha: vertex_constructor_param_types, beta: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().InverseGammaVertex, label, cast_to_double_vertex(alpha), cast_to_double_vertex(beta)) | [
"\n One to one constructor for mapping some shape of alpha and beta to\n alpha matching shaped Inverse Gamma.\n \n :param alpha: the alpha of the Inverse Gamma with either the same shape as specified for this vertex or alpha scalar\n :param beta: the beta of the Inverse Gamma with either the same sha... |
Please provide a description of the function:def Laplace(mu: vertex_constructor_param_types, beta: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().LaplaceVertex, label, cast_to_double_vertex(mu), cast_to_double_vertex(beta)) | [
"\n One to one constructor for mapping some shape of mu and sigma to\n a matching shaped Laplace.\n \n :param mu: the mu of the Laplace with either the same shape as specified for this vertex or a scalar\n :param beta: the beta of the Laplace with either the same shape as specified for this vertex or... |
Please provide a description of the function:def MultivariateGaussian(mu: vertex_constructor_param_types, covariance: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().MultivariateGaussianVertex, label, cast_to_double_vertex(mu), cast_to_double_vertex(covari... | [
"\n Matches a mu and covariance of some shape to a Multivariate Gaussian\n \n :param mu: the mu of the Multivariate Gaussian\n :param covariance: the covariance matrix of the Multivariate Gaussian\n "
] |
Please provide a description of the function:def Triangular(x_min: vertex_constructor_param_types, x_max: vertex_constructor_param_types, c: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().TriangularVertex, label, cast_to_double_vertex(x_min), cast_to_doub... | [
"\n One to one constructor for mapping some shape of xMin, xMax and c to a matching shaped triangular.\n \n :param x_min: the xMin of the Triangular with either the same shape as specified for this vertex or a scalar\n :param x_max: the xMax of the Triangular with either the same shape as specified for ... |
Please provide a description of the function:def Uniform(x_min: vertex_constructor_param_types, x_max: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().UniformVertex, label, cast_to_double_vertex(x_min), cast_to_double_vertex(x_max)) | [
"\n One to one constructor for mapping some shape of mu and sigma to\n a matching shaped Uniform Vertex\n \n :param x_min: the inclusive lower bound of the Uniform with either the same shape as specified for this vertex or a scalar\n :param x_max: the exclusive upper bound of the Uniform with either ... |
Please provide a description of the function:def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerAdditionVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Adds one vertex to another\n \n :param left: a vertex to add\n :param right: a vertex to add\n "
] |
Please provide a description of the function:def IntegerDifference(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerDifferenceVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Subtracts one vertex from another\n \n :param left: the vertex to be subtracted from\n :param right: the vertex to subtract\n "
] |
Please provide a description of the function:def IntegerDivision(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerDivisionVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Divides one vertex by another\n \n :param left: a vertex to be divided\n :param right: a vertex to divide by\n "
] |
Please provide a description of the function:def IntegerMax(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerMaxVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Finds the maximum between two vertices\n \n :param left: one of the vertices to find the maximum of\n :param right: one of the vertices to find the maximum of\n "
] |
Please provide a description of the function:def IntegerMin(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerMinVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Finds the minimum between two vertices\n \n :param left: one of the vertices to find the minimum of\n :param right: one of the vertices to find the minimum of\n "
] |
Please provide a description of the function:def IntegerMultiplication(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerMultiplicationVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(ri... | [
"\n Multiplies one vertex by another\n \n :param left: a vertex to be multiplied\n :param right: a vertex to be multiplied\n "
] |
Please provide a description of the function:def IntegerPower(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerPowerVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | [
"\n Raises one vertex to the power of another\n \n :param left: the base vertex\n :param right: the exponent vertex\n "
] |
Please provide a description of the function:def IntegerAbs(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerAbsVertex, label, cast_to_integer_vertex(input_vertex)) | [
"\n Takes the absolute value of a vertex\n \n :param input_vertex: the vertex\n "
] |
Please provide a description of the function:def IntegerSlice(input_vertex: vertex_constructor_param_types, dimension: int, index: int, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerSliceVertex, label, cast_to_integer_vertex(input_vertex), cast_to_integer(dimension), cast_to_in... | [
"\n Takes the slice along a given dimension and index of a vertex\n \n :param input_vertex: the input vertex\n :param dimension: the dimension to extract along\n :param index: the index of extraction\n "
] |
Please provide a description of the function:def IntegerSum(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerSumVertex, label, cast_to_integer_vertex(input_vertex)) | [
"\n Performs a sum across all dimensions\n \n :param input_vertex: the vertex to have its values summed\n "
] |
Please provide a description of the function:def IntegerTake(input_vertex: vertex_constructor_param_types, index: Collection[int], label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerTakeVertex, label, cast_to_integer_vertex(input_vertex), cast_to_long_array(index)) | [
"\n A vertex that extracts a scalar at a given index\n \n :param input_vertex: the input vertex to extract from\n :param index: the index to extract at\n "
] |
Please provide a description of the function:def Poisson(mu: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().PoissonVertex, label, cast_to_double_vertex(mu)) | [
"\n One to one constructor for mapping some shape of mu to\n a matching shaped Poisson.\n \n :param mu: mu with same shape as desired Poisson tensor or scalar\n "
] |
Please provide a description of the function:def Assert(predicate: vertex_constructor_param_types, error_message: str, label: Optional[str]=None) -> Vertex:
return Boolean(context.jvm_view().AssertVertex, label, cast_to_vertex(predicate), error_message) | [
"\n A vertex that asserts a {@link BooleanVertex} is all true on calculation.\n \n :param predicate: the predicate to evaluate\n :param error_message: a message to include in the {@link AssertionError}\n "
] |
Please provide a description of the function:def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None,
x0: int = 0) -> Any:
if labels is None:
labels = list(trace.keys())
if ax is None:
_, ax = plt.subplots(len(labels), 1, squeeze=F... | [
"\n Plot samples values.\n\n :param trace: result of MCMC run\n :param labels: labels of vertices to be plotted. if None, all vertices are plotted.\n :param ax: Matplotlib axes\n :param x0: index of first data point, used for sample stream plots\n "
] |
Please provide a description of the function:def sample(net: BayesNet,
sample_from: Iterable[Vertex],
sampling_algorithm: PosteriorSamplingAlgorithm = None,
draws: int = 500,
drop: int = 0,
down_sample_interval: int = 1,
plot: bool = False,
ax... | [
"\n :param net: Bayesian Network containing latent variables.\n :param sample_from: Vertices to include in the returned samples.\n :param sampling_algorithm: The posterior sampling algorithm to use.\n Options are :class:`keanu.algorithm.MetropolisHastingsSampler`, :class:`keanu.algorithm.NUTSSampler... |
Please provide a description of the function:def generate_samples(net: BayesNet,
sample_from: Iterable[Vertex],
sampling_algorithm: PosteriorSamplingAlgorithm = None,
drop: int = 0,
down_sample_interval: int = 1,
li... | [
"\n :param net: Bayesian Network containing latent variables.\n :param sample_from: Vertices to include in the returned samples.\n :param sampling_algorithm: The posterior sampling algorithm to use.\n Options are :class:`keanu.algorithm.MetropolisHastingsSampler` and :class:`keanu.algorithm.NUTSSamp... |
Please provide a description of the function:def accept(self, arg1: JavaObject, arg2: JavaObject) -> None:
self.lambda_function(arg1, arg2) | [
"\n >>> c = BiConsumer(lambda x,y : print(x + y))\n >>> c.accept(\"foo\", \"bar\")\n foobar\n "
] |
Please provide a description of the function:def read_file_snippets(file, snippet_store):
start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)")
end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)")
open_snippets = {}
with open(file, encoding="utf-8") as w:
lines = w.readlines(... | [
"Parse a file and add all snippets to the snippet_store dictionary"
] |
Please provide a description of the function:def strip_block_whitespace(string_list):
min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n'])
return [x[min_ws:] if x != '\n' else x for x in string_list] | [
"Treats a list of strings as a code block and strips\n whitespace so that the min whitespace line sits at char 0 of line."
] |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input_dir", help="The Input file directory", default="doc_templates/")
parser.add_argument("--output_dir", help="Where to store the processed files", default="current_docs/")
parser.a... | [
"Parse args (expects source and dest doc directories and snippet source dir)\n read all snippets and then process the input files\n writing out the new versions to the output location"
] |
Please provide a description of the function:def add_double_proxy_for(self, label: str, shape: Collection[int] = None) -> Vertex:
if shape is None:
return Vertex._from_java_vertex(self.unwrap().addDoubleProxyFor(_VertexLabel(label).unwrap()))
else:
return Vertex._from_ja... | [
"\n Creates a proxy vertex for the given label and adds to the sequence item\n "
] |
Please provide a description of the function:def add_integer_proxy_for(self, label: str, shape: Collection[int] = None) -> Vertex:
if shape is None:
return Vertex._from_java_vertex(self.unwrap().addIntegerProxyFor(_VertexLabel(label).unwrap()))
else:
return Vertex._from_... | [
"\n Creates a proxy vertex for the given label and adds to the sequence item\n "
] |
Please provide a description of the function:def add_boolean_proxy_for(self, label: str, shape: Collection[int] = None) -> Vertex:
if shape is None:
return Vertex._from_java_vertex(self.unwrap().addBooleanProxyFor(_VertexLabel(label).unwrap()))
else:
return Vertex._from_... | [
"\n Creates a proxy vertex for the given label and adds to the sequence item\n "
] |
Please provide a description of the function:def proxy_label_for(label: str) -> str:
label_java = _VertexLabel(label).unwrap()
proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java)
return proxy_label_java.getQualifiedName() | [
"\n >>> Sequence.proxy_label_for(\"foo\")\n 'proxy_for.foo'\n "
] |
Please provide a description of the function:async def prepare(self, request):
if request.method != 'GET':
raise HTTPMethodNotAllowed(request.method, ['GET'])
if not self.prepared:
writer = await super().prepare(request)
self._loop = request.app.loop
... | [
"Prepare for streaming and send HTTP headers.\n\n :param request: regular aiohttp.web.Request.\n "
] |
Please provide a description of the function:async def send(self, data, id=None, event=None, retry=None):
buffer = io.StringIO()
if id is not None:
buffer.write(self.LINE_SEP_EXPR.sub('', 'id: {}'.format(id)))
buffer.write(self._sep)
if event is not None:
... | [
"Send data using EventSource protocol\n\n :param str data: The data field for the message.\n :param str id: The event ID to set the EventSource object's last\n event ID value to.\n :param str event: The event's type. If this is specified, an event will\n be dispatched on t... |
Please provide a description of the function:async def wait(self):
if self._ping_task is None:
raise RuntimeError('Response is not started')
with contextlib.suppress(asyncio.CancelledError):
await self._ping_task | [
"EventSourceResponse object is used for streaming data to the client,\n this method returns future, so we can wain until connection will\n be closed or other task explicitly call ``stop_streaming`` method.\n "
] |
Please provide a description of the function:def ping_interval(self, value):
if not isinstance(value, int):
raise TypeError("ping interval must be int")
if value < 0:
raise ValueError("ping interval must be greater then 0")
self._ping_interval = value | [
"Setter for ping_interval property.\n\n :param int value: interval in sec between two ping values.\n "
] |
Please provide a description of the function:def get_parser(segmenter, **options):
if segmenter == 'nlapi':
return NLAPIParser(**options)
elif segmenter == 'mecab':
return MecabParser()
elif segmenter == 'tinysegmenter':
return TinysegmenterParser()
else:
raise ValueError('Segmenter {} is not... | [
"Gets a parser.\n\n Args:\n segmenter (str): Segmenter to use.\n options (:obj:`dict`, optional): Optional settings.\n\n Returns:\n Parser (:obj:`budou.parser.Parser`)\n\n Raises:\n ValueError: If unsupported segmenter is specified.\n "
] |
Please provide a description of the function:def parse_attributes(attributes=None, classname=None):
if not attributes:
attributes = {}
attributes.setdefault('class', DEFAULT_CLASS_NAME)
# If `classname` is specified, it overwrites `class` property in `attributes`.
if classname:
attributes['class'] = ... | [
"Parses attributes,\n\n Args:\n attributes (dict): Input attributes.\n classname (:obj:`str`, optional): Class name of output SPAN tags.\n\n Returns:\n Parsed attributes. (dict)\n "
] |
Please provide a description of the function:def preprocess(source):
doc = html5lib.parseFragment(source)
source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8')
source = source.replace(u'\n', u'').strip()
source = re.sub(r'\s\s+', u' ', source)
return source | [
"Removes unnecessary break lines and white spaces.\n\n Args:\n source (str): Input sentence.\n\n Returns:\n Preprocessed sentence. (str)\n "
] |
Please provide a description of the function:def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by NLAPI segmenter'.format(language))
chunks = ChunkList()
results = tinysegmenter.tokenize(s... | [
"Returns a chunk list from the given sentence.\n\n Args:\n source (str): Source string to segment.\n language (:obj:`str`, optional): A language code.\n\n Returns:\n A chunk list. (:obj:`budou.chunk.ChunkList`)\n\n Raises:\n ValueError: If :obj:`language` is given and it is not included... |
Please provide a description of the function:def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by MeCab segmenter'.format(language))
chunks = ChunkList()
seek = 0
source_str = source.e... | [
"Returns a chunk list from the given sentence.\n\n Args:\n source (str): Source string to segment.\n language (:obj:`str`, optional): A language code.\n\n Returns:\n A chunk list. (:obj:`budou.chunk.ChunkList`)\n\n Raises:\n ValueError: If :obj:`language` is given and it is not included... |
Please provide a description of the function:def main():
args = docopt(__doc__)
if args['--version']:
print(__version__)
sys.exit()
result = parse(
args['<source>'],
segmenter=args['--segmenter'],
language=args['--language'],
classname=args['--classname'])
print(result['html_... | [
"Budou main method for the command line tool.\n "
] |
Please provide a description of the function:def parse(source, segmenter='nlapi', language=None, max_length=None,
classname=None, attributes=None, **kwargs):
parser = get_parser(segmenter, **kwargs)
return parser.parse(
source, language=language, max_length=max_length, classname=classname,
... | [
"Parses input source.\n\n Args:\n source (str): Input source to process.\n segmenter (:obj:`str`, optional): Segmenter to use [default: nlapi].\n language (:obj:`str`, optional): Language code.\n max_length (:obj:`int`, optional): Maximum length of a chunk.\n classname (:obj:`str`, optional): Class ... |
Please provide a description of the function:def authenticate(json_path=None):
msg = ('budou.authentication() is deprecated. '
'Please use budou.get_parser() to obtain a parser instead.')
warnings.warn(msg, DeprecationWarning)
parser = get_parser('nlapi', credentials_path=json_path)
return parser | [
"Gets a Natural Language API parser by authenticating the API.\n\n **This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a\n parser instead.\n\n Args:\n json_path (:obj:`str`, optional): The file path to the service account's\n credentials.\n\n Returns:\n Parser. (:obj:`budou.... |
Please provide a description of the function:def _memorize(func):
def _wrapper(self, *args, **kwargs):
if self.use_cache:
cache = load_cache(self.cache_filename)
original_key = ':'.join([
self.__class__.__name__,
func.__name__,
'_'.join([str(a) for a in args]),
... | [
"Decorator to cache the given function's output.\n ",
"Wrapper to cache the function's output.\n "
] |
Please provide a description of the function:def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by NLAPI segmenter'.format(language))
chunks, language = self._get_source_chunks(source, language... | [
"Returns a chunk list from the given sentence.\n\n Args:\n source (str): Source string to segment.\n language (:obj:`str`, optional): A language code.\n\n Returns:\n A chunk list. (:obj:`budou.chunk.ChunkList`)\n\n Raises:\n ValueError: If :obj:`language` is given and it is not included... |
Please provide a description of the function:def _get_source_chunks(self, input_text, language=None):
chunks = ChunkList()
seek = 0
result = self._get_annotations(input_text, language=language)
tokens = result['tokens']
language = result['language']
for i, token in enumerate(tokens):
... | [
"Returns a chunk list retrieved from Syntax Analysis results.\n\n Args:\n input_text (str): Text to annotate.\n language (:obj:`str`, optional): Language of the text.\n\n Returns:\n A chunk list. (:obj:`budou.chunk.ChunkList`)\n "
] |
Please provide a description of the function:def _group_chunks_by_entities(self, chunks, entities):
for entity in entities:
chunks_to_concat = chunks.get_overlaps(
entity['beginOffset'], len(entity['content']))
if not chunks_to_concat:
continue
new_chunk_word = u''.join([chu... | [
"Groups chunks by entities retrieved from NL API Entity Analysis.\n\n Args:\n chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.\n entities (:obj:`list` of :obj:`dict`): List of entities.\n\n Returns:\n A chunk list. (:obj:`budou.chunk.ChunkList`)\n "
] |
Please provide a description of the function:def _get_annotations(self, text, language=''):
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'features': {
'extract_syntax': True,
},
'encodingType': 'UTF32',
}
if... | [
"Returns the list of annotations retrieved from the given text.\n\n Args:\n text (str): Input text.\n language (:obj:`str`, optional): Language code.\n\n Returns:\n Results in a dictionary. :code:`tokens` contains the list of annotations\n and :code:`language` contains the inferred languag... |
Please provide a description of the function:def _get_entities(self, text, language=''):
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'encodingType': 'UTF32',
}
if language:
body['document']['language'] = language
request = ... | [
"Returns the list of entities retrieved from the given text.\n\n Args:\n text (str): Input text.\n language (:obj:`str`, optional): Language code.\n\n Returns:\n List of entities.\n "
] |
Please provide a description of the function:def get(self, key):
self._create_file_if_none_exists()
with open(self.filename, 'rb') as file_object:
cache_pickle = pickle.load(file_object)
val = cache_pickle.get(key, None)
return val | [
"Gets a value by a key.\n\n Args:\n key (str): Key to retrieve the value.\n\n Returns: Retrieved value.\n "
] |
Please provide a description of the function:def set(self, key, val):
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache_pickle[key] = val
file_object.seek(0)
pickle.dump(cache_pickle, file_object) | [
"Sets a value in a key.\n\n Args:\n key (str): Key for the value.\n val: Value to set.\n\n Returns:\n Retrieved value.\n "
] |
Please provide a description of the function:def serialize(self):
return {
'word': self.word,
'pos': self.pos,
'label': self.label,
'dependency': self.dependency,
'has_cjk': self.has_cjk(),
} | [
"Returns serialized chunk data in dictionary."
] |
Please provide a description of the function:def has_cjk(self):
cjk_codepoint_ranges = [
(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215),
(63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)]
for char in self.word:
if any([start <= ord(char) <= end
... | [
"Checks if the word of the chunk contains CJK characters.\n\n This is using unicode codepoint ranges from\n https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149\n\n Returns:\n bool: True if the chunk has any CJK character.\n "
] |
Please provide a description of the function:def get_overlaps(self, offset, length):
# In case entity's offset points to a space just before the entity.
if ''.join([chunk.word for chunk in self])[offset] == ' ':
offset += 1
index = 0
result = ChunkList()
for chunk in self:
if offset... | [
"Returns chunks overlapped with the given range.\n\n Args:\n offset (int): Begin offset of the range.\n length (int): Length of the range.\n\n Returns:\n Overlapped chunks. (:obj:`budou.chunk.ChunkList`)\n "
] |
Please provide a description of the function:def swap(self, old_chunks, new_chunk):
indexes = [self.index(chunk) for chunk in old_chunks]
del self[indexes[0]:indexes[-1] + 1]
self.insert(indexes[0], new_chunk) | [
"Swaps old consecutive chunks with new chunk.\n\n Args:\n old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to\n be removed.\n new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted.\n "
] |
Please provide a description of the function:def resolve_dependencies(self):
self._concatenate_inner(True)
self._concatenate_inner(False)
self._insert_breaklines() | [
"Resolves chunk dependency by concatenating them.\n "
] |
Please provide a description of the function:def _concatenate_inner(self, direction):
tmp_bucket = []
source_chunks = self if direction else self[::-1]
target_chunks = ChunkList()
for chunk in source_chunks:
if (
# if the chunk has matched dependency, do concatenation.
chu... | [
"Concatenates chunks based on each chunk's dependency.\n\n Args:\n direction (bool): Direction of concatenation process. True for forward.\n "
] |
Please provide a description of the function:def _insert_breaklines(self):
target_chunks = ChunkList()
for chunk in self:
if chunk.word[-1] == ' ' and chunk.has_cjk():
chunk.word = chunk.word[:-1]
target_chunks.append(chunk)
target_chunks.append(chunk.breakline())
else:
... | [
"Inserts a breakline instead of a trailing space if the chunk is in CJK.\n "
] |
Please provide a description of the function:def html_serialize(self, attributes, max_length=None):
doc = ET.Element('span')
for chunk in self:
if (chunk.has_cjk() and
not (max_length and len(chunk.word) > max_length)):
ele = ET.Element('span')
ele.text = chunk.word
... | [
"Returns concatenated HTML code with SPAN tag.\n\n Args:\n attributes (dict): A map of name-value pairs for attributes of output\n SPAN tags.\n max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.\n\n Returns:\n The organized HTML code. (str)\n "
] |
Please provide a description of the function:def poll(target, step, args=(), kwargs=None, timeout=None, max_tries=None, check_success=is_truthy,
step_function=step_constant, ignore_exceptions=(), poll_forever=False, collect_values=None, *a, **k):
assert (timeout is not None or max_tries is not None) ... | [
"Poll by calling a target function until a certain condition is met. You must specify at least a target\n function to be called and the step -- base wait time between each function call.\n\n :param step: Step defines the amount of time to wait (in seconds)\n :param args: Arguments to be passed to the targe... |
Please provide a description of the function:def _etextno_to_uri_subdirectory(etextno):
str_etextno = str(etextno).zfill(2)
all_but_last_digit = list(str_etextno[:-1])
subdir_part = "/".join(all_but_last_digit)
subdir = "{}/{}".format(subdir_part, etextno) # etextno not zfilled
return subdir | [
"Returns the subdirectory that an etextno will be found in a gutenberg\n mirror. Generally, one finds the subdirectory by separating out each digit\n of the etext number, and uses it for a directory. The exception here is for\n etext numbers less than 10, which are prepended with a 0 for the directory\n ... |
Please provide a description of the function:def _format_download_uri_for_extension(etextno, extension, mirror=None):
mirror = mirror or _GUTENBERG_MIRROR
root = mirror.strip().rstrip('/')
path = _etextno_to_uri_subdirectory(etextno)
uri = '{root}/{path}/{etextno}{extension}'.format(
root=... | [
"Returns the download location on the Project Gutenberg servers for a\n given text and extension. The list of available extensions for a given\n text can be found via the formaturi metadata extractor.\n\n "
] |
Please provide a description of the function:def _format_download_uri(etextno, mirror=None, prefer_ascii=False):
mirror = mirror or _GUTENBERG_MIRROR
if not _does_mirror_exist(mirror):
raise UnknownDownloadUriException(
'Could not reach Gutenberg mirror "{:s}". Try setting a '
... | [
"Returns the download location on the Project Gutenberg servers for a\n given text.\n\n Use prefer_ascii to control whether you want to fetch plaintext us-ascii\n file first (default old behavior) or if you prefer UTF-8 then 8-bits then\n plaintext.\n\n Raises:\n UnknownDownloadUri: If no down... |
Please provide a description of the function:def load_etext(etextno, refresh_cache=False, mirror=None, prefer_ascii=False):
etextno = validate_etextno(etextno)
cached = os.path.join(_TEXT_CACHE, '{}.txt.gz'.format(etextno))
if refresh_cache:
remove(cached)
if not os.path.exists(cached):
... | [
"Returns a unicode representation of the full body of a Project Gutenberg\n text. After making an initial remote call to Project Gutenberg's servers,\n the text is persisted locally.\n\n "
] |
Please provide a description of the function:def _main():
from argparse import ArgumentParser, FileType
from gutenberg import Error
from gutenberg._util.os import reopen_encoded
parser = ArgumentParser(description='Download a Project Gutenberg text')
parser.add_argument('etextno', type=int)
... | [
"Command line interface to the module.\n\n "
] |
Please provide a description of the function:def rdf_bind_to_string(rdf_type):
string_type = unicode if sys.version_info < (3,) else str # noqa
bind(rdf_type, string_type) | [
"Python2/3 compatibility wrapper around rdflib.term.bind that binds a\n term to the appropriate string type.\n\n "
] |
Please provide a description of the function:def disable_logging(logger=None):
logger = logger or logging.getLogger()
disabled = logger.disabled
logger.disabled = True
yield
logger.disabled = disabled | [
"Context manager to temporarily suppress all logging for a given logger\n or the root logger if no particular logger is specified.\n\n "
] |
Please provide a description of the function:def makedirs(*args, **kwargs):
try:
os.makedirs(*args, **kwargs)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise | [
"Wrapper around os.makedirs that doesn't raise an exception if the\n directory already exists.\n\n "
] |
Please provide a description of the function:def remove(path):
if not os.path.exists(path):
return
if os.path.isdir(path):
return shutil.rmtree(path)
if os.path.isfile(path):
return os.remove(path) | [
"Wrapper that switches between os.remove and shutil.rmtree depending on\n whether the provided path is a file or directory.\n\n "
] |
Please provide a description of the function:def determine_encoding(path, default=None):
byte_order_marks = (
('utf-8-sig', (codecs.BOM_UTF8, )),
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),
)
try:
with ... | [
"Determines the encoding of a file based on byte order marks.\n\n Arguments:\n path (str): The path to the file.\n default (str, optional): The encoding to return if the byte-order-mark\n lookup does not return an answer.\n\n Returns:\n str: The encoding of the file.\n\n "
] |
Please provide a description of the function:def reopen_encoded(fileobj, mode='r', fallback_encoding=None):
encoding = determine_encoding(fileobj.name, fallback_encoding)
fileobj.close()
return open(fileobj.name, mode, encoding=encoding) | [
"Makes sure that a file was opened with some valid encoding.\n\n Arguments:\n fileobj (file): The file-object.\n mode (str, optional): The mode in which to re-open the file.\n fallback_encoding (str, optional): The encoding in which to re-open\n the file if it does not specify an ... |
Please provide a description of the function:def strip_headers(text):
lines = text.splitlines()
sep = str(os.linesep)
out = []
i = 0
footer_found = False
ignore_section = False
for line in lines:
reset = False
if i <= 600:
# Check if the header ends here
... | [
"Remove lines that are part of the Project Gutenberg header or footer.\n Note: this function is a port of the C++ utility by Johannes Krugel. The\n original version of the code can be found at:\n http://www14.in.tum.de/spp1307/src/strip_headers.cpp\n\n Args:\n text (unicode): The body of the text... |
Please provide a description of the function:def _main():
from argparse import ArgumentParser, FileType
from gutenberg import Error
from gutenberg._util.os import reopen_encoded
parser = ArgumentParser(description='Remove headers and footers from a '
'Projec... | [
"Command line interface to the module.\n\n "
] |
Please provide a description of the function:def get_metadata(feature_name, etextno):
metadata_values = MetadataExtractor.get(feature_name).get_metadata(etextno)
return frozenset(metadata_values) | [
"Looks up the value of a meta-data feature for a given text.\n\n Arguments:\n feature_name (str): The name of the meta-data to look up.\n etextno (int): The identifier of the Gutenberg text for which to look\n up the meta-data.\n\n Returns:\n frozenset: The values of the meta-d... |
Please provide a description of the function:def get_etexts(feature_name, value):
matching_etexts = MetadataExtractor.get(feature_name).get_etexts(value)
return frozenset(matching_etexts) | [
"Looks up all the texts that have meta-data matching some criterion.\n\n Arguments:\n feature_name (str): The meta-data on which to select the texts.\n value (str): The value of the meta-data on which to filter the texts.\n\n Returns:\n frozenset: The set of all the Project Gutenberg text... |
Please provide a description of the function:def _uri_to_etext(cls, uri_ref):
try:
return validate_etextno(int(os.path.basename(uri_ref.toPython())))
except InvalidEtextIdException:
return None | [
"Converts the representation used to identify a text in the\n meta-data RDF graph to a human-friendly integer text identifier.\n\n "
] |
Please provide a description of the function:def _implementations(cls):
if cls.__implementations:
return cls.__implementations
cls.__implementations = {}
for implementation in all_subclasses(MetadataExtractor):
try:
feature_name = implementation.... | [
"Returns all the concrete subclasses of MetadataExtractor.\n\n "
] |
Please provide a description of the function:def get(feature_name):
implementations = MetadataExtractor._implementations()
try:
return implementations[feature_name]
except KeyError:
raise UnsupportedFeatureException(
'no MetadataExtractor register... | [
"Returns the MetadataExtractor that can extract information about the\n provided feature name.\n\n Raises:\n UnsupportedFeature: If no extractor exists for the feature name.\n\n "
] |
Please provide a description of the function:def set_metadata_cache(cache):
global _METADATA_CACHE
if _METADATA_CACHE and _METADATA_CACHE.is_open:
_METADATA_CACHE.close()
_METADATA_CACHE = cache | [
"Sets the metadata cache object to use.\n\n "
] |
Please provide a description of the function:def _create_metadata_cache(cache_location):
cache_url = os.getenv('GUTENBERG_FUSEKI_URL')
if cache_url:
return FusekiMetadataCache(cache_location, cache_url)
try:
return SleepycatMetadataCache(cache_location)
except InvalidCacheException... | [
"Creates a new metadata cache instance appropriate for this platform.\n\n "
] |
Please provide a description of the function:def load_metadata(refresh_cache=False):
cache = get_metadata_cache()
if refresh_cache:
cache.refresh()
if not cache.is_open:
cache.open()
return cache.graph | [
"Returns a graph representing meta-data for all Project Gutenberg texts.\n Pertinent information about texts or about how texts relate to each other\n (e.g. shared authors, shared subjects) can be extracted using standard RDF\n processing techniques (e.g. SPARQL queries). After making an initial remote\n ... |
Please provide a description of the function:def open(self):
try:
self.graph.open(self.cache_uri, create=False)
self._add_namespaces(self.graph)
self.is_open = True
except Exception:
raise InvalidCacheException('The cache is invalid or not created... | [
"Opens an existing cache.\n\n "
] |
Please provide a description of the function:def populate(self):
if self.exists:
raise CacheAlreadyExistsException('location: %s' % self.cache_uri)
self._populate_setup()
with closing(self.graph):
with self._download_metadata_archive() as metadata_archive:
... | [
"Populates a new cache.\n\n "
] |
Please provide a description of the function:def refresh(self):
if self.exists:
self.delete()
self.populate()
self.open() | [
"Refresh the cache by deleting the old one and creating a new one.\n\n "
] |
Please provide a description of the function:def _download_metadata_archive(self):
with tempfile.NamedTemporaryFile(delete=False) as metadata_archive:
shutil.copyfileobj(urlopen(self.catalog_source), metadata_archive)
yield metadata_archive.name
remove(metadata_archive.name) | [
"Makes a remote call to the Project Gutenberg servers and downloads\n the entire Project Gutenberg meta-data catalog. The catalog describes\n the texts on Project Gutenberg in RDF. The function returns a\n file-pointer to the catalog.\n\n "
] |
Please provide a description of the function:def _metadata_is_invalid(cls, fact):
return any(isinstance(token, URIRef) and ' ' in token
for token in fact) | [
"Determines if the fact is not well formed.\n\n "
] |
Please provide a description of the function:def _iter_metadata_triples(cls, metadata_archive_path):
pg_rdf_regex = re.compile(r'pg\d+.rdf$')
with closing(tarfile.open(metadata_archive_path)) as metadata_archive:
for item in metadata_archive:
if pg_rdf_regex.search(i... | [
"Yields all meta-data of Project Gutenberg texts contained in the\n catalog dump.\n\n "
] |
Please provide a description of the function:def _populate_setup(self):
makedirs(os.path.dirname(self._cache_marker))
with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj:
fobj.write(self.cache_uri)
self.graph.open(self.cache_uri) | [
"Just create a local marker file since the actual database should\n already be created on the Fuseki server.\n\n "
] |
Please provide a description of the function:def delete(self):
MetadataCache.delete(self)
try:
self.graph.query('DELETE WHERE { ?s ?p ?o . }')
except ResultException:
# this is often just a false positive since Jena Fuseki does not
# return tuples for... | [
"Deletes the local marker file and also any data in the Fuseki\n server.\n\n "
] |
Please provide a description of the function:def _check_can_be_instantiated(cls, cache_location):
if not any(cache_location.startswith(prefix)
for prefix in cls._CACHE_URL_PREFIXES):
raise InvalidCacheException('cache location is not a Fuseki url')
try:
... | [
"Pre-conditions: the cache location is the URL to a Fuseki server\n and the SPARQLWrapper library exists (transitive dependency of\n RDFlib's sparqlstore).\n\n "
] |
Please provide a description of the function:def _metadata_is_invalid(cls, fact):
return (MetadataCache._metadata_is_invalid(fact)
or any(isinstance(token, BNode) for token in fact)) | [
"Filters out blank nodes since the SPARQLUpdateStore does not\n support them.\n\n "
] |
Please provide a description of the function:def all_subclasses(cls):
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | [
"Recursively returns all the subclasses of the provided class.\n\n "
] |
Please provide a description of the function:def main():
scheme_names = sorted(six.iterkeys(SCHEME))
version_str = pkg_resources.get_distribution('ansi2html').version
parser = optparse.OptionParser(
usage=main.__doc__,
version="%%prog %s" % version_str)
parser.add_option(
"... | [
"\n $ ls --color=always | ansi2html > directories.html\n $ sudo tail /var/log/messages | ccze -A | ansi2html > logs.html\n $ task burndown | ansi2html > burndown.html\n "
] |
Please provide a description of the function:def _collapse_cursor(self, parts):
final_parts = []
for part in parts:
# Throw out empty string tokens ("")
if not part:
continue
# Go back, deleting every token in the last 'line'
if... | [
" Act on any CursorMoveUp commands by deleting preceding tokens "
] |
Please provide a description of the function:def prepare(self, ansi='', ensure_trailing_newline=False):
body, styles = self.apply_regex(ansi)
if ensure_trailing_newline and _needs_extra_newline(body):
body += '\n'
self._attrs = {
'dark_bg': self.dark_bg,
... | [
" Load the contents of 'ansi' into this object "
] |
Please provide a description of the function:def run(self):
if self.has_rust_extensions():
log.info("running build_rust")
build_rust = self.get_finalized_command("build_rust")
build_rust.inplace = self.inplace
build_rust.run()
_build_ext.run(self... | [
"Run build_rust sub command "
] |
Please provide a description of the function:def get_lib_name(self):
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
name = cfg.get("p... | [
" Parse Cargo.toml to get the name of the shared library. "
] |
Please provide a description of the function:def find_rust_extensions(*directories, **kwargs):
# Get the file used to mark a Rust extension
libfile = kwargs.get("libfile", "lib.rs")
# Get the directories to explore
directories = directories or [os.getcwd()]
extensions = []
for directory ... | [
"Attempt to find Rust extensions in given directories.\n\n This function will recurse through the directories in the given\n directories, to find a name whose name is ``libfile``. When such\n a file is found, an extension is created, expecting the cargo\n manifest file (``Cargo.toml``) to be next to tha... |
Please provide a description of the function:def register(self, event, fn):
# TODO: Can we check the method signature?
self._handler_dict.setdefault(event, [])
if fn not in self._handler_dict[event]:
self._handler_dict[event].append(fn) | [
"\n Registers the given function as a handler to be applied\n in response to the the given event.\n "
] |
Please provide a description of the function:def apply(self, event, document, *args, **kwargs):
for fn in self._handler_dict.get(event, []):
fn(document, *args, **kwargs) | [
"\n Applies all middleware functions registered against the given\n event in order to the given document.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.