_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q240500 | filterCollapsedItems | train | def filterCollapsedItems(data):
"""Return a filtered iteration over a list of items."""
return ((key, value)\
for key, value in six.iteritems(data) \
if not (isinstance(value, StatContainer) and value.isCollapsed())) | python | {
"resource": ""
} |
q240501 | dumpStatsTo | train | def dumpStatsTo(filename):
"""Writes the stats dict to filanem"""
with open(filename, 'w') as f:
latest = getStats()
latest['last-updated'] = time.time()
json.dump(getStats(), f, cls=StatContainerEncoder) | python | {
"resource": ""
} |
q240502 | collection | train | def collection(path, *stats):
"""Creates a named stats collection object."""
def initMethod(self):
"""Init method for the underlying stat object's class."""
init(self, path)
attributes = {'__init__': initMethod}
for stat in stats:
attributes[stat.getName()] = stat
newClass = type('Stats:%s' % pa... | python | {
"resource": ""
} |
q240503 | _Stats.reset | train | def reset(cls):
"""Resets the static state. Should only be called by tests."""
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | python | {
"resource": ""
} |
q240504 | _Stats.init | train | def init(cls, obj, context):
"""Implementation of init."""
addr = statsId(obj)
if addr not in cls.containerMap:
cls.containerMap[addr] = cls.__getStatContainer(context)
return cls.containerMap[addr] | python | {
"resource": ""
} |
q240505 | _Stats.initChild | train | def initChild(cls, obj, name, subContext, parent = None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentfra... | python | {
"resource": ""
} |
q240506 | _Stats.__getStatContainer | train | def __getStatContainer(cls, context, parent=None):
"""Get the stat container for the given context under the given parent."""
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
... | python | {
"resource": ""
} |
q240507 | _Stats.getStat | train | def getStat(cls, obj, name):
"""Gets the stat for the given object with the given name, or None if no such stat exists."""
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and v... | python | {
"resource": ""
} |
q240508 | _Stats.getAggregator | train | def getAggregator(cls, instanceId, name):
"""Gets the aggregate stat for the given stat."""
parent = cls.parentMap.get(instanceId)
while parent:
stat = cls.getStat(parent, name)
if stat:
return stat, parent
parent = cls.parentMap.get(statsId(parent)) | python | {
"resource": ""
} |
q240509 | Stat._aggregate | train | def _aggregate(self, instanceId, container, value, subKey = None):
"""Performs stat aggregation."""
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we a... | python | {
"resource": ""
} |
q240510 | Stat.updateItem | train | def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | python | {
"resource": ""
} |
q240511 | StateTimeStatDict.incr | train | def incr(self, item, value):
"""Increment a key by the given amount."""
if item in self:
old = UserDict.__getitem__(self, item)
else:
old = 0.0
self[item] = old + value | python | {
"resource": ""
} |
q240512 | Aggregation.addSource | train | def addSource(self, source, data):
"""Adds the given source's stats."""
self._aggregate(source, self._aggregators, data, self._result) | python | {
"resource": ""
} |
q240513 | Aggregation.addJsonDirectory | train | def addJsonDirectory(self, directory, test=None):
"""Adds data from json files in the given directory."""
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonD... | python | {
"resource": ""
} |
q240514 | Sampler.mean | train | def mean(self):
"""Return the sample mean."""
if len(self) == 0:
return float('NaN')
arr = self.samples()
return sum(arr) / float(len(arr)) | python | {
"resource": ""
} |
q240515 | Sampler.stddev | train | def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqr... | python | {
"resource": ""
} |
q240516 | ExponentiallyDecayingReservoir.clear | train | def clear(self):
""" Clear the samples. """
self.__init__(size=self.size, alpha=self.alpha, clock=self.clock) | python | {
"resource": ""
} |
q240517 | ExponentiallyDecayingReservoir.update | train | def update(self, value):
"""
Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added
"""
super(ExponentiallyDecayingReservoir, self).update(value)
timestamp = self.clock.time()
self.__rescaleIfNeeded()
priority = self.__weight(timestamp - s... | python | {
"resource": ""
} |
q240518 | UniformSample.clear | train | def clear(self):
"""Clear the sample."""
for i in range(len(self.sample)):
self.sample[i] = 0.0
self.count = 0 | python | {
"resource": ""
} |
q240519 | UniformSample.update | train | def update(self, value):
"""Add a value to the sample."""
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | python | {
"resource": ""
} |
q240520 | GraphitePusher._forbidden | train | def _forbidden(self, path, value):
"""Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.r... | python | {
"resource": ""
} |
q240521 | GraphitePusher._pruned | train | def _pruned(self, path):
"""Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default."""
if path[0] == '/':
path = path[1:]
for rule ... | python | {
"resource": ""
} |
q240522 | GraphitePusher.push | train | def push(self, statsDict=None, prefix=None, path=None):
"""Push stat values out to Graphite."""
if statsDict is None:
statsDict = scales.getStats()
prefix = prefix or self.prefix
path = path or '/'
for name, value in list(statsDict.items()):
name = str(name)
subpath = os.path.join... | python | {
"resource": ""
} |
q240523 | GraphitePeriodicPusher.run | train | def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats t... | python | {
"resource": ""
} |
q240524 | installStatsLoop | train | def installStatsLoop(statsFile, statsDelay):
"""Installs an interval loop that dumps stats to a file."""
def dumpStats():
"""Actual stats dump function."""
scales.dumpStatsTo(statsFile)
reactor.callLater(statsDelay, dumpStats)
def startStats():
"""Starts the stats dump in "statsDelay" seconds.""... | python | {
"resource": ""
} |
q240525 | runQuery | train | def runQuery(statDict, query):
"""Filters for the given query."""
parts = [x.strip() for x in OPERATOR.split(query)]
assert len(parts) in (1, 3)
queryKey = parts[0]
result = {}
for key, value in six.iteritems(statDict):
if key == queryKey:
if len(parts) == 3:
op = OPERATORS[parts[1]]
... | python | {
"resource": ""
} |
q240526 | htmlHeader | train | def htmlHeader(output, path, serverName, query = None):
"""Writes an HTML header."""
if path and path != '/':
output.write('<title>%s - Status: %s</title>' % (serverName, path))
else:
output.write('<title>%s - Status</title>' % serverName)
output.write('''
<style>
body,td { font-family: monospace }
.lev... | python | {
"resource": ""
} |
q240527 | htmlFormat | train | def htmlFormat(output, pathParts = (), statDict = None, query = None):
"""Formats as HTML, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | python | {
"resource": ""
} |
q240528 | _htmlRenderDict | train | def _htmlRenderDict(pathParts, statDict, output):
"""Render a dictionary as a table - recursing as necessary."""
keys = list(statDict.keys())
keys.sort()
links = []
output.write('<div class="level">')
for key in keys:
keyStr = cgi.escape(_utf8str(key))
value = statDict[key]
if hasattr(value, '... | python | {
"resource": ""
} |
q240529 | jsonFormat | train | def jsonFormat(output, statDict = None, query = None, pretty = False):
"""Formats as JSON, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
indent = 2 if pretty else None
# At first, assume that strings are in UTF-8. If this fails -- i... | python | {
"resource": ""
} |
q240530 | RepeatTimer | train | def RepeatTimer(interval, function, iterations=0, *args, **kwargs):
"""Repeating timer. Returns a thread id."""
def __repeat_timer(interval, function, iterations, args, kwargs):
"""Inner function, run in background thread."""
count = 0
while iterations <= 0 or count < iterations:
sleep(interval)
... | python | {
"resource": ""
} |
q240531 | get_config | train | def get_config(context):
"""
Return the formatted javascript for any disqus config variables.
"""
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\t... | python | {
"resource": ""
} |
q240532 | disqus_show_comments | train | def disqus_show_comments(context, shortname=''):
"""
Return the HTML code to display DISQUS comments.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | python | {
"resource": ""
} |
q240533 | WxrFeedType.add_item | train | def add_item(self, title, link, description, author_email=None,
author_name=None, author_link=None, pubdate=None, comments=None,
unique_id=None, enclosure=None, categories=(), item_copyright=None,
ttl=None, **kwargs):
"""
Adds an item to the feed. All args are expected to be Pyth... | python | {
"resource": ""
} |
q240534 | call | train | def call(method, data, post=False):
"""
Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response.
"""
url = "%s%s" % ('http://disqus.com/api/', method)
if post:
# POST request
url += "/"
data = urlencode(data)
else:
... | python | {
"resource": ""
} |
q240535 | Command._get_comments_to_export | train | def _get_comments_to_export(self, last_export_id=None):
"""Return comments which should be exported."""
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(l... | python | {
"resource": ""
} |
q240536 | Command._get_last_state | train | def _get_last_state(self, state_file):
"""Checks the given path for the last exported comment's id"""
state = None
fp = open(state_file)
try:
state = int(fp.read())
print("Found previous state: %d" % (state,))
finally:
fp.close()
return... | python | {
"resource": ""
} |
q240537 | Command._save_state | train | def _save_state(self, state_file, last_pk):
"""Saves the last_pk into the given state_file"""
fp = open(state_file, 'w+')
try:
fp.write(str(last_pk))
finally:
fp.close() | python | {
"resource": ""
} |
q240538 | DisqusClient._get_request | train | def _get_request(self, request_url, request_method, **params):
"""
Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object.
"""
if request_method == 'GET':
if params:
request_url += '&%s' % urlenc... | python | {
"resource": ""
} |
q240539 | DisqusClient.call | train | def call(self, method, **params):
"""
Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed.
"""
url = self.api_url % method
request = self._get_request(url, self.METHO... | python | {
"resource": ""
} |
q240540 | init_app | train | def init_app(app):
"""
'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object
"""
config = EmailsConfig(app)
... | python | {
"resource": ""
} |
q240541 | Message.send | train | def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response ... | python | {
"resource": ""
} |
q240542 | EmailsConfig.options | train | def options(self):
"""
Reads all EMAIL_ options and set default values.
"""
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(con... | python | {
"resource": ""
} |
q240543 | EmailsConfig.smtp_options | train | def smtp_options(self):
"""
Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory
"""
o = {}
options = self.options
for key in self._default_smtp_options:
if key in options:
o[key] = options[key]
... | python | {
"resource": ""
} |
q240544 | EmailsConfig.message_options | train | def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | python | {
"resource": ""
} |
q240545 | LivySession.start | train | def start(self) -> None:
"""Create the remote Spark session and wait for it to be ready."""
session = self.client.create_session(
self.kind,
self.proxy_user,
self.jars,
self.py_files,
self.files,
self.driver_memory,
sel... | python | {
"resource": ""
} |
q240546 | LivySession.state | train | def state(self) -> SessionState:
"""The state of the managed Spark session."""
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it m... | python | {
"resource": ""
} |
q240547 | LivySession.close | train | def close(self) -> None:
"""Kill the managed Spark session."""
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | python | {
"resource": ""
} |
q240548 | LivySession.run | train | def run(self, code: str) -> Output:
"""Run some code in the managed Spark session.
:param code: The code to run.
"""
output = self._execute(code)
if self.echo and output.text:
print(output.text)
if self.check:
output.raise_for_status()
ret... | python | {
"resource": ""
} |
q240549 | LivySession.read | train | def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)... | python | {
"resource": ""
} |
q240550 | LivySession.read_sql | train | def read_sql(self, code: str) -> pandas.DataFrame:
"""Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate.
"""
if self.kind != SessionKind.SQL:
raise ValueError("not a SQL session")
output = self._execute(code)
... | python | {
"resource": ""
} |
q240551 | LivyClient.server_version | train | def server_version(self) -> Version:
"""Get the version of Livy running on the server."""
if self._server_version_cache is None:
data = self._client.get("/version")
self._server_version_cache = Version(data["version"])
return self._server_version_cache | python | {
"resource": ""
} |
q240552 | LivyClient.list_sessions | train | def list_sessions(self) -> List[Session]:
"""List all the active sessions in Livy."""
data = self._client.get("/sessions")
return [Session.from_json(item) for item in data["sessions"]] | python | {
"resource": ""
} |
q240553 | LivyClient.create_session | train | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cor... | python | {
"resource": ""
} |
q240554 | LivyClient.list_statements | train | def list_statements(self, session_id: int) -> List[Statement]:
"""Get all the statements in a session.
:param session_id: The ID of the session.
"""
response = self._client.get(f"/sessions/{session_id}/statements")
return [
Statement.from_json(session_id, data)
... | python | {
"resource": ""
} |
q240555 | LivyClient.create_statement | train | def create_statement(
self, session_id: int, code: str, kind: StatementKind = None
) -> Statement:
"""Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute.
"""
data... | python | {
"resource": ""
} |
q240556 | LivyClient.get_statement | train | def get_statement(self, session_id: int, statement_id: int) -> Statement:
"""Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement.
"""
response = self._client.get(
f"/sessions/{session_... | python | {
"resource": ""
} |
q240557 | lattice | train | def lattice(lattice, filename, directory, render, view, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape=... | python | {
"resource": ""
} |
q240558 | Format.load | train | def load(cls, filename, encoding):
"""Load and parse serialized objects, properties, bools from file."""
if encoding is None:
encoding = cls.encoding
with io.open(filename, 'r', encoding=encoding) as fd:
source = fd.read()
if cls.normalize_newlines:
... | python | {
"resource": ""
} |
q240559 | Format.dump | train | def dump(cls, filename, objects, properties, bools, encoding):
"""Write serialized objects, properties, bools to file."""
if encoding is None:
encoding = cls.encoding
source = cls.dumps(objects, properties, bools)
if PY2:
source = unicode(source)
with io... | python | {
"resource": ""
} |
q240560 | load_csv | train | def load_csv(filename, dialect='excel', encoding='utf-8'):
"""Load and return formal context from CSV file.
Args:
filename: Path to the CSV file to load the context from.
dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``).
encoding (str): Encoding of the file (``'utf... | python | {
"resource": ""
} |
q240561 | ensure_compatible | train | def ensure_compatible(left, right):
"""Raise an informative ``ValueError`` if the two definitions disagree."""
conflicts = list(conflicting_pairs(left, right))
if conflicts:
raise ValueError('conflicting values for object/property pairs: %r' % conflicts) | python | {
"resource": ""
} |
q240562 | Definition.rename_object | train | def rename_object(self, old, new):
"""Replace the name of an object by a new one."""
self._objects.replace(old, new)
pairs = self._pairs
pairs |= {(new, p) for p in self._properties
if (old, p) in pairs and not pairs.remove((old, p))} | python | {
"resource": ""
} |
q240563 | Definition.rename_property | train | def rename_property(self, old, new):
"""Replace the name of a property by a new one."""
self._properties.replace(old, new)
pairs = self._pairs
pairs |= {(o, new) for o in self._objects
if (o, old) in pairs and not pairs.remove((o, old))} | python | {
"resource": ""
} |
q240564 | Definition.add_object | train | def add_object(self, obj, properties=()):
"""Add an object to the definition and add ``properties`` as related."""
self._objects.add(obj)
self._properties |= properties
self._pairs.update((obj, p) for p in properties) | python | {
"resource": ""
} |
q240565 | Definition.add_property | train | def add_property(self, prop, objects=()):
"""Add a property to the definition and add ``objects`` as related."""
self._properties.add(prop)
self._objects |= objects
self._pairs.update((o, prop) for o in objects) | python | {
"resource": ""
} |
q240566 | Definition.remove_object | train | def remove_object(self, obj):
"""Remove an object from the definition."""
self._objects.remove(obj)
self._pairs.difference_update((obj, p) for p in self._properties) | python | {
"resource": ""
} |
q240567 | Definition.remove_property | train | def remove_property(self, prop):
"""Remove a property from the definition."""
self._properties.remove(prop)
self._pairs.difference_update((o, prop) for o in self._objects) | python | {
"resource": ""
} |
q240568 | Definition.set_object | train | def set_object(self, obj, properties):
"""Add an object to the definition and set its ``properties``."""
self._objects.add(obj)
properties = set(properties)
self._properties |= properties
pairs = self._pairs
for p in self._properties:
if p in properties:
... | python | {
"resource": ""
} |
q240569 | Definition.set_property | train | def set_property(self, prop, objects):
"""Add a property to the definition and set its ``objects``."""
self._properties.add(prop)
objects = set(objects)
self._objects |= objects
pairs = self._pairs
for o in self._objects:
if o in objects:
pairs... | python | {
"resource": ""
} |
q240570 | Definition.union_update | train | def union_update(self, other, ignore_conflicts=False):
"""Update the definition with the union of the ``other``."""
if not ignore_conflicts:
ensure_compatible(self, other)
self._objects |= other._objects
self._properties |= other._properties
self._pairs |= other._pair... | python | {
"resource": ""
} |
q240571 | Definition.union | train | def union(self, other, ignore_conflicts=False):
"""Return a new definition from the union of the definitions."""
result = self.copy()
result.union_update(other, ignore_conflicts)
return result | python | {
"resource": ""
} |
q240572 | Definition.intersection | train | def intersection(self, other, ignore_conflicts=False):
"""Return a new definition from the intersection of the definitions."""
result = self.copy()
result.intersection_update(other, ignore_conflicts)
return result | python | {
"resource": ""
} |
q240573 | maximal | train | def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)):
"""Yield the unique maximal elements from ``iterable`` using ``comparison``.
>>> list(maximal([1, 2, 3, 3]))
[3]
>>> list(maximal([1]))
[1]
"""
iterable = set(iterable)
if len(iterable) < 2:
return... | python | {
"resource": ""
} |
q240574 | Unique.replace | train | def replace(self, item, new_item):
"""Replace an item preserving order.
>>> u = Unique([0, 1, 2])
>>> u.replace(1, 'spam')
>>> u
Unique([0, 'spam', 2])
>>> u.replace('eggs', 1)
Traceback (most recent call last):
...
ValueError: 'eggs' is not ... | python | {
"resource": ""
} |
q240575 | Unique.move | train | def move(self, item, new_index):
"""Move an item to the given position.
>>> u = Unique(['spam', 'eggs'])
>>> u.move('spam', 1)
>>> u
Unique(['eggs', 'spam'])
>>> u.move('ham', 0)
Traceback (most recent call last):
...
ValueError: 'ham' is not... | python | {
"resource": ""
} |
q240576 | Unique.issuperset | train | def issuperset(self, items):
"""Return whether this collection contains all items.
>>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])
True
"""
return all(_compat.map(self._seen.__contains__, items)) | python | {
"resource": ""
} |
q240577 | Unique.rsub | train | def rsub(self, items):
"""Return order preserving unique items not in this collection.
>>> Unique(['spam']).rsub(['ham', 'spam', 'eggs'])
Unique(['ham', 'eggs'])
"""
ignore = self._seen
seen = set()
add = seen.add
items = [i for i in items
... | python | {
"resource": ""
} |
q240578 | merge_schema | train | def merge_schema(first, second):
"""Returns the result of merging the two given schemas.
"""
if not (type(first) == type(second) == dict):
raise ValueError("Argument is not a schema")
if not (first.get('type') == second.get('type') == 'object'):
raise NotImplementedError("Unsupported ro... | python | {
"resource": ""
} |
q240579 | generate_and_merge_schemas | train | def generate_and_merge_schemas(samples):
"""Iterates through the given samples, generating schemas
and merging them, returning the resulting merged schema.
"""
merged = generate_schema_for_sample(next(iter(samples)))
for sample in samples:
merged = merge_schema(merged, generate_schema_for_... | python | {
"resource": ""
} |
q240580 | sine_psd | train | def sine_psd(data, delta, number_of_tapers=None, number_of_iterations=2,
degree_of_smoothing=1.0, statistics=False, verbose=False):
"""
Wrapper method for the sine_psd subroutine in the library by German A.
Prieto.
The subroutine is in charge of estimating the adaptive sine multitaper as
... | python | {
"resource": ""
} |
q240581 | dpss | train | def dpss(npts, fw, number_of_tapers, auto_spline=True, npts_max=None):
"""
Calculates DPSS also known as Slepian sequences or Slepian tapers.
Calculation of the DPSS (Discrete Prolate Spheroidal Sequences) and the
correspondent eigenvalues. The (1 - eigenvalue) terms are also calculated.
Wraps the... | python | {
"resource": ""
} |
q240582 | wigner_ville_spectrum | train | def wigner_ville_spectrum(data, delta, time_bandwidth=3.5,
number_of_tapers=None, smoothing_filter=None,
filter_width=100, frequency_divider=1,
verbose=False):
"""
Function to calculate the Wigner-Ville Distribution or Wigner-Ville
... | python | {
"resource": ""
} |
q240583 | mt_deconvolve | train | def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None,
number_of_tapers=None, weights="adaptive", demean=True,
fmax=0.0):
"""
Deconvolve two time series using multitapers.
This uses the eigencoefficients and the weights from the multitaper
spectral ... | python | {
"resource": ""
} |
q240584 | _MtspecType.empty | train | def empty(self, shape, complex=False):
"""
A wrapper around np.empty which automatically sets the correct type
and returns an empty array.
:param shape: The shape of the array in np.empty format
"""
if complex:
return np.empty(shape, dtype=self.complex, order... | python | {
"resource": ""
} |
q240585 | signal_bursts | train | def signal_bursts():
"""
Generates a signal with two bursts inside. Useful for testing time
frequency distributions.
:returns: Generated signal
:rtype: numpy.ndarray
"""
np.random.seed(815)
length = 5 * 512
# Baseline low frequency plus noise.
data = np.sin(np.linspace(0, 80 * ... | python | {
"resource": ""
} |
q240586 | linear_chirp | train | def linear_chirp(npts=2000):
"""
Generates a simple linear chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray
"""
time = np.linspace(0, 20, npts)
chirp = np.sin(0.2 * np.pi * (0.1 + 24.0 / 2.0 * time) * time)
return chirp | python | {
"resource": ""
} |
q240587 | exponential_chirp | train | def exponential_chirp(npts=2000):
"""
Generates an exponential chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray
"""
time = np.linspace(0, 20, npts)
chirp = np.sin(2 * np.pi * 0.2 * (1.3 ** time - 1) / np.log(1.3))
return chi... | python | {
"resource": ""
} |
q240588 | get_libgfortran_dir | train | def get_libgfortran_dir():
"""
Helper function returning the library directory of libgfortran. Useful
on OSX where the C compiler oftentimes has no knowledge of the library
directories of the Fortran compiler. I don't think it can do any harm on
Linux.
"""
for ending in [".3.dylib", ".dylib"... | python | {
"resource": ""
} |
q240589 | PrototypeObject.create | train | def create(cls, obj):
"""
Create a new prototype object with the argument as the source
prototype.
.. Note:
This does not `initialize` the newly created object any
more than setting its prototype.
Calling the __init__ method is usually unnecessary as... | python | {
"resource": ""
} |
q240590 | PrototypeObject.bind | train | def bind(self, func):
"""
Take a function and create a bound method
"""
if self.__methods__ is None:
self.__methods__ = {}
self.__methods__[func.__name__] = BoundFunction(func) | python | {
"resource": ""
} |
q240591 | PrototypeObject.has_own_property | train | def has_own_property(self, attr):
"""
Returns if the property
"""
try:
object.__getattribute__(self, attr)
except AttributeError:
return False
else:
return True | python | {
"resource": ""
} |
q240592 | Application.add_router | train | def add_router(self, path, router):
"""
Adds a router to the list of routers
Args:
path (str or regex): The path on which the router binds
router (growler.Router): The router which will respond to
requests
Raises:
TypeError: If `stric... | python | {
"resource": ""
} |
q240593 | Application.create_server | train | def create_server(self,
loop=None,
as_coroutine=False,
protocol_factory=None,
**server_config):
"""
Helper function which constructs a listening server, using the
default growler.http.protocol.Protocol which ... | python | {
"resource": ""
} |
q240594 | Application.create_server_and_run_forever | train | def create_server_and_run_forever(self, loop=None, **server_config):
"""
Helper function which constructs an HTTP server and listens the
loop forever.
This function exists only to remove boilerplate code for starting
up a growler app.
Args:
**server_config: ... | python | {
"resource": ""
} |
q240595 | RenderEngine.find_template_filename | train | def find_template_filename(self, template_name):
"""
Searches for a file matching the given template name.
If found, this method returns the pathlib.Path object of the found
template file.
Args:
template_name (str): Name of the template, with or without a file
... | python | {
"resource": ""
} |
q240596 | GrowlerHTTPResponder.set_request_line | train | def set_request_line(self, method, url, version):
"""
Sets the request line on the responder.
"""
self.parsed_request = (method, url, version)
self.request = {
'method': method,
'url': url,
'version': version
} | python | {
"resource": ""
} |
q240597 | GrowlerHTTPResponder.init_body_buffer | train | def init_body_buffer(self, method, headers):
"""
Sets up the body_buffer and content_length attributes based
on method and headers.
"""
content_length = headers.get("CONTENT-LENGTH", None)
if method in (HTTPMethod.POST, HTTPMethod.PUT):
if content_length is N... | python | {
"resource": ""
} |
q240598 | GrowlerHTTPResponder.build_req_and_res | train | def build_req_and_res(self):
"""
Simple method which calls the request and response factories
the responder was given, and returns the pair.
"""
req = self.build_req(self, self.headers)
res = self.build_res(self._handler)
return req, res | python | {
"resource": ""
} |
q240599 | GrowlerHTTPResponder.validate_and_store_body_data | train | def validate_and_store_body_data(self, data):
"""
Attempts simple body data validation by comparining incoming
data to the content length header.
If passes store the data into self._buffer.
Parameters:
data (bytes): Incoming client data to be added to the body
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.