_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q240600 | GrowlerHTTPProtocol.begin_application | train | def begin_application(self, req, res):
"""
Entry point for the application middleware chain for an asyncio
event loop.
"""
# Add the middleware processing to the event loop - this *should*
# change the call stack so any server errors do not link back to this
# fun... | python | {
"resource": ""
} |
q240601 | Static.calculate_etag | train | def calculate_etag(file_path):
"""
Calculate an etag value
Args:
a_file (pathlib.Path): The filepath to the
Returns:
String of the etag value to be sent back in header
"""
stat = file_path.stat()
etag = "%x-%x" % (stat.st_mtime_ns, stat.s... | python | {
"resource": ""
} |
q240602 | HTTPResponse._set_default_headers | train | def _set_default_headers(self):
"""
Create some default headers that should be sent along with every HTTP
response
"""
self.headers.setdefault('Date', self.get_current_time)
self.headers.setdefault('Server', self.SERVER_INFO)
self.headers.setdefault('Content-Lengt... | python | {
"resource": ""
} |
q240603 | HTTPResponse.send_headers | train | def send_headers(self):
"""
Sends the headers to the client
"""
self.events.sync_emit('headers')
self._set_default_headers()
header_str = self.status_line + self.EOL + str(self.headers)
self.stream.write(header_str.encode())
self.events.sync_emit('after_he... | python | {
"resource": ""
} |
q240604 | HTTPResponse.end | train | def end(self):
"""
Ends the response. Useful for quickly ending connection with no data
sent
"""
self.send_headers()
self.write()
self.write_eof()
self.has_ended = True | python | {
"resource": ""
} |
q240605 | HTTPResponse.redirect | train | def redirect(self, url, status=None):
"""
Redirect to the specified url, optional status code defaults to 302.
"""
self.status_code = 302 if status is None else status
self.headers = Headers([('location', url)])
self.message = ''
self.end() | python | {
"resource": ""
} |
q240606 | HTTPResponse.set | train | def set(self, header, value=None):
"""Set header to the value"""
if value is None:
for k, v in header.items():
self.headers[k] = v
else:
self.headers[header] = value | python | {
"resource": ""
} |
q240607 | HTTPResponse.links | train | def links(self, links):
"""Sets the Link """
s = ['<{}>; rel="{}"'.format(link, rel)
for link, rel in links.items()]
self.headers['Link'] = ','.join(s) | python | {
"resource": ""
} |
q240608 | HTTPResponse.send_file | train | def send_file(self, filename, status=200):
"""
Reads in the file 'filename' and sends bytes to client
Parameters
----------
filename : str
Filename of the file to read
status : int, optional
The HTTP status code, defaults to 200 (OK)
"""
... | python | {
"resource": ""
} |
q240609 | Headers.update | train | def update(self, *args, **kwargs):
"""
Equivalent to the python dict update method.
Update the dictionary with the key/value pairs from other, overwriting
existing keys.
Args:
other (dict): The source of key value pairs to add to headers
Keyword Args:
... | python | {
"resource": ""
} |
q240610 | Headers.add_header | train | def add_header(self, key, value, **params):
"""
Add a header to the collection, including potential parameters.
Args:
key (str): The name of the header
value (str): The value to store under that key
params: Option parameters to be appended to the value,
... | python | {
"resource": ""
} |
q240611 | index | train | def index(req, res):
"""
Return root page of website.
"""
number = req.session.get('counter', -1)
req.session['counter'] = int(number) + 1
print(" -- Session '{id}' returned {counter} times".format(**req.session))
msg = "Hello!! You've been here [[%s]] times" % (req.session['counter'])
r... | python | {
"resource": ""
} |
q240612 | HTTPRequest.body | train | async def body(self):
"""
A helper function which blocks until the body has been read
completely.
Returns the bytes of the body which the user should decode.
If the request does not have a body part (i.e. it is a GET
request) this function returns None.
"""
... | python | {
"resource": ""
} |
q240613 | event_emitter | train | def event_emitter(cls_=None, *, events=('*', )):
"""
A class-decorator which will add the specified events and the methods 'on'
and 'emit' to the class.
"""
# create a dictionary from items in the 'events' parameter and with empty
# lists as values
event_dict = dict.fromkeys(events, [])
... | python | {
"resource": ""
} |
q240614 | Events.on | train | def on(self, name, _callback=None):
"""
Add a callback to the event named 'name'.
Returns callback object for decorationable calls.
"""
# this is being used as a decorator
if _callback is None:
return lambda cb: self.on(name, cb)
if not (callable(_ca... | python | {
"resource": ""
} |
q240615 | Events.emit | train | async def emit(self, name):
"""
Add a callback to the event named 'name'.
Returns this object for chained 'on' calls.
"""
for cb in self._event_list[name]:
if isawaitable(cb):
await cb
else:
cb() | python | {
"resource": ""
} |
q240616 | routerify | train | def routerify(obj):
"""
Scan through attributes of object parameter looking for any which
match a route signature.
A router will be created and added to the object with parameter.
Args:
obj (object): The object (with attributes) from which to
setup a router
Returns:
... | python | {
"resource": ""
} |
q240617 | Router._add_route | train | def _add_route(self, method, path, middleware=None):
"""The implementation of adding a route"""
if middleware is not None:
self.add(method, path, middleware)
return self
else:
# return a lambda that will return the 'func' argument
return lambda fun... | python | {
"resource": ""
} |
q240618 | Router.use | train | def use(self, middleware, path=None):
"""
Call the provided middleware upon requests matching the path.
If path is not provided or None, all requests will match.
Args:
middleware (callable): Callable with the signature
``(res, req) -> None``
path ... | python | {
"resource": ""
} |
q240619 | Router.sinatra_path_to_regex | train | def sinatra_path_to_regex(cls, path):
"""
Converts a sinatra-style path to a regex with named
parameters.
"""
# Return the path if already a (compiled) regex
if type(path) is cls.regex_type:
return path
# Build a regular expression string which is spl... | python | {
"resource": ""
} |
q240620 | Parser._parse_and_store_headers | train | def _parse_and_store_headers(self):
"""
Coroutine used retrieve header data and parse each header until
the body is found.
"""
header_storage = self._store_header()
header_storage.send(None)
for header_line in self._next_header_line():
if header_line... | python | {
"resource": ""
} |
q240621 | Parser._store_header | train | def _store_header(self):
"""
Logic & state behind storing headers. This is a coroutine that
should be sent header lines in the usual fashion. Sending it
None will indicate there are no more lines, and the dictionary
of headers will be returned.
"""
key, value = No... | python | {
"resource": ""
} |
q240622 | Parser._store_request_line | train | def _store_request_line(self, req_line):
"""
Splits the request line given into three components.
Ensures that the version and method are valid for this server,
and uses the urllib.parse function to parse the request URI.
Note:
This method has the additional side eff... | python | {
"resource": ""
} |
q240623 | Parser.determine_newline | train | def determine_newline(data):
"""
Looks for a newline character in bytestring parameter 'data'.
Currently only looks for strings '\r\n', '\n'. If '\n' is
found at the first position of the string, this raises an
exception.
Parameters:
data (bytes): The data to... | python | {
"resource": ""
} |
q240624 | MiddlewareNode.path_split | train | def path_split(self, path):
"""
Splits a path into the part matching this middleware and the part remaining.
If path does not exist, it returns a pair of None values.
If the regex matches the entire pair, the second item in returned tuple is None.
Args:
path (str): T... | python | {
"resource": ""
} |
q240625 | MiddlewareChain.find_matching_middleware | train | def find_matching_middleware(self, method, path):
"""
Iterator handling the matching of middleware against a method+path
pair. Yields the middleware, and the
"""
for mw in self.mw_list:
if not mw.matches_method(method):
continue
# get the ... | python | {
"resource": ""
} |
q240626 | MiddlewareChain.add | train | def add(self, method_mask, path, func):
"""
Add a function to the middleware chain.
This function is returned when iterating over the chain with matching method and path.
Args:
method_mask (growler.http.HTTPMethod): A bitwise mask intended to match specific
r... | python | {
"resource": ""
} |
q240627 | MiddlewareChain.count_all | train | def count_all(self):
"""
Returns the total number of middleware in this chain and subchains.
"""
return sum(x.func.count_all() if x.is_subchain else 1 for x in self) | python | {
"resource": ""
} |
q240628 | if_relationship | train | def if_relationship(parser, token):
"""
Determine if a certain type of relationship exists between two users.
The ``status`` parameter must be a slug matching either the from_slug,
to_slug or symmetrical_slug of a RelationshipStatus.
Example::
{% if_relationship from_user to_user "friends"... | python | {
"resource": ""
} |
q240629 | add_relationship_url | train | def add_relationship_url(user, status):
"""
Generate a url for adding a relationship on a given user. ``user`` is a
User object, and ``status`` is either a relationship_status object or a
string denoting a RelationshipStatus
Usage::
href="{{ user|add_relationship_url:"following" }}"
"... | python | {
"resource": ""
} |
q240630 | PostProcessor._rename_glyphs_from_ufo | train | def _rename_glyphs_from_ufo(self):
"""Rename glyphs using ufo.lib.public.postscriptNames in UFO."""
rename_map = self._build_production_names()
otf = self.otf
otf.setGlyphOrder([rename_map.get(n, n) for n in otf.getGlyphOrder()])
# we need to compile format 2 'post' table so th... | python | {
"resource": ""
} |
q240631 | PostProcessor._unique_name | train | def _unique_name(name, seen):
"""Append incremental '.N' suffix if glyph is a duplicate."""
if name in seen:
n = seen[name]
while (name + ".%d" % n) in seen:
n += 1
seen[name] = n + 1
name += ".%d" % n
seen[name] = 1
return ... | python | {
"resource": ""
} |
q240632 | PostProcessor._build_production_name | train | def _build_production_name(self, glyph):
"""Build a production name for a single glyph."""
# use PostScript names from UFO lib if available
if self._postscriptNames:
production_name = self._postscriptNames.get(glyph.name)
return production_name if production_name else gl... | python | {
"resource": ""
} |
q240633 | makeFeaClassName | train | def makeFeaClassName(name, existingClassNames=None):
"""Make a glyph class name which is legal to use in feature text.
Ensures the name only includes characters in "A-Za-z0-9._", and
isn't already defined.
"""
name = re.sub(r"[^A-Za-z0-9._]", r"", name)
if existingClassNames is None:
re... | python | {
"resource": ""
} |
q240634 | addLookupReference | train | def addLookupReference(
feature, lookup, script=None, languages=None, exclude_dflt=False
):
"""Shortcut for addLookupReferences, but for a single lookup.
"""
return addLookupReferences(
feature,
(lookup,),
script=script,
languages=languages,
exclude_dflt=exclude_d... | python | {
"resource": ""
} |
q240635 | openTypeHeadCreatedFallback | train | def openTypeHeadCreatedFallback(info):
"""
Fallback to the environment variable SOURCE_DATE_EPOCH if set, otherwise
now.
"""
if "SOURCE_DATE_EPOCH" in os.environ:
t = datetime.utcfromtimestamp(int(os.environ["SOURCE_DATE_EPOCH"]))
return t.strftime(_date_format)
else:
ret... | python | {
"resource": ""
} |
q240636 | preflightInfo | train | def preflightInfo(info):
"""
Returns a dict containing two items. The value for each
item will be a list of info attribute names.
================== ===
missingRequired Required data that is missing.
missingRecommended Recommended data that is missing.
================== ===
"""
... | python | {
"resource": ""
} |
q240637 | RelationshipManager.add | train | def add(self, user, status=None, symmetrical=False):
"""
Add a relationship from one user to another with the given status,
which defaults to "following".
Adding a relationship is by default asymmetrical (akin to following
someone on twitter). Specify a symmetrical relationship... | python | {
"resource": ""
} |
q240638 | RelationshipManager.remove | train | def remove(self, user, status=None, symmetrical=False):
"""
Remove a relationship from one user to another, with the same caveats
and behavior as adding a relationship.
"""
if not status:
status = RelationshipStatus.objects.following()
res = Relationship.obje... | python | {
"resource": ""
} |
q240639 | RelationshipManager.get_relationships | train | def get_relationships(self, status, symmetrical=False):
"""
Returns a QuerySet of user objects with which the given user has
established a relationship.
"""
query = self._get_from_query(status)
if symmetrical:
query.update(self._get_to_query(status))
... | python | {
"resource": ""
} |
q240640 | RelationshipManager.only_to | train | def only_to(self, status):
"""
Returns a QuerySet of user objects who have created a relationship to
the given user, but which the given user has not reciprocated
"""
from_relationships = self.get_relationships(status)
to_relationships = self.get_related_to(status)
... | python | {
"resource": ""
} |
q240641 | makeOfficialGlyphOrder | train | def makeOfficialGlyphOrder(font, glyphOrder=None):
""" Make the final glyph order for 'font'.
If glyphOrder is None, try getting the font.glyphOrder list.
If not explicit glyphOrder is defined, sort glyphs alphabetically.
If ".notdef" glyph is present in the font, force this to always be
the first... | python | {
"resource": ""
} |
q240642 | _GlyphSet.from_layer | train | def from_layer(cls, font, layerName=None, copy=False, skipExportGlyphs=None):
"""Return a mapping of glyph names to glyph objects from `font`."""
if layerName is not None:
layer = font.layers[layerName]
else:
layer = font.layers.defaultLayer
if copy:
... | python | {
"resource": ""
} |
q240643 | parseLayoutFeatures | train | def parseLayoutFeatures(font):
""" Parse OpenType layout features in the UFO and return a
feaLib.ast.FeatureFile instance.
"""
featxt = tounicode(font.features.text or "", "utf-8")
if not featxt:
return ast.FeatureFile()
buf = UnicodeIO(featxt)
# the path is used by the lexer to reso... | python | {
"resource": ""
} |
q240644 | FeatureCompiler.setupFeatures | train | def setupFeatures(self):
"""
Make the features source.
**This should not be called externally.** Subclasses
may override this method to handle the file creation
in a different way if desired.
"""
if self.featureWriters:
featureFile = parseLayoutFeatur... | python | {
"resource": ""
} |
q240645 | FeatureCompiler.buildTables | train | def buildTables(self):
"""
Compile OpenType feature tables from the source.
Raises a FeaLibError if the feature compilation was unsuccessful.
**This should not be called externally.** Subclasses
may override this method to handle the table compilation
in a different way ... | python | {
"resource": ""
} |
q240646 | maxCtxFont | train | def maxCtxFont(font):
"""Calculate the usMaxContext value for an entire font."""
maxCtx = 0
for tag in ('GSUB', 'GPOS'):
if tag not in font:
continue
table = font[tag].table
if table.LookupList is None:
continue
for lookup in table.LookupList.Lookup:
... | python | {
"resource": ""
} |
q240647 | maxCtxContextualSubtable | train | def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=''):
"""Calculate usMaxContext based on a contextual feature subtable."""
if st.Format == 1:
for ruleset in getattr(st, '%s%sRuleSet' % (chain, ruleType)):
if ruleset is None:
continue
for rule in getattr(r... | python | {
"resource": ""
} |
q240648 | maxCtxContextualRule | train | def maxCtxContextualRule(maxCtx, st, chain):
"""Calculate usMaxContext based on a contextual feature rule."""
if not chain:
return max(maxCtx, st.GlyphCount)
elif chain == 'Reverse':
return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount)
return max(maxCtx, st.InputGlyphCount + st.Lo... | python | {
"resource": ""
} |
q240649 | compileOTF | train | def compileOTF(
ufo,
preProcessorClass=OTFPreProcessor,
outlineCompilerClass=OutlineOTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
optimizeCFF=CFFOptimization.SUBROUTINIZE,
roundTolerance=None,
removeOverlaps=False,
over... | python | {
"resource": ""
} |
q240650 | compileTTF | train | def compileTTF(
ufo,
preProcessorClass=TTFPreProcessor,
outlineCompilerClass=OutlineTTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
convertCubics=True,
cubicConversionError=None,
reverseDirection=True,
rememberCurveType=T... | python | {
"resource": ""
} |
q240651 | compileInterpolatableTTFs | train | def compileInterpolatableTTFs(
ufos,
preProcessorClass=TTFInterpolatablePreProcessor,
outlineCompilerClass=OutlineTTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
cubicConversionError=None,
reverseDirection=True,
inplace=False... | python | {
"resource": ""
} |
q240652 | compileInterpolatableTTFsFromDS | train | def compileInterpolatableTTFsFromDS(
designSpaceDoc,
preProcessorClass=TTFInterpolatablePreProcessor,
outlineCompilerClass=OutlineTTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
cubicConversionError=None,
reverseDirection=True,
... | python | {
"resource": ""
} |
q240653 | compileInterpolatableOTFsFromDS | train | def compileInterpolatableOTFsFromDS(
designSpaceDoc,
preProcessorClass=OTFPreProcessor,
outlineCompilerClass=OutlineOTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
roundTolerance=None,
inplace=False,
):
"""Create FontTools CF... | python | {
"resource": ""
} |
q240654 | compileFeatures | train | def compileFeatures(
ufo,
ttFont=None,
glyphSet=None,
featureWriters=None,
featureCompilerClass=None,
):
""" Compile OpenType Layout features from `ufo` into FontTools OTL tables.
If `ttFont` is None, a new TTFont object is created containing the new
tables, else the provided `ttFont` is... | python | {
"resource": ""
} |
q240655 | _propagate_glyph_anchors | train | def _propagate_glyph_anchors(glyphSet, composite, processed):
"""
Propagate anchors from base glyphs to a given composite
glyph, and to all composite glyphs used in between.
"""
if composite.name in processed:
return
processed.add(composite.name)
if not composite.components:
... | python | {
"resource": ""
} |
q240656 | _get_anchor_data | train | def _get_anchor_data(anchor_data, glyphSet, components, anchor_name):
"""Get data for an anchor from a list of components."""
anchors = []
for component in components:
for anchor in glyphSet[component.baseGlyph].anchors:
if anchor.name == anchor_name:
anchors.append((anc... | python | {
"resource": ""
} |
q240657 | BaseFeatureWriter.setContext | train | def setContext(self, font, feaFile, compiler=None):
""" Populate a temporary `self.context` namespace, which is reset
after each new call to `_write` method.
Subclasses can override this to provide contextual information
which depends on other data, or set any temporary attributes.
... | python | {
"resource": ""
} |
q240658 | BaseFeatureWriter.write | train | def write(self, font, feaFile, compiler=None):
"""Write features and class definitions for this font to a feaLib
FeatureFile object.
Returns True if feature file was modified, False if no new features
were generated.
"""
self.setContext(font, feaFile, compiler=compiler)
... | python | {
"resource": ""
} |
q240659 | BaseFeatureWriter.makeUnicodeToGlyphNameMapping | train | def makeUnicodeToGlyphNameMapping(self):
"""Return the Unicode to glyph name mapping for the current font.
"""
# Try to get the "best" Unicode cmap subtable if this writer is running
# in the context of a FeatureCompiler, else create a new mapping from
# the UFO glyphs
co... | python | {
"resource": ""
} |
q240660 | BaseFeatureWriter.compileGSUB | train | def compileGSUB(self):
"""Compile a temporary GSUB table from the current feature file.
"""
from ufo2ft.util import compileGSUB
compiler = self.context.compiler
if compiler is not None:
# The result is cached in the compiler instance, so if another
# writ... | python | {
"resource": ""
} |
q240661 | BaseOutlineCompiler.compile | train | def compile(self):
"""
Compile the OpenType binary.
"""
self.otf = TTFont(sfntVersion=self.sfntVersion)
# only compile vertical metrics tables if vhea metrics a defined
vertical_metrics = [
"openTypeVheaVertTypoAscender",
"openTypeVheaVertTypoDesc... | python | {
"resource": ""
} |
q240662 | BaseOutlineCompiler.makeFontBoundingBox | train | def makeFontBoundingBox(self):
"""
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
if not hasattr(self, "glyphBoundingBoxes"):
... | python | {
"resource": ""
} |
q240663 | BaseOutlineCompiler.makeMissingRequiredGlyphs | train | def makeMissingRequiredGlyphs(font, glyphSet):
"""
Add .notdef to the glyph set if it is not present.
**This should not be called externally.** Subclasses
may override this method to handle the glyph creation
in a different way if desired.
"""
if ".notdef" in gly... | python | {
"resource": ""
} |
q240664 | BaseOutlineCompiler.setupTable_head | train | def setupTable_head(self):
"""
Make the head table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "head" not in self.tables:
return
... | python | {
"resource": ""
} |
q240665 | BaseOutlineCompiler.setupTable_name | train | def setupTable_name(self):
"""
Make the name table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "name" not in self.tables:
return
... | python | {
"resource": ""
} |
q240666 | BaseOutlineCompiler.setupTable_cmap | train | def setupTable_cmap(self):
"""
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "cmap" not in self.tables:
return
... | python | {
"resource": ""
} |
q240667 | BaseOutlineCompiler.setupTable_hmtx | train | def setupTable_hmtx(self):
"""
Make the hmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "hmtx" not in self.tables:
return
... | python | {
"resource": ""
} |
q240668 | BaseOutlineCompiler._setupTable_hhea_or_vhea | train | def _setupTable_hhea_or_vhea(self, tag):
"""
Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first.
"""
if tag not in self.tables:
return
if tag == "hhea":
isHhea = True
else:
isHh... | python | {
"resource": ""
} |
q240669 | BaseOutlineCompiler.setupTable_vmtx | train | def setupTable_vmtx(self):
"""
Make the vmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "vmtx" not in self.tables:
return
... | python | {
"resource": ""
} |
q240670 | BaseOutlineCompiler.setupTable_VORG | train | def setupTable_VORG(self):
"""
Make the VORG table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "VORG" not in self.tables:
return
... | python | {
"resource": ""
} |
q240671 | BaseOutlineCompiler.setupTable_post | train | def setupTable_post(self):
"""
Make the post table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "post" not in self.tables:
return
... | python | {
"resource": ""
} |
q240672 | BaseOutlineCompiler.importTTX | train | def importTTX(self):
"""
Merge TTX files from data directory "com.github.fonttools.ttx"
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
import os
import re
... | python | {
"resource": ""
} |
q240673 | OutlineTTFCompiler.setupTable_post | train | def setupTable_post(self):
"""Make a format 2 post table with the compiler's glyph order."""
super(OutlineTTFCompiler, self).setupTable_post()
if "post" not in self.otf:
return
post = self.otf["post"]
post.formatType = 2.0
post.extraNames = []
post.ma... | python | {
"resource": ""
} |
q240674 | OutlineTTFCompiler.setupTable_glyf | train | def setupTable_glyf(self):
"""Make the glyf table."""
if not {"glyf", "loca"}.issubset(self.tables):
return
self.otf["loca"] = newTable("loca")
self.otf["glyf"] = glyf = newTable("glyf")
glyf.glyphs = {}
glyf.glyphOrder = self.glyphOrder
hmtx = self.... | python | {
"resource": ""
} |
q240675 | loadLanguage | train | def loadLanguage(filename) :
'''This function loads up a language configuration file and returns
the configuration to be passed to the syllabify function.'''
L = { "consonants" : [], "vowels" : [], "onsets" : [] }
f = open(filename, "r")
section = None
for line in f :
line = line.strip()
if line in ("[cons... | python | {
"resource": ""
} |
q240676 | stringify | train | def stringify(syllables) :
'''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nu... | python | {
"resource": ""
} |
q240677 | slice | train | def slice(l,num_slices=None,slice_length=None,runts=True,random=False):
"""
Returns a new list of n evenly-sized segments of the original list
"""
if random:
import random
random.shuffle(l)
if not num_slices and not slice_length: return l
if not slice_length: slice_length=int(len(l)/num_slices)
newlist=[l[i:... | python | {
"resource": ""
} |
q240678 | entity.u2s | train | def u2s(self,u):
"""Returns an ASCII representation of the Unicode string 'u'."""
try:
return u.encode('utf-8',errors='ignore')
except (UnicodeDecodeError,AttributeError) as e:
try:
return str(u)
except UnicodeEncodeError:
return unicode(u).encode('utf-8',errors='ignore') | python | {
"resource": ""
} |
q240679 | entity.wordtokens | train | def wordtokens(self,include_punct=True):
"""Returns a list of this object's Words in order of their appearance.
Set flattenList to False to receive a list of lists of Words."""
ws=self.ents('WordToken')
if not include_punct: return [w for w in ws if not w.is_punct]
return ws | python | {
"resource": ""
} |
q240680 | entity.dir | train | def dir(self,methods=True,showall=True):
"""Show this object's attributes and methods."""
import inspect
#print "[attributes]"
for k,v in sorted(self.__dict__.items()):
if k.startswith("_"): continue
print makeminlength("."+k,being.linelen),"\t",v
if not methods:
return
entmethods=dir(entity)
... | python | {
"resource": ""
} |
q240681 | entity.makeBubbleChart | train | def makeBubbleChart(self,posdict,name,stattup=None):
"""Returns HTML for a bubble chart of the positin dictionary."""
xname=[x for x in name.split(".") if x.startswith("X_")][0]
yname=[x for x in name.split(".") if x.startswith("Y_")][0]
#elsename=name.replace(xname,'').replace(yname,'').replace('..','.').repl... | python | {
"resource": ""
} |
q240682 | entity.getName | train | def getName(self):
"""Return a Name string for this object."""
name=self.findattr('name')
if not name:
name="_directinput_"
if self.classname().lower()=="line":
name+="."+str(self).replace(" ","_").lower()
else:
name=name.replace('.txt','')
while name.startswith("."):
name=name[1:]
return... | python | {
"resource": ""
} |
q240683 | entity.scansion_prepare | train | def scansion_prepare(self,meter=None,conscious=False):
"""Print out header column for line-scansions for a given meter. """
import prosodic
config=prosodic.config
if not meter:
if not hasattr(self,'_Text__bestparses'): return
x=getattr(self,'_Text__bestparses')
if not x.keys(): return
meter=x.keys(... | python | {
"resource": ""
} |
q240684 | entity.report | train | def report(self,meter=None,include_bounded=False,reverse=True):
""" Print all parses and their violations in a structured format. """
ReportStr = ''
if not meter:
from Meter import Meter
meter=Meter.genDefault()
if (hasattr(self,'allParses')):
self.om(unicode(self))
allparses=self.allParses(meter=m... | python | {
"resource": ""
} |
q240685 | entity.tree | train | def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']):
"""Print a tree-structure of this object's phonological representation."""
tree = ""
numchild=0
for child in self.children:
if type(child)==type([]):
child=child[0]
numchild+=1
classname=child.classname()
if classname=="Wor... | python | {
"resource": ""
} |
q240686 | entity.search | train | def search(self, searchTerm):
"""Returns objects matching the query."""
if type(searchTerm)==type(''):
searchTerm=SearchTerm(searchTerm)
if searchTerm not in self.featpaths:
matches = None
if searchTerm.type != None and searchTerm.type != self.classname():
matches = self._searchInChildren(searchTerm... | python | {
"resource": ""
} |
q240687 | Text.stats_positions | train | def stats_positions(self,meter=None,all_parses=False):
"""Produce statistics from the parser"""
"""Positions
All feats of slots
All constraint violations
"""
parses = self.allParses(meter=meter) if all_parses else [[parse] for parse in self.bestParses(meter=meter)]
dx={}
for parselist in parses:
... | python | {
"resource": ""
} |
q240688 | Text.iparse | train | def iparse(self,meter=None,num_processes=1,arbiter='Line',line_lim=None):
"""Parse this text metrically, yielding it line by line."""
from Meter import Meter,genDefault,parse_ent,parse_ent_mp
import multiprocessing as mp
meter=self.get_meter(meter)
# set internal attributes
self.__parses[meter.id]=[]
sel... | python | {
"resource": ""
} |
q240689 | Text.scansion | train | def scansion(self,meter=None,conscious=False):
"""Print out the parses and their violations in scansion format."""
meter=self.get_meter(meter)
self.scansion_prepare(meter=meter,conscious=conscious)
for line in self.lines():
try:
line.scansion(meter=meter,conscious=conscious)
except AttributeError:
... | python | {
"resource": ""
} |
q240690 | Text.allParses | train | def allParses(self,meter=None,include_bounded=False,one_per_meter=True):
"""Return a list of lists of parses."""
meter=self.get_meter(meter)
try:
parses=self.__parses[meter.id]
if one_per_meter:
toreturn=[]
for _parses in parses:
sofar=set()
_parses2=[]
for _p in _parses:
_pm=... | python | {
"resource": ""
} |
q240691 | Text.validlines | train | def validlines(self):
"""Return all lines within which Prosodic understood all words."""
return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)] | python | {
"resource": ""
} |
q240692 | MarkupFormatter.choices | train | def choices(self):
"""
Returns the filter list as a tuple. Useful for model choices.
"""
choice_list = getattr(
settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES
)
return [(f, self._get_filter_title(f)) for f in choice_list] | python | {
"resource": ""
} |
q240693 | MarkupFormatter.unregister | train | def unregister(self, filter_name):
"""
Unregister a filter from the filter list
"""
if filter_name in self.filter_list:
self.filter_list.pop(filter_name) | python | {
"resource": ""
} |
q240694 | MetricalTree.convert | train | def convert(cls, tree):
"""
Convert a tree between different subtypes of Tree. ``cls`` determines
which class will be used to encode the new tree.
:type tree: Tree
:param tree: The tree that should be converted.
:return: The new Tree.
"""
if isinstance(... | python | {
"resource": ""
} |
q240695 | RuntimeRawExtension.raw | train | def raw(self, raw):
"""Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str
"""
if raw is None:
raise ValueError("Invalid value f... | python | {
"resource": ""
} |
q240696 | Watch.unmarshal_event | train | def unmarshal_event(self, data: str, response_type):
"""Return the K8s response `data` in JSON format.
"""
js = json.loads(data)
# Make a copy of the original object and save it under the
# `raw_object` key because we will replace the data under `object` with
# a Python... | python | {
"resource": ""
} |
q240697 | Watch.stream | train | def stream(self, func, *args, **kwargs):
"""Watch an API resource and stream the result back via a generator.
:param func: The API function pointer. Any parameter to the function
can be passed after this parameter.
:return: Event object with these keys:
... | python | {
"resource": ""
} |
q240698 | RESTResponse.getheader | train | def getheader(self, name, default=None):
"""Returns a given response header."""
return self.aiohttp_response.headers.get(name, default) | python | {
"resource": ""
} |
q240699 | authentication_required | train | def authentication_required(req, resp, resource, uri_kwargs):
"""Ensure that user is authenticated otherwise return ``401 Unauthorized``.
If request fails to authenticate this authorization hook will also
include list of ``WWW-Athenticate`` challenges.
Args:
req (falcon.Request): the request o... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.