code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def push_cached_cluster_configuration(self, mdmPassword, liaPassword, noUpload = False, noInstall= False, noConfigure = False):
"""
Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM)
Method: POST
Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords)
"""
self.logger.debug("push_cached_cluster_configuration(" + "{},{},{},{},{}".format(mdmPassword, liaPassword, noUpload, noInstall, noConfigure))
config_params = {'noUpload': noUpload, 'noInstall': noInstall, 'noConfigure':noConfigure}
#print "Push cached ScaleIO cluster configuration to IM"
self._cluster_config_cached.setMdmPassword(mdmPassword)
self._cluster_config_cached.setLiaPassword(liaPassword)
self.logger.debug("Push JSON data:")
self.logger.debug("{}".format(self._cluster_config_cached.to_JSON()))
####### FINISH METOD - CAN ONLY PUSH - USE CACHE
# SDS configured to use /home/scaleio1
#default_minimal_cluster_config = '{"installationId":null,"mdmIPs":["192.168.102.12","192.168.102.13"],"mdmPassword":"Scaleio123","liaPassword":"Scaleio123","licenseKey":null,"primaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.102.12"]},"secondaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.102.13"]},"tb":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"tbIPs":["192.168.102.11"]},"sdsList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.11]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.11"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.12]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.12"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.13]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.13"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072}],"sdcList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null}],"callHomeConfiguration":null,"remoteSyslogConfiguration":null}'
# Generated with scelio_object.py - Progammatically generated JSON using a set of classes that represent different ScaleIO components
default_minimal_cluster_config = '{"licenseKey": null, "mdmPassword": "Scaleio123", "mdmIPs": ["192.168.102.12", "192.168.102.13"], "sdsList": [{"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.11", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.11"]}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.12", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.12"]}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.13", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.13"]}], "liaPassword": "Scaleio123", "primaryMdm": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "managementIPs": [], "mdmIPs": ["192.168.102.12"]}, "callHomeConfiguration": null, "installationId": null, "secondaryMdm": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "managementIPs": [], "mdmIPs": ["192.168.102.13"]}, "sdcList": [{"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}], "tb": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "tbIPs": ["192.168.102.11"]}, "remoteSyslogConfiguration": null}'
#
#default_minimal_cluster_config = '{"installationId":null,"mdmIPs":["192.168.100.51","192.168.100.52"],"mdmPassword":"Password1!","liaPassword":"Password1!","licenseKey":null,"primaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.100.51"]},"secondaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.100.52"]},"tb":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"tbIPs":["192.168.100.53"]},"sdsList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.51]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.51"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.52]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.52"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.53]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.53"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072}],"sdcList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null}],"callHomeConfiguration":null,"remoteSyslogConfiguration":null}'
#print "JSON DUMP OF INSTALL CONFIG:"
#pprint (json.loads(default_minimal_cluster_config))
r1 = self._im_session.post(
"{}/{}".format(self._im_api_url,"types/Installation/instances/"),
headers={'Content-type':'application/json','Version':'1.0'},
params = config_params,
verify=self._im_verify_ssl,
#json=json.loads(self._cluster_config_cached.to_JSON()),
json = json.loads(default_minimal_cluster_config),
stream=True
)
if not r1.ok:
# Something went wrong
self.logger.error("Error push_cached_cluster_configuration()")
#print "Response after push_cached_cluster_configuration()"
# RESPONSE NEED TO BE WRAPPED IN tey/catch. Can?t assume JSON is returned.
self.logger.debug("HTTP Response:")
self.logger.debug("{}".format(r1.text))
return r1.text | Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM)
Method: POST
Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords) | Below is the the instruction that describes the task:
### Input:
Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM)
Method: POST
Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords)
### Response:
def push_cached_cluster_configuration(self, mdmPassword, liaPassword, noUpload = False, noInstall= False, noConfigure = False):
"""
Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM)
Method: POST
Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords)
"""
self.logger.debug("push_cached_cluster_configuration(" + "{},{},{},{},{}".format(mdmPassword, liaPassword, noUpload, noInstall, noConfigure))
config_params = {'noUpload': noUpload, 'noInstall': noInstall, 'noConfigure':noConfigure}
#print "Push cached ScaleIO cluster configuration to IM"
self._cluster_config_cached.setMdmPassword(mdmPassword)
self._cluster_config_cached.setLiaPassword(liaPassword)
self.logger.debug("Push JSON data:")
self.logger.debug("{}".format(self._cluster_config_cached.to_JSON()))
####### FINISH METOD - CAN ONLY PUSH - USE CACHE
# SDS configured to use /home/scaleio1
#default_minimal_cluster_config = '{"installationId":null,"mdmIPs":["192.168.102.12","192.168.102.13"],"mdmPassword":"Scaleio123","liaPassword":"Scaleio123","licenseKey":null,"primaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.102.12"]},"secondaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.102.13"]},"tb":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"tbIPs":["192.168.102.11"]},"sdsList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.11]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.11"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.12]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.12"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.102.13]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.102.13"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/home/vagrant/scaleio1","storagePool":null,"deviceName":null}],"optimized":false,"port":7072}],"sdcList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.11"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.12"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.102.13"],"domain":null,"userName":"root","password":"vagrant","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null}],"callHomeConfiguration":null,"remoteSyslogConfiguration":null}'
# Generated with scelio_object.py - Progammatically generated JSON using a set of classes that represent different ScaleIO components
default_minimal_cluster_config = '{"licenseKey": null, "mdmPassword": "Scaleio123", "mdmIPs": ["192.168.102.12", "192.168.102.13"], "sdsList": [{"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.11", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.11"]}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.12", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.12"]}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "protectionDomain": "default", "nodeInfo": null, "sdsName": "SDS_192.168.102.13", "sdcOnlyIPs": [], "optimized": false, "devices": [{"devicePath": "/home/vagrant/scaleio1", "storagePool": null, "deviceName": null}], "faultSet": null, "port": "7072", "sdsOnlyIPs": [], "allIPs": ["192.168.102.13"]}], "liaPassword": "Scaleio123", "primaryMdm": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "managementIPs": [], "mdmIPs": ["192.168.102.12"]}, "callHomeConfiguration": null, "installationId": null, "secondaryMdm": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "managementIPs": [], "mdmIPs": ["192.168.102.13"]}, "sdcList": [{"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.12"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}, {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.13"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "splitterRpaIp": null}], "tb": {"node": {"userName": "root", "domain": null, "nodeName": null, "nodeIPs": ["192.168.102.11"], "liaPassword": null, "ostype": "linux", "password": "vagrant"}, "nodeInfo": null, "tbIPs": ["192.168.102.11"]}, "remoteSyslogConfiguration": null}'
#
#default_minimal_cluster_config = '{"installationId":null,"mdmIPs":["192.168.100.51","192.168.100.52"],"mdmPassword":"Password1!","liaPassword":"Password1!","licenseKey":null,"primaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.100.51"]},"secondaryMdm":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"managementIPs":null,"mdmIPs":["192.168.100.52"]},"tb":{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"tbIPs":["192.168.100.53"]},"sdsList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.51]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.51"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.52]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.52"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"sdsName":"SDS_[192.168.100.53]","protectionDomain":"default","faultSet":null,"allIPs":["192.168.100.53"],"sdsOnlyIPs":null,"sdcOnlyIPs":null,"devices":[{"devicePath":"/dev/sdb","storagePool":null,"deviceName":null}],"optimized":false,"port":7072}],"sdcList":[{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.51"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.52"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null},{"node":{"ostype":"linux","nodeName":null,"nodeIPs":["192.168.100.53"],"domain":null,"userName":"root","password":"password","liaPassword":null},"nodeInfo":null,"splitterRpaIp":null}],"callHomeConfiguration":null,"remoteSyslogConfiguration":null}'
#print "JSON DUMP OF INSTALL CONFIG:"
#pprint (json.loads(default_minimal_cluster_config))
r1 = self._im_session.post(
"{}/{}".format(self._im_api_url,"types/Installation/instances/"),
headers={'Content-type':'application/json','Version':'1.0'},
params = config_params,
verify=self._im_verify_ssl,
#json=json.loads(self._cluster_config_cached.to_JSON()),
json = json.loads(default_minimal_cluster_config),
stream=True
)
if not r1.ok:
# Something went wrong
self.logger.error("Error push_cached_cluster_configuration()")
#print "Response after push_cached_cluster_configuration()"
# RESPONSE NEED TO BE WRAPPED IN tey/catch. Can?t assume JSON is returned.
self.logger.debug("HTTP Response:")
self.logger.debug("{}".format(r1.text))
return r1.text |
def policy(self, args):
"""
setter for the policy descriptor
"""
word = args[0]
if word == 'reject':
self.accepted_ports = None
self.rejected_ports = []
target = self.rejected_ports
elif word == 'accept':
self.accepted_ports = []
self.rejected_ports = None
target = self.accepted_ports
else:
raise RuntimeError("Don't understand policy word \"%s\"" % word)
for port in args[1].split(','):
if '-' in port:
(a, b) = port.split('-')
target.append(PortRange(int(a), int(b)))
else:
target.append(int(port)) | setter for the policy descriptor | Below is the the instruction that describes the task:
### Input:
setter for the policy descriptor
### Response:
def policy(self, args):
"""
setter for the policy descriptor
"""
word = args[0]
if word == 'reject':
self.accepted_ports = None
self.rejected_ports = []
target = self.rejected_ports
elif word == 'accept':
self.accepted_ports = []
self.rejected_ports = None
target = self.accepted_ports
else:
raise RuntimeError("Don't understand policy word \"%s\"" % word)
for port in args[1].split(','):
if '-' in port:
(a, b) = port.split('-')
target.append(PortRange(int(a), int(b)))
else:
target.append(int(port)) |
def get_relaxation(self, level, objective=None, inequalities=None,
equalities=None, substitutions=None,
momentinequalities=None, momentequalities=None,
momentsubstitutions=None,
removeequalities=False, extramonomials=None,
extramomentmatrices=None, extraobjexpr=None,
localizing_monomials=None, chordal_extension=False):
"""Get the SDP relaxation of a noncommutative polynomial optimization
problem.
:param level: The level of the relaxation. The value -1 will skip
automatic monomial generation and use only the monomials
supplied by the option `extramonomials`.
:type level: int.
:param obj: Optional parameter to describe the objective function.
:type obj: :class:`sympy.core.exp.Expr`.
:param inequalities: Optional parameter to list inequality constraints.
:type inequalities: list of :class:`sympy.core.exp.Expr`.
:param equalities: Optional parameter to list equality constraints.
:type equalities: list of :class:`sympy.core.exp.Expr`.
:param substitutions: Optional parameter containing monomials that can
be replaced (e.g., idempotent variables).
:type substitutions: dict of :class:`sympy.core.exp.Expr`.
:param momentinequalities: Optional parameter of inequalities defined
on moments.
:type momentinequalities: list of :class:`sympy.core.exp.Expr`.
:param momentequalities: Optional parameter of equalities defined
on moments.
:type momentequalities: list of :class:`sympy.core.exp.Expr`.
:param momentsubstitutions: Optional parameter containing moments that
can be replaced.
:type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`.
:param removeequalities: Optional parameter to attempt removing the
equalities by solving the linear equations.
:type removeequalities: bool.
:param extramonomials: Optional paramter of monomials to be included,
on top of the requested level of relaxation.
:type extramonomials: list of :class:`sympy.core.exp.Expr`.
:param extramomentmatrices: Optional paramter of duplicating or adding
moment matrices. A new moment matrix can be
unconstrained (""), a copy of the first one
("copy"), and satisfying a partial positivity
constraint ("ppt"). Each new moment matrix is
requested as a list of string of these options.
For instance, adding a single new moment matrix
as a copy of the first would be
``extramomentmatrices=[["copy"]]``.
:type extramomentmatrices: list of list of str.
:param extraobjexpr: Optional parameter of a string expression of a
linear combination of moment matrix elements to be
included in the objective function.
:type extraobjexpr: str.
:param localizing_monomials: Optional parameter to specify sets of
localizing monomials for each constraint.
The internal order of constraints is
inequalities first, followed by the
equalities. If the parameter is specified,
but for a certain constraint the automatic
localization is requested, leave None in
its place in this parameter.
:type localizing_monomials: list of list of `sympy.core.exp.Expr`.
:param chordal_extension: Optional parameter to request a sparse
chordal extension.
:type chordal_extension: bool.
"""
if self.level < -1:
raise Exception("Invalid level of relaxation")
self.level = level
if substitutions is None:
self.substitutions = {}
else:
self.substitutions = substitutions
for lhs, rhs in substitutions.items():
if not is_pure_substitution_rule(lhs, rhs):
self.pure_substitution_rules = False
if iscomplex(lhs) or iscomplex(rhs):
self.complex_matrix = True
if momentsubstitutions is not None:
self.moment_substitutions = momentsubstitutions.copy()
# If we have a real-valued problem, the moment matrix is symmetric
# and moment substitutions also apply to the conjugate monomials
if not self.complex_matrix:
for key, val in self.moment_substitutions.copy().items():
adjoint_monomial = apply_substitutions(key.adjoint(),
self.substitutions)
self.moment_substitutions[adjoint_monomial] = val
if chordal_extension:
self.variables = find_variable_cliques(self.variables, objective,
inequalities, equalities,
momentinequalities,
momentequalities)
self.__generate_monomial_sets(extramonomials)
self.localizing_monomial_sets = localizing_monomials
# Figure out basic structure of the SDP
self._calculate_block_structure(inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrices,
removeequalities)
self._estimate_n_vars()
if extramomentmatrices is not None:
for parameters in extramomentmatrices:
copy = False
for parameter in parameters:
if parameter == "copy":
copy = True
if copy:
self.n_vars += self.n_vars + 1
else:
self.n_vars += (self.block_struct[0]**2)/2
if self.complex_matrix:
dtype = np.complex128
else:
dtype = np.float64
self.F = lil_matrix((sum([bs**2 for bs in self.block_struct]),
self.n_vars + 1), dtype=dtype)
if self.verbose > 0:
print(('Estimated number of SDP variables: %d' % self.n_vars))
print('Generating moment matrix...')
# Generate moment matrices
new_n_vars, block_index = self.__add_parameters()
self._time0 = time.time()
new_n_vars, block_index = \
self._generate_all_moment_matrix_blocks(new_n_vars, block_index)
if extramomentmatrices is not None:
new_n_vars, block_index = \
self.__add_extra_momentmatrices(extramomentmatrices,
new_n_vars, block_index)
# The initial estimate for the size of F was overly generous.
self.n_vars = new_n_vars
# We don't correct the size of F, because that would trigger
# memory copies, and extra columns in lil_matrix are free anyway.
# self.F = self.F[:, 0:self.n_vars + 1]
if self.verbose > 0:
print(('Reduced number of SDP variables: %d' % self.n_vars))
# Objective function
self.set_objective(objective, extraobjexpr)
# Process constraints
self.constraint_starting_block = block_index
self.process_constraints(inequalities, equalities, momentinequalities,
momentequalities, block_index,
removeequalities) | Get the SDP relaxation of a noncommutative polynomial optimization
problem.
:param level: The level of the relaxation. The value -1 will skip
automatic monomial generation and use only the monomials
supplied by the option `extramonomials`.
:type level: int.
:param obj: Optional parameter to describe the objective function.
:type obj: :class:`sympy.core.exp.Expr`.
:param inequalities: Optional parameter to list inequality constraints.
:type inequalities: list of :class:`sympy.core.exp.Expr`.
:param equalities: Optional parameter to list equality constraints.
:type equalities: list of :class:`sympy.core.exp.Expr`.
:param substitutions: Optional parameter containing monomials that can
be replaced (e.g., idempotent variables).
:type substitutions: dict of :class:`sympy.core.exp.Expr`.
:param momentinequalities: Optional parameter of inequalities defined
on moments.
:type momentinequalities: list of :class:`sympy.core.exp.Expr`.
:param momentequalities: Optional parameter of equalities defined
on moments.
:type momentequalities: list of :class:`sympy.core.exp.Expr`.
:param momentsubstitutions: Optional parameter containing moments that
can be replaced.
:type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`.
:param removeequalities: Optional parameter to attempt removing the
equalities by solving the linear equations.
:type removeequalities: bool.
:param extramonomials: Optional paramter of monomials to be included,
on top of the requested level of relaxation.
:type extramonomials: list of :class:`sympy.core.exp.Expr`.
:param extramomentmatrices: Optional paramter of duplicating or adding
moment matrices. A new moment matrix can be
unconstrained (""), a copy of the first one
("copy"), and satisfying a partial positivity
constraint ("ppt"). Each new moment matrix is
requested as a list of string of these options.
For instance, adding a single new moment matrix
as a copy of the first would be
``extramomentmatrices=[["copy"]]``.
:type extramomentmatrices: list of list of str.
:param extraobjexpr: Optional parameter of a string expression of a
linear combination of moment matrix elements to be
included in the objective function.
:type extraobjexpr: str.
:param localizing_monomials: Optional parameter to specify sets of
localizing monomials for each constraint.
The internal order of constraints is
inequalities first, followed by the
equalities. If the parameter is specified,
but for a certain constraint the automatic
localization is requested, leave None in
its place in this parameter.
:type localizing_monomials: list of list of `sympy.core.exp.Expr`.
:param chordal_extension: Optional parameter to request a sparse
chordal extension.
:type chordal_extension: bool. | Below is the the instruction that describes the task:
### Input:
Get the SDP relaxation of a noncommutative polynomial optimization
problem.
:param level: The level of the relaxation. The value -1 will skip
automatic monomial generation and use only the monomials
supplied by the option `extramonomials`.
:type level: int.
:param obj: Optional parameter to describe the objective function.
:type obj: :class:`sympy.core.exp.Expr`.
:param inequalities: Optional parameter to list inequality constraints.
:type inequalities: list of :class:`sympy.core.exp.Expr`.
:param equalities: Optional parameter to list equality constraints.
:type equalities: list of :class:`sympy.core.exp.Expr`.
:param substitutions: Optional parameter containing monomials that can
be replaced (e.g., idempotent variables).
:type substitutions: dict of :class:`sympy.core.exp.Expr`.
:param momentinequalities: Optional parameter of inequalities defined
on moments.
:type momentinequalities: list of :class:`sympy.core.exp.Expr`.
:param momentequalities: Optional parameter of equalities defined
on moments.
:type momentequalities: list of :class:`sympy.core.exp.Expr`.
:param momentsubstitutions: Optional parameter containing moments that
can be replaced.
:type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`.
:param removeequalities: Optional parameter to attempt removing the
equalities by solving the linear equations.
:type removeequalities: bool.
:param extramonomials: Optional paramter of monomials to be included,
on top of the requested level of relaxation.
:type extramonomials: list of :class:`sympy.core.exp.Expr`.
:param extramomentmatrices: Optional paramter of duplicating or adding
moment matrices. A new moment matrix can be
unconstrained (""), a copy of the first one
("copy"), and satisfying a partial positivity
constraint ("ppt"). Each new moment matrix is
requested as a list of string of these options.
For instance, adding a single new moment matrix
as a copy of the first would be
``extramomentmatrices=[["copy"]]``.
:type extramomentmatrices: list of list of str.
:param extraobjexpr: Optional parameter of a string expression of a
linear combination of moment matrix elements to be
included in the objective function.
:type extraobjexpr: str.
:param localizing_monomials: Optional parameter to specify sets of
localizing monomials for each constraint.
The internal order of constraints is
inequalities first, followed by the
equalities. If the parameter is specified,
but for a certain constraint the automatic
localization is requested, leave None in
its place in this parameter.
:type localizing_monomials: list of list of `sympy.core.exp.Expr`.
:param chordal_extension: Optional parameter to request a sparse
chordal extension.
:type chordal_extension: bool.
### Response:
def get_relaxation(self, level, objective=None, inequalities=None,
equalities=None, substitutions=None,
momentinequalities=None, momentequalities=None,
momentsubstitutions=None,
removeequalities=False, extramonomials=None,
extramomentmatrices=None, extraobjexpr=None,
localizing_monomials=None, chordal_extension=False):
"""Get the SDP relaxation of a noncommutative polynomial optimization
problem.
:param level: The level of the relaxation. The value -1 will skip
automatic monomial generation and use only the monomials
supplied by the option `extramonomials`.
:type level: int.
:param obj: Optional parameter to describe the objective function.
:type obj: :class:`sympy.core.exp.Expr`.
:param inequalities: Optional parameter to list inequality constraints.
:type inequalities: list of :class:`sympy.core.exp.Expr`.
:param equalities: Optional parameter to list equality constraints.
:type equalities: list of :class:`sympy.core.exp.Expr`.
:param substitutions: Optional parameter containing monomials that can
be replaced (e.g., idempotent variables).
:type substitutions: dict of :class:`sympy.core.exp.Expr`.
:param momentinequalities: Optional parameter of inequalities defined
on moments.
:type momentinequalities: list of :class:`sympy.core.exp.Expr`.
:param momentequalities: Optional parameter of equalities defined
on moments.
:type momentequalities: list of :class:`sympy.core.exp.Expr`.
:param momentsubstitutions: Optional parameter containing moments that
can be replaced.
:type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`.
:param removeequalities: Optional parameter to attempt removing the
equalities by solving the linear equations.
:type removeequalities: bool.
:param extramonomials: Optional paramter of monomials to be included,
on top of the requested level of relaxation.
:type extramonomials: list of :class:`sympy.core.exp.Expr`.
:param extramomentmatrices: Optional paramter of duplicating or adding
moment matrices. A new moment matrix can be
unconstrained (""), a copy of the first one
("copy"), and satisfying a partial positivity
constraint ("ppt"). Each new moment matrix is
requested as a list of string of these options.
For instance, adding a single new moment matrix
as a copy of the first would be
``extramomentmatrices=[["copy"]]``.
:type extramomentmatrices: list of list of str.
:param extraobjexpr: Optional parameter of a string expression of a
linear combination of moment matrix elements to be
included in the objective function.
:type extraobjexpr: str.
:param localizing_monomials: Optional parameter to specify sets of
localizing monomials for each constraint.
The internal order of constraints is
inequalities first, followed by the
equalities. If the parameter is specified,
but for a certain constraint the automatic
localization is requested, leave None in
its place in this parameter.
:type localizing_monomials: list of list of `sympy.core.exp.Expr`.
:param chordal_extension: Optional parameter to request a sparse
chordal extension.
:type chordal_extension: bool.
"""
if self.level < -1:
raise Exception("Invalid level of relaxation")
self.level = level
if substitutions is None:
self.substitutions = {}
else:
self.substitutions = substitutions
for lhs, rhs in substitutions.items():
if not is_pure_substitution_rule(lhs, rhs):
self.pure_substitution_rules = False
if iscomplex(lhs) or iscomplex(rhs):
self.complex_matrix = True
if momentsubstitutions is not None:
self.moment_substitutions = momentsubstitutions.copy()
# If we have a real-valued problem, the moment matrix is symmetric
# and moment substitutions also apply to the conjugate monomials
if not self.complex_matrix:
for key, val in self.moment_substitutions.copy().items():
adjoint_monomial = apply_substitutions(key.adjoint(),
self.substitutions)
self.moment_substitutions[adjoint_monomial] = val
if chordal_extension:
self.variables = find_variable_cliques(self.variables, objective,
inequalities, equalities,
momentinequalities,
momentequalities)
self.__generate_monomial_sets(extramonomials)
self.localizing_monomial_sets = localizing_monomials
# Figure out basic structure of the SDP
self._calculate_block_structure(inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrices,
removeequalities)
self._estimate_n_vars()
if extramomentmatrices is not None:
for parameters in extramomentmatrices:
copy = False
for parameter in parameters:
if parameter == "copy":
copy = True
if copy:
self.n_vars += self.n_vars + 1
else:
self.n_vars += (self.block_struct[0]**2)/2
if self.complex_matrix:
dtype = np.complex128
else:
dtype = np.float64
self.F = lil_matrix((sum([bs**2 for bs in self.block_struct]),
self.n_vars + 1), dtype=dtype)
if self.verbose > 0:
print(('Estimated number of SDP variables: %d' % self.n_vars))
print('Generating moment matrix...')
# Generate moment matrices
new_n_vars, block_index = self.__add_parameters()
self._time0 = time.time()
new_n_vars, block_index = \
self._generate_all_moment_matrix_blocks(new_n_vars, block_index)
if extramomentmatrices is not None:
new_n_vars, block_index = \
self.__add_extra_momentmatrices(extramomentmatrices,
new_n_vars, block_index)
# The initial estimate for the size of F was overly generous.
self.n_vars = new_n_vars
# We don't correct the size of F, because that would trigger
# memory copies, and extra columns in lil_matrix are free anyway.
# self.F = self.F[:, 0:self.n_vars + 1]
if self.verbose > 0:
print(('Reduced number of SDP variables: %d' % self.n_vars))
# Objective function
self.set_objective(objective, extraobjexpr)
# Process constraints
self.constraint_starting_block = block_index
self.process_constraints(inequalities, equalities, momentinequalities,
momentequalities, block_index,
removeequalities) |
async def _send_generic_template(self, request: Request, stack: Stack):
"""
Generates and send a generic template.
"""
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
'attachment': {
'type': 'template',
'payload': payload
}
}
await self._add_qr(stack, msg, request)
await self._send(request, msg, stack) | Generates and send a generic template. | Below is the the instruction that describes the task:
### Input:
Generates and send a generic template.
### Response:
async def _send_generic_template(self, request: Request, stack: Stack):
"""
Generates and send a generic template.
"""
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
'attachment': {
'type': 'template',
'payload': payload
}
}
await self._add_qr(stack, msg, request)
await self._send(request, msg, stack) |
def create_unique_transfer_operation_id(ase):
# type: (blobxfer.models.azure.StorageEntity) -> str
"""Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity ase: storage entity
:rtype: str
:return: unique transfer id
"""
return ';'.join(
(ase._client.primary_endpoint, ase.path, str(ase.vectored_io))
) | Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity ase: storage entity
:rtype: str
:return: unique transfer id | Below is the the instruction that describes the task:
### Input:
Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity ase: storage entity
:rtype: str
:return: unique transfer id
### Response:
def create_unique_transfer_operation_id(ase):
# type: (blobxfer.models.azure.StorageEntity) -> str
"""Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity ase: storage entity
:rtype: str
:return: unique transfer id
"""
return ';'.join(
(ase._client.primary_endpoint, ase.path, str(ase.vectored_io))
) |
def _add_plots_to_output(out, data):
"""Add CNVkit plots summarizing called copy number values.
"""
out["plot"] = {}
diagram_plot = _add_diagram_plot(out, data)
if diagram_plot:
out["plot"]["diagram"] = diagram_plot
scatter = _add_scatter_plot(out, data)
if scatter:
out["plot"]["scatter"] = scatter
scatter_global = _add_global_scatter_plot(out, data)
if scatter_global:
out["plot"]["scatter_global"] = scatter_global
return out | Add CNVkit plots summarizing called copy number values. | Below is the the instruction that describes the task:
### Input:
Add CNVkit plots summarizing called copy number values.
### Response:
def _add_plots_to_output(out, data):
"""Add CNVkit plots summarizing called copy number values.
"""
out["plot"] = {}
diagram_plot = _add_diagram_plot(out, data)
if diagram_plot:
out["plot"]["diagram"] = diagram_plot
scatter = _add_scatter_plot(out, data)
if scatter:
out["plot"]["scatter"] = scatter
scatter_global = _add_global_scatter_plot(out, data)
if scatter_global:
out["plot"]["scatter_global"] = scatter_global
return out |
def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using warehouse api to find all of the "releases" """
url = '/'.join((index_url, project_name, 'json'))
response = requests.get(url, verify=requests_verify)
if response.status_code == 200:
return response.json()['releases'].keys()
return None | Query the pypi index at index_url using warehouse api to find all of the "releases" | Below is the the instruction that describes the task:
### Input:
Query the pypi index at index_url using warehouse api to find all of the "releases"
### Response:
def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using warehouse api to find all of the "releases" """
url = '/'.join((index_url, project_name, 'json'))
response = requests.get(url, verify=requests_verify)
if response.status_code == 200:
return response.json()['releases'].keys()
return None |
def wrap(self, data, many):
"""Wrap response in envelope."""
if not many:
return data
else:
data = {'parts': data}
multipart = self.context.get('multipart')
if multipart:
data.update(MultipartObjectSchema(context={
'bucket': multipart.bucket}).dump(multipart).data)
return data | Wrap response in envelope. | Below is the the instruction that describes the task:
### Input:
Wrap response in envelope.
### Response:
def wrap(self, data, many):
"""Wrap response in envelope."""
if not many:
return data
else:
data = {'parts': data}
multipart = self.context.get('multipart')
if multipart:
data.update(MultipartObjectSchema(context={
'bucket': multipart.bucket}).dump(multipart).data)
return data |
def box(self, bottom_left_corner, top_right_corner, paint=None, blank=False):
''' creates the visual frame/box in which we place the graph '''
path = [
bottom_left_corner,
Point(bottom_left_corner.x, top_right_corner.y),
top_right_corner,
Point(top_right_corner.x, bottom_left_corner.y),
bottom_left_corner
]
# use the bottom left corner as the starting point
last_point = bottom_left_corner
for idx, point in enumerate(path):
# skipping the first item because we use it as starting point
if idx != 0:
self.line(last_point, point, paint=paint, character=" " if blank else None)
last_point = point | creates the visual frame/box in which we place the graph | Below is the the instruction that describes the task:
### Input:
creates the visual frame/box in which we place the graph
### Response:
def box(self, bottom_left_corner, top_right_corner, paint=None, blank=False):
''' creates the visual frame/box in which we place the graph '''
path = [
bottom_left_corner,
Point(bottom_left_corner.x, top_right_corner.y),
top_right_corner,
Point(top_right_corner.x, bottom_left_corner.y),
bottom_left_corner
]
# use the bottom left corner as the starting point
last_point = bottom_left_corner
for idx, point in enumerate(path):
# skipping the first item because we use it as starting point
if idx != 0:
self.line(last_point, point, paint=paint, character=" " if blank else None)
last_point = point |
def decode_body(cls, header, f):
"""Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttPubrel(packet_id) | Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``. | Below is the the instruction that describes the task:
### Input:
Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``.
### Response:
def decode_body(cls, header, f):
"""Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttPubrel(packet_id) |
def recv(self, timeout=None):
"""Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:
if an error occurred while reading
"""
start = time()
time_left = timeout
while True:
# try to get a message
msg, already_filtered = self._recv_internal(timeout=time_left)
# return it, if it matches
if msg and (already_filtered or self._matches_filters(msg)):
LOG.log(self.RECV_LOGGING_LEVEL, 'Received: %s', msg)
return msg
# if not, and timeout is None, try indefinitely
elif timeout is None:
continue
# try next one only if there still is time, and with
# reduced timeout
else:
time_left = timeout - (time() - start)
if time_left > 0:
continue
else:
return None | Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:
if an error occurred while reading | Below is the the instruction that describes the task:
### Input:
Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:
if an error occurred while reading
### Response:
def recv(self, timeout=None):
"""Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:
if an error occurred while reading
"""
start = time()
time_left = timeout
while True:
# try to get a message
msg, already_filtered = self._recv_internal(timeout=time_left)
# return it, if it matches
if msg and (already_filtered or self._matches_filters(msg)):
LOG.log(self.RECV_LOGGING_LEVEL, 'Received: %s', msg)
return msg
# if not, and timeout is None, try indefinitely
elif timeout is None:
continue
# try next one only if there still is time, and with
# reduced timeout
else:
time_left = timeout - (time() - start)
if time_left > 0:
continue
else:
return None |
def decompress(f):
"""Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed\n' string.
"""
r = meta(f.read(60))
return r, decomprest(f, r[4]) | Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed\n' string. | Below is the the instruction that describes the task:
### Input:
Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed\n' string.
### Response:
def decompress(f):
"""Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed\n' string.
"""
r = meta(f.read(60))
return r, decomprest(f, r[4]) |
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
] | Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int | Below is the the instruction that describes the task:
### Input:
Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
### Response:
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
] |
def flatten_multi_dim(sequence):
"""Flatten a multi-dimensional array-like to a single dimensional sequence
(as a generator).
"""
for x in sequence:
if (isinstance(x, collections.Iterable)
and not isinstance(x, six.string_types)):
for y in flatten_multi_dim(x):
yield y
else:
yield x | Flatten a multi-dimensional array-like to a single dimensional sequence
(as a generator). | Below is the the instruction that describes the task:
### Input:
Flatten a multi-dimensional array-like to a single dimensional sequence
(as a generator).
### Response:
def flatten_multi_dim(sequence):
"""Flatten a multi-dimensional array-like to a single dimensional sequence
(as a generator).
"""
for x in sequence:
if (isinstance(x, collections.Iterable)
and not isinstance(x, six.string_types)):
for y in flatten_multi_dim(x):
yield y
else:
yield x |
def simxGetObjectOrientation(clientID, objectHandle, relativeToObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
eulerAngles = (ct.c_float*3)()
ret = c_GetObjectOrientation(clientID, objectHandle, relativeToObjectHandle, eulerAngles, operationMode)
arr = []
for i in range(3):
arr.append(eulerAngles[i])
return ret, arr | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxGetObjectOrientation(clientID, objectHandle, relativeToObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
eulerAngles = (ct.c_float*3)()
ret = c_GetObjectOrientation(clientID, objectHandle, relativeToObjectHandle, eulerAngles, operationMode)
arr = []
for i in range(3):
arr.append(eulerAngles[i])
return ret, arr |
def get(cls, user_id, client_id):
"""Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
"""
return cls.query.filter_by(
user_id=user_id,
client_id=client_id,
).first() | Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. | Below is the the instruction that describes the task:
### Input:
Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
### Response:
def get(cls, user_id, client_id):
"""Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
"""
return cls.query.filter_by(
user_id=user_id,
client_id=client_id,
).first() |
def target_str(self):
"""Returns the string representation of the target property."""
if isinstance(self.target, tuple):
return "({})".format(", ".join(self.target))
else:
return self.target | Returns the string representation of the target property. | Below is the the instruction that describes the task:
### Input:
Returns the string representation of the target property.
### Response:
def target_str(self):
"""Returns the string representation of the target property."""
if isinstance(self.target, tuple):
return "({})".format(", ".join(self.target))
else:
return self.target |
def equal(lhs, rhs):
"""Returns the result of element-wise **equal to** (==) comparison operation with
broadcasting.
For each element in input arrays, return 1(true) if corresponding elements are same,
otherwise return 0(false).
Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array to be compared.
rhs : scalar or mxnet.ndarray.array
Second array to be compared. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
Output array of boolean values.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
[ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0., 1.]], dtype=float32)
>>> (x == 1).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x == y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> mx.nd.equal(x,y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1., 0.],
[ 0., 1.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_equal,
lambda x, y: 1 if x == y else 0,
_internal._equal_scalar,
None) | Returns the result of element-wise **equal to** (==) comparison operation with
broadcasting.
For each element in input arrays, return 1(true) if corresponding elements are same,
otherwise return 0(false).
Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array to be compared.
rhs : scalar or mxnet.ndarray.array
Second array to be compared. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
Output array of boolean values.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
[ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0., 1.]], dtype=float32)
>>> (x == 1).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x == y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> mx.nd.equal(x,y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1., 0.],
[ 0., 1.]], dtype=float32) | Below is the the instruction that describes the task:
### Input:
Returns the result of element-wise **equal to** (==) comparison operation with
broadcasting.
For each element in input arrays, return 1(true) if corresponding elements are same,
otherwise return 0(false).
Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array to be compared.
rhs : scalar or mxnet.ndarray.array
Second array to be compared. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
Output array of boolean values.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
[ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0., 1.]], dtype=float32)
>>> (x == 1).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x == y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> mx.nd.equal(x,y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1., 0.],
[ 0., 1.]], dtype=float32)
### Response:
def equal(lhs, rhs):
"""Returns the result of element-wise **equal to** (==) comparison operation with
broadcasting.
For each element in input arrays, return 1(true) if corresponding elements are same,
otherwise return 0(false).
Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array to be compared.
rhs : scalar or mxnet.ndarray.array
Second array to be compared. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
Output array of boolean values.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
[ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0., 1.]], dtype=float32)
>>> (x == 1).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x == y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> mx.nd.equal(x,y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1., 0.],
[ 0., 1.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_equal,
lambda x, y: 1 if x == y else 0,
_internal._equal_scalar,
None) |
def validate_regex(regex, sub_service):
"""Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements.
"""
# The regex generated by stackinabox starts with ^
# and ends with $. Enforce that the provided regex does the same.
if regex.pattern.startswith('^') is False:
logger.debug('StackInABoxService: Pattern must start with ^')
raise InvalidRouteRegexError('Pattern must start with ^')
# Note: pattern may end with $ even if sub_service is True
if regex.pattern.endswith('$') is False and sub_service is False:
logger.debug('StackInABoxService: Pattern must end with $')
raise InvalidRouteRegexError('Pattern must end with $')
# Enforce that if the pattern does not end with $ that it is a service
if regex.pattern.endswith('$') is True and sub_service is True:
logger.debug(
'StackInABoxService: Sub-Service RegEx Pattern must not '
'end with $')
raise InvalidRouteRegexError('Pattern must end with $') | Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements. | Below is the the instruction that describes the task:
### Input:
Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements.
### Response:
def validate_regex(regex, sub_service):
"""Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements.
"""
# The regex generated by stackinabox starts with ^
# and ends with $. Enforce that the provided regex does the same.
if regex.pattern.startswith('^') is False:
logger.debug('StackInABoxService: Pattern must start with ^')
raise InvalidRouteRegexError('Pattern must start with ^')
# Note: pattern may end with $ even if sub_service is True
if regex.pattern.endswith('$') is False and sub_service is False:
logger.debug('StackInABoxService: Pattern must end with $')
raise InvalidRouteRegexError('Pattern must end with $')
# Enforce that if the pattern does not end with $ that it is a service
if regex.pattern.endswith('$') is True and sub_service is True:
logger.debug(
'StackInABoxService: Sub-Service RegEx Pattern must not '
'end with $')
raise InvalidRouteRegexError('Pattern must end with $') |
def bss_eval_sources(reference_sources, estimated_sources,
compute_permutation=True):
"""
Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter distortion of length
512, as described in Section III.B of [#vincent2006performance]_.
Passing ``False`` for ``compute_permutation`` will improve the computation
performance of the evaluation; however, it is not always appropriate and
is not the way that the BSS_EVAL Matlab toolbox computes bss_eval_sources.
Examples
--------
>>> # reference_sources[n] should be an ndarray of samples of the
>>> # n'th reference source
>>> # estimated_sources[n] should be the same for the n'th estimated
>>> # source
>>> (sdr, sir, sar,
... perm) = mir_eval.separation.bss_eval_sources(reference_sources,
... estimated_sources)
Parameters
----------
reference_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing true sources (must have same shape as
estimated_sources)
estimated_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing estimated sources (must have same shape as
reference_sources)
compute_permutation : bool, optional
compute permutation of estimate/source combinations (True by default)
Returns
-------
sdr : np.ndarray, shape=(nsrc,)
vector of Signal to Distortion Ratios (SDR)
sir : np.ndarray, shape=(nsrc,)
vector of Source to Interference Ratios (SIR)
sar : np.ndarray, shape=(nsrc,)
vector of Sources to Artifacts Ratios (SAR)
perm : np.ndarray, shape=(nsrc,)
vector containing the best ordering of estimated sources in
the mean SIR sense (estimated source number ``perm[j]`` corresponds to
true source number ``j``). Note: ``perm`` will be ``[0, 1, ...,
nsrc-1]`` if ``compute_permutation`` is ``False``.
References
----------
.. [#] Emmanuel Vincent, Shoko Araki, Fabian J. Theis, Guido Nolte, Pau
Bofill, Hiroshi Sawada, Alexey Ozerov, B. Vikrham Gowreesunker, Dominik
Lutter and Ngoc Q.K. Duong, "The Signal Separation Evaluation Campaign
(2007-2010): Achievements and remaining challenges", Signal Processing,
92, pp. 1928-1936, 2012.
"""
# make sure the input is of shape (nsrc, nsampl)
if estimated_sources.ndim == 1:
estimated_sources = estimated_sources[np.newaxis, :]
if reference_sources.ndim == 1:
reference_sources = reference_sources[np.newaxis, :]
validate(reference_sources, estimated_sources)
# If empty matrices were supplied, return empty lists (special case)
if reference_sources.size == 0 or estimated_sources.size == 0:
return np.array([]), np.array([]), np.array([]), np.array([])
nsrc = estimated_sources.shape[0]
# does user desire permutations?
if compute_permutation:
# compute criteria for all possible pair matches
sdr = np.empty((nsrc, nsrc))
sir = np.empty((nsrc, nsrc))
sar = np.empty((nsrc, nsrc))
for jest in range(nsrc):
for jtrue in range(nsrc):
s_true, e_spat, e_interf, e_artif = \
_bss_decomp_mtifilt(reference_sources,
estimated_sources[jest],
jtrue, 512)
sdr[jest, jtrue], sir[jest, jtrue], sar[jest, jtrue] = \
_bss_source_crit(s_true, e_spat, e_interf, e_artif)
# select the best ordering
perms = list(itertools.permutations(list(range(nsrc))))
mean_sir = np.empty(len(perms))
dum = np.arange(nsrc)
for (i, perm) in enumerate(perms):
mean_sir[i] = np.mean(sir[perm, dum])
popt = perms[np.argmax(mean_sir)]
idx = (popt, dum)
return (sdr[idx], sir[idx], sar[idx], np.asarray(popt))
else:
# compute criteria for only the simple correspondence
# (estimate 1 is estimate corresponding to reference source 1, etc.)
sdr = np.empty(nsrc)
sir = np.empty(nsrc)
sar = np.empty(nsrc)
for j in range(nsrc):
s_true, e_spat, e_interf, e_artif = \
_bss_decomp_mtifilt(reference_sources,
estimated_sources[j],
j, 512)
sdr[j], sir[j], sar[j] = \
_bss_source_crit(s_true, e_spat, e_interf, e_artif)
# return the default permutation for compatibility
popt = np.arange(nsrc)
return (sdr, sir, sar, popt) | Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter distortion of length
512, as described in Section III.B of [#vincent2006performance]_.
Passing ``False`` for ``compute_permutation`` will improve the computation
performance of the evaluation; however, it is not always appropriate and
is not the way that the BSS_EVAL Matlab toolbox computes bss_eval_sources.
Examples
--------
>>> # reference_sources[n] should be an ndarray of samples of the
>>> # n'th reference source
>>> # estimated_sources[n] should be the same for the n'th estimated
>>> # source
>>> (sdr, sir, sar,
... perm) = mir_eval.separation.bss_eval_sources(reference_sources,
... estimated_sources)
Parameters
----------
reference_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing true sources (must have same shape as
estimated_sources)
estimated_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing estimated sources (must have same shape as
reference_sources)
compute_permutation : bool, optional
compute permutation of estimate/source combinations (True by default)
Returns
-------
sdr : np.ndarray, shape=(nsrc,)
vector of Signal to Distortion Ratios (SDR)
sir : np.ndarray, shape=(nsrc,)
vector of Source to Interference Ratios (SIR)
sar : np.ndarray, shape=(nsrc,)
vector of Sources to Artifacts Ratios (SAR)
perm : np.ndarray, shape=(nsrc,)
vector containing the best ordering of estimated sources in
the mean SIR sense (estimated source number ``perm[j]`` corresponds to
true source number ``j``). Note: ``perm`` will be ``[0, 1, ...,
nsrc-1]`` if ``compute_permutation`` is ``False``.
References
----------
.. [#] Emmanuel Vincent, Shoko Araki, Fabian J. Theis, Guido Nolte, Pau
Bofill, Hiroshi Sawada, Alexey Ozerov, B. Vikrham Gowreesunker, Dominik
Lutter and Ngoc Q.K. Duong, "The Signal Separation Evaluation Campaign
(2007-2010): Achievements and remaining challenges", Signal Processing,
92, pp. 1928-1936, 2012. | Below is the the instruction that describes the task:
### Input:
Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter distortion of length
512, as described in Section III.B of [#vincent2006performance]_.
Passing ``False`` for ``compute_permutation`` will improve the computation
performance of the evaluation; however, it is not always appropriate and
is not the way that the BSS_EVAL Matlab toolbox computes bss_eval_sources.
Examples
--------
>>> # reference_sources[n] should be an ndarray of samples of the
>>> # n'th reference source
>>> # estimated_sources[n] should be the same for the n'th estimated
>>> # source
>>> (sdr, sir, sar,
... perm) = mir_eval.separation.bss_eval_sources(reference_sources,
... estimated_sources)
Parameters
----------
reference_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing true sources (must have same shape as
estimated_sources)
estimated_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing estimated sources (must have same shape as
reference_sources)
compute_permutation : bool, optional
compute permutation of estimate/source combinations (True by default)
Returns
-------
sdr : np.ndarray, shape=(nsrc,)
vector of Signal to Distortion Ratios (SDR)
sir : np.ndarray, shape=(nsrc,)
vector of Source to Interference Ratios (SIR)
sar : np.ndarray, shape=(nsrc,)
vector of Sources to Artifacts Ratios (SAR)
perm : np.ndarray, shape=(nsrc,)
vector containing the best ordering of estimated sources in
the mean SIR sense (estimated source number ``perm[j]`` corresponds to
true source number ``j``). Note: ``perm`` will be ``[0, 1, ...,
nsrc-1]`` if ``compute_permutation`` is ``False``.
References
----------
.. [#] Emmanuel Vincent, Shoko Araki, Fabian J. Theis, Guido Nolte, Pau
Bofill, Hiroshi Sawada, Alexey Ozerov, B. Vikrham Gowreesunker, Dominik
Lutter and Ngoc Q.K. Duong, "The Signal Separation Evaluation Campaign
(2007-2010): Achievements and remaining challenges", Signal Processing,
92, pp. 1928-1936, 2012.
### Response:
def bss_eval_sources(reference_sources, estimated_sources,
compute_permutation=True):
"""
Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter distortion of length
512, as described in Section III.B of [#vincent2006performance]_.
Passing ``False`` for ``compute_permutation`` will improve the computation
performance of the evaluation; however, it is not always appropriate and
is not the way that the BSS_EVAL Matlab toolbox computes bss_eval_sources.
Examples
--------
>>> # reference_sources[n] should be an ndarray of samples of the
>>> # n'th reference source
>>> # estimated_sources[n] should be the same for the n'th estimated
>>> # source
>>> (sdr, sir, sar,
... perm) = mir_eval.separation.bss_eval_sources(reference_sources,
... estimated_sources)
Parameters
----------
reference_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing true sources (must have same shape as
estimated_sources)
estimated_sources : np.ndarray, shape=(nsrc, nsampl)
matrix containing estimated sources (must have same shape as
reference_sources)
compute_permutation : bool, optional
compute permutation of estimate/source combinations (True by default)
Returns
-------
sdr : np.ndarray, shape=(nsrc,)
vector of Signal to Distortion Ratios (SDR)
sir : np.ndarray, shape=(nsrc,)
vector of Source to Interference Ratios (SIR)
sar : np.ndarray, shape=(nsrc,)
vector of Sources to Artifacts Ratios (SAR)
perm : np.ndarray, shape=(nsrc,)
vector containing the best ordering of estimated sources in
the mean SIR sense (estimated source number ``perm[j]`` corresponds to
true source number ``j``). Note: ``perm`` will be ``[0, 1, ...,
nsrc-1]`` if ``compute_permutation`` is ``False``.
References
----------
.. [#] Emmanuel Vincent, Shoko Araki, Fabian J. Theis, Guido Nolte, Pau
Bofill, Hiroshi Sawada, Alexey Ozerov, B. Vikrham Gowreesunker, Dominik
Lutter and Ngoc Q.K. Duong, "The Signal Separation Evaluation Campaign
(2007-2010): Achievements and remaining challenges", Signal Processing,
92, pp. 1928-1936, 2012.
"""
# make sure the input is of shape (nsrc, nsampl)
if estimated_sources.ndim == 1:
estimated_sources = estimated_sources[np.newaxis, :]
if reference_sources.ndim == 1:
reference_sources = reference_sources[np.newaxis, :]
validate(reference_sources, estimated_sources)
# If empty matrices were supplied, return empty lists (special case)
if reference_sources.size == 0 or estimated_sources.size == 0:
return np.array([]), np.array([]), np.array([]), np.array([])
nsrc = estimated_sources.shape[0]
# does user desire permutations?
if compute_permutation:
# compute criteria for all possible pair matches
sdr = np.empty((nsrc, nsrc))
sir = np.empty((nsrc, nsrc))
sar = np.empty((nsrc, nsrc))
for jest in range(nsrc):
for jtrue in range(nsrc):
s_true, e_spat, e_interf, e_artif = \
_bss_decomp_mtifilt(reference_sources,
estimated_sources[jest],
jtrue, 512)
sdr[jest, jtrue], sir[jest, jtrue], sar[jest, jtrue] = \
_bss_source_crit(s_true, e_spat, e_interf, e_artif)
# select the best ordering
perms = list(itertools.permutations(list(range(nsrc))))
mean_sir = np.empty(len(perms))
dum = np.arange(nsrc)
for (i, perm) in enumerate(perms):
mean_sir[i] = np.mean(sir[perm, dum])
popt = perms[np.argmax(mean_sir)]
idx = (popt, dum)
return (sdr[idx], sir[idx], sar[idx], np.asarray(popt))
else:
# compute criteria for only the simple correspondence
# (estimate 1 is estimate corresponding to reference source 1, etc.)
sdr = np.empty(nsrc)
sir = np.empty(nsrc)
sar = np.empty(nsrc)
for j in range(nsrc):
s_true, e_spat, e_interf, e_artif = \
_bss_decomp_mtifilt(reference_sources,
estimated_sources[j],
j, 512)
sdr[j], sir[j], sar[j] = \
_bss_source_crit(s_true, e_spat, e_interf, e_artif)
# return the default permutation for compatibility
popt = np.arange(nsrc)
return (sdr, sir, sar, popt) |
def get_dataset(self, dataset=None, **kwargs):
"""
Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if dataset is not None:
kwargs['dataset'] = dataset
kwargs['context'] = 'dataset'
if 'kind' in kwargs.keys():
# since we switched how dataset kinds are named, let's just
# automatically handle switching to lowercase
kwargs['kind'] = kwargs['kind'].lower()
return self.filter(**kwargs) | Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | Below is the the instruction that describes the task:
### Input:
Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
### Response:
def get_dataset(self, dataset=None, **kwargs):
"""
Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if dataset is not None:
kwargs['dataset'] = dataset
kwargs['context'] = 'dataset'
if 'kind' in kwargs.keys():
# since we switched how dataset kinds are named, let's just
# automatically handle switching to lowercase
kwargs['kind'] = kwargs['kind'].lower()
return self.filter(**kwargs) |
def register(cls, name, entrypoint):
""" Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry
"""
if not issubclass(entrypoint, Entrypoint):
raise ValidationError(
"Invalid type for entry '{}', MUST implement "
"kser.entry.Entrypoint".format(name),
extra=dict(entrypoint=name)
)
cls.ENTRYPOINTS[name] = entrypoint
logger.debug("{}.Registered: {}".format(cls.__name__, name)) | Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry | Below is the the instruction that describes the task:
### Input:
Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry
### Response:
def register(cls, name, entrypoint):
""" Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry
"""
if not issubclass(entrypoint, Entrypoint):
raise ValidationError(
"Invalid type for entry '{}', MUST implement "
"kser.entry.Entrypoint".format(name),
extra=dict(entrypoint=name)
)
cls.ENTRYPOINTS[name] = entrypoint
logger.debug("{}.Registered: {}".format(cls.__name__, name)) |
def _get_complex_agents(self, complex_id):
"""Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex."""
agents = []
components = self._recursively_lookup_complex(complex_id)
for c in components:
db_refs = {}
name = uniprot_client.get_gene_name(c)
if name is None:
db_refs['SIGNOR'] = c
else:
db_refs['UP'] = c
hgnc_id = hgnc_client.get_hgnc_id(name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
famplex_key = ('SIGNOR', c)
if famplex_key in famplex_map:
db_refs['FPLX'] = famplex_map[famplex_key]
if not name:
name = db_refs['FPLX'] # Set agent name to Famplex name if
# the Uniprot name is not available
elif not name:
# We neither have a Uniprot nor Famplex grounding
logger.info('Have neither a Uniprot nor Famplex grounding ' + \
'for ' + c)
if not name:
name = db_refs['SIGNOR'] # Set the agent name to the
# Signor name if neither the
# Uniprot nor Famplex names are
# available
assert(name is not None)
agents.append(Agent(name, db_refs=db_refs))
return agents | Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex. | Below is the the instruction that describes the task:
### Input:
Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex.
### Response:
def _get_complex_agents(self, complex_id):
"""Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex."""
agents = []
components = self._recursively_lookup_complex(complex_id)
for c in components:
db_refs = {}
name = uniprot_client.get_gene_name(c)
if name is None:
db_refs['SIGNOR'] = c
else:
db_refs['UP'] = c
hgnc_id = hgnc_client.get_hgnc_id(name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
famplex_key = ('SIGNOR', c)
if famplex_key in famplex_map:
db_refs['FPLX'] = famplex_map[famplex_key]
if not name:
name = db_refs['FPLX'] # Set agent name to Famplex name if
# the Uniprot name is not available
elif not name:
# We neither have a Uniprot nor Famplex grounding
logger.info('Have neither a Uniprot nor Famplex grounding ' + \
'for ' + c)
if not name:
name = db_refs['SIGNOR'] # Set the agent name to the
# Signor name if neither the
# Uniprot nor Famplex names are
# available
assert(name is not None)
agents.append(Agent(name, db_refs=db_refs))
return agents |
def validate_signature(self, filename):
"""Returns True if a valid signature is present for filename"""
if not GPG_PRESENT:
return False
sigfilename = filename + '.sig'
try:
with open(sigfilename):
pass
except IOError:
# Signature file does not exist
return False
# Check if the sig is valid for the sigfile
# TODO: Check for whitespace in filepaths
return verify(sigfilename, filename) | Returns True if a valid signature is present for filename | Below is the the instruction that describes the task:
### Input:
Returns True if a valid signature is present for filename
### Response:
def validate_signature(self, filename):
"""Returns True if a valid signature is present for filename"""
if not GPG_PRESENT:
return False
sigfilename = filename + '.sig'
try:
with open(sigfilename):
pass
except IOError:
# Signature file does not exist
return False
# Check if the sig is valid for the sigfile
# TODO: Check for whitespace in filepaths
return verify(sigfilename, filename) |
def __getContributions(self, web):
"""Scrap the contributions from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
"""
contributions_raw = web.find_all('h2',
{'class': 'f4 text-normal mb-2'})
try:
contrText = contributions_raw[0].text
contrText = contrText.lstrip().split(" ")[0]
contrText = contrText.replace(",", "")
except IndexError as error:
print("There was an error with the user " + self.name)
print(error)
except AttributeError as error:
print("There was an error with the user " + self.name)
print(error)
self.contributions = int(contrText) | Scrap the contributions from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node. | Below is the the instruction that describes the task:
### Input:
Scrap the contributions from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
### Response:
def __getContributions(self, web):
"""Scrap the contributions from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
"""
contributions_raw = web.find_all('h2',
{'class': 'f4 text-normal mb-2'})
try:
contrText = contributions_raw[0].text
contrText = contrText.lstrip().split(" ")[0]
contrText = contrText.replace(",", "")
except IndexError as error:
print("There was an error with the user " + self.name)
print(error)
except AttributeError as error:
print("There was an error with the user " + self.name)
print(error)
self.contributions = int(contrText) |
def defer(self, func, *args, **kwargs):
"""
Arrange for `func()` to execute on the broker thread. This function
returns immediately without waiting the result of `func()`. Use
:meth:`defer_sync` to block until a result is available.
:raises mitogen.core.Error:
:meth:`defer` was called after :class:`Broker` has begun shutdown.
"""
if thread.get_ident() == self.broker_ident:
_vv and IOLOG.debug('%r.defer() [immediate]', self)
return func(*args, **kwargs)
if self._broker._exitted:
raise Error(self.broker_shutdown_msg)
_vv and IOLOG.debug('%r.defer() [fd=%r]', self, self.transmit_side.fd)
self._lock.acquire()
try:
if not self._deferred:
self._wake()
self._deferred.append((func, args, kwargs))
finally:
self._lock.release() | Arrange for `func()` to execute on the broker thread. This function
returns immediately without waiting the result of `func()`. Use
:meth:`defer_sync` to block until a result is available.
:raises mitogen.core.Error:
:meth:`defer` was called after :class:`Broker` has begun shutdown. | Below is the the instruction that describes the task:
### Input:
Arrange for `func()` to execute on the broker thread. This function
returns immediately without waiting the result of `func()`. Use
:meth:`defer_sync` to block until a result is available.
:raises mitogen.core.Error:
:meth:`defer` was called after :class:`Broker` has begun shutdown.
### Response:
def defer(self, func, *args, **kwargs):
"""
Arrange for `func()` to execute on the broker thread. This function
returns immediately without waiting the result of `func()`. Use
:meth:`defer_sync` to block until a result is available.
:raises mitogen.core.Error:
:meth:`defer` was called after :class:`Broker` has begun shutdown.
"""
if thread.get_ident() == self.broker_ident:
_vv and IOLOG.debug('%r.defer() [immediate]', self)
return func(*args, **kwargs)
if self._broker._exitted:
raise Error(self.broker_shutdown_msg)
_vv and IOLOG.debug('%r.defer() [fd=%r]', self, self.transmit_side.fd)
self._lock.acquire()
try:
if not self._deferred:
self._wake()
self._deferred.append((func, args, kwargs))
finally:
self._lock.release() |
def get_mongo_query_from_arguments(self, reserved_attributes=[]):
"""Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict
"""
query = {}
for arg in self.request.arguments:
if arg not in reserved_attributes:
if len(self.request.arguments.get(arg)) > 1:
query["$or"] = []
for val in self.request.arguments.get(arg):
query["$or"].append({arg: self.get_arg_value_as_type(val)})
else:
query[arg] = self.get_arg_value_as_type(self.request.arguments.get(arg)[0])
return query | Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict | Below is the the instruction that describes the task:
### Input:
Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict
### Response:
def get_mongo_query_from_arguments(self, reserved_attributes=[]):
"""Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict
"""
query = {}
for arg in self.request.arguments:
if arg not in reserved_attributes:
if len(self.request.arguments.get(arg)) > 1:
query["$or"] = []
for val in self.request.arguments.get(arg):
query["$or"].append({arg: self.get_arg_value_as_type(val)})
else:
query[arg] = self.get_arg_value_as_type(self.request.arguments.get(arg)[0])
return query |
def get_security_group_dict():
"""Returns dictionary of named security groups {name: securitygroup}."""
client = get_ec2_client()
response = client.describe_security_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for security_group_response in response['SecurityGroups']:
key = get_name(security_group_response.get('Tags', []))
if not key or key == EMPTY_NAME:
continue # ignore unnamed security groups
# key = security_group_response['GroupName']
if key in result:
util.log(f"Warning: Duplicate security group {key}")
if DUPLICATE_CHECKING:
assert key not in result, ("Duplicate security group " + key)
result[key] = ec2.SecurityGroup(security_group_response['GroupId'])
return result | Returns dictionary of named security groups {name: securitygroup}. | Below is the the instruction that describes the task:
### Input:
Returns dictionary of named security groups {name: securitygroup}.
### Response:
def get_security_group_dict():
"""Returns dictionary of named security groups {name: securitygroup}."""
client = get_ec2_client()
response = client.describe_security_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for security_group_response in response['SecurityGroups']:
key = get_name(security_group_response.get('Tags', []))
if not key or key == EMPTY_NAME:
continue # ignore unnamed security groups
# key = security_group_response['GroupName']
if key in result:
util.log(f"Warning: Duplicate security group {key}")
if DUPLICATE_CHECKING:
assert key not in result, ("Duplicate security group " + key)
result[key] = ec2.SecurityGroup(security_group_response['GroupId'])
return result |
def set_from_config_file(self, filename):
""" Loads lint config from a ini-style config file """
if not os.path.exists(filename):
raise LintConfigError(u"Invalid file path: {0}".format(filename))
self._config_path = os.path.abspath(filename)
try:
parser = ConfigParser()
parser.read(filename)
for section_name in parser.sections():
for option_name, option_value in parser.items(section_name):
self.set_option(section_name, option_name, ustr(option_value))
except ConfigParserError as e:
raise LintConfigError(ustr(e)) | Loads lint config from a ini-style config file | Below is the the instruction that describes the task:
### Input:
Loads lint config from a ini-style config file
### Response:
def set_from_config_file(self, filename):
""" Loads lint config from a ini-style config file """
if not os.path.exists(filename):
raise LintConfigError(u"Invalid file path: {0}".format(filename))
self._config_path = os.path.abspath(filename)
try:
parser = ConfigParser()
parser.read(filename)
for section_name in parser.sections():
for option_name, option_value in parser.items(section_name):
self.set_option(section_name, option_name, ustr(option_value))
except ConfigParserError as e:
raise LintConfigError(ustr(e)) |
def call(self, identifier, *args, **kwargs):
""" Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument.
"""
encoder = kwargs.get('encoder', None)
timeout = kwargs.get('timeout', 0)
max_memory = kwargs.get('max_memory', 0)
json_args = json.dumps(args, separators=(',', ':'), cls=encoder)
js = "{identifier}.apply(this, {json_args})"
return self.eval(js.format(identifier=identifier, json_args=json_args), timeout, max_memory) | Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument. | Below is the the instruction that describes the task:
### Input:
Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument.
### Response:
def call(self, identifier, *args, **kwargs):
""" Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument.
"""
encoder = kwargs.get('encoder', None)
timeout = kwargs.get('timeout', 0)
max_memory = kwargs.get('max_memory', 0)
json_args = json.dumps(args, separators=(',', ':'), cls=encoder)
js = "{identifier}.apply(this, {json_args})"
return self.eval(js.format(identifier=identifier, json_args=json_args), timeout, max_memory) |
def competition_submissions_cli(self,
competition=None,
competition_opt=None,
csv_display=False,
quiet=False):
""" wrapper to competition_submission, will return either json or csv
to the user. Additional parameters are listed below, see
competition_submissions for rest.
Parameters
==========
competition: the name of the competition. If None, look to config
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
submissions = self.competition_submissions(competition)
fields = [
'fileName', 'date', 'description', 'status', 'publicScore',
'privateScore'
]
if submissions:
if csv_display:
self.print_csv(submissions, fields)
else:
self.print_table(submissions, fields)
else:
print('No submissions found') | wrapper to competition_submission, will return either json or csv
to the user. Additional parameters are listed below, see
competition_submissions for rest.
Parameters
==========
competition: the name of the competition. If None, look to config
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False) | Below is the the instruction that describes the task:
### Input:
wrapper to competition_submission, will return either json or csv
to the user. Additional parameters are listed below, see
competition_submissions for rest.
Parameters
==========
competition: the name of the competition. If None, look to config
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False)
### Response:
def competition_submissions_cli(self,
competition=None,
competition_opt=None,
csv_display=False,
quiet=False):
""" wrapper to competition_submission, will return either json or csv
to the user. Additional parameters are listed below, see
competition_submissions for rest.
Parameters
==========
competition: the name of the competition. If None, look to config
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
submissions = self.competition_submissions(competition)
fields = [
'fileName', 'date', 'description', 'status', 'publicScore',
'privateScore'
]
if submissions:
if csv_display:
self.print_csv(submissions, fields)
else:
self.print_table(submissions, fields)
else:
print('No submissions found') |
def from_jsonstring(cls, s, selector_handler=None, strict=False, debug=False):
"""
Create a Parselet instance from s (str) containing
the Parsley script as JSON
>>> import parslepy
>>> parsley_string = '{ "title": "h1", "link": "a @href"}'
>>> p = parslepy.Parselet.from_jsonstring(parsley_string)
>>> type(p)
<class 'parslepy.base.Parselet'>
>>>
:param string s: a Parsley script as a JSON string
:rtype: :class:`.Parselet`
Other arguments: same as for :class:`.Parselet` contructor
"""
return cls._from_jsonlines(s.split("\n"),
selector_handler=selector_handler, strict=strict, debug=debug) | Create a Parselet instance from s (str) containing
the Parsley script as JSON
>>> import parslepy
>>> parsley_string = '{ "title": "h1", "link": "a @href"}'
>>> p = parslepy.Parselet.from_jsonstring(parsley_string)
>>> type(p)
<class 'parslepy.base.Parselet'>
>>>
:param string s: a Parsley script as a JSON string
:rtype: :class:`.Parselet`
Other arguments: same as for :class:`.Parselet` contructor | Below is the the instruction that describes the task:
### Input:
Create a Parselet instance from s (str) containing
the Parsley script as JSON
>>> import parslepy
>>> parsley_string = '{ "title": "h1", "link": "a @href"}'
>>> p = parslepy.Parselet.from_jsonstring(parsley_string)
>>> type(p)
<class 'parslepy.base.Parselet'>
>>>
:param string s: a Parsley script as a JSON string
:rtype: :class:`.Parselet`
Other arguments: same as for :class:`.Parselet` contructor
### Response:
def from_jsonstring(cls, s, selector_handler=None, strict=False, debug=False):
"""
Create a Parselet instance from s (str) containing
the Parsley script as JSON
>>> import parslepy
>>> parsley_string = '{ "title": "h1", "link": "a @href"}'
>>> p = parslepy.Parselet.from_jsonstring(parsley_string)
>>> type(p)
<class 'parslepy.base.Parselet'>
>>>
:param string s: a Parsley script as a JSON string
:rtype: :class:`.Parselet`
Other arguments: same as for :class:`.Parselet` contructor
"""
return cls._from_jsonlines(s.split("\n"),
selector_handler=selector_handler, strict=strict, debug=debug) |
def srun_nodes(self):
"""Get list of nodes where to execute the command
"""
count = self.execution.get('srun_nodes', 0)
if isinstance(count, six.string_types):
tag = count
count = 0
elif isinstance(count, SEQUENCES):
return count
else:
assert isinstance(count, int)
tag = self.tag
nodes = self._srun_nodes(tag, count)
if 'srun_nodes' in self.execution:
self.execution['srun_nodes'] = nodes
self.execution['srun_nodes_count'] = len(nodes)
return nodes | Get list of nodes where to execute the command | Below is the the instruction that describes the task:
### Input:
Get list of nodes where to execute the command
### Response:
def srun_nodes(self):
"""Get list of nodes where to execute the command
"""
count = self.execution.get('srun_nodes', 0)
if isinstance(count, six.string_types):
tag = count
count = 0
elif isinstance(count, SEQUENCES):
return count
else:
assert isinstance(count, int)
tag = self.tag
nodes = self._srun_nodes(tag, count)
if 'srun_nodes' in self.execution:
self.execution['srun_nodes'] = nodes
self.execution['srun_nodes_count'] = len(nodes)
return nodes |
def has_commit(self):
"""
:return:
:rtype: boolean
"""
current_revision = self.history.current_revision
revision_id = self.state.revision_id
return current_revision.revision_id != revision_id | :return:
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
:return:
:rtype: boolean
### Response:
def has_commit(self):
"""
:return:
:rtype: boolean
"""
current_revision = self.history.current_revision
revision_id = self.state.revision_id
return current_revision.revision_id != revision_id |
def reporter(self):
"""
Creates a report of the results
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
logging.info('Creating {} report'.format(self.analysistype))
# Initialise the header and data strings
header = 'Strain,Gene,PercentIdentity,Genus,FoldCoverage\n'
data = ''
with open(self.sixteens_report, 'w') as report:
with open(os.path.join(self.reportpath, self.analysistype + '_sequences.fa'), 'w') as sequences:
for sample in self.runmetadata.samples:
# Initialise
sample[self.analysistype].sixteens_match = 'NA'
sample[self.analysistype].species = 'NA'
try:
# Select the best hit of all the full-length 16S genes mapped - for 16S use the hit with the
# fewest number of SNPs rather than the highest percent identity
sample[self.analysistype].besthit = sorted(sample[self.analysistype].resultssnp.items(),
key=operator.itemgetter(1))[0][0]
# Parse the baited FASTA file to pull out the the description of the hit
for record in SeqIO.parse(sample[self.analysistype].baitfile, 'fasta'):
# If the best hit e.g. gi|631251361|ref|NR_112558.1| is present in the current record,
# gi|631251361|ref|NR_112558.1| Escherichia coli strain JCM 1649 16S ribosomal RNA ...,
# extract the match and the species
if sample[self.analysistype].besthit in record.id:
# Set the best match and species from the records
sample[self.analysistype].sixteens_match = record.description.split(' 16S')[0]
sample[self.analysistype].species = \
sample[self.analysistype].sixteens_match.split('|')[-1].split()[1]
# Add the sample name to the data string
data += sample.name + ','
# Find the record that matches the best hit, and extract the necessary values to be place in the
# data string
for name, identity in sample[self.analysistype].results.items():
if name == sample[self.analysistype].besthit:
data += '{},{},{},{}\n'.format(name, identity, sample[self.analysistype].genus,
sample[self.analysistype].avgdepth[name])
# Create a FASTA-formatted sequence output of the 16S sequence
record = SeqRecord(Seq(sample[self.analysistype].sequences[name],
IUPAC.unambiguous_dna),
id='{}_{}'.format(sample.name, '16S'),
description='')
SeqIO.write(record, sequences, 'fasta')
except (AttributeError, IndexError):
data += '{}\n'.format(sample.name)
# Write the results to the report
report.write(header)
report.write(data) | Creates a report of the results | Below is the the instruction that describes the task:
### Input:
Creates a report of the results
### Response:
def reporter(self):
"""
Creates a report of the results
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
logging.info('Creating {} report'.format(self.analysistype))
# Initialise the header and data strings
header = 'Strain,Gene,PercentIdentity,Genus,FoldCoverage\n'
data = ''
with open(self.sixteens_report, 'w') as report:
with open(os.path.join(self.reportpath, self.analysistype + '_sequences.fa'), 'w') as sequences:
for sample in self.runmetadata.samples:
# Initialise
sample[self.analysistype].sixteens_match = 'NA'
sample[self.analysistype].species = 'NA'
try:
# Select the best hit of all the full-length 16S genes mapped - for 16S use the hit with the
# fewest number of SNPs rather than the highest percent identity
sample[self.analysistype].besthit = sorted(sample[self.analysistype].resultssnp.items(),
key=operator.itemgetter(1))[0][0]
# Parse the baited FASTA file to pull out the the description of the hit
for record in SeqIO.parse(sample[self.analysistype].baitfile, 'fasta'):
# If the best hit e.g. gi|631251361|ref|NR_112558.1| is present in the current record,
# gi|631251361|ref|NR_112558.1| Escherichia coli strain JCM 1649 16S ribosomal RNA ...,
# extract the match and the species
if sample[self.analysistype].besthit in record.id:
# Set the best match and species from the records
sample[self.analysistype].sixteens_match = record.description.split(' 16S')[0]
sample[self.analysistype].species = \
sample[self.analysistype].sixteens_match.split('|')[-1].split()[1]
# Add the sample name to the data string
data += sample.name + ','
# Find the record that matches the best hit, and extract the necessary values to be place in the
# data string
for name, identity in sample[self.analysistype].results.items():
if name == sample[self.analysistype].besthit:
data += '{},{},{},{}\n'.format(name, identity, sample[self.analysistype].genus,
sample[self.analysistype].avgdepth[name])
# Create a FASTA-formatted sequence output of the 16S sequence
record = SeqRecord(Seq(sample[self.analysistype].sequences[name],
IUPAC.unambiguous_dna),
id='{}_{}'.format(sample.name, '16S'),
description='')
SeqIO.write(record, sequences, 'fasta')
except (AttributeError, IndexError):
data += '{}\n'.format(sample.name)
# Write the results to the report
report.write(header)
report.write(data) |
def coarseMaximum(arr, shape):
'''
return an array of [shape]
where every cell equals the localised maximum of the given array [arr]
at the same (scalled) position
'''
ss0, ss1 = shape
s0, s1 = arr.shape
pos0 = linspace2(0, s0, ss0, dtype=int)
pos1 = linspace2(0, s1, ss1, dtype=int)
k0 = pos0[0]
k1 = pos1[0]
out = np.empty(shape, dtype=arr.dtype)
_calc(arr, out, pos0, pos1, k0, k1, ss0, ss1)
return out | return an array of [shape]
where every cell equals the localised maximum of the given array [arr]
at the same (scalled) position | Below is the the instruction that describes the task:
### Input:
return an array of [shape]
where every cell equals the localised maximum of the given array [arr]
at the same (scalled) position
### Response:
def coarseMaximum(arr, shape):
'''
return an array of [shape]
where every cell equals the localised maximum of the given array [arr]
at the same (scalled) position
'''
ss0, ss1 = shape
s0, s1 = arr.shape
pos0 = linspace2(0, s0, ss0, dtype=int)
pos1 = linspace2(0, s1, ss1, dtype=int)
k0 = pos0[0]
k1 = pos1[0]
out = np.empty(shape, dtype=arr.dtype)
_calc(arr, out, pos0, pos1, k0, k1, ss0, ss1)
return out |
def get_11u_advert(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n676.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
"""
answers = dict()
idx = 0
while idx < len(data) - 1:
qri = data[idx]
proto_id = data[idx + 1]
answers['Query Response Info'] = qri
answers['Query Response Length Limit'] = qri & 0x7f
if qri & (1 << 7):
answers['PAME-BI'] = True
answers['proto_id'] = {0: 'ANQP', 1: 'MIH Information Service', 3: 'Emergency Alert System (EAS)',
2: 'MIH Command and Event Services Capability Discovery',
221: 'Vendor Specific'}.get(proto_id, 'Reserved: {0}'.format(proto_id))
idx += 2
return answers | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n676.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict. | Below is the the instruction that describes the task:
### Input:
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n676.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
### Response:
def get_11u_advert(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n676.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
"""
answers = dict()
idx = 0
while idx < len(data) - 1:
qri = data[idx]
proto_id = data[idx + 1]
answers['Query Response Info'] = qri
answers['Query Response Length Limit'] = qri & 0x7f
if qri & (1 << 7):
answers['PAME-BI'] = True
answers['proto_id'] = {0: 'ANQP', 1: 'MIH Information Service', 3: 'Emergency Alert System (EAS)',
2: 'MIH Command and Event Services Capability Discovery',
221: 'Vendor Specific'}.get(proto_id, 'Reserved: {0}'.format(proto_id))
idx += 2
return answers |
def show_dlg(self, dlg):
"""
Abstraction function that is to be used instead of dlg.ShowModal
Parameters
----------
dlg : dialog to ShowModal if possible
"""
if not self.test_mode:
dlg.Center()
return dlg.ShowModal()
else:
return dlg.GetAffirmativeId() | Abstraction function that is to be used instead of dlg.ShowModal
Parameters
----------
dlg : dialog to ShowModal if possible | Below is the the instruction that describes the task:
### Input:
Abstraction function that is to be used instead of dlg.ShowModal
Parameters
----------
dlg : dialog to ShowModal if possible
### Response:
def show_dlg(self, dlg):
"""
Abstraction function that is to be used instead of dlg.ShowModal
Parameters
----------
dlg : dialog to ShowModal if possible
"""
if not self.test_mode:
dlg.Center()
return dlg.ShowModal()
else:
return dlg.GetAffirmativeId() |
def get_authentication_statement(self, subject, ticket):
"""
Build an AuthenticationStatement XML block for a SAML 1.1
Assertion.
"""
authentication_statement = etree.Element('AuthenticationStatement')
authentication_statement.set('AuthenticationInstant',
self.instant(instant=ticket.consumed))
authentication_statement.set('AuthenticationMethod',
self.authn_method_password)
authentication_statement.append(subject)
return authentication_statement | Build an AuthenticationStatement XML block for a SAML 1.1
Assertion. | Below is the the instruction that describes the task:
### Input:
Build an AuthenticationStatement XML block for a SAML 1.1
Assertion.
### Response:
def get_authentication_statement(self, subject, ticket):
"""
Build an AuthenticationStatement XML block for a SAML 1.1
Assertion.
"""
authentication_statement = etree.Element('AuthenticationStatement')
authentication_statement.set('AuthenticationInstant',
self.instant(instant=ticket.consumed))
authentication_statement.set('AuthenticationMethod',
self.authn_method_password)
authentication_statement.append(subject)
return authentication_statement |
def componentSelection(self, comp):
"""Toggles the selection of *comp* from the currently active parameter"""
# current row which is selected in auto parameters to all component selection to
indexes = self.selectedIndexes()
index = indexes[0]
self.model().toggleSelection(index, comp) | Toggles the selection of *comp* from the currently active parameter | Below is the the instruction that describes the task:
### Input:
Toggles the selection of *comp* from the currently active parameter
### Response:
def componentSelection(self, comp):
"""Toggles the selection of *comp* from the currently active parameter"""
# current row which is selected in auto parameters to all component selection to
indexes = self.selectedIndexes()
index = indexes[0]
self.model().toggleSelection(index, comp) |
def _CheckIfPathIsValidForDeletion(path, prefix=None, directories=None):
"""Checks if given path is valid for deletion."""
precondition.AssertType(path, Text)
precondition.AssertType(prefix, Text)
if prefix and os.path.basename(path).startswith(prefix):
return True
path = path.lower()
for directory in directories or []:
directory = directory.lower()
if os.path.commonprefix([directory, path]) == directory:
return True
return False | Checks if given path is valid for deletion. | Below is the the instruction that describes the task:
### Input:
Checks if given path is valid for deletion.
### Response:
def _CheckIfPathIsValidForDeletion(path, prefix=None, directories=None):
"""Checks if given path is valid for deletion."""
precondition.AssertType(path, Text)
precondition.AssertType(prefix, Text)
if prefix and os.path.basename(path).startswith(prefix):
return True
path = path.lower()
for directory in directories or []:
directory = directory.lower()
if os.path.commonprefix([directory, path]) == directory:
return True
return False |
def _styles_part(self):
"""
Instance of |StylesPart| for this document. Creates an empty styles
part if one is not present.
"""
try:
return self.part_related_by(RT.STYLES)
except KeyError:
styles_part = StylesPart.default(self.package)
self.relate_to(styles_part, RT.STYLES)
return styles_part | Instance of |StylesPart| for this document. Creates an empty styles
part if one is not present. | Below is the the instruction that describes the task:
### Input:
Instance of |StylesPart| for this document. Creates an empty styles
part if one is not present.
### Response:
def _styles_part(self):
"""
Instance of |StylesPart| for this document. Creates an empty styles
part if one is not present.
"""
try:
return self.part_related_by(RT.STYLES)
except KeyError:
styles_part = StylesPart.default(self.package)
self.relate_to(styles_part, RT.STYLES)
return styles_part |
def count(args):
"""
%prog count frgfile
Count each type of messages
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fp = open(frgfile)
counts = defaultdict(int)
for rec in iter_records(fp):
counts[rec.type] += 1
for type, cnt in sorted(counts.items()):
print('{0}: {1}'.format(type, cnt), file=sys.stderr) | %prog count frgfile
Count each type of messages | Below is the the instruction that describes the task:
### Input:
%prog count frgfile
Count each type of messages
### Response:
def count(args):
"""
%prog count frgfile
Count each type of messages
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fp = open(frgfile)
counts = defaultdict(int)
for rec in iter_records(fp):
counts[rec.type] += 1
for type, cnt in sorted(counts.items()):
print('{0}: {1}'.format(type, cnt), file=sys.stderr) |
def url_split(s3_url):
"""Split S3 URL and return a tuple of (bucket, key).
S3 URL is expected to be of "s3://<bucket>/<key>" format.
"""
assert isinstance(s3_url, str)
match = re_s3_url.match(s3_url)
if not match:
raise UrlParseError('Error parsing S3 URL: "%s"' % s3_url)
parts = match.groupdict()
return (parts['bucket'], parts['key']) | Split S3 URL and return a tuple of (bucket, key).
S3 URL is expected to be of "s3://<bucket>/<key>" format. | Below is the the instruction that describes the task:
### Input:
Split S3 URL and return a tuple of (bucket, key).
S3 URL is expected to be of "s3://<bucket>/<key>" format.
### Response:
def url_split(s3_url):
"""Split S3 URL and return a tuple of (bucket, key).
S3 URL is expected to be of "s3://<bucket>/<key>" format.
"""
assert isinstance(s3_url, str)
match = re_s3_url.match(s3_url)
if not match:
raise UrlParseError('Error parsing S3 URL: "%s"' % s3_url)
parts = match.groupdict()
return (parts['bucket'], parts['key']) |
def split_colors(cls, multicolor, guidance=None, sorted_guidance=False,
account_for_color_multiplicity_in_guidance=True):
""" Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects
"""
if guidance is None:
###############################################################################################
#
# if guidance is not specified, it will be derived from colors in the targeted multicolor
# initially the multiplicity of colors remains as is
#
###############################################################################################
guidance = [Multicolor(*(color for _ in range(multicolor.multicolors[color]))) for color in multicolor.colors]
###############################################################################################
#
# since at this we have a single-colored (maybe with multiplicity greater than 1)
# we don't need to sort anything, as there will be no overlapping multicolor in guidance
#
###############################################################################################
sorted_guidance = True
###############################################################################################
#
# a reference to the targeted multicolor.
# such reference is created only for the future requirement to access information about original multicolor
# Is done for the sake of code clarity and consistency.
#
###############################################################################################
splitting_multicolor = deepcopy(multicolor)
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# we need to create a new guidance (even if original is perfect)
# a new one shall preserve the order of the original, but all multicolors in it
# while keeping information about the actual colors itself, shall have multiplicity equal to 1
#
###############################################################################################
splitting_multicolor = Multicolor(*multicolor.colors)
colors_guidance = [Multicolor(*tmp_multicolor.colors) for tmp_multicolor in guidance]
###############################################################################################
#
# since there might be different multicolors, with the same colors content
# and they will be changed to same multicolors object, after colors multiplicity adjustment
# we need, while preserving the order, leave only unique ones in (the first appearance)
#
###############################################################################################
unique = set()
guidance = []
for c_multicolor in colors_guidance:
if c_multicolor.hashable_representation not in unique:
unique.add(c_multicolor.hashable_representation)
guidance.append(c_multicolor)
if not sorted_guidance:
###############################################################################################
#
# if arguments in function call do not specify explicitly, that the guidance shall be used "as is"
# it is sorted to put "bigger" multicolors in front, and smaller at the back
# as bigger multicolor might contain several smaller multicolors from the guidance, but the correct splitting
# always assumes that the smaller is the splitted result, the better it is
# and such minimization can be obtained only if the biggest chunk of targeted multicolor are ripped off of it first
#
###############################################################################################
guidance = sorted({g_multicolor.hashable_representation for g_multicolor in guidance},
key=lambda g_multicolor: len(g_multicolor),
reverse=True)
guidance = [Multicolor(*hashed) for hashed in guidance]
first_run_result = []
second_run_result = []
for g_multicolor in guidance:
###############################################################################################
#
# first we determine which multicolors in guidance are fully present in the multicolor to split
# "<=" operator can be read as "is_multi_subset_of"
# and retrieve as many copies of it from the multicolor, as we can
# Example:
# multicolor has only one color "blue" with multiplicity "4"
# in guidance we have multicolor with color "blue" with multiplicity "2"
# we must retrieve it fully twice
#
###############################################################################################
###############################################################################################
#
# empty guidance multicolors shall be ignored, as they have no impact on the splitting algorithm
#
###############################################################################################
if len(g_multicolor.colors) == 0:
continue
while g_multicolor <= splitting_multicolor:
first_run_result.append(g_multicolor)
splitting_multicolor -= g_multicolor
for g_multicolor in guidance:
###############################################################################################
#
# secondly we determine which multicolors in guidance are partially present in the multicolor
# NOTE that this is not possible for the case of tree consistent multicolor
# as every partially present
#
###############################################################################################
while len(g_multicolor.intersect(splitting_multicolor).multicolors) > 0:
second_run_result.append(g_multicolor.intersect(splitting_multicolor))
splitting_multicolor -= g_multicolor.intersect(splitting_multicolor)
appendix = splitting_multicolor
result = deepcopy(first_run_result) + deepcopy(second_run_result) + deepcopy([appendix] if len(appendix.multicolors) > 0 else [])
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# if we didn't care for guidance multicolors colors multiplicity, we we splitting a specially created Multicolor
# based only on the colors content.
# After this is done, we need to restore the original multiplicity of each color in result multicolors to the
# count they had in the targeted for splitting multicolor.
# This is possible since in the case when we do not account for colors multiplicity in guidance, we have
# splitting_color variable referencing not the supplied multicolor, and thus internal changes are not made to
# supplied multicolor.
#
###############################################################################################
for r_multicolor in result:
for color in r_multicolor.colors:
r_multicolor.multicolors[color] = multicolor.multicolors[color]
return result | Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects | Below is the the instruction that describes the task:
### Input:
Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects
### Response:
def split_colors(cls, multicolor, guidance=None, sorted_guidance=False,
account_for_color_multiplicity_in_guidance=True):
""" Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects
"""
if guidance is None:
###############################################################################################
#
# if guidance is not specified, it will be derived from colors in the targeted multicolor
# initially the multiplicity of colors remains as is
#
###############################################################################################
guidance = [Multicolor(*(color for _ in range(multicolor.multicolors[color]))) for color in multicolor.colors]
###############################################################################################
#
# since at this we have a single-colored (maybe with multiplicity greater than 1)
# we don't need to sort anything, as there will be no overlapping multicolor in guidance
#
###############################################################################################
sorted_guidance = True
###############################################################################################
#
# a reference to the targeted multicolor.
# such reference is created only for the future requirement to access information about original multicolor
# Is done for the sake of code clarity and consistency.
#
###############################################################################################
splitting_multicolor = deepcopy(multicolor)
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# we need to create a new guidance (even if original is perfect)
# a new one shall preserve the order of the original, but all multicolors in it
# while keeping information about the actual colors itself, shall have multiplicity equal to 1
#
###############################################################################################
splitting_multicolor = Multicolor(*multicolor.colors)
colors_guidance = [Multicolor(*tmp_multicolor.colors) for tmp_multicolor in guidance]
###############################################################################################
#
# since there might be different multicolors, with the same colors content
# and they will be changed to same multicolors object, after colors multiplicity adjustment
# we need, while preserving the order, leave only unique ones in (the first appearance)
#
###############################################################################################
unique = set()
guidance = []
for c_multicolor in colors_guidance:
if c_multicolor.hashable_representation not in unique:
unique.add(c_multicolor.hashable_representation)
guidance.append(c_multicolor)
if not sorted_guidance:
###############################################################################################
#
# if arguments in function call do not specify explicitly, that the guidance shall be used "as is"
# it is sorted to put "bigger" multicolors in front, and smaller at the back
# as bigger multicolor might contain several smaller multicolors from the guidance, but the correct splitting
# always assumes that the smaller is the splitted result, the better it is
# and such minimization can be obtained only if the biggest chunk of targeted multicolor are ripped off of it first
#
###############################################################################################
guidance = sorted({g_multicolor.hashable_representation for g_multicolor in guidance},
key=lambda g_multicolor: len(g_multicolor),
reverse=True)
guidance = [Multicolor(*hashed) for hashed in guidance]
first_run_result = []
second_run_result = []
for g_multicolor in guidance:
###############################################################################################
#
# first we determine which multicolors in guidance are fully present in the multicolor to split
# "<=" operator can be read as "is_multi_subset_of"
# and retrieve as many copies of it from the multicolor, as we can
# Example:
# multicolor has only one color "blue" with multiplicity "4"
# in guidance we have multicolor with color "blue" with multiplicity "2"
# we must retrieve it fully twice
#
###############################################################################################
###############################################################################################
#
# empty guidance multicolors shall be ignored, as they have no impact on the splitting algorithm
#
###############################################################################################
if len(g_multicolor.colors) == 0:
continue
while g_multicolor <= splitting_multicolor:
first_run_result.append(g_multicolor)
splitting_multicolor -= g_multicolor
for g_multicolor in guidance:
###############################################################################################
#
# secondly we determine which multicolors in guidance are partially present in the multicolor
# NOTE that this is not possible for the case of tree consistent multicolor
# as every partially present
#
###############################################################################################
while len(g_multicolor.intersect(splitting_multicolor).multicolors) > 0:
second_run_result.append(g_multicolor.intersect(splitting_multicolor))
splitting_multicolor -= g_multicolor.intersect(splitting_multicolor)
appendix = splitting_multicolor
result = deepcopy(first_run_result) + deepcopy(second_run_result) + deepcopy([appendix] if len(appendix.multicolors) > 0 else [])
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# if we didn't care for guidance multicolors colors multiplicity, we we splitting a specially created Multicolor
# based only on the colors content.
# After this is done, we need to restore the original multiplicity of each color in result multicolors to the
# count they had in the targeted for splitting multicolor.
# This is possible since in the case when we do not account for colors multiplicity in guidance, we have
# splitting_color variable referencing not the supplied multicolor, and thus internal changes are not made to
# supplied multicolor.
#
###############################################################################################
for r_multicolor in result:
for color in r_multicolor.colors:
r_multicolor.multicolors[color] = multicolor.multicolors[color]
return result |
def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
payload = {'client_id': self._key,
'client_secret': self._secret,
'scope': scope,
'grant_type': 'client_credentials'
}
url = "%s/oauth/token" % self._endpoint
headers = {'Accept': 'application/json'}
response = requests.post(url, data=payload, headers=headers,
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return response.json()['access_token'] | Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token. | Below is the the instruction that describes the task:
### Input:
Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
### Response:
def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
payload = {'client_id': self._key,
'client_secret': self._secret,
'scope': scope,
'grant_type': 'client_credentials'
}
url = "%s/oauth/token" % self._endpoint
headers = {'Accept': 'application/json'}
response = requests.post(url, data=payload, headers=headers,
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return response.json()['access_token'] |
def simxGetObjectGroupData(clientID, objectType, dataType, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handles =[]
intData =[]
floatData =[]
stringData =[]
handlesC = ct.c_int()
handlesP = ct.POINTER(ct.c_int)()
intDataC = ct.c_int()
intDataP = ct.POINTER(ct.c_int)()
floatDataC = ct.c_int()
floatDataP = ct.POINTER(ct.c_float)()
stringDataC = ct.c_int()
stringDataP = ct.POINTER(ct.c_char)()
ret = c_GetObjectGroupData(clientID, objectType, dataType, ct.byref(handlesC), ct.byref(handlesP), ct.byref(intDataC), ct.byref(intDataP), ct.byref(floatDataC), ct.byref(floatDataP), ct.byref(stringDataC), ct.byref(stringDataP), operationMode)
if ret == 0:
for i in range(handlesC.value):
handles.append(handlesP[i])
for i in range(intDataC.value):
intData.append(intDataP[i])
for i in range(floatDataC.value):
floatData.append(floatDataP[i])
s = 0
for i in range(stringDataC.value):
a = bytearray()
while stringDataP[s] != b'\0':
if sys.version_info[0] == 3:
a.append(int.from_bytes(stringDataP[s],'big'))
else:
a.append(stringDataP[s])
s += 1
s += 1 #skip null
if sys.version_info[0] == 3:
a=str(a,'utf-8')
else:
a=str(a)
stringData.append(a)
return ret, handles, intData, floatData, stringData | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxGetObjectGroupData(clientID, objectType, dataType, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handles =[]
intData =[]
floatData =[]
stringData =[]
handlesC = ct.c_int()
handlesP = ct.POINTER(ct.c_int)()
intDataC = ct.c_int()
intDataP = ct.POINTER(ct.c_int)()
floatDataC = ct.c_int()
floatDataP = ct.POINTER(ct.c_float)()
stringDataC = ct.c_int()
stringDataP = ct.POINTER(ct.c_char)()
ret = c_GetObjectGroupData(clientID, objectType, dataType, ct.byref(handlesC), ct.byref(handlesP), ct.byref(intDataC), ct.byref(intDataP), ct.byref(floatDataC), ct.byref(floatDataP), ct.byref(stringDataC), ct.byref(stringDataP), operationMode)
if ret == 0:
for i in range(handlesC.value):
handles.append(handlesP[i])
for i in range(intDataC.value):
intData.append(intDataP[i])
for i in range(floatDataC.value):
floatData.append(floatDataP[i])
s = 0
for i in range(stringDataC.value):
a = bytearray()
while stringDataP[s] != b'\0':
if sys.version_info[0] == 3:
a.append(int.from_bytes(stringDataP[s],'big'))
else:
a.append(stringDataP[s])
s += 1
s += 1 #skip null
if sys.version_info[0] == 3:
a=str(a,'utf-8')
else:
a=str(a)
stringData.append(a)
return ret, handles, intData, floatData, stringData |
def decodeBinaryData(binaryData, arrayLength, bitEncoding, compression):
"""Function to decode a mzML byte array into a numpy array. This is the
inverse function of :func:`encodeBinaryData`. Concept inherited from
:func:`pymzml.spec.Spectrum._decode` of the python library `pymzML
<https://pymzml.github.io/>`_.
:param binaryData: #TODO: docstring
:param arrayLength: #TODO: docstring
:param binEncoding: #TODO: docstring
:param compression: #TODO: docstring
:returns: #TODO: docstring
"""
#TODO: should raise an error if a wrong compression is specified
bitEncodedData = binaryData.encode("utf-8")
bitDecodedData = B64DEC(bitEncodedData)
floattype, numpyType = interpretBitEncoding(bitEncoding)
if compression == 'zlib':
decompressedData = zlib.decompress(bitDecodedData)
else:
decompressedData = bitDecodedData
fmt = '{endian}{arraylength}{floattype}'.format(endian='<',
arraylength=arrayLength,
floattype=floattype
)
dataArray = numpy.array(UNPACK(fmt, decompressedData), dtype=numpyType)
return dataArray | Function to decode a mzML byte array into a numpy array. This is the
inverse function of :func:`encodeBinaryData`. Concept inherited from
:func:`pymzml.spec.Spectrum._decode` of the python library `pymzML
<https://pymzml.github.io/>`_.
:param binaryData: #TODO: docstring
:param arrayLength: #TODO: docstring
:param binEncoding: #TODO: docstring
:param compression: #TODO: docstring
:returns: #TODO: docstring | Below is the the instruction that describes the task:
### Input:
Function to decode a mzML byte array into a numpy array. This is the
inverse function of :func:`encodeBinaryData`. Concept inherited from
:func:`pymzml.spec.Spectrum._decode` of the python library `pymzML
<https://pymzml.github.io/>`_.
:param binaryData: #TODO: docstring
:param arrayLength: #TODO: docstring
:param binEncoding: #TODO: docstring
:param compression: #TODO: docstring
:returns: #TODO: docstring
### Response:
def decodeBinaryData(binaryData, arrayLength, bitEncoding, compression):
"""Function to decode a mzML byte array into a numpy array. This is the
inverse function of :func:`encodeBinaryData`. Concept inherited from
:func:`pymzml.spec.Spectrum._decode` of the python library `pymzML
<https://pymzml.github.io/>`_.
:param binaryData: #TODO: docstring
:param arrayLength: #TODO: docstring
:param binEncoding: #TODO: docstring
:param compression: #TODO: docstring
:returns: #TODO: docstring
"""
#TODO: should raise an error if a wrong compression is specified
bitEncodedData = binaryData.encode("utf-8")
bitDecodedData = B64DEC(bitEncodedData)
floattype, numpyType = interpretBitEncoding(bitEncoding)
if compression == 'zlib':
decompressedData = zlib.decompress(bitDecodedData)
else:
decompressedData = bitDecodedData
fmt = '{endian}{arraylength}{floattype}'.format(endian='<',
arraylength=arrayLength,
floattype=floattype
)
dataArray = numpy.array(UNPACK(fmt, decompressedData), dtype=numpyType)
return dataArray |
def download(self, directory='~/Music', song_name='%a - %s - %A'):
"""
Download a song to a directory.
:param directory: A system file path.
:param song_name: A name that will be formatted with :meth:`format`.
:return: The formatted song name.
"""
formatted = self.format(song_name)
path = os.path.expanduser(directory) + os.path.sep + formatted + '.mp3'
try:
raw = self.safe_download()
with open(path, 'wb') as f:
f.write(raw)
except:
raise
return formatted | Download a song to a directory.
:param directory: A system file path.
:param song_name: A name that will be formatted with :meth:`format`.
:return: The formatted song name. | Below is the the instruction that describes the task:
### Input:
Download a song to a directory.
:param directory: A system file path.
:param song_name: A name that will be formatted with :meth:`format`.
:return: The formatted song name.
### Response:
def download(self, directory='~/Music', song_name='%a - %s - %A'):
"""
Download a song to a directory.
:param directory: A system file path.
:param song_name: A name that will be formatted with :meth:`format`.
:return: The formatted song name.
"""
formatted = self.format(song_name)
path = os.path.expanduser(directory) + os.path.sep + formatted + '.mp3'
try:
raw = self.safe_download()
with open(path, 'wb') as f:
f.write(raw)
except:
raise
return formatted |
def cli(env, context_id, translation_id):
"""Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure translation can be retrieved by given id
manager.get_translation(context_id, translation_id)
succeeded = manager.remove_translation(context_id, translation_id)
if succeeded:
env.out('Removed translation #{}'.format(translation_id))
else:
raise CLIHalt('Failed to remove translation #{}'.format(translation_id)) | Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices. | Below is the the instruction that describes the task:
### Input:
Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
### Response:
def cli(env, context_id, translation_id):
"""Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure translation can be retrieved by given id
manager.get_translation(context_id, translation_id)
succeeded = manager.remove_translation(context_id, translation_id)
if succeeded:
env.out('Removed translation #{}'.format(translation_id))
else:
raise CLIHalt('Failed to remove translation #{}'.format(translation_id)) |
def divs(x,y):
"""safe division"""
tmp = np.ones(x.shape)
nonzero_y = y != 0
tmp[nonzero_y] = x[nonzero_y]/y[nonzero_y]
return tmp | safe division | Below is the the instruction that describes the task:
### Input:
safe division
### Response:
def divs(x,y):
"""safe division"""
tmp = np.ones(x.shape)
nonzero_y = y != 0
tmp[nonzero_y] = x[nonzero_y]/y[nonzero_y]
return tmp |
def wait(*coros_or_futures, limit=0, timeout=None, loop=None,
return_exceptions=False, return_when='ALL_COMPLETED'):
"""
Wait for the Futures and coroutine objects given by the sequence
futures to complete, with optional concurrency limit.
Coroutines will be wrapped in Tasks.
``timeout`` can be used to control the maximum number of seconds to
wait before returning. timeout can be an int or float.
If timeout is not specified or None, there is no limit to the wait time.
If ``return_exceptions`` is True, exceptions in the tasks are treated the
same as successful results, and gathered in the result list; otherwise,
the first raised exception will be immediately propagated to the
returned future.
``return_when`` indicates when this function should return.
It must be one of the following constants of the concurrent.futures module.
All futures must share the same event loop.
This functions is mostly compatible with Python standard
``asyncio.wait()``.
Arguments:
*coros_or_futures (iter|list):
an iterable collection yielding coroutines functions.
limit (int):
optional concurrency execution limit. Use ``0`` for no limit.
timeout (int/float):
maximum number of seconds to wait before returning.
return_exceptions (bool):
exceptions in the tasks are treated the same as successful results,
instead of raising them.
return_when (str):
indicates when this function should return.
loop (asyncio.BaseEventLoop):
optional event loop to use.
*args (mixed):
optional variadic argument to pass to the coroutines function.
Returns:
tuple: Returns two sets of Future: (done, pending).
Raises:
TypeError: in case of invalid coroutine object.
ValueError: in case of empty set of coroutines or futures.
TimeoutError: if execution takes more than expected.
Usage::
async def sum(x, y):
return x + y
done, pending = await paco.wait(
sum(1, 2),
sum(3, 4))
[task.result() for task in done]
# => [3, 7]
"""
# Support iterable as first argument for better interoperability
if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]):
coros_or_futures = coros_or_futures[0]
# If no coroutines to schedule, return empty list
# Mimics asyncio behaviour.
if len(coros_or_futures) == 0:
raise ValueError('paco: set of coroutines/futures is empty')
# Create concurrent executor
pool = ConcurrentExecutor(limit=limit, loop=loop,
coros=coros_or_futures)
# Wait until all the tasks finishes
return (yield from pool.run(timeout=timeout,
return_when=return_when,
return_exceptions=return_exceptions)) | Wait for the Futures and coroutine objects given by the sequence
futures to complete, with optional concurrency limit.
Coroutines will be wrapped in Tasks.
``timeout`` can be used to control the maximum number of seconds to
wait before returning. timeout can be an int or float.
If timeout is not specified or None, there is no limit to the wait time.
If ``return_exceptions`` is True, exceptions in the tasks are treated the
same as successful results, and gathered in the result list; otherwise,
the first raised exception will be immediately propagated to the
returned future.
``return_when`` indicates when this function should return.
It must be one of the following constants of the concurrent.futures module.
All futures must share the same event loop.
This functions is mostly compatible with Python standard
``asyncio.wait()``.
Arguments:
*coros_or_futures (iter|list):
an iterable collection yielding coroutines functions.
limit (int):
optional concurrency execution limit. Use ``0`` for no limit.
timeout (int/float):
maximum number of seconds to wait before returning.
return_exceptions (bool):
exceptions in the tasks are treated the same as successful results,
instead of raising them.
return_when (str):
indicates when this function should return.
loop (asyncio.BaseEventLoop):
optional event loop to use.
*args (mixed):
optional variadic argument to pass to the coroutines function.
Returns:
tuple: Returns two sets of Future: (done, pending).
Raises:
TypeError: in case of invalid coroutine object.
ValueError: in case of empty set of coroutines or futures.
TimeoutError: if execution takes more than expected.
Usage::
async def sum(x, y):
return x + y
done, pending = await paco.wait(
sum(1, 2),
sum(3, 4))
[task.result() for task in done]
# => [3, 7] | Below is the the instruction that describes the task:
### Input:
Wait for the Futures and coroutine objects given by the sequence
futures to complete, with optional concurrency limit.
Coroutines will be wrapped in Tasks.
``timeout`` can be used to control the maximum number of seconds to
wait before returning. timeout can be an int or float.
If timeout is not specified or None, there is no limit to the wait time.
If ``return_exceptions`` is True, exceptions in the tasks are treated the
same as successful results, and gathered in the result list; otherwise,
the first raised exception will be immediately propagated to the
returned future.
``return_when`` indicates when this function should return.
It must be one of the following constants of the concurrent.futures module.
All futures must share the same event loop.
This functions is mostly compatible with Python standard
``asyncio.wait()``.
Arguments:
*coros_or_futures (iter|list):
an iterable collection yielding coroutines functions.
limit (int):
optional concurrency execution limit. Use ``0`` for no limit.
timeout (int/float):
maximum number of seconds to wait before returning.
return_exceptions (bool):
exceptions in the tasks are treated the same as successful results,
instead of raising them.
return_when (str):
indicates when this function should return.
loop (asyncio.BaseEventLoop):
optional event loop to use.
*args (mixed):
optional variadic argument to pass to the coroutines function.
Returns:
tuple: Returns two sets of Future: (done, pending).
Raises:
TypeError: in case of invalid coroutine object.
ValueError: in case of empty set of coroutines or futures.
TimeoutError: if execution takes more than expected.
Usage::
async def sum(x, y):
return x + y
done, pending = await paco.wait(
sum(1, 2),
sum(3, 4))
[task.result() for task in done]
# => [3, 7]
### Response:
def wait(*coros_or_futures, limit=0, timeout=None, loop=None,
return_exceptions=False, return_when='ALL_COMPLETED'):
"""
Wait for the Futures and coroutine objects given by the sequence
futures to complete, with optional concurrency limit.
Coroutines will be wrapped in Tasks.
``timeout`` can be used to control the maximum number of seconds to
wait before returning. timeout can be an int or float.
If timeout is not specified or None, there is no limit to the wait time.
If ``return_exceptions`` is True, exceptions in the tasks are treated the
same as successful results, and gathered in the result list; otherwise,
the first raised exception will be immediately propagated to the
returned future.
``return_when`` indicates when this function should return.
It must be one of the following constants of the concurrent.futures module.
All futures must share the same event loop.
This functions is mostly compatible with Python standard
``asyncio.wait()``.
Arguments:
*coros_or_futures (iter|list):
an iterable collection yielding coroutines functions.
limit (int):
optional concurrency execution limit. Use ``0`` for no limit.
timeout (int/float):
maximum number of seconds to wait before returning.
return_exceptions (bool):
exceptions in the tasks are treated the same as successful results,
instead of raising them.
return_when (str):
indicates when this function should return.
loop (asyncio.BaseEventLoop):
optional event loop to use.
*args (mixed):
optional variadic argument to pass to the coroutines function.
Returns:
tuple: Returns two sets of Future: (done, pending).
Raises:
TypeError: in case of invalid coroutine object.
ValueError: in case of empty set of coroutines or futures.
TimeoutError: if execution takes more than expected.
Usage::
async def sum(x, y):
return x + y
done, pending = await paco.wait(
sum(1, 2),
sum(3, 4))
[task.result() for task in done]
# => [3, 7]
"""
# Support iterable as first argument for better interoperability
if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]):
coros_or_futures = coros_or_futures[0]
# If no coroutines to schedule, return empty list
# Mimics asyncio behaviour.
if len(coros_or_futures) == 0:
raise ValueError('paco: set of coroutines/futures is empty')
# Create concurrent executor
pool = ConcurrentExecutor(limit=limit, loop=loop,
coros=coros_or_futures)
# Wait until all the tasks finishes
return (yield from pool.run(timeout=timeout,
return_when=return_when,
return_exceptions=return_exceptions)) |
def __build_export(self, stats):
"""Build the export lists."""
export_names = []
export_values = []
if isinstance(stats, dict):
# Stats is a dict
# Is there a key ?
if 'key' in iterkeys(stats) and stats['key'] in iterkeys(stats):
pre_key = '{}.'.format(stats[stats['key']])
else:
pre_key = ''
# Walk through the dict
for key, value in iteritems(stats):
if isinstance(value, bool):
value = json.dumps(value)
if isinstance(value, list):
try:
value = value[0]
except IndexError:
value = ''
if isinstance(value, dict):
item_names, item_values = self.__build_export(value)
item_names = [pre_key + key.lower() + str(i) for i in item_names]
export_names += item_names
export_values += item_values
else:
export_names.append(pre_key + key.lower())
export_values.append(value)
elif isinstance(stats, list):
# Stats is a list (of dict)
# Recursive loop through the list
for item in stats:
item_names, item_values = self.__build_export(item)
export_names += item_names
export_values += item_values
return export_names, export_values | Build the export lists. | Below is the the instruction that describes the task:
### Input:
Build the export lists.
### Response:
def __build_export(self, stats):
"""Build the export lists."""
export_names = []
export_values = []
if isinstance(stats, dict):
# Stats is a dict
# Is there a key ?
if 'key' in iterkeys(stats) and stats['key'] in iterkeys(stats):
pre_key = '{}.'.format(stats[stats['key']])
else:
pre_key = ''
# Walk through the dict
for key, value in iteritems(stats):
if isinstance(value, bool):
value = json.dumps(value)
if isinstance(value, list):
try:
value = value[0]
except IndexError:
value = ''
if isinstance(value, dict):
item_names, item_values = self.__build_export(value)
item_names = [pre_key + key.lower() + str(i) for i in item_names]
export_names += item_names
export_values += item_values
else:
export_names.append(pre_key + key.lower())
export_values.append(value)
elif isinstance(stats, list):
# Stats is a list (of dict)
# Recursive loop through the list
for item in stats:
item_names, item_values = self.__build_export(item)
export_names += item_names
export_values += item_values
return export_names, export_values |
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("SignatureRef", dict(SignatureOID=self.oid))
builder.end("SignatureRef") | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("SignatureRef", dict(SignatureOID=self.oid))
builder.end("SignatureRef") |
def simxCreateDummy(clientID, size, color, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if color != None:
c_color = (ct.c_ubyte*12)(*color)
else:
c_color = None
return c_CreateDummy(clientID, size, c_color, ct.byref(handle), operationMode), handle.value | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxCreateDummy(clientID, size, color, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if color != None:
c_color = (ct.c_ubyte*12)(*color)
else:
c_color = None
return c_CreateDummy(clientID, size, c_color, ct.byref(handle), operationMode), handle.value |
def md_jdbc_virtual_table(key, node):
"""Extract metadata JDBC Virtual Tables from an xml node"""
name = node.find("name")
sql = node.find("sql")
escapeSql = node.find("escapeSql")
escapeSql = escapeSql.text if escapeSql is not None else None
keyColumn = node.find("keyColumn")
keyColumn = keyColumn.text if keyColumn is not None else None
n_g = node.find("geometry")
geometry = JDBCVirtualTableGeometry(n_g.find("name"), n_g.find("type"), n_g.find("srid"))
parameters = []
for n_p in node.findall("parameter"):
p_name = n_p.find("name")
p_defaultValue = n_p.find("defaultValue")
p_defaultValue = p_defaultValue.text if p_defaultValue is not None else None
p_regexpValidator = n_p.find("regexpValidator")
p_regexpValidator = p_regexpValidator.text if p_regexpValidator is not None else None
parameters.append(JDBCVirtualTableParam(p_name, p_defaultValue, p_regexpValidator))
return JDBCVirtualTable(name, sql, escapeSql, geometry, keyColumn, parameters) | Extract metadata JDBC Virtual Tables from an xml node | Below is the the instruction that describes the task:
### Input:
Extract metadata JDBC Virtual Tables from an xml node
### Response:
def md_jdbc_virtual_table(key, node):
"""Extract metadata JDBC Virtual Tables from an xml node"""
name = node.find("name")
sql = node.find("sql")
escapeSql = node.find("escapeSql")
escapeSql = escapeSql.text if escapeSql is not None else None
keyColumn = node.find("keyColumn")
keyColumn = keyColumn.text if keyColumn is not None else None
n_g = node.find("geometry")
geometry = JDBCVirtualTableGeometry(n_g.find("name"), n_g.find("type"), n_g.find("srid"))
parameters = []
for n_p in node.findall("parameter"):
p_name = n_p.find("name")
p_defaultValue = n_p.find("defaultValue")
p_defaultValue = p_defaultValue.text if p_defaultValue is not None else None
p_regexpValidator = n_p.find("regexpValidator")
p_regexpValidator = p_regexpValidator.text if p_regexpValidator is not None else None
parameters.append(JDBCVirtualTableParam(p_name, p_defaultValue, p_regexpValidator))
return JDBCVirtualTable(name, sql, escapeSql, geometry, keyColumn, parameters) |
def strip_context_items(self, a_string):
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This method removes those lines.
"""
strings_to_strip = [
r"\[edit.*\]",
r"\{master:.*\}",
r"\{backup:.*\}",
r"\{line.*\}",
r"\{primary.*\}",
r"\{secondary.*\}",
]
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
for pattern in strings_to_strip:
if re.search(pattern, last_line):
return self.RESPONSE_RETURN.join(response_list[:-1])
return a_string | Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This method removes those lines. | Below is the the instruction that describes the task:
### Input:
Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This method removes those lines.
### Response:
def strip_context_items(self, a_string):
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This method removes those lines.
"""
strings_to_strip = [
r"\[edit.*\]",
r"\{master:.*\}",
r"\{backup:.*\}",
r"\{line.*\}",
r"\{primary.*\}",
r"\{secondary.*\}",
]
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
for pattern in strings_to_strip:
if re.search(pattern, last_line):
return self.RESPONSE_RETURN.join(response_list[:-1])
return a_string |
def _set_state_from_serializeable_fields_and_state(self, state, klass):
""" set only fields from state, which are present in klass.__serialize_fields """
if _debug:
logger.debug("restoring state for class %s", klass)
for field in SerializableMixIn._get_serialize_fields(klass):
if field in state:
# ensure we can set attributes. Log culprits.
try:
setattr(self, field, state.get(field))
except AttributeError:
logger.debug('field: %s', field, exc_info=True)
else:
if _debug:
logger.debug("skipped %s, because it is not contained in state", field) | set only fields from state, which are present in klass.__serialize_fields | Below is the the instruction that describes the task:
### Input:
set only fields from state, which are present in klass.__serialize_fields
### Response:
def _set_state_from_serializeable_fields_and_state(self, state, klass):
""" set only fields from state, which are present in klass.__serialize_fields """
if _debug:
logger.debug("restoring state for class %s", klass)
for field in SerializableMixIn._get_serialize_fields(klass):
if field in state:
# ensure we can set attributes. Log culprits.
try:
setattr(self, field, state.get(field))
except AttributeError:
logger.debug('field: %s', field, exc_info=True)
else:
if _debug:
logger.debug("skipped %s, because it is not contained in state", field) |
def copy_data_from_scenario(resource_attrs, source_scenario_id, target_scenario_id, **kwargs):
"""
For a given list of resource attribute IDS copy the dataset_ids from
the resource scenarios in the source scenario to those in the 'target' scenario.
"""
#Get all the resource scenarios we wish to update
target_resourcescenarios = db.DBSession.query(ResourceScenario).filter(
ResourceScenario.scenario_id==target_scenario_id,
ResourceScenario.resource_attr_id.in_(resource_attrs)).all()
target_rs_dict = {}
for target_rs in target_resourcescenarios:
target_rs_dict[target_rs.resource_attr_id] = target_rs
#get all the resource scenarios we are using to get our datsets source.
source_resourcescenarios = db.DBSession.query(ResourceScenario).filter(
ResourceScenario.scenario_id==source_scenario_id,
ResourceScenario.resource_attr_id.in_(resource_attrs)).all()
#If there is an RS in scenario 'source' but not in 'target', then create
#a new one in 'target'
for source_rs in source_resourcescenarios:
target_rs = target_rs_dict.get(source_rs.resource_attr_id)
if target_rs is not None:
target_rs.dataset_id = source_rs.dataset_id
else:
target_rs = ResourceScenario()
target_rs.scenario_id = target_scenario_id
target_rs.dataset_id = source_rs.dataset_id
target_rs.resource_attr_id = source_rs.resource_attr_id
db.DBSession.add(target_rs)
db.DBSession.flush()
return target_resourcescenarios | For a given list of resource attribute IDS copy the dataset_ids from
the resource scenarios in the source scenario to those in the 'target' scenario. | Below is the the instruction that describes the task:
### Input:
For a given list of resource attribute IDS copy the dataset_ids from
the resource scenarios in the source scenario to those in the 'target' scenario.
### Response:
def copy_data_from_scenario(resource_attrs, source_scenario_id, target_scenario_id, **kwargs):
"""
For a given list of resource attribute IDS copy the dataset_ids from
the resource scenarios in the source scenario to those in the 'target' scenario.
"""
#Get all the resource scenarios we wish to update
target_resourcescenarios = db.DBSession.query(ResourceScenario).filter(
ResourceScenario.scenario_id==target_scenario_id,
ResourceScenario.resource_attr_id.in_(resource_attrs)).all()
target_rs_dict = {}
for target_rs in target_resourcescenarios:
target_rs_dict[target_rs.resource_attr_id] = target_rs
#get all the resource scenarios we are using to get our datsets source.
source_resourcescenarios = db.DBSession.query(ResourceScenario).filter(
ResourceScenario.scenario_id==source_scenario_id,
ResourceScenario.resource_attr_id.in_(resource_attrs)).all()
#If there is an RS in scenario 'source' but not in 'target', then create
#a new one in 'target'
for source_rs in source_resourcescenarios:
target_rs = target_rs_dict.get(source_rs.resource_attr_id)
if target_rs is not None:
target_rs.dataset_id = source_rs.dataset_id
else:
target_rs = ResourceScenario()
target_rs.scenario_id = target_scenario_id
target_rs.dataset_id = source_rs.dataset_id
target_rs.resource_attr_id = source_rs.resource_attr_id
db.DBSession.add(target_rs)
db.DBSession.flush()
return target_resourcescenarios |
def stop(self):
"""Stops the coordinator thread and all related threads."""
if self.interrupted:
return
for thread in self.worker_threads:
thread.interrupted = True
self.interrupted = True | Stops the coordinator thread and all related threads. | Below is the the instruction that describes the task:
### Input:
Stops the coordinator thread and all related threads.
### Response:
def stop(self):
"""Stops the coordinator thread and all related threads."""
if self.interrupted:
return
for thread in self.worker_threads:
thread.interrupted = True
self.interrupted = True |
def notices(self):
"""pops and returns all notices
http://initd.org/psycopg/docs/connection.html#connection.notices
"""
return [self._db.notices.pop()[8:].strip() for x in range(len(self._db.notices))] | pops and returns all notices
http://initd.org/psycopg/docs/connection.html#connection.notices | Below is the the instruction that describes the task:
### Input:
pops and returns all notices
http://initd.org/psycopg/docs/connection.html#connection.notices
### Response:
def notices(self):
"""pops and returns all notices
http://initd.org/psycopg/docs/connection.html#connection.notices
"""
return [self._db.notices.pop()[8:].strip() for x in range(len(self._db.notices))] |
def ajDesinence(self, d):
""" Ajoute la désinence d dans la map des désinences. """
self.lemmatiseur._desinences[deramise(d.gr())].append(d) | Ajoute la désinence d dans la map des désinences. | Below is the the instruction that describes the task:
### Input:
Ajoute la désinence d dans la map des désinences.
### Response:
def ajDesinence(self, d):
""" Ajoute la désinence d dans la map des désinences. """
self.lemmatiseur._desinences[deramise(d.gr())].append(d) |
def _data_dep_init(self, inputs):
"""Data dependent initialization for eager execution."""
with tf.variable_scope("data_dep_init"):
# Generate data dependent init values
activation = self.layer.activation
self.layer.activation = None
x_init = self.layer.call(inputs)
m_init, v_init = tf.moments(x_init, self.norm_axes)
scale_init = 1. / tf.sqrt(v_init + 1e-10)
# Assign data dependent init values
self.layer.g = self.layer.g * scale_init
self.layer.bias = (-m_init * scale_init)
self.layer.activation = activation
self.initialized = True | Data dependent initialization for eager execution. | Below is the the instruction that describes the task:
### Input:
Data dependent initialization for eager execution.
### Response:
def _data_dep_init(self, inputs):
"""Data dependent initialization for eager execution."""
with tf.variable_scope("data_dep_init"):
# Generate data dependent init values
activation = self.layer.activation
self.layer.activation = None
x_init = self.layer.call(inputs)
m_init, v_init = tf.moments(x_init, self.norm_axes)
scale_init = 1. / tf.sqrt(v_init + 1e-10)
# Assign data dependent init values
self.layer.g = self.layer.g * scale_init
self.layer.bias = (-m_init * scale_init)
self.layer.activation = activation
self.initialized = True |
def shutdown_kernel(self, kernel_id):
"""Shutdown a kernel and remove its notebook association."""
self._check_kernel_id(kernel_id)
super(MappingKernelManager, self).shutdown_kernel(kernel_id)
self.delete_mapping_for_kernel(kernel_id)
self.log.info("Kernel shutdown: %s" % kernel_id) | Shutdown a kernel and remove its notebook association. | Below is the the instruction that describes the task:
### Input:
Shutdown a kernel and remove its notebook association.
### Response:
def shutdown_kernel(self, kernel_id):
"""Shutdown a kernel and remove its notebook association."""
self._check_kernel_id(kernel_id)
super(MappingKernelManager, self).shutdown_kernel(kernel_id)
self.delete_mapping_for_kernel(kernel_id)
self.log.info("Kernel shutdown: %s" % kernel_id) |
def find_natural_neighbors(tri, grid_points):
r"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the grid cell center.
Parameters
----------
tri: Object
A Delaunay Triangulation.
grid_points: (X, Y) ndarray
Locations of grids.
Returns
-------
members: dictionary
List of simplex codes for natural neighbor
triangles in 'tri' for each grid cell.
triangle_info: dictionary
Circumcenter and radius information for each
triangle in 'tri'.
"""
tree = cKDTree(grid_points)
in_triangulation = tri.find_simplex(tree.data) >= 0
triangle_info = {}
members = {key: [] for key in range(len(tree.data))}
for i, simplices in enumerate(tri.simplices):
ps = tri.points[simplices]
cc = circumcenter(*ps)
r = circumcircle_radius(*ps)
triangle_info[i] = {'cc': cc, 'r': r}
qualifiers = tree.query_ball_point(cc, r)
for qualifier in qualifiers:
if in_triangulation[qualifier]:
members[qualifier].append(i)
return members, triangle_info | r"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the grid cell center.
Parameters
----------
tri: Object
A Delaunay Triangulation.
grid_points: (X, Y) ndarray
Locations of grids.
Returns
-------
members: dictionary
List of simplex codes for natural neighbor
triangles in 'tri' for each grid cell.
triangle_info: dictionary
Circumcenter and radius information for each
triangle in 'tri'. | Below is the the instruction that describes the task:
### Input:
r"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the grid cell center.
Parameters
----------
tri: Object
A Delaunay Triangulation.
grid_points: (X, Y) ndarray
Locations of grids.
Returns
-------
members: dictionary
List of simplex codes for natural neighbor
triangles in 'tri' for each grid cell.
triangle_info: dictionary
Circumcenter and radius information for each
triangle in 'tri'.
### Response:
def find_natural_neighbors(tri, grid_points):
r"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the grid cell center.
Parameters
----------
tri: Object
A Delaunay Triangulation.
grid_points: (X, Y) ndarray
Locations of grids.
Returns
-------
members: dictionary
List of simplex codes for natural neighbor
triangles in 'tri' for each grid cell.
triangle_info: dictionary
Circumcenter and radius information for each
triangle in 'tri'.
"""
tree = cKDTree(grid_points)
in_triangulation = tri.find_simplex(tree.data) >= 0
triangle_info = {}
members = {key: [] for key in range(len(tree.data))}
for i, simplices in enumerate(tri.simplices):
ps = tri.points[simplices]
cc = circumcenter(*ps)
r = circumcircle_radius(*ps)
triangle_info[i] = {'cc': cc, 'r': r}
qualifiers = tree.query_ball_point(cc, r)
for qualifier in qualifiers:
if in_triangulation[qualifier]:
members[qualifier].append(i)
return members, triangle_info |
def _validate_data(self):
"""Verifies that the data points contained in the class are valid.
"""
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) | Verifies that the data points contained in the class are valid. | Below is the the instruction that describes the task:
### Input:
Verifies that the data points contained in the class are valid.
### Response:
def _validate_data(self):
"""Verifies that the data points contained in the class are valid.
"""
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) |
def setMaxSpeed(self, vehID, speed):
"""setMaxSpeed(string, double) -> None
Sets the maximum speed in m/s for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_MAXSPEED, vehID, speed) | setMaxSpeed(string, double) -> None
Sets the maximum speed in m/s for this vehicle. | Below is the the instruction that describes the task:
### Input:
setMaxSpeed(string, double) -> None
Sets the maximum speed in m/s for this vehicle.
### Response:
def setMaxSpeed(self, vehID, speed):
"""setMaxSpeed(string, double) -> None
Sets the maximum speed in m/s for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_MAXSPEED, vehID, speed) |
def get_initial_status_brok(self, extra=None):
"""
Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok
"""
data = {'uuid': self.uuid}
self.fill_data_brok_from(data, 'full_status')
if extra:
data.update(extra)
return Brok({'type': 'initial_' + self.my_type + '_status', 'data': data}) | Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok | Below is the the instruction that describes the task:
### Input:
Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok
### Response:
def get_initial_status_brok(self, extra=None):
"""
Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok
"""
data = {'uuid': self.uuid}
self.fill_data_brok_from(data, 'full_status')
if extra:
data.update(extra)
return Brok({'type': 'initial_' + self.my_type + '_status', 'data': data}) |
def main():
"""The main entrypoint."""
from optparse import OptionParser
parser = OptionParser(usage="%prog [options]")
parser.add_option(
"--werkzeug-path",
"-p",
dest="path",
default="..",
help="the path to the werkzeug package. defaults to cwd",
)
parser.add_option(
"--compare",
"-c",
dest="compare",
nargs=2,
default=False,
help="compare two hg nodes of Werkzeug",
)
parser.add_option(
"--init-compare",
dest="init_compare",
action="store_true",
default=False,
help="Initializes the comparison feature",
)
options, args = parser.parse_args()
if args:
parser.error("Script takes no arguments")
if options.compare:
compare(*options.compare)
elif options.init_compare:
init_compare()
else:
run(options.path) | The main entrypoint. | Below is the the instruction that describes the task:
### Input:
The main entrypoint.
### Response:
def main():
"""The main entrypoint."""
from optparse import OptionParser
parser = OptionParser(usage="%prog [options]")
parser.add_option(
"--werkzeug-path",
"-p",
dest="path",
default="..",
help="the path to the werkzeug package. defaults to cwd",
)
parser.add_option(
"--compare",
"-c",
dest="compare",
nargs=2,
default=False,
help="compare two hg nodes of Werkzeug",
)
parser.add_option(
"--init-compare",
dest="init_compare",
action="store_true",
default=False,
help="Initializes the comparison feature",
)
options, args = parser.parse_args()
if args:
parser.error("Script takes no arguments")
if options.compare:
compare(*options.compare)
elif options.init_compare:
init_compare()
else:
run(options.path) |
def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
test_list = yaml.safe_load(f)
project_list = test_list['ignore_directories']
except KeyError:
logger.info('No ignore_directories for %s', project)
if project_list:
ignore_directories = ignore_directories + project_list
return ignore_directories
else:
return ignore_directories | Gathers a list of directories to ignore | Below is the the instruction that describes the task:
### Input:
Gathers a list of directories to ignore
### Response:
def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
test_list = yaml.safe_load(f)
project_list = test_list['ignore_directories']
except KeyError:
logger.info('No ignore_directories for %s', project)
if project_list:
ignore_directories = ignore_directories + project_list
return ignore_directories
else:
return ignore_directories |
def preprocessing(aws_config, ip_ranges = [], ip_ranges_name_key = None):
"""
Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param aws_config:
:return:
"""
map_all_sgs(aws_config)
map_all_subnets(aws_config)
set_emr_vpc_ids(aws_config)
#parse_elb_policies(aws_config)
# Various data processing calls
add_security_group_name_to_ec2_grants(aws_config['services']['ec2'], aws_config['aws_account_id'])
process_cloudtrail_trails(aws_config['services']['cloudtrail'])
add_cidr_display_name(aws_config, ip_ranges, ip_ranges_name_key)
merge_route53_and_route53domains(aws_config)
match_instances_and_roles(aws_config)
match_iam_policies_and_buckets(aws_config)
# Preprocessing dictated by metadata
process_metadata_callbacks(aws_config) | Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param aws_config:
:return: | Below is the the instruction that describes the task:
### Input:
Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param aws_config:
:return:
### Response:
def preprocessing(aws_config, ip_ranges = [], ip_ranges_name_key = None):
"""
Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param aws_config:
:return:
"""
map_all_sgs(aws_config)
map_all_subnets(aws_config)
set_emr_vpc_ids(aws_config)
#parse_elb_policies(aws_config)
# Various data processing calls
add_security_group_name_to_ec2_grants(aws_config['services']['ec2'], aws_config['aws_account_id'])
process_cloudtrail_trails(aws_config['services']['cloudtrail'])
add_cidr_display_name(aws_config, ip_ranges, ip_ranges_name_key)
merge_route53_and_route53domains(aws_config)
match_instances_and_roles(aws_config)
match_iam_policies_and_buckets(aws_config)
# Preprocessing dictated by metadata
process_metadata_callbacks(aws_config) |
def print_progress(file=None):
"""!
@brief Progress printer factory.
This factory function checks whether the output file is a TTY, and instantiates the
appropriate subclass of ProgressReport.
@param file The output file. Optional. If not provided, or if set to None, then sys.stdout
will be used automatically.
"""
if file is None:
file = sys.stdout
try:
istty = os.isatty(file.fileno())
except (OSError, AttributeError):
# Either the file doesn't have a fileno method, or calling it returned an
# error. In either case, just assume we're not connected to a TTY.
istty = False
klass = ProgressReportTTY if istty else ProgressReportNoTTY
return klass(file) | !
@brief Progress printer factory.
This factory function checks whether the output file is a TTY, and instantiates the
appropriate subclass of ProgressReport.
@param file The output file. Optional. If not provided, or if set to None, then sys.stdout
will be used automatically. | Below is the the instruction that describes the task:
### Input:
!
@brief Progress printer factory.
This factory function checks whether the output file is a TTY, and instantiates the
appropriate subclass of ProgressReport.
@param file The output file. Optional. If not provided, or if set to None, then sys.stdout
will be used automatically.
### Response:
def print_progress(file=None):
"""!
@brief Progress printer factory.
This factory function checks whether the output file is a TTY, and instantiates the
appropriate subclass of ProgressReport.
@param file The output file. Optional. If not provided, or if set to None, then sys.stdout
will be used automatically.
"""
if file is None:
file = sys.stdout
try:
istty = os.isatty(file.fileno())
except (OSError, AttributeError):
# Either the file doesn't have a fileno method, or calling it returned an
# error. In either case, just assume we're not connected to a TTY.
istty = False
klass = ProgressReportTTY if istty else ProgressReportNoTTY
return klass(file) |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant Apple Account entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
"""
accounts = match.get('Accounts', {})
for name_account, account in iter(accounts.items()):
first_name = account.get('FirstName', '<FirstName>')
last_name = account.get('LastName', '<LastName>')
general_description = '{0:s} ({1:s} {2:s})'.format(
name_account, first_name, last_name)
event_data = plist_event.PlistTimeEventData()
event_data.key = name_account
event_data.root = '/Accounts'
datetime_value = account.get('CreationDate', None)
if datetime_value:
event_data.desc = 'Configured Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data)
datetime_value = account.get('LastSuccessfulConnect', None)
if datetime_value:
event_data.desc = 'Connected Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data)
datetime_value = account.get('ValidationDate', None)
if datetime_value:
event_data.desc = 'Last validation Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data) | Extracts relevant Apple Account entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | Below is the the instruction that describes the task:
### Input:
Extracts relevant Apple Account entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
### Response:
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant Apple Account entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
"""
accounts = match.get('Accounts', {})
for name_account, account in iter(accounts.items()):
first_name = account.get('FirstName', '<FirstName>')
last_name = account.get('LastName', '<LastName>')
general_description = '{0:s} ({1:s} {2:s})'.format(
name_account, first_name, last_name)
event_data = plist_event.PlistTimeEventData()
event_data.key = name_account
event_data.root = '/Accounts'
datetime_value = account.get('CreationDate', None)
if datetime_value:
event_data.desc = 'Configured Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data)
datetime_value = account.get('LastSuccessfulConnect', None)
if datetime_value:
event_data.desc = 'Connected Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data)
datetime_value = account.get('ValidationDate', None)
if datetime_value:
event_data.desc = 'Last validation Apple account {0:s}'.format(
general_description)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data) |
def add_log_callback(callback):
"""Adds a log callback."""
global _log_callbacks
if not callable(callback):
raise ValueError("Callback must be callable")
_log_callbacks.add(callback)
return callback | Adds a log callback. | Below is the the instruction that describes the task:
### Input:
Adds a log callback.
### Response:
def add_log_callback(callback):
"""Adds a log callback."""
global _log_callbacks
if not callable(callback):
raise ValueError("Callback must be callable")
_log_callbacks.add(callback)
return callback |
def protein_statistics(self):
"""Get a dictionary of basic statistics describing this protein"""
# TODO: can i use get_dict here instead
d = {}
d['id'] = self.id
d['sequences'] = [x.id for x in self.sequences]
d['num_sequences'] = self.num_sequences
if self.representative_sequence:
d['representative_sequence'] = self.representative_sequence.id
d['repseq_gene_name'] = self.representative_sequence.gene_name
d['repseq_uniprot'] = self.representative_sequence.uniprot
d['repseq_description'] = self.representative_sequence.description
d['num_structures'] = self.num_structures
d['experimental_structures'] = [x.id for x in self.get_experimental_structures()]
d['num_experimental_structures'] = self.num_structures_experimental
d['homology_models'] = [x.id for x in self.get_homology_models()]
d['num_homology_models'] = self.num_structures_homology
if self.representative_structure:
d['representative_structure'] = self.representative_structure.id
d['representative_chain'] = self.representative_chain
d['representative_chain_seq_coverage'] = self.representative_chain_seq_coverage
d['repstruct_description'] = self.description
if self.representative_structure.is_experimental:
d['repstruct_resolution'] = self.representative_structure.resolution
d['num_sequence_alignments'] = len(self.sequence_alignments)
d['num_structure_alignments'] = len(self.structure_alignments)
return d | Get a dictionary of basic statistics describing this protein | Below is the the instruction that describes the task:
### Input:
Get a dictionary of basic statistics describing this protein
### Response:
def protein_statistics(self):
"""Get a dictionary of basic statistics describing this protein"""
# TODO: can i use get_dict here instead
d = {}
d['id'] = self.id
d['sequences'] = [x.id for x in self.sequences]
d['num_sequences'] = self.num_sequences
if self.representative_sequence:
d['representative_sequence'] = self.representative_sequence.id
d['repseq_gene_name'] = self.representative_sequence.gene_name
d['repseq_uniprot'] = self.representative_sequence.uniprot
d['repseq_description'] = self.representative_sequence.description
d['num_structures'] = self.num_structures
d['experimental_structures'] = [x.id for x in self.get_experimental_structures()]
d['num_experimental_structures'] = self.num_structures_experimental
d['homology_models'] = [x.id for x in self.get_homology_models()]
d['num_homology_models'] = self.num_structures_homology
if self.representative_structure:
d['representative_structure'] = self.representative_structure.id
d['representative_chain'] = self.representative_chain
d['representative_chain_seq_coverage'] = self.representative_chain_seq_coverage
d['repstruct_description'] = self.description
if self.representative_structure.is_experimental:
d['repstruct_resolution'] = self.representative_structure.resolution
d['num_sequence_alignments'] = len(self.sequence_alignments)
d['num_structure_alignments'] = len(self.structure_alignments)
return d |
def get_limits(self):
""" Return the limits of this task """
vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits)
return vals[0] if len(vals) else self._limits | Return the limits of this task | Below is the the instruction that describes the task:
### Input:
Return the limits of this task
### Response:
def get_limits(self):
""" Return the limits of this task """
vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits)
return vals[0] if len(vals) else self._limits |
def draw(self, X, y, **kwargs):
"""
Called from the fit method, this method creates the parallel
coordinates canvas and draws each instance and vertical lines on it.
Parameters
----------
X : ndarray of shape n x m
A matrix of n instances with m features
y : ndarray of length n
An array or series of target or class values
kwargs : dict
Pass generic arguments to the drawing method
"""
if self.fast:
return self.draw_classes(X, y, **kwargs)
return self.draw_instances(X, y, **kwargs) | Called from the fit method, this method creates the parallel
coordinates canvas and draws each instance and vertical lines on it.
Parameters
----------
X : ndarray of shape n x m
A matrix of n instances with m features
y : ndarray of length n
An array or series of target or class values
kwargs : dict
Pass generic arguments to the drawing method | Below is the the instruction that describes the task:
### Input:
Called from the fit method, this method creates the parallel
coordinates canvas and draws each instance and vertical lines on it.
Parameters
----------
X : ndarray of shape n x m
A matrix of n instances with m features
y : ndarray of length n
An array or series of target or class values
kwargs : dict
Pass generic arguments to the drawing method
### Response:
def draw(self, X, y, **kwargs):
"""
Called from the fit method, this method creates the parallel
coordinates canvas and draws each instance and vertical lines on it.
Parameters
----------
X : ndarray of shape n x m
A matrix of n instances with m features
y : ndarray of length n
An array or series of target or class values
kwargs : dict
Pass generic arguments to the drawing method
"""
if self.fast:
return self.draw_classes(X, y, **kwargs)
return self.draw_instances(X, y, **kwargs) |
def goto_line(self):
"""
Shows the *go to line dialog* and go to the selected line.
"""
helper = TextHelper(self)
line, result = DlgGotoLine.get_line(
self, helper.current_line_nbr(), helper.line_count())
if not result:
return
return helper.goto_line(line, move=True) | Shows the *go to line dialog* and go to the selected line. | Below is the the instruction that describes the task:
### Input:
Shows the *go to line dialog* and go to the selected line.
### Response:
def goto_line(self):
"""
Shows the *go to line dialog* and go to the selected line.
"""
helper = TextHelper(self)
line, result = DlgGotoLine.get_line(
self, helper.current_line_nbr(), helper.line_count())
if not result:
return
return helper.goto_line(line, move=True) |
def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None):
"""Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not route.trips:
return None
trips = list(route.trips)
trips.sort(key=lambda x: x.trip_id)
trips_folder = self._CreateFolder(parent, 'Trips', visible=False)
for trip in trips:
if (self.date_filter and
not trip.service_period.IsActiveOn(self.date_filter)):
continue
if trip.trip_headsign:
description = 'Headsign: %s' % trip.trip_headsign
else:
description = None
coordinate_list = []
for secs, stoptime, tp in trip.GetTimeInterpolatedStops():
if self.altitude_per_sec > 0:
coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat,
(secs - 3600 * 4) * self.altitude_per_sec))
else:
coordinate_list.append((stoptime.stop.stop_lon,
stoptime.stop.stop_lat))
placemark = self._CreatePlacemark(trips_folder,
trip.trip_id,
style_id=style_id,
visible=False,
description=description)
self._CreateLineString(placemark, coordinate_list)
return trips_folder | Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None. | Below is the the instruction that describes the task:
### Input:
Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None.
### Response:
def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None):
"""Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not route.trips:
return None
trips = list(route.trips)
trips.sort(key=lambda x: x.trip_id)
trips_folder = self._CreateFolder(parent, 'Trips', visible=False)
for trip in trips:
if (self.date_filter and
not trip.service_period.IsActiveOn(self.date_filter)):
continue
if trip.trip_headsign:
description = 'Headsign: %s' % trip.trip_headsign
else:
description = None
coordinate_list = []
for secs, stoptime, tp in trip.GetTimeInterpolatedStops():
if self.altitude_per_sec > 0:
coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat,
(secs - 3600 * 4) * self.altitude_per_sec))
else:
coordinate_list.append((stoptime.stop.stop_lon,
stoptime.stop.stop_lat))
placemark = self._CreatePlacemark(trips_folder,
trip.trip_id,
style_id=style_id,
visible=False,
description=description)
self._CreateLineString(placemark, coordinate_list)
return trips_folder |
def mv_data_dir(target):
"""
Move data_dir to {target} location, refineable in case data_dir is a mounted volume or object storage and needs special treatments
:return:
"""
from django_productline.context import PRODUCT_CONTEXT
os.rename(PRODUCT_CONTEXT.DATA_DIR, target) | Move data_dir to {target} location, refineable in case data_dir is a mounted volume or object storage and needs special treatments
:return: | Below is the the instruction that describes the task:
### Input:
Move data_dir to {target} location, refineable in case data_dir is a mounted volume or object storage and needs special treatments
:return:
### Response:
def mv_data_dir(target):
"""
Move data_dir to {target} location, refineable in case data_dir is a mounted volume or object storage and needs special treatments
:return:
"""
from django_productline.context import PRODUCT_CONTEXT
os.rename(PRODUCT_CONTEXT.DATA_DIR, target) |
def close(self):
"""
Just send a message off to all the pool members which contains
the special :class:`_close_pool_message` sentinel.
"""
if self.is_master():
for i in range(self.size):
self.comm.isend(_close_pool_message(), dest=i + 1) | Just send a message off to all the pool members which contains
the special :class:`_close_pool_message` sentinel. | Below is the the instruction that describes the task:
### Input:
Just send a message off to all the pool members which contains
the special :class:`_close_pool_message` sentinel.
### Response:
def close(self):
"""
Just send a message off to all the pool members which contains
the special :class:`_close_pool_message` sentinel.
"""
if self.is_master():
for i in range(self.size):
self.comm.isend(_close_pool_message(), dest=i + 1) |
def severity(self, severity):
"""Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str
"""
if severity is None:
raise ValueError("Invalid value for `severity`, must not be `None`") # noqa: E501
allowed_values = ["MARKETING", "INFO", "WARN", "SEVERE"] # noqa: E501
if severity not in allowed_values:
raise ValueError(
"Invalid value for `severity` ({0}), must be one of {1}" # noqa: E501
.format(severity, allowed_values)
)
self._severity = severity | Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str
### Response:
def severity(self, severity):
"""Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str
"""
if severity is None:
raise ValueError("Invalid value for `severity`, must not be `None`") # noqa: E501
allowed_values = ["MARKETING", "INFO", "WARN", "SEVERE"] # noqa: E501
if severity not in allowed_values:
raise ValueError(
"Invalid value for `severity` ({0}), must be one of {1}" # noqa: E501
.format(severity, allowed_values)
)
self._severity = severity |
def _submit_to_queue(self, script_file):
"""Submit a job script to the queue."""
if sys.version_info[0] < 3:
process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE)
else:
# need string not bytes so must use universal_newlines
process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE, universal_newlines=True)
out, err = process.communicate()
# grab the return code. PBS returns 0 if the job was successful
queue_id = None
if process.returncode == 0:
try:
# output should of the form '2561553.sdb' or '352353.jessup' - just grab the first part for job id
queue_id = int(out.split('.')[0])
except:
# probably error parsing job code
logger.critical("Could not parse job id following qsub...")
return SubmitResults(qid=queue_id, out=out, err=err, process=process) | Submit a job script to the queue. | Below is the the instruction that describes the task:
### Input:
Submit a job script to the queue.
### Response:
def _submit_to_queue(self, script_file):
"""Submit a job script to the queue."""
if sys.version_info[0] < 3:
process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE)
else:
# need string not bytes so must use universal_newlines
process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE, universal_newlines=True)
out, err = process.communicate()
# grab the return code. PBS returns 0 if the job was successful
queue_id = None
if process.returncode == 0:
try:
# output should of the form '2561553.sdb' or '352353.jessup' - just grab the first part for job id
queue_id = int(out.split('.')[0])
except:
# probably error parsing job code
logger.critical("Could not parse job id following qsub...")
return SubmitResults(qid=queue_id, out=out, err=err, process=process) |
def rename(self, new_name_or_name_dict=None, **names):
"""Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names to new names for coordinates. Otherwise, use the argument
as the new name for this array.
**names, optional
The keyword arguments form of a mapping from old names to
new names for coordinates.
One of new_name_or_name_dict or names must be provided.
Returns
-------
renamed : DataArray
Renamed array or array with renamed coordinates.
See Also
--------
Dataset.rename
DataArray.swap_dims
"""
if names or utils.is_dict_like(new_name_or_name_dict):
name_dict = either_dict_or_kwargs(
new_name_or_name_dict, names, 'rename')
dataset = self._to_temp_dataset().rename(name_dict)
return self._from_temp_dataset(dataset)
else:
return self._replace(name=new_name_or_name_dict) | Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names to new names for coordinates. Otherwise, use the argument
as the new name for this array.
**names, optional
The keyword arguments form of a mapping from old names to
new names for coordinates.
One of new_name_or_name_dict or names must be provided.
Returns
-------
renamed : DataArray
Renamed array or array with renamed coordinates.
See Also
--------
Dataset.rename
DataArray.swap_dims | Below is the the instruction that describes the task:
### Input:
Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names to new names for coordinates. Otherwise, use the argument
as the new name for this array.
**names, optional
The keyword arguments form of a mapping from old names to
new names for coordinates.
One of new_name_or_name_dict or names must be provided.
Returns
-------
renamed : DataArray
Renamed array or array with renamed coordinates.
See Also
--------
Dataset.rename
DataArray.swap_dims
### Response:
def rename(self, new_name_or_name_dict=None, **names):
"""Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names to new names for coordinates. Otherwise, use the argument
as the new name for this array.
**names, optional
The keyword arguments form of a mapping from old names to
new names for coordinates.
One of new_name_or_name_dict or names must be provided.
Returns
-------
renamed : DataArray
Renamed array or array with renamed coordinates.
See Also
--------
Dataset.rename
DataArray.swap_dims
"""
if names or utils.is_dict_like(new_name_or_name_dict):
name_dict = either_dict_or_kwargs(
new_name_or_name_dict, names, 'rename')
dataset = self._to_temp_dataset().rename(name_dict)
return self._from_temp_dataset(dataset)
else:
return self._replace(name=new_name_or_name_dict) |
def _get_branch_opts(branch, local_branch, all_local_branches,
desired_upstream, git_ver=None):
'''
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
'''
if branch is not None and branch not in all_local_branches:
# We won't be setting upstream because the act of checking out a new
# branch will set upstream for us
return None
if git_ver is None:
git_ver = _LooseVersion(__salt__['git.version'](versioninfo=False))
ret = []
if git_ver >= _LooseVersion('1.8.0'):
ret.extend(['--set-upstream-to', desired_upstream])
else:
ret.append('--set-upstream')
# --set-upstream does not assume the current branch, so we have to
# tell it which branch we'll be using
ret.append(local_branch if branch is None else branch)
ret.append(desired_upstream)
return ret | DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch | Below is the the instruction that describes the task:
### Input:
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
### Response:
def _get_branch_opts(branch, local_branch, all_local_branches,
desired_upstream, git_ver=None):
'''
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
'''
if branch is not None and branch not in all_local_branches:
# We won't be setting upstream because the act of checking out a new
# branch will set upstream for us
return None
if git_ver is None:
git_ver = _LooseVersion(__salt__['git.version'](versioninfo=False))
ret = []
if git_ver >= _LooseVersion('1.8.0'):
ret.extend(['--set-upstream-to', desired_upstream])
else:
ret.append('--set-upstream')
# --set-upstream does not assume the current branch, so we have to
# tell it which branch we'll be using
ret.append(local_branch if branch is None else branch)
ret.append(desired_upstream)
return ret |
def feature_names(self, feature_names):
"""Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names
"""
if feature_names is not None:
# validate feature name
try:
if not isinstance(feature_names, str):
feature_names = [n for n in iter(feature_names)]
else:
feature_names = [feature_names]
except TypeError:
feature_names = [feature_names]
if len(feature_names) != len(set(feature_names)):
raise ValueError('feature_names must be unique')
if len(feature_names) != self.num_col():
msg = 'feature_names must have the same length as data'
raise ValueError(msg)
# prohibit to use symbols may affect to parse. e.g. []<
if not all(isinstance(f, STRING_TYPES) and
not any(x in f for x in set(('[', ']', '<')))
for f in feature_names):
raise ValueError('feature_names may not contain [, ] or <')
else:
# reset feature_types also
self.feature_types = None
self._feature_names = feature_names | Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names | Below is the the instruction that describes the task:
### Input:
Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names
### Response:
def feature_names(self, feature_names):
"""Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names
"""
if feature_names is not None:
# validate feature name
try:
if not isinstance(feature_names, str):
feature_names = [n for n in iter(feature_names)]
else:
feature_names = [feature_names]
except TypeError:
feature_names = [feature_names]
if len(feature_names) != len(set(feature_names)):
raise ValueError('feature_names must be unique')
if len(feature_names) != self.num_col():
msg = 'feature_names must have the same length as data'
raise ValueError(msg)
# prohibit to use symbols may affect to parse. e.g. []<
if not all(isinstance(f, STRING_TYPES) and
not any(x in f for x in set(('[', ']', '<')))
for f in feature_names):
raise ValueError('feature_names may not contain [, ] or <')
else:
# reset feature_types also
self.feature_types = None
self._feature_names = feature_names |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Rekey request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the payload is missing the unique identifier.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier is not None:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
else:
raise ValueError(
"The Rekey response payload is missing the unique identifier."
)
if self._template_attribute is not None:
self._template_attribute.write(
local_stream,
kmip_version=kmip_version
)
self.length = local_stream.length()
super(RekeyResponsePayload, self).write(
output_stream,
kmip_version=kmip_version
)
output_stream.write(local_stream.buffer) | Write the data encoding the Rekey request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the payload is missing the unique identifier. | Below is the the instruction that describes the task:
### Input:
Write the data encoding the Rekey request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the payload is missing the unique identifier.
### Response:
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Rekey request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the payload is missing the unique identifier.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier is not None:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
else:
raise ValueError(
"The Rekey response payload is missing the unique identifier."
)
if self._template_attribute is not None:
self._template_attribute.write(
local_stream,
kmip_version=kmip_version
)
self.length = local_stream.length()
super(RekeyResponsePayload, self).write(
output_stream,
kmip_version=kmip_version
)
output_stream.write(local_stream.buffer) |
def get_multisample_vcf(fnames, name, caller, data):
"""Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches.
"""
unique_fnames = []
for f in fnames:
if f not in unique_fnames:
unique_fnames.append(f)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
if len(unique_fnames) > 1:
gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller))
vrn_file_batch = None
for variant in data.get("variants", []):
if variant["variantcaller"] == caller and variant.get("vrn_file_batch"):
vrn_file_batch = variant["vrn_file_batch"]
if vrn_file_batch:
utils.symlink_plus(vrn_file_batch, gemini_vcf)
return gemini_vcf
else:
return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, dd.get_ref_file(data),
data["config"])
else:
gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1]))
utils.symlink_plus(unique_fnames[0], gemini_vcf)
return gemini_vcf | Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches. | Below is the the instruction that describes the task:
### Input:
Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches.
### Response:
def get_multisample_vcf(fnames, name, caller, data):
"""Retrieve a multiple sample VCF file in a standard location.
Handles inputs with multiple repeated input files from batches.
"""
unique_fnames = []
for f in fnames:
if f not in unique_fnames:
unique_fnames.append(f)
out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini"))
if len(unique_fnames) > 1:
gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller))
vrn_file_batch = None
for variant in data.get("variants", []):
if variant["variantcaller"] == caller and variant.get("vrn_file_batch"):
vrn_file_batch = variant["vrn_file_batch"]
if vrn_file_batch:
utils.symlink_plus(vrn_file_batch, gemini_vcf)
return gemini_vcf
else:
return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, dd.get_ref_file(data),
data["config"])
else:
gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1]))
utils.symlink_plus(unique_fnames[0], gemini_vcf)
return gemini_vcf |
def CreateUser(self, database_link, user, options=None):
"""Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:return:
The created User.
:rtype:
dict
"""
if options is None:
options = {}
database_id, path = self._GetDatabaseIdWithPathForUser(database_link, user)
return self.Create(user,
path,
'users',
database_id,
None,
options) | Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:return:
The created User.
:rtype:
dict | Below is the the instruction that describes the task:
### Input:
Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:return:
The created User.
:rtype:
dict
### Response:
def CreateUser(self, database_link, user, options=None):
"""Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:return:
The created User.
:rtype:
dict
"""
if options is None:
options = {}
database_id, path = self._GetDatabaseIdWithPathForUser(database_link, user)
return self.Create(user,
path,
'users',
database_id,
None,
options) |
def view(cls, request, response):
"""
Entry-point of the request / response cycle; Handles resource creation
and delegation.
@param[in] requset
The HTTP request object; containing accessors for information
about the request.
@param[in] response
The HTTP response object; contains accessors for modifying
the information that will be sent to the client.
"""
# Determine if we need to redirect.
test = cls.meta.trailing_slash
if test ^ request.path.endswith('/'):
# Construct a new URL by removing or adding the trailing slash.
path = request.path + '/' if test else request.path[:-1]
response['Location'] = '{}://{}{}{}{}'.format(
request.protocol.lower(),
request.host,
request.mount_point,
path,
'?' + request.query if request.query else '')
# Redirect to the version with the correct trailing slash.
return cls.redirect(request, response)
try:
# Instantiate the resource.
obj = cls(request, response)
# Bind the request and response objects to the constructed
# resource.
request.bind(obj)
response.bind(obj)
# Bind the request object to the resource.
# This is used to facilitate the serializer and deserializer.
obj._request = request
# Initiate the dispatch cycle and handle its result on
# synchronous requests.
result = obj.dispatch(request, response)
if not response.asynchronous:
# There is several things that dispatch is allowed to return.
if (isinstance(result, collections.Iterable) and
not isinstance(result, six.string_types)):
# Return the stream generator.
return cls.stream(response, result)
else:
# Leave it up to the response to throw or write whatever
# we got back.
response.end(result)
if response.body:
# Return the body if there was any set.
return response.body
except http.exceptions.BaseHTTPException as e:
# Something that we can handle and return properly happened.
# Set response properties from the exception.
response.status = e.status
response.headers.update(e.headers)
if e.content:
# Write the exception body if present and close
# the response.
# TODO: Use the plain-text encoder.
response.send(e.content, serialize=True, format='json')
# Terminate the connection and return the body.
response.close()
if response.body:
return response.body
except Exception:
# Something unexpected happened.
# Log error message to the logger.
logger.exception('Internal server error')
# Write a debug message for the client.
if not response.streaming and not response.closed:
response.status = http.client.INTERNAL_SERVER_ERROR
response.headers.clear()
response.close() | Entry-point of the request / response cycle; Handles resource creation
and delegation.
@param[in] requset
The HTTP request object; containing accessors for information
about the request.
@param[in] response
The HTTP response object; contains accessors for modifying
the information that will be sent to the client. | Below is the the instruction that describes the task:
### Input:
Entry-point of the request / response cycle; Handles resource creation
and delegation.
@param[in] requset
The HTTP request object; containing accessors for information
about the request.
@param[in] response
The HTTP response object; contains accessors for modifying
the information that will be sent to the client.
### Response:
def view(cls, request, response):
"""
Entry-point of the request / response cycle; Handles resource creation
and delegation.
@param[in] requset
The HTTP request object; containing accessors for information
about the request.
@param[in] response
The HTTP response object; contains accessors for modifying
the information that will be sent to the client.
"""
# Determine if we need to redirect.
test = cls.meta.trailing_slash
if test ^ request.path.endswith('/'):
# Construct a new URL by removing or adding the trailing slash.
path = request.path + '/' if test else request.path[:-1]
response['Location'] = '{}://{}{}{}{}'.format(
request.protocol.lower(),
request.host,
request.mount_point,
path,
'?' + request.query if request.query else '')
# Redirect to the version with the correct trailing slash.
return cls.redirect(request, response)
try:
# Instantiate the resource.
obj = cls(request, response)
# Bind the request and response objects to the constructed
# resource.
request.bind(obj)
response.bind(obj)
# Bind the request object to the resource.
# This is used to facilitate the serializer and deserializer.
obj._request = request
# Initiate the dispatch cycle and handle its result on
# synchronous requests.
result = obj.dispatch(request, response)
if not response.asynchronous:
# There is several things that dispatch is allowed to return.
if (isinstance(result, collections.Iterable) and
not isinstance(result, six.string_types)):
# Return the stream generator.
return cls.stream(response, result)
else:
# Leave it up to the response to throw or write whatever
# we got back.
response.end(result)
if response.body:
# Return the body if there was any set.
return response.body
except http.exceptions.BaseHTTPException as e:
# Something that we can handle and return properly happened.
# Set response properties from the exception.
response.status = e.status
response.headers.update(e.headers)
if e.content:
# Write the exception body if present and close
# the response.
# TODO: Use the plain-text encoder.
response.send(e.content, serialize=True, format='json')
# Terminate the connection and return the body.
response.close()
if response.body:
return response.body
except Exception:
# Something unexpected happened.
# Log error message to the logger.
logger.exception('Internal server error')
# Write a debug message for the client.
if not response.streaming and not response.closed:
response.status = http.client.INTERNAL_SERVER_ERROR
response.headers.clear()
response.close() |
def _initialize_memory(self, policy_params):
"""Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episodes
memory serves to collect multiple episodes in parallel. Finished episodes
are copied into the next free slot of the second memory. The memory index
points to the next free slot.
"""
# We store observation, action, policy parameters, and reward.
template = (
self._batch_env.observ[0],
self._batch_env.action[0],
tools.nested.map(lambda x: x[0, 0], policy_params),
self._batch_env.reward[0])
with tf.variable_scope('ppo_temporary'):
self._current_episodes = parts.EpisodeMemory(
template, len(self._batch_env), self._config.max_length, 'episodes')
self._finished_episodes = parts.EpisodeMemory(
template, self._config.update_every, self._config.max_length, 'memory')
self._num_finished_episodes = tf.Variable(0, False) | Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episodes
memory serves to collect multiple episodes in parallel. Finished episodes
are copied into the next free slot of the second memory. The memory index
points to the next free slot. | Below is the the instruction that describes the task:
### Input:
Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episodes
memory serves to collect multiple episodes in parallel. Finished episodes
are copied into the next free slot of the second memory. The memory index
points to the next free slot.
### Response:
def _initialize_memory(self, policy_params):
"""Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episodes
memory serves to collect multiple episodes in parallel. Finished episodes
are copied into the next free slot of the second memory. The memory index
points to the next free slot.
"""
# We store observation, action, policy parameters, and reward.
template = (
self._batch_env.observ[0],
self._batch_env.action[0],
tools.nested.map(lambda x: x[0, 0], policy_params),
self._batch_env.reward[0])
with tf.variable_scope('ppo_temporary'):
self._current_episodes = parts.EpisodeMemory(
template, len(self._batch_env), self._config.max_length, 'episodes')
self._finished_episodes = parts.EpisodeMemory(
template, self._config.update_every, self._config.max_length, 'memory')
self._num_finished_episodes = tf.Variable(0, False) |
def insert(self):
"""persist the .fields"""
self.default_val = 0
#fields = self.fields
#fields = self.orm_class.depart(self.fields, is_update=False)
#self.set_fields(fields)
return self.interface.insert(
self.schema,
self.fields
)
return self.interface.insert(self.schema, self.fields) | persist the .fields | Below is the the instruction that describes the task:
### Input:
persist the .fields
### Response:
def insert(self):
"""persist the .fields"""
self.default_val = 0
#fields = self.fields
#fields = self.orm_class.depart(self.fields, is_update=False)
#self.set_fields(fields)
return self.interface.insert(
self.schema,
self.fields
)
return self.interface.insert(self.schema, self.fields) |
def num_qubits(self) -> Optional[int]:
"""Returns number of qubits in the domain if known, None if unknown."""
if not self:
return None
any_gate = next(iter(self))
return any_gate.num_qubits() | Returns number of qubits in the domain if known, None if unknown. | Below is the the instruction that describes the task:
### Input:
Returns number of qubits in the domain if known, None if unknown.
### Response:
def num_qubits(self) -> Optional[int]:
"""Returns number of qubits in the domain if known, None if unknown."""
if not self:
return None
any_gate = next(iter(self))
return any_gate.num_qubits() |
def _override_dependencies_globals():
"""
Overrides dependencies globals.
"""
foundations.globals.constants.Constants.logger = manager.globals.constants.Constants.logger = Constants.logger
foundations.globals.constants.Constants.application_directory = \
manager.globals.constants.Constants.application_directory = Constants.application_directory | Overrides dependencies globals. | Below is the the instruction that describes the task:
### Input:
Overrides dependencies globals.
### Response:
def _override_dependencies_globals():
"""
Overrides dependencies globals.
"""
foundations.globals.constants.Constants.logger = manager.globals.constants.Constants.logger = Constants.logger
foundations.globals.constants.Constants.application_directory = \
manager.globals.constants.Constants.application_directory = Constants.application_directory |
def get_derived_metric_by_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific historical version of a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_derived_metric_by_version(id, version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param int version: (required)
:return: ResponseContainerDerivedMetricDefinition
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_derived_metric_by_version_with_http_info(id, version, **kwargs) # noqa: E501
else:
(data) = self.get_derived_metric_by_version_with_http_info(id, version, **kwargs) # noqa: E501
return data | Get a specific historical version of a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_derived_metric_by_version(id, version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param int version: (required)
:return: ResponseContainerDerivedMetricDefinition
If the method is called asynchronously,
returns the request thread. | Below is the the instruction that describes the task:
### Input:
Get a specific historical version of a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_derived_metric_by_version(id, version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param int version: (required)
:return: ResponseContainerDerivedMetricDefinition
If the method is called asynchronously,
returns the request thread.
### Response:
def get_derived_metric_by_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific historical version of a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_derived_metric_by_version(id, version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param int version: (required)
:return: ResponseContainerDerivedMetricDefinition
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_derived_metric_by_version_with_http_info(id, version, **kwargs) # noqa: E501
else:
(data) = self.get_derived_metric_by_version_with_http_info(id, version, **kwargs) # noqa: E501
return data |
def fetch_events_for_issues_and_pr(self):
"""
Fetch event for issues and pull requests
@return [Array] array of fetched issues
"""
# Async fetching events:
self.fetcher.fetch_events_async(self.issues, "issues")
self.fetcher.fetch_events_async(self.pull_requests, "pull requests") | Fetch event for issues and pull requests
@return [Array] array of fetched issues | Below is the the instruction that describes the task:
### Input:
Fetch event for issues and pull requests
@return [Array] array of fetched issues
### Response:
def fetch_events_for_issues_and_pr(self):
"""
Fetch event for issues and pull requests
@return [Array] array of fetched issues
"""
# Async fetching events:
self.fetcher.fetch_events_async(self.issues, "issues")
self.fetcher.fetch_events_async(self.pull_requests, "pull requests") |
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'):
"""Download a lab class from the relevant course
:param course: the course short name to download the class from.
:type course: string
:param reference: reference to the course for downloading the class.
:type reference: string
:param github: github repo for downloading the course from.
:type string: github repo for downloading the lab."""
github_stub = 'https://raw.githubusercontent.com/'
if not name.endswith('.ipynb'):
name += '.ipynb'
from pods.util import download_url
download_url(os.path.join(github_stub, github, course, name), store_directory=course) | Download a lab class from the relevant course
:param course: the course short name to download the class from.
:type course: string
:param reference: reference to the course for downloading the class.
:type reference: string
:param github: github repo for downloading the course from.
:type string: github repo for downloading the lab. | Below is the the instruction that describes the task:
### Input:
Download a lab class from the relevant course
:param course: the course short name to download the class from.
:type course: string
:param reference: reference to the course for downloading the class.
:type reference: string
:param github: github repo for downloading the course from.
:type string: github repo for downloading the lab.
### Response:
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'):
"""Download a lab class from the relevant course
:param course: the course short name to download the class from.
:type course: string
:param reference: reference to the course for downloading the class.
:type reference: string
:param github: github repo for downloading the course from.
:type string: github repo for downloading the lab."""
github_stub = 'https://raw.githubusercontent.com/'
if not name.endswith('.ipynb'):
name += '.ipynb'
from pods.util import download_url
download_url(os.path.join(github_stub, github, course, name), store_directory=course) |
def pool(builder, size, timeout=None):
"""Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exception if no instances are available
within that time.
Raises:
If ``timeout`` is defined but the request is taking longer
than the specified time, the context manager will raise
a ``queue.Empty`` exception.
Returns:
A context manager that can be used with the ``with``
statement.
"""
lock = threading.Lock()
local_pool = queue.Queue()
current_size = 0
@contextlib.contextmanager
def pooled():
nonlocal current_size
instance = None
# If we still have free slots, then we have room to create new
# instances.
if current_size < size:
with lock:
# We need to check again if we have slots available, since
# the situation might be different after acquiring the lock
if current_size < size:
current_size += 1
instance = builder()
# Watchout: current_size can be equal to size if the previous part of
# the function has been executed, that's why we need to check if the
# instance is None.
if instance is None:
instance = local_pool.get(timeout=timeout)
yield instance
local_pool.put(instance)
return pooled | Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exception if no instances are available
within that time.
Raises:
If ``timeout`` is defined but the request is taking longer
than the specified time, the context manager will raise
a ``queue.Empty`` exception.
Returns:
A context manager that can be used with the ``with``
statement. | Below is the the instruction that describes the task:
### Input:
Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exception if no instances are available
within that time.
Raises:
If ``timeout`` is defined but the request is taking longer
than the specified time, the context manager will raise
a ``queue.Empty`` exception.
Returns:
A context manager that can be used with the ``with``
statement.
### Response:
def pool(builder, size, timeout=None):
"""Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exception if no instances are available
within that time.
Raises:
If ``timeout`` is defined but the request is taking longer
than the specified time, the context manager will raise
a ``queue.Empty`` exception.
Returns:
A context manager that can be used with the ``with``
statement.
"""
lock = threading.Lock()
local_pool = queue.Queue()
current_size = 0
@contextlib.contextmanager
def pooled():
nonlocal current_size
instance = None
# If we still have free slots, then we have room to create new
# instances.
if current_size < size:
with lock:
# We need to check again if we have slots available, since
# the situation might be different after acquiring the lock
if current_size < size:
current_size += 1
instance = builder()
# Watchout: current_size can be equal to size if the previous part of
# the function has been executed, that's why we need to check if the
# instance is None.
if instance is None:
instance = local_pool.get(timeout=timeout)
yield instance
local_pool.put(instance)
return pooled |
def ruencode(string, extension=False):
"""Encode a string using 'rotunicode' codec.
:param string:
The input string to encode.
:type string:
`basestring`
:param extension:
True if the entire input string should be encoded.
False to split the input string using :func:`os.path.splitext` and
encode only the file name portion keeping the extension as is.
:type extension:
`bool`
:return:
Encoded string.
:rtype:
`unicode`
"""
if extension:
file_name = string
file_ext = ''
else:
file_name, file_ext = splitext(string)
encoded_value, _ = _ROT_UNICODE.encode(file_name)
return encoded_value + file_ext | Encode a string using 'rotunicode' codec.
:param string:
The input string to encode.
:type string:
`basestring`
:param extension:
True if the entire input string should be encoded.
False to split the input string using :func:`os.path.splitext` and
encode only the file name portion keeping the extension as is.
:type extension:
`bool`
:return:
Encoded string.
:rtype:
`unicode` | Below is the the instruction that describes the task:
### Input:
Encode a string using 'rotunicode' codec.
:param string:
The input string to encode.
:type string:
`basestring`
:param extension:
True if the entire input string should be encoded.
False to split the input string using :func:`os.path.splitext` and
encode only the file name portion keeping the extension as is.
:type extension:
`bool`
:return:
Encoded string.
:rtype:
`unicode`
### Response:
def ruencode(string, extension=False):
"""Encode a string using 'rotunicode' codec.
:param string:
The input string to encode.
:type string:
`basestring`
:param extension:
True if the entire input string should be encoded.
False to split the input string using :func:`os.path.splitext` and
encode only the file name portion keeping the extension as is.
:type extension:
`bool`
:return:
Encoded string.
:rtype:
`unicode`
"""
if extension:
file_name = string
file_ext = ''
else:
file_name, file_ext = splitext(string)
encoded_value, _ = _ROT_UNICODE.encode(file_name)
return encoded_value + file_ext |
def extract_as_epilog(self, text, sections=None, overwrite=False,
append=True):
"""Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog"""
if sections is None:
sections = self.epilog_sections
if ((not self.epilog or overwrite or append) and sections):
epilog_parts = []
for sec in sections:
text = docstrings._get_section(text, sec).strip()
if text:
epilog_parts.append(
self.format_epilog_section(sec, text))
if epilog_parts:
epilog = '\n\n'.join(epilog_parts)
if overwrite or not self.epilog:
self.epilog = epilog
else:
self.epilog += '\n\n' + epilog | Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog | Below is the the instruction that describes the task:
### Input:
Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog
### Response:
def extract_as_epilog(self, text, sections=None, overwrite=False,
append=True):
"""Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog"""
if sections is None:
sections = self.epilog_sections
if ((not self.epilog or overwrite or append) and sections):
epilog_parts = []
for sec in sections:
text = docstrings._get_section(text, sec).strip()
if text:
epilog_parts.append(
self.format_epilog_section(sec, text))
if epilog_parts:
epilog = '\n\n'.join(epilog_parts)
if overwrite or not self.epilog:
self.epilog = epilog
else:
self.epilog += '\n\n' + epilog |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.