_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q247500 | run_parallel | train | def run_parallel(
workflow, *, n_threads, registry, db_file, echo_log=True,
always_cache=False):
"""Run a workflow in parallel threads, storing results in a Sqlite3
database.
:param workflow: Workflow or PromisedObject to evaluate.
:param n_threads: number of threads to use (in addition... | python | {
"resource": ""
} |
q247501 | is_unwrapped | train | def is_unwrapped(f):
"""If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`"""
try:
g = look_up(object_name(f))
return g != f and unwrap(g) == f
except (AttributeError, TypeError, ImportError):
return Fals... | python | {
"resource": ""
} |
q247502 | inverse_deep_map | train | def inverse_deep_map(f, root):
"""Sibling to |deep_map|. Recursively maps objects in a nested structure of
``list`` and ``dict`` objects. Where |deep_map| starts at the top,
|inverse_deep_map| starts at the bottom. First, if `root` is a ``list`` or
``dict``, its contents are |inverse_deep_map|ed. Then a... | python | {
"resource": ""
} |
q247503 | Registry.decode | train | def decode(self, rec, deref=False):
"""Decode a record to return an object that could be considered
equivalent to the original.
The record is not touched if `_noodles` is not an item in the record.
:param rec:
A dictionary record to be decoded.
:type rec: dict
... | python | {
"resource": ""
} |
q247504 | Registry.to_json | train | def to_json(self, obj, host=None, indent=None):
"""Recursively encode `obj` and convert it to a JSON string.
:param obj:
Object to encode.
:param host:
hostname where this object is being encoded.
:type host: str"""
if indent:
return json.dum... | python | {
"resource": ""
} |
q247505 | Registry.from_json | train | def from_json(self, data, deref=False):
"""Decode the string from JSON to return the original object (if
`deref` is true. Uses the `json.loads` function with `self.decode`
as object_hook.
:param data:
JSON encoded string.
:type data: str
:param deref:
... | python | {
"resource": ""
} |
q247506 | Registry.dereference | train | def dereference(self, data, host=None):
"""Dereferences RefObjects stuck in the hierarchy. This is a bit
of an ugly hack."""
return self.deep_decode(self.deep_encode(data, host), deref=True) | python | {
"resource": ""
} |
q247507 | run_single | train | def run_single(workflow, *, registry, db_file, always_cache=True):
""""Run workflow in a single thread, storing results in a Sqlite3
database.
:param workflow: Workflow or PromisedObject to be evaluated.
:param registry: serialization Registry function.
:param db_file: filename of Sqlite3 database,... | python | {
"resource": ""
} |
q247508 | Machine.scheduler | train | def scheduler(self):
"""Returns the scheduler object."""
if self._scheduler is None:
self._scheduler = xenon.Scheduler.create(**self.scheduler_args)
return self._scheduler | python | {
"resource": ""
} |
q247509 | Machine.file_system | train | def file_system(self):
"""Gets the filesystem corresponding to the open scheduler."""
if self._file_system is None:
self._file_system = self.scheduler.get_file_system()
return self._file_system | python | {
"resource": ""
} |
q247510 | registry | train | def registry():
"""Returns the Noodles base serialisation registry."""
return Registry(
types={
dict: SerDict(),
tuple: SerSequence(tuple),
set: SerSequence(set),
bytes: SerBytes(),
slice: SerSlice(),
complex: SerByMembers(complex, ... | python | {
"resource": ""
} |
q247511 | scheduled_function | train | def scheduled_function(f, hints=None):
"""The Noodles schedule function decorator.
The decorated function will return a workflow in stead of
being applied immediately. This workflow can then be passed to a job
scheduler in order to be run on any architecture supporting the current
python environmen... | python | {
"resource": ""
} |
q247512 | worker | train | def worker(job):
"""Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker`"""
if job is EndOfQueue:
return
if not isin... | python | {
"resource": ""
} |
q247513 | run_job | train | def run_job(key, node):
"""Run a job. This applies the function node, and returns a |ResultMessage|
when complete. If an exception is raised in the job, the |ResultMessage|
will have ``'error'`` status.
.. |run_job| replace:: :py:func:`run_job`"""
try:
result = node.apply()
return R... | python | {
"resource": ""
} |
q247514 | hybrid_coroutine_worker | train | def hybrid_coroutine_worker(selector, workers):
"""Runs a set of workers, all of them in the main thread.
This runner is here for testing purposes.
:param selector:
A function returning a worker key, given a job.
:type selector: function
:param workers:
A dict of workers.
:type... | python | {
"resource": ""
} |
q247515 | hybrid_threaded_worker | train | def hybrid_threaded_worker(selector, workers):
"""Runs a set of workers, each in a separate thread.
:param selector:
A function that takes a hints-tuple and returns a key
indexing a worker in the `workers` dictionary.
:param workers:
A dictionary of workers.
:returns:
A... | python | {
"resource": ""
} |
q247516 | run_hybrid | train | def run_hybrid(wf, selector, workers):
"""
Returns the result of evaluating the workflow; runs through several
supplied workers in as many threads.
:param wf:
Workflow to compute
:type wf: :py:class:`Workflow` or :py:class:`PromisedObject`
:param selector:
A function selecting ... | python | {
"resource": ""
} |
q247517 | prov_key | train | def prov_key(job_msg, extra=None):
"""Retrieves a MD5 sum from a function call. This takes into account the
name of the function, the arguments and possibly a version number of the
function, if that is given in the hints.
This version can also be auto-generated by generating an MD5 hash from the
fun... | python | {
"resource": ""
} |
q247518 | JSONObjectReader | train | def JSONObjectReader(registry, fi, deref=False):
"""Stream objects from a JSON file.
:param registry: serialisation registry.
:param fi: input file
:param deref: flag, if True, objects will be dereferenced on decoding,
otherwise we are lazy about decoding a JSON string.
"""
for line in ... | python | {
"resource": ""
} |
q247519 | JSONObjectWriter | train | def JSONObjectWriter(registry, fo, host=None):
"""Sink; writes object as JSON to a file.
:param registry: serialisation registry.
:param fo: output file.
:param host: name of the host that encodes the JSON. This is relevant if
the encoded data refers to external files for mass storage.
In ... | python | {
"resource": ""
} |
q247520 | matrix | train | def matrix(mat):
"""Convert a ROOT TMatrix into a NumPy matrix.
Parameters
----------
mat : ROOT TMatrixT
A ROOT TMatrixD or TMatrixF
Returns
-------
mat : numpy.matrix
A NumPy matrix
Examples
--------
>>> from root_numpy import matrix
>>> from ROOT import ... | python | {
"resource": ""
} |
q247521 | fill_graph | train | def fill_graph(graph, array):
"""Fill a ROOT graph with a NumPy array.
Parameters
----------
graph : a ROOT TGraph or TGraph2D
The ROOT graph to fill.
array : numpy array of shape [n_samples, n_dimensions]
The values to fill the graph with. The number of columns must match the
... | python | {
"resource": ""
} |
q247522 | random_sample | train | def random_sample(obj, n_samples, seed=None):
"""Create a random array by sampling a ROOT function or histogram.
Parameters
----------
obj : TH[1|2|3] or TF[1|2|3]
The ROOT function or histogram to sample.
n_samples : positive int
The number of random samples to generate.
seed :... | python | {
"resource": ""
} |
q247523 | _glob | train | def _glob(filenames):
"""Glob a filename or list of filenames but always return the original
string if the glob didn't match anything so URLs for remote file access
are not clobbered.
"""
if isinstance(filenames, string_types):
filenames = [filenames]
matches = []
for name in filenam... | python | {
"resource": ""
} |
q247524 | list_structures | train | def list_structures(filename, treename=None):
"""Get a dictionary mapping branch names to leaf structures.
.. warning:: ``list_structures`` is deprecated and will be removed in
release 5.0.0.
Parameters
----------
filename : str
Path to ROOT file.
treename : str, optional (defau... | python | {
"resource": ""
} |
q247525 | root2array | train | def root2array(filenames,
treename=None,
branches=None,
selection=None,
object_selection=None,
start=None,
stop=None,
step=None,
include_weight=False,
weight_name='weight',
... | python | {
"resource": ""
} |
q247526 | tree2array | train | def tree2array(tree,
branches=None,
selection=None,
object_selection=None,
start=None,
stop=None,
step=None,
include_weight=False,
weight_name='weight',
cache_size=-1):
"""Convert a... | python | {
"resource": ""
} |
q247527 | array2tree | train | def array2tree(arr, name='tree', tree=None):
"""Convert a numpy structured array into a ROOT TTree.
Fields of basic types, strings, and fixed-size subarrays of basic types are
supported. ``np.object`` and ``np.float16`` are currently not supported.
Parameters
----------
arr : array
A n... | python | {
"resource": ""
} |
q247528 | array2root | train | def array2root(arr, filename, treename='tree', mode='update'):
"""Convert a numpy array into a ROOT TTree and save it in a ROOT TFile.
Fields of basic types, strings, and fixed-size subarrays of basic types are
supported. ``np.object`` and ``np.float16`` are currently not supported.
Parameters
---... | python | {
"resource": ""
} |
q247529 | fill_hist | train | def fill_hist(hist, array, weights=None, return_indices=False):
"""Fill a ROOT histogram with a NumPy array.
Parameters
----------
hist : ROOT TH1, TH2, or TH3
The ROOT histogram to fill.
array : numpy array of shape [n_samples, n_dimensions]
The values to fill the histogram with. T... | python | {
"resource": ""
} |
q247530 | fill_profile | train | def fill_profile(profile, array, weights=None, return_indices=False):
"""Fill a ROOT profile with a NumPy array.
Parameters
----------
profile : ROOT TProfile, TProfile2D, or TProfile3D
The ROOT profile to fill.
array : numpy array of shape [n_samples, n_dimensions]
The values to fi... | python | {
"resource": ""
} |
q247531 | array2hist | train | def array2hist(array, hist, errors=None):
"""Convert a NumPy array into a ROOT histogram
Parameters
----------
array : numpy array
A 1, 2, or 3-d numpy array that will set the bin contents of the
ROOT histogram.
hist : ROOT TH1, TH2, or TH3
A ROOT histogram.
errors : num... | python | {
"resource": ""
} |
q247532 | extract_docstring | train | def extract_docstring(filename):
""" Extract a module-level docstring, if any
"""
lines = file(filename).readlines()
start_row = 0
if lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
docstring = ''
first_par = ''
tokens = tokenize.generate_tokens(iter(lines).next)
... | python | {
"resource": ""
} |
q247533 | generate_example_rst | train | def generate_example_rst(app):
""" Generate the list of examples, as well as the contents of
examples.
"""
root_dir = os.path.join(app.builder.srcdir, 'auto_examples')
example_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
try:
plot_gallery = eval(app.builder.config.... | python | {
"resource": ""
} |
q247534 | array | train | def array(arr, copy=True):
"""Convert a ROOT TArray into a NumPy array.
Parameters
----------
arr : ROOT TArray
A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS
copy : bool, optional (default=True)
If True (the default) then copy the underlying array, otherwise the
NumPy... | python | {
"resource": ""
} |
q247535 | stretch | train | def stretch(arr, fields=None, return_indices=False):
"""Stretch an array.
Stretch an array by ``hstack()``-ing multiple array fields while
preserving column names and record array structure. If a scalar field is
specified, it will be stretched along with array fields.
Parameters
----------
... | python | {
"resource": ""
} |
q247536 | dup_idx | train | def dup_idx(arr):
"""Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from ... | python | {
"resource": ""
} |
q247537 | blockwise_inner_join | train | def blockwise_inner_join(data, left, foreign_key, right,
force_repeat=None,
foreign_key_name=None):
"""Perform a blockwise inner join.
Perform a blockwise inner join from names specified in ``left`` to
``right`` via ``foreign_key``: left->foreign_key->right... | python | {
"resource": ""
} |
q247538 | Cursor.executemany | train | def executemany(self, query, args):
"""Run several data against one query
PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'.
In other form of queries, just run :meth:`execute` many times.
"""
if not args:
return
m = RE_INSERT_VALUES.matc... | python | {
"resource": ""
} |
q247539 | Binary | train | def Binary(x):
"""Return x as a binary type."""
if isinstance(x, text_type) and not (JYTHON or IRONPYTHON):
return x.encode()
return bytes(x) | python | {
"resource": ""
} |
q247540 | convert_mysql_timestamp | train | def convert_mysql_timestamp(timestamp):
"""Convert a MySQL TIMESTAMP to a Timestamp object.
MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:
>>> mysql_timestamp_converter('2007-02-25 22:32:17')
datetime.datetime(2007, 2, 25, 22, 32, 17)
MySQL < 4.1 uses a big string of numbers:
... | python | {
"resource": ""
} |
q247541 | Connection.close | train | def close(self):
"""Close the socket without sending quit message."""
stream = self._stream
if stream is None:
return
self._stream = None
stream.close() | python | {
"resource": ""
} |
q247542 | Connection.close_async | train | def close_async(self):
"""Send the quit message and close the socket"""
if self._stream is None or self._stream.closed():
self._stream = None
return
send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT)
yield self._stream.write(send_data)
self.clos... | python | {
"resource": ""
} |
q247543 | Connection.select_db | train | def select_db(self, db):
'''Set current db'''
yield self._execute_command(COMMAND.COM_INIT_DB, db)
yield self._read_ok_packet() | python | {
"resource": ""
} |
q247544 | Pool.execute | train | def execute(self, query, params=None, cursor=None):
"""Execute query in pool.
Returns future yielding closed cursor.
You can get rows, lastrowid, etc from the cursor.
:param cursor: cursor class(Cursor, DictCursor. etc.)
:return: Future of cursor
:rtype: Future
... | python | {
"resource": ""
} |
q247545 | TiledGeoJSONLayerView.get_queryset | train | def get_queryset(self):
"""
Inspired by Glen Roberton's django-geojson-tiles view
"""
self.z, self.x, self.y = self._parse_args()
nw = self.tile_coord(self.x, self.y, self.z)
se = self.tile_coord(self.x + 1, self.y + 1, self.z)
bbox = Polygon((nw, (se[0], nw[1]),
... | python | {
"resource": ""
} |
q247546 | json_encoder_with_precision | train | def json_encoder_with_precision(precision, JSONEncoderClass):
"""
Context manager to set float precision during json encoding
"""
needs_class_hack = not hasattr(json.encoder, 'FLOAT_REPR')
try:
if precision is not None:
def float_repr(o):
return format(o, '.%sf' %... | python | {
"resource": ""
} |
q247547 | datetime_to_utc | train | def datetime_to_utc(ts):
"""Convert a timestamp to UTC+0 timezone.
Returns the given datetime object converted to a date with
UTC+0 timezone. For naive datetimes, it will be assumed that
they are in UTC+0. When the timezone is wrong, UTC+0 will
be set as default (using `dateutil.tz.tzutc` object).
... | python | {
"resource": ""
} |
q247548 | unixtime_to_datetime | train | def unixtime_to_datetime(ut):
"""Convert a unixtime timestamp to a datetime object.
The function converts a timestamp in Unix format to a
datetime object. UTC timezone will also be set.
:param ut: Unix timestamp to convert
:returns: a datetime object
:raises InvalidDateError: when the given ... | python | {
"resource": ""
} |
q247549 | inspect_signature_parameters | train | def inspect_signature_parameters(callable_, excluded=None):
"""Get the parameters of a callable.
Returns a list with the signature parameters of `callable_`.
Parameters contained in `excluded` tuple will not be included
in the result.
:param callable_: callable object
:param excluded: tuple wi... | python | {
"resource": ""
} |
q247550 | find_signature_parameters | train | def find_signature_parameters(callable_, candidates,
excluded=('self', 'cls')):
"""Find on a set of candidates the parameters needed to execute a callable.
Returns a dictionary with the `candidates` found on `callable_`.
When any of the required parameters of a callable is not... | python | {
"resource": ""
} |
q247551 | find_class_properties | train | def find_class_properties(cls):
"""Find property members in a class.
Returns all the property members of a class in a list of
(name, value) pairs. Only those members defined with `property`
decorator will be included in the list.
:param cls: class where property members will be searched
:retu... | python | {
"resource": ""
} |
q247552 | coroutine | train | def coroutine(func):
"""Basic decorator to implement the coroutine pattern."""
def __start(*args, **kwargs):
"""Automatically calls next() on the internal generator function."""
__cr = func(*args, **kwargs)
next(__cr)
return __cr
return __start | python | {
"resource": ""
} |
q247553 | AstWalker._endCodeIfNeeded | train | def _endCodeIfNeeded(line, inCodeBlock):
"""Simple routine to append end code marker if needed."""
assert isinstance(line, str)
if inCodeBlock:
line = '# @endcode{0}{1}'.format(linesep, line.rstrip())
inCodeBlock = False
return line, inCodeBlock | python | {
"resource": ""
} |
q247554 | AstWalker._checkIfCode | train | def _checkIfCode(self, inCodeBlockObj):
"""Checks whether or not a given line appears to be Python code."""
while True:
line, lines, lineNum = (yield)
testLineNum = 1
currentLineNum = 0
testLine = line.strip()
lineOfCode = None
whil... | python | {
"resource": ""
} |
q247555 | AstWalker.__writeDocstring | train | def __writeDocstring(self):
"""
Runs eternally, dumping out docstring line batches as they get fed in.
Replaces original batches of docstring lines with modified versions
fed in via send.
"""
while True:
firstLineNum, lastLineNum, lines = (yield)
... | python | {
"resource": ""
} |
q247556 | AstWalker._checkMemberName | train | def _checkMemberName(name):
"""
See if a member name indicates that it should be private.
Private variables in Python (starting with a double underscore but
not ending in a double underscore) and bed lumps (variables that
are not really private but are by common convention treat... | python | {
"resource": ""
} |
q247557 | AstWalker._processMembers | train | def _processMembers(self, node, contextTag):
"""
Mark up members if they should be private.
If the name indicates it should be private or protected, apply
the appropriate Doxygen tags.
"""
restrictionLevel = self._checkMemberName(node.name)
if restrictionLevel:
... | python | {
"resource": ""
} |
q247558 | AstWalker.visit | train | def visit(self, node, **kwargs):
"""
Visit a node and extract useful information from it.
This is virtually identical to the standard version contained in
NodeVisitor. It is only overridden because we're tracking extra
information (the hierarchy of containing nodes) not preserv... | python | {
"resource": ""
} |
q247559 | AstWalker._getFullPathName | train | def _getFullPathName(self, containingNodes):
"""
Returns the full node hierarchy rooted at module name.
The list representing the full path through containing nodes
(starting with the module itself) is returned.
"""
assert isinstance(containingNodes, list)
return... | python | {
"resource": ""
} |
q247560 | AstWalker.visit_Module | train | def visit_Module(self, node, **kwargs):
"""
Handles the module-level docstring.
Process the module-level docstring and create appropriate Doxygen tags
if autobrief option is set.
"""
containingNodes=kwargs.get('containingNodes', [])
if self.options.debug:
... | python | {
"resource": ""
} |
q247561 | AstWalker.visit_Assign | train | def visit_Assign(self, node, **kwargs):
"""
Handles assignments within code.
Variable assignments in Python are used to represent interface
attributes in addition to basic variables. If an assignment appears
to be an attribute, it gets labeled as such for Doxygen. If a variabl... | python | {
"resource": ""
} |
q247562 | AstWalker.visit_Call | train | def visit_Call(self, node, **kwargs):
"""
Handles function calls within code.
Function calls in Python are used to represent interface implementations
in addition to their normal use. If a call appears to mark an
implementation, it gets labeled as such for Doxygen.
"""
... | python | {
"resource": ""
} |
q247563 | AstWalker.visit_FunctionDef | train | def visit_FunctionDef(self, node, **kwargs):
"""
Handles function definitions within code.
Process a function's docstring, keeping well aware of the function's
context and whether or not it's part of an interface definition.
"""
if self.options.debug:
stderr.... | python | {
"resource": ""
} |
q247564 | AstWalker.visit_ClassDef | train | def visit_ClassDef(self, node, **kwargs):
"""
Handles class definitions within code.
Process the docstring. Note though that in Python Class definitions
are used to define interfaces in addition to classes.
If a class definition appears to be an interface definition tag it as a... | python | {
"resource": ""
} |
q247565 | AstWalker.parseLines | train | def parseLines(self):
"""Form an AST for the code and produce a new version of the source."""
inAst = parse(''.join(self.lines), self.inFilename)
# Visit all the nodes in our tree and apply Doxygen tags to the source.
self.visit(inAst) | python | {
"resource": ""
} |
q247566 | lambda_handler | train | def lambda_handler(event, context=None, settings_name="zappa_settings"): # NoQA
"""
An AWS Lambda function which parses specific API Gateway input into a WSGI request.
The request get fed it to Django, processes the Django response, and returns that
back to the API Gateway.
"""
time_start = da... | python | {
"resource": ""
} |
q247567 | ZappaCommand.require_settings | train | def require_settings(self, args, options):
"""
Load the ZAPPA_SETTINGS as we expect it.
"""
if not options.has_key('environment'):
print(
"You must call deploy with an environment name. \n python manage.py deploy <environment>")
raise ImproperlyC... | python | {
"resource": ""
} |
q247568 | HousemateCreateForm.clean_account | train | def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
account.hou... | python | {
"resource": ""
} |
q247569 | RecurringCost.get_amount_normal | train | def get_amount_normal(self, billing_cycle):
"""Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
"""
if self.is_one_off():
... | python | {
"resource": ""
} |
q247570 | RecurringCost.get_amount_arrears_balance | train | def get_amount_arrears_balance(self, billing_cycle):
"""Get the balance of to_account at the end of billing_cycle"""
return self.to_account.balance(
transaction__date__lt=billing_cycle.date_range.lower,
) | python | {
"resource": ""
} |
q247571 | RecurringCost.get_amount_arrears_transactions | train | def get_amount_arrears_transactions(self, billing_cycle):
"""Get the sum of all transaction legs in to_account during given billing cycle"""
previous_billing_cycle = billing_cycle.get_previous()
if not previous_billing_cycle:
return Decimal(0)
return self.to_account.balance(
... | python | {
"resource": ""
} |
q247572 | RecurringCost.enact | train | def enact(self, billing_cycle, disable_if_done=True):
"""Enact this RecurringCost for the given billing cycle
This will:
- Create a RecurredCost and the relevant Transactions & Transaction Legs
- Mark this RecurringCost as disabled if this is its final billing cycle
"""
... | python | {
"resource": ""
} |
q247573 | RecurringCost.disable_if_done | train | def disable_if_done(self, commit=True):
"""Set disabled=True if we have billed all we need to
Will only have an effect on one-off costs.
"""
if self._is_billing_complete() and not self.disabled:
self.disabled = True
if commit:
self.save() | python | {
"resource": ""
} |
q247574 | RecurringCost.is_enactable | train | def is_enactable(self, as_of):
"""Can this RecurringCost be enacted"""
return \
not self.disabled and \
not self.archived and \
not self._is_finished(as_of) and \
self._is_ready(as_of) and \
not self._is_billing_complete() | python | {
"resource": ""
} |
q247575 | RecurringCost.has_enacted | train | def has_enacted(self, billing_cycle):
"""Has this recurring cost already enacted transactions for given billing cycle?"""
return RecurredCost.objects.filter(
recurring_cost=self,
billing_cycle=billing_cycle,
).exists() | python | {
"resource": ""
} |
q247576 | RecurringCost._is_ready | train | def _is_ready(self, as_of):
"""Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date):
"""
if self.... | python | {
"resource": ""
} |
q247577 | RecurringCost._is_finished | train | def _is_finished(self, as_of):
"""Have the specified number of billing cycles been completed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1]
return last_... | python | {
"resource": ""
} |
q247578 | RecurringCost._is_billing_complete | train | def _is_billing_complete(self):
"""Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency)
else:
return False | python | {
"resource": ""
} |
q247579 | RecurringCost._get_billing_cycle_number | train | def _get_billing_cycle_number(self, billing_cycle):
"""Gets the 1-indexed number of the billing cycle relative to the provided billing cycle"""
begins_before_initial_date = billing_cycle.date_range.lower < self.initial_billing_cycle.date_range.lower
if begins_before_initial_date:
rai... | python | {
"resource": ""
} |
q247580 | RecurringCostSplitQuerySet.split | train | def split(self, amount):
"""Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)
"""
split_objs... | python | {
"resource": ""
} |
q247581 | RecurredCost.make_transaction | train | def make_transaction(self):
"""Create the transaction for this RecurredCost
May only be used to create the RecurredCost's initial transaction.
Returns:
Transaction: The created transaction, also assigned to self.transaction. None if the amount is zero.
"""
if self.p... | python | {
"resource": ""
} |
q247582 | BillingCycle.populate | train | def populate(cls, as_of=None):
"""Ensure the next X years of billing cycles exist
"""
return cls._populate(as_of=as_of or date.today(), delete=True) | python | {
"resource": ""
} |
q247583 | BillingCycle._populate | train | def _populate(cls, as_of=None, delete=False):
"""Populate the table with billing cycles starting from `as_of`
Args:
as_of (date): The date at which to begin the populating
delete (bool): Should future billing cycles be deleted?
"""
billing_cycle_helper = get_bi... | python | {
"resource": ""
} |
q247584 | BillingCycle.get_next | train | def get_next(self):
"""Get the billing cycle after this one. May return None"""
return BillingCycle.objects.filter(date_range__gt=self.date_range).order_by('date_range').first() | python | {
"resource": ""
} |
q247585 | BillingCycle.get_previous | train | def get_previous(self):
"""Get the billing cycle prior to this one. May return None"""
return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last() | python | {
"resource": ""
} |
q247586 | BillingCycle.is_reconciled | train | def is_reconciled(self):
"""Have transactions been imported and reconciled for this billing cycle?"""
from hordak.models import StatementImport, StatementLine
since = datetime(
self.date_range.lower.year,
self.date_range.lower.month,
self.date_range.lower.day,... | python | {
"resource": ""
} |
q247587 | hash | train | def hash(filename, algorithm='sha256'):
"""
Hash the given filename. Unavailable in `pip<8.0.0`
"""
if incompatible:
raise Incompatible
if algorithm not in ['sha256', 'sha384', 'sha512']:
raise InvalidArguments('Algorithm {} not supported'.format(algorithm))
result = call('hash... | python | {
"resource": ""
} |
q247588 | partition | train | def partition(list_, columns=2):
"""
Break a list into ``columns`` number of columns.
"""
iter_ = iter(list_)
columns = int(columns)
rows = []
while True:
row = []
for column_number in range(1, columns + 1):
try:
value = six.next(iter_)
... | python | {
"resource": ""
} |
q247589 | DashboardView.get_balance_context | train | def get_balance_context(self):
"""Get the high level balances"""
bank_account = Account.objects.get(name='Bank')
return dict(
bank=bank_account,
retained_earnings_accounts=Account.objects.filter(parent__name='Retained Earnings'),
) | python | {
"resource": ""
} |
q247590 | DashboardView.get_accounts_context | train | def get_accounts_context(self):
"""Get the accounts we may want to display"""
income_parent = Account.objects.get(name='Income')
housemate_parent = Account.objects.get(name='Housemate Income')
expense_parent = Account.objects.get(name='Expenses')
current_liabilities_parent = Acco... | python | {
"resource": ""
} |
q247591 | _build_syl | train | def _build_syl(vowels, tone_numbers=False):
"""Builds a Pinyin syllable re pattern.
Syllables can be preceded by a middle dot (tone mark). Syllables that end
in a consonant are only valid if they aren't followed directly by a vowel
with no apostrophe in between.
The rough approach used to validate... | python | {
"resource": ""
} |
q247592 | _build_word | train | def _build_word(syl, vowels):
"""Builds a Pinyin word re pattern from a Pinyin syllable re pattern.
A word is defined as a series of consecutive valid Pinyin syllables
with optional hyphens and apostrophes interspersed. Hyphens must be
followed immediately by another valid Pinyin syllable. Apostrophes ... | python | {
"resource": ""
} |
q247593 | _build_sentence | train | def _build_sentence(word):
"""Builds a Pinyin sentence re pattern from a Pinyin word re pattern.
A sentence is defined as a series of valid Pinyin words, punctuation
(non-stops), and spaces followed by a single stop and zero or more
container-closing punctuation marks (e.g. apostrophe and brackets).
... | python | {
"resource": ""
} |
q247594 | read_file | train | def read_file(filename):
"""Read contents of the specified file.
Parameters:
-----------
filename : str
The name of the file to be read
Returns:
lines : list of str
The contents of the file, split by line
"""
infile = open(filename, 'r')
lines = infile.readlines()
infile.cl... | python | {
"resource": ""
} |
q247595 | MBAR._computeWeights | train | def _computeWeights(self, logform=False, include_nonzero=False, recalc_denom=True, return_f_k=False):
"""Compute the normalized weights corresponding to samples for the given reduced potential.
Compute the normalized weights corresponding to samples for the given reduced potential.
Also stores ... | python | {
"resource": ""
} |
q247596 | MBAR._pseudoinverse | train | def _pseudoinverse(self, A, tol=1.0e-10):
"""
Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
... | python | {
"resource": ""
} |
q247597 | MBAR._zerosamestates | train | def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 | python | {
"resource": ""
} |
q247598 | MBAR._initializeFreeEnergies | train | def _initializeFreeEnergies(self, verbose=False, method='zeros'):
"""
Compute an initial guess at the relative free energies.
OPTIONAL ARGUMENTS
verbose (boolean) - If True, will print debug information (default: False)
method (string) - Method for initializing guess at free ene... | python | {
"resource": ""
} |
q247599 | MBAR._amIdoneIterating | train | def _amIdoneIterating(self, f_k_new, relative_tolerance, iteration, maximum_iterations, print_warning, verbose):
"""
Convenience function to test whether we are done iterating, same for all iteration types
REQUIRED ARGUMENTS
f_k_new (array): new free energies
f_k (array) : o... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.