code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_record(self, name, record_id):
"""Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
"""
if name in self._cache:
if record_id in self._cache[name]:
return self._cache[name][record_id] | Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model. | Below is the the instruction that describes the task:
### Input:
Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
### Response:
def get_record(self, name, record_id):
"""Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
"""
if name in self._cache:
if record_id in self._cache[name]:
return self._cache[name][record_id] |
def fit_model(ts, sc=None):
"""
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
"""
assert sc != None, "Missing SparkContext"
jvm = sc._jvm
jmodel = jvm.com.cloudera.sparkts.models.GARCH.fitModel(_py2java(sc, Vectors.dense(ts)))
return GARCHModel(jmodel=jmodel, sc=sc) | Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model | Below is the the instruction that describes the task:
### Input:
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
### Response:
def fit_model(ts, sc=None):
"""
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
"""
assert sc != None, "Missing SparkContext"
jvm = sc._jvm
jmodel = jvm.com.cloudera.sparkts.models.GARCH.fitModel(_py2java(sc, Vectors.dense(ts)))
return GARCHModel(jmodel=jmodel, sc=sc) |
def set_version(self):
""" compute and set our version """
version = _ensure_decoded(
getattr(self.group._v_attrs, 'pandas_version', None))
try:
self.version = tuple(int(x) for x in version.split('.'))
if len(self.version) == 2:
self.version = self.version + (0,)
except AttributeError:
self.version = (0, 0, 0) | compute and set our version | Below is the the instruction that describes the task:
### Input:
compute and set our version
### Response:
def set_version(self):
""" compute and set our version """
version = _ensure_decoded(
getattr(self.group._v_attrs, 'pandas_version', None))
try:
self.version = tuple(int(x) for x in version.split('.'))
if len(self.version) == 2:
self.version = self.version + (0,)
except AttributeError:
self.version = (0, 0, 0) |
def parse_multiple(s, f, values=None):
"""Parse multiple comma-separated elements, each of which is parsed
using function f."""
if values is None: values = []
values.append(f(s))
if s.pos < len(s) and s.cur == ',':
s.pos += 1
return parse_multiple(s, f, values)
else:
return values | Parse multiple comma-separated elements, each of which is parsed
using function f. | Below is the the instruction that describes the task:
### Input:
Parse multiple comma-separated elements, each of which is parsed
using function f.
### Response:
def parse_multiple(s, f, values=None):
"""Parse multiple comma-separated elements, each of which is parsed
using function f."""
if values is None: values = []
values.append(f(s))
if s.pos < len(s) and s.cur == ',':
s.pos += 1
return parse_multiple(s, f, values)
else:
return values |
def publish(self):
'''
Perform HTTP session to transmit defined weather values.
'''
return self._publish( self.args, self.server, self.URI) | Perform HTTP session to transmit defined weather values. | Below is the the instruction that describes the task:
### Input:
Perform HTTP session to transmit defined weather values.
### Response:
def publish(self):
'''
Perform HTTP session to transmit defined weather values.
'''
return self._publish( self.args, self.server, self.URI) |
def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ind = range(len(string))
pos = self.buildfence(ind, self.key)
return ''.join(string[pos.index(i)] for i in ind) | Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string. | Below is the the instruction that describes the task:
### Input:
Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
### Response:
def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ind = range(len(string))
pos = self.buildfence(ind, self.key)
return ''.join(string[pos.index(i)] for i in ind) |
def value(self, index, extra):
"""Returns ('Simple', #codewords) or ('Complex', HSKIP)
"""
if index==1:
if extra>3:
raise ValueError('value: extra out of range')
return 'Simple', extra+1
if extra:
raise ValueError('value: extra out of range')
return 'Complex', index | Returns ('Simple', #codewords) or ('Complex', HSKIP) | Below is the the instruction that describes the task:
### Input:
Returns ('Simple', #codewords) or ('Complex', HSKIP)
### Response:
def value(self, index, extra):
"""Returns ('Simple', #codewords) or ('Complex', HSKIP)
"""
if index==1:
if extra>3:
raise ValueError('value: extra out of range')
return 'Simple', extra+1
if extra:
raise ValueError('value: extra out of range')
return 'Complex', index |
def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
'%s.avsc' % (content_type,)), 'r') as fp:
data = fp.read()
return avro.schema.parse(data)
except IOError: # pragma: no cover
raise NotFound('Schema does not exist.') | Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict | Below is the the instruction that describes the task:
### Input:
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
### Response:
def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
'%s.avsc' % (content_type,)), 'r') as fp:
data = fp.read()
return avro.schema.parse(data)
except IOError: # pragma: no cover
raise NotFound('Schema does not exist.') |
def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
"""
list_from, list_to = self.compute_before_after()
if source_path.startswith(os.sep):
source_path = source_path[1:]
if source_path and not source_path.endswith(os.sep):
source_path += os.sep
if target_path.startswith(os.sep):
target_path = target_path[1:]
if target_path and not target_path.endswith(os.sep):
target_path += os.sep
fromfile = 'a/' + source_path + os.path.basename(self.input_file)
tofile = 'b/' + target_path + os.path.basename(self.input_file)
diff_list = difflib.unified_diff(list_from, list_to, fromfile, tofile)
return [d for d in diff_list] | Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str] | Below is the the instruction that describes the task:
### Input:
Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
### Response:
def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
"""
list_from, list_to = self.compute_before_after()
if source_path.startswith(os.sep):
source_path = source_path[1:]
if source_path and not source_path.endswith(os.sep):
source_path += os.sep
if target_path.startswith(os.sep):
target_path = target_path[1:]
if target_path and not target_path.endswith(os.sep):
target_path += os.sep
fromfile = 'a/' + source_path + os.path.basename(self.input_file)
tofile = 'b/' + target_path + os.path.basename(self.input_file)
diff_list = difflib.unified_diff(list_from, list_to, fromfile, tofile)
return [d for d in diff_list] |
def compute_metric(self, components):
"""Compute recall from `components`"""
numerator = components[RECALL_RELEVANT_RETRIEVED]
denominator = components[RECALL_RELEVANT]
if denominator == 0.:
if numerator == 0:
return 1.
else:
raise ValueError('')
else:
return numerator/denominator | Compute recall from `components` | Below is the the instruction that describes the task:
### Input:
Compute recall from `components`
### Response:
def compute_metric(self, components):
"""Compute recall from `components`"""
numerator = components[RECALL_RELEVANT_RETRIEVED]
denominator = components[RECALL_RELEVANT]
if denominator == 0.:
if numerator == 0:
return 1.
else:
raise ValueError('')
else:
return numerator/denominator |
def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify()
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
# flag all notifications as disabled and re-enable as required
Notification.objects.all().update(enabled=False)
if site_notifications.loaded:
if verbose:
sys.stdout.write(
style.MIGRATE_HEADING("Populating Notification model:\n")
)
self.delete_unregistered_notifications(apps=apps)
for name, notification_cls in site_notifications.registry.items():
if verbose:
sys.stdout.write(
f" * Adding '{name}': '{notification_cls().display_name}'\n"
)
try:
obj = Notification.objects.get(name=name)
except ObjectDoesNotExist:
Notification.objects.create(
name=name,
display_name=notification_cls().display_name,
enabled=True,
)
else:
obj.display_name = notification_cls().display_name
obj.enabled = True
obj.save() | Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify() | Below is the the instruction that describes the task:
### Input:
Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify()
### Response:
def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify()
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
# flag all notifications as disabled and re-enable as required
Notification.objects.all().update(enabled=False)
if site_notifications.loaded:
if verbose:
sys.stdout.write(
style.MIGRATE_HEADING("Populating Notification model:\n")
)
self.delete_unregistered_notifications(apps=apps)
for name, notification_cls in site_notifications.registry.items():
if verbose:
sys.stdout.write(
f" * Adding '{name}': '{notification_cls().display_name}'\n"
)
try:
obj = Notification.objects.get(name=name)
except ObjectDoesNotExist:
Notification.objects.create(
name=name,
display_name=notification_cls().display_name,
enabled=True,
)
else:
obj.display_name = notification_cls().display_name
obj.enabled = True
obj.save() |
def or_(cls, *queries):
"""
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
"""
if len(queries) < 2:
raise ValueError('or_ need two queries at least')
if not all(x._query_class._class_name == queries[0]._query_class._class_name for x in queries):
raise TypeError('All queries must be for the same class')
query = Query(queries[0]._query_class._class_name)
query._or_query(queries)
return query | 根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query | Below is the the instruction that describes the task:
### Input:
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
### Response:
def or_(cls, *queries):
"""
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
"""
if len(queries) < 2:
raise ValueError('or_ need two queries at least')
if not all(x._query_class._class_name == queries[0]._query_class._class_name for x in queries):
raise TypeError('All queries must be for the same class')
query = Query(queries[0]._query_class._class_name)
query._or_query(queries)
return query |
def critical_section_lock(lock=None, blocking=True, timeout=None, raise_exception=True):
""" An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a function will be protected
:param blocking: same as blocking in :func:`.critical_section_dynamic_lock` function
:param timeout: same as timeout in :func:`.critical_section_dynamic_lock` function
:param raise_exception: same as raise_exception in :func:`.critical_section_dynamic_lock` function
:return: decorator with which a target function may be protected
"""
def lock_getter(*args, **kwargs):
return lock
return critical_section_dynamic_lock(
lock_fn=lock_getter, blocking=blocking, timeout=timeout, raise_exception=raise_exception
) | An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a function will be protected
:param blocking: same as blocking in :func:`.critical_section_dynamic_lock` function
:param timeout: same as timeout in :func:`.critical_section_dynamic_lock` function
:param raise_exception: same as raise_exception in :func:`.critical_section_dynamic_lock` function
:return: decorator with which a target function may be protected | Below is the the instruction that describes the task:
### Input:
An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a function will be protected
:param blocking: same as blocking in :func:`.critical_section_dynamic_lock` function
:param timeout: same as timeout in :func:`.critical_section_dynamic_lock` function
:param raise_exception: same as raise_exception in :func:`.critical_section_dynamic_lock` function
:return: decorator with which a target function may be protected
### Response:
def critical_section_lock(lock=None, blocking=True, timeout=None, raise_exception=True):
""" An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a function will be protected
:param blocking: same as blocking in :func:`.critical_section_dynamic_lock` function
:param timeout: same as timeout in :func:`.critical_section_dynamic_lock` function
:param raise_exception: same as raise_exception in :func:`.critical_section_dynamic_lock` function
:return: decorator with which a target function may be protected
"""
def lock_getter(*args, **kwargs):
return lock
return critical_section_dynamic_lock(
lock_fn=lock_getter, blocking=blocking, timeout=timeout, raise_exception=raise_exception
) |
def command(self, vehicle_id, name, data=None, wake_if_asleep=True):
"""Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdorr.com/api-basics/vehicles#vehicle_id-vs-id
name : string
Tesla API command. https://tesla-api.timdorr.com/vehicle/commands
data : dict
Optional parameters.
wake_if_asleep : bool
Function for underlying api call for whether a failed response
should wake up the vehicle or retry.
Returns
-------
dict
Tesla json object.
"""
data = data or {}
return self.post(vehicle_id, 'command/%s' % name, data,
wake_if_asleep=wake_if_asleep) | Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdorr.com/api-basics/vehicles#vehicle_id-vs-id
name : string
Tesla API command. https://tesla-api.timdorr.com/vehicle/commands
data : dict
Optional parameters.
wake_if_asleep : bool
Function for underlying api call for whether a failed response
should wake up the vehicle or retry.
Returns
-------
dict
Tesla json object. | Below is the the instruction that describes the task:
### Input:
Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdorr.com/api-basics/vehicles#vehicle_id-vs-id
name : string
Tesla API command. https://tesla-api.timdorr.com/vehicle/commands
data : dict
Optional parameters.
wake_if_asleep : bool
Function for underlying api call for whether a failed response
should wake up the vehicle or retry.
Returns
-------
dict
Tesla json object.
### Response:
def command(self, vehicle_id, name, data=None, wake_if_asleep=True):
"""Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdorr.com/api-basics/vehicles#vehicle_id-vs-id
name : string
Tesla API command. https://tesla-api.timdorr.com/vehicle/commands
data : dict
Optional parameters.
wake_if_asleep : bool
Function for underlying api call for whether a failed response
should wake up the vehicle or retry.
Returns
-------
dict
Tesla json object.
"""
data = data or {}
return self.post(vehicle_id, 'command/%s' % name, data,
wake_if_asleep=wake_if_asleep) |
def zip_clean_metaxml(zip_src, logger=None):
""" Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
content = zip_src.read(name)
if name.startswith(META_XML_CLEAN_DIRS) and name.endswith("-meta.xml"):
try:
content.decode("utf-8")
except UnicodeDecodeError:
# if we cannot decode the content, it may be binary;
# don't try and replace it.
pass
else:
clean_content = remove_xml_element_string("packageVersions", content)
if clean_content != content:
changed.append(name)
content = clean_content
zip_dest.writestr(name, content)
if changed and logger:
logger.info(
"Cleaned package versions from {} meta.xml files".format(len(changed))
)
return zip_dest | Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements | Below is the the instruction that describes the task:
### Input:
Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements
### Response:
def zip_clean_metaxml(zip_src, logger=None):
""" Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
content = zip_src.read(name)
if name.startswith(META_XML_CLEAN_DIRS) and name.endswith("-meta.xml"):
try:
content.decode("utf-8")
except UnicodeDecodeError:
# if we cannot decode the content, it may be binary;
# don't try and replace it.
pass
else:
clean_content = remove_xml_element_string("packageVersions", content)
if clean_content != content:
changed.append(name)
content = clean_content
zip_dest.writestr(name, content)
if changed and logger:
logger.info(
"Cleaned package versions from {} meta.xml files".format(len(changed))
)
return zip_dest |
def visit_Method(self, method):
"""
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
"""
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should already be the resolved version.
result = []
for param in method.params:
resolved_param = texpr(param.resolved.type, param.resolved.bindings, extra_bindings)
result.append(resolved_param.id)
return result
def get_return_type(method, extra_bindings):
# The Method should already be the resolved version.
return texpr(method.type.resolved.type, method.type.resolved.bindings,
extra_bindings).id
def signature(method, return_type, params):
return "%s %s(%s)" % (return_type, method.name.text, ", ".join(params))
# Ensure the method has the same signature as matching methods on parent
# interfaces:
interfaces = list(t for t in method.clazz.bases if isinstance(t.resolved.type, Interface))
for interface in interfaces:
interfaceTypeExpr = interface.resolved
for definition in interfaceTypeExpr.type.definitions:
if definition.name.text == method.name.text:
resolved_definition = definition.resolved.type
method_params = get_params(resolved_method, method.clazz.resolved.bindings)
definition_params = get_params(resolved_definition, interfaceTypeExpr.bindings)
method_return = get_return_type(resolved_method, method.clazz.resolved.bindings)
definition_return = get_return_type(resolved_definition, interfaceTypeExpr.bindings)
if method_params != definition_params or method_return != definition_return:
self.errors.append(
"%s: method signature '%s' on %s does not match method '%s' on interface %s" % (
lineinfo(method), signature(resolved_method, method_return, method_params),
method.clazz.resolved.type.id,
signature(resolved_definition, definition_return, definition_params),
interface.resolved.type.id)) | Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance. | Below is the the instruction that describes the task:
### Input:
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
### Response:
def visit_Method(self, method):
"""
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
"""
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should already be the resolved version.
result = []
for param in method.params:
resolved_param = texpr(param.resolved.type, param.resolved.bindings, extra_bindings)
result.append(resolved_param.id)
return result
def get_return_type(method, extra_bindings):
# The Method should already be the resolved version.
return texpr(method.type.resolved.type, method.type.resolved.bindings,
extra_bindings).id
def signature(method, return_type, params):
return "%s %s(%s)" % (return_type, method.name.text, ", ".join(params))
# Ensure the method has the same signature as matching methods on parent
# interfaces:
interfaces = list(t for t in method.clazz.bases if isinstance(t.resolved.type, Interface))
for interface in interfaces:
interfaceTypeExpr = interface.resolved
for definition in interfaceTypeExpr.type.definitions:
if definition.name.text == method.name.text:
resolved_definition = definition.resolved.type
method_params = get_params(resolved_method, method.clazz.resolved.bindings)
definition_params = get_params(resolved_definition, interfaceTypeExpr.bindings)
method_return = get_return_type(resolved_method, method.clazz.resolved.bindings)
definition_return = get_return_type(resolved_definition, interfaceTypeExpr.bindings)
if method_params != definition_params or method_return != definition_return:
self.errors.append(
"%s: method signature '%s' on %s does not match method '%s' on interface %s" % (
lineinfo(method), signature(resolved_method, method_return, method_params),
method.clazz.resolved.type.id,
signature(resolved_definition, definition_return, definition_params),
interface.resolved.type.id)) |
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
return __import__(obj) | Import and return bar given the string foo.bar. | Below is the the instruction that describes the task:
### Input:
Import and return bar given the string foo.bar.
### Response:
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
return __import__(obj) |
def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
"orderId": orderId,
"parentId": parentId,
"lastPrice": lastPrice,
"trailAmount": trailAmount,
"trailPercent": trailPercent,
"quantity": quantity,
"ticksize": ticksize
}
return trailingStop | adds trailing stop to monitor list | Below is the the instruction that describes the task:
### Input:
adds trailing stop to monitor list
### Response:
def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
"orderId": orderId,
"parentId": parentId,
"lastPrice": lastPrice,
"trailAmount": trailAmount,
"trailPercent": trailPercent,
"quantity": quantity,
"ticksize": ticksize
}
return trailingStop |
def indexOf(self, url):
"""
Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int>
"""
for i, (m_url, _) in enumerate(self._stack):
if m_url == url:
return i
return -1 | Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int> | Below is the the instruction that describes the task:
### Input:
Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int>
### Response:
def indexOf(self, url):
"""
Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int>
"""
for i, (m_url, _) in enumerate(self._stack):
if m_url == url:
return i
return -1 |
def _consolidate(self, inplace=False):
"""
Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing object
Returns
-------
consolidated : same type as caller
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if inplace:
self._consolidate_inplace()
else:
f = lambda: self._data.consolidate()
cons_data = self._protect_consolidate(f)
return self._constructor(cons_data).__finalize__(self) | Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing object
Returns
-------
consolidated : same type as caller | Below is the the instruction that describes the task:
### Input:
Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing object
Returns
-------
consolidated : same type as caller
### Response:
def _consolidate(self, inplace=False):
"""
Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing object
Returns
-------
consolidated : same type as caller
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if inplace:
self._consolidate_inplace()
else:
f = lambda: self._data.consolidate()
cons_data = self._protect_consolidate(f)
return self._constructor(cons_data).__finalize__(self) |
def provision_vdp_overlay_networks(self, port_uuid, mac, net_uuid,
segmentation_id, lvid, oui):
"""Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_uuid: the uuid of the network associated with this vlan.
:param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel'
:lvid: Local VLAN ID
:oui: OUI Parameters
"""
lldpad_port = self.lldpad_info
if lldpad_port:
ovs_cb_data = {'obj': self, 'port_uuid': port_uuid, 'mac': mac,
'net_uuid': net_uuid}
vdp_vlan, fail_reason = lldpad_port.send_vdp_vnic_up(
port_uuid=port_uuid, vsiid=port_uuid, gid=segmentation_id,
mac=mac, new_network=True, oui=oui,
vsw_cb_fn=self.vdp_vlan_change, vsw_cb_data=ovs_cb_data)
else:
fail_reason = "There is no LLDPad port available."
LOG.error("%s", fail_reason)
return {'result': False, 'vdp_vlan': cconstants.INVALID_VLAN,
'fail_reason': fail_reason}
# check validity
if not ovs_lib.is_valid_vlan_tag(vdp_vlan):
LOG.error("Cannot provision VDP Overlay network for"
" net-id=%(net_uuid)s - Invalid ",
{'net_uuid': net_uuid})
return {'result': True, 'vdp_vlan': cconstants.INVALID_VLAN,
'fail_reason': fail_reason}
LOG.info('provision_vdp_overlay_networks: add_flow for '
'Local Vlan %(local_vlan)s VDP VLAN %(vdp_vlan)s',
{'local_vlan': lvid, 'vdp_vlan': vdp_vlan})
self.program_vm_ovs_flows(lvid, 0, vdp_vlan)
return {'result': True, 'vdp_vlan': vdp_vlan, 'fail_reason': None} | Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_uuid: the uuid of the network associated with this vlan.
:param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel'
:lvid: Local VLAN ID
:oui: OUI Parameters | Below is the the instruction that describes the task:
### Input:
Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_uuid: the uuid of the network associated with this vlan.
:param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel'
:lvid: Local VLAN ID
:oui: OUI Parameters
### Response:
def provision_vdp_overlay_networks(self, port_uuid, mac, net_uuid,
segmentation_id, lvid, oui):
"""Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_uuid: the uuid of the network associated with this vlan.
:param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel'
:lvid: Local VLAN ID
:oui: OUI Parameters
"""
lldpad_port = self.lldpad_info
if lldpad_port:
ovs_cb_data = {'obj': self, 'port_uuid': port_uuid, 'mac': mac,
'net_uuid': net_uuid}
vdp_vlan, fail_reason = lldpad_port.send_vdp_vnic_up(
port_uuid=port_uuid, vsiid=port_uuid, gid=segmentation_id,
mac=mac, new_network=True, oui=oui,
vsw_cb_fn=self.vdp_vlan_change, vsw_cb_data=ovs_cb_data)
else:
fail_reason = "There is no LLDPad port available."
LOG.error("%s", fail_reason)
return {'result': False, 'vdp_vlan': cconstants.INVALID_VLAN,
'fail_reason': fail_reason}
# check validity
if not ovs_lib.is_valid_vlan_tag(vdp_vlan):
LOG.error("Cannot provision VDP Overlay network for"
" net-id=%(net_uuid)s - Invalid ",
{'net_uuid': net_uuid})
return {'result': True, 'vdp_vlan': cconstants.INVALID_VLAN,
'fail_reason': fail_reason}
LOG.info('provision_vdp_overlay_networks: add_flow for '
'Local Vlan %(local_vlan)s VDP VLAN %(vdp_vlan)s',
{'local_vlan': lvid, 'vdp_vlan': vdp_vlan})
self.program_vm_ovs_flows(lvid, 0, vdp_vlan)
return {'result': True, 'vdp_vlan': vdp_vlan, 'fail_reason': None} |
def _pos(self, k):
"""
Description:
Position k breaking
Parameters:
k: position k is used for the breaking
"""
if k < 2:
raise ValueError("k smaller than 2")
G = np.zeros((self.m, self.m))
for i in range(self.m):
for j in range(self.m):
if i == j:
continue
if i < k or j < k:
continue
if i == k or j == k:
G[i][j] = 1
return G | Description:
Position k breaking
Parameters:
k: position k is used for the breaking | Below is the the instruction that describes the task:
### Input:
Description:
Position k breaking
Parameters:
k: position k is used for the breaking
### Response:
def _pos(self, k):
"""
Description:
Position k breaking
Parameters:
k: position k is used for the breaking
"""
if k < 2:
raise ValueError("k smaller than 2")
G = np.zeros((self.m, self.m))
for i in range(self.m):
for j in range(self.m):
if i == j:
continue
if i < k or j < k:
continue
if i == k or j == k:
G[i][j] = 1
return G |
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={},
style={}, options={}, **kwargs):
"""
Get Chartjs html
"""
try:
xdata = list(self.df[xcol])
except Exception as e:
self.err(e, self._get_chartjs_chart,
"Can not get data for x field ", ycol)
return
if label is None:
label = "Data"
try:
if type(ycol) != list:
ydata = [dict(name=label, data=list(self.df[ycol]))]
else:
ydata = []
for col in ycol:
y = {}
y["name"] = col
y["data"] = list(self.df[col])
ydata.append(y)
except Exception as e:
self.err(e, self._get_chartjs_chart,
"Can not get data for y field ", xcol)
return
try:
slug = str(uuid.uuid4())
html = chart.get(slug, xdata, ydata, label,
opts, style, chart_type, **kwargs)
return html
except Exception as e:
self.err(e, self._get_chartjs_chart, "Can not get chart") | Get Chartjs html | Below is the the instruction that describes the task:
### Input:
Get Chartjs html
### Response:
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={},
style={}, options={}, **kwargs):
"""
Get Chartjs html
"""
try:
xdata = list(self.df[xcol])
except Exception as e:
self.err(e, self._get_chartjs_chart,
"Can not get data for x field ", ycol)
return
if label is None:
label = "Data"
try:
if type(ycol) != list:
ydata = [dict(name=label, data=list(self.df[ycol]))]
else:
ydata = []
for col in ycol:
y = {}
y["name"] = col
y["data"] = list(self.df[col])
ydata.append(y)
except Exception as e:
self.err(e, self._get_chartjs_chart,
"Can not get data for y field ", xcol)
return
try:
slug = str(uuid.uuid4())
html = chart.get(slug, xdata, ydata, label,
opts, style, chart_type, **kwargs)
return html
except Exception as e:
self.err(e, self._get_chartjs_chart, "Can not get chart") |
def _enable_profiling():
""" Start profiling and register callback to print stats when the program
exits.
"""
import cProfile
import atexit
global _profiler
_profiler = cProfile.Profile()
_profiler.enable()
atexit.register(_profile_atexit) | Start profiling and register callback to print stats when the program
exits. | Below is the the instruction that describes the task:
### Input:
Start profiling and register callback to print stats when the program
exits.
### Response:
def _enable_profiling():
""" Start profiling and register callback to print stats when the program
exits.
"""
import cProfile
import atexit
global _profiler
_profiler = cProfile.Profile()
_profiler.enable()
atexit.register(_profile_atexit) |
def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]):
"""
Attach list of media
:param medias:
"""
for media in medias:
self.attach(media) | Attach list of media
:param medias: | Below is the the instruction that describes the task:
### Input:
Attach list of media
:param medias:
### Response:
def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]):
"""
Attach list of media
:param medias:
"""
for media in medias:
self.attach(media) |
def conf_sets(self):
'''The dictionary of configuration sets in this component, if any.'''
with self._mutex:
if not self._conf_sets:
self._parse_configuration()
return self._conf_sets | The dictionary of configuration sets in this component, if any. | Below is the the instruction that describes the task:
### Input:
The dictionary of configuration sets in this component, if any.
### Response:
def conf_sets(self):
'''The dictionary of configuration sets in this component, if any.'''
with self._mutex:
if not self._conf_sets:
self._parse_configuration()
return self._conf_sets |
def convert_to_vertexlist(geometry, **kwargs):
"""
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor.
"""
if util.is_instance_named(geometry, 'Trimesh'):
return mesh_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'Path'):
# works for Path3D and Path2D
# both of which inherit from Path
return path_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'PointCloud'):
# pointcloud objects contain colors
return points_to_vertexlist(geometry.vertices,
colors=geometry.colors,
**kwargs)
elif util.is_instance_named(geometry, 'ndarray'):
# (n,2) or (n,3) points
return points_to_vertexlist(geometry, **kwargs)
else:
raise ValueError('Geometry passed is not a viewable type!') | Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor. | Below is the the instruction that describes the task:
### Input:
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor.
### Response:
def convert_to_vertexlist(geometry, **kwargs):
"""
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor.
"""
if util.is_instance_named(geometry, 'Trimesh'):
return mesh_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'Path'):
# works for Path3D and Path2D
# both of which inherit from Path
return path_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'PointCloud'):
# pointcloud objects contain colors
return points_to_vertexlist(geometry.vertices,
colors=geometry.colors,
**kwargs)
elif util.is_instance_named(geometry, 'ndarray'):
# (n,2) or (n,3) points
return points_to_vertexlist(geometry, **kwargs)
else:
raise ValueError('Geometry passed is not a viewable type!') |
def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
assert isinstance(condition, basestring), 'conditions must be strings'
namespace = condition_set.get_namespace()
if namespace not in self.value:
self.value[namespace] = {}
if field_name not in self.value[namespace]:
self.value[namespace][field_name] = []
if condition not in self.value[namespace][field_name]:
self.value[namespace][field_name].append((exclude and EXCLUDE or INCLUDE, condition))
if commit:
self.save() | Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP | Below is the the instruction that describes the task:
### Input:
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP
### Response:
def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
assert isinstance(condition, basestring), 'conditions must be strings'
namespace = condition_set.get_namespace()
if namespace not in self.value:
self.value[namespace] = {}
if field_name not in self.value[namespace]:
self.value[namespace][field_name] = []
if condition not in self.value[namespace][field_name]:
self.value[namespace][field_name].append((exclude and EXCLUDE or INCLUDE, condition))
if commit:
self.save() |
def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
'''
init_kwds = {}
iprot.read_struct_begin()
while True:
ifield_name, ifield_type, _ifield_id = iprot.read_field_begin()
if ifield_type == 0: # STOP
break
elif ifield_name == 'full_size_url':
init_kwds['full_size_url'] = iprot.read_string()
elif ifield_name == 'mediaid':
init_kwds['mediaid'] = iprot.read_string()
elif ifield_name == 'objectid':
init_kwds['objectid'] = iprot.read_string()
elif ifield_name == 'src':
init_kwds['src'] = iprot.read_string()
elif ifield_name == 'thumbnail_url':
init_kwds['thumbnail_url'] = iprot.read_string()
elif ifield_name == 'title':
init_kwds['title'] = iprot.read_string()
elif ifield_name == 'type':
init_kwds['type'] = pastpy.gen.database.impl.online.online_database_object_detail_image_type.OnlineDatabaseObjectDetailImageType.value_of(iprot.read_string().strip().upper())
iprot.read_field_end()
iprot.read_struct_end()
return cls(**init_kwds) | Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage | Below is the the instruction that describes the task:
### Input:
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
### Response:
def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
'''
init_kwds = {}
iprot.read_struct_begin()
while True:
ifield_name, ifield_type, _ifield_id = iprot.read_field_begin()
if ifield_type == 0: # STOP
break
elif ifield_name == 'full_size_url':
init_kwds['full_size_url'] = iprot.read_string()
elif ifield_name == 'mediaid':
init_kwds['mediaid'] = iprot.read_string()
elif ifield_name == 'objectid':
init_kwds['objectid'] = iprot.read_string()
elif ifield_name == 'src':
init_kwds['src'] = iprot.read_string()
elif ifield_name == 'thumbnail_url':
init_kwds['thumbnail_url'] = iprot.read_string()
elif ifield_name == 'title':
init_kwds['title'] = iprot.read_string()
elif ifield_name == 'type':
init_kwds['type'] = pastpy.gen.database.impl.online.online_database_object_detail_image_type.OnlineDatabaseObjectDetailImageType.value_of(iprot.read_string().strip().upper())
iprot.read_field_end()
iprot.read_struct_end()
return cls(**init_kwds) |
def export_data(self, phases=[], filename=None, filetype='vtp'):
r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
The file name to use. If none is supplied then one will be
automatically generated based on the name of the project
containing the supplied Network, with the date and time appended.
filetype : string
Which file format to store the data. If a valid extension is
included in the ``filename``, this is ignored. Option are:
**'vtk'** : (default) The Visualization Toolkit format, used by
various softwares such as Paraview. This actually produces a 'vtp'
file. NOTE: This can be quite slow since all the data is written
to a simple text file. For large data simulations consider
'xdmf'.
**'csv'** : The comma-separated values format, which is easily
openned in any spreadsheet program. The column names represent
the property name, including the type and name of the object to
which they belonged, all separated by the pipe character.
**'xmf'** : The extensible data markup format, is a very efficient
format for large data sets. This actually results in the creation
of two files, the *xmf* file and an associated *hdf* file. The
*xmf* file contains instructions for looking into the *hdf* file
where the data is stored. Paraview opens the *xmf* format natively,
and is very fast.
**'mat'** : Matlab 'mat-file', which can be openned in Matlab.
Notes
-----
This is a helper function for the actual functions in the IO module.
For more control over the format of the output, and more information
about the format refer to ``openpnm.io``.
"""
project = self
network = self.network
if filename is None:
filename = project.name + '_' + time.strftime('%Y%b%d_%H%M%p')
# Infer filetype from extension on file name...if given
if '.' in filename:
exts = ['vtk', 'vtp', 'vtu', 'csv', 'xmf', 'xdmf', 'hdf', 'hdf5',
'h5', 'mat']
if filename.split('.')[-1] in exts:
filename, filetype = filename.rsplit('.', 1)
if filetype.lower() in ['vtk', 'vtp', 'vtu']:
openpnm.io.VTK.save(network=network, phases=phases,
filename=filename)
if filetype.lower() == 'csv':
openpnm.io.CSV.save(network=network, phases=phases,
filename=filename)
if filetype.lower() in ['xmf', 'xdmf']:
openpnm.io.XDMF.save(network=network, phases=phases,
filename=filename)
if filetype.lower() in ['hdf5', 'hdf', 'h5']:
f = openpnm.io.HDF5.to_hdf5(network=network, phases=phases,
filename=filename)
f.close()
if filetype.lower() == 'mat':
openpnm.io.MAT.save(network=network, phases=phases,
filename=filename) | r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
The file name to use. If none is supplied then one will be
automatically generated based on the name of the project
containing the supplied Network, with the date and time appended.
filetype : string
Which file format to store the data. If a valid extension is
included in the ``filename``, this is ignored. Option are:
**'vtk'** : (default) The Visualization Toolkit format, used by
various softwares such as Paraview. This actually produces a 'vtp'
file. NOTE: This can be quite slow since all the data is written
to a simple text file. For large data simulations consider
'xdmf'.
**'csv'** : The comma-separated values format, which is easily
openned in any spreadsheet program. The column names represent
the property name, including the type and name of the object to
which they belonged, all separated by the pipe character.
**'xmf'** : The extensible data markup format, is a very efficient
format for large data sets. This actually results in the creation
of two files, the *xmf* file and an associated *hdf* file. The
*xmf* file contains instructions for looking into the *hdf* file
where the data is stored. Paraview opens the *xmf* format natively,
and is very fast.
**'mat'** : Matlab 'mat-file', which can be openned in Matlab.
Notes
-----
This is a helper function for the actual functions in the IO module.
For more control over the format of the output, and more information
about the format refer to ``openpnm.io``. | Below is the the instruction that describes the task:
### Input:
r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
The file name to use. If none is supplied then one will be
automatically generated based on the name of the project
containing the supplied Network, with the date and time appended.
filetype : string
Which file format to store the data. If a valid extension is
included in the ``filename``, this is ignored. Option are:
**'vtk'** : (default) The Visualization Toolkit format, used by
various softwares such as Paraview. This actually produces a 'vtp'
file. NOTE: This can be quite slow since all the data is written
to a simple text file. For large data simulations consider
'xdmf'.
**'csv'** : The comma-separated values format, which is easily
openned in any spreadsheet program. The column names represent
the property name, including the type and name of the object to
which they belonged, all separated by the pipe character.
**'xmf'** : The extensible data markup format, is a very efficient
format for large data sets. This actually results in the creation
of two files, the *xmf* file and an associated *hdf* file. The
*xmf* file contains instructions for looking into the *hdf* file
where the data is stored. Paraview opens the *xmf* format natively,
and is very fast.
**'mat'** : Matlab 'mat-file', which can be openned in Matlab.
Notes
-----
This is a helper function for the actual functions in the IO module.
For more control over the format of the output, and more information
about the format refer to ``openpnm.io``.
### Response:
def export_data(self, phases=[], filename=None, filetype='vtp'):
r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
The file name to use. If none is supplied then one will be
automatically generated based on the name of the project
containing the supplied Network, with the date and time appended.
filetype : string
Which file format to store the data. If a valid extension is
included in the ``filename``, this is ignored. Option are:
**'vtk'** : (default) The Visualization Toolkit format, used by
various softwares such as Paraview. This actually produces a 'vtp'
file. NOTE: This can be quite slow since all the data is written
to a simple text file. For large data simulations consider
'xdmf'.
**'csv'** : The comma-separated values format, which is easily
openned in any spreadsheet program. The column names represent
the property name, including the type and name of the object to
which they belonged, all separated by the pipe character.
**'xmf'** : The extensible data markup format, is a very efficient
format for large data sets. This actually results in the creation
of two files, the *xmf* file and an associated *hdf* file. The
*xmf* file contains instructions for looking into the *hdf* file
where the data is stored. Paraview opens the *xmf* format natively,
and is very fast.
**'mat'** : Matlab 'mat-file', which can be openned in Matlab.
Notes
-----
This is a helper function for the actual functions in the IO module.
For more control over the format of the output, and more information
about the format refer to ``openpnm.io``.
"""
project = self
network = self.network
if filename is None:
filename = project.name + '_' + time.strftime('%Y%b%d_%H%M%p')
# Infer filetype from extension on file name...if given
if '.' in filename:
exts = ['vtk', 'vtp', 'vtu', 'csv', 'xmf', 'xdmf', 'hdf', 'hdf5',
'h5', 'mat']
if filename.split('.')[-1] in exts:
filename, filetype = filename.rsplit('.', 1)
if filetype.lower() in ['vtk', 'vtp', 'vtu']:
openpnm.io.VTK.save(network=network, phases=phases,
filename=filename)
if filetype.lower() == 'csv':
openpnm.io.CSV.save(network=network, phases=phases,
filename=filename)
if filetype.lower() in ['xmf', 'xdmf']:
openpnm.io.XDMF.save(network=network, phases=phases,
filename=filename)
if filetype.lower() in ['hdf5', 'hdf', 'h5']:
f = openpnm.io.HDF5.to_hdf5(network=network, phases=phases,
filename=filename)
f.close()
if filetype.lower() == 'mat':
openpnm.io.MAT.save(network=network, phases=phases,
filename=filename) |
def on_raw_update(
self=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: callable) -> Tuple[Handler, int]:
if isinstance(func, tuple):
func = func[0].callback
handler = pyrogram.RawUpdateHandler(func)
if isinstance(self, int):
return handler, group if self is None else group
if self is not None:
self.add_handler(handler, group)
return handler, group
return decorator | Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*):
The group identifier, defaults to 0. | Below is the the instruction that describes the task:
### Input:
Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*):
The group identifier, defaults to 0.
### Response:
def on_raw_update(
self=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
def decorator(func: callable) -> Tuple[Handler, int]:
if isinstance(func, tuple):
func = func[0].callback
handler = pyrogram.RawUpdateHandler(func)
if isinstance(self, int):
return handler, group if self is None else group
if self is not None:
self.add_handler(handler, group)
return handler, group
return decorator |
def set(self, value, mode=None):
"""Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is less that the current one.
:rtype: bool
"""
if mode == 'max':
func = uwsgi.metric_set_max
elif mode == 'min':
func = uwsgi.metric_set_min
else:
func = uwsgi.metric_set
return func(self.name, value) | Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is less that the current one.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is less that the current one.
:rtype: bool
### Response:
def set(self, value, mode=None):
"""Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is less that the current one.
:rtype: bool
"""
if mode == 'max':
func = uwsgi.metric_set_max
elif mode == 'min':
func = uwsgi.metric_set_min
else:
func = uwsgi.metric_set
return func(self.name, value) |
def deploy(self, args, **extra_args):
"""Deploy a docker container to a specific container ship (host)
:param args:
:type args:
"""
if not isinstance(args, argparse.Namespace):
raise TypeError(logger.error("args should of an instance of argparse.Namespace"))
# create new freight forwarder
freight_forwarder = FreightForwarder()
# create commercial invoice this is the contact given to freight forwarder to dispatch containers and images
commercial_invoice = freight_forwarder.commercial_invoice(
'deploy',
args.data_center,
args.environment,
args.service
)
# deploy containers.
bill_of_lading = freight_forwarder.deploy_containers(commercial_invoice, args.tag, args.env)
# pretty lame... Need to work on return values through to app to make them consistent.
exit_code = 0 if bill_of_lading else 1
if exit_code != 0:
exit(exit_code) | Deploy a docker container to a specific container ship (host)
:param args:
:type args: | Below is the the instruction that describes the task:
### Input:
Deploy a docker container to a specific container ship (host)
:param args:
:type args:
### Response:
def deploy(self, args, **extra_args):
"""Deploy a docker container to a specific container ship (host)
:param args:
:type args:
"""
if not isinstance(args, argparse.Namespace):
raise TypeError(logger.error("args should of an instance of argparse.Namespace"))
# create new freight forwarder
freight_forwarder = FreightForwarder()
# create commercial invoice this is the contact given to freight forwarder to dispatch containers and images
commercial_invoice = freight_forwarder.commercial_invoice(
'deploy',
args.data_center,
args.environment,
args.service
)
# deploy containers.
bill_of_lading = freight_forwarder.deploy_containers(commercial_invoice, args.tag, args.env)
# pretty lame... Need to work on return values through to app to make them consistent.
exit_code = 0 if bill_of_lading else 1
if exit_code != 0:
exit(exit_code) |
def _parse(self, text, i):
"""Recursive function to parse a single dictionary, list, or value."""
m = self.start_dict_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_dict(text, i)
m = self.start_list_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_list(text, i)
m = self.value_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
if hasattr(self.current_type, "read"):
reader = self.current_type()
# Give the escaped value to `read` to be symetrical with
# `plistValue` which handles the escaping itself.
value = reader.read(m.group(1))
return value, i
value = self._trim_value(m.group(1))
if self.current_type in (None, dict, OrderedDict):
self.current_type = self._guess_current_type(parsed, value)
if self.current_type == bool:
value = bool(int(value)) # bool(u'0') returns True
return value, i
value = self.current_type(value)
return value, i
m = self.hex_re.match(text, i)
if m:
from glyphsLib.types import BinaryData
parsed, value = m.group(0), m.group(1)
decoded = BinaryData.fromHex(value)
i += len(parsed)
return decoded, i
else:
self._fail("Unexpected content", text, i) | Recursive function to parse a single dictionary, list, or value. | Below is the the instruction that describes the task:
### Input:
Recursive function to parse a single dictionary, list, or value.
### Response:
def _parse(self, text, i):
"""Recursive function to parse a single dictionary, list, or value."""
m = self.start_dict_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_dict(text, i)
m = self.start_list_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_list(text, i)
m = self.value_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
if hasattr(self.current_type, "read"):
reader = self.current_type()
# Give the escaped value to `read` to be symetrical with
# `plistValue` which handles the escaping itself.
value = reader.read(m.group(1))
return value, i
value = self._trim_value(m.group(1))
if self.current_type in (None, dict, OrderedDict):
self.current_type = self._guess_current_type(parsed, value)
if self.current_type == bool:
value = bool(int(value)) # bool(u'0') returns True
return value, i
value = self.current_type(value)
return value, i
m = self.hex_re.match(text, i)
if m:
from glyphsLib.types import BinaryData
parsed, value = m.group(0), m.group(1)
decoded = BinaryData.fromHex(value)
i += len(parsed)
return decoded, i
else:
self._fail("Unexpected content", text, i) |
def _createSegment(cls, connections, lastUsedIterationForSegment, cell,
iteration, maxSegmentsPerCell):
"""
Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.
"""
# Enforce maxSegmentsPerCell.
while connections.numSegments(cell) >= maxSegmentsPerCell:
leastRecentlyUsedSegment = min(
connections.segmentsForCell(cell),
key=lambda segment : lastUsedIterationForSegment[segment.flatIdx])
connections.destroySegment(leastRecentlyUsedSegment)
# Create the segment.
segment = connections.createSegment(cell)
# Do TM-specific bookkeeping for the segment.
if segment.flatIdx == len(lastUsedIterationForSegment):
lastUsedIterationForSegment.append(iteration)
elif segment.flatIdx < len(lastUsedIterationForSegment):
# A flatIdx was recycled.
lastUsedIterationForSegment[segment.flatIdx] = iteration
else:
raise AssertionError(
"All segments should be created with the TM createSegment method.")
return segment | Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter. | Below is the the instruction that describes the task:
### Input:
Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.
### Response:
def _createSegment(cls, connections, lastUsedIterationForSegment, cell,
iteration, maxSegmentsPerCell):
"""
Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.
"""
# Enforce maxSegmentsPerCell.
while connections.numSegments(cell) >= maxSegmentsPerCell:
leastRecentlyUsedSegment = min(
connections.segmentsForCell(cell),
key=lambda segment : lastUsedIterationForSegment[segment.flatIdx])
connections.destroySegment(leastRecentlyUsedSegment)
# Create the segment.
segment = connections.createSegment(cell)
# Do TM-specific bookkeeping for the segment.
if segment.flatIdx == len(lastUsedIterationForSegment):
lastUsedIterationForSegment.append(iteration)
elif segment.flatIdx < len(lastUsedIterationForSegment):
# A flatIdx was recycled.
lastUsedIterationForSegment[segment.flatIdx] = iteration
else:
raise AssertionError(
"All segments should be created with the TM createSegment method.")
return segment |
def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
return False
except Exception as ex:
print('error launching app ' + str(app_path) + ' with params ' + str(params) + '\n' + str(ex))
return False | start an app | Below is the the instruction that describes the task:
### Input:
start an app
### Response:
def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
return False
except Exception as ex:
print('error launching app ' + str(app_path) + ' with params ' + str(params) + '\n' + str(ex))
return False |
def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification`
"""
sspairs = []
# some type checking
if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)):
raise TypeError("Unexpected subject value: {:s}".format(str(type(subject))))
if not isinstance(signature, (type(None), PGPSignature)):
raise TypeError("Unexpected signature value: {:s}".format(str(type(signature))))
def _filter_sigs(sigs):
_ids = {self.fingerprint.keyid} | set(self.subkeys)
return [ sig for sig in sigs if sig.signer in _ids ]
# collect signature(s)
if signature is None:
if isinstance(subject, PGPMessage):
sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ]
if isinstance(subject, (PGPUID, PGPKey)):
sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ]
if isinstance(subject, PGPKey):
# user ids
sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ]
# user attributes
sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ]
# subkey binding signatures
sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ]
elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys):
sspairs += [(signature, subject)]
if len(sspairs) == 0:
raise PGPError("No signatures to verify")
# finally, start verifying signatures
sigv = SignatureVerification()
for sig, subj in sspairs:
if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys:
warnings.warn("Signature was signed with this key's subkey: {:s}. "
"Verifying with subkey...".format(sig.signer),
stacklevel=2)
sigv &= self.subkeys[sig.signer].verify(subj, sig)
else:
verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)())
if verified is NotImplemented:
raise NotImplementedError(sig.key_algorithm)
sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified)
return sigv | Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification` | Below is the the instruction that describes the task:
### Input:
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification`
### Response:
def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification`
"""
sspairs = []
# some type checking
if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)):
raise TypeError("Unexpected subject value: {:s}".format(str(type(subject))))
if not isinstance(signature, (type(None), PGPSignature)):
raise TypeError("Unexpected signature value: {:s}".format(str(type(signature))))
def _filter_sigs(sigs):
_ids = {self.fingerprint.keyid} | set(self.subkeys)
return [ sig for sig in sigs if sig.signer in _ids ]
# collect signature(s)
if signature is None:
if isinstance(subject, PGPMessage):
sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ]
if isinstance(subject, (PGPUID, PGPKey)):
sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ]
if isinstance(subject, PGPKey):
# user ids
sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ]
# user attributes
sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ]
# subkey binding signatures
sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ]
elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys):
sspairs += [(signature, subject)]
if len(sspairs) == 0:
raise PGPError("No signatures to verify")
# finally, start verifying signatures
sigv = SignatureVerification()
for sig, subj in sspairs:
if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys:
warnings.warn("Signature was signed with this key's subkey: {:s}. "
"Verifying with subkey...".format(sig.signer),
stacklevel=2)
sigv &= self.subkeys[sig.signer].verify(subj, sig)
else:
verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)())
if verified is NotImplemented:
raise NotImplementedError(sig.key_algorithm)
sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified)
return sigv |
def moves_from_games(self, start_game, end_game, moves, shuffle,
column_family, column):
"""Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how many moves should be sampled
from those N games.
column_family: name of the column family containing move examples.
column: name of the column containing move examples.
shuffle: if True, shuffle the selected move examples.
Returns:
A dataset containing no more than `moves` examples, sampled
randomly from the last `n` games in the table.
"""
start_row = ROW_PREFIX.format(start_game)
end_row = ROW_PREFIX.format(end_game)
# NOTE: Choose a probability high enough to guarantee at least the
# required number of moves, by using a slightly lower estimate
# of the total moves, then trimming the result.
total_moves = self.count_moves_in_game_range(start_game, end_game)
probability = moves / (total_moves * 0.99)
utils.dbg('Row range: %s - %s; total moves: %d; probability %.3f; moves %d' % (
start_row, end_row, total_moves, probability, moves))
ds = self.tf_table.parallel_scan_range(start_row, end_row,
probability=probability,
columns=[(column_family, column)])
if shuffle:
utils.dbg('Doing a complete shuffle of %d moves' % moves)
ds = ds.shuffle(moves)
ds = ds.take(moves)
return ds | Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how many moves should be sampled
from those N games.
column_family: name of the column family containing move examples.
column: name of the column containing move examples.
shuffle: if True, shuffle the selected move examples.
Returns:
A dataset containing no more than `moves` examples, sampled
randomly from the last `n` games in the table. | Below is the the instruction that describes the task:
### Input:
Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how many moves should be sampled
from those N games.
column_family: name of the column family containing move examples.
column: name of the column containing move examples.
shuffle: if True, shuffle the selected move examples.
Returns:
A dataset containing no more than `moves` examples, sampled
randomly from the last `n` games in the table.
### Response:
def moves_from_games(self, start_game, end_game, moves, shuffle,
column_family, column):
"""Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how many moves should be sampled
from those N games.
column_family: name of the column family containing move examples.
column: name of the column containing move examples.
shuffle: if True, shuffle the selected move examples.
Returns:
A dataset containing no more than `moves` examples, sampled
randomly from the last `n` games in the table.
"""
start_row = ROW_PREFIX.format(start_game)
end_row = ROW_PREFIX.format(end_game)
# NOTE: Choose a probability high enough to guarantee at least the
# required number of moves, by using a slightly lower estimate
# of the total moves, then trimming the result.
total_moves = self.count_moves_in_game_range(start_game, end_game)
probability = moves / (total_moves * 0.99)
utils.dbg('Row range: %s - %s; total moves: %d; probability %.3f; moves %d' % (
start_row, end_row, total_moves, probability, moves))
ds = self.tf_table.parallel_scan_range(start_row, end_row,
probability=probability,
columns=[(column_family, column)])
if shuffle:
utils.dbg('Doing a complete shuffle of %d moves' % moves)
ds = ds.shuffle(moves)
ds = ds.take(moves)
return ds |
def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
def scan_list(ITEM, TERMINATOR, line, p, groups, item_name):
items = []
while not TERMINATOR(line, p):
if CONTINUE(line, p):
try:
line = next(lines)
p = 0
except StopIteration:
msg = "\\ must not appear on the last nonblank line"
raise RequirementParseError(msg)
match = ITEM(line, p)
if not match:
msg = "Expected " + item_name + " in"
raise RequirementParseError(msg, line, "at", line[p:])
items.append(match.group(*groups))
p = match.end()
match = COMMA(line, p)
if match:
# skip the comma
p = match.end()
elif not TERMINATOR(line, p):
msg = "Expected ',' or end-of-list in"
raise RequirementParseError(msg, line, "at", line[p:])
match = TERMINATOR(line, p)
# skip the terminator, if any
if match:
p = match.end()
return line, p, items
for line in lines:
match = DISTRO(line)
if not match:
raise RequirementParseError("Missing distribution spec", line)
project_name = match.group(1)
p = match.end()
extras = []
match = OBRACKET(line, p)
if match:
p = match.end()
line, p, extras = scan_list(
DISTRO, CBRACKET, line, p, (1,), "'extra' name"
)
line, p, specs = scan_list(VERSION, LINE_END, line, p, (1, 2),
"version spec")
specs = [(op, val) for op, val in specs]
yield Requirement(project_name, specs, extras) | Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof. | Below is the the instruction that describes the task:
### Input:
Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
### Response:
def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
def scan_list(ITEM, TERMINATOR, line, p, groups, item_name):
items = []
while not TERMINATOR(line, p):
if CONTINUE(line, p):
try:
line = next(lines)
p = 0
except StopIteration:
msg = "\\ must not appear on the last nonblank line"
raise RequirementParseError(msg)
match = ITEM(line, p)
if not match:
msg = "Expected " + item_name + " in"
raise RequirementParseError(msg, line, "at", line[p:])
items.append(match.group(*groups))
p = match.end()
match = COMMA(line, p)
if match:
# skip the comma
p = match.end()
elif not TERMINATOR(line, p):
msg = "Expected ',' or end-of-list in"
raise RequirementParseError(msg, line, "at", line[p:])
match = TERMINATOR(line, p)
# skip the terminator, if any
if match:
p = match.end()
return line, p, items
for line in lines:
match = DISTRO(line)
if not match:
raise RequirementParseError("Missing distribution spec", line)
project_name = match.group(1)
p = match.end()
extras = []
match = OBRACKET(line, p)
if match:
p = match.end()
line, p, extras = scan_list(
DISTRO, CBRACKET, line, p, (1,), "'extra' name"
)
line, p, specs = scan_list(VERSION, LINE_END, line, p, (1, 2),
"version spec")
specs = [(op, val) for op, val in specs]
yield Requirement(project_name, specs, extras) |
def residual_histogram(df, col_true, col_pred=None):
"""
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'prediction_score' by default.
:type col_pred: str
:return: histograms for every columns, containing histograms and bins.
"""
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['hist'] | Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'prediction_score' by default.
:type col_pred: str
:return: histograms for every columns, containing histograms and bins. | Below is the the instruction that describes the task:
### Input:
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'prediction_score' by default.
:type col_pred: str
:return: histograms for every columns, containing histograms and bins.
### Response:
def residual_histogram(df, col_true, col_pred=None):
"""
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'prediction_score' by default.
:type col_pred: str
:return: histograms for every columns, containing histograms and bins.
"""
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['hist'] |
def rrmdir(directory):
"""
Recursivly delete a directory
:param directory: directory to remove
"""
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(directory) | Recursivly delete a directory
:param directory: directory to remove | Below is the the instruction that describes the task:
### Input:
Recursivly delete a directory
:param directory: directory to remove
### Response:
def rrmdir(directory):
"""
Recursivly delete a directory
:param directory: directory to remove
"""
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(directory) |
def create_attach_volumes(name, kwargs, call=None):
'''
.. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, either pd-standard or pd-ssd. Optional, defaults to pd-standard.
image
An image to use for this new disk. Optional.
snapshot
A snapshot to use for this new disk. Optional.
auto_delete
An option(bool) to keep or remove the disk upon instance deletion.
Optional, defaults to False.
Volumes are attached in the order in which they are given, thus on a new
node the first volume will be /dev/sdb, the second /dev/sdc, and so on.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
volumes = literal_eval(kwargs['volumes'])
node = kwargs['node']
conn = get_conn()
node_data = _expand_node(conn.ex_get_node(node))
letter = ord('a') - 1
for idx, volume in enumerate(volumes):
volume_name = '{0}-sd{1}'.format(name, chr(letter + 2 + idx))
volume_dict = {
'disk_name': volume_name,
'location': node_data['extra']['zone']['name'],
'size': volume['size'],
'type': volume.get('type', 'pd-standard'),
'image': volume.get('image', None),
'snapshot': volume.get('snapshot', None),
'auto_delete': volume.get('auto_delete', False)
}
create_disk(volume_dict, 'function')
attach_disk(name, volume_dict, 'action') | .. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, either pd-standard or pd-ssd. Optional, defaults to pd-standard.
image
An image to use for this new disk. Optional.
snapshot
A snapshot to use for this new disk. Optional.
auto_delete
An option(bool) to keep or remove the disk upon instance deletion.
Optional, defaults to False.
Volumes are attached in the order in which they are given, thus on a new
node the first volume will be /dev/sdb, the second /dev/sdc, and so on. | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, either pd-standard or pd-ssd. Optional, defaults to pd-standard.
image
An image to use for this new disk. Optional.
snapshot
A snapshot to use for this new disk. Optional.
auto_delete
An option(bool) to keep or remove the disk upon instance deletion.
Optional, defaults to False.
Volumes are attached in the order in which they are given, thus on a new
node the first volume will be /dev/sdb, the second /dev/sdc, and so on.
### Response:
def create_attach_volumes(name, kwargs, call=None):
'''
.. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, either pd-standard or pd-ssd. Optional, defaults to pd-standard.
image
An image to use for this new disk. Optional.
snapshot
A snapshot to use for this new disk. Optional.
auto_delete
An option(bool) to keep or remove the disk upon instance deletion.
Optional, defaults to False.
Volumes are attached in the order in which they are given, thus on a new
node the first volume will be /dev/sdb, the second /dev/sdc, and so on.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
volumes = literal_eval(kwargs['volumes'])
node = kwargs['node']
conn = get_conn()
node_data = _expand_node(conn.ex_get_node(node))
letter = ord('a') - 1
for idx, volume in enumerate(volumes):
volume_name = '{0}-sd{1}'.format(name, chr(letter + 2 + idx))
volume_dict = {
'disk_name': volume_name,
'location': node_data['extra']['zone']['name'],
'size': volume['size'],
'type': volume.get('type', 'pd-standard'),
'image': volume.get('image', None),
'snapshot': volume.get('snapshot', None),
'auto_delete': volume.get('auto_delete', False)
}
create_disk(volume_dict, 'function')
attach_disk(name, volume_dict, 'action') |
def _get_class_repo(self, namespace):
"""
Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the class repository does not contain the namespace yet, it is
added.
Parameters:
namespace(:term:`string`): Namespace name. Must not be `None`.
Returns:
dict of CIMClass: Class repository.
Raises:
:exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does
not exist.
"""
self._validate_namespace(namespace)
if namespace not in self.classes:
self.classes[namespace] = NocaseDict()
return self.classes[namespace] | Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the class repository does not contain the namespace yet, it is
added.
Parameters:
namespace(:term:`string`): Namespace name. Must not be `None`.
Returns:
dict of CIMClass: Class repository.
Raises:
:exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does
not exist. | Below is the the instruction that describes the task:
### Input:
Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the class repository does not contain the namespace yet, it is
added.
Parameters:
namespace(:term:`string`): Namespace name. Must not be `None`.
Returns:
dict of CIMClass: Class repository.
Raises:
:exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does
not exist.
### Response:
def _get_class_repo(self, namespace):
"""
Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the class repository does not contain the namespace yet, it is
added.
Parameters:
namespace(:term:`string`): Namespace name. Must not be `None`.
Returns:
dict of CIMClass: Class repository.
Raises:
:exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does
not exist.
"""
self._validate_namespace(namespace)
if namespace not in self.classes:
self.classes[namespace] = NocaseDict()
return self.classes[namespace] |
def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print(row, end=' ')
else:
print(row)
return None | Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None | Below is the the instruction that describes the task:
### Input:
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
### Response:
def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print(row, end=' ')
else:
print(row)
return None |
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) | Load a :class:`Item` from a dictionary ot string (that will be parsed
as json) | Below is the the instruction that describes the task:
### Input:
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
### Response:
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) |
def make_fuzzy(word, max=1):
"""Naive neighborhoods algo."""
# inversions
neighbors = []
for i in range(0, len(word) - 1):
neighbor = list(word)
neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i]
neighbors.append(''.join(neighbor))
# substitutions
for letter in string.ascii_lowercase:
for i in range(0, len(word)):
neighbor = list(word)
if letter != neighbor[i]:
neighbor[i] = letter
neighbors.append(''.join(neighbor))
# insertions
for letter in string.ascii_lowercase:
for i in range(0, len(word) + 1):
neighbor = list(word)
neighbor.insert(i, letter)
neighbors.append(''.join(neighbor))
if len(word) > 3:
# removal
for i in range(0, len(word)):
neighbor = list(word)
del neighbor[i]
neighbors.append(''.join(neighbor))
return neighbors | Naive neighborhoods algo. | Below is the the instruction that describes the task:
### Input:
Naive neighborhoods algo.
### Response:
def make_fuzzy(word, max=1):
"""Naive neighborhoods algo."""
# inversions
neighbors = []
for i in range(0, len(word) - 1):
neighbor = list(word)
neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i]
neighbors.append(''.join(neighbor))
# substitutions
for letter in string.ascii_lowercase:
for i in range(0, len(word)):
neighbor = list(word)
if letter != neighbor[i]:
neighbor[i] = letter
neighbors.append(''.join(neighbor))
# insertions
for letter in string.ascii_lowercase:
for i in range(0, len(word) + 1):
neighbor = list(word)
neighbor.insert(i, letter)
neighbors.append(''.join(neighbor))
if len(word) > 3:
# removal
for i in range(0, len(word)):
neighbor = list(word)
del neighbor[i]
neighbors.append(''.join(neighbor))
return neighbors |
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed.
"""
# Since this header value is really generic it is hard not to use filename
# as an indicator too.
# TODO: Rethink this and potentially make a better test.
filename = parser_mediator.GetFilename()
if not filename.startswith('INFO2'):
return
file_header_map = self._GetDataTypeMap('recycler_info2_file_header')
try:
file_header, _ = self._ReadStructureFromFileObject(
file_object, 0, file_header_map)
except (ValueError, errors.ParseError) as exception:
raise errors.UnableToParseFile((
'Unable to parse Windows Recycler INFO2 file header with '
'error: {0!s}').format(exception))
if file_header.unknown1 != 5:
parser_mediator.ProduceExtractionWarning('unsupported format signature.')
return
file_entry_size = file_header.file_entry_size
if file_entry_size not in (280, 800):
parser_mediator.ProduceExtractionWarning(
'unsupported file entry size: {0:d}'.format(file_entry_size))
return
file_offset = file_object.get_offset()
file_size = file_object.get_size()
while file_offset < file_size:
self._ParseInfo2Record(
parser_mediator, file_object, file_offset, file_entry_size)
file_offset += file_entry_size | Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed. | Below is the the instruction that describes the task:
### Input:
Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed.
### Response:
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed.
"""
# Since this header value is really generic it is hard not to use filename
# as an indicator too.
# TODO: Rethink this and potentially make a better test.
filename = parser_mediator.GetFilename()
if not filename.startswith('INFO2'):
return
file_header_map = self._GetDataTypeMap('recycler_info2_file_header')
try:
file_header, _ = self._ReadStructureFromFileObject(
file_object, 0, file_header_map)
except (ValueError, errors.ParseError) as exception:
raise errors.UnableToParseFile((
'Unable to parse Windows Recycler INFO2 file header with '
'error: {0!s}').format(exception))
if file_header.unknown1 != 5:
parser_mediator.ProduceExtractionWarning('unsupported format signature.')
return
file_entry_size = file_header.file_entry_size
if file_entry_size not in (280, 800):
parser_mediator.ProduceExtractionWarning(
'unsupported file entry size: {0:d}'.format(file_entry_size))
return
file_offset = file_object.get_offset()
file_size = file_object.get_size()
while file_offset < file_size:
self._ParseInfo2Record(
parser_mediator, file_object, file_offset, file_entry_size)
file_offset += file_entry_size |
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz.
"""
tmpdir = tempfile.mkdtemp()
zonedir = os.path.join(tmpdir, "zoneinfo")
moduledir = os.path.dirname(__file__)
try:
with tar_open(filename) as tf:
for name in zonegroups:
tf.extract(name, tmpdir)
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
try:
check_call(["zic", "-d", zonedir] + filepaths)
except OSError as e:
_print_on_nosuchfile(e)
raise
# write metadata file
with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
json.dump(metadata, f, indent=4, sort_keys=True)
target = os.path.join(moduledir, ZONEFILENAME)
with tar_open(target, "w:%s" % format) as tf:
for entry in os.listdir(zonedir):
entrypath = os.path.join(zonedir, entry)
tf.add(entrypath, entry)
finally:
shutil.rmtree(tmpdir) | Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz. | Below is the the instruction that describes the task:
### Input:
Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz.
### Response:
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz.
"""
tmpdir = tempfile.mkdtemp()
zonedir = os.path.join(tmpdir, "zoneinfo")
moduledir = os.path.dirname(__file__)
try:
with tar_open(filename) as tf:
for name in zonegroups:
tf.extract(name, tmpdir)
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
try:
check_call(["zic", "-d", zonedir] + filepaths)
except OSError as e:
_print_on_nosuchfile(e)
raise
# write metadata file
with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
json.dump(metadata, f, indent=4, sort_keys=True)
target = os.path.join(moduledir, ZONEFILENAME)
with tar_open(target, "w:%s" % format) as tf:
for entry in os.listdir(zonedir):
entrypath = os.path.join(zonedir, entry)
tf.add(entrypath, entry)
finally:
shutil.rmtree(tmpdir) |
def ajRadical(self, i, r=None):
""" Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical
"""
if r:
self._radicaux[i].append(r) | Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical | Below is the the instruction that describes the task:
### Input:
Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical
### Response:
def ajRadical(self, i, r=None):
""" Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical
"""
if r:
self._radicaux[i].append(r) |
def new(self, repo_type, name=None, make_default=False,
repository_class=None, aggregate_class=None,
configuration=None):
"""
Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
is passed as a repository name, the type string is used as the name;
if no name is passed, a unique name is created automatically.
"""
if name == REPOSITORY_DOMAINS.ROOT:
# Unless explicitly configured differently, all root repositories
# join the transaction.
join_transaction = True
autocommit = False
name = repo_type
else:
join_transaction = False
if name is None:
name = "%s%d" % (repo_type, next(self.__repo_id_gen))
# The system repository is special in that its repository
# should not join the transaction but still commit all changes.
autocommit = name == REPOSITORY_DOMAINS.SYSTEM
if repository_class is None:
reg = get_current_registry()
repository_class = reg.queryUtility(IRepository, name=repo_type)
if repository_class is None:
raise ValueError('Unknown repository type "%s".' % repo_type)
repo = repository_class(name,
aggregate_class,
join_transaction=join_transaction,
autocommit=autocommit)
if not configuration is None:
repo.configure(**configuration)
if make_default:
self.__default_repo = repo
return repo | Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
is passed as a repository name, the type string is used as the name;
if no name is passed, a unique name is created automatically. | Below is the the instruction that describes the task:
### Input:
Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
is passed as a repository name, the type string is used as the name;
if no name is passed, a unique name is created automatically.
### Response:
def new(self, repo_type, name=None, make_default=False,
repository_class=None, aggregate_class=None,
configuration=None):
"""
Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
is passed as a repository name, the type string is used as the name;
if no name is passed, a unique name is created automatically.
"""
if name == REPOSITORY_DOMAINS.ROOT:
# Unless explicitly configured differently, all root repositories
# join the transaction.
join_transaction = True
autocommit = False
name = repo_type
else:
join_transaction = False
if name is None:
name = "%s%d" % (repo_type, next(self.__repo_id_gen))
# The system repository is special in that its repository
# should not join the transaction but still commit all changes.
autocommit = name == REPOSITORY_DOMAINS.SYSTEM
if repository_class is None:
reg = get_current_registry()
repository_class = reg.queryUtility(IRepository, name=repo_type)
if repository_class is None:
raise ValueError('Unknown repository type "%s".' % repo_type)
repo = repository_class(name,
aggregate_class,
join_transaction=join_transaction,
autocommit=autocommit)
if not configuration is None:
repo.configure(**configuration)
if make_default:
self.__default_repo = repo
return repo |
def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return ((username in self.authorized_users[subject]) or
self.group_access_manager.MemberOfAuthorizedGroup(
username, subject))
# In case the subject is not found, the safest thing to do is to raise.
# It's up to the users of this class to handle this exception and
# grant/not grant permissions to the user in question.
raise InvalidSubject("Subject %s was not found." % subject) | Checks if a given user has access to a given subject. | Below is the the instruction that describes the task:
### Input:
Checks if a given user has access to a given subject.
### Response:
def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return ((username in self.authorized_users[subject]) or
self.group_access_manager.MemberOfAuthorizedGroup(
username, subject))
# In case the subject is not found, the safest thing to do is to raise.
# It's up to the users of this class to handle this exception and
# grant/not grant permissions to the user in question.
raise InvalidSubject("Subject %s was not found." % subject) |
def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found."""
# Build a version of the pattern with a non-capturing group around it.
# This is needed to get m.end() to correctly report the size of the
# matched expression (as per the final doctest above).
grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags)
m = grouped_pattern.match(string)
if m and m.end() < len(string):
# Incomplete match (which should never happen because of the $ at the
# end of the regexp), treat as failure.
m = None # pragma no cover
return m | Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found. | Below is the the instruction that describes the task:
### Input:
Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found.
### Response:
def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found."""
# Build a version of the pattern with a non-capturing group around it.
# This is needed to get m.end() to correctly report the size of the
# matched expression (as per the final doctest above).
grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags)
m = grouped_pattern.match(string)
if m and m.end() < len(string):
# Incomplete match (which should never happen because of the $ at the
# end of the regexp), treat as failure.
m = None # pragma no cover
return m |
def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs):
'''wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube`
'''
name = name or cube
config = copy(self.config) if copy_config else {}
config_file = self.config_file
container = type(self.container)
container_config = copy(self.container_config)
proxy = str(type(self.proxy))
return get_cube(cube=cube, init=init, name=name, config=config,
config_file=config_file, container=container,
container_config=container_config,
proxy=proxy, proxy_config=self.proxy_config, **kwargs) | wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube` | Below is the the instruction that describes the task:
### Input:
wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube`
### Response:
def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs):
'''wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube`
'''
name = name or cube
config = copy(self.config) if copy_config else {}
config_file = self.config_file
container = type(self.container)
container_config = copy(self.container_config)
proxy = str(type(self.proxy))
return get_cube(cube=cube, init=init, name=name, config=config,
config_file=config_file, container=container,
container_config=container_config,
proxy=proxy, proxy_config=self.proxy_config, **kwargs) |
def remove_rules_with_epsilon(grammar, inplace=False):
# type: (Grammar, bool) -> Grammar
"""
Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules.
"""
# copy if required
if inplace is False:
grammar = copy(grammar)
# find nonterminals rewritable to epsilon
rewritable = find_nonterminals_rewritable_to_epsilon(grammar) # type: Dict[Type[Nonterminal], Type[Rule]]
# create queue from rules to iterate over
rules = Queue()
for r in grammar.rules:
rules.put(r)
# iterate thought rules
while not rules.empty():
rule = rules.get()
right = rule.right
# if the rule rewrite to epsilon we can safely delete it
if right == [EPSILON]:
# unless it rewrites from the start symbol
if rule.fromSymbol != grammar.start:
grammar.rules.discard(rule)
# continue IS executed, but due optimization line is marked as missed.
continue # pragma: no cover
# iterate over the right side
for rule_index in range(len(right)):
symbol = right[rule_index]
# if symbol is rewritable, generate new rule without that symbol
if symbol in rewritable:
new_rule = _create_rule(rule, rule_index, rewritable)
grammar.rules.add(new_rule)
rules.put(new_rule) # in case there are more rewritable symbols
return grammar | Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules. | Below is the the instruction that describes the task:
### Input:
Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules.
### Response:
def remove_rules_with_epsilon(grammar, inplace=False):
# type: (Grammar, bool) -> Grammar
"""
Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules.
"""
# copy if required
if inplace is False:
grammar = copy(grammar)
# find nonterminals rewritable to epsilon
rewritable = find_nonterminals_rewritable_to_epsilon(grammar) # type: Dict[Type[Nonterminal], Type[Rule]]
# create queue from rules to iterate over
rules = Queue()
for r in grammar.rules:
rules.put(r)
# iterate thought rules
while not rules.empty():
rule = rules.get()
right = rule.right
# if the rule rewrite to epsilon we can safely delete it
if right == [EPSILON]:
# unless it rewrites from the start symbol
if rule.fromSymbol != grammar.start:
grammar.rules.discard(rule)
# continue IS executed, but due optimization line is marked as missed.
continue # pragma: no cover
# iterate over the right side
for rule_index in range(len(right)):
symbol = right[rule_index]
# if symbol is rewritable, generate new rule without that symbol
if symbol in rewritable:
new_rule = _create_rule(rule, rule_index, rewritable)
grammar.rules.add(new_rule)
rules.put(new_rule) # in case there are more rewritable symbols
return grammar |
def ge(self, event_property, value):
"""A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500)
"""
c = self.copy()
c.filters.append(filters.GE(event_property, value))
return c | A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500) | Below is the the instruction that describes the task:
### Input:
A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500)
### Response:
def ge(self, event_property, value):
"""A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500)
"""
c = self.copy()
c.filters.append(filters.GE(event_property, value))
return c |
def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
elif ttype not in T.Keyword: # if normal token return
return 0
# Everything after here is ttype = T.Keyword
# Also to note, once entered an If statement you are done and basically
# returning
unified = value.upper()
# three keywords begin with CREATE, but only one of them is DDL
# DDL Create though can contain more words such as "or replace"
if ttype is T.Keyword.DDL and unified.startswith('CREATE'):
self._is_create = True
return 0
# can have nested declare inside of being...
if unified == 'DECLARE' and self._is_create and self._begin_depth == 0:
self._in_declare = True
return 1
if unified == 'BEGIN':
self._begin_depth += 1
if self._is_create:
# FIXME(andi): This makes no sense.
return 1
return 0
# Should this respect a preceding BEGIN?
# In CASE ... WHEN ... END this results in a split level -1.
# Would having multiple CASE WHEN END and a Assignment Operator
# cause the statement to cut off prematurely?
if unified == 'END':
self._begin_depth = max(0, self._begin_depth - 1)
return -1
if (unified in ('IF', 'FOR', 'WHILE')
and self._is_create and self._begin_depth > 0):
return 1
if unified in ('END IF', 'END FOR', 'END WHILE'):
return -1
# Default
return 0 | Get the new split level (increase, decrease or remain equal) | Below is the the instruction that describes the task:
### Input:
Get the new split level (increase, decrease or remain equal)
### Response:
def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
elif ttype not in T.Keyword: # if normal token return
return 0
# Everything after here is ttype = T.Keyword
# Also to note, once entered an If statement you are done and basically
# returning
unified = value.upper()
# three keywords begin with CREATE, but only one of them is DDL
# DDL Create though can contain more words such as "or replace"
if ttype is T.Keyword.DDL and unified.startswith('CREATE'):
self._is_create = True
return 0
# can have nested declare inside of being...
if unified == 'DECLARE' and self._is_create and self._begin_depth == 0:
self._in_declare = True
return 1
if unified == 'BEGIN':
self._begin_depth += 1
if self._is_create:
# FIXME(andi): This makes no sense.
return 1
return 0
# Should this respect a preceding BEGIN?
# In CASE ... WHEN ... END this results in a split level -1.
# Would having multiple CASE WHEN END and a Assignment Operator
# cause the statement to cut off prematurely?
if unified == 'END':
self._begin_depth = max(0, self._begin_depth - 1)
return -1
if (unified in ('IF', 'FOR', 'WHILE')
and self._is_create and self._begin_depth > 0):
return 1
if unified in ('END IF', 'END FOR', 'END WHILE'):
return -1
# Default
return 0 |
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):
"""Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere.
"""
phalf = np.zeros((arr.shape[0] + 1, arr.shape[1], arr.shape[2]))
phalf[0] = val_toa
phalf[-1] = val_sfc
phalf[1:-1] = 0.5*(arr[:-1] + arr[1:])
return phalf | Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere. | Below is the the instruction that describes the task:
### Input:
Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere.
### Response:
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):
"""Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere.
"""
phalf = np.zeros((arr.shape[0] + 1, arr.shape[1], arr.shape[2]))
phalf[0] = val_toa
phalf[-1] = val_sfc
phalf[1:-1] = 0.5*(arr[:-1] + arr[1:])
return phalf |
def killCells(self, percent = 0.05):
"""
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
"""
if self.zombiePermutation is None:
self.zombiePermutation = numpy.random.permutation(self.numberOfCells())
self.numDead = int(round(percent * self.numberOfCells()))
if self.numDead > 0:
self.deadCells = set(self.zombiePermutation[0:self.numDead])
else:
self.deadCells = set()
print "Total number of dead cells=",len(self.deadCells)
numSegmentDeleted = 0
for cellIdx in self.deadCells:
# Destroy segments. self.destroySegment() takes care of deleting synapses
for segment in self.connections.segmentsForCell(cellIdx):
self.connections.destroySegment(segment)
numSegmentDeleted += 1
print "Total number of segments removed=", numSegmentDeleted
# Strip out segments for dead cells
self.activeSegments = [s for s in self.activeSegments if
s.cell not in self.deadCells]
self.matchingSegments = [s for s in self.matchingSegments if
s.cell not in self.deadCells] | Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead. | Below is the the instruction that describes the task:
### Input:
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
### Response:
def killCells(self, percent = 0.05):
"""
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
"""
if self.zombiePermutation is None:
self.zombiePermutation = numpy.random.permutation(self.numberOfCells())
self.numDead = int(round(percent * self.numberOfCells()))
if self.numDead > 0:
self.deadCells = set(self.zombiePermutation[0:self.numDead])
else:
self.deadCells = set()
print "Total number of dead cells=",len(self.deadCells)
numSegmentDeleted = 0
for cellIdx in self.deadCells:
# Destroy segments. self.destroySegment() takes care of deleting synapses
for segment in self.connections.segmentsForCell(cellIdx):
self.connections.destroySegment(segment)
numSegmentDeleted += 1
print "Total number of segments removed=", numSegmentDeleted
# Strip out segments for dead cells
self.activeSegments = [s for s in self.activeSegments if
s.cell not in self.deadCells]
self.matchingSegments = [s for s in self.matchingSegments if
s.cell not in self.deadCells] |
def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
"""
result = None
r = parse_requirement(requirement)
if r is None:
raise DistlibException('Not a valid requirement: %r' % requirement)
scheme = get_scheme(self.scheme)
self.matcher = matcher = scheme.matcher(r.requirement)
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
versions = self.get_project(r.name)
if len(versions) > 2: # urls and digests keys are present
# sometimes, versions are invalid
slist = []
vcls = matcher.version_class
for k in versions:
if k in ('urls', 'digests'):
continue
try:
if not matcher.match(k):
logger.debug('%s did not match %r', matcher, k)
else:
if prereleases or not vcls(k).is_prerelease:
slist.append(k)
else:
logger.debug('skipping pre-release '
'version %s of %s', k, matcher.name)
except Exception: # pragma: no cover
logger.warning('error matching %s with %r', matcher, k)
pass # slist.append(k)
if len(slist) > 1:
slist = sorted(slist, key=scheme.key)
if slist:
logger.debug('sorted list: %s', slist)
version = slist[-1]
result = versions[version]
if result:
if r.extras:
result.extras = r.extras
result.download_urls = versions.get('urls', {}).get(version, set())
d = {}
sd = versions.get('digests', {})
for url in result.download_urls:
if url in sd:
d[url] = sd[url]
result.digests = d
self.matcher = None
return result | Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located. | Below is the the instruction that describes the task:
### Input:
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
### Response:
def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
"""
result = None
r = parse_requirement(requirement)
if r is None:
raise DistlibException('Not a valid requirement: %r' % requirement)
scheme = get_scheme(self.scheme)
self.matcher = matcher = scheme.matcher(r.requirement)
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
versions = self.get_project(r.name)
if len(versions) > 2: # urls and digests keys are present
# sometimes, versions are invalid
slist = []
vcls = matcher.version_class
for k in versions:
if k in ('urls', 'digests'):
continue
try:
if not matcher.match(k):
logger.debug('%s did not match %r', matcher, k)
else:
if prereleases or not vcls(k).is_prerelease:
slist.append(k)
else:
logger.debug('skipping pre-release '
'version %s of %s', k, matcher.name)
except Exception: # pragma: no cover
logger.warning('error matching %s with %r', matcher, k)
pass # slist.append(k)
if len(slist) > 1:
slist = sorted(slist, key=scheme.key)
if slist:
logger.debug('sorted list: %s', slist)
version = slist[-1]
result = versions[version]
if result:
if r.extras:
result.extras = r.extras
result.download_urls = versions.get('urls', {}).get(version, set())
d = {}
sd = versions.get('digests', {})
for url in result.download_urls:
if url in sd:
d[url] = sd[url]
result.digests = d
self.matcher = None
return result |
def transformer_moe_2k():
"""Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)
* Layer 1: a - a - sepm
* Layer 2: a - a - moe (mixture of expert layers in the middle)
* Layer 3: a - a - sepm
* Layer 4: a - a - sepm
Returns:
hparams
"""
hparams = transformer_moe_8k()
hparams.batch_size = 2048
hparams.default_ff = "sep"
# hparams.layer_types contains the network architecture:
encoder_archi = "a/a/a/a/a"
decoder_archi = "a-sepm/a-sepm/a-moe/a-sepm/a-sepm"
hparams.layer_types = "{}#{}".format(encoder_archi, decoder_archi)
return hparams | Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)
* Layer 1: a - a - sepm
* Layer 2: a - a - moe (mixture of expert layers in the middle)
* Layer 3: a - a - sepm
* Layer 4: a - a - sepm
Returns:
hparams | Below is the the instruction that describes the task:
### Input:
Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)
* Layer 1: a - a - sepm
* Layer 2: a - a - moe (mixture of expert layers in the middle)
* Layer 3: a - a - sepm
* Layer 4: a - a - sepm
Returns:
hparams
### Response:
def transformer_moe_2k():
"""Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)
* Layer 1: a - a - sepm
* Layer 2: a - a - moe (mixture of expert layers in the middle)
* Layer 3: a - a - sepm
* Layer 4: a - a - sepm
Returns:
hparams
"""
hparams = transformer_moe_8k()
hparams.batch_size = 2048
hparams.default_ff = "sep"
# hparams.layer_types contains the network architecture:
encoder_archi = "a/a/a/a/a"
decoder_archi = "a-sepm/a-sepm/a-moe/a-sepm/a-sepm"
hparams.layer_types = "{}#{}".format(encoder_archi, decoder_archi)
return hparams |
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request = self._py_object.request
request.environ['PATH_INFO'] = '/%s' % path
return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_response) | Call Paste's FileApp (a WSGI application) to serve the file
at the specified path | Below is the the instruction that describes the task:
### Input:
Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
### Response:
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request = self._py_object.request
request.environ['PATH_INFO'] = '/%s' % path
return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_response) |
def insert(self):
"""Insert this document"""
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and update the Id
self._id = self.get_collection().insert_one(document).inserted_id
# Send inserted signal
signal('inserted').send(self.__class__, frames=[self]) | Insert this document | Below is the the instruction that describes the task:
### Input:
Insert this document
### Response:
def insert(self):
"""Insert this document"""
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and update the Id
self._id = self.get_collection().insert_one(document).inserted_id
# Send inserted signal
signal('inserted').send(self.__class__, frames=[self]) |
def _data_format_resolver(data_format, resolver_dict):
"""Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
for any of the valid :attr:`data_format` strings
Returns:
The value of the key in :attr:`resolver_dict` that matches
:attr:`data_format`
"""
try:
data_format = DataFormat(data_format)
except ValueError:
supported_formats = ', '.join(
["'{}'".format(f.value) for f in DataFormat])
raise ValueError(("'data_format' must be one of {formats}. Given "
"'{value}'.").format(formats=supported_formats,
value=data_format))
return (resolver_dict.get(data_format) or
resolver_dict.get(data_format.value)) | Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
for any of the valid :attr:`data_format` strings
Returns:
The value of the key in :attr:`resolver_dict` that matches
:attr:`data_format` | Below is the the instruction that describes the task:
### Input:
Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
for any of the valid :attr:`data_format` strings
Returns:
The value of the key in :attr:`resolver_dict` that matches
:attr:`data_format`
### Response:
def _data_format_resolver(data_format, resolver_dict):
"""Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
for any of the valid :attr:`data_format` strings
Returns:
The value of the key in :attr:`resolver_dict` that matches
:attr:`data_format`
"""
try:
data_format = DataFormat(data_format)
except ValueError:
supported_formats = ', '.join(
["'{}'".format(f.value) for f in DataFormat])
raise ValueError(("'data_format' must be one of {formats}. Given "
"'{value}'.").format(formats=supported_formats,
value=data_format))
return (resolver_dict.get(data_format) or
resolver_dict.get(data_format.value)) |
def on_service_add(self, service):
"""
When a new service is added, a worker thread is launched to
periodically run the checks for that service.
"""
self.launch_thread(service.name, self.check_loop, service) | When a new service is added, a worker thread is launched to
periodically run the checks for that service. | Below is the the instruction that describes the task:
### Input:
When a new service is added, a worker thread is launched to
periodically run the checks for that service.
### Response:
def on_service_add(self, service):
"""
When a new service is added, a worker thread is launched to
periodically run the checks for that service.
"""
self.launch_thread(service.name, self.check_loop, service) |
def _disable_encryption(self):
# () -> None
"""Enable encryption methods for ciphers that support them."""
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt | Enable encryption methods for ciphers that support them. | Below is the the instruction that describes the task:
### Input:
Enable encryption methods for ciphers that support them.
### Response:
def _disable_encryption(self):
# () -> None
"""Enable encryption methods for ciphers that support them."""
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt |
def roundrobin(*iterables):
"""roundrobin('ABC', 'D', 'EF') --> A D E B F C"""
raise NotImplementedError('not sure if this implementation is correct')
# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python
#sentinel = object()
#return (x for x in chain(*zip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)
pending = len(iterables)
if six.PY2:
nexts = cycle(iter(it).next for it in iterables)
else:
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending)) | roundrobin('ABC', 'D', 'EF') --> A D E B F C | Below is the the instruction that describes the task:
### Input:
roundrobin('ABC', 'D', 'EF') --> A D E B F C
### Response:
def roundrobin(*iterables):
"""roundrobin('ABC', 'D', 'EF') --> A D E B F C"""
raise NotImplementedError('not sure if this implementation is correct')
# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python
#sentinel = object()
#return (x for x in chain(*zip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)
pending = len(iterables)
if six.PY2:
nexts = cycle(iter(it).next for it in iterables)
else:
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending)) |
def query(cls, offset=None, limit=None, api=None):
"""
Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object.
"""
api = api if api else cls._API
return super(Division, cls)._query(
url=cls._URL['query'], offset=offset, limit=limit,
fields='_all', api=api
) | Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object. | Below is the the instruction that describes the task:
### Input:
Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object.
### Response:
def query(cls, offset=None, limit=None, api=None):
"""
Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object.
"""
api = api if api else cls._API
return super(Division, cls)._query(
url=cls._URL['query'], offset=offset, limit=limit,
fields='_all', api=api
) |
def _legacy_upload_archive(self, data_collected, duration):
'''
Do an HTTPS upload of the archive
'''
file_name = os.path.basename(data_collected)
try:
from insights.contrib import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
mime_type = m.file(data_collected)
except ImportError:
magic = None
logger.debug('python-magic not installed, using backup function...')
from .utilities import magic_plan_b
mime_type = magic_plan_b(data_collected)
files = {
'file': (file_name, open(data_collected, 'rb'), mime_type)}
if self.config.analyze_container:
logger.debug('Uploading container, image, mountpoint or tarfile.')
upload_url = self.upload_url
else:
logger.debug('Uploading a host.')
upload_url = self.upload_url + '/' + generate_machine_id()
logger.debug("Uploading %s to %s", data_collected, upload_url)
headers = {'x-rh-collection-time': str(duration)}
net_logger.info("POST %s", upload_url)
upload = self.session.post(upload_url, files=files, headers=headers)
logger.debug("Upload status: %s %s %s",
upload.status_code, upload.reason, upload.text)
if upload.status_code in (200, 201):
the_json = json.loads(upload.text)
else:
logger.error("Upload archive failed with status code %s", upload.status_code)
return upload
try:
self.config.account_number = the_json["upload"]["account_number"]
except:
self.config.account_number = None
logger.debug("Upload duration: %s", upload.elapsed)
return upload | Do an HTTPS upload of the archive | Below is the the instruction that describes the task:
### Input:
Do an HTTPS upload of the archive
### Response:
def _legacy_upload_archive(self, data_collected, duration):
'''
Do an HTTPS upload of the archive
'''
file_name = os.path.basename(data_collected)
try:
from insights.contrib import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
mime_type = m.file(data_collected)
except ImportError:
magic = None
logger.debug('python-magic not installed, using backup function...')
from .utilities import magic_plan_b
mime_type = magic_plan_b(data_collected)
files = {
'file': (file_name, open(data_collected, 'rb'), mime_type)}
if self.config.analyze_container:
logger.debug('Uploading container, image, mountpoint or tarfile.')
upload_url = self.upload_url
else:
logger.debug('Uploading a host.')
upload_url = self.upload_url + '/' + generate_machine_id()
logger.debug("Uploading %s to %s", data_collected, upload_url)
headers = {'x-rh-collection-time': str(duration)}
net_logger.info("POST %s", upload_url)
upload = self.session.post(upload_url, files=files, headers=headers)
logger.debug("Upload status: %s %s %s",
upload.status_code, upload.reason, upload.text)
if upload.status_code in (200, 201):
the_json = json.loads(upload.text)
else:
logger.error("Upload archive failed with status code %s", upload.status_code)
return upload
try:
self.config.account_number = the_json["upload"]["account_number"]
except:
self.config.account_number = None
logger.debug("Upload duration: %s", upload.elapsed)
return upload |
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
groups = config_item['groups']
if 'defaults' in config_item:
defaults = config_item['defaults']
with salt.utils.files.fopen(BTMP, 'rb') as fp_:
loc = __context__.get(LOC_KEY, 0)
if loc == 0:
fp_.seek(0, 2)
__context__[LOC_KEY] = fp_.tell()
return ret
else:
fp_.seek(loc)
while True:
now = datetime.datetime.now()
raw = fp_.read(SIZE)
if len(raw) != SIZE:
return ret
__context__[LOC_KEY] = fp_.tell()
pack = struct.unpack(FMT, raw)
event = {}
for ind, field in enumerate(FIELDS):
event[field] = pack[ind]
if isinstance(event[field], salt.ext.six.string_types):
if isinstance(event[field], bytes):
event[field] = salt.utils.stringutils.to_unicode(event[field])
event[field] = event[field].strip('\x00')
for group in groups:
_gather_group_members(group, groups, users)
if users:
if event['user'] in users:
_user = users[event['user']]
if isinstance(_user, dict) and 'time_range' in _user:
if _check_time_range(_user['time_range'], now):
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'],
now):
ret.append(event)
else:
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'], now):
ret.append(event)
else:
ret.append(event)
return ret | Read the last btmp file and return information on the failed logins | Below is the the instruction that describes the task:
### Input:
Read the last btmp file and return information on the failed logins
### Response:
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
groups = config_item['groups']
if 'defaults' in config_item:
defaults = config_item['defaults']
with salt.utils.files.fopen(BTMP, 'rb') as fp_:
loc = __context__.get(LOC_KEY, 0)
if loc == 0:
fp_.seek(0, 2)
__context__[LOC_KEY] = fp_.tell()
return ret
else:
fp_.seek(loc)
while True:
now = datetime.datetime.now()
raw = fp_.read(SIZE)
if len(raw) != SIZE:
return ret
__context__[LOC_KEY] = fp_.tell()
pack = struct.unpack(FMT, raw)
event = {}
for ind, field in enumerate(FIELDS):
event[field] = pack[ind]
if isinstance(event[field], salt.ext.six.string_types):
if isinstance(event[field], bytes):
event[field] = salt.utils.stringutils.to_unicode(event[field])
event[field] = event[field].strip('\x00')
for group in groups:
_gather_group_members(group, groups, users)
if users:
if event['user'] in users:
_user = users[event['user']]
if isinstance(_user, dict) and 'time_range' in _user:
if _check_time_range(_user['time_range'], now):
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'],
now):
ret.append(event)
else:
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'], now):
ret.append(event)
else:
ret.append(event)
return ret |
def insertPDF(self, docsrc, from_page=-1, to_page=-1, start_at=-1, rotate=-1, links=1):
"""Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
if id(self) == id(docsrc):
raise ValueError("source must not equal target PDF")
sa = start_at
if sa < 0:
sa = self.pageCount
val = _fitz.Document_insertPDF(self, docsrc, from_page, to_page, start_at, rotate, links)
self._reset_page_refs()
if links:
self._do_links(docsrc, from_page = from_page, to_page = to_page,
start_at = sa)
return val | Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'. | Below is the the instruction that describes the task:
### Input:
Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'.
### Response:
def insertPDF(self, docsrc, from_page=-1, to_page=-1, start_at=-1, rotate=-1, links=1):
"""Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
if id(self) == id(docsrc):
raise ValueError("source must not equal target PDF")
sa = start_at
if sa < 0:
sa = self.pageCount
val = _fitz.Document_insertPDF(self, docsrc, from_page, to_page, start_at, rotate, links)
self._reset_page_refs()
if links:
self._do_links(docsrc, from_page = from_page, to_page = to_page,
start_at = sa)
return val |
def run(self):
"""Main thread for processing messages."""
self.OnStartup()
try:
while True:
message = self._in_queue.get()
# A message of None is our terminal message.
if message is None:
break
try:
self.HandleMessage(message)
# Catch any errors and keep going here
except Exception as e: # pylint: disable=broad-except
logging.warning("%s", e)
self.SendReply(
rdf_flows.GrrStatus(
status=rdf_flows.GrrStatus.ReturnedStatus.GENERIC_ERROR,
error_message=utils.SmartUnicode(e)),
request_id=message.request_id,
response_id=1,
session_id=message.session_id,
task_id=message.task_id,
message_type=rdf_flows.GrrMessage.Type.STATUS)
if flags.FLAGS.pdb_post_mortem:
pdb.post_mortem()
except Exception as e: # pylint: disable=broad-except
logging.error("Exception outside of the processing loop: %r", e)
finally:
# There's no point in running the client if it's broken out of the
# processing loop and it should be restarted shortly anyway.
logging.fatal("The client has broken out of its processing loop.")
# The binary (Python threading library, perhaps) has proven in tests to be
# very persistent to termination calls, so we kill it with fire.
os.kill(os.getpid(), signal.SIGKILL) | Main thread for processing messages. | Below is the the instruction that describes the task:
### Input:
Main thread for processing messages.
### Response:
def run(self):
"""Main thread for processing messages."""
self.OnStartup()
try:
while True:
message = self._in_queue.get()
# A message of None is our terminal message.
if message is None:
break
try:
self.HandleMessage(message)
# Catch any errors and keep going here
except Exception as e: # pylint: disable=broad-except
logging.warning("%s", e)
self.SendReply(
rdf_flows.GrrStatus(
status=rdf_flows.GrrStatus.ReturnedStatus.GENERIC_ERROR,
error_message=utils.SmartUnicode(e)),
request_id=message.request_id,
response_id=1,
session_id=message.session_id,
task_id=message.task_id,
message_type=rdf_flows.GrrMessage.Type.STATUS)
if flags.FLAGS.pdb_post_mortem:
pdb.post_mortem()
except Exception as e: # pylint: disable=broad-except
logging.error("Exception outside of the processing loop: %r", e)
finally:
# There's no point in running the client if it's broken out of the
# processing loop and it should be restarted shortly anyway.
logging.fatal("The client has broken out of its processing loop.")
# The binary (Python threading library, perhaps) has proven in tests to be
# very persistent to termination calls, so we kill it with fire.
os.kill(os.getpid(), signal.SIGKILL) |
def _local_install(self, args, pkg_name=None):
'''
Install a package from a file
'''
if len(args) < 2:
raise SPMInvocationError('A package file must be specified')
self._install(args) | Install a package from a file | Below is the the instruction that describes the task:
### Input:
Install a package from a file
### Response:
def _local_install(self, args, pkg_name=None):
'''
Install a package from a file
'''
if len(args) < 2:
raise SPMInvocationError('A package file must be specified')
self._install(args) |
def rdfs_classes(rdf):
"""Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class."""
# find out the subclass mappings
upperclasses = {} # key: class val: set([superclass1, superclass2..])
for s, o in rdf.subject_objects(RDFS.subClassOf):
upperclasses.setdefault(s, set())
for uc in rdf.transitive_objects(s, RDFS.subClassOf):
if uc != s:
upperclasses[s].add(uc)
# set the superclass type information for subclass instances
for s, ucs in upperclasses.items():
logging.debug("setting superclass types: %s -> %s", s, str(ucs))
for res in rdf.subjects(RDF.type, s):
for uc in ucs:
rdf.add((res, RDF.type, uc)) | Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class. | Below is the the instruction that describes the task:
### Input:
Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class.
### Response:
def rdfs_classes(rdf):
"""Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class."""
# find out the subclass mappings
upperclasses = {} # key: class val: set([superclass1, superclass2..])
for s, o in rdf.subject_objects(RDFS.subClassOf):
upperclasses.setdefault(s, set())
for uc in rdf.transitive_objects(s, RDFS.subClassOf):
if uc != s:
upperclasses[s].add(uc)
# set the superclass type information for subclass instances
for s, ucs in upperclasses.items():
logging.debug("setting superclass types: %s -> %s", s, str(ucs))
for res in rdf.subjects(RDF.type, s):
for uc in ucs:
rdf.add((res, RDF.type, uc)) |
def get_extr_license_ident(self, extr_lic):
"""
Return an a license identifier from an ExtractedLicense or None.
"""
identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))
if not identifier_tripples:
self.error = True
msg = 'Extracted license must have licenseId property.'
self.logger.log(msg)
return
if len(identifier_tripples) > 1:
self.more_than_one_error('extracted license identifier_tripples')
return
identifier_tripple = identifier_tripples[0]
_s, _p, identifier = identifier_tripple
return identifier | Return an a license identifier from an ExtractedLicense or None. | Below is the the instruction that describes the task:
### Input:
Return an a license identifier from an ExtractedLicense or None.
### Response:
def get_extr_license_ident(self, extr_lic):
"""
Return an a license identifier from an ExtractedLicense or None.
"""
identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))
if not identifier_tripples:
self.error = True
msg = 'Extracted license must have licenseId property.'
self.logger.log(msg)
return
if len(identifier_tripples) > 1:
self.more_than_one_error('extracted license identifier_tripples')
return
identifier_tripple = identifier_tripples[0]
_s, _p, identifier = identifier_tripple
return identifier |
def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | Below is the the instruction that describes the task:
### Input:
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
### Response:
def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) |
def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) | Flips the layer, either HORIZONTAL or VERTICAL. | Below is the the instruction that describes the task:
### Input:
Flips the layer, either HORIZONTAL or VERTICAL.
### Response:
def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) |
def render_formset(formset, **kwargs):
"""
Render a formset to a Bootstrap layout
"""
renderer_cls = get_formset_renderer(**kwargs)
return renderer_cls(formset, **kwargs).render() | Render a formset to a Bootstrap layout | Below is the the instruction that describes the task:
### Input:
Render a formset to a Bootstrap layout
### Response:
def render_formset(formset, **kwargs):
"""
Render a formset to a Bootstrap layout
"""
renderer_cls = get_formset_renderer(**kwargs)
return renderer_cls(formset, **kwargs).render() |
def paschen_back_energies(fine_state, Bz):
r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25
-1.88423787397534e-24]
[-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25
1.88368413689800e-24]
"""
element = fine_state.element
isotope = fine_state.isotope
N = fine_state.n
L = fine_state.l
J = fine_state.j
II = Atom(element, isotope).nuclear_spin
MJ = [-J+i for i in range(2*J+1)]
MI = [-II+i for i in range(2*II+1)]
Ahfs = fine_state.Ahfs
Bhfs = fine_state.Bhfs
gL, gS, gI, gJ = lande_g_factors(element, isotope, L, J)
energiesPBack = []
for mj in MJ:
energiesMJ = []
unperturbed_energy = hbar*State(element, isotope, N, L, J).omega
for mi in MI:
energyMI = unperturbed_energy
energyMI += 2*pi*hbar*Ahfs*mi*mj
if J != 1/Integer(2) and II != 1/Integer(2):
num = 9*(mi*mj)**2 - 3*J*(J+1)*mi**2
num += -3*II*(II+1)*mj**2 + II*(II+1)*J*(J+1)
den = 4*J*(2*J-1)*II*(2*II-1)
energyMI += 2*pi*hbar*Bhfs*num/den
energyMI += muB*(gJ*mj+gI*mi)*Bz
energiesMJ += [energyMI]
energiesPBack += [energiesMJ]
return array(energiesPBack) | r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25
-1.88423787397534e-24]
[-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25
1.88368413689800e-24] | Below is the the instruction that describes the task:
### Input:
r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25
-1.88423787397534e-24]
[-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25
1.88368413689800e-24]
### Response:
def paschen_back_energies(fine_state, Bz):
r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25
-1.88423787397534e-24]
[-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25
1.88368413689800e-24]
"""
element = fine_state.element
isotope = fine_state.isotope
N = fine_state.n
L = fine_state.l
J = fine_state.j
II = Atom(element, isotope).nuclear_spin
MJ = [-J+i for i in range(2*J+1)]
MI = [-II+i for i in range(2*II+1)]
Ahfs = fine_state.Ahfs
Bhfs = fine_state.Bhfs
gL, gS, gI, gJ = lande_g_factors(element, isotope, L, J)
energiesPBack = []
for mj in MJ:
energiesMJ = []
unperturbed_energy = hbar*State(element, isotope, N, L, J).omega
for mi in MI:
energyMI = unperturbed_energy
energyMI += 2*pi*hbar*Ahfs*mi*mj
if J != 1/Integer(2) and II != 1/Integer(2):
num = 9*(mi*mj)**2 - 3*J*(J+1)*mi**2
num += -3*II*(II+1)*mj**2 + II*(II+1)*J*(J+1)
den = 4*J*(2*J-1)*II*(2*II-1)
energyMI += 2*pi*hbar*Bhfs*num/den
energyMI += muB*(gJ*mj+gI*mi)*Bz
energiesMJ += [energyMI]
energiesPBack += [energiesMJ]
return array(energiesPBack) |
def _schema_nodes(self):
"""parse self._ontology_file into a graph"""
name, ext = os.path.splitext(self._ontology_file)
if ext in ['.ttl']:
self._ontology_parser_function = \
lambda s: rdflib.Graph().parse(s, format='n3')
else:
self._ontology_parser_function = \
lambda s: pyRdfa().graph_from_source(s)
if not self._ontology_parser_function:
raise ValueError(
"No function found to parse ontology. %s" %
self.errorstring_base)
if not self._ontology_file:
raise ValueError(
"No ontology file specified. %s" % self.errorstring_base)
if not self.lexicon:
raise ValueError(
"No lexicon object assigned. %s" % self.errorstring_base)
latest_file = self._read_schema()
try:
self.graph = self._ontology_parser_function(latest_file)
except:
raise IOError("Error parsing ontology at %s" % latest_file)
for subj, pred, obj in self.graph:
self.ontology[subj].append((pred, obj))
yield (subj, pred, obj) | parse self._ontology_file into a graph | Below is the the instruction that describes the task:
### Input:
parse self._ontology_file into a graph
### Response:
def _schema_nodes(self):
"""parse self._ontology_file into a graph"""
name, ext = os.path.splitext(self._ontology_file)
if ext in ['.ttl']:
self._ontology_parser_function = \
lambda s: rdflib.Graph().parse(s, format='n3')
else:
self._ontology_parser_function = \
lambda s: pyRdfa().graph_from_source(s)
if not self._ontology_parser_function:
raise ValueError(
"No function found to parse ontology. %s" %
self.errorstring_base)
if not self._ontology_file:
raise ValueError(
"No ontology file specified. %s" % self.errorstring_base)
if not self.lexicon:
raise ValueError(
"No lexicon object assigned. %s" % self.errorstring_base)
latest_file = self._read_schema()
try:
self.graph = self._ontology_parser_function(latest_file)
except:
raise IOError("Error parsing ontology at %s" % latest_file)
for subj, pred, obj in self.graph:
self.ontology[subj].append((pred, obj))
yield (subj, pred, obj) |
def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) | generate the analysis settings from Python land | Below is the the instruction that describes the task:
### Input:
generate the analysis settings from Python land
### Response:
def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) |
def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._suri_cmd(pcap, tmpdir), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise Exception("\n".join(["Execution failed return code: {0}" \
.format(proc.returncode), stderr or ""]))
with open(os.path.join(tmpdir, 'fast.log')) as tmp:
return (parse_version(stdout),
[ x for x in parse_alert(tmp.read()) ])
finally:
if tmpdir:
shutil.rmtree(tmpdir) | Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | Below is the the instruction that describes the task:
### Input:
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
### Response:
def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._suri_cmd(pcap, tmpdir), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise Exception("\n".join(["Execution failed return code: {0}" \
.format(proc.returncode), stderr or ""]))
with open(os.path.join(tmpdir, 'fast.log')) as tmp:
return (parse_version(stdout),
[ x for x in parse_alert(tmp.read()) ])
finally:
if tmpdir:
shutil.rmtree(tmpdir) |
def _allKeys(self, prefix):
""" Private implementation method. Use keys() instead. """
global dictItemsIter
result = [prefix + self.key] if self.key != None else []
for key, trie in dictItemsIter(self.slots):
result.extend(trie._allKeys(prefix + key))
return result | Private implementation method. Use keys() instead. | Below is the the instruction that describes the task:
### Input:
Private implementation method. Use keys() instead.
### Response:
def _allKeys(self, prefix):
""" Private implementation method. Use keys() instead. """
global dictItemsIter
result = [prefix + self.key] if self.key != None else []
for key, trie in dictItemsIter(self.slots):
result.extend(trie._allKeys(prefix + key))
return result |
def check_commutation(pauli_list, pauli_two):
"""
Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting PauliTerms)
instead of the no. of coincidences, as in the paper.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm pauli_two_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool
"""
def coincident_parity(p1, p2):
non_similar = 0
p1_indices = set(p1._ops.keys())
p2_indices = set(p2._ops.keys())
for idx in p1_indices.intersection(p2_indices):
if p1[idx] != p2[idx]:
non_similar += 1
return non_similar % 2 == 0
for term in pauli_list:
if not coincident_parity(term, pauli_two):
return False
return True | Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting PauliTerms)
instead of the no. of coincidences, as in the paper.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm pauli_two_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting PauliTerms)
instead of the no. of coincidences, as in the paper.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm pauli_two_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool
### Response:
def check_commutation(pauli_list, pauli_two):
"""
Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting PauliTerms)
instead of the no. of coincidences, as in the paper.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm pauli_two_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool
"""
def coincident_parity(p1, p2):
non_similar = 0
p1_indices = set(p1._ops.keys())
p2_indices = set(p2._ops.keys())
for idx in p1_indices.intersection(p2_indices):
if p1[idx] != p2[idx]:
non_similar += 1
return non_similar % 2 == 0
for term in pauli_list:
if not coincident_parity(term, pauli_two):
return False
return True |
def _add_admin(self, app, **kwargs):
"""Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
"""
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
admin = Admin(app, **kwargs)
for flask_admin_model in self.flask_admin_models:
if isinstance(flask_admin_model, tuple): # assume its a 2 tuple
if len(flask_admin_model) != 2:
raise TypeError
model, view = flask_admin_model
admin.add_view(view(model, self.session))
else:
admin.add_view(ModelView(flask_admin_model, self.session))
return admin | Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin | Below is the the instruction that describes the task:
### Input:
Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
### Response:
def _add_admin(self, app, **kwargs):
"""Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
"""
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
admin = Admin(app, **kwargs)
for flask_admin_model in self.flask_admin_models:
if isinstance(flask_admin_model, tuple): # assume its a 2 tuple
if len(flask_admin_model) != 2:
raise TypeError
model, view = flask_admin_model
admin.add_view(view(model, self.session))
else:
admin.add_view(ModelView(flask_admin_model, self.session))
return admin |
def add_group(self, name, desc, status):
"""
Add a new group to a network.
"""
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resource group with name %s is already in network %s"%(name, self.id))
group_i = ResourceGroup()
group_i.name = name
group_i.description = desc
group_i.status = status
get_session().add(group_i)
self.resourcegroups.append(group_i)
return group_i | Add a new group to a network. | Below is the the instruction that describes the task:
### Input:
Add a new group to a network.
### Response:
def add_group(self, name, desc, status):
"""
Add a new group to a network.
"""
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resource group with name %s is already in network %s"%(name, self.id))
group_i = ResourceGroup()
group_i.name = name
group_i.description = desc
group_i.status = status
get_session().add(group_i)
self.resourcegroups.append(group_i)
return group_i |
def save(self, filename, fformat=None, fill_value=None, compute=True,
keep_palette=False, cmap=None, **format_kwargs):
"""Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
one of many image formats supported by the
`rasterio` or `PIL` libraries ('jpg', 'png',
'tif'). By default this is determined by the
extension of the provided filename.
If the format allows, geographical information will
be saved to the ouput file, in the form of grid
mapping or ground control points.
fill_value (float): Replace invalid data values with this value
and do not produce an Alpha band. Default
behavior is to create an alpha band.
compute (bool): If True (default) write the data to the file
immediately. If False the return value is either
a `dask.Delayed` object or a tuple of
``(source, target)`` to be passed to
`dask.array.store`.
keep_palette (bool): Saves the palettized version of the image if
set to True. False by default.
cmap (Colormap or dict): Colormap to be applied to the image when
saving with rasterio, used with
keep_palette=True. Should be uint8.
format_kwargs: Additional format options to pass to `rasterio`
or `PIL` saving methods.
Returns:
Either `None` if `compute` is True or a `dask.Delayed` object or
``(source, target)`` pair to be passed to `dask.array.store`.
If compute is False the return value depends on format and how
the image backend is used. If ``(source, target)`` is provided
then target is an open file-like object that must be closed by
the caller.
"""
fformat = fformat or os.path.splitext(filename)[1][1:4]
if fformat in ('tif', 'jp2') and rasterio:
return self.rio_save(filename, fformat=fformat,
fill_value=fill_value, compute=compute,
keep_palette=keep_palette, cmap=cmap,
**format_kwargs)
else:
return self.pil_save(filename, fformat, fill_value,
compute=compute, **format_kwargs) | Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
one of many image formats supported by the
`rasterio` or `PIL` libraries ('jpg', 'png',
'tif'). By default this is determined by the
extension of the provided filename.
If the format allows, geographical information will
be saved to the ouput file, in the form of grid
mapping or ground control points.
fill_value (float): Replace invalid data values with this value
and do not produce an Alpha band. Default
behavior is to create an alpha band.
compute (bool): If True (default) write the data to the file
immediately. If False the return value is either
a `dask.Delayed` object or a tuple of
``(source, target)`` to be passed to
`dask.array.store`.
keep_palette (bool): Saves the palettized version of the image if
set to True. False by default.
cmap (Colormap or dict): Colormap to be applied to the image when
saving with rasterio, used with
keep_palette=True. Should be uint8.
format_kwargs: Additional format options to pass to `rasterio`
or `PIL` saving methods.
Returns:
Either `None` if `compute` is True or a `dask.Delayed` object or
``(source, target)`` pair to be passed to `dask.array.store`.
If compute is False the return value depends on format and how
the image backend is used. If ``(source, target)`` is provided
then target is an open file-like object that must be closed by
the caller. | Below is the the instruction that describes the task:
### Input:
Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
one of many image formats supported by the
`rasterio` or `PIL` libraries ('jpg', 'png',
'tif'). By default this is determined by the
extension of the provided filename.
If the format allows, geographical information will
be saved to the ouput file, in the form of grid
mapping or ground control points.
fill_value (float): Replace invalid data values with this value
and do not produce an Alpha band. Default
behavior is to create an alpha band.
compute (bool): If True (default) write the data to the file
immediately. If False the return value is either
a `dask.Delayed` object or a tuple of
``(source, target)`` to be passed to
`dask.array.store`.
keep_palette (bool): Saves the palettized version of the image if
set to True. False by default.
cmap (Colormap or dict): Colormap to be applied to the image when
saving with rasterio, used with
keep_palette=True. Should be uint8.
format_kwargs: Additional format options to pass to `rasterio`
or `PIL` saving methods.
Returns:
Either `None` if `compute` is True or a `dask.Delayed` object or
``(source, target)`` pair to be passed to `dask.array.store`.
If compute is False the return value depends on format and how
the image backend is used. If ``(source, target)`` is provided
then target is an open file-like object that must be closed by
the caller.
### Response:
def save(self, filename, fformat=None, fill_value=None, compute=True,
keep_palette=False, cmap=None, **format_kwargs):
"""Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
one of many image formats supported by the
`rasterio` or `PIL` libraries ('jpg', 'png',
'tif'). By default this is determined by the
extension of the provided filename.
If the format allows, geographical information will
be saved to the ouput file, in the form of grid
mapping or ground control points.
fill_value (float): Replace invalid data values with this value
and do not produce an Alpha band. Default
behavior is to create an alpha band.
compute (bool): If True (default) write the data to the file
immediately. If False the return value is either
a `dask.Delayed` object or a tuple of
``(source, target)`` to be passed to
`dask.array.store`.
keep_palette (bool): Saves the palettized version of the image if
set to True. False by default.
cmap (Colormap or dict): Colormap to be applied to the image when
saving with rasterio, used with
keep_palette=True. Should be uint8.
format_kwargs: Additional format options to pass to `rasterio`
or `PIL` saving methods.
Returns:
Either `None` if `compute` is True or a `dask.Delayed` object or
``(source, target)`` pair to be passed to `dask.array.store`.
If compute is False the return value depends on format and how
the image backend is used. If ``(source, target)`` is provided
then target is an open file-like object that must be closed by
the caller.
"""
fformat = fformat or os.path.splitext(filename)[1][1:4]
if fformat in ('tif', 'jp2') and rasterio:
return self.rio_save(filename, fformat=fformat,
fill_value=fill_value, compute=compute,
keep_palette=keep_palette, cmap=cmap,
**format_kwargs)
else:
return self.pil_save(filename, fformat, fill_value,
compute=compute, **format_kwargs) |
def writeln(self, data):
"""
Write a line of text to the file
:param data: The text to write
"""
self.f.write(" "*self.indent_level)
self.f.write(data + "\n") | Write a line of text to the file
:param data: The text to write | Below is the the instruction that describes the task:
### Input:
Write a line of text to the file
:param data: The text to write
### Response:
def writeln(self, data):
"""
Write a line of text to the file
:param data: The text to write
"""
self.f.write(" "*self.indent_level)
self.f.write(data + "\n") |
def set_pair(self, term1, term2, value, **kwargs):
"""
Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed)
"""
key = self.key(term1, term2)
self.keys.update([term1, term2])
self.pairs[key] = value | Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed) | Below is the the instruction that describes the task:
### Input:
Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed)
### Response:
def set_pair(self, term1, term2, value, **kwargs):
"""
Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed)
"""
key = self.key(term1, term2)
self.keys.update([term1, term2])
self.pairs[key] = value |
def calculate_content_width(self):
"""
Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins each set to 2, the content
width would be 71 (77 - 2 - 2 - 2 = 71).
Returns:
int: the inner content width in columns.
"""
return self.calculate_border_width() - self.padding.left - self.padding.right - 2 | Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins each set to 2, the content
width would be 71 (77 - 2 - 2 - 2 = 71).
Returns:
int: the inner content width in columns. | Below is the the instruction that describes the task:
### Input:
Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins each set to 2, the content
width would be 71 (77 - 2 - 2 - 2 = 71).
Returns:
int: the inner content width in columns.
### Response:
def calculate_content_width(self):
"""
Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins each set to 2, the content
width would be 71 (77 - 2 - 2 - 2 = 71).
Returns:
int: the inner content width in columns.
"""
return self.calculate_border_width() - self.padding.left - self.padding.right - 2 |
def deserialize(datagram, source):
"""
De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message
"""
try:
fmt = "!BBH"
pos = struct.calcsize(fmt)
s = struct.Struct(fmt)
values = s.unpack_from(datagram)
first = values[0]
code = values[1]
mid = values[2]
version = (first & 0xC0) >> 6
message_type = (first & 0x30) >> 4
token_length = (first & 0x0F)
if Serializer.is_response(code):
message = Response()
message.code = code
elif Serializer.is_request(code):
message = Request()
message.code = code
else:
message = Message()
message.source = source
message.destination = None
message.version = version
message.type = message_type
message.mid = mid
if token_length > 0:
fmt = "%ss" % token_length
s = struct.Struct(fmt)
token_value = s.unpack_from(datagram[pos:])[0]
message.token = token_value.decode("utf-8")
else:
message.token = None
pos += token_length
current_option = 0
values = datagram[pos:]
length_packet = len(values)
pos = 0
while pos < length_packet:
next_byte = struct.unpack("B", values[pos].to_bytes(1, "big"))[0]
pos += 1
if next_byte != int(defines.PAYLOAD_MARKER):
# the first 4 bits of the byte represent the option delta
# delta = self._reader.read(4).uint
num, option_length, pos = Serializer.read_option_value_len_from_byte(next_byte, pos, values)
current_option += num
# read option
try:
option_item = defines.OptionRegistry.LIST[current_option]
except KeyError:
(opt_critical, _, _) = defines.OptionRegistry.get_option_flags(current_option)
if opt_critical:
raise AttributeError("Critical option %s unknown" % current_option)
else:
# If the non-critical option is unknown
# (vendor-specific, proprietary) - just skip it
#log.err("unrecognized option %d" % current_option)
pass
else:
if option_length == 0:
value = None
elif option_item.value_type == defines.INTEGER:
tmp = values[pos: pos + option_length]
value = 0
for b in tmp:
value = (value << 8) | struct.unpack("B", b.to_bytes(1, "big"))[0]
elif option_item.value_type == defines.OPAQUE:
tmp = values[pos: pos + option_length]
value = tmp
else:
value = values[pos: pos + option_length]
option = Option()
option.number = current_option
option.value = Serializer.convert_to_raw(current_option, value, option_length)
message.add_option(option)
if option.number == defines.OptionRegistry.CONTENT_TYPE.number:
message.payload_type = option.value
finally:
pos += option_length
else:
if length_packet <= pos:
# log.err("Payload Marker with no payload")
raise AttributeError("Packet length %s, pos %s" % (length_packet, pos))
message.payload = ""
payload = values[pos:]
try:
if message.payload_type == defines.Content_types["application/octet-stream"]:
message.payload = payload
else:
message.payload = payload.decode("utf-8")
except AttributeError:
message.payload = payload.decode("utf-8")
pos += len(payload)
return message
except AttributeError:
return defines.Codes.BAD_REQUEST.number
except struct.error:
return defines.Codes.BAD_REQUEST.number | De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message | Below is the the instruction that describes the task:
### Input:
De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message
### Response:
def deserialize(datagram, source):
"""
De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message
"""
try:
fmt = "!BBH"
pos = struct.calcsize(fmt)
s = struct.Struct(fmt)
values = s.unpack_from(datagram)
first = values[0]
code = values[1]
mid = values[2]
version = (first & 0xC0) >> 6
message_type = (first & 0x30) >> 4
token_length = (first & 0x0F)
if Serializer.is_response(code):
message = Response()
message.code = code
elif Serializer.is_request(code):
message = Request()
message.code = code
else:
message = Message()
message.source = source
message.destination = None
message.version = version
message.type = message_type
message.mid = mid
if token_length > 0:
fmt = "%ss" % token_length
s = struct.Struct(fmt)
token_value = s.unpack_from(datagram[pos:])[0]
message.token = token_value.decode("utf-8")
else:
message.token = None
pos += token_length
current_option = 0
values = datagram[pos:]
length_packet = len(values)
pos = 0
while pos < length_packet:
next_byte = struct.unpack("B", values[pos].to_bytes(1, "big"))[0]
pos += 1
if next_byte != int(defines.PAYLOAD_MARKER):
# the first 4 bits of the byte represent the option delta
# delta = self._reader.read(4).uint
num, option_length, pos = Serializer.read_option_value_len_from_byte(next_byte, pos, values)
current_option += num
# read option
try:
option_item = defines.OptionRegistry.LIST[current_option]
except KeyError:
(opt_critical, _, _) = defines.OptionRegistry.get_option_flags(current_option)
if opt_critical:
raise AttributeError("Critical option %s unknown" % current_option)
else:
# If the non-critical option is unknown
# (vendor-specific, proprietary) - just skip it
#log.err("unrecognized option %d" % current_option)
pass
else:
if option_length == 0:
value = None
elif option_item.value_type == defines.INTEGER:
tmp = values[pos: pos + option_length]
value = 0
for b in tmp:
value = (value << 8) | struct.unpack("B", b.to_bytes(1, "big"))[0]
elif option_item.value_type == defines.OPAQUE:
tmp = values[pos: pos + option_length]
value = tmp
else:
value = values[pos: pos + option_length]
option = Option()
option.number = current_option
option.value = Serializer.convert_to_raw(current_option, value, option_length)
message.add_option(option)
if option.number == defines.OptionRegistry.CONTENT_TYPE.number:
message.payload_type = option.value
finally:
pos += option_length
else:
if length_packet <= pos:
# log.err("Payload Marker with no payload")
raise AttributeError("Packet length %s, pos %s" % (length_packet, pos))
message.payload = ""
payload = values[pos:]
try:
if message.payload_type == defines.Content_types["application/octet-stream"]:
message.payload = payload
else:
message.payload = payload.decode("utf-8")
except AttributeError:
message.payload = payload.decode("utf-8")
pos += len(payload)
return message
except AttributeError:
return defines.Codes.BAD_REQUEST.number
except struct.error:
return defines.Codes.BAD_REQUEST.number |
def vsubg(v1, v2, ndim):
"""
Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param ndim: Dimension of v1, v2, and vout.
:type ndim: int
:return: Difference vector, v1 - v2.
:rtype: Array of floats
"""
v1 = stypes.toDoubleVector(v1)
v2 = stypes.toDoubleVector(v2)
vout = stypes.emptyDoubleVector(ndim)
ndim = ctypes.c_int(ndim)
libspice.vsubg_c(v1, v2, ndim, vout)
return stypes.cVectorToPython(vout) | Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param ndim: Dimension of v1, v2, and vout.
:type ndim: int
:return: Difference vector, v1 - v2.
:rtype: Array of floats | Below is the the instruction that describes the task:
### Input:
Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param ndim: Dimension of v1, v2, and vout.
:type ndim: int
:return: Difference vector, v1 - v2.
:rtype: Array of floats
### Response:
def vsubg(v1, v2, ndim):
"""
Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param ndim: Dimension of v1, v2, and vout.
:type ndim: int
:return: Difference vector, v1 - v2.
:rtype: Array of floats
"""
v1 = stypes.toDoubleVector(v1)
v2 = stypes.toDoubleVector(v2)
vout = stypes.emptyDoubleVector(ndim)
ndim = ctypes.c_int(ndim)
libspice.vsubg_c(v1, v2, ndim, vout)
return stypes.cVectorToPython(vout) |
def remove_markables(self,list_mark_ids):
"""
Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed
"""
nodes_to_remove = set()
for markable in self:
if markable.get_id() in list_mark_ids:
nodes_to_remove.add(markable.get_node())
#For removing the previous comment
prv = markable.get_node().getprevious()
if prv is not None:
nodes_to_remove.add(prv)
for node in nodes_to_remove:
self.node.remove(node) | Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed | Below is the the instruction that describes the task:
### Input:
Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed
### Response:
def remove_markables(self,list_mark_ids):
"""
Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed
"""
nodes_to_remove = set()
for markable in self:
if markable.get_id() in list_mark_ids:
nodes_to_remove.add(markable.get_node())
#For removing the previous comment
prv = markable.get_node().getprevious()
if prv is not None:
nodes_to_remove.add(prv)
for node in nodes_to_remove:
self.node.remove(node) |
def _parse_caps_devices_features(node):
'''
Parse the devices or features list of the domain capatilities
'''
result = {}
for child in node:
if child.get('supported') == 'yes':
enums = [_parse_caps_enum(node) for node in child.findall('enum')]
result[child.tag] = {item[0]: item[1] for item in enums if item[0]}
return result | Parse the devices or features list of the domain capatilities | Below is the the instruction that describes the task:
### Input:
Parse the devices or features list of the domain capatilities
### Response:
def _parse_caps_devices_features(node):
'''
Parse the devices or features list of the domain capatilities
'''
result = {}
for child in node:
if child.get('supported') == 'yes':
enums = [_parse_caps_enum(node) for node in child.findall('enum')]
result[child.tag] = {item[0]: item[1] for item in enums if item[0]}
return result |
def syd(c, s, l):
""" This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the fixed asset
Example: syd(1000, 100, 5)
"""
return [(c-s) * (x/(l*(l+1)/2)) for x in range(l,0,-1)] | This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the fixed asset
Example: syd(1000, 100, 5) | Below is the the instruction that describes the task:
### Input:
This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the fixed asset
Example: syd(1000, 100, 5)
### Response:
def syd(c, s, l):
""" This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the fixed asset
Example: syd(1000, 100, 5)
"""
return [(c-s) * (x/(l*(l+1)/2)) for x in range(l,0,-1)] |
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
radius_arcsec : float
The radius (in arc seconds) of the circle within which pixels unmasked.
centre: (float, float)
The centre of the circle used to mask pixels.
"""
mask = mask_util.mask_circular_from_shape_pixel_scale_and_radius(shape, pixel_scale, radius_arcsec,
centre)
if invert: mask = np.invert(mask)
return cls(array=mask.astype('bool'), pixel_scale=pixel_scale) | Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
radius_arcsec : float
The radius (in arc seconds) of the circle within which pixels unmasked.
centre: (float, float)
The centre of the circle used to mask pixels. | Below is the the instruction that describes the task:
### Input:
Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
radius_arcsec : float
The radius (in arc seconds) of the circle within which pixels unmasked.
centre: (float, float)
The centre of the circle used to mask pixels.
### Response:
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
radius_arcsec : float
The radius (in arc seconds) of the circle within which pixels unmasked.
centre: (float, float)
The centre of the circle used to mask pixels.
"""
mask = mask_util.mask_circular_from_shape_pixel_scale_and_radius(shape, pixel_scale, radius_arcsec,
centre)
if invert: mask = np.invert(mask)
return cls(array=mask.astype('bool'), pixel_scale=pixel_scale) |
def load_payload(self, payload, serializer=None):
"""Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
"""
if serializer is None:
serializer = self.serializer
is_text = self.is_text_serializer
else:
is_text = is_text_serializer(serializer)
try:
if is_text:
payload = payload.decode('utf-8')
return serializer.loads(payload)
except Exception as e:
raise BadPayload('Could not load the payload because an '
'exception occurred on unserializing the data',
original_error=e) | Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based. | Below is the the instruction that describes the task:
### Input:
Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
### Response:
def load_payload(self, payload, serializer=None):
"""Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
"""
if serializer is None:
serializer = self.serializer
is_text = self.is_text_serializer
else:
is_text = is_text_serializer(serializer)
try:
if is_text:
payload = payload.decode('utf-8')
return serializer.loads(payload)
except Exception as e:
raise BadPayload('Could not load the payload because an '
'exception occurred on unserializing the data',
original_error=e) |
def get_all_cache_subnet_groups(name=None, region=None, key=None,
keyid=None, profile=None):
'''
Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
marker = ''
groups = []
while marker is not None:
ret = conn.describe_cache_subnet_groups(cache_subnet_group_name=name,
marker=marker)
trimmed = ret.get('DescribeCacheSubnetGroupsResponse',
{}).get('DescribeCacheSubnetGroupsResult', {})
groups += trimmed.get('CacheSubnetGroups', [])
marker = trimmed.get('Marker', None)
if not groups:
log.debug('No ElastiCache subnet groups found.')
return groups
except boto.exception.BotoServerError as e:
log.error(e)
return [] | Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1
### Response:
def get_all_cache_subnet_groups(name=None, region=None, key=None,
keyid=None, profile=None):
'''
Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
marker = ''
groups = []
while marker is not None:
ret = conn.describe_cache_subnet_groups(cache_subnet_group_name=name,
marker=marker)
trimmed = ret.get('DescribeCacheSubnetGroupsResponse',
{}).get('DescribeCacheSubnetGroupsResult', {})
groups += trimmed.get('CacheSubnetGroups', [])
marker = trimmed.get('Marker', None)
if not groups:
log.debug('No ElastiCache subnet groups found.')
return groups
except boto.exception.BotoServerError as e:
log.error(e)
return [] |
def get_or_init_instance(self, instance_loader, row):
"""
Either fetches an already existing instance or initializes a new one.
"""
instance = self.get_instance(instance_loader, row)
if instance:
return (instance, False)
else:
return (self.init_instance(row), True) | Either fetches an already existing instance or initializes a new one. | Below is the the instruction that describes the task:
### Input:
Either fetches an already existing instance or initializes a new one.
### Response:
def get_or_init_instance(self, instance_loader, row):
"""
Either fetches an already existing instance or initializes a new one.
"""
instance = self.get_instance(instance_loader, row)
if instance:
return (instance, False)
else:
return (self.init_instance(row), True) |
def dump(self, file, payload):
"""Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None.
"""
json.dump(payload, file, indent=2, ensure_ascii=False) | Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None. | Below is the the instruction that describes the task:
### Input:
Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None.
### Response:
def dump(self, file, payload):
"""Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None.
"""
json.dump(payload, file, indent=2, ensure_ascii=False) |
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):
"""
Convert result from datetime_to_dtstr to datetime in timezone UTC0.
"""
try:
dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)
if to_tz:
dt = timezone.make_aware(dt, timezone=pytz.UTC)
if to_tz != pytz.UTC:
dt = dt.astimezone(to_tz)
return dt
except ValueError, e:
if not fail_silently:
raise e
return None | Convert result from datetime_to_dtstr to datetime in timezone UTC0. | Below is the the instruction that describes the task:
### Input:
Convert result from datetime_to_dtstr to datetime in timezone UTC0.
### Response:
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):
"""
Convert result from datetime_to_dtstr to datetime in timezone UTC0.
"""
try:
dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)
if to_tz:
dt = timezone.make_aware(dt, timezone=pytz.UTC)
if to_tz != pytz.UTC:
dt = dt.astimezone(to_tz)
return dt
except ValueError, e:
if not fail_silently:
raise e
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.