code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def option(self, key, value):
"""Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone.
"""
self._jreader = self._jreader.option(key, to_str(value))
return self | Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone. | Below is the the instruction that describes the task:
### Input:
Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone.
### Response:
def option(self, key, value):
"""Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone.
"""
self._jreader = self._jreader.option(key, to_str(value))
return self |
def convert_out(self, obj):
"""Write EMIRUUID header on reduction"""
newobj = super(ProcessedImageProduct, self).convert_out(obj)
if newobj:
hdulist = newobj.open()
hdr = hdulist[0].header
if 'EMIRUUID' not in hdr:
hdr['EMIRUUID'] = str(uuid.uuid1())
return newobj | Write EMIRUUID header on reduction | Below is the the instruction that describes the task:
### Input:
Write EMIRUUID header on reduction
### Response:
def convert_out(self, obj):
"""Write EMIRUUID header on reduction"""
newobj = super(ProcessedImageProduct, self).convert_out(obj)
if newobj:
hdulist = newobj.open()
hdr = hdulist[0].header
if 'EMIRUUID' not in hdr:
hdr['EMIRUUID'] = str(uuid.uuid1())
return newobj |
def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response."""
try:
return super(WebSocketRpcRequest, self)._handle_exception(exception)
except Exception:
if not isinstance(exception, (odoo.exceptions.Warning, odoo.http.SessionExpiredException, odoo.exceptions.except_orm)):
_logger.exception("Exception during JSON request handling.")
error = {
'code': 200,
'message': "Odoo Server Error",
'data': odoo.http.serialize_exception(exception)
}
if isinstance(exception, odoo.http.AuthenticationError):
error['code'] = 100
error['message'] = "Odoo Session Invalid"
if isinstance(exception, odoo.http.SessionExpiredException):
error['code'] = 100
error['message'] = "Odoo Session Expired"
return self._json_response(error=error) | Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response. | Below is the the instruction that describes the task:
### Input:
Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response.
### Response:
def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response."""
try:
return super(WebSocketRpcRequest, self)._handle_exception(exception)
except Exception:
if not isinstance(exception, (odoo.exceptions.Warning, odoo.http.SessionExpiredException, odoo.exceptions.except_orm)):
_logger.exception("Exception during JSON request handling.")
error = {
'code': 200,
'message': "Odoo Server Error",
'data': odoo.http.serialize_exception(exception)
}
if isinstance(exception, odoo.http.AuthenticationError):
error['code'] = 100
error['message'] = "Odoo Session Invalid"
if isinstance(exception, odoo.http.SessionExpiredException):
error['code'] = 100
error['message'] = "Odoo Session Expired"
return self._json_response(error=error) |
def prebuild_arch(self, arch):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
if hasattr(self, prebuild):
getattr(self, prebuild)()
else:
info('{} has no {}, skipping'.format(self.name, prebuild)) | Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so. | Below is the the instruction that describes the task:
### Input:
Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.
### Response:
def prebuild_arch(self, arch):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
if hasattr(self, prebuild):
getattr(self, prebuild)()
else:
info('{} has no {}, skipping'.format(self.name, prebuild)) |
def _put(self, timestamp, value):
"""Replace the value associated with "timestamp" or add the new value"""
idx = self._lookup(timestamp)
if idx is not None:
self._values[idx] = (timestamp, value)
else:
self._values.append((timestamp, value)) | Replace the value associated with "timestamp" or add the new value | Below is the the instruction that describes the task:
### Input:
Replace the value associated with "timestamp" or add the new value
### Response:
def _put(self, timestamp, value):
"""Replace the value associated with "timestamp" or add the new value"""
idx = self._lookup(timestamp)
if idx is not None:
self._values[idx] = (timestamp, value)
else:
self._values.append((timestamp, value)) |
def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
ids = map(api.get_id, brains)
return ids | Return a list of ids sharing the same portal type and prefix | Below is the the instruction that describes the task:
### Input:
Return a list of ids sharing the same portal type and prefix
### Response:
def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
ids = map(api.get_id, brains)
return ids |
def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, memo.value)
raise ndb.Return(memo.value)
logging.info('memo fail: %d', n)
a = yield memoizing_fibonacci(n - 1)
b = yield memoizing_fibonacci(n - 2)
ans = a + b
memo = FibonacciMemo(key=key, arg=n, value=ans)
logging.info('memo write: %d -> %d', n, memo.value)
yield memo.put_async(ndb_should_cache=False)
raise ndb.Return(ans) | A memoizing recursive Fibonacci to exercise RPCs. | Below is the the instruction that describes the task:
### Input:
A memoizing recursive Fibonacci to exercise RPCs.
### Response:
def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, memo.value)
raise ndb.Return(memo.value)
logging.info('memo fail: %d', n)
a = yield memoizing_fibonacci(n - 1)
b = yield memoizing_fibonacci(n - 2)
ans = a + b
memo = FibonacciMemo(key=key, arg=n, value=ans)
logging.info('memo write: %d -> %d', n, memo.value)
yield memo.put_async(ndb_should_cache=False)
raise ndb.Return(ans) |
def contribute_to_class(self, cls, name):
"""Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
"""
super(StateField, self).contribute_to_class(cls, name)
parent_property = getattr(cls, self.name, None)
setattr(cls, self.name, StateFieldProperty(self, parent_property)) | Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute. | Below is the the instruction that describes the task:
### Input:
Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
### Response:
def contribute_to_class(self, cls, name):
"""Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
"""
super(StateField, self).contribute_to_class(cls, name)
parent_property = getattr(cls, self.name, None)
setattr(cls, self.name, StateFieldProperty(self, parent_property)) |
def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) | Make file user readable if it is not a link. | Below is the the instruction that describes the task:
### Input:
Make file user readable if it is not a link.
### Response:
def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) |
def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) | Serializer for consistency | Below is the the instruction that describes the task:
### Input:
Serializer for consistency
### Response:
def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) |
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._html:
self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
# Fall back to requests' detected encoding if decode fails.
try:
self.raw_html.decode(self.encoding, errors='replace')
except UnicodeDecodeError:
self._encoding = self.default_encoding
return self._encoding if self._encoding else self.default_encoding | The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers. | Below is the the instruction that describes the task:
### Input:
The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
### Response:
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._html:
self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
# Fall back to requests' detected encoding if decode fails.
try:
self.raw_html.decode(self.encoding, errors='replace')
except UnicodeDecodeError:
self._encoding = self.default_encoding
return self._encoding if self._encoding else self.default_encoding |
def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | Return the stored MD5 sum for a particular named resource. | Below is the the instruction that describes the task:
### Input:
Return the stored MD5 sum for a particular named resource.
### Response:
def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] |
def p_pvar_list(self, p):
'''pvar_list : pvar_list pvar_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1].append(p[2])
p[0] = p[1] | pvar_list : pvar_list pvar_def
| empty | Below is the the instruction that describes the task:
### Input:
pvar_list : pvar_list pvar_def
| empty
### Response:
def p_pvar_list(self, p):
'''pvar_list : pvar_list pvar_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1].append(p[2])
p[0] = p[1] |
def r12_serial_port(port):
''' Create a serial connect to the arm. '''
return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
stopbits=STOP_BITS, bytesize=BYTE_SIZE) | Create a serial connect to the arm. | Below is the the instruction that describes the task:
### Input:
Create a serial connect to the arm.
### Response:
def r12_serial_port(port):
''' Create a serial connect to the arm. '''
return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
stopbits=STOP_BITS, bytesize=BYTE_SIZE) |
def get_current_traceback(ignore_system_exceptions=False,
show_hidden_frames=False, skip=0):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
"""
exc_type, exc_value, tb = sys.exc_info()
if ignore_system_exceptions and exc_type in system_exceptions:
raise
for x in range_type(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb)
if not show_hidden_frames:
tb.filter_hidden_frames()
return tb | Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter. | Below is the the instruction that describes the task:
### Input:
Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
### Response:
def get_current_traceback(ignore_system_exceptions=False,
show_hidden_frames=False, skip=0):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
"""
exc_type, exc_value, tb = sys.exc_info()
if ignore_system_exceptions and exc_type in system_exceptions:
raise
for x in range_type(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb)
if not show_hidden_frames:
tb.filter_hidden_frames()
return tb |
def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
# Refer to the __set_format__ method for an explanation
# of the following construct.
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, int) or isinstance(val, long):
val_str = '0x%-8X' % (val)
if key == 'TimeDateStamp' or key == 'dwTimeStamp':
try:
val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
except exceptions.ValueError, e:
val_str += ' [INVALID TIME]'
else:
val_str = ''.join(filter(lambda c:c != '\0', str(val)))
dump.append('0x%-8X 0x%-3X %-30s %s' % (
self.__field_offsets__[key] + self.__file_offset__,
self.__field_offsets__[key], key+':', val_str))
return dump | Returns a string representation of the structure. | Below is the the instruction that describes the task:
### Input:
Returns a string representation of the structure.
### Response:
def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
# Refer to the __set_format__ method for an explanation
# of the following construct.
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, int) or isinstance(val, long):
val_str = '0x%-8X' % (val)
if key == 'TimeDateStamp' or key == 'dwTimeStamp':
try:
val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
except exceptions.ValueError, e:
val_str += ' [INVALID TIME]'
else:
val_str = ''.join(filter(lambda c:c != '\0', str(val)))
dump.append('0x%-8X 0x%-3X %-30s %s' % (
self.__field_offsets__[key] + self.__file_offset__,
self.__field_offsets__[key], key+':', val_str))
return dump |
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
if len(filenames) != 0:
findcmd = ['find']
findcmd.extend([util.shell_quote(x) for x in filenames])
findcmd.extend(['-print0', '|'])
cmdlist[0:0] = findcmd
cmdlist.append('-0')
cmdlist.extend([">", util.shell_quote(archive)])
return (cmdlist, {'shell': True}) | Create a CPIO archive. | Below is the the instruction that describes the task:
### Input:
Create a CPIO archive.
### Response:
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
if len(filenames) != 0:
findcmd = ['find']
findcmd.extend([util.shell_quote(x) for x in filenames])
findcmd.extend(['-print0', '|'])
cmdlist[0:0] = findcmd
cmdlist.append('-0')
cmdlist.extend([">", util.shell_quote(archive)])
return (cmdlist, {'shell': True}) |
def get_alternatives(self, rank):
"""
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
"""
if self.ranks_to_alts is None:
raise ValueError("Aggregate ranking must be created first")
try:
alts = self.ranks_to_alts[rank]
return alts
except KeyError:
raise KeyError("No ranking \"{}\" found in ".format(str(rank)) +
"the aggregate ranking") | Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist. | Below is the the instruction that describes the task:
### Input:
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
### Response:
def get_alternatives(self, rank):
"""
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
"""
if self.ranks_to_alts is None:
raise ValueError("Aggregate ranking must be created first")
try:
alts = self.ranks_to_alts[rank]
return alts
except KeyError:
raise KeyError("No ranking \"{}\" found in ".format(str(rank)) +
"the aggregate ranking") |
def copy_tree_and_replace_vars(self, src, dst):
"""
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
"""
if os.path.isdir(src):
copy_tree(src, self.temp_dir)
elif os.path.isfile(src):
shutil.copy(src, self.temp_dir)
for root, subdirs, files in os.walk(self.temp_dir, topdown=False):
for file in files:
self.replace_f(os.path.join(root, file))
for subdir in subdirs:
self.replace_d(os.path.join(root, subdir))
copy_tree(self.temp_dir, dst)
# Очистить временную директорию
shutil.rmtree(self.temp_dir)
os.makedirs(self.temp_dir) | Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться | Below is the the instruction that describes the task:
### Input:
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
### Response:
def copy_tree_and_replace_vars(self, src, dst):
"""
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
"""
if os.path.isdir(src):
copy_tree(src, self.temp_dir)
elif os.path.isfile(src):
shutil.copy(src, self.temp_dir)
for root, subdirs, files in os.walk(self.temp_dir, topdown=False):
for file in files:
self.replace_f(os.path.join(root, file))
for subdir in subdirs:
self.replace_d(os.path.join(root, subdir))
copy_tree(self.temp_dir, dst)
# Очистить временную директорию
shutil.rmtree(self.temp_dir)
os.makedirs(self.temp_dir) |
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry. | Below is the the instruction that describes the task:
### Input:
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
### Response:
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) |
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match | Checks if a target name matches with an input regular expression. | Below is the the instruction that describes the task:
### Input:
Checks if a target name matches with an input regular expression.
### Response:
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match |
def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None,
max_retries=-1, mount_point=DEFAULT_MOUNT_POINT):
"""Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'access_key': access_key,
'secret_key': secret_key,
'region': region,
'iam_endpoint': iam_endpoint,
'sts_endpoint': sts_endpoint,
'max_retries': max_retries,
}
api_path = '/v1/{mount_point}/config/root'.format(mount_point=mount_point)
return self._adapter.post(
url=api_path,
json=params,
) | Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response | Below is the the instruction that describes the task:
### Input:
Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
### Response:
def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None,
max_retries=-1, mount_point=DEFAULT_MOUNT_POINT):
"""Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'access_key': access_key,
'secret_key': secret_key,
'region': region,
'iam_endpoint': iam_endpoint,
'sts_endpoint': sts_endpoint,
'max_retries': max_retries,
}
api_path = '/v1/{mount_point}/config/root'.format(mount_point=mount_point)
return self._adapter.post(
url=api_path,
json=params,
) |
def get_role_secret_id(self, role_name, secret_id, mount_point='approle'):
"""POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
url = '/v1/auth/{0}/role/{1}/secret-id/lookup'.format(mount_point, role_name)
params = {
'secret_id': secret_id
}
return self._adapter.post(url, json=params).json() | POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
### Response:
def get_role_secret_id(self, role_name, secret_id, mount_point='approle'):
"""POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
url = '/v1/auth/{0}/role/{1}/secret-id/lookup'.format(mount_point, role_name)
params = {
'secret_id': secret_id
}
return self._adapter.post(url, json=params).json() |
def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] | Return a list of all genes. | Below is the the instruction that describes the task:
### Input:
Return a list of all genes.
### Response:
def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] |
def _add_conversation(self, conversation, events=[],
event_cont_token=None):
"""Add new conversation from hangouts_pb2.Conversation"""
# pylint: disable=dangerous-default-value
conv_id = conversation.conversation_id.id
logger.debug('Adding new conversation: {}'.format(conv_id))
conv = Conversation(self._client, self._user_list, conversation,
events, event_cont_token)
self._conv_dict[conv_id] = conv
return conv | Add new conversation from hangouts_pb2.Conversation | Below is the the instruction that describes the task:
### Input:
Add new conversation from hangouts_pb2.Conversation
### Response:
def _add_conversation(self, conversation, events=[],
event_cont_token=None):
"""Add new conversation from hangouts_pb2.Conversation"""
# pylint: disable=dangerous-default-value
conv_id = conversation.conversation_id.id
logger.debug('Adding new conversation: {}'.format(conv_id))
conv = Conversation(self._client, self._user_list, conversation,
events, event_cont_token)
self._conv_dict[conv_id] = conv
return conv |
def intensities_from_grid_radii(self, grid_radii):
"""
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
"""
np.seterr(all='ignore')
return np.multiply(self.intensity, np.exp(
np.multiply(-self.sersic_constant,
np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1)))) | Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid. | Below is the the instruction that describes the task:
### Input:
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
### Response:
def intensities_from_grid_radii(self, grid_radii):
"""
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
"""
np.seterr(all='ignore')
return np.multiply(self.intensity, np.exp(
np.multiply(-self.sersic_constant,
np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1)))) |
def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(self.nonlin)
sequence.append(nn.Dropout(self.dropout))
sequence = sequence[:-2]
if self.output_nonlin:
sequence.append(self.output_nonlin)
self.sequential = nn.Sequential(*sequence) | (Re)set all parameters. | Below is the the instruction that describes the task:
### Input:
(Re)set all parameters.
### Response:
def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(self.nonlin)
sequence.append(nn.Dropout(self.dropout))
sequence = sequence[:-2]
if self.output_nonlin:
sequence.append(self.output_nonlin)
self.sequential = nn.Sequential(*sequence) |
def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | Creates the directory tree if non existing. | Below is the the instruction that describes the task:
### Input:
Creates the directory tree if non existing.
### Response:
def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) |
def n_orifices_per_row_max(self):
"""A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
"""
c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr)
b = self.orifice_diameter + self.s_orifice
return math.floor(c/b) | A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe. | Below is the the instruction that describes the task:
### Input:
A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
### Response:
def n_orifices_per_row_max(self):
"""A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
"""
c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr)
b = self.orifice_diameter + self.s_orifice
return math.floor(c/b) |
def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
for exclude in excludes:
if root.startswith(exclude):
return True
return False | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | Below is the the instruction that describes the task:
### Input:
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
### Response:
def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
for exclude in excludes:
if root.startswith(exclude):
return True
return False |
def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if None in (beta, rho):
print("warning: 'theta', 'rho' should be positive float numbers.")
return m
else:
m[1, 0] = np.tan(beta) / rho
m[3, 2] = -np.tan(beta) / rho
return m | Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array | Below is the the instruction that describes the task:
### Input:
Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
### Response:
def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if None in (beta, rho):
print("warning: 'theta', 'rho' should be positive float numbers.")
return m
else:
m[1, 0] = np.tan(beta) / rho
m[3, 2] = -np.tan(beta) / rho
return m |
def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission
"""
obj = api.get_object(brain_or_object)
valid_roles = get_valid_roles_for(obj)
to_grant = list(get_roles_for_permission(permission, obj))
if isinstance(roles, basestring):
roles = [roles]
for role in roles:
if role not in to_grant:
if role not in valid_roles:
raise ValueError("The Role '{}' is invalid.".format(role))
# Append the role
to_grant.append(role)
manage_permission_for(obj, permission, to_grant, acquire=acquire) | Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission | Below is the the instruction that describes the task:
### Input:
Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission
### Response:
def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission
"""
obj = api.get_object(brain_or_object)
valid_roles = get_valid_roles_for(obj)
to_grant = list(get_roles_for_permission(permission, obj))
if isinstance(roles, basestring):
roles = [roles]
for role in roles:
if role not in to_grant:
if role not in valid_roles:
raise ValueError("The Role '{}' is invalid.".format(role))
# Append the role
to_grant.append(role)
manage_permission_for(obj, permission, to_grant, acquire=acquire) |
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret": self.appsecret
}
) | 获取 Access Token。
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
获取 Access Token。
:return: 返回的 JSON 数据包
### Response:
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret": self.appsecret
}
) |
def import_(module):
"""Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables')
"""
try:
return importlib.import_module(module)
except ImportError as e:
try:
message = MESSAGES[module]
except KeyError:
message = 'The code at {filename}:{line_number} requires the ' + module + ' package'
e = ImportError('No module named %s' % module)
frame, filename, line_number, function_name, lines, index = \
inspect.getouterframes(inspect.currentframe())[1]
m = message.format(filename=os.path.basename(filename), line_number=line_number)
m = textwrap.dedent(m)
bar = '\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\033[0m'
print('', file=sys.stderr)
print(bar, file=sys.stderr)
print(m, file=sys.stderr)
print(bar, file=sys.stderr)
raise DelayImportError(m) | Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables') | Below is the the instruction that describes the task:
### Input:
Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables')
### Response:
def import_(module):
"""Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables')
"""
try:
return importlib.import_module(module)
except ImportError as e:
try:
message = MESSAGES[module]
except KeyError:
message = 'The code at {filename}:{line_number} requires the ' + module + ' package'
e = ImportError('No module named %s' % module)
frame, filename, line_number, function_name, lines, index = \
inspect.getouterframes(inspect.currentframe())[1]
m = message.format(filename=os.path.basename(filename), line_number=line_number)
m = textwrap.dedent(m)
bar = '\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\033[0m'
print('', file=sys.stderr)
print(bar, file=sys.stderr)
print(m, file=sys.stderr)
print(bar, file=sys.stderr)
raise DelayImportError(m) |
def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List Artifacts associated with a BuildRecord
"""
data = list_built_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List Artifacts associated with a BuildRecord | Below is the the instruction that describes the task:
### Input:
List Artifacts associated with a BuildRecord
### Response:
def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List Artifacts associated with a BuildRecord
"""
data = list_built_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) |
def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
runas_user = runas
else:
runas_user = current_user
current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name
if group and group != current_grp:
set_grp = True
runas_grp = group
else:
runas_grp = current_grp
if set_runas or set_grp:
chugid(runas_user, runas_grp)
if umask is not None:
os.umask(umask) | Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process. | Below is the the instruction that describes the task:
### Input:
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
### Response:
def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
runas_user = runas
else:
runas_user = current_user
current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name
if group and group != current_grp:
set_grp = True
runas_grp = group
else:
runas_grp = current_grp
if set_runas or set_grp:
chugid(runas_user, runas_grp)
if umask is not None:
os.umask(umask) |
def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str = 'git remote prune origin'
# Attempt to force all output to plain ascii english, which is what some parsing code
# may expect.
# According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well
# just to be sure.
env = os.environ.copy()
env[b"LANGUAGE"] = b"C"
env[b"LC_ALL"] = b"C"
cmd = subprocess.Popen(
shlex.split(cmd_str),
close_fds=not salt.utils.platform.is_windows(),
cwd=os.path.dirname(self.gitdir),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = cmd.communicate()[0]
if six.PY3:
output = output.decode(__salt_system_encoding__)
if cmd.returncode != 0:
log.warning(
'Failed to prune stale branches for %s remote \'%s\'. '
'Output from \'%s\' follows:\n%s',
self.role, self.id, cmd_str, output
)
else:
marker = ' * [pruned] '
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith(marker):
cleaned.append(line[len(marker):].strip())
if cleaned:
log.debug(
'%s pruned the following stale refs: %s',
self.role, ', '.join(cleaned)
)
return cleaned | Remove stale refs so that they are no longer seen as fileserver envs | Below is the the instruction that describes the task:
### Input:
Remove stale refs so that they are no longer seen as fileserver envs
### Response:
def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str = 'git remote prune origin'
# Attempt to force all output to plain ascii english, which is what some parsing code
# may expect.
# According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well
# just to be sure.
env = os.environ.copy()
env[b"LANGUAGE"] = b"C"
env[b"LC_ALL"] = b"C"
cmd = subprocess.Popen(
shlex.split(cmd_str),
close_fds=not salt.utils.platform.is_windows(),
cwd=os.path.dirname(self.gitdir),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = cmd.communicate()[0]
if six.PY3:
output = output.decode(__salt_system_encoding__)
if cmd.returncode != 0:
log.warning(
'Failed to prune stale branches for %s remote \'%s\'. '
'Output from \'%s\' follows:\n%s',
self.role, self.id, cmd_str, output
)
else:
marker = ' * [pruned] '
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith(marker):
cleaned.append(line[len(marker):].strip())
if cleaned:
log.debug(
'%s pruned the following stale refs: %s',
self.role, ', '.join(cleaned)
)
return cleaned |
def get(self, aspect):
"""Get a network, system or configure or contextualize with the same id as aspect passed."""
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstance(aspect, t)]
assert len(aspect_list) == 1, "Unexpected aspect for RADL."
aspect_list = aspect_list[0]
old_aspect = [a for a in aspect_list if a.getId() == aspect.getId()]
return old_aspect[0] if old_aspect else None | Get a network, system or configure or contextualize with the same id as aspect passed. | Below is the the instruction that describes the task:
### Input:
Get a network, system or configure or contextualize with the same id as aspect passed.
### Response:
def get(self, aspect):
"""Get a network, system or configure or contextualize with the same id as aspect passed."""
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstance(aspect, t)]
assert len(aspect_list) == 1, "Unexpected aspect for RADL."
aspect_list = aspect_list[0]
old_aspect = [a for a in aspect_list if a.getId() == aspect.getId()]
return old_aspect[0] if old_aspect else None |
def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scenario':
# required_params_per_trt makes no sense for GMFs from file
self.add('required_params_per_trt')
self.add('rlzs_assoc', ds['csm_info'].get_rlzs_assoc())
if 'csm_info' in ds:
self.add('ruptures_per_trt')
if 'rup_data' in ds:
self.add('ruptures_events')
if oq.calculation_mode in ('event_based_risk',):
self.add('avglosses_data_transfer')
if 'exposure' in oq.inputs:
self.add('exposure_info')
if 'source_info' in ds:
self.add('slow_sources')
self.add('times_by_source_class')
self.add('dupl_sources')
if 'task_info' in ds:
self.add('task_info')
tasks = set(ds['task_info'])
if 'classical' in tasks:
self.add('task_hazard:0')
self.add('task_hazard:-1')
self.add('job_info')
if 'performance_data' in ds:
self.add('performance')
return self.text | Build the report and return a restructed text string | Below is the the instruction that describes the task:
### Input:
Build the report and return a restructed text string
### Response:
def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scenario':
# required_params_per_trt makes no sense for GMFs from file
self.add('required_params_per_trt')
self.add('rlzs_assoc', ds['csm_info'].get_rlzs_assoc())
if 'csm_info' in ds:
self.add('ruptures_per_trt')
if 'rup_data' in ds:
self.add('ruptures_events')
if oq.calculation_mode in ('event_based_risk',):
self.add('avglosses_data_transfer')
if 'exposure' in oq.inputs:
self.add('exposure_info')
if 'source_info' in ds:
self.add('slow_sources')
self.add('times_by_source_class')
self.add('dupl_sources')
if 'task_info' in ds:
self.add('task_info')
tasks = set(ds['task_info'])
if 'classical' in tasks:
self.add('task_hazard:0')
self.add('task_hazard:-1')
self.add('job_info')
if 'performance_data' in ds:
self.add('performance')
return self.text |
def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res | Decorator that wraps a wire transform function | Below is the the instruction that describes the task:
### Input:
Decorator that wraps a wire transform function
### Response:
def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res |
def _distort_color(image, color_ordering=0, scope=None):
"""Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3]
"""
with tf.name_scope(scope, "distort_color", [image]):
if color_ordering == 0:
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
elif color_ordering == 1:
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
elif color_ordering == 2:
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
elif color_ordering == 3:
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
else:
raise ValueError("color_ordering must be in [0, 3]")
# The random_* ops do not necessarily clamp.
return tf.clip_by_value(image, 0.0, 1.0) | Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3] | Below is the the instruction that describes the task:
### Input:
Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3]
### Response:
def _distort_color(image, color_ordering=0, scope=None):
"""Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3]
"""
with tf.name_scope(scope, "distort_color", [image]):
if color_ordering == 0:
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
elif color_ordering == 1:
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
elif color_ordering == 2:
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
elif color_ordering == 3:
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
else:
raise ValueError("color_ordering must be in [0, 3]")
# The random_* ops do not necessarily clamp.
return tf.clip_by_value(image, 0.0, 1.0) |
def _find_inline_images(contentsinfo):
"Find inline images in the contentstream"
for n, inline in enumerate(contentsinfo.inline_images):
yield ImageInfo(
name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline
) | Find inline images in the contentstream | Below is the the instruction that describes the task:
### Input:
Find inline images in the contentstream
### Response:
def _find_inline_images(contentsinfo):
"Find inline images in the contentstream"
for n, inline in enumerate(contentsinfo.inline_images):
yield ImageInfo(
name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline
) |
def reset(self):
"""
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
"""
# set all output pins to a value of 0
for pin in range(0, self._command_handler.total_pins_discovered):
if self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.PWM:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.SERVO:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.TONE:
data = [self.TONE_NO_TONE, pin]
self._command_handler.send_sysex(self._command_handler.TONE_PLAY, data)
else:
self.digital_write(pin, 0)
self._command_handler.system_reset() | This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value. | Below is the the instruction that describes the task:
### Input:
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
### Response:
def reset(self):
"""
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
"""
# set all output pins to a value of 0
for pin in range(0, self._command_handler.total_pins_discovered):
if self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.PWM:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.SERVO:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.TONE:
data = [self.TONE_NO_TONE, pin]
self._command_handler.send_sysex(self._command_handler.TONE_PLAY, data)
else:
self.digital_write(pin, 0)
self._command_handler.system_reset() |
def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Karalkin
# Looking in error schema path for
# property that failed validation
# Schema example:
# {
# "type": "object",
# "properties": {
# "foo": {"type": "number"},
# "bar": {"type": "string"}
# }
# "required": ["foo", "bar"]
# }
#
# Related err.schema_path examples:
# ['required'],
# ['properties', 'foo', 'type']
if "properties" in path:
path.remove("properties")
key = path.popleft()
# If validation failed by missing property,
# then parse err.message to find property name
# as it always first word enclosed in quotes
if key == "required":
key = err.message.split("'")[1]
_errors[key].append(str(err))
if _errors:
_raise_exception(
web.HTTPBadRequest,
"Request is invalid; There are validation errors.",
_errors) | Validate the dict against given schema (using given validator class). | Below is the the instruction that describes the task:
### Input:
Validate the dict against given schema (using given validator class).
### Response:
def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Karalkin
# Looking in error schema path for
# property that failed validation
# Schema example:
# {
# "type": "object",
# "properties": {
# "foo": {"type": "number"},
# "bar": {"type": "string"}
# }
# "required": ["foo", "bar"]
# }
#
# Related err.schema_path examples:
# ['required'],
# ['properties', 'foo', 'type']
if "properties" in path:
path.remove("properties")
key = path.popleft()
# If validation failed by missing property,
# then parse err.message to find property name
# as it always first word enclosed in quotes
if key == "required":
key = err.message.split("'")[1]
_errors[key].append(str(err))
if _errors:
_raise_exception(
web.HTTPBadRequest,
"Request is invalid; There are validation errors.",
_errors) |
def stack(self, size=None):
"""
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray
"""
stk = StackedArray(self._rdd, shape=self.shape, split=self.split)
return stk.stack(size) | Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray | Below is the the instruction that describes the task:
### Input:
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray
### Response:
def stack(self, size=None):
"""
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray
"""
stk = StackedArray(self._rdd, shape=self.shape, split=self.split)
return stk.stack(size) |
def get_radiussettings(self, domainid, serverid, settingsid):
"""Get RADIUS settings"""
return self.api_call(
ENDPOINTS['radiussettings']['get'],
dict(domainid=domainid, serverid=serverid, settingsid=settingsid)) | Get RADIUS settings | Below is the the instruction that describes the task:
### Input:
Get RADIUS settings
### Response:
def get_radiussettings(self, domainid, serverid, settingsid):
"""Get RADIUS settings"""
return self.api_call(
ENDPOINTS['radiussettings']['get'],
dict(domainid=domainid, serverid=serverid, settingsid=settingsid)) |
def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised.
"""
text = text.strip()
lines = text.splitlines()
parsed_lines = []
encountered_date = False
for (lineno, line) in enumerate(lines, 1):
try:
parsed_line = self.parse_line(line)
if isinstance(parsed_line, DateLine):
encountered_date = True
elif isinstance(parsed_line, Entry) and not encountered_date:
raise ParseError("Entries must be defined inside a date section")
except ParseError as e:
# Update exception with some more information
e.line_number = lineno
e.line = line
raise
else:
parsed_lines.append(parsed_line)
return parsed_lines | Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised. | Below is the the instruction that describes the task:
### Input:
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised.
### Response:
def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised.
"""
text = text.strip()
lines = text.splitlines()
parsed_lines = []
encountered_date = False
for (lineno, line) in enumerate(lines, 1):
try:
parsed_line = self.parse_line(line)
if isinstance(parsed_line, DateLine):
encountered_date = True
elif isinstance(parsed_line, Entry) and not encountered_date:
raise ParseError("Entries must be defined inside a date section")
except ParseError as e:
# Update exception with some more information
e.line_number = lineno
e.line = line
raise
else:
parsed_lines.append(parsed_line)
return parsed_lines |
def until(self, func, message='', *args, **kwargs):
"""
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None
"""
value = None
end_time = time.time() + self._timeout
while True:
value = func(*args, **kwargs)
if self._debug:
print("Value from func within ActionWait: {}".format(value))
if value:
break
time.sleep(self._poll)
self._poll *= 1.25
if time.time() > end_time:
raise RuntimeError(message)
return value | Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None | Below is the the instruction that describes the task:
### Input:
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None
### Response:
def until(self, func, message='', *args, **kwargs):
"""
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None
"""
value = None
end_time = time.time() + self._timeout
while True:
value = func(*args, **kwargs)
if self._debug:
print("Value from func within ActionWait: {}".format(value))
if value:
break
time.sleep(self._poll)
self._poll *= 1.25
if time.time() > end_time:
raise RuntimeError(message)
return value |
def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing gevent in the parent
# process and then using it int he child. This is meant to relieve that
# problem by allowing `klass` to be specified as a string.
if isinstance(self.klass, string_types):
self.klass = util.import_class(self.klass)
return self.klass(self.queues, self.client, **copy) | Return a new worker for a child process | Below is the the instruction that describes the task:
### Input:
Return a new worker for a child process
### Response:
def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing gevent in the parent
# process and then using it int he child. This is meant to relieve that
# problem by allowing `klass` to be specified as a string.
if isinstance(self.klass, string_types):
self.klass = util.import_class(self.klass)
return self.klass(self.queues, self.client, **copy) |
def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type: List[Text]
except StopIteration:
pass
return self._errors | Returns all errors found with the bundle. | Below is the the instruction that describes the task:
### Input:
Returns all errors found with the bundle.
### Response:
def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type: List[Text]
except StopIteration:
pass
return self._errors |
def _monkey_patch_boto():
"""
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
"""
from boto import provider
from botocore.session import Session
from botocore.credentials import create_credential_resolver, RefreshableCredentials
# We cache the final credentials so that we don't send multiple processes to
# simultaneously bang on the EC2 metadata server or ask for MFA pins from the
# user.
cache_path = '~/.cache/aws/cached_temporary_credentials'
datetime_format = "%Y-%m-%dT%H:%M:%SZ" # incidentally the same as the format used by AWS
log = logging.getLogger(__name__)
def datetime_to_str(dt):
"""
Convert a naive (implicitly UTC) datetime object into a string, explicitly UTC.
>>> datetime_to_str(datetime(1970, 1, 1, 0, 0, 0))
'1970-01-01T00:00:00Z'
"""
return dt.strftime(datetime_format)
def str_to_datetime(s):
"""
Convert a string, explicitly UTC into a naive (implicitly UTC) datetime object.
>>> str_to_datetime( '1970-01-01T00:00:00Z' )
datetime.datetime(1970, 1, 1, 0, 0)
Just to show that the constructor args for seconds and microseconds are optional:
>>> datetime(1970, 1, 1, 0, 0, 0)
datetime.datetime(1970, 1, 1, 0, 0)
"""
return datetime.strptime(s, datetime_format)
class BotoCredentialAdapter(provider.Provider):
"""
Adapter to allow Boto 2 to use AWS credentials obtained via Boto 3's
credential finding logic. This allows for automatic role assumption
respecting the Boto 3 config files, even when parts of the app still use
Boto 2.
This class also handles cacheing credentials in multi-process environments
to avoid loads of processes swamping the EC2 metadata service.
"""
def __init__(self, name, access_key=None, secret_key=None,
security_token=None, profile_name=None, **kwargs):
"""
Create a new BotoCredentialAdapter.
"""
# TODO: We take kwargs because new boto2 versions have an 'anon'
# argument and we want to be future proof
if (name == 'aws' or name is None) and access_key is None and not kwargs.get('anon', False):
# We are on AWS and we don't have credentials passed along and we aren't anonymous.
# We will backend into a boto3 resolver for getting credentials.
self._boto3_resolver = create_credential_resolver(Session(profile=profile_name))
else:
# We will use the normal flow
self._boto3_resolver = None
# Pass along all the arguments
super(BotoCredentialAdapter, self).__init__(name, access_key=access_key,
secret_key=secret_key, security_token=security_token,
profile_name=profile_name, **kwargs)
def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None):
"""
Make sure our credential fields are populated. Called by the base class
constructor.
"""
if self._boto3_resolver is not None:
# Go get the credentials from the cache, or from boto3 if not cached.
# We need to be eager here; having the default None
# _credential_expiry_time makes the accessors never try to refresh.
self._obtain_credentials_from_cache_or_boto3()
else:
# We're not on AWS, or they passed a key, or we're anonymous.
# Use the normal route; our credentials shouldn't expire.
super(BotoCredentialAdapter, self).get_credentials(access_key=access_key,
secret_key=secret_key, security_token=security_token, profile_name=profile_name)
def _populate_keys_from_metadata_server(self):
"""
This override is misnamed; it's actually the only hook we have to catch
_credential_expiry_time being too soon and refresh the credentials. We
actually just go back and poke the cache to see if it feels like
getting us new credentials.
Boto 2 hardcodes a refresh within 5 minutes of expiry:
https://github.com/boto/boto/blob/591911db1029f2fbb8ba1842bfcc514159b37b32/boto/provider.py#L247
Boto 3 wants to refresh 15 or 10 minutes before expiry:
https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L279
So if we ever want to refresh, Boto 3 wants to refresh too.
"""
# This should only happen if we have expiring credentials, which we should only get from boto3
assert(self._boto3_resolver is not None)
self._obtain_credentials_from_cache_or_boto3()
def _obtain_credentials_from_boto3(self):
"""
We know the current cached credentials are not good, and that we
need to get them from Boto 3. Fill in our credential fields
(_access_key, _secret_key, _security_token,
_credential_expiry_time) from Boto 3.
"""
# We get a Credentials object
# <https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L227>
# or a RefreshableCredentials, or None on failure.
creds = None
for attempt in retry(timeout=10, predicate=lambda _: True):
with attempt:
creds = self._boto3_resolver.load_credentials()
if creds is None:
try:
resolvers = str(self._boto3_resolver.providers)
except:
resolvers = "(Resolvers unavailable)"
raise RuntimeError("Could not obtain AWS credentials from Boto3. Resolvers tried: " + resolvers)
# Make sure the credentials actually has some credentials if it is lazy
creds.get_frozen_credentials()
# Get when the credentials will expire, if ever
if isinstance(creds, RefreshableCredentials):
# Credentials may expire.
# Get a naive UTC datetime like boto 2 uses from the boto 3 time.
self._credential_expiry_time = creds._expiry_time.astimezone(timezone('UTC')).replace(tzinfo=None)
else:
# Credentials never expire
self._credential_expiry_time = None
# Then, atomically get all the credentials bits. They may be newer than we think they are, but never older.
frozen = creds.get_frozen_credentials()
# Copy them into us
self._access_key = frozen.access_key
self._secret_key = frozen.secret_key
self._security_token = frozen.token
def _obtain_credentials_from_cache_or_boto3(self):
"""
Get the cached credentials, or retrieve them from Boto 3 and cache them
(or wait for another cooperating process to do so) if they are missing
or not fresh enough.
"""
path = os.path.expanduser(cache_path)
tmp_path = path + '.tmp'
while True:
log.debug('Attempting to read cached credentials from %s.', path)
try:
with open(path, 'r') as f:
content = f.read()
if content:
record = content.split('\n')
assert len(record) == 4
self._access_key = record[0]
self._secret_key = record[1]
self._security_token = record[2]
self._credential_expiry_time = str_to_datetime(record[3])
else:
log.debug('%s is empty. Credentials are not temporary.', path)
self._obtain_credentials_from_boto3()
return
except IOError as e:
if e.errno == errno.ENOENT:
log.debug('Cached credentials are missing.')
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
log.debug('Creating parent directory %s', dir_path)
# A race would be ok at this point
mkdir_p(dir_path)
else:
raise
else:
if self._credentials_need_refresh():
log.debug('Cached credentials are expired.')
else:
log.debug('Cached credentials exist and are still fresh.')
return
# We get here if credentials are missing or expired
log.debug('Racing to create %s.', tmp_path)
# Only one process, the winner, will succeed
try:
fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except OSError as e:
if e.errno == errno.EEXIST:
log.debug('Lost the race to create %s. Waiting on winner to remove it.', tmp_path)
while os.path.exists(tmp_path):
time.sleep(0.1)
log.debug('Winner removed %s. Trying from the top.', tmp_path)
else:
raise
else:
try:
log.debug('Won the race to create %s. Requesting credentials from backend.', tmp_path)
self._obtain_credentials_from_boto3()
except:
os.close(fd)
fd = None
log.debug('Failed to obtain credentials, removing %s.', tmp_path)
# This unblocks the loosers.
os.unlink(tmp_path)
# Bail out. It's too likely to happen repeatedly
raise
else:
if self._credential_expiry_time is None:
os.close(fd)
fd = None
log.debug('Credentials are not temporary. Leaving %s empty and renaming it to %s.', tmp_path, path)
# No need to actually cache permanent credentials,
# because we hnow we aren't getting them from the
# metadata server or by assuming a role. Those both
# give temporary credentials.
else:
log.debug('Writing credentials to %s.', tmp_path)
with os.fdopen(fd, 'w') as fh:
fd = None
fh.write('\n'.join([
self._access_key,
self._secret_key,
self._security_token,
datetime_to_str(self._credential_expiry_time)]))
log.debug('Wrote credentials to %s. Renaming to %s.', tmp_path, path)
os.rename(tmp_path, path)
return
finally:
if fd is not None:
os.close(fd)
# Now we have defined the adapter class. Patch the Boto module so it replaces the default Provider when Boto makes Providers.
provider.Provider = BotoCredentialAdapter | Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles. | Below is the the instruction that describes the task:
### Input:
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
### Response:
def _monkey_patch_boto():
"""
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
"""
from boto import provider
from botocore.session import Session
from botocore.credentials import create_credential_resolver, RefreshableCredentials
# We cache the final credentials so that we don't send multiple processes to
# simultaneously bang on the EC2 metadata server or ask for MFA pins from the
# user.
cache_path = '~/.cache/aws/cached_temporary_credentials'
datetime_format = "%Y-%m-%dT%H:%M:%SZ" # incidentally the same as the format used by AWS
log = logging.getLogger(__name__)
def datetime_to_str(dt):
"""
Convert a naive (implicitly UTC) datetime object into a string, explicitly UTC.
>>> datetime_to_str(datetime(1970, 1, 1, 0, 0, 0))
'1970-01-01T00:00:00Z'
"""
return dt.strftime(datetime_format)
def str_to_datetime(s):
"""
Convert a string, explicitly UTC into a naive (implicitly UTC) datetime object.
>>> str_to_datetime( '1970-01-01T00:00:00Z' )
datetime.datetime(1970, 1, 1, 0, 0)
Just to show that the constructor args for seconds and microseconds are optional:
>>> datetime(1970, 1, 1, 0, 0, 0)
datetime.datetime(1970, 1, 1, 0, 0)
"""
return datetime.strptime(s, datetime_format)
class BotoCredentialAdapter(provider.Provider):
"""
Adapter to allow Boto 2 to use AWS credentials obtained via Boto 3's
credential finding logic. This allows for automatic role assumption
respecting the Boto 3 config files, even when parts of the app still use
Boto 2.
This class also handles cacheing credentials in multi-process environments
to avoid loads of processes swamping the EC2 metadata service.
"""
def __init__(self, name, access_key=None, secret_key=None,
security_token=None, profile_name=None, **kwargs):
"""
Create a new BotoCredentialAdapter.
"""
# TODO: We take kwargs because new boto2 versions have an 'anon'
# argument and we want to be future proof
if (name == 'aws' or name is None) and access_key is None and not kwargs.get('anon', False):
# We are on AWS and we don't have credentials passed along and we aren't anonymous.
# We will backend into a boto3 resolver for getting credentials.
self._boto3_resolver = create_credential_resolver(Session(profile=profile_name))
else:
# We will use the normal flow
self._boto3_resolver = None
# Pass along all the arguments
super(BotoCredentialAdapter, self).__init__(name, access_key=access_key,
secret_key=secret_key, security_token=security_token,
profile_name=profile_name, **kwargs)
def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None):
"""
Make sure our credential fields are populated. Called by the base class
constructor.
"""
if self._boto3_resolver is not None:
# Go get the credentials from the cache, or from boto3 if not cached.
# We need to be eager here; having the default None
# _credential_expiry_time makes the accessors never try to refresh.
self._obtain_credentials_from_cache_or_boto3()
else:
# We're not on AWS, or they passed a key, or we're anonymous.
# Use the normal route; our credentials shouldn't expire.
super(BotoCredentialAdapter, self).get_credentials(access_key=access_key,
secret_key=secret_key, security_token=security_token, profile_name=profile_name)
def _populate_keys_from_metadata_server(self):
"""
This override is misnamed; it's actually the only hook we have to catch
_credential_expiry_time being too soon and refresh the credentials. We
actually just go back and poke the cache to see if it feels like
getting us new credentials.
Boto 2 hardcodes a refresh within 5 minutes of expiry:
https://github.com/boto/boto/blob/591911db1029f2fbb8ba1842bfcc514159b37b32/boto/provider.py#L247
Boto 3 wants to refresh 15 or 10 minutes before expiry:
https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L279
So if we ever want to refresh, Boto 3 wants to refresh too.
"""
# This should only happen if we have expiring credentials, which we should only get from boto3
assert(self._boto3_resolver is not None)
self._obtain_credentials_from_cache_or_boto3()
def _obtain_credentials_from_boto3(self):
"""
We know the current cached credentials are not good, and that we
need to get them from Boto 3. Fill in our credential fields
(_access_key, _secret_key, _security_token,
_credential_expiry_time) from Boto 3.
"""
# We get a Credentials object
# <https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L227>
# or a RefreshableCredentials, or None on failure.
creds = None
for attempt in retry(timeout=10, predicate=lambda _: True):
with attempt:
creds = self._boto3_resolver.load_credentials()
if creds is None:
try:
resolvers = str(self._boto3_resolver.providers)
except:
resolvers = "(Resolvers unavailable)"
raise RuntimeError("Could not obtain AWS credentials from Boto3. Resolvers tried: " + resolvers)
# Make sure the credentials actually has some credentials if it is lazy
creds.get_frozen_credentials()
# Get when the credentials will expire, if ever
if isinstance(creds, RefreshableCredentials):
# Credentials may expire.
# Get a naive UTC datetime like boto 2 uses from the boto 3 time.
self._credential_expiry_time = creds._expiry_time.astimezone(timezone('UTC')).replace(tzinfo=None)
else:
# Credentials never expire
self._credential_expiry_time = None
# Then, atomically get all the credentials bits. They may be newer than we think they are, but never older.
frozen = creds.get_frozen_credentials()
# Copy them into us
self._access_key = frozen.access_key
self._secret_key = frozen.secret_key
self._security_token = frozen.token
def _obtain_credentials_from_cache_or_boto3(self):
"""
Get the cached credentials, or retrieve them from Boto 3 and cache them
(or wait for another cooperating process to do so) if they are missing
or not fresh enough.
"""
path = os.path.expanduser(cache_path)
tmp_path = path + '.tmp'
while True:
log.debug('Attempting to read cached credentials from %s.', path)
try:
with open(path, 'r') as f:
content = f.read()
if content:
record = content.split('\n')
assert len(record) == 4
self._access_key = record[0]
self._secret_key = record[1]
self._security_token = record[2]
self._credential_expiry_time = str_to_datetime(record[3])
else:
log.debug('%s is empty. Credentials are not temporary.', path)
self._obtain_credentials_from_boto3()
return
except IOError as e:
if e.errno == errno.ENOENT:
log.debug('Cached credentials are missing.')
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
log.debug('Creating parent directory %s', dir_path)
# A race would be ok at this point
mkdir_p(dir_path)
else:
raise
else:
if self._credentials_need_refresh():
log.debug('Cached credentials are expired.')
else:
log.debug('Cached credentials exist and are still fresh.')
return
# We get here if credentials are missing or expired
log.debug('Racing to create %s.', tmp_path)
# Only one process, the winner, will succeed
try:
fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except OSError as e:
if e.errno == errno.EEXIST:
log.debug('Lost the race to create %s. Waiting on winner to remove it.', tmp_path)
while os.path.exists(tmp_path):
time.sleep(0.1)
log.debug('Winner removed %s. Trying from the top.', tmp_path)
else:
raise
else:
try:
log.debug('Won the race to create %s. Requesting credentials from backend.', tmp_path)
self._obtain_credentials_from_boto3()
except:
os.close(fd)
fd = None
log.debug('Failed to obtain credentials, removing %s.', tmp_path)
# This unblocks the loosers.
os.unlink(tmp_path)
# Bail out. It's too likely to happen repeatedly
raise
else:
if self._credential_expiry_time is None:
os.close(fd)
fd = None
log.debug('Credentials are not temporary. Leaving %s empty and renaming it to %s.', tmp_path, path)
# No need to actually cache permanent credentials,
# because we hnow we aren't getting them from the
# metadata server or by assuming a role. Those both
# give temporary credentials.
else:
log.debug('Writing credentials to %s.', tmp_path)
with os.fdopen(fd, 'w') as fh:
fd = None
fh.write('\n'.join([
self._access_key,
self._secret_key,
self._security_token,
datetime_to_str(self._credential_expiry_time)]))
log.debug('Wrote credentials to %s. Renaming to %s.', tmp_path, path)
os.rename(tmp_path, path)
return
finally:
if fd is not None:
os.close(fd)
# Now we have defined the adapter class. Patch the Boto module so it replaces the default Provider when Boto makes Providers.
provider.Provider = BotoCredentialAdapter |
def jsonify(obj, **kwargs):
"""
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj
"""
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
# will work for numpy.ndarrays
# as well as their int64/etc objects
if hasattr(obj, 'tolist'):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
# run the dumps using our encoder
dumped = json.dumps(obj, cls=NumpyEncoder, **kwargs)
return dumped | A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj | Below is the the instruction that describes the task:
### Input:
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj
### Response:
def jsonify(obj, **kwargs):
"""
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj
"""
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
# will work for numpy.ndarrays
# as well as their int64/etc objects
if hasattr(obj, 'tolist'):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
# run the dumps using our encoder
dumped = json.dumps(obj, cls=NumpyEncoder, **kwargs)
return dumped |
def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) | Called by the timeout alarm during the collector run time | Below is the the instruction that describes the task:
### Input:
Called by the timeout alarm during the collector run time
### Response:
def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) |
def vm_cputime(vm_=None, **kwargs):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime
'''
conn = __get_conn(**kwargs)
host_cpus = conn.getInfo()[2]
def _info(dom):
'''
Compute cputime info of a domain
'''
raw = dom.info()
vcpus = int(raw[3])
cputime = int(raw[4])
cputime_percent = 0
if cputime:
# Divide by vcpus to always return a number between 0 and 100
cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus
return {
'cputime': int(raw[4]),
'cputime_percent': int('{0:.0f}'.format(cputime_percent))
}
info = {}
if vm_:
info[vm_] = _info(_get_domain(conn, vm_))
else:
for domain in _get_domain(conn, iterable=True):
info[domain.name()] = _info(domain)
conn.close()
return info | Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime | Below is the the instruction that describes the task:
### Input:
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime
### Response:
def vm_cputime(vm_=None, **kwargs):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime
'''
conn = __get_conn(**kwargs)
host_cpus = conn.getInfo()[2]
def _info(dom):
'''
Compute cputime info of a domain
'''
raw = dom.info()
vcpus = int(raw[3])
cputime = int(raw[4])
cputime_percent = 0
if cputime:
# Divide by vcpus to always return a number between 0 and 100
cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus
return {
'cputime': int(raw[4]),
'cputime_percent': int('{0:.0f}'.format(cputime_percent))
}
info = {}
if vm_:
info[vm_] = _info(_get_domain(conn, vm_))
else:
for domain in _get_domain(conn, iterable=True):
info[domain.name()] = _info(domain)
conn.close()
return info |
def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
"""
now = time.localtime(ref)
# If no year, it's our year
if self.syear == 0:
self.syear = now.tm_year
month_start_id = now.tm_mon
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Same for end year
if self.eyear == 0:
self.eyear = now.tm_year
month_end_id = now.tm_mon
day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday,
self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
# Maybe end_time is before start. So look for the
# next month
if start_time > end_time:
month_end_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
now_epoch = time.mktime(now)
# But maybe we look not enought far. We should add a month
if end_time < now_epoch:
month_end_id += 1
month_start_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
if month_start_id > 12:
month_start_id = 1
self.syear += 1
# First start
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Then end
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
return (start_time, end_time) | Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int) | Below is the the instruction that describes the task:
### Input:
Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
### Response:
def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
"""
now = time.localtime(ref)
# If no year, it's our year
if self.syear == 0:
self.syear = now.tm_year
month_start_id = now.tm_mon
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Same for end year
if self.eyear == 0:
self.eyear = now.tm_year
month_end_id = now.tm_mon
day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday,
self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
# Maybe end_time is before start. So look for the
# next month
if start_time > end_time:
month_end_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
now_epoch = time.mktime(now)
# But maybe we look not enought far. We should add a month
if end_time < now_epoch:
month_end_id += 1
month_start_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
if month_start_id > 12:
month_start_id = 1
self.syear += 1
# First start
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Then end
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
return (start_time, end_time) |
def checkAuthentication():
"""
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception.
"""
if app.oidcClient is None:
return
if flask.request.endpoint == 'oidcCallback':
return
key = flask.session.get('key') or flask.request.args.get('key')
if key is None or not app.cache.get(key):
if 'key' in flask.request.args:
raise exceptions.NotAuthenticatedException()
else:
return startLogin() | The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception. | Below is the the instruction that describes the task:
### Input:
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception.
### Response:
def checkAuthentication():
"""
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception.
"""
if app.oidcClient is None:
return
if flask.request.endpoint == 'oidcCallback':
return
key = flask.session.get('key') or flask.request.args.get('key')
if key is None or not app.cache.get(key):
if 'key' in flask.request.args:
raise exceptions.NotAuthenticatedException()
else:
return startLogin() |
def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The files that will need counting
sample_file = None
marker_file = None
if file_type == "bfile":
# Binary files (.bed, .bim and .fam)
sample_file = prefix + ".fam"
marker_file = prefix + ".bim"
elif file_type == "file":
# Pedfile (.ped and .map)
sample_file = prefix + ".ped"
marker_file = prefix + ".map"
elif file_type == "tfile":
# Transposed pedfile (.tped and .tfam)
sample_file = prefix + ".tfam"
marker_file = prefix + ".tped"
# Counting (this may take some time)
nb_samples = 0
with open(sample_file, "r") as f:
for line in f:
nb_samples += 1
nb_markers = 0
with open(marker_file, "r") as f:
for line in f:
nb_markers += 1
return nb_markers, nb_samples | Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple). | Below is the the instruction that describes the task:
### Input:
Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
### Response:
def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The files that will need counting
sample_file = None
marker_file = None
if file_type == "bfile":
# Binary files (.bed, .bim and .fam)
sample_file = prefix + ".fam"
marker_file = prefix + ".bim"
elif file_type == "file":
# Pedfile (.ped and .map)
sample_file = prefix + ".ped"
marker_file = prefix + ".map"
elif file_type == "tfile":
# Transposed pedfile (.tped and .tfam)
sample_file = prefix + ".tfam"
marker_file = prefix + ".tped"
# Counting (this may take some time)
nb_samples = 0
with open(sample_file, "r") as f:
for line in f:
nb_samples += 1
nb_markers = 0
with open(marker_file, "r") as f:
for line in f:
nb_markers += 1
return nb_markers, nb_samples |
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None
'''
# Get and store states for newly born agents
N = np.sum(which_agents) # Number of new consumers to make
aNrmNow_new = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1))
self.pLvlNow[which_agents] = drawLognormal(N,mu=self.pLvlInitMean,sigma=self.pLvlInitStd,seed=self.RNG.randint(0,2**31-1))
self.aLvlNow[which_agents] = aNrmNow_new*self.pLvlNow[which_agents]
self.t_age[which_agents] = 0 # How many periods since each agent was born
self.t_cycle[which_agents] = 0 | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None
### Response:
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None
'''
# Get and store states for newly born agents
N = np.sum(which_agents) # Number of new consumers to make
aNrmNow_new = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1))
self.pLvlNow[which_agents] = drawLognormal(N,mu=self.pLvlInitMean,sigma=self.pLvlInitStd,seed=self.RNG.randint(0,2**31-1))
self.aLvlNow[which_agents] = aNrmNow_new*self.pLvlNow[which_agents]
self.t_age[which_agents] = 0 # How many periods since each agent was born
self.t_cycle[which_agents] = 0 |
def get_conversions(self):
"""Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage).
"""
# NOTE: This pattern gets all reactions in which a protein is the
# controller and chemicals are converted. But with this pattern only
# a single chemical is extracted from each side. This can be misleading
# since we want to capture all inputs and all outputs of the
# conversion. So we need to step back to the conversion itself and
# enumerate all inputs/outputs, make sure they constitute the kind
# of conversion we can capture here and then extract as a Conversion
# Statement. Another issue here is that the same reaction will be
# extracted multiple times if there is more then one input or output.
# Therefore we need to cache the ID of the reactions that have already
# been handled.
p = _bpp('Pattern')(_bpimpl('PhysicalEntity')().getModelInterface(),
'controller PE')
# Getting the control itself
p.add(cb.peToControl(), "controller PE", "Control")
# Make sure the controller is a protein
# TODO: possibly allow Complex too
p.add(tp(_bpimpl('Protein')().getModelInterface()), "controller PE")
# Link the control to the conversion that it controls
p.add(cb.controlToConv(), "Control", "Conversion")
# Make sure this is a BiochemicalRection (as opposed to, for instance,
# ComplexAssembly)
p.add(tp(_bpimpl('BiochemicalReaction')().getModelInterface()),
"Conversion")
# The controller shouldn't be a participant of the conversion
p.add(_bpp('constraint.NOT')(cb.participant()),
"Conversion", "controller PE")
# Get the input participant of the conversion
p.add(pt(rt.INPUT, True), "Control", "Conversion", "input PE")
# Link to the other side of the conversion
p.add(cs(cst.OTHER_SIDE), "input PE", "Conversion", "output PE")
# Make sure the two sides are not the same
p.add(_bpp('constraint.Equality')(False), "input PE", "output PE")
# Make sure the input/output is a chemical
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "input PE")
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "output PE")
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
stmts = []
reaction_extracted = set()
for r in res_array:
controller_pe = r[p.indexOf('controller PE')]
reaction = r[p.indexOf('Conversion')]
control = r[p.indexOf('Control')]
input_pe = r[p.indexOf('input PE')]
output_pe = r[p.indexOf('output PE')]
if control.getUri() in reaction_extracted:
continue
# Get controller
subj_list = self._get_agents_from_entity(controller_pe)
# Get inputs and outputs
left = reaction.getLeft().toArray()
right = reaction.getRight().toArray()
# Skip this if not all participants are chemicals
if any([not _is_small_molecule(e) for e in left]):
continue
if any([not _is_small_molecule(e) for e in right]):
continue
obj_left = []
obj_right = []
for participant in left:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_left += agent
else:
obj_left.append(agent)
for participant in right:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_right += agent
else:
obj_right.append(agent)
ev = self._get_evidence(control)
for subj in _listify(subj_list):
st = Conversion(subj, obj_left, obj_right, evidence=ev)
st_dec = decode_obj(st, encoding='utf-8')
self.statements.append(st_dec)
reaction_extracted.add(control.getUri()) | Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage). | Below is the the instruction that describes the task:
### Input:
Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage).
### Response:
def get_conversions(self):
"""Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage).
"""
# NOTE: This pattern gets all reactions in which a protein is the
# controller and chemicals are converted. But with this pattern only
# a single chemical is extracted from each side. This can be misleading
# since we want to capture all inputs and all outputs of the
# conversion. So we need to step back to the conversion itself and
# enumerate all inputs/outputs, make sure they constitute the kind
# of conversion we can capture here and then extract as a Conversion
# Statement. Another issue here is that the same reaction will be
# extracted multiple times if there is more then one input or output.
# Therefore we need to cache the ID of the reactions that have already
# been handled.
p = _bpp('Pattern')(_bpimpl('PhysicalEntity')().getModelInterface(),
'controller PE')
# Getting the control itself
p.add(cb.peToControl(), "controller PE", "Control")
# Make sure the controller is a protein
# TODO: possibly allow Complex too
p.add(tp(_bpimpl('Protein')().getModelInterface()), "controller PE")
# Link the control to the conversion that it controls
p.add(cb.controlToConv(), "Control", "Conversion")
# Make sure this is a BiochemicalRection (as opposed to, for instance,
# ComplexAssembly)
p.add(tp(_bpimpl('BiochemicalReaction')().getModelInterface()),
"Conversion")
# The controller shouldn't be a participant of the conversion
p.add(_bpp('constraint.NOT')(cb.participant()),
"Conversion", "controller PE")
# Get the input participant of the conversion
p.add(pt(rt.INPUT, True), "Control", "Conversion", "input PE")
# Link to the other side of the conversion
p.add(cs(cst.OTHER_SIDE), "input PE", "Conversion", "output PE")
# Make sure the two sides are not the same
p.add(_bpp('constraint.Equality')(False), "input PE", "output PE")
# Make sure the input/output is a chemical
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "input PE")
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "output PE")
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
stmts = []
reaction_extracted = set()
for r in res_array:
controller_pe = r[p.indexOf('controller PE')]
reaction = r[p.indexOf('Conversion')]
control = r[p.indexOf('Control')]
input_pe = r[p.indexOf('input PE')]
output_pe = r[p.indexOf('output PE')]
if control.getUri() in reaction_extracted:
continue
# Get controller
subj_list = self._get_agents_from_entity(controller_pe)
# Get inputs and outputs
left = reaction.getLeft().toArray()
right = reaction.getRight().toArray()
# Skip this if not all participants are chemicals
if any([not _is_small_molecule(e) for e in left]):
continue
if any([not _is_small_molecule(e) for e in right]):
continue
obj_left = []
obj_right = []
for participant in left:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_left += agent
else:
obj_left.append(agent)
for participant in right:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_right += agent
else:
obj_right.append(agent)
ev = self._get_evidence(control)
for subj in _listify(subj_list):
st = Conversion(subj, obj_left, obj_right, evidence=ev)
st_dec = decode_obj(st, encoding='utf-8')
self.statements.append(st_dec)
reaction_extracted.add(control.getUri()) |
def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and solved_by
if identity in item and item[identity]:
user = self.get_sh_identity(item[identity])
yield user
if 'answers_data' in item:
for answer in item['answers_data']:
user = self.get_sh_identity(answer[identity])
yield user | Return the identities from an item | Below is the the instruction that describes the task:
### Input:
Return the identities from an item
### Response:
def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and solved_by
if identity in item and item[identity]:
user = self.get_sh_identity(item[identity])
yield user
if 'answers_data' in item:
for answer in item['answers_data']:
user = self.get_sh_identity(answer[identity])
yield user |
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_filename(
filename,
width,
height,
filename_key
)
joined_path = os.path.join(*[
VERSATILEIMAGEFIELD_SIZED_DIRNAME,
containing_folder,
resized_filename
]).replace(' ', '') # Removing spaces so this path is memcached friendly
return joined_path | Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key` | Below is the the instruction that describes the task:
### Input:
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
### Response:
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_filename(
filename,
width,
height,
filename_key
)
joined_path = os.path.join(*[
VERSATILEIMAGEFIELD_SIZED_DIRNAME,
containing_folder,
resized_filename
]).replace(' ', '') # Removing spaces so this path is memcached friendly
return joined_path |
def force_slash(fn):
"""
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if request.environ['PATH_INFO'].endswith('/'):
return fn(*args, **kwargs)
else:
redirect(request.environ['SCRIPT_NAME'] + request.environ['PATH_INFO'] + '/')
return wrapped | Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work | Below is the the instruction that describes the task:
### Input:
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
### Response:
def force_slash(fn):
"""
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if request.environ['PATH_INFO'].endswith('/'):
return fn(*args, **kwargs)
else:
redirect(request.environ['SCRIPT_NAME'] + request.environ['PATH_INFO'] + '/')
return wrapped |
def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
while True:
line = f.readline()
if line == "":
break
# at each line, a parsers checks if it has to process a piece of
# file. If that happens, the parser gets control over the file
# and reads as many lines as it needs to collect data for some
# attributes.
for parser in parsers:
if parser.test(line, data):
parser.read(line, f, data)
break
self.__dict__.update(data) | Internal routine that reads all data from the punch file. | Below is the the instruction that describes the task:
### Input:
Internal routine that reads all data from the punch file.
### Response:
def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
while True:
line = f.readline()
if line == "":
break
# at each line, a parsers checks if it has to process a piece of
# file. If that happens, the parser gets control over the file
# and reads as many lines as it needs to collect data for some
# attributes.
for parser in parsers:
if parser.test(line, data):
parser.read(line, f, data)
break
self.__dict__.update(data) |
def format_as_dataframe(explanation):
# type: (Explanation) -> Optional[pd.DataFrame]
""" Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`.
"""
for attr in _EXPORTED_ATTRIBUTES:
value = getattr(explanation, attr)
if value:
other_attrs = [a for a in _EXPORTED_ATTRIBUTES
if getattr(explanation, a) and a != attr]
if other_attrs:
warnings.warn('Exporting {} to DataFrame, but also {} could be '
'exported. Consider using eli5.format_as_dataframes.'
.format(attr, ', '.join(other_attrs)))
return format_as_dataframe(value)
return None | Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`. | Below is the the instruction that describes the task:
### Input:
Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`.
### Response:
def format_as_dataframe(explanation):
# type: (Explanation) -> Optional[pd.DataFrame]
""" Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`.
"""
for attr in _EXPORTED_ATTRIBUTES:
value = getattr(explanation, attr)
if value:
other_attrs = [a for a in _EXPORTED_ATTRIBUTES
if getattr(explanation, a) and a != attr]
if other_attrs:
warnings.warn('Exporting {} to DataFrame, but also {} could be '
'exported. Consider using eli5.format_as_dataframes.'
.format(attr, ', '.join(other_attrs)))
return format_as_dataframe(value)
return None |
def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins | Returns a list of drink admins uids | Below is the the instruction that describes the task:
### Input:
Returns a list of drink admins uids
### Response:
def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')
callback = kwargs.pop('callback', self._callback)
return callback(config) | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
def process_post_many_to_many_field(existing_post, field, related_objects):
"""
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None
"""
to_add = set(related_objects.get(existing_post.wp_id, set())) - set(getattr(existing_post, field).all())
to_remove = set(getattr(existing_post, field).all()) - set(related_objects.get(existing_post.wp_id, set()))
if to_add:
getattr(existing_post, field).add(*to_add)
if to_remove:
getattr(existing_post, field).remove(*to_remove) | Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None | Below is the the instruction that describes the task:
### Input:
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None
### Response:
def process_post_many_to_many_field(existing_post, field, related_objects):
"""
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None
"""
to_add = set(related_objects.get(existing_post.wp_id, set())) - set(getattr(existing_post, field).all())
to_remove = set(getattr(existing_post, field).all()) - set(related_objects.get(existing_post.wp_id, set()))
if to_add:
getattr(existing_post, field).add(*to_add)
if to_remove:
getattr(existing_post, field).remove(*to_remove) |
def _load_script(self):
"""Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
"""
script_text = filesystem.read_file(self.path, self.filename)
if not script_text:
raise IOError("Script file could not be opened or was empty: {0}"
"".format(os.path.join(self.path, self.filename)))
self.script = script_text | Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened | Below is the the instruction that describes the task:
### Input:
Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
### Response:
def _load_script(self):
"""Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
"""
script_text = filesystem.read_file(self.path, self.filename)
if not script_text:
raise IOError("Script file could not be opened or was empty: {0}"
"".format(os.path.join(self.path, self.filename)))
self.script = script_text |
def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._emit_all(tag) | Parse an HTML tag at the head of the wikicode string. | Below is the the instruction that describes the task:
### Input:
Parse an HTML tag at the head of the wikicode string.
### Response:
def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._emit_all(tag) |
def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
"""
if self._ctx is not None:
# Note: same as io_destroy
self._io_queue_release(self._ctx)
del self._ctx | Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context. | Below is the the instruction that describes the task:
### Input:
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
### Response:
def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
"""
if self._ctx is not None:
# Note: same as io_destroy
self._io_queue_release(self._ctx)
del self._ctx |
def _is_subspan(self, m, span):
"""Tests if mention m does exist"""
return m.figure.document.id == span[0] and m.figure.position == span[1] | Tests if mention m does exist | Below is the the instruction that describes the task:
### Input:
Tests if mention m does exist
### Response:
def _is_subspan(self, m, span):
"""Tests if mention m does exist"""
return m.figure.document.id == span[0] and m.figure.position == span[1] |
def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("Starting in mitiff save_datasets ... ")
def _delayed_create(create_opts, datasets):
LOG.debug("create_opts: %s", create_opts)
try:
if 'platform_name' not in kwargs:
kwargs['platform_name'] = datasets.attrs['platform_name']
if 'name' not in kwargs:
kwargs['name'] = datasets[0].attrs['name']
if 'start_time' not in kwargs:
kwargs['start_time'] = datasets[0].attrs['start_time']
if 'sensor' not in kwargs:
kwargs['sensor'] = datasets[0].attrs['sensor']
try:
self.mitiff_config[kwargs['sensor']] = datasets['metadata_requirements']['config']
self.translate_channel_name[kwargs['sensor']] = datasets['metadata_requirements']['translate']
self.channel_order[kwargs['sensor']] = datasets['metadata_requirements']['order']
self.file_pattern = datasets['metadata_requirements']['file_pattern']
except KeyError:
# For some mitiff products this info is needed, for others not.
# If needed you should know how to fix this
pass
image_description = self._make_image_description(datasets, **kwargs)
LOG.debug("File pattern %s", self.file_pattern)
if isinstance(datasets, list):
kwargs['start_time'] = datasets[0].attrs['start_time']
else:
kwargs['start_time'] = datasets.attrs['start_time']
gen_filename = filename or self.get_filename(**kwargs)
LOG.info("Saving mitiff to: %s ...", gen_filename)
self._save_datasets_as_mitiff(datasets, image_description, gen_filename, **kwargs)
except (KeyError, ValueError, RuntimeError):
raise
create_opts = ()
delayed = dask.delayed(_delayed_create)(create_opts, datasets)
LOG.debug("About to call delayed compute ...")
if compute:
return delayed.compute()
return delayed | Save all datasets to one or more files. | Below is the the instruction that describes the task:
### Input:
Save all datasets to one or more files.
### Response:
def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("Starting in mitiff save_datasets ... ")
def _delayed_create(create_opts, datasets):
LOG.debug("create_opts: %s", create_opts)
try:
if 'platform_name' not in kwargs:
kwargs['platform_name'] = datasets.attrs['platform_name']
if 'name' not in kwargs:
kwargs['name'] = datasets[0].attrs['name']
if 'start_time' not in kwargs:
kwargs['start_time'] = datasets[0].attrs['start_time']
if 'sensor' not in kwargs:
kwargs['sensor'] = datasets[0].attrs['sensor']
try:
self.mitiff_config[kwargs['sensor']] = datasets['metadata_requirements']['config']
self.translate_channel_name[kwargs['sensor']] = datasets['metadata_requirements']['translate']
self.channel_order[kwargs['sensor']] = datasets['metadata_requirements']['order']
self.file_pattern = datasets['metadata_requirements']['file_pattern']
except KeyError:
# For some mitiff products this info is needed, for others not.
# If needed you should know how to fix this
pass
image_description = self._make_image_description(datasets, **kwargs)
LOG.debug("File pattern %s", self.file_pattern)
if isinstance(datasets, list):
kwargs['start_time'] = datasets[0].attrs['start_time']
else:
kwargs['start_time'] = datasets.attrs['start_time']
gen_filename = filename or self.get_filename(**kwargs)
LOG.info("Saving mitiff to: %s ...", gen_filename)
self._save_datasets_as_mitiff(datasets, image_description, gen_filename, **kwargs)
except (KeyError, ValueError, RuntimeError):
raise
create_opts = ()
delayed = dask.delayed(_delayed_create)(create_opts, datasets)
LOG.debug("About to call delayed compute ...")
if compute:
return delayed.compute()
return delayed |
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subclass))
return tuple(subclasses) | All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780 | Below is the the instruction that describes the task:
### Input:
All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
### Response:
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subclass))
return tuple(subclasses) |
def publish_request(self, subject, reply, payload):
"""
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5
"""
payload_size = len(payload)
if payload_size > self._max_payload_size:
raise ErrMaxPayload
if self.is_closed:
raise ErrConnectionClosed
yield self._publish(subject, reply, payload, payload_size)
if self._flush_queue.empty():
yield self._flush_pending() | Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5 | Below is the the instruction that describes the task:
### Input:
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5
### Response:
def publish_request(self, subject, reply, payload):
"""
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5
"""
payload_size = len(payload)
if payload_size > self._max_payload_size:
raise ErrMaxPayload
if self.is_closed:
raise ErrConnectionClosed
yield self._publish(subject, reply, payload, payload_size)
if self._flush_queue.empty():
yield self._flush_pending() |
def async_get_device(self, uid, fields='*'):
"""Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) | Get specific device by ID. | Below is the the instruction that describes the task:
### Input:
Get specific device by ID.
### Response:
def async_get_device(self, uid, fields='*'):
"""Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) |
def feature_enabled(self, feature_name):
"""
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError`
"""
feature_list = self.prop('available-features-list', None)
if feature_list is None:
raise ValueError("Firmware features are not supported on CPC %s" %
self.manager.cpc.name)
for feature in feature_list:
if feature['name'] == feature_name:
break
else:
raise ValueError("Firmware feature %s is not available on CPC %s" %
(feature_name, self.manager.cpc.name))
return feature['state'] | Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError` | Below is the the instruction that describes the task:
### Input:
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError`
### Response:
def feature_enabled(self, feature_name):
"""
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError`
"""
feature_list = self.prop('available-features-list', None)
if feature_list is None:
raise ValueError("Firmware features are not supported on CPC %s" %
self.manager.cpc.name)
for feature in feature_list:
if feature['name'] == feature_name:
break
else:
raise ValueError("Firmware feature %s is not available on CPC %s" %
(feature_name, self.manager.cpc.name))
return feature['state'] |
def build_address_distance(number=None, street=None, city=None, state=None,
zip_code=None):
"""
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]]
"""
## Validate inputs
for param in [number, street, city, state, zip_code]:
if param is not None and not isinstance(param, str):
raise TypeError("All inputs must be strings. Each parameter is " +
"intended to be the name of an SFrame column.")
## Figure out features for levenshtein distance.
string_features = []
if city:
string_features.append(city)
if zip_code:
string_features.append(zip_code)
## Compile the distance components.
dist = []
if number:
dist.append([[number], 'jaccard', 1])
if street:
dist.append([[street], 'jaccard', 5])
if state:
dist.append([[state], 'jaccard', 5])
if len(string_features) > 0:
dist.append([string_features, 'levenshtein', 1])
return dist | Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]] | Below is the the instruction that describes the task:
### Input:
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]]
### Response:
def build_address_distance(number=None, street=None, city=None, state=None,
zip_code=None):
"""
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]]
"""
## Validate inputs
for param in [number, street, city, state, zip_code]:
if param is not None and not isinstance(param, str):
raise TypeError("All inputs must be strings. Each parameter is " +
"intended to be the name of an SFrame column.")
## Figure out features for levenshtein distance.
string_features = []
if city:
string_features.append(city)
if zip_code:
string_features.append(zip_code)
## Compile the distance components.
dist = []
if number:
dist.append([[number], 'jaccard', 1])
if street:
dist.append([[street], 'jaccard', 5])
if state:
dist.append([[state], 'jaccard', 5])
if len(string_features) > 0:
dist.append([string_features, 'levenshtein', 1])
return dist |
def import_foreign(name, custom_name=None):
"""
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found.
"""
if lab.is_python3():
io.error(("Ignoring attempt to import foreign module '{mod}' "
"using python version {major}.{minor}"
.format(mod=name, major=sys.version_info[0],
minor=sys.version_info[1])))
return
custom_name = custom_name or name
f, pathname, desc = imp.find_module(name, sys.path[1:])
module = imp.load_module(custom_name, f, pathname, desc)
f.close()
return module | Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found. | Below is the the instruction that describes the task:
### Input:
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found.
### Response:
def import_foreign(name, custom_name=None):
"""
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found.
"""
if lab.is_python3():
io.error(("Ignoring attempt to import foreign module '{mod}' "
"using python version {major}.{minor}"
.format(mod=name, major=sys.version_info[0],
minor=sys.version_info[1])))
return
custom_name = custom_name or name
f, pathname, desc = imp.find_module(name, sys.path[1:])
module = imp.load_module(custom_name, f, pathname, desc)
f.close()
return module |
def get_recurrent_encoder(config: RecurrentEncoderConfig, prefix: str) -> 'Encoder':
"""
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance.
"""
# TODO give more control on encoder architecture
encoder_seq = EncoderSequence([], config.dtype)
if config.conv_config is not None:
encoder_seq.append(ConvolutionalEmbeddingEncoder, config=config.conv_config,
prefix=prefix + C.CHAR_SEQ_ENCODER_PREFIX)
if config.conv_config.add_positional_encoding:
# If specified, add positional encodings to segment embeddings
encoder_seq.append(AddSinCosPositionalEmbeddings,
num_embed=config.conv_config.num_embed,
scale_up_input=False,
scale_down_positions=False,
prefix="%s%sadd_positional_encodings" % (prefix, C.CHAR_SEQ_ENCODER_PREFIX))
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.TIME_MAJOR)
else:
encoder_seq.append(ConvertLayout, target_layout=C.TIME_MAJOR, num_hidden=0)
if config.reverse_input:
encoder_seq.append(ReverseSequence, infer_hidden=True)
if config.rnn_config.residual:
utils.check_condition(config.rnn_config.first_residual_layer >= 2,
"Residual connections on the first encoder layer are not supported")
# One layer bi-directional RNN:
encoder_seq.append(BiDirectionalRNNEncoder,
rnn_config=config.rnn_config.copy(num_layers=1),
prefix=prefix + C.BIDIRECTIONALRNN_PREFIX,
layout=C.TIME_MAJOR)
if config.rnn_config.num_layers > 1:
# Stacked uni-directional RNN:
# Because we already have a one layer bi-rnn we reduce the num_layers as well as the first_residual_layer.
remaining_rnn_config = config.rnn_config.copy(num_layers=config.rnn_config.num_layers - 1,
first_residual_layer=config.rnn_config.first_residual_layer - 1)
encoder_seq.append(RecurrentEncoder,
rnn_config=remaining_rnn_config,
prefix=prefix + C.STACKEDRNN_PREFIX,
layout=C.TIME_MAJOR)
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.BATCH_MAJOR)
return encoder_seq | Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. | Below is the the instruction that describes the task:
### Input:
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance.
### Response:
def get_recurrent_encoder(config: RecurrentEncoderConfig, prefix: str) -> 'Encoder':
"""
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance.
"""
# TODO give more control on encoder architecture
encoder_seq = EncoderSequence([], config.dtype)
if config.conv_config is not None:
encoder_seq.append(ConvolutionalEmbeddingEncoder, config=config.conv_config,
prefix=prefix + C.CHAR_SEQ_ENCODER_PREFIX)
if config.conv_config.add_positional_encoding:
# If specified, add positional encodings to segment embeddings
encoder_seq.append(AddSinCosPositionalEmbeddings,
num_embed=config.conv_config.num_embed,
scale_up_input=False,
scale_down_positions=False,
prefix="%s%sadd_positional_encodings" % (prefix, C.CHAR_SEQ_ENCODER_PREFIX))
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.TIME_MAJOR)
else:
encoder_seq.append(ConvertLayout, target_layout=C.TIME_MAJOR, num_hidden=0)
if config.reverse_input:
encoder_seq.append(ReverseSequence, infer_hidden=True)
if config.rnn_config.residual:
utils.check_condition(config.rnn_config.first_residual_layer >= 2,
"Residual connections on the first encoder layer are not supported")
# One layer bi-directional RNN:
encoder_seq.append(BiDirectionalRNNEncoder,
rnn_config=config.rnn_config.copy(num_layers=1),
prefix=prefix + C.BIDIRECTIONALRNN_PREFIX,
layout=C.TIME_MAJOR)
if config.rnn_config.num_layers > 1:
# Stacked uni-directional RNN:
# Because we already have a one layer bi-rnn we reduce the num_layers as well as the first_residual_layer.
remaining_rnn_config = config.rnn_config.copy(num_layers=config.rnn_config.num_layers - 1,
first_residual_layer=config.rnn_config.first_residual_layer - 1)
encoder_seq.append(RecurrentEncoder,
rnn_config=remaining_rnn_config,
prefix=prefix + C.STACKEDRNN_PREFIX,
layout=C.TIME_MAJOR)
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.BATCH_MAJOR)
return encoder_seq |
def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | Get tracked position for a given operation and field. | Below is the the instruction that describes the task:
### Input:
Get tracked position for a given operation and field.
### Response:
def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) |
def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.dumps({
"channel": self.channel,
"sender": sender,
"receiver": receiver,
"message": message,
"context_uid": context_uid,
"meta": meta,
})
response = requests.post(self.get_api_url("/tips/"), data=data, headers={'content-type': 'application/json'})
if response.headers.get("Content-Type", None) == "application/json":
out = response.json()
out["state"] = response.reason.lower()
return out
else:
return {"state": response.reason.lower(), "error": "%s error submitting tip" % response.status_code} | Send a request to the ChangeTip API, to be delivered immediately. | Below is the the instruction that describes the task:
### Input:
Send a request to the ChangeTip API, to be delivered immediately.
### Response:
def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.dumps({
"channel": self.channel,
"sender": sender,
"receiver": receiver,
"message": message,
"context_uid": context_uid,
"meta": meta,
})
response = requests.post(self.get_api_url("/tips/"), data=data, headers={'content-type': 'application/json'})
if response.headers.get("Content-Type", None) == "application/json":
out = response.json()
out["state"] = response.reason.lower()
return out
else:
return {"state": response.reason.lower(), "error": "%s error submitting tip" % response.status_code} |
def get_flag_status(self, name):
"""
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information.
"""
f = self.get_flags(name)
if not f:
return None
# This method works only for simple flags that have only one
# value set.
assert len(f) <= 1
return f[0]['status'] | Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information. | Below is the the instruction that describes the task:
### Input:
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information.
### Response:
def get_flag_status(self, name):
"""
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information.
"""
f = self.get_flags(name)
if not f:
return None
# This method works only for simple flags that have only one
# value set.
assert len(f) <= 1
return f[0]['status'] |
def create_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'
'''
if not name:
raise SaltInvocationError('Required parameter \'name\' is missing')
if job_exists(name):
raise CommandExecutionError('Job \'{0}\' already exists'.format(name))
if not config_xml:
config_xml = jenkins.EMPTY_CONFIG_XML
else:
config_xml_file = _retrieve_config_xml(config_xml, saltenv)
with salt.utils.files.fopen(config_xml_file) as _fp:
config_xml = salt.utils.stringutils.to_unicode(_fp.read())
server = _connect()
try:
server.create_job(name, config_xml)
except jenkins.JenkinsException as err:
raise CommandExecutionError(
'Encountered error creating job \'{0}\': {1}'.format(name, err)
)
return config_xml | Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml' | Below is the the instruction that describes the task:
### Input:
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'
### Response:
def create_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'
'''
if not name:
raise SaltInvocationError('Required parameter \'name\' is missing')
if job_exists(name):
raise CommandExecutionError('Job \'{0}\' already exists'.format(name))
if not config_xml:
config_xml = jenkins.EMPTY_CONFIG_XML
else:
config_xml_file = _retrieve_config_xml(config_xml, saltenv)
with salt.utils.files.fopen(config_xml_file) as _fp:
config_xml = salt.utils.stringutils.to_unicode(_fp.read())
server = _connect()
try:
server.create_job(name, config_xml)
except jenkins.JenkinsException as err:
raise CommandExecutionError(
'Encountered error creating job \'{0}\': {1}'.format(name, err)
)
return config_xml |
async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) | Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated. | Below is the the instruction that describes the task:
### Input:
Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
### Response:
async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) |
def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
self._object_views['authorization'] = COMPARATIVE
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
session.use_comparative_authorization_view()
except AttributeError:
pass | Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view
### Response:
def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
self._object_views['authorization'] = COMPARATIVE
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
session.use_comparative_authorization_view()
except AttributeError:
pass |
def pushnotify(subject, message, api="pushover", priority=0, timestamp=None):
"""
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd
"""
import types
assert type(priority) is int and -1 <= priority <= 2, \
"Priority should be and int() between -1 and 2"
cfgfile = op.join(op.expanduser("~"), "pushnotify.ini")
Config = ConfigParser()
if op.exists(cfgfile):
Config.read(cfgfile)
else:
sys.exit("Push notification config file `{0}`".format(cfgfile) + \
" does not exist!")
if api == "pushover":
cfg = ConfigSectionMap(Config, api)
token, key = cfg["token"], cfg["user"]
pushover(message, token, key, title=subject, \
priority=priority, timestamp=timestamp)
elif api == "nma":
cfg = ConfigSectionMap(Config, api)
apikey = cfg["apikey"]
nma(message, apikey, event=subject, \
priority=priority)
elif api == "pushbullet":
cfg = ConfigSectionMap(Config, api)
apikey, iden = cfg["apikey"], cfg['iden']
pushbullet(message, apikey, iden, title=subject, \
type="note") | Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd | Below is the the instruction that describes the task:
### Input:
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd
### Response:
def pushnotify(subject, message, api="pushover", priority=0, timestamp=None):
"""
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd
"""
import types
assert type(priority) is int and -1 <= priority <= 2, \
"Priority should be and int() between -1 and 2"
cfgfile = op.join(op.expanduser("~"), "pushnotify.ini")
Config = ConfigParser()
if op.exists(cfgfile):
Config.read(cfgfile)
else:
sys.exit("Push notification config file `{0}`".format(cfgfile) + \
" does not exist!")
if api == "pushover":
cfg = ConfigSectionMap(Config, api)
token, key = cfg["token"], cfg["user"]
pushover(message, token, key, title=subject, \
priority=priority, timestamp=timestamp)
elif api == "nma":
cfg = ConfigSectionMap(Config, api)
apikey = cfg["apikey"]
nma(message, apikey, event=subject, \
priority=priority)
elif api == "pushbullet":
cfg = ConfigSectionMap(Config, api)
apikey, iden = cfg["apikey"], cfg['iden']
pushbullet(message, apikey, iden, title=subject, \
type="note") |
def evaluate(self, *args):
"""
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result
"""
if len(args) == 0:
callBigDlFunc(self.bigdl_type,
"evaluate", self.value)
return self
elif len(args) == 3:
dataset, batch_size, val_methods = args
if (isinstance(dataset, ImageFrame)):
return callBigDlFunc(self.bigdl_type,
"modelEvaluateImageFrame",
self.value,
dataset, batch_size, val_methods)
else:
return callBigDlFunc(self.bigdl_type,
"modelEvaluate",
self.value,
dataset, batch_size, val_methods)
else:
raise Exception("Error when calling evaluate(): it takes no argument or exactly three arguments only") | No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result | Below is the the instruction that describes the task:
### Input:
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result
### Response:
def evaluate(self, *args):
"""
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result
"""
if len(args) == 0:
callBigDlFunc(self.bigdl_type,
"evaluate", self.value)
return self
elif len(args) == 3:
dataset, batch_size, val_methods = args
if (isinstance(dataset, ImageFrame)):
return callBigDlFunc(self.bigdl_type,
"modelEvaluateImageFrame",
self.value,
dataset, batch_size, val_methods)
else:
return callBigDlFunc(self.bigdl_type,
"modelEvaluate",
self.value,
dataset, batch_size, val_methods)
else:
raise Exception("Error when calling evaluate(): it takes no argument or exactly three arguments only") |
async def commit(self, snap):
'''
Push the recorded changes to disk, notify all the listeners
'''
if not self.npvs: # nothing to do
return
for node, prop, _, valu in self.npvs:
node.props[prop.name] = valu
node.proplayr[prop.name] = snap.wlyr
splices = [snap.splice('node:add', ndef=node.ndef) for node in self.mybldgbuids.values()]
for node, prop, oldv, valu in self.npvs:
info = {'ndef': node.ndef, 'prop': prop.name, 'valu': valu}
if oldv is not None:
info['oldv'] = oldv
splices.append(snap.splice('prop:set', **info))
await snap.stor(self.sops, splices)
for node in self.mybldgbuids.values():
snap.core.pokeFormCount(node.form.name, 1)
snap.buidcache.append(node)
snap.livenodes[node.buid] = node
await self.rendevous()
for node in self.mybldgbuids.values():
await node.form.wasAdded(node)
# fire all his prop sets
for node, prop, oldv, valu in self.npvs:
await prop.wasSet(node, oldv)
if prop.univ:
univ = snap.model.prop(prop.univ)
await univ.wasSet(node, oldv)
# Finally, fire all the triggers
for node, prop, oldv, _ in self.npvs:
await snap.core.triggers.runPropSet(node, prop, oldv) | Push the recorded changes to disk, notify all the listeners | Below is the the instruction that describes the task:
### Input:
Push the recorded changes to disk, notify all the listeners
### Response:
async def commit(self, snap):
'''
Push the recorded changes to disk, notify all the listeners
'''
if not self.npvs: # nothing to do
return
for node, prop, _, valu in self.npvs:
node.props[prop.name] = valu
node.proplayr[prop.name] = snap.wlyr
splices = [snap.splice('node:add', ndef=node.ndef) for node in self.mybldgbuids.values()]
for node, prop, oldv, valu in self.npvs:
info = {'ndef': node.ndef, 'prop': prop.name, 'valu': valu}
if oldv is not None:
info['oldv'] = oldv
splices.append(snap.splice('prop:set', **info))
await snap.stor(self.sops, splices)
for node in self.mybldgbuids.values():
snap.core.pokeFormCount(node.form.name, 1)
snap.buidcache.append(node)
snap.livenodes[node.buid] = node
await self.rendevous()
for node in self.mybldgbuids.values():
await node.form.wasAdded(node)
# fire all his prop sets
for node, prop, oldv, valu in self.npvs:
await prop.wasSet(node, oldv)
if prop.univ:
univ = snap.model.prop(prop.univ)
await univ.wasSet(node, oldv)
# Finally, fire all the triggers
for node, prop, oldv, _ in self.npvs:
await snap.core.triggers.runPropSet(node, prop, oldv) |
def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a value in the ZBarSymbol enumeration
symbol_type = ZBarSymbol(symbol.contents.type).name
polygon = convex_hull(
(
zbar_symbol_get_loc_x(symbol, index),
zbar_symbol_get_loc_y(symbol, index)
)
for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))
)
yield Decoded(
data=data,
type=symbol_type,
rect=bounding_box(polygon),
polygon=polygon
) | Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol | Below is the the instruction that describes the task:
### Input:
Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
### Response:
def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a value in the ZBarSymbol enumeration
symbol_type = ZBarSymbol(symbol.contents.type).name
polygon = convex_hull(
(
zbar_symbol_get_loc_x(symbol, index),
zbar_symbol_get_loc_y(symbol, index)
)
for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))
)
yield Decoded(
data=data,
type=symbol_type,
rect=bounding_box(polygon),
polygon=polygon
) |
def isempty(path):
"""Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
"""
cmd = "hadoop fs -test -z %s"
p = _hadoop_fs_command(cmd % (path))
p.communicate()
rcode = p.returncode
return bool(int(rcode == 0)) | Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
### Response:
def isempty(path):
"""Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
"""
cmd = "hadoop fs -test -z %s"
p = _hadoop_fs_command(cmd % (path))
p.communicate()
rcode = p.returncode
return bool(int(rcode == 0)) |
def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} | Figure out if an aesthetic is a position aesthetic or not | Below is the the instruction that describes the task:
### Input:
Figure out if an aesthetic is a position aesthetic or not
### Response:
def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} |
def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp = self.request('POST', action, data)
if resp['code'] == 200:
return resp['result']['songs']
return [] | get songs list from search keywords | Below is the the instruction that describes the task:
### Input:
get songs list from search keywords
### Response:
def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp = self.request('POST', action, data)
if resp['code'] == 200:
return resp['result']['songs']
return [] |
def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
def _get_institutions(value):
c_values = force_list(value.get('c'))
z_values = force_list(value.get('z'))
# XXX: we zip only when they have the same length, otherwise
# we might match a value with the wrong recid.
if len(c_values) != len(z_values):
return [{'name': c_value} for c_value in c_values]
else:
return [{
'curated_relation': True,
'name': c_value,
'record': get_record_ref(z_value, 'institutions'),
} for c_value, z_value in zip(c_values, z_values)]
thesis_info = self.get('thesis_info', {})
thesis_info['date'] = normalize_date(force_single_element(value.get('d')))
thesis_info['degree_type'] = _get_degree_type(value)
thesis_info['institutions'] = _get_institutions(value)
return thesis_info | Populate the ``thesis_info`` key. | Below is the the instruction that describes the task:
### Input:
Populate the ``thesis_info`` key.
### Response:
def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
def _get_institutions(value):
c_values = force_list(value.get('c'))
z_values = force_list(value.get('z'))
# XXX: we zip only when they have the same length, otherwise
# we might match a value with the wrong recid.
if len(c_values) != len(z_values):
return [{'name': c_value} for c_value in c_values]
else:
return [{
'curated_relation': True,
'name': c_value,
'record': get_record_ref(z_value, 'institutions'),
} for c_value, z_value in zip(c_values, z_values)]
thesis_info = self.get('thesis_info', {})
thesis_info['date'] = normalize_date(force_single_element(value.get('d')))
thesis_info['degree_type'] = _get_degree_type(value)
thesis_info['institutions'] = _get_institutions(value)
return thesis_info |
def get_kws_plt(self):
"""Get keyword args for GoSubDagPlot from self unless they are None."""
kws_plt = {}
for key_plt in self.keys_plt:
key_val = getattr(self, key_plt, None)
if key_val is not None:
kws_plt[key_plt] = key_val
elif key_plt in self.kws:
kws_plt[key_plt] = self.kws[key_plt]
return kws_plt | Get keyword args for GoSubDagPlot from self unless they are None. | Below is the the instruction that describes the task:
### Input:
Get keyword args for GoSubDagPlot from self unless they are None.
### Response:
def get_kws_plt(self):
"""Get keyword args for GoSubDagPlot from self unless they are None."""
kws_plt = {}
for key_plt in self.keys_plt:
key_val = getattr(self, key_plt, None)
if key_val is not None:
kws_plt[key_plt] = key_val
elif key_plt in self.kws:
kws_plt[key_plt] = self.kws[key_plt]
return kws_plt |
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | set the environment timezone to the timezone
set in your twitter settings | Below is the the instruction that describes the task:
### Input:
set the environment timezone to the timezone
set in your twitter settings
### Response:
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() |
def macro_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-macro"
api_path = "/api/v2/macros/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/macros#show-macro | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/macros#show-macro
### Response:
def macro_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-macro"
api_path = "/api/v2/macros/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False,
truesize=None):
"""Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle
"""
im = np.asarray(im)
# Compute edge
if not isshiftdftedge:
im = edge(im)
return reg.orientation_angle(im, isshiftdft=isshiftdftedge,
approxangle=chanapproxangle,
truesize=truesize) | Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle | Below is the the instruction that describes the task:
### Input:
Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle
### Response:
def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False,
truesize=None):
"""Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle
"""
im = np.asarray(im)
# Compute edge
if not isshiftdftedge:
im = edge(im)
return reg.orientation_angle(im, isshiftdft=isshiftdftedge,
approxangle=chanapproxangle,
truesize=truesize) |
def _plot_simple_fault(self, source, border='k-', border_width=1.0):
"""
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail)
"""
# Get the trace
trace_lons = np.array([pnt.longitude
for pnt in source.fault_trace.points])
trace_lats = np.array([pnt.latitude
for pnt in source.fault_trace.points])
surface_projection = _fault_polygon_from_mesh(source)
# Plot surface projection first
x, y = self.m(surface_projection[:, 0], surface_projection[:, 1])
self.m.plot(x, y, border, linewidth=border_width)
# Plot fault trace
x, y = self.m(trace_lons, trace_lats)
self.m.plot(x, y, border, linewidth=1.3 * border_width) | Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail) | Below is the the instruction that describes the task:
### Input:
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail)
### Response:
def _plot_simple_fault(self, source, border='k-', border_width=1.0):
"""
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail)
"""
# Get the trace
trace_lons = np.array([pnt.longitude
for pnt in source.fault_trace.points])
trace_lats = np.array([pnt.latitude
for pnt in source.fault_trace.points])
surface_projection = _fault_polygon_from_mesh(source)
# Plot surface projection first
x, y = self.m(surface_projection[:, 0], surface_projection[:, 1])
self.m.plot(x, y, border, linewidth=border_width)
# Plot fault trace
x, y = self.m(trace_lons, trace_lats)
self.m.plot(x, y, border, linewidth=1.3 * border_width) |
def log_level(level_string):
"""
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
"""
if level_string.isdigit():
return int(level_string)
return getattr(logging, level_string.upper()) | Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True | Below is the the instruction that describes the task:
### Input:
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
### Response:
def log_level(level_string):
"""
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
"""
if level_string.isdigit():
return int(level_string)
return getattr(logging, level_string.upper()) |
def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) | Log things with the global logger. | Below is the the instruction that describes the task:
### Input:
Log things with the global logger.
### Response:
def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.