code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def observation_spec(self):
"""The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facilitate printing of the images.
... | The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facilitate printing of the images.
Returns:
The dict of observat... | Below is the the instruction that describes the task:
### Input:
The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facili... |
def log(ltype, method, page, user_agent):
"""Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>"
"""
try:
f = open(settings.DJANGOSPAM_LOG, "a")
f.write("%s: %s method %s pag... | Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>" | Below is the the instruction that describes the task:
### Input:
Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>"
### Response:
def log(ltype, method, page, user_agent):
"""Writes to the log a message in ... |
def query(self, parents=None):
""" Compose the query and generate SPARQL. """
# TODO: benchmark single-query strategy
q = Select([])
q = self.project(q, parent=True)
q = self.filter(q, parents=parents)
if self.parent is None:
subq = Select([self.var])
... | Compose the query and generate SPARQL. | Below is the the instruction that describes the task:
### Input:
Compose the query and generate SPARQL.
### Response:
def query(self, parents=None):
""" Compose the query and generate SPARQL. """
# TODO: benchmark single-query strategy
q = Select([])
q = self.project(q, parent=True)... |
async def release_control(self):
"""Release control of QTM.
"""
cmd = "releasecontrol"
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._timeout
) | Release control of QTM. | Below is the the instruction that describes the task:
### Input:
Release control of QTM.
### Response:
async def release_control(self):
"""Release control of QTM.
"""
cmd = "releasecontrol"
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._t... |
def __register_library(self, module_name: str, attr: str, fallback: str = None):
"""Inserts Interpreter Library of imports into sketch in a very non-consensual way"""
# Import the module Named in the string
try:
module = importlib.import_module(module_name)
# If module is n... | Inserts Interpreter Library of imports into sketch in a very non-consensual way | Below is the the instruction that describes the task:
### Input:
Inserts Interpreter Library of imports into sketch in a very non-consensual way
### Response:
def __register_library(self, module_name: str, attr: str, fallback: str = None):
"""Inserts Interpreter Library of imports into sketch in a very non... |
def read_auth_method_tuning(self, path):
"""Read the given auth path's configuration.
This endpoint requires sudo capability on the final path, but the same functionality can be achieved without
sudo via sys/mounts/auth/[auth-path]/tune.
Supported methods:
GET: /sys/auth/{p... | Read the given auth path's configuration.
This endpoint requires sudo capability on the final path, but the same functionality can be achieved without
sudo via sys/mounts/auth/[auth-path]/tune.
Supported methods:
GET: /sys/auth/{path}/tune. Produces: 200 application/json
:... | Below is the the instruction that describes the task:
### Input:
Read the given auth path's configuration.
This endpoint requires sudo capability on the final path, but the same functionality can be achieved without
sudo via sys/mounts/auth/[auth-path]/tune.
Supported methods:
... |
def permissions(self):
"""
Return each permission role mapping for this Admin User. A permission
role will have 3 fields:
* Domain
* Role (Viewer, Operator, etc)
* Elements (Engines, Policies, or ACLs)
:return: permissions as list
:rtype:... | Return each permission role mapping for this Admin User. A permission
role will have 3 fields:
* Domain
* Role (Viewer, Operator, etc)
* Elements (Engines, Policies, or ACLs)
:return: permissions as list
:rtype: list(Permission) | Below is the the instruction that describes the task:
### Input:
Return each permission role mapping for this Admin User. A permission
role will have 3 fields:
* Domain
* Role (Viewer, Operator, etc)
* Elements (Engines, Policies, or ACLs)
:return: permissio... |
def load_jinja_template(file_name):
"""
Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script.
"""
original_script_path = sys.argv[0]
#script_path = os.path.dirname(os.path.realpath(__file__))
script_dir = os.path.dirname(original_sc... | Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script. | Below is the the instruction that describes the task:
### Input:
Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script.
### Response:
def load_jinja_template(file_name):
"""
Loads the jinja2 HTML template from the given file.
Assumes that t... |
def clear(self, fg, attr, bg):
"""
Clear the double-buffer.
This does not clear the screen buffer and so the next call to deltas will still show all changes.
:param fg: The foreground colour to use for the new buffer.
:param attr: The attribute value to use for the new buffer.
... | Clear the double-buffer.
This does not clear the screen buffer and so the next call to deltas will still show all changes.
:param fg: The foreground colour to use for the new buffer.
:param attr: The attribute value to use for the new buffer.
:param bg: The background colour to use for... | Below is the the instruction that describes the task:
### Input:
Clear the double-buffer.
This does not clear the screen buffer and so the next call to deltas will still show all changes.
:param fg: The foreground colour to use for the new buffer.
:param attr: The attribute value to use fo... |
def killServices(self, services, error=False):
"""
:param dict services: Maps service jobStoreIDs to the communication flags for the service
"""
for serviceJobStoreID in services:
serviceJob = services[serviceJobStoreID]
if error:
self.jobStore.del... | :param dict services: Maps service jobStoreIDs to the communication flags for the service | Below is the the instruction that describes the task:
### Input:
:param dict services: Maps service jobStoreIDs to the communication flags for the service
### Response:
def killServices(self, services, error=False):
"""
:param dict services: Maps service jobStoreIDs to the communication flags for t... |
def plot_feature(feature, cell):
'''Plot a feature
'''
fig = pl.figure()
ax = fig.add_subplot(111)
if cell is not None:
try:
histogram(cell, feature, ax)
except ValueError:
pass
stylize(ax, cell.name, feature)
return fig | Plot a feature | Below is the the instruction that describes the task:
### Input:
Plot a feature
### Response:
def plot_feature(feature, cell):
'''Plot a feature
'''
fig = pl.figure()
ax = fig.add_subplot(111)
if cell is not None:
try:
histogram(cell, feature, ax)
except ValueError:... |
def getCipherText(self, iv, key, plaintext):
"""
:type iv: bytearray
:type key: bytearray
:type plaintext: bytearray
"""
cipher = AESCipher(key, iv)
return cipher.encrypt(bytes(plaintext)) | :type iv: bytearray
:type key: bytearray
:type plaintext: bytearray | Below is the the instruction that describes the task:
### Input:
:type iv: bytearray
:type key: bytearray
:type plaintext: bytearray
### Response:
def getCipherText(self, iv, key, plaintext):
"""
:type iv: bytearray
:type key: bytearray
:type plaintext: bytearray
... |
def get_next(self):
"""Return the next set of objects in a list"""
url = self._get_link('next')
resource = self.object_type.get_resource_class(self.client)
resp = resource.perform_api_call(resource.REST_READ, url)
return List(resp, self.object_type, self.client) | Return the next set of objects in a list | Below is the the instruction that describes the task:
### Input:
Return the next set of objects in a list
### Response:
def get_next(self):
"""Return the next set of objects in a list"""
url = self._get_link('next')
resource = self.object_type.get_resource_class(self.client)
resp = ... |
def parse_location(loc, default_port):
'''
loc can be of the format http://<ip/domain>[:<port>]
eg:
http://localhost:8888
http://localhost/
return ip (str), port (int)
>>> parse_location('http://localhost/', 6379)
('localhost', 6379)
>>> parse_location('http://localhost:8888'... | loc can be of the format http://<ip/domain>[:<port>]
eg:
http://localhost:8888
http://localhost/
return ip (str), port (int)
>>> parse_location('http://localhost/', 6379)
('localhost', 6379)
>>> parse_location('http://localhost:8888', 6379)
('localhost', 8888) | Below is the the instruction that describes the task:
### Input:
loc can be of the format http://<ip/domain>[:<port>]
eg:
http://localhost:8888
http://localhost/
return ip (str), port (int)
>>> parse_location('http://localhost/', 6379)
('localhost', 6379)
>>> parse_location('http... |
def GetIPAddresses(self):
"""IP addresses from all interfaces."""
result = []
filtered_ips = ["127.0.0.1", "::1", "fe80::1"]
for interface in self.interfaces:
for address in interface.addresses:
if address.human_readable_address not in filtered_ips:
result.append(Text(address.hu... | IP addresses from all interfaces. | Below is the the instruction that describes the task:
### Input:
IP addresses from all interfaces.
### Response:
def GetIPAddresses(self):
"""IP addresses from all interfaces."""
result = []
filtered_ips = ["127.0.0.1", "::1", "fe80::1"]
for interface in self.interfaces:
for address in inter... |
def load_udata_commands(self, ctx):
'''
Load udata commands from:
- `udata.commands.*` module
- known internal modules with commands
- plugins exporting a `udata.commands` entrypoint
'''
if self._udata_commands_loaded:
return
# Load all comman... | Load udata commands from:
- `udata.commands.*` module
- known internal modules with commands
- plugins exporting a `udata.commands` entrypoint | Below is the the instruction that describes the task:
### Input:
Load udata commands from:
- `udata.commands.*` module
- known internal modules with commands
- plugins exporting a `udata.commands` entrypoint
### Response:
def load_udata_commands(self, ctx):
'''
Load udata co... |
def parse_azimuth(azimuth):
"""
Parses an azimuth measurement in azimuth or quadrant format.
Parameters
-----------
azimuth : string or number
An azimuth measurement in degrees or a quadrant measurement of azimuth.
Returns
-------
azi : float
The azimuth in degrees cloc... | Parses an azimuth measurement in azimuth or quadrant format.
Parameters
-----------
azimuth : string or number
An azimuth measurement in degrees or a quadrant measurement of azimuth.
Returns
-------
azi : float
The azimuth in degrees clockwise from north (range: 0-360)
See... | Below is the the instruction that describes the task:
### Input:
Parses an azimuth measurement in azimuth or quadrant format.
Parameters
-----------
azimuth : string or number
An azimuth measurement in degrees or a quadrant measurement of azimuth.
Returns
-------
azi : float
... |
def prepare(self):
'''
Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Syndic, self).prepare()
try:
if self.config['verify_env']:
... | Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare() | Below is the the instruction that describes the task:
### Input:
Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
### Response:
def prepare(self):
'''
Run the preparation sequ... |
def wsproto_demo(host, port):
'''
Demonstrate wsproto:
0) Open TCP connection
1) Negotiate WebSocket opening handshake
2) Send a message and display response
3) Send ping and display pong
4) Negotiate WebSocket closing handshake
:param stream: a socket stream
'''
# 0) Open TCP... | Demonstrate wsproto:
0) Open TCP connection
1) Negotiate WebSocket opening handshake
2) Send a message and display response
3) Send ping and display pong
4) Negotiate WebSocket closing handshake
:param stream: a socket stream | Below is the the instruction that describes the task:
### Input:
Demonstrate wsproto:
0) Open TCP connection
1) Negotiate WebSocket opening handshake
2) Send a message and display response
3) Send ping and display pong
4) Negotiate WebSocket closing handshake
:param stream: a socket stream... |
def get_angles(self, angle_id):
"""Get sun-satellite viewing angles"""
tic = datetime.now()
sunz40km = self._data["ang"][:, :, 0] * 1e-2
satz40km = self._data["ang"][:, :, 1] * 1e-2
azidiff40km = self._data["ang"][:, :, 2] * 1e-2
try:
from geotiepoints.inte... | Get sun-satellite viewing angles | Below is the the instruction that describes the task:
### Input:
Get sun-satellite viewing angles
### Response:
def get_angles(self, angle_id):
"""Get sun-satellite viewing angles"""
tic = datetime.now()
sunz40km = self._data["ang"][:, :, 0] * 1e-2
satz40km = self._data["ang"][:, ... |
def _press_pwr_btn(self, pushType="Press"):
"""Simulates a physical press of the server power button.
:param pushType: Type of power button press to simulate
Supported values are: 'Press' and 'PressAndHold'
:raises: IloError, on an error from iLO.
"""
po... | Simulates a physical press of the server power button.
:param pushType: Type of power button press to simulate
Supported values are: 'Press' and 'PressAndHold'
:raises: IloError, on an error from iLO. | Below is the the instruction that describes the task:
### Input:
Simulates a physical press of the server power button.
:param pushType: Type of power button press to simulate
Supported values are: 'Press' and 'PressAndHold'
:raises: IloError, on an error from iLO.
### Resp... |
def route(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']):
'''
Route specified path to a WSGI-styled routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routi... | Route specified path to a WSGI-styled routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routinemethod(env), env is an Environment object
see also utils.http.Environment
:param container: rout... | Below is the the instruction that describes the task:
### Input:
Route specified path to a WSGI-styled routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routinemethod(env), env is an Environment object
se... |
def model(method):
"""Use this to decorate methods that expect a model."""
def wrapper(self, *args, **kwargs):
if self.__model__ is None:
raise ValidationError(
'You cannot perform CRUD operations without selecting a '
'model first.',
... | Use this to decorate methods that expect a model. | Below is the the instruction that describes the task:
### Input:
Use this to decorate methods that expect a model.
### Response:
def model(method):
"""Use this to decorate methods that expect a model."""
def wrapper(self, *args, **kwargs):
if self.__model__ is None:
rais... |
def set_meta_all(self, props):
"""Set metadata values for collection.
``props`` a dict with values for properties.
"""
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.updat... | Set metadata values for collection.
``props`` a dict with values for properties. | Below is the the instruction that describes the task:
### Input:
Set metadata values for collection.
``props`` a dict with values for properties.
### Response:
def set_meta_all(self, props):
"""Set metadata values for collection.
``props`` a dict with values for properties.
"""
... |
def cert_chain(certs):
"""Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
See `validate.retrieve` to create c... | Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
See `validate.retrieve` to create certs obj.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
... |
def default_handler(self, signum, frame):
""" Default handler, a generic callback method for signal processing"""
self.log.debug("Signal handler called with signal: {0}".format(signum))
# 1. If signal is HUP restart the python process
# 2. If signal is TERM, INT or QUIT we try to cleanup... | Default handler, a generic callback method for signal processing | Below is the the instruction that describes the task:
### Input:
Default handler, a generic callback method for signal processing
### Response:
def default_handler(self, signum, frame):
""" Default handler, a generic callback method for signal processing"""
self.log.debug("Signal handler called wit... |
def output_schema(
self, what="", file_path=None, append=False, sort_keys=False
):
"""*Outputs JSON Schema to terminal or a file.*
By default, the schema is output for the last request and response.
The output can be limited further by:
- The property of the last instance,... | *Outputs JSON Schema to terminal or a file.*
By default, the schema is output for the last request and response.
The output can be limited further by:
- The property of the last instance, e.g. ``request`` or ``response``
- Any nested property that exists, similarly as for assertion ke... | Below is the the instruction that describes the task:
### Input:
*Outputs JSON Schema to terminal or a file.*
By default, the schema is output for the last request and response.
The output can be limited further by:
- The property of the last instance, e.g. ``request`` or ``response``
... |
def guest_start(self, userid):
""""Power on z/VM instance."""
LOG.info("Begin to power on vm %s", userid)
self._smtclient.guest_start(userid)
LOG.info("Complete power on vm %s", userid) | Power on z/VM instance. | Below is the the instruction that describes the task:
### Input:
Power on z/VM instance.
### Response:
def guest_start(self, userid):
""""Power on z/VM instance."""
LOG.info("Begin to power on vm %s", userid)
self._smtclient.guest_start(userid)
LOG.info("Complete power on vm %s", us... |
def _is_indirect_jump(_, sim_successors):
"""
Determine if this SimIRSB has an indirect jump as its exit
"""
if sim_successors.artifacts['irsb_direct_next']:
# It's a direct jump
return False
default_jumpkind = sim_successors.artifacts['irsb_default_jump... | Determine if this SimIRSB has an indirect jump as its exit | Below is the the instruction that describes the task:
### Input:
Determine if this SimIRSB has an indirect jump as its exit
### Response:
def _is_indirect_jump(_, sim_successors):
"""
Determine if this SimIRSB has an indirect jump as its exit
"""
if sim_successors.artifacts['irsb_d... |
def heatmap_mpl(dfr, outfilename=None, title=None, params=None):
"""Returns matplotlib heatmap with cluster dendrograms.
- dfr - pandas DataFrame with relevant data
- outfilename - path to output file (indicates output format)
- params - a list of parameters for plotting: [colormap, vmin, vmax]
- l... | Returns matplotlib heatmap with cluster dendrograms.
- dfr - pandas DataFrame with relevant data
- outfilename - path to output file (indicates output format)
- params - a list of parameters for plotting: [colormap, vmin, vmax]
- labels - dictionary of alternative labels, keyed by default sequence
... | Below is the the instruction that describes the task:
### Input:
Returns matplotlib heatmap with cluster dendrograms.
- dfr - pandas DataFrame with relevant data
- outfilename - path to output file (indicates output format)
- params - a list of parameters for plotting: [colormap, vmin, vmax]
- labe... |
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_ret) as fret
from returns
where fun = '{0}'
group by fun, id
'''.format(fun)
data = serv.que... | Return a dict of the last function called for all minions | Below is the the instruction that describes the task:
### Input:
Return a dict of the last function called for all minions
### Response:
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
sql = '''select first(id) as fid, first(full_r... |
def storage_detail(self, name, timeout=10):
"""
Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
... | Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result | Below is the the instruction that describes the task:
### Input:
Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result
### Response:
def storage_detail(self, name, timeout=10):
... |
def nodes_touching_edge(edge_coord):
"""
Returns the two node coordinates which are on the given edge coordinate.
:return: list of 2 node coordinates which are on the given edge coordinate, list(int)
"""
a, b = hex_digit(edge_coord, 1), hex_digit(edge_coord, 2)
if a % 2 == 0 and b % 2 == 0:
... | Returns the two node coordinates which are on the given edge coordinate.
:return: list of 2 node coordinates which are on the given edge coordinate, list(int) | Below is the the instruction that describes the task:
### Input:
Returns the two node coordinates which are on the given edge coordinate.
:return: list of 2 node coordinates which are on the given edge coordinate, list(int)
### Response:
def nodes_touching_edge(edge_coord):
"""
Returns the two node co... |
def open_application(self, remote_url, alias=None, **kwargs):
"""Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* ... | Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* | *Man.* | *Description* |
| remote_url | Yes ... | Below is the the instruction that describes the task:
### Input:
Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* | ... |
def memoize_with_ttl(ttl_secs=60 * 60 * 24):
"""Memoizes return values of the decorated function for a given time-to-live.
Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache()
is called on the function or the time-to-live expires. By default, the time-to-live is ... | Memoizes return values of the decorated function for a given time-to-live.
Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache()
is called on the function or the time-to-live expires. By default, the time-to-live is set to
24 hours. | Below is the the instruction that describes the task:
### Input:
Memoizes return values of the decorated function for a given time-to-live.
Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache()
is called on the function or the time-to-live expires. By default, the... |
def visit_DictComp(self, node: ast.DictComp) -> Any:
"""Compile the dictionary comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
... | Compile the dictionary comprehension as a function and call it. | Below is the the instruction that describes the task:
### Input:
Compile the dictionary comprehension as a function and call it.
### Response:
def visit_DictComp(self, node: ast.DictComp) -> Any:
"""Compile the dictionary comprehension as a function and call it."""
result = self._execute_comprehens... |
def forget_importer(name):
'''
forget_importer(name) yields True if an importer of type name was successfully forgotten from
the neuropythy importers list and false otherwise. This function must be called before an
importer can be replaced.
'''
global importers
name = name.lower()
if... | forget_importer(name) yields True if an importer of type name was successfully forgotten from
the neuropythy importers list and false otherwise. This function must be called before an
importer can be replaced. | Below is the the instruction that describes the task:
### Input:
forget_importer(name) yields True if an importer of type name was successfully forgotten from
the neuropythy importers list and false otherwise. This function must be called before an
importer can be replaced.
### Response:
def forget_imp... |
def _config_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine config
location.
"""
_check_old_config_root()
fallback = os.path.expanduser('~/.local/share')
key = 'XDG_CONFIG_HOME'
root = os.environ.get(key, None) or fallback
return os.path.join(root, 'python_ke... | Use freedesktop.org Base Dir Specfication to determine config
location. | Below is the the instruction that describes the task:
### Input:
Use freedesktop.org Base Dir Specfication to determine config
location.
### Response:
def _config_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine config
location.
"""
_check_old_config_root()
fallb... |
def load_config(self):
"""Loads the configuration."""
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value) | Loads the configuration. | Below is the the instruction that describes the task:
### Input:
Loads the configuration.
### Response:
def load_config(self):
"""Loads the configuration."""
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for ... |
def properties(self) -> dict:
"""
Returns the properties of the current node in the iteration.
"""
if isinstance(self._last_node, dict):
return self._last_node.keys()
else:
return {} | Returns the properties of the current node in the iteration. | Below is the the instruction that describes the task:
### Input:
Returns the properties of the current node in the iteration.
### Response:
def properties(self) -> dict:
"""
Returns the properties of the current node in the iteration.
"""
if isinstance(self._last_node, dict):
... |
def __get_bundle_data(self, bundleId):
"""``GET /{serviceInstanceId}/v2/bundles/{bundleId}``
Gets the bundle's information.
"""
url = self.__get_base_bundle_url() + '/' + bundleId
response = self.__perform_rest_call(requestURL=url)
if not response:
... | ``GET /{serviceInstanceId}/v2/bundles/{bundleId}``
Gets the bundle's information. | Below is the the instruction that describes the task:
### Input:
``GET /{serviceInstanceId}/v2/bundles/{bundleId}``
Gets the bundle's information.
### Response:
def __get_bundle_data(self, bundleId):
"""``GET /{serviceInstanceId}/v2/bundles/{bundleId}``
Gets the bundle's information.... |
def validate(self, data): # pylint: disable=arguments-differ
"""
Validate that at least one of the user identifier fields has been passed in.
"""
lms_user_id = data.get('lms_user_id')
tpa_user_id = data.get('tpa_user_id')
user_email = data.get('user_email')
if no... | Validate that at least one of the user identifier fields has been passed in. | Below is the the instruction that describes the task:
### Input:
Validate that at least one of the user identifier fields has been passed in.
### Response:
def validate(self, data): # pylint: disable=arguments-differ
"""
Validate that at least one of the user identifier fields has been passed in.
... |
def print_traceback(self, always_print=False):
"""
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
"""
if self._exception or always_print:
... | Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false) | Below is the the instruction that describes the task:
### Input:
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
### Response:
def print_traceback(self, always_print=Fals... |
def Zoom(self, zoomLevel: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern2::Zoom.
Zoom the viewport of the control.
zoomLevel: float for int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https:/... | Call IUIAutomationTransformPattern2::Zoom.
Zoom the viewport of the control.
zoomLevel: float for int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationt... | Below is the the instruction that describes the task:
### Input:
Call IUIAutomationTransformPattern2::Zoom.
Zoom the viewport of the control.
zoomLevel: float for int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/window... |
def _getCandidateParticleAndSwarm (self, exhaustedSwarmId=None):
"""Find or create a candidate particle to produce a new model.
At any one time, there is an active set of swarms in the current sprint, where
each swarm in the sprint represents a particular combination of fields.
Ideally, we should try t... | Find or create a candidate particle to produce a new model.
At any one time, there is an active set of swarms in the current sprint, where
each swarm in the sprint represents a particular combination of fields.
Ideally, we should try to balance the number of models we have evaluated for
each swarm at a... | Below is the the instruction that describes the task:
### Input:
Find or create a candidate particle to produce a new model.
At any one time, there is an active set of swarms in the current sprint, where
each swarm in the sprint represents a particular combination of fields.
Ideally, we should try to b... |
def lower(self):
"""Lower bound"""
if self._reaction in self._view._flipped:
return -super(FlipableFluxBounds, self).upper
return super(FlipableFluxBounds, self).lower | Lower bound | Below is the the instruction that describes the task:
### Input:
Lower bound
### Response:
def lower(self):
"""Lower bound"""
if self._reaction in self._view._flipped:
return -super(FlipableFluxBounds, self).upper
return super(FlipableFluxBounds, self).lower |
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
state = self.state
while state.in_queue.qsize():
try:
obj = state.in_queue.get()
except Exception:
time.sleep(0.05)
... | the redraw timer ensures we show new map tiles as they
are downloaded | Below is the the instruction that describes the task:
### Input:
the redraw timer ensures we show new map tiles as they
are downloaded
### Response:
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
state = self.state
... |
def variance_larger_than_standard_deviation(x):
"""
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x
being larger than 1
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this featur... | Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x
being larger than 1
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: bool | Below is the the instruction that describes the task:
### Input:
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x
being larger than 1
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of th... |
def resolve_heron_suffix_issue(abs_pex_path, class_path):
"""Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this Heron ... | Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this Heron Instance pex package (heron.instance.src.python...), making the... | Below is the the instruction that describes the task:
### Input:
Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this ... |
def indented_tree_line_generator(el, max_lines=None):
"""
Like tree_line_generator, but yields tuples (start_ref, end_ref, line),
where the line already takes the indentation into account by having "> "
prepended. If a line already starts with ">", it is escaped ("\\>"). This
makes it possible to re... | Like tree_line_generator, but yields tuples (start_ref, end_ref, line),
where the line already takes the indentation into account by having "> "
prepended. If a line already starts with ">", it is escaped ("\\>"). This
makes it possible to reliably use methods that analyze plain text to detect
quoting. | Below is the the instruction that describes the task:
### Input:
Like tree_line_generator, but yields tuples (start_ref, end_ref, line),
where the line already takes the indentation into account by having "> "
prepended. If a line already starts with ">", it is escaped ("\\>"). This
makes it possible to... |
def dst_to_src(self, dst_file):
"""Map destination path to source URI."""
for map in self.mappings:
src_uri = map.dst_to_src(dst_file)
if (src_uri is not None):
return(src_uri)
# Must have failed if loop exited
raise MapperError(
"Unabl... | Map destination path to source URI. | Below is the the instruction that describes the task:
### Input:
Map destination path to source URI.
### Response:
def dst_to_src(self, dst_file):
"""Map destination path to source URI."""
for map in self.mappings:
src_uri = map.dst_to_src(dst_file)
if (src_uri is not None):... |
def migrateFileFields(portal):
"""
This function walks over all attachment types and migrates their FileField
fields.
"""
portal_types = [
"Attachment",
"ARImport",
"Instrument",
"InstrumentCertification",
"Method",
"Multifile",
"Report",
... | This function walks over all attachment types and migrates their FileField
fields. | Below is the the instruction that describes the task:
### Input:
This function walks over all attachment types and migrates their FileField
fields.
### Response:
def migrateFileFields(portal):
"""
This function walks over all attachment types and migrates their FileField
fields.
"""
portal_... |
def write_table_report(summary_dict, seqid, genus):
"""
Parse the PointFinder table output, and write a summary report
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:param genus: MASH-calculat... | Parse the PointFinder table output, and write a summary report
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:param genus: MASH-calculated genus of current isolate | Below is the the instruction that describes the task:
### Input:
Parse the PointFinder table output, and write a summary report
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:param genus: MASH-calculated ... |
def absent(name, entry=None, entries=None, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Netwo... | .. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Network family, ipv4 or ipv6. | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Network family, i... |
def add_handler(self, fn, handle=None, persist=True,
policy=None, respondent=None,
overwrite=False):
"""
Invoke `fn(msg)` on the :class:`Broker` thread for each Message sent to
`handle` from this context. Unregister after one invocation if
`persist... | Invoke `fn(msg)` on the :class:`Broker` thread for each Message sent to
`handle` from this context. Unregister after one invocation if
`persist` is :data:`False`. If `handle` is :data:`None`, a new handle
is allocated and returned.
:param int handle:
If not :data:`None`, an ... | Below is the the instruction that describes the task:
### Input:
Invoke `fn(msg)` on the :class:`Broker` thread for each Message sent to
`handle` from this context. Unregister after one invocation if
`persist` is :data:`False`. If `handle` is :data:`None`, a new handle
is allocated and retur... |
def extract_contours(array, tile, interval=100, field='elev', base=0):
"""
Extract contour lines from an array.
Parameters
----------
array : array
input elevation data
tile : Tile
tile covering the array
interval : integer
elevation value interval when drawing conto... | Extract contour lines from an array.
Parameters
----------
array : array
input elevation data
tile : Tile
tile covering the array
interval : integer
elevation value interval when drawing contour lines
field : string
output field name containing elevation value
... | Below is the the instruction that describes the task:
### Input:
Extract contour lines from an array.
Parameters
----------
array : array
input elevation data
tile : Tile
tile covering the array
interval : integer
elevation value interval when drawing contour lines
f... |
def compare(self):
"""
Main comparison function
"""
"""
Note: Make sure to be able to handle these ref/test scenarios:
A:
o----o---o---o
x-------x----x
B:
o----o-----o---o
x--------x--x--x
C:
o------o-----o---o
... | Main comparison function | Below is the the instruction that describes the task:
### Input:
Main comparison function
### Response:
def compare(self):
"""
Main comparison function
"""
"""
Note: Make sure to be able to handle these ref/test scenarios:
A:
o----o---o---o
x-------x... |
def get_azure_cli_credentials(resource=None, with_tenant=False):
"""Return Credentials and default SubscriptionID of current loaded profile of the CLI.
Credentials will be the "az login" command:
https://docs.microsoft.com/cli/azure/authenticate-azure-cli
Default subscription ID is either the only one... | Return Credentials and default SubscriptionID of current loaded profile of the CLI.
Credentials will be the "az login" command:
https://docs.microsoft.com/cli/azure/authenticate-azure-cli
Default subscription ID is either the only one you have, or you can define it:
https://docs.microsoft.com/cli/azur... | Below is the the instruction that describes the task:
### Input:
Return Credentials and default SubscriptionID of current loaded profile of the CLI.
Credentials will be the "az login" command:
https://docs.microsoft.com/cli/azure/authenticate-azure-cli
Default subscription ID is either the only one yo... |
def set_listener(self, name, listener):
"""
Set a named listener to use with this connection.
See :py:class:`stomp.listener.ConnectionListener`
:param str name: the name of the listener
:param ConnectionListener listener: the listener object
"""
with self.__liste... | Set a named listener to use with this connection.
See :py:class:`stomp.listener.ConnectionListener`
:param str name: the name of the listener
:param ConnectionListener listener: the listener object | Below is the the instruction that describes the task:
### Input:
Set a named listener to use with this connection.
See :py:class:`stomp.listener.ConnectionListener`
:param str name: the name of the listener
:param ConnectionListener listener: the listener object
### Response:
def set_liste... |
def normalize(self, inplace=True):
"""
Normalizes the values of factor so that they sum to 1.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor
Returns
-------
... | Normalizes the values of factor so that they sum to 1.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor
Returns
-------
DiscreteFactor or None: if inplace=True (default) retur... | Below is the the instruction that describes the task:
### Input:
Normalizes the values of factor so that they sum to 1.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor
Returns
--... |
def get_first_of_week(self):
"""
Returns an integer representing the first day of the week.
0 represents Monday, 6 represents Sunday.
"""
if self.first_of_week is None:
raise ImproperlyConfigured("%s.first_of_week is required." % self.__class__.__name__)
if s... | Returns an integer representing the first day of the week.
0 represents Monday, 6 represents Sunday. | Below is the the instruction that describes the task:
### Input:
Returns an integer representing the first day of the week.
0 represents Monday, 6 represents Sunday.
### Response:
def get_first_of_week(self):
"""
Returns an integer representing the first day of the week.
0 represe... |
def children(self):
"""
Children matches.
"""
if self._children is None:
self._children = Matches(None, self.input_string)
return self._children | Children matches. | Below is the the instruction that describes the task:
### Input:
Children matches.
### Response:
def children(self):
"""
Children matches.
"""
if self._children is None:
self._children = Matches(None, self.input_string)
return self._children |
def str_summaryline(self):
"""Print: 47 GOs, 262 genes described by 10 of 19 sections consistent_increase."""
return "{N} GOs, {M} genes described by {X} of {Y} sections {NM}".format(
N=len(self.go2nt), M=len(self.gene2gos),
X=len(self.sec2chr), Y=len(self.datobj.sec2chr), NM=sel... | Print: 47 GOs, 262 genes described by 10 of 19 sections consistent_increase. | Below is the the instruction that describes the task:
### Input:
Print: 47 GOs, 262 genes described by 10 of 19 sections consistent_increase.
### Response:
def str_summaryline(self):
"""Print: 47 GOs, 262 genes described by 10 of 19 sections consistent_increase."""
return "{N} GOs, {M} genes descri... |
def AddClusterTags(r, tags, dry_run=False):
"""
Adds tags to the cluster.
@type tags: list of str
@param tags: tags to add to the cluster
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: int
@return: job id
"""
query = {
"dry-run": dry_run,
... | Adds tags to the cluster.
@type tags: list of str
@param tags: tags to add to the cluster
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: int
@return: job id | Below is the the instruction that describes the task:
### Input:
Adds tags to the cluster.
@type tags: list of str
@param tags: tags to add to the cluster
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: int
@return: job id
### Response:
def AddClusterTags(r, tags,... |
def get(self, data_view_id):
"""
Gets basic information about a view
:param data_view_id: Identifier of the data view
:return: Metadata about the view as JSON
"""
failure_message = "Dataview get failed"
return self._get_success_json(self._get(
'v1/da... | Gets basic information about a view
:param data_view_id: Identifier of the data view
:return: Metadata about the view as JSON | Below is the the instruction that describes the task:
### Input:
Gets basic information about a view
:param data_view_id: Identifier of the data view
:return: Metadata about the view as JSON
### Response:
def get(self, data_view_id):
"""
Gets basic information about a view
... |
def _detect_encoding(readline):
"""Return file encoding."""
try:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(readline)[0]
return encoding
except (LookupError, SyntaxError, UnicodeDecodeError):
return 'latin-1' | Return file encoding. | Below is the the instruction that describes the task:
### Input:
Return file encoding.
### Response:
def _detect_encoding(readline):
"""Return file encoding."""
try:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(readline)[0]
retur... |
def list_basebackups(self, arg):
"""List basebackups from an object store"""
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
site = config.get_site_from_config(self.config, arg.site)
self.storage = self._get_object_storage(site, pgdata=Non... | List basebackups from an object store | Below is the the instruction that describes the task:
### Input:
List basebackups from an object store
### Response:
def list_basebackups(self, arg):
"""List basebackups from an object store"""
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
... |
def accuracy(mod_y, ref_y, summary=True, name="accuracy"):
"""Accuracy computation op.
Parameters
----------
mod_y : tf.Tensor
Model output tensor.
ref_y : tf.Tensor
Reference input tensor.
summary : bool, optional (default = True)
... | Accuracy computation op.
Parameters
----------
mod_y : tf.Tensor
Model output tensor.
ref_y : tf.Tensor
Reference input tensor.
summary : bool, optional (default = True)
Whether to save tf summary for the op.
Returns
------... | Below is the the instruction that describes the task:
### Input:
Accuracy computation op.
Parameters
----------
mod_y : tf.Tensor
Model output tensor.
ref_y : tf.Tensor
Reference input tensor.
summary : bool, optional (default = True)
W... |
def add_file_to_tree(tree, file_path, file_contents, is_executable=False):
"""Add a file to a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of the new file in the tree.
file_contents
The (UTF-8 encod... | Add a file to a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of the new file in the tree.
file_contents
The (UTF-8 encoded) contents of the new file.
is_executable
If ``True``, the ... | Below is the the instruction that describes the task:
### Input:
Add a file to a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of the new file in the tree.
file_contents
The (UTF-8 encoded) contents ... |
async def article(
self, title, description=None,
*, url=None, thumb=None, content=None,
id=None, text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
"""
Creates new inline result of article type.... | Creates new inline result of article type.
Args:
title (`str`):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
url (`str`, optional):
The URL to be shown f... | Below is the the instruction that describes the task:
### Input:
Creates new inline result of article type.
Args:
title (`str`):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
... |
def to_curl(request, compressed=False, verify=True):
"""
Returns string with curl command by provided request object
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result
"""
parts = [
('curl', None),
('-X', request.me... | Returns string with curl command by provided request object
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result | Below is the the instruction that describes the task:
### Input:
Returns string with curl command by provided request object
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result
### Response:
def to_curl(request, compressed=False, verify=True):... |
def objects_to_root(objects: List) -> Root:
"""
Convert a list of s3 ObjectSummaries into a directory tree.
:param objects: The list of objects, e.g. the result of calling
`.objects.all()` on a bucket.
:return: The tree structure, contained within a root node.
"""
def _to_t... | Convert a list of s3 ObjectSummaries into a directory tree.
:param objects: The list of objects, e.g. the result of calling
`.objects.all()` on a bucket.
:return: The tree structure, contained within a root node. | Below is the the instruction that describes the task:
### Input:
Convert a list of s3 ObjectSummaries into a directory tree.
:param objects: The list of objects, e.g. the result of calling
`.objects.all()` on a bucket.
:return: The tree structure, contained within a root node.
### Respo... |
def _earth_orientation(date):
"""Earth orientation parameters in degrees
"""
ttt = date.change_scale('TT').julian_century
# a_a = 0.12
# a_c = 0.26
# s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt
s_prime = - 0.000047 * ttt
return date.eop.x / 3600., date.eop.y / 3600., s_prime ... | Earth orientation parameters in degrees | Below is the the instruction that describes the task:
### Input:
Earth orientation parameters in degrees
### Response:
def _earth_orientation(date):
"""Earth orientation parameters in degrees
"""
ttt = date.change_scale('TT').julian_century
# a_a = 0.12
# a_c = 0.26
# s_prime = -0.0015 * (... |
def addAxes(axtype=None, c=None):
"""Draw axes on scene. Available axes types:
:param int axtype:
- 0, no axes,
- 1, draw three gray grid walls
- 2, show cartesian axes from (0,0,0)
- 3, show positive range of cartesian axes from (0,0,0)
- 4, show a triad... | Draw axes on scene. Available axes types:
:param int axtype:
- 0, no axes,
- 1, draw three gray grid walls
- 2, show cartesian axes from (0,0,0)
- 3, show positive range of cartesian axes from (0,0,0)
- 4, show a triad at bottom left
- 5, show a cu... | Below is the the instruction that describes the task:
### Input:
Draw axes on scene. Available axes types:
:param int axtype:
- 0, no axes,
- 1, draw three gray grid walls
- 2, show cartesian axes from (0,0,0)
- 3, show positive range of cartesian axes from (0,0,0)
... |
def _meco_frequency(m1, m2, chi1, chi2):
"""Returns the frequency of the minimum energy cutoff for 3.5pN (2.5pN spin)
"""
return velocity_to_frequency(meco_velocity(m1, m2, chi1, chi2), m1+m2) | Returns the frequency of the minimum energy cutoff for 3.5pN (2.5pN spin) | Below is the the instruction that describes the task:
### Input:
Returns the frequency of the minimum energy cutoff for 3.5pN (2.5pN spin)
### Response:
def _meco_frequency(m1, m2, chi1, chi2):
"""Returns the frequency of the minimum energy cutoff for 3.5pN (2.5pN spin)
"""
return velocity_to_frequency... |
def plot_somas(somas):
'''Plot set of somas on same figure as spheres, each with different color'''
_, ax = common.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect': 'equal'})
for s in somas:
common.plot_sphere(ax, s.center, s.radius, color=rand... | Plot set of somas on same figure as spheres, each with different color | Below is the the instruction that describes the task:
### Input:
Plot set of somas on same figure as spheres, each with different color
### Response:
def plot_somas(somas):
'''Plot set of somas on same figure as spheres, each with different color'''
_, ax = common.get_figure(new_fig=True, subplot=111,
... |
def underflow(self, axis=0):
"""
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
"""
if axis not in range(3):
raise ValueError("axis must be 0, 1, or 2")
if self.DIM == 1:
return self.GetB... | Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array. | Below is the the instruction that describes the task:
### Input:
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
### Response:
def underflow(self, axis=0):
"""
Return the underflow for the given axis.
Depending on the dime... |
def __looks_like_html(response):
"""Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out.
"""
text = response.text.lstrip().lower()
return text.startswith('<html') or text.startswith('<!doctype') | Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out. | Below is the the instruction that describes the task:
### Input:
Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out.
### Response:
def __looks_like_html(response):
"""Guesses entity type when Content-Type header is missing... |
def process_char(buffer: str, char: str, mappings=_char_mappings):
"""This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be ... | This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be desireable.
Also backspace cant just be added to a string either, ther... | Below is the the instruction that describes the task:
### Input:
This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be desir... |
def remove_invalid_fields(self, queryset, fields, view, request):
"""
Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to
validate that all provided sort fields exist (as contrasted with the super's behavior
which is to silently remove invalid fields).
... | Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to
validate that all provided sort fields exist (as contrasted with the super's behavior
which is to silently remove invalid fields).
:raises ValidationError: if a sort field is invalid. | Below is the the instruction that describes the task:
### Input:
Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to
validate that all provided sort fields exist (as contrasted with the super's behavior
which is to silently remove invalid fields).
:raises Valida... |
def shlex_split(s, **kwargs):
'''
Only split if variable is a string
'''
if isinstance(s, six.string_types):
# On PY2, shlex.split will fail with unicode types if there are
# non-ascii characters in the string. So, we need to make sure we
# invoke it with a str type, and then dec... | Only split if variable is a string | Below is the the instruction that describes the task:
### Input:
Only split if variable is a string
### Response:
def shlex_split(s, **kwargs):
'''
Only split if variable is a string
'''
if isinstance(s, six.string_types):
# On PY2, shlex.split will fail with unicode types if there are
... |
def StartsWithIgnoreCase(self, value):
"""Sets the type of the WHERE clause as "starts with ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateSingleValueCondition(value,
... | Sets the type of the WHERE clause as "starts with ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to. | Below is the the instruction that describes the task:
### Input:
Sets the type of the WHERE clause as "starts with ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
### Response:
def StartsWithIgnoreCase(self, ... |
def _exc_middleware_factory(app):
"""Handle exceptions.
Route exceptions to handlers if they are registered in application.
"""
@web.middleware
async def middleware(request, handler):
try:
return await handler(request)
except Exception as exc:
for cls in typ... | Handle exceptions.
Route exceptions to handlers if they are registered in application. | Below is the the instruction that describes the task:
### Input:
Handle exceptions.
Route exceptions to handlers if they are registered in application.
### Response:
def _exc_middleware_factory(app):
"""Handle exceptions.
Route exceptions to handlers if they are registered in application.
"""
... |
def addSuccess(self, test: unittest.case.TestCase) -> None:
"""
Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
"""
# noinspection PyTypeChecker
self.add_result(TestState.success, test) | Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save | Below is the the instruction that describes the task:
### Input:
Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
### Response:
def addSuccess(self, test: unittest.case.TestCase) -> None:
"""
Transforms the test ... |
def mul(self, other, axis="columns", level=None, fill_value=None):
"""Multiplies this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the multiply against this.
axis: The axis to multiply over.
level: The Multilevel in... | Multiplies this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the multiply against this.
axis: The axis to multiply over.
level: The Multilevel index level to apply multiply over.
fill_value: The value to fill Na... | Below is the the instruction that describes the task:
### Input:
Multiplies this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the multiply against this.
axis: The axis to multiply over.
level: The Multilevel index level ... |
def fastaSubtract(fastaFiles):
"""
Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An ite... | Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An iterator producing C{Bio.SeqRecord} instances ... | Below is the the instruction that describes the task:
### Input:
Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty... |
def _parse_sig(sig, arg_names, validate=False):
"""
Parses signatures into a ``OrderedDict`` of paramName => type.
Numerically-indexed arguments that do not correspond to an argument
name in python (ie: it takes a variable number of arguments) will be
keyed as the stringified version of it's index.
... | Parses signatures into a ``OrderedDict`` of paramName => type.
Numerically-indexed arguments that do not correspond to an argument
name in python (ie: it takes a variable number of arguments) will be
keyed as the stringified version of it's index.
sig the signature to be parsed
arg_name... | Below is the the instruction that describes the task:
### Input:
Parses signatures into a ``OrderedDict`` of paramName => type.
Numerically-indexed arguments that do not correspond to an argument
name in python (ie: it takes a variable number of arguments) will be
keyed as the stringified version of it'... |
def File(self, name, directory = None, create = 1):
"""Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supp... | Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supplied at construction
time) if no directory is supplied.... | Below is the the instruction that describes the task:
### Input:
Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS... |
def create_admin(self, account_id, user_id, role):
"""
Flag an existing user as an admin within the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.create
"""
url = ADMINS_API.format(account_id)
body = {"user_id": unquote(str(user_id)),
... | Flag an existing user as an admin within the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.create | Below is the the instruction that describes the task:
### Input:
Flag an existing user as an admin within the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.create
### Response:
def create_admin(self, account_id, user_id, role):
"""
Flag an existing user as an ad... |
def best_buy_1(self):
""" 量大收紅
:rtype: bool
"""
result = self.data.value[-1] > self.data.value[-2] and \
self.data.price[-1] > self.data.openprice[-1]
return result | 量大收紅
:rtype: bool | Below is the the instruction that describes the task:
### Input:
量大收紅
:rtype: bool
### Response:
def best_buy_1(self):
""" 量大收紅
:rtype: bool
"""
result = self.data.value[-1] > self.data.value[-2] and \
self.data.price[-1] > self.data.openprice[-1]
... |
def preprocess(pipeline, args):
"""Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matche... | Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matches the serving csv that a trained mode... | Below is the the instruction that describes the task:
### Input:
Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced ... |
def observe_all(self, callback: Callable[[str, Any, Any], None]):
"""Subscribes to all keys changes"""
self._all_callbacks.append(callback) | Subscribes to all keys changes | Below is the the instruction that describes the task:
### Input:
Subscribes to all keys changes
### Response:
def observe_all(self, callback: Callable[[str, Any, Any], None]):
"""Subscribes to all keys changes"""
self._all_callbacks.append(callback) |
def _execute_expression(self, expression: Any):
"""
This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we eval... | This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we evaluate all elements of the list.
If it's a constant (or a zero... | Below is the the instruction that describes the task:
### Input:
This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we eva... |
def cardInfo(self, resource_id):
"""Return card info.
:params resource_id: Resource id.
"""
# TODO: add referer to headers (futweb)
base_id = baseId(resource_id)
if base_id in self.players:
return self.players[base_id]
else: # not a player?
... | Return card info.
:params resource_id: Resource id. | Below is the the instruction that describes the task:
### Input:
Return card info.
:params resource_id: Resource id.
### Response:
def cardInfo(self, resource_id):
"""Return card info.
:params resource_id: Resource id.
"""
# TODO: add referer to headers (futweb)
ba... |
def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.default_buffer:
try:
line_no = self.default_buffer.docum... | When the cursor changes in the default buffer. Synchronize with
history buffer. | Below is the the instruction that describes the task:
### Input:
When the cursor changes in the default buffer. Synchronize with
history buffer.
### Response:
def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
... |
def alignment_correcter(self, alignment_file_list, output_file_name,
filter_minimum=None):
'''
Remove lower case insertions in alignment outputs from HMM align. Give
a list of alignments, and an output file name, and each alignment will
be corrected, and writt... | Remove lower case insertions in alignment outputs from HMM align. Give
a list of alignments, and an output file name, and each alignment will
be corrected, and written to a single file, ready to be placed together
using pplacer.
Parameters
----------
alignment_file_list ... | Below is the the instruction that describes the task:
### Input:
Remove lower case insertions in alignment outputs from HMM align. Give
a list of alignments, and an output file name, and each alignment will
be corrected, and written to a single file, ready to be placed together
using pplacer... |
def humanize_bytes(bytesize, precision=2):
"""
Humanize byte size figures
https://gist.github.com/moird/3684595
"""
abbrevs = (
(1 << 50, 'PB'),
(1 << 40, 'TB'),
(1 << 30, 'GB'),
(1 << 20, 'MB'),
(1 << 10, 'kB'),
(1, 'bytes')
)
if bytesize == ... | Humanize byte size figures
https://gist.github.com/moird/3684595 | Below is the the instruction that describes the task:
### Input:
Humanize byte size figures
https://gist.github.com/moird/3684595
### Response:
def humanize_bytes(bytesize, precision=2):
"""
Humanize byte size figures
https://gist.github.com/moird/3684595
"""
abbrevs = (
(1 << 50,... |
def blastparser(self, report, sample, fieldnames):
"""
Parse the number of core genes present in the strain from the BLAST outputs
:param report: the name and path of the BLAST outputs
:param sample: the sample object
:param fieldnames: type LIST: List of fields used to in BLAST ... | Parse the number of core genes present in the strain from the BLAST outputs
:param report: the name and path of the BLAST outputs
:param sample: the sample object
:param fieldnames: type LIST: List of fields used to in BLAST analyses | Below is the the instruction that describes the task:
### Input:
Parse the number of core genes present in the strain from the BLAST outputs
:param report: the name and path of the BLAST outputs
:param sample: the sample object
:param fieldnames: type LIST: List of fields used to in BLAST an... |
def find_stream(cls, fileobj, max_bytes):
"""Returns a possibly valid _ADTSStream or None.
Args:
max_bytes (int): maximum bytes to read
"""
r = BitReader(fileobj)
stream = cls(r)
if stream.sync(max_bytes):
stream.offset = (r.get_position() - 12) ... | Returns a possibly valid _ADTSStream or None.
Args:
max_bytes (int): maximum bytes to read | Below is the the instruction that describes the task:
### Input:
Returns a possibly valid _ADTSStream or None.
Args:
max_bytes (int): maximum bytes to read
### Response:
def find_stream(cls, fileobj, max_bytes):
"""Returns a possibly valid _ADTSStream or None.
Args:
... |
def by_identifier_secret(self, request):
"""
Authenticates a client by its identifier and secret (aka password).
:param request: The incoming request
:type request: oauth2.web.Request
:return: The identified client
:rtype: oauth2.datatype.Client
:raises OAuthIn... | Authenticates a client by its identifier and secret (aka password).
:param request: The incoming request
:type request: oauth2.web.Request
:return: The identified client
:rtype: oauth2.datatype.Client
:raises OAuthInvalidError: If the client could not be found, is not
... | Below is the the instruction that describes the task:
### Input:
Authenticates a client by its identifier and secret (aka password).
:param request: The incoming request
:type request: oauth2.web.Request
:return: The identified client
:rtype: oauth2.datatype.Client
:raises... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.