positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def claim(ctx, vestingid, account, amount):
""" Claim funds from the vesting balance
"""
vesting = Vesting(vestingid)
if amount:
amount = Amount(float(amount), "BTS")
else:
amount = vesting.claimable
print_tx(
ctx.bitshares.vesting_balance_withdraw(
vesting["i... | Claim funds from the vesting balance |
def _get_bool_val(self, name):
"""
Return the value of the boolean child element having *name*, e.g.
'b', 'i', and 'smallCaps'.
"""
element = getattr(self, name)
if element is None:
return None
return element.val | Return the value of the boolean child element having *name*, e.g.
'b', 'i', and 'smallCaps'. |
def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories',
'--preserve-modification-time']
if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'):
cmdlist.extend... | Extract a CPIO archive. |
def do_clearrep(self, line):
"""clearrep Set the replication policy to default.
The default replication policy has no preferred or blocked member nodes, allows
replication and sets the preferred number of replicas to 3.
"""
self._split_args(line, 0, 0)
self._command_pro... | clearrep Set the replication policy to default.
The default replication policy has no preferred or blocked member nodes, allows
replication and sets the preferred number of replicas to 3. |
def transfer_credits(self, credits, can_use_my_credits_when_they_run_out):
"""Transfer credits to or from this client.
:param credits: An Integer representing the number of credits to transfer.
This value may be either positive if you want to allocate credits from
your account to th... | Transfer credits to or from this client.
:param credits: An Integer representing the number of credits to transfer.
This value may be either positive if you want to allocate credits from
your account to the client, or negative if you want to deduct credits
from the client back int... |
def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed:
"""Multi-file feed filtering"""
config_ = remove_node_attributes(config, ["converters", "transformations"])
feed_ = Feed(path, view={}, config=config_)
for filename, column_filters in view.items():
config_ = reroot_graph(config_,... | Multi-file feed filtering |
def target_doc(self):
"""Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict"""
if not hasatt... | Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict |
def wordrelationships(relationshiplist):
'''Generate a Word relationships file'''
# Default list of relationships
# FIXME: using string hack instead of making element
#relationships = makeelement('Relationships', nsprefix='pr')
relationships = etree.fromstring(
'<Relationships xmlns="http://... | Generate a Word relationships file |
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iter... | Pull the extend data and add it to the respective high data |
def format_from_extension(fname):
""" Tries to infer a protocol from the file extension."""
_base, ext = os.path.splitext(fname)
if not ext:
return None
try:
format = known_extensions[ext.replace('.', '')]
except KeyError:
format = None
return format | Tries to infer a protocol from the file extension. |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Add Candidate Adapter Ports to an FCP Storage Group."""
assert wait_for_completion is True # async not supported yet
# The URI is a POST operation, so we need to construct the SG URI
... | Operation: Add Candidate Adapter Ports to an FCP Storage Group. |
def find_matching(cls, message, channel):
"""
Yield ``cls`` subclasses that match message and channel
"""
return (
handler
for handler in cls._registry
if isinstance(handler, cls)
and handler.match(message, channel)
) | Yield ``cls`` subclasses that match message and channel |
def spelling(self):
"""Flag incorrectly spelled words.
Returns a list of booleans, where element at each position denotes, if the word at the same position
is spelled correctly.
"""
if not self.is_tagged(WORDS):
self.tokenize_words()
return [data[SPELLING] for... | Flag incorrectly spelled words.
Returns a list of booleans, where element at each position denotes, if the word at the same position
is spelled correctly. |
def redirect(to, headers=None, status=302,
content_type='text/html; charset=utf-8'):
'''Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status ... | Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defaults to 302
:param content_type: the content type (string) of the ... |
def loadModules(self, *modNames, **userCtx):
"""Load (optionally, compiling) pysnmp MIB modules"""
# Build a list of available modules
if not modNames:
modNames = {}
for mibSource in self._mibSources:
for modName in mibSource.listdir():
... | Load (optionally, compiling) pysnmp MIB modules |
def merge_two_dicts(x: Dict, y: Dict) -> Dict:
"""
Given two dicts, merge them into a new dict as a shallow copy, e.g.
.. code-block:: python
z = merge_two_dicts(x, y)
If you can guarantee Python 3.5, then a simpler syntax is:
.. code-block:: python
z = {**x, **y}
See http:... | Given two dicts, merge them into a new dict as a shallow copy, e.g.
.. code-block:: python
z = merge_two_dicts(x, y)
If you can guarantee Python 3.5, then a simpler syntax is:
.. code-block:: python
z = {**x, **y}
See http://stackoverflow.com/questions/38987. |
def parsecounter(table, field, parsers=(('int', int), ('float', float))):
"""
Count the number of `str` or `unicode` values under the given fields that
can be parsed as ints, floats or via custom parser functions. Return a
pair of `Counter` objects, the first mapping parser names to the number of
st... | Count the number of `str` or `unicode` values under the given fields that
can be parsed as ints, floats or via custom parser functions. Return a
pair of `Counter` objects, the first mapping parser names to the number of
strings successfully parsed, the second mapping parser names to the
number of errors... |
def register_calendar_alias(self, alias, real_name, force=False):
"""
Register an alias for a calendar.
This is useful when multiple exchanges should share a calendar, or when
there are multiple ways to refer to the same exchange.
After calling ``register_alias('alias', 'real_n... | Register an alias for a calendar.
This is useful when multiple exchanges should share a calendar, or when
there are multiple ways to refer to the same exchange.
After calling ``register_alias('alias', 'real_name')``, subsequent
calls to ``get_calendar('alias')`` will return the same re... |
def list_same(list_a, list_b):
"""
Return the items from list_b that are also on list_a
"""
result = []
for item in list_b:
if item in list_a:
result.append(item)
return result | Return the items from list_b that are also on list_a |
def do_pending_lookups(event, sender, **kwargs):
"""Handle any pending relations to the sending model.
Sent from class_prepared."""
key = (sender._meta.app_label, sender._meta.name)
for callback in pending_lookups.pop(key, []):
callback(sender) | Handle any pending relations to the sending model.
Sent from class_prepared. |
def dwelling_type(self):
"""
This method returns the dwelling type.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
r... | This method returns the dwelling type.
:return: |
def read_data(self, dstart=None, dend=None):
"""Read data from `file` and return it as Numpy array.
Parameters
----------
dstart : int, optional
Offset in bytes of the data field. By default, it is taken to
be the header size as determined from reading the header... | Read data from `file` and return it as Numpy array.
Parameters
----------
dstart : int, optional
Offset in bytes of the data field. By default, it is taken to
be the header size as determined from reading the header.
Backwards indexing with negative values is... |
def fixed_poch(a, n):
"""Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly.
Need conditional statement because scipy's impelementation of the Pochhammer
symbol is wrong for negative integer arguments. This function uses the
definition from
h... | Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly.
Need conditional statement because scipy's impelementation of the Pochhammer
symbol is wrong for negative integer arguments. This function uses the
definition from
http://functions.wolfram.com/G... |
def mthread_submit(nslave, worker_args, worker_envs):
"""
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args... | customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arguments to launch each job
this usually includes th... |
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3):
'''
Execute a shell command via VT. This is blocking and assumes that ssh
is being run
'''
if not cmd:
return '', 'No command or passphrase', 245
term = salt.utils.vt.Terminal(
cmd,
... | Execute a shell command via VT. This is blocking and assumes that ssh
is being run |
def render(self, template_name, __data=None, **kw):
'''Given a template name and template data.
Renders a template and returns as string'''
return self.template.render(template_name,
**self._vars(__data, **kw)) | Given a template name and template data.
Renders a template and returns as string |
def removeComments( self, comment = None ):
"""
Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> ... | Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> | success |
def find_ip6_by_network(self, id_network):
"""List IPv6 from network.
:param id_network: Network ipv6 identifier. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{'ip': {'id': < id >,
'id_vlan': < id_vlan >,
... | List IPv6 from network.
:param id_network: Network ipv6 identifier. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{'ip': {'id': < id >,
'id_vlan': < id_vlan >,
'block1': <block1>,
'block2': <block2>,
... |
def split_backward(layers): # pragma: no cover
"""Separate a sequence of layers' `begin_update` methods into two lists of
functions: one that computes the forward values, and the other that completes
the backward pass. The backward sequence is only populated after the forward
functions have been applie... | Separate a sequence of layers' `begin_update` methods into two lists of
functions: one that computes the forward values, and the other that completes
the backward pass. The backward sequence is only populated after the forward
functions have been applied. |
def update(self, data):
"""Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
... | Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
data (:obj:): AWS API Resource ... |
def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
... | Return a dictionary with the DataFrame data. |
def ednde_deriv(self, x, params=None):
"""Evaluate derivative of E times differential flux with respect to
E."""
params = self.params if params is None else params
return np.squeeze(self.eval_ednde_deriv(x, params, self.scale,
self.extra_pa... | Evaluate derivative of E times differential flux with respect to
E. |
def allocate(self, pool, tenant_id=None, **params):
"""Allocates a floating IP to the tenant.
You must provide a pool name or id for which you would like to
allocate a floating IP.
:returns: FloatingIp object corresponding to an allocated floating IP
"""
if not tenant_i... | Allocates a floating IP to the tenant.
You must provide a pool name or id for which you would like to
allocate a floating IP.
:returns: FloatingIp object corresponding to an allocated floating IP |
def starttls(self, ssl_context=None,
post_handshake_callback=None):
"""
Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructo... | Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the ... |
def enable_radio_button(self):
"""Enable radio button and custom value input area then set selected
radio button to 'Do not report'.
"""
for button in self.default_input_button_group.buttons():
button.setEnabled(True)
self.set_selected_radio_button()
self.cust... | Enable radio button and custom value input area then set selected
radio button to 'Do not report'. |
def _set_advertisement_interval(self, v, load=False):
"""
Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container)
If thi... | Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container)
If this variable is read-only (config: false) in the
source YANG fil... |
def get(context, request, key=None):
"""Return all registry items if key is None, otherwise try to fetch the registry key
"""
registry_records = api.get_registry_records_by_keyword(key)
# Prepare batch
size = req.get_batch_size()
start = req.get_batch_start()
batch = api.make_batch(registry... | Return all registry items if key is None, otherwise try to fetch the registry key |
def extend(self, other):
"""
Adds the values from the iterable *other* to the end of this
collection.
"""
def extend_trans(pipe):
values = list(other.__iter__(pipe)) if use_redis else other
len_self = pipe.rpush(self.key, *(self._pickle(v) for v in values)... | Adds the values from the iterable *other* to the end of this
collection. |
def update_id_counter(self):
"""Update the `id_` counter so that it doesn't grow forever.
"""
if not self.__entries:
self.__next_id = 1
else:
self.__next_id = max(self.__entries.keys()) + 1 | Update the `id_` counter so that it doesn't grow forever. |
def prepare(self, f):
"""Accept an objective function for optimization."""
self.g = autograd.grad(f)
self.h = autograd.hessian(f) | Accept an objective function for optimization. |
def report_accounts(self, path, per_region=True,
per_capita=False, pic_size=1000,
format='rst', **kwargs):
""" Generates a report to the given path for all extension
This method calls .report_accounts for all extensions
Notes
-----
... | Generates a report to the given path for all extension
This method calls .report_accounts for all extensions
Notes
-----
This looks prettier with the seaborn module (import seaborn before
calling this method)
Parameters
----------
path : string
... |
def download_archive(sources):
"""
Downloads an archive and saves locally (taken from PySMT).
"""
# last element is expected to be the local archive name
save_to = sources[-1]
# not downloading the file again if it exists
if os.path.exists(save_to):
print('not downloading {0} s... | Downloads an archive and saves locally (taken from PySMT). |
def user(self, login=None):
"""Returns a User object for the specified login name if
provided. If no login name is provided, this will return a User
object for the authenticated user.
:param str login: (optional)
:returns: :class:`User <github3.users.User>`
"""
i... | Returns a User object for the specified login name if
provided. If no login name is provided, this will return a User
object for the authenticated user.
:param str login: (optional)
:returns: :class:`User <github3.users.User>` |
def help_center_section_subscription_delete(self, section_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#delete-section-subscription"
api_path = "/api/v2/help_center/sections/{section_id}/subscriptions/{id}.json"
api_path = api_path.format(section_id=se... | https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#delete-section-subscription |
def uni(key):
'''as a crutch, we allow str-type keys, but they really should be
unicode.
'''
if isinstance(key, str):
logger.warn('assuming utf8 on: %r', key)
return unicode(key, 'utf-8')
elif isinstance(key, unicode):
return key
else:
raise NonUnicodeKeyError(ke... | as a crutch, we allow str-type keys, but they really should be
unicode. |
def getCollapseRequestsFn(self):
"""Helper function to determine which collapseRequests function to use
from L{_collapseRequests}, or None for no merging"""
# first, seek through builder, global, and the default
collapseRequests_fn = self.config.collapseRequests
if collapseReques... | Helper function to determine which collapseRequests function to use
from L{_collapseRequests}, or None for no merging |
async def raw(self, key, *, dc=None, watch=None, consistency=None):
"""Returns the specified key
Parameters:
key (str): Key to fetch
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a... | Returns the specified key
Parameters:
key (str): Key to fetch
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
... |
def flatten_all(nested_iterable):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Example::
>>> list(flatten_all([[1, 2], "abc", [3, ["x", "y", "z"]], 4]))
[1, 2, "abc", 3, "x", "y", "z", 4]
**中文文档**
将任意维度的列表压平成一维列表。
注: 使用hasattr(i,... | Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Example::
>>> list(flatten_all([[1, 2], "abc", [3, ["x", "y", "z"]], 4]))
[1, 2, "abc", 3, "x", "y", "z", 4]
**中文文档**
将任意维度的列表压平成一维列表。
注: 使用hasattr(i, "__iter__")方法做是否是可循环对象的判断, 性能要高于其他
任... |
def short_description(description):
"""
Sets 'short_description' attribute (this attribute is in exports to generate header name).
"""
def decorator(func):
if isinstance(func, property):
func = func.fget
func.short_description = description
return func
return deco... | Sets 'short_description' attribute (this attribute is in exports to generate header name). |
def random_get_int_mean(
rnd: Optional[tcod.random.Random], mi: int, ma: int, mean: int
) -> int:
"""Return a random weighted integer in the range: ``mi`` <= n <= ``ma``.
The result is affacted by calls to :any:`random_set_distribution`.
Args:
rnd (Optional[Random]): A Random instance, or None... | Return a random weighted integer in the range: ``mi`` <= n <= ``ma``.
The result is affacted by calls to :any:`random_set_distribution`.
Args:
rnd (Optional[Random]): A Random instance, or None to use the default.
low (int): The lower bound of the random range, inclusive.
high (int): T... |
def do_part(self, cmdargs, nick, target, msgtype, send, c):
"""Leaves a channel.
Prevent user from leaving the primary channel.
"""
channel = self.config['core']['channel']
botnick = self.config['core']['nick']
if not cmdargs:
# don't leave the primary chann... | Leaves a channel.
Prevent user from leaving the primary channel. |
def rot_from_vectors(start_vec, end_vec):
"""Return the rotation matrix to rotate from one vector to another."""
dot = start_vec.dot(end_vec)
# TODO: check if dot is a valid number
angle = math.acos(dot)
# TODO: check if angle is a valid number
cross = start_vec.cross(en... | Return the rotation matrix to rotate from one vector to another. |
def to_dqflags(self, bits=None, minlen=1, dtype=float, round=False):
"""Convert this `StateVector` into a `~gwpy.segments.DataQualityDict`
The `StateTimeSeries` for each bit is converted into a
`~gwpy.segments.DataQualityFlag` with the bits combined into a dict.
Parameters
----... | Convert this `StateVector` into a `~gwpy.segments.DataQualityDict`
The `StateTimeSeries` for each bit is converted into a
`~gwpy.segments.DataQualityFlag` with the bits combined into a dict.
Parameters
----------
minlen : `int`, optional, default: 1
minimum number of... |
def on_receive_append_entries(self, data):
"""If we discover a Leader with the same term — step down"""
if self.storage.term == data['term']:
self.state.to_follower() | If we discover a Leader with the same term — step down |
def get_oauth_url(self):
""" Returns the URL with OAuth params """
params = OrderedDict()
if "?" in self.url:
url = self.url[:self.url.find("?")]
for key, value in parse_qsl(urlparse(self.url).query):
params[key] = value
else:
url = se... | Returns the URL with OAuth params |
def search_regexp(self, pattern, audio_basename=None):
"""
First joins the words of the word_blocks of timestamps with space, per
audio_basename. Then matches `pattern` and calculates the index of the
word_block where the first and last word of the matched result appears
in. Then... | First joins the words of the word_blocks of timestamps with space, per
audio_basename. Then matches `pattern` and calculates the index of the
word_block where the first and last word of the matched result appears
in. Then presents the output like `search_all` method.
Note that the leadi... |
def dump_links(self, o):
"""Dump links."""
links = {
'self': url_for(
'.object_api',
bucket_id=o.bucket_id,
key=o.key,
uploadId=o.upload_id,
_external=True,
),
'object': url_for(
... | Dump links. |
def to_dict(self):
"""
Return a dict respresentation of an MNLDiscreteChoiceModel
instance.
"""
return {
'model_type': 'discretechoice',
'model_expression': self.model_expression,
'sample_size': self.sample_size,
'name': self.name,... | Return a dict respresentation of an MNLDiscreteChoiceModel
instance. |
def do_loop_turn(self):
"""Receiver daemon main loop
:return: None
"""
# Begin to clean modules
self.check_and_del_zombie_modules()
# Maybe the arbiter pushed a new configuration...
if self.watch_for_new_conf(timeout=0.05):
logger.info("I got a new ... | Receiver daemon main loop
:return: None |
def connect(self):
"""Authenticate to WOS and set the SID cookie."""
if not self._SID:
self._SID = self._auth.service.authenticate()
print('Authenticated (SID: %s)' % self._SID)
self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID})
self._auth.optio... | Authenticate to WOS and set the SID cookie. |
def finish(self):
"""Combines coverage data and sets the list of coverage objects to report on."""
# Combine all the suffix files into the data file.
self.cov.stop()
self.cov.combine()
self.cov.save() | Combines coverage data and sets the list of coverage objects to report on. |
def get_layer(pressure, *args, **kwargs):
r"""Return an atmospheric layer from upper air data with the requested bottom and depth.
This function will subset an upper air dataset to contain only the specified layer. The
bottom of the layer can be specified with a pressure or height above the surface
pre... | r"""Return an atmospheric layer from upper air data with the requested bottom and depth.
This function will subset an upper air dataset to contain only the specified layer. The
bottom of the layer can be specified with a pressure or height above the surface
pressure. The bottom defaults to the surface pres... |
def delimiters_to_re(delimiters):
"""convert delimiters to corresponding regular expressions"""
# caching
delimiters = tuple(delimiters)
if delimiters in re_delimiters:
re_tag = re_delimiters[delimiters]
else:
open_tag, close_tag = delimiters
# escape
open_tag = ''.... | convert delimiters to corresponding regular expressions |
def builder(sp, authnsign=False, wsign=False, valid_until=None, cache_duration=None, contacts=None, organization=None):
"""
Builds the metadata of the SP
:param sp: The SP data
:type sp: string
:param authnsign: authnRequestsSigned attribute
:type authnsign: string
... | Builds the metadata of the SP
:param sp: The SP data
:type sp: string
:param authnsign: authnRequestsSigned attribute
:type authnsign: string
:param wsign: wantAssertionsSigned attribute
:type wsign: string
:param valid_until: Metadata's expiry date
:t... |
def main(relation_name=None):
"""
This is the main entry point for the reactive framework. It calls
:func:`~bus.discover` to find and load all reactive handlers (e.g.,
:func:`@when <decorators.when>` decorated blocks), and then
:func:`~bus.dispatch` to trigger handlers until the queue settles out.
... | This is the main entry point for the reactive framework. It calls
:func:`~bus.discover` to find and load all reactive handlers (e.g.,
:func:`@when <decorators.when>` decorated blocks), and then
:func:`~bus.dispatch` to trigger handlers until the queue settles out.
Finally, :meth:`unitdata.kv().flush <c... |
def get_term_by_date(date):
"""
Returns a term for the datetime.date object given.
"""
year = date.year
term = None
for quarter in ('autumn', 'summer', 'spring', 'winter'):
term = get_term_by_year_and_quarter(year, quarter)
if date >= term.first_day_quarter:
break
... | Returns a term for the datetime.date object given. |
def get(self, path, query=None, redirects=True):
"""
GET request wrapper for :func:`request()`
"""
return self.request('GET', path, query, None, redirects) | GET request wrapper for :func:`request()` |
def _tupleload(l: Loader, value, type_) -> Tuple:
"""
This loads into something like Tuple[int,str]
"""
if HAS_TUPLEARGS:
args = type_.__args__
else:
args = type_.__tuple_params__
if len(args) == 2 and args[1] == ...: # Tuple[something, ...]
return tuple(l.load(i, args[0... | This loads into something like Tuple[int,str] |
def detect_encoding(filename):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
# Check for correctness of encoding.
... | Return file encoding. |
def estimated_document_count(self, **kwargs):
"""Get an estimate of the number of documents in this collection using
collection metadata.
The :meth:`estimated_document_count` method is **not** supported in a
transaction.
All optional parameters should be passed as keyword argum... | Get an estimate of the number of documents in this collection using
collection metadata.
The :meth:`estimated_document_count` method is **not** supported in a
transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
... |
def broadcast(data, root):
"""Broadcast object from one node to all other nodes.
Parameters
----------
data : any type that can be pickled
Input data, if current rank does not equal root, this can be None
root : int
Rank of the node to broadcast data from.
Returns
-------
... | Broadcast object from one node to all other nodes.
Parameters
----------
data : any type that can be pickled
Input data, if current rank does not equal root, this can be None
root : int
Rank of the node to broadcast data from.
Returns
-------
object : int
the result... |
def save_configuration_to_hdf5(register, configuration_file, name=''):
'''Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
... | Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
name : string
Additional identifier (subgroup). Useful when storing mo... |
def _process_plan_lines(self, final_line_count):
"""Process plan line rules."""
if not self._lines_seen["plan"]:
self._add_error(_("Missing a plan."))
return
if len(self._lines_seen["plan"]) > 1:
self._add_error(_("Only one plan line is permitted per file."))... | Process plan line rules. |
def focus_next_sibling(self):
"""focus next sibling of currently focussed message in thread tree"""
mid = self.get_selected_mid()
newpos = self._tree.next_sibling_position(mid)
if newpos is not None:
newpos = self._sanitize_position((newpos,))
self.body.set_focus(... | focus next sibling of currently focussed message in thread tree |
def delete(self, expected_value=None, return_values=None):
"""
Delete the item from DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that you expect.
This dictionary should have name/value pairs where the name
is the na... | Delete the item from DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that you expect.
This dictionary should have name/value pairs where the name
is the name of the attribute and the value is either the value
you are expec... |
def serial_ppmap(func, fixed_arg, var_arg_iter):
"""A serial implementation of the "partially-pickling map" function returned
by the :meth:`ParallelHelper.get_ppmap` interface. Its arguments are:
*func*
A callable taking three arguments and returning a Pickle-able value.
*fixed_arg*
Any val... | A serial implementation of the "partially-pickling map" function returned
by the :meth:`ParallelHelper.get_ppmap` interface. Its arguments are:
*func*
A callable taking three arguments and returning a Pickle-able value.
*fixed_arg*
Any value, even one that is not pickle-able.
*var_arg_iter*... |
def load_and_process_igor_model(self, marginals_file_name):
"""Set attributes by reading a generative model from IGoR marginal file.
Sets attributes PV, PdelV_given_V, PDJ, PdelJ_given_J,
PdelDldelDr_given_D, PinsVD, PinsDJ, Rvd, and Rdj.
Parameters
----------
... | Set attributes by reading a generative model from IGoR marginal file.
Sets attributes PV, PdelV_given_V, PDJ, PdelJ_given_J,
PdelDldelDr_given_D, PinsVD, PinsDJ, Rvd, and Rdj.
Parameters
----------
marginals_file_name : str
File name for a IGoR mode... |
def main(importer_class=None, args=None):
"""Entry point for import program.
If the ``args`` are provided, these should be a list of strings that will
be used instead of ``sys.argv[1:]``. This is mostly useful for testing.
"""
parser = argparse.ArgumentParser(
description='Import from exter... | Entry point for import program.
If the ``args`` are provided, these should be a list of strings that will
be used instead of ``sys.argv[1:]``. This is mostly useful for testing. |
def add_cmd_handler(self, cmd, func):
"""Adds a command handler for a command."""
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - 1 # exclude self
... | Adds a command handler for a command. |
def mapValues(self, f):
"""
Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): retur... | Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): return len(x)
>>> x.mapValues(f).collect(... |
def _make_register(self) -> BaseRegisterStore:
"""
Make the register storage.
"""
s = settings.REGISTER_STORE
store_class = import_class(s['class'])
return store_class(**s['params']) | Make the register storage. |
def deserialize(self, value, attr=None, data=None, **kwargs):
"""Deserialize ``value``.
:param value: The value to be deserialized.
:param str attr: The attribute/key in `data` to be deserialized.
:param dict data: The raw input data passed to the `Schema.load`.
:param dict kwar... | Deserialize ``value``.
:param value: The value to be deserialized.
:param str attr: The attribute/key in `data` to be deserialized.
:param dict data: The raw input data passed to the `Schema.load`.
:param dict kwargs': Field-specific keyword arguments.
:raise ValidationError: If... |
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_password(username, password) | Create a databse user. |
def find_all(self, model_class, params={}):
"""Return an list of models from the API and caches the result.
Args:
model_class (:class:`cinder_data.model.CinderModel`): A subclass of
:class:`cinder_data.model.CinderModel` of your chosen model.
params (dict, option... | Return an list of models from the API and caches the result.
Args:
model_class (:class:`cinder_data.model.CinderModel`): A subclass of
:class:`cinder_data.model.CinderModel` of your chosen model.
params (dict, optional): Description
Returns:
list: A ... |
def in_chain(cls, client, chain_id, expiration_dates=[]):
"""
fetch all option instruments in an options chain
- expiration_dates = optionally scope
"""
request_url = "https://api.robinhood.com/options/instruments/"
params = {
"chain_id": chain_id,
... | fetch all option instruments in an options chain
- expiration_dates = optionally scope |
def get_elements(html_file, tags):
"""
Extract all the elements we're interested in.
Returns a list of tuples with the attribute as first item
and the list of elements as the second item.
"""
with open(html_file) as f:
document = BeautifulSoup(f, 'html.parser')
def condition(ta... | Extract all the elements we're interested in.
Returns a list of tuples with the attribute as first item
and the list of elements as the second item. |
def infops(self, uuid):
"""
Get info per second about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
return self._clien... | Get info per second about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: |
def add_plot(self, *args, extension='pdf', **kwargs):
"""Add the current Matplotlib plot to the figure.
The plot that gets added is the one that would normally be shown when
using ``plt.show()``.
Args
----
args:
Arguments passed to plt.savefig for displaying... | Add the current Matplotlib plot to the figure.
The plot that gets added is the one that would normally be shown when
using ``plt.show()``.
Args
----
args:
Arguments passed to plt.savefig for displaying the plot.
extension : str
extension of image... |
def cancelMktDepth(self, contract: Contract, isSmartDepth=False):
"""
Unsubscribe from market depth data.
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTic... | Unsubscribe from market depth data.
Args:
contract: The exact contract object that was used to
subscribe with. |
def flightmode_menu():
'''construct flightmode menu'''
modes = mestate.mlog.flightmode_list()
ret = []
idx = 0
for (mode,t1,t2) in modes:
modestr = "%s %us" % (mode, (t2-t1))
ret.append(MPMenuCheckbox(modestr, modestr, 'mode-%u' % idx))
idx += 1
mestate.flightmode_sel... | construct flightmode menu |
def _convert_many_to_one(self, col_name, label, description,
lst_validators, filter_rel_fields,
form_props):
"""
Creates a WTForm field for many to one related fields,
will use a Select box based on a query. Will only
... | Creates a WTForm field for many to one related fields,
will use a Select box based on a query. Will only
work with SQLAlchemy interface. |
def create_plan(self, posted_plan, project):
"""CreatePlan.
Add a new plan for the team
:param :class:`<CreatePlan> <azure.devops.v5_0.work.models.CreatePlan>` posted_plan: Plan definition
:param str project: Project ID or project name
:rtype: :class:`<Plan> <azure.devops.v5_0.wo... | CreatePlan.
Add a new plan for the team
:param :class:`<CreatePlan> <azure.devops.v5_0.work.models.CreatePlan>` posted_plan: Plan definition
:param str project: Project ID or project name
:rtype: :class:`<Plan> <azure.devops.v5_0.work.models.Plan>` |
def chaincode_query(self, chaincode_name, type=CHAINCODE_LANG_GO,
function="query",
args=["a"], id=1,
secure_context=None,
confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB,
metadata=None):
"""... | {
"jsonrpc": "2.0",
"method": "query",
"params": {
"type": 1,
"chaincodeID":{
"name":"52b0d803fc395b5e34d8d4a7cd69fb6aa00099b8fabed83504ac1c5d61a425aca5b3ad3bf96643ea4fdaac132c417c37b00f88fa800de7ece387d008a76d3586"
},
... |
def hide_routemap_holder_route_map_content_set_ipv6_next_vrf_next_vrf_list_next_hop(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route... | Auto Generated Code |
def supported_currencies(self, project='moneywagon', level="full"):
"""
Returns a list of all currencies that are supported by the passed in project.
and support level. Support level can be: "block", "transaction", "address"
or "full".
"""
ret = []
if project == '... | Returns a list of all currencies that are supported by the passed in project.
and support level. Support level can be: "block", "transaction", "address"
or "full". |
def get_referenced_user(self):
"""
:rtype: BunqModel
"""
if self._user_person is not None:
return self._user_person
if self._user_company is not None:
return self._user_company
if self._user_api_key is not None:
return self._user_api... | :rtype: BunqModel |
def get_hash(self, length=HASH_LENGTH):
"""
Generate and return a hash of data that can be used as suffix of logicalId
:return: Hash of data if it was present
:rtype string
"""
data_hash = ""
if not self.data_str:
return data_hash
encoded_da... | Generate and return a hash of data that can be used as suffix of logicalId
:return: Hash of data if it was present
:rtype string |
def send_respawn(self):
"""
Respawns the player.
"""
nick = self.player.nick
self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) | Respawns the player. |
def build_sdist(sdist_directory, config_settings=None):
"""Builds an sdist, places it in sdist_directory"""
poetry = Poetry.create(".")
path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build(
Path(sdist_directory)
)
return unicode(path.name) | Builds an sdist, places it in sdist_directory |
def meanvR(self,R,t=0.,nsigma=None,deg=False,phi=0.,
epsrel=1.e-02,epsabs=1.e-05,
grid=None,gridpoints=101,returnGrid=False,
surfacemass=None,
hierarchgrid=False,nlevels=2,integrate_method='dopr54_c'):
"""
NAME:
meanvR
PURP... | NAME:
meanvR
PURPOSE:
calculate the mean vR of the velocity distribution at (R,phi)
INPUT:
R - radius at which to calculate the moment(/ro) (can be Quantity)
phi= azimuth (rad unless deg=True; can be Quantity)
t= time at which to evaluate the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.