Unnamed: 0
int64 0
10k
| repository_name
stringlengths 7
54
| func_path_in_repository
stringlengths 5
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 100
30.3k
| language
stringclasses 1
value | func_code_string
stringlengths 100
30.3k
| func_code_tokens
stringlengths 138
33.2k
| func_documentation_string
stringlengths 1
15k
| func_documentation_tokens
stringlengths 5
5.14k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
|
---|---|---|---|---|---|---|---|---|---|---|---|
8,000 | osrg/ryu | ryu/services/protocols/bgp/peer.py | Peer.bind_protocol | def bind_protocol(self, proto):
"""Tries to bind given protocol to this peer.
Should only be called by `proto` trying to bind.
Once bound this protocol instance will be used to communicate with
peer. If another protocol is already bound, connection collision
resolution takes place.
"""
LOG.debug('Trying to bind protocol %s to peer %s', proto, self)
# Validate input.
if not isinstance(proto, BgpProtocol):
raise ValueError('Currently only supports valid instances of'
' `BgpProtocol`')
if proto.state != const.BGP_FSM_OPEN_CONFIRM:
raise ValueError('Only protocols in OpenConfirm state can be'
' bound')
# If we are not bound to any protocol
is_bound = False
if not self._protocol:
self._set_protocol(proto)
is_bound = True
else:
# If existing protocol is already established, we raise exception.
if self.state.bgp_state != const.BGP_FSM_IDLE:
LOG.debug('Currently in %s state, hence will send collision'
' Notification to close this protocol.',
self.state.bgp_state)
self._send_collision_err_and_stop(proto)
return
# If we have a collision that need to be resolved
assert proto.is_colliding(self._protocol), \
('Tried to bind second protocol that is not colliding with '
'first/bound protocol')
LOG.debug('Currently have one protocol in %s state and '
'another protocol in %s state',
self._protocol.state, proto.state)
# Protocol that is already bound
first_protocol = self._protocol
assert ((first_protocol.is_reactive and not proto.is_reactive) or
(proto.is_reactive and not first_protocol.is_reactive))
# Connection initiated by peer.
reactive_proto = None
# Connection initiated locally.
proactive_proto = None
# Identify which protocol was initiated by which peer.
if proto.is_reactive:
reactive_proto = proto
proactive_proto = self._protocol
else:
reactive_proto = self._protocol
proactive_proto = proto
LOG.debug('Pro-active/Active protocol %s', proactive_proto)
# We compare bgp local and remote router id and keep the protocol
# that was initiated by peer with highest id.
if proto.is_local_router_id_greater():
self._set_protocol(proactive_proto)
else:
self._set_protocol(reactive_proto)
if self._protocol is not proto:
# If new proto did not win collision we return False to
# indicate this.
is_bound = False
else:
# If first protocol did not win collision resolution we
# we send notification to peer and stop it
self._send_collision_err_and_stop(first_protocol)
is_bound = True
return is_bound | python | def bind_protocol(self, proto):
"""Tries to bind given protocol to this peer.
Should only be called by `proto` trying to bind.
Once bound this protocol instance will be used to communicate with
peer. If another protocol is already bound, connection collision
resolution takes place.
"""
LOG.debug('Trying to bind protocol %s to peer %s', proto, self)
# Validate input.
if not isinstance(proto, BgpProtocol):
raise ValueError('Currently only supports valid instances of'
' `BgpProtocol`')
if proto.state != const.BGP_FSM_OPEN_CONFIRM:
raise ValueError('Only protocols in OpenConfirm state can be'
' bound')
# If we are not bound to any protocol
is_bound = False
if not self._protocol:
self._set_protocol(proto)
is_bound = True
else:
# If existing protocol is already established, we raise exception.
if self.state.bgp_state != const.BGP_FSM_IDLE:
LOG.debug('Currently in %s state, hence will send collision'
' Notification to close this protocol.',
self.state.bgp_state)
self._send_collision_err_and_stop(proto)
return
# If we have a collision that need to be resolved
assert proto.is_colliding(self._protocol), \
('Tried to bind second protocol that is not colliding with '
'first/bound protocol')
LOG.debug('Currently have one protocol in %s state and '
'another protocol in %s state',
self._protocol.state, proto.state)
# Protocol that is already bound
first_protocol = self._protocol
assert ((first_protocol.is_reactive and not proto.is_reactive) or
(proto.is_reactive and not first_protocol.is_reactive))
# Connection initiated by peer.
reactive_proto = None
# Connection initiated locally.
proactive_proto = None
# Identify which protocol was initiated by which peer.
if proto.is_reactive:
reactive_proto = proto
proactive_proto = self._protocol
else:
reactive_proto = self._protocol
proactive_proto = proto
LOG.debug('Pro-active/Active protocol %s', proactive_proto)
# We compare bgp local and remote router id and keep the protocol
# that was initiated by peer with highest id.
if proto.is_local_router_id_greater():
self._set_protocol(proactive_proto)
else:
self._set_protocol(reactive_proto)
if self._protocol is not proto:
# If new proto did not win collision we return False to
# indicate this.
is_bound = False
else:
# If first protocol did not win collision resolution we
# we send notification to peer and stop it
self._send_collision_err_and_stop(first_protocol)
is_bound = True
return is_bound | ['def', 'bind_protocol', '(', 'self', ',', 'proto', ')', ':', 'LOG', '.', 'debug', '(', "'Trying to bind protocol %s to peer %s'", ',', 'proto', ',', 'self', ')', '# Validate input.', 'if', 'not', 'isinstance', '(', 'proto', ',', 'BgpProtocol', ')', ':', 'raise', 'ValueError', '(', "'Currently only supports valid instances of'", "' `BgpProtocol`'", ')', 'if', 'proto', '.', 'state', '!=', 'const', '.', 'BGP_FSM_OPEN_CONFIRM', ':', 'raise', 'ValueError', '(', "'Only protocols in OpenConfirm state can be'", "' bound'", ')', '# If we are not bound to any protocol', 'is_bound', '=', 'False', 'if', 'not', 'self', '.', '_protocol', ':', 'self', '.', '_set_protocol', '(', 'proto', ')', 'is_bound', '=', 'True', 'else', ':', '# If existing protocol is already established, we raise exception.', 'if', 'self', '.', 'state', '.', 'bgp_state', '!=', 'const', '.', 'BGP_FSM_IDLE', ':', 'LOG', '.', 'debug', '(', "'Currently in %s state, hence will send collision'", "' Notification to close this protocol.'", ',', 'self', '.', 'state', '.', 'bgp_state', ')', 'self', '.', '_send_collision_err_and_stop', '(', 'proto', ')', 'return', '# If we have a collision that need to be resolved', 'assert', 'proto', '.', 'is_colliding', '(', 'self', '.', '_protocol', ')', ',', '(', "'Tried to bind second protocol that is not colliding with '", "'first/bound protocol'", ')', 'LOG', '.', 'debug', '(', "'Currently have one protocol in %s state and '", "'another protocol in %s state'", ',', 'self', '.', '_protocol', '.', 'state', ',', 'proto', '.', 'state', ')', '# Protocol that is already bound', 'first_protocol', '=', 'self', '.', '_protocol', 'assert', '(', '(', 'first_protocol', '.', 'is_reactive', 'and', 'not', 'proto', '.', 'is_reactive', ')', 'or', '(', 'proto', '.', 'is_reactive', 'and', 'not', 'first_protocol', '.', 'is_reactive', ')', ')', '# Connection initiated by peer.', 'reactive_proto', '=', 'None', '# Connection initiated locally.', 'proactive_proto', '=', 'None', '# Identify which protocol was initiated by which peer.', 'if', 'proto', '.', 'is_reactive', ':', 'reactive_proto', '=', 'proto', 'proactive_proto', '=', 'self', '.', '_protocol', 'else', ':', 'reactive_proto', '=', 'self', '.', '_protocol', 'proactive_proto', '=', 'proto', 'LOG', '.', 'debug', '(', "'Pro-active/Active protocol %s'", ',', 'proactive_proto', ')', '# We compare bgp local and remote router id and keep the protocol', '# that was initiated by peer with highest id.', 'if', 'proto', '.', 'is_local_router_id_greater', '(', ')', ':', 'self', '.', '_set_protocol', '(', 'proactive_proto', ')', 'else', ':', 'self', '.', '_set_protocol', '(', 'reactive_proto', ')', 'if', 'self', '.', '_protocol', 'is', 'not', 'proto', ':', '# If new proto did not win collision we return False to', '# indicate this.', 'is_bound', '=', 'False', 'else', ':', '# If first protocol did not win collision resolution we', '# we send notification to peer and stop it', 'self', '.', '_send_collision_err_and_stop', '(', 'first_protocol', ')', 'is_bound', '=', 'True', 'return', 'is_bound'] | Tries to bind given protocol to this peer.
Should only be called by `proto` trying to bind.
Once bound this protocol instance will be used to communicate with
peer. If another protocol is already bound, connection collision
resolution takes place. | ['Tries', 'to', 'bind', 'given', 'protocol', 'to', 'this', 'peer', '.'] | train | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/peer.py#L1338-L1411 |
8,001 | PaulHancock/Aegean | AegeanTools/fits_image.py | get_beam | def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
Beam object, with a, b, and pa in degrees.
"""
if "BPA" not in header:
log.warning("BPA not present in fits header, using 0")
bpa = 0
else:
bpa = header["BPA"]
if "BMAJ" not in header:
log.warning("BMAJ not present in fits header.")
bmaj = None
else:
bmaj = header["BMAJ"]
if "BMIN" not in header:
log.warning("BMIN not present in fits header.")
bmin = None
else:
bmin = header["BMIN"]
if None in [bmaj, bmin, bpa]:
return None
beam = Beam(bmaj, bmin, bpa)
return beam | python | def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
Beam object, with a, b, and pa in degrees.
"""
if "BPA" not in header:
log.warning("BPA not present in fits header, using 0")
bpa = 0
else:
bpa = header["BPA"]
if "BMAJ" not in header:
log.warning("BMAJ not present in fits header.")
bmaj = None
else:
bmaj = header["BMAJ"]
if "BMIN" not in header:
log.warning("BMIN not present in fits header.")
bmin = None
else:
bmin = header["BMIN"]
if None in [bmaj, bmin, bpa]:
return None
beam = Beam(bmaj, bmin, bpa)
return beam | ['def', 'get_beam', '(', 'header', ')', ':', 'if', '"BPA"', 'not', 'in', 'header', ':', 'log', '.', 'warning', '(', '"BPA not present in fits header, using 0"', ')', 'bpa', '=', '0', 'else', ':', 'bpa', '=', 'header', '[', '"BPA"', ']', 'if', '"BMAJ"', 'not', 'in', 'header', ':', 'log', '.', 'warning', '(', '"BMAJ not present in fits header."', ')', 'bmaj', '=', 'None', 'else', ':', 'bmaj', '=', 'header', '[', '"BMAJ"', ']', 'if', '"BMIN"', 'not', 'in', 'header', ':', 'log', '.', 'warning', '(', '"BMIN not present in fits header."', ')', 'bmin', '=', 'None', 'else', ':', 'bmin', '=', 'header', '[', '"BMIN"', ']', 'if', 'None', 'in', '[', 'bmaj', ',', 'bmin', ',', 'bpa', ']', ':', 'return', 'None', 'beam', '=', 'Beam', '(', 'bmaj', ',', 'bmin', ',', 'bpa', ')', 'return', 'beam'] | Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
Beam object, with a, b, and pa in degrees. | ['Create', 'a', ':', 'class', ':', 'AegeanTools', '.', 'fits_image', '.', 'Beam', 'object', 'from', 'a', 'fits', 'header', '.'] | train | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fits_image.py#L63-L102 |
8,002 | PyGithub/PyGithub | github/Repository.py | Repository.get_collaborator_permission | def get_collaborator_permission(self, collaborator):
"""
:calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/collaborators/" + collaborator + "/permission",
)
return data["permission"] | python | def get_collaborator_permission(self, collaborator):
"""
:calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/collaborators/" + collaborator + "/permission",
)
return data["permission"] | ['def', 'get_collaborator_permission', '(', 'self', ',', 'collaborator', ')', ':', 'assert', 'isinstance', '(', 'collaborator', ',', 'github', '.', 'NamedUser', '.', 'NamedUser', ')', 'or', 'isinstance', '(', 'collaborator', ',', '(', 'str', ',', 'unicode', ')', ')', ',', 'collaborator', 'if', 'isinstance', '(', 'collaborator', ',', 'github', '.', 'NamedUser', '.', 'NamedUser', ')', ':', 'collaborator', '=', 'collaborator', '.', '_identity', 'headers', ',', 'data', '=', 'self', '.', '_requester', '.', 'requestJsonAndCheck', '(', '"GET"', ',', 'self', '.', 'url', '+', '"/collaborators/"', '+', 'collaborator', '+', '"/permission"', ',', ')', 'return', 'data', '[', '"permission"', ']'] | :calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string | [':', 'calls', ':', 'GET', '/', 'repos', '/', ':', 'owner', '/', ':', 'repo', '/', 'collaborators', '/', ':', 'username', '/', 'permission', '<http', ':', '//', 'developer', '.', 'github', '.', 'com', '/', 'v3', '/', 'repos', '/', 'collaborators', '>', '_', ':', 'param', 'collaborator', ':', 'string', 'or', ':', 'class', ':', 'github', '.', 'NamedUser', '.', 'NamedUser', ':', 'rtype', ':', 'string'] | train | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Repository.py#L802-L815 |
8,003 | jmbeach/KEP.py | src/keppy/project.py | Project.parse_channels | def parse_channels(self):
"""Creates an array of Channel objects from the project"""
channels = []
for channel in self._project_dict["channels"]:
channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list))
return channels | python | def parse_channels(self):
"""Creates an array of Channel objects from the project"""
channels = []
for channel in self._project_dict["channels"]:
channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list))
return channels | ['def', 'parse_channels', '(', 'self', ')', ':', 'channels', '=', '[', ']', 'for', 'channel', 'in', 'self', '.', '_project_dict', '[', '"channels"', ']', ':', 'channels', '.', 'append', '(', 'Channel', '(', 'channel', ',', 'self', '.', '_is_sixteen_bit', ',', 'self', '.', '_ignore_list', ')', ')', 'return', 'channels'] | Creates an array of Channel objects from the project | ['Creates', 'an', 'array', 'of', 'Channel', 'objects', 'from', 'the', 'project'] | train | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/project.py#L20-L25 |
8,004 | openid/python-openid | openid/consumer/consumer.py | GenericConsumer._doIdRes | def _doIdRes(self, message, endpoint, return_to):
"""Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response}
"""
# Checks for presence of appropriate fields (and checks
# signed list fields)
self._idResCheckForFields(message)
if not self._checkReturnTo(message, return_to):
raise ProtocolError(
"return_to does not match return URL. Expected %r, got %r"
% (return_to, message.getArg(OPENID_NS, 'return_to')))
# Verify discovery information:
endpoint = self._verifyDiscoveryResults(message, endpoint)
logging.info("Received id_res response from %s using association %s" %
(endpoint.server_url,
message.getArg(OPENID_NS, 'assoc_handle')))
self._idResCheckSignature(message, endpoint.server_url)
# Will raise a ProtocolError if the nonce is bad
self._idResCheckNonce(message, endpoint)
signed_list_str = message.getArg(OPENID_NS, 'signed', no_default)
signed_list = signed_list_str.split(',')
signed_fields = ["openid." + s for s in signed_list]
return SuccessResponse(endpoint, message, signed_fields) | python | def _doIdRes(self, message, endpoint, return_to):
"""Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response}
"""
# Checks for presence of appropriate fields (and checks
# signed list fields)
self._idResCheckForFields(message)
if not self._checkReturnTo(message, return_to):
raise ProtocolError(
"return_to does not match return URL. Expected %r, got %r"
% (return_to, message.getArg(OPENID_NS, 'return_to')))
# Verify discovery information:
endpoint = self._verifyDiscoveryResults(message, endpoint)
logging.info("Received id_res response from %s using association %s" %
(endpoint.server_url,
message.getArg(OPENID_NS, 'assoc_handle')))
self._idResCheckSignature(message, endpoint.server_url)
# Will raise a ProtocolError if the nonce is bad
self._idResCheckNonce(message, endpoint)
signed_list_str = message.getArg(OPENID_NS, 'signed', no_default)
signed_list = signed_list_str.split(',')
signed_fields = ["openid." + s for s in signed_list]
return SuccessResponse(endpoint, message, signed_fields) | ['def', '_doIdRes', '(', 'self', ',', 'message', ',', 'endpoint', ',', 'return_to', ')', ':', '# Checks for presence of appropriate fields (and checks', '# signed list fields)', 'self', '.', '_idResCheckForFields', '(', 'message', ')', 'if', 'not', 'self', '.', '_checkReturnTo', '(', 'message', ',', 'return_to', ')', ':', 'raise', 'ProtocolError', '(', '"return_to does not match return URL. Expected %r, got %r"', '%', '(', 'return_to', ',', 'message', '.', 'getArg', '(', 'OPENID_NS', ',', "'return_to'", ')', ')', ')', '# Verify discovery information:', 'endpoint', '=', 'self', '.', '_verifyDiscoveryResults', '(', 'message', ',', 'endpoint', ')', 'logging', '.', 'info', '(', '"Received id_res response from %s using association %s"', '%', '(', 'endpoint', '.', 'server_url', ',', 'message', '.', 'getArg', '(', 'OPENID_NS', ',', "'assoc_handle'", ')', ')', ')', 'self', '.', '_idResCheckSignature', '(', 'message', ',', 'endpoint', '.', 'server_url', ')', '# Will raise a ProtocolError if the nonce is bad', 'self', '.', '_idResCheckNonce', '(', 'message', ',', 'endpoint', ')', 'signed_list_str', '=', 'message', '.', 'getArg', '(', 'OPENID_NS', ',', "'signed'", ',', 'no_default', ')', 'signed_list', '=', 'signed_list_str', '.', 'split', '(', "','", ')', 'signed_fields', '=', '[', '"openid."', '+', 's', 'for', 's', 'in', 'signed_list', ']', 'return', 'SuccessResponse', '(', 'endpoint', ',', 'message', ',', 'signed_fields', ')'] | Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response} | ['Handle', 'id_res', 'responses', 'that', 'are', 'not', 'cancellations', 'of', 'immediate', 'mode', 'requests', '.'] | train | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L701-L744 |
8,005 | cloudant/python-cloudant | src/cloudant/_client_session.py | CookieSession.login | def login(self):
"""
Perform cookie based user login.
"""
resp = super(CookieSession, self).request(
'POST',
self._session_url,
data={'name': self._username, 'password': self._password},
)
resp.raise_for_status() | python | def login(self):
"""
Perform cookie based user login.
"""
resp = super(CookieSession, self).request(
'POST',
self._session_url,
data={'name': self._username, 'password': self._password},
)
resp.raise_for_status() | ['def', 'login', '(', 'self', ')', ':', 'resp', '=', 'super', '(', 'CookieSession', ',', 'self', ')', '.', 'request', '(', "'POST'", ',', 'self', '.', '_session_url', ',', 'data', '=', '{', "'name'", ':', 'self', '.', '_username', ',', "'password'", ':', 'self', '.', '_password', '}', ',', ')', 'resp', '.', 'raise_for_status', '(', ')'] | Perform cookie based user login. | ['Perform', 'cookie', 'based', 'user', 'login', '.'] | train | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/_client_session.py#L146-L155 |
8,006 | inasafe/inasafe | safe/report/impact_report.py | ImpactReport.output_folder | def output_folder(self, value):
"""Output folder path for the rendering.
:param value: output folder path
:type value: str
"""
self._output_folder = value
if not os.path.exists(self._output_folder):
os.makedirs(self._output_folder) | python | def output_folder(self, value):
"""Output folder path for the rendering.
:param value: output folder path
:type value: str
"""
self._output_folder = value
if not os.path.exists(self._output_folder):
os.makedirs(self._output_folder) | ['def', 'output_folder', '(', 'self', ',', 'value', ')', ':', 'self', '.', '_output_folder', '=', 'value', 'if', 'not', 'os', '.', 'path', '.', 'exists', '(', 'self', '.', '_output_folder', ')', ':', 'os', '.', 'makedirs', '(', 'self', '.', '_output_folder', ')'] | Output folder path for the rendering.
:param value: output folder path
:type value: str | ['Output', 'folder', 'path', 'for', 'the', 'rendering', '.'] | train | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L368-L376 |
8,007 | django-salesforce/django-salesforce | salesforce/dbapi/driver.py | RawConnection.handle_api_exceptions | def handle_api_exceptions(self, method, *url_parts, **kwargs):
"""Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: other parameters passed to requests.request,
but the only notable parameter is: (... json=data)
that works like (...
headers = {'Content-Type': 'application/json'},
data=json.dumps(data))
"""
# The outer part - about error handler
assert method in ('HEAD', 'GET', 'POST', 'PATCH', 'DELETE')
cursor_context = kwargs.pop('cursor_context', None)
errorhandler = cursor_context.errorhandler if cursor_context else self.errorhandler
catched_exceptions = (SalesforceError, requests.exceptions.RequestException) if errorhandler else ()
try:
return self.handle_api_exceptions_inter(method, *url_parts, **kwargs)
except catched_exceptions:
# nothing is catched usually and error handler not used
exc_class, exc_value, _ = sys.exc_info()
errorhandler(self, cursor_context, exc_class, exc_value)
raise | python | def handle_api_exceptions(self, method, *url_parts, **kwargs):
"""Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: other parameters passed to requests.request,
but the only notable parameter is: (... json=data)
that works like (...
headers = {'Content-Type': 'application/json'},
data=json.dumps(data))
"""
# The outer part - about error handler
assert method in ('HEAD', 'GET', 'POST', 'PATCH', 'DELETE')
cursor_context = kwargs.pop('cursor_context', None)
errorhandler = cursor_context.errorhandler if cursor_context else self.errorhandler
catched_exceptions = (SalesforceError, requests.exceptions.RequestException) if errorhandler else ()
try:
return self.handle_api_exceptions_inter(method, *url_parts, **kwargs)
except catched_exceptions:
# nothing is catched usually and error handler not used
exc_class, exc_value, _ = sys.exc_info()
errorhandler(self, cursor_context, exc_class, exc_value)
raise | ['def', 'handle_api_exceptions', '(', 'self', ',', 'method', ',', '*', 'url_parts', ',', '*', '*', 'kwargs', ')', ':', '# The outer part - about error handler', 'assert', 'method', 'in', '(', "'HEAD'", ',', "'GET'", ',', "'POST'", ',', "'PATCH'", ',', "'DELETE'", ')', 'cursor_context', '=', 'kwargs', '.', 'pop', '(', "'cursor_context'", ',', 'None', ')', 'errorhandler', '=', 'cursor_context', '.', 'errorhandler', 'if', 'cursor_context', 'else', 'self', '.', 'errorhandler', 'catched_exceptions', '=', '(', 'SalesforceError', ',', 'requests', '.', 'exceptions', '.', 'RequestException', ')', 'if', 'errorhandler', 'else', '(', ')', 'try', ':', 'return', 'self', '.', 'handle_api_exceptions_inter', '(', 'method', ',', '*', 'url_parts', ',', '*', '*', 'kwargs', ')', 'except', 'catched_exceptions', ':', '# nothing is catched usually and error handler not used', 'exc_class', ',', 'exc_value', ',', '_', '=', 'sys', '.', 'exc_info', '(', ')', 'errorhandler', '(', 'self', ',', 'cursor_context', ',', 'exc_class', ',', 'exc_value', ')', 'raise'] | Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: other parameters passed to requests.request,
but the only notable parameter is: (... json=data)
that works like (...
headers = {'Content-Type': 'application/json'},
data=json.dumps(data)) | ['Call', 'REST', 'API', 'and', 'handle', 'exceptions', 'Params', ':', 'method', ':', 'HEAD', 'GET', 'POST', 'PATCH', 'or', 'DELETE', 'url_parts', ':', 'like', 'in', 'rest_api_url', '()', 'method', 'api_ver', ':', 'like', 'in', 'rest_api_url', '()', 'method', 'kwargs', ':', 'other', 'parameters', 'passed', 'to', 'requests', '.', 'request', 'but', 'the', 'only', 'notable', 'parameter', 'is', ':', '(', '...', 'json', '=', 'data', ')'] | train | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/driver.py#L218-L243 |
8,008 | idlesign/torrentool | torrentool/torrent.py | Torrent.to_file | def to_file(self, filepath=None):
"""Writes Torrent object into file, either
:param filepath:
"""
if filepath is None and self._filepath is None:
raise TorrentError('Unable to save torrent to file: no filepath supplied.')
if filepath is not None:
self._filepath = filepath
with open(self._filepath, mode='wb') as f:
f.write(self.to_string()) | python | def to_file(self, filepath=None):
"""Writes Torrent object into file, either
:param filepath:
"""
if filepath is None and self._filepath is None:
raise TorrentError('Unable to save torrent to file: no filepath supplied.')
if filepath is not None:
self._filepath = filepath
with open(self._filepath, mode='wb') as f:
f.write(self.to_string()) | ['def', 'to_file', '(', 'self', ',', 'filepath', '=', 'None', ')', ':', 'if', 'filepath', 'is', 'None', 'and', 'self', '.', '_filepath', 'is', 'None', ':', 'raise', 'TorrentError', '(', "'Unable to save torrent to file: no filepath supplied.'", ')', 'if', 'filepath', 'is', 'not', 'None', ':', 'self', '.', '_filepath', '=', 'filepath', 'with', 'open', '(', 'self', '.', '_filepath', ',', 'mode', '=', "'wb'", ')', 'as', 'f', ':', 'f', '.', 'write', '(', 'self', '.', 'to_string', '(', ')', ')'] | Writes Torrent object into file, either
:param filepath: | ['Writes', 'Torrent', 'object', 'into', 'file', 'either'] | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L300-L312 |
8,009 | pyparsing/pyparsing | examples/pymicko.py | CodeGenerator.restore_used_registers | def restore_used_registers(self):
"""Pops all used working registers after function call"""
used = self.used_registers_stack.pop()
self.used_registers = used[:]
used.sort(reverse = True)
for reg in used:
self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], True)
self.free_registers.remove(reg) | python | def restore_used_registers(self):
"""Pops all used working registers after function call"""
used = self.used_registers_stack.pop()
self.used_registers = used[:]
used.sort(reverse = True)
for reg in used:
self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], True)
self.free_registers.remove(reg) | ['def', 'restore_used_registers', '(', 'self', ')', ':', 'used', '=', 'self', '.', 'used_registers_stack', '.', 'pop', '(', ')', 'self', '.', 'used_registers', '=', 'used', '[', ':', ']', 'used', '.', 'sort', '(', 'reverse', '=', 'True', ')', 'for', 'reg', 'in', 'used', ':', 'self', '.', 'newline_text', '(', '"POP \\t%s"', '%', 'SharedData', '.', 'REGISTERS', '[', 'reg', ']', ',', 'True', ')', 'self', '.', 'free_registers', '.', 'remove', '(', 'reg', ')'] | Pops all used working registers after function call | ['Pops', 'all', 'used', 'working', 'registers', 'after', 'function', 'call'] | train | https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/pymicko.py#L639-L646 |
8,010 | HazyResearch/fonduer | src/fonduer/utils/data_model_utils/utils.py | _to_spans | def _to_spans(x):
"""Convert a Candidate, Mention, or Span to a list of spans."""
if isinstance(x, Candidate):
return [_to_span(m) for m in x]
elif isinstance(x, Mention):
return [x.context]
elif isinstance(x, TemporarySpanMention):
return [x]
else:
raise ValueError(f"{type(x)} is an invalid argument type") | python | def _to_spans(x):
"""Convert a Candidate, Mention, or Span to a list of spans."""
if isinstance(x, Candidate):
return [_to_span(m) for m in x]
elif isinstance(x, Mention):
return [x.context]
elif isinstance(x, TemporarySpanMention):
return [x]
else:
raise ValueError(f"{type(x)} is an invalid argument type") | ['def', '_to_spans', '(', 'x', ')', ':', 'if', 'isinstance', '(', 'x', ',', 'Candidate', ')', ':', 'return', '[', '_to_span', '(', 'm', ')', 'for', 'm', 'in', 'x', ']', 'elif', 'isinstance', '(', 'x', ',', 'Mention', ')', ':', 'return', '[', 'x', '.', 'context', ']', 'elif', 'isinstance', '(', 'x', ',', 'TemporarySpanMention', ')', ':', 'return', '[', 'x', ']', 'else', ':', 'raise', 'ValueError', '(', 'f"{type(x)} is an invalid argument type"', ')'] | Convert a Candidate, Mention, or Span to a list of spans. | ['Convert', 'a', 'Candidate', 'Mention', 'or', 'Span', 'to', 'a', 'list', 'of', 'spans', '.'] | train | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/utils.py#L22-L31 |
8,011 | tensorpack/tensorpack | examples/PennTreebank/reader.py | ptb_producer | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high.
"""
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw_data[0 : batch_size * batch_len],
[batch_size, batch_len])
epoch_size = (batch_len - 1) // num_steps
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps],
[batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1],
[batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y | python | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high.
"""
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw_data[0 : batch_size * batch_len],
[batch_size, batch_len])
epoch_size = (batch_len - 1) // num_steps
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps],
[batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1],
[batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y | ['def', 'ptb_producer', '(', 'raw_data', ',', 'batch_size', ',', 'num_steps', ',', 'name', '=', 'None', ')', ':', 'with', 'tf', '.', 'name_scope', '(', 'name', ',', '"PTBProducer"', ',', '[', 'raw_data', ',', 'batch_size', ',', 'num_steps', ']', ')', ':', 'raw_data', '=', 'tf', '.', 'convert_to_tensor', '(', 'raw_data', ',', 'name', '=', '"raw_data"', ',', 'dtype', '=', 'tf', '.', 'int32', ')', 'data_len', '=', 'tf', '.', 'size', '(', 'raw_data', ')', 'batch_len', '=', 'data_len', '//', 'batch_size', 'data', '=', 'tf', '.', 'reshape', '(', 'raw_data', '[', '0', ':', 'batch_size', '*', 'batch_len', ']', ',', '[', 'batch_size', ',', 'batch_len', ']', ')', 'epoch_size', '=', '(', 'batch_len', '-', '1', ')', '//', 'num_steps', 'assertion', '=', 'tf', '.', 'assert_positive', '(', 'epoch_size', ',', 'message', '=', '"epoch_size == 0, decrease batch_size or num_steps"', ')', 'with', 'tf', '.', 'control_dependencies', '(', '[', 'assertion', ']', ')', ':', 'epoch_size', '=', 'tf', '.', 'identity', '(', 'epoch_size', ',', 'name', '=', '"epoch_size"', ')', 'i', '=', 'tf', '.', 'train', '.', 'range_input_producer', '(', 'epoch_size', ',', 'shuffle', '=', 'False', ')', '.', 'dequeue', '(', ')', 'x', '=', 'tf', '.', 'strided_slice', '(', 'data', ',', '[', '0', ',', 'i', '*', 'num_steps', ']', ',', '[', 'batch_size', ',', '(', 'i', '+', '1', ')', '*', 'num_steps', ']', ')', 'x', '.', 'set_shape', '(', '[', 'batch_size', ',', 'num_steps', ']', ')', 'y', '=', 'tf', '.', 'strided_slice', '(', 'data', ',', '[', '0', ',', 'i', '*', 'num_steps', '+', '1', ']', ',', '[', 'batch_size', ',', '(', 'i', '+', '1', ')', '*', 'num_steps', '+', '1', ']', ')', 'y', '.', 'set_shape', '(', '[', 'batch_size', ',', 'num_steps', ']', ')', 'return', 'x', ',', 'y'] | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high. | ['Iterate', 'on', 'the', 'raw', 'PTB', 'data', '.'] | train | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/PennTreebank/reader.py#L78-L119 |
8,012 | CI-WATER/gsshapy | gsshapy/modeling/event.py | LongTermMode.prepare_hmet_lsm | def prepare_hmet_lsm(self, lsm_data_var_map_array,
hmet_ascii_output_folder=None,
netcdf_file_path=None):
"""
Prepares HMET data for GSSHA simulation from land surface model data.
Parameters:
lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.`
hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None.
netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None.
"""
if self.l2g is None:
raise ValueError("LSM converter not loaded ...")
with tmp_chdir(self.project_manager.project_directory):
# GSSHA simulation does not work after HMET data is finished
self._update_simulation_end_from_lsm()
# HMET CARDS
if netcdf_file_path is not None:
self.l2g.lsm_data_to_subset_netcdf(netcdf_file_path, lsm_data_var_map_array)
self._update_card("HMET_NETCDF", netcdf_file_path, True)
self.project_manager.deleteCard('HMET_ASCII', self.db_session)
else:
if "{0}" in hmet_ascii_output_folder and "{1}" in hmet_ascii_output_folder:
hmet_ascii_output_folder = hmet_ascii_output_folder.format(self.simulation_start.strftime("%Y%m%d%H%M"),
self.simulation_end.strftime("%Y%m%d%H%M"))
self.l2g.lsm_data_to_arc_ascii(lsm_data_var_map_array,
main_output_folder=os.path.join(self.gssha_directory,
hmet_ascii_output_folder))
self._update_card("HMET_ASCII", os.path.join(hmet_ascii_output_folder, 'hmet_file_list.txt'), True)
self.project_manager.deleteCard('HMET_NETCDF', self.db_session)
# UPDATE GMT CARD
self._update_gmt() | python | def prepare_hmet_lsm(self, lsm_data_var_map_array,
hmet_ascii_output_folder=None,
netcdf_file_path=None):
"""
Prepares HMET data for GSSHA simulation from land surface model data.
Parameters:
lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.`
hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None.
netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None.
"""
if self.l2g is None:
raise ValueError("LSM converter not loaded ...")
with tmp_chdir(self.project_manager.project_directory):
# GSSHA simulation does not work after HMET data is finished
self._update_simulation_end_from_lsm()
# HMET CARDS
if netcdf_file_path is not None:
self.l2g.lsm_data_to_subset_netcdf(netcdf_file_path, lsm_data_var_map_array)
self._update_card("HMET_NETCDF", netcdf_file_path, True)
self.project_manager.deleteCard('HMET_ASCII', self.db_session)
else:
if "{0}" in hmet_ascii_output_folder and "{1}" in hmet_ascii_output_folder:
hmet_ascii_output_folder = hmet_ascii_output_folder.format(self.simulation_start.strftime("%Y%m%d%H%M"),
self.simulation_end.strftime("%Y%m%d%H%M"))
self.l2g.lsm_data_to_arc_ascii(lsm_data_var_map_array,
main_output_folder=os.path.join(self.gssha_directory,
hmet_ascii_output_folder))
self._update_card("HMET_ASCII", os.path.join(hmet_ascii_output_folder, 'hmet_file_list.txt'), True)
self.project_manager.deleteCard('HMET_NETCDF', self.db_session)
# UPDATE GMT CARD
self._update_gmt() | ['def', 'prepare_hmet_lsm', '(', 'self', ',', 'lsm_data_var_map_array', ',', 'hmet_ascii_output_folder', '=', 'None', ',', 'netcdf_file_path', '=', 'None', ')', ':', 'if', 'self', '.', 'l2g', 'is', 'None', ':', 'raise', 'ValueError', '(', '"LSM converter not loaded ..."', ')', 'with', 'tmp_chdir', '(', 'self', '.', 'project_manager', '.', 'project_directory', ')', ':', '# GSSHA simulation does not work after HMET data is finished', 'self', '.', '_update_simulation_end_from_lsm', '(', ')', '# HMET CARDS', 'if', 'netcdf_file_path', 'is', 'not', 'None', ':', 'self', '.', 'l2g', '.', 'lsm_data_to_subset_netcdf', '(', 'netcdf_file_path', ',', 'lsm_data_var_map_array', ')', 'self', '.', '_update_card', '(', '"HMET_NETCDF"', ',', 'netcdf_file_path', ',', 'True', ')', 'self', '.', 'project_manager', '.', 'deleteCard', '(', "'HMET_ASCII'", ',', 'self', '.', 'db_session', ')', 'else', ':', 'if', '"{0}"', 'in', 'hmet_ascii_output_folder', 'and', '"{1}"', 'in', 'hmet_ascii_output_folder', ':', 'hmet_ascii_output_folder', '=', 'hmet_ascii_output_folder', '.', 'format', '(', 'self', '.', 'simulation_start', '.', 'strftime', '(', '"%Y%m%d%H%M"', ')', ',', 'self', '.', 'simulation_end', '.', 'strftime', '(', '"%Y%m%d%H%M"', ')', ')', 'self', '.', 'l2g', '.', 'lsm_data_to_arc_ascii', '(', 'lsm_data_var_map_array', ',', 'main_output_folder', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', 'gssha_directory', ',', 'hmet_ascii_output_folder', ')', ')', 'self', '.', '_update_card', '(', '"HMET_ASCII"', ',', 'os', '.', 'path', '.', 'join', '(', 'hmet_ascii_output_folder', ',', "'hmet_file_list.txt'", ')', ',', 'True', ')', 'self', '.', 'project_manager', '.', 'deleteCard', '(', "'HMET_NETCDF'", ',', 'self', '.', 'db_session', ')', '# UPDATE GMT CARD', 'self', '.', '_update_gmt', '(', ')'] | Prepares HMET data for GSSHA simulation from land surface model data.
Parameters:
lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.`
hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None.
netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None. | ['Prepares', 'HMET', 'data', 'for', 'GSSHA', 'simulation', 'from', 'land', 'surface', 'model', 'data', '.'] | train | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/modeling/event.py#L508-L542 |
8,013 | firecat53/urlscan | urlscan/urlchoose.py | URLChooser._help_menu | def _help_menu(self):
"""F1"""
if self.help_menu is False:
self.focus_pos_saved = self.top.body.focus_position
help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_'))
for i, j in self.keys.items() if j.__name__ !=
'_digits'])
help_men = "KEYBINDINGS\n" + help_men + "\n<0-9> - Jump to item"
docs = ("OPTIONS\n"
"all_escape -- toggle unescape all URLs\n"
"all_shorten -- toggle shorten all URLs\n"
"bottom -- move cursor to last item\n"
"clear_screen -- redraw screen\n"
"clipboard -- copy highlighted URL to clipboard using xsel/xclip\n"
"clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\n"
"config_create -- create ~/.config/urlscan/config.json\n"
"context -- show/hide context\n"
"down -- cursor down\n"
"help_menu -- show/hide help menu\n"
"open_url -- open selected URL\n"
"palette -- cycle through palettes\n"
"quit -- quit\n"
"shorten -- toggle shorten highlighted URL\n"
"top -- move to first list item\n"
"up -- cursor up\n")
self.top.body = \
urwid.ListBox(urwid.SimpleListWalker([urwid.Columns([(30, urwid.Text(help_men)),
urwid.Text(docs)])]))
else:
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self.focus_pos_saved
self.help_menu = not self.help_menu | python | def _help_menu(self):
"""F1"""
if self.help_menu is False:
self.focus_pos_saved = self.top.body.focus_position
help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_'))
for i, j in self.keys.items() if j.__name__ !=
'_digits'])
help_men = "KEYBINDINGS\n" + help_men + "\n<0-9> - Jump to item"
docs = ("OPTIONS\n"
"all_escape -- toggle unescape all URLs\n"
"all_shorten -- toggle shorten all URLs\n"
"bottom -- move cursor to last item\n"
"clear_screen -- redraw screen\n"
"clipboard -- copy highlighted URL to clipboard using xsel/xclip\n"
"clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\n"
"config_create -- create ~/.config/urlscan/config.json\n"
"context -- show/hide context\n"
"down -- cursor down\n"
"help_menu -- show/hide help menu\n"
"open_url -- open selected URL\n"
"palette -- cycle through palettes\n"
"quit -- quit\n"
"shorten -- toggle shorten highlighted URL\n"
"top -- move to first list item\n"
"up -- cursor up\n")
self.top.body = \
urwid.ListBox(urwid.SimpleListWalker([urwid.Columns([(30, urwid.Text(help_men)),
urwid.Text(docs)])]))
else:
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self.focus_pos_saved
self.help_menu = not self.help_menu | ['def', '_help_menu', '(', 'self', ')', ':', 'if', 'self', '.', 'help_menu', 'is', 'False', ':', 'self', '.', 'focus_pos_saved', '=', 'self', '.', 'top', '.', 'body', '.', 'focus_position', 'help_men', '=', '"\\n"', '.', 'join', '(', '[', '"{} - {}"', '.', 'format', '(', 'i', ',', 'j', '.', '__name__', '.', 'strip', '(', "'_'", ')', ')', 'for', 'i', ',', 'j', 'in', 'self', '.', 'keys', '.', 'items', '(', ')', 'if', 'j', '.', '__name__', '!=', "'_digits'", ']', ')', 'help_men', '=', '"KEYBINDINGS\\n"', '+', 'help_men', '+', '"\\n<0-9> - Jump to item"', 'docs', '=', '(', '"OPTIONS\\n"', '"all_escape -- toggle unescape all URLs\\n"', '"all_shorten -- toggle shorten all URLs\\n"', '"bottom -- move cursor to last item\\n"', '"clear_screen -- redraw screen\\n"', '"clipboard -- copy highlighted URL to clipboard using xsel/xclip\\n"', '"clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\\n"', '"config_create -- create ~/.config/urlscan/config.json\\n"', '"context -- show/hide context\\n"', '"down -- cursor down\\n"', '"help_menu -- show/hide help menu\\n"', '"open_url -- open selected URL\\n"', '"palette -- cycle through palettes\\n"', '"quit -- quit\\n"', '"shorten -- toggle shorten highlighted URL\\n"', '"top -- move to first list item\\n"', '"up -- cursor up\\n"', ')', 'self', '.', 'top', '.', 'body', '=', 'urwid', '.', 'ListBox', '(', 'urwid', '.', 'SimpleListWalker', '(', '[', 'urwid', '.', 'Columns', '(', '[', '(', '30', ',', 'urwid', '.', 'Text', '(', 'help_men', ')', ')', ',', 'urwid', '.', 'Text', '(', 'docs', ')', ']', ')', ']', ')', ')', 'else', ':', 'self', '.', 'top', '.', 'body', '=', 'urwid', '.', 'ListBox', '(', 'self', '.', 'items', ')', 'self', '.', 'top', '.', 'body', '.', 'focus_position', '=', 'self', '.', 'focus_pos_saved', 'self', '.', 'help_menu', '=', 'not', 'self', '.', 'help_menu'] | F1 | ['F1'] | train | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L306-L337 |
8,014 | astraw38/lint | lint/main.py | run_validators | def run_validators(new_data, old_data):
"""
Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return:
"""
#{'validator_name': (success, score, message)}
validation_data = {}
for file_type, lint_data in list(new_data.items()):
#TODO: What to do if old data doesn't have this filetype?
old_lint_data = old_data.get(file_type, {})
validator = ValidatorFactory.get_validator(file_type)
if validator is not None:
validation_data[validator.name] = validator.run(lint_data, old_lint_data)
return validation_data | python | def run_validators(new_data, old_data):
"""
Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return:
"""
#{'validator_name': (success, score, message)}
validation_data = {}
for file_type, lint_data in list(new_data.items()):
#TODO: What to do if old data doesn't have this filetype?
old_lint_data = old_data.get(file_type, {})
validator = ValidatorFactory.get_validator(file_type)
if validator is not None:
validation_data[validator.name] = validator.run(lint_data, old_lint_data)
return validation_data | ['def', 'run_validators', '(', 'new_data', ',', 'old_data', ')', ':', "#{'validator_name': (success, score, message)}", 'validation_data', '=', '{', '}', 'for', 'file_type', ',', 'lint_data', 'in', 'list', '(', 'new_data', '.', 'items', '(', ')', ')', ':', "#TODO: What to do if old data doesn't have this filetype?", 'old_lint_data', '=', 'old_data', '.', 'get', '(', 'file_type', ',', '{', '}', ')', 'validator', '=', 'ValidatorFactory', '.', 'get_validator', '(', 'file_type', ')', 'if', 'validator', 'is', 'not', 'None', ':', 'validation_data', '[', 'validator', '.', 'name', ']', '=', 'validator', '.', 'run', '(', 'lint_data', ',', 'old_lint_data', ')', 'return', 'validation_data'] | Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return: | ['Run', 'through', 'all', 'matching', 'validators', '.'] | train | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/main.py#L31-L47 |
8,015 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.is_early_compact_l2a | def is_early_compact_l2a(self):
"""Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool
"""
return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \
self.baseline <= '02.06' | python | def is_early_compact_l2a(self):
"""Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool
"""
return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \
self.baseline <= '02.06' | ['def', 'is_early_compact_l2a', '(', 'self', ')', ':', 'return', 'self', '.', 'data_source', 'is', 'DataSource', '.', 'SENTINEL2_L2A', 'and', 'self', '.', 'safe_type', 'is', 'EsaSafeType', '.', 'COMPACT_TYPE', 'and', 'self', '.', 'baseline', '<=', "'02.06'"] | Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool | ['Check', 'if', 'product', 'is', 'early', 'version', 'of', 'compact', 'L2A', 'product'] | train | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L275-L282 |
8,016 | datamachine/twx.botapi | twx/botapi/botapi.py | export_chat_invite_link | def export_chat_invite_link(chat_id, **kwargs):
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`
:return: Returns the new invite link as String on success.
:rtype: str
"""
# required args
params = dict(chat_id=chat_id)
return TelegramBotRPCRequest('exportChatInviteLink', params=params, on_result=lambda result: result, **kwargs) | python | def export_chat_invite_link(chat_id, **kwargs):
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`
:return: Returns the new invite link as String on success.
:rtype: str
"""
# required args
params = dict(chat_id=chat_id)
return TelegramBotRPCRequest('exportChatInviteLink', params=params, on_result=lambda result: result, **kwargs) | ['def', 'export_chat_invite_link', '(', 'chat_id', ',', '*', '*', 'kwargs', ')', ':', '# required args', 'params', '=', 'dict', '(', 'chat_id', '=', 'chat_id', ')', 'return', 'TelegramBotRPCRequest', '(', "'exportChatInviteLink'", ',', 'params', '=', 'params', ',', 'on_result', '=', 'lambda', 'result', ':', 'result', ',', '*', '*', 'kwargs', ')'] | Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`
:return: Returns the new invite link as String on success.
:rtype: str | ['Use', 'this', 'method', 'to', 'generate', 'a', 'new', 'invite', 'link', 'for', 'a', 'chat', ';', 'any', 'previously', 'generated', 'link', 'is', 'revoked', '.', 'The', 'bot', 'must', 'be', 'an', 'administrator', 'in', 'the', 'chat', 'for', 'this', 'to', 'work', 'and', 'must', 'have', 'the', 'appropriate', 'admin', 'rights', '.', ':', 'param', 'chat_id', ':', 'Unique', 'identifier', 'for', 'the', 'target', 'chat', 'or', 'username', 'of', 'the', 'target', 'channel', '(', 'in', 'the', 'format'] | train | https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L2296-L2309 |
8,017 | zhmcclient/python-zhmcclient | zhmcclient_mock/_hmc.py | FakedMetricsContext.get_metric_values_response | def get_metric_values_response(self):
"""
Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object, as a
string in the format needed for the "Get Metrics" operation response.
Returns:
"MetricsResponse" string as described for the "Get Metrics"
operation response.
"""
mv_list = self.get_metric_values()
resp_lines = []
for mv in mv_list:
group_name = mv[0]
resp_lines.append('"{}"'.format(group_name))
mo_vals = mv[1]
for mo_val in mo_vals:
resp_lines.append('"{}"'.format(mo_val.resource_uri))
resp_lines.append(
str(timestamp_from_datetime(mo_val.timestamp)))
v_list = []
for n, v in mo_val.values:
if isinstance(v, six.string_types):
v_str = '"{}"'.format(v)
else:
v_str = str(v)
v_list.append(v_str)
v_line = ','.join(v_list)
resp_lines.append(v_line)
resp_lines.append('')
resp_lines.append('')
resp_lines.append('')
return '\n'.join(resp_lines) + '\n' | python | def get_metric_values_response(self):
"""
Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object, as a
string in the format needed for the "Get Metrics" operation response.
Returns:
"MetricsResponse" string as described for the "Get Metrics"
operation response.
"""
mv_list = self.get_metric_values()
resp_lines = []
for mv in mv_list:
group_name = mv[0]
resp_lines.append('"{}"'.format(group_name))
mo_vals = mv[1]
for mo_val in mo_vals:
resp_lines.append('"{}"'.format(mo_val.resource_uri))
resp_lines.append(
str(timestamp_from_datetime(mo_val.timestamp)))
v_list = []
for n, v in mo_val.values:
if isinstance(v, six.string_types):
v_str = '"{}"'.format(v)
else:
v_str = str(v)
v_list.append(v_str)
v_line = ','.join(v_list)
resp_lines.append(v_line)
resp_lines.append('')
resp_lines.append('')
resp_lines.append('')
return '\n'.join(resp_lines) + '\n' | ['def', 'get_metric_values_response', '(', 'self', ')', ':', 'mv_list', '=', 'self', '.', 'get_metric_values', '(', ')', 'resp_lines', '=', '[', ']', 'for', 'mv', 'in', 'mv_list', ':', 'group_name', '=', 'mv', '[', '0', ']', 'resp_lines', '.', 'append', '(', '\'"{}"\'', '.', 'format', '(', 'group_name', ')', ')', 'mo_vals', '=', 'mv', '[', '1', ']', 'for', 'mo_val', 'in', 'mo_vals', ':', 'resp_lines', '.', 'append', '(', '\'"{}"\'', '.', 'format', '(', 'mo_val', '.', 'resource_uri', ')', ')', 'resp_lines', '.', 'append', '(', 'str', '(', 'timestamp_from_datetime', '(', 'mo_val', '.', 'timestamp', ')', ')', ')', 'v_list', '=', '[', ']', 'for', 'n', ',', 'v', 'in', 'mo_val', '.', 'values', ':', 'if', 'isinstance', '(', 'v', ',', 'six', '.', 'string_types', ')', ':', 'v_str', '=', '\'"{}"\'', '.', 'format', '(', 'v', ')', 'else', ':', 'v_str', '=', 'str', '(', 'v', ')', 'v_list', '.', 'append', '(', 'v_str', ')', 'v_line', '=', "','", '.', 'join', '(', 'v_list', ')', 'resp_lines', '.', 'append', '(', 'v_line', ')', 'resp_lines', '.', 'append', '(', "''", ')', 'resp_lines', '.', 'append', '(', "''", ')', 'resp_lines', '.', 'append', '(', "''", ')', 'return', "'\\n'", '.', 'join', '(', 'resp_lines', ')', '+', "'\\n'"] | Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object, as a
string in the format needed for the "Get Metrics" operation response.
Returns:
"MetricsResponse" string as described for the "Get Metrics"
operation response. | ['Get', 'the', 'faked', 'metrics', 'for', 'all', 'metric', 'groups', 'and', 'all', 'resources', 'that', 'have', 'been', 'prepared', 'on', 'the', 'manager', 'object', 'of', 'this', 'context', 'object', 'as', 'a', 'string', 'in', 'the', 'format', 'needed', 'for', 'the', 'Get', 'Metrics', 'operation', 'response', '.'] | train | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3077-L3110 |
8,018 | bitesofcode/projexui | projexui/widgets/xganttwidget/xganttviewitem.py | XGanttViewItem.mouseReleaseEvent | def mouseReleaseEvent(self, event):
"""
Overloads the mouse release event to apply the current changes.
:param event | <QEvent>
"""
super(XGanttViewItem, self).mouseReleaseEvent(event)
if not self.flags() & self.ItemIsMovable:
return
# force the x position to snap to the nearest date
scene = self.scene()
if scene:
gantt = scene.ganttWidget()
curr_x = self.pos().x() + gantt.cellWidth() / 2.0
new_x = curr_x - curr_x % gantt.cellWidth()
self.setPos(new_x, self.pos().y())
# look for date based times
gantt = self.scene().ganttWidget()
# determine hour/minute information
if gantt.timescale() in (gantt.Timescale.Minute,
gantt.Timescale.Hour,
gantt.Timescale.Day):
dstart = self.scene().datetimeAt(self.pos().x())
dend = self.scene().datetimeAt(self.pos().x() + self.rect().width())
dend.addSecs(-60)
else:
dstart = self.scene().dateAt(self.pos().x())
dend = self.scene().dateAt(self.pos().x() + self.rect().width())
dend = dend.addDays(-1)
item = self._treeItem()
if item:
item.viewChanged(dstart, dend) | python | def mouseReleaseEvent(self, event):
"""
Overloads the mouse release event to apply the current changes.
:param event | <QEvent>
"""
super(XGanttViewItem, self).mouseReleaseEvent(event)
if not self.flags() & self.ItemIsMovable:
return
# force the x position to snap to the nearest date
scene = self.scene()
if scene:
gantt = scene.ganttWidget()
curr_x = self.pos().x() + gantt.cellWidth() / 2.0
new_x = curr_x - curr_x % gantt.cellWidth()
self.setPos(new_x, self.pos().y())
# look for date based times
gantt = self.scene().ganttWidget()
# determine hour/minute information
if gantt.timescale() in (gantt.Timescale.Minute,
gantt.Timescale.Hour,
gantt.Timescale.Day):
dstart = self.scene().datetimeAt(self.pos().x())
dend = self.scene().datetimeAt(self.pos().x() + self.rect().width())
dend.addSecs(-60)
else:
dstart = self.scene().dateAt(self.pos().x())
dend = self.scene().dateAt(self.pos().x() + self.rect().width())
dend = dend.addDays(-1)
item = self._treeItem()
if item:
item.viewChanged(dstart, dend) | ['def', 'mouseReleaseEvent', '(', 'self', ',', 'event', ')', ':', 'super', '(', 'XGanttViewItem', ',', 'self', ')', '.', 'mouseReleaseEvent', '(', 'event', ')', 'if', 'not', 'self', '.', 'flags', '(', ')', '&', 'self', '.', 'ItemIsMovable', ':', 'return', '# force the x position to snap to the nearest date\r', 'scene', '=', 'self', '.', 'scene', '(', ')', 'if', 'scene', ':', 'gantt', '=', 'scene', '.', 'ganttWidget', '(', ')', 'curr_x', '=', 'self', '.', 'pos', '(', ')', '.', 'x', '(', ')', '+', 'gantt', '.', 'cellWidth', '(', ')', '/', '2.0', 'new_x', '=', 'curr_x', '-', 'curr_x', '%', 'gantt', '.', 'cellWidth', '(', ')', 'self', '.', 'setPos', '(', 'new_x', ',', 'self', '.', 'pos', '(', ')', '.', 'y', '(', ')', ')', '# look for date based times\r', 'gantt', '=', 'self', '.', 'scene', '(', ')', '.', 'ganttWidget', '(', ')', '# determine hour/minute information\r', 'if', 'gantt', '.', 'timescale', '(', ')', 'in', '(', 'gantt', '.', 'Timescale', '.', 'Minute', ',', 'gantt', '.', 'Timescale', '.', 'Hour', ',', 'gantt', '.', 'Timescale', '.', 'Day', ')', ':', 'dstart', '=', 'self', '.', 'scene', '(', ')', '.', 'datetimeAt', '(', 'self', '.', 'pos', '(', ')', '.', 'x', '(', ')', ')', 'dend', '=', 'self', '.', 'scene', '(', ')', '.', 'datetimeAt', '(', 'self', '.', 'pos', '(', ')', '.', 'x', '(', ')', '+', 'self', '.', 'rect', '(', ')', '.', 'width', '(', ')', ')', 'dend', '.', 'addSecs', '(', '-', '60', ')', 'else', ':', 'dstart', '=', 'self', '.', 'scene', '(', ')', '.', 'dateAt', '(', 'self', '.', 'pos', '(', ')', '.', 'x', '(', ')', ')', 'dend', '=', 'self', '.', 'scene', '(', ')', '.', 'dateAt', '(', 'self', '.', 'pos', '(', ')', '.', 'x', '(', ')', '+', 'self', '.', 'rect', '(', ')', '.', 'width', '(', ')', ')', 'dend', '=', 'dend', '.', 'addDays', '(', '-', '1', ')', 'item', '=', 'self', '.', '_treeItem', '(', ')', 'if', 'item', ':', 'item', '.', 'viewChanged', '(', 'dstart', ',', 'dend', ')'] | Overloads the mouse release event to apply the current changes.
:param event | <QEvent> | ['Overloads', 'the', 'mouse', 'release', 'event', 'to', 'apply', 'the', 'current', 'changes', '.', ':', 'param', 'event', '|', '<QEvent', '>'] | train | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttviewitem.py#L182-L219 |
8,019 | vimalkvn/riboplot | riboplot/riboplot.py | set_axis_color | def set_axis_color(axis, color, alpha=None):
"""Sets the spine color of all sides of an axis (top, right, bottom, left)."""
for side in ('top', 'right', 'bottom', 'left'):
spine = axis.spines[side]
spine.set_color(color)
if alpha is not None:
spine.set_alpha(alpha) | python | def set_axis_color(axis, color, alpha=None):
"""Sets the spine color of all sides of an axis (top, right, bottom, left)."""
for side in ('top', 'right', 'bottom', 'left'):
spine = axis.spines[side]
spine.set_color(color)
if alpha is not None:
spine.set_alpha(alpha) | ['def', 'set_axis_color', '(', 'axis', ',', 'color', ',', 'alpha', '=', 'None', ')', ':', 'for', 'side', 'in', '(', "'top'", ',', "'right'", ',', "'bottom'", ',', "'left'", ')', ':', 'spine', '=', 'axis', '.', 'spines', '[', 'side', ']', 'spine', '.', 'set_color', '(', 'color', ')', 'if', 'alpha', 'is', 'not', 'None', ':', 'spine', '.', 'set_alpha', '(', 'alpha', ')'] | Sets the spine color of all sides of an axis (top, right, bottom, left). | ['Sets', 'the', 'spine', 'color', 'of', 'all', 'sides', 'of', 'an', 'axis', '(', 'top', 'right', 'bottom', 'left', ')', '.'] | train | https://github.com/vimalkvn/riboplot/blob/914515df54eccc2e726ba71e751c3260f2066d97/riboplot/riboplot.py#L109-L115 |
8,020 | tmbo/questionary | questionary/prompts/password.py | password | def password(message: Text,
default: Text = "",
validate: Union[Type[Validator],
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Question the user to enter a secret text not displayed in the prompt.
This question type can be used to prompt the user for information
that should not be shown in the command line. The typed text will be
replaced with `*`.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
validate: Require the entered value to pass a validation. The
value can not be submited until the validator accepts
it (e.g. to check minimum password length).
This can either be a function accepting the input and
returning a boolean, or an class reference to a
subclass of the prompt toolkit Validator class.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
return text.text(message, default, validate, qmark, style,
is_password=True, **kwargs) | python | def password(message: Text,
default: Text = "",
validate: Union[Type[Validator],
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Question the user to enter a secret text not displayed in the prompt.
This question type can be used to prompt the user for information
that should not be shown in the command line. The typed text will be
replaced with `*`.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
validate: Require the entered value to pass a validation. The
value can not be submited until the validator accepts
it (e.g. to check minimum password length).
This can either be a function accepting the input and
returning a boolean, or an class reference to a
subclass of the prompt toolkit Validator class.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
return text.text(message, default, validate, qmark, style,
is_password=True, **kwargs) | ['def', 'password', '(', 'message', ':', 'Text', ',', 'default', ':', 'Text', '=', '""', ',', 'validate', ':', 'Union', '[', 'Type', '[', 'Validator', ']', ',', 'Callable', '[', '[', 'Text', ']', ',', 'bool', ']', ',', 'None', ']', '=', 'None', ',', '# noqa', 'qmark', ':', 'Text', '=', 'DEFAULT_QUESTION_PREFIX', ',', 'style', ':', 'Optional', '[', 'Style', ']', '=', 'None', ',', '*', '*', 'kwargs', ':', 'Any', ')', '->', 'Question', ':', 'return', 'text', '.', 'text', '(', 'message', ',', 'default', ',', 'validate', ',', 'qmark', ',', 'style', ',', 'is_password', '=', 'True', ',', '*', '*', 'kwargs', ')'] | Question the user to enter a secret text not displayed in the prompt.
This question type can be used to prompt the user for information
that should not be shown in the command line. The typed text will be
replaced with `*`.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
validate: Require the entered value to pass a validation. The
value can not be submited until the validator accepts
it (e.g. to check minimum password length).
This can either be a function accepting the input and
returning a boolean, or an class reference to a
subclass of the prompt toolkit Validator class.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`). | ['Question', 'the', 'user', 'to', 'enter', 'a', 'secret', 'text', 'not', 'displayed', 'in', 'the', 'prompt', '.'] | train | https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/password.py#L12-L51 |
8,021 | saltstack/salt | salt/modules/grains.py | append | def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 0.17.0
Append a value to a list in the grains config file. If the grain doesn't
exist, the grain key is added and the value is appended to the new grain
as a list item.
key
The grain key to be appended to
val
The value to append to the grain key
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
The key can be a nested dict key. Use this parameter to
specify the delimiter you use, instead of the default ``:``.
You can now append values to a list in nested dictionary grains. If the
list doesn't exist at this level, it will be created.
.. versionadded:: 2014.7.6
CLI Example:
.. code-block:: bash
salt '*' grains.append key val
'''
grains = get(key, [], delimiter)
if convert:
if not isinstance(grains, list):
grains = [] if grains is None else [grains]
if not isinstance(grains, list):
return 'The key {0} is not a valid list'.format(key)
if val in grains:
return 'The val {0} was already in the list {1}'.format(val, key)
if isinstance(val, list):
for item in val:
grains.append(item)
else:
grains.append(val)
while delimiter in key:
key, rest = key.rsplit(delimiter, 1)
_grain = get(key, _infinitedict(), delimiter)
if isinstance(_grain, dict):
_grain.update({rest: grains})
grains = _grain
return setval(key, grains) | python | def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 0.17.0
Append a value to a list in the grains config file. If the grain doesn't
exist, the grain key is added and the value is appended to the new grain
as a list item.
key
The grain key to be appended to
val
The value to append to the grain key
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
The key can be a nested dict key. Use this parameter to
specify the delimiter you use, instead of the default ``:``.
You can now append values to a list in nested dictionary grains. If the
list doesn't exist at this level, it will be created.
.. versionadded:: 2014.7.6
CLI Example:
.. code-block:: bash
salt '*' grains.append key val
'''
grains = get(key, [], delimiter)
if convert:
if not isinstance(grains, list):
grains = [] if grains is None else [grains]
if not isinstance(grains, list):
return 'The key {0} is not a valid list'.format(key)
if val in grains:
return 'The val {0} was already in the list {1}'.format(val, key)
if isinstance(val, list):
for item in val:
grains.append(item)
else:
grains.append(val)
while delimiter in key:
key, rest = key.rsplit(delimiter, 1)
_grain = get(key, _infinitedict(), delimiter)
if isinstance(_grain, dict):
_grain.update({rest: grains})
grains = _grain
return setval(key, grains) | ['def', 'append', '(', 'key', ',', 'val', ',', 'convert', '=', 'False', ',', 'delimiter', '=', 'DEFAULT_TARGET_DELIM', ')', ':', 'grains', '=', 'get', '(', 'key', ',', '[', ']', ',', 'delimiter', ')', 'if', 'convert', ':', 'if', 'not', 'isinstance', '(', 'grains', ',', 'list', ')', ':', 'grains', '=', '[', ']', 'if', 'grains', 'is', 'None', 'else', '[', 'grains', ']', 'if', 'not', 'isinstance', '(', 'grains', ',', 'list', ')', ':', 'return', "'The key {0} is not a valid list'", '.', 'format', '(', 'key', ')', 'if', 'val', 'in', 'grains', ':', 'return', "'The val {0} was already in the list {1}'", '.', 'format', '(', 'val', ',', 'key', ')', 'if', 'isinstance', '(', 'val', ',', 'list', ')', ':', 'for', 'item', 'in', 'val', ':', 'grains', '.', 'append', '(', 'item', ')', 'else', ':', 'grains', '.', 'append', '(', 'val', ')', 'while', 'delimiter', 'in', 'key', ':', 'key', ',', 'rest', '=', 'key', '.', 'rsplit', '(', 'delimiter', ',', '1', ')', '_grain', '=', 'get', '(', 'key', ',', '_infinitedict', '(', ')', ',', 'delimiter', ')', 'if', 'isinstance', '(', '_grain', ',', 'dict', ')', ':', '_grain', '.', 'update', '(', '{', 'rest', ':', 'grains', '}', ')', 'grains', '=', '_grain', 'return', 'setval', '(', 'key', ',', 'grains', ')'] | .. versionadded:: 0.17.0
Append a value to a list in the grains config file. If the grain doesn't
exist, the grain key is added and the value is appended to the new grain
as a list item.
key
The grain key to be appended to
val
The value to append to the grain key
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
The key can be a nested dict key. Use this parameter to
specify the delimiter you use, instead of the default ``:``.
You can now append values to a list in nested dictionary grains. If the
list doesn't exist at this level, it will be created.
.. versionadded:: 2014.7.6
CLI Example:
.. code-block:: bash
salt '*' grains.append key val | ['..', 'versionadded', '::', '0', '.', '17', '.', '0'] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L337-L391 |
8,022 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer.py | imagetransformer_base_10l_16h_big_dr01_imgnet | def imagetransformer_base_10l_16h_big_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.unconditional = False
hparams.layer_prepostprocess_dropout = 0.1
return hparams | python | def imagetransformer_base_10l_16h_big_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.unconditional = False
hparams.layer_prepostprocess_dropout = 0.1
return hparams | ['def', 'imagetransformer_base_10l_16h_big_dr01_imgnet', '(', ')', ':', 'hparams', '=', 'imagetransformer_base_14l_8h_big_dr01', '(', ')', '# num_hidden_layers', 'hparams', '.', 'num_decoder_layers', '=', '10', 'hparams', '.', 'num_heads', '=', '16', 'hparams', '.', 'hidden_size', '=', '1024', 'hparams', '.', 'filter_size', '=', '4096', 'hparams', '.', 'batch_size', '=', '1', 'hparams', '.', 'unconditional', '=', 'False', 'hparams', '.', 'layer_prepostprocess_dropout', '=', '0.1', 'return', 'hparams'] | big 1d model for conditional image generation. | ['big', '1d', 'model', 'for', 'conditional', 'image', 'generation', '.'] | train | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L813-L824 |
8,023 | saltstack/salt | doc/_ext/saltautodoc.py | SaltFunctionDocumenter.format_name | def format_name(self):
'''
Format the function name
'''
if not hasattr(self.module, '__func_alias__'):
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if not self.objpath:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if len(self.objpath) > 1:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
# Use the salt func aliased name instead of the real name
return self.module.__func_alias__.get(self.objpath[0], self.objpath[0]) | python | def format_name(self):
'''
Format the function name
'''
if not hasattr(self.module, '__func_alias__'):
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if not self.objpath:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if len(self.objpath) > 1:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
# Use the salt func aliased name instead of the real name
return self.module.__func_alias__.get(self.objpath[0], self.objpath[0]) | ['def', 'format_name', '(', 'self', ')', ':', 'if', 'not', 'hasattr', '(', 'self', '.', 'module', ',', "'__func_alias__'", ')', ':', '# Resume normal sphinx.ext.autodoc operation', 'return', 'super', '(', 'FunctionDocumenter', ',', 'self', ')', '.', 'format_name', '(', ')', 'if', 'not', 'self', '.', 'objpath', ':', '# Resume normal sphinx.ext.autodoc operation', 'return', 'super', '(', 'FunctionDocumenter', ',', 'self', ')', '.', 'format_name', '(', ')', 'if', 'len', '(', 'self', '.', 'objpath', ')', '>', '1', ':', '# Resume normal sphinx.ext.autodoc operation', 'return', 'super', '(', 'FunctionDocumenter', ',', 'self', ')', '.', 'format_name', '(', ')', '# Use the salt func aliased name instead of the real name', 'return', 'self', '.', 'module', '.', '__func_alias__', '.', 'get', '(', 'self', '.', 'objpath', '[', '0', ']', ',', 'self', '.', 'objpath', '[', '0', ']', ')'] | Format the function name | ['Format', 'the', 'function', 'name'] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltautodoc.py#L22-L39 |
8,024 | SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py | _get_events_list | def _get_events_list(object_key: str) -> List[str]:
"""Get list of event ids for the object with the specified key.
Args:
object_key (str): Key of an object in the database.
"""
return DB.get_list(_keys.events_list(object_key)) | python | def _get_events_list(object_key: str) -> List[str]:
"""Get list of event ids for the object with the specified key.
Args:
object_key (str): Key of an object in the database.
"""
return DB.get_list(_keys.events_list(object_key)) | ['def', '_get_events_list', '(', 'object_key', ':', 'str', ')', '->', 'List', '[', 'str', ']', ':', 'return', 'DB', '.', 'get_list', '(', '_keys', '.', 'events_list', '(', 'object_key', ')', ')'] | Get list of event ids for the object with the specified key.
Args:
object_key (str): Key of an object in the database. | ['Get', 'list', 'of', 'event', 'ids', 'for', 'the', 'object', 'with', 'the', 'specified', 'key', '.'] | train | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py#L92-L99 |
8,025 | SoCo/SoCo | soco/alarms.py | Alarm.volume | def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | python | def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | ['def', 'volume', '(', 'self', ',', 'volume', ')', ':', '# max 100', 'volume', '=', 'int', '(', 'volume', ')', 'self', '.', '_volume', '=', 'max', '(', '0', ',', 'min', '(', 'volume', ',', '100', ')', ')'] | See `volume`. | ['See', 'volume', '.'] | train | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L179-L183 |
8,026 | cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._add_discovery_config | def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.DiscoveryService.API_CONFIG['version'])
self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG | python | def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.DiscoveryService.API_CONFIG['version'])
self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG | ['def', '_add_discovery_config', '(', 'self', ')', ':', 'lookup_key', '=', '(', 'discovery_service', '.', 'DiscoveryService', '.', 'API_CONFIG', '[', "'name'", ']', ',', 'discovery_service', '.', 'DiscoveryService', '.', 'API_CONFIG', '[', "'version'", ']', ')', 'self', '.', '_configs', '[', 'lookup_key', ']', '=', 'discovery_service', '.', 'DiscoveryService', '.', 'API_CONFIG'] | Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held. | ['Add', 'the', 'Discovery', 'configuration', 'to', 'our', 'list', 'of', 'configs', '.'] | train | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L204-L212 |
8,027 | peterbrittain/asciimatics | asciimatics/widgets.py | Widget._pick_colours | def _pick_colours(self, palette_name, selected=False):
"""
Pick the rendering colour for a widget based on the current state.
:param palette_name: The stem name for the widget - e.g. "button".
:param selected: Whether this item is selected or not.
:returns: A colour tuple (fg, attr, bg) to be used.
"""
return self._frame.palette[self._pick_palette_key(palette_name, selected)] | python | def _pick_colours(self, palette_name, selected=False):
"""
Pick the rendering colour for a widget based on the current state.
:param palette_name: The stem name for the widget - e.g. "button".
:param selected: Whether this item is selected or not.
:returns: A colour tuple (fg, attr, bg) to be used.
"""
return self._frame.palette[self._pick_palette_key(palette_name, selected)] | ['def', '_pick_colours', '(', 'self', ',', 'palette_name', ',', 'selected', '=', 'False', ')', ':', 'return', 'self', '.', '_frame', '.', 'palette', '[', 'self', '.', '_pick_palette_key', '(', 'palette_name', ',', 'selected', ')', ']'] | Pick the rendering colour for a widget based on the current state.
:param palette_name: The stem name for the widget - e.g. "button".
:param selected: Whether this item is selected or not.
:returns: A colour tuple (fg, attr, bg) to be used. | ['Pick', 'the', 'rendering', 'colour', 'for', 'a', 'widget', 'based', 'on', 'the', 'current', 'state', '.'] | train | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L1587-L1595 |
8,028 | csparpa/pyowm | pyowm/stationsapi30/station.py | Station.creation_time | def creation_time(self, timeformat='unix'):
"""Returns the UTC time of creation of this station
:param timeformat: the format for the time value. May be:
'*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for
a ``datetime.datetime`` object
:type timeformat: str
:returns: an int or a str or a ``datetime.datetime`` object or None
:raises: ValueError
"""
if self.created_at is None:
return None
return timeformatutils.timeformat(self.created_at, timeformat) | python | def creation_time(self, timeformat='unix'):
"""Returns the UTC time of creation of this station
:param timeformat: the format for the time value. May be:
'*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for
a ``datetime.datetime`` object
:type timeformat: str
:returns: an int or a str or a ``datetime.datetime`` object or None
:raises: ValueError
"""
if self.created_at is None:
return None
return timeformatutils.timeformat(self.created_at, timeformat) | ['def', 'creation_time', '(', 'self', ',', 'timeformat', '=', "'unix'", ')', ':', 'if', 'self', '.', 'created_at', 'is', 'None', ':', 'return', 'None', 'return', 'timeformatutils', '.', 'timeformat', '(', 'self', '.', 'created_at', ',', 'timeformat', ')'] | Returns the UTC time of creation of this station
:param timeformat: the format for the time value. May be:
'*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for
a ``datetime.datetime`` object
:type timeformat: str
:returns: an int or a str or a ``datetime.datetime`` object or None
:raises: ValueError | ['Returns', 'the', 'UTC', 'time', 'of', 'creation', 'of', 'this', 'station'] | train | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/station.py#L87-L101 |
8,029 | openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_db_v2.py | update_host_mapping | def update_host_mapping(host_id, interface, nexus_ip, new_ch_grp):
"""Change channel_group in host/interface mapping data base."""
LOG.debug("update_host_mapping called")
session = bc.get_writer_session()
mapping = _lookup_one_host_mapping(
session=session,
host_id=host_id,
if_id=interface,
switch_ip=nexus_ip)
mapping.ch_grp = new_ch_grp
session.merge(mapping)
session.flush()
return mapping | python | def update_host_mapping(host_id, interface, nexus_ip, new_ch_grp):
"""Change channel_group in host/interface mapping data base."""
LOG.debug("update_host_mapping called")
session = bc.get_writer_session()
mapping = _lookup_one_host_mapping(
session=session,
host_id=host_id,
if_id=interface,
switch_ip=nexus_ip)
mapping.ch_grp = new_ch_grp
session.merge(mapping)
session.flush()
return mapping | ['def', 'update_host_mapping', '(', 'host_id', ',', 'interface', ',', 'nexus_ip', ',', 'new_ch_grp', ')', ':', 'LOG', '.', 'debug', '(', '"update_host_mapping called"', ')', 'session', '=', 'bc', '.', 'get_writer_session', '(', ')', 'mapping', '=', '_lookup_one_host_mapping', '(', 'session', '=', 'session', ',', 'host_id', '=', 'host_id', ',', 'if_id', '=', 'interface', ',', 'switch_ip', '=', 'nexus_ip', ')', 'mapping', '.', 'ch_grp', '=', 'new_ch_grp', 'session', '.', 'merge', '(', 'mapping', ')', 'session', '.', 'flush', '(', ')', 'return', 'mapping'] | Change channel_group in host/interface mapping data base. | ['Change', 'channel_group', 'in', 'host', '/', 'interface', 'mapping', 'data', 'base', '.'] | train | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_db_v2.py#L528-L541 |
8,030 | erdc/RAPIDpy | RAPIDpy/helper_functions.py | add_latlon_metadata | def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
lon_var.long_name = 'longitude'
lon_var.standard_name = 'longitude'
lon_var.units = 'degrees_east'
lon_var.axis = 'X' | python | def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
lon_var.long_name = 'longitude'
lon_var.standard_name = 'longitude'
lon_var.units = 'degrees_east'
lon_var.axis = 'X' | ['def', 'add_latlon_metadata', '(', 'lat_var', ',', 'lon_var', ')', ':', 'lat_var', '.', 'long_name', '=', "'latitude'", 'lat_var', '.', 'standard_name', '=', "'latitude'", 'lat_var', '.', 'units', '=', "'degrees_north'", 'lat_var', '.', 'axis', '=', "'Y'", 'lon_var', '.', 'long_name', '=', "'longitude'", 'lon_var', '.', 'standard_name', '=', "'longitude'", 'lon_var', '.', 'units', '=', "'degrees_east'", 'lon_var', '.', 'axis', '=', "'X'"] | Adds latitude and longitude metadata | ['Adds', 'latitude', 'and', 'longitude', 'metadata'] | train | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/helper_functions.py#L126-L136 |
8,031 | OpenHydrology/floodestimation | floodestimation/analysis.py | QmedAnalysis._model_error_corr | def _model_error_corr(self, catchment1, catchment2):
"""
Return model error correlation between subject catchment and other catchment.
Methodology source: Kjeldsen & Jones, 2009, table 3
:param catchment1: catchment to calculate error correlation with
:type catchment1: :class:`Catchment`
:param catchment2: catchment to calculate error correlation with
:type catchment2: :class:`Catchment`
:return: correlation coefficient, r
:rtype: float
"""
dist = catchment1.distance_to(catchment2)
return self._dist_corr(dist, 0.3998, 0.0283, 0.9494) | python | def _model_error_corr(self, catchment1, catchment2):
"""
Return model error correlation between subject catchment and other catchment.
Methodology source: Kjeldsen & Jones, 2009, table 3
:param catchment1: catchment to calculate error correlation with
:type catchment1: :class:`Catchment`
:param catchment2: catchment to calculate error correlation with
:type catchment2: :class:`Catchment`
:return: correlation coefficient, r
:rtype: float
"""
dist = catchment1.distance_to(catchment2)
return self._dist_corr(dist, 0.3998, 0.0283, 0.9494) | ['def', '_model_error_corr', '(', 'self', ',', 'catchment1', ',', 'catchment2', ')', ':', 'dist', '=', 'catchment1', '.', 'distance_to', '(', 'catchment2', ')', 'return', 'self', '.', '_dist_corr', '(', 'dist', ',', '0.3998', ',', '0.0283', ',', '0.9494', ')'] | Return model error correlation between subject catchment and other catchment.
Methodology source: Kjeldsen & Jones, 2009, table 3
:param catchment1: catchment to calculate error correlation with
:type catchment1: :class:`Catchment`
:param catchment2: catchment to calculate error correlation with
:type catchment2: :class:`Catchment`
:return: correlation coefficient, r
:rtype: float | ['Return', 'model', 'error', 'correlation', 'between', 'subject', 'catchment', 'and', 'other', 'catchment', '.'] | train | https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L460-L474 |
8,032 | tijme/not-your-average-web-crawler | nyawc/Crawler.py | Crawler.__crawler_start | def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks.
"""
try:
self.__options.callbacks.crawler_before_start()
except Exception as e:
print(e)
print(traceback.format_exc())
self.__spawn_new_requests()
while not self.__stopped:
if self.__should_stop:
self.__crawler_stop()
if self.__should_spawn_new_requests:
self.__spawn_new_requests()
time.sleep(0.1) | python | def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks.
"""
try:
self.__options.callbacks.crawler_before_start()
except Exception as e:
print(e)
print(traceback.format_exc())
self.__spawn_new_requests()
while not self.__stopped:
if self.__should_stop:
self.__crawler_stop()
if self.__should_spawn_new_requests:
self.__spawn_new_requests()
time.sleep(0.1) | ['def', '__crawler_start', '(', 'self', ')', ':', 'try', ':', 'self', '.', '__options', '.', 'callbacks', '.', 'crawler_before_start', '(', ')', 'except', 'Exception', 'as', 'e', ':', 'print', '(', 'e', ')', 'print', '(', 'traceback', '.', 'format_exc', '(', ')', ')', 'self', '.', '__spawn_new_requests', '(', ')', 'while', 'not', 'self', '.', '__stopped', ':', 'if', 'self', '.', '__should_stop', ':', 'self', '.', '__crawler_stop', '(', ')', 'if', 'self', '.', '__should_spawn_new_requests', ':', 'self', '.', '__spawn_new_requests', '(', ')', 'time', '.', 'sleep', '(', '0.1', ')'] | Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks. | ['Spawn', 'the', 'first', 'X', 'queued', 'request', 'where', 'X', 'is', 'the', 'max', 'threads', 'option', '.'] | train | https://github.com/tijme/not-your-average-web-crawler/blob/d77c14e1616c541bb3980f649a7e6f8ed02761fb/nyawc/Crawler.py#L151-L179 |
8,033 | etal/biofrills | biofrills/logoutils.py | letter_scales | def letter_scales(counts):
"""Convert letter counts to frequencies, sorted increasing."""
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
# This logo is all gaps, nothing can be done
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
freqs.sort(key=lambda pair: pair[1])
return freqs | python | def letter_scales(counts):
"""Convert letter counts to frequencies, sorted increasing."""
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
# This logo is all gaps, nothing can be done
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
freqs.sort(key=lambda pair: pair[1])
return freqs | ['def', 'letter_scales', '(', 'counts', ')', ':', 'try', ':', 'scale', '=', '1.0', '/', 'sum', '(', 'counts', '.', 'values', '(', ')', ')', 'except', 'ZeroDivisionError', ':', '# This logo is all gaps, nothing can be done', 'return', '[', ']', 'freqs', '=', '[', '(', 'aa', ',', 'cnt', '*', 'scale', ')', 'for', 'aa', ',', 'cnt', 'in', 'counts', '.', 'iteritems', '(', ')', 'if', 'cnt', ']', 'freqs', '.', 'sort', '(', 'key', '=', 'lambda', 'pair', ':', 'pair', '[', '1', ']', ')', 'return', 'freqs'] | Convert letter counts to frequencies, sorted increasing. | ['Convert', 'letter', 'counts', 'to', 'frequencies', 'sorted', 'increasing', '.'] | train | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/logoutils.py#L46-L55 |
8,034 | klmitch/turnstile | turnstile/control.py | ControlDaemon.reload | def reload(self):
"""
Reloads the limits configuration from the database.
If an error occurs loading the configuration, an error-level
log message will be emitted. Additionally, the error message
will be added to the set specified by the 'redis.errors_key'
configuration ('errors' by default) and sent to the publishing
channel specified by the 'redis.errors_channel' configuration
('errors' by default).
"""
# Acquire the pending semaphore. If we fail, exit--someone
# else is already doing the reload
if not self.pending.acquire(False):
return
# Do the remaining steps in a try/finally block so we make
# sure to release the semaphore
control_args = self.config['control']
try:
# Load all the limits
key = control_args.get('limits_key', 'limits')
self.limits.set_limits(self.db.zrange(key, 0, -1))
except Exception:
# Log an error
LOG.exception("Could not load limits")
# Get our error set and publish channel
error_key = control_args.get('errors_key', 'errors')
error_channel = control_args.get('errors_channel', 'errors')
# Get an informative message
msg = "Failed to load limits: " + traceback.format_exc()
# Store the message into the error set. We use a set here
# because it's likely that more than one node will
# generate the same message if there is an error, and this
# avoids an explosion in the size of the set.
with utils.ignore_except():
self.db.sadd(error_key, msg)
# Publish the message to a channel
with utils.ignore_except():
self.db.publish(error_channel, msg)
finally:
self.pending.release() | python | def reload(self):
"""
Reloads the limits configuration from the database.
If an error occurs loading the configuration, an error-level
log message will be emitted. Additionally, the error message
will be added to the set specified by the 'redis.errors_key'
configuration ('errors' by default) and sent to the publishing
channel specified by the 'redis.errors_channel' configuration
('errors' by default).
"""
# Acquire the pending semaphore. If we fail, exit--someone
# else is already doing the reload
if not self.pending.acquire(False):
return
# Do the remaining steps in a try/finally block so we make
# sure to release the semaphore
control_args = self.config['control']
try:
# Load all the limits
key = control_args.get('limits_key', 'limits')
self.limits.set_limits(self.db.zrange(key, 0, -1))
except Exception:
# Log an error
LOG.exception("Could not load limits")
# Get our error set and publish channel
error_key = control_args.get('errors_key', 'errors')
error_channel = control_args.get('errors_channel', 'errors')
# Get an informative message
msg = "Failed to load limits: " + traceback.format_exc()
# Store the message into the error set. We use a set here
# because it's likely that more than one node will
# generate the same message if there is an error, and this
# avoids an explosion in the size of the set.
with utils.ignore_except():
self.db.sadd(error_key, msg)
# Publish the message to a channel
with utils.ignore_except():
self.db.publish(error_channel, msg)
finally:
self.pending.release() | ['def', 'reload', '(', 'self', ')', ':', '# Acquire the pending semaphore. If we fail, exit--someone', '# else is already doing the reload', 'if', 'not', 'self', '.', 'pending', '.', 'acquire', '(', 'False', ')', ':', 'return', '# Do the remaining steps in a try/finally block so we make', '# sure to release the semaphore', 'control_args', '=', 'self', '.', 'config', '[', "'control'", ']', 'try', ':', '# Load all the limits', 'key', '=', 'control_args', '.', 'get', '(', "'limits_key'", ',', "'limits'", ')', 'self', '.', 'limits', '.', 'set_limits', '(', 'self', '.', 'db', '.', 'zrange', '(', 'key', ',', '0', ',', '-', '1', ')', ')', 'except', 'Exception', ':', '# Log an error', 'LOG', '.', 'exception', '(', '"Could not load limits"', ')', '# Get our error set and publish channel', 'error_key', '=', 'control_args', '.', 'get', '(', "'errors_key'", ',', "'errors'", ')', 'error_channel', '=', 'control_args', '.', 'get', '(', "'errors_channel'", ',', "'errors'", ')', '# Get an informative message', 'msg', '=', '"Failed to load limits: "', '+', 'traceback', '.', 'format_exc', '(', ')', '# Store the message into the error set. We use a set here', "# because it's likely that more than one node will", '# generate the same message if there is an error, and this', '# avoids an explosion in the size of the set.', 'with', 'utils', '.', 'ignore_except', '(', ')', ':', 'self', '.', 'db', '.', 'sadd', '(', 'error_key', ',', 'msg', ')', '# Publish the message to a channel', 'with', 'utils', '.', 'ignore_except', '(', ')', ':', 'self', '.', 'db', '.', 'publish', '(', 'error_channel', ',', 'msg', ')', 'finally', ':', 'self', '.', 'pending', '.', 'release', '(', ')'] | Reloads the limits configuration from the database.
If an error occurs loading the configuration, an error-level
log message will be emitted. Additionally, the error message
will be added to the set specified by the 'redis.errors_key'
configuration ('errors' by default) and sent to the publishing
channel specified by the 'redis.errors_channel' configuration
('errors' by default). | ['Reloads', 'the', 'limits', 'configuration', 'from', 'the', 'database', '.'] | train | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L225-L271 |
8,035 | akfullfo/taskforce | taskforce/watch_files.py | watch.commit | def commit(self, **params):
"""
Rebuild kevent operations by removing open files that no longer need to
be watched, and adding new files if they are not currently being watched.
This is done by comparing self.paths to self.paths_open.
"""
log = self._getparam('log', self._discard, **params)
# Find all the modules that no longer need watching
#
removed = 0
added = 0
for path in list(self.paths_open):
if path not in self.paths:
fd = self.paths_open[path]
if self._mode == WF_KQUEUE:
# kevent automatically deletes the event when the fd is closed
try:
os.close(fd)
except Exception as e:
log.warning("close failed on watched file %r -- %s", path, e)
elif self._mode == WF_INOTIFYX:
try:
pynotifyx.rm_watch(self._inx_fd, fd)
except Exception as e:
log.warning("remove failed on watched file %r -- %s", path, e)
if path in self._inx_inode:
del self._inx_inode[path]
elif self._mode == WF_POLLING:
if fd in self._poll_stat:
del self._poll_stat[fd]
else:
log.warning("fd watched path %r missing from _poll_stat map", path)
try:
os.close(fd)
except Exception as e:
log.warning("close failed on watched file %r -- %s", path, e)
if fd in self.fds_open:
del self.fds_open[fd]
else:
log.warning("fd watched path %r missing from fd map", path)
del self.paths_open[path]
log.debug("Removed watch for path %r", path)
removed += 1
# Find all the paths that are new and should be watched
#
fdlist = []
failed = []
last_exc = None
log.debug("%d watched path%s", len(self.paths), ses(len(self.paths)))
for path in list(self.paths):
if path not in self.paths_open:
try:
if not self._add_file(path, **params):
continue
except Exception as e:
last_exc = e
failed.append(path)
continue
fdlist.append(self.paths_open[path])
if path in self.paths_pending:
log.debug("pending path %r has now appeared", path)
del self.paths_pending[path]
self._trigger(self.paths_open[path], **params)
added += 1
log.debug("Added watch for path %r with ident %d", path, self.paths_open[path])
if failed:
self._clean_failed_fds(fdlist)
raise Exception("Failed to set watch on %s -- %s" % (str(failed), str(last_exc)))
log.debug("%d added, %d removed", added, removed) | python | def commit(self, **params):
"""
Rebuild kevent operations by removing open files that no longer need to
be watched, and adding new files if they are not currently being watched.
This is done by comparing self.paths to self.paths_open.
"""
log = self._getparam('log', self._discard, **params)
# Find all the modules that no longer need watching
#
removed = 0
added = 0
for path in list(self.paths_open):
if path not in self.paths:
fd = self.paths_open[path]
if self._mode == WF_KQUEUE:
# kevent automatically deletes the event when the fd is closed
try:
os.close(fd)
except Exception as e:
log.warning("close failed on watched file %r -- %s", path, e)
elif self._mode == WF_INOTIFYX:
try:
pynotifyx.rm_watch(self._inx_fd, fd)
except Exception as e:
log.warning("remove failed on watched file %r -- %s", path, e)
if path in self._inx_inode:
del self._inx_inode[path]
elif self._mode == WF_POLLING:
if fd in self._poll_stat:
del self._poll_stat[fd]
else:
log.warning("fd watched path %r missing from _poll_stat map", path)
try:
os.close(fd)
except Exception as e:
log.warning("close failed on watched file %r -- %s", path, e)
if fd in self.fds_open:
del self.fds_open[fd]
else:
log.warning("fd watched path %r missing from fd map", path)
del self.paths_open[path]
log.debug("Removed watch for path %r", path)
removed += 1
# Find all the paths that are new and should be watched
#
fdlist = []
failed = []
last_exc = None
log.debug("%d watched path%s", len(self.paths), ses(len(self.paths)))
for path in list(self.paths):
if path not in self.paths_open:
try:
if not self._add_file(path, **params):
continue
except Exception as e:
last_exc = e
failed.append(path)
continue
fdlist.append(self.paths_open[path])
if path in self.paths_pending:
log.debug("pending path %r has now appeared", path)
del self.paths_pending[path]
self._trigger(self.paths_open[path], **params)
added += 1
log.debug("Added watch for path %r with ident %d", path, self.paths_open[path])
if failed:
self._clean_failed_fds(fdlist)
raise Exception("Failed to set watch on %s -- %s" % (str(failed), str(last_exc)))
log.debug("%d added, %d removed", added, removed) | ['def', 'commit', '(', 'self', ',', '*', '*', 'params', ')', ':', 'log', '=', 'self', '.', '_getparam', '(', "'log'", ',', 'self', '.', '_discard', ',', '*', '*', 'params', ')', '# Find all the modules that no longer need watching', '#', 'removed', '=', '0', 'added', '=', '0', 'for', 'path', 'in', 'list', '(', 'self', '.', 'paths_open', ')', ':', 'if', 'path', 'not', 'in', 'self', '.', 'paths', ':', 'fd', '=', 'self', '.', 'paths_open', '[', 'path', ']', 'if', 'self', '.', '_mode', '==', 'WF_KQUEUE', ':', '# kevent automatically deletes the event when the fd is closed', 'try', ':', 'os', '.', 'close', '(', 'fd', ')', 'except', 'Exception', 'as', 'e', ':', 'log', '.', 'warning', '(', '"close failed on watched file %r -- %s"', ',', 'path', ',', 'e', ')', 'elif', 'self', '.', '_mode', '==', 'WF_INOTIFYX', ':', 'try', ':', 'pynotifyx', '.', 'rm_watch', '(', 'self', '.', '_inx_fd', ',', 'fd', ')', 'except', 'Exception', 'as', 'e', ':', 'log', '.', 'warning', '(', '"remove failed on watched file %r -- %s"', ',', 'path', ',', 'e', ')', 'if', 'path', 'in', 'self', '.', '_inx_inode', ':', 'del', 'self', '.', '_inx_inode', '[', 'path', ']', 'elif', 'self', '.', '_mode', '==', 'WF_POLLING', ':', 'if', 'fd', 'in', 'self', '.', '_poll_stat', ':', 'del', 'self', '.', '_poll_stat', '[', 'fd', ']', 'else', ':', 'log', '.', 'warning', '(', '"fd watched path %r missing from _poll_stat map"', ',', 'path', ')', 'try', ':', 'os', '.', 'close', '(', 'fd', ')', 'except', 'Exception', 'as', 'e', ':', 'log', '.', 'warning', '(', '"close failed on watched file %r -- %s"', ',', 'path', ',', 'e', ')', 'if', 'fd', 'in', 'self', '.', 'fds_open', ':', 'del', 'self', '.', 'fds_open', '[', 'fd', ']', 'else', ':', 'log', '.', 'warning', '(', '"fd watched path %r missing from fd map"', ',', 'path', ')', 'del', 'self', '.', 'paths_open', '[', 'path', ']', 'log', '.', 'debug', '(', '"Removed watch for path %r"', ',', 'path', ')', 'removed', '+=', '1', '# Find all the paths that are new and should be watched', '#', 'fdlist', '=', '[', ']', 'failed', '=', '[', ']', 'last_exc', '=', 'None', 'log', '.', 'debug', '(', '"%d watched path%s"', ',', 'len', '(', 'self', '.', 'paths', ')', ',', 'ses', '(', 'len', '(', 'self', '.', 'paths', ')', ')', ')', 'for', 'path', 'in', 'list', '(', 'self', '.', 'paths', ')', ':', 'if', 'path', 'not', 'in', 'self', '.', 'paths_open', ':', 'try', ':', 'if', 'not', 'self', '.', '_add_file', '(', 'path', ',', '*', '*', 'params', ')', ':', 'continue', 'except', 'Exception', 'as', 'e', ':', 'last_exc', '=', 'e', 'failed', '.', 'append', '(', 'path', ')', 'continue', 'fdlist', '.', 'append', '(', 'self', '.', 'paths_open', '[', 'path', ']', ')', 'if', 'path', 'in', 'self', '.', 'paths_pending', ':', 'log', '.', 'debug', '(', '"pending path %r has now appeared"', ',', 'path', ')', 'del', 'self', '.', 'paths_pending', '[', 'path', ']', 'self', '.', '_trigger', '(', 'self', '.', 'paths_open', '[', 'path', ']', ',', '*', '*', 'params', ')', 'added', '+=', '1', 'log', '.', 'debug', '(', '"Added watch for path %r with ident %d"', ',', 'path', ',', 'self', '.', 'paths_open', '[', 'path', ']', ')', 'if', 'failed', ':', 'self', '.', '_clean_failed_fds', '(', 'fdlist', ')', 'raise', 'Exception', '(', '"Failed to set watch on %s -- %s"', '%', '(', 'str', '(', 'failed', ')', ',', 'str', '(', 'last_exc', ')', ')', ')', 'log', '.', 'debug', '(', '"%d added, %d removed"', ',', 'added', ',', 'removed', ')'] | Rebuild kevent operations by removing open files that no longer need to
be watched, and adding new files if they are not currently being watched.
This is done by comparing self.paths to self.paths_open. | ['Rebuild', 'kevent', 'operations', 'by', 'removing', 'open', 'files', 'that', 'no', 'longer', 'need', 'to', 'be', 'watched', 'and', 'adding', 'new', 'files', 'if', 'they', 'are', 'not', 'currently', 'being', 'watched', '.'] | train | https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/watch_files.py#L451-L524 |
8,036 | bxlab/bx-python | lib/bx/align/epo.py | EPOitem.cigar_iter | def cigar_iter(self, reverse):
"""self.cigar => [(length, type) ... ] iterate the cigar
:param reverse: whether to iterate in the reverse direction (right-to-left)
:type reverse: boolean
:return a list of pairs of the type [(length, M/D) ..]
"""
l = 0
P = self.cigar_pattern
data = []
cigar = self.cigar
parsed_cigar = re.findall(P, cigar)
if reverse:
parsed_cigar = parsed_cigar[::-1]
for _l, t in parsed_cigar:
# 1M is encoded as M
l = (_l and int(_l) or 1) # int(_l) cannot be 0
data.append( (l, t) )
return data | python | def cigar_iter(self, reverse):
"""self.cigar => [(length, type) ... ] iterate the cigar
:param reverse: whether to iterate in the reverse direction (right-to-left)
:type reverse: boolean
:return a list of pairs of the type [(length, M/D) ..]
"""
l = 0
P = self.cigar_pattern
data = []
cigar = self.cigar
parsed_cigar = re.findall(P, cigar)
if reverse:
parsed_cigar = parsed_cigar[::-1]
for _l, t in parsed_cigar:
# 1M is encoded as M
l = (_l and int(_l) or 1) # int(_l) cannot be 0
data.append( (l, t) )
return data | ['def', 'cigar_iter', '(', 'self', ',', 'reverse', ')', ':', 'l', '=', '0', 'P', '=', 'self', '.', 'cigar_pattern', 'data', '=', '[', ']', 'cigar', '=', 'self', '.', 'cigar', 'parsed_cigar', '=', 're', '.', 'findall', '(', 'P', ',', 'cigar', ')', 'if', 'reverse', ':', 'parsed_cigar', '=', 'parsed_cigar', '[', ':', ':', '-', '1', ']', 'for', '_l', ',', 't', 'in', 'parsed_cigar', ':', '# 1M is encoded as M', 'l', '=', '(', '_l', 'and', 'int', '(', '_l', ')', 'or', '1', ')', '# int(_l) cannot be 0', 'data', '.', 'append', '(', '(', 'l', ',', 't', ')', ')', 'return', 'data'] | self.cigar => [(length, type) ... ] iterate the cigar
:param reverse: whether to iterate in the reverse direction (right-to-left)
:type reverse: boolean
:return a list of pairs of the type [(length, M/D) ..] | ['self', '.', 'cigar', '=', '>', '[', '(', 'length', 'type', ')', '...', ']', 'iterate', 'the', 'cigar'] | train | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/epo.py#L226-L247 |
8,037 | martinrusev/django-redis-sessions | redis_sessions/session.py | SessionStore.get_real_stored_key | def get_real_stored_key(self, session_key):
"""Return the real key name in redis storage
@return string
"""
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | python | def get_real_stored_key(self, session_key):
"""Return the real key name in redis storage
@return string
"""
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | ['def', 'get_real_stored_key', '(', 'self', ',', 'session_key', ')', ':', 'prefix', '=', 'settings', '.', 'SESSION_REDIS_PREFIX', 'if', 'not', 'prefix', ':', 'return', 'session_key', 'return', "':'", '.', 'join', '(', '[', 'prefix', ',', 'session_key', ']', ')'] | Return the real key name in redis storage
@return string | ['Return', 'the', 'real', 'key', 'name', 'in', 'redis', 'storage'] | train | https://github.com/martinrusev/django-redis-sessions/blob/260b9f3b61a17de9fa26f3e697b94bceee21e715/redis_sessions/session.py#L169-L176 |
8,038 | pypa/pipenv | pipenv/vendor/urllib3/util/ssl_.py | ssl_wrap_socket | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
"""
All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support.
:param ca_cert_dir:
A directory containing CA certificates in multiple separate files, as
supported by OpenSSL's -CApath flag or the capath argument to
SSLContext.load_verify_locations().
"""
context = ssl_context
if context is None:
# Note: This branch of code and all the variables in it are no longer
# used by urllib3 itself. We should consider deprecating and removing
# this code.
context = create_urllib3_context(ssl_version, cert_reqs,
ciphers=ciphers)
if ca_certs or ca_cert_dir:
try:
context.load_verify_locations(ca_certs, ca_cert_dir)
except IOError as e: # Platform-specific: Python 2.7
raise SSLError(e)
# Py33 raises FileNotFoundError which subclasses OSError
# These are not equivalent unless we check the errno attribute
except OSError as e: # Platform-specific: Python 3.3 and beyond
if e.errno == errno.ENOENT:
raise SSLError(e)
raise
elif getattr(context, 'load_default_certs', None) is not None:
# try to load OS default certs; works well on Windows (require Python3.4+)
context.load_default_certs()
if certfile:
context.load_cert_chain(certfile, keyfile)
# If we detect server_hostname is an IP address then the SNI
# extension should not be used according to RFC3546 Section 3.1
# We shouldn't warn the user if SNI isn't available but we would
# not be using SNI anyways due to IP address for server_hostname.
if ((server_hostname is not None and not is_ipaddress(server_hostname))
or IS_SECURETRANSPORT):
if HAS_SNI and server_hostname is not None:
return context.wrap_socket(sock, server_hostname=server_hostname)
warnings.warn(
'An HTTPS request has been made, but the SNI (Server Name '
'Indication) extension to TLS is not available on this platform. '
'This may cause the server to present an incorrect TLS '
'certificate, which can cause validation failures. You can upgrade to '
'a newer version of Python to solve this. For more information, see '
'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
'#ssl-warnings',
SNIMissingWarning
)
return context.wrap_socket(sock) | python | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
"""
All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support.
:param ca_cert_dir:
A directory containing CA certificates in multiple separate files, as
supported by OpenSSL's -CApath flag or the capath argument to
SSLContext.load_verify_locations().
"""
context = ssl_context
if context is None:
# Note: This branch of code and all the variables in it are no longer
# used by urllib3 itself. We should consider deprecating and removing
# this code.
context = create_urllib3_context(ssl_version, cert_reqs,
ciphers=ciphers)
if ca_certs or ca_cert_dir:
try:
context.load_verify_locations(ca_certs, ca_cert_dir)
except IOError as e: # Platform-specific: Python 2.7
raise SSLError(e)
# Py33 raises FileNotFoundError which subclasses OSError
# These are not equivalent unless we check the errno attribute
except OSError as e: # Platform-specific: Python 3.3 and beyond
if e.errno == errno.ENOENT:
raise SSLError(e)
raise
elif getattr(context, 'load_default_certs', None) is not None:
# try to load OS default certs; works well on Windows (require Python3.4+)
context.load_default_certs()
if certfile:
context.load_cert_chain(certfile, keyfile)
# If we detect server_hostname is an IP address then the SNI
# extension should not be used according to RFC3546 Section 3.1
# We shouldn't warn the user if SNI isn't available but we would
# not be using SNI anyways due to IP address for server_hostname.
if ((server_hostname is not None and not is_ipaddress(server_hostname))
or IS_SECURETRANSPORT):
if HAS_SNI and server_hostname is not None:
return context.wrap_socket(sock, server_hostname=server_hostname)
warnings.warn(
'An HTTPS request has been made, but the SNI (Server Name '
'Indication) extension to TLS is not available on this platform. '
'This may cause the server to present an incorrect TLS '
'certificate, which can cause validation failures. You can upgrade to '
'a newer version of Python to solve this. For more information, see '
'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
'#ssl-warnings',
SNIMissingWarning
)
return context.wrap_socket(sock) | ['def', 'ssl_wrap_socket', '(', 'sock', ',', 'keyfile', '=', 'None', ',', 'certfile', '=', 'None', ',', 'cert_reqs', '=', 'None', ',', 'ca_certs', '=', 'None', ',', 'server_hostname', '=', 'None', ',', 'ssl_version', '=', 'None', ',', 'ciphers', '=', 'None', ',', 'ssl_context', '=', 'None', ',', 'ca_cert_dir', '=', 'None', ')', ':', 'context', '=', 'ssl_context', 'if', 'context', 'is', 'None', ':', '# Note: This branch of code and all the variables in it are no longer', '# used by urllib3 itself. We should consider deprecating and removing', '# this code.', 'context', '=', 'create_urllib3_context', '(', 'ssl_version', ',', 'cert_reqs', ',', 'ciphers', '=', 'ciphers', ')', 'if', 'ca_certs', 'or', 'ca_cert_dir', ':', 'try', ':', 'context', '.', 'load_verify_locations', '(', 'ca_certs', ',', 'ca_cert_dir', ')', 'except', 'IOError', 'as', 'e', ':', '# Platform-specific: Python 2.7', 'raise', 'SSLError', '(', 'e', ')', '# Py33 raises FileNotFoundError which subclasses OSError', '# These are not equivalent unless we check the errno attribute', 'except', 'OSError', 'as', 'e', ':', '# Platform-specific: Python 3.3 and beyond', 'if', 'e', '.', 'errno', '==', 'errno', '.', 'ENOENT', ':', 'raise', 'SSLError', '(', 'e', ')', 'raise', 'elif', 'getattr', '(', 'context', ',', "'load_default_certs'", ',', 'None', ')', 'is', 'not', 'None', ':', '# try to load OS default certs; works well on Windows (require Python3.4+)', 'context', '.', 'load_default_certs', '(', ')', 'if', 'certfile', ':', 'context', '.', 'load_cert_chain', '(', 'certfile', ',', 'keyfile', ')', '# If we detect server_hostname is an IP address then the SNI', '# extension should not be used according to RFC3546 Section 3.1', "# We shouldn't warn the user if SNI isn't available but we would", '# not be using SNI anyways due to IP address for server_hostname.', 'if', '(', '(', 'server_hostname', 'is', 'not', 'None', 'and', 'not', 'is_ipaddress', '(', 'server_hostname', ')', ')', 'or', 'IS_SECURETRANSPORT', ')', ':', 'if', 'HAS_SNI', 'and', 'server_hostname', 'is', 'not', 'None', ':', 'return', 'context', '.', 'wrap_socket', '(', 'sock', ',', 'server_hostname', '=', 'server_hostname', ')', 'warnings', '.', 'warn', '(', "'An HTTPS request has been made, but the SNI (Server Name '", "'Indication) extension to TLS is not available on this platform. '", "'This may cause the server to present an incorrect TLS '", "'certificate, which can cause validation failures. You can upgrade to '", "'a newer version of Python to solve this. For more information, see '", "'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'", "'#ssl-warnings'", ',', 'SNIMissingWarning', ')', 'return', 'context', '.', 'wrap_socket', '(', 'sock', ')'] | All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support.
:param ca_cert_dir:
A directory containing CA certificates in multiple separate files, as
supported by OpenSSL's -CApath flag or the capath argument to
SSLContext.load_verify_locations(). | ['All', 'arguments', 'except', 'for', 'server_hostname', 'ssl_context', 'and', 'ca_cert_dir', 'have', 'the', 'same', 'meaning', 'as', 'they', 'do', 'when', 'using', ':', 'func', ':', 'ssl', '.', 'wrap_socket', '.'] | train | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/ssl_.py#L291-L357 |
8,039 | hwmrocker/smtplibaio | smtplibaio/smtp.py | SMTP.mail | async def mail(self, sender, options=None):
"""
Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options (list of str or None, optional): Additional options to send
along with the *MAIL* command.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPCommandFailedError: If the MAIL command fails.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response.
.. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2
.. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
"""
if options is None:
options = []
from_addr = "FROM:{}".format(quoteaddr(sender))
code, message = await self.do_cmd("MAIL", from_addr, *options)
return code, message | python | async def mail(self, sender, options=None):
"""
Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options (list of str or None, optional): Additional options to send
along with the *MAIL* command.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPCommandFailedError: If the MAIL command fails.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response.
.. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2
.. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
"""
if options is None:
options = []
from_addr = "FROM:{}".format(quoteaddr(sender))
code, message = await self.do_cmd("MAIL", from_addr, *options)
return code, message | ['async', 'def', 'mail', '(', 'self', ',', 'sender', ',', 'options', '=', 'None', ')', ':', 'if', 'options', 'is', 'None', ':', 'options', '=', '[', ']', 'from_addr', '=', '"FROM:{}"', '.', 'format', '(', 'quoteaddr', '(', 'sender', ')', ')', 'code', ',', 'message', '=', 'await', 'self', '.', 'do_cmd', '(', '"MAIL"', ',', 'from_addr', ',', '*', 'options', ')', 'return', 'code', ',', 'message'] | Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options (list of str or None, optional): Additional options to send
along with the *MAIL* command.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPCommandFailedError: If the MAIL command fails.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response.
.. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2
.. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 | ['Sends', 'a', 'SMTP', 'MAIL', 'command', '.', '-', 'Starts', 'the', 'mail', 'transfer', 'session', '.'] | train | https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L487-L517 |
8,040 | CamDavidsonPilon/lifelines | lifelines/fitters/__init__.py | ParametericUnivariateFitter.cumulative_density_at_times | def cumulative_density_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
--------
pd.Series
"""
label = coalesce(label, self._label)
return pd.Series(self._cumulative_density(self._fitted_parameters_, times), index=_to_array(times), name=label) | python | def cumulative_density_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
--------
pd.Series
"""
label = coalesce(label, self._label)
return pd.Series(self._cumulative_density(self._fitted_parameters_, times), index=_to_array(times), name=label) | ['def', 'cumulative_density_at_times', '(', 'self', ',', 'times', ',', 'label', '=', 'None', ')', ':', 'label', '=', 'coalesce', '(', 'label', ',', 'self', '.', '_label', ')', 'return', 'pd', '.', 'Series', '(', 'self', '.', '_cumulative_density', '(', 'self', '.', '_fitted_parameters_', ',', 'times', ')', ',', 'index', '=', '_to_array', '(', 'times', ')', ',', 'name', '=', 'label', ')'] | Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
--------
pd.Series | ['Return', 'a', 'Pandas', 'series', 'of', 'the', 'predicted', 'cumulative', 'density', 'function', '(', '1', '-', 'survival', 'function', ')', 'at', 'specific', 'times', '.'] | train | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/__init__.py#L946-L963 |
8,041 | mikedh/trimesh | trimesh/path/simplify.py | fit_circle_check | def fit_circle_check(points,
scale,
prior=None,
final=False,
verbose=False):
"""
Fit a circle, and reject the fit if:
* the radius is larger than tol.radius_min*scale or tol.radius_max*scale
* any segment spans more than tol.seg_angle
* any segment is longer than tol.seg_frac*scale
* the fit deviates by more than tol.radius_frac*radius
* the segments on the ends deviate from tangent by more than tol.tangent
Parameters
---------
points: (n, d) set of points which represent a path
prior: (center, radius) tuple for best guess, or None if unknown
scale: float, what is the overall scale of the set of points
verbose: boolean, if True output log.debug messages for the reasons
for fit rejection. Potentially generates hundreds of thousands of
messages so only suggested in manual debugging.
Returns
---------
if fit is acceptable:
(center, radius) tuple
else:
None
"""
# an arc needs at least three points
if len(points) < 3:
return None
# do a least squares fit on the points
C, R, r_deviation = fit_nsphere(points, prior=prior)
# check to make sure radius is between min and max allowed
if not tol.radius_min < (R / scale) < tol.radius_max:
if verbose:
log.debug('circle fit error: R %f', R / scale)
return None
# check point radius error
r_error = r_deviation / R
if r_error > tol.radius_frac:
if verbose:
log.debug('circle fit error: fit %s', str(r_error))
return None
vectors = np.diff(points, axis=0)
segment = np.linalg.norm(vectors, axis=1)
# approximate angle in radians, segments are linear length
# not arc length but this is close and avoids a cosine
angle = segment / R
if (angle > tol.seg_angle).any():
if verbose:
log.debug('circle fit error: angle %s', str(angle))
return None
if final and (angle > tol.seg_angle_min).sum() < 3:
log.debug('final: angle %s', str(angle))
return None
# check segment length as a fraction of drawing scale
scaled = segment / scale
if (scaled > tol.seg_frac).any():
if verbose:
log.debug('circle fit error: segment %s', str(scaled))
return None
# check to make sure the line segments on the ends are actually
# tangent with the candidate circle fit
mid_pt = points[[0, -2]] + (vectors[[0, -1]] * .5)
radial = unitize(mid_pt - C)
ends = unitize(vectors[[0, -1]])
tangent = np.abs(np.arccos(diagonal_dot(radial, ends)))
tangent = np.abs(tangent - np.pi / 2).max()
if tangent > tol.tangent:
if verbose:
log.debug('circle fit error: tangent %f',
np.degrees(tangent))
return None
result = {'center': C,
'radius': R}
return result | python | def fit_circle_check(points,
scale,
prior=None,
final=False,
verbose=False):
"""
Fit a circle, and reject the fit if:
* the radius is larger than tol.radius_min*scale or tol.radius_max*scale
* any segment spans more than tol.seg_angle
* any segment is longer than tol.seg_frac*scale
* the fit deviates by more than tol.radius_frac*radius
* the segments on the ends deviate from tangent by more than tol.tangent
Parameters
---------
points: (n, d) set of points which represent a path
prior: (center, radius) tuple for best guess, or None if unknown
scale: float, what is the overall scale of the set of points
verbose: boolean, if True output log.debug messages for the reasons
for fit rejection. Potentially generates hundreds of thousands of
messages so only suggested in manual debugging.
Returns
---------
if fit is acceptable:
(center, radius) tuple
else:
None
"""
# an arc needs at least three points
if len(points) < 3:
return None
# do a least squares fit on the points
C, R, r_deviation = fit_nsphere(points, prior=prior)
# check to make sure radius is between min and max allowed
if not tol.radius_min < (R / scale) < tol.radius_max:
if verbose:
log.debug('circle fit error: R %f', R / scale)
return None
# check point radius error
r_error = r_deviation / R
if r_error > tol.radius_frac:
if verbose:
log.debug('circle fit error: fit %s', str(r_error))
return None
vectors = np.diff(points, axis=0)
segment = np.linalg.norm(vectors, axis=1)
# approximate angle in radians, segments are linear length
# not arc length but this is close and avoids a cosine
angle = segment / R
if (angle > tol.seg_angle).any():
if verbose:
log.debug('circle fit error: angle %s', str(angle))
return None
if final and (angle > tol.seg_angle_min).sum() < 3:
log.debug('final: angle %s', str(angle))
return None
# check segment length as a fraction of drawing scale
scaled = segment / scale
if (scaled > tol.seg_frac).any():
if verbose:
log.debug('circle fit error: segment %s', str(scaled))
return None
# check to make sure the line segments on the ends are actually
# tangent with the candidate circle fit
mid_pt = points[[0, -2]] + (vectors[[0, -1]] * .5)
radial = unitize(mid_pt - C)
ends = unitize(vectors[[0, -1]])
tangent = np.abs(np.arccos(diagonal_dot(radial, ends)))
tangent = np.abs(tangent - np.pi / 2).max()
if tangent > tol.tangent:
if verbose:
log.debug('circle fit error: tangent %f',
np.degrees(tangent))
return None
result = {'center': C,
'radius': R}
return result | ['def', 'fit_circle_check', '(', 'points', ',', 'scale', ',', 'prior', '=', 'None', ',', 'final', '=', 'False', ',', 'verbose', '=', 'False', ')', ':', '# an arc needs at least three points', 'if', 'len', '(', 'points', ')', '<', '3', ':', 'return', 'None', '# do a least squares fit on the points', 'C', ',', 'R', ',', 'r_deviation', '=', 'fit_nsphere', '(', 'points', ',', 'prior', '=', 'prior', ')', '# check to make sure radius is between min and max allowed', 'if', 'not', 'tol', '.', 'radius_min', '<', '(', 'R', '/', 'scale', ')', '<', 'tol', '.', 'radius_max', ':', 'if', 'verbose', ':', 'log', '.', 'debug', '(', "'circle fit error: R %f'", ',', 'R', '/', 'scale', ')', 'return', 'None', '# check point radius error', 'r_error', '=', 'r_deviation', '/', 'R', 'if', 'r_error', '>', 'tol', '.', 'radius_frac', ':', 'if', 'verbose', ':', 'log', '.', 'debug', '(', "'circle fit error: fit %s'", ',', 'str', '(', 'r_error', ')', ')', 'return', 'None', 'vectors', '=', 'np', '.', 'diff', '(', 'points', ',', 'axis', '=', '0', ')', 'segment', '=', 'np', '.', 'linalg', '.', 'norm', '(', 'vectors', ',', 'axis', '=', '1', ')', '# approximate angle in radians, segments are linear length', '# not arc length but this is close and avoids a cosine', 'angle', '=', 'segment', '/', 'R', 'if', '(', 'angle', '>', 'tol', '.', 'seg_angle', ')', '.', 'any', '(', ')', ':', 'if', 'verbose', ':', 'log', '.', 'debug', '(', "'circle fit error: angle %s'", ',', 'str', '(', 'angle', ')', ')', 'return', 'None', 'if', 'final', 'and', '(', 'angle', '>', 'tol', '.', 'seg_angle_min', ')', '.', 'sum', '(', ')', '<', '3', ':', 'log', '.', 'debug', '(', "'final: angle %s'", ',', 'str', '(', 'angle', ')', ')', 'return', 'None', '# check segment length as a fraction of drawing scale', 'scaled', '=', 'segment', '/', 'scale', 'if', '(', 'scaled', '>', 'tol', '.', 'seg_frac', ')', '.', 'any', '(', ')', ':', 'if', 'verbose', ':', 'log', '.', 'debug', '(', "'circle fit error: segment %s'", ',', 'str', '(', 'scaled', ')', ')', 'return', 'None', '# check to make sure the line segments on the ends are actually', '# tangent with the candidate circle fit', 'mid_pt', '=', 'points', '[', '[', '0', ',', '-', '2', ']', ']', '+', '(', 'vectors', '[', '[', '0', ',', '-', '1', ']', ']', '*', '.5', ')', 'radial', '=', 'unitize', '(', 'mid_pt', '-', 'C', ')', 'ends', '=', 'unitize', '(', 'vectors', '[', '[', '0', ',', '-', '1', ']', ']', ')', 'tangent', '=', 'np', '.', 'abs', '(', 'np', '.', 'arccos', '(', 'diagonal_dot', '(', 'radial', ',', 'ends', ')', ')', ')', 'tangent', '=', 'np', '.', 'abs', '(', 'tangent', '-', 'np', '.', 'pi', '/', '2', ')', '.', 'max', '(', ')', 'if', 'tangent', '>', 'tol', '.', 'tangent', ':', 'if', 'verbose', ':', 'log', '.', 'debug', '(', "'circle fit error: tangent %f'", ',', 'np', '.', 'degrees', '(', 'tangent', ')', ')', 'return', 'None', 'result', '=', '{', "'center'", ':', 'C', ',', "'radius'", ':', 'R', '}', 'return', 'result'] | Fit a circle, and reject the fit if:
* the radius is larger than tol.radius_min*scale or tol.radius_max*scale
* any segment spans more than tol.seg_angle
* any segment is longer than tol.seg_frac*scale
* the fit deviates by more than tol.radius_frac*radius
* the segments on the ends deviate from tangent by more than tol.tangent
Parameters
---------
points: (n, d) set of points which represent a path
prior: (center, radius) tuple for best guess, or None if unknown
scale: float, what is the overall scale of the set of points
verbose: boolean, if True output log.debug messages for the reasons
for fit rejection. Potentially generates hundreds of thousands of
messages so only suggested in manual debugging.
Returns
---------
if fit is acceptable:
(center, radius) tuple
else:
None | ['Fit', 'a', 'circle', 'and', 'reject', 'the', 'fit', 'if', ':', '*', 'the', 'radius', 'is', 'larger', 'than', 'tol', '.', 'radius_min', '*', 'scale', 'or', 'tol', '.', 'radius_max', '*', 'scale', '*', 'any', 'segment', 'spans', 'more', 'than', 'tol', '.', 'seg_angle', '*', 'any', 'segment', 'is', 'longer', 'than', 'tol', '.', 'seg_frac', '*', 'scale', '*', 'the', 'fit', 'deviates', 'by', 'more', 'than', 'tol', '.', 'radius_frac', '*', 'radius', '*', 'the', 'segments', 'on', 'the', 'ends', 'deviate', 'from', 'tangent', 'by', 'more', 'than', 'tol', '.', 'tangent'] | train | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/simplify.py#L15-L104 |
8,042 | materialsproject/pymatgen | pymatgen/analysis/ferroelectricity/polarization.py | Polarization.get_lattice_quanta | def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Returns the dipole / polarization quanta along a, b, and c for
all structures.
"""
lattices = [s.lattice for s in self.structures]
volumes = np.array([s.lattice.volume for s in self.structures])
L = len(self.structures)
e_to_muC = -1.6021766e-13
cm2_to_A2 = 1e16
units = 1.0 / np.array(volumes)
units *= e_to_muC * cm2_to_A2
# convert polarizations and lattice lengths prior to adjustment
if convert_to_muC_per_cm2 and not all_in_polar:
# adjust lattices
for i in range(L):
lattice = lattices[i]
l, a = lattice.lengths_and_angles
lattices[i] = Lattice.from_lengths_and_angles(
np.array(l) * units.ravel()[i], a)
elif convert_to_muC_per_cm2 and all_in_polar:
for i in range(L):
lattice = lattices[-1]
l, a = lattice.lengths_and_angles
lattices[i] = Lattice.from_lengths_and_angles(
np.array(l) * units.ravel()[-1], a)
quanta = np.array(
[np.array(l.lengths_and_angles[0]) for l in lattices])
return quanta | python | def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Returns the dipole / polarization quanta along a, b, and c for
all structures.
"""
lattices = [s.lattice for s in self.structures]
volumes = np.array([s.lattice.volume for s in self.structures])
L = len(self.structures)
e_to_muC = -1.6021766e-13
cm2_to_A2 = 1e16
units = 1.0 / np.array(volumes)
units *= e_to_muC * cm2_to_A2
# convert polarizations and lattice lengths prior to adjustment
if convert_to_muC_per_cm2 and not all_in_polar:
# adjust lattices
for i in range(L):
lattice = lattices[i]
l, a = lattice.lengths_and_angles
lattices[i] = Lattice.from_lengths_and_angles(
np.array(l) * units.ravel()[i], a)
elif convert_to_muC_per_cm2 and all_in_polar:
for i in range(L):
lattice = lattices[-1]
l, a = lattice.lengths_and_angles
lattices[i] = Lattice.from_lengths_and_angles(
np.array(l) * units.ravel()[-1], a)
quanta = np.array(
[np.array(l.lengths_and_angles[0]) for l in lattices])
return quanta | ['def', 'get_lattice_quanta', '(', 'self', ',', 'convert_to_muC_per_cm2', '=', 'True', ',', 'all_in_polar', '=', 'True', ')', ':', 'lattices', '=', '[', 's', '.', 'lattice', 'for', 's', 'in', 'self', '.', 'structures', ']', 'volumes', '=', 'np', '.', 'array', '(', '[', 's', '.', 'lattice', '.', 'volume', 'for', 's', 'in', 'self', '.', 'structures', ']', ')', 'L', '=', 'len', '(', 'self', '.', 'structures', ')', 'e_to_muC', '=', '-', '1.6021766e-13', 'cm2_to_A2', '=', '1e16', 'units', '=', '1.0', '/', 'np', '.', 'array', '(', 'volumes', ')', 'units', '*=', 'e_to_muC', '*', 'cm2_to_A2', '# convert polarizations and lattice lengths prior to adjustment', 'if', 'convert_to_muC_per_cm2', 'and', 'not', 'all_in_polar', ':', '# adjust lattices', 'for', 'i', 'in', 'range', '(', 'L', ')', ':', 'lattice', '=', 'lattices', '[', 'i', ']', 'l', ',', 'a', '=', 'lattice', '.', 'lengths_and_angles', 'lattices', '[', 'i', ']', '=', 'Lattice', '.', 'from_lengths_and_angles', '(', 'np', '.', 'array', '(', 'l', ')', '*', 'units', '.', 'ravel', '(', ')', '[', 'i', ']', ',', 'a', ')', 'elif', 'convert_to_muC_per_cm2', 'and', 'all_in_polar', ':', 'for', 'i', 'in', 'range', '(', 'L', ')', ':', 'lattice', '=', 'lattices', '[', '-', '1', ']', 'l', ',', 'a', '=', 'lattice', '.', 'lengths_and_angles', 'lattices', '[', 'i', ']', '=', 'Lattice', '.', 'from_lengths_and_angles', '(', 'np', '.', 'array', '(', 'l', ')', '*', 'units', '.', 'ravel', '(', ')', '[', '-', '1', ']', ',', 'a', ')', 'quanta', '=', 'np', '.', 'array', '(', '[', 'np', '.', 'array', '(', 'l', '.', 'lengths_and_angles', '[', '0', ']', ')', 'for', 'l', 'in', 'lattices', ']', ')', 'return', 'quanta'] | Returns the dipole / polarization quanta along a, b, and c for
all structures. | ['Returns', 'the', 'dipole', '/', 'polarization', 'quanta', 'along', 'a', 'b', 'and', 'c', 'for', 'all', 'structures', '.'] | train | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/ferroelectricity/polarization.py#L330-L363 |
8,043 | mardix/Yass | yass/cli.py | init | def init():
"""Initialize Yass in the current directory """
yass_conf = os.path.join(CWD, "yass.yml")
if os.path.isfile(yass_conf):
print("::ALERT::")
print("It seems like Yass is already initialized here.")
print("If it's a mistake, delete 'yass.yml' in this directory")
else:
print("Init Yass in %s ..." % CWD)
copy_resource("skel/", CWD)
stamp_yass_current_version(CWD)
print("Yass init successfully!")
print("Run 'yass serve' to view the site")
footer() | python | def init():
"""Initialize Yass in the current directory """
yass_conf = os.path.join(CWD, "yass.yml")
if os.path.isfile(yass_conf):
print("::ALERT::")
print("It seems like Yass is already initialized here.")
print("If it's a mistake, delete 'yass.yml' in this directory")
else:
print("Init Yass in %s ..." % CWD)
copy_resource("skel/", CWD)
stamp_yass_current_version(CWD)
print("Yass init successfully!")
print("Run 'yass serve' to view the site")
footer() | ['def', 'init', '(', ')', ':', 'yass_conf', '=', 'os', '.', 'path', '.', 'join', '(', 'CWD', ',', '"yass.yml"', ')', 'if', 'os', '.', 'path', '.', 'isfile', '(', 'yass_conf', ')', ':', 'print', '(', '"::ALERT::"', ')', 'print', '(', '"It seems like Yass is already initialized here."', ')', 'print', '(', '"If it\'s a mistake, delete \'yass.yml\' in this directory"', ')', 'else', ':', 'print', '(', '"Init Yass in %s ..."', '%', 'CWD', ')', 'copy_resource', '(', '"skel/"', ',', 'CWD', ')', 'stamp_yass_current_version', '(', 'CWD', ')', 'print', '(', '"Yass init successfully!"', ')', 'print', '(', '"Run \'yass serve\' to view the site"', ')', 'footer', '(', ')'] | Initialize Yass in the current directory | ['Initialize', 'Yass', 'in', 'the', 'current', 'directory'] | train | https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/cli.py#L244-L258 |
8,044 | boriel/zxbasic | arch/zx48k/backend/__pload.py | _ploadf | def _ploadf(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
"""
output = _pload(ins.quad[2], 5)
output.extend(_fpush())
return output | python | def _ploadf(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
"""
output = _pload(ins.quad[2], 5)
output.extend(_fpush())
return output | ['def', '_ploadf', '(', 'ins', ')', ':', 'output', '=', '_pload', '(', 'ins', '.', 'quad', '[', '2', ']', ',', '5', ')', 'output', '.', 'extend', '(', '_fpush', '(', ')', ')', 'return', 'output'] | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer. | ['Loads', 'from', 'stack', 'pointer', '(', 'SP', ')', '+', 'X', 'being', 'X', '2st', 'parameter', '.'] | train | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L161-L169 |
8,045 | Dallinger/Dallinger | dallinger/experiment_server/experiment_server.py | info_post | def info_post(node_id):
"""Create an info.
The node id must be specified in the url.
You must pass contents as an argument.
info_type is an additional optional argument.
If info_type is a custom subclass of Info it must be
added to the known_classes of the experiment class.
"""
# get the parameters and validate them
contents = request_parameter(parameter="contents")
info_type = request_parameter(
parameter="info_type", parameter_type="known_class", default=models.Info
)
for x in [contents, info_type]:
if type(x) == Response:
return x
# check the node exists
node = models.Node.query.get(node_id)
if node is None:
return error_response(error_type="/info POST, node does not exist")
exp = Experiment(session)
try:
# execute the request
info = info_type(origin=node, contents=contents)
assign_properties(info)
# ping the experiment
exp.info_post_request(node=node, info=info)
session.commit()
except Exception:
return error_response(
error_type="/info POST server error",
status=403,
participant=node.participant,
)
# return the data
return success_response(info=info.__json__()) | python | def info_post(node_id):
"""Create an info.
The node id must be specified in the url.
You must pass contents as an argument.
info_type is an additional optional argument.
If info_type is a custom subclass of Info it must be
added to the known_classes of the experiment class.
"""
# get the parameters and validate them
contents = request_parameter(parameter="contents")
info_type = request_parameter(
parameter="info_type", parameter_type="known_class", default=models.Info
)
for x in [contents, info_type]:
if type(x) == Response:
return x
# check the node exists
node = models.Node.query.get(node_id)
if node is None:
return error_response(error_type="/info POST, node does not exist")
exp = Experiment(session)
try:
# execute the request
info = info_type(origin=node, contents=contents)
assign_properties(info)
# ping the experiment
exp.info_post_request(node=node, info=info)
session.commit()
except Exception:
return error_response(
error_type="/info POST server error",
status=403,
participant=node.participant,
)
# return the data
return success_response(info=info.__json__()) | ['def', 'info_post', '(', 'node_id', ')', ':', '# get the parameters and validate them', 'contents', '=', 'request_parameter', '(', 'parameter', '=', '"contents"', ')', 'info_type', '=', 'request_parameter', '(', 'parameter', '=', '"info_type"', ',', 'parameter_type', '=', '"known_class"', ',', 'default', '=', 'models', '.', 'Info', ')', 'for', 'x', 'in', '[', 'contents', ',', 'info_type', ']', ':', 'if', 'type', '(', 'x', ')', '==', 'Response', ':', 'return', 'x', '# check the node exists', 'node', '=', 'models', '.', 'Node', '.', 'query', '.', 'get', '(', 'node_id', ')', 'if', 'node', 'is', 'None', ':', 'return', 'error_response', '(', 'error_type', '=', '"/info POST, node does not exist"', ')', 'exp', '=', 'Experiment', '(', 'session', ')', 'try', ':', '# execute the request', 'info', '=', 'info_type', '(', 'origin', '=', 'node', ',', 'contents', '=', 'contents', ')', 'assign_properties', '(', 'info', ')', '# ping the experiment', 'exp', '.', 'info_post_request', '(', 'node', '=', 'node', ',', 'info', '=', 'info', ')', 'session', '.', 'commit', '(', ')', 'except', 'Exception', ':', 'return', 'error_response', '(', 'error_type', '=', '"/info POST server error"', ',', 'status', '=', '403', ',', 'participant', '=', 'node', '.', 'participant', ',', ')', '# return the data', 'return', 'success_response', '(', 'info', '=', 'info', '.', '__json__', '(', ')', ')'] | Create an info.
The node id must be specified in the url.
You must pass contents as an argument.
info_type is an additional optional argument.
If info_type is a custom subclass of Info it must be
added to the known_classes of the experiment class. | ['Create', 'an', 'info', '.'] | train | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1341-L1382 |
8,046 | SpockBotMC/SpockBot | spockbot/plugins/tools/smpmap.py | Dimension.get_block_entity_data | def get_block_entity_data(self, pos_or_x, y=None, z=None):
"""
Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location.
"""
if None not in (y, z): # x y z supplied
pos_or_x = pos_or_x, y, z
coord_tuple = tuple(int(floor(c)) for c in pos_or_x)
return self.block_entities.get(coord_tuple, None) | python | def get_block_entity_data(self, pos_or_x, y=None, z=None):
"""
Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location.
"""
if None not in (y, z): # x y z supplied
pos_or_x = pos_or_x, y, z
coord_tuple = tuple(int(floor(c)) for c in pos_or_x)
return self.block_entities.get(coord_tuple, None) | ['def', 'get_block_entity_data', '(', 'self', ',', 'pos_or_x', ',', 'y', '=', 'None', ',', 'z', '=', 'None', ')', ':', 'if', 'None', 'not', 'in', '(', 'y', ',', 'z', ')', ':', '# x y z supplied', 'pos_or_x', '=', 'pos_or_x', ',', 'y', ',', 'z', 'coord_tuple', '=', 'tuple', '(', 'int', '(', 'floor', '(', 'c', ')', ')', 'for', 'c', 'in', 'pos_or_x', ')', 'return', 'self', '.', 'block_entities', '.', 'get', '(', 'coord_tuple', ',', 'None', ')'] | Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location. | ['Access', 'block', 'entity', 'data', '.'] | train | https://github.com/SpockBotMC/SpockBot/blob/f89911551f18357720034fbaa52837a0d09f66ea/spockbot/plugins/tools/smpmap.py#L302-L313 |
8,047 | sdispater/orator | orator/orm/builder.py | Builder.has | def has(self, relation, operator=">=", count=1, boolean="and", extra=None):
"""
Add a relationship count condition to the query.
:param relation: The relation to count
:type relation: str
:param operator: The operator
:type operator: str
:param count: The count
:type count: int
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type extra: Builder or callable
:type: Builder
"""
if relation.find(".") >= 0:
return self._has_nested(relation, operator, count, boolean, extra)
relation = self._get_has_relation_query(relation)
query = relation.get_relation_count_query(
relation.get_related().new_query(), self
)
# TODO: extra query
if extra:
if callable(extra):
extra(query)
return self._add_has_where(
query.apply_scopes(), relation, operator, count, boolean
) | python | def has(self, relation, operator=">=", count=1, boolean="and", extra=None):
"""
Add a relationship count condition to the query.
:param relation: The relation to count
:type relation: str
:param operator: The operator
:type operator: str
:param count: The count
:type count: int
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type extra: Builder or callable
:type: Builder
"""
if relation.find(".") >= 0:
return self._has_nested(relation, operator, count, boolean, extra)
relation = self._get_has_relation_query(relation)
query = relation.get_relation_count_query(
relation.get_related().new_query(), self
)
# TODO: extra query
if extra:
if callable(extra):
extra(query)
return self._add_has_where(
query.apply_scopes(), relation, operator, count, boolean
) | ['def', 'has', '(', 'self', ',', 'relation', ',', 'operator', '=', '">="', ',', 'count', '=', '1', ',', 'boolean', '=', '"and"', ',', 'extra', '=', 'None', ')', ':', 'if', 'relation', '.', 'find', '(', '"."', ')', '>=', '0', ':', 'return', 'self', '.', '_has_nested', '(', 'relation', ',', 'operator', ',', 'count', ',', 'boolean', ',', 'extra', ')', 'relation', '=', 'self', '.', '_get_has_relation_query', '(', 'relation', ')', 'query', '=', 'relation', '.', 'get_relation_count_query', '(', 'relation', '.', 'get_related', '(', ')', '.', 'new_query', '(', ')', ',', 'self', ')', '# TODO: extra query', 'if', 'extra', ':', 'if', 'callable', '(', 'extra', ')', ':', 'extra', '(', 'query', ')', 'return', 'self', '.', '_add_has_where', '(', 'query', '.', 'apply_scopes', '(', ')', ',', 'relation', ',', 'operator', ',', 'count', ',', 'boolean', ')'] | Add a relationship count condition to the query.
:param relation: The relation to count
:type relation: str
:param operator: The operator
:type operator: str
:param count: The count
:type count: int
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type extra: Builder or callable
:type: Builder | ['Add', 'a', 'relationship', 'count', 'condition', 'to', 'the', 'query', '.'] | train | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/builder.py#L646-L683 |
8,048 | aws/aws-xray-sdk-python | aws_xray_sdk/core/plugins/utils.py | get_plugin_modules | def get_plugin_modules(plugins):
"""
Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str
"""
if not plugins:
raise MissingPluginNames("input plugin names are required")
modules = []
for plugin in plugins:
short_name = PLUGIN_MAPPING.get(plugin.lower(), plugin.lower())
full_path = '%s%s' % (module_prefix, short_name)
modules.append(importlib.import_module(full_path))
return tuple(modules) | python | def get_plugin_modules(plugins):
"""
Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str
"""
if not plugins:
raise MissingPluginNames("input plugin names are required")
modules = []
for plugin in plugins:
short_name = PLUGIN_MAPPING.get(plugin.lower(), plugin.lower())
full_path = '%s%s' % (module_prefix, short_name)
modules.append(importlib.import_module(full_path))
return tuple(modules) | ['def', 'get_plugin_modules', '(', 'plugins', ')', ':', 'if', 'not', 'plugins', ':', 'raise', 'MissingPluginNames', '(', '"input plugin names are required"', ')', 'modules', '=', '[', ']', 'for', 'plugin', 'in', 'plugins', ':', 'short_name', '=', 'PLUGIN_MAPPING', '.', 'get', '(', 'plugin', '.', 'lower', '(', ')', ',', 'plugin', '.', 'lower', '(', ')', ')', 'full_path', '=', "'%s%s'", '%', '(', 'module_prefix', ',', 'short_name', ')', 'modules', '.', 'append', '(', 'importlib', '.', 'import_module', '(', 'full_path', ')', ')', 'return', 'tuple', '(', 'modules', ')'] | Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str | ['Get', 'plugin', 'modules', 'from', 'input', 'strings', ':', 'param', 'tuple', 'plugins', ':', 'a', 'tuple', 'of', 'plugin', 'names', 'in', 'str'] | train | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/plugins/utils.py#L13-L28 |
8,049 | saulpw/visidata | visidata/canvas.py | clipline | def clipline(x1, y1, x2, y2, xmin, ymin, xmax, ymax):
'Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None'
dx = x2-x1
dy = y2-y1
pq = [
(-dx, x1-xmin), # left
( dx, xmax-x1), # right
(-dy, y1-ymin), # bottom
( dy, ymax-y1), # top
]
u1, u2 = 0, 1
for p, q in pq:
if p < 0: # from outside to inside
u1 = max(u1, q/p)
elif p > 0: # from inside to outside
u2 = min(u2, q/p)
else: # p == 0: # parallel to bbox
if q < 0: # completely outside bbox
return None
if u1 > u2: # completely outside bbox
return None
xn1 = x1 + dx*u1
yn1 = y1 + dy*u1
xn2 = x1 + dx*u2
yn2 = y1 + dy*u2
return xn1, yn1, xn2, yn2 | python | def clipline(x1, y1, x2, y2, xmin, ymin, xmax, ymax):
'Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None'
dx = x2-x1
dy = y2-y1
pq = [
(-dx, x1-xmin), # left
( dx, xmax-x1), # right
(-dy, y1-ymin), # bottom
( dy, ymax-y1), # top
]
u1, u2 = 0, 1
for p, q in pq:
if p < 0: # from outside to inside
u1 = max(u1, q/p)
elif p > 0: # from inside to outside
u2 = min(u2, q/p)
else: # p == 0: # parallel to bbox
if q < 0: # completely outside bbox
return None
if u1 > u2: # completely outside bbox
return None
xn1 = x1 + dx*u1
yn1 = y1 + dy*u1
xn2 = x1 + dx*u2
yn2 = y1 + dy*u2
return xn1, yn1, xn2, yn2 | ['def', 'clipline', '(', 'x1', ',', 'y1', ',', 'x2', ',', 'y2', ',', 'xmin', ',', 'ymin', ',', 'xmax', ',', 'ymax', ')', ':', 'dx', '=', 'x2', '-', 'x1', 'dy', '=', 'y2', '-', 'y1', 'pq', '=', '[', '(', '-', 'dx', ',', 'x1', '-', 'xmin', ')', ',', '# left', '(', 'dx', ',', 'xmax', '-', 'x1', ')', ',', '# right', '(', '-', 'dy', ',', 'y1', '-', 'ymin', ')', ',', '# bottom', '(', 'dy', ',', 'ymax', '-', 'y1', ')', ',', '# top', ']', 'u1', ',', 'u2', '=', '0', ',', '1', 'for', 'p', ',', 'q', 'in', 'pq', ':', 'if', 'p', '<', '0', ':', '# from outside to inside', 'u1', '=', 'max', '(', 'u1', ',', 'q', '/', 'p', ')', 'elif', 'p', '>', '0', ':', '# from inside to outside', 'u2', '=', 'min', '(', 'u2', ',', 'q', '/', 'p', ')', 'else', ':', '# p == 0: # parallel to bbox', 'if', 'q', '<', '0', ':', '# completely outside bbox', 'return', 'None', 'if', 'u1', '>', 'u2', ':', '# completely outside bbox', 'return', 'None', 'xn1', '=', 'x1', '+', 'dx', '*', 'u1', 'yn1', '=', 'y1', '+', 'dy', '*', 'u1', 'xn2', '=', 'x1', '+', 'dx', '*', 'u2', 'yn2', '=', 'y1', '+', 'dy', '*', 'u2', 'return', 'xn1', ',', 'yn1', ',', 'xn2', ',', 'yn2'] | Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None | ['Liang', '-', 'Barsky', 'algorithm', 'returns', '[', 'xn1', 'yn1', 'xn2', 'yn2', ']', 'of', 'clipped', 'line', 'within', 'given', 'area', 'or', 'None'] | train | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L74-L104 |
8,050 | ionelmc/python-cogen | cogen/web/wsgi.py | WSGIConnection.run | def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
self.sent_headers = False
self.chunked_write = False
self.write_buffer = StringIO.StringIO()
self.content_length = None
# Copy the class environ into self.
ENVIRON = self.environ = self.connection_environ.copy()
self.environ.update(self.server_environ)
request_line = yield self.connfh.readline()
if request_line == "\r\n":
# RFC 2616 sec 4.1: "... it should ignore the CRLF."
tolerance = 5
while tolerance and request_line == "\r\n":
request_line = yield self.connfh.readline()
tolerance -= 1
if not tolerance:
return
method, path, req_protocol = request_line.strip().split(" ", 2)
ENVIRON["REQUEST_METHOD"] = method
ENVIRON["CONTENT_LENGTH"] = ''
scheme, location, path, params, qs, frag = urlparse(path)
if frag:
yield self.simple_response("400 Bad Request",
"Illegal #fragment in Request-URI.")
return
if scheme:
ENVIRON["wsgi.url_scheme"] = scheme
if params:
path = path + ";" + params
ENVIRON["SCRIPT_NAME"] = ""
# Unquote the path+params (e.g. "/this%20path" -> "this path").
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
#
# But note that "...a URI must be separated into its components
# before the escaped characters within those components can be
# safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2
atoms = [unquote(x) for x in quoted_slash.split(path)]
path = "%2F".join(atoms)
ENVIRON["PATH_INFO"] = path
# Note that, like wsgiref and most other WSGI servers,
# we unquote the path but not the query string.
ENVIRON["QUERY_STRING"] = qs
# Compare request and server HTTP protocol versions, in case our
# server does not support the requested protocol. Limit our output
# to min(req, server). We want the following output:
# request server actual written supported response
# protocol protocol response protocol feature set
# a 1.0 1.0 1.0 1.0
# b 1.0 1.1 1.1 1.0
# c 1.1 1.0 1.0 1.0
# d 1.1 1.1 1.1 1.1
# Notice that, in (b), the response will be "HTTP/1.1" even though
# the client only understands 1.0. RFC 2616 10.5.6 says we should
# only return 505 if the _major_ version is different.
rp = int(req_protocol[5]), int(req_protocol[7])
server_protocol = ENVIRON["ACTUAL_SERVER_PROTOCOL"]
sp = int(server_protocol[5]), int(server_protocol[7])
if sp[0] != rp[0]:
yield self.simple_response("505 HTTP Version Not Supported")
return
# Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
ENVIRON["SERVER_PROTOCOL"] = req_protocol
self.response_protocol = "HTTP/%s.%s" % min(rp, sp)
# If the Request-URI was an absoluteURI, use its location atom.
if location:
ENVIRON["SERVER_NAME"] = location
# then all the http headers
try:
while True:
line = yield self.connfh.readline()
if line == '\r\n':
# Normal end of headers
break
if line[0] in ' \t':
# It's a continuation line.
v = line.strip()
else:
k, v = line.split(":", 1)
k, v = k.strip().upper(), v.strip()
envname = "HTTP_" + k.replace("-", "_")
if k in comma_separated_headers:
existing = ENVIRON.get(envname)
if existing:
v = ", ".join((existing, v))
ENVIRON[envname] = v
ct = ENVIRON.pop("HTTP_CONTENT_TYPE", None)
if ct:
ENVIRON["CONTENT_TYPE"] = ct
cl = ENVIRON.pop("HTTP_CONTENT_LENGTH", None)
if cl:
ENVIRON["CONTENT_LENGTH"] = cl
except ValueError, ex:
yield self.simple_response("400 Bad Request", repr(ex.args))
return
creds = ENVIRON.get("HTTP_AUTHORIZATION", "").split(" ", 1)
ENVIRON["AUTH_TYPE"] = creds[0]
if creds[0].lower() == 'basic':
user, pw = base64.decodestring(creds[1]).split(":", 1)
ENVIRON["REMOTE_USER"] = user
# Persistent connection support
if req_protocol == "HTTP/1.1":
if ENVIRON.get("HTTP_CONNECTION", "") == "close":
self.close_connection = True
else:
# HTTP/1.0
if ENVIRON.get("HTTP_CONNECTION", "").lower() != "keep-alive":
self.close_connection = True
# Transfer-Encoding support
te = None
if self.response_protocol == "HTTP/1.1":
te = ENVIRON.get("HTTP_TRANSFER_ENCODING")
if te:
te = [x.strip().lower() for x in te.split(",") if x.strip()]
if te:
# reject transfer encodings for now
yield self.simple_response("501 Unimplemented")
self.close_connection = True
return
ENV_COGEN_PROXY = ENVIRON['cogen.wsgi'] = async.COGENProxy(
content_length = int(ENVIRON.get('CONTENT_LENGTH', None) or 0) or None,
read_count = 0,
operation = None,
result = None,
exception = None
)
ENVIRON['cogen.http_connection'] = self
ENVIRON['cogen.core'] = async.COGENOperationWrapper(
ENV_COGEN_PROXY,
core
)
ENVIRON['cogen.call'] = async.COGENCallWrapper(ENV_COGEN_PROXY)
ENVIRON['cogen.input'] = async.COGENOperationWrapper(
ENV_COGEN_PROXY,
self.connfh
)
ENVIRON['cogen.yield'] = async.COGENSimpleWrapper(ENV_COGEN_PROXY)
response = self.wsgi_app(ENVIRON, self.start_response)
#~ print 'WSGI RESPONSE:', response
try:
if isinstance(response, WSGIFileWrapper):
# set tcp_cork to pack the header with the file data
if hasattr(socket, "TCP_CORK"):
self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
assert self.started_response, "App returned the wsgi.file_wrapper but didn't call start_response."
assert not self.sent_headers
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue()
)
offset = response.filelike.tell()
if self.chunked_write:
fsize = os.fstat(response.filelike.fileno()).st_size
yield sockets.SendAll(self.conn, hex(int(fsize-offset))+"\r\n")
yield self.conn.sendfile(
response.filelike,
blocksize=response.blocksize,
offset=offset,
length=self.content_length,
timeout=self.sendfile_timeout
)
if self.chunked_write:
yield sockets.SendAll(self.conn, "\r\n")
# also, tcp_cork will make the file data sent on packet boundaries,
# wich is a good thing
if hasattr(socket, "TCP_CORK"):
self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0)
else:
for chunk in response:
if chunk:
assert self.started_response, "App sended a value but hasn't called start_response."
if not self.sent_headers:
self.sent_headers = True
headers = [self.render_headers(), self.write_buffer.getvalue()]
else:
headers = []
if self.chunked_write:
buf = [hex(len(chunk))[2:], "\r\n", chunk, "\r\n"]
if headers:
headers.extend(buf)
yield sockets.SendAll(self.conn, "".join(headers))
else:
yield sockets.SendAll(self.conn, "".join(buf))
else:
if headers:
headers.append(chunk)
yield sockets.SendAll(self.conn, "".join(headers))
else:
yield sockets.SendAll(self.conn, chunk)
else:
if self.started_response:
if not self.sent_headers:
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue())
if ENV_COGEN_PROXY.operation:
op = ENV_COGEN_PROXY.operation
ENV_COGEN_PROXY.operation = None
try:
#~ print 'WSGI OP:', op
ENV_COGEN_PROXY.exception = None
ENV_COGEN_PROXY.result = yield op
#~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result
except:
#~ print 'WSGI OP EXCEPTION:', sys.exc_info()
ENV_COGEN_PROXY.exception = sys.exc_info()
ENV_COGEN_PROXY.result = ENV_COGEN_PROXY.exception[1]
del op
finally:
if hasattr(response, 'close'):
response.close()
if self.started_response:
if not self.sent_headers:
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue()
)
else:
import warnings
warnings.warn("App was consumed and hasn't called start_response")
if self.chunked_write:
yield sockets.SendAll(self.conn, "0\r\n\r\n")
if self.close_connection:
return
# TODO: consume any unread data
except (socket.error, OSError, pywinerror), e:
errno = e.args[0]
if errno not in useless_socket_errors:
yield self.simple_response("500 Internal Server Error",
format_exc())
return
except (OperationTimeout, ConnectionClosed, SocketError):
return
except (KeyboardInterrupt, SystemExit, GeneratorExit, MemoryError):
raise
except:
if not self.started_response:
yield self.simple_response(
"500 Internal Server Error",
format_exc()
)
else:
print "*" * 60
traceback.print_exc()
print "*" * 60
sys.exc_clear()
finally:
self.conn.close()
ENVIRON = self.environ = None | python | def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
self.sent_headers = False
self.chunked_write = False
self.write_buffer = StringIO.StringIO()
self.content_length = None
# Copy the class environ into self.
ENVIRON = self.environ = self.connection_environ.copy()
self.environ.update(self.server_environ)
request_line = yield self.connfh.readline()
if request_line == "\r\n":
# RFC 2616 sec 4.1: "... it should ignore the CRLF."
tolerance = 5
while tolerance and request_line == "\r\n":
request_line = yield self.connfh.readline()
tolerance -= 1
if not tolerance:
return
method, path, req_protocol = request_line.strip().split(" ", 2)
ENVIRON["REQUEST_METHOD"] = method
ENVIRON["CONTENT_LENGTH"] = ''
scheme, location, path, params, qs, frag = urlparse(path)
if frag:
yield self.simple_response("400 Bad Request",
"Illegal #fragment in Request-URI.")
return
if scheme:
ENVIRON["wsgi.url_scheme"] = scheme
if params:
path = path + ";" + params
ENVIRON["SCRIPT_NAME"] = ""
# Unquote the path+params (e.g. "/this%20path" -> "this path").
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
#
# But note that "...a URI must be separated into its components
# before the escaped characters within those components can be
# safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2
atoms = [unquote(x) for x in quoted_slash.split(path)]
path = "%2F".join(atoms)
ENVIRON["PATH_INFO"] = path
# Note that, like wsgiref and most other WSGI servers,
# we unquote the path but not the query string.
ENVIRON["QUERY_STRING"] = qs
# Compare request and server HTTP protocol versions, in case our
# server does not support the requested protocol. Limit our output
# to min(req, server). We want the following output:
# request server actual written supported response
# protocol protocol response protocol feature set
# a 1.0 1.0 1.0 1.0
# b 1.0 1.1 1.1 1.0
# c 1.1 1.0 1.0 1.0
# d 1.1 1.1 1.1 1.1
# Notice that, in (b), the response will be "HTTP/1.1" even though
# the client only understands 1.0. RFC 2616 10.5.6 says we should
# only return 505 if the _major_ version is different.
rp = int(req_protocol[5]), int(req_protocol[7])
server_protocol = ENVIRON["ACTUAL_SERVER_PROTOCOL"]
sp = int(server_protocol[5]), int(server_protocol[7])
if sp[0] != rp[0]:
yield self.simple_response("505 HTTP Version Not Supported")
return
# Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
ENVIRON["SERVER_PROTOCOL"] = req_protocol
self.response_protocol = "HTTP/%s.%s" % min(rp, sp)
# If the Request-URI was an absoluteURI, use its location atom.
if location:
ENVIRON["SERVER_NAME"] = location
# then all the http headers
try:
while True:
line = yield self.connfh.readline()
if line == '\r\n':
# Normal end of headers
break
if line[0] in ' \t':
# It's a continuation line.
v = line.strip()
else:
k, v = line.split(":", 1)
k, v = k.strip().upper(), v.strip()
envname = "HTTP_" + k.replace("-", "_")
if k in comma_separated_headers:
existing = ENVIRON.get(envname)
if existing:
v = ", ".join((existing, v))
ENVIRON[envname] = v
ct = ENVIRON.pop("HTTP_CONTENT_TYPE", None)
if ct:
ENVIRON["CONTENT_TYPE"] = ct
cl = ENVIRON.pop("HTTP_CONTENT_LENGTH", None)
if cl:
ENVIRON["CONTENT_LENGTH"] = cl
except ValueError, ex:
yield self.simple_response("400 Bad Request", repr(ex.args))
return
creds = ENVIRON.get("HTTP_AUTHORIZATION", "").split(" ", 1)
ENVIRON["AUTH_TYPE"] = creds[0]
if creds[0].lower() == 'basic':
user, pw = base64.decodestring(creds[1]).split(":", 1)
ENVIRON["REMOTE_USER"] = user
# Persistent connection support
if req_protocol == "HTTP/1.1":
if ENVIRON.get("HTTP_CONNECTION", "") == "close":
self.close_connection = True
else:
# HTTP/1.0
if ENVIRON.get("HTTP_CONNECTION", "").lower() != "keep-alive":
self.close_connection = True
# Transfer-Encoding support
te = None
if self.response_protocol == "HTTP/1.1":
te = ENVIRON.get("HTTP_TRANSFER_ENCODING")
if te:
te = [x.strip().lower() for x in te.split(",") if x.strip()]
if te:
# reject transfer encodings for now
yield self.simple_response("501 Unimplemented")
self.close_connection = True
return
ENV_COGEN_PROXY = ENVIRON['cogen.wsgi'] = async.COGENProxy(
content_length = int(ENVIRON.get('CONTENT_LENGTH', None) or 0) or None,
read_count = 0,
operation = None,
result = None,
exception = None
)
ENVIRON['cogen.http_connection'] = self
ENVIRON['cogen.core'] = async.COGENOperationWrapper(
ENV_COGEN_PROXY,
core
)
ENVIRON['cogen.call'] = async.COGENCallWrapper(ENV_COGEN_PROXY)
ENVIRON['cogen.input'] = async.COGENOperationWrapper(
ENV_COGEN_PROXY,
self.connfh
)
ENVIRON['cogen.yield'] = async.COGENSimpleWrapper(ENV_COGEN_PROXY)
response = self.wsgi_app(ENVIRON, self.start_response)
#~ print 'WSGI RESPONSE:', response
try:
if isinstance(response, WSGIFileWrapper):
# set tcp_cork to pack the header with the file data
if hasattr(socket, "TCP_CORK"):
self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
assert self.started_response, "App returned the wsgi.file_wrapper but didn't call start_response."
assert not self.sent_headers
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue()
)
offset = response.filelike.tell()
if self.chunked_write:
fsize = os.fstat(response.filelike.fileno()).st_size
yield sockets.SendAll(self.conn, hex(int(fsize-offset))+"\r\n")
yield self.conn.sendfile(
response.filelike,
blocksize=response.blocksize,
offset=offset,
length=self.content_length,
timeout=self.sendfile_timeout
)
if self.chunked_write:
yield sockets.SendAll(self.conn, "\r\n")
# also, tcp_cork will make the file data sent on packet boundaries,
# wich is a good thing
if hasattr(socket, "TCP_CORK"):
self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0)
else:
for chunk in response:
if chunk:
assert self.started_response, "App sended a value but hasn't called start_response."
if not self.sent_headers:
self.sent_headers = True
headers = [self.render_headers(), self.write_buffer.getvalue()]
else:
headers = []
if self.chunked_write:
buf = [hex(len(chunk))[2:], "\r\n", chunk, "\r\n"]
if headers:
headers.extend(buf)
yield sockets.SendAll(self.conn, "".join(headers))
else:
yield sockets.SendAll(self.conn, "".join(buf))
else:
if headers:
headers.append(chunk)
yield sockets.SendAll(self.conn, "".join(headers))
else:
yield sockets.SendAll(self.conn, chunk)
else:
if self.started_response:
if not self.sent_headers:
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue())
if ENV_COGEN_PROXY.operation:
op = ENV_COGEN_PROXY.operation
ENV_COGEN_PROXY.operation = None
try:
#~ print 'WSGI OP:', op
ENV_COGEN_PROXY.exception = None
ENV_COGEN_PROXY.result = yield op
#~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result
except:
#~ print 'WSGI OP EXCEPTION:', sys.exc_info()
ENV_COGEN_PROXY.exception = sys.exc_info()
ENV_COGEN_PROXY.result = ENV_COGEN_PROXY.exception[1]
del op
finally:
if hasattr(response, 'close'):
response.close()
if self.started_response:
if not self.sent_headers:
self.sent_headers = True
yield sockets.SendAll(self.conn,
self.render_headers()+self.write_buffer.getvalue()
)
else:
import warnings
warnings.warn("App was consumed and hasn't called start_response")
if self.chunked_write:
yield sockets.SendAll(self.conn, "0\r\n\r\n")
if self.close_connection:
return
# TODO: consume any unread data
except (socket.error, OSError, pywinerror), e:
errno = e.args[0]
if errno not in useless_socket_errors:
yield self.simple_response("500 Internal Server Error",
format_exc())
return
except (OperationTimeout, ConnectionClosed, SocketError):
return
except (KeyboardInterrupt, SystemExit, GeneratorExit, MemoryError):
raise
except:
if not self.started_response:
yield self.simple_response(
"500 Internal Server Error",
format_exc()
)
else:
print "*" * 60
traceback.print_exc()
print "*" * 60
sys.exc_clear()
finally:
self.conn.close()
ENVIRON = self.environ = None | ['def', 'run', '(', 'self', ')', ':', 'self', '.', 'close_connection', '=', 'False', 'try', ':', 'while', 'True', ':', 'self', '.', 'started_response', '=', 'False', 'self', '.', 'status', '=', '""', 'self', '.', 'outheaders', '=', '[', ']', 'self', '.', 'sent_headers', '=', 'False', 'self', '.', 'chunked_write', '=', 'False', 'self', '.', 'write_buffer', '=', 'StringIO', '.', 'StringIO', '(', ')', 'self', '.', 'content_length', '=', 'None', '# Copy the class environ into self.\r', 'ENVIRON', '=', 'self', '.', 'environ', '=', 'self', '.', 'connection_environ', '.', 'copy', '(', ')', 'self', '.', 'environ', '.', 'update', '(', 'self', '.', 'server_environ', ')', 'request_line', '=', 'yield', 'self', '.', 'connfh', '.', 'readline', '(', ')', 'if', 'request_line', '==', '"\\r\\n"', ':', '# RFC 2616 sec 4.1: "... it should ignore the CRLF."\r', 'tolerance', '=', '5', 'while', 'tolerance', 'and', 'request_line', '==', '"\\r\\n"', ':', 'request_line', '=', 'yield', 'self', '.', 'connfh', '.', 'readline', '(', ')', 'tolerance', '-=', '1', 'if', 'not', 'tolerance', ':', 'return', 'method', ',', 'path', ',', 'req_protocol', '=', 'request_line', '.', 'strip', '(', ')', '.', 'split', '(', '" "', ',', '2', ')', 'ENVIRON', '[', '"REQUEST_METHOD"', ']', '=', 'method', 'ENVIRON', '[', '"CONTENT_LENGTH"', ']', '=', "''", 'scheme', ',', 'location', ',', 'path', ',', 'params', ',', 'qs', ',', 'frag', '=', 'urlparse', '(', 'path', ')', 'if', 'frag', ':', 'yield', 'self', '.', 'simple_response', '(', '"400 Bad Request"', ',', '"Illegal #fragment in Request-URI."', ')', 'return', 'if', 'scheme', ':', 'ENVIRON', '[', '"wsgi.url_scheme"', ']', '=', 'scheme', 'if', 'params', ':', 'path', '=', 'path', '+', '";"', '+', 'params', 'ENVIRON', '[', '"SCRIPT_NAME"', ']', '=', '""', '# Unquote the path+params (e.g. "/this%20path" -> "this path").\r', '# http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2\r', '#\r', '# But note that "...a URI must be separated into its components\r', '# before the escaped characters within those components can be\r', '# safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2\r', 'atoms', '=', '[', 'unquote', '(', 'x', ')', 'for', 'x', 'in', 'quoted_slash', '.', 'split', '(', 'path', ')', ']', 'path', '=', '"%2F"', '.', 'join', '(', 'atoms', ')', 'ENVIRON', '[', '"PATH_INFO"', ']', '=', 'path', '# Note that, like wsgiref and most other WSGI servers,\r', '# we unquote the path but not the query string.\r', 'ENVIRON', '[', '"QUERY_STRING"', ']', '=', 'qs', '# Compare request and server HTTP protocol versions, in case our\r', '# server does not support the requested protocol. Limit our output\r', '# to min(req, server). We want the following output:\r', '# request server actual written supported response\r', '# protocol protocol response protocol feature set\r', '# a 1.0 1.0 1.0 1.0\r', '# b 1.0 1.1 1.1 1.0\r', '# c 1.1 1.0 1.0 1.0\r', '# d 1.1 1.1 1.1 1.1\r', '# Notice that, in (b), the response will be "HTTP/1.1" even though\r', '# the client only understands 1.0. RFC 2616 10.5.6 says we should\r', '# only return 505 if the _major_ version is different.\r', 'rp', '=', 'int', '(', 'req_protocol', '[', '5', ']', ')', ',', 'int', '(', 'req_protocol', '[', '7', ']', ')', 'server_protocol', '=', 'ENVIRON', '[', '"ACTUAL_SERVER_PROTOCOL"', ']', 'sp', '=', 'int', '(', 'server_protocol', '[', '5', ']', ')', ',', 'int', '(', 'server_protocol', '[', '7', ']', ')', 'if', 'sp', '[', '0', ']', '!=', 'rp', '[', '0', ']', ':', 'yield', 'self', '.', 'simple_response', '(', '"505 HTTP Version Not Supported"', ')', 'return', '# Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.\r', 'ENVIRON', '[', '"SERVER_PROTOCOL"', ']', '=', 'req_protocol', 'self', '.', 'response_protocol', '=', '"HTTP/%s.%s"', '%', 'min', '(', 'rp', ',', 'sp', ')', '# If the Request-URI was an absoluteURI, use its location atom.\r', 'if', 'location', ':', 'ENVIRON', '[', '"SERVER_NAME"', ']', '=', 'location', '# then all the http headers\r', 'try', ':', 'while', 'True', ':', 'line', '=', 'yield', 'self', '.', 'connfh', '.', 'readline', '(', ')', 'if', 'line', '==', "'\\r\\n'", ':', '# Normal end of headers\r', 'break', 'if', 'line', '[', '0', ']', 'in', "' \\t'", ':', "# It's a continuation line.\r", 'v', '=', 'line', '.', 'strip', '(', ')', 'else', ':', 'k', ',', 'v', '=', 'line', '.', 'split', '(', '":"', ',', '1', ')', 'k', ',', 'v', '=', 'k', '.', 'strip', '(', ')', '.', 'upper', '(', ')', ',', 'v', '.', 'strip', '(', ')', 'envname', '=', '"HTTP_"', '+', 'k', '.', 'replace', '(', '"-"', ',', '"_"', ')', 'if', 'k', 'in', 'comma_separated_headers', ':', 'existing', '=', 'ENVIRON', '.', 'get', '(', 'envname', ')', 'if', 'existing', ':', 'v', '=', '", "', '.', 'join', '(', '(', 'existing', ',', 'v', ')', ')', 'ENVIRON', '[', 'envname', ']', '=', 'v', 'ct', '=', 'ENVIRON', '.', 'pop', '(', '"HTTP_CONTENT_TYPE"', ',', 'None', ')', 'if', 'ct', ':', 'ENVIRON', '[', '"CONTENT_TYPE"', ']', '=', 'ct', 'cl', '=', 'ENVIRON', '.', 'pop', '(', '"HTTP_CONTENT_LENGTH"', ',', 'None', ')', 'if', 'cl', ':', 'ENVIRON', '[', '"CONTENT_LENGTH"', ']', '=', 'cl', 'except', 'ValueError', ',', 'ex', ':', 'yield', 'self', '.', 'simple_response', '(', '"400 Bad Request"', ',', 'repr', '(', 'ex', '.', 'args', ')', ')', 'return', 'creds', '=', 'ENVIRON', '.', 'get', '(', '"HTTP_AUTHORIZATION"', ',', '""', ')', '.', 'split', '(', '" "', ',', '1', ')', 'ENVIRON', '[', '"AUTH_TYPE"', ']', '=', 'creds', '[', '0', ']', 'if', 'creds', '[', '0', ']', '.', 'lower', '(', ')', '==', "'basic'", ':', 'user', ',', 'pw', '=', 'base64', '.', 'decodestring', '(', 'creds', '[', '1', ']', ')', '.', 'split', '(', '":"', ',', '1', ')', 'ENVIRON', '[', '"REMOTE_USER"', ']', '=', 'user', '# Persistent connection support\r', 'if', 'req_protocol', '==', '"HTTP/1.1"', ':', 'if', 'ENVIRON', '.', 'get', '(', '"HTTP_CONNECTION"', ',', '""', ')', '==', '"close"', ':', 'self', '.', 'close_connection', '=', 'True', 'else', ':', '# HTTP/1.0\r', 'if', 'ENVIRON', '.', 'get', '(', '"HTTP_CONNECTION"', ',', '""', ')', '.', 'lower', '(', ')', '!=', '"keep-alive"', ':', 'self', '.', 'close_connection', '=', 'True', '# Transfer-Encoding support\r', 'te', '=', 'None', 'if', 'self', '.', 'response_protocol', '==', '"HTTP/1.1"', ':', 'te', '=', 'ENVIRON', '.', 'get', '(', '"HTTP_TRANSFER_ENCODING"', ')', 'if', 'te', ':', 'te', '=', '[', 'x', '.', 'strip', '(', ')', '.', 'lower', '(', ')', 'for', 'x', 'in', 'te', '.', 'split', '(', '","', ')', 'if', 'x', '.', 'strip', '(', ')', ']', 'if', 'te', ':', '# reject transfer encodings for now\r', 'yield', 'self', '.', 'simple_response', '(', '"501 Unimplemented"', ')', 'self', '.', 'close_connection', '=', 'True', 'return', 'ENV_COGEN_PROXY', '=', 'ENVIRON', '[', "'cogen.wsgi'", ']', '=', 'async', '.', 'COGENProxy', '(', 'content_length', '=', 'int', '(', 'ENVIRON', '.', 'get', '(', "'CONTENT_LENGTH'", ',', 'None', ')', 'or', '0', ')', 'or', 'None', ',', 'read_count', '=', '0', ',', 'operation', '=', 'None', ',', 'result', '=', 'None', ',', 'exception', '=', 'None', ')', 'ENVIRON', '[', "'cogen.http_connection'", ']', '=', 'self', 'ENVIRON', '[', "'cogen.core'", ']', '=', 'async', '.', 'COGENOperationWrapper', '(', 'ENV_COGEN_PROXY', ',', 'core', ')', 'ENVIRON', '[', "'cogen.call'", ']', '=', 'async', '.', 'COGENCallWrapper', '(', 'ENV_COGEN_PROXY', ')', 'ENVIRON', '[', "'cogen.input'", ']', '=', 'async', '.', 'COGENOperationWrapper', '(', 'ENV_COGEN_PROXY', ',', 'self', '.', 'connfh', ')', 'ENVIRON', '[', "'cogen.yield'", ']', '=', 'async', '.', 'COGENSimpleWrapper', '(', 'ENV_COGEN_PROXY', ')', 'response', '=', 'self', '.', 'wsgi_app', '(', 'ENVIRON', ',', 'self', '.', 'start_response', ')', "#~ print 'WSGI RESPONSE:', response\r", 'try', ':', 'if', 'isinstance', '(', 'response', ',', 'WSGIFileWrapper', ')', ':', '# set tcp_cork to pack the header with the file data\r', 'if', 'hasattr', '(', 'socket', ',', '"TCP_CORK"', ')', ':', 'self', '.', 'conn', '.', 'setsockopt', '(', 'socket', '.', 'IPPROTO_TCP', ',', 'socket', '.', 'TCP_CORK', ',', '1', ')', 'assert', 'self', '.', 'started_response', ',', '"App returned the wsgi.file_wrapper but didn\'t call start_response."', 'assert', 'not', 'self', '.', 'sent_headers', 'self', '.', 'sent_headers', '=', 'True', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', 'self', '.', 'render_headers', '(', ')', '+', 'self', '.', 'write_buffer', '.', 'getvalue', '(', ')', ')', 'offset', '=', 'response', '.', 'filelike', '.', 'tell', '(', ')', 'if', 'self', '.', 'chunked_write', ':', 'fsize', '=', 'os', '.', 'fstat', '(', 'response', '.', 'filelike', '.', 'fileno', '(', ')', ')', '.', 'st_size', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', 'hex', '(', 'int', '(', 'fsize', '-', 'offset', ')', ')', '+', '"\\r\\n"', ')', 'yield', 'self', '.', 'conn', '.', 'sendfile', '(', 'response', '.', 'filelike', ',', 'blocksize', '=', 'response', '.', 'blocksize', ',', 'offset', '=', 'offset', ',', 'length', '=', 'self', '.', 'content_length', ',', 'timeout', '=', 'self', '.', 'sendfile_timeout', ')', 'if', 'self', '.', 'chunked_write', ':', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', '"\\r\\n"', ')', '# also, tcp_cork will make the file data sent on packet boundaries,\r', '# wich is a good thing\r', 'if', 'hasattr', '(', 'socket', ',', '"TCP_CORK"', ')', ':', 'self', '.', 'conn', '.', 'setsockopt', '(', 'socket', '.', 'IPPROTO_TCP', ',', 'socket', '.', 'TCP_CORK', ',', '0', ')', 'else', ':', 'for', 'chunk', 'in', 'response', ':', 'if', 'chunk', ':', 'assert', 'self', '.', 'started_response', ',', '"App sended a value but hasn\'t called start_response."', 'if', 'not', 'self', '.', 'sent_headers', ':', 'self', '.', 'sent_headers', '=', 'True', 'headers', '=', '[', 'self', '.', 'render_headers', '(', ')', ',', 'self', '.', 'write_buffer', '.', 'getvalue', '(', ')', ']', 'else', ':', 'headers', '=', '[', ']', 'if', 'self', '.', 'chunked_write', ':', 'buf', '=', '[', 'hex', '(', 'len', '(', 'chunk', ')', ')', '[', '2', ':', ']', ',', '"\\r\\n"', ',', 'chunk', ',', '"\\r\\n"', ']', 'if', 'headers', ':', 'headers', '.', 'extend', '(', 'buf', ')', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', '""', '.', 'join', '(', 'headers', ')', ')', 'else', ':', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', '""', '.', 'join', '(', 'buf', ')', ')', 'else', ':', 'if', 'headers', ':', 'headers', '.', 'append', '(', 'chunk', ')', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', '""', '.', 'join', '(', 'headers', ')', ')', 'else', ':', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', 'chunk', ')', 'else', ':', 'if', 'self', '.', 'started_response', ':', 'if', 'not', 'self', '.', 'sent_headers', ':', 'self', '.', 'sent_headers', '=', 'True', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', 'self', '.', 'render_headers', '(', ')', '+', 'self', '.', 'write_buffer', '.', 'getvalue', '(', ')', ')', 'if', 'ENV_COGEN_PROXY', '.', 'operation', ':', 'op', '=', 'ENV_COGEN_PROXY', '.', 'operation', 'ENV_COGEN_PROXY', '.', 'operation', '=', 'None', 'try', ':', "#~ print 'WSGI OP:', op\r", 'ENV_COGEN_PROXY', '.', 'exception', '=', 'None', 'ENV_COGEN_PROXY', '.', 'result', '=', 'yield', 'op', "#~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result\r", 'except', ':', "#~ print 'WSGI OP EXCEPTION:', sys.exc_info()\r", 'ENV_COGEN_PROXY', '.', 'exception', '=', 'sys', '.', 'exc_info', '(', ')', 'ENV_COGEN_PROXY', '.', 'result', '=', 'ENV_COGEN_PROXY', '.', 'exception', '[', '1', ']', 'del', 'op', 'finally', ':', 'if', 'hasattr', '(', 'response', ',', "'close'", ')', ':', 'response', '.', 'close', '(', ')', 'if', 'self', '.', 'started_response', ':', 'if', 'not', 'self', '.', 'sent_headers', ':', 'self', '.', 'sent_headers', '=', 'True', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', 'self', '.', 'render_headers', '(', ')', '+', 'self', '.', 'write_buffer', '.', 'getvalue', '(', ')', ')', 'else', ':', 'import', 'warnings', 'warnings', '.', 'warn', '(', '"App was consumed and hasn\'t called start_response"', ')', 'if', 'self', '.', 'chunked_write', ':', 'yield', 'sockets', '.', 'SendAll', '(', 'self', '.', 'conn', ',', '"0\\r\\n\\r\\n"', ')', 'if', 'self', '.', 'close_connection', ':', 'return', '# TODO: consume any unread data\r', 'except', '(', 'socket', '.', 'error', ',', 'OSError', ',', 'pywinerror', ')', ',', 'e', ':', 'errno', '=', 'e', '.', 'args', '[', '0', ']', 'if', 'errno', 'not', 'in', 'useless_socket_errors', ':', 'yield', 'self', '.', 'simple_response', '(', '"500 Internal Server Error"', ',', 'format_exc', '(', ')', ')', 'return', 'except', '(', 'OperationTimeout', ',', 'ConnectionClosed', ',', 'SocketError', ')', ':', 'return', 'except', '(', 'KeyboardInterrupt', ',', 'SystemExit', ',', 'GeneratorExit', ',', 'MemoryError', ')', ':', 'raise', 'except', ':', 'if', 'not', 'self', '.', 'started_response', ':', 'yield', 'self', '.', 'simple_response', '(', '"500 Internal Server Error"', ',', 'format_exc', '(', ')', ')', 'else', ':', 'print', '"*"', '*', '60', 'traceback', '.', 'print_exc', '(', ')', 'print', '"*"', '*', '60', 'sys', '.', 'exc_clear', '(', ')', 'finally', ':', 'self', '.', 'conn', '.', 'close', '(', ')', 'ENVIRON', '=', 'self', '.', 'environ', '=', 'None'] | A bit bulky atm... | ['A', 'bit', 'bulky', 'atm', '...'] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/web/wsgi.py#L250-L533 |
8,051 | yueyoum/social-oauth | example/_bottle.py | BaseRequest.remote_route | def remote_route(self):
""" A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. """
proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
if proxy: return [ip.strip() for ip in proxy.split(',')]
remote = self.environ.get('REMOTE_ADDR')
return [remote] if remote else [] | python | def remote_route(self):
""" A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. """
proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
if proxy: return [ip.strip() for ip in proxy.split(',')]
remote = self.environ.get('REMOTE_ADDR')
return [remote] if remote else [] | ['def', 'remote_route', '(', 'self', ')', ':', 'proxy', '=', 'self', '.', 'environ', '.', 'get', '(', "'HTTP_X_FORWARDED_FOR'", ')', 'if', 'proxy', ':', 'return', '[', 'ip', '.', 'strip', '(', ')', 'for', 'ip', 'in', 'proxy', '.', 'split', '(', "','", ')', ']', 'remote', '=', 'self', '.', 'environ', '.', 'get', '(', "'REMOTE_ADDR'", ')', 'return', '[', 'remote', ']', 'if', 'remote', 'else', '[', ']'] | A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. | ['A', 'list', 'of', 'all', 'IPs', 'that', 'were', 'involved', 'in', 'this', 'request', 'starting', 'with', 'the', 'client', 'IP', 'and', 'followed', 'by', 'zero', 'or', 'more', 'proxies', '.', 'This', 'does', 'only', 'work', 'if', 'all', 'proxies', 'support', 'the', 'X', '-', 'Forwarded', '-', 'For', 'header', '.', 'Note', 'that', 'this', 'information', 'can', 'be', 'forged', 'by', 'malicious', 'clients', '.'] | train | https://github.com/yueyoum/social-oauth/blob/80600ea737355b20931c8a0b5223f5b68175d930/example/_bottle.py#L1152-L1160 |
8,052 | UCL-INGI/INGInious | inginious/common/course_factory.py | CourseFactory.get_course_fs | def get_course_fs(self, courseid):
"""
:param courseid:
:return: a FileSystemProvider pointing to the directory of the course
"""
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
return self._filesystem.from_subfolder(courseid) | python | def get_course_fs(self, courseid):
"""
:param courseid:
:return: a FileSystemProvider pointing to the directory of the course
"""
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
return self._filesystem.from_subfolder(courseid) | ['def', 'get_course_fs', '(', 'self', ',', 'courseid', ')', ':', 'if', 'not', 'id_checker', '(', 'courseid', ')', ':', 'raise', 'InvalidNameException', '(', '"Course with invalid name: "', '+', 'courseid', ')', 'return', 'self', '.', '_filesystem', '.', 'from_subfolder', '(', 'courseid', ')'] | :param courseid:
:return: a FileSystemProvider pointing to the directory of the course | [':', 'param', 'courseid', ':', ':', 'return', ':', 'a', 'FileSystemProvider', 'pointing', 'to', 'the', 'directory', 'of', 'the', 'course'] | train | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/course_factory.py#L75-L82 |
8,053 | gem/oq-engine | openquake/hmtk/sources/area_source.py | mtkAreaSource.create_geometry | def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km)
'''
self._check_seismogenic_depths(upper_depth, lower_depth)
# Check/create the geometry class
if not isinstance(input_geometry, Polygon):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
if np.shape(input_geometry)[0] < 3:
raise ValueError('Incorrectly formatted polygon geometry -'
' needs three or more vertices')
geometry = []
for row in input_geometry:
geometry.append(Point(row[0], row[1], self.upper_depth))
self.geometry = Polygon(geometry)
else:
self.geometry = input_geometry | python | def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km)
'''
self._check_seismogenic_depths(upper_depth, lower_depth)
# Check/create the geometry class
if not isinstance(input_geometry, Polygon):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
if np.shape(input_geometry)[0] < 3:
raise ValueError('Incorrectly formatted polygon geometry -'
' needs three or more vertices')
geometry = []
for row in input_geometry:
geometry.append(Point(row[0], row[1], self.upper_depth))
self.geometry = Polygon(geometry)
else:
self.geometry = input_geometry | ['def', 'create_geometry', '(', 'self', ',', 'input_geometry', ',', 'upper_depth', ',', 'lower_depth', ')', ':', 'self', '.', '_check_seismogenic_depths', '(', 'upper_depth', ',', 'lower_depth', ')', '# Check/create the geometry class', 'if', 'not', 'isinstance', '(', 'input_geometry', ',', 'Polygon', ')', ':', 'if', 'not', 'isinstance', '(', 'input_geometry', ',', 'np', '.', 'ndarray', ')', ':', 'raise', 'ValueError', '(', "'Unrecognised or unsupported geometry '", "'definition'", ')', 'if', 'np', '.', 'shape', '(', 'input_geometry', ')', '[', '0', ']', '<', '3', ':', 'raise', 'ValueError', '(', "'Incorrectly formatted polygon geometry -'", "' needs three or more vertices'", ')', 'geometry', '=', '[', ']', 'for', 'row', 'in', 'input_geometry', ':', 'geometry', '.', 'append', '(', 'Point', '(', 'row', '[', '0', ']', ',', 'row', '[', '1', ']', ',', 'self', '.', 'upper_depth', ')', ')', 'self', '.', 'geometry', '=', 'Polygon', '(', 'geometry', ')', 'else', ':', 'self', '.', 'geometry', '=', 'input_geometry'] | If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km) | ['If', 'geometry', 'is', 'defined', 'as', 'a', 'numpy', 'array', 'then', 'create', 'instance', 'of', 'nhlib', '.', 'geo', '.', 'polygon', '.', 'Polygon', 'class', 'otherwise', 'if', 'already', 'instance', 'of', 'class', 'accept', 'class'] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L118-L151 |
8,054 | mbedmicro/pyOCD | pyocd/probe/pydapaccess/dap_access_cmsis_dap.py | DAPAccessCMSISDAP.set_deferred_transfer | def set_deferred_transfer(self, enable):
"""
Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
increases speed. When memory is written to, the transfer
might take place immediately, or might take place on a future
memory write. This means that an invalid write could cause an
exception to occur on a later, unrelated write. To guarantee
that previous writes are complete call the flush() function.
The behaviour of read operations is determined by the modes
READ_START, READ_NOW and READ_END. The option READ_NOW is the
default and will cause the read to flush all previous writes,
and read the data immediately. To improve performance, multiple
reads can be made using READ_START and finished later with READ_NOW.
This allows the reads to be buffered and sent at once. Note - All
READ_ENDs must be called before a call using READ_NOW can be made.
"""
if self._deferred_transfer and not enable:
self.flush()
self._deferred_transfer = enable | python | def set_deferred_transfer(self, enable):
"""
Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
increases speed. When memory is written to, the transfer
might take place immediately, or might take place on a future
memory write. This means that an invalid write could cause an
exception to occur on a later, unrelated write. To guarantee
that previous writes are complete call the flush() function.
The behaviour of read operations is determined by the modes
READ_START, READ_NOW and READ_END. The option READ_NOW is the
default and will cause the read to flush all previous writes,
and read the data immediately. To improve performance, multiple
reads can be made using READ_START and finished later with READ_NOW.
This allows the reads to be buffered and sent at once. Note - All
READ_ENDs must be called before a call using READ_NOW can be made.
"""
if self._deferred_transfer and not enable:
self.flush()
self._deferred_transfer = enable | ['def', 'set_deferred_transfer', '(', 'self', ',', 'enable', ')', ':', 'if', 'self', '.', '_deferred_transfer', 'and', 'not', 'enable', ':', 'self', '.', 'flush', '(', ')', 'self', '.', '_deferred_transfer', '=', 'enable'] | Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
increases speed. When memory is written to, the transfer
might take place immediately, or might take place on a future
memory write. This means that an invalid write could cause an
exception to occur on a later, unrelated write. To guarantee
that previous writes are complete call the flush() function.
The behaviour of read operations is determined by the modes
READ_START, READ_NOW and READ_END. The option READ_NOW is the
default and will cause the read to flush all previous writes,
and read the data immediately. To improve performance, multiple
reads can be made using READ_START and finished later with READ_NOW.
This allows the reads to be buffered and sent at once. Note - All
READ_ENDs must be called before a call using READ_NOW can be made. | ['Allow', 'transfers', 'to', 'be', 'delayed', 'and', 'buffered'] | train | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/pydapaccess/dap_access_cmsis_dap.py#L626-L650 |
8,055 | ralphje/imagemounter | imagemounter/volume.py | Volume.init | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result
of the :func:`init` call on each subvolume is yielded
:param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings.
:param skip_mount: if specified, volume indexes in this list are not mounted.
:param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an
exception attribute to the yielded objects.
"""
if swallow_exceptions:
self.exception = None
try:
if not self._should_mount(only_mount, skip_mount):
yield self
return
if not self.init_volume():
yield self
return
except ImageMounterError as e:
if swallow_exceptions:
self.exception = e
else:
raise
if not self.volumes:
yield self
else:
for v in self.volumes:
for s in v.init(only_mount, skip_mount, swallow_exceptions):
yield s | python | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result
of the :func:`init` call on each subvolume is yielded
:param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings.
:param skip_mount: if specified, volume indexes in this list are not mounted.
:param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an
exception attribute to the yielded objects.
"""
if swallow_exceptions:
self.exception = None
try:
if not self._should_mount(only_mount, skip_mount):
yield self
return
if not self.init_volume():
yield self
return
except ImageMounterError as e:
if swallow_exceptions:
self.exception = e
else:
raise
if not self.volumes:
yield self
else:
for v in self.volumes:
for s in v.init(only_mount, skip_mount, swallow_exceptions):
yield s | ['def', 'init', '(', 'self', ',', 'only_mount', '=', 'None', ',', 'skip_mount', '=', 'None', ',', 'swallow_exceptions', '=', 'True', ')', ':', 'if', 'swallow_exceptions', ':', 'self', '.', 'exception', '=', 'None', 'try', ':', 'if', 'not', 'self', '.', '_should_mount', '(', 'only_mount', ',', 'skip_mount', ')', ':', 'yield', 'self', 'return', 'if', 'not', 'self', '.', 'init_volume', '(', ')', ':', 'yield', 'self', 'return', 'except', 'ImageMounterError', 'as', 'e', ':', 'if', 'swallow_exceptions', ':', 'self', '.', 'exception', '=', 'e', 'else', ':', 'raise', 'if', 'not', 'self', '.', 'volumes', ':', 'yield', 'self', 'else', ':', 'for', 'v', 'in', 'self', '.', 'volumes', ':', 'for', 's', 'in', 'v', '.', 'init', '(', 'only_mount', ',', 'skip_mount', ',', 'swallow_exceptions', ')', ':', 'yield', 's'] | Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result
of the :func:`init` call on each subvolume is yielded
:param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings.
:param skip_mount: if specified, volume indexes in this list are not mounted.
:param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an
exception attribute to the yielded objects. | ['Generator', 'that', 'mounts', 'this', 'volume', 'and', 'either', 'yields', 'itself', 'or', 'recursively', 'generates', 'its', 'subvolumes', '.'] | train | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L374-L409 |
8,056 | threeML/astromodels | astromodels/functions/functions_3D.py | Continuous_injection_diffusion_ellipse.get_total_spatial_integral | def get_total_spatial_integral(self, z=None):
"""
Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z).
"""
if isinstance( z, u.Quantity):
z = z.value
return np.ones_like( z ) | python | def get_total_spatial_integral(self, z=None):
"""
Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z).
"""
if isinstance( z, u.Quantity):
z = z.value
return np.ones_like( z ) | ['def', 'get_total_spatial_integral', '(', 'self', ',', 'z', '=', 'None', ')', ':', 'if', 'isinstance', '(', 'z', ',', 'u', '.', 'Quantity', ')', ':', 'z', '=', 'z', '.', 'value', 'return', 'np', '.', 'ones_like', '(', 'z', ')'] | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | ['Returns', 'the', 'total', 'integral', '(', 'for', '2D', 'functions', ')', 'or', 'the', 'integral', 'over', 'the', 'spatial', 'components', '(', 'for', '3D', 'functions', ')', '.', 'needs', 'to', 'be', 'implemented', 'in', 'subclasses', '.'] | train | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/functions_3D.py#L192-L202 |
8,057 | crccheck/cloudwatch-to-graphite | leadbutt.py | output_results | def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
except AttributeError:
context['dimension'] = ''
for result in results:
stat_keys = metric['Statistics']
if not isinstance(stat_keys, list):
stat_keys = [stat_keys]
for statistic in stat_keys:
context['statistic'] = statistic
# get and then sanitize metric name, first copy the unit name from the
# result to the context to keep the default format happy
context['Unit'] = result['Unit']
metric_name = (formatter % context).replace('/', '.').lower()
line = '{0} {1} {2}\n'.format(
metric_name,
result[statistic],
timegm(result['Timestamp'].timetuple()),
)
sys.stdout.write(line) | python | def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
except AttributeError:
context['dimension'] = ''
for result in results:
stat_keys = metric['Statistics']
if not isinstance(stat_keys, list):
stat_keys = [stat_keys]
for statistic in stat_keys:
context['statistic'] = statistic
# get and then sanitize metric name, first copy the unit name from the
# result to the context to keep the default format happy
context['Unit'] = result['Unit']
metric_name = (formatter % context).replace('/', '.').lower()
line = '{0} {1} {2}\n'.format(
metric_name,
result[statistic],
timegm(result['Timestamp'].timetuple()),
)
sys.stdout.write(line) | ['def', 'output_results', '(', 'results', ',', 'metric', ',', 'options', ')', ':', 'formatter', '=', 'options', '[', "'Formatter'", ']', 'context', '=', 'metric', '.', 'copy', '(', ')', '# XXX might need to sanitize this', 'try', ':', 'context', '[', "'dimension'", ']', '=', 'list', '(', 'metric', '[', "'Dimensions'", ']', '.', 'values', '(', ')', ')', '[', '0', ']', 'except', 'AttributeError', ':', 'context', '[', "'dimension'", ']', '=', "''", 'for', 'result', 'in', 'results', ':', 'stat_keys', '=', 'metric', '[', "'Statistics'", ']', 'if', 'not', 'isinstance', '(', 'stat_keys', ',', 'list', ')', ':', 'stat_keys', '=', '[', 'stat_keys', ']', 'for', 'statistic', 'in', 'stat_keys', ':', 'context', '[', "'statistic'", ']', '=', 'statistic', '# get and then sanitize metric name, first copy the unit name from the', '# result to the context to keep the default format happy', 'context', '[', "'Unit'", ']', '=', 'result', '[', "'Unit'", ']', 'metric_name', '=', '(', 'formatter', '%', 'context', ')', '.', 'replace', '(', "'/'", ',', "'.'", ')', '.', 'lower', '(', ')', 'line', '=', "'{0} {1} {2}\\n'", '.', 'format', '(', 'metric_name', ',', 'result', '[', 'statistic', ']', ',', 'timegm', '(', 'result', '[', "'Timestamp'", ']', '.', 'timetuple', '(', ')', ')', ',', ')', 'sys', '.', 'stdout', '.', 'write', '(', 'line', ')'] | Output the results to stdout.
TODO: add AMPQ support for efficiency | ['Output', 'the', 'results', 'to', 'stdout', '.'] | train | https://github.com/crccheck/cloudwatch-to-graphite/blob/28a11ee56f7231cef6b6f8af142a8aab3d2eb5a6/leadbutt.py#L90-L117 |
8,058 | kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.get_groups | def get_groups(self, username):
"""Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search(searchfilter, NO_ATTR, self.groupdn)
ret = []
for entry in groups:
ret.append(self._uni(entry[0]))
return ret | python | def get_groups(self, username):
"""Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search(searchfilter, NO_ATTR, self.groupdn)
ret = []
for entry in groups:
ret.append(self._uni(entry[0]))
return ret | ['def', 'get_groups', '(', 'self', ',', 'username', ')', ':', 'username', '=', 'ldap', '.', 'filter', '.', 'escape_filter_chars', '(', 'self', '.', '_byte_p2', '(', 'username', ')', ')', 'userdn', '=', 'self', '.', '_get_user', '(', 'username', ',', 'NO_ATTR', ')', 'searchfilter', '=', 'self', '.', 'group_filter_tmpl', '%', '{', "'userdn'", ':', 'userdn', ',', "'username'", ':', 'username', '}', 'groups', '=', 'self', '.', '_search', '(', 'searchfilter', ',', 'NO_ATTR', ',', 'self', '.', 'groupdn', ')', 'ret', '=', '[', ']', 'for', 'entry', 'in', 'groups', ':', 'ret', '.', 'append', '(', 'self', '.', '_uni', '(', 'entry', '[', '0', ']', ')', ')', 'return', 'ret'] | Get all groups of a user | ['Get', 'all', 'groups', 'of', 'a', 'user'] | train | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L651-L665 |
8,059 | openstack/proliantutils | proliantutils/ilo/ribcl.py | RIBCLOperations.get_ilo_firmware_version_as_major_minor | def get_ilo_firmware_version_as_major_minor(self):
"""Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None.
"""
data = self.get_host_health_data()
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
ilo_version_str = firmware_details.get('iLO', None)
return common.get_major_minor(ilo_version_str) | python | def get_ilo_firmware_version_as_major_minor(self):
"""Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None.
"""
data = self.get_host_health_data()
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
ilo_version_str = firmware_details.get('iLO', None)
return common.get_major_minor(ilo_version_str) | ['def', 'get_ilo_firmware_version_as_major_minor', '(', 'self', ')', ':', 'data', '=', 'self', '.', 'get_host_health_data', '(', ')', 'firmware_details', '=', 'self', '.', '_get_firmware_embedded_health', '(', 'data', ')', 'if', 'firmware_details', ':', 'ilo_version_str', '=', 'firmware_details', '.', 'get', '(', "'iLO'", ',', 'None', ')', 'return', 'common', '.', 'get_major_minor', '(', 'ilo_version_str', ')'] | Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None. | ['Gets', 'the', 'ilo', 'firmware', 'version', 'for', 'server', 'capabilities'] | train | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ribcl.py#L1042-L1056 |
8,060 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | gated_linear_unit_layer | def gated_linear_unit_layer(x, name=None):
"""Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x.
"""
with tf.variable_scope(name, default_name="glu_layer", values=[x]):
depth = shape_list(x)[-1]
x = layers().Dense(depth * 2, activation=None)(x)
x, gating_x = tf.split(x, 2, axis=-1)
return x * tf.nn.sigmoid(gating_x) | python | def gated_linear_unit_layer(x, name=None):
"""Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x.
"""
with tf.variable_scope(name, default_name="glu_layer", values=[x]):
depth = shape_list(x)[-1]
x = layers().Dense(depth * 2, activation=None)(x)
x, gating_x = tf.split(x, 2, axis=-1)
return x * tf.nn.sigmoid(gating_x) | ['def', 'gated_linear_unit_layer', '(', 'x', ',', 'name', '=', 'None', ')', ':', 'with', 'tf', '.', 'variable_scope', '(', 'name', ',', 'default_name', '=', '"glu_layer"', ',', 'values', '=', '[', 'x', ']', ')', ':', 'depth', '=', 'shape_list', '(', 'x', ')', '[', '-', '1', ']', 'x', '=', 'layers', '(', ')', '.', 'Dense', '(', 'depth', '*', '2', ',', 'activation', '=', 'None', ')', '(', 'x', ')', 'x', ',', 'gating_x', '=', 'tf', '.', 'split', '(', 'x', ',', '2', ',', 'axis', '=', '-', '1', ')', 'return', 'x', '*', 'tf', '.', 'nn', '.', 'sigmoid', '(', 'gating_x', ')'] | Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x. | ['Gated', 'linear', 'unit', 'layer', '.'] | train | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2217-L2235 |
8,061 | saltstack/salt | salt/modules/rpmbuild_pkgbuild.py | make_src_pkg | def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base', runas='root'):
'''
Create a source rpm from the given spec file and sources
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_src_pkg /var/www/html/
https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz
This example command should build the libnacl SOURCE package and place it in
/var/www/html/ on the minion
.. versionchanged:: 2017.7.0
dest_dir
The directory on the minion to place the built package(s)
spec
The location of the spec file (used for rpms)
sources
The list of package sources
env
A dictionary of environment variables to be set prior to execution.
template
Run the spec file through a templating engine
Optional arguement, allows for no templating engine used to be
if none is desired.
saltenv
The saltenv to use for files downloaded from the salt filesever
runas
The user to run the build process as
.. versionadded:: 2018.3.3
.. note::
using SHA256 as digest and minimum level dist el6
'''
_create_rpmmacros(runas)
tree_base = _mk_tree(runas)
spec_path = _get_spec(tree_base, spec, template, saltenv)
__salt__['file.chown'](path=spec_path, user=runas, group='mock')
__salt__['file.chown'](path=tree_base, user=runas, group='mock')
if isinstance(sources, six.string_types):
sources = sources.split(',')
for src in sources:
_get_src(tree_base, src, saltenv, runas)
# make source rpms for dist el6 with SHA256, usable with mock on other dists
cmd = 'rpmbuild --verbose --define "_topdir {0}" -bs --define "dist .el6" {1}'.format(tree_base, spec_path)
retrc = __salt__['cmd.retcode'](cmd, runas=runas)
if retrc != 0:
raise SaltInvocationError(
'Make source package for destination directory {0}, spec {1}, sources {2}, failed '
'with return error {3}, check logs for further details'.format(
dest_dir,
spec,
sources,
retrc)
)
srpms = os.path.join(tree_base, 'SRPMS')
ret = []
if not os.path.isdir(dest_dir):
__salt__['file.makedirs_perms'](name=dest_dir, user=runas, group='mock')
for fn_ in os.listdir(srpms):
full = os.path.join(srpms, fn_)
tgt = os.path.join(dest_dir, fn_)
shutil.copy(full, tgt)
ret.append(tgt)
return ret | python | def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base', runas='root'):
'''
Create a source rpm from the given spec file and sources
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_src_pkg /var/www/html/
https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz
This example command should build the libnacl SOURCE package and place it in
/var/www/html/ on the minion
.. versionchanged:: 2017.7.0
dest_dir
The directory on the minion to place the built package(s)
spec
The location of the spec file (used for rpms)
sources
The list of package sources
env
A dictionary of environment variables to be set prior to execution.
template
Run the spec file through a templating engine
Optional arguement, allows for no templating engine used to be
if none is desired.
saltenv
The saltenv to use for files downloaded from the salt filesever
runas
The user to run the build process as
.. versionadded:: 2018.3.3
.. note::
using SHA256 as digest and minimum level dist el6
'''
_create_rpmmacros(runas)
tree_base = _mk_tree(runas)
spec_path = _get_spec(tree_base, spec, template, saltenv)
__salt__['file.chown'](path=spec_path, user=runas, group='mock')
__salt__['file.chown'](path=tree_base, user=runas, group='mock')
if isinstance(sources, six.string_types):
sources = sources.split(',')
for src in sources:
_get_src(tree_base, src, saltenv, runas)
# make source rpms for dist el6 with SHA256, usable with mock on other dists
cmd = 'rpmbuild --verbose --define "_topdir {0}" -bs --define "dist .el6" {1}'.format(tree_base, spec_path)
retrc = __salt__['cmd.retcode'](cmd, runas=runas)
if retrc != 0:
raise SaltInvocationError(
'Make source package for destination directory {0}, spec {1}, sources {2}, failed '
'with return error {3}, check logs for further details'.format(
dest_dir,
spec,
sources,
retrc)
)
srpms = os.path.join(tree_base, 'SRPMS')
ret = []
if not os.path.isdir(dest_dir):
__salt__['file.makedirs_perms'](name=dest_dir, user=runas, group='mock')
for fn_ in os.listdir(srpms):
full = os.path.join(srpms, fn_)
tgt = os.path.join(dest_dir, fn_)
shutil.copy(full, tgt)
ret.append(tgt)
return ret | ['def', 'make_src_pkg', '(', 'dest_dir', ',', 'spec', ',', 'sources', ',', 'env', '=', 'None', ',', 'template', '=', 'None', ',', 'saltenv', '=', "'base'", ',', 'runas', '=', "'root'", ')', ':', '_create_rpmmacros', '(', 'runas', ')', 'tree_base', '=', '_mk_tree', '(', 'runas', ')', 'spec_path', '=', '_get_spec', '(', 'tree_base', ',', 'spec', ',', 'template', ',', 'saltenv', ')', '__salt__', '[', "'file.chown'", ']', '(', 'path', '=', 'spec_path', ',', 'user', '=', 'runas', ',', 'group', '=', "'mock'", ')', '__salt__', '[', "'file.chown'", ']', '(', 'path', '=', 'tree_base', ',', 'user', '=', 'runas', ',', 'group', '=', "'mock'", ')', 'if', 'isinstance', '(', 'sources', ',', 'six', '.', 'string_types', ')', ':', 'sources', '=', 'sources', '.', 'split', '(', "','", ')', 'for', 'src', 'in', 'sources', ':', '_get_src', '(', 'tree_base', ',', 'src', ',', 'saltenv', ',', 'runas', ')', '# make source rpms for dist el6 with SHA256, usable with mock on other dists', 'cmd', '=', '\'rpmbuild --verbose --define "_topdir {0}" -bs --define "dist .el6" {1}\'', '.', 'format', '(', 'tree_base', ',', 'spec_path', ')', 'retrc', '=', '__salt__', '[', "'cmd.retcode'", ']', '(', 'cmd', ',', 'runas', '=', 'runas', ')', 'if', 'retrc', '!=', '0', ':', 'raise', 'SaltInvocationError', '(', "'Make source package for destination directory {0}, spec {1}, sources {2}, failed '", "'with return error {3}, check logs for further details'", '.', 'format', '(', 'dest_dir', ',', 'spec', ',', 'sources', ',', 'retrc', ')', ')', 'srpms', '=', 'os', '.', 'path', '.', 'join', '(', 'tree_base', ',', "'SRPMS'", ')', 'ret', '=', '[', ']', 'if', 'not', 'os', '.', 'path', '.', 'isdir', '(', 'dest_dir', ')', ':', '__salt__', '[', "'file.makedirs_perms'", ']', '(', 'name', '=', 'dest_dir', ',', 'user', '=', 'runas', ',', 'group', '=', "'mock'", ')', 'for', 'fn_', 'in', 'os', '.', 'listdir', '(', 'srpms', ')', ':', 'full', '=', 'os', '.', 'path', '.', 'join', '(', 'srpms', ',', 'fn_', ')', 'tgt', '=', 'os', '.', 'path', '.', 'join', '(', 'dest_dir', ',', 'fn_', ')', 'shutil', '.', 'copy', '(', 'full', ',', 'tgt', ')', 'ret', '.', 'append', '(', 'tgt', ')', 'return', 'ret'] | Create a source rpm from the given spec file and sources
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_src_pkg /var/www/html/
https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz
This example command should build the libnacl SOURCE package and place it in
/var/www/html/ on the minion
.. versionchanged:: 2017.7.0
dest_dir
The directory on the minion to place the built package(s)
spec
The location of the spec file (used for rpms)
sources
The list of package sources
env
A dictionary of environment variables to be set prior to execution.
template
Run the spec file through a templating engine
Optional arguement, allows for no templating engine used to be
if none is desired.
saltenv
The saltenv to use for files downloaded from the salt filesever
runas
The user to run the build process as
.. versionadded:: 2018.3.3
.. note::
using SHA256 as digest and minimum level dist el6 | ['Create', 'a', 'source', 'rpm', 'from', 'the', 'given', 'spec', 'file', 'and', 'sources'] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpmbuild_pkgbuild.py#L176-L257 |
8,062 | thiagopbueno/rddl2tf | rddl2tf/compiler.py | Compiler._compile_expression | def _compile_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None) -> TensorFluent:
'''Compile the expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.fluent.TensorFluent`: The compiled TensorFluent.
'''
etype2compiler = {
'constant': self._compile_constant_expression,
'pvar': self._compile_pvariable_expression,
'randomvar': self._compile_random_variable_expression,
'arithmetic': self._compile_arithmetic_expression,
'boolean': self._compile_boolean_expression,
'relational': self._compile_relational_expression,
'func': self._compile_function_expression,
'control': self._compile_control_flow_expression,
'aggregation': self._compile_aggregation_expression
}
etype = expr.etype
if etype[0] not in etype2compiler:
raise ValueError('Expression type unknown: {}'.format(etype))
with self.graph.as_default():
compiler_fn = etype2compiler[etype[0]]
return compiler_fn(expr, scope, batch_size, noise) | python | def _compile_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None) -> TensorFluent:
'''Compile the expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.fluent.TensorFluent`: The compiled TensorFluent.
'''
etype2compiler = {
'constant': self._compile_constant_expression,
'pvar': self._compile_pvariable_expression,
'randomvar': self._compile_random_variable_expression,
'arithmetic': self._compile_arithmetic_expression,
'boolean': self._compile_boolean_expression,
'relational': self._compile_relational_expression,
'func': self._compile_function_expression,
'control': self._compile_control_flow_expression,
'aggregation': self._compile_aggregation_expression
}
etype = expr.etype
if etype[0] not in etype2compiler:
raise ValueError('Expression type unknown: {}'.format(etype))
with self.graph.as_default():
compiler_fn = etype2compiler[etype[0]]
return compiler_fn(expr, scope, batch_size, noise) | ['def', '_compile_expression', '(', 'self', ',', 'expr', ':', 'Expression', ',', 'scope', ':', 'Dict', '[', 'str', ',', 'TensorFluent', ']', ',', 'batch_size', ':', 'Optional', '[', 'int', ']', '=', 'None', ',', 'noise', ':', 'Optional', '[', 'List', '[', 'tf', '.', 'Tensor', ']', ']', '=', 'None', ')', '->', 'TensorFluent', ':', 'etype2compiler', '=', '{', "'constant'", ':', 'self', '.', '_compile_constant_expression', ',', "'pvar'", ':', 'self', '.', '_compile_pvariable_expression', ',', "'randomvar'", ':', 'self', '.', '_compile_random_variable_expression', ',', "'arithmetic'", ':', 'self', '.', '_compile_arithmetic_expression', ',', "'boolean'", ':', 'self', '.', '_compile_boolean_expression', ',', "'relational'", ':', 'self', '.', '_compile_relational_expression', ',', "'func'", ':', 'self', '.', '_compile_function_expression', ',', "'control'", ':', 'self', '.', '_compile_control_flow_expression', ',', "'aggregation'", ':', 'self', '.', '_compile_aggregation_expression', '}', 'etype', '=', 'expr', '.', 'etype', 'if', 'etype', '[', '0', ']', 'not', 'in', 'etype2compiler', ':', 'raise', 'ValueError', '(', "'Expression type unknown: {}'", '.', 'format', '(', 'etype', ')', ')', 'with', 'self', '.', 'graph', '.', 'as_default', '(', ')', ':', 'compiler_fn', '=', 'etype2compiler', '[', 'etype', '[', '0', ']', ']', 'return', 'compiler_fn', '(', 'expr', ',', 'scope', ',', 'batch_size', ',', 'noise', ')'] | Compile the expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.fluent.TensorFluent`: The compiled TensorFluent. | ['Compile', 'the', 'expression', 'expr', 'into', 'a', 'TensorFluent', 'in', 'the', 'given', 'scope', 'with', 'optional', 'batch', 'size', '.'] | train | https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L589-L623 |
8,063 | zikzakmedia/python-mediawiki | mediawiki/wikimarkup/__init__.py | str2url | def str2url(str):
"""
Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit
ASCII. It returns a plain ASCII string usable in URLs.
"""
try:
str = str.encode('utf-8')
except:
pass
mfrom = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï"
to = "AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceeeeiiii"
mfrom += "ñòóôõöøùúûüýÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģ"
to += "noooooouuuuyyaaaaaaccccccccddddeeeeeeeeeegggggggg"
mfrom += "ĤĥĦħĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘř"
to += "hhhhiiiiiiiiiijjkkkllllllllllnnnnnnnnnoooooooorrrrrr"
mfrom += "ŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƂƃƄƅƇƈƉƊƐƑƒƓƔ"
to += "ssssssssttttttuuuuuuuuuuuuwwyyyzzzzzzfbbbbbccddeffgv"
mfrom += "ƖƗƘƙƚƝƞƟƠƤƦƫƬƭƮƯưƱƲƳƴƵƶǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩ"
to += "likklnnoopettttuuuuyyzzaaiioouuuuuuuuuueaaaaeeggggkk"
mfrom += "ǪǫǬǭǰǴǵǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȞȟȤȥȦȧȨȩ"
to += "oooojggpnnaaeeooaaaaeeeeiiiioooorrrruuuusstthhzzaaee"
mfrom += "ȪȫȬȭȮȯȰȱȲȳḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫ"
to += "ooooooooyyaabbbbbbccddddddddddeeeeeeeeeeffgghhhhhhhhhh"
mfrom += "ḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟ"
to += "iiiikkkkkkllllllllmmmmmmnnnnnnnnoooooooopppprrrrrrrr"
mfrom += "ṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕ"
to += "ssssssssssttttttttuuuuuuuuuuvvvvwwwwwwwwwwxxxxxyzzzzzz"
mfrom += "ẖẗẘẙẚẛẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊị"
to += "htwyafaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeiiii"
mfrom += "ỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹ"
to += "oooooooooooooooooooooooouuuuuuuuuuuuuuyyyyyyyy"
for i in zip(mfrom, to):
str = str.replace(*i)
return str | python | def str2url(str):
"""
Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit
ASCII. It returns a plain ASCII string usable in URLs.
"""
try:
str = str.encode('utf-8')
except:
pass
mfrom = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï"
to = "AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceeeeiiii"
mfrom += "ñòóôõöøùúûüýÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģ"
to += "noooooouuuuyyaaaaaaccccccccddddeeeeeeeeeegggggggg"
mfrom += "ĤĥĦħĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘř"
to += "hhhhiiiiiiiiiijjkkkllllllllllnnnnnnnnnoooooooorrrrrr"
mfrom += "ŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƂƃƄƅƇƈƉƊƐƑƒƓƔ"
to += "ssssssssttttttuuuuuuuuuuuuwwyyyzzzzzzfbbbbbccddeffgv"
mfrom += "ƖƗƘƙƚƝƞƟƠƤƦƫƬƭƮƯưƱƲƳƴƵƶǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩ"
to += "likklnnoopettttuuuuyyzzaaiioouuuuuuuuuueaaaaeeggggkk"
mfrom += "ǪǫǬǭǰǴǵǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȞȟȤȥȦȧȨȩ"
to += "oooojggpnnaaeeooaaaaeeeeiiiioooorrrruuuusstthhzzaaee"
mfrom += "ȪȫȬȭȮȯȰȱȲȳḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫ"
to += "ooooooooyyaabbbbbbccddddddddddeeeeeeeeeeffgghhhhhhhhhh"
mfrom += "ḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟ"
to += "iiiikkkkkkllllllllmmmmmmnnnnnnnnoooooooopppprrrrrrrr"
mfrom += "ṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕ"
to += "ssssssssssttttttttuuuuuuuuuuvvvvwwwwwwwwwwxxxxxyzzzzzz"
mfrom += "ẖẗẘẙẚẛẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊị"
to += "htwyafaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeiiii"
mfrom += "ỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹ"
to += "oooooooooooooooooooooooouuuuuuuuuuuuuuyyyyyyyy"
for i in zip(mfrom, to):
str = str.replace(*i)
return str | ['def', 'str2url', '(', 'str', ')', ':', 'try', ':', 'str', '=', 'str', '.', 'encode', '(', "'utf-8'", ')', 'except', ':', 'pass', 'mfrom', '=', '"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï"', 'to', '=', '"AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceeeeiiii"', 'mfrom', '+=', '"ñòóôõöøùúûüýÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģ"', 'to', '+=', '"noooooouuuuyyaaaaaaccccccccddddeeeeeeeeeegggggggg"', 'mfrom', '+=', '"ĤĥĦħĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘř"', 'to', '+=', '"hhhhiiiiiiiiiijjkkkllllllllllnnnnnnnnnoooooooorrrrrr"', 'mfrom', '+=', '"ŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƂƃƄƅƇƈƉƊƐƑƒƓƔ"', 'to', '+=', '"ssssssssttttttuuuuuuuuuuuuwwyyyzzzzzzfbbbbbccddeffgv"', 'mfrom', '+=', '"ƖƗƘƙƚƝƞƟƠƤƦƫƬƭƮƯưƱƲƳƴƵƶǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩ"', 'to', '+=', '"likklnnoopettttuuuuyyzzaaiioouuuuuuuuuueaaaaeeggggkk"', 'mfrom', '+=', '"ǪǫǬǭǰǴǵǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȞȟȤȥȦȧȨȩ"', 'to', '+=', '"oooojggpnnaaeeooaaaaeeeeiiiioooorrrruuuusstthhzzaaee"', 'mfrom', '+=', '"ȪȫȬȭȮȯȰȱȲȳḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫ"', 'to', '+=', '"ooooooooyyaabbbbbbccddddddddddeeeeeeeeeeffgghhhhhhhhhh"', 'mfrom', '+=', '"ḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟ"', 'to', '+=', '"iiiikkkkkkllllllllmmmmmmnnnnnnnnoooooooopppprrrrrrrr"', 'mfrom', '+=', '"ṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕ"', 'to', '+=', '"ssssssssssttttttttuuuuuuuuuuvvvvwwwwwwwwwwxxxxxyzzzzzz"', 'mfrom', '+=', '"ẖẗẘẙẚẛẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊị"', 'to', '+=', '"htwyafaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeiiii"', 'mfrom', '+=', '"ỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹ"', 'to', '+=', '"oooooooooooooooooooooooouuuuuuuuuuuuuuyyyyyyyy"', 'for', 'i', 'in', 'zip', '(', 'mfrom', ',', 'to', ')', ':', 'str', '=', 'str', '.', 'replace', '(', '*', 'i', ')', 'return', 'str'] | Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit
ASCII. It returns a plain ASCII string usable in URLs. | ['Takes', 'a', 'UTF', '-', '8', 'string', 'and', 'replaces', 'all', 'characters', 'with', 'the', 'equivalent', 'in', '7', '-', 'bit', 'ASCII', '.', 'It', 'returns', 'a', 'plain', 'ASCII', 'string', 'usable', 'in', 'URLs', '.'] | train | https://github.com/zikzakmedia/python-mediawiki/blob/7c26732efa520e16c35350815ce98cd7610a0bcb/mediawiki/wikimarkup/__init__.py#L2113-L2146 |
8,064 | awacha/credolib | credolib/utils.py | putlogo | def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
"""
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1], anchor='NW')
logoaxis.set_axis_off()
logoaxis.xaxis.set_visible(False)
logoaxis.yaxis.set_visible(False)
logoaxis.imshow(credo_logo)
figure.subplots_adjust(right=0.98)
figure.sca(curraxis) | python | def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
"""
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1], anchor='NW')
logoaxis.set_axis_off()
logoaxis.xaxis.set_visible(False)
logoaxis.yaxis.set_visible(False)
logoaxis.imshow(credo_logo)
figure.subplots_adjust(right=0.98)
figure.sca(curraxis) | ['def', 'putlogo', '(', 'figure', '=', 'None', ')', ':', 'ip', '=', 'get_ipython', '(', ')', 'if', 'figure', 'is', 'None', ':', 'figure', '=', 'plt', '.', 'gcf', '(', ')', 'curraxis', '=', 'figure', '.', 'gca', '(', ')', 'logoaxis', '=', 'figure', '.', 'add_axes', '(', '[', '0.89', ',', '0.01', ',', '0.1', ',', '0.1', ']', ',', 'anchor', '=', "'NW'", ')', 'logoaxis', '.', 'set_axis_off', '(', ')', 'logoaxis', '.', 'xaxis', '.', 'set_visible', '(', 'False', ')', 'logoaxis', '.', 'yaxis', '.', 'set_visible', '(', 'False', ')', 'logoaxis', '.', 'imshow', '(', 'credo_logo', ')', 'figure', '.', 'subplots_adjust', '(', 'right', '=', '0.98', ')', 'figure', '.', 'sca', '(', 'curraxis', ')'] | Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied). | ['Puts', 'the', 'CREDO', 'logo', 'at', 'the', 'bottom', 'right', 'of', 'the', 'current', 'figure', '(', 'or', 'the', 'figure', 'given', 'by', 'the', 'figure', 'argument', 'if', 'supplied', ')', '.'] | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/utils.py#L16-L30 |
8,065 | sailthru/sailthru-python-client | sailthru/sailthru_client.py | SailthruClient.receive_verify_post | def receive_verify_post(self, post_params):
"""
Returns true if the incoming request is an authenticated verify post.
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'send_id', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
else:
return False
if post_params['action'] != 'verify':
return False
sig = post_params['sig']
post_params = post_params.copy()
del post_params['sig']
if sig != get_signature_hash(post_params, self.secret):
return False
send_response = self.get_send(post_params['send_id'])
try:
send_body = send_response.get_body()
send_json = json.loads(send_body)
if 'email' not in send_body:
return False
if send_json['email'] != post_params['email']:
return False
except ValueError:
return False
return True | python | def receive_verify_post(self, post_params):
"""
Returns true if the incoming request is an authenticated verify post.
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'send_id', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
else:
return False
if post_params['action'] != 'verify':
return False
sig = post_params['sig']
post_params = post_params.copy()
del post_params['sig']
if sig != get_signature_hash(post_params, self.secret):
return False
send_response = self.get_send(post_params['send_id'])
try:
send_body = send_response.get_body()
send_json = json.loads(send_body)
if 'email' not in send_body:
return False
if send_json['email'] != post_params['email']:
return False
except ValueError:
return False
return True | ['def', 'receive_verify_post', '(', 'self', ',', 'post_params', ')', ':', 'if', 'isinstance', '(', 'post_params', ',', 'dict', ')', ':', 'required_params', '=', '[', "'action'", ',', "'email'", ',', "'send_id'", ',', "'sig'", ']', 'if', 'not', 'self', '.', 'check_for_valid_postback_actions', '(', 'required_params', ',', 'post_params', ')', ':', 'return', 'False', 'else', ':', 'return', 'False', 'if', 'post_params', '[', "'action'", ']', '!=', "'verify'", ':', 'return', 'False', 'sig', '=', 'post_params', '[', "'sig'", ']', 'post_params', '=', 'post_params', '.', 'copy', '(', ')', 'del', 'post_params', '[', "'sig'", ']', 'if', 'sig', '!=', 'get_signature_hash', '(', 'post_params', ',', 'self', '.', 'secret', ')', ':', 'return', 'False', 'send_response', '=', 'self', '.', 'get_send', '(', 'post_params', '[', "'send_id'", ']', ')', 'try', ':', 'send_body', '=', 'send_response', '.', 'get_body', '(', ')', 'send_json', '=', 'json', '.', 'loads', '(', 'send_body', ')', 'if', "'email'", 'not', 'in', 'send_body', ':', 'return', 'False', 'if', 'send_json', '[', "'email'", ']', '!=', 'post_params', '[', "'email'", ']', ':', 'return', 'False', 'except', 'ValueError', ':', 'return', 'False', 'return', 'True'] | Returns true if the incoming request is an authenticated verify post. | ['Returns', 'true', 'if', 'the', 'incoming', 'request', 'is', 'an', 'authenticated', 'verify', 'post', '.'] | train | https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L566-L599 |
8,066 | tradenity/python-sdk | tradenity/resources/fixed_rate_shipping.py | FixedRateShipping.create_fixed_rate_shipping | def create_fixed_rate_shipping(cls, fixed_rate_shipping, **kwargs):
"""Create FixedRateShipping
Create a new FixedRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True)
>>> result = thread.get()
:param async bool
:param FixedRateShipping fixed_rate_shipping: Attributes of fixedRateShipping to create (required)
:return: FixedRateShipping
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs)
else:
(data) = cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs)
return data | python | def create_fixed_rate_shipping(cls, fixed_rate_shipping, **kwargs):
"""Create FixedRateShipping
Create a new FixedRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True)
>>> result = thread.get()
:param async bool
:param FixedRateShipping fixed_rate_shipping: Attributes of fixedRateShipping to create (required)
:return: FixedRateShipping
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs)
else:
(data) = cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs)
return data | ['def', 'create_fixed_rate_shipping', '(', 'cls', ',', 'fixed_rate_shipping', ',', '*', '*', 'kwargs', ')', ':', 'kwargs', '[', "'_return_http_data_only'", ']', '=', 'True', 'if', 'kwargs', '.', 'get', '(', "'async'", ')', ':', 'return', 'cls', '.', '_create_fixed_rate_shipping_with_http_info', '(', 'fixed_rate_shipping', ',', '*', '*', 'kwargs', ')', 'else', ':', '(', 'data', ')', '=', 'cls', '.', '_create_fixed_rate_shipping_with_http_info', '(', 'fixed_rate_shipping', ',', '*', '*', 'kwargs', ')', 'return', 'data'] | Create FixedRateShipping
Create a new FixedRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True)
>>> result = thread.get()
:param async bool
:param FixedRateShipping fixed_rate_shipping: Attributes of fixedRateShipping to create (required)
:return: FixedRateShipping
If the method is called asynchronously,
returns the request thread. | ['Create', 'FixedRateShipping'] | train | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/fixed_rate_shipping.py#L461-L481 |
8,067 | Morrolan/surrealism | surrealism.py | __get_sentence | def __get_sentence(counts, sentence_id=None):
"""Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id:
"""
# First of all we need a cursor and a query to retrieve our ID's
cursor = CONN.cursor()
check_query = "select sen_id from sursentences"
# Now we fetch the result of the query and save it into check_result
cursor.execute(check_query)
check_result = cursor.fetchall()
# declare an empty list to be populated below
id_list = []
id_to_fetch = None
# Populate the id_list variable with all of the ID's we retrieved from the database query.
for row in check_result:
id_list.append(row[0])
if sentence_id is not None:
if type(sentence_id) is int:
id_to_fetch = sentence_id
else:
id_to_fetch = random.randint(1, counts['max_sen'])
while id_to_fetch not in id_list:
id_to_fetch = random.randint(1, counts['max_sen'])
query = ("select * from sursentences where sen_id = {0}".format(id_to_fetch))
cursor.execute(query)
result = cursor.fetchone()
# cursor.close()
return result | python | def __get_sentence(counts, sentence_id=None):
"""Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id:
"""
# First of all we need a cursor and a query to retrieve our ID's
cursor = CONN.cursor()
check_query = "select sen_id from sursentences"
# Now we fetch the result of the query and save it into check_result
cursor.execute(check_query)
check_result = cursor.fetchall()
# declare an empty list to be populated below
id_list = []
id_to_fetch = None
# Populate the id_list variable with all of the ID's we retrieved from the database query.
for row in check_result:
id_list.append(row[0])
if sentence_id is not None:
if type(sentence_id) is int:
id_to_fetch = sentence_id
else:
id_to_fetch = random.randint(1, counts['max_sen'])
while id_to_fetch not in id_list:
id_to_fetch = random.randint(1, counts['max_sen'])
query = ("select * from sursentences where sen_id = {0}".format(id_to_fetch))
cursor.execute(query)
result = cursor.fetchone()
# cursor.close()
return result | ['def', '__get_sentence', '(', 'counts', ',', 'sentence_id', '=', 'None', ')', ':', "# First of all we need a cursor and a query to retrieve our ID's", 'cursor', '=', 'CONN', '.', 'cursor', '(', ')', 'check_query', '=', '"select sen_id from sursentences"', '# Now we fetch the result of the query and save it into check_result', 'cursor', '.', 'execute', '(', 'check_query', ')', 'check_result', '=', 'cursor', '.', 'fetchall', '(', ')', '# declare an empty list to be populated below', 'id_list', '=', '[', ']', 'id_to_fetch', '=', 'None', "# Populate the id_list variable with all of the ID's we retrieved from the database query.", 'for', 'row', 'in', 'check_result', ':', 'id_list', '.', 'append', '(', 'row', '[', '0', ']', ')', 'if', 'sentence_id', 'is', 'not', 'None', ':', 'if', 'type', '(', 'sentence_id', ')', 'is', 'int', ':', 'id_to_fetch', '=', 'sentence_id', 'else', ':', 'id_to_fetch', '=', 'random', '.', 'randint', '(', '1', ',', 'counts', '[', "'max_sen'", ']', ')', 'while', 'id_to_fetch', 'not', 'in', 'id_list', ':', 'id_to_fetch', '=', 'random', '.', 'randint', '(', '1', ',', 'counts', '[', "'max_sen'", ']', ')', 'query', '=', '(', '"select * from sursentences where sen_id = {0}"', '.', 'format', '(', 'id_to_fetch', ')', ')', 'cursor', '.', 'execute', '(', 'query', ')', 'result', '=', 'cursor', '.', 'fetchone', '(', ')', '# cursor.close()', 'return', 'result'] | Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id: | ['Let', 's', 'fetch', 'a', 'random', 'sentence', 'that', 'we', 'then', 'need', 'to', 'substitute', 'bits', 'of', '...'] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L327-L364 |
8,068 | coldfix/udiskie | udiskie/cli.py | _EntryPoint.run | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1 | python | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1 | ['def', 'run', '(', 'self', ')', ':', 'self', '.', 'exit_code', '=', '1', 'self', '.', 'mainloop', '=', 'GLib', '.', 'MainLoop', '(', ')', 'try', ':', 'future', '=', 'ensure_future', '(', 'self', '.', '_start_async_tasks', '(', ')', ')', 'future', '.', 'callbacks', '.', 'append', '(', 'self', '.', 'set_exit_code', ')', 'self', '.', 'mainloop', '.', 'run', '(', ')', 'return', 'self', '.', 'exit_code', 'except', 'KeyboardInterrupt', ':', 'return', '1'] | Run the main loop. Returns exit code. | ['Run', 'the', 'main', 'loop', '.', 'Returns', 'exit', 'code', '.'] | train | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L204-L214 |
8,069 | fronzbot/blinkpy | blinkpy/helpers/util.py | attempt_reauthorization | def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
_LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token(is_retry=True)
return headers | python | def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
_LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token(is_retry=True)
return headers | ['def', 'attempt_reauthorization', '(', 'blink', ')', ':', '_LOGGER', '.', 'info', '(', '"Auth token expired, attempting reauthorization."', ')', 'headers', '=', 'blink', '.', 'get_auth_token', '(', 'is_retry', '=', 'True', ')', 'return', 'headers'] | Attempt to refresh auth token and links. | ['Attempt', 'to', 'refresh', 'auth', 'token', 'and', 'links', '.'] | train | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/helpers/util.py#L36-L40 |
8,070 | BernardFW/bernard | src/bernard/platforms/facebook/layers.py | MessagingType.serialize | def serialize(self):
"""
Generates the messaging-type-related part of the message dictionary.
"""
if self.response is not None:
return {'messaging_type': 'RESPONSE'}
if self.update is not None:
return {'messaging_type': 'UPDATE'}
if self.tag is not None:
return {
'messaging_type': 'MESSAGE_TAG',
'tag': self.tag.value,
}
if self.subscription is not None:
return {'messaging_type': 'NON_PROMOTIONAL_SUBSCRIPTION'} | python | def serialize(self):
"""
Generates the messaging-type-related part of the message dictionary.
"""
if self.response is not None:
return {'messaging_type': 'RESPONSE'}
if self.update is not None:
return {'messaging_type': 'UPDATE'}
if self.tag is not None:
return {
'messaging_type': 'MESSAGE_TAG',
'tag': self.tag.value,
}
if self.subscription is not None:
return {'messaging_type': 'NON_PROMOTIONAL_SUBSCRIPTION'} | ['def', 'serialize', '(', 'self', ')', ':', 'if', 'self', '.', 'response', 'is', 'not', 'None', ':', 'return', '{', "'messaging_type'", ':', "'RESPONSE'", '}', 'if', 'self', '.', 'update', 'is', 'not', 'None', ':', 'return', '{', "'messaging_type'", ':', "'UPDATE'", '}', 'if', 'self', '.', 'tag', 'is', 'not', 'None', ':', 'return', '{', "'messaging_type'", ':', "'MESSAGE_TAG'", ',', "'tag'", ':', 'self', '.', 'tag', '.', 'value', ',', '}', 'if', 'self', '.', 'subscription', 'is', 'not', 'None', ':', 'return', '{', "'messaging_type'", ':', "'NON_PROMOTIONAL_SUBSCRIPTION'", '}'] | Generates the messaging-type-related part of the message dictionary. | ['Generates', 'the', 'messaging', '-', 'type', '-', 'related', 'part', 'of', 'the', 'message', 'dictionary', '.'] | train | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/layers.py#L102-L120 |
8,071 | Cue/scales | src/greplin/scales/flaskhandler.py | statsHandler | def statsHandler(serverName, path=''):
"""Renders a GET request, by showing this nodes stats and children."""
path = path.lstrip('/')
parts = path.split('/')
if not parts[0]:
parts = parts[1:]
statDict = util.lookup(scales.getStats(), parts)
if statDict is None:
abort(404, 'No stats found with path /%s' % '/'.join(parts))
output = StringIO()
outputFormat = request.args.get('format', 'html')
query = request.args.get('query', None)
if outputFormat == 'json':
formats.jsonFormat(output, statDict, query)
elif outputFormat == 'prettyjson':
formats.jsonFormat(output, statDict, query, pretty=True)
else:
formats.htmlHeader(output, '/' + path, serverName, query)
formats.htmlFormat(output, tuple(parts), statDict, query)
return output.getvalue() | python | def statsHandler(serverName, path=''):
"""Renders a GET request, by showing this nodes stats and children."""
path = path.lstrip('/')
parts = path.split('/')
if not parts[0]:
parts = parts[1:]
statDict = util.lookup(scales.getStats(), parts)
if statDict is None:
abort(404, 'No stats found with path /%s' % '/'.join(parts))
output = StringIO()
outputFormat = request.args.get('format', 'html')
query = request.args.get('query', None)
if outputFormat == 'json':
formats.jsonFormat(output, statDict, query)
elif outputFormat == 'prettyjson':
formats.jsonFormat(output, statDict, query, pretty=True)
else:
formats.htmlHeader(output, '/' + path, serverName, query)
formats.htmlFormat(output, tuple(parts), statDict, query)
return output.getvalue() | ['def', 'statsHandler', '(', 'serverName', ',', 'path', '=', "''", ')', ':', 'path', '=', 'path', '.', 'lstrip', '(', "'/'", ')', 'parts', '=', 'path', '.', 'split', '(', "'/'", ')', 'if', 'not', 'parts', '[', '0', ']', ':', 'parts', '=', 'parts', '[', '1', ':', ']', 'statDict', '=', 'util', '.', 'lookup', '(', 'scales', '.', 'getStats', '(', ')', ',', 'parts', ')', 'if', 'statDict', 'is', 'None', ':', 'abort', '(', '404', ',', "'No stats found with path /%s'", '%', "'/'", '.', 'join', '(', 'parts', ')', ')', 'output', '=', 'StringIO', '(', ')', 'outputFormat', '=', 'request', '.', 'args', '.', 'get', '(', "'format'", ',', "'html'", ')', 'query', '=', 'request', '.', 'args', '.', 'get', '(', "'query'", ',', 'None', ')', 'if', 'outputFormat', '==', "'json'", ':', 'formats', '.', 'jsonFormat', '(', 'output', ',', 'statDict', ',', 'query', ')', 'elif', 'outputFormat', '==', "'prettyjson'", ':', 'formats', '.', 'jsonFormat', '(', 'output', ',', 'statDict', ',', 'query', ',', 'pretty', '=', 'True', ')', 'else', ':', 'formats', '.', 'htmlHeader', '(', 'output', ',', "'/'", '+', 'path', ',', 'serverName', ',', 'query', ')', 'formats', '.', 'htmlFormat', '(', 'output', ',', 'tuple', '(', 'parts', ')', ',', 'statDict', ',', 'query', ')', 'return', 'output', '.', 'getvalue', '(', ')'] | Renders a GET request, by showing this nodes stats and children. | ['Renders', 'a', 'GET', 'request', 'by', 'showing', 'this', 'nodes', 'stats', 'and', 'children', '.'] | train | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/flaskhandler.py#L28-L50 |
8,072 | delph-in/pydelphin | delphin/mrs/penman.py | dumps | def dumps(xs, model=None, properties=False, indent=True, **kwargs):
"""
Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` or `None`,
don't indent; if a non-negative integer N, indent N spaces
per level
Returns:
the PENMAN serialization of *xs*
"""
xs = list(xs)
if not xs:
return ''
given_class = xs[0].__class__ # assume they are all the same
if model is None:
model = xs[0].__class__
if not hasattr(model, 'to_triples'):
raise TypeError(
'{} class does not implement to_triples()'.format(model.__name__)
)
# convert MRS to DMRS if necessary; EDS cannot convert
if given_class.__name__ in ('Mrs', 'Xmrs'):
xs = [model.from_xmrs(x, **kwargs) for x in xs]
elif given_class.__name__ == 'Eds' and model.__name__ != 'Eds':
raise ValueError('Cannot convert EDS to non-EDS')
codec = XMRSCodec()
graphs = [
codec.triples_to_graph(model.to_triples(x, properties=properties))
for x in xs
]
if 'pretty_print' in kwargs:
indent = kwargs['pretty_print']
return penman.dumps(graphs, cls=XMRSCodec, indent=indent) | python | def dumps(xs, model=None, properties=False, indent=True, **kwargs):
"""
Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` or `None`,
don't indent; if a non-negative integer N, indent N spaces
per level
Returns:
the PENMAN serialization of *xs*
"""
xs = list(xs)
if not xs:
return ''
given_class = xs[0].__class__ # assume they are all the same
if model is None:
model = xs[0].__class__
if not hasattr(model, 'to_triples'):
raise TypeError(
'{} class does not implement to_triples()'.format(model.__name__)
)
# convert MRS to DMRS if necessary; EDS cannot convert
if given_class.__name__ in ('Mrs', 'Xmrs'):
xs = [model.from_xmrs(x, **kwargs) for x in xs]
elif given_class.__name__ == 'Eds' and model.__name__ != 'Eds':
raise ValueError('Cannot convert EDS to non-EDS')
codec = XMRSCodec()
graphs = [
codec.triples_to_graph(model.to_triples(x, properties=properties))
for x in xs
]
if 'pretty_print' in kwargs:
indent = kwargs['pretty_print']
return penman.dumps(graphs, cls=XMRSCodec, indent=indent) | ['def', 'dumps', '(', 'xs', ',', 'model', '=', 'None', ',', 'properties', '=', 'False', ',', 'indent', '=', 'True', ',', '*', '*', 'kwargs', ')', ':', 'xs', '=', 'list', '(', 'xs', ')', 'if', 'not', 'xs', ':', 'return', "''", 'given_class', '=', 'xs', '[', '0', ']', '.', '__class__', '# assume they are all the same', 'if', 'model', 'is', 'None', ':', 'model', '=', 'xs', '[', '0', ']', '.', '__class__', 'if', 'not', 'hasattr', '(', 'model', ',', "'to_triples'", ')', ':', 'raise', 'TypeError', '(', "'{} class does not implement to_triples()'", '.', 'format', '(', 'model', '.', '__name__', ')', ')', '# convert MRS to DMRS if necessary; EDS cannot convert', 'if', 'given_class', '.', '__name__', 'in', '(', "'Mrs'", ',', "'Xmrs'", ')', ':', 'xs', '=', '[', 'model', '.', 'from_xmrs', '(', 'x', ',', '*', '*', 'kwargs', ')', 'for', 'x', 'in', 'xs', ']', 'elif', 'given_class', '.', '__name__', '==', "'Eds'", 'and', 'model', '.', '__name__', '!=', "'Eds'", ':', 'raise', 'ValueError', '(', "'Cannot convert EDS to non-EDS'", ')', 'codec', '=', 'XMRSCodec', '(', ')', 'graphs', '=', '[', 'codec', '.', 'triples_to_graph', '(', 'model', '.', 'to_triples', '(', 'x', ',', 'properties', '=', 'properties', ')', ')', 'for', 'x', 'in', 'xs', ']', 'if', "'pretty_print'", 'in', 'kwargs', ':', 'indent', '=', 'kwargs', '[', "'pretty_print'", ']', 'return', 'penman', '.', 'dumps', '(', 'graphs', ',', 'cls', '=', 'XMRSCodec', ',', 'indent', '=', 'indent', ')'] | Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` or `None`,
don't indent; if a non-negative integer N, indent N spaces
per level
Returns:
the PENMAN serialization of *xs* | ['Serialize', 'Xmrs', '(', 'or', 'subclass', ')', 'objects', 'to', 'PENMAN', 'notation'] | train | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/penman.py#L83-L127 |
8,073 | moralrecordings/mrcrowbar | mrcrowbar/utils.py | pixdump | def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ):
"""Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Width of image to render in pixels (default: 64)
height
Height of image to render in pixels (default: auto)
palette
List of Colours to use (default: test palette)
"""
for line in pixdump_iter( source, start, end, length, width, height, palette ):
print( line ) | python | def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ):
"""Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Width of image to render in pixels (default: 64)
height
Height of image to render in pixels (default: auto)
palette
List of Colours to use (default: test palette)
"""
for line in pixdump_iter( source, start, end, length, width, height, palette ):
print( line ) | ['def', 'pixdump', '(', 'source', ',', 'start', '=', 'None', ',', 'end', '=', 'None', ',', 'length', '=', 'None', ',', 'width', '=', '64', ',', 'height', '=', 'None', ',', 'palette', '=', 'None', ')', ':', 'for', 'line', 'in', 'pixdump_iter', '(', 'source', ',', 'start', ',', 'end', ',', 'length', ',', 'width', ',', 'height', ',', 'palette', ')', ':', 'print', '(', 'line', ')'] | Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Width of image to render in pixels (default: 64)
height
Height of image to render in pixels (default: auto)
palette
List of Colours to use (default: test palette) | ['Print', 'the', 'contents', 'of', 'a', 'byte', 'string', 'as', 'a', '256', 'colour', 'image', '.'] | train | https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/utils.py#L450-L476 |
8,074 | sigsep/sigsep-mus-eval | museval/__init__.py | pad_or_truncate | def pad_or_truncate(
audio_reference,
audio_estimates
):
"""Pad or truncate estimates by duration of references:
- If reference > estimates: add zeros at the and of the estimated signal
- If estimates > references: truncate estimates to duration of references
Parameters
----------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources
Returns
-------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources
"""
est_shape = audio_estimates.shape
ref_shape = audio_reference.shape
if est_shape[1] != ref_shape[1]:
if est_shape[1] >= ref_shape[1]:
audio_estimates = audio_estimates[:, :ref_shape[1], :]
else:
# pad end with zeros
audio_estimates = np.pad(
audio_estimates,
[
(0, 0),
(0, ref_shape[1] - est_shape[1]),
(0, 0)
],
mode='constant'
)
return audio_reference, audio_estimates | python | def pad_or_truncate(
audio_reference,
audio_estimates
):
"""Pad or truncate estimates by duration of references:
- If reference > estimates: add zeros at the and of the estimated signal
- If estimates > references: truncate estimates to duration of references
Parameters
----------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources
Returns
-------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources
"""
est_shape = audio_estimates.shape
ref_shape = audio_reference.shape
if est_shape[1] != ref_shape[1]:
if est_shape[1] >= ref_shape[1]:
audio_estimates = audio_estimates[:, :ref_shape[1], :]
else:
# pad end with zeros
audio_estimates = np.pad(
audio_estimates,
[
(0, 0),
(0, ref_shape[1] - est_shape[1]),
(0, 0)
],
mode='constant'
)
return audio_reference, audio_estimates | ['def', 'pad_or_truncate', '(', 'audio_reference', ',', 'audio_estimates', ')', ':', 'est_shape', '=', 'audio_estimates', '.', 'shape', 'ref_shape', '=', 'audio_reference', '.', 'shape', 'if', 'est_shape', '[', '1', ']', '!=', 'ref_shape', '[', '1', ']', ':', 'if', 'est_shape', '[', '1', ']', '>=', 'ref_shape', '[', '1', ']', ':', 'audio_estimates', '=', 'audio_estimates', '[', ':', ',', ':', 'ref_shape', '[', '1', ']', ',', ':', ']', 'else', ':', '# pad end with zeros', 'audio_estimates', '=', 'np', '.', 'pad', '(', 'audio_estimates', ',', '[', '(', '0', ',', '0', ')', ',', '(', '0', ',', 'ref_shape', '[', '1', ']', '-', 'est_shape', '[', '1', ']', ')', ',', '(', '0', ',', '0', ')', ']', ',', 'mode', '=', "'constant'", ')', 'return', 'audio_reference', ',', 'audio_estimates'] | Pad or truncate estimates by duration of references:
- If reference > estimates: add zeros at the and of the estimated signal
- If estimates > references: truncate estimates to duration of references
Parameters
----------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources
Returns
-------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing estimated sources | ['Pad', 'or', 'truncate', 'estimates', 'by', 'duration', 'of', 'references', ':', '-', 'If', 'reference', '>', 'estimates', ':', 'add', 'zeros', 'at', 'the', 'and', 'of', 'the', 'estimated', 'signal', '-', 'If', 'estimates', '>', 'references', ':', 'truncate', 'estimates', 'to', 'duration', 'of', 'references'] | train | https://github.com/sigsep/sigsep-mus-eval/blob/a7c9af3647f0c0bb9bbaeccec0b1a6a9e09d1e2d/museval/__init__.py#L466-L504 |
8,075 | pantsbuild/pants | src/python/pants/base/run_info.py | RunInfo.add_scm_info | def add_scm_info(self):
"""Adds SCM-related info."""
scm = get_scm()
if scm:
revision = scm.commit_id
branch = scm.branch_name or revision
else:
revision, branch = 'none', 'none'
self.add_infos(('revision', revision), ('branch', branch)) | python | def add_scm_info(self):
"""Adds SCM-related info."""
scm = get_scm()
if scm:
revision = scm.commit_id
branch = scm.branch_name or revision
else:
revision, branch = 'none', 'none'
self.add_infos(('revision', revision), ('branch', branch)) | ['def', 'add_scm_info', '(', 'self', ')', ':', 'scm', '=', 'get_scm', '(', ')', 'if', 'scm', ':', 'revision', '=', 'scm', '.', 'commit_id', 'branch', '=', 'scm', '.', 'branch_name', 'or', 'revision', 'else', ':', 'revision', ',', 'branch', '=', "'none'", ',', "'none'", 'self', '.', 'add_infos', '(', '(', "'revision'", ',', 'revision', ')', ',', '(', "'branch'", ',', 'branch', ')', ')'] | Adds SCM-related info. | ['Adds', 'SCM', '-', 'related', 'info', '.'] | train | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/run_info.py#L90-L98 |
8,076 | jobovy/galpy | galpy/orbit/FullOrbit.py | _rectForce | def _rectForce(x,pot,t=0.):
"""
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU)
"""
#x is rectangular so calculate R and phi
R= nu.sqrt(x[0]**2.+x[1]**2.)
phi= nu.arccos(x[0]/R)
sinphi= x[1]/R
cosphi= x[0]/R
if x[1] < 0.: phi= 2.*nu.pi-phi
#calculate forces
Rforce= _evaluateRforces(pot,R,x[2],phi=phi,t=t)
phiforce= _evaluatephiforces(pot,R,x[2],phi=phi,t=t)
return nu.array([cosphi*Rforce-1./R*sinphi*phiforce,
sinphi*Rforce+1./R*cosphi*phiforce,
_evaluatezforces(pot,R,x[2],phi=phi,t=t)]) | python | def _rectForce(x,pot,t=0.):
"""
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU)
"""
#x is rectangular so calculate R and phi
R= nu.sqrt(x[0]**2.+x[1]**2.)
phi= nu.arccos(x[0]/R)
sinphi= x[1]/R
cosphi= x[0]/R
if x[1] < 0.: phi= 2.*nu.pi-phi
#calculate forces
Rforce= _evaluateRforces(pot,R,x[2],phi=phi,t=t)
phiforce= _evaluatephiforces(pot,R,x[2],phi=phi,t=t)
return nu.array([cosphi*Rforce-1./R*sinphi*phiforce,
sinphi*Rforce+1./R*cosphi*phiforce,
_evaluatezforces(pot,R,x[2],phi=phi,t=t)]) | ['def', '_rectForce', '(', 'x', ',', 'pot', ',', 't', '=', '0.', ')', ':', '#x is rectangular so calculate R and phi', 'R', '=', 'nu', '.', 'sqrt', '(', 'x', '[', '0', ']', '**', '2.', '+', 'x', '[', '1', ']', '**', '2.', ')', 'phi', '=', 'nu', '.', 'arccos', '(', 'x', '[', '0', ']', '/', 'R', ')', 'sinphi', '=', 'x', '[', '1', ']', '/', 'R', 'cosphi', '=', 'x', '[', '0', ']', '/', 'R', 'if', 'x', '[', '1', ']', '<', '0.', ':', 'phi', '=', '2.', '*', 'nu', '.', 'pi', '-', 'phi', '#calculate forces', 'Rforce', '=', '_evaluateRforces', '(', 'pot', ',', 'R', ',', 'x', '[', '2', ']', ',', 'phi', '=', 'phi', ',', 't', '=', 't', ')', 'phiforce', '=', '_evaluatephiforces', '(', 'pot', ',', 'R', ',', 'x', '[', '2', ']', ',', 'phi', '=', 'phi', ',', 't', '=', 't', ')', 'return', 'nu', '.', 'array', '(', '[', 'cosphi', '*', 'Rforce', '-', '1.', '/', 'R', '*', 'sinphi', '*', 'phiforce', ',', 'sinphi', '*', 'Rforce', '+', '1.', '/', 'R', '*', 'cosphi', '*', 'phiforce', ',', '_evaluatezforces', '(', 'pot', ',', 'R', ',', 'x', '[', '2', ']', ',', 'phi', '=', 'phi', ',', 't', '=', 't', ')', ']', ')'] | NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU) | ['NAME', ':', '_rectForce', 'PURPOSE', ':', 'returns', 'the', 'force', 'in', 'the', 'rectangular', 'frame', 'INPUT', ':', 'x', '-', 'current', 'position', 't', '-', 'current', 'time', 'pot', '-', '(', 'list', 'of', ')', 'Potential', 'instance', '(', 's', ')', 'OUTPUT', ':', 'force', 'HISTORY', ':', '2011', '-', '02', '-', '02', '-', 'Written', '-', 'Bovy', '(', 'NYU', ')'] | train | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/FullOrbit.py#L693-L719 |
8,077 | taddeus/wspy | frame.py | Frame.fragment | def fragment(self, fragment_size, mask=False):
"""
Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final = True. Thus, this function returns a list containing
at least a single frame.
`fragment_size` indicates the maximum payload size of each fragment.
The payload of the original frame is split into one or more parts, and
each part is converted to a Frame instance.
`mask` is a boolean (default False) indicating whether the payloads
should be masked. If True, each frame is assigned a randomly generated
masking key.
"""
frames = []
for start in xrange(0, len(self.payload), fragment_size):
payload = self.payload[start:start + fragment_size]
frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask,
final=False))
frames[0].opcode = self.opcode
frames[-1].final = True
return frames | python | def fragment(self, fragment_size, mask=False):
"""
Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final = True. Thus, this function returns a list containing
at least a single frame.
`fragment_size` indicates the maximum payload size of each fragment.
The payload of the original frame is split into one or more parts, and
each part is converted to a Frame instance.
`mask` is a boolean (default False) indicating whether the payloads
should be masked. If True, each frame is assigned a randomly generated
masking key.
"""
frames = []
for start in xrange(0, len(self.payload), fragment_size):
payload = self.payload[start:start + fragment_size]
frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask,
final=False))
frames[0].opcode = self.opcode
frames[-1].final = True
return frames | ['def', 'fragment', '(', 'self', ',', 'fragment_size', ',', 'mask', '=', 'False', ')', ':', 'frames', '=', '[', ']', 'for', 'start', 'in', 'xrange', '(', '0', ',', 'len', '(', 'self', '.', 'payload', ')', ',', 'fragment_size', ')', ':', 'payload', '=', 'self', '.', 'payload', '[', 'start', ':', 'start', '+', 'fragment_size', ']', 'frames', '.', 'append', '(', 'Frame', '(', 'OPCODE_CONTINUATION', ',', 'payload', ',', 'mask', '=', 'mask', ',', 'final', '=', 'False', ')', ')', 'frames', '[', '0', ']', '.', 'opcode', '=', 'self', '.', 'opcode', 'frames', '[', '-', '1', ']', '.', 'final', '=', 'True', 'return', 'frames'] | Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final = True. Thus, this function returns a list containing
at least a single frame.
`fragment_size` indicates the maximum payload size of each fragment.
The payload of the original frame is split into one or more parts, and
each part is converted to a Frame instance.
`mask` is a boolean (default False) indicating whether the payloads
should be masked. If True, each frame is assigned a randomly generated
masking key. | ['Fragment', 'the', 'frame', 'into', 'a', 'chain', 'of', 'fragment', 'frames', ':', '-', 'An', 'initial', 'frame', 'with', 'non', '-', 'zero', 'opcode', '-', 'Zero', 'or', 'more', 'frames', 'with', 'opcode', '=', '0', 'and', 'final', '=', 'False', '-', 'A', 'final', 'frame', 'with', 'opcode', '=', '0', 'and', 'final', '=', 'True'] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/frame.py#L115-L144 |
8,078 | Robpol86/libnl | libnl/socket_.py | nl_socket_alloc | def nl_socket_alloc(cb=None):
"""Allocate new Netlink socket. Does not yet actually open a socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206
Also has code for generating local port once.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123
Keyword arguments:
cb -- custom callback handler.
Returns:
Newly allocated Netlink socket (nl_sock class instance) or None.
"""
# Allocate the callback.
cb = cb or nl_cb_alloc(default_cb)
if not cb:
return None
# Allocate the socket.
sk = nl_sock()
sk.s_cb = cb
sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1)
sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1)
sk.s_seq_expect = sk.s_seq_next = int(time.time())
sk.s_flags = NL_OWN_PORT # The port is 0 (unspecified), meaning NL_OWN_PORT.
# Generate local port.
nl_socket_get_local_port(sk) # I didn't find this in the C source, but during testing I saw this behavior.
return sk | python | def nl_socket_alloc(cb=None):
"""Allocate new Netlink socket. Does not yet actually open a socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206
Also has code for generating local port once.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123
Keyword arguments:
cb -- custom callback handler.
Returns:
Newly allocated Netlink socket (nl_sock class instance) or None.
"""
# Allocate the callback.
cb = cb or nl_cb_alloc(default_cb)
if not cb:
return None
# Allocate the socket.
sk = nl_sock()
sk.s_cb = cb
sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1)
sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1)
sk.s_seq_expect = sk.s_seq_next = int(time.time())
sk.s_flags = NL_OWN_PORT # The port is 0 (unspecified), meaning NL_OWN_PORT.
# Generate local port.
nl_socket_get_local_port(sk) # I didn't find this in the C source, but during testing I saw this behavior.
return sk | ['def', 'nl_socket_alloc', '(', 'cb', '=', 'None', ')', ':', '# Allocate the callback.', 'cb', '=', 'cb', 'or', 'nl_cb_alloc', '(', 'default_cb', ')', 'if', 'not', 'cb', ':', 'return', 'None', '# Allocate the socket.', 'sk', '=', 'nl_sock', '(', ')', 'sk', '.', 's_cb', '=', 'cb', 'sk', '.', 's_local', '.', 'nl_family', '=', 'getattr', '(', 'socket', ',', "'AF_NETLINK'", ',', '-', '1', ')', 'sk', '.', 's_peer', '.', 'nl_family', '=', 'getattr', '(', 'socket', ',', "'AF_NETLINK'", ',', '-', '1', ')', 'sk', '.', 's_seq_expect', '=', 'sk', '.', 's_seq_next', '=', 'int', '(', 'time', '.', 'time', '(', ')', ')', 'sk', '.', 's_flags', '=', 'NL_OWN_PORT', '# The port is 0 (unspecified), meaning NL_OWN_PORT.', '# Generate local port.', 'nl_socket_get_local_port', '(', 'sk', ')', "# I didn't find this in the C source, but during testing I saw this behavior.", 'return', 'sk'] | Allocate new Netlink socket. Does not yet actually open a socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206
Also has code for generating local port once.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123
Keyword arguments:
cb -- custom callback handler.
Returns:
Newly allocated Netlink socket (nl_sock class instance) or None. | ['Allocate', 'new', 'Netlink', 'socket', '.', 'Does', 'not', 'yet', 'actually', 'open', 'a', 'socket', '.'] | train | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/socket_.py#L64-L94 |
8,079 | boppreh/keyboard | keyboard/_darwinmouse.py | move_to | def move_to(x, y):
""" Sets the mouse's location to the specified coordinates. """
for b in _button_state:
if _button_state[b]:
e = Quartz.CGEventCreateMouseEvent(
None,
_button_mapping[b][3], # Drag Event
(x, y),
_button_mapping[b][0])
break
else:
e = Quartz.CGEventCreateMouseEvent(
None,
Quartz.kCGEventMouseMoved,
(x, y),
Quartz.kCGMouseButtonLeft)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, e) | python | def move_to(x, y):
""" Sets the mouse's location to the specified coordinates. """
for b in _button_state:
if _button_state[b]:
e = Quartz.CGEventCreateMouseEvent(
None,
_button_mapping[b][3], # Drag Event
(x, y),
_button_mapping[b][0])
break
else:
e = Quartz.CGEventCreateMouseEvent(
None,
Quartz.kCGEventMouseMoved,
(x, y),
Quartz.kCGMouseButtonLeft)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, e) | ['def', 'move_to', '(', 'x', ',', 'y', ')', ':', 'for', 'b', 'in', '_button_state', ':', 'if', '_button_state', '[', 'b', ']', ':', 'e', '=', 'Quartz', '.', 'CGEventCreateMouseEvent', '(', 'None', ',', '_button_mapping', '[', 'b', ']', '[', '3', ']', ',', '# Drag Event', '(', 'x', ',', 'y', ')', ',', '_button_mapping', '[', 'b', ']', '[', '0', ']', ')', 'break', 'else', ':', 'e', '=', 'Quartz', '.', 'CGEventCreateMouseEvent', '(', 'None', ',', 'Quartz', '.', 'kCGEventMouseMoved', ',', '(', 'x', ',', 'y', ')', ',', 'Quartz', '.', 'kCGMouseButtonLeft', ')', 'Quartz', '.', 'CGEventPost', '(', 'Quartz', '.', 'kCGHIDEventTap', ',', 'e', ')'] | Sets the mouse's location to the specified coordinates. | ['Sets', 'the', 'mouse', 's', 'location', 'to', 'the', 'specified', 'coordinates', '.'] | train | https://github.com/boppreh/keyboard/blob/dbb73dfff484f733d5fed8dbc53301af5b6c7f50/keyboard/_darwinmouse.py#L151-L167 |
8,080 | peterbrittain/asciimatics | asciimatics/utilities.py | readable_mem | def readable_mem(mem):
"""
:param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number.
"""
for suffix in ["", "K", "M", "G", "T"]:
if mem < 10000:
return "{}{}".format(int(mem), suffix)
mem /= 1024
return "{}P".format(int(mem)) | python | def readable_mem(mem):
"""
:param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number.
"""
for suffix in ["", "K", "M", "G", "T"]:
if mem < 10000:
return "{}{}".format(int(mem), suffix)
mem /= 1024
return "{}P".format(int(mem)) | ['def', 'readable_mem', '(', 'mem', ')', ':', 'for', 'suffix', 'in', '[', '""', ',', '"K"', ',', '"M"', ',', '"G"', ',', '"T"', ']', ':', 'if', 'mem', '<', '10000', ':', 'return', '"{}{}"', '.', 'format', '(', 'int', '(', 'mem', ')', ',', 'suffix', ')', 'mem', '/=', '1024', 'return', '"{}P"', '.', 'format', '(', 'int', '(', 'mem', ')', ')'] | :param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number. | [':', 'param', 'mem', ':', 'An', 'integer', 'number', 'of', 'bytes', 'to', 'convert', 'to', 'human', '-', 'readable', 'form', '.', ':', 'return', ':', 'A', 'human', '-', 'readable', 'string', 'representation', 'of', 'the', 'number', '.'] | train | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/utilities.py#L12-L21 |
8,081 | mitsei/dlkit | dlkit/json_/learning/sessions.py | ActivityLookupSession.get_activities_by_ids | def get_activities_by_ids(self, activity_ids):
"""Gets an ``ActivityList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
activities specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccessible. Otherwise,
inaccessible ``Activities`` may be omitted from the list and may
present the elements in any order including returning a unique
set.
arg: activity_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ActivityList) - the returned ``Activity``
list
raise: NotFound - an ``Id was`` not found
raise: NullArgument - ``activity_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_ids
# NOTE: This implementation currently ignores plenary view
collection = JSONClientValidated('learning',
collection='Activity',
runtime=self._runtime)
object_id_list = []
for i in activity_ids:
object_id_list.append(ObjectId(self._get_id(i, 'learning').get_identifier()))
result = collection.find(
dict({'_id': {'$in': object_id_list}},
**self._view_filter()))
result = list(result)
sorted_result = []
for object_id in object_id_list:
for object_map in result:
if object_map['_id'] == object_id:
sorted_result.append(object_map)
break
return objects.ActivityList(sorted_result, runtime=self._runtime, proxy=self._proxy) | python | def get_activities_by_ids(self, activity_ids):
"""Gets an ``ActivityList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
activities specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccessible. Otherwise,
inaccessible ``Activities`` may be omitted from the list and may
present the elements in any order including returning a unique
set.
arg: activity_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ActivityList) - the returned ``Activity``
list
raise: NotFound - an ``Id was`` not found
raise: NullArgument - ``activity_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_ids
# NOTE: This implementation currently ignores plenary view
collection = JSONClientValidated('learning',
collection='Activity',
runtime=self._runtime)
object_id_list = []
for i in activity_ids:
object_id_list.append(ObjectId(self._get_id(i, 'learning').get_identifier()))
result = collection.find(
dict({'_id': {'$in': object_id_list}},
**self._view_filter()))
result = list(result)
sorted_result = []
for object_id in object_id_list:
for object_map in result:
if object_map['_id'] == object_id:
sorted_result.append(object_map)
break
return objects.ActivityList(sorted_result, runtime=self._runtime, proxy=self._proxy) | ['def', 'get_activities_by_ids', '(', 'self', ',', 'activity_ids', ')', ':', '# Implemented from template for', '# osid.resource.ResourceLookupSession.get_resources_by_ids', '# NOTE: This implementation currently ignores plenary view', 'collection', '=', 'JSONClientValidated', '(', "'learning'", ',', 'collection', '=', "'Activity'", ',', 'runtime', '=', 'self', '.', '_runtime', ')', 'object_id_list', '=', '[', ']', 'for', 'i', 'in', 'activity_ids', ':', 'object_id_list', '.', 'append', '(', 'ObjectId', '(', 'self', '.', '_get_id', '(', 'i', ',', "'learning'", ')', '.', 'get_identifier', '(', ')', ')', ')', 'result', '=', 'collection', '.', 'find', '(', 'dict', '(', '{', "'_id'", ':', '{', "'$in'", ':', 'object_id_list', '}', '}', ',', '*', '*', 'self', '.', '_view_filter', '(', ')', ')', ')', 'result', '=', 'list', '(', 'result', ')', 'sorted_result', '=', '[', ']', 'for', 'object_id', 'in', 'object_id_list', ':', 'for', 'object_map', 'in', 'result', ':', 'if', 'object_map', '[', "'_id'", ']', '==', 'object_id', ':', 'sorted_result', '.', 'append', '(', 'object_map', ')', 'break', 'return', 'objects', '.', 'ActivityList', '(', 'sorted_result', ',', 'runtime', '=', 'self', '.', '_runtime', ',', 'proxy', '=', 'self', '.', '_proxy', ')'] | Gets an ``ActivityList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
activities specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccessible. Otherwise,
inaccessible ``Activities`` may be omitted from the list and may
present the elements in any order including returning a unique
set.
arg: activity_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ActivityList) - the returned ``Activity``
list
raise: NotFound - an ``Id was`` not found
raise: NullArgument - ``activity_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | ['Gets', 'an', 'ActivityList', 'corresponding', 'to', 'the', 'given', 'IdList', '.'] | train | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L2600-L2641 |
8,082 | mitsei/dlkit | dlkit/aws_adapter/repository/sessions.py | AssetAdminSession.update_asset | def update_asset(self, asset_form=None):
"""Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_form`` did not originate from
``get_asset_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
return Asset(self._provider_session.update_asset(asset_form), self._config_map) | python | def update_asset(self, asset_form=None):
"""Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_form`` did not originate from
``get_asset_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
return Asset(self._provider_session.update_asset(asset_form), self._config_map) | ['def', 'update_asset', '(', 'self', ',', 'asset_form', '=', 'None', ')', ':', 'return', 'Asset', '(', 'self', '.', '_provider_session', '.', 'update_asset', '(', 'asset_form', ')', ',', 'self', '.', '_config_map', ')'] | Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_form`` did not originate from
``get_asset_form_for_update()``
*compliance: mandatory -- This method must be implemented.* | ['Updates', 'an', 'existing', 'asset', '.'] | train | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/sessions.py#L986-L1002 |
8,083 | manns/pyspread | pyspread/src/lib/vlc.py | module_description_list | def module_description_list(head):
"""Convert a ModuleDescription linked list to a Python list (and release the former).
"""
r = []
if head:
item = head
while item:
item = item.contents
r.append((item.name, item.shortname, item.longname, item.help))
item = item.next
libvlc_module_description_list_release(head)
return r | python | def module_description_list(head):
"""Convert a ModuleDescription linked list to a Python list (and release the former).
"""
r = []
if head:
item = head
while item:
item = item.contents
r.append((item.name, item.shortname, item.longname, item.help))
item = item.next
libvlc_module_description_list_release(head)
return r | ['def', 'module_description_list', '(', 'head', ')', ':', 'r', '=', '[', ']', 'if', 'head', ':', 'item', '=', 'head', 'while', 'item', ':', 'item', '=', 'item', '.', 'contents', 'r', '.', 'append', '(', '(', 'item', '.', 'name', ',', 'item', '.', 'shortname', ',', 'item', '.', 'longname', ',', 'item', '.', 'help', ')', ')', 'item', '=', 'item', '.', 'next', 'libvlc_module_description_list_release', '(', 'head', ')', 'return', 'r'] | Convert a ModuleDescription linked list to a Python list (and release the former). | ['Convert', 'a', 'ModuleDescription', 'linked', 'list', 'to', 'a', 'Python', 'list', '(', 'and', 'release', 'the', 'former', ')', '.'] | train | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L1376-L1387 |
8,084 | bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | ExportAnnualOverview.is_all_field_none | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._year is not None:
return False
if self._alias_user is not None:
return False
return True | python | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._year is not None:
return False
if self._alias_user is not None:
return False
return True | ['def', 'is_all_field_none', '(', 'self', ')', ':', 'if', 'self', '.', '_id_', 'is', 'not', 'None', ':', 'return', 'False', 'if', 'self', '.', '_created', 'is', 'not', 'None', ':', 'return', 'False', 'if', 'self', '.', '_updated', 'is', 'not', 'None', ':', 'return', 'False', 'if', 'self', '.', '_year', 'is', 'not', 'None', ':', 'return', 'False', 'if', 'self', '.', '_alias_user', 'is', 'not', 'None', ':', 'return', 'False', 'return', 'True'] | :rtype: bool | [':', 'rtype', ':', 'bool'] | train | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L16081-L16101 |
8,085 | robehickman/simple-http-file-sync | shttpfs/server.py | delete_files | def delete_files():
""" Delete one or more files from the server """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
body_data = request.get_json()
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
try:
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
#-------------
for fle in json.loads(body_data['files']):
data_store.fs_delete(fle)
# updates the user lock expiry
update_user_lock(repository_path, session_token)
return success()
except Exception: return fail() # pylint: disable=broad-except
return lock_access(repository_path, with_exclusive_lock) | python | def delete_files():
""" Delete one or more files from the server """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
body_data = request.get_json()
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
try:
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
#-------------
for fle in json.loads(body_data['files']):
data_store.fs_delete(fle)
# updates the user lock expiry
update_user_lock(repository_path, session_token)
return success()
except Exception: return fail() # pylint: disable=broad-except
return lock_access(repository_path, with_exclusive_lock) | ['def', 'delete_files', '(', ')', ':', 'session_token', '=', 'request', '.', 'headers', '[', "'session_token'", ']', 'repository', '=', 'request', '.', 'headers', '[', "'repository'", ']', '#===', 'current_user', '=', 'have_authenticated_user', '(', 'request', '.', 'environ', '[', "'REMOTE_ADDR'", ']', ',', 'repository', ',', 'session_token', ')', 'if', 'current_user', 'is', 'False', ':', 'return', 'fail', '(', 'user_auth_fail_msg', ')', '#===', 'repository_path', '=', 'config', '[', "'repositories'", ']', '[', 'repository', ']', '[', "'path'", ']', 'body_data', '=', 'request', '.', 'get_json', '(', ')', 'def', 'with_exclusive_lock', '(', ')', ':', 'if', 'not', 'varify_user_lock', '(', 'repository_path', ',', 'session_token', ')', ':', 'return', 'fail', '(', 'lock_fail_msg', ')', 'try', ':', 'data_store', '=', 'versioned_storage', '(', 'repository_path', ')', 'if', 'not', 'data_store', '.', 'have_active_commit', '(', ')', ':', 'return', 'fail', '(', 'no_active_commit_msg', ')', '#-------------', 'for', 'fle', 'in', 'json', '.', 'loads', '(', 'body_data', '[', "'files'", ']', ')', ':', 'data_store', '.', 'fs_delete', '(', 'fle', ')', '# updates the user lock expiry', 'update_user_lock', '(', 'repository_path', ',', 'session_token', ')', 'return', 'success', '(', ')', 'except', 'Exception', ':', 'return', 'fail', '(', ')', '# pylint: disable=broad-except', 'return', 'lock_access', '(', 'repository_path', ',', 'with_exclusive_lock', ')'] | Delete one or more files from the server | ['Delete', 'one', 'or', 'more', 'files', 'from', 'the', 'server'] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/server.py#L475-L504 |
8,086 | django-salesforce/django-salesforce | salesforce/dbapi/driver.py | RawConnection.raise_errors | def raise_errors(self, response):
"""The innermost part - report errors by exceptions"""
# Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500)
# TODO extract a case ID for Salesforce support from code 500 messages
# TODO disabled 'debug_verbs' temporarily, after writing better default messages
verb = self.debug_verbs # NOQA pylint:disable=unused-variable
method = response.request.method
data = None
is_json = 'json' in response.headers.get('Content-Type', '') and response.text
if is_json:
data = json.loads(response.text)
if not (isinstance(data, list) and data and 'errorCode' in data[0]):
messages = [response.text] if is_json else []
raise OperationalError(
['HTTP error "%d %s":' % (response.status_code, response.reason)]
+ messages, response, ['method+url'])
# Other Errors are reported in the json body
err_msg = data[0]['message']
err_code = data[0]['errorCode']
if response.status_code == 404: # ResourceNotFound
if method == 'DELETE' and err_code in ('ENTITY_IS_DELETED', 'INVALID_CROSS_REFERENCE_KEY'):
# It was a delete command and the object is in trash bin or it is
# completely deleted or it could be a valid Id for this sobject type.
# Then we accept it with a warning, similarly to delete by a classic database query:
# DELETE FROM xy WHERE id = 'something_deleted_yet'
warn_sf([err_msg, "Object is deleted before delete or update"], response, ['method+url'])
# TODO add a warning and add it to messages
return None
if err_code in ('NOT_FOUND', # 404 e.g. invalid object type in url path or url query?q=select ...
'METHOD_NOT_ALLOWED', # 405 e.g. patch instead of post
): # both need to report the url
raise SalesforceError([err_msg], response, ['method+url'])
# it is good e.g for these errorCode: ('INVALID_FIELD', 'MALFORMED_QUERY', 'INVALID_FIELD_FOR_INSERT_UPDATE')
raise SalesforceError([err_msg], response) | python | def raise_errors(self, response):
"""The innermost part - report errors by exceptions"""
# Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500)
# TODO extract a case ID for Salesforce support from code 500 messages
# TODO disabled 'debug_verbs' temporarily, after writing better default messages
verb = self.debug_verbs # NOQA pylint:disable=unused-variable
method = response.request.method
data = None
is_json = 'json' in response.headers.get('Content-Type', '') and response.text
if is_json:
data = json.loads(response.text)
if not (isinstance(data, list) and data and 'errorCode' in data[0]):
messages = [response.text] if is_json else []
raise OperationalError(
['HTTP error "%d %s":' % (response.status_code, response.reason)]
+ messages, response, ['method+url'])
# Other Errors are reported in the json body
err_msg = data[0]['message']
err_code = data[0]['errorCode']
if response.status_code == 404: # ResourceNotFound
if method == 'DELETE' and err_code in ('ENTITY_IS_DELETED', 'INVALID_CROSS_REFERENCE_KEY'):
# It was a delete command and the object is in trash bin or it is
# completely deleted or it could be a valid Id for this sobject type.
# Then we accept it with a warning, similarly to delete by a classic database query:
# DELETE FROM xy WHERE id = 'something_deleted_yet'
warn_sf([err_msg, "Object is deleted before delete or update"], response, ['method+url'])
# TODO add a warning and add it to messages
return None
if err_code in ('NOT_FOUND', # 404 e.g. invalid object type in url path or url query?q=select ...
'METHOD_NOT_ALLOWED', # 405 e.g. patch instead of post
): # both need to report the url
raise SalesforceError([err_msg], response, ['method+url'])
# it is good e.g for these errorCode: ('INVALID_FIELD', 'MALFORMED_QUERY', 'INVALID_FIELD_FOR_INSERT_UPDATE')
raise SalesforceError([err_msg], response) | ['def', 'raise_errors', '(', 'self', ',', 'response', ')', ':', '# Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500)', '# TODO extract a case ID for Salesforce support from code 500 messages', "# TODO disabled 'debug_verbs' temporarily, after writing better default messages", 'verb', '=', 'self', '.', 'debug_verbs', '# NOQA pylint:disable=unused-variable', 'method', '=', 'response', '.', 'request', '.', 'method', 'data', '=', 'None', 'is_json', '=', "'json'", 'in', 'response', '.', 'headers', '.', 'get', '(', "'Content-Type'", ',', "''", ')', 'and', 'response', '.', 'text', 'if', 'is_json', ':', 'data', '=', 'json', '.', 'loads', '(', 'response', '.', 'text', ')', 'if', 'not', '(', 'isinstance', '(', 'data', ',', 'list', ')', 'and', 'data', 'and', "'errorCode'", 'in', 'data', '[', '0', ']', ')', ':', 'messages', '=', '[', 'response', '.', 'text', ']', 'if', 'is_json', 'else', '[', ']', 'raise', 'OperationalError', '(', '[', '\'HTTP error "%d %s":\'', '%', '(', 'response', '.', 'status_code', ',', 'response', '.', 'reason', ')', ']', '+', 'messages', ',', 'response', ',', '[', "'method+url'", ']', ')', '# Other Errors are reported in the json body', 'err_msg', '=', 'data', '[', '0', ']', '[', "'message'", ']', 'err_code', '=', 'data', '[', '0', ']', '[', "'errorCode'", ']', 'if', 'response', '.', 'status_code', '==', '404', ':', '# ResourceNotFound', 'if', 'method', '==', "'DELETE'", 'and', 'err_code', 'in', '(', "'ENTITY_IS_DELETED'", ',', "'INVALID_CROSS_REFERENCE_KEY'", ')', ':', '# It was a delete command and the object is in trash bin or it is', '# completely deleted or it could be a valid Id for this sobject type.', '# Then we accept it with a warning, similarly to delete by a classic database query:', "# DELETE FROM xy WHERE id = 'something_deleted_yet'", 'warn_sf', '(', '[', 'err_msg', ',', '"Object is deleted before delete or update"', ']', ',', 'response', ',', '[', "'method+url'", ']', ')', '# TODO add a warning and add it to messages', 'return', 'None', 'if', 'err_code', 'in', '(', "'NOT_FOUND'", ',', '# 404 e.g. invalid object type in url path or url query?q=select ...', "'METHOD_NOT_ALLOWED'", ',', '# 405 e.g. patch instead of post', ')', ':', '# both need to report the url', 'raise', 'SalesforceError', '(', '[', 'err_msg', ']', ',', 'response', ',', '[', "'method+url'", ']', ')', "# it is good e.g for these errorCode: ('INVALID_FIELD', 'MALFORMED_QUERY', 'INVALID_FIELD_FOR_INSERT_UPDATE')", 'raise', 'SalesforceError', '(', '[', 'err_msg', ']', ',', 'response', ')'] | The innermost part - report errors by exceptions | ['The', 'innermost', 'part', '-', 'report', 'errors', 'by', 'exceptions'] | train | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/driver.py#L287-L322 |
8,087 | PMEAL/OpenPNM | openpnm/core/Base.py | Base.num_throats | def num_throats(self, labels='all', mode='union'):
r"""
Return the number of throats of the specified labels
Parameters
----------
labels : list of strings, optional
The throat labels that should be included in the count.
If not supplied, all throats are counted.
mode : string, optional
Specifies how the count should be performed. The options are:
**'or', 'union', 'any'** : (default) Throats with *one or more* of
the given labels are counted.
**'and', 'intersection', 'all'** : Throats with *all* of the given
labels are counted.
**'xor', 'exclusive_or'** : Throats with *only one* of the given
labels are counted.
**'nor', 'none', 'not'** : Throats with *none* of the given labels
are counted.
**'nand'** : Throats with *some but not all* of the given labels
are counted.
**'xnor'** : Throats with *more than one* of the given labels are
counted.
Returns
-------
Nt : int
Number of throats with the specified labels
See Also
--------
num_pores
count
Notes
-----
Technically, *'nand'* and *'xnor'* should also count throats with
*none* of the labels, however, to make the count more useful these are
not included.
"""
# Count number of pores of specified type
Ts = self._get_indices(labels=labels, mode=mode, element='throat')
Nt = sp.shape(Ts)[0]
return Nt | python | def num_throats(self, labels='all', mode='union'):
r"""
Return the number of throats of the specified labels
Parameters
----------
labels : list of strings, optional
The throat labels that should be included in the count.
If not supplied, all throats are counted.
mode : string, optional
Specifies how the count should be performed. The options are:
**'or', 'union', 'any'** : (default) Throats with *one or more* of
the given labels are counted.
**'and', 'intersection', 'all'** : Throats with *all* of the given
labels are counted.
**'xor', 'exclusive_or'** : Throats with *only one* of the given
labels are counted.
**'nor', 'none', 'not'** : Throats with *none* of the given labels
are counted.
**'nand'** : Throats with *some but not all* of the given labels
are counted.
**'xnor'** : Throats with *more than one* of the given labels are
counted.
Returns
-------
Nt : int
Number of throats with the specified labels
See Also
--------
num_pores
count
Notes
-----
Technically, *'nand'* and *'xnor'* should also count throats with
*none* of the labels, however, to make the count more useful these are
not included.
"""
# Count number of pores of specified type
Ts = self._get_indices(labels=labels, mode=mode, element='throat')
Nt = sp.shape(Ts)[0]
return Nt | ['def', 'num_throats', '(', 'self', ',', 'labels', '=', "'all'", ',', 'mode', '=', "'union'", ')', ':', '# Count number of pores of specified type', 'Ts', '=', 'self', '.', '_get_indices', '(', 'labels', '=', 'labels', ',', 'mode', '=', 'mode', ',', 'element', '=', "'throat'", ')', 'Nt', '=', 'sp', '.', 'shape', '(', 'Ts', ')', '[', '0', ']', 'return', 'Nt'] | r"""
Return the number of throats of the specified labels
Parameters
----------
labels : list of strings, optional
The throat labels that should be included in the count.
If not supplied, all throats are counted.
mode : string, optional
Specifies how the count should be performed. The options are:
**'or', 'union', 'any'** : (default) Throats with *one or more* of
the given labels are counted.
**'and', 'intersection', 'all'** : Throats with *all* of the given
labels are counted.
**'xor', 'exclusive_or'** : Throats with *only one* of the given
labels are counted.
**'nor', 'none', 'not'** : Throats with *none* of the given labels
are counted.
**'nand'** : Throats with *some but not all* of the given labels
are counted.
**'xnor'** : Throats with *more than one* of the given labels are
counted.
Returns
-------
Nt : int
Number of throats with the specified labels
See Also
--------
num_pores
count
Notes
-----
Technically, *'nand'* and *'xnor'* should also count throats with
*none* of the labels, however, to make the count more useful these are
not included. | ['r', 'Return', 'the', 'number', 'of', 'throats', 'of', 'the', 'specified', 'labels'] | train | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/Base.py#L1329-L1380 |
8,088 | onelogin/python3-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.process_slo | def process_slo(self, keep_local_session=False, request_id=None, delete_session_cb=None):
"""
Process the SAML Logout Response / Logout Request sent by the IdP.
:param keep_local_session: When false will destroy the local session, otherwise will destroy it
:type keep_local_session: bool
:param request_id: The ID of the LogoutRequest sent by this SP to the IdP
:type request_id: string
:returns: Redirection url
"""
self.__errors = []
self.__error_reason = None
get_data = 'get_data' in self.__request_data and self.__request_data['get_data']
if get_data and 'SAMLResponse' in get_data:
logout_response = OneLogin_Saml2_Logout_Response(self.__settings, get_data['SAMLResponse'])
self.__last_response = logout_response.get_xml()
if not self.validate_response_signature(get_data):
self.__errors.append('invalid_logout_response_signature')
self.__errors.append('Signature validation failed. Logout Response rejected')
elif not logout_response.is_valid(self.__request_data, request_id):
self.__errors.append('invalid_logout_response')
self.__error_reason = logout_response.get_error()
elif logout_response.get_status() != OneLogin_Saml2_Constants.STATUS_SUCCESS:
self.__errors.append('logout_not_success')
else:
self.__last_message_id = logout_response.id
if not keep_local_session:
OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
elif get_data and 'SAMLRequest' in get_data:
logout_request = OneLogin_Saml2_Logout_Request(self.__settings, get_data['SAMLRequest'])
self.__last_request = logout_request.get_xml()
if not self.validate_request_signature(get_data):
self.__errors.append("invalid_logout_request_signature")
self.__errors.append('Signature validation failed. Logout Request rejected')
elif not logout_request.is_valid(self.__request_data):
self.__errors.append('invalid_logout_request')
self.__error_reason = logout_request.get_error()
else:
if not keep_local_session:
OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
in_response_to = logout_request.id
self.__last_message_id = logout_request.id
response_builder = OneLogin_Saml2_Logout_Response(self.__settings)
response_builder.build(in_response_to)
self.__last_response = response_builder.get_xml()
logout_response = response_builder.get_response()
parameters = {'SAMLResponse': logout_response}
if 'RelayState' in self.__request_data['get_data']:
parameters['RelayState'] = self.__request_data['get_data']['RelayState']
security = self.__settings.get_security_data()
if security['logoutResponseSigned']:
self.add_response_signature(parameters, security['signatureAlgorithm'])
return self.redirect_to(self.get_slo_url(), parameters)
else:
self.__errors.append('invalid_binding')
raise OneLogin_Saml2_Error(
'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding',
OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND
) | python | def process_slo(self, keep_local_session=False, request_id=None, delete_session_cb=None):
"""
Process the SAML Logout Response / Logout Request sent by the IdP.
:param keep_local_session: When false will destroy the local session, otherwise will destroy it
:type keep_local_session: bool
:param request_id: The ID of the LogoutRequest sent by this SP to the IdP
:type request_id: string
:returns: Redirection url
"""
self.__errors = []
self.__error_reason = None
get_data = 'get_data' in self.__request_data and self.__request_data['get_data']
if get_data and 'SAMLResponse' in get_data:
logout_response = OneLogin_Saml2_Logout_Response(self.__settings, get_data['SAMLResponse'])
self.__last_response = logout_response.get_xml()
if not self.validate_response_signature(get_data):
self.__errors.append('invalid_logout_response_signature')
self.__errors.append('Signature validation failed. Logout Response rejected')
elif not logout_response.is_valid(self.__request_data, request_id):
self.__errors.append('invalid_logout_response')
self.__error_reason = logout_response.get_error()
elif logout_response.get_status() != OneLogin_Saml2_Constants.STATUS_SUCCESS:
self.__errors.append('logout_not_success')
else:
self.__last_message_id = logout_response.id
if not keep_local_session:
OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
elif get_data and 'SAMLRequest' in get_data:
logout_request = OneLogin_Saml2_Logout_Request(self.__settings, get_data['SAMLRequest'])
self.__last_request = logout_request.get_xml()
if not self.validate_request_signature(get_data):
self.__errors.append("invalid_logout_request_signature")
self.__errors.append('Signature validation failed. Logout Request rejected')
elif not logout_request.is_valid(self.__request_data):
self.__errors.append('invalid_logout_request')
self.__error_reason = logout_request.get_error()
else:
if not keep_local_session:
OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
in_response_to = logout_request.id
self.__last_message_id = logout_request.id
response_builder = OneLogin_Saml2_Logout_Response(self.__settings)
response_builder.build(in_response_to)
self.__last_response = response_builder.get_xml()
logout_response = response_builder.get_response()
parameters = {'SAMLResponse': logout_response}
if 'RelayState' in self.__request_data['get_data']:
parameters['RelayState'] = self.__request_data['get_data']['RelayState']
security = self.__settings.get_security_data()
if security['logoutResponseSigned']:
self.add_response_signature(parameters, security['signatureAlgorithm'])
return self.redirect_to(self.get_slo_url(), parameters)
else:
self.__errors.append('invalid_binding')
raise OneLogin_Saml2_Error(
'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding',
OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND
) | ['def', 'process_slo', '(', 'self', ',', 'keep_local_session', '=', 'False', ',', 'request_id', '=', 'None', ',', 'delete_session_cb', '=', 'None', ')', ':', 'self', '.', '__errors', '=', '[', ']', 'self', '.', '__error_reason', '=', 'None', 'get_data', '=', "'get_data'", 'in', 'self', '.', '__request_data', 'and', 'self', '.', '__request_data', '[', "'get_data'", ']', 'if', 'get_data', 'and', "'SAMLResponse'", 'in', 'get_data', ':', 'logout_response', '=', 'OneLogin_Saml2_Logout_Response', '(', 'self', '.', '__settings', ',', 'get_data', '[', "'SAMLResponse'", ']', ')', 'self', '.', '__last_response', '=', 'logout_response', '.', 'get_xml', '(', ')', 'if', 'not', 'self', '.', 'validate_response_signature', '(', 'get_data', ')', ':', 'self', '.', '__errors', '.', 'append', '(', "'invalid_logout_response_signature'", ')', 'self', '.', '__errors', '.', 'append', '(', "'Signature validation failed. Logout Response rejected'", ')', 'elif', 'not', 'logout_response', '.', 'is_valid', '(', 'self', '.', '__request_data', ',', 'request_id', ')', ':', 'self', '.', '__errors', '.', 'append', '(', "'invalid_logout_response'", ')', 'self', '.', '__error_reason', '=', 'logout_response', '.', 'get_error', '(', ')', 'elif', 'logout_response', '.', 'get_status', '(', ')', '!=', 'OneLogin_Saml2_Constants', '.', 'STATUS_SUCCESS', ':', 'self', '.', '__errors', '.', 'append', '(', "'logout_not_success'", ')', 'else', ':', 'self', '.', '__last_message_id', '=', 'logout_response', '.', 'id', 'if', 'not', 'keep_local_session', ':', 'OneLogin_Saml2_Utils', '.', 'delete_local_session', '(', 'delete_session_cb', ')', 'elif', 'get_data', 'and', "'SAMLRequest'", 'in', 'get_data', ':', 'logout_request', '=', 'OneLogin_Saml2_Logout_Request', '(', 'self', '.', '__settings', ',', 'get_data', '[', "'SAMLRequest'", ']', ')', 'self', '.', '__last_request', '=', 'logout_request', '.', 'get_xml', '(', ')', 'if', 'not', 'self', '.', 'validate_request_signature', '(', 'get_data', ')', ':', 'self', '.', '__errors', '.', 'append', '(', '"invalid_logout_request_signature"', ')', 'self', '.', '__errors', '.', 'append', '(', "'Signature validation failed. Logout Request rejected'", ')', 'elif', 'not', 'logout_request', '.', 'is_valid', '(', 'self', '.', '__request_data', ')', ':', 'self', '.', '__errors', '.', 'append', '(', "'invalid_logout_request'", ')', 'self', '.', '__error_reason', '=', 'logout_request', '.', 'get_error', '(', ')', 'else', ':', 'if', 'not', 'keep_local_session', ':', 'OneLogin_Saml2_Utils', '.', 'delete_local_session', '(', 'delete_session_cb', ')', 'in_response_to', '=', 'logout_request', '.', 'id', 'self', '.', '__last_message_id', '=', 'logout_request', '.', 'id', 'response_builder', '=', 'OneLogin_Saml2_Logout_Response', '(', 'self', '.', '__settings', ')', 'response_builder', '.', 'build', '(', 'in_response_to', ')', 'self', '.', '__last_response', '=', 'response_builder', '.', 'get_xml', '(', ')', 'logout_response', '=', 'response_builder', '.', 'get_response', '(', ')', 'parameters', '=', '{', "'SAMLResponse'", ':', 'logout_response', '}', 'if', "'RelayState'", 'in', 'self', '.', '__request_data', '[', "'get_data'", ']', ':', 'parameters', '[', "'RelayState'", ']', '=', 'self', '.', '__request_data', '[', "'get_data'", ']', '[', "'RelayState'", ']', 'security', '=', 'self', '.', '__settings', '.', 'get_security_data', '(', ')', 'if', 'security', '[', "'logoutResponseSigned'", ']', ':', 'self', '.', 'add_response_signature', '(', 'parameters', ',', 'security', '[', "'signatureAlgorithm'", ']', ')', 'return', 'self', '.', 'redirect_to', '(', 'self', '.', 'get_slo_url', '(', ')', ',', 'parameters', ')', 'else', ':', 'self', '.', '__errors', '.', 'append', '(', "'invalid_binding'", ')', 'raise', 'OneLogin_Saml2_Error', '(', "'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding'", ',', 'OneLogin_Saml2_Error', '.', 'SAML_LOGOUTMESSAGE_NOT_FOUND', ')'] | Process the SAML Logout Response / Logout Request sent by the IdP.
:param keep_local_session: When false will destroy the local session, otherwise will destroy it
:type keep_local_session: bool
:param request_id: The ID of the LogoutRequest sent by this SP to the IdP
:type request_id: string
:returns: Redirection url | ['Process', 'the', 'SAML', 'Logout', 'Response', '/', 'Logout', 'Request', 'sent', 'by', 'the', 'IdP', '.'] | train | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L129-L195 |
8,089 | christophertbrown/bioscripts | ctbBio/stockholm2oneline.py | stock2one | def stock2one(stock):
"""
convert stockholm to single line format
"""
lines = {}
for line in stock:
line = line.strip()
if print_line(line) is True:
yield line
continue
if line.startswith('//'):
continue
ID, seq = line.rsplit(' ', 1)
if ID not in lines:
lines[ID] = ''
else:
# remove preceding white space
seq = seq.strip()
lines[ID] += seq
for ID, line in lines.items():
yield '\t'.join([ID, line])
yield '\n//' | python | def stock2one(stock):
"""
convert stockholm to single line format
"""
lines = {}
for line in stock:
line = line.strip()
if print_line(line) is True:
yield line
continue
if line.startswith('//'):
continue
ID, seq = line.rsplit(' ', 1)
if ID not in lines:
lines[ID] = ''
else:
# remove preceding white space
seq = seq.strip()
lines[ID] += seq
for ID, line in lines.items():
yield '\t'.join([ID, line])
yield '\n//' | ['def', 'stock2one', '(', 'stock', ')', ':', 'lines', '=', '{', '}', 'for', 'line', 'in', 'stock', ':', 'line', '=', 'line', '.', 'strip', '(', ')', 'if', 'print_line', '(', 'line', ')', 'is', 'True', ':', 'yield', 'line', 'continue', 'if', 'line', '.', 'startswith', '(', "'//'", ')', ':', 'continue', 'ID', ',', 'seq', '=', 'line', '.', 'rsplit', '(', "' '", ',', '1', ')', 'if', 'ID', 'not', 'in', 'lines', ':', 'lines', '[', 'ID', ']', '=', "''", 'else', ':', '# remove preceding white space', 'seq', '=', 'seq', '.', 'strip', '(', ')', 'lines', '[', 'ID', ']', '+=', 'seq', 'for', 'ID', ',', 'line', 'in', 'lines', '.', 'items', '(', ')', ':', 'yield', "'\\t'", '.', 'join', '(', '[', 'ID', ',', 'line', ']', ')', 'yield', "'\\n//'"] | convert stockholm to single line format | ['convert', 'stockholm', 'to', 'single', 'line', 'format'] | train | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/stockholm2oneline.py#L23-L44 |
8,090 | Bachmann1234/diff-cover | diff_cover/snippets.py | Snippet.load_snippets_html | def load_snippets_html(cls, src_path, violation_lines):
"""
Load snippets from the file at `src_path` and format
them as HTML.
See `load_snippets()` for details.
"""
snippet_list = cls.load_snippets(src_path, violation_lines)
return [snippet.html() for snippet in snippet_list] | python | def load_snippets_html(cls, src_path, violation_lines):
"""
Load snippets from the file at `src_path` and format
them as HTML.
See `load_snippets()` for details.
"""
snippet_list = cls.load_snippets(src_path, violation_lines)
return [snippet.html() for snippet in snippet_list] | ['def', 'load_snippets_html', '(', 'cls', ',', 'src_path', ',', 'violation_lines', ')', ':', 'snippet_list', '=', 'cls', '.', 'load_snippets', '(', 'src_path', ',', 'violation_lines', ')', 'return', '[', 'snippet', '.', 'html', '(', ')', 'for', 'snippet', 'in', 'snippet_list', ']'] | Load snippets from the file at `src_path` and format
them as HTML.
See `load_snippets()` for details. | ['Load', 'snippets', 'from', 'the', 'file', 'at', 'src_path', 'and', 'format', 'them', 'as', 'HTML', '.'] | train | https://github.com/Bachmann1234/diff-cover/blob/901cb3fc986982961785e841658085ead453c6c9/diff_cover/snippets.py#L130-L138 |
8,091 | FNNDSC/pfmisc | pfmisc/C_snode.py | C_stree.lsf | def lsf(self, astr_path=""):
"""
List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files
"""
d_files = self.ls(astr_path, nodes=False, data=True)
l_files = d_files.keys()
return l_files | python | def lsf(self, astr_path=""):
"""
List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files
"""
d_files = self.ls(astr_path, nodes=False, data=True)
l_files = d_files.keys()
return l_files | ['def', 'lsf', '(', 'self', ',', 'astr_path', '=', '""', ')', ':', 'd_files', '=', 'self', '.', 'ls', '(', 'astr_path', ',', 'nodes', '=', 'False', ',', 'data', '=', 'True', ')', 'l_files', '=', 'd_files', '.', 'keys', '(', ')', 'return', 'l_files'] | List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files | ['List', 'only', 'the', 'files', 'in', 'the', 'astr_path', '.'] | train | https://github.com/FNNDSC/pfmisc/blob/960b4d6135fcc50bed0a8e55db2ab1ddad9b99d8/pfmisc/C_snode.py#L1026-L1035 |
8,092 | horazont/aioxmpp | aioxmpp/service.py | presence_handler | def presence_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | python | def presence_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | ['def', 'presence_handler', '(', 'type_', ',', 'from_', ')', ':', 'import', 'aioxmpp', '.', 'dispatcher', 'return', 'aioxmpp', '.', 'dispatcher', '.', 'presence_handler', '(', 'type_', ',', 'from_', ')'] | Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9 | ['Deprecated', 'alias', 'of', ':', 'func', ':', '.', 'dispatcher', '.', 'presence_handler', '.'] | train | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1073-L1080 |
8,093 | faxir/faxir-python | faxir/api/numbers_api.py | NumbersApi.update_number | def update_number(self, number, payload_number_modification, **kwargs): # noqa: E501
"""Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_number(number, payload_number_modification, async=True)
>>> result = thread.get()
:param async bool
:param str number: (required)
:param PayloadNumberModification payload_number_modification: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501
else:
(data) = self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501
return data | python | def update_number(self, number, payload_number_modification, **kwargs): # noqa: E501
"""Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_number(number, payload_number_modification, async=True)
>>> result = thread.get()
:param async bool
:param str number: (required)
:param PayloadNumberModification payload_number_modification: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501
else:
(data) = self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501
return data | ['def', 'update_number', '(', 'self', ',', 'number', ',', 'payload_number_modification', ',', '*', '*', 'kwargs', ')', ':', '# noqa: E501', 'kwargs', '[', "'_return_http_data_only'", ']', '=', 'True', 'if', 'kwargs', '.', 'get', '(', "'async'", ')', ':', 'return', 'self', '.', 'update_number_with_http_info', '(', 'number', ',', 'payload_number_modification', ',', '*', '*', 'kwargs', ')', '# noqa: E501', 'else', ':', '(', 'data', ')', '=', 'self', '.', 'update_number_with_http_info', '(', 'number', ',', 'payload_number_modification', ',', '*', '*', 'kwargs', ')', '# noqa: E501', 'return', 'data'] | Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_number(number, payload_number_modification, async=True)
>>> result = thread.get()
:param async bool
:param str number: (required)
:param PayloadNumberModification payload_number_modification: (required)
:return: None
If the method is called asynchronously,
returns the request thread. | ['Assign', 'number', '#', 'noqa', ':', 'E501'] | train | https://github.com/faxir/faxir-python/blob/75ed2ea487a6be537342baea1077a02b0c8e70c1/faxir/api/numbers_api.py#L325-L346 |
8,094 | ecederstrand/exchangelib | exchangelib/services.py | GetFolder.call | def call(self, folders, additional_fields, shape):
"""
Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for the folders, in stable order
"""
# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same
# class as the folder instance it was requested with.
from .folders import Folder, DistinguishedFolderId, RootOfHierarchy
folders_list = list(folders) # Convert to a list, in case 'folders' is a generator
for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload(
folders=folders,
additional_fields=additional_fields,
shape=shape,
))):
if isinstance(elem, Exception):
yield elem
continue
if isinstance(folder, RootOfHierarchy):
f = folder.from_xml(elem=elem, account=self.account)
elif isinstance(folder, Folder):
f = folder.from_xml(elem=elem, root=folder.root)
elif isinstance(folder, DistinguishedFolderId):
# We don't know the root, so assume account.root.
for folder_cls in self.account.root.WELLKNOWN_FOLDERS:
if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id:
break
else:
raise ValueError('Unknown distinguished folder ID: %s', folder.id)
f = folder_cls.from_xml(elem=elem, root=self.account.root)
else:
# 'folder' is a generic FolderId instance. We don't know the root so assume account.root.
f = Folder.from_xml(elem=elem, root=self.account.root)
if isinstance(folder, DistinguishedFolderId):
f.is_distinguished = True
elif isinstance(folder, Folder) and folder.is_distinguished:
f.is_distinguished = True
yield f | python | def call(self, folders, additional_fields, shape):
"""
Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for the folders, in stable order
"""
# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same
# class as the folder instance it was requested with.
from .folders import Folder, DistinguishedFolderId, RootOfHierarchy
folders_list = list(folders) # Convert to a list, in case 'folders' is a generator
for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload(
folders=folders,
additional_fields=additional_fields,
shape=shape,
))):
if isinstance(elem, Exception):
yield elem
continue
if isinstance(folder, RootOfHierarchy):
f = folder.from_xml(elem=elem, account=self.account)
elif isinstance(folder, Folder):
f = folder.from_xml(elem=elem, root=folder.root)
elif isinstance(folder, DistinguishedFolderId):
# We don't know the root, so assume account.root.
for folder_cls in self.account.root.WELLKNOWN_FOLDERS:
if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id:
break
else:
raise ValueError('Unknown distinguished folder ID: %s', folder.id)
f = folder_cls.from_xml(elem=elem, root=self.account.root)
else:
# 'folder' is a generic FolderId instance. We don't know the root so assume account.root.
f = Folder.from_xml(elem=elem, root=self.account.root)
if isinstance(folder, DistinguishedFolderId):
f.is_distinguished = True
elif isinstance(folder, Folder) and folder.is_distinguished:
f.is_distinguished = True
yield f | ['def', 'call', '(', 'self', ',', 'folders', ',', 'additional_fields', ',', 'shape', ')', ':', "# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same", '# class as the folder instance it was requested with.', 'from', '.', 'folders', 'import', 'Folder', ',', 'DistinguishedFolderId', ',', 'RootOfHierarchy', 'folders_list', '=', 'list', '(', 'folders', ')', "# Convert to a list, in case 'folders' is a generator", 'for', 'folder', ',', 'elem', 'in', 'zip', '(', 'folders_list', ',', 'self', '.', '_get_elements', '(', 'payload', '=', 'self', '.', 'get_payload', '(', 'folders', '=', 'folders', ',', 'additional_fields', '=', 'additional_fields', ',', 'shape', '=', 'shape', ',', ')', ')', ')', ':', 'if', 'isinstance', '(', 'elem', ',', 'Exception', ')', ':', 'yield', 'elem', 'continue', 'if', 'isinstance', '(', 'folder', ',', 'RootOfHierarchy', ')', ':', 'f', '=', 'folder', '.', 'from_xml', '(', 'elem', '=', 'elem', ',', 'account', '=', 'self', '.', 'account', ')', 'elif', 'isinstance', '(', 'folder', ',', 'Folder', ')', ':', 'f', '=', 'folder', '.', 'from_xml', '(', 'elem', '=', 'elem', ',', 'root', '=', 'folder', '.', 'root', ')', 'elif', 'isinstance', '(', 'folder', ',', 'DistinguishedFolderId', ')', ':', "# We don't know the root, so assume account.root.", 'for', 'folder_cls', 'in', 'self', '.', 'account', '.', 'root', '.', 'WELLKNOWN_FOLDERS', ':', 'if', 'folder_cls', '.', 'DISTINGUISHED_FOLDER_ID', '==', 'folder', '.', 'id', ':', 'break', 'else', ':', 'raise', 'ValueError', '(', "'Unknown distinguished folder ID: %s'", ',', 'folder', '.', 'id', ')', 'f', '=', 'folder_cls', '.', 'from_xml', '(', 'elem', '=', 'elem', ',', 'root', '=', 'self', '.', 'account', '.', 'root', ')', 'else', ':', "# 'folder' is a generic FolderId instance. We don't know the root so assume account.root.", 'f', '=', 'Folder', '.', 'from_xml', '(', 'elem', '=', 'elem', ',', 'root', '=', 'self', '.', 'account', '.', 'root', ')', 'if', 'isinstance', '(', 'folder', ',', 'DistinguishedFolderId', ')', ':', 'f', '.', 'is_distinguished', '=', 'True', 'elif', 'isinstance', '(', 'folder', ',', 'Folder', ')', 'and', 'folder', '.', 'is_distinguished', ':', 'f', '.', 'is_distinguished', '=', 'True', 'yield', 'f'] | Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for the folders, in stable order | ['Takes', 'a', 'folder', 'ID', 'and', 'returns', 'the', 'full', 'information', 'for', 'that', 'folder', '.'] | train | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1132-L1172 |
8,095 | twisted/txaws | txaws/reactor.py | get_exitcode_reactor | def get_exitcode_reactor():
"""
This is only neccesary until a fix like the one outlined here is
implemented for Twisted:
http://twistedmatrix.com/trac/ticket/2182
"""
from twisted.internet.main import installReactor
from twisted.internet.selectreactor import SelectReactor
class ExitCodeReactor(SelectReactor):
def stop(self, exitStatus=0):
super(ExitCodeReactor, self).stop()
self.exitStatus = exitStatus
def run(self, *args, **kwargs):
super(ExitCodeReactor, self).run(*args, **kwargs)
return self.exitStatus
reactor = ExitCodeReactor()
installReactor(reactor)
return reactor | python | def get_exitcode_reactor():
"""
This is only neccesary until a fix like the one outlined here is
implemented for Twisted:
http://twistedmatrix.com/trac/ticket/2182
"""
from twisted.internet.main import installReactor
from twisted.internet.selectreactor import SelectReactor
class ExitCodeReactor(SelectReactor):
def stop(self, exitStatus=0):
super(ExitCodeReactor, self).stop()
self.exitStatus = exitStatus
def run(self, *args, **kwargs):
super(ExitCodeReactor, self).run(*args, **kwargs)
return self.exitStatus
reactor = ExitCodeReactor()
installReactor(reactor)
return reactor | ['def', 'get_exitcode_reactor', '(', ')', ':', 'from', 'twisted', '.', 'internet', '.', 'main', 'import', 'installReactor', 'from', 'twisted', '.', 'internet', '.', 'selectreactor', 'import', 'SelectReactor', 'class', 'ExitCodeReactor', '(', 'SelectReactor', ')', ':', 'def', 'stop', '(', 'self', ',', 'exitStatus', '=', '0', ')', ':', 'super', '(', 'ExitCodeReactor', ',', 'self', ')', '.', 'stop', '(', ')', 'self', '.', 'exitStatus', '=', 'exitStatus', 'def', 'run', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'super', '(', 'ExitCodeReactor', ',', 'self', ')', '.', 'run', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', 'return', 'self', '.', 'exitStatus', 'reactor', '=', 'ExitCodeReactor', '(', ')', 'installReactor', '(', 'reactor', ')', 'return', 'reactor'] | This is only neccesary until a fix like the one outlined here is
implemented for Twisted:
http://twistedmatrix.com/trac/ticket/2182 | ['This', 'is', 'only', 'neccesary', 'until', 'a', 'fix', 'like', 'the', 'one', 'outlined', 'here', 'is', 'implemented', 'for', 'Twisted', ':', 'http', ':', '//', 'twistedmatrix', '.', 'com', '/', 'trac', '/', 'ticket', '/', '2182'] | train | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/reactor.py#L4-L25 |
8,096 | cogeotiff/rio-tiler | rio_tiler/cbers.py | bounds | def bounds(sceneid):
"""
Retrieve image bounds.
Attributes
----------
sceneid : str
CBERS sceneid.
Returns
-------
out : dict
dictionary with image bounds.
"""
scene_params = _cbers_parse_scene_id(sceneid)
cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"])
with rasterio.open(
"{}/{}_BAND{}.tif".format(
cbers_address, sceneid, scene_params["reference_band"]
)
) as src:
wgs_bounds = transform_bounds(
*[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21
)
info = {"sceneid": sceneid}
info["bounds"] = list(wgs_bounds)
return info | python | def bounds(sceneid):
"""
Retrieve image bounds.
Attributes
----------
sceneid : str
CBERS sceneid.
Returns
-------
out : dict
dictionary with image bounds.
"""
scene_params = _cbers_parse_scene_id(sceneid)
cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"])
with rasterio.open(
"{}/{}_BAND{}.tif".format(
cbers_address, sceneid, scene_params["reference_band"]
)
) as src:
wgs_bounds = transform_bounds(
*[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21
)
info = {"sceneid": sceneid}
info["bounds"] = list(wgs_bounds)
return info | ['def', 'bounds', '(', 'sceneid', ')', ':', 'scene_params', '=', '_cbers_parse_scene_id', '(', 'sceneid', ')', 'cbers_address', '=', '"{}/{}"', '.', 'format', '(', 'CBERS_BUCKET', ',', 'scene_params', '[', '"key"', ']', ')', 'with', 'rasterio', '.', 'open', '(', '"{}/{}_BAND{}.tif"', '.', 'format', '(', 'cbers_address', ',', 'sceneid', ',', 'scene_params', '[', '"reference_band"', ']', ')', ')', 'as', 'src', ':', 'wgs_bounds', '=', 'transform_bounds', '(', '*', '[', 'src', '.', 'crs', ',', '"epsg:4326"', ']', '+', 'list', '(', 'src', '.', 'bounds', ')', ',', 'densify_pts', '=', '21', ')', 'info', '=', '{', '"sceneid"', ':', 'sceneid', '}', 'info', '[', '"bounds"', ']', '=', 'list', '(', 'wgs_bounds', ')', 'return', 'info'] | Retrieve image bounds.
Attributes
----------
sceneid : str
CBERS sceneid.
Returns
-------
out : dict
dictionary with image bounds. | ['Retrieve', 'image', 'bounds', '.'] | train | https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/cbers.py#L115-L145 |
8,097 | ktbyers/netmiko | netmiko/juniper/juniper.py | JuniperBase.enter_cli_mode | def enter_cli_mode(self):
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
cur_prompt = ""
while count < 50:
self.write_channel(self.RETURN)
time.sleep(0.1 * delay_factor)
cur_prompt = self.read_channel()
if re.search(r"root@", cur_prompt) or re.search(r"^%$", cur_prompt.strip()):
self.write_channel("cli" + self.RETURN)
time.sleep(0.3 * delay_factor)
self.clear_buffer()
break
elif ">" in cur_prompt or "#" in cur_prompt:
break
count += 1 | python | def enter_cli_mode(self):
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
cur_prompt = ""
while count < 50:
self.write_channel(self.RETURN)
time.sleep(0.1 * delay_factor)
cur_prompt = self.read_channel()
if re.search(r"root@", cur_prompt) or re.search(r"^%$", cur_prompt.strip()):
self.write_channel("cli" + self.RETURN)
time.sleep(0.3 * delay_factor)
self.clear_buffer()
break
elif ">" in cur_prompt or "#" in cur_prompt:
break
count += 1 | ['def', 'enter_cli_mode', '(', 'self', ')', ':', 'delay_factor', '=', 'self', '.', 'select_delay_factor', '(', 'delay_factor', '=', '0', ')', 'count', '=', '0', 'cur_prompt', '=', '""', 'while', 'count', '<', '50', ':', 'self', '.', 'write_channel', '(', 'self', '.', 'RETURN', ')', 'time', '.', 'sleep', '(', '0.1', '*', 'delay_factor', ')', 'cur_prompt', '=', 'self', '.', 'read_channel', '(', ')', 'if', 're', '.', 'search', '(', 'r"root@"', ',', 'cur_prompt', ')', 'or', 're', '.', 'search', '(', 'r"^%$"', ',', 'cur_prompt', '.', 'strip', '(', ')', ')', ':', 'self', '.', 'write_channel', '(', '"cli"', '+', 'self', '.', 'RETURN', ')', 'time', '.', 'sleep', '(', '0.3', '*', 'delay_factor', ')', 'self', '.', 'clear_buffer', '(', ')', 'break', 'elif', '">"', 'in', 'cur_prompt', 'or', '"#"', 'in', 'cur_prompt', ':', 'break', 'count', '+=', '1'] | Check if at shell prompt root@ and go into CLI. | ['Check', 'if', 'at', 'shell', 'prompt', 'root'] | train | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/juniper/juniper.py#L43-L59 |
8,098 | dslackw/slpkg | slpkg/main.py | ArgParse.congiguration | def congiguration(self):
"""Manage slpkg configuration file
"""
options = [
"-g",
"--config"
]
command = [
"print",
"edit",
"reset"
]
conf = Config()
if (len(self.args) == 2 and self.args[0] in options and
self.args[1] == command[1]):
conf.edit()
elif (len(self.args) == 2 and self.args[0] in options and
self.args[1] == (command[0])):
conf.view()
elif (len(self.args) == 2 and self.args[0] in options and
self.args[1] == (command[2])):
conf.reset()
else:
usage("") | python | def congiguration(self):
"""Manage slpkg configuration file
"""
options = [
"-g",
"--config"
]
command = [
"print",
"edit",
"reset"
]
conf = Config()
if (len(self.args) == 2 and self.args[0] in options and
self.args[1] == command[1]):
conf.edit()
elif (len(self.args) == 2 and self.args[0] in options and
self.args[1] == (command[0])):
conf.view()
elif (len(self.args) == 2 and self.args[0] in options and
self.args[1] == (command[2])):
conf.reset()
else:
usage("") | ['def', 'congiguration', '(', 'self', ')', ':', 'options', '=', '[', '"-g"', ',', '"--config"', ']', 'command', '=', '[', '"print"', ',', '"edit"', ',', '"reset"', ']', 'conf', '=', 'Config', '(', ')', 'if', '(', 'len', '(', 'self', '.', 'args', ')', '==', '2', 'and', 'self', '.', 'args', '[', '0', ']', 'in', 'options', 'and', 'self', '.', 'args', '[', '1', ']', '==', 'command', '[', '1', ']', ')', ':', 'conf', '.', 'edit', '(', ')', 'elif', '(', 'len', '(', 'self', '.', 'args', ')', '==', '2', 'and', 'self', '.', 'args', '[', '0', ']', 'in', 'options', 'and', 'self', '.', 'args', '[', '1', ']', '==', '(', 'command', '[', '0', ']', ')', ')', ':', 'conf', '.', 'view', '(', ')', 'elif', '(', 'len', '(', 'self', '.', 'args', ')', '==', '2', 'and', 'self', '.', 'args', '[', '0', ']', 'in', 'options', 'and', 'self', '.', 'args', '[', '1', ']', '==', '(', 'command', '[', '2', ']', ')', ')', ':', 'conf', '.', 'reset', '(', ')', 'else', ':', 'usage', '(', '""', ')'] | Manage slpkg configuration file | ['Manage', 'slpkg', 'configuration', 'file'] | train | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/main.py#L697-L720 |
8,099 | cognitect/transit-python | transit/writer.py | JsonMarshaler.emit_map | def emit_map(self, m, _, cache):
"""Emits array as per default JSON spec."""
self.emit_array_start(None)
self.marshal(MAP_AS_ARR, False, cache)
for k, v in m.items():
self.marshal(k, True, cache)
self.marshal(v, False, cache)
self.emit_array_end() | python | def emit_map(self, m, _, cache):
"""Emits array as per default JSON spec."""
self.emit_array_start(None)
self.marshal(MAP_AS_ARR, False, cache)
for k, v in m.items():
self.marshal(k, True, cache)
self.marshal(v, False, cache)
self.emit_array_end() | ['def', 'emit_map', '(', 'self', ',', 'm', ',', '_', ',', 'cache', ')', ':', 'self', '.', 'emit_array_start', '(', 'None', ')', 'self', '.', 'marshal', '(', 'MAP_AS_ARR', ',', 'False', ',', 'cache', ')', 'for', 'k', ',', 'v', 'in', 'm', '.', 'items', '(', ')', ':', 'self', '.', 'marshal', '(', 'k', ',', 'True', ',', 'cache', ')', 'self', '.', 'marshal', '(', 'v', ',', 'False', ',', 'cache', ')', 'self', '.', 'emit_array_end', '(', ')'] | Emits array as per default JSON spec. | ['Emits', 'array', 'as', 'per', 'default', 'JSON', 'spec', '.'] | train | https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L353-L360 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.