code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def switch_mode(self, new_mode):
""" Explicitly switch the Bus Pirate mode
:param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
"""
packet = bytearray()
packet.append(new_mode)
self.device.write(packet)
possible_responses = {
sel... | Explicitly switch the Bus Pirate mode
:param new_mode: The mode to switch to. Use the buspirate.MODE_* constants | Below is the the instruction that describes the task:
### Input:
Explicitly switch the Bus Pirate mode
:param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
### Response:
def switch_mode(self, new_mode):
""" Explicitly switch the Bus Pirate mode
:param new_mode: The m... |
def _tasks_to_reinsert(tasks, transactional):
"""Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not.
"""
if transactional:
return tasks
return [task for task in tasks if not task.was_enqueued] | Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not. | Below is the the instruction that describes the task:
### Input:
Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not.
### Response:
def _tasks_to_reinsert(tasks, transactional):
"""Return a list containing the tasks ... |
def tty(tty_reload):
"""Load colors in tty."""
tty_script = os.path.join(CACHE_DIR, "colors-tty.sh")
term = os.environ.get("TERM")
if tty_reload and term == "linux":
subprocess.Popen(["sh", tty_script]) | Load colors in tty. | Below is the the instruction that describes the task:
### Input:
Load colors in tty.
### Response:
def tty(tty_reload):
"""Load colors in tty."""
tty_script = os.path.join(CACHE_DIR, "colors-tty.sh")
term = os.environ.get("TERM")
if tty_reload and term == "linux":
subprocess.Popen(["sh", t... |
def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the... | Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSErro... | Below is the the instruction that describes the task:
### Input:
Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
... |
def _create_token_set(self):
"""Creates a token set of all tokens in the index using `lunr.TokenSet`
"""
self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys()))) | Creates a token set of all tokens in the index using `lunr.TokenSet` | Below is the the instruction that describes the task:
### Input:
Creates a token set of all tokens in the index using `lunr.TokenSet`
### Response:
def _create_token_set(self):
"""Creates a token set of all tokens in the index using `lunr.TokenSet`
"""
self.token_set = TokenSet.from_list(so... |
def run(self):
"""Run checker."""
def split(module):
"""Split module into submodules."""
return tuple(module.split("."))
def modcmp(lib=(), test=()):
"""Compare import modules."""
if len(lib) > len(test):
return False
... | Run checker. | Below is the the instruction that describes the task:
### Input:
Run checker.
### Response:
def run(self):
"""Run checker."""
def split(module):
"""Split module into submodules."""
return tuple(module.split("."))
def modcmp(lib=(), test=()):
"""Compare ... |
def rebase(self, qemu_img, base_image):
"""
Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image
"""
if not os.path.exists(base_image):
raise FileNotFoundError(base_imag... | Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image | Below is the the instruction that describes the task:
### Input:
Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image
### Response:
def rebase(self, qemu_img, base_image):
"""
Rebase a linked c... |
def cleanup(self):
"""Remove any created temp paths"""
for path in self.paths:
if isinstance(path, tuple):
os.close(path[0])
os.unlink(path[1])
else:
shutil.rmtree(path)
self.paths = [] | Remove any created temp paths | Below is the the instruction that describes the task:
### Input:
Remove any created temp paths
### Response:
def cleanup(self):
"""Remove any created temp paths"""
for path in self.paths:
if isinstance(path, tuple):
os.close(path[0])
os.unlink(path[1])
... |
def load_cookies(self):
"""
Load any stored cookies for the plugin that have not expired.
:return: list of the restored cookie names
"""
if not self.session or not self.cache:
raise RuntimeError("Cannot loaded cached cookies in unbound plugin")
restored = []... | Load any stored cookies for the plugin that have not expired.
:return: list of the restored cookie names | Below is the the instruction that describes the task:
### Input:
Load any stored cookies for the plugin that have not expired.
:return: list of the restored cookie names
### Response:
def load_cookies(self):
"""
Load any stored cookies for the plugin that have not expired.
:return... |
def analyze(self, scratch, **kwargs):
"""Run and return the results from the Animation plugin."""
results = Counter()
for script in self.iter_scripts(scratch):
gen = self.iter_blocks(script.blocks)
name = 'start'
level = None
while name != '':
... | Run and return the results from the Animation plugin. | Below is the the instruction that describes the task:
### Input:
Run and return the results from the Animation plugin.
### Response:
def analyze(self, scratch, **kwargs):
"""Run and return the results from the Animation plugin."""
results = Counter()
for script in self.iter_scripts(scratch)... |
def modflow_sfr_gag_to_instruction_file(gage_output_file, ins_file=None, parse_filename=False):
"""writes an instruction file for an SFR gage output file to read Flow only at all times
Parameters
----------
gage_output_file : str
the gage output filename (ASCII).
... | writes an instruction file for an SFR gage output file to read Flow only at all times
Parameters
----------
gage_output_file : str
the gage output filename (ASCII).
ins_file : str
the name of the instruction file to create. If None, the name
... | Below is the the instruction that describes the task:
### Input:
writes an instruction file for an SFR gage output file to read Flow only at all times
Parameters
----------
gage_output_file : str
the gage output filename (ASCII).
ins_file : str
... |
def action_range_type(self) -> Sequence[str]:
'''The range type of each action fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.action_fluents
ordering = self.domain... | The range type of each action fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent. | Below is the the instruction that describes the task:
### Input:
The range type of each action fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
### Response:
def action_range_type(self) -> Sequence[str]:
'''The... |
def _check_default(value, parameter, default_chars):
'''Returns the default if the value is "empty"'''
# not using a set here because it fails when value is unhashable
if value in default_chars:
if parameter.default is inspect.Parameter.empty:
raise ValueError('Value was empty, but no de... | Returns the default if the value is "empty" | Below is the the instruction that describes the task:
### Input:
Returns the default if the value is "empty"
### Response:
def _check_default(value, parameter, default_chars):
'''Returns the default if the value is "empty"'''
# not using a set here because it fails when value is unhashable
if value in ... |
def _parse_uri(uri):
"""Parse and validate MediaFire URI."""
tokens = urlparse(uri)
if tokens.netloc != '':
logger.error("Invalid URI: %s", uri)
raise ValueError("MediaFire URI format error: "
"host should be empty - mf:///path")
if... | Parse and validate MediaFire URI. | Below is the the instruction that describes the task:
### Input:
Parse and validate MediaFire URI.
### Response:
def _parse_uri(uri):
"""Parse and validate MediaFire URI."""
tokens = urlparse(uri)
if tokens.netloc != '':
logger.error("Invalid URI: %s", uri)
raise V... |
def decorator(func):
"""A function timer decorator."""
def function_timer(*args, **kwargs):
"""A nested function for timing other functions."""
# Capture start time
start = time.time()
# Execute function with arguments
value = func(*args, **k... | A function timer decorator. | Below is the the instruction that describes the task:
### Input:
A function timer decorator.
### Response:
def decorator(func):
"""A function timer decorator."""
def function_timer(*args, **kwargs):
"""A nested function for timing other functions."""
# Capture start time
... |
def _jobStoreClasses(self):
"""
A list of concrete AbstractJobStore implementations whose dependencies are installed.
:rtype: list[AbstractJobStore]
"""
jobStoreClassNames = (
"toil.jobStores.azureJobStore.AzureJobStore",
"toil.jobStores.fileJobStore.File... | A list of concrete AbstractJobStore implementations whose dependencies are installed.
:rtype: list[AbstractJobStore] | Below is the the instruction that describes the task:
### Input:
A list of concrete AbstractJobStore implementations whose dependencies are installed.
:rtype: list[AbstractJobStore]
### Response:
def _jobStoreClasses(self):
"""
A list of concrete AbstractJobStore implementations whose depe... |
def insert(self, table, kwargs, execute=True):
""".. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'})
insert into hospital (id, province) values ('12de3wrv', 'shanghai');
:param string table: table name
:param dict kwargs:... | .. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'})
insert into hospital (id, province) values ('12de3wrv', 'shanghai');
:param string table: table name
:param dict kwargs: name and value
:param bool execute: if not execut... | Below is the the instruction that describes the task:
### Input:
.. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'})
insert into hospital (id, province) values ('12de3wrv', 'shanghai');
:param string table: table name
:param d... |
def restart(self, restart_only_stale_services=None,
redeploy_client_configuration=None,
restart_service_names=None):
"""
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that ... | Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have stale
configuration and their dependent
services. De... | Below is the the instruction that describes the task:
### Input:
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have stale
configuration and... |
def get_annotations(self):
'''
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering().
'''
... | This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering(). | Below is the the instruction that describes the task:
### Input:
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering().
#... |
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'):
""" Download and parse English->French translation dataset used in Keras seq2seq example """
download_unzip(url)
return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split()) | Download and parse English->French translation dataset used in Keras seq2seq example | Below is the the instruction that describes the task:
### Input:
Download and parse English->French translation dataset used in Keras seq2seq example
### Response:
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'):
""" Download and parse English->French translation dataset used in Keras seq2seq e... |
def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6)
"""
... | Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6) | Below is the the instruction that describes the task:
### Input:
Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6)
... |
def _ordereddict2dict(input_ordered_dict):
'''
Convert ordered dictionary to a dictionary
'''
return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict)) | Convert ordered dictionary to a dictionary | Below is the the instruction that describes the task:
### Input:
Convert ordered dictionary to a dictionary
### Response:
def _ordereddict2dict(input_ordered_dict):
'''
Convert ordered dictionary to a dictionary
'''
return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict)) |
def global_injector_decorator(inject_globals):
'''
Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject
'''
def inner_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
... | Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject | Below is the the instruction that describes the task:
### Input:
Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject
### Response:
def global_injector_decorator(inject_globals):
'''
Decorator used by the Laz... |
def _read_interleaved_numpy(self, f, data_objects):
"""Read interleaved data where all channels have a numpy type"""
log.debug("Reading interleaved data all at once")
# Read all data into 1 byte unsigned ints first
all_channel_bytes = data_objects[0].raw_data_width
if all_channe... | Read interleaved data where all channels have a numpy type | Below is the the instruction that describes the task:
### Input:
Read interleaved data where all channels have a numpy type
### Response:
def _read_interleaved_numpy(self, f, data_objects):
"""Read interleaved data where all channels have a numpy type"""
log.debug("Reading interleaved data all at ... |
def objectify(self, load, node, depth=2, path=None):
""" Given a node ID, return an object the information available about
this node. This accepts a loader function as it's first argument, which
is expected to return all tuples of (predicate, object, source) for
the given subject. """
... | Given a node ID, return an object the information available about
this node. This accepts a loader function as it's first argument, which
is expected to return all tuples of (predicate, object, source) for
the given subject. | Below is the the instruction that describes the task:
### Input:
Given a node ID, return an object the information available about
this node. This accepts a loader function as it's first argument, which
is expected to return all tuples of (predicate, object, source) for
the given subject.
##... |
def add_cluster_admin(self, new_username, new_password):
"""Add cluster admin."""
data = {
'name': new_username,
'password': new_password
}
self.request(
url="cluster_admins",
method='POST',
data=data,
expected_resp... | Add cluster admin. | Below is the the instruction that describes the task:
### Input:
Add cluster admin.
### Response:
def add_cluster_admin(self, new_username, new_password):
"""Add cluster admin."""
data = {
'name': new_username,
'password': new_password
}
self.request(
... |
def difference(self, another_moc, *args):
"""
Difference between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used that will be substracted to self.
args : `~mocpy.moc.MOC`
Other additional MOCs to ... | Difference between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used that will be substracted to self.
args : `~mocpy.moc.MOC`
Other additional MOCs to perform the difference with.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Difference between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used that will be substracted to self.
args : `~mocpy.moc.MOC`
Other additional M... |
def _to_representation(self, instance):
"""Uncached `to_representation`."""
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
)... | Uncached `to_representation`. | Below is the the instruction that describes the task:
### Input:
Uncached `to_representation`.
### Response:
def _to_representation(self, instance):
"""Uncached `to_representation`."""
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
... |
def move_group(self, group = None, parent = None):
"""Append group to a new parent.
group and parent must be v1Group-instances.
"""
if group is None or type(group) is not v1Group:
raise KPError("A valid group must be given.")
elif parent is not None and type(parent... | Append group to a new parent.
group and parent must be v1Group-instances. | Below is the the instruction that describes the task:
### Input:
Append group to a new parent.
group and parent must be v1Group-instances.
### Response:
def move_group(self, group = None, parent = None):
"""Append group to a new parent.
group and parent must be v1Group-instances.
... |
def filebrowser_remove_file(request, item_id, file_type):
""" Remove file """
fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id)
fobj.delete()
if file_type == 'doc':
return HttpResponseRedirect(reverse('mce-filebrowser-documents'))
return HttpResponseRedirec... | Remove file | Below is the the instruction that describes the task:
### Input:
Remove file
### Response:
def filebrowser_remove_file(request, item_id, file_type):
""" Remove file """
fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id)
fobj.delete()
if file_type == 'doc':
retur... |
def _ParseDateTimeValue(self, parser_mediator, date_time_value):
"""Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_... | Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: "YYYYMMDDhhmmssZ".
Returns:
... | Below is the the instruction that describes the task:
### Input:
Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_FOR... |
def adjustMask(self):
"""
Updates the alpha mask for this popup widget.
"""
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask()
return
path = self.borderPath()
bitmap = QBitmap(self.width(), self.height())
... | Updates the alpha mask for this popup widget. | Below is the the instruction that describes the task:
### Input:
Updates the alpha mask for this popup widget.
### Response:
def adjustMask(self):
"""
Updates the alpha mask for this popup widget.
"""
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask... |
def get_country(self):
"""
:return: Country or None
"""
response = self._session.fetch("users.get", user_ids=self.id, fields="country")[0]
if response.get('country'):
return Country.from_json(self._session, response.get('country')) | :return: Country or None | Below is the the instruction that describes the task:
### Input:
:return: Country or None
### Response:
def get_country(self):
"""
:return: Country or None
"""
response = self._session.fetch("users.get", user_ids=self.id, fields="country")[0]
if response.get('country'):
... |
async def remove(self) -> None:
"""
Remove serialized wallet if it exists.
"""
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wallet: %s', self.name)
await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds))
ex... | Remove serialized wallet if it exists. | Below is the the instruction that describes the task:
### Input:
Remove serialized wallet if it exists.
### Response:
async def remove(self) -> None:
"""
Remove serialized wallet if it exists.
"""
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wal... |
def retrieve_public_key(user_repo):
"""Retrieve the public key from the Travis API.
The Travis API response is accessed as JSON so that Travis-Encrypt
can easily find the public key that is to be passed to cryptography's
load_pem_public_key function. Due to issues with some public keys being
return... | Retrieve the public key from the Travis API.
The Travis API response is accessed as JSON so that Travis-Encrypt
can easily find the public key that is to be passed to cryptography's
load_pem_public_key function. Due to issues with some public keys being
returned from the Travis API as PKCS8 encoded, th... | Below is the the instruction that describes the task:
### Input:
Retrieve the public key from the Travis API.
The Travis API response is accessed as JSON so that Travis-Encrypt
can easily find the public key that is to be passed to cryptography's
load_pem_public_key function. Due to issues with some pu... |
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move f... | Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float. | Below is the the instruction that describes the task:
### Input:
Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float.
### Response:
def DragDrop(x1: in... |
def generate_validator_constructor(ns, data_type):
"""
Given a Stone data type, returns a string that can be used to construct
the appropriate validation object in Python.
"""
dt, nullable_dt = unwrap_nullable(data_type)
if is_list_type(dt):
v = generate_func_call(
'bv.List',... | Given a Stone data type, returns a string that can be used to construct
the appropriate validation object in Python. | Below is the the instruction that describes the task:
### Input:
Given a Stone data type, returns a string that can be used to construct
the appropriate validation object in Python.
### Response:
def generate_validator_constructor(ns, data_type):
"""
Given a Stone data type, returns a string that can b... |
def color_split_position(self):
"""The SVG x position where the color split should occur."""
return self.get_text_width(' ') + self.label_width + \
int(float(self.font_width) * float(self.num_padding_chars)) | The SVG x position where the color split should occur. | Below is the the instruction that describes the task:
### Input:
The SVG x position where the color split should occur.
### Response:
def color_split_position(self):
"""The SVG x position where the color split should occur."""
return self.get_text_width(' ') + self.label_width + \
int(f... |
def piece_file(input_f, chunk_size):
"""
Provides a streaming interface to file data in chunks of even size, which
avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
"""
chunk = input_f.read(chunk_size)
total_bytes = 0
while chunk:
... | Provides a streaming interface to file data in chunks of even size, which
avoids memoryerrors from loading whole files into RAM to pass to `pieces`. | Below is the the instruction that describes the task:
### Input:
Provides a streaming interface to file data in chunks of even size, which
avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
### Response:
def piece_file(input_f, chunk_size):
"""
Provides a streaming i... |
def _realpath(fs, path, seen=pset()):
"""
.. warning::
The ``os.path`` module's realpath does not error or warn about
loops, but we do, following the behavior of GNU ``realpath(1)``!
"""
real = Path.root()
for segment in path.segments:
current = real / segment
seen ... | .. warning::
The ``os.path`` module's realpath does not error or warn about
loops, but we do, following the behavior of GNU ``realpath(1)``! | Below is the the instruction that describes the task:
### Input:
.. warning::
The ``os.path`` module's realpath does not error or warn about
loops, but we do, following the behavior of GNU ``realpath(1)``!
### Response:
def _realpath(fs, path, seen=pset()):
"""
.. warning::
The ``... |
def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.... | Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk. | Below is the the instruction that describes the task:
### Input:
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
### Response:
def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Ar... |
def get_attributes(self, section, strip_namespaces=False):
"""
Returns given section attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_pa... | Returns given section attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = cont... | Below is the the instruction that describes the task:
### Input:
Returns given section attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = Sec... |
def merge(cls, *others):
"""
Merge the `others` schema into this instance.
The values will all be read from the provider of the original object.
"""
for other in others:
for k, v in other:
setattr(cls, k, BoundValue(cls, k, v.value)) | Merge the `others` schema into this instance.
The values will all be read from the provider of the original object. | Below is the the instruction that describes the task:
### Input:
Merge the `others` schema into this instance.
The values will all be read from the provider of the original object.
### Response:
def merge(cls, *others):
"""
Merge the `others` schema into this instance.
The values ... |
def fingerprint_target(self, target):
"""Consumers of subclass instances call this to get a fingerprint labeled with the name"""
fingerprint = self.compute_fingerprint(target)
if fingerprint:
return '{fingerprint}-{name}'.format(fingerprint=fingerprint, name=type(self).__name__)
else:
return... | Consumers of subclass instances call this to get a fingerprint labeled with the name | Below is the the instruction that describes the task:
### Input:
Consumers of subclass instances call this to get a fingerprint labeled with the name
### Response:
def fingerprint_target(self, target):
"""Consumers of subclass instances call this to get a fingerprint labeled with the name"""
fingerprint = ... |
def execute_cast_timestamp_to_timestamp(op, data, type, **kwargs):
"""Cast timestamps to other timestamps including timezone if necessary"""
input_timezone = data.tz
target_timezone = type.timezone
if input_timezone == target_timezone:
return data
if input_timezone is None or target_timezo... | Cast timestamps to other timestamps including timezone if necessary | Below is the the instruction that describes the task:
### Input:
Cast timestamps to other timestamps including timezone if necessary
### Response:
def execute_cast_timestamp_to_timestamp(op, data, type, **kwargs):
"""Cast timestamps to other timestamps including timezone if necessary"""
input_timezone = da... |
def regenerate_good_tokens(string):
"""
Given an input string, part of speech tags the string, then generates a list of
ngrams that appear in the string.
Used to define grammatically correct part of speech tag sequences.
Returns a list of part of speech tag sequences.
"""
toks = nltk.word_to... | Given an input string, part of speech tags the string, then generates a list of
ngrams that appear in the string.
Used to define grammatically correct part of speech tag sequences.
Returns a list of part of speech tag sequences. | Below is the the instruction that describes the task:
### Input:
Given an input string, part of speech tags the string, then generates a list of
ngrams that appear in the string.
Used to define grammatically correct part of speech tag sequences.
Returns a list of part of speech tag sequences.
### Respon... |
def parse_authn_query_response(self, response, binding=BINDING_SOAP):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
return self._parse_response(response, AuthnQueryResponse,... | Verify that the response is OK | Below is the the instruction that describes the task:
### Input:
Verify that the response is OK
### Response:
def parse_authn_query_response(self, response, binding=BINDING_SOAP):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribut... |
def _format_output(content, typ):
"""Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format.
"""
if "csv" in str(typ):
... | Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format. | Below is the the instruction that describes the task:
### Input:
Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format.
### Response... |
def getNamespaces(self):
"""
Get the I{unique} set of namespaces referenced in the branch.
@return: A set of namespaces.
@rtype: set
"""
s = set()
for n in self.branch + self.node.ancestors():
if self.permit(n.expns):
s.add(n.expns)
... | Get the I{unique} set of namespaces referenced in the branch.
@return: A set of namespaces.
@rtype: set | Below is the the instruction that describes the task:
### Input:
Get the I{unique} set of namespaces referenced in the branch.
@return: A set of namespaces.
@rtype: set
### Response:
def getNamespaces(self):
"""
Get the I{unique} set of namespaces referenced in the branch.
@... |
def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
... | Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([]) | Below is the the instruction that describes the task:
### Input:
Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
chi... |
def get_albums(self, path):
"""Return the list of all sub-directories of path."""
for name in self.albums[path].subdirs:
subdir = os.path.normpath(join(path, name))
yield subdir, self.albums[subdir]
for subname, album in self.get_albums(subdir):
yield... | Return the list of all sub-directories of path. | Below is the the instruction that describes the task:
### Input:
Return the list of all sub-directories of path.
### Response:
def get_albums(self, path):
"""Return the list of all sub-directories of path."""
for name in self.albums[path].subdirs:
subdir = os.path.normpath(join(path, n... |
async def _sync_revoc_for_proof(self, rr_id: str) -> None:
"""
Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
... | Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
Raise AbsentTails for missing corresponding tails file.
:param rr_id... | Below is the the instruction that describes the task:
### Input:
Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
Raise Ab... |
def _cmd_run(cmd):
'''
Run the aptly command.
:return: The string output of the command.
:rtype: str
'''
cmd.insert(0, 'aptly')
cmd_ret = __salt__['cmd.run_all'](cmd, ignore_retcode=True)
if cmd_ret['retcode'] != 0:
log.debug('Unable to execute command: %s\nError: %s', cmd,
... | Run the aptly command.
:return: The string output of the command.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Run the aptly command.
:return: The string output of the command.
:rtype: str
### Response:
def _cmd_run(cmd):
'''
Run the aptly command.
:return: The string output of the command.
:rtype: str
'''
cmd.insert(0, 'aptl... |
def load_models(self, model_path):
"""
Load models from pickle files.
"""
condition_model_files = sorted(glob(model_path + "*_condition.pkl"))
if len(condition_model_files) > 0:
for condition_model_file in condition_model_files:
model_comps = condition... | Load models from pickle files. | Below is the the instruction that describes the task:
### Input:
Load models from pickle files.
### Response:
def load_models(self, model_path):
"""
Load models from pickle files.
"""
condition_model_files = sorted(glob(model_path + "*_condition.pkl"))
if len(condition_model... |
def get_token(self, appname, username, password):
"""
get the security token by connecting to TouchWorks API
"""
ext_exception = TouchWorksException(
TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR)
data = {'Username': username,
'Password': password... | get the security token by connecting to TouchWorks API | Below is the the instruction that describes the task:
### Input:
get the security token by connecting to TouchWorks API
### Response:
def get_token(self, appname, username, password):
"""
get the security token by connecting to TouchWorks API
"""
ext_exception = TouchWorksExcept... |
def values(self):
"""
Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray`
"""
separate_values = [domain.valu... | Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray` | Below is the the instruction that describes the task:
### Input:
Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray`
### Response:
def ... |
def aggregate_series(self, key, aggregate, start=None, end=None,
interval=None, namespace=None, cache=None,
percentile=None):
"""Get a time series of gauge aggregates"""
return self.make_context(key=key, aggregate=aggregate, start=start,
... | Get a time series of gauge aggregates | Below is the the instruction that describes the task:
### Input:
Get a time series of gauge aggregates
### Response:
def aggregate_series(self, key, aggregate, start=None, end=None,
interval=None, namespace=None, cache=None,
percentile=None):
"""Get a time ... |
def toggle_shells(command, enable):
"""Enable or disable the specified shells. If the command would have
no effect, it changes all other shells to the inverse enable value."""
selection = list(selected_shells(command))
if command and command != '*' and selection:
for i in selection:
... | Enable or disable the specified shells. If the command would have
no effect, it changes all other shells to the inverse enable value. | Below is the the instruction that describes the task:
### Input:
Enable or disable the specified shells. If the command would have
no effect, it changes all other shells to the inverse enable value.
### Response:
def toggle_shells(command, enable):
"""Enable or disable the specified shells. If the command ... |
def get_readable_tasks(self, course):
""" Returns the list of all available tasks in a course """
course_fs = self._filesystem.from_subfolder(course.get_id())
tasks = [
task[0:len(task)-1] # remove trailing /
for task in course_fs.list(folders=True, files=False, recursiv... | Returns the list of all available tasks in a course | Below is the the instruction that describes the task:
### Input:
Returns the list of all available tasks in a course
### Response:
def get_readable_tasks(self, course):
""" Returns the list of all available tasks in a course """
course_fs = self._filesystem.from_subfolder(course.get_id())
t... |
def _gen_4spec(op, path, value,
create_path=False, xattr=False, _expand_macros=False):
"""
Like `_gen_3spec`, but also accepts a mandatory value as its third argument
:param bool _expand_macros: Whether macros in the value should be expanded.
The macros themselves are defined at the s... | Like `_gen_3spec`, but also accepts a mandatory value as its third argument
:param bool _expand_macros: Whether macros in the value should be expanded.
The macros themselves are defined at the server side | Below is the the instruction that describes the task:
### Input:
Like `_gen_3spec`, but also accepts a mandatory value as its third argument
:param bool _expand_macros: Whether macros in the value should be expanded.
The macros themselves are defined at the server side
### Response:
def _gen_4spec(op, ... |
def reverseComplement(self, isRNA=None):
"""
Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or DNA.
"""
... | Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or DNA. | Below is the the instruction that describes the task:
### Input:
Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or... |
def _get_showcase_dataset_dict(self, dataset):
# type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict
"""Get showcase dataset dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
... | Get showcase dataset dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
Dict: showcase dataset dict | Below is the the instruction that describes the task:
### Input:
Get showcase dataset dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
Dict: showcase dataset dict
### Response:
def _get_... |
def _remove_last(votes, fpl, cl, ranking):
"""Remove last candidate in IRV voting.
"""
for v in votes:
for r in v:
if r == fpl[-1]:
v.remove(r)
for c in cl:
if c == fpl[-1]:
if c not in ranking:
ranking.append((c, len(ranking) + 1)) | Remove last candidate in IRV voting. | Below is the the instruction that describes the task:
### Input:
Remove last candidate in IRV voting.
### Response:
def _remove_last(votes, fpl, cl, ranking):
"""Remove last candidate in IRV voting.
"""
for v in votes:
for r in v:
if r == fpl[-1]:
v.remove(r)
for... |
def append_pipeline(self, name, *args, **kwargs) -> Pipeline:
"""Add an entry to the pipeline. Defers to :meth:`pybel_tools.pipeline.Pipeline.append`.
:param name: The name of the function
:type name: str or types.FunctionType
:return: This pipeline for fluid query building
"""
... | Add an entry to the pipeline. Defers to :meth:`pybel_tools.pipeline.Pipeline.append`.
:param name: The name of the function
:type name: str or types.FunctionType
:return: This pipeline for fluid query building | Below is the the instruction that describes the task:
### Input:
Add an entry to the pipeline. Defers to :meth:`pybel_tools.pipeline.Pipeline.append`.
:param name: The name of the function
:type name: str or types.FunctionType
:return: This pipeline for fluid query building
### Response:
d... |
def format_json(config):
"""format config for lambda exec
"""
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) | format config for lambda exec | Below is the the instruction that describes the task:
### Input:
format config for lambda exec
### Response:
def format_json(config):
"""format config for lambda exec
"""
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) |
def deleteFile(self, CorpNum, ItemCode, MgtKey, FileID, UserID=None):
""" 첨부파일 삭제
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
... | 첨부파일 삭제
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
FileID : 파일아이디, 첨부파일 목록확인(getFiles) API 응답전... | Below is the the instruction that describes the task:
### Input:
첨부파일 삭제
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트... |
def ReadTrigger(self, trigger_link, options=None):
"""Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict
""... | Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict | Below is the the instruction that describes the task:
### Input:
Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict
### ... |
def mapToPixel(mX, mY, geoTransform):
"""Convert map coordinates to pixel coordinates based on geotransform
Accepts float or NumPy arrays
GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
"""
mX = np.asarray(mX)
mY = np.asarray(mY)
if geoTran... | Convert map coordinates to pixel coordinates based on geotransform
Accepts float or NumPy arrays
GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) | Below is the the instruction that describes the task:
### Input:
Convert map coordinates to pixel coordinates based on geotransform
Accepts float or NumPy arrays
GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
### Response:
def mapToPixel(mX, mY, geoTrans... |
def simulate_paths(is_returns, num_days,
starting_value=1, num_samples=1000, random_seed=None):
"""
Gnerate alternate paths using available values from in-sample returns.
Parameters
----------
is_returns : pandas.core.frame.DataFrame
Non-cumulative in-sample returns.
... | Gnerate alternate paths using available values from in-sample returns.
Parameters
----------
is_returns : pandas.core.frame.DataFrame
Non-cumulative in-sample returns.
num_days : int
Number of days to project the probability cone forward.
starting_value : int or float
Starti... | Below is the the instruction that describes the task:
### Input:
Gnerate alternate paths using available values from in-sample returns.
Parameters
----------
is_returns : pandas.core.frame.DataFrame
Non-cumulative in-sample returns.
num_days : int
Number of days to project the proba... |
def write_and_return(
command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial_with_temp_timeout(
serial_connection, timeout) as device_connection:
response = _write_to_device_and_re... | Write a command and return the response | Below is the the instruction that describes the task:
### Input:
Write a command and return the response
### Response:
def write_and_return(
command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial... |
def fluence(
power_mW,
color,
beam_radius,
reprate_Hz,
pulse_width,
color_units="wn",
beam_radius_units="mm",
pulse_width_units="fs_t",
area_type="even",
) -> tuple:
"""Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated p... | Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated power of beam.
color : number
Color of beam in units.
beam_radius : number
Radius of beam in units.
reprate_Hz : number
Laser repetition rate in inverse seconds (Hz).
pul... | Below is the the instruction that describes the task:
### Input:
Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated power of beam.
color : number
Color of beam in units.
beam_radius : number
Radius of beam in units.
reprate_Hz : ... |
def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 3... | Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-... | Below is the the instruction that describes the task:
### Input:
Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5,... |
def CreateString(self, s, encoding='utf-8', errors='strict'):
"""CreateString writes a null-terminated byte string as a vector."""
self.assertNotNested()
## @cond FLATBUFFERS_INTERNAL
self.nested = True
## @endcond
if isinstance(s, compat.string_types):
x = ... | CreateString writes a null-terminated byte string as a vector. | Below is the the instruction that describes the task:
### Input:
CreateString writes a null-terminated byte string as a vector.
### Response:
def CreateString(self, s, encoding='utf-8', errors='strict'):
"""CreateString writes a null-terminated byte string as a vector."""
self.assertNotNested()
... |
def draw_scatter_plot(world, size, target):
""" This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI)
"""
#Find min and max values of humidity and temperature on land so we can
#normalize temperature and humidity to the chart
humid = numpy... | This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI) | Below is the the instruction that describes the task:
### Input:
This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI)
### Response:
def draw_scatter_plot(world, size, target):
""" This function can be used on a generic canvas (either an image to save... |
def search_task_views(self, user, search_string):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConstants.ACTION_SEARCH_TASK_VIEWS,
parameter1=us... | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response | Below is the the instruction that describes the task:
### Input:
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response
### Response:
def search_task_views(self, user, search_string):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIS... |
def run(self, message_id, **kwargs):
"""
Load and contruct message and send them off
"""
log = self.get_logger(**kwargs)
error_retry_count = kwargs.get("error_retry_count", 0)
if error_retry_count >= self.max_error_retries:
raise MaxRetriesExceededError(
... | Load and contruct message and send them off | Below is the the instruction that describes the task:
### Input:
Load and contruct message and send them off
### Response:
def run(self, message_id, **kwargs):
"""
Load and contruct message and send them off
"""
log = self.get_logger(**kwargs)
error_retry_count = kwargs.get... |
def server_setting(name, settings=None, server=_DEFAULT_SERVER):
'''
Ensure the value is set for the specified setting.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
Ex... | Ensure the value is set for the specified setting.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
Example of usage:
.. code-block:: yaml
smtp-settings:
... | Below is the the instruction that describes the task:
### Input:
Ensure the value is set for the specified setting.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
Example of... |
def measure(note1, note2):
"""Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10
"""
res = notes.note_to_int(note2) - notes.note_to_int(note1)
if res < 0:
return 12 -... | Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10 | Below is the the instruction that describes the task:
### Input:
Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10
### Response:
def measure(note1, note2):
"""Return an integer in ... |
def create(self):
"""
Create a new ConfigurationInstance
:returns: Newly created ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
"""
data = values.of({})
payload = self._version.create(
'POST',
se... | Create a new ConfigurationInstance
:returns: Newly created ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance | Below is the the instruction that describes the task:
### Input:
Create a new ConfigurationInstance
:returns: Newly created ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
### Response:
def create(self):
"""
Create a new ConfigurationInstan... |
def create_vlan(self):
"""Get an instance of vlan services facade."""
return Vlan(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of vlan services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of vlan services facade.
### Response:
def create_vlan(self):
"""Get an instance of vlan services facade."""
return Vlan(
self.networkapi_url,
self.user,
self.password,
s... |
def setup_interpreter(distributions, interpreter=None):
"""Return an interpreter configured with vendored distributions as extras.
Any distributions that are present in the vendored set will be added to the interpreter as extras.
:param distributions: The names of distributions to setup the interpreter with.
... | Return an interpreter configured with vendored distributions as extras.
Any distributions that are present in the vendored set will be added to the interpreter as extras.
:param distributions: The names of distributions to setup the interpreter with.
:type distributions: list of str
:param interpreter: An opt... | Below is the the instruction that describes the task:
### Input:
Return an interpreter configured with vendored distributions as extras.
Any distributions that are present in the vendored set will be added to the interpreter as extras.
:param distributions: The names of distributions to setup the interpreter ... |
def parse_year_days(year_info):
"""Parse year days from a year info.
"""
leap_month, leap_days = _parse_leap(year_info)
res = leap_days
for month in range(1, 13):
res += (year_info >> (16 - month)) % 2 + 29
return res | Parse year days from a year info. | Below is the the instruction that describes the task:
### Input:
Parse year days from a year info.
### Response:
def parse_year_days(year_info):
"""Parse year days from a year info.
"""
leap_month, leap_days = _parse_leap(year_info)
res = leap_days
for month in range(1, 13):
res += (yea... |
def removeSessionWithKey(self, key):
"""
Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier.
"""
self.store.query(
PersistentSession,
PersistentSession.sessionKey == key).deleteFromStore() | Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier. | Below is the the instruction that describes the task:
### Input:
Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier.
### Response:
def removeSessionWithKey(self, key):
"""
Remove a persistent session, if it exists.
... |
def _check_special_kwargs(self, name):
''' check special functions for kwargs
Checks the content of the special functions (%methodname) for
any keyword arguments referenced within
Parameters:
name (str):
A path key name
Returns:
... | check special functions for kwargs
Checks the content of the special functions (%methodname) for
any keyword arguments referenced within
Parameters:
name (str):
A path key name
Returns:
A list of keyword arguments found in any special fu... | Below is the the instruction that describes the task:
### Input:
check special functions for kwargs
Checks the content of the special functions (%methodname) for
any keyword arguments referenced within
Parameters:
name (str):
A path key name
Ret... |
def cmd(send, msg, args):
"""Nukes somebody.
Syntax: {command} <target>
"""
c, nick = args['handler'].connection, args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
if not msg:
send("Nuke who?")
return
with args['hand... | Nukes somebody.
Syntax: {command} <target> | Below is the the instruction that describes the task:
### Input:
Nukes somebody.
Syntax: {command} <target>
### Response:
def cmd(send, msg, args):
"""Nukes somebody.
Syntax: {command} <target>
"""
c, nick = args['handler'].connection, args['nick']
channel = args['target'] if args['targe... |
def psit(t, x, xf):
""" A function of t, X_t and X_{t+1} (f=future) """
if t == 0:
return psi0(x) + psit(1, x, xf)
else:
return -0.5 / sigma0**2 + (0.5 / sigma0**4) * ((xf - mu0) -
phi0 * (x - mu0))**2 | A function of t, X_t and X_{t+1} (f=future) | Below is the the instruction that describes the task:
### Input:
A function of t, X_t and X_{t+1} (f=future)
### Response:
def psit(t, x, xf):
""" A function of t, X_t and X_{t+1} (f=future) """
if t == 0:
return psi0(x) + psit(1, x, xf)
else:
return -0.5 / sigma0**2 + (0.5 / sigma0**4)... |
def remove_keywords_from_list(self, keyword_list):
"""To remove keywords present in list
Args:
keyword_list (list(str)): List of keywords to remove
Examples:
>>> keyword_processor.remove_keywords_from_list(["java", "python"]})
Raises:
AttributeError:... | To remove keywords present in list
Args:
keyword_list (list(str)): List of keywords to remove
Examples:
>>> keyword_processor.remove_keywords_from_list(["java", "python"]})
Raises:
AttributeError: If `keyword_list` is not a list. | Below is the the instruction that describes the task:
### Input:
To remove keywords present in list
Args:
keyword_list (list(str)): List of keywords to remove
Examples:
>>> keyword_processor.remove_keywords_from_list(["java", "python"]})
Raises:
Attribut... |
def set_user_password(environment, parameter, password):
"""
Sets a user's password in the keyring storage
"""
username = '%s:%s' % (environment, parameter)
return password_set(username, password) | Sets a user's password in the keyring storage | Below is the the instruction that describes the task:
### Input:
Sets a user's password in the keyring storage
### Response:
def set_user_password(environment, parameter, password):
"""
Sets a user's password in the keyring storage
"""
username = '%s:%s' % (environment, parameter)
return passwo... |
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
"""Writes MNIST image/label vectors into parallelized files on HDFS"""
# load MNIST gzip into memory
with open(input_images, 'rb') as f:
images = numpy.array(mnist.extract_images(f))
with open(input_labels, 'rb') as f:
if f... | Writes MNIST image/label vectors into parallelized files on HDFS | Below is the the instruction that describes the task:
### Input:
Writes MNIST image/label vectors into parallelized files on HDFS
### Response:
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
"""Writes MNIST image/label vectors into parallelized files on HDFS"""
# load MNIST gzi... |
def mtf_transformer_lm_baseline():
"""Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams
"""
hparams = mtf_transformer_paper_lm(-1)
hparams... | Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams | Below is the the instruction that describes the task:
### Input:
Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams
### Response:
def mtf_tran... |
def bench(client, n):
""" Benchmark n requests """
items = list(range(n))
# Time client publish operations
# ------------------------------
started = time.time()
msg = b'x'
for i in items:
client.socket.send(msg)
res = client.socket.recv()
assert msg == res
durat... | Benchmark n requests | Below is the the instruction that describes the task:
### Input:
Benchmark n requests
### Response:
def bench(client, n):
""" Benchmark n requests """
items = list(range(n))
# Time client publish operations
# ------------------------------
started = time.time()
msg = b'x'
for i in item... |
def _gather_active_forms(self):
"""Collect all the active forms of each Agent in the Statements."""
for stmt in self.statements:
if isinstance(stmt, ActiveForm):
base_agent = self.agent_set.get_create_base_agent(stmt.agent)
# Handle the case where an activity ... | Collect all the active forms of each Agent in the Statements. | Below is the the instruction that describes the task:
### Input:
Collect all the active forms of each Agent in the Statements.
### Response:
def _gather_active_forms(self):
"""Collect all the active forms of each Agent in the Statements."""
for stmt in self.statements:
if isinstance(stm... |
def filter(self, networks):
"""
Returns a new experimental setup restricted to species present in the given list of networks
Parameters
----------
networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
List of logical networks
Returns
-----... | Returns a new experimental setup restricted to species present in the given list of networks
Parameters
----------
networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
List of logical networks
Returns
-------
caspo.core.setup.Setup
Th... | Below is the the instruction that describes the task:
### Input:
Returns a new experimental setup restricted to species present in the given list of networks
Parameters
----------
networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
List of logical networks
... |
def recvmsgs(sk, cb):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775.
This is where callbacks are called.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
cb -- callbacks (nl_cb class instance).
Returns:
Number of bytes received or a negative error ... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775.
This is where callbacks are called.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
cb -- callbacks (nl_cb class instance).
Returns:
Number of bytes received or a negative error code. | Below is the the instruction that describes the task:
### Input:
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775.
This is where callbacks are called.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
cb -- callbacks (nl_cb class instance).
Returns:
Numbe... |
def get_params_and_defaults(param_list, db):
"""
Deduce [parameter, default] pairs from simulations available in the db.
Args:
param_list (list): List of parameters to query for.
db (DatabaseManager): Database where to query for defaults.
"""
return [[p, d] for p, d in db.get_all_values... | Deduce [parameter, default] pairs from simulations available in the db.
Args:
param_list (list): List of parameters to query for.
db (DatabaseManager): Database where to query for defaults. | Below is the the instruction that describes the task:
### Input:
Deduce [parameter, default] pairs from simulations available in the db.
Args:
param_list (list): List of parameters to query for.
db (DatabaseManager): Database where to query for defaults.
### Response:
def get_params_and_defaults(p... |
def create_auth_manifest(**kwargs):
"""
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
"""
class AuthProgram(Program):
pre_input_middleware = [AuthenticationMiddleware]
def register(username, password, password2):
"""
De... | Creates a basic authentication manifest for logging in, logging out and
registering new accounts. | Below is the the instruction that describes the task:
### Input:
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
### Response:
def create_auth_manifest(**kwargs):
"""
Creates a basic authentication manifest for logging in, logging out and
registerin... |
def get_out_seg_vlan(cls, tenant_id):
"""Retrieves the OUT Seg, VLAN, mob domain. """
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared for tenant %s", tenant_id)
return None, None
tenant_obj = cls.serv_obj_dict.get(tenant_id)
return tenant_obj... | Retrieves the OUT Seg, VLAN, mob domain. | Below is the the instruction that describes the task:
### Input:
Retrieves the OUT Seg, VLAN, mob domain.
### Response:
def get_out_seg_vlan(cls, tenant_id):
"""Retrieves the OUT Seg, VLAN, mob domain. """
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared for tenant ... |
def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name)
""" find the attribute method on each module """
if hasattr(mod, '__method__'):
""" register ... | if module found load module and save all attributes in the module found | Below is the the instruction that describes the task:
### Input:
if module found load module and save all attributes in the module found
### Response:
def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.fin... |
def remove_optional(annotation: type):
"""
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
"""
origin = getattr(annotation, '__origin__', None)
args = getattr(annotation, '__args__', (... | Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away. | Below is the the instruction that describes the task:
### Input:
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
### Response:
def remove_optional(annotation: type):
"""
Optional[X] annotatio... |
def hash(self):
"""Generate a hash value."""
h = hash_pandas_object(self, index=True)
return hashlib.md5(h.values.tobytes()).hexdigest() | Generate a hash value. | Below is the the instruction that describes the task:
### Input:
Generate a hash value.
### Response:
def hash(self):
"""Generate a hash value."""
h = hash_pandas_object(self, index=True)
return hashlib.md5(h.values.tobytes()).hexdigest() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.