code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def as_iso8601(self):
"""
example: 2016-08-13T00:38:05.210+00:00
"""
if self.__date is None or self.__time is None:
return None
return "20%s-%s-%sT%s:%s:%s0Z" % \
(self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], s... | example: 2016-08-13T00:38:05.210+00:00 | Below is the the instruction that describes the task:
### Input:
example: 2016-08-13T00:38:05.210+00:00
### Response:
def as_iso8601(self):
"""
example: 2016-08-13T00:38:05.210+00:00
"""
if self.__date is None or self.__time is None:
return None
return "20%s-%s-... |
async def open_async(self):
"""
Starts the host.
"""
if not self.loop:
self.loop = asyncio.get_event_loop()
await self.partition_manager.start_async() | Starts the host. | Below is the the instruction that describes the task:
### Input:
Starts the host.
### Response:
async def open_async(self):
"""
Starts the host.
"""
if not self.loop:
self.loop = asyncio.get_event_loop()
await self.partition_manager.start_async() |
def future_datetime(self, end_date='+30d', tzinfo=None):
"""
Get a DateTime object based on a random date between 1 second form now
and a given date.
Accepts date strings that can be recognized by strtotime().
:param end_date Defaults to "+30d"
:param tzinfo: timezone, i... | Get a DateTime object based on a random date between 1 second form now
and a given date.
Accepts date strings that can be recognized by strtotime().
:param end_date Defaults to "+30d"
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 11:... | Below is the the instruction that describes the task:
### Input:
Get a DateTime object based on a random date between 1 second form now
and a given date.
Accepts date strings that can be recognized by strtotime().
:param end_date Defaults to "+30d"
:param tzinfo: timezone, instance ... |
def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1,
seq_align="start", trim_seq_len=None):
"""
Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column use... | Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column used as the reponse variable.
sequence (str): Name of the column storing the DNA/RNA sequences.
k (int): Desired k-mer length.
... | Below is the the instruction that describes the task:
### Input:
Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column used as the reponse variable.
sequence (str): Name of the column sto... |
def build(capabilities, device_handler):
"Given a list of capability URI's returns <hello> message XML string"
if device_handler:
# This is used as kwargs dictionary for lxml's Element() function.
# Therefore the arg-name ("nsmap") is used as key here.
xml_namespace_k... | Given a list of capability URI's returns <hello> message XML string | Below is the the instruction that describes the task:
### Input:
Given a list of capability URI's returns <hello> message XML string
### Response:
def build(capabilities, device_handler):
"Given a list of capability URI's returns <hello> message XML string"
if device_handler:
# This is ... |
def set_logging_level(cl_args):
"""simply set verbose level based on command-line args
:param cl_args: CLI arguments
:type cl_args: dict
:return: None
:rtype: None
"""
if 'verbose' in cl_args and cl_args['verbose']:
configure(logging.DEBUG)
else:
configure(logging.INFO) | simply set verbose level based on command-line args
:param cl_args: CLI arguments
:type cl_args: dict
:return: None
:rtype: None | Below is the the instruction that describes the task:
### Input:
simply set verbose level based on command-line args
:param cl_args: CLI arguments
:type cl_args: dict
:return: None
:rtype: None
### Response:
def set_logging_level(cl_args):
"""simply set verbose level based on command-line args
:param... |
def argval(self):
""" Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered.
"""
if self.arg is None or any(x is None for x in self.arg):
return None
for x in self.arg:
if not isinstance(x, int):
... | Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered. | Below is the the instruction that describes the task:
### Input:
Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered.
### Response:
def argval(self):
""" Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be... |
def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(sel... | Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state. | Below is the the instruction that describes the task:
### Input:
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
### Response:
def urlstate(self, encryption_key):
"""
... |
def send_status(self, payload):
"""Send the daemon status and the current queue for displaying."""
answer = {}
data = []
# Get daemon status
if self.paused:
answer['status'] = 'paused'
else:
answer['status'] = 'running'
# Add current queue... | Send the daemon status and the current queue for displaying. | Below is the the instruction that describes the task:
### Input:
Send the daemon status and the current queue for displaying.
### Response:
def send_status(self, payload):
"""Send the daemon status and the current queue for displaying."""
answer = {}
data = []
# Get daemon status
... |
def get_full_name_or_username(self):
"""
Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
suppli... | Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
supplied.
:return:
``String`` containing t... | Below is the the instruction that describes the task:
### Input:
Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
... |
def set_pkg_desc(self, doc, text):
"""Set's the package's description.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if description already set.
Raises OrderError if no package previously defined.
"""
self.assert_package_exists()
if ... | Set's the package's description.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if description already set.
Raises OrderError if no package previously defined. | Below is the the instruction that describes the task:
### Input:
Set's the package's description.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if description already set.
Raises OrderError if no package previously defined.
### Response:
def set_pkg_desc(self,... |
def instance_present(name, instance_name=None, instance_id=None, image_id=None,
image_name=None, tags=None, key_name=None,
security_groups=None, user_data=None, instance_type=None,
placement=None, kernel_id=None, ramdisk_id=None,
vpc_id... | Ensure an EC2 instance is running with the given attributes and state.
name
(string) - The name of the state definition. Recommended that this
match the instance_name attribute (generally the FQDN of the instance).
instance_name
(string) - The name of the instance, generally its FQDN. ... | Below is the the instruction that describes the task:
### Input:
Ensure an EC2 instance is running with the given attributes and state.
name
(string) - The name of the state definition. Recommended that this
match the instance_name attribute (generally the FQDN of the instance).
instance_n... |
def _check_cats(cats, vtypes, df, prep, callers):
"""Only include categories in the final output if they have values.
"""
out = []
for cat in cats:
all_vals = []
for vtype in vtypes:
vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers)
all_vals.ex... | Only include categories in the final output if they have values. | Below is the the instruction that describes the task:
### Input:
Only include categories in the final output if they have values.
### Response:
def _check_cats(cats, vtypes, df, prep, callers):
"""Only include categories in the final output if they have values.
"""
out = []
for cat in cats:
... |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface... |
def wasp_snp_directory(vcf, directory, sample_name=None):
"""
Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
used.
Parameters:
-----------
vcf : str
Path to VCF file.
directory : str
Output directory. This is the directory that will hold the fi... | Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
used.
Parameters:
-----------
vcf : str
Path to VCF file.
directory : str
Output directory. This is the directory that will hold the files for
WASP.
sample_name : str
If provided, use ... | Below is the the instruction that describes the task:
### Input:
Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
used.
Parameters:
-----------
vcf : str
Path to VCF file.
directory : str
Output directory. This is the directory that will hold the fil... |
def rtm( # type: ignore
self, url: Optional[str] = None, bot_id: Optional[str] = None
) -> Iterator[events.Event]:
"""
Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`sla... | Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` | Below is the the instruction that describes the task:
### Input:
Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message`
### Response:
def rtm( # ty... |
def close(self):
"""Close socket connection"""
if self._writer:
self._writer.transport.close()
self._writer = None
self._reader = None | Close socket connection | Below is the the instruction that describes the task:
### Input:
Close socket connection
### Response:
def close(self):
"""Close socket connection"""
if self._writer:
self._writer.transport.close()
self._writer = None
self._reader = None |
def pivot_filter(pivot_array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
... | Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
... | Below is the the instruction that describes the task:
### Input:
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate ... |
def sprint(string, *args, **kwargs):
"""Safe Print (handle UnicodeEncodeErrors on some terminals)"""
try:
print(string, *args, **kwargs)
except UnicodeEncodeError:
string = string.encode('utf-8', errors='ignore')\
.decode('ascii', errors='ignore')
print(string,... | Safe Print (handle UnicodeEncodeErrors on some terminals) | Below is the the instruction that describes the task:
### Input:
Safe Print (handle UnicodeEncodeErrors on some terminals)
### Response:
def sprint(string, *args, **kwargs):
"""Safe Print (handle UnicodeEncodeErrors on some terminals)"""
try:
print(string, *args, **kwargs)
except UnicodeEncodeE... |
def get_image_label(name, default="not_found.png"):
"""Return image inside a QLabel object"""
label = QLabel()
label.setPixmap(QPixmap(get_image_path(name, default)))
return label | Return image inside a QLabel object | Below is the the instruction that describes the task:
### Input:
Return image inside a QLabel object
### Response:
def get_image_label(name, default="not_found.png"):
"""Return image inside a QLabel object"""
label = QLabel()
label.setPixmap(QPixmap(get_image_path(name, default)))
return label |
def GetZoneGroupState(self, *args, **kwargs):
"""Overrides default handling to use the global shared zone group state
cache, unless another cache is specified."""
kwargs['cache'] = kwargs.get('cache', zone_group_state_shared_cache)
return self.send_command('GetZoneGroupState', *args, **k... | Overrides default handling to use the global shared zone group state
cache, unless another cache is specified. | Below is the the instruction that describes the task:
### Input:
Overrides default handling to use the global shared zone group state
cache, unless another cache is specified.
### Response:
def GetZoneGroupState(self, *args, **kwargs):
"""Overrides default handling to use the global shared zone gro... |
def process_equations(key, value, fmt, meta):
"""Processes the attributed equations."""
if key == 'Math' and len(value) == 3:
# Process the equation
eq = _process_equation(value, fmt)
# Get the attributes and label
attrs = eq['attrs']
label = attrs[0]
if eq['is... | Processes the attributed equations. | Below is the the instruction that describes the task:
### Input:
Processes the attributed equations.
### Response:
def process_equations(key, value, fmt, meta):
"""Processes the attributed equations."""
if key == 'Math' and len(value) == 3:
# Process the equation
eq = _process_equation(va... |
def _parse_assembly(self, assembly_file):
"""Parse an assembly file in fasta format.
This is a Fasta parsing method that populates the
:py:attr:`Assembly.contigs` attribute with data for each contig in the
assembly.
Parameters
----------
assembly_file : str
... | Parse an assembly file in fasta format.
This is a Fasta parsing method that populates the
:py:attr:`Assembly.contigs` attribute with data for each contig in the
assembly.
Parameters
----------
assembly_file : str
Path to the assembly fasta file. | Below is the the instruction that describes the task:
### Input:
Parse an assembly file in fasta format.
This is a Fasta parsing method that populates the
:py:attr:`Assembly.contigs` attribute with data for each contig in the
assembly.
Parameters
----------
assembl... |
def get_class_name(self):
"""
Return the class name of the field
:rtype: string
"""
if self.class_idx_value is None:
self.class_idx_value = self.CM.get_type(self.class_idx)
return self.class_idx_value | Return the class name of the field
:rtype: string | Below is the the instruction that describes the task:
### Input:
Return the class name of the field
:rtype: string
### Response:
def get_class_name(self):
"""
Return the class name of the field
:rtype: string
"""
if self.class_idx_value is None:
self.cl... |
def _get_fs(thin_pathname):
"""
Returns the file system type (xfs, ext4) of a given device
"""
cmd = ['lsblk', '-o', 'FSTYPE', '-n', thin_pathname]
fs_return = util.subp(cmd)
return fs_return.stdout.strip() | Returns the file system type (xfs, ext4) of a given device | Below is the the instruction that describes the task:
### Input:
Returns the file system type (xfs, ext4) of a given device
### Response:
def _get_fs(thin_pathname):
"""
Returns the file system type (xfs, ext4) of a given device
"""
cmd = ['lsblk', '-o', 'FSTYPE', '-n', thin_pathnam... |
def apply_parallel(func: Callable,
data: List[Any],
cpu_cores: int = None) -> List[Any]:
"""
Apply function to list of elements.
Automatically determines the chunk size.
"""
if not cpu_cores:
cpu_cores = cpu_count()
try:
chunk_size = ceil(l... | Apply function to list of elements.
Automatically determines the chunk size. | Below is the the instruction that describes the task:
### Input:
Apply function to list of elements.
Automatically determines the chunk size.
### Response:
def apply_parallel(func: Callable,
data: List[Any],
cpu_cores: int = None) -> List[Any]:
"""
Apply function ... |
def clean(all=False, docs=False, dist=False, extra=None):
"""Clean up build files"""
run('find . -type f -name "*.py[co]" -delete')
run('find . -type d -name "__pycache__" -delete')
patterns = ['build', '*.egg-info/']
if all or docs:
patterns.append('doc/build/*')
if all or dist:
... | Clean up build files | Below is the the instruction that describes the task:
### Input:
Clean up build files
### Response:
def clean(all=False, docs=False, dist=False, extra=None):
"""Clean up build files"""
run('find . -type f -name "*.py[co]" -delete')
run('find . -type d -name "__pycache__" -delete')
patterns = ['bu... |
def _add_qualified_edge(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add an edge, then adds the opposite direction edge if it should."""
sha512 = self._add_qualified_edge_helper(
u,
v,
relation=relation,
annotations=anno... | Add an edge, then adds the opposite direction edge if it should. | Below is the the instruction that describes the task:
### Input:
Add an edge, then adds the opposite direction edge if it should.
### Response:
def _add_qualified_edge(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add an edge, then adds the opposite direction edge if it s... |
def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Rel... | Delete the Relation object when the last Entity is removed. | Below is the the instruction that describes the task:
### Input:
Delete the Relation object when the last Entity is removed.
### Response:
def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the r... |
def delete_posix_account(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a POSIX account.
Example:
>>> from google.cloud import oslogin_v1
... | Deletes a POSIX account.
Example:
>>> from google.cloud import oslogin_v1
>>>
>>> client = oslogin_v1.OsLoginServiceClient()
>>>
>>> name = client.project_path('[USER]', '[PROJECT]')
>>>
>>> client.delete_posix_account(name)
... | Below is the the instruction that describes the task:
### Input:
Deletes a POSIX account.
Example:
>>> from google.cloud import oslogin_v1
>>>
>>> client = oslogin_v1.OsLoginServiceClient()
>>>
>>> name = client.project_path('[USER]', '[PROJECT]')... |
def Mx(mt, x):
""" Return the Mx """
n = len(mt.Cx)
sum1 = 0
for j in range(x, n):
k = mt.Cx[j]
sum1 += k
return sum1 | Return the Mx | Below is the the instruction that describes the task:
### Input:
Return the Mx
### Response:
def Mx(mt, x):
""" Return the Mx """
n = len(mt.Cx)
sum1 = 0
for j in range(x, n):
k = mt.Cx[j]
sum1 += k
return sum1 |
def convert_relational(relational):
"""Convert all inequalities to >=0 form.
"""
rel = relational.rel_op
if rel in ['==', '>=', '>']:
return relational.lhs-relational.rhs
elif rel in ['<=', '<']:
return relational.rhs-relational.lhs
else:
raise Exception("The relational o... | Convert all inequalities to >=0 form. | Below is the the instruction that describes the task:
### Input:
Convert all inequalities to >=0 form.
### Response:
def convert_relational(relational):
"""Convert all inequalities to >=0 form.
"""
rel = relational.rel_op
if rel in ['==', '>=', '>']:
return relational.lhs-relational.rhs
... |
def lookup(self, row_labels, col_labels):
"""
Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
Parameters
----------
row_labels : sequenc... | Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
Parameters
----------
row_labels : sequence
The row labels to use for lookup
col_lab... | Below is the the instruction that describes the task:
### Input:
Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
Parameters
----------
row_labels : ... |
async def query(self, stmt, *args):
"""Query for a list of results.
Typical usage::
results = await self.query(...)
Or::
for row in await self.query(...)
"""
with (await self.application.db.cursor()) as cur:
await cur.execute(stmt, args)
... | Query for a list of results.
Typical usage::
results = await self.query(...)
Or::
for row in await self.query(...) | Below is the the instruction that describes the task:
### Input:
Query for a list of results.
Typical usage::
results = await self.query(...)
Or::
for row in await self.query(...)
### Response:
async def query(self, stmt, *args):
"""Query for a list of results.
... |
def press(*keys):
"""
Simulates a key-press for all the keys passed to the function
:param keys: list of keys to be pressed
:return: None
"""
for key in keys:
win32api.keybd_event(codes[key], 0, 0, 0)
release(key) | Simulates a key-press for all the keys passed to the function
:param keys: list of keys to be pressed
:return: None | Below is the the instruction that describes the task:
### Input:
Simulates a key-press for all the keys passed to the function
:param keys: list of keys to be pressed
:return: None
### Response:
def press(*keys):
"""
Simulates a key-press for all the keys passed to the function
:param keys: l... |
def _load_transition_models(self):
""" Adds models for each transition of the state """
self.transitions = []
for transition in self.state.transitions.values():
self._add_model(self.transitions, transition, TransitionModel) | Adds models for each transition of the state | Below is the the instruction that describes the task:
### Input:
Adds models for each transition of the state
### Response:
def _load_transition_models(self):
""" Adds models for each transition of the state """
self.transitions = []
for transition in self.state.transitions.values():
... |
def create(server, name, project, apikey, output, threshold, verbose):
"""Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run.
"""
if verbose:
log("Entity Matching Server: {}".format(server))... | Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run. | Below is the the instruction that describes the task:
### Input:
Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run.
### Response:
def create(server, name, project, apikey, output, threshold, verbose):
... |
def make_item_class_for_custom_generator_class(cls):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = cls.__tohu_items_name__
attr_names = cls.field_gens.keys()
return make_item_class(clsname, attr_names) | cls:
The custom generator class for which to create an item-class | Below is the the instruction that describes the task:
### Input:
cls:
The custom generator class for which to create an item-class
### Response:
def make_item_class_for_custom_generator_class(cls):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = c... |
def _evaluate_convolution(t_val, f, g, n_integral = 100, inverse_time=None, return_log=False):
"""
Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau
"""
FG = _convolution_integrand(t_val, f, g, inverse_time, return_log)
#integrate the interpolation object, return log, make neg_log
... | Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau | Below is the the instruction that describes the task:
### Input:
Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau
### Response:
def _evaluate_convolution(t_val, f, g, n_integral = 100, inverse_time=None, return_log=False):
"""
Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau
"""
F... |
def compile_loaderplugin_entry(self, spec, entry):
"""
Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the ... | Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the resolution of the
loader plugin handlers must be available in t... | Below is the the instruction that describes the task:
### Input:
Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the re... |
def decode(data):
'''
str -> bytes
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
if data.find(riemann.network.CASHADDR_PREFIX) != 0:
raise ValueError(... | str -> bytes | Below is the the instruction that describes the task:
### Input:
str -> bytes
### Response:
def decode(data):
'''
str -> bytes
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_n... |
def get_learning_rate(self, iter):
'''
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
'''
return self.init_lr * (self.gamma ** (iter // se... | Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate | Below is the the instruction that describes the task:
### Input:
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
### Response:
def get_learning_rate(self, iter):
... |
def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, len_,
add_args, lock, info_line, no_move_up=False):
"""
call the static method s... | call the static method show_stat_wrapper for each process | Below is the the instruction that describes the task:
### Input:
call the static method show_stat_wrapper for each process
### Response:
def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat... |
def dragRel(xOffset=0, yOffset=0, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True):
"""Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen, relative to its current position.
The x and y parameters detail where the mouse event happ... | Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen, relative to its current position.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the... | Below is the the instruction that describes the task:
### Input:
Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen, relative to its current position.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a ... |
def _maybe_refresh_metadata(self, wakeup=False):
"""Send a metadata request if needed.
Returns:
int: milliseconds until next refresh
"""
ttl = self.cluster.ttl()
wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0
... | Send a metadata request if needed.
Returns:
int: milliseconds until next refresh | Below is the the instruction that describes the task:
### Input:
Send a metadata request if needed.
Returns:
int: milliseconds until next refresh
### Response:
def _maybe_refresh_metadata(self, wakeup=False):
"""Send a metadata request if needed.
Returns:
int: mill... |
def serialize_operator_not_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
... | Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
</not-equals> | Below is the the instruction that describes the task:
### Input:
Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
... |
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class."""
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) | Improve the documentation of a class. | Below is the the instruction that describes the task:
### Input:
Improve the documentation of a class.
### Response:
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class."""
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubcla... |
def set_author(voevent, title=None, shortName=None, logoURL=None,
contactName=None, contactEmail=None, contactPhone=None,
contributor=None):
"""For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.... | For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.. note:: Unusually for this library,
the args here use CamelCase naming convention,
since there's a direct mapping to the ``Author.*``
attributes to which... | Below is the the instruction that describes the task:
### Input:
For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.. note:: Unusually for this library,
the args here use CamelCase naming convention,
since the... |
def new_scansock (self):
"""Return a connected socket for sending scan data to it."""
port = None
try:
self.sock.sendall("STREAM")
port = None
for dummy in range(60):
data = self.sock.recv(self.sock_rcvbuf)
i = data.find("PORT")... | Return a connected socket for sending scan data to it. | Below is the the instruction that describes the task:
### Input:
Return a connected socket for sending scan data to it.
### Response:
def new_scansock (self):
"""Return a connected socket for sending scan data to it."""
port = None
try:
self.sock.sendall("STREAM")
po... |
def process_tag(node):
"""
Recursively go through a tag's children, converting them, then
convert the tag itself.
"""
text = ''
exceptions = ['table']
for element in node.children:
if isinstance(element, NavigableString):
text += element
elif not node.name in e... | Recursively go through a tag's children, converting them, then
convert the tag itself. | Below is the the instruction that describes the task:
### Input:
Recursively go through a tag's children, converting them, then
convert the tag itself.
### Response:
def process_tag(node):
"""
Recursively go through a tag's children, converting them, then
convert the tag itself.
"""
text =... |
def write(self, group_id, handle):
'''Write this parameter group, with parameters, to a file handle.
Parameters
----------
group_id : int
The numerical ID of the group.
handle : file handle
An open, writable, binary file handle.
'''
name =... | Write this parameter group, with parameters, to a file handle.
Parameters
----------
group_id : int
The numerical ID of the group.
handle : file handle
An open, writable, binary file handle. | Below is the the instruction that describes the task:
### Input:
Write this parameter group, with parameters, to a file handle.
Parameters
----------
group_id : int
The numerical ID of the group.
handle : file handle
An open, writable, binary file handle.
###... |
def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) | Remove the given key from the cache. | Below is the the instruction that describes the task:
### Input:
Remove the given key from the cache.
### Response:
def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) |
def fit(self, X, y=None):
"""Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
"""
return self.parti... | Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self | Below is the the instruction that describes the task:
### Input:
Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
### R... |
def plot_grid(images, slices=None, axes=2,
# general figure arguments
figsize=1., rpad=0, cpad=0,
# title arguments
title=None, tfontsize=20, title_dx=0, title_dy=0,
# row arguments
rlabels=None, rfontsize=14, rfontcolor='white', rfacecolor='black',
# column arguments
clabels=None, cf... | Plot a collection of images in an arbitrarily-defined grid
Matplotlib named colors: https://matplotlib.org/examples/color/named_colors.html
Arguments
---------
images : list of ANTsImage types
image(s) to plot.
if one image, this image will be used for all grid locations.
i... | Below is the the instruction that describes the task:
### Input:
Plot a collection of images in an arbitrarily-defined grid
Matplotlib named colors: https://matplotlib.org/examples/color/named_colors.html
Arguments
---------
images : list of ANTsImage types
image(s) to plot.
if... |
def destroy_ssh_key(self, ssh_key_id):
"""
This method will delete the SSH key from your account.
"""
json = self.request('/ssh_keys/%s/destroy' % ssh_key_id, method='GET')
status = json.get('status')
return status | This method will delete the SSH key from your account. | Below is the the instruction that describes the task:
### Input:
This method will delete the SSH key from your account.
### Response:
def destroy_ssh_key(self, ssh_key_id):
"""
This method will delete the SSH key from your account.
"""
json = self.request('/ssh_keys/%s/destroy' % ss... |
def output(self, out_file):
"""Write the converted entries to out_file"""
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('events: ns\n')
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
self._o... | Write the converted entries to out_file | Below is the the instruction that describes the task:
### Input:
Write the converted entries to out_file
### Response:
def output(self, out_file):
"""Write the converted entries to out_file"""
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('event... |
def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
first_run,
last_run,
last_success,
depends_on,
error_count,
... | return all the app_names and their values as tuples | Below is the the instruction that describes the task:
### Input:
return all the app_names and their values as tuples
### Response:
def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
... |
def substitute_partner(self, state, partners_recp, recp, alloc_id):
'''
Establish the partnership to recp and, when it is successfull
remove partner with recipient partners_recp.
Use with caution: The partner which we are removing is not notified
in any way, so he still keeps li... | Establish the partnership to recp and, when it is successfull
remove partner with recipient partners_recp.
Use with caution: The partner which we are removing is not notified
in any way, so he still keeps link in his description. The correct
usage of this method requires calling it from... | Below is the the instruction that describes the task:
### Input:
Establish the partnership to recp and, when it is successfull
remove partner with recipient partners_recp.
Use with caution: The partner which we are removing is not notified
in any way, so he still keeps link in his descripti... |
def do_info(self, arg, arguments):
"""
::
Usage:
info [--all]
Options:
--all -a more extensive information
Prints some internal information about the shell
"""
if arguments["--all"]:
Console.ok(... | ::
Usage:
info [--all]
Options:
--all -a more extensive information
Prints some internal information about the shell | Below is the the instruction that describes the task:
### Input:
::
Usage:
info [--all]
Options:
--all -a more extensive information
Prints some internal information about the shell
### Response:
def do_info(self, arg, arguments):
... |
def get_power_state(self, userid):
"""Get power status of a z/VM instance."""
LOG.debug('Querying power stat of %s' % userid)
requestData = "PowerVM " + userid + " status"
action = "query power state of '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
... | Get power status of a z/VM instance. | Below is the the instruction that describes the task:
### Input:
Get power status of a z/VM instance.
### Response:
def get_power_state(self, userid):
"""Get power status of a z/VM instance."""
LOG.debug('Querying power stat of %s' % userid)
requestData = "PowerVM " + userid + " status"
... |
def makepipecomponent(idf, pname):
"""make a pipe component
generate inlet outlet names"""
apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname)
apipe.Inlet_Node_Name = "%s_inlet" % (pname,)
apipe.Outlet_Node_Name = "%s_outlet" % (pname,)
return apipe | make a pipe component
generate inlet outlet names | Below is the the instruction that describes the task:
### Input:
make a pipe component
generate inlet outlet names
### Response:
def makepipecomponent(idf, pname):
"""make a pipe component
generate inlet outlet names"""
apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname)
apipe.Inlet_... |
def update_state(self):
""" Update state with latest info from Wink API. """
response = self.api_interface.get_device_state(self, id_override=self.parent_id(),
type_override=self.parent_object_type())
self._update_state_from_response(res... | Update state with latest info from Wink API. | Below is the the instruction that describes the task:
### Input:
Update state with latest info from Wink API.
### Response:
def update_state(self):
""" Update state with latest info from Wink API. """
response = self.api_interface.get_device_state(self, id_override=self.parent_id(),
... |
def set_main(key, value, path=MAIN_CF):
'''
Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq
'''
pairs, conf_list = _parse_main(path)
new_conf =... | Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq | Below is the the instruction that describes the task:
### Input:
Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq
### Response:
def set_main(key, value, path=MA... |
def update(self):
"""
Get virtual size of current process by reading the process' stat file.
This should work for Linux.
"""
try:
stat = open('/proc/self/stat')
status = open('/proc/self/status')
except IOError: # pragma: no cover
retur... | Get virtual size of current process by reading the process' stat file.
This should work for Linux. | Below is the the instruction that describes the task:
### Input:
Get virtual size of current process by reading the process' stat file.
This should work for Linux.
### Response:
def update(self):
"""
Get virtual size of current process by reading the process' stat file.
This should ... |
def plot_fit(self):
"""
Add the fit to the plot.
"""
self.plt.plot(*self.fit.fit, **self.options['fit']) | Add the fit to the plot. | Below is the the instruction that describes the task:
### Input:
Add the fit to the plot.
### Response:
def plot_fit(self):
"""
Add the fit to the plot.
"""
self.plt.plot(*self.fit.fit, **self.options['fit']) |
async def recv_multipart(self):
"""
Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result.
"""
if not self._sockets:
return []
results = []
async def recv_and_store(socke... | Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result. | Below is the the instruction that describes the task:
### Input:
Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result.
### Response:
async def recv_multipart(self):
"""
Read from all the associated sockets.
... |
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', da... | Transform a QuantumChannel to the Kraus representation. | Below is the the instruction that describes the task:
### Input:
Transform a QuantumChannel to the Kraus representation.
### Response:
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinesp... |
def get_class_field(cls, field_name):
"""
Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form)
"""
if not cls.has_field(field_name):
raise AttributeError('"%s" is not a field for the model "%s"' %
... | Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form) | Below is the the instruction that describes the task:
### Input:
Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form)
### Response:
def get_class_field(cls, field_name):
"""
Return the field object with the given name (for the class, the f... |
def get_reference_lines(docbody,
ref_sect_start_line,
ref_sect_end_line,
ref_sect_title,
ref_line_marker_ptn,
title_marker_same_line):
"""After the reference section of a document has been identif... | After the reference section of a document has been identified, and the
first and last lines of the reference section have been recorded, this
function is called to take the reference lines out of the document body.
The document's reference lines are returned in a list of strings whereby
each... | Below is the the instruction that describes the task:
### Input:
After the reference section of a document has been identified, and the
first and last lines of the reference section have been recorded, this
function is called to take the reference lines out of the document body.
The document's ... |
def _set_ra_dns_server(self, v, load=False):
"""
Setter method for ra_dns_server, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/ra_dns_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ra_dns_server is considered as ... | Setter method for ra_dns_server, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/ra_dns_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ra_dns_server is considered as a private
method. Backends looking to populate this v... | Below is the the instruction that describes the task:
### Input:
Setter method for ra_dns_server, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/ra_dns_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ra_dns_server is co... |
def obo(self):
"""str: the ontology serialized in obo format.
"""
meta = self._obo_meta()
meta = [meta] if meta else []
newline = "\n\n" if six.PY3 else "\n\n".encode('utf-8')
try: # if 'namespace' in self.meta:
return newline.join( meta + [
r... | str: the ontology serialized in obo format. | Below is the the instruction that describes the task:
### Input:
str: the ontology serialized in obo format.
### Response:
def obo(self):
"""str: the ontology serialized in obo format.
"""
meta = self._obo_meta()
meta = [meta] if meta else []
newline = "\n\n" if six.PY3 else... |
def set_const(const, val):
'''Convenience wrapper to reliably set the value of a constant from
outside of package scope'''
try:
cur = getattr(_c, const)
except AttributeError:
raise FSQEnvError(errno.ENOENT, u'no such constant:'\
u' {0}'.format(const))
ex... | Convenience wrapper to reliably set the value of a constant from
outside of package scope | Below is the the instruction that describes the task:
### Input:
Convenience wrapper to reliably set the value of a constant from
outside of package scope
### Response:
def set_const(const, val):
'''Convenience wrapper to reliably set the value of a constant from
outside of package scope'''
t... |
def context_factory(apply_globally=False, api=None):
"""A decorator that registers a single hug context factory"""
def decorator(context_factory_):
if apply_globally:
hug.defaults.context_factory = context_factory_
else:
apply_to_api = hug.API(api) if api else hug.api.fro... | A decorator that registers a single hug context factory | Below is the the instruction that describes the task:
### Input:
A decorator that registers a single hug context factory
### Response:
def context_factory(apply_globally=False, api=None):
"""A decorator that registers a single hug context factory"""
def decorator(context_factory_):
if apply_globall... |
def fetch_token(self):
"""Gains token from secure backend service.
:return: Token formatted for Cocaine protocol header.
"""
grant_type = 'client_credentials'
channel = yield self._tvm.ticket_full(
self._client_id, self._client_secret, grant_type, {})
ticket... | Gains token from secure backend service.
:return: Token formatted for Cocaine protocol header. | Below is the the instruction that describes the task:
### Input:
Gains token from secure backend service.
:return: Token formatted for Cocaine protocol header.
### Response:
def fetch_token(self):
"""Gains token from secure backend service.
:return: Token formatted for Cocaine protocol he... |
def spinn5_local_eth_coord(x, y, w, h, root_x=0, root_y=0):
"""Get the coordinates of a chip's local ethernet connected chip.
Returns the coordinates of the ethernet connected chip on the same board as
the supplied chip.
.. note::
This function assumes the system is constructed from SpiNN-5 bo... | Get the coordinates of a chip's local ethernet connected chip.
Returns the coordinates of the ethernet connected chip on the same board as
the supplied chip.
.. note::
This function assumes the system is constructed from SpiNN-5 boards
.. warning::
In general, applications should int... | Below is the the instruction that describes the task:
### Input:
Get the coordinates of a chip's local ethernet connected chip.
Returns the coordinates of the ethernet connected chip on the same board as
the supplied chip.
.. note::
This function assumes the system is constructed from SpiNN-5 ... |
def _writepydoc(doc, *args):
"""create pydoc html pages
doc -- destination directory for documents
*args -- modules run thru pydoc
"""
ok = True
if not os.path.isdir(doc):
os.makedirs(doc)
if os.path.curdir not in sys.path:
sys.path.append(os.path.curdir)
for f in a... | create pydoc html pages
doc -- destination directory for documents
*args -- modules run thru pydoc | Below is the the instruction that describes the task:
### Input:
create pydoc html pages
doc -- destination directory for documents
*args -- modules run thru pydoc
### Response:
def _writepydoc(doc, *args):
"""create pydoc html pages
doc -- destination directory for documents
*args -- modules r... |
def get_context(self, arr, expr, context):
"""
Returns a context dictionary for use in evaluating the expression.
:param arr: The input array.
:param expr: The input expression.
:param context: Evaluation context.
"""
expression_names = [x for x in self.get_expr... | Returns a context dictionary for use in evaluating the expression.
:param arr: The input array.
:param expr: The input expression.
:param context: Evaluation context. | Below is the the instruction that describes the task:
### Input:
Returns a context dictionary for use in evaluating the expression.
:param arr: The input array.
:param expr: The input expression.
:param context: Evaluation context.
### Response:
def get_context(self, arr, expr, context):
... |
def assign_aromatic(mol):
"""Assign aromatic ring
sp2 atom:
pi=1 -> +1
N, O, S, C- -> +2
>C=O, B, C+ -> 0
sp3 atom -> not aromatic
sum of the score satisfies 4n+2 -> aromatic
"""
mol.require("Valence")
mol.require("MinifiedRing")
for ring in mol.rings:
pi_cnt = 0
... | Assign aromatic ring
sp2 atom:
pi=1 -> +1
N, O, S, C- -> +2
>C=O, B, C+ -> 0
sp3 atom -> not aromatic
sum of the score satisfies 4n+2 -> aromatic | Below is the the instruction that describes the task:
### Input:
Assign aromatic ring
sp2 atom:
pi=1 -> +1
N, O, S, C- -> +2
>C=O, B, C+ -> 0
sp3 atom -> not aromatic
sum of the score satisfies 4n+2 -> aromatic
### Response:
def assign_aromatic(mol):
"""Assign aromatic ring
sp2 atom... |
def login(self, user_id, password, svctype = "Android NDrive App ver", auth = 0):
"""Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
... | Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
Remarks:
self.cookie is a dictionary with 5 keys: path, domain, NID_AUT, ni... | Below is the the instruction that describes the task:
### Input:
Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
Remarks:
... |
def get_image_attribute(self, image_id, attribute='launchPermission'):
"""
Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need informa... | Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need information about.
Valid choices are:
* launch... | Below is the the instruction that describes the task:
### Input:
Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need information about.
... |
def _get_sorted_cond_keys(self, keys_list):
"""
This function returns only the elements starting with
'analysisservice-' in 'keys_list'. The returned list is sorted by the
index appended to the end of each element
"""
# The names can be found in reflexrulewidget.pt inside... | This function returns only the elements starting with
'analysisservice-' in 'keys_list'. The returned list is sorted by the
index appended to the end of each element | Below is the the instruction that describes the task:
### Input:
This function returns only the elements starting with
'analysisservice-' in 'keys_list'. The returned list is sorted by the
index appended to the end of each element
### Response:
def _get_sorted_cond_keys(self, keys_list):
""... |
def get_slice(self, start_index=None, stop_index=None, as_list=False):
"""
For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
... | For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
start or stop index is None then will include from the first or last element, similar to st... | Below is the the instruction that describes the task:
### Input:
For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
start or stop index is... |
def _unary_op(name, doc="unary operator"):
""" Create a method for given unary operator """
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = doc
return _ | Create a method for given unary operator | Below is the the instruction that describes the task:
### Input:
Create a method for given unary operator
### Response:
def _unary_op(name, doc="unary operator"):
""" Create a method for given unary operator """
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = d... |
def create_report(outdirname, report_filename, **kwargs):
"""Creates a LaTeX report.
:param report_filename: the name of the file.
:param outdirname: the name of the output directory.
:type report_filename: str
:type outdirname: str
"""
# Checking the required variables
if "steps" in ... | Creates a LaTeX report.
:param report_filename: the name of the file.
:param outdirname: the name of the output directory.
:type report_filename: str
:type outdirname: str | Below is the the instruction that describes the task:
### Input:
Creates a LaTeX report.
:param report_filename: the name of the file.
:param outdirname: the name of the output directory.
:type report_filename: str
:type outdirname: str
### Response:
def create_report(outdirname, report_filename,... |
def namedb_namespace_fields_check( namespace_rec ):
"""
Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec
"""
assert namespace_rec.has_key('namespace_id'), "BUG: na... | Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec | Below is the the instruction that describes the task:
### Input:
Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec
### Response:
def namedb_namespace_fields_check( namespace_re... |
def sms_recipients(self):
"""Returns a list of recipients subscribed to receive SMS's
for this "notifications" class.
See also: edc_auth.UserProfile.
"""
sms_recipients = []
UserProfile = django_apps.get_model("edc_auth.UserProfile")
for user_profile in UserProfi... | Returns a list of recipients subscribed to receive SMS's
for this "notifications" class.
See also: edc_auth.UserProfile. | Below is the the instruction that describes the task:
### Input:
Returns a list of recipients subscribed to receive SMS's
for this "notifications" class.
See also: edc_auth.UserProfile.
### Response:
def sms_recipients(self):
"""Returns a list of recipients subscribed to receive SMS's
... |
def _is_logged_in(self):
""" Check whether or not the user is logged in. """
# if the user has not logged in in 24 hours, relogin
if not self._http._has_session() or datetime.utcnow() >= self._lastlogin + timedelta(hours=24):
return self._login()
else:
return {} | Check whether or not the user is logged in. | Below is the the instruction that describes the task:
### Input:
Check whether or not the user is logged in.
### Response:
def _is_logged_in(self):
""" Check whether or not the user is logged in. """
# if the user has not logged in in 24 hours, relogin
if not self._http._has_session() or da... |
def filter_ast(module_ast):
"""
Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps
"""
def node_predic... | Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps | Below is the the instruction that describes the task:
### Input:
Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all cap... |
def starting_offset(source_code, offset):
"""Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where... | Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where starting_offset is the offset returned by this f... | Below is the the instruction that describes the task:
### Input:
Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[... |
def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
R... | Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
Returns:
If failed to retrieve progress, ... | Below is the the instruction that describes the task:
### Input:
Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the fun... |
def data_filler_user_agent(self, number_of_rows, conn):
'''creates and fills the table with user agent data
'''
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE user_agent(id TEXT PRIMARY KEY,
ip TEXT, countrycode TEXT, useragent TEXT)
''')
conn.com... | creates and fills the table with user agent data | Below is the the instruction that describes the task:
### Input:
creates and fills the table with user agent data
### Response:
def data_filler_user_agent(self, number_of_rows, conn):
'''creates and fills the table with user agent data
'''
cursor = conn.cursor()
cursor.execute('''
... |
def model_argmax(sess, x, predictions, samples, feed=None):
"""
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed:... | Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed: An optional dictionary that is appended to the feeding
d... | Below is the the instruction that describes the task:
### Input:
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed... |
def logmid_n(max_n, ratio=1/4.0, nsteps=15):
"""
Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has... | Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has benefits in hurst_rs, because it cuts away both very... | Below is the the instruction that describes the task:
### Input:
Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
T... |
def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 9999)
re... | An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True | Below is the the instruction that describes the task:
### Input:
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
### Response:
def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
... |
def takeStereoScreenshot(self, pchPreviewFilename, pchVRFilename):
"""
Tells the compositor to take an internal screenshot of
type VRScreenshotType_Stereo. It will take the current
submitted scene textures of the running application and
write them into the preview image and a ... | Tells the compositor to take an internal screenshot of
type VRScreenshotType_Stereo. It will take the current
submitted scene textures of the running application and
write them into the preview image and a side-by-side file
for the VR image.
This is similar to request screen... | Below is the the instruction that describes the task:
### Input:
Tells the compositor to take an internal screenshot of
type VRScreenshotType_Stereo. It will take the current
submitted scene textures of the running application and
write them into the preview image and a side-by-side file
... |
def concretize_read_addr(self, addr, strategies=None):
"""
Concretizes an address meant for reading.
:param addr: An expression for the address.
:param strategies: A list of concretization strategies (to override the default).
:returns: ... | Concretizes an address meant for reading.
:param addr: An expression for the address.
:param strategies: A list of concretization strategies (to override the default).
:returns: A list of concrete addresses. | Below is the the instruction that describes the task:
### Input:
Concretizes an address meant for reading.
:param addr: An expression for the address.
:param strategies: A list of concretization strategies (to override the default).
:returns: A list... |
def get_method(self, name):
"""
Get registered method callend `name`.
"""
try:
return self.funcs[name]
except KeyError:
try:
return self.instance._get_method(name)
except AttributeError:
return SimpleXMLRPCServer... | Get registered method callend `name`. | Below is the the instruction that describes the task:
### Input:
Get registered method callend `name`.
### Response:
def get_method(self, name):
"""
Get registered method callend `name`.
"""
try:
return self.funcs[name]
except KeyError:
try:
... |
def get_logger(name):
"""Get a logging instance we can use."""
import logging
import sys
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
shandler = logging.StreamHandler(sys.stdout)
fmt = ""
fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():'
fmt += '%(linen... | Get a logging instance we can use. | Below is the the instruction that describes the task:
### Input:
Get a logging instance we can use.
### Response:
def get_logger(name):
"""Get a logging instance we can use."""
import logging
import sys
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
shandler = logging.Strea... |
def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):
"""Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary.
"""
if uf["location"].startswith("toilfs:") or uf["location"].startswith("_:"):
return
if u... | Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary. | Below is the the instruction that describes the task:
### Input:
Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary.
### Response:
def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):
"""Update a file object so that ... |
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError | Add an entry to the system crontab. | Below is the the instruction that describes the task:
### Input:
Add an entry to the system crontab.
### Response:
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.