code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def lockout_response(request):
""" if we are locked out, here is the response """
if config.LOCKOUT_TEMPLATE:
context = {
'cooloff_time_seconds': config.COOLOFF_TIME,
'cooloff_time_minutes': config.COOLOFF_TIME / 60,
'failure_limit': config.FAILURE_LIMIT,
}
... | if we are locked out, here is the response | Below is the the instruction that describes the task:
### Input:
if we are locked out, here is the response
### Response:
def lockout_response(request):
""" if we are locked out, here is the response """
if config.LOCKOUT_TEMPLATE:
context = {
'cooloff_time_seconds': config.COOLOFF_TIME... |
def pop(self, key, default=_NotGiven):
"""
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised.
"""
if key in self:
self._list_remove(key)
... | If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised. | Below is the the instruction that describes the task:
### Input:
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised.
### Response:
def pop(self, key, default=_NotGiven):
"""... |
def get_timedelta(self, now=None):
"""
Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet.
"""
def datetime_to_time(timestamp):
atime = time.mktime(timestamp.timetuple())
atime += ti... | Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet. | Below is the the instruction that describes the task:
### Input:
Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet.
### Response:
def get_timedelta(self, now=None):
"""
Returns number of seconds that passed since ``s... |
def relation_get(attribute=None, unit=None, rid=None):
"""Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we as... | Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we assume we are
within the peer relation context). | Below is the the instruction that describes the task:
### Input:
Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which cas... |
def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split('\n')]
for idx, line in enumerate(lines):
... | Remote TLS processing - one address:port per line
:param data:
:param name:
:return: | Below is the the instruction that describes the task:
### Input:
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
### Response:
def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
... |
def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file):
"""Deploy the project to the development stage."""
config = _load_config(config_file)
if stage is None:
stage = config['devstage']
s3 = boto3.client('s3')
cfn = boto3.client('cloudformation')
region = _get_aws_regi... | Deploy the project to the development stage. | Below is the the instruction that describes the task:
### Input:
Deploy the project to the development stage.
### Response:
def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file):
"""Deploy the project to the development stage."""
config = _load_config(config_file)
if stage is None:
... |
def drop_incomplete_days(dataframe, shift=0):
"""truncates a given dataframe to full days only
This funtion truncates a given pandas dataframe (time series) to full days
only, thus dropping leading and tailing hours of incomplete days. Please
note that this methodology only applies to hourly time serie... | truncates a given dataframe to full days only
This funtion truncates a given pandas dataframe (time series) to full days
only, thus dropping leading and tailing hours of incomplete days. Please
note that this methodology only applies to hourly time series.
Args:
dataframe: A pandas dataframe o... | Below is the the instruction that describes the task:
### Input:
truncates a given dataframe to full days only
This funtion truncates a given pandas dataframe (time series) to full days
only, thus dropping leading and tailing hours of incomplete days. Please
note that this methodology only applies to h... |
def show_image(kwargs, call=None):
'''
Show the details from QingCloud concerning an image.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_image my-qingcloud image=trustysrvx64c
salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
salt-cloud -f show_image m... | Show the details from QingCloud concerning an image.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_image my-qingcloud image=trustysrvx64c
salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1 | Below is the the instruction that describes the task:
### Input:
Show the details from QingCloud concerning an image.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_image my-qingcloud image=trustysrvx64c
salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
salt... |
def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default) | Below is the the instruction that describes the task:
### Input:
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
### Response:
def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.... |
def build_groups(self):
"""
Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str
"""
# check if there are any groupings
if len(self.groups):
groups = []
# get the group sql for eac... | Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str | Below is the the instruction that describes the task:
### Input:
Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str
### Response:
def build_groups(self):
"""
Generates the sql for the GROUP BY portion of the query
... |
def propose_unif(self):
"""Propose a new live point by sampling *uniformly*
within the unit cube."""
u = self.unitcube.sample(rstate=self.rstate)
ax = np.identity(self.npdim)
return u, ax | Propose a new live point by sampling *uniformly*
within the unit cube. | Below is the the instruction that describes the task:
### Input:
Propose a new live point by sampling *uniformly*
within the unit cube.
### Response:
def propose_unif(self):
"""Propose a new live point by sampling *uniformly*
within the unit cube."""
u = self.unitcube.sample(rstate... |
def send_keyboard_input(text=None, key_list=None):
"""
Args:
text (None):
key_list (list):
References:
http://stackoverflow.com/questions/14788036/python-win32api-sendmesage
http://www.pinvoke.net/default.aspx/user32.sendinput
CommandLine:
python -m utool.util_c... | Args:
text (None):
key_list (list):
References:
http://stackoverflow.com/questions/14788036/python-win32api-sendmesage
http://www.pinvoke.net/default.aspx/user32.sendinput
CommandLine:
python -m utool.util_cplat --test-send_keyboard_input
Example:
>>> # DIS... | Below is the the instruction that describes the task:
### Input:
Args:
text (None):
key_list (list):
References:
http://stackoverflow.com/questions/14788036/python-win32api-sendmesage
http://www.pinvoke.net/default.aspx/user32.sendinput
CommandLine:
python -m utool.... |
def _candidate_filenames():
"""Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames.
"""
while True:
random_stub = ''.join([
random.choice(string.ascii_letters + string.digits)
... | Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames. | Below is the the instruction that describes the task:
### Input:
Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames.
### Response:
def _candidate_filenames():
"""Generates filenames of the form 'specktr... |
def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
"""
try:
if args[0].api_token is None:
raise AttributeError('Parameter api_token is required.')
except AttributeError:
... | Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured. | Below is the the instruction that describes the task:
### Input:
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
### Response:
def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly ca... |
def upload(self, filename, configuration=None, metadata=None, transcript=None):
"""
Upload new new media to the service as an attachment or from a url.
HTTP POST on /media
:param filename: Media file attached to the request.
:param configuration: VoicebaseMediaConfiguration
... | Upload new new media to the service as an attachment or from a url.
HTTP POST on /media
:param filename: Media file attached to the request.
:param configuration: VoicebaseMediaConfiguration
:param metadata: VoicebaseMediaMeta
:param transcript: attached transcript
:retur... | Below is the the instruction that describes the task:
### Input:
Upload new new media to the service as an attachment or from a url.
HTTP POST on /media
:param filename: Media file attached to the request.
:param configuration: VoicebaseMediaConfiguration
:param metadata: VoicebaseMe... |
def _read_utf(cls, data, pos, kind=None):
"""
:param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
Used to construct more informative exception messages when a decoding er... | :param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
Used to construct more informative exception messages when a decoding error occurs. | Below is the the instruction that describes the task:
### Input:
:param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
Used to construct more informative exception messages when a deco... |
def p_define(p):
""" define : DEFINE ID params defs
"""
if ENABLED:
if p[4]:
if SPACES.match(p[4][0]):
p[4][0] = p[4][0][1:]
else:
warning(p.lineno(1), "missing whitespace after the macro name")
ID_TABLE.define(p[2], args=p[3], value=p... | define : DEFINE ID params defs | Below is the the instruction that describes the task:
### Input:
define : DEFINE ID params defs
### Response:
def p_define(p):
""" define : DEFINE ID params defs
"""
if ENABLED:
if p[4]:
if SPACES.match(p[4][0]):
p[4][0] = p[4][0][1:]
else:
... |
def exclude_package(self, package):
"""Remove packages, modules, and extensions in named package"""
pfx = package + '.'
if self.packages:
self.packages = [
p for p in self.packages
if p != package and not p.startswith(pfx)
]
if se... | Remove packages, modules, and extensions in named package | Below is the the instruction that describes the task:
### Input:
Remove packages, modules, and extensions in named package
### Response:
def exclude_package(self, package):
"""Remove packages, modules, and extensions in named package"""
pfx = package + '.'
if self.packages:
sel... |
def draw_separators(self):
"""Draw the lines separating the categories on the Canvas"""
total = 1
self._timeline.create_line((0, 1, self.pixel_width, 1))
for index, (category, label) in enumerate(self._category_labels.items()):
height = label.winfo_reqheight()
sel... | Draw the lines separating the categories on the Canvas | Below is the the instruction that describes the task:
### Input:
Draw the lines separating the categories on the Canvas
### Response:
def draw_separators(self):
"""Draw the lines separating the categories on the Canvas"""
total = 1
self._timeline.create_line((0, 1, self.pixel_width, 1))
... |
def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None):
"""Representation of the parameter in html for notebook display."""
filter_ = self._current_slice_
vals = self.flat
if indices is None: indices = self._indices(filter_)
if iops is None:
ravi =... | Representation of the parameter in html for notebook display. | Below is the the instruction that describes the task:
### Input:
Representation of the parameter in html for notebook display.
### Response:
def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None):
"""Representation of the parameter in html for notebook display."""
filter_ = self... |
def get_bool_value(self, section, option, default=True):
"""Get the bool value of an option, if it exists."""
try:
return self.parser.getboolean(section, option)
except NoOptionError:
return bool(default) | Get the bool value of an option, if it exists. | Below is the the instruction that describes the task:
### Input:
Get the bool value of an option, if it exists.
### Response:
def get_bool_value(self, section, option, default=True):
"""Get the bool value of an option, if it exists."""
try:
return self.parser.getboolean(section, option)... |
def Failed(self):
"""Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds).
"""
interval = self._current_interval_sec
self._current_interval_sec = min(
self.max_interval_sec, self._current_interval_sec * self.multiplier)
return interval | Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds). | Below is the the instruction that describes the task:
### Input:
Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds).
### Response:
def Failed(self):
"""Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in sec... |
def sgd(fun, x0, data, args=(), bounds=None, batch_size=10, maxiter=5000,
updater=None, eval_obj=False, random_state=None):
"""
Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x,... | Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x, data, ...)`, where the ``eval_obj`` argument tells
``sgd`` if an objective function value is going to be returned by
``fun``.
... | Below is the the instruction that describes the task:
### Input:
Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x, data, ...)`, where the ``eval_obj`` argument tells
``sgd`` if an o... |
async def search_raw(self, term: str, limit: int = 3) -> List[dict]:
"""Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
... | Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
Returns:
A list of :class:`dict`\s which contain word information. | Below is the the instruction that describes the task:
### Input:
Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
Returns:
... |
def _tagValuedProperties(self, content_type):
"""Document properties for property files having constructs like
<ns:name>value</ns:name>
:param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS``
:return: mapping like {'property name': 'property value', ...}
... | Document properties for property files having constructs like
<ns:name>value</ns:name>
:param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS``
:return: mapping like {'property name': 'property value', ...} | Below is the the instruction that describes the task:
### Input:
Document properties for property files having constructs like
<ns:name>value</ns:name>
:param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS``
:return: mapping like {'property name': 'property valu... |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_content = properties.get("statistics", None)
if raw_content is not None:
statistics = BGPPeersStatistics.from_raw_data(raw_content)
... | Create a new model using raw API response. | Below is the the instruction that describes the task:
### Input:
Create a new model using raw API response.
### Response:
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_content = properties.get("statisti... |
def str_repr(klass):
"""
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
"""
if PY2:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self._... | Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2). | Below is the the instruction that describes the task:
### Input:
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
### Response:
def str_repr(klass):
"""
Implements string conv... |
def sigma_to_pressure(sigma, psfc, ptop):
r"""Calculate pressure from sigma values.
Parameters
----------
sigma : ndarray
The sigma levels to be converted to pressure levels.
psfc : `pint.Quantity`
The surface pressure value.
ptop : `pint.Quantity`
The pressure value a... | r"""Calculate pressure from sigma values.
Parameters
----------
sigma : ndarray
The sigma levels to be converted to pressure levels.
psfc : `pint.Quantity`
The surface pressure value.
ptop : `pint.Quantity`
The pressure value at the top of the model domain.
Returns
... | Below is the the instruction that describes the task:
### Input:
r"""Calculate pressure from sigma values.
Parameters
----------
sigma : ndarray
The sigma levels to be converted to pressure levels.
psfc : `pint.Quantity`
The surface pressure value.
ptop : `pint.Quantity`
... |
def unflatten(flat_dict, separator='_'):
"""
Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy
"""
_unflatten_asse... | Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy | Below is the the instruction that describes the task:
### Input:
Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy
### Respons... |
def recherche(self, pattern, entete):
"""Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place
"... | Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place | Below is the the instruction that describes the task:
### Input:
Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is change... |
def squash_unicode(obj):
"""coerce unicode back to bytestrings."""
if isinstance(obj,dict):
for key in obj.keys():
obj[key] = squash_unicode(obj[key])
if isinstance(key, unicode):
obj[squash_unicode(key)] = obj.pop(key)
elif isinstance(obj, list):
for ... | coerce unicode back to bytestrings. | Below is the the instruction that describes the task:
### Input:
coerce unicode back to bytestrings.
### Response:
def squash_unicode(obj):
"""coerce unicode back to bytestrings."""
if isinstance(obj,dict):
for key in obj.keys():
obj[key] = squash_unicode(obj[key])
if isinst... |
def get(self, attri, fname=None, numtype='cycNum', decayed=False):
'''
In this method all data for an entire cycle (basically the
content of an iso_massfnnnn.DAT file) or a column of data for
the associated attribute is returned.
Parameters
----------
attri : str... | In this method all data for an entire cycle (basically the
content of an iso_massfnnnn.DAT file) or a column of data for
the associated attribute is returned.
Parameters
----------
attri : string or integer
If attri is a string, attri is the cycle or name of the
... | Below is the the instruction that describes the task:
### Input:
In this method all data for an entire cycle (basically the
content of an iso_massfnnnn.DAT file) or a column of data for
the associated attribute is returned.
Parameters
----------
attri : string or integer
... |
def _initial_estimate(self, y, modelmat):
"""
Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
... | Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
---------
y : array-like of shape (n,)
... | Below is the the instruction that describes the task:
### Input:
Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameter... |
def get_full_id(self, state):
"""Return a global unique identifier for this agent instance.
It's a combination of agent_id and instance_id:
full_id = agent_id + '/' + instance_id
"""
desc = state.medium.get_descriptor()
return desc.doc_id + u"/" + unicode(desc.instance_... | Return a global unique identifier for this agent instance.
It's a combination of agent_id and instance_id:
full_id = agent_id + '/' + instance_id | Below is the the instruction that describes the task:
### Input:
Return a global unique identifier for this agent instance.
It's a combination of agent_id and instance_id:
full_id = agent_id + '/' + instance_id
### Response:
def get_full_id(self, state):
"""Return a global unique identifi... |
def validate(raw_schema, target=None, **kwargs):
"""
Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema.
"""
schema = schema_validator(raw_s... | Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema. | Below is the the instruction that describes the task:
### Input:
Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema.
### Response:
def validate(raw_sch... |
def before_request(request, tracer=None):
"""
Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a re... | Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional... | Below is the the instruction that describes the task:
### Input:
Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that... |
def size_changed(self, settings, key, user_data):
"""If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window) | If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake. | Below is the the instruction that describes the task:
### Input:
If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake.
### Response:
def size_changed(self, settings, key, user_data):
"""If the gconf var window_heig... |
def set_flag(self, value, flag, reset_val=False):
"""Set a flag to 0 if the corresponding value is 0"""
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__... | Set a flag to 0 if the corresponding value is 0 | Below is the the instruction that describes the task:
### Input:
Set a flag to 0 if the corresponding value is 0
### Response:
def set_flag(self, value, flag, reset_val=False):
"""Set a flag to 0 if the corresponding value is 0"""
if not self.__dict__[flag]:
self.__dict__[flag] = matrix... |
def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender... | Sends the sms message | Below is the the instruction that describes the task:
### Input:
Sends the sms message
### Response:
def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return ... |
def _applicationStart(self, data):
"""
Initializes the database connection pool.
:param data: <object> event data object
:return: <void>
"""
checkup = False
if "viper.mysql" in self.application.config \
and isinstance(self.application.config["vipe... | Initializes the database connection pool.
:param data: <object> event data object
:return: <void> | Below is the the instruction that describes the task:
### Input:
Initializes the database connection pool.
:param data: <object> event data object
:return: <void>
### Response:
def _applicationStart(self, data):
"""
Initializes the database connection pool.
:param data: <o... |
def set_friend_add_request(self, *, flag, approve=True, remark=None):
"""
处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None
"""
return... | 处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None | Below is the the instruction that describes the task:
### Input:
处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None
### Response:
def set_friend_add_request(self,... |
def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = Heroku(*args)
return cls.__singleton | Returns a singleton instance of the class | Below is the the instruction that describes the task:
### Input:
Returns a singleton instance of the class
### Response:
def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = Heroku(*args)
return ... |
def expire_cache(fragment_name, *args):
"""
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
"""
cache_key = make_temp... | Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop. | Below is the the instruction that describes the task:
### Input:
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
### Response:
d... |
def _check_rr_name(self, rr_name):
# type: (Optional[str]) -> bytes
'''
An internal method to check whether this ISO requires or does not
require a Rock Ridge path.
Parameters:
rr_name - The Rock Ridge name.
Returns:
The Rock Ridge name in bytes if this... | An internal method to check whether this ISO requires or does not
require a Rock Ridge path.
Parameters:
rr_name - The Rock Ridge name.
Returns:
The Rock Ridge name in bytes if this is a Rock Ridge ISO, None otherwise. | Below is the the instruction that describes the task:
### Input:
An internal method to check whether this ISO requires or does not
require a Rock Ridge path.
Parameters:
rr_name - The Rock Ridge name.
Returns:
The Rock Ridge name in bytes if this is a Rock Ridge ISO, None ... |
def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result | Fetch the next row | Below is the the instruction that describes the task:
### Input:
Fetch the next row
### Response:
def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumbe... |
def generate_GitHub_token(*, note="Doctr token for pushing to gh-pages from Travis", scopes=None, **login_kwargs):
"""
Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The toke... | Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The token created here can be revoked at
https://github.com/settings/tokens. | Below is the the instruction that describes the task:
### Input:
Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The token created here can be revoked at
https://github.com/se... |
def bool(self):
"""
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
v = self.squeeze()
... | Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean | Below is the the instruction that describes the task:
### Input:
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
### Response:... |
def to_s3_uri(code_dict):
"""Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype stri... | Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype string | Below is the the instruction that describes the task:
### Input:
Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/k... |
def unpack(regex):
"""
Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]'
"""
if is_packed(regex) and not regex.startswith('(?P<'):
retu... | Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]' | Below is the the instruction that describes the task:
### Input:
Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]'
### Response:
def unpack(regex):
""... |
def error(code, message, template):
"""A generic error handler"""
if json_requested():
return json_error(code, message)
else:
return render_template(template, message=message), code | A generic error handler | Below is the the instruction that describes the task:
### Input:
A generic error handler
### Response:
def error(code, message, template):
"""A generic error handler"""
if json_requested():
return json_error(code, message)
else:
return render_template(template, message=message), code |
def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids):
"""Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns.
"""
# Get the CampaignService.
ca... | Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns. | Below is the the instruction that describes the task:
### Input:
Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns.
### Response:
def _AddCampaignsToGroup(cl... |
def do_POST(self):
'''The POST command.
'''
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolv... | The POST command. | Below is the the instruction that describes the task:
### Input:
The POST command.
### Response:
def do_POST(self):
'''The POST command.
'''
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.r... |
def nvmlDeviceGetTopologyCommonAncestor(device1, device2):
r"""
/**
* Retrieve the common ancestor for two devices
* For all products.
* Supported on Linux only.
*
* @param device1 The identifier of the first device
* @param device2 ... | r"""
/**
* Retrieve the common ancestor for two devices
* For all products.
* Supported on Linux only.
*
* @param device1 The identifier of the first device
* @param device2 The identifier of the second device
* @param path... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Retrieve the common ancestor for two devices
* For all products.
* Supported on Linux only.
*
* @param device1 The identifier of the first device
* @param device2 ... |
def create_button(self, widget):
"""Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None
"""
btn = Qt... | Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None | Below is the the instruction that describes the task:
### Input:
Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None
###... |
def unders_to_dashes_in_keys(self) -> None:
"""Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
... | Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
dashes in their keys. | Below is the the instruction that describes the task:
### Input:
Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based forma... |
def __getDecision(self, result, multiple=False, **values):
"""
The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder ... | The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder look for, (headerString : value).
Returns: Maped result values w... | Below is the the instruction that describes the task:
### Input:
The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finde... |
def _process_group(input_group, required_group, groupname, append_subgroups=None):
"""
Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:p... | Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:param dict input_group: The dict of values of the input group
:param dict required_group: Th... | Below is the the instruction that describes the task:
### Input:
Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:param dict input_group: The... |
def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
"""Execute SQL query."""
i = 0
errcode = 0
caughte = None
while i < self.numTries:
i += 1
try:
cursor = self.connection.cursor(cursorClass)
if parameters:
errcode = cursor.execute(sql, parame... | Execute SQL query. | Below is the the instruction that describes the task:
### Input:
Execute SQL query.
### Response:
def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
"""Execute SQL query."""
i = 0
errcode = 0
caughte = None
while i < self.numTries:
i += 1
try:
cu... |
def __store_clustering_results(self, amount_clusters, leaf_blocks):
"""!
@brief Stores clustering results in a convenient way.
@param[in] amount_clusters (uint): Amount of cluster that was allocated during processing.
@param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest ce... | !
@brief Stores clustering results in a convenient way.
@param[in] amount_clusters (uint): Amount of cluster that was allocated during processing.
@param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest cells). | Below is the the instruction that describes the task:
### Input:
!
@brief Stores clustering results in a convenient way.
@param[in] amount_clusters (uint): Amount of cluster that was allocated during processing.
@param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest cells).
### R... |
def list_tickers(self, assetType):
"""Return a list of dicts of metadata tickers for all supported tickers
of the specified asset type, as well as metadata about each ticker.
This includes supported date range, the exchange the ticker is traded
on, and the currency the stock ... | Return a list of dicts of metadata tickers for all supported tickers
of the specified asset type, as well as metadata about each ticker.
This includes supported date range, the exchange the ticker is traded
on, and the currency the stock is traded on.
Tickers for unrelated... | Below is the the instruction that describes the task:
### Input:
Return a list of dicts of metadata tickers for all supported tickers
of the specified asset type, as well as metadata about each ticker.
This includes supported date range, the exchange the ticker is traded
on, and ... |
async def edit(self, **fields):
"""|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
... | |coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
represents the image being uploaded. If t... | Below is the the instruction that describes the task:
### Input:
|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` mus... |
def lookup_int(values, name=None):
"""
Lookup field which transforms the result into an integer.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field
"""
field = basic.lookup(values, name)
field.addParseAction(lambda l: int(l[0]))
ret... | Lookup field which transforms the result into an integer.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field | Below is the the instruction that describes the task:
### Input:
Lookup field which transforms the result into an integer.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field
### Response:
def lookup_int(values, name=None):
"""
Lookup field which... |
def get_method_contents(self, method):
"""
Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dicti... | Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dictionary
:return: list of swagger component dictionari... | Below is the the instruction that describes the task:
### Input:
Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: me... |
def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_rc_path())) | Create a .vacationrc file if none exists. | Below is the the instruction that describes the task:
### Input:
Create a .vacationrc file if none exists.
### Response:
def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_... |
def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
stop_reached, limit_reached, sl_stop_reached = \
self.check_order_triggers(price)
if (stop_reached, limit_reached) \
!= (sel... | Update internal state based on price triggers and the
trade event's price. | Below is the the instruction that describes the task:
### Input:
Update internal state based on price triggers and the
trade event's price.
### Response:
def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
... |
def lock_file(path):
"""File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released.
"""
with _paths_lock:
lock = _paths_to_locks.get(path)
if lock is None:
_paths_to_lo... | File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released. | Below is the the instruction that describes the task:
### Input:
File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released.
### Response:
def lock_file(path):
"""File based lock on ``path``.
Cr... |
def contains(ell, p, shell_only=False):
"""
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
"""
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else ... | Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False). | Below is the the instruction that describes the task:
### Input:
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
### Response:
def contains(ell, p, shell_only=False):
"""
Check to see whether point... |
def quilc_compile_payload(quil_program, isa, specs):
"""REST payload for :py:func:`ForestConnection._quilc_compile`"""
if not quil_program:
raise ValueError("You have attempted to compile an empty program."
" Please provide an actual program.")
if not isinstance(quil_program... | REST payload for :py:func:`ForestConnection._quilc_compile` | Below is the the instruction that describes the task:
### Input:
REST payload for :py:func:`ForestConnection._quilc_compile`
### Response:
def quilc_compile_payload(quil_program, isa, specs):
"""REST payload for :py:func:`ForestConnection._quilc_compile`"""
if not quil_program:
raise ValueError("Yo... |
def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"] | Retrieve a simple OAuth Token for use with the local http client. | Below is the the instruction that describes the task:
### Input:
Retrieve a simple OAuth Token for use with the local http client.
### Response:
def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(ur... |
def _remove_node(self, node):
"""
Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None
"""
self.graph.remove_node(node)
if node.addr ... | Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None | Below is the the instruction that describes the task:
### Input:
Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None
### Response:
def _remove_node(self, node):
... |
def remove_forwarding_rules(self, forwarding_rules):
"""
Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
"""
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.... | Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects | Below is the the instruction that describes the task:
### Input:
Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
### Response:
def remove_forwarding_rules(self, forwarding_rules):
"""
Removes existin... |
def _get_container_environment(self, **kwargs):
"""Get all the Environment variables that will be passed to the container
Certain input fields such as BatchStrategy have different values for the API vs the Environment
variables, such as SingleRecord vs SINGLE_RECORD. This method also handles th... | Get all the Environment variables that will be passed to the container
Certain input fields such as BatchStrategy have different values for the API vs the Environment
variables, such as SingleRecord vs SINGLE_RECORD. This method also handles this conversion.
Args:
**kwargs: existin... | Below is the the instruction that describes the task:
### Input:
Get all the Environment variables that will be passed to the container
Certain input fields such as BatchStrategy have different values for the API vs the Environment
variables, such as SingleRecord vs SINGLE_RECORD. This method also ... |
def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
"""
d = types.ModuleType('config')
d.__file__ = filename
with open(filename) as config_file:
exec(compile(config_file.r... | 在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常 | Below is the the instruction that describes the task:
### Input:
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
### Response:
def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,... |
def add_predicate(self, predicate_obj):
"""
Adds a predicate to the semantic layer
@type predicate_obj: L{Cpredicate}
@param predicate_obj: the predicate object
"""
if self.srl_layer is None:
self.srl_layer = Csrl()
self.root.append(self.srl_layer.... | Adds a predicate to the semantic layer
@type predicate_obj: L{Cpredicate}
@param predicate_obj: the predicate object | Below is the the instruction that describes the task:
### Input:
Adds a predicate to the semantic layer
@type predicate_obj: L{Cpredicate}
@param predicate_obj: the predicate object
### Response:
def add_predicate(self, predicate_obj):
"""
Adds a predicate to the semantic layer
... |
def noEmptyNests(node):
'''recursively make sure that no dictionaries inside node contain empty children lists '''
if type(node)==list:
for i in node:
noEmptyNests(i)
if type(node)==dict:
for i in node.values():
noEmptyNests(i)
if node["children"] == []:
... | recursively make sure that no dictionaries inside node contain empty children lists | Below is the the instruction that describes the task:
### Input:
recursively make sure that no dictionaries inside node contain empty children lists
### Response:
def noEmptyNests(node):
'''recursively make sure that no dictionaries inside node contain empty children lists '''
if type(node)==list:
... |
def MAH(z, zi, Mi, **cosmo):
""" Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
zi : float
Redshift
M... | Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
zi : float
Redshift
Mi : float
Halo mass at redshi... | Below is the the instruction that describes the task:
### Input:
Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
z... |
def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | Fill file at @path with @lines then flush all buffers
(Python and system buffers) | Below is the the instruction that describes the task:
### Input:
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
### Response:
def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""... |
def query_device_capacity(device_fd):
"""Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
inst... | Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
instance.
Thanks to the following resources for ... | Below is the the instruction that describes the task:
### Input:
Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :c... |
def get_boundaries(self):
"""
Returns just the upper and lower boundaries
[upper, lower] representing the most general positive
boundaries and the most specific lower boundaries
"""
if not self.__values_computed:
self.__compute_values()
return set(self... | Returns just the upper and lower boundaries
[upper, lower] representing the most general positive
boundaries and the most specific lower boundaries | Below is the the instruction that describes the task:
### Input:
Returns just the upper and lower boundaries
[upper, lower] representing the most general positive
boundaries and the most specific lower boundaries
### Response:
def get_boundaries(self):
"""
Returns just the upper and... |
def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | Below is the the instruction that describes the task:
### Input:
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body... |
def createBlocksFromHTML(cls, html, encoding='utf-8'):
'''
createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or... | createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or AdvancedTag (tags)
NOTE:
Results may be checked b... | Below is the the instruction that describes the task:
### Input:
createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or AdvancedT... |
def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False):
"""Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
inpu... | Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
input_size : int
input dimension
seq_len : int
sequence length
batch_size : int
... | Below is the the instruction that describes the task:
### Input:
Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
input_size : int
input dimension
... |
def format_row(self, row, key, color):
"""For a given row from the table, format it (i.e. floating
points and color if applicable).
"""
value = row[key]
if isinstance(value, bool) or value is None:
return '+' if value else ''
if not isinstance(value, Number... | For a given row from the table, format it (i.e. floating
points and color if applicable). | Below is the the instruction that describes the task:
### Input:
For a given row from the table, format it (i.e. floating
points and color if applicable).
### Response:
def format_row(self, row, key, color):
"""For a given row from the table, format it (i.e. floating
points and color if app... |
def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
import utool as ut
arr1 = np.array(arr_test)
arr2 = np.array(a... | r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list): | Below is the the instruction that describes the task:
### Input:
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
### Response:
def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray ... |
def split_tag(section):
"""
Split the JSDoc tag text (everything following the @) at the first
whitespace. Returns a tuple of (tagname, body).
"""
splitval = re.split('\s+', section, 1)
tag, body = len(splitval) > 1 and splitval or (splitval[0], '')
return tag.strip(), body.strip() | Split the JSDoc tag text (everything following the @) at the first
whitespace. Returns a tuple of (tagname, body). | Below is the the instruction that describes the task:
### Input:
Split the JSDoc tag text (everything following the @) at the first
whitespace. Returns a tuple of (tagname, body).
### Response:
def split_tag(section):
"""
Split the JSDoc tag text (everything following the @) at the first
whitespac... |
def write_atom(dest, entries, author, title, address, updated=None, link=None,
language="en"):
"""
Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : st... | Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : str
Author of the feed.
title : str
Title for the feed.
address : str
Address (domain name o... | Below is the the instruction that describes the task:
### Input:
Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : str
Author of the feed.
title : str
... |
def sys_maxfd():
"""
Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value.
"""
maxfd = None
try:
maxfd = int(resource.getrlimit(resource.RLIMIT_NOFILE)[0])
if maxfd == resource.RLIM_INFINITY: #... | Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value. | Below is the the instruction that describes the task:
### Input:
Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value.
### Response:
def sys_maxfd():
"""
Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value.
"""
maxfd... |
def dataCollector( self ):
"""
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |fro... | Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |from projexui.qt.QtCore import QMimeData, QWidget
... | Below is the the instruction that describes the task:
### Input:
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
... |
def get_class_from_file(_file, saltclass_path):
'''
Converts the absolute path to a saltclass file back to the dotted notation.
.. code-block:: python
print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass'))
# services.nginx
:param str _file: Absolu... | Converts the absolute path to a saltclass file back to the dotted notation.
.. code-block:: python
print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass'))
# services.nginx
:param str _file: Absolute path to file
:param str saltclass_path: Root to saltc... | Below is the the instruction that describes the task:
### Input:
Converts the absolute path to a saltclass file back to the dotted notation.
.. code-block:: python
print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass'))
# services.nginx
:param str _fil... |
def add_rules(self, rules: _RuleList) -> None:
"""Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor).
"""
for rule in rules:
if isinstance(rule, (tuple, list)):
asse... | Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor). | Below is the the instruction that describes the task:
### Input:
Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor).
### Response:
def add_rules(self, rules: _RuleList) -> None:
"""Appends new rules to th... |
def send(messages=None, conf=None, parse_mode=None, disable_web_page_preview=False, files=None, images=None,
captions=None, locations=None, timeout=30):
"""Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` ... | Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` instead of `send(["Hello!"])` as the latter
will *break* when I change the order of the arguments.
The `file` type is the [file object][] returned by the `open(... | Below is the the instruction that describes the task:
### Input:
Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` instead of `send(["Hello!"])` as the latter
will *break* when I change the order of the argument... |
def create_record(self, zone_name, params):
"""
Create a record
:param zone_name: Name of the zone
:param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
'target': '1.2.3.4'
"""
self.log.debug('Create record: zone: %s, id %s', zone_name,
... | Create a record
:param zone_name: Name of the zone
:param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
'target': '1.2.3.4' | Below is the the instruction that describes the task:
### Input:
Create a record
:param zone_name: Name of the zone
:param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
'target': '1.2.3.4'
### Response:
def create_record(self, zone_name, params):
"""
Create a rec... |
def create_on_demand(self,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False):
"""Create one... | Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
:param root_device_type: The type of the root device.
:typ... | Below is the the instruction that describes the task:
### Input:
Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
... |
def run(
stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None,
quiet=False, overwrite_output=False):
"""Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
c... | Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``.
input: text to be sent to... | Below is the the instruction that describes the task:
### Input:
Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``captu... |
def calculate_weights(self, measure='tfidf'):
"""
Counts word frequency and calculates tf-idf values for words in every document.
:param measure: example weights approach (can be one of ``tfidf, binary, tf``).
"""
from math import log
# TODO replace with spipy matri... | Counts word frequency and calculates tf-idf values for words in every document.
:param measure: example weights approach (can be one of ``tfidf, binary, tf``). | Below is the the instruction that describes the task:
### Input:
Counts word frequency and calculates tf-idf values for words in every document.
:param measure: example weights approach (can be one of ``tfidf, binary, tf``).
### Response:
def calculate_weights(self, measure='tfidf'):
"""
... |
def get_queryset(self):
"""
Overridde the get_queryset method to
do some validations and build the search queryset.
"""
entries = Entry.published.none()
if self.request.GET:
self.pattern = self.request.GET.get('pattern', '')
if len(self.pattern) <... | Overridde the get_queryset method to
do some validations and build the search queryset. | Below is the the instruction that describes the task:
### Input:
Overridde the get_queryset method to
do some validations and build the search queryset.
### Response:
def get_queryset(self):
"""
Overridde the get_queryset method to
do some validations and build the search queryset.
... |
def execute_watch(self, id=None, body=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html>`_
:arg id: Watch ID
:arg body: Execution control
:arg debug: indicates whether the watch should execute in debug mode
... | `<http://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html>`_
:arg id: Watch ID
:arg body: Execution control
:arg debug: indicates whether the watch should execute in debug mode | Below is the the instruction that describes the task:
### Input:
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html>`_
:arg id: Watch ID
:arg body: Execution control
:arg debug: indicates whether the watch should execute in debug mode
### Respons... |
def get_current_instruction(self) -> Dict:
"""Gets the current instruction for this GlobalState.
:return:
"""
instructions = self.environment.code.instruction_list
return instructions[self.mstate.pc] | Gets the current instruction for this GlobalState.
:return: | Below is the the instruction that describes the task:
### Input:
Gets the current instruction for this GlobalState.
:return:
### Response:
def get_current_instruction(self) -> Dict:
"""Gets the current instruction for this GlobalState.
:return:
"""
instructions = self.env... |
def plot(self,
legend=None,
width=1.5,
ladder=True,
aspect=10,
ticks=(1, 10),
match_only=None,
ax=None,
return_fig=False,
colour=None,
cmap='viridis',
default=None,
... | Hands-free plotting.
Args:
legend (Legend): The Legend to use for colours, etc.
width (int): The width of the plot, in inches. Default 1.
ladder (bool): Whether to use widths or not. Default False.
aspect (int): The aspect ratio of the plot. Default 10.
... | Below is the the instruction that describes the task:
### Input:
Hands-free plotting.
Args:
legend (Legend): The Legend to use for colours, etc.
width (int): The width of the plot, in inches. Default 1.
ladder (bool): Whether to use widths or not. Default False.
... |
def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)... | Delete a record and it's persistent identifiers. | Below is the the instruction that describes the task:
### Input:
Delete a record and it's persistent identifiers.
### Response:
def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.