Unnamed: 0.1 int64 0 3k | Unnamed: 0 int64 27 389k | code stringlengths 79 19.4k | docstring stringlengths 1 6.27k | prompt stringlengths 248 23k |
|---|---|---|---|---|
0 | 267,427 | def post_exec_hook(hook):
module_name = .join([env.project_package_name,])
funcs_run = []
try:
imported = import_module(module_name)
func = vars(imported).get(hook)
if func:
func()
funcs_run.append(func)
except ImportError:
return
... | Runs a hook function defined in a deploy.py file | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Runs a hook function defined in a deploy.py file
### Output:
def post_exec_hook(hook):
module_name = .join([env.project_package_name,])
funcs_run = []
try:
imported... |
1 | 316,487 | def _parse_calls_data(klass, format_, infos, gt_str):
data = OrderedDict()
for key, info, value in zip(format_, infos, gt_str.split(":")):
data[key] = parse_field_value(info, value)
return data | Parse genotype call information from arrays using format array
:param list format: List of strings with format names
:param gt_str arr: string with genotype information values | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Parse genotype call information from arrays using format array
:param list format: List of strings with format names
:param gt_str arr: string with genotype information values
##... |
2 | 324,875 | def git_url_ssh_to_https(url):
path = url.split(, 1)[1][1:].strip()
new = % path
print( % new)
return new.format(GITHUB_TOKEN=os.getenv()) | Convert a git url
url will look like
https://github.com/ARMmbed/mbed-cloud-sdk-python.git
or
git@github.com:ARMmbed/mbed-cloud-sdk-python.git
we want:
https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Convert a git url
url will look like
https://github.com/ARMmbed/mbed-cloud-sdk-python.git
or
git@github.com:ARMmbed/mbed-cloud-sdk-python.git
we want:
https://${GITHUB_TO... |
3 | 28,023 | def scan(self, table, scan_filter=None,
attributes_to_get=None, request_limit=None, max_results=None,
count=False, exclusive_start_key=None, item_class=Item):
sf = self.dynamize_scan_filter(scan_filter)
response = True
n = 0
while response:
... | Perform a scan of DynamoDB.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Table object that is being scanned.
:type scan_filter: A list of tuples
:param scan_filter: A list of tuples where each tuple consists
of an attribute name, a comparison operator, ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Perform a scan of DynamoDB.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Table object that is being scanned.
:type scan_filter: A list of tuples
... |
4 | 382,049 | def repeat_last_axis(array, count):
return as_strided(array, array.shape + (count,), array.strides + (0,)) | Restride `array` to repeat `count` times along the last axis.
Parameters
----------
array : np.array
The array to restride.
count : int
Number of times to repeat `array`.
Returns
-------
result : array
Array of shape array.shape + (count,) composed of `array` repeat... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Restride `array` to repeat `count` times along the last axis.
Parameters
----------
array : np.array
The array to restride.
count : int
Number of times to repeat ... |
5 | 200,716 | def upload_file(self, real_file_path, file_name, dir_name=None):
if dir_name is not None and dir_name[0] == :
dir_name = dir_name[1:len(dir_name)]
if dir_name is None:
dir_name = ""
self.url = + self.config.region + + str(self.config.app_id) + + self.config.b... | 简单上传文件(https://www.qcloud.com/document/product/436/6066)
:param real_file_path: 文件的物理地址
:param file_name: 文件名称
:param dir_name: 文件夹名称(可选)
:return:json数据串 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
简单上传文件(https://www.qcloud.com/document/product/436/6066)
:param real_file_path: 文件的物理地址
:param file_name: 文件名称
:param dir_name: 文件夹名称(可选)
:return:json数据串
### Outp... |
6 | 301,615 | def mix_columns(state):
state = state.reshape(4, 4, 8)
return fcat(
multiply(MA, state[0]),
multiply(MA, state[1]),
multiply(MA, state[2]),
multiply(MA, state[3]),
) | Transformation in the Cipher that takes all of the columns of the State and
mixes their data (independently of one another) to produce new columns. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Transformation in the Cipher that takes all of the columns of the State and
mixes their data (independently of one another) to produce new columns.
### Output:
def mix_columns(state):
... |
7 | 232,389 | def _to_fields(self, data):
(len_t, val_t) = self.list_dtype()
data = _np.asarray(data, dtype=val_t).ravel()
yield _np.dtype(len_t).type(data.size)
for x in data:
yield x | Return generator over the (numerical) PLY representation of the
list data (length followed by actual data). | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return generator over the (numerical) PLY representation of the
list data (length followed by actual data).
### Output:
def _to_fields(self, data):
(len_t, val_t) = self... |
8 | 272,080 | def xml(self, operator=, indent = ""):
xml = indent + "<meta id=\"" + self.key + "\""
if operator != :
xml += " operator=\"" + operator + "\""
if not self.value:
xml += " />"
else:
xml += ">" + self.value + "</meta>"
return xml | Serialize the metadata field to XML | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Serialize the metadata field to XML
### Output:
def xml(self, operator=, indent = ""):
xml = indent + "<meta id=\"" + self.key + "\""
if operator != :
xml +=... |
9 | 298,104 | def train_model(self,
train_op,
cost_to_log,
num_steps,
feed_vars=(),
feed_data=None,
print_every=100):
costs = [train_op]
if (isinstance(cost_to_log, collections.Sequence)
and not isinstance... | Trains the given model.
Args:
train_op: The training operation.
cost_to_log: A cost to log.
num_steps: Number of batches to run.
feed_vars: A list or tuple of the variables that will be fed.
feed_data: A generator that produces tuples of the same length as
feed_vars.
pri... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Trains the given model.
Args:
train_op: The training operation.
cost_to_log: A cost to log.
num_steps: Number of batches to run.
feed_vars: A list or tuple of the var... |
10 | 255,085 | def input_thread(log, stdin, is_alive, quit, close_before_term):
done = False
closed = False
alive = True
poller = Poller()
poller.register_write(stdin)
while poller and alive:
changed = poller.poll(1)
for fd, events in changed:
if events & (POLLER_EVENT_WRITE ... | this is run in a separate thread. it writes into our process's
stdin (a streamwriter) and waits the process to end AND everything that
can be written to be written | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
this is run in a separate thread. it writes into our process's
stdin (a streamwriter) and waits the process to end AND everything that
can be written to be written
### Output:
def input... |
11 | 122,477 | def to_xml_string(self):
self.update_xml_element()
xml = self.xml_element
return etree.tostring(xml, pretty_print=True).decode() | Exports the element in XML format.
:returns: element in XML format.
:rtype: str | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Exports the element in XML format.
:returns: element in XML format.
:rtype: str
### Output:
def to_xml_string(self):
self.update_xml_element()
xml = se... |
12 | 342,715 | def connectionLost(self, reason):
self.setTimeout(None)
if reason.check(ResponseDone, PotentialDataLoss):
self.deferred.callback(None)
else:
self.deferred.errback(reason) | Called when the body is complete or the connection was lost.
@note: As the body length is usually not known at the beginning of the
response we expect a L{PotentialDataLoss} when Twitter closes the
stream, instead of L{ResponseDone}. Other exceptions are treated
as error conditions. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Called when the body is complete or the connection was lost.
@note: As the body length is usually not known at the beginning of the
response we expect a L{PotentialDataLoss} when... |
13 | 336,907 | def _check_integrity(self, lons, lats):
lons = np.array(lons).ravel()
lats = np.array(lats).ravel()
if len(lons.shape) != 1 or len(lats.shape) != 1:
raise ValueError()
if lats.size != lons.size:
raise ValueError()
if (np.abs(lons)).max() > 2.*np... | Ensure lons and lats are:
- 1D numpy arrays
- equal size
- within the appropriate range in radians | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Ensure lons and lats are:
- 1D numpy arrays
- equal size
- within the appropriate range in radians
### Output:
def _check_integrity(self, lons, lats):
... |
14 | 236,323 | def _post(url, headers={}, data=None, files=None):
try:
response = requests.post(url, headers=headers, data=data, files=files, verify=VERIFY_SSL)
return _process_response(response)
except requests.exceptions.RequestException as e:
_log_and_raise_exception(, e) | Tries to POST data to an endpoint | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Tries to POST data to an endpoint
### Output:
def _post(url, headers={}, data=None, files=None):
try:
response = requests.post(url, headers=headers, data=data, files=files, veri... |
15 | 322,291 | def etfindex(
self, index_id="", min_volume=0, max_discount=None, min_discount=None
):
self.__etf_index_url = self.__etf_index_url.format(
ctime=int(time.time())
)
rep = requests.get(self.__etf_index_url)
etf_json = rep.json()
... | 以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:return: {"fund_id":{}} | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率,... |
16 | 131,480 | def create(cls, val):
if val in cls._invalid:
raise ValueError("Invalid value %r" % val)
if val == 0:
return Zero
elif val == 1:
return One
elif isinstance(val, Scalar):
return val
else:
... | Instatiate the :class:`ScalarValue` while recognizing :class:`Zero`
and :class:`One`.
:class:`Scalar` instances as `val` (including
:class:`ScalarExpression` instances) are left unchanged. This makes
:meth:`ScalarValue.create` a safe method for converting unknown objects
to :cla... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Instatiate the :class:`ScalarValue` while recognizing :class:`Zero`
and :class:`One`.
:class:`Scalar` instances as `val` (including
:class:`ScalarExpression` instances) a... |
17 | 169,098 | def _are_js_vars_defined(browser, js_vars):
script = u" && ".join([
u"!(typeof {0} === )".format(var)
for var in js_vars
])
try:
return browser.execute_script(u"return {}".format(script))
except WebDriverException as exc:
if "is not defined" in exc.msg or ... | Return a boolean indicating whether all the JavaScript
variables `js_vars` are defined on the current page.
`browser` is a Selenium webdriver instance. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a boolean indicating whether all the JavaScript
variables `js_vars` are defined on the current page.
`browser` is a Selenium webdriver instance.
### Output:
def _are_js_vars_defi... |
18 | 233,452 | def result_or_error(response):
data = response.json()
result = data.get()
if result is not None:
return result
raise exceptions.ApiError(response, data) | Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed
### Output:
def result_or_error(response):... |
19 | 247,583 | def merge_deep(dct1, dct2, merger=None):
my_merger = merger or Merger(
[
(list, ["append"]),
(dict, ["merge"])
],
["override"],
["override"]
)
return my_merger.merge(dct1, dct2) | Deep merge by this spec below
:param dct1:
:param dct2:
:param merger Optional merger
:return: | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Deep merge by this spec below
:param dct1:
:param dct2:
:param merger Optional merger
:return:
### Output:
def merge_deep(dct1, dct2, merger=None):
my_merger = merger or... |
20 | 57,896 | def get_inbox_documents_per_page(self, per_page=1000, page=1):
return self._get_resource_per_page(
resource=INBOX_DOCUMENTS,
per_page=per_page,
page=page,
) | Get inbox documents per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get inbox documents per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
### Output:
def get_inbox_docume... |
21 | 80,071 | def pcolor_axes(array, px_to_units=px_to_units):
x_size = array.shape[0]+1
y_size = array.shape[1]+1
x = _np.empty((x_size, y_size))
y = _np.empty((x_size, y_size))
for i in range(x_size):
for j in range(y_size):
x[i, j], y[i, j] = px_to_units(i-0.5, j-0.5)
... | Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
### Output:
def pco... |
22 | 184,283 | def _get_process_cwd(pid):
cmd = .format(pid)
data = common.shell_process(cmd)
if not data is None:
lines = str(data).split()
if len(lines) > 1:
return lines[1][1:] or None
return None | Returns the working directory for the provided process identifier.
`pid`
System process identifier.
Returns string or ``None``.
Note this is used as a workaround, since `psutil` isn't consistent on
being able to provide this path in all cases, especially MacOS X. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns the working directory for the provided process identifier.
`pid`
System process identifier.
Returns string or ``None``.
Note this is used as a worka... |
23 | 294,133 | def serialize_instance(instance):
data = {}
for k, v in instance.__dict__.items():
if k.startswith() or callable(v):
continue
try:
field = instance._meta.get_field(k)
if isinstance(field, BinaryField):
v = force_str(base64.b64encode(v))
... | Since Django 1.6 items added to the session are no longer pickled,
but JSON encoded by default. We are storing partially complete models
in the session (user, account, token, ...). We cannot use standard
Django serialization, as these are models are not "complete" yet.
Serialization will start complaini... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Since Django 1.6 items added to the session are no longer pickled,
but JSON encoded by default. We are storing partially complete models
in the session (user, account, token, ...). We can... |
24 | 292,621 | def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self.closed = self.byte_to_channels(data[0])
sel... | :return: None | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
:return: None
### Output:
def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rt... |
25 | 374,519 | def clientConnected(self, proto):
proto.uniqueName = % (self.next_id,)
self.next_id += 1
self.clients[proto.uniqueName] = proto | Called when a client connects to the bus. This method assigns the
new connection a unique bus name. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Called when a client connects to the bus. This method assigns the
new connection a unique bus name.
### Output:
def clientConnected(self, proto):
proto.uniqueName = % (... |
26 | 300,901 | def parser(parser_type=basic_parser, functions=None, patterns=None, expressions=None, patterns_yaml_path=None,
expressions_yaml_path=None):
from reparse.builders import build_all
from reparse.validators import validate
def _load_yaml(file_path):
import yaml
with open(file_pa... | A Reparse parser description.
Simply provide the functions, patterns, & expressions to build.
If you are using YAML for expressions + patterns, you can use
``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience.
The default parser_type is the basic ordered parser. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
A Reparse parser description.
Simply provide the functions, patterns, & expressions to build.
If you are using YAML for expressions + patterns, you can use
``expressions_y... |
27 | 188,019 | def open_bare_resource(self, resource_name,
access_mode=constants.AccessModes.no_lock,
open_timeout=constants.VI_TMO_IMMEDIATE):
return self.visalib.open(self.session, resource_name, access_mode, open_timeout) | Open the specified resource without wrapping into a class
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: time out to open.
:return: Unique logical identi... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Open the specified resource without wrapping into a class
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode:... |
28 | 234,563 | def show_position(self):
pos = self.click_position
dms = (mp_util.degrees_to_dms(pos[0]), mp_util.degrees_to_dms(pos[1]))
msg = "Coordinates in WGS84\n"
msg += "Decimal: %.6f %.6f\n" % (pos[0], pos[1])
msg += "DMS: %s %s\n" % (dms[0], dms[1])
msg += "Grid: ... | show map position click information | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
show map position click information
### Output:
def show_position(self):
pos = self.click_position
dms = (mp_util.degrees_to_dms(pos[0]), mp_util.degrees_to_dms(pos[1]))... |
29 | 14,813 | def set_options(self, **kw):
r
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v | r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads` | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
### Output:
def set_options(self, **kw):
r
for k, v in... |
30 | 369,064 | def dump_weights(tf_save_dir, outfile, options):
def _get_outname(tf_name):
outname = re.sub(, , tf_name)
outname = outname.lstrip()
outname = re.sub(, , outname)
outname = re.sub(, , outname)
outname = re.sub(, , outname)
outname = re.sub(, , outname)
i... | Dump the trained weights from a model to a HDF5 file. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Dump the trained weights from a model to a HDF5 file.
### Output:
def dump_weights(tf_save_dir, outfile, options):
def _get_outname(tf_name):
outname = re.sub(, , tf_name)
... |
31 | 264,987 | def get_ocv_old(self, cycle_number=None, ocv_type=, dataset_number=None):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
if ocv_type in [, ]:
ocv = self._get_ocv(d... | Find ocv data in DataSet (voltage vs time).
Args:
cycle_number (int): find for all cycles if None.
ocv_type ("ocv", "ocvrlx_up", "ocvrlx_down"):
ocv - get up and down (default)
ocvrlx_up - get up
ocvrlx_down - get down
... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Find ocv data in DataSet (voltage vs time).
Args:
cycle_number (int): find for all cycles if None.
ocv_type ("ocv", "ocvrlx_up", "ocvrlx_down"):
... |
32 | 203,280 | def run_hooks(self, packet):
if packet.__class__ in self.internal_hooks:
self.internal_hooks[packet.__class__](packet)
if packet.__class__ in self.hooks:
self.hooks[packet.__class__](packet) | Run any additional functions that want to process this type of packet.
These can be internal parser hooks, or external hooks that process
information | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Run any additional functions that want to process this type of packet.
These can be internal parser hooks, or external hooks that process
information
### Output:
def run_hooks(se... |
33 | 354,754 | def func_attr(f, attr):
if hasattr(f, % attr):
return getattr(f, % attr)
elif hasattr(f, % attr):
return getattr(f, % attr)
else:
raise ValueError( % (str(f), attr)) | Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x
### Output:
def func_attr(f, attr):
if hasattr(f, % attr):
return ge... |
34 | 233,867 | def load_model_from_file(self, filename):
assert os.path.isfile(filename)
data = np.loadtxt(filename).squeeze()
assert len(data.shape) == 1
pid = self.add_data(data)
return pid | Load one parameter set from a file which contains one value per line
No row is skipped.
Parameters
----------
filename : string, file path
Filename to loaded data from
Returns
-------
pid : int
ID of parameter set | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Load one parameter set from a file which contains one value per line
No row is skipped.
Parameters
----------
filename : string, file path
Filename t... |
35 | 176,784 | def ExpandPath(path, opts=None):
precondition.AssertType(path, Text)
for grouped_path in ExpandGroups(path):
for globbed_path in ExpandGlobs(grouped_path, opts):
yield globbed_path | Applies all expansion mechanisms to the given path.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Yields:
All paths possible to obtain from a given path by performing expansions. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Applies all expansion mechanisms to the given path.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Yields:
All paths possible to obtain from a given path by performing... |
36 | 275,871 | def insert_top(self, node):
if not isinstance(node, grammar.STATEMENTS):
raise ValueError
self.to_insert_top.append(node) | Insert statements at the top of the function body.
Note that multiple calls to `insert_top` will result in the statements
being prepended in that order; this is different behavior from `prepend`.
Args:
node: The statement to prepend.
Raises:
ValueError: If the given node is not a statemen... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Insert statements at the top of the function body.
Note that multiple calls to `insert_top` will result in the statements
being prepended in that order; this is different behavior from `... |
37 | 61,423 | def get_zonefiles_by_block(from_block, to_block, hostport=None, proxy=None):
assert hostport or proxy,
if proxy is None:
proxy = connect_hostport(hostport)
zonefile_info_schema = {
: ,
: {
: ,
: {
: { : },
: { : ,
... | Get zonefile information for zonefiles announced in [@from_block, @to_block]
Returns { 'last_block' : server's last seen block,
'zonefile_info' : [ { 'zonefile_hash' : '...',
'txid' : '...',
'block_height' : '...' } ] } | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get zonefile information for zonefiles announced in [@from_block, @to_block]
Returns { 'last_block' : server's last seen block,
'zonefile_info' : [ { 'zonefile_hash' : '...',
... |
38 | 323,483 | def labels_to_indices(self, labels: Sequence[str]) -> List[int]:
return [self.LABEL_TO_INDEX[label] for label in labels] | Converts a sequence of labels into their corresponding indices. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Converts a sequence of labels into their corresponding indices.
### Output:
def labels_to_indices(self, labels: Sequence[str]) -> List[int]:
return [self.LABEL_TO_INDEX[label] ... |
39 | 303,521 | def discrete_best_alpha(self, alpharangemults=(0.9,1.1), n_alpha=201,
approximate=True, verbose=True, finite=True):
data = self.data
self._xmins = xmins = np.unique(data)
if approximate:
alpha_of_xmin = [ discrete_alpha_mle(data,xmin) for xmin in... | Use the maximum likelihood to determine the most likely value of alpha
*alpharangemults* [ 2-tuple ]
Pair of values indicating multiplicative factors above and below the
approximate alpha from the MLE alpha to use when determining the
"exact" alpha (by directly maximizing th... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Use the maximum likelihood to determine the most likely value of alpha
*alpharangemults* [ 2-tuple ]
Pair of values indicating multiplicative factors above and below the
... |
40 | 39,703 | def sign(self, pkey, digest):
if not isinstance(pkey, PKey):
raise TypeError("pkey must be a PKey instance")
if pkey._only_public:
raise ValueError("Key only has public part")
if not pkey._initialized:
raise ValueError("Key is uninitialized")
... | Sign the certificate with this key and digest type.
:param pkey: The key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The name of the message digest to use.
:type digest: :py:class:`bytes`
:return: :py:data:`None` | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Sign the certificate with this key and digest type.
:param pkey: The key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The name of the message digest to use.... |
41 | 219,327 | def restructuredtext(text, **kwargs):
from docutils import core
parts = core.publish_parts(source=text,
writer_name=,
**kwargs)
return parts[] | Applies reStructuredText conversion to a string, and returns the
HTML. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Applies reStructuredText conversion to a string, and returns the
HTML.
### Output:
def restructuredtext(text, **kwargs):
from docutils import core
parts = core.publish_parts(sou... |
42 | 294,398 | def derived(self, locals=None):
context = new_context(self.environment, self.name, {},
self.get_all(), True, None, locals)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
return context | Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
### Output:
def d... |
43 | 62,560 | def temperature(self) -> Optional[ErrorValue]:
try:
return ErrorValue(self._data[], self._data.setdefault(, 0.0))
except KeyError:
return None | Sample temperature | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Sample temperature
### Output:
def temperature(self) -> Optional[ErrorValue]:
try:
return ErrorValue(self._data[], self._data.setdefault(, 0.0))
except KeyEr... |
44 | 3,403 | def index_config(request):
if _permission_denied_check(request):
return HttpResponseForbidden(, content_type=)
content_list = getattr(settings, , [])
if not content_list:
for cls in six.itervalues(DigitalObject.defined_types):
content_group = [m... | This view returns the index configuration of the current
application as JSON. Currently, this consists of a Solr index url
and the Fedora content models that this application expects to index.
.. Note::
By default, Fedora system content models (such as
``fedora-system:ContentModel-3.0``) ar... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
This view returns the index configuration of the current
application as JSON. Currently, this consists of a Solr index url
and the Fedora content models that this application expects to ... |
45 | 223,409 | def _peek_unicode(
self, is_long
):
with self._state(save_marker=True, restore=True):
if self._current not in {"u", "U"}:
raise self.parse_error(
InternalParserError, "_peek_unicode() entered on non-unicode value"
)
... | Peeks ahead non-intrusively by cloning then restoring the
initial state of the parser.
Returns the unicode value is it's a valid one else None. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Peeks ahead non-intrusively by cloning then restoring the
initial state of the parser.
Returns the unicode value is it's a valid one else None.
### Output:
def _peek_unicode(
... |
46 | 257,004 | async def copy(self, key_source, storage_dest, key_dest):
from aioworkers.storage.filesystem import FileSystemStorage
if not isinstance(storage_dest, FileSystemStorage):
return super().copy(key_source, storage_dest, key_dest)
url = self.raw_key(key_source)
logger = s... | Return True if data are copied
* optimized for http->fs copy
* not supported return_status | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return True if data are copied
* optimized for http->fs copy
* not supported return_status
### Output:
async def copy(self, key_source, storage_dest, key_dest):
... |
47 | 310,567 | def _minute_exclusion_tree(self):
itree = IntervalTree()
for market_open, early_close in self._minutes_to_exclude():
start_pos = self._find_position_of_minute(early_close) + 1
end_pos = (
self._find_position_of_minute(market_open)
+
... | Build an interval tree keyed by the start and end of each range
of positions should be dropped from windows. (These are the minutes
between an early close and the minute which would be the close based
on the regular period if there were no early close.)
The value of each node is the same... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Build an interval tree keyed by the start and end of each range
of positions should be dropped from windows. (These are the minutes
between an early close and the minute which wou... |
48 | 261,503 | def _load_config_include(self, include_directory):
include_directory = os.path.join(self.app_path, include_directory)
if not os.path.isdir(include_directory):
msg = .format(include_directory)
sys.exit(msg)
profiles = []
for filename in sorted(os.listdir(... | Load included configuration files.
Args:
include_directory (str): The name of the config include directory.
Returns:
list: A list of all profiles for the current App. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Load included configuration files.
Args:
include_directory (str): The name of the config include directory.
Returns:
list: A list of all profiles for the... |
49 | 180,569 | def cmd_list(self):
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel()
LOGGER.propagate = 0
router = Router(self.database,
migrate_dir=self.app.config[],
migrate_table=self.app.config[])
LOGGER.info()
... | List migrations. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
List migrations.
### Output:
def cmd_list(self):
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel()
LOGGER.propagate = 0
router = Route... |
50 | 47,973 | def buttons(self, master):
box = tk.Frame(master)
ttk.Button(
box,
text="Next",
width=10,
command=self.next_day
).pack(side=tk.LEFT, padx=5, pady=5)
ttk.Button(
box,
text="OK",
width=10,
... | Add a standard button box.
Override if you do not want the standard buttons | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Add a standard button box.
Override if you do not want the standard buttons
### Output:
def buttons(self, master):
box = tk.Frame(master)
ttk.Button(
... |
51 | 189,679 | def subvolume_delete(name=None, names=None, commit=None):
aftereach**
if not name and not (names and type(names) is list):
raise CommandExecutionError()
if commit and commit not in (, ):
raise CommandExecutionError()
names = [n for n in itertools.chain([name], names or [])
... | Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified.
Please, refer to the documentation to understand the implication
on the transactions, and when the subvolume is re... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified... |
52 | 312,707 | def generate(self):
self._setup()
for config_name in self.report_info.config_to_test_names_map.keys():
config_dir = os.path.join(self.report_info.resource_dir, config_name)
utils.makedirs(config_dir)
testsuite = self._generate_junit_xml(config_name)
with open(os.path.join(self.repor... | Generates the report | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Generates the report
### Output:
def generate(self):
self._setup()
for config_name in self.report_info.config_to_test_names_map.keys():
config_dir = os.path.join(self.report_i... |
53 | 281,475 | def annotate_arg(arg_name, with_annotation):
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)
return _get_pinject_wrapper(locations.get_back_frame_loc(),
arg_binding_key=arg_binding_key) | Adds an annotation to an injected arg.
arg_name must be one of the named args of the decorated function, i.e.,
@annotate_arg('foo', with_annotation='something')
def a_function(foo): # ...
is OK, but
@annotate_arg('foo', with_annotation='something')
def a_function(bar, **kwargs): # ...... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Adds an annotation to an injected arg.
arg_name must be one of the named args of the decorated function, i.e.,
@annotate_arg('foo', with_annotation='something')
def a_function(fo... |
54 | 304,287 | def run_operation(jboss_config, operation, fail_on_error=True, retries=1):
success*{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}
cli_command_result = __call_cli(jboss_config, operation, retries)
... | Execute an operation against jboss instance through the CLI interface.
jboss_config
Configuration dictionary with properties specified above.
operation
An operation to execute against jboss instance
fail_on_error (default=True)
Is true, raise CommandExecutionError exceptio... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Execute an operation against jboss instance through the CLI interface.
jboss_config
Configuration dictionary with properties specified above.
operation
An operation... |
55 | 177,375 | def n_bifurcation_points(neurites, neurite_type=NeuriteType.all):
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point) | number of bifurcation points in a collection of neurites | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
number of bifurcation points in a collection of neurites
### Output:
def n_bifurcation_points(neurites, neurite_type=NeuriteType.all):
return n_sections(neurites, neurite_type=neurite_t... |
56 | 380,334 | def run_sex_check(in_prefix, in_type, out_prefix, base_dir, options):
os.mkdir(out_prefix)
required_type = "bfile"
check_input_files(in_prefix, in_type, required_type)
script_prefix = os.path.join(out_prefix, "sexcheck")
options += ["--{}".format(required_type), in_prefix,... | Runs step6 (sexcheck).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
:type in_type: str
:type out_prefix... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Runs step6 (sexcheck).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the ou... |
57 | 249,590 | def resume(localfile, jottafile, JFS):
with open(localfile) as lf:
_complete = jottafile.resume(lf)
return _complete | Continue uploading a new file from local file (already exists on JottaCloud | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Continue uploading a new file from local file (already exists on JottaCloud
### Output:
def resume(localfile, jottafile, JFS):
with open(localfile) as lf:
_complete = jottafile.... |
58 | 293,342 | def insert_entity(self, entity):
request = _insert_entity(entity, self._require_encryption, self._key_encryption_key,
self._encryption_resolver)
self._add_to_batch(entity[], entity[], request) | Adds an insert entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_entity` for more
information on inserts.
The operation will not be executed until the batch is committed.
:param entity:
The entity to insert. Could be a... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Adds an insert entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_entity` for more
information on inserts.
The oper... |
59 | 69,124 | def get_environ_list(name, default=None):
packed = os.environ.get(name)
if packed is not None:
return packed.split()
elif default is not None:
return default
else:
return [] | Return the split colon-delimited list from an environment variable.
Returns an empty list if the variable didn't exist. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return the split colon-delimited list from an environment variable.
Returns an empty list if the variable didn't exist.
### Output:
def get_environ_list(name, default=None):
packed... |
60 | 194,117 | def safe_index(cls, unique_id):
index = unique_id
if unique_id:
index = unique_id.replace("/", "_").lower()
return index | Return a valid elastic index generated from unique_id | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a valid elastic index generated from unique_id
### Output:
def safe_index(cls, unique_id):
index = unique_id
if unique_id:
index = unique_id.replace("... |
61 | 34,237 | def raw_print_err(*args, **kw):
print(*args, sep=kw.get(, ), end=kw.get(, ),
file=sys.__stderr__)
sys.__stderr__.flush() | Raw print to sys.__stderr__, otherwise identical interface to print(). | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Raw print to sys.__stderr__, otherwise identical interface to print().
### Output:
def raw_print_err(*args, **kw):
print(*args, sep=kw.get(, ), end=kw.get(, ),
file=sys.__std... |
62 | 270,171 | def render_js_code(self, id_, *args, **kwargs):
if id_:
options = self.render_select2_options_code(
dict(self.get_options()), id_)
return mark_safe(self.html.format(id=id_, options=options))
return u | Render html container for Select2 widget with options. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Render html container for Select2 widget with options.
### Output:
def render_js_code(self, id_, *args, **kwargs):
if id_:
options = self.render_select2_options_code... |
63 | 114,475 | def add_custom_options(parser):
parser.add_argument("--report-title", type=str, metavar="TITLE",
default="Genetic Data Clean Up",
help="The report title. [default: %(default)s]")
parser.add_argument("--report-author", type=str, metavar="AUTHOR",
... | Adds custom options to a parser.
:param parser: the parser to which to add options.
:type parser: argparse.ArgumentParser | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Adds custom options to a parser.
:param parser: the parser to which to add options.
:type parser: argparse.ArgumentParser
### Output:
def add_custom_options(parser):
parser.ad... |
64 | 305,976 | def get_functions_by_search(self, function_query, function_search):
if not self._can():
raise PermissionDenied()
return self._provider_session.get_functions_by_search(function_query, function_search) | Pass through to provider FunctionSearchSession.get_functions_by_search | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Pass through to provider FunctionSearchSession.get_functions_by_search
### Output:
def get_functions_by_search(self, function_query, function_search):
if not s... |
65 | 315,413 | def deserialize(self, value, **kwargs):
kwargs.update({: kwargs.get(, False)})
if self.deserializer is not None:
return self.deserializer(value, **kwargs)
if value is None:
return None
instance_props = [
prop for prop in self.props if isinstan... | Return a deserialized value
If no deserializer is provided, it uses the deserialize method of the
prop corresponding to the value | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a deserialized value
If no deserializer is provided, it uses the deserialize method of the
prop corresponding to the value
### Output:
def deserialize(self, value, **kwar... |
66 | 381,428 | def load_and_parse(self):
archives = []
to_return = {}
for name, project in self.all_projects.items():
archives = archives + self.parse_archives_from_project(project)
archive = UnparsedNode(**a)
node_path = self.get_path(archive.resource_t... | Load and parse archives in a list of projects. Returns a dict
that maps unique ids onto ParsedNodes | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Load and parse archives in a list of projects. Returns a dict
that maps unique ids onto ParsedNodes
### Output:
def load_and_parse(self):
archives = []
to_re... |
67 | 217,292 | def pause(self):
if self._status == TransferState.RUNNING:
self._running.clear()
self._status = TransferState.PAUSED
else:
raise SbgError() | Pauses the download.
:raises SbgError: If upload is not in RUNNING state. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Pauses the download.
:raises SbgError: If upload is not in RUNNING state.
### Output:
def pause(self):
if self._status == TransferState.RUNNING:
self._runnin... |
68 | 380,293 | def parse_cidr (addr, infer=True, allow_host=False):
def check (r0, r1):
a = int(r0)
b = r1
if (not allow_host) and (a & ((1<<b)-1)):
raise RuntimeError("Host part of CIDR address is not zero (%s)"
% (addr,))
return (r0,32-r1)
addr = addr.split(, 2)
if len(addr) ... | Takes a CIDR address or plain dotted-quad, and returns a tuple of address
and count-of-network-bits.
Can infer the network bits based on network classes if infer=True.
Can also take a string in the form 'address/netmask', as long as the
netmask is representable in CIDR.
FIXME: This function is badly named. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Takes a CIDR address or plain dotted-quad, and returns a tuple of address
and count-of-network-bits.
Can infer the network bits based on network classes if infer=True.
Can also take a strin... |
69 | 62,164 | def get_msms_df(model, pdb_id, outfile=None, outdir=None, outext=, force_rerun=False):
outfile = ssbio.utils.outfile_maker(inname=pdb_id, outname=outfile, outdir=outdir, outext=outext)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
try:
rd = PDB... | Run MSMS (using Biopython) on a Biopython Structure Model.
Depths are in units Angstroms. 1A = 10^-10 m = 1nm. Returns a dictionary of::
{
chain_id:{
resnum1_id: (res_depth, ca_depth),
resnum2_id: (res_depth, ca_depth)
}
... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Run MSMS (using Biopython) on a Biopython Structure Model.
Depths are in units Angstroms. 1A = 10^-10 m = 1nm. Returns a dictionary of::
{
chain_id:{
... |
70 | 61,529 | def has_key(self, key):
try:
if type(self.attrs) == dict:
return key in self.attrs
else:
raise AttributeError
except AttributeError:
raise NotImplementedError | Dict-like behaviour | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Dict-like behaviour
### Output:
def has_key(self, key):
try:
if type(self.attrs) == dict:
return key in self.attrs
else:
... |
71 | 194,802 | def box_score(game_id):
data = mlbgame.data.get_box_score(game_id)
parsed = etree.parse(data)
root = parsed.getroot()
linescore = root.find()
result = dict()
result[] = game_id
for x in linescore:
inning = x.attrib[]
home = value_to_int(x.attrib, )
... | Gets the box score information for the game with matching id. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Gets the box score information for the game with matching id.
### Output:
def box_score(game_id):
data = mlbgame.data.get_box_score(game_id)
parsed = etree.parse(data)
... |
72 | 95,927 | def export_dae(filename, cutout, level=0):
if ".dae" not in filename:
filename = filename + ".dae"
vs, fs = mcubes.marching_cubes(cutout, level)
mcubes.export_mesh(vs, fs, filename, "ndioexport") | Converts a dense annotation to a DAE, using Marching Cubes (PyMCubes).
Arguments:
filename (str): The filename to write out to
cutout (numpy.ndarray): The dense annotation
level (int): The level at which to run mcubes
Returns:
boolean success | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Converts a dense annotation to a DAE, using Marching Cubes (PyMCubes).
Arguments:
filename (str): The filename to write out to
cutout (numpy.ndarray): The dense annotation
... |
73 | 144,089 | def do_flip(dec=None, inc=None, di_block=None):
if di_block is None:
dec_flip = []
inc_flip = []
for n in range(0, len(dec)):
dec_flip.append((dec[n] - 180.) % 360.0)
inc_flip.append(-inc[n])
return dec_flip, inc_flip
else:
dflip = []
... | This function returns the antipode (i.e. it flips) of directions.
The function can take dec and inc as seperate lists if they are of equal
length and explicitly specified or are the first two arguments. It will then
return a list of flipped decs and a list of flipped incs. If a di_block (a
nested list ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
This function returns the antipode (i.e. it flips) of directions.
The function can take dec and inc as seperate lists if they are of equal
length and explicitly specified or are the firs... |
74 | 74,729 | def format_table(rows, sep=):
max_col_length = [0] * 100
for row in rows:
for index, (col, length) in enumerate(zip(row, max_col_length)):
if len(text_type(col)) > length:
max_col_length[index] = len(text_type(col))
formated_rows = []
for row in rows:
... | Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo', 45, 'bar', 2345]
]
`format... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
... |
75 | 214,703 | def lonlat_box(self, west, east, south, north):
self._set_query(self.spatial_query, west=west, east=east, south=south,
north=north)
return self | Add a latitude/longitude bounding box to the query.
This adds a request for a spatial bounding box, bounded by ('north', 'south')
for latitude and ('east', 'west') for the longitude. This modifies the query
in-place, but returns `self` so that multiple queries can be chained together
on... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Add a latitude/longitude bounding box to the query.
This adds a request for a spatial bounding box, bounded by ('north', 'south')
for latitude and ('east', 'west') for the longit... |
76 | 326,366 | def ImportDNS(self, config, token=None):
if not token:
raise Exception("You must have the dns token set first.")
self.dns = CotendoDNS([token, config])
return True | Import a dns configuration file into the helper
Note: This requires that you have the latest token.
To get the latest token, run the GrabDNS command first. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Import a dns configuration file into the helper
Note: This requires that you have the latest token.
To get the latest token, run the GrabDNS command first.
### Output:
def Impor... |
77 | 128,695 | def enable_auto_login(name, password):
*
cmd = [,
,
,
,
name]
__salt__[](cmd)
current = get_auto_login()
o_password = _kcpassword(password=password)
with salt.utils.files.set_umask(0o077):
with salt.utils.files.fopen(, if six.PY2 el... | .. versionadded:: 2016.3.0
Configures the machine to auto login with the specified user
Args:
name (str): The user account use for auto login
password (str): The password to user for auto login
.. versionadded:: 2017.7.3
Returns:
bool: ``True`` if successful, otherw... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
.. versionadded:: 2016.3.0
Configures the machine to auto login with the specified user
Args:
name (str): The user account use for auto login
password (str): The passw... |
78 | 118,000 | def firstElementChild(self):
ret = libxml2mod.xmlFirstElementChild(self._o)
if ret is None:return None
__tmp = xmlNode(_obj=ret)
return __tmp | Finds the first child node of that element which is a
Element node Note the handling of entities references is
different than in the W3C DOM element traversal spec since
we don't have back reference from entities content to
entities references. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Finds the first child node of that element which is a
Element node Note the handling of entities references is
different than in the W3C DOM element traversal spec since
... |
79 | 89,867 | def as_region_controller(self):
if self.node_type not in [
NodeType.REGION_CONTROLLER,
NodeType.REGION_AND_RACK_CONTROLLER]:
raise ValueError(
)
return self._origin.RegionController(self._data) | Convert to a `RegionController` object.
`node_type` must be `NodeType.REGION_CONTROLLER` or
`NodeType.REGION_AND_RACK_CONTROLLER`. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Convert to a `RegionController` object.
`node_type` must be `NodeType.REGION_CONTROLLER` or
`NodeType.REGION_AND_RACK_CONTROLLER`.
### Output:
def as_region_controller(self):
... |
80 | 74,367 | def searchFileLocation(targetFileName, targetFileExtension, rootDirectory,
recursive=True):
expectedFileName = targetFileName.split()[0] + + targetFileExtension
targetFilePath = None
if recursive:
for dirpath, dirnames, filenames in os.walk(rootDirectory):
f... | Search for a filename with a specified file extension in all subfolders
of specified rootDirectory, returns first matching instance.
:param targetFileName: #TODO: docstring
:type targetFileName: str
:param rootDirectory: #TODO: docstring
:type rootDirectory: str
:param targetFileExtension: #TOD... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Search for a filename with a specified file extension in all subfolders
of specified rootDirectory, returns first matching instance.
:param targetFileName: #TODO: docstring
:type tar... |
81 | 235,558 | def make_stacked(self):
"If unstacked, convert to stacked. If stacked, do nothing."
if self.stacked:
return
self._boundaries = bounds = np.r_[0, np.cumsum(self.n_pts)]
self.stacked_features = stacked = np.vstack(self.features)
self.features = np.array(
[s... | If unstacked, convert to stacked. If stacked, do nothing. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
If unstacked, convert to stacked. If stacked, do nothing.
### Output:
def make_stacked(self):
"If unstacked, convert to stacked. If stacked, do nothing."
if self.stacked:
... |
82 | 285,511 | def bin_tree_to_list(root):
if not root:
return root
root = bin_tree_to_list_util(root)
while root.left:
root = root.left
return root | type root: root class | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
type root: root class
### Output:
def bin_tree_to_list(root):
if not root:
return root
root = bin_tree_to_list_util(root)
while root.left:
root = root.left
r... |
83 | 350,928 | def __load_unique_identity(self, uidentity, verbose):
uuid = uidentity.uuid
if uuid:
try:
api.unique_identities(self.db, uuid)
self.log("-- %s already exists." % uuid, verbose)
return uuid
except NotFoundError as e:
... | Seek or store unique identity | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Seek or store unique identity
### Output:
def __load_unique_identity(self, uidentity, verbose):
uuid = uidentity.uuid
if uuid:
try:
api.uni... |
84 | 371,322 | def colorbar(self, cmap, position="right",
label="", clim=("", ""),
border_width=0.0, border_color="black",
**kwargs):
self._configure_2d()
cbar = scene.ColorBarWidget(orientation=position,
label_str=label,... | Show a ColorBar
Parameters
----------
cmap : str | vispy.color.ColorMap
Either the name of the ColorMap to be used from the standard
set of names (refer to `vispy.color.get_colormap`),
or a custom ColorMap object.
The ColorMap is used to apply a g... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Show a ColorBar
Parameters
----------
cmap : str | vispy.color.ColorMap
Either the name of the ColorMap to be used from the standard
set of names ... |
85 | 145,095 | def transactions(self, cursor=None, order=, limit=10, sse=False):
return self.horizon.account_transactions(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param... |
86 | 147,911 | def saturation(p):
max_c = max(p)
min_c = min(p)
if max_c == 0:
return 0
return (max_c - min_c) / float(max_c) | Returns the saturation of a pixel, defined as the ratio of chroma to value.
:param p: A tuple of (R,G,B) values
:return: The saturation of a pixel, from 0 to 1 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns the saturation of a pixel, defined as the ratio of chroma to value.
:param p: A tuple of (R,G,B) values
:return: The saturation of a pixel, from 0 to 1
### Output:
def saturation... |
87 | 257,010 | def get_members(obj, predicate=None):
members = {member: getattr(obj, member) for member in dir(obj) if not member.startswith()}
if predicate is None:
return members
return {name: member for name, member in members.items() if predicate(member)} | Returns all members of an object for which the supplied predicate is true and that do not
begin with __. Keep in mind that the supplied function must accept a potentially very broad
range of inputs, because the members of an object can be of any type. The function puts
those members into a dict with the mem... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns all members of an object for which the supplied predicate is true and that do not
begin with __. Keep in mind that the supplied function must accept a potentially very broad
range... |
88 | 385,562 | def eigenvectors(T, k=None, right=True, ncv=None, reversible=False, mu=None):
r
if k is None:
raise ValueError("Number of eigenvectors required for decomposition of sparse matrix")
else:
if reversible:
eigvec = eigenvectors_rev(T, k, right=right, ncv=ncv, mu=mu)
retur... | r"""Compute eigenvectors of given transition matrix.
Parameters
----------
T : scipy.sparse matrix
Transition matrix (stochastic matrix).
k : int (optional) or array-like
For integer k compute the first k eigenvalues of T
else return those eigenvector sepcified by integer indice... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
r"""Compute eigenvectors of given transition matrix.
Parameters
----------
T : scipy.sparse matrix
Transition matrix (stochastic matrix).
k : int (optional) or array-like... |
89 | 361,873 | def kwinsert(clas,pool_or_cursor,**kwargs):
"kwargs version of insert"
returning = kwargs.pop(,None)
fields,vals = zip(*kwargs.items())
return clas.insert(pool_or_cursor,fields,vals,returning=returning) | kwargs version of insert | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
kwargs version of insert
### Output:
def kwinsert(clas,pool_or_cursor,**kwargs):
"kwargs version of insert"
returning = kwargs.pop(,None)
fields,vals = zip(*kwargs.items())
... |
90 | 48,740 | def _update_aes(self):
if salt.master.SMaster.secrets[][].value != self.crypticle.key_string:
self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets[][].value)
return True
return False | Check to see if a fresh AES key is available and update the components
of the worker | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Check to see if a fresh AES key is available and update the components
of the worker
### Output:
def _update_aes(self):
if salt.master.SMaster.secrets[][].value != self.... |
End of preview. Expand in Data Studio
- Downloads last month
- 15