repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
opennode/waldur-core
|
waldur_core/core/models.py
|
ReversionMixin.get_version_fields
|
def get_version_fields(self):
""" Get field that are tracked in object history versions. """
options = reversion._get_options(self)
return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
|
python
|
def get_version_fields(self):
""" Get field that are tracked in object history versions. """
options = reversion._get_options(self)
return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
|
[
"def",
"get_version_fields",
"(",
"self",
")",
":",
"options",
"=",
"reversion",
".",
"_get_options",
"(",
"self",
")",
"return",
"options",
".",
"fields",
"or",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"self",
".",
"_meta",
".",
"fields",
"if",
"f",
"not",
"in",
"options",
".",
"exclude",
"]"
] |
Get field that are tracked in object history versions.
|
[
"Get",
"field",
"that",
"are",
"tracked",
"in",
"object",
"history",
"versions",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L380-L383
|
train
|
opennode/waldur-core
|
waldur_core/core/models.py
|
ReversionMixin._is_version_duplicate
|
def _is_version_duplicate(self):
""" Define should new version be created for object or no.
Reasons to provide custom check instead of default `ignore_revision_duplicates`:
- no need to compare all revisions - it is OK if right object version exists in any revision;
- need to compare object attributes (not serialized data) to avoid
version creation on wrong <float> vs <int> comparison;
"""
if self.id is None:
return False
try:
latest_version = Version.objects.get_for_object(self).latest('revision__date_created')
except Version.DoesNotExist:
return False
latest_version_object = latest_version._object_version.object
fields = self.get_version_fields()
return all([getattr(self, f) == getattr(latest_version_object, f) for f in fields])
|
python
|
def _is_version_duplicate(self):
""" Define should new version be created for object or no.
Reasons to provide custom check instead of default `ignore_revision_duplicates`:
- no need to compare all revisions - it is OK if right object version exists in any revision;
- need to compare object attributes (not serialized data) to avoid
version creation on wrong <float> vs <int> comparison;
"""
if self.id is None:
return False
try:
latest_version = Version.objects.get_for_object(self).latest('revision__date_created')
except Version.DoesNotExist:
return False
latest_version_object = latest_version._object_version.object
fields = self.get_version_fields()
return all([getattr(self, f) == getattr(latest_version_object, f) for f in fields])
|
[
"def",
"_is_version_duplicate",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
"is",
"None",
":",
"return",
"False",
"try",
":",
"latest_version",
"=",
"Version",
".",
"objects",
".",
"get_for_object",
"(",
"self",
")",
".",
"latest",
"(",
"'revision__date_created'",
")",
"except",
"Version",
".",
"DoesNotExist",
":",
"return",
"False",
"latest_version_object",
"=",
"latest_version",
".",
"_object_version",
".",
"object",
"fields",
"=",
"self",
".",
"get_version_fields",
"(",
")",
"return",
"all",
"(",
"[",
"getattr",
"(",
"self",
",",
"f",
")",
"==",
"getattr",
"(",
"latest_version_object",
",",
"f",
")",
"for",
"f",
"in",
"fields",
"]",
")"
] |
Define should new version be created for object or no.
Reasons to provide custom check instead of default `ignore_revision_duplicates`:
- no need to compare all revisions - it is OK if right object version exists in any revision;
- need to compare object attributes (not serialized data) to avoid
version creation on wrong <float> vs <int> comparison;
|
[
"Define",
"should",
"new",
"version",
"be",
"created",
"for",
"object",
"or",
"no",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L385-L401
|
train
|
opennode/waldur-core
|
waldur_core/core/models.py
|
DescendantMixin.get_ancestors
|
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)]
for ancestor in ancestors_with_parents:
for parent in ancestor.get_ancestors():
if (parent.__class__, parent.id) not in ancestor_unique_attributes:
ancestors.append(parent)
return ancestors
|
python
|
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)]
for ancestor in ancestors_with_parents:
for parent in ancestor.get_ancestors():
if (parent.__class__, parent.id) not in ancestor_unique_attributes:
ancestors.append(parent)
return ancestors
|
[
"def",
"get_ancestors",
"(",
"self",
")",
":",
"ancestors",
"=",
"list",
"(",
"self",
".",
"get_parents",
"(",
")",
")",
"ancestor_unique_attributes",
"=",
"set",
"(",
"[",
"(",
"a",
".",
"__class__",
",",
"a",
".",
"id",
")",
"for",
"a",
"in",
"ancestors",
"]",
")",
"ancestors_with_parents",
"=",
"[",
"a",
"for",
"a",
"in",
"ancestors",
"if",
"isinstance",
"(",
"a",
",",
"DescendantMixin",
")",
"]",
"for",
"ancestor",
"in",
"ancestors_with_parents",
":",
"for",
"parent",
"in",
"ancestor",
".",
"get_ancestors",
"(",
")",
":",
"if",
"(",
"parent",
".",
"__class__",
",",
"parent",
".",
"id",
")",
"not",
"in",
"ancestor_unique_attributes",
":",
"ancestors",
".",
"append",
"(",
"parent",
")",
"return",
"ancestors"
] |
Get all unique instance ancestors
|
[
"Get",
"all",
"unique",
"instance",
"ancestors"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L424-L433
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection.has_succeed
|
def has_succeed(self):
""" Check if the connection has succeed
Returns:
Returns True if connection has succeed.
False otherwise.
"""
status_code = self._response.status_code
if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY, HTTP_CODE_MULTIPLE_CHOICES]:
return True
if status_code in [HTTP_CODE_BAD_REQUEST, HTTP_CODE_UNAUTHORIZED, HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_NOT_FOUND, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_CONNECTION_TIMEOUT, HTTP_CODE_CONFLICT, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_INTERNAL_SERVER_ERROR, HTTP_CODE_SERVICE_UNAVAILABLE]:
return False
raise Exception('Unknown status code %s.', status_code)
|
python
|
def has_succeed(self):
""" Check if the connection has succeed
Returns:
Returns True if connection has succeed.
False otherwise.
"""
status_code = self._response.status_code
if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY, HTTP_CODE_MULTIPLE_CHOICES]:
return True
if status_code in [HTTP_CODE_BAD_REQUEST, HTTP_CODE_UNAUTHORIZED, HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_NOT_FOUND, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_CONNECTION_TIMEOUT, HTTP_CODE_CONFLICT, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_INTERNAL_SERVER_ERROR, HTTP_CODE_SERVICE_UNAVAILABLE]:
return False
raise Exception('Unknown status code %s.', status_code)
|
[
"def",
"has_succeed",
"(",
"self",
")",
":",
"status_code",
"=",
"self",
".",
"_response",
".",
"status_code",
"if",
"status_code",
"in",
"[",
"HTTP_CODE_ZERO",
",",
"HTTP_CODE_SUCCESS",
",",
"HTTP_CODE_CREATED",
",",
"HTTP_CODE_EMPTY",
",",
"HTTP_CODE_MULTIPLE_CHOICES",
"]",
":",
"return",
"True",
"if",
"status_code",
"in",
"[",
"HTTP_CODE_BAD_REQUEST",
",",
"HTTP_CODE_UNAUTHORIZED",
",",
"HTTP_CODE_PERMISSION_DENIED",
",",
"HTTP_CODE_NOT_FOUND",
",",
"HTTP_CODE_METHOD_NOT_ALLOWED",
",",
"HTTP_CODE_CONNECTION_TIMEOUT",
",",
"HTTP_CODE_CONFLICT",
",",
"HTTP_CODE_PRECONDITION_FAILED",
",",
"HTTP_CODE_INTERNAL_SERVER_ERROR",
",",
"HTTP_CODE_SERVICE_UNAVAILABLE",
"]",
":",
"return",
"False",
"raise",
"Exception",
"(",
"'Unknown status code %s.'",
",",
"status_code",
")"
] |
Check if the connection has succeed
Returns:
Returns True if connection has succeed.
False otherwise.
|
[
"Check",
"if",
"the",
"connection",
"has",
"succeed"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L233-L249
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection.handle_response_for_connection
|
def handle_response_for_connection(self, should_post=False):
""" Check if the response succeed or not.
In case of error, this method also print messages and set
an array of errors in the response object.
Returns:
Returns True if the response has succeed, False otherwise
"""
status_code = self._response.status_code
data = self._response.data
# TODO : Get errors in response data after bug fix : http://mvjira.mv.usa.alcatel.com/browse/VSD-2735
if data and 'errors' in data:
self._response.errors = data['errors']
if status_code in [HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY]:
return True
if status_code == HTTP_CODE_MULTIPLE_CHOICES:
return False
if status_code in [HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_UNAUTHORIZED]:
if not should_post:
return True
return False
if status_code in [HTTP_CODE_CONFLICT, HTTP_CODE_NOT_FOUND, HTTP_CODE_BAD_REQUEST, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_SERVICE_UNAVAILABLE]:
if not should_post:
return True
return False
if status_code == HTTP_CODE_INTERNAL_SERVER_ERROR:
return False
if status_code == HTTP_CODE_ZERO:
bambou_logger.error("NURESTConnection: Connection error with code 0. Sending NUNURESTConnectionFailureNotification notification and exiting.")
return False
bambou_logger.error("NURESTConnection: Report this error, because this should not happen: %s" % self._response)
return False
|
python
|
def handle_response_for_connection(self, should_post=False):
""" Check if the response succeed or not.
In case of error, this method also print messages and set
an array of errors in the response object.
Returns:
Returns True if the response has succeed, False otherwise
"""
status_code = self._response.status_code
data = self._response.data
# TODO : Get errors in response data after bug fix : http://mvjira.mv.usa.alcatel.com/browse/VSD-2735
if data and 'errors' in data:
self._response.errors = data['errors']
if status_code in [HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY]:
return True
if status_code == HTTP_CODE_MULTIPLE_CHOICES:
return False
if status_code in [HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_UNAUTHORIZED]:
if not should_post:
return True
return False
if status_code in [HTTP_CODE_CONFLICT, HTTP_CODE_NOT_FOUND, HTTP_CODE_BAD_REQUEST, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_SERVICE_UNAVAILABLE]:
if not should_post:
return True
return False
if status_code == HTTP_CODE_INTERNAL_SERVER_ERROR:
return False
if status_code == HTTP_CODE_ZERO:
bambou_logger.error("NURESTConnection: Connection error with code 0. Sending NUNURESTConnectionFailureNotification notification and exiting.")
return False
bambou_logger.error("NURESTConnection: Report this error, because this should not happen: %s" % self._response)
return False
|
[
"def",
"handle_response_for_connection",
"(",
"self",
",",
"should_post",
"=",
"False",
")",
":",
"status_code",
"=",
"self",
".",
"_response",
".",
"status_code",
"data",
"=",
"self",
".",
"_response",
".",
"data",
"# TODO : Get errors in response data after bug fix : http://mvjira.mv.usa.alcatel.com/browse/VSD-2735",
"if",
"data",
"and",
"'errors'",
"in",
"data",
":",
"self",
".",
"_response",
".",
"errors",
"=",
"data",
"[",
"'errors'",
"]",
"if",
"status_code",
"in",
"[",
"HTTP_CODE_SUCCESS",
",",
"HTTP_CODE_CREATED",
",",
"HTTP_CODE_EMPTY",
"]",
":",
"return",
"True",
"if",
"status_code",
"==",
"HTTP_CODE_MULTIPLE_CHOICES",
":",
"return",
"False",
"if",
"status_code",
"in",
"[",
"HTTP_CODE_PERMISSION_DENIED",
",",
"HTTP_CODE_UNAUTHORIZED",
"]",
":",
"if",
"not",
"should_post",
":",
"return",
"True",
"return",
"False",
"if",
"status_code",
"in",
"[",
"HTTP_CODE_CONFLICT",
",",
"HTTP_CODE_NOT_FOUND",
",",
"HTTP_CODE_BAD_REQUEST",
",",
"HTTP_CODE_METHOD_NOT_ALLOWED",
",",
"HTTP_CODE_PRECONDITION_FAILED",
",",
"HTTP_CODE_SERVICE_UNAVAILABLE",
"]",
":",
"if",
"not",
"should_post",
":",
"return",
"True",
"return",
"False",
"if",
"status_code",
"==",
"HTTP_CODE_INTERNAL_SERVER_ERROR",
":",
"return",
"False",
"if",
"status_code",
"==",
"HTTP_CODE_ZERO",
":",
"bambou_logger",
".",
"error",
"(",
"\"NURESTConnection: Connection error with code 0. Sending NUNURESTConnectionFailureNotification notification and exiting.\"",
")",
"return",
"False",
"bambou_logger",
".",
"error",
"(",
"\"NURESTConnection: Report this error, because this should not happen: %s\"",
"%",
"self",
".",
"_response",
")",
"return",
"False"
] |
Check if the response succeed or not.
In case of error, this method also print messages and set
an array of errors in the response object.
Returns:
Returns True if the response has succeed, False otherwise
|
[
"Check",
"if",
"the",
"response",
"succeed",
"or",
"not",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L260-L305
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection._did_receive_response
|
def _did_receive_response(self, response):
""" Called when a response is received """
try:
data = response.json()
except:
data = None
self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason)
level = logging.WARNING if self._response.status_code >= 300 else logging.DEBUG
bambou_logger.info('< %s %s %s [%s] ' % (self._request.method, self._request.url, self._request.params if self._request.params else "", self._response.status_code))
bambou_logger.log(level, '< headers: %s' % self._response.headers)
bambou_logger.log(level, '< data:\n%s' % json.dumps(self._response.data, indent=4))
self._callback(self)
return self
|
python
|
def _did_receive_response(self, response):
""" Called when a response is received """
try:
data = response.json()
except:
data = None
self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason)
level = logging.WARNING if self._response.status_code >= 300 else logging.DEBUG
bambou_logger.info('< %s %s %s [%s] ' % (self._request.method, self._request.url, self._request.params if self._request.params else "", self._response.status_code))
bambou_logger.log(level, '< headers: %s' % self._response.headers)
bambou_logger.log(level, '< data:\n%s' % json.dumps(self._response.data, indent=4))
self._callback(self)
return self
|
[
"def",
"_did_receive_response",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"except",
":",
"data",
"=",
"None",
"self",
".",
"_response",
"=",
"NURESTResponse",
"(",
"status_code",
"=",
"response",
".",
"status_code",
",",
"headers",
"=",
"response",
".",
"headers",
",",
"data",
"=",
"data",
",",
"reason",
"=",
"response",
".",
"reason",
")",
"level",
"=",
"logging",
".",
"WARNING",
"if",
"self",
".",
"_response",
".",
"status_code",
">=",
"300",
"else",
"logging",
".",
"DEBUG",
"bambou_logger",
".",
"info",
"(",
"'< %s %s %s [%s] '",
"%",
"(",
"self",
".",
"_request",
".",
"method",
",",
"self",
".",
"_request",
".",
"url",
",",
"self",
".",
"_request",
".",
"params",
"if",
"self",
".",
"_request",
".",
"params",
"else",
"\"\"",
",",
"self",
".",
"_response",
".",
"status_code",
")",
")",
"bambou_logger",
".",
"log",
"(",
"level",
",",
"'< headers: %s'",
"%",
"self",
".",
"_response",
".",
"headers",
")",
"bambou_logger",
".",
"log",
"(",
"level",
",",
"'< data:\\n%s'",
"%",
"json",
".",
"dumps",
"(",
"self",
".",
"_response",
".",
"data",
",",
"indent",
"=",
"4",
")",
")",
"self",
".",
"_callback",
"(",
"self",
")",
"return",
"self"
] |
Called when a response is received
|
[
"Called",
"when",
"a",
"response",
"is",
"received"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L309-L326
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection._did_timeout
|
def _did_timeout(self):
""" Called when a resquest has timeout """
bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout))
self._has_timeouted = True
if self.async:
self._callback(self)
else:
return self
|
python
|
def _did_timeout(self):
""" Called when a resquest has timeout """
bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout))
self._has_timeouted = True
if self.async:
self._callback(self)
else:
return self
|
[
"def",
"_did_timeout",
"(",
"self",
")",
":",
"bambou_logger",
".",
"debug",
"(",
"'Bambou %s on %s has timeout (timeout=%ss)..'",
"%",
"(",
"self",
".",
"_request",
".",
"method",
",",
"self",
".",
"_request",
".",
"url",
",",
"self",
".",
"timeout",
")",
")",
"self",
".",
"_has_timeouted",
"=",
"True",
"if",
"self",
".",
"async",
":",
"self",
".",
"_callback",
"(",
"self",
")",
"else",
":",
"return",
"self"
] |
Called when a resquest has timeout
|
[
"Called",
"when",
"a",
"resquest",
"has",
"timeout"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L328-L337
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection._make_request
|
def _make_request(self, session=None):
""" Make a synchronous request """
if session is None:
session = NURESTSession.get_current_session()
self._has_timeouted = False
# Add specific headers
controller = session.login_controller
enterprise = controller.enterprise
user_name = controller.user
api_key = controller.api_key
certificate = controller.certificate
if self._root_object:
enterprise = self._root_object.enterprise_name
user_name = self._root_object.user_name
api_key = self._root_object.api_key
if self._uses_authentication:
self._request.set_header('X-Nuage-Organization', enterprise)
self._request.set_header('Authorization', controller.get_authentication_header(user_name, api_key))
if controller.is_impersonating:
self._request.set_header('X-Nuage-ProxyUser', controller.impersonation)
headers = self._request.headers
data = json.dumps(self._request.data)
bambou_logger.info('> %s %s %s' % (self._request.method, self._request.url, self._request.params if self._request.params else ""))
bambou_logger.debug('> headers: %s' % headers)
bambou_logger.debug('> data:\n %s' % json.dumps(self._request.data, indent=4))
response = self.__make_request(requests_session=session.requests_session, method=self._request.method, url=self._request.url, params=self._request.params, data=data, headers=headers, certificate=certificate)
retry_request = False
if response.status_code == HTTP_CODE_MULTIPLE_CHOICES:
self._request.url += '?responseChoice=1'
bambou_logger.debug('Bambou got [%s] response. Trying to force response choice' % HTTP_CODE_MULTIPLE_CHOICES)
retry_request = True
elif response.status_code == HTTP_CODE_AUTHENTICATION_EXPIRED and session:
bambou_logger.debug('Bambou got [%s] response . Trying to reconnect your session that has expired' % HTTP_CODE_AUTHENTICATION_EXPIRED)
session.reset()
session.start()
retry_request = True
if retry_request:
response = self.__make_request(requests_session=session.requests_session, method=self._request.method, url=self._request.url, params=self._request.params, data=data, headers=headers, certificate=certificate)
return self._did_receive_response(response)
|
python
|
def _make_request(self, session=None):
""" Make a synchronous request """
if session is None:
session = NURESTSession.get_current_session()
self._has_timeouted = False
# Add specific headers
controller = session.login_controller
enterprise = controller.enterprise
user_name = controller.user
api_key = controller.api_key
certificate = controller.certificate
if self._root_object:
enterprise = self._root_object.enterprise_name
user_name = self._root_object.user_name
api_key = self._root_object.api_key
if self._uses_authentication:
self._request.set_header('X-Nuage-Organization', enterprise)
self._request.set_header('Authorization', controller.get_authentication_header(user_name, api_key))
if controller.is_impersonating:
self._request.set_header('X-Nuage-ProxyUser', controller.impersonation)
headers = self._request.headers
data = json.dumps(self._request.data)
bambou_logger.info('> %s %s %s' % (self._request.method, self._request.url, self._request.params if self._request.params else ""))
bambou_logger.debug('> headers: %s' % headers)
bambou_logger.debug('> data:\n %s' % json.dumps(self._request.data, indent=4))
response = self.__make_request(requests_session=session.requests_session, method=self._request.method, url=self._request.url, params=self._request.params, data=data, headers=headers, certificate=certificate)
retry_request = False
if response.status_code == HTTP_CODE_MULTIPLE_CHOICES:
self._request.url += '?responseChoice=1'
bambou_logger.debug('Bambou got [%s] response. Trying to force response choice' % HTTP_CODE_MULTIPLE_CHOICES)
retry_request = True
elif response.status_code == HTTP_CODE_AUTHENTICATION_EXPIRED and session:
bambou_logger.debug('Bambou got [%s] response . Trying to reconnect your session that has expired' % HTTP_CODE_AUTHENTICATION_EXPIRED)
session.reset()
session.start()
retry_request = True
if retry_request:
response = self.__make_request(requests_session=session.requests_session, method=self._request.method, url=self._request.url, params=self._request.params, data=data, headers=headers, certificate=certificate)
return self._did_receive_response(response)
|
[
"def",
"_make_request",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"NURESTSession",
".",
"get_current_session",
"(",
")",
"self",
".",
"_has_timeouted",
"=",
"False",
"# Add specific headers",
"controller",
"=",
"session",
".",
"login_controller",
"enterprise",
"=",
"controller",
".",
"enterprise",
"user_name",
"=",
"controller",
".",
"user",
"api_key",
"=",
"controller",
".",
"api_key",
"certificate",
"=",
"controller",
".",
"certificate",
"if",
"self",
".",
"_root_object",
":",
"enterprise",
"=",
"self",
".",
"_root_object",
".",
"enterprise_name",
"user_name",
"=",
"self",
".",
"_root_object",
".",
"user_name",
"api_key",
"=",
"self",
".",
"_root_object",
".",
"api_key",
"if",
"self",
".",
"_uses_authentication",
":",
"self",
".",
"_request",
".",
"set_header",
"(",
"'X-Nuage-Organization'",
",",
"enterprise",
")",
"self",
".",
"_request",
".",
"set_header",
"(",
"'Authorization'",
",",
"controller",
".",
"get_authentication_header",
"(",
"user_name",
",",
"api_key",
")",
")",
"if",
"controller",
".",
"is_impersonating",
":",
"self",
".",
"_request",
".",
"set_header",
"(",
"'X-Nuage-ProxyUser'",
",",
"controller",
".",
"impersonation",
")",
"headers",
"=",
"self",
".",
"_request",
".",
"headers",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_request",
".",
"data",
")",
"bambou_logger",
".",
"info",
"(",
"'> %s %s %s'",
"%",
"(",
"self",
".",
"_request",
".",
"method",
",",
"self",
".",
"_request",
".",
"url",
",",
"self",
".",
"_request",
".",
"params",
"if",
"self",
".",
"_request",
".",
"params",
"else",
"\"\"",
")",
")",
"bambou_logger",
".",
"debug",
"(",
"'> headers: %s'",
"%",
"headers",
")",
"bambou_logger",
".",
"debug",
"(",
"'> data:\\n %s'",
"%",
"json",
".",
"dumps",
"(",
"self",
".",
"_request",
".",
"data",
",",
"indent",
"=",
"4",
")",
")",
"response",
"=",
"self",
".",
"__make_request",
"(",
"requests_session",
"=",
"session",
".",
"requests_session",
",",
"method",
"=",
"self",
".",
"_request",
".",
"method",
",",
"url",
"=",
"self",
".",
"_request",
".",
"url",
",",
"params",
"=",
"self",
".",
"_request",
".",
"params",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"certificate",
"=",
"certificate",
")",
"retry_request",
"=",
"False",
"if",
"response",
".",
"status_code",
"==",
"HTTP_CODE_MULTIPLE_CHOICES",
":",
"self",
".",
"_request",
".",
"url",
"+=",
"'?responseChoice=1'",
"bambou_logger",
".",
"debug",
"(",
"'Bambou got [%s] response. Trying to force response choice'",
"%",
"HTTP_CODE_MULTIPLE_CHOICES",
")",
"retry_request",
"=",
"True",
"elif",
"response",
".",
"status_code",
"==",
"HTTP_CODE_AUTHENTICATION_EXPIRED",
"and",
"session",
":",
"bambou_logger",
".",
"debug",
"(",
"'Bambou got [%s] response . Trying to reconnect your session that has expired'",
"%",
"HTTP_CODE_AUTHENTICATION_EXPIRED",
")",
"session",
".",
"reset",
"(",
")",
"session",
".",
"start",
"(",
")",
"retry_request",
"=",
"True",
"if",
"retry_request",
":",
"response",
"=",
"self",
".",
"__make_request",
"(",
"requests_session",
"=",
"session",
".",
"requests_session",
",",
"method",
"=",
"self",
".",
"_request",
".",
"method",
",",
"url",
"=",
"self",
".",
"_request",
".",
"url",
",",
"params",
"=",
"self",
".",
"_request",
".",
"params",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"certificate",
"=",
"certificate",
")",
"return",
"self",
".",
"_did_receive_response",
"(",
"response",
")"
] |
Make a synchronous request
|
[
"Make",
"a",
"synchronous",
"request"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L339-L392
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection.__make_request
|
def __make_request(self, requests_session, method, url, params, data, headers, certificate):
""" Encapsulate requests call
"""
verify = False
timeout = self.timeout
try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546
response = requests_session.request(method=method,
url=url,
data=data,
headers=headers,
verify=verify,
timeout=timeout,
params=params,
cert=certificate)
except requests.exceptions.SSLError:
try:
response = requests_session.request(method=method,
url=url,
data=data,
headers=headers,
verify=verify,
timeout=timeout,
params=params,
cert=certificate)
except requests.exceptions.Timeout:
return self._did_timeout()
except requests.exceptions.Timeout:
return self._did_timeout()
return response
|
python
|
def __make_request(self, requests_session, method, url, params, data, headers, certificate):
""" Encapsulate requests call
"""
verify = False
timeout = self.timeout
try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546
response = requests_session.request(method=method,
url=url,
data=data,
headers=headers,
verify=verify,
timeout=timeout,
params=params,
cert=certificate)
except requests.exceptions.SSLError:
try:
response = requests_session.request(method=method,
url=url,
data=data,
headers=headers,
verify=verify,
timeout=timeout,
params=params,
cert=certificate)
except requests.exceptions.Timeout:
return self._did_timeout()
except requests.exceptions.Timeout:
return self._did_timeout()
return response
|
[
"def",
"__make_request",
"(",
"self",
",",
"requests_session",
",",
"method",
",",
"url",
",",
"params",
",",
"data",
",",
"headers",
",",
"certificate",
")",
":",
"verify",
"=",
"False",
"timeout",
"=",
"self",
".",
"timeout",
"try",
":",
"# TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546",
"response",
"=",
"requests_session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"verify",
",",
"timeout",
"=",
"timeout",
",",
"params",
"=",
"params",
",",
"cert",
"=",
"certificate",
")",
"except",
"requests",
".",
"exceptions",
".",
"SSLError",
":",
"try",
":",
"response",
"=",
"requests_session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"verify",
",",
"timeout",
"=",
"timeout",
",",
"params",
"=",
"params",
",",
"cert",
"=",
"certificate",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"return",
"self",
".",
"_did_timeout",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"return",
"self",
".",
"_did_timeout",
"(",
")",
"return",
"response"
] |
Encapsulate requests call
|
[
"Encapsulate",
"requests",
"call"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L394-L425
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection.start
|
def start(self):
""" Make an HTTP request with a specific method """
# TODO : Use Timeout here and _ignore_request_idle
from .nurest_session import NURESTSession
session = NURESTSession.get_current_session()
if self.async:
thread = threading.Thread(target=self._make_request, kwargs={'session': session})
thread.is_daemon = False
thread.start()
return self.transaction_id
return self._make_request(session=session)
|
python
|
def start(self):
""" Make an HTTP request with a specific method """
# TODO : Use Timeout here and _ignore_request_idle
from .nurest_session import NURESTSession
session = NURESTSession.get_current_session()
if self.async:
thread = threading.Thread(target=self._make_request, kwargs={'session': session})
thread.is_daemon = False
thread.start()
return self.transaction_id
return self._make_request(session=session)
|
[
"def",
"start",
"(",
"self",
")",
":",
"# TODO : Use Timeout here and _ignore_request_idle",
"from",
".",
"nurest_session",
"import",
"NURESTSession",
"session",
"=",
"NURESTSession",
".",
"get_current_session",
"(",
")",
"if",
"self",
".",
"async",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_make_request",
",",
"kwargs",
"=",
"{",
"'session'",
":",
"session",
"}",
")",
"thread",
".",
"is_daemon",
"=",
"False",
"thread",
".",
"start",
"(",
")",
"return",
"self",
".",
"transaction_id",
"return",
"self",
".",
"_make_request",
"(",
"session",
"=",
"session",
")"
] |
Make an HTTP request with a specific method
|
[
"Make",
"an",
"HTTP",
"request",
"with",
"a",
"specific",
"method"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L427-L440
|
train
|
nuagenetworks/bambou
|
bambou/nurest_connection.py
|
NURESTConnection.reset
|
def reset(self):
""" Reset the connection
"""
self._request = None
self._response = None
self._transaction_id = uuid.uuid4().hex
|
python
|
def reset(self):
""" Reset the connection
"""
self._request = None
self._response = None
self._transaction_id = uuid.uuid4().hex
|
[
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_request",
"=",
"None",
"self",
".",
"_response",
"=",
"None",
"self",
".",
"_transaction_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex"
] |
Reset the connection
|
[
"Reset",
"the",
"connection"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L442-L448
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/managers.py
|
ConsumptionDetailsQuerySet.create
|
def create(self, price_estimate):
""" Take configuration from previous month, it it exists.
Set last_update_time equals to the beginning of the month.
"""
kwargs = {}
try:
previous_price_estimate = price_estimate.get_previous()
except ObjectDoesNotExist:
pass
else:
configuration = previous_price_estimate.consumption_details.configuration
kwargs['configuration'] = configuration
month_start = core_utils.month_start(datetime.date(price_estimate.year, price_estimate.month, 1))
kwargs['last_update_time'] = month_start
return super(ConsumptionDetailsQuerySet, self).create(price_estimate=price_estimate, **kwargs)
|
python
|
def create(self, price_estimate):
""" Take configuration from previous month, it it exists.
Set last_update_time equals to the beginning of the month.
"""
kwargs = {}
try:
previous_price_estimate = price_estimate.get_previous()
except ObjectDoesNotExist:
pass
else:
configuration = previous_price_estimate.consumption_details.configuration
kwargs['configuration'] = configuration
month_start = core_utils.month_start(datetime.date(price_estimate.year, price_estimate.month, 1))
kwargs['last_update_time'] = month_start
return super(ConsumptionDetailsQuerySet, self).create(price_estimate=price_estimate, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"price_estimate",
")",
":",
"kwargs",
"=",
"{",
"}",
"try",
":",
"previous_price_estimate",
"=",
"price_estimate",
".",
"get_previous",
"(",
")",
"except",
"ObjectDoesNotExist",
":",
"pass",
"else",
":",
"configuration",
"=",
"previous_price_estimate",
".",
"consumption_details",
".",
"configuration",
"kwargs",
"[",
"'configuration'",
"]",
"=",
"configuration",
"month_start",
"=",
"core_utils",
".",
"month_start",
"(",
"datetime",
".",
"date",
"(",
"price_estimate",
".",
"year",
",",
"price_estimate",
".",
"month",
",",
"1",
")",
")",
"kwargs",
"[",
"'last_update_time'",
"]",
"=",
"month_start",
"return",
"super",
"(",
"ConsumptionDetailsQuerySet",
",",
"self",
")",
".",
"create",
"(",
"price_estimate",
"=",
"price_estimate",
",",
"*",
"*",
"kwargs",
")"
] |
Take configuration from previous month, it it exists.
Set last_update_time equals to the beginning of the month.
|
[
"Take",
"configuration",
"from",
"previous",
"month",
"it",
"it",
"exists",
".",
"Set",
"last_update_time",
"equals",
"to",
"the",
"beginning",
"of",
"the",
"month",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/managers.py#L59-L73
|
train
|
opennode/waldur-core
|
waldur_core/logging/serializers.py
|
BaseHookSerializer.get_fields
|
def get_fields(self):
"""
When static declaration is used, event type choices are fetched too early -
even before all apps are initialized. As a result, some event types are missing.
When dynamic declaration is used, all valid event types are available as choices.
"""
fields = super(BaseHookSerializer, self).get_fields()
fields['event_types'] = serializers.MultipleChoiceField(
choices=loggers.get_valid_events(), required=False)
fields['event_groups'] = serializers.MultipleChoiceField(
choices=loggers.get_event_groups_keys(), required=False)
return fields
|
python
|
def get_fields(self):
"""
When static declaration is used, event type choices are fetched too early -
even before all apps are initialized. As a result, some event types are missing.
When dynamic declaration is used, all valid event types are available as choices.
"""
fields = super(BaseHookSerializer, self).get_fields()
fields['event_types'] = serializers.MultipleChoiceField(
choices=loggers.get_valid_events(), required=False)
fields['event_groups'] = serializers.MultipleChoiceField(
choices=loggers.get_event_groups_keys(), required=False)
return fields
|
[
"def",
"get_fields",
"(",
"self",
")",
":",
"fields",
"=",
"super",
"(",
"BaseHookSerializer",
",",
"self",
")",
".",
"get_fields",
"(",
")",
"fields",
"[",
"'event_types'",
"]",
"=",
"serializers",
".",
"MultipleChoiceField",
"(",
"choices",
"=",
"loggers",
".",
"get_valid_events",
"(",
")",
",",
"required",
"=",
"False",
")",
"fields",
"[",
"'event_groups'",
"]",
"=",
"serializers",
".",
"MultipleChoiceField",
"(",
"choices",
"=",
"loggers",
".",
"get_event_groups_keys",
"(",
")",
",",
"required",
"=",
"False",
")",
"return",
"fields"
] |
When static declaration is used, event type choices are fetched too early -
even before all apps are initialized. As a result, some event types are missing.
When dynamic declaration is used, all valid event types are available as choices.
|
[
"When",
"static",
"declaration",
"is",
"used",
"event",
"type",
"choices",
"are",
"fetched",
"too",
"early",
"-",
"even",
"before",
"all",
"apps",
"are",
"initialized",
".",
"As",
"a",
"result",
"some",
"event",
"types",
"are",
"missing",
".",
"When",
"dynamic",
"declaration",
"is",
"used",
"all",
"valid",
"event",
"types",
"are",
"available",
"as",
"choices",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/serializers.py#L68-L79
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/serializers.py
|
PriceEstimateSerializer.build_nested_field
|
def build_nested_field(self, field_name, relation_info, nested_depth):
""" Use PriceEstimateSerializer to serialize estimate children """
if field_name != 'children':
return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth)
field_class = self.__class__
field_kwargs = {'read_only': True, 'many': True, 'context': {'depth': nested_depth - 1}}
return field_class, field_kwargs
|
python
|
def build_nested_field(self, field_name, relation_info, nested_depth):
""" Use PriceEstimateSerializer to serialize estimate children """
if field_name != 'children':
return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth)
field_class = self.__class__
field_kwargs = {'read_only': True, 'many': True, 'context': {'depth': nested_depth - 1}}
return field_class, field_kwargs
|
[
"def",
"build_nested_field",
"(",
"self",
",",
"field_name",
",",
"relation_info",
",",
"nested_depth",
")",
":",
"if",
"field_name",
"!=",
"'children'",
":",
"return",
"super",
"(",
"PriceEstimateSerializer",
",",
"self",
")",
".",
"build_nested_field",
"(",
"field_name",
",",
"relation_info",
",",
"nested_depth",
")",
"field_class",
"=",
"self",
".",
"__class__",
"field_kwargs",
"=",
"{",
"'read_only'",
":",
"True",
",",
"'many'",
":",
"True",
",",
"'context'",
":",
"{",
"'depth'",
":",
"nested_depth",
"-",
"1",
"}",
"}",
"return",
"field_class",
",",
"field_kwargs"
] |
Use PriceEstimateSerializer to serialize estimate children
|
[
"Use",
"PriceEstimateSerializer",
"to",
"serialize",
"estimate",
"children"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/serializers.py#L43-L49
|
train
|
quora/qcore
|
qcore/errors.py
|
prepare_for_reraise
|
def prepare_for_reraise(error, exc_info=None):
"""Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
"""
if not hasattr(error, "_type_"):
if exc_info is None:
exc_info = sys.exc_info()
error._type_ = exc_info[0]
error._traceback = exc_info[2]
return error
|
python
|
def prepare_for_reraise(error, exc_info=None):
"""Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
"""
if not hasattr(error, "_type_"):
if exc_info is None:
exc_info = sys.exc_info()
error._type_ = exc_info[0]
error._traceback = exc_info[2]
return error
|
[
"def",
"prepare_for_reraise",
"(",
"error",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"error",
",",
"\"_type_\"",
")",
":",
"if",
"exc_info",
"is",
"None",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"error",
".",
"_type_",
"=",
"exc_info",
"[",
"0",
"]",
"error",
".",
"_traceback",
"=",
"exc_info",
"[",
"2",
"]",
"return",
"error"
] |
Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
|
[
"Prepares",
"the",
"exception",
"for",
"re",
"-",
"raising",
"with",
"reraise",
"method",
"."
] |
fa5cd438eea554db35fd29cbc8dfbde69f09961c
|
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/errors.py#L72-L84
|
train
|
quora/qcore
|
qcore/errors.py
|
reraise
|
def reraise(error):
"""Re-raises the error that was processed by prepare_for_reraise earlier."""
if hasattr(error, "_type_"):
six.reraise(type(error), error, error._traceback)
raise error
|
python
|
def reraise(error):
"""Re-raises the error that was processed by prepare_for_reraise earlier."""
if hasattr(error, "_type_"):
six.reraise(type(error), error, error._traceback)
raise error
|
[
"def",
"reraise",
"(",
"error",
")",
":",
"if",
"hasattr",
"(",
"error",
",",
"\"_type_\"",
")",
":",
"six",
".",
"reraise",
"(",
"type",
"(",
"error",
")",
",",
"error",
",",
"error",
".",
"_traceback",
")",
"raise",
"error"
] |
Re-raises the error that was processed by prepare_for_reraise earlier.
|
[
"Re",
"-",
"raises",
"the",
"error",
"that",
"was",
"processed",
"by",
"prepare_for_reraise",
"earlier",
"."
] |
fa5cd438eea554db35fd29cbc8dfbde69f09961c
|
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/errors.py#L90-L94
|
train
|
stepank/pyws
|
src/pyws/functions/register.py
|
register
|
def register(*args, **kwargs):
"""
Creates a registrator that, being called with a function as the only
argument, wraps a function with ``pyws.functions.NativeFunctionAdapter``
and registers it to the server. Arguments are exactly the same as for
``pyws.functions.NativeFunctionAdapter`` except that you can pass
an additional keyword argument ``to`` designating the name of the server
which the function must be registered to:
>>> from pyws.server import Server
>>> server = Server()
>>> from pyws.functions.register import register
>>> @register()
... def say_hello(name):
... return 'Hello, %s' % name
>>> server.get_functions(context=None)[0].name
'say_hello'
>>> another_server = Server(dict(NAME='another_server'))
>>> @register(to='another_server', return_type=int, args=(int, 0))
... def gimme_more(x):
... return x * 2
>>> another_server.get_functions(context=None)[0].name
'gimme_more'
"""
if args and callable(args[0]):
raise ConfigurationError(
'You might have tried to decorate a function directly with '
'@register which is not supported, use @register(...) instead')
def registrator(origin):
try:
server = SERVERS[kwargs.pop('to')]
except KeyError:
server = SERVERS.default
server.add_function(
NativeFunctionAdapter(origin, *args, **kwargs))
return origin
return registrator
|
python
|
def register(*args, **kwargs):
"""
Creates a registrator that, being called with a function as the only
argument, wraps a function with ``pyws.functions.NativeFunctionAdapter``
and registers it to the server. Arguments are exactly the same as for
``pyws.functions.NativeFunctionAdapter`` except that you can pass
an additional keyword argument ``to`` designating the name of the server
which the function must be registered to:
>>> from pyws.server import Server
>>> server = Server()
>>> from pyws.functions.register import register
>>> @register()
... def say_hello(name):
... return 'Hello, %s' % name
>>> server.get_functions(context=None)[0].name
'say_hello'
>>> another_server = Server(dict(NAME='another_server'))
>>> @register(to='another_server', return_type=int, args=(int, 0))
... def gimme_more(x):
... return x * 2
>>> another_server.get_functions(context=None)[0].name
'gimme_more'
"""
if args and callable(args[0]):
raise ConfigurationError(
'You might have tried to decorate a function directly with '
'@register which is not supported, use @register(...) instead')
def registrator(origin):
try:
server = SERVERS[kwargs.pop('to')]
except KeyError:
server = SERVERS.default
server.add_function(
NativeFunctionAdapter(origin, *args, **kwargs))
return origin
return registrator
|
[
"def",
"register",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"raise",
"ConfigurationError",
"(",
"'You might have tried to decorate a function directly with '",
"'@register which is not supported, use @register(...) instead'",
")",
"def",
"registrator",
"(",
"origin",
")",
":",
"try",
":",
"server",
"=",
"SERVERS",
"[",
"kwargs",
".",
"pop",
"(",
"'to'",
")",
"]",
"except",
"KeyError",
":",
"server",
"=",
"SERVERS",
".",
"default",
"server",
".",
"add_function",
"(",
"NativeFunctionAdapter",
"(",
"origin",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"origin",
"return",
"registrator"
] |
Creates a registrator that, being called with a function as the only
argument, wraps a function with ``pyws.functions.NativeFunctionAdapter``
and registers it to the server. Arguments are exactly the same as for
``pyws.functions.NativeFunctionAdapter`` except that you can pass
an additional keyword argument ``to`` designating the name of the server
which the function must be registered to:
>>> from pyws.server import Server
>>> server = Server()
>>> from pyws.functions.register import register
>>> @register()
... def say_hello(name):
... return 'Hello, %s' % name
>>> server.get_functions(context=None)[0].name
'say_hello'
>>> another_server = Server(dict(NAME='another_server'))
>>> @register(to='another_server', return_type=int, args=(int, 0))
... def gimme_more(x):
... return x * 2
>>> another_server.get_functions(context=None)[0].name
'gimme_more'
|
[
"Creates",
"a",
"registrator",
"that",
"being",
"called",
"with",
"a",
"function",
"as",
"the",
"only",
"argument",
"wraps",
"a",
"function",
"with",
"pyws",
".",
"functions",
".",
"NativeFunctionAdapter",
"and",
"registers",
"it",
"to",
"the",
"server",
".",
"Arguments",
"are",
"exactly",
"the",
"same",
"as",
"for",
"pyws",
".",
"functions",
".",
"NativeFunctionAdapter",
"except",
"that",
"you",
"can",
"pass",
"an",
"additional",
"keyword",
"argument",
"to",
"designating",
"the",
"name",
"of",
"the",
"server",
"which",
"the",
"function",
"must",
"be",
"registered",
"to",
":"
] |
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
|
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/register.py#L9-L47
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NUMetaRESTObject.rest_name
|
def rest_name(cls):
""" Represents a singular REST name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__rest_name__ is None:
raise NotImplementedError('%s has no defined name. Implement rest_name property first.' % cls)
return cls.__rest_name__
|
python
|
def rest_name(cls):
""" Represents a singular REST name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__rest_name__ is None:
raise NotImplementedError('%s has no defined name. Implement rest_name property first.' % cls)
return cls.__rest_name__
|
[
"def",
"rest_name",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__name__",
"==",
"\"NURESTRootObject\"",
"or",
"cls",
".",
"__name__",
"==",
"\"NURESTObject\"",
":",
"return",
"\"Not Implemented\"",
"if",
"cls",
".",
"__rest_name__",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'%s has no defined name. Implement rest_name property first.'",
"%",
"cls",
")",
"return",
"cls",
".",
"__rest_name__"
] |
Represents a singular REST name
|
[
"Represents",
"a",
"singular",
"REST",
"name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L51-L60
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NUMetaRESTObject.resource_name
|
def resource_name(cls):
""" Represents the resource name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__resource_name__ is None:
raise NotImplementedError('%s has no defined resource name. Implement resource_name property first.' % cls)
return cls.__resource_name__
|
python
|
def resource_name(cls):
""" Represents the resource name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__resource_name__ is None:
raise NotImplementedError('%s has no defined resource name. Implement resource_name property first.' % cls)
return cls.__resource_name__
|
[
"def",
"resource_name",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__name__",
"==",
"\"NURESTRootObject\"",
"or",
"cls",
".",
"__name__",
"==",
"\"NURESTObject\"",
":",
"return",
"\"Not Implemented\"",
"if",
"cls",
".",
"__resource_name__",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'%s has no defined resource name. Implement resource_name property first.'",
"%",
"cls",
")",
"return",
"cls",
".",
"__resource_name__"
] |
Represents the resource name
|
[
"Represents",
"the",
"resource",
"name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L63-L72
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._compute_args
|
def _compute_args(self, data=dict(), **kwargs):
""" Compute the arguments
Try to import attributes from data.
Otherwise compute kwargs arguments.
Args:
data: a dict()
kwargs: a list of arguments
"""
for name, remote_attribute in self._attributes.items():
default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type)
setattr(self, name, default_value)
if len(data) > 0:
self.from_dict(data)
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
|
python
|
def _compute_args(self, data=dict(), **kwargs):
""" Compute the arguments
Try to import attributes from data.
Otherwise compute kwargs arguments.
Args:
data: a dict()
kwargs: a list of arguments
"""
for name, remote_attribute in self._attributes.items():
default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type)
setattr(self, name, default_value)
if len(data) > 0:
self.from_dict(data)
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
|
[
"def",
"_compute_args",
"(",
"self",
",",
"data",
"=",
"dict",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"remote_attribute",
"in",
"self",
".",
"_attributes",
".",
"items",
"(",
")",
":",
"default_value",
"=",
"BambouConfig",
".",
"get_default_attribute_value",
"(",
"self",
".",
"__class__",
",",
"name",
",",
"remote_attribute",
".",
"attribute_type",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"default_value",
")",
"if",
"len",
"(",
"data",
")",
">",
"0",
":",
"self",
".",
"from_dict",
"(",
"data",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"key",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")"
] |
Compute the arguments
Try to import attributes from data.
Otherwise compute kwargs arguments.
Args:
data: a dict()
kwargs: a list of arguments
|
[
"Compute",
"the",
"arguments"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L116-L136
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.children_rest_names
|
def children_rest_names(self):
""" Gets the list of all possible children ReST names.
Returns:
list: list containing all possible rest names as string
Example:
>>> entity = NUEntity()
>>> entity.children_rest_names
["foo", "bar"]
"""
names = []
for fetcher in self.fetchers:
names.append(fetcher.__class__.managed_object_rest_name())
return names
|
python
|
def children_rest_names(self):
""" Gets the list of all possible children ReST names.
Returns:
list: list containing all possible rest names as string
Example:
>>> entity = NUEntity()
>>> entity.children_rest_names
["foo", "bar"]
"""
names = []
for fetcher in self.fetchers:
names.append(fetcher.__class__.managed_object_rest_name())
return names
|
[
"def",
"children_rest_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"for",
"fetcher",
"in",
"self",
".",
"fetchers",
":",
"names",
".",
"append",
"(",
"fetcher",
".",
"__class__",
".",
"managed_object_rest_name",
"(",
")",
")",
"return",
"names"
] |
Gets the list of all possible children ReST names.
Returns:
list: list containing all possible rest names as string
Example:
>>> entity = NUEntity()
>>> entity.children_rest_names
["foo", "bar"]
|
[
"Gets",
"the",
"list",
"of",
"all",
"possible",
"children",
"ReST",
"names",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L266-L283
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.get_resource_url
|
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
if self.id is not None:
return "%s/%s/%s" % (url, name, self.id)
return "%s/%s" % (url, name)
|
python
|
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
if self.id is not None:
return "%s/%s/%s" % (url, name, self.id)
return "%s/%s" % (url, name)
|
[
"def",
"get_resource_url",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"__class__",
".",
"resource_name",
"url",
"=",
"self",
".",
"__class__",
".",
"rest_base_url",
"(",
")",
"if",
"self",
".",
"id",
"is",
"not",
"None",
":",
"return",
"\"%s/%s/%s\"",
"%",
"(",
"url",
",",
"name",
",",
"self",
".",
"id",
")",
"return",
"\"%s/%s\"",
"%",
"(",
"url",
",",
"name",
")"
] |
Get resource complete url
|
[
"Get",
"resource",
"complete",
"url"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L309-L318
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.validate
|
def validate(self):
""" Validate the current object attributes.
Check all attributes and store errors
Returns:
Returns True if all attibutes of the object
respect contraints. Returns False otherwise and
store error in errors dict.
"""
self._attribute_errors = dict() # Reset validation errors
for local_name, attribute in self._attributes.items():
value = getattr(self, local_name, None)
if attribute.is_required and (value is None or value == ""):
self._attribute_errors[local_name] = {'title': 'Invalid input',
'description': 'This value is mandatory.',
'remote_name': attribute.remote_name}
continue
if value is None:
continue # without error
if not self._validate_type(local_name, attribute.remote_name, value, attribute.attribute_type):
continue
if attribute.min_length is not None and len(value) < attribute.min_length:
self._attribute_errors[local_name] = {'title': 'Invalid length',
'description': 'Attribute %s minimum length should be %s but is %s' % (attribute.remote_name, attribute.min_length, len(value)),
'remote_name': attribute.remote_name}
continue
if attribute.max_length is not None and len(value) > attribute.max_length:
self._attribute_errors[local_name] = {'title': 'Invalid length',
'description': 'Attribute %s maximum length should be %s but is %s' % (attribute.remote_name, attribute.max_length, len(value)),
'remote_name': attribute.remote_name}
continue
if attribute.attribute_type == list:
valid = True
for item in value:
if valid is True:
valid = self._validate_value(local_name, attribute, item)
else:
self._validate_value(local_name, attribute, value)
return self.is_valid()
|
python
|
def validate(self):
""" Validate the current object attributes.
Check all attributes and store errors
Returns:
Returns True if all attibutes of the object
respect contraints. Returns False otherwise and
store error in errors dict.
"""
self._attribute_errors = dict() # Reset validation errors
for local_name, attribute in self._attributes.items():
value = getattr(self, local_name, None)
if attribute.is_required and (value is None or value == ""):
self._attribute_errors[local_name] = {'title': 'Invalid input',
'description': 'This value is mandatory.',
'remote_name': attribute.remote_name}
continue
if value is None:
continue # without error
if not self._validate_type(local_name, attribute.remote_name, value, attribute.attribute_type):
continue
if attribute.min_length is not None and len(value) < attribute.min_length:
self._attribute_errors[local_name] = {'title': 'Invalid length',
'description': 'Attribute %s minimum length should be %s but is %s' % (attribute.remote_name, attribute.min_length, len(value)),
'remote_name': attribute.remote_name}
continue
if attribute.max_length is not None and len(value) > attribute.max_length:
self._attribute_errors[local_name] = {'title': 'Invalid length',
'description': 'Attribute %s maximum length should be %s but is %s' % (attribute.remote_name, attribute.max_length, len(value)),
'remote_name': attribute.remote_name}
continue
if attribute.attribute_type == list:
valid = True
for item in value:
if valid is True:
valid = self._validate_value(local_name, attribute, item)
else:
self._validate_value(local_name, attribute, value)
return self.is_valid()
|
[
"def",
"validate",
"(",
"self",
")",
":",
"self",
".",
"_attribute_errors",
"=",
"dict",
"(",
")",
"# Reset validation errors",
"for",
"local_name",
",",
"attribute",
"in",
"self",
".",
"_attributes",
".",
"items",
"(",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"local_name",
",",
"None",
")",
"if",
"attribute",
".",
"is_required",
"and",
"(",
"value",
"is",
"None",
"or",
"value",
"==",
"\"\"",
")",
":",
"self",
".",
"_attribute_errors",
"[",
"local_name",
"]",
"=",
"{",
"'title'",
":",
"'Invalid input'",
",",
"'description'",
":",
"'This value is mandatory.'",
",",
"'remote_name'",
":",
"attribute",
".",
"remote_name",
"}",
"continue",
"if",
"value",
"is",
"None",
":",
"continue",
"# without error",
"if",
"not",
"self",
".",
"_validate_type",
"(",
"local_name",
",",
"attribute",
".",
"remote_name",
",",
"value",
",",
"attribute",
".",
"attribute_type",
")",
":",
"continue",
"if",
"attribute",
".",
"min_length",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
"<",
"attribute",
".",
"min_length",
":",
"self",
".",
"_attribute_errors",
"[",
"local_name",
"]",
"=",
"{",
"'title'",
":",
"'Invalid length'",
",",
"'description'",
":",
"'Attribute %s minimum length should be %s but is %s'",
"%",
"(",
"attribute",
".",
"remote_name",
",",
"attribute",
".",
"min_length",
",",
"len",
"(",
"value",
")",
")",
",",
"'remote_name'",
":",
"attribute",
".",
"remote_name",
"}",
"continue",
"if",
"attribute",
".",
"max_length",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"attribute",
".",
"max_length",
":",
"self",
".",
"_attribute_errors",
"[",
"local_name",
"]",
"=",
"{",
"'title'",
":",
"'Invalid length'",
",",
"'description'",
":",
"'Attribute %s maximum length should be %s but is %s'",
"%",
"(",
"attribute",
".",
"remote_name",
",",
"attribute",
".",
"max_length",
",",
"len",
"(",
"value",
")",
")",
",",
"'remote_name'",
":",
"attribute",
".",
"remote_name",
"}",
"continue",
"if",
"attribute",
".",
"attribute_type",
"==",
"list",
":",
"valid",
"=",
"True",
"for",
"item",
"in",
"value",
":",
"if",
"valid",
"is",
"True",
":",
"valid",
"=",
"self",
".",
"_validate_value",
"(",
"local_name",
",",
"attribute",
",",
"item",
")",
"else",
":",
"self",
".",
"_validate_value",
"(",
"local_name",
",",
"attribute",
",",
"value",
")",
"return",
"self",
".",
"is_valid",
"(",
")"
] |
Validate the current object attributes.
Check all attributes and store errors
Returns:
Returns True if all attibutes of the object
respect contraints. Returns False otherwise and
store error in errors dict.
|
[
"Validate",
"the",
"current",
"object",
"attributes",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L330-L379
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.expose_attribute
|
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, subtype=None, min_value=None, max_value=None):
""" Expose local_name as remote_name
An exposed attribute `local_name` will be sent within the HTTP request as
a `remote_name`
"""
if remote_name is None:
remote_name = local_name
if display_name is None:
display_name = local_name
attribute = NURemoteAttribute(local_name=local_name, remote_name=remote_name, attribute_type=attribute_type)
attribute.display_name = display_name
attribute.is_required = is_required
attribute.is_readonly = is_readonly
attribute.min_length = min_length
attribute.max_length = max_length
attribute.is_editable = is_editable
attribute.is_identifier = is_identifier
attribute.choices = choices
attribute.is_unique = is_unique
attribute.is_email = is_email
attribute.is_login = is_login
attribute.is_password = is_password
attribute.can_order = can_order
attribute.can_search = can_search
attribute.subtype = subtype
attribute.min_value = min_value
attribute.max_value = max_value
self._attributes[local_name] = attribute
|
python
|
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, subtype=None, min_value=None, max_value=None):
""" Expose local_name as remote_name
An exposed attribute `local_name` will be sent within the HTTP request as
a `remote_name`
"""
if remote_name is None:
remote_name = local_name
if display_name is None:
display_name = local_name
attribute = NURemoteAttribute(local_name=local_name, remote_name=remote_name, attribute_type=attribute_type)
attribute.display_name = display_name
attribute.is_required = is_required
attribute.is_readonly = is_readonly
attribute.min_length = min_length
attribute.max_length = max_length
attribute.is_editable = is_editable
attribute.is_identifier = is_identifier
attribute.choices = choices
attribute.is_unique = is_unique
attribute.is_email = is_email
attribute.is_login = is_login
attribute.is_password = is_password
attribute.can_order = can_order
attribute.can_search = can_search
attribute.subtype = subtype
attribute.min_value = min_value
attribute.max_value = max_value
self._attributes[local_name] = attribute
|
[
"def",
"expose_attribute",
"(",
"self",
",",
"local_name",
",",
"attribute_type",
",",
"remote_name",
"=",
"None",
",",
"display_name",
"=",
"None",
",",
"is_required",
"=",
"False",
",",
"is_readonly",
"=",
"False",
",",
"max_length",
"=",
"None",
",",
"min_length",
"=",
"None",
",",
"is_identifier",
"=",
"False",
",",
"choices",
"=",
"None",
",",
"is_unique",
"=",
"False",
",",
"is_email",
"=",
"False",
",",
"is_login",
"=",
"False",
",",
"is_editable",
"=",
"True",
",",
"is_password",
"=",
"False",
",",
"can_order",
"=",
"False",
",",
"can_search",
"=",
"False",
",",
"subtype",
"=",
"None",
",",
"min_value",
"=",
"None",
",",
"max_value",
"=",
"None",
")",
":",
"if",
"remote_name",
"is",
"None",
":",
"remote_name",
"=",
"local_name",
"if",
"display_name",
"is",
"None",
":",
"display_name",
"=",
"local_name",
"attribute",
"=",
"NURemoteAttribute",
"(",
"local_name",
"=",
"local_name",
",",
"remote_name",
"=",
"remote_name",
",",
"attribute_type",
"=",
"attribute_type",
")",
"attribute",
".",
"display_name",
"=",
"display_name",
"attribute",
".",
"is_required",
"=",
"is_required",
"attribute",
".",
"is_readonly",
"=",
"is_readonly",
"attribute",
".",
"min_length",
"=",
"min_length",
"attribute",
".",
"max_length",
"=",
"max_length",
"attribute",
".",
"is_editable",
"=",
"is_editable",
"attribute",
".",
"is_identifier",
"=",
"is_identifier",
"attribute",
".",
"choices",
"=",
"choices",
"attribute",
".",
"is_unique",
"=",
"is_unique",
"attribute",
".",
"is_email",
"=",
"is_email",
"attribute",
".",
"is_login",
"=",
"is_login",
"attribute",
".",
"is_password",
"=",
"is_password",
"attribute",
".",
"can_order",
"=",
"can_order",
"attribute",
".",
"can_search",
"=",
"can_search",
"attribute",
".",
"subtype",
"=",
"subtype",
"attribute",
".",
"min_value",
"=",
"min_value",
"attribute",
".",
"max_value",
"=",
"max_value",
"self",
".",
"_attributes",
"[",
"local_name",
"]",
"=",
"attribute"
] |
Expose local_name as remote_name
An exposed attribute `local_name` will be sent within the HTTP request as
a `remote_name`
|
[
"Expose",
"local_name",
"as",
"remote_name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L432-L464
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.is_owned_by_current_user
|
def is_owned_by_current_user(self):
""" Check if the current user owns the object """
from bambou.nurest_root_object import NURESTRootObject
root_object = NURESTRootObject.get_default_root_object()
return self._owner == root_object.id
|
python
|
def is_owned_by_current_user(self):
""" Check if the current user owns the object """
from bambou.nurest_root_object import NURESTRootObject
root_object = NURESTRootObject.get_default_root_object()
return self._owner == root_object.id
|
[
"def",
"is_owned_by_current_user",
"(",
"self",
")",
":",
"from",
"bambou",
".",
"nurest_root_object",
"import",
"NURESTRootObject",
"root_object",
"=",
"NURESTRootObject",
".",
"get_default_root_object",
"(",
")",
"return",
"self",
".",
"_owner",
"==",
"root_object",
".",
"id"
] |
Check if the current user owns the object
|
[
"Check",
"if",
"the",
"current",
"user",
"owns",
"the",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L490-L495
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.parent_for_matching_rest_name
|
def parent_for_matching_rest_name(self, rest_names):
""" Return parent that matches a rest name """
parent = self
while parent:
if parent.rest_name in rest_names:
return parent
parent = parent.parent_object
return None
|
python
|
def parent_for_matching_rest_name(self, rest_names):
""" Return parent that matches a rest name """
parent = self
while parent:
if parent.rest_name in rest_names:
return parent
parent = parent.parent_object
return None
|
[
"def",
"parent_for_matching_rest_name",
"(",
"self",
",",
"rest_names",
")",
":",
"parent",
"=",
"self",
"while",
"parent",
":",
"if",
"parent",
".",
"rest_name",
"in",
"rest_names",
":",
"return",
"parent",
"parent",
"=",
"parent",
".",
"parent_object",
"return",
"None"
] |
Return parent that matches a rest name
|
[
"Return",
"parent",
"that",
"matches",
"a",
"rest",
"name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L497-L508
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.genealogic_types
|
def genealogic_types(self):
""" Get genealogic types
Returns:
Returns a list of all parent types
"""
types = []
parent = self
while parent:
types.append(parent.rest_name)
parent = parent.parent_object
return types
|
python
|
def genealogic_types(self):
""" Get genealogic types
Returns:
Returns a list of all parent types
"""
types = []
parent = self
while parent:
types.append(parent.rest_name)
parent = parent.parent_object
return types
|
[
"def",
"genealogic_types",
"(",
"self",
")",
":",
"types",
"=",
"[",
"]",
"parent",
"=",
"self",
"while",
"parent",
":",
"types",
".",
"append",
"(",
"parent",
".",
"rest_name",
")",
"parent",
"=",
"parent",
".",
"parent_object",
"return",
"types"
] |
Get genealogic types
Returns:
Returns a list of all parent types
|
[
"Get",
"genealogic",
"types"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L510-L524
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.genealogic_ids
|
def genealogic_ids(self):
""" Get all genealogic ids
Returns:
A list of all parent ids
"""
ids = []
parent = self
while parent:
ids.append(parent.id)
parent = parent.parent_object
return ids
|
python
|
def genealogic_ids(self):
""" Get all genealogic ids
Returns:
A list of all parent ids
"""
ids = []
parent = self
while parent:
ids.append(parent.id)
parent = parent.parent_object
return ids
|
[
"def",
"genealogic_ids",
"(",
"self",
")",
":",
"ids",
"=",
"[",
"]",
"parent",
"=",
"self",
"while",
"parent",
":",
"ids",
".",
"append",
"(",
"parent",
".",
"id",
")",
"parent",
"=",
"parent",
".",
"parent_object",
"return",
"ids"
] |
Get all genealogic ids
Returns:
A list of all parent ids
|
[
"Get",
"all",
"genealogic",
"ids"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L526-L540
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.get_formated_creation_date
|
def get_formated_creation_date(self, format='%b %Y %d %H:%I:%S'):
""" Return creation date with a given format. Default is '%b %Y %d %H:%I:%S' """
if not self._creation_date:
return None
date = datetime.datetime.utcfromtimestamp(self._creation_date)
return date.strftime(format)
|
python
|
def get_formated_creation_date(self, format='%b %Y %d %H:%I:%S'):
""" Return creation date with a given format. Default is '%b %Y %d %H:%I:%S' """
if not self._creation_date:
return None
date = datetime.datetime.utcfromtimestamp(self._creation_date)
return date.strftime(format)
|
[
"def",
"get_formated_creation_date",
"(",
"self",
",",
"format",
"=",
"'%b %Y %d %H:%I:%S'",
")",
":",
"if",
"not",
"self",
".",
"_creation_date",
":",
"return",
"None",
"date",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"_creation_date",
")",
"return",
"date",
".",
"strftime",
"(",
"format",
")"
] |
Return creation date with a given format. Default is '%b %Y %d %H:%I:%S'
|
[
"Return",
"creation",
"date",
"with",
"a",
"given",
"format",
".",
"Default",
"is",
"%b",
"%Y",
"%d",
"%H",
":",
"%I",
":",
"%S"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L568-L575
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.add_child
|
def add_child(self, child):
""" Add a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
if children is None:
raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, child, self))
if child not in children:
child.parent_object = self
children.append(child)
|
python
|
def add_child(self, child):
""" Add a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
if children is None:
raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, child, self))
if child not in children:
child.parent_object = self
children.append(child)
|
[
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"rest_name",
"=",
"child",
".",
"rest_name",
"children",
"=",
"self",
".",
"fetcher_for_rest_name",
"(",
"rest_name",
")",
"if",
"children",
"is",
"None",
":",
"raise",
"InternalConsitencyError",
"(",
"'Could not find fetcher with name %s while adding %s in parent %s'",
"%",
"(",
"rest_name",
",",
"child",
",",
"self",
")",
")",
"if",
"child",
"not",
"in",
"children",
":",
"child",
".",
"parent_object",
"=",
"self",
"children",
".",
"append",
"(",
"child",
")"
] |
Add a child
|
[
"Add",
"a",
"child"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L605-L616
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.remove_child
|
def remove_child(self, child):
""" Remove a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
target_child = None
for local_child in children:
if local_child.id == child.id:
target_child = local_child
break
if target_child:
target_child.parent_object = None
children.remove(target_child)
|
python
|
def remove_child(self, child):
""" Remove a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
target_child = None
for local_child in children:
if local_child.id == child.id:
target_child = local_child
break
if target_child:
target_child.parent_object = None
children.remove(target_child)
|
[
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"rest_name",
"=",
"child",
".",
"rest_name",
"children",
"=",
"self",
".",
"fetcher_for_rest_name",
"(",
"rest_name",
")",
"target_child",
"=",
"None",
"for",
"local_child",
"in",
"children",
":",
"if",
"local_child",
".",
"id",
"==",
"child",
".",
"id",
":",
"target_child",
"=",
"local_child",
"break",
"if",
"target_child",
":",
"target_child",
".",
"parent_object",
"=",
"None",
"children",
".",
"remove",
"(",
"target_child",
")"
] |
Remove a child
|
[
"Remove",
"a",
"child"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L618-L633
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.update_child
|
def update_child(self, child):
""" Update child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
index = None
for local_child in children:
if local_child.id == child.id:
index = children.index(local_child)
break
if index is not None:
children[index] = child
|
python
|
def update_child(self, child):
""" Update child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
index = None
for local_child in children:
if local_child.id == child.id:
index = children.index(local_child)
break
if index is not None:
children[index] = child
|
[
"def",
"update_child",
"(",
"self",
",",
"child",
")",
":",
"rest_name",
"=",
"child",
".",
"rest_name",
"children",
"=",
"self",
".",
"fetcher_for_rest_name",
"(",
"rest_name",
")",
"index",
"=",
"None",
"for",
"local_child",
"in",
"children",
":",
"if",
"local_child",
".",
"id",
"==",
"child",
".",
"id",
":",
"index",
"=",
"children",
".",
"index",
"(",
"local_child",
")",
"break",
"if",
"index",
"is",
"not",
"None",
":",
"children",
"[",
"index",
"]",
"=",
"child"
] |
Update child
|
[
"Update",
"child"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L635-L649
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.to_dict
|
def to_dict(self):
""" Converts the current object into a Dictionary using all exposed ReST attributes.
Returns:
dict: the dictionary containing all the exposed ReST attributes and their values.
Example::
>>> print entity.to_dict()
{"name": "my entity", "description": "Hello World", "ID": "xxxx-xxx-xxxx-xxx", ...}
"""
dictionary = dict()
for local_name, attribute in self._attributes.items():
remote_name = attribute.remote_name
if hasattr(self, local_name):
value = getattr(self, local_name)
# Removed to resolve issue http://mvjira.mv.usa.alcatel.com/browse/VSD-5940 (12/15/2014)
# if isinstance(value, bool):
# value = int(value)
if isinstance(value, NURESTObject):
value = value.to_dict()
if isinstance(value, list) and len(value) > 0 and isinstance(value[0], NURESTObject):
tmp = list()
for obj in value:
tmp.append(obj.to_dict())
value = tmp
dictionary[remote_name] = value
else:
pass # pragma: no cover
return dictionary
|
python
|
def to_dict(self):
""" Converts the current object into a Dictionary using all exposed ReST attributes.
Returns:
dict: the dictionary containing all the exposed ReST attributes and their values.
Example::
>>> print entity.to_dict()
{"name": "my entity", "description": "Hello World", "ID": "xxxx-xxx-xxxx-xxx", ...}
"""
dictionary = dict()
for local_name, attribute in self._attributes.items():
remote_name = attribute.remote_name
if hasattr(self, local_name):
value = getattr(self, local_name)
# Removed to resolve issue http://mvjira.mv.usa.alcatel.com/browse/VSD-5940 (12/15/2014)
# if isinstance(value, bool):
# value = int(value)
if isinstance(value, NURESTObject):
value = value.to_dict()
if isinstance(value, list) and len(value) > 0 and isinstance(value[0], NURESTObject):
tmp = list()
for obj in value:
tmp.append(obj.to_dict())
value = tmp
dictionary[remote_name] = value
else:
pass # pragma: no cover
return dictionary
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"dictionary",
"=",
"dict",
"(",
")",
"for",
"local_name",
",",
"attribute",
"in",
"self",
".",
"_attributes",
".",
"items",
"(",
")",
":",
"remote_name",
"=",
"attribute",
".",
"remote_name",
"if",
"hasattr",
"(",
"self",
",",
"local_name",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"local_name",
")",
"# Removed to resolve issue http://mvjira.mv.usa.alcatel.com/browse/VSD-5940 (12/15/2014)",
"# if isinstance(value, bool):",
"# value = int(value)",
"if",
"isinstance",
"(",
"value",
",",
"NURESTObject",
")",
":",
"value",
"=",
"value",
".",
"to_dict",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"len",
"(",
"value",
")",
">",
"0",
"and",
"isinstance",
"(",
"value",
"[",
"0",
"]",
",",
"NURESTObject",
")",
":",
"tmp",
"=",
"list",
"(",
")",
"for",
"obj",
"in",
"value",
":",
"tmp",
".",
"append",
"(",
"obj",
".",
"to_dict",
"(",
")",
")",
"value",
"=",
"tmp",
"dictionary",
"[",
"remote_name",
"]",
"=",
"value",
"else",
":",
"pass",
"# pragma: no cover",
"return",
"dictionary"
] |
Converts the current object into a Dictionary using all exposed ReST attributes.
Returns:
dict: the dictionary containing all the exposed ReST attributes and their values.
Example::
>>> print entity.to_dict()
{"name": "my entity", "description": "Hello World", "ID": "xxxx-xxx-xxxx-xxx", ...}
|
[
"Converts",
"the",
"current",
"object",
"into",
"a",
"Dictionary",
"using",
"all",
"exposed",
"ReST",
"attributes",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L667-L704
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.from_dict
|
def from_dict(self, dictionary):
""" Sets all the exposed ReST attribues from the given dictionary
Args:
dictionary (dict): dictionnary containing the raw object attributes and their values.
Example:
>>> info = {"name": "my group", "private": False}
>>> group = NUGroup()
>>> group.from_dict(info)
>>> print "name: %s - private: %s" % (group.name, group.private)
"name: my group - private: False"
"""
for remote_name, remote_value in dictionary.items():
# Check if a local attribute is exposed with the remote_name
# if no attribute is exposed, return None
local_name = next((name for name, attribute in self._attributes.items() if attribute.remote_name == remote_name), None)
if local_name:
setattr(self, local_name, remote_value)
else:
# print('Attribute %s could not be added to object %s' % (remote_name, self))
pass
|
python
|
def from_dict(self, dictionary):
""" Sets all the exposed ReST attribues from the given dictionary
Args:
dictionary (dict): dictionnary containing the raw object attributes and their values.
Example:
>>> info = {"name": "my group", "private": False}
>>> group = NUGroup()
>>> group.from_dict(info)
>>> print "name: %s - private: %s" % (group.name, group.private)
"name: my group - private: False"
"""
for remote_name, remote_value in dictionary.items():
# Check if a local attribute is exposed with the remote_name
# if no attribute is exposed, return None
local_name = next((name for name, attribute in self._attributes.items() if attribute.remote_name == remote_name), None)
if local_name:
setattr(self, local_name, remote_value)
else:
# print('Attribute %s could not be added to object %s' % (remote_name, self))
pass
|
[
"def",
"from_dict",
"(",
"self",
",",
"dictionary",
")",
":",
"for",
"remote_name",
",",
"remote_value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"# Check if a local attribute is exposed with the remote_name",
"# if no attribute is exposed, return None",
"local_name",
"=",
"next",
"(",
"(",
"name",
"for",
"name",
",",
"attribute",
"in",
"self",
".",
"_attributes",
".",
"items",
"(",
")",
"if",
"attribute",
".",
"remote_name",
"==",
"remote_name",
")",
",",
"None",
")",
"if",
"local_name",
":",
"setattr",
"(",
"self",
",",
"local_name",
",",
"remote_value",
")",
"else",
":",
"# print('Attribute %s could not be added to object %s' % (remote_name, self))",
"pass"
] |
Sets all the exposed ReST attribues from the given dictionary
Args:
dictionary (dict): dictionnary containing the raw object attributes and their values.
Example:
>>> info = {"name": "my group", "private": False}
>>> group = NUGroup()
>>> group.from_dict(info)
>>> print "name: %s - private: %s" % (group.name, group.private)
"name: my group - private: False"
|
[
"Sets",
"all",
"the",
"exposed",
"ReST",
"attribues",
"from",
"the",
"given",
"dictionary"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L706-L729
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.delete
|
def delete(self, response_choice=1, async=False, callback=None):
""" Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.delete() # will delete the enterprise from the server
"""
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_DELETE, async=async, callback=callback, response_choice=response_choice)
|
python
|
def delete(self, response_choice=1, async=False, callback=None):
""" Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.delete() # will delete the enterprise from the server
"""
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_DELETE, async=async, callback=callback, response_choice=response_choice)
|
[
"def",
"delete",
"(",
"self",
",",
"response_choice",
"=",
"1",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_manage_child_object",
"(",
"nurest_object",
"=",
"self",
",",
"method",
"=",
"HTTP_METHOD_DELETE",
",",
"async",
"=",
"async",
",",
"callback",
"=",
"callback",
",",
"response_choice",
"=",
"response_choice",
")"
] |
Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.delete() # will delete the enterprise from the server
|
[
"Delete",
"object",
"and",
"call",
"given",
"callback",
"in",
"case",
"of",
"call",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L733-L744
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.save
|
def save(self, response_choice=None, async=False, callback=None):
""" Update object and call given callback in case of async call
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.name = "My Super Object"
>>> entity.save() # will save the new name in the server
"""
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_PUT, async=async, callback=callback, response_choice=response_choice)
|
python
|
def save(self, response_choice=None, async=False, callback=None):
""" Update object and call given callback in case of async call
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.name = "My Super Object"
>>> entity.save() # will save the new name in the server
"""
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_PUT, async=async, callback=callback, response_choice=response_choice)
|
[
"def",
"save",
"(",
"self",
",",
"response_choice",
"=",
"None",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_manage_child_object",
"(",
"nurest_object",
"=",
"self",
",",
"method",
"=",
"HTTP_METHOD_PUT",
",",
"async",
"=",
"async",
",",
"callback",
"=",
"callback",
",",
"response_choice",
"=",
"response_choice",
")"
] |
Update object and call given callback in case of async call
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.name = "My Super Object"
>>> entity.save() # will save the new name in the server
|
[
"Update",
"object",
"and",
"call",
"given",
"callback",
"in",
"case",
"of",
"async",
"call"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L746-L757
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.send_request
|
def send_request(self, request, async=False, local_callback=None, remote_callback=None, user_info=None):
""" Sends a request, calls the local callback, then the remote callback in case of async call
Args:
request: The request to send
local_callback: local method that will be triggered in case of async call
remote_callback: remote moethd that will be triggered in case of async call
user_info: contains additionnal information to carry during the request
Returns:
Returns the object and connection (object, connection)
"""
callbacks = dict()
if local_callback:
callbacks['local'] = local_callback
if remote_callback:
callbacks['remote'] = remote_callback
connection = NURESTConnection(request=request, async=async, callback=self._did_receive_response, callbacks=callbacks)
connection.user_info = user_info
return connection.start()
|
python
|
def send_request(self, request, async=False, local_callback=None, remote_callback=None, user_info=None):
""" Sends a request, calls the local callback, then the remote callback in case of async call
Args:
request: The request to send
local_callback: local method that will be triggered in case of async call
remote_callback: remote moethd that will be triggered in case of async call
user_info: contains additionnal information to carry during the request
Returns:
Returns the object and connection (object, connection)
"""
callbacks = dict()
if local_callback:
callbacks['local'] = local_callback
if remote_callback:
callbacks['remote'] = remote_callback
connection = NURESTConnection(request=request, async=async, callback=self._did_receive_response, callbacks=callbacks)
connection.user_info = user_info
return connection.start()
|
[
"def",
"send_request",
"(",
"self",
",",
"request",
",",
"async",
"=",
"False",
",",
"local_callback",
"=",
"None",
",",
"remote_callback",
"=",
"None",
",",
"user_info",
"=",
"None",
")",
":",
"callbacks",
"=",
"dict",
"(",
")",
"if",
"local_callback",
":",
"callbacks",
"[",
"'local'",
"]",
"=",
"local_callback",
"if",
"remote_callback",
":",
"callbacks",
"[",
"'remote'",
"]",
"=",
"remote_callback",
"connection",
"=",
"NURESTConnection",
"(",
"request",
"=",
"request",
",",
"async",
"=",
"async",
",",
"callback",
"=",
"self",
".",
"_did_receive_response",
",",
"callbacks",
"=",
"callbacks",
")",
"connection",
".",
"user_info",
"=",
"user_info",
"return",
"connection",
".",
"start",
"(",
")"
] |
Sends a request, calls the local callback, then the remote callback in case of async call
Args:
request: The request to send
local_callback: local method that will be triggered in case of async call
remote_callback: remote moethd that will be triggered in case of async call
user_info: contains additionnal information to carry during the request
Returns:
Returns the object and connection (object, connection)
|
[
"Sends",
"a",
"request",
"calls",
"the",
"local",
"callback",
"then",
"the",
"remote",
"callback",
"in",
"case",
"of",
"async",
"call"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L789-L813
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._manage_child_object
|
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False):
""" Low level child management. Send given HTTP method with given nurest_object to given ressource of current object
Args:
nurest_object: the NURESTObject object to manage
method: the HTTP method to use (GET, POST, PUT, DELETE)
callback: the callback to call at the end
handler: a custom handler to call when complete, before calling the callback
commit: True to auto commit changes in the current object
Returns:
Returns the object and connection (object, connection)
"""
url = None
if method == HTTP_METHOD_POST:
url = self.get_resource_url_for_child_type(nurest_object.__class__)
else:
url = self.get_resource_url()
if response_choice is not None:
url += '?responseChoice=%s' % response_choice
request = NURESTRequest(method=method, url=url, data=nurest_object.to_dict())
user_info = {'nurest_object': nurest_object, 'commit': commit}
if not handler:
handler = self._did_perform_standard_operation
if async:
return self.send_request(request=request, async=async, local_callback=handler, remote_callback=callback, user_info=user_info)
else:
connection = self.send_request(request=request, user_info=user_info)
return handler(connection)
|
python
|
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False):
""" Low level child management. Send given HTTP method with given nurest_object to given ressource of current object
Args:
nurest_object: the NURESTObject object to manage
method: the HTTP method to use (GET, POST, PUT, DELETE)
callback: the callback to call at the end
handler: a custom handler to call when complete, before calling the callback
commit: True to auto commit changes in the current object
Returns:
Returns the object and connection (object, connection)
"""
url = None
if method == HTTP_METHOD_POST:
url = self.get_resource_url_for_child_type(nurest_object.__class__)
else:
url = self.get_resource_url()
if response_choice is not None:
url += '?responseChoice=%s' % response_choice
request = NURESTRequest(method=method, url=url, data=nurest_object.to_dict())
user_info = {'nurest_object': nurest_object, 'commit': commit}
if not handler:
handler = self._did_perform_standard_operation
if async:
return self.send_request(request=request, async=async, local_callback=handler, remote_callback=callback, user_info=user_info)
else:
connection = self.send_request(request=request, user_info=user_info)
return handler(connection)
|
[
"def",
"_manage_child_object",
"(",
"self",
",",
"nurest_object",
",",
"method",
"=",
"HTTP_METHOD_GET",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"handler",
"=",
"None",
",",
"response_choice",
"=",
"None",
",",
"commit",
"=",
"False",
")",
":",
"url",
"=",
"None",
"if",
"method",
"==",
"HTTP_METHOD_POST",
":",
"url",
"=",
"self",
".",
"get_resource_url_for_child_type",
"(",
"nurest_object",
".",
"__class__",
")",
"else",
":",
"url",
"=",
"self",
".",
"get_resource_url",
"(",
")",
"if",
"response_choice",
"is",
"not",
"None",
":",
"url",
"+=",
"'?responseChoice=%s'",
"%",
"response_choice",
"request",
"=",
"NURESTRequest",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"data",
"=",
"nurest_object",
".",
"to_dict",
"(",
")",
")",
"user_info",
"=",
"{",
"'nurest_object'",
":",
"nurest_object",
",",
"'commit'",
":",
"commit",
"}",
"if",
"not",
"handler",
":",
"handler",
"=",
"self",
".",
"_did_perform_standard_operation",
"if",
"async",
":",
"return",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"async",
"=",
"async",
",",
"local_callback",
"=",
"handler",
",",
"remote_callback",
"=",
"callback",
",",
"user_info",
"=",
"user_info",
")",
"else",
":",
"connection",
"=",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"user_info",
"=",
"user_info",
")",
"return",
"handler",
"(",
"connection",
")"
] |
Low level child management. Send given HTTP method with given nurest_object to given ressource of current object
Args:
nurest_object: the NURESTObject object to manage
method: the HTTP method to use (GET, POST, PUT, DELETE)
callback: the callback to call at the end
handler: a custom handler to call when complete, before calling the callback
commit: True to auto commit changes in the current object
Returns:
Returns the object and connection (object, connection)
|
[
"Low",
"level",
"child",
"management",
".",
"Send",
"given",
"HTTP",
"method",
"with",
"given",
"nurest_object",
"to",
"given",
"ressource",
"of",
"current",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L815-L849
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._did_receive_response
|
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
should_post = not has_callbacks
if connection.handle_response_for_connection(should_post=should_post) and has_callbacks:
callback = connection.callbacks['local']
callback(connection)
|
python
|
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
should_post = not has_callbacks
if connection.handle_response_for_connection(should_post=should_post) and has_callbacks:
callback = connection.callbacks['local']
callback(connection)
|
[
"def",
"_did_receive_response",
"(",
"self",
",",
"connection",
")",
":",
"if",
"connection",
".",
"has_timeouted",
":",
"bambou_logger",
".",
"info",
"(",
"\"NURESTConnection has timeout.\"",
")",
"return",
"has_callbacks",
"=",
"connection",
".",
"has_callbacks",
"(",
")",
"should_post",
"=",
"not",
"has_callbacks",
"if",
"connection",
".",
"handle_response_for_connection",
"(",
"should_post",
"=",
"should_post",
")",
"and",
"has_callbacks",
":",
"callback",
"=",
"connection",
".",
"callbacks",
"[",
"'local'",
"]",
"callback",
"(",
"connection",
")"
] |
Receive a response from the connection
|
[
"Receive",
"a",
"response",
"from",
"the",
"connection"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L853-L865
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._did_retrieve
|
def _did_retrieve(self, connection):
""" Callback called after fetching the object """
response = connection.response
try:
self.from_dict(response.data[0])
except:
pass
return self._did_perform_standard_operation(connection)
|
python
|
def _did_retrieve(self, connection):
""" Callback called after fetching the object """
response = connection.response
try:
self.from_dict(response.data[0])
except:
pass
return self._did_perform_standard_operation(connection)
|
[
"def",
"_did_retrieve",
"(",
"self",
",",
"connection",
")",
":",
"response",
"=",
"connection",
".",
"response",
"try",
":",
"self",
".",
"from_dict",
"(",
"response",
".",
"data",
"[",
"0",
"]",
")",
"except",
":",
"pass",
"return",
"self",
".",
"_did_perform_standard_operation",
"(",
"connection",
")"
] |
Callback called after fetching the object
|
[
"Callback",
"called",
"after",
"fetching",
"the",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L867-L877
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._did_perform_standard_operation
|
def _did_perform_standard_operation(self, connection):
""" Performs standard opertions """
if connection.async:
callback = connection.callbacks['remote']
if connection.user_info and 'nurest_object' in connection.user_info:
callback(connection.user_info['nurest_object'], connection)
else:
callback(self, connection)
else:
if connection.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error:
raise BambouHTTPError(connection=connection)
# Case with multiple objects like assignment
if connection.user_info and 'nurest_objects' in connection.user_info:
if connection.user_info['commit']:
for nurest_object in connection.user_info['nurest_objects']:
self.add_child(nurest_object)
return (connection.user_info['nurest_objects'], connection)
if connection.user_info and 'nurest_object' in connection.user_info:
if connection.user_info['commit']:
self.add_child(connection.user_info['nurest_object'])
return (connection.user_info['nurest_object'], connection)
return (self, connection)
|
python
|
def _did_perform_standard_operation(self, connection):
""" Performs standard opertions """
if connection.async:
callback = connection.callbacks['remote']
if connection.user_info and 'nurest_object' in connection.user_info:
callback(connection.user_info['nurest_object'], connection)
else:
callback(self, connection)
else:
if connection.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error:
raise BambouHTTPError(connection=connection)
# Case with multiple objects like assignment
if connection.user_info and 'nurest_objects' in connection.user_info:
if connection.user_info['commit']:
for nurest_object in connection.user_info['nurest_objects']:
self.add_child(nurest_object)
return (connection.user_info['nurest_objects'], connection)
if connection.user_info and 'nurest_object' in connection.user_info:
if connection.user_info['commit']:
self.add_child(connection.user_info['nurest_object'])
return (connection.user_info['nurest_object'], connection)
return (self, connection)
|
[
"def",
"_did_perform_standard_operation",
"(",
"self",
",",
"connection",
")",
":",
"if",
"connection",
".",
"async",
":",
"callback",
"=",
"connection",
".",
"callbacks",
"[",
"'remote'",
"]",
"if",
"connection",
".",
"user_info",
"and",
"'nurest_object'",
"in",
"connection",
".",
"user_info",
":",
"callback",
"(",
"connection",
".",
"user_info",
"[",
"'nurest_object'",
"]",
",",
"connection",
")",
"else",
":",
"callback",
"(",
"self",
",",
"connection",
")",
"else",
":",
"if",
"connection",
".",
"response",
".",
"status_code",
">=",
"400",
"and",
"BambouConfig",
".",
"_should_raise_bambou_http_error",
":",
"raise",
"BambouHTTPError",
"(",
"connection",
"=",
"connection",
")",
"# Case with multiple objects like assignment",
"if",
"connection",
".",
"user_info",
"and",
"'nurest_objects'",
"in",
"connection",
".",
"user_info",
":",
"if",
"connection",
".",
"user_info",
"[",
"'commit'",
"]",
":",
"for",
"nurest_object",
"in",
"connection",
".",
"user_info",
"[",
"'nurest_objects'",
"]",
":",
"self",
".",
"add_child",
"(",
"nurest_object",
")",
"return",
"(",
"connection",
".",
"user_info",
"[",
"'nurest_objects'",
"]",
",",
"connection",
")",
"if",
"connection",
".",
"user_info",
"and",
"'nurest_object'",
"in",
"connection",
".",
"user_info",
":",
"if",
"connection",
".",
"user_info",
"[",
"'commit'",
"]",
":",
"self",
".",
"add_child",
"(",
"connection",
".",
"user_info",
"[",
"'nurest_object'",
"]",
")",
"return",
"(",
"connection",
".",
"user_info",
"[",
"'nurest_object'",
"]",
",",
"connection",
")",
"return",
"(",
"self",
",",
"connection",
")"
] |
Performs standard opertions
|
[
"Performs",
"standard",
"opertions"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L879-L908
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.create_child
|
def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True):
""" Add given nurest_object to the current object
For example, to add a child into a parent, you can call
parent.create_child(nurest_object=child)
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to add
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): should the request be done asynchronously or not
callback (function): callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> entity = NUEntity(name="Super Entity")
>>> parent_entity.create_child(entity) # the new entity as been created in the parent_entity
"""
# if nurest_object.id:
# raise InternalConsitencyError("Cannot create a child that already has an ID: %s." % nurest_object)
return self._manage_child_object(nurest_object=nurest_object,
async=async,
method=HTTP_METHOD_POST,
callback=callback,
handler=self._did_create_child,
response_choice=response_choice,
commit=commit)
|
python
|
def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True):
""" Add given nurest_object to the current object
For example, to add a child into a parent, you can call
parent.create_child(nurest_object=child)
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to add
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): should the request be done asynchronously or not
callback (function): callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> entity = NUEntity(name="Super Entity")
>>> parent_entity.create_child(entity) # the new entity as been created in the parent_entity
"""
# if nurest_object.id:
# raise InternalConsitencyError("Cannot create a child that already has an ID: %s." % nurest_object)
return self._manage_child_object(nurest_object=nurest_object,
async=async,
method=HTTP_METHOD_POST,
callback=callback,
handler=self._did_create_child,
response_choice=response_choice,
commit=commit)
|
[
"def",
"create_child",
"(",
"self",
",",
"nurest_object",
",",
"response_choice",
"=",
"None",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"# if nurest_object.id:",
"# raise InternalConsitencyError(\"Cannot create a child that already has an ID: %s.\" % nurest_object)",
"return",
"self",
".",
"_manage_child_object",
"(",
"nurest_object",
"=",
"nurest_object",
",",
"async",
"=",
"async",
",",
"method",
"=",
"HTTP_METHOD_POST",
",",
"callback",
"=",
"callback",
",",
"handler",
"=",
"self",
".",
"_did_create_child",
",",
"response_choice",
"=",
"response_choice",
",",
"commit",
"=",
"commit",
")"
] |
Add given nurest_object to the current object
For example, to add a child into a parent, you can call
parent.create_child(nurest_object=child)
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to add
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): should the request be done asynchronously or not
callback (function): callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> entity = NUEntity(name="Super Entity")
>>> parent_entity.create_child(entity) # the new entity as been created in the parent_entity
|
[
"Add",
"given",
"nurest_object",
"to",
"the",
"current",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L912-L941
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.instantiate_child
|
def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True):
""" Instantiate an nurest_object from a template object
Args:
nurest_object: the NURESTObject object to add
from_template: the NURESTObject template object
callback: callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> parent_entity = NUParentEntity(id="xxxx-xxxx-xxx-xxxx") # create a NUParentEntity with an existing ID (or retrieve one)
>>> other_entity_template = NUOtherEntityTemplate(id="yyyy-yyyy-yyyy-yyyy") # create a NUOtherEntityTemplate with an existing ID (or retrieve one)
>>> other_entity_instance = NUOtherEntityInstance(name="my new instance") # create a new NUOtherEntityInstance to be intantiated from other_entity_template
>>>
>>> parent_entity.instantiate_child(other_entity_instance, other_entity_template) # instatiate the new domain in the server
"""
# if nurest_object.id:
# raise InternalConsitencyError("Cannot instantiate a child that already has an ID: %s." % nurest_object)
if not from_template.id:
raise InternalConsitencyError("Cannot instantiate a child from a template with no ID: %s." % from_template)
nurest_object.template_id = from_template.id
return self._manage_child_object(nurest_object=nurest_object,
async=async,
method=HTTP_METHOD_POST,
callback=callback,
handler=self._did_create_child,
response_choice=response_choice,
commit=commit)
|
python
|
def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True):
""" Instantiate an nurest_object from a template object
Args:
nurest_object: the NURESTObject object to add
from_template: the NURESTObject template object
callback: callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> parent_entity = NUParentEntity(id="xxxx-xxxx-xxx-xxxx") # create a NUParentEntity with an existing ID (or retrieve one)
>>> other_entity_template = NUOtherEntityTemplate(id="yyyy-yyyy-yyyy-yyyy") # create a NUOtherEntityTemplate with an existing ID (or retrieve one)
>>> other_entity_instance = NUOtherEntityInstance(name="my new instance") # create a new NUOtherEntityInstance to be intantiated from other_entity_template
>>>
>>> parent_entity.instantiate_child(other_entity_instance, other_entity_template) # instatiate the new domain in the server
"""
# if nurest_object.id:
# raise InternalConsitencyError("Cannot instantiate a child that already has an ID: %s." % nurest_object)
if not from_template.id:
raise InternalConsitencyError("Cannot instantiate a child from a template with no ID: %s." % from_template)
nurest_object.template_id = from_template.id
return self._manage_child_object(nurest_object=nurest_object,
async=async,
method=HTTP_METHOD_POST,
callback=callback,
handler=self._did_create_child,
response_choice=response_choice,
commit=commit)
|
[
"def",
"instantiate_child",
"(",
"self",
",",
"nurest_object",
",",
"from_template",
",",
"response_choice",
"=",
"None",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"# if nurest_object.id:",
"# raise InternalConsitencyError(\"Cannot instantiate a child that already has an ID: %s.\" % nurest_object)",
"if",
"not",
"from_template",
".",
"id",
":",
"raise",
"InternalConsitencyError",
"(",
"\"Cannot instantiate a child from a template with no ID: %s.\"",
"%",
"from_template",
")",
"nurest_object",
".",
"template_id",
"=",
"from_template",
".",
"id",
"return",
"self",
".",
"_manage_child_object",
"(",
"nurest_object",
"=",
"nurest_object",
",",
"async",
"=",
"async",
",",
"method",
"=",
"HTTP_METHOD_POST",
",",
"callback",
"=",
"callback",
",",
"handler",
"=",
"self",
".",
"_did_create_child",
",",
"response_choice",
"=",
"response_choice",
",",
"commit",
"=",
"commit",
")"
] |
Instantiate an nurest_object from a template object
Args:
nurest_object: the NURESTObject object to add
from_template: the NURESTObject template object
callback: callback containing the object and the connection
Returns:
Returns the object and connection (object, connection)
Example:
>>> parent_entity = NUParentEntity(id="xxxx-xxxx-xxx-xxxx") # create a NUParentEntity with an existing ID (or retrieve one)
>>> other_entity_template = NUOtherEntityTemplate(id="yyyy-yyyy-yyyy-yyyy") # create a NUOtherEntityTemplate with an existing ID (or retrieve one)
>>> other_entity_instance = NUOtherEntityInstance(name="my new instance") # create a new NUOtherEntityInstance to be intantiated from other_entity_template
>>>
>>> parent_entity.instantiate_child(other_entity_instance, other_entity_template) # instatiate the new domain in the server
|
[
"Instantiate",
"an",
"nurest_object",
"from",
"a",
"template",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L943-L975
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject._did_create_child
|
def _did_create_child(self, connection):
""" Callback called after adding a new child nurest_object """
response = connection.response
try:
connection.user_info['nurest_object'].from_dict(response.data[0])
except Exception:
pass
return self._did_perform_standard_operation(connection)
|
python
|
def _did_create_child(self, connection):
""" Callback called after adding a new child nurest_object """
response = connection.response
try:
connection.user_info['nurest_object'].from_dict(response.data[0])
except Exception:
pass
return self._did_perform_standard_operation(connection)
|
[
"def",
"_did_create_child",
"(",
"self",
",",
"connection",
")",
":",
"response",
"=",
"connection",
".",
"response",
"try",
":",
"connection",
".",
"user_info",
"[",
"'nurest_object'",
"]",
".",
"from_dict",
"(",
"response",
".",
"data",
"[",
"0",
"]",
")",
"except",
"Exception",
":",
"pass",
"return",
"self",
".",
"_did_perform_standard_operation",
"(",
"connection",
")"
] |
Callback called after adding a new child nurest_object
|
[
"Callback",
"called",
"after",
"adding",
"a",
"new",
"child",
"nurest_object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L977-L986
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.assign
|
def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True):
""" Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback method that should be fired at the end
Returns:
Returns the current object and the connection (object, connection)
Example:
>>> entity.assign([entity1, entity2, entity3], NUEntity) # entity1, entity2 and entity3 are now part of the entity
"""
ids = list()
for nurest_object in objects:
ids.append(nurest_object.id)
url = self.get_resource_url_for_child_type(nurest_object_type)
request = NURESTRequest(method=HTTP_METHOD_PUT, url=url, data=ids)
user_info = {'nurest_objects': objects, 'commit': commit}
if async:
return self.send_request(request=request,
async=async,
local_callback=self._did_perform_standard_operation,
remote_callback=callback,
user_info=user_info)
else:
connection = self.send_request(request=request,
user_info=user_info)
return self._did_perform_standard_operation(connection)
|
python
|
def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True):
""" Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback method that should be fired at the end
Returns:
Returns the current object and the connection (object, connection)
Example:
>>> entity.assign([entity1, entity2, entity3], NUEntity) # entity1, entity2 and entity3 are now part of the entity
"""
ids = list()
for nurest_object in objects:
ids.append(nurest_object.id)
url = self.get_resource_url_for_child_type(nurest_object_type)
request = NURESTRequest(method=HTTP_METHOD_PUT, url=url, data=ids)
user_info = {'nurest_objects': objects, 'commit': commit}
if async:
return self.send_request(request=request,
async=async,
local_callback=self._did_perform_standard_operation,
remote_callback=callback,
user_info=user_info)
else:
connection = self.send_request(request=request,
user_info=user_info)
return self._did_perform_standard_operation(connection)
|
[
"def",
"assign",
"(",
"self",
",",
"objects",
",",
"nurest_object_type",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"ids",
"=",
"list",
"(",
")",
"for",
"nurest_object",
"in",
"objects",
":",
"ids",
".",
"append",
"(",
"nurest_object",
".",
"id",
")",
"url",
"=",
"self",
".",
"get_resource_url_for_child_type",
"(",
"nurest_object_type",
")",
"request",
"=",
"NURESTRequest",
"(",
"method",
"=",
"HTTP_METHOD_PUT",
",",
"url",
"=",
"url",
",",
"data",
"=",
"ids",
")",
"user_info",
"=",
"{",
"'nurest_objects'",
":",
"objects",
",",
"'commit'",
":",
"commit",
"}",
"if",
"async",
":",
"return",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"async",
"=",
"async",
",",
"local_callback",
"=",
"self",
".",
"_did_perform_standard_operation",
",",
"remote_callback",
"=",
"callback",
",",
"user_info",
"=",
"user_info",
")",
"else",
":",
"connection",
"=",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"user_info",
"=",
"user_info",
")",
"return",
"self",
".",
"_did_perform_standard_operation",
"(",
"connection",
")"
] |
Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback method that should be fired at the end
Returns:
Returns the current object and the connection (object, connection)
Example:
>>> entity.assign([entity1, entity2, entity3], NUEntity) # entity1, entity2 and entity3 are now part of the entity
|
[
"Reference",
"a",
"list",
"of",
"objects",
"into",
"the",
"current",
"resource"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L988-L1022
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.rest_equals
|
def rest_equals(self, rest_object):
""" Compare objects REST attributes
"""
if not self.equals(rest_object):
return False
return self.to_dict() == rest_object.to_dict()
|
python
|
def rest_equals(self, rest_object):
""" Compare objects REST attributes
"""
if not self.equals(rest_object):
return False
return self.to_dict() == rest_object.to_dict()
|
[
"def",
"rest_equals",
"(",
"self",
",",
"rest_object",
")",
":",
"if",
"not",
"self",
".",
"equals",
"(",
"rest_object",
")",
":",
"return",
"False",
"return",
"self",
".",
"to_dict",
"(",
")",
"==",
"rest_object",
".",
"to_dict",
"(",
")"
] |
Compare objects REST attributes
|
[
"Compare",
"objects",
"REST",
"attributes"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L1026-L1033
|
train
|
nuagenetworks/bambou
|
bambou/nurest_object.py
|
NURESTObject.equals
|
def equals(self, rest_object):
""" Compare with another object """
if self._is_dirty:
return False
if rest_object is None:
return False
if not isinstance(rest_object, NURESTObject):
raise TypeError('The object is not a NURESTObject %s' % rest_object)
if self.rest_name != rest_object.rest_name:
return False
if self.id and rest_object.id:
return self.id == rest_object.id
if self.local_id and rest_object.local_id:
return self.local_id == rest_object.local_id
return False
|
python
|
def equals(self, rest_object):
""" Compare with another object """
if self._is_dirty:
return False
if rest_object is None:
return False
if not isinstance(rest_object, NURESTObject):
raise TypeError('The object is not a NURESTObject %s' % rest_object)
if self.rest_name != rest_object.rest_name:
return False
if self.id and rest_object.id:
return self.id == rest_object.id
if self.local_id and rest_object.local_id:
return self.local_id == rest_object.local_id
return False
|
[
"def",
"equals",
"(",
"self",
",",
"rest_object",
")",
":",
"if",
"self",
".",
"_is_dirty",
":",
"return",
"False",
"if",
"rest_object",
"is",
"None",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"rest_object",
",",
"NURESTObject",
")",
":",
"raise",
"TypeError",
"(",
"'The object is not a NURESTObject %s'",
"%",
"rest_object",
")",
"if",
"self",
".",
"rest_name",
"!=",
"rest_object",
".",
"rest_name",
":",
"return",
"False",
"if",
"self",
".",
"id",
"and",
"rest_object",
".",
"id",
":",
"return",
"self",
".",
"id",
"==",
"rest_object",
".",
"id",
"if",
"self",
".",
"local_id",
"and",
"rest_object",
".",
"local_id",
":",
"return",
"self",
".",
"local_id",
"==",
"rest_object",
".",
"local_id",
"return",
"False"
] |
Compare with another object
|
[
"Compare",
"with",
"another",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L1035-L1056
|
train
|
opennode/waldur-core
|
waldur_core/logging/middleware.py
|
get_ip_address
|
def get_ip_address(request):
"""
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
else:
return request.META['REMOTE_ADDR']
|
python
|
def get_ip_address(request):
"""
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
else:
return request.META['REMOTE_ADDR']
|
[
"def",
"get_ip_address",
"(",
"request",
")",
":",
"if",
"'HTTP_X_FORWARDED_FOR'",
"in",
"request",
".",
"META",
":",
"return",
"request",
".",
"META",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"else",
":",
"return",
"request",
".",
"META",
"[",
"'REMOTE_ADDR'",
"]"
] |
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
|
[
"Correct",
"IP",
"address",
"is",
"expected",
"as",
"first",
"element",
"of",
"HTTP_X_FORWARDED_FOR",
"or",
"REMOTE_ADDR"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/middleware.py#L29-L36
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/management/commands/delete_invalid_price_estimates.py
|
Command.get_estimates_without_scope_in_month
|
def get_estimates_without_scope_in_month(self, customer):
"""
It is expected that valid row for each month contains at least one
price estimate for customer, service setting, service,
service project link, project and resource.
Otherwise all price estimates in the row should be deleted.
"""
estimates = self.get_price_estimates_for_customer(customer)
if not estimates:
return []
tables = {model: collections.defaultdict(list)
for model in self.get_estimated_models()}
dates = set()
for estimate in estimates:
date = (estimate.year, estimate.month)
dates.add(date)
cls = estimate.content_type.model_class()
for model, table in tables.items():
if issubclass(cls, model):
table[date].append(estimate)
break
invalid_estimates = []
for date in dates:
if any(map(lambda table: len(table[date]) == 0, tables.values())):
for table in tables.values():
invalid_estimates.extend(table[date])
print(invalid_estimates)
return invalid_estimates
|
python
|
def get_estimates_without_scope_in_month(self, customer):
"""
It is expected that valid row for each month contains at least one
price estimate for customer, service setting, service,
service project link, project and resource.
Otherwise all price estimates in the row should be deleted.
"""
estimates = self.get_price_estimates_for_customer(customer)
if not estimates:
return []
tables = {model: collections.defaultdict(list)
for model in self.get_estimated_models()}
dates = set()
for estimate in estimates:
date = (estimate.year, estimate.month)
dates.add(date)
cls = estimate.content_type.model_class()
for model, table in tables.items():
if issubclass(cls, model):
table[date].append(estimate)
break
invalid_estimates = []
for date in dates:
if any(map(lambda table: len(table[date]) == 0, tables.values())):
for table in tables.values():
invalid_estimates.extend(table[date])
print(invalid_estimates)
return invalid_estimates
|
[
"def",
"get_estimates_without_scope_in_month",
"(",
"self",
",",
"customer",
")",
":",
"estimates",
"=",
"self",
".",
"get_price_estimates_for_customer",
"(",
"customer",
")",
"if",
"not",
"estimates",
":",
"return",
"[",
"]",
"tables",
"=",
"{",
"model",
":",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"model",
"in",
"self",
".",
"get_estimated_models",
"(",
")",
"}",
"dates",
"=",
"set",
"(",
")",
"for",
"estimate",
"in",
"estimates",
":",
"date",
"=",
"(",
"estimate",
".",
"year",
",",
"estimate",
".",
"month",
")",
"dates",
".",
"add",
"(",
"date",
")",
"cls",
"=",
"estimate",
".",
"content_type",
".",
"model_class",
"(",
")",
"for",
"model",
",",
"table",
"in",
"tables",
".",
"items",
"(",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"model",
")",
":",
"table",
"[",
"date",
"]",
".",
"append",
"(",
"estimate",
")",
"break",
"invalid_estimates",
"=",
"[",
"]",
"for",
"date",
"in",
"dates",
":",
"if",
"any",
"(",
"map",
"(",
"lambda",
"table",
":",
"len",
"(",
"table",
"[",
"date",
"]",
")",
"==",
"0",
",",
"tables",
".",
"values",
"(",
")",
")",
")",
":",
"for",
"table",
"in",
"tables",
".",
"values",
"(",
")",
":",
"invalid_estimates",
".",
"extend",
"(",
"table",
"[",
"date",
"]",
")",
"print",
"(",
"invalid_estimates",
")",
"return",
"invalid_estimates"
] |
It is expected that valid row for each month contains at least one
price estimate for customer, service setting, service,
service project link, project and resource.
Otherwise all price estimates in the row should be deleted.
|
[
"It",
"is",
"expected",
"that",
"valid",
"row",
"for",
"each",
"month",
"contains",
"at",
"least",
"one",
"price",
"estimate",
"for",
"customer",
"service",
"setting",
"service",
"service",
"project",
"link",
"project",
"and",
"resource",
".",
"Otherwise",
"all",
"price",
"estimates",
"in",
"the",
"row",
"should",
"be",
"deleted",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/management/commands/delete_invalid_price_estimates.py#L78-L109
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.is_identifier
|
def is_identifier(self, is_identifier):
""" Setter for is_identifier """
if is_identifier:
self.is_editable = False
self._is_identifier = is_identifier
|
python
|
def is_identifier(self, is_identifier):
""" Setter for is_identifier """
if is_identifier:
self.is_editable = False
self._is_identifier = is_identifier
|
[
"def",
"is_identifier",
"(",
"self",
",",
"is_identifier",
")",
":",
"if",
"is_identifier",
":",
"self",
".",
"is_editable",
"=",
"False",
"self",
".",
"_is_identifier",
"=",
"is_identifier"
] |
Setter for is_identifier
|
[
"Setter",
"for",
"is_identifier"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L75-L81
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.is_password
|
def is_password(self, is_password):
""" Setter for is_identifier """
if is_password:
self.is_forgetable = True
self._is_password = is_password
|
python
|
def is_password(self, is_password):
""" Setter for is_identifier """
if is_password:
self.is_forgetable = True
self._is_password = is_password
|
[
"def",
"is_password",
"(",
"self",
",",
"is_password",
")",
":",
"if",
"is_password",
":",
"self",
".",
"is_forgetable",
"=",
"True",
"self",
".",
"_is_password",
"=",
"is_password"
] |
Setter for is_identifier
|
[
"Setter",
"for",
"is_identifier"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L90-L96
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.choices
|
def choices(self, choices):
""" Setter for is_identifier """
if choices is not None and len(choices) > 0:
self.has_choices = True
self._choices = choices
|
python
|
def choices(self, choices):
""" Setter for is_identifier """
if choices is not None and len(choices) > 0:
self.has_choices = True
self._choices = choices
|
[
"def",
"choices",
"(",
"self",
",",
"choices",
")",
":",
"if",
"choices",
"is",
"not",
"None",
"and",
"len",
"(",
"choices",
")",
">",
"0",
":",
"self",
".",
"has_choices",
"=",
"True",
"self",
".",
"_choices",
"=",
"choices"
] |
Setter for is_identifier
|
[
"Setter",
"for",
"is_identifier"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L105-L111
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.get_default_value
|
def get_default_value(self):
""" Get a default value of the attribute_type """
if self.choices:
return self.choices[0]
value = self.attribute_type()
if self.attribute_type is time:
value = int(value)
elif self.attribute_type is str:
value = "A"
if self.min_length:
if self.attribute_type is str:
value = value.ljust(self.min_length, 'a')
elif self.attribute_type is int:
value = self.min_length
elif self.max_length:
if self.attribute_type is str:
value = value.ljust(self.max_length, 'a')
elif self.attribute_type is int:
value = self.max_length
return value
|
python
|
def get_default_value(self):
""" Get a default value of the attribute_type """
if self.choices:
return self.choices[0]
value = self.attribute_type()
if self.attribute_type is time:
value = int(value)
elif self.attribute_type is str:
value = "A"
if self.min_length:
if self.attribute_type is str:
value = value.ljust(self.min_length, 'a')
elif self.attribute_type is int:
value = self.min_length
elif self.max_length:
if self.attribute_type is str:
value = value.ljust(self.max_length, 'a')
elif self.attribute_type is int:
value = self.max_length
return value
|
[
"def",
"get_default_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"choices",
":",
"return",
"self",
".",
"choices",
"[",
"0",
"]",
"value",
"=",
"self",
".",
"attribute_type",
"(",
")",
"if",
"self",
".",
"attribute_type",
"is",
"time",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"self",
".",
"attribute_type",
"is",
"str",
":",
"value",
"=",
"\"A\"",
"if",
"self",
".",
"min_length",
":",
"if",
"self",
".",
"attribute_type",
"is",
"str",
":",
"value",
"=",
"value",
".",
"ljust",
"(",
"self",
".",
"min_length",
",",
"'a'",
")",
"elif",
"self",
".",
"attribute_type",
"is",
"int",
":",
"value",
"=",
"self",
".",
"min_length",
"elif",
"self",
".",
"max_length",
":",
"if",
"self",
".",
"attribute_type",
"is",
"str",
":",
"value",
"=",
"value",
".",
"ljust",
"(",
"self",
".",
"max_length",
",",
"'a'",
")",
"elif",
"self",
".",
"attribute_type",
"is",
"int",
":",
"value",
"=",
"self",
".",
"max_length",
"return",
"value"
] |
Get a default value of the attribute_type
|
[
"Get",
"a",
"default",
"value",
"of",
"the",
"attribute_type"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L115-L141
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.get_min_value
|
def get_min_value(self):
""" Get the minimum value """
value = self.get_default_value()
if self.attribute_type is str:
min_value = value[:self.min_length - 1]
elif self.attribute_type is int:
min_value = self.min_length - 1
else:
raise TypeError('Attribute %s can not have a minimum value' % self.local_name)
return min_value
|
python
|
def get_min_value(self):
""" Get the minimum value """
value = self.get_default_value()
if self.attribute_type is str:
min_value = value[:self.min_length - 1]
elif self.attribute_type is int:
min_value = self.min_length - 1
else:
raise TypeError('Attribute %s can not have a minimum value' % self.local_name)
return min_value
|
[
"def",
"get_min_value",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"get_default_value",
"(",
")",
"if",
"self",
".",
"attribute_type",
"is",
"str",
":",
"min_value",
"=",
"value",
"[",
":",
"self",
".",
"min_length",
"-",
"1",
"]",
"elif",
"self",
".",
"attribute_type",
"is",
"int",
":",
"min_value",
"=",
"self",
".",
"min_length",
"-",
"1",
"else",
":",
"raise",
"TypeError",
"(",
"'Attribute %s can not have a minimum value'",
"%",
"self",
".",
"local_name",
")",
"return",
"min_value"
] |
Get the minimum value
|
[
"Get",
"the",
"minimum",
"value"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L143-L157
|
train
|
nuagenetworks/bambou
|
bambou/utils/nuremote_attribute.py
|
NURemoteAttribute.get_max_value
|
def get_max_value(self):
""" Get the maximum value """
value = self.get_default_value()
if self.attribute_type is str:
max_value = value.ljust(self.max_length + 1, 'a')
elif self.attribute_type is int:
max_value = self.max_length + 1
else:
raise TypeError('Attribute %s can not have a maximum value' % self.local_name)
return max_value
|
python
|
def get_max_value(self):
""" Get the maximum value """
value = self.get_default_value()
if self.attribute_type is str:
max_value = value.ljust(self.max_length + 1, 'a')
elif self.attribute_type is int:
max_value = self.max_length + 1
else:
raise TypeError('Attribute %s can not have a maximum value' % self.local_name)
return max_value
|
[
"def",
"get_max_value",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"get_default_value",
"(",
")",
"if",
"self",
".",
"attribute_type",
"is",
"str",
":",
"max_value",
"=",
"value",
".",
"ljust",
"(",
"self",
".",
"max_length",
"+",
"1",
",",
"'a'",
")",
"elif",
"self",
".",
"attribute_type",
"is",
"int",
":",
"max_value",
"=",
"self",
".",
"max_length",
"+",
"1",
"else",
":",
"raise",
"TypeError",
"(",
"'Attribute %s can not have a maximum value'",
"%",
"self",
".",
"local_name",
")",
"return",
"max_value"
] |
Get the maximum value
|
[
"Get",
"the",
"maximum",
"value"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/nuremote_attribute.py#L159-L173
|
train
|
opennode/waldur-core
|
waldur_core/core/routers.py
|
SortedDefaultRouter.get_api_root_view
|
def get_api_root_view(self, api_urls=None):
"""
Return a basic root view.
"""
api_root_dict = OrderedDict()
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
class APIRootView(views.APIView):
_ignore_model_permissions = True
exclude_from_schema = True
def get(self, request, *args, **kwargs):
# Return a plain {"name": "hyperlink"} response.
ret = OrderedDict()
namespace = request.resolver_match.namespace
for key, url_name in sorted(api_root_dict.items(), key=itemgetter(0)):
if namespace:
url_name = namespace + ':' + url_name
try:
ret[key] = reverse(
url_name,
args=args,
kwargs=kwargs,
request=request,
format=kwargs.get('format', None)
)
except NoReverseMatch:
# Don't bail out if eg. no list routes exist, only detail routes.
continue
return Response(ret)
return APIRootView.as_view()
|
python
|
def get_api_root_view(self, api_urls=None):
"""
Return a basic root view.
"""
api_root_dict = OrderedDict()
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
class APIRootView(views.APIView):
_ignore_model_permissions = True
exclude_from_schema = True
def get(self, request, *args, **kwargs):
# Return a plain {"name": "hyperlink"} response.
ret = OrderedDict()
namespace = request.resolver_match.namespace
for key, url_name in sorted(api_root_dict.items(), key=itemgetter(0)):
if namespace:
url_name = namespace + ':' + url_name
try:
ret[key] = reverse(
url_name,
args=args,
kwargs=kwargs,
request=request,
format=kwargs.get('format', None)
)
except NoReverseMatch:
# Don't bail out if eg. no list routes exist, only detail routes.
continue
return Response(ret)
return APIRootView.as_view()
|
[
"def",
"get_api_root_view",
"(",
"self",
",",
"api_urls",
"=",
"None",
")",
":",
"api_root_dict",
"=",
"OrderedDict",
"(",
")",
"list_name",
"=",
"self",
".",
"routes",
"[",
"0",
"]",
".",
"name",
"for",
"prefix",
",",
"viewset",
",",
"basename",
"in",
"self",
".",
"registry",
":",
"api_root_dict",
"[",
"prefix",
"]",
"=",
"list_name",
".",
"format",
"(",
"basename",
"=",
"basename",
")",
"class",
"APIRootView",
"(",
"views",
".",
"APIView",
")",
":",
"_ignore_model_permissions",
"=",
"True",
"exclude_from_schema",
"=",
"True",
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Return a plain {\"name\": \"hyperlink\"} response.",
"ret",
"=",
"OrderedDict",
"(",
")",
"namespace",
"=",
"request",
".",
"resolver_match",
".",
"namespace",
"for",
"key",
",",
"url_name",
"in",
"sorted",
"(",
"api_root_dict",
".",
"items",
"(",
")",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
":",
"if",
"namespace",
":",
"url_name",
"=",
"namespace",
"+",
"':'",
"+",
"url_name",
"try",
":",
"ret",
"[",
"key",
"]",
"=",
"reverse",
"(",
"url_name",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"request",
"=",
"request",
",",
"format",
"=",
"kwargs",
".",
"get",
"(",
"'format'",
",",
"None",
")",
")",
"except",
"NoReverseMatch",
":",
"# Don't bail out if eg. no list routes exist, only detail routes.",
"continue",
"return",
"Response",
"(",
"ret",
")",
"return",
"APIRootView",
".",
"as_view",
"(",
")"
] |
Return a basic root view.
|
[
"Return",
"a",
"basic",
"root",
"view",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/routers.py#L13-L47
|
train
|
opennode/waldur-core
|
waldur_core/core/routers.py
|
SortedDefaultRouter.get_default_base_name
|
def get_default_base_name(self, viewset):
"""
Attempt to automatically determine base name using `get_url_name`.
"""
queryset = getattr(viewset, 'queryset', None)
if queryset is not None:
get_url_name = getattr(queryset.model, 'get_url_name', None)
if get_url_name is not None:
return get_url_name()
return super(SortedDefaultRouter, self).get_default_base_name(viewset)
|
python
|
def get_default_base_name(self, viewset):
"""
Attempt to automatically determine base name using `get_url_name`.
"""
queryset = getattr(viewset, 'queryset', None)
if queryset is not None:
get_url_name = getattr(queryset.model, 'get_url_name', None)
if get_url_name is not None:
return get_url_name()
return super(SortedDefaultRouter, self).get_default_base_name(viewset)
|
[
"def",
"get_default_base_name",
"(",
"self",
",",
"viewset",
")",
":",
"queryset",
"=",
"getattr",
"(",
"viewset",
",",
"'queryset'",
",",
"None",
")",
"if",
"queryset",
"is",
"not",
"None",
":",
"get_url_name",
"=",
"getattr",
"(",
"queryset",
".",
"model",
",",
"'get_url_name'",
",",
"None",
")",
"if",
"get_url_name",
"is",
"not",
"None",
":",
"return",
"get_url_name",
"(",
")",
"return",
"super",
"(",
"SortedDefaultRouter",
",",
"self",
")",
".",
"get_default_base_name",
"(",
"viewset",
")"
] |
Attempt to automatically determine base name using `get_url_name`.
|
[
"Attempt",
"to",
"automatically",
"determine",
"base",
"name",
"using",
"get_url_name",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/routers.py#L49-L60
|
train
|
opennode/waldur-core
|
waldur_core/structure/handlers.py
|
change_customer_nc_users_quota
|
def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs):
""" Modify nc_user_count quota usage on structure role grant or revoke """
assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \
'Handler "change_customer_nc_users_quota" has to be used only with structure_role signals'
assert sender in (Customer, Project), \
'Handler "change_customer_nc_users_quota" works only with Project and Customer models'
if sender == Customer:
customer = structure
elif sender == Project:
customer = structure.customer
customer_users = customer.get_users()
customer.set_quota_usage(Customer.Quotas.nc_user_count, customer_users.count())
|
python
|
def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs):
""" Modify nc_user_count quota usage on structure role grant or revoke """
assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \
'Handler "change_customer_nc_users_quota" has to be used only with structure_role signals'
assert sender in (Customer, Project), \
'Handler "change_customer_nc_users_quota" works only with Project and Customer models'
if sender == Customer:
customer = structure
elif sender == Project:
customer = structure.customer
customer_users = customer.get_users()
customer.set_quota_usage(Customer.Quotas.nc_user_count, customer_users.count())
|
[
"def",
"change_customer_nc_users_quota",
"(",
"sender",
",",
"structure",
",",
"user",
",",
"role",
",",
"signal",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"signal",
"in",
"(",
"signals",
".",
"structure_role_granted",
",",
"signals",
".",
"structure_role_revoked",
")",
",",
"'Handler \"change_customer_nc_users_quota\" has to be used only with structure_role signals'",
"assert",
"sender",
"in",
"(",
"Customer",
",",
"Project",
")",
",",
"'Handler \"change_customer_nc_users_quota\" works only with Project and Customer models'",
"if",
"sender",
"==",
"Customer",
":",
"customer",
"=",
"structure",
"elif",
"sender",
"==",
"Project",
":",
"customer",
"=",
"structure",
".",
"customer",
"customer_users",
"=",
"customer",
".",
"get_users",
"(",
")",
"customer",
".",
"set_quota_usage",
"(",
"Customer",
".",
"Quotas",
".",
"nc_user_count",
",",
"customer_users",
".",
"count",
"(",
")",
")"
] |
Modify nc_user_count quota usage on structure role grant or revoke
|
[
"Modify",
"nc_user_count",
"quota",
"usage",
"on",
"structure",
"role",
"grant",
"or",
"revoke"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/handlers.py#L196-L209
|
train
|
opennode/waldur-core
|
waldur_core/structure/handlers.py
|
delete_service_settings_on_service_delete
|
def delete_service_settings_on_service_delete(sender, instance, **kwargs):
""" Delete not shared service settings without services """
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
# If this handler works together with delete_service_settings_on_scope_delete
# it tries to delete service settings that are already deleted.
return
if not service_settings.shared:
service.settings.delete()
|
python
|
def delete_service_settings_on_service_delete(sender, instance, **kwargs):
""" Delete not shared service settings without services """
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
# If this handler works together with delete_service_settings_on_scope_delete
# it tries to delete service settings that are already deleted.
return
if not service_settings.shared:
service.settings.delete()
|
[
"def",
"delete_service_settings_on_service_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"service",
"=",
"instance",
"try",
":",
"service_settings",
"=",
"service",
".",
"settings",
"except",
"ServiceSettings",
".",
"DoesNotExist",
":",
"# If this handler works together with delete_service_settings_on_scope_delete",
"# it tries to delete service settings that are already deleted.",
"return",
"if",
"not",
"service_settings",
".",
"shared",
":",
"service",
".",
"settings",
".",
"delete",
"(",
")"
] |
Delete not shared service settings without services
|
[
"Delete",
"not",
"shared",
"service",
"settings",
"without",
"services"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/handlers.py#L312-L322
|
train
|
opennode/waldur-core
|
waldur_core/structure/handlers.py
|
delete_service_settings_on_scope_delete
|
def delete_service_settings_on_scope_delete(sender, instance, **kwargs):
""" If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
"""
for service_settings in ServiceSettings.objects.filter(scope=instance):
service_settings.unlink_descendants()
service_settings.delete()
|
python
|
def delete_service_settings_on_scope_delete(sender, instance, **kwargs):
""" If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
"""
for service_settings in ServiceSettings.objects.filter(scope=instance):
service_settings.unlink_descendants()
service_settings.delete()
|
[
"def",
"delete_service_settings_on_scope_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"service_settings",
"in",
"ServiceSettings",
".",
"objects",
".",
"filter",
"(",
"scope",
"=",
"instance",
")",
":",
"service_settings",
".",
"unlink_descendants",
"(",
")",
"service_settings",
".",
"delete",
"(",
")"
] |
If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
|
[
"If",
"VM",
"that",
"contains",
"service",
"settings",
"were",
"deleted",
"-",
"all",
"settings",
"resources",
"could",
"be",
"safely",
"deleted",
"from",
"NC",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/handlers.py#L343-L349
|
train
|
nuagenetworks/bambou
|
bambou/nurest_login_controller.py
|
NURESTLoginController.url
|
def url(self, url):
""" Set API URL endpoint
Args:
url: the url of the API endpoint
"""
if url and url.endswith('/'):
url = url[:-1]
self._url = url
|
python
|
def url(self, url):
""" Set API URL endpoint
Args:
url: the url of the API endpoint
"""
if url and url.endswith('/'):
url = url[:-1]
self._url = url
|
[
"def",
"url",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"and",
"url",
".",
"endswith",
"(",
"'/'",
")",
":",
"url",
"=",
"url",
"[",
":",
"-",
"1",
"]",
"self",
".",
"_url",
"=",
"url"
] |
Set API URL endpoint
Args:
url: the url of the API endpoint
|
[
"Set",
"API",
"URL",
"endpoint"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L191-L200
|
train
|
nuagenetworks/bambou
|
bambou/nurest_login_controller.py
|
NURESTLoginController.get_authentication_header
|
def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None):
""" Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are responsible to
clean the password property.
Returns:
Returns the XREST Authentication string with API Key or user password encoded.
"""
if not user:
user = self.user
if not api_key:
api_key = self.api_key
if not password:
password = self.password
if not password:
password = self.password
if not certificate:
certificate = self._certificate
if certificate:
return "XREST %s" % urlsafe_b64encode("{}:".format(user).encode('utf-8')).decode('utf-8')
if api_key:
return "XREST %s" % urlsafe_b64encode("{}:{}".format(user, api_key).encode('utf-8')).decode('utf-8')
return "XREST %s" % urlsafe_b64encode("{}:{}".format(user, password).encode('utf-8')).decode('utf-8')
|
python
|
def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None):
""" Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are responsible to
clean the password property.
Returns:
Returns the XREST Authentication string with API Key or user password encoded.
"""
if not user:
user = self.user
if not api_key:
api_key = self.api_key
if not password:
password = self.password
if not password:
password = self.password
if not certificate:
certificate = self._certificate
if certificate:
return "XREST %s" % urlsafe_b64encode("{}:".format(user).encode('utf-8')).decode('utf-8')
if api_key:
return "XREST %s" % urlsafe_b64encode("{}:{}".format(user, api_key).encode('utf-8')).decode('utf-8')
return "XREST %s" % urlsafe_b64encode("{}:{}".format(user, password).encode('utf-8')).decode('utf-8')
|
[
"def",
"get_authentication_header",
"(",
"self",
",",
"user",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"password",
"=",
"None",
",",
"certificate",
"=",
"None",
")",
":",
"if",
"not",
"user",
":",
"user",
"=",
"self",
".",
"user",
"if",
"not",
"api_key",
":",
"api_key",
"=",
"self",
".",
"api_key",
"if",
"not",
"password",
":",
"password",
"=",
"self",
".",
"password",
"if",
"not",
"password",
":",
"password",
"=",
"self",
".",
"password",
"if",
"not",
"certificate",
":",
"certificate",
"=",
"self",
".",
"_certificate",
"if",
"certificate",
":",
"return",
"\"XREST %s\"",
"%",
"urlsafe_b64encode",
"(",
"\"{}:\"",
".",
"format",
"(",
"user",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"api_key",
":",
"return",
"\"XREST %s\"",
"%",
"urlsafe_b64encode",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"user",
",",
"api_key",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"\"XREST %s\"",
"%",
"urlsafe_b64encode",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"user",
",",
"password",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are responsible to
clean the password property.
Returns:
Returns the XREST Authentication string with API Key or user password encoded.
|
[
"Return",
"authenication",
"string",
"to",
"place",
"in",
"Authorization",
"Header"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L223-L256
|
train
|
nuagenetworks/bambou
|
bambou/nurest_login_controller.py
|
NURESTLoginController.reset
|
def reset(self):
""" Reset controller
It removes all information about previous session
"""
self._is_impersonating = False
self._impersonation = None
self.user = None
self.password = None
self.api_key = None
self.enterprise = None
self.url = None
|
python
|
def reset(self):
""" Reset controller
It removes all information about previous session
"""
self._is_impersonating = False
self._impersonation = None
self.user = None
self.password = None
self.api_key = None
self.enterprise = None
self.url = None
|
[
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_is_impersonating",
"=",
"False",
"self",
".",
"_impersonation",
"=",
"None",
"self",
".",
"user",
"=",
"None",
"self",
".",
"password",
"=",
"None",
"self",
".",
"api_key",
"=",
"None",
"self",
".",
"enterprise",
"=",
"None",
"self",
".",
"url",
"=",
"None"
] |
Reset controller
It removes all information about previous session
|
[
"Reset",
"controller"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L258-L271
|
train
|
nuagenetworks/bambou
|
bambou/nurest_login_controller.py
|
NURESTLoginController.impersonate
|
def impersonate(self, user, enterprise):
""" Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation
"""
if not user or not enterprise:
raise ValueError('You must set a user name and an enterprise name to begin impersonification')
self._is_impersonating = True
self._impersonation = "%s@%s" % (user, enterprise)
|
python
|
def impersonate(self, user, enterprise):
""" Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation
"""
if not user or not enterprise:
raise ValueError('You must set a user name and an enterprise name to begin impersonification')
self._is_impersonating = True
self._impersonation = "%s@%s" % (user, enterprise)
|
[
"def",
"impersonate",
"(",
"self",
",",
"user",
",",
"enterprise",
")",
":",
"if",
"not",
"user",
"or",
"not",
"enterprise",
":",
"raise",
"ValueError",
"(",
"'You must set a user name and an enterprise name to begin impersonification'",
")",
"self",
".",
"_is_impersonating",
"=",
"True",
"self",
".",
"_impersonation",
"=",
"\"%s@%s\"",
"%",
"(",
"user",
",",
"enterprise",
")"
] |
Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation
|
[
"Impersonate",
"a",
"user",
"in",
"a",
"enterprise"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L273-L285
|
train
|
nuagenetworks/bambou
|
bambou/nurest_login_controller.py
|
NURESTLoginController.equals
|
def equals(self, controller):
""" Verify if the controller corresponds
to the current one.
"""
if controller is None:
return False
return self.user == controller.user and self.enterprise == controller.enterprise and self.url == controller.url
|
python
|
def equals(self, controller):
""" Verify if the controller corresponds
to the current one.
"""
if controller is None:
return False
return self.user == controller.user and self.enterprise == controller.enterprise and self.url == controller.url
|
[
"def",
"equals",
"(",
"self",
",",
"controller",
")",
":",
"if",
"controller",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"user",
"==",
"controller",
".",
"user",
"and",
"self",
".",
"enterprise",
"==",
"controller",
".",
"enterprise",
"and",
"self",
".",
"url",
"==",
"controller",
".",
"url"
] |
Verify if the controller corresponds
to the current one.
|
[
"Verify",
"if",
"the",
"controller",
"corresponds",
"to",
"the",
"current",
"one",
"."
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L294-L302
|
train
|
stepank/pyws
|
src/pyws/adapters/_wsgi.py
|
create_application
|
def create_application(server, root_url):
"""
WSGI adapter. It creates a simple WSGI application, that can be used with
any WSGI server. The arguments are:
#. ``server`` is a pyws server object,
#. ``root_url`` is an URL to which the server will be bound.
An application created by the function transforms WSGI environment into a
pyws request object. Then it feeds the request to the server, gets the
response, sets header ``Content-Type`` and returns response text.
"""
def serve(environ, start_response):
root = root_url.lstrip('/')
tail, get = (util.request_uri(environ).split('?') + [''])[:2]
tail = tail[len(util.application_uri(environ)):]
tail = tail.lstrip('/')
result = []
content_type = 'text/plain'
status = '200 OK'
if tail.startswith(root):
tail = tail[len(root):]
get = parse_qs(get)
method = environ['REQUEST_METHOD']
text, post = '', {}
if method == 'POST':
text = environ['wsgi.input'].\
read(int(environ.get('CONTENT_LENGTH', 0)))
post = parse_qs(text)
response = server.process_request(
Request(tail, text, get, post, {}))
content_type = response.content_type
status = get_http_response_code(response)
result.append(response.text)
headers = [('Content-type', content_type)]
start_response(status, headers)
return result
return serve
|
python
|
def create_application(server, root_url):
"""
WSGI adapter. It creates a simple WSGI application, that can be used with
any WSGI server. The arguments are:
#. ``server`` is a pyws server object,
#. ``root_url`` is an URL to which the server will be bound.
An application created by the function transforms WSGI environment into a
pyws request object. Then it feeds the request to the server, gets the
response, sets header ``Content-Type`` and returns response text.
"""
def serve(environ, start_response):
root = root_url.lstrip('/')
tail, get = (util.request_uri(environ).split('?') + [''])[:2]
tail = tail[len(util.application_uri(environ)):]
tail = tail.lstrip('/')
result = []
content_type = 'text/plain'
status = '200 OK'
if tail.startswith(root):
tail = tail[len(root):]
get = parse_qs(get)
method = environ['REQUEST_METHOD']
text, post = '', {}
if method == 'POST':
text = environ['wsgi.input'].\
read(int(environ.get('CONTENT_LENGTH', 0)))
post = parse_qs(text)
response = server.process_request(
Request(tail, text, get, post, {}))
content_type = response.content_type
status = get_http_response_code(response)
result.append(response.text)
headers = [('Content-type', content_type)]
start_response(status, headers)
return result
return serve
|
[
"def",
"create_application",
"(",
"server",
",",
"root_url",
")",
":",
"def",
"serve",
"(",
"environ",
",",
"start_response",
")",
":",
"root",
"=",
"root_url",
".",
"lstrip",
"(",
"'/'",
")",
"tail",
",",
"get",
"=",
"(",
"util",
".",
"request_uri",
"(",
"environ",
")",
".",
"split",
"(",
"'?'",
")",
"+",
"[",
"''",
"]",
")",
"[",
":",
"2",
"]",
"tail",
"=",
"tail",
"[",
"len",
"(",
"util",
".",
"application_uri",
"(",
"environ",
")",
")",
":",
"]",
"tail",
"=",
"tail",
".",
"lstrip",
"(",
"'/'",
")",
"result",
"=",
"[",
"]",
"content_type",
"=",
"'text/plain'",
"status",
"=",
"'200 OK'",
"if",
"tail",
".",
"startswith",
"(",
"root",
")",
":",
"tail",
"=",
"tail",
"[",
"len",
"(",
"root",
")",
":",
"]",
"get",
"=",
"parse_qs",
"(",
"get",
")",
"method",
"=",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"text",
",",
"post",
"=",
"''",
",",
"{",
"}",
"if",
"method",
"==",
"'POST'",
":",
"text",
"=",
"environ",
"[",
"'wsgi.input'",
"]",
".",
"read",
"(",
"int",
"(",
"environ",
".",
"get",
"(",
"'CONTENT_LENGTH'",
",",
"0",
")",
")",
")",
"post",
"=",
"parse_qs",
"(",
"text",
")",
"response",
"=",
"server",
".",
"process_request",
"(",
"Request",
"(",
"tail",
",",
"text",
",",
"get",
",",
"post",
",",
"{",
"}",
")",
")",
"content_type",
"=",
"response",
".",
"content_type",
"status",
"=",
"get_http_response_code",
"(",
"response",
")",
"result",
".",
"append",
"(",
"response",
".",
"text",
")",
"headers",
"=",
"[",
"(",
"'Content-type'",
",",
"content_type",
")",
"]",
"start_response",
"(",
"status",
",",
"headers",
")",
"return",
"result",
"return",
"serve"
] |
WSGI adapter. It creates a simple WSGI application, that can be used with
any WSGI server. The arguments are:
#. ``server`` is a pyws server object,
#. ``root_url`` is an URL to which the server will be bound.
An application created by the function transforms WSGI environment into a
pyws request object. Then it feeds the request to the server, gets the
response, sets header ``Content-Type`` and returns response text.
|
[
"WSGI",
"adapter",
".",
"It",
"creates",
"a",
"simple",
"WSGI",
"application",
"that",
"can",
"be",
"used",
"with",
"any",
"WSGI",
"server",
".",
"The",
"arguments",
"are",
":"
] |
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
|
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_wsgi.py#L8-L58
|
train
|
zeromake/aiosqlite3
|
aiosqlite3/sa/engine.py
|
compiler_dialect
|
def compiler_dialect(paramstyle='named'):
"""
构建dialect
"""
dialect = SQLiteDialect_pysqlite(
json_serializer=json.dumps,
json_deserializer=json_deserializer,
paramstyle=paramstyle
)
dialect.default_paramstyle = paramstyle
dialect.statement_compiler = ACompiler_sqlite
return dialect
|
python
|
def compiler_dialect(paramstyle='named'):
"""
构建dialect
"""
dialect = SQLiteDialect_pysqlite(
json_serializer=json.dumps,
json_deserializer=json_deserializer,
paramstyle=paramstyle
)
dialect.default_paramstyle = paramstyle
dialect.statement_compiler = ACompiler_sqlite
return dialect
|
[
"def",
"compiler_dialect",
"(",
"paramstyle",
"=",
"'named'",
")",
":",
"dialect",
"=",
"SQLiteDialect_pysqlite",
"(",
"json_serializer",
"=",
"json",
".",
"dumps",
",",
"json_deserializer",
"=",
"json_deserializer",
",",
"paramstyle",
"=",
"paramstyle",
")",
"dialect",
".",
"default_paramstyle",
"=",
"paramstyle",
"dialect",
".",
"statement_compiler",
"=",
"ACompiler_sqlite",
"return",
"dialect"
] |
构建dialect
|
[
"构建dialect"
] |
1a74a062507e2df8f833a70885e69dca0ab3e7e7
|
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/engine.py#L58-L69
|
train
|
zeromake/aiosqlite3
|
aiosqlite3/sa/engine.py
|
create_engine
|
def create_engine(
database,
minsize=1,
maxsize=10,
loop=None,
dialect=_dialect,
paramstyle=None,
**kwargs):
"""
A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to sqlite3.
"""
coro = _create_engine(
database=database,
minsize=minsize,
maxsize=maxsize,
loop=loop,
dialect=dialect,
paramstyle=paramstyle,
**kwargs
)
return _EngineContextManager(coro)
|
python
|
def create_engine(
database,
minsize=1,
maxsize=10,
loop=None,
dialect=_dialect,
paramstyle=None,
**kwargs):
"""
A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to sqlite3.
"""
coro = _create_engine(
database=database,
minsize=minsize,
maxsize=maxsize,
loop=loop,
dialect=dialect,
paramstyle=paramstyle,
**kwargs
)
return _EngineContextManager(coro)
|
[
"def",
"create_engine",
"(",
"database",
",",
"minsize",
"=",
"1",
",",
"maxsize",
"=",
"10",
",",
"loop",
"=",
"None",
",",
"dialect",
"=",
"_dialect",
",",
"paramstyle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"coro",
"=",
"_create_engine",
"(",
"database",
"=",
"database",
",",
"minsize",
"=",
"minsize",
",",
"maxsize",
"=",
"maxsize",
",",
"loop",
"=",
"loop",
",",
"dialect",
"=",
"dialect",
",",
"paramstyle",
"=",
"paramstyle",
",",
"*",
"*",
"kwargs",
")",
"return",
"_EngineContextManager",
"(",
"coro",
")"
] |
A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to sqlite3.
|
[
"A",
"coroutine",
"for",
"Engine",
"creation",
"."
] |
1a74a062507e2df8f833a70885e69dca0ab3e7e7
|
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/engine.py#L75-L99
|
train
|
zeromake/aiosqlite3
|
aiosqlite3/sa/engine.py
|
Engine.release
|
def release(self, conn):
"""Revert back connection to pool."""
if conn.in_transaction:
raise InvalidRequestError(
"Cannot release a connection with "
"not finished transaction"
)
raw = conn.connection
res = yield from self._pool.release(raw)
return res
|
python
|
def release(self, conn):
"""Revert back connection to pool."""
if conn.in_transaction:
raise InvalidRequestError(
"Cannot release a connection with "
"not finished transaction"
)
raw = conn.connection
res = yield from self._pool.release(raw)
return res
|
[
"def",
"release",
"(",
"self",
",",
"conn",
")",
":",
"if",
"conn",
".",
"in_transaction",
":",
"raise",
"InvalidRequestError",
"(",
"\"Cannot release a connection with \"",
"\"not finished transaction\"",
")",
"raw",
"=",
"conn",
".",
"connection",
"res",
"=",
"yield",
"from",
"self",
".",
"_pool",
".",
"release",
"(",
"raw",
")",
"return",
"res"
] |
Revert back connection to pool.
|
[
"Revert",
"back",
"connection",
"to",
"pool",
"."
] |
1a74a062507e2df8f833a70885e69dca0ab3e7e7
|
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/engine.py#L213-L222
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/__init__.py
|
CostTrackingRegister.get_configuration
|
def get_configuration(cls, resource):
""" Return how much consumables are used by resource with current configuration.
Output example:
{
<ConsumableItem instance>: <usage>,
<ConsumableItem instance>: <usage>,
...
}
"""
strategy = cls._get_strategy(resource.__class__)
return strategy.get_configuration(resource)
|
python
|
def get_configuration(cls, resource):
""" Return how much consumables are used by resource with current configuration.
Output example:
{
<ConsumableItem instance>: <usage>,
<ConsumableItem instance>: <usage>,
...
}
"""
strategy = cls._get_strategy(resource.__class__)
return strategy.get_configuration(resource)
|
[
"def",
"get_configuration",
"(",
"cls",
",",
"resource",
")",
":",
"strategy",
"=",
"cls",
".",
"_get_strategy",
"(",
"resource",
".",
"__class__",
")",
"return",
"strategy",
".",
"get_configuration",
"(",
"resource",
")"
] |
Return how much consumables are used by resource with current configuration.
Output example:
{
<ConsumableItem instance>: <usage>,
<ConsumableItem instance>: <usage>,
...
}
|
[
"Return",
"how",
"much",
"consumables",
"are",
"used",
"by",
"resource",
"with",
"current",
"configuration",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/__init__.py#L124-L135
|
train
|
zeromake/aiosqlite3
|
aiosqlite3/sa/result.py
|
ResultProxy.close
|
def close(self):
"""Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generated from an implicit execution,
the underlying Connection will also be closed (returns the
underlying DBAPI connection to the connection pool.)
This method is called automatically when:
* all result rows are exhausted using the fetchXXX() methods.
* cursor.description is None.
"""
if not self._closed:
self._closed = True
yield from self._cursor.close()
# allow consistent errors
self._cursor = None
self._weak = None
else:
# pragma: no cover
pass
|
python
|
def close(self):
"""Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generated from an implicit execution,
the underlying Connection will also be closed (returns the
underlying DBAPI connection to the connection pool.)
This method is called automatically when:
* all result rows are exhausted using the fetchXXX() methods.
* cursor.description is None.
"""
if not self._closed:
self._closed = True
yield from self._cursor.close()
# allow consistent errors
self._cursor = None
self._weak = None
else:
# pragma: no cover
pass
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"yield",
"from",
"self",
".",
"_cursor",
".",
"close",
"(",
")",
"# allow consistent errors",
"self",
".",
"_cursor",
"=",
"None",
"self",
".",
"_weak",
"=",
"None",
"else",
":",
"# pragma: no cover",
"pass"
] |
Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generated from an implicit execution,
the underlying Connection will also be closed (returns the
underlying DBAPI connection to the connection pool.)
This method is called automatically when:
* all result rows are exhausted using the fetchXXX() methods.
* cursor.description is None.
|
[
"Close",
"this",
"ResultProxy",
".",
"Closes",
"the",
"underlying",
"DBAPI",
"cursor",
"corresponding",
"to",
"the",
"execution",
".",
"Note",
"that",
"any",
"data",
"cached",
"within",
"this",
"ResultProxy",
"is",
"still",
"available",
".",
"For",
"some",
"types",
"of",
"results",
"this",
"may",
"include",
"buffered",
"rows",
".",
"If",
"this",
"ResultProxy",
"was",
"generated",
"from",
"an",
"implicit",
"execution",
"the",
"underlying",
"Connection",
"will",
"also",
"be",
"closed",
"(",
"returns",
"the",
"underlying",
"DBAPI",
"connection",
"to",
"the",
"connection",
"pool",
".",
")",
"This",
"method",
"is",
"called",
"automatically",
"when",
":",
"*",
"all",
"result",
"rows",
"are",
"exhausted",
"using",
"the",
"fetchXXX",
"()",
"methods",
".",
"*",
"cursor",
".",
"description",
"is",
"None",
"."
] |
1a74a062507e2df8f833a70885e69dca0ab3e7e7
|
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/result.py#L315-L336
|
train
|
OpenDataScienceLab/skdata
|
setup.py
|
get_version
|
def get_version():
"""Obtain the version number"""
import imp
import os
mod = imp.load_source(
'version', os.path.join('skdata', '__init__.py')
)
return mod.__version__
|
python
|
def get_version():
"""Obtain the version number"""
import imp
import os
mod = imp.load_source(
'version', os.path.join('skdata', '__init__.py')
)
return mod.__version__
|
[
"def",
"get_version",
"(",
")",
":",
"import",
"imp",
"import",
"os",
"mod",
"=",
"imp",
".",
"load_source",
"(",
"'version'",
",",
"os",
".",
"path",
".",
"join",
"(",
"'skdata'",
",",
"'__init__.py'",
")",
")",
"return",
"mod",
".",
"__version__"
] |
Obtain the version number
|
[
"Obtain",
"the",
"version",
"number"
] |
34f06845a944ff4f048b55c7babdd8420f71a6b9
|
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/setup.py#L29-L36
|
train
|
opennode/waldur-core
|
waldur_core/users/views.py
|
InvitationViewSet.accept
|
def accept(self, request, uuid=None):
""" Accept invitation for current user.
To replace user's email with email from invitation - add parameter
'replace_email' to request POST body.
"""
invitation = self.get_object()
if invitation.state != models.Invitation.State.PENDING:
raise ValidationError(_('Only pending invitation can be accepted.'))
elif invitation.civil_number and invitation.civil_number != request.user.civil_number:
raise ValidationError(_('User has an invalid civil number.'))
if invitation.project:
if invitation.project.has_user(request.user):
raise ValidationError(_('User already has role within this project.'))
elif invitation.customer.has_user(request.user):
raise ValidationError(_('User already has role within this customer.'))
if settings.WALDUR_CORE['VALIDATE_INVITATION_EMAIL'] and invitation.email != request.user.email:
raise ValidationError(_('Invitation and user emails mismatch.'))
replace_email = bool(request.data.get('replace_email'))
invitation.accept(request.user, replace_email=replace_email)
return Response({'detail': _('Invitation has been successfully accepted.')},
status=status.HTTP_200_OK)
|
python
|
def accept(self, request, uuid=None):
""" Accept invitation for current user.
To replace user's email with email from invitation - add parameter
'replace_email' to request POST body.
"""
invitation = self.get_object()
if invitation.state != models.Invitation.State.PENDING:
raise ValidationError(_('Only pending invitation can be accepted.'))
elif invitation.civil_number and invitation.civil_number != request.user.civil_number:
raise ValidationError(_('User has an invalid civil number.'))
if invitation.project:
if invitation.project.has_user(request.user):
raise ValidationError(_('User already has role within this project.'))
elif invitation.customer.has_user(request.user):
raise ValidationError(_('User already has role within this customer.'))
if settings.WALDUR_CORE['VALIDATE_INVITATION_EMAIL'] and invitation.email != request.user.email:
raise ValidationError(_('Invitation and user emails mismatch.'))
replace_email = bool(request.data.get('replace_email'))
invitation.accept(request.user, replace_email=replace_email)
return Response({'detail': _('Invitation has been successfully accepted.')},
status=status.HTTP_200_OK)
|
[
"def",
"accept",
"(",
"self",
",",
"request",
",",
"uuid",
"=",
"None",
")",
":",
"invitation",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"invitation",
".",
"state",
"!=",
"models",
".",
"Invitation",
".",
"State",
".",
"PENDING",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Only pending invitation can be accepted.'",
")",
")",
"elif",
"invitation",
".",
"civil_number",
"and",
"invitation",
".",
"civil_number",
"!=",
"request",
".",
"user",
".",
"civil_number",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'User has an invalid civil number.'",
")",
")",
"if",
"invitation",
".",
"project",
":",
"if",
"invitation",
".",
"project",
".",
"has_user",
"(",
"request",
".",
"user",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'User already has role within this project.'",
")",
")",
"elif",
"invitation",
".",
"customer",
".",
"has_user",
"(",
"request",
".",
"user",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'User already has role within this customer.'",
")",
")",
"if",
"settings",
".",
"WALDUR_CORE",
"[",
"'VALIDATE_INVITATION_EMAIL'",
"]",
"and",
"invitation",
".",
"email",
"!=",
"request",
".",
"user",
".",
"email",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Invitation and user emails mismatch.'",
")",
")",
"replace_email",
"=",
"bool",
"(",
"request",
".",
"data",
".",
"get",
"(",
"'replace_email'",
")",
")",
"invitation",
".",
"accept",
"(",
"request",
".",
"user",
",",
"replace_email",
"=",
"replace_email",
")",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"_",
"(",
"'Invitation has been successfully accepted.'",
")",
"}",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")"
] |
Accept invitation for current user.
To replace user's email with email from invitation - add parameter
'replace_email' to request POST body.
|
[
"Accept",
"invitation",
"for",
"current",
"user",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/users/views.py#L94-L119
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/handlers.py
|
scope_deletion
|
def scope_deletion(sender, instance, **kwargs):
""" Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
If scope is a unlinked resource - delete all resource price estimates and update ancestors.
In all other cases - update price estimate details.
"""
is_resource = isinstance(instance, structure_models.ResourceMixin)
if is_resource and getattr(instance, 'PERFORM_UNLINK', False):
_resource_unlink(resource=instance)
elif is_resource and not getattr(instance, 'PERFORM_UNLINK', False):
_resource_deletion(resource=instance)
elif isinstance(instance, structure_models.Customer):
_customer_deletion(customer=instance)
else:
for price_estimate in models.PriceEstimate.objects.filter(scope=instance):
price_estimate.init_details()
|
python
|
def scope_deletion(sender, instance, **kwargs):
""" Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
If scope is a unlinked resource - delete all resource price estimates and update ancestors.
In all other cases - update price estimate details.
"""
is_resource = isinstance(instance, structure_models.ResourceMixin)
if is_resource and getattr(instance, 'PERFORM_UNLINK', False):
_resource_unlink(resource=instance)
elif is_resource and not getattr(instance, 'PERFORM_UNLINK', False):
_resource_deletion(resource=instance)
elif isinstance(instance, structure_models.Customer):
_customer_deletion(customer=instance)
else:
for price_estimate in models.PriceEstimate.objects.filter(scope=instance):
price_estimate.init_details()
|
[
"def",
"scope_deletion",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"is_resource",
"=",
"isinstance",
"(",
"instance",
",",
"structure_models",
".",
"ResourceMixin",
")",
"if",
"is_resource",
"and",
"getattr",
"(",
"instance",
",",
"'PERFORM_UNLINK'",
",",
"False",
")",
":",
"_resource_unlink",
"(",
"resource",
"=",
"instance",
")",
"elif",
"is_resource",
"and",
"not",
"getattr",
"(",
"instance",
",",
"'PERFORM_UNLINK'",
",",
"False",
")",
":",
"_resource_deletion",
"(",
"resource",
"=",
"instance",
")",
"elif",
"isinstance",
"(",
"instance",
",",
"structure_models",
".",
"Customer",
")",
":",
"_customer_deletion",
"(",
"customer",
"=",
"instance",
")",
"else",
":",
"for",
"price_estimate",
"in",
"models",
".",
"PriceEstimate",
".",
"objects",
".",
"filter",
"(",
"scope",
"=",
"instance",
")",
":",
"price_estimate",
".",
"init_details",
"(",
")"
] |
Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
If scope is a unlinked resource - delete all resource price estimates and update ancestors.
In all other cases - update price estimate details.
|
[
"Run",
"different",
"actions",
"on",
"price",
"estimate",
"scope",
"deletion",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L16-L35
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/handlers.py
|
_resource_deletion
|
def _resource_deletion(resource):
""" Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources:
return
new_configuration = {}
price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration)
price_estimate.init_details()
|
python
|
def _resource_deletion(resource):
""" Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources:
return
new_configuration = {}
price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration)
price_estimate.init_details()
|
[
"def",
"_resource_deletion",
"(",
"resource",
")",
":",
"if",
"resource",
".",
"__class__",
"not",
"in",
"CostTrackingRegister",
".",
"registered_resources",
":",
"return",
"new_configuration",
"=",
"{",
"}",
"price_estimate",
"=",
"models",
".",
"PriceEstimate",
".",
"update_resource_estimate",
"(",
"resource",
",",
"new_configuration",
")",
"price_estimate",
".",
"init_details",
"(",
")"
] |
Recalculate consumption details and save resource details
|
[
"Recalculate",
"consumption",
"details",
"and",
"save",
"resource",
"details"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L52-L58
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/handlers.py
|
resource_update
|
def resource_update(sender, instance, created=False, **kwargs):
""" Update resource consumption details and price estimate if its configuration has changed.
Create estimates for previous months if resource was created not in current month.
"""
resource = instance
try:
new_configuration = CostTrackingRegister.get_configuration(resource)
except ResourceNotRegisteredError:
return
models.PriceEstimate.update_resource_estimate(
resource, new_configuration, raise_exception=not _is_in_celery_task())
# Try to create historical price estimates
if created:
_create_historical_estimates(resource, new_configuration)
|
python
|
def resource_update(sender, instance, created=False, **kwargs):
""" Update resource consumption details and price estimate if its configuration has changed.
Create estimates for previous months if resource was created not in current month.
"""
resource = instance
try:
new_configuration = CostTrackingRegister.get_configuration(resource)
except ResourceNotRegisteredError:
return
models.PriceEstimate.update_resource_estimate(
resource, new_configuration, raise_exception=not _is_in_celery_task())
# Try to create historical price estimates
if created:
_create_historical_estimates(resource, new_configuration)
|
[
"def",
"resource_update",
"(",
"sender",
",",
"instance",
",",
"created",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"instance",
"try",
":",
"new_configuration",
"=",
"CostTrackingRegister",
".",
"get_configuration",
"(",
"resource",
")",
"except",
"ResourceNotRegisteredError",
":",
"return",
"models",
".",
"PriceEstimate",
".",
"update_resource_estimate",
"(",
"resource",
",",
"new_configuration",
",",
"raise_exception",
"=",
"not",
"_is_in_celery_task",
"(",
")",
")",
"# Try to create historical price estimates",
"if",
"created",
":",
"_create_historical_estimates",
"(",
"resource",
",",
"new_configuration",
")"
] |
Update resource consumption details and price estimate if its configuration has changed.
Create estimates for previous months if resource was created not in current month.
|
[
"Update",
"resource",
"consumption",
"details",
"and",
"price",
"estimate",
"if",
"its",
"configuration",
"has",
"changed",
".",
"Create",
"estimates",
"for",
"previous",
"months",
"if",
"resource",
"was",
"created",
"not",
"in",
"current",
"month",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L66-L79
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/handlers.py
|
resource_quota_update
|
def resource_quota_update(sender, instance, **kwargs):
""" Update resource consumption details and price estimate if its configuration has changed """
quota = instance
resource = quota.scope
try:
new_configuration = CostTrackingRegister.get_configuration(resource)
except ResourceNotRegisteredError:
return
models.PriceEstimate.update_resource_estimate(
resource, new_configuration, raise_exception=not _is_in_celery_task())
|
python
|
def resource_quota_update(sender, instance, **kwargs):
""" Update resource consumption details and price estimate if its configuration has changed """
quota = instance
resource = quota.scope
try:
new_configuration = CostTrackingRegister.get_configuration(resource)
except ResourceNotRegisteredError:
return
models.PriceEstimate.update_resource_estimate(
resource, new_configuration, raise_exception=not _is_in_celery_task())
|
[
"def",
"resource_quota_update",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"quota",
"=",
"instance",
"resource",
"=",
"quota",
".",
"scope",
"try",
":",
"new_configuration",
"=",
"CostTrackingRegister",
".",
"get_configuration",
"(",
"resource",
")",
"except",
"ResourceNotRegisteredError",
":",
"return",
"models",
".",
"PriceEstimate",
".",
"update_resource_estimate",
"(",
"resource",
",",
"new_configuration",
",",
"raise_exception",
"=",
"not",
"_is_in_celery_task",
"(",
")",
")"
] |
Update resource consumption details and price estimate if its configuration has changed
|
[
"Update",
"resource",
"consumption",
"details",
"and",
"price",
"estimate",
"if",
"its",
"configuration",
"has",
"changed"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L82-L91
|
train
|
opennode/waldur-core
|
waldur_core/cost_tracking/handlers.py
|
_create_historical_estimates
|
def _create_historical_estimates(resource, configuration):
""" Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import.
"""
today = timezone.now()
month_start = core_utils.month_start(today)
while month_start > resource.created:
month_start -= relativedelta(months=1)
models.PriceEstimate.create_historical(resource, configuration, max(month_start, resource.created))
|
python
|
def _create_historical_estimates(resource, configuration):
""" Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import.
"""
today = timezone.now()
month_start = core_utils.month_start(today)
while month_start > resource.created:
month_start -= relativedelta(months=1)
models.PriceEstimate.create_historical(resource, configuration, max(month_start, resource.created))
|
[
"def",
"_create_historical_estimates",
"(",
"resource",
",",
"configuration",
")",
":",
"today",
"=",
"timezone",
".",
"now",
"(",
")",
"month_start",
"=",
"core_utils",
".",
"month_start",
"(",
"today",
")",
"while",
"month_start",
">",
"resource",
".",
"created",
":",
"month_start",
"-=",
"relativedelta",
"(",
"months",
"=",
"1",
")",
"models",
".",
"PriceEstimate",
".",
"create_historical",
"(",
"resource",
",",
"configuration",
",",
"max",
"(",
"month_start",
",",
"resource",
".",
"created",
")",
")"
] |
Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import.
|
[
"Create",
"consumption",
"details",
"and",
"price",
"estimates",
"for",
"past",
"months",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L94-L103
|
train
|
deathbeds/importnb
|
src/importnb/ipython_extension.py
|
IPYTHON_MAIN
|
def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__
)
|
python
|
def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__
)
|
[
"def",
"IPYTHON_MAIN",
"(",
")",
":",
"import",
"pkg_resources",
"runner_frame",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")",
")",
"[",
"-",
"2",
"]",
"return",
"(",
"getattr",
"(",
"runner_frame",
",",
"\"function\"",
",",
"None",
")",
"==",
"pkg_resources",
".",
"load_entry_point",
"(",
"\"ipython\"",
",",
"\"console_scripts\"",
",",
"\"ipython\"",
")",
".",
"__name__",
")"
] |
Decide if the Ipython command line is running code.
|
[
"Decide",
"if",
"the",
"Ipython",
"command",
"line",
"is",
"running",
"code",
"."
] |
ec870d1f8ab99fd5b363267f89787a3e442a779f
|
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/ipython_extension.py#L85-L93
|
train
|
nuagenetworks/bambou
|
bambou/nurest_modelcontroller.py
|
NURESTModelController.register_model
|
def register_model(cls, model):
"""
Register a model class according to its remote name
Args:
model: the model to register
"""
rest_name = model.rest_name
resource_name = model.resource_name
if rest_name not in cls._model_rest_name_registry:
cls._model_rest_name_registry[rest_name] = [model]
cls._model_resource_name_registry[resource_name] = [model]
elif model not in cls._model_rest_name_registry[rest_name]:
cls._model_rest_name_registry[rest_name].append(model)
cls._model_resource_name_registry[resource_name].append(model)
|
python
|
def register_model(cls, model):
"""
Register a model class according to its remote name
Args:
model: the model to register
"""
rest_name = model.rest_name
resource_name = model.resource_name
if rest_name not in cls._model_rest_name_registry:
cls._model_rest_name_registry[rest_name] = [model]
cls._model_resource_name_registry[resource_name] = [model]
elif model not in cls._model_rest_name_registry[rest_name]:
cls._model_rest_name_registry[rest_name].append(model)
cls._model_resource_name_registry[resource_name].append(model)
|
[
"def",
"register_model",
"(",
"cls",
",",
"model",
")",
":",
"rest_name",
"=",
"model",
".",
"rest_name",
"resource_name",
"=",
"model",
".",
"resource_name",
"if",
"rest_name",
"not",
"in",
"cls",
".",
"_model_rest_name_registry",
":",
"cls",
".",
"_model_rest_name_registry",
"[",
"rest_name",
"]",
"=",
"[",
"model",
"]",
"cls",
".",
"_model_resource_name_registry",
"[",
"resource_name",
"]",
"=",
"[",
"model",
"]",
"elif",
"model",
"not",
"in",
"cls",
".",
"_model_rest_name_registry",
"[",
"rest_name",
"]",
":",
"cls",
".",
"_model_rest_name_registry",
"[",
"rest_name",
"]",
".",
"append",
"(",
"model",
")",
"cls",
".",
"_model_resource_name_registry",
"[",
"resource_name",
"]",
".",
"append",
"(",
"model",
")"
] |
Register a model class according to its remote name
Args:
model: the model to register
|
[
"Register",
"a",
"model",
"class",
"according",
"to",
"its",
"remote",
"name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L37-L54
|
train
|
nuagenetworks/bambou
|
bambou/nurest_modelcontroller.py
|
NURESTModelController.get_first_model_with_rest_name
|
def get_first_model_with_rest_name(cls, rest_name):
""" Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
"""
models = cls.get_models_with_rest_name(rest_name)
if len(models) > 0:
return models[0]
return None
|
python
|
def get_first_model_with_rest_name(cls, rest_name):
""" Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
"""
models = cls.get_models_with_rest_name(rest_name)
if len(models) > 0:
return models[0]
return None
|
[
"def",
"get_first_model_with_rest_name",
"(",
"cls",
",",
"rest_name",
")",
":",
"models",
"=",
"cls",
".",
"get_models_with_rest_name",
"(",
"rest_name",
")",
"if",
"len",
"(",
"models",
")",
">",
"0",
":",
"return",
"models",
"[",
"0",
"]",
"return",
"None"
] |
Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
|
[
"Get",
"the",
"first",
"model",
"corresponding",
"to",
"a",
"rest_name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L87-L99
|
train
|
nuagenetworks/bambou
|
bambou/nurest_modelcontroller.py
|
NURESTModelController.get_first_model_with_resource_name
|
def get_first_model_with_resource_name(cls, resource_name):
""" Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
"""
models = cls.get_models_with_resource_name(resource_name)
if len(models) > 0:
return models[0]
return None
|
python
|
def get_first_model_with_resource_name(cls, resource_name):
""" Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
"""
models = cls.get_models_with_resource_name(resource_name)
if len(models) > 0:
return models[0]
return None
|
[
"def",
"get_first_model_with_resource_name",
"(",
"cls",
",",
"resource_name",
")",
":",
"models",
"=",
"cls",
".",
"get_models_with_resource_name",
"(",
"resource_name",
")",
"if",
"len",
"(",
"models",
")",
">",
"0",
":",
"return",
"models",
"[",
"0",
"]",
"return",
"None"
] |
Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
|
[
"Get",
"the",
"first",
"model",
"corresponding",
"to",
"a",
"resource_name"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L121-L133
|
train
|
zeromake/aiosqlite3
|
aiosqlite3/sqlite_thread.py
|
SqliteThread.run
|
def run(self):
"""
执行任务
"""
while not self._stoped:
self._tx_event.wait()
self._tx_event.clear()
try:
func = self._tx_queue.get_nowait()
if isinstance(func, str):
self._stoped = True
self._rx_queue.put('closed')
self.notice()
break
except Empty:
# pragma: no cover
continue
try:
result = func()
self._rx_queue.put(result)
except Exception as e:
self._rx_queue.put(e)
self.notice()
else:
# pragma: no cover
pass
|
python
|
def run(self):
"""
执行任务
"""
while not self._stoped:
self._tx_event.wait()
self._tx_event.clear()
try:
func = self._tx_queue.get_nowait()
if isinstance(func, str):
self._stoped = True
self._rx_queue.put('closed')
self.notice()
break
except Empty:
# pragma: no cover
continue
try:
result = func()
self._rx_queue.put(result)
except Exception as e:
self._rx_queue.put(e)
self.notice()
else:
# pragma: no cover
pass
|
[
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_stoped",
":",
"self",
".",
"_tx_event",
".",
"wait",
"(",
")",
"self",
".",
"_tx_event",
".",
"clear",
"(",
")",
"try",
":",
"func",
"=",
"self",
".",
"_tx_queue",
".",
"get_nowait",
"(",
")",
"if",
"isinstance",
"(",
"func",
",",
"str",
")",
":",
"self",
".",
"_stoped",
"=",
"True",
"self",
".",
"_rx_queue",
".",
"put",
"(",
"'closed'",
")",
"self",
".",
"notice",
"(",
")",
"break",
"except",
"Empty",
":",
"# pragma: no cover",
"continue",
"try",
":",
"result",
"=",
"func",
"(",
")",
"self",
".",
"_rx_queue",
".",
"put",
"(",
"result",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_rx_queue",
".",
"put",
"(",
"e",
")",
"self",
".",
"notice",
"(",
")",
"else",
":",
"# pragma: no cover",
"pass"
] |
执行任务
|
[
"执行任务"
] |
1a74a062507e2df8f833a70885e69dca0ab3e7e7
|
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sqlite_thread.py#L22-L47
|
train
|
OpenDataScienceLab/skdata
|
skdata/widgets.py
|
SkDataWidget.build_layout
|
def build_layout(self, dset_id: str):
"""
:param dset_id:
:return:
"""
all_fields = list(self.get_data(dset_id=dset_id).keys())
try:
field_reference = self.skd[dset_id].attrs('target')
except:
field_reference = all_fields[0]
fields_comparison = [all_fields[1]]
# chart type widget
self.register_widget(
chart_type=widgets.RadioButtons(
options=['individual', 'grouped'],
value='individual',
description='Chart Type:'
)
)
# bins widget
self.register_widget(
bins=IntSlider(
description='Bins:',
min=2, max=10, value=2,
continuous_update=False
)
)
# fields comparison widget
self.register_widget(
xs=widgets.SelectMultiple(
description='Xs:',
options=[f for f in all_fields if not f == field_reference],
value=fields_comparison
)
)
# field reference widget
self.register_widget(
y=widgets.Dropdown(
description='Y:',
options=all_fields,
value=field_reference
)
)
# used to internal flow control
y_changed = [False]
self.register_widget(
box_filter_panel=widgets.VBox([
self._('y'), self._('xs'), self._('bins')
])
)
# layout widgets
self.register_widget(
table=widgets.HTML(),
chart=widgets.HTML()
)
self.register_widget(vbox_chart=widgets.VBox([
self._('chart_type'), self._('chart')
]))
self.register_widget(
tab=widgets.Tab(
children=[
self._('box_filter_panel'),
self._('table'),
self._('vbox_chart')
]
)
)
self.register_widget(dashboard=widgets.HBox([self._('tab')]))
# observe hooks
def w_y_change(change: dict):
"""
When y field was changed xs field should be updated and data table
and chart should be displayed/updated.
:param change:
:return:
"""
# remove reference field from the comparison field list
_xs = [
f for f in all_fields
if not f == change['new']
]
y_changed[0] = True # flow control variable
_xs_value = list(self._('xs').value)
if change['new'] in self._('xs').value:
_xs_value.pop(_xs_value.index(change['new']))
if not _xs_value:
_xs_value = [_xs[0]]
self._('xs').options = _xs
self._('xs').value = _xs_value
self._display_result(y=change['new'], dset_id=dset_id)
y_changed[0] = False # flow control variable
# widgets registration
# change tab settings
self._('tab').set_title(0, 'Filter')
self._('tab').set_title(1, 'Data')
self._('tab').set_title(2, 'Chart')
# data panel
self._('table').value = '...'
# chart panel
self._('chart').value = '...'
# create observe callbacks
self._('bins').observe(
lambda change: (
self._display_result(bins=change['new'], dset_id=dset_id)
), 'value'
)
self._('y').observe(w_y_change, 'value')
# execute display result if 'y' was not changing.
self._('xs').observe(
lambda change: (
self._display_result(xs=change['new'], dset_id=dset_id)
if not y_changed[0] else None
), 'value'
)
self._('chart_type').observe(
lambda change: (
self._display_result(chart_type=change['new'], dset_id=dset_id)
), 'value'
)
|
python
|
def build_layout(self, dset_id: str):
"""
:param dset_id:
:return:
"""
all_fields = list(self.get_data(dset_id=dset_id).keys())
try:
field_reference = self.skd[dset_id].attrs('target')
except:
field_reference = all_fields[0]
fields_comparison = [all_fields[1]]
# chart type widget
self.register_widget(
chart_type=widgets.RadioButtons(
options=['individual', 'grouped'],
value='individual',
description='Chart Type:'
)
)
# bins widget
self.register_widget(
bins=IntSlider(
description='Bins:',
min=2, max=10, value=2,
continuous_update=False
)
)
# fields comparison widget
self.register_widget(
xs=widgets.SelectMultiple(
description='Xs:',
options=[f for f in all_fields if not f == field_reference],
value=fields_comparison
)
)
# field reference widget
self.register_widget(
y=widgets.Dropdown(
description='Y:',
options=all_fields,
value=field_reference
)
)
# used to internal flow control
y_changed = [False]
self.register_widget(
box_filter_panel=widgets.VBox([
self._('y'), self._('xs'), self._('bins')
])
)
# layout widgets
self.register_widget(
table=widgets.HTML(),
chart=widgets.HTML()
)
self.register_widget(vbox_chart=widgets.VBox([
self._('chart_type'), self._('chart')
]))
self.register_widget(
tab=widgets.Tab(
children=[
self._('box_filter_panel'),
self._('table'),
self._('vbox_chart')
]
)
)
self.register_widget(dashboard=widgets.HBox([self._('tab')]))
# observe hooks
def w_y_change(change: dict):
"""
When y field was changed xs field should be updated and data table
and chart should be displayed/updated.
:param change:
:return:
"""
# remove reference field from the comparison field list
_xs = [
f for f in all_fields
if not f == change['new']
]
y_changed[0] = True # flow control variable
_xs_value = list(self._('xs').value)
if change['new'] in self._('xs').value:
_xs_value.pop(_xs_value.index(change['new']))
if not _xs_value:
_xs_value = [_xs[0]]
self._('xs').options = _xs
self._('xs').value = _xs_value
self._display_result(y=change['new'], dset_id=dset_id)
y_changed[0] = False # flow control variable
# widgets registration
# change tab settings
self._('tab').set_title(0, 'Filter')
self._('tab').set_title(1, 'Data')
self._('tab').set_title(2, 'Chart')
# data panel
self._('table').value = '...'
# chart panel
self._('chart').value = '...'
# create observe callbacks
self._('bins').observe(
lambda change: (
self._display_result(bins=change['new'], dset_id=dset_id)
), 'value'
)
self._('y').observe(w_y_change, 'value')
# execute display result if 'y' was not changing.
self._('xs').observe(
lambda change: (
self._display_result(xs=change['new'], dset_id=dset_id)
if not y_changed[0] else None
), 'value'
)
self._('chart_type').observe(
lambda change: (
self._display_result(chart_type=change['new'], dset_id=dset_id)
), 'value'
)
|
[
"def",
"build_layout",
"(",
"self",
",",
"dset_id",
":",
"str",
")",
":",
"all_fields",
"=",
"list",
"(",
"self",
".",
"get_data",
"(",
"dset_id",
"=",
"dset_id",
")",
".",
"keys",
"(",
")",
")",
"try",
":",
"field_reference",
"=",
"self",
".",
"skd",
"[",
"dset_id",
"]",
".",
"attrs",
"(",
"'target'",
")",
"except",
":",
"field_reference",
"=",
"all_fields",
"[",
"0",
"]",
"fields_comparison",
"=",
"[",
"all_fields",
"[",
"1",
"]",
"]",
"# chart type widget",
"self",
".",
"register_widget",
"(",
"chart_type",
"=",
"widgets",
".",
"RadioButtons",
"(",
"options",
"=",
"[",
"'individual'",
",",
"'grouped'",
"]",
",",
"value",
"=",
"'individual'",
",",
"description",
"=",
"'Chart Type:'",
")",
")",
"# bins widget",
"self",
".",
"register_widget",
"(",
"bins",
"=",
"IntSlider",
"(",
"description",
"=",
"'Bins:'",
",",
"min",
"=",
"2",
",",
"max",
"=",
"10",
",",
"value",
"=",
"2",
",",
"continuous_update",
"=",
"False",
")",
")",
"# fields comparison widget",
"self",
".",
"register_widget",
"(",
"xs",
"=",
"widgets",
".",
"SelectMultiple",
"(",
"description",
"=",
"'Xs:'",
",",
"options",
"=",
"[",
"f",
"for",
"f",
"in",
"all_fields",
"if",
"not",
"f",
"==",
"field_reference",
"]",
",",
"value",
"=",
"fields_comparison",
")",
")",
"# field reference widget",
"self",
".",
"register_widget",
"(",
"y",
"=",
"widgets",
".",
"Dropdown",
"(",
"description",
"=",
"'Y:'",
",",
"options",
"=",
"all_fields",
",",
"value",
"=",
"field_reference",
")",
")",
"# used to internal flow control",
"y_changed",
"=",
"[",
"False",
"]",
"self",
".",
"register_widget",
"(",
"box_filter_panel",
"=",
"widgets",
".",
"VBox",
"(",
"[",
"self",
".",
"_",
"(",
"'y'",
")",
",",
"self",
".",
"_",
"(",
"'xs'",
")",
",",
"self",
".",
"_",
"(",
"'bins'",
")",
"]",
")",
")",
"# layout widgets",
"self",
".",
"register_widget",
"(",
"table",
"=",
"widgets",
".",
"HTML",
"(",
")",
",",
"chart",
"=",
"widgets",
".",
"HTML",
"(",
")",
")",
"self",
".",
"register_widget",
"(",
"vbox_chart",
"=",
"widgets",
".",
"VBox",
"(",
"[",
"self",
".",
"_",
"(",
"'chart_type'",
")",
",",
"self",
".",
"_",
"(",
"'chart'",
")",
"]",
")",
")",
"self",
".",
"register_widget",
"(",
"tab",
"=",
"widgets",
".",
"Tab",
"(",
"children",
"=",
"[",
"self",
".",
"_",
"(",
"'box_filter_panel'",
")",
",",
"self",
".",
"_",
"(",
"'table'",
")",
",",
"self",
".",
"_",
"(",
"'vbox_chart'",
")",
"]",
")",
")",
"self",
".",
"register_widget",
"(",
"dashboard",
"=",
"widgets",
".",
"HBox",
"(",
"[",
"self",
".",
"_",
"(",
"'tab'",
")",
"]",
")",
")",
"# observe hooks",
"def",
"w_y_change",
"(",
"change",
":",
"dict",
")",
":",
"\"\"\"\n When y field was changed xs field should be updated and data table\n and chart should be displayed/updated.\n\n :param change:\n :return:\n \"\"\"",
"# remove reference field from the comparison field list",
"_xs",
"=",
"[",
"f",
"for",
"f",
"in",
"all_fields",
"if",
"not",
"f",
"==",
"change",
"[",
"'new'",
"]",
"]",
"y_changed",
"[",
"0",
"]",
"=",
"True",
"# flow control variable",
"_xs_value",
"=",
"list",
"(",
"self",
".",
"_",
"(",
"'xs'",
")",
".",
"value",
")",
"if",
"change",
"[",
"'new'",
"]",
"in",
"self",
".",
"_",
"(",
"'xs'",
")",
".",
"value",
":",
"_xs_value",
".",
"pop",
"(",
"_xs_value",
".",
"index",
"(",
"change",
"[",
"'new'",
"]",
")",
")",
"if",
"not",
"_xs_value",
":",
"_xs_value",
"=",
"[",
"_xs",
"[",
"0",
"]",
"]",
"self",
".",
"_",
"(",
"'xs'",
")",
".",
"options",
"=",
"_xs",
"self",
".",
"_",
"(",
"'xs'",
")",
".",
"value",
"=",
"_xs_value",
"self",
".",
"_display_result",
"(",
"y",
"=",
"change",
"[",
"'new'",
"]",
",",
"dset_id",
"=",
"dset_id",
")",
"y_changed",
"[",
"0",
"]",
"=",
"False",
"# flow control variable",
"# widgets registration",
"# change tab settings",
"self",
".",
"_",
"(",
"'tab'",
")",
".",
"set_title",
"(",
"0",
",",
"'Filter'",
")",
"self",
".",
"_",
"(",
"'tab'",
")",
".",
"set_title",
"(",
"1",
",",
"'Data'",
")",
"self",
".",
"_",
"(",
"'tab'",
")",
".",
"set_title",
"(",
"2",
",",
"'Chart'",
")",
"# data panel",
"self",
".",
"_",
"(",
"'table'",
")",
".",
"value",
"=",
"'...'",
"# chart panel",
"self",
".",
"_",
"(",
"'chart'",
")",
".",
"value",
"=",
"'...'",
"# create observe callbacks",
"self",
".",
"_",
"(",
"'bins'",
")",
".",
"observe",
"(",
"lambda",
"change",
":",
"(",
"self",
".",
"_display_result",
"(",
"bins",
"=",
"change",
"[",
"'new'",
"]",
",",
"dset_id",
"=",
"dset_id",
")",
")",
",",
"'value'",
")",
"self",
".",
"_",
"(",
"'y'",
")",
".",
"observe",
"(",
"w_y_change",
",",
"'value'",
")",
"# execute display result if 'y' was not changing.",
"self",
".",
"_",
"(",
"'xs'",
")",
".",
"observe",
"(",
"lambda",
"change",
":",
"(",
"self",
".",
"_display_result",
"(",
"xs",
"=",
"change",
"[",
"'new'",
"]",
",",
"dset_id",
"=",
"dset_id",
")",
"if",
"not",
"y_changed",
"[",
"0",
"]",
"else",
"None",
")",
",",
"'value'",
")",
"self",
".",
"_",
"(",
"'chart_type'",
")",
".",
"observe",
"(",
"lambda",
"change",
":",
"(",
"self",
".",
"_display_result",
"(",
"chart_type",
"=",
"change",
"[",
"'new'",
"]",
",",
"dset_id",
"=",
"dset_id",
")",
")",
",",
"'value'",
")"
] |
:param dset_id:
:return:
|
[
":",
"param",
"dset_id",
":",
":",
"return",
":"
] |
34f06845a944ff4f048b55c7babdd8420f71a6b9
|
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/widgets.py#L108-L249
|
train
|
OpenDataScienceLab/skdata
|
skdata/widgets.py
|
SkDataWidget.display
|
def display(self, dset_id: str):
"""
:param dset_id:
:return:
"""
# update result
self.skd[dset_id].compute()
# build layout
self.build_layout(dset_id=dset_id)
# display widgets
display(self._('dashboard'))
# display data table and chart
self._display_result(dset_id=dset_id)
|
python
|
def display(self, dset_id: str):
"""
:param dset_id:
:return:
"""
# update result
self.skd[dset_id].compute()
# build layout
self.build_layout(dset_id=dset_id)
# display widgets
display(self._('dashboard'))
# display data table and chart
self._display_result(dset_id=dset_id)
|
[
"def",
"display",
"(",
"self",
",",
"dset_id",
":",
"str",
")",
":",
"# update result",
"self",
".",
"skd",
"[",
"dset_id",
"]",
".",
"compute",
"(",
")",
"# build layout",
"self",
".",
"build_layout",
"(",
"dset_id",
"=",
"dset_id",
")",
"# display widgets",
"display",
"(",
"self",
".",
"_",
"(",
"'dashboard'",
")",
")",
"# display data table and chart",
"self",
".",
"_display_result",
"(",
"dset_id",
"=",
"dset_id",
")"
] |
:param dset_id:
:return:
|
[
":",
"param",
"dset_id",
":",
":",
"return",
":"
] |
34f06845a944ff4f048b55c7babdd8420f71a6b9
|
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/widgets.py#L251-L264
|
train
|
deathbeds/importnb
|
src/importnb/finder.py
|
FuzzyFinder.find_spec
|
def find_spec(self, fullname, target=None):
"""Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
"""
spec = super().find_spec(fullname, target=target)
if spec is None:
original = fullname
if "." in fullname:
original, fullname = fullname.rsplit(".", 1)
else:
original, fullname = "", original
if "_" in fullname:
files = fuzzy_file_search(self.path, fullname)
if files:
file = Path(sorted(files)[0])
spec = super().find_spec(
(original + "." + file.stem.split(".", 1)[0]).lstrip("."), target=target
)
fullname = (original + "." + fullname).lstrip(".")
if spec and fullname != spec.name:
spec = FuzzySpec(
spec.name,
spec.loader,
origin=spec.origin,
loader_state=spec.loader_state,
alias=fullname,
is_package=bool(spec.submodule_search_locations),
)
return spec
|
python
|
def find_spec(self, fullname, target=None):
"""Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
"""
spec = super().find_spec(fullname, target=target)
if spec is None:
original = fullname
if "." in fullname:
original, fullname = fullname.rsplit(".", 1)
else:
original, fullname = "", original
if "_" in fullname:
files = fuzzy_file_search(self.path, fullname)
if files:
file = Path(sorted(files)[0])
spec = super().find_spec(
(original + "." + file.stem.split(".", 1)[0]).lstrip("."), target=target
)
fullname = (original + "." + fullname).lstrip(".")
if spec and fullname != spec.name:
spec = FuzzySpec(
spec.name,
spec.loader,
origin=spec.origin,
loader_state=spec.loader_state,
alias=fullname,
is_package=bool(spec.submodule_search_locations),
)
return spec
|
[
"def",
"find_spec",
"(",
"self",
",",
"fullname",
",",
"target",
"=",
"None",
")",
":",
"spec",
"=",
"super",
"(",
")",
".",
"find_spec",
"(",
"fullname",
",",
"target",
"=",
"target",
")",
"if",
"spec",
"is",
"None",
":",
"original",
"=",
"fullname",
"if",
"\".\"",
"in",
"fullname",
":",
"original",
",",
"fullname",
"=",
"fullname",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"original",
",",
"fullname",
"=",
"\"\"",
",",
"original",
"if",
"\"_\"",
"in",
"fullname",
":",
"files",
"=",
"fuzzy_file_search",
"(",
"self",
".",
"path",
",",
"fullname",
")",
"if",
"files",
":",
"file",
"=",
"Path",
"(",
"sorted",
"(",
"files",
")",
"[",
"0",
"]",
")",
"spec",
"=",
"super",
"(",
")",
".",
"find_spec",
"(",
"(",
"original",
"+",
"\".\"",
"+",
"file",
".",
"stem",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
")",
".",
"lstrip",
"(",
"\".\"",
")",
",",
"target",
"=",
"target",
")",
"fullname",
"=",
"(",
"original",
"+",
"\".\"",
"+",
"fullname",
")",
".",
"lstrip",
"(",
"\".\"",
")",
"if",
"spec",
"and",
"fullname",
"!=",
"spec",
".",
"name",
":",
"spec",
"=",
"FuzzySpec",
"(",
"spec",
".",
"name",
",",
"spec",
".",
"loader",
",",
"origin",
"=",
"spec",
".",
"origin",
",",
"loader_state",
"=",
"spec",
".",
"loader_state",
",",
"alias",
"=",
"fullname",
",",
"is_package",
"=",
"bool",
"(",
"spec",
".",
"submodule_search_locations",
")",
",",
")",
"return",
"spec"
] |
Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
|
[
"Try",
"to",
"finder",
"the",
"spec",
"and",
"if",
"it",
"cannot",
"be",
"found",
"use",
"the",
"underscore",
"starring",
"syntax",
"to",
"identify",
"potential",
"matches",
"."
] |
ec870d1f8ab99fd5b363267f89787a3e442a779f
|
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/finder.py#L58-L89
|
train
|
nuagenetworks/bambou
|
bambou/nurest_root_object.py
|
NURESTRootObject.get_resource_url
|
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
return "%s/%s" % (url, name)
|
python
|
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
return "%s/%s" % (url, name)
|
[
"def",
"get_resource_url",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"__class__",
".",
"resource_name",
"url",
"=",
"self",
".",
"__class__",
".",
"rest_base_url",
"(",
")",
"return",
"\"%s/%s\"",
"%",
"(",
"url",
",",
"name",
")"
] |
Get resource complete url
|
[
"Get",
"resource",
"complete",
"url"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L118-L124
|
train
|
nuagenetworks/bambou
|
bambou/nurest_root_object.py
|
NURESTRootObject.save
|
def save(self, async=False, callback=None, encrypted=True):
""" Updates the user and perform the callback method """
if self._new_password and encrypted:
self.password = Sha1.encrypt(self._new_password)
controller = NURESTSession.get_current_session().login_controller
controller.password = self._new_password
controller.api_key = None
data = json.dumps(self.to_dict())
request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data)
if async:
return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_save(connection)
|
python
|
def save(self, async=False, callback=None, encrypted=True):
""" Updates the user and perform the callback method """
if self._new_password and encrypted:
self.password = Sha1.encrypt(self._new_password)
controller = NURESTSession.get_current_session().login_controller
controller.password = self._new_password
controller.api_key = None
data = json.dumps(self.to_dict())
request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data)
if async:
return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_save(connection)
|
[
"def",
"save",
"(",
"self",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"encrypted",
"=",
"True",
")",
":",
"if",
"self",
".",
"_new_password",
"and",
"encrypted",
":",
"self",
".",
"password",
"=",
"Sha1",
".",
"encrypt",
"(",
"self",
".",
"_new_password",
")",
"controller",
"=",
"NURESTSession",
".",
"get_current_session",
"(",
")",
".",
"login_controller",
"controller",
".",
"password",
"=",
"self",
".",
"_new_password",
"controller",
".",
"api_key",
"=",
"None",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
")",
")",
"request",
"=",
"NURESTRequest",
"(",
"method",
"=",
"HTTP_METHOD_PUT",
",",
"url",
"=",
"self",
".",
"get_resource_url",
"(",
")",
",",
"data",
"=",
"data",
")",
"if",
"async",
":",
"return",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"async",
"=",
"async",
",",
"local_callback",
"=",
"self",
".",
"_did_save",
",",
"remote_callback",
"=",
"callback",
")",
"else",
":",
"connection",
"=",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
")",
"return",
"self",
".",
"_did_save",
"(",
"connection",
")"
] |
Updates the user and perform the callback method
|
[
"Updates",
"the",
"user",
"and",
"perform",
"the",
"callback",
"method"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L131-L148
|
train
|
nuagenetworks/bambou
|
bambou/nurest_root_object.py
|
NURESTRootObject._did_save
|
def _did_save(self, connection):
""" Launched when save has been successfully executed """
self._new_password = None
controller = NURESTSession.get_current_session().login_controller
controller.password = None
controller.api_key = self.api_key
if connection.async:
callback = connection.callbacks['remote']
if connection.user_info:
callback(connection.user_info, connection)
else:
callback(self, connection)
else:
return (self, connection)
|
python
|
def _did_save(self, connection):
""" Launched when save has been successfully executed """
self._new_password = None
controller = NURESTSession.get_current_session().login_controller
controller.password = None
controller.api_key = self.api_key
if connection.async:
callback = connection.callbacks['remote']
if connection.user_info:
callback(connection.user_info, connection)
else:
callback(self, connection)
else:
return (self, connection)
|
[
"def",
"_did_save",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"_new_password",
"=",
"None",
"controller",
"=",
"NURESTSession",
".",
"get_current_session",
"(",
")",
".",
"login_controller",
"controller",
".",
"password",
"=",
"None",
"controller",
".",
"api_key",
"=",
"self",
".",
"api_key",
"if",
"connection",
".",
"async",
":",
"callback",
"=",
"connection",
".",
"callbacks",
"[",
"'remote'",
"]",
"if",
"connection",
".",
"user_info",
":",
"callback",
"(",
"connection",
".",
"user_info",
",",
"connection",
")",
"else",
":",
"callback",
"(",
"self",
",",
"connection",
")",
"else",
":",
"return",
"(",
"self",
",",
"connection",
")"
] |
Launched when save has been successfully executed
|
[
"Launched",
"when",
"save",
"has",
"been",
"successfully",
"executed"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L150-L167
|
train
|
nuagenetworks/bambou
|
bambou/nurest_root_object.py
|
NURESTRootObject.fetch
|
def fetch(self, async=False, callback=None):
""" Fetch all information about the current object
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Returns:
tuple: (current_fetcher, callee_parent, fetched_bjects, connection)
Example:
>>> entity = NUEntity(id="xxx-xxx-xxx-xxx")
>>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx"
>>> print entity.name
"My Entity"
"""
request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url())
if async:
return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_retrieve(connection)
|
python
|
def fetch(self, async=False, callback=None):
""" Fetch all information about the current object
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Returns:
tuple: (current_fetcher, callee_parent, fetched_bjects, connection)
Example:
>>> entity = NUEntity(id="xxx-xxx-xxx-xxx")
>>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx"
>>> print entity.name
"My Entity"
"""
request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url())
if async:
return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_retrieve(connection)
|
[
"def",
"fetch",
"(",
"self",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
")",
":",
"request",
"=",
"NURESTRequest",
"(",
"method",
"=",
"HTTP_METHOD_GET",
",",
"url",
"=",
"self",
".",
"get_resource_url",
"(",
")",
")",
"if",
"async",
":",
"return",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
",",
"async",
"=",
"async",
",",
"local_callback",
"=",
"self",
".",
"_did_fetch",
",",
"remote_callback",
"=",
"callback",
")",
"else",
":",
"connection",
"=",
"self",
".",
"send_request",
"(",
"request",
"=",
"request",
")",
"return",
"self",
".",
"_did_retrieve",
"(",
"connection",
")"
] |
Fetch all information about the current object
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Returns:
tuple: (current_fetcher, callee_parent, fetched_bjects, connection)
Example:
>>> entity = NUEntity(id="xxx-xxx-xxx-xxx")
>>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx"
>>> print entity.name
"My Entity"
|
[
"Fetch",
"all",
"information",
"about",
"the",
"current",
"object"
] |
d334fea23e384d3df8e552fe1849ad707941c666
|
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L169-L191
|
train
|
noumar/iso639
|
iso639/iso639.py
|
_fabtabular
|
def _fabtabular():
"""
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
"""
import csv
import sys
from pkg_resources import resource_filename
data = resource_filename(__package__, 'iso-639-3.tab')
inverted = resource_filename(__package__, 'iso-639-3_Name_Index.tab')
macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab')
part5 = resource_filename(__package__, 'iso639-5.tsv')
part2 = resource_filename(__package__, 'iso639-2.tsv')
part1 = resource_filename(__package__, 'iso639-1.tsv')
# if sys.version_info[0] == 2:
# from urllib2 import urlopen
# from contextlib import closing
# data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab'))
# inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab'))
# else:
# from urllib.request import urlopen
# import io
# data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode())
# inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode())
if sys.version_info[0] == 3:
from functools import partial
global open
open = partial(open, encoding='utf-8')
data_fo = open(data)
inverted_fo = open(inverted)
macro_fo = open(macro)
part5_fo = open(part5)
part2_fo = open(part2)
part1_fo = open(part1)
with data_fo as u:
with inverted_fo as i:
with macro_fo as m:
with part5_fo as p5:
with part2_fo as p2:
with part1_fo as p1:
return (list(csv.reader(u, delimiter='\t'))[1:],
list(csv.reader(i, delimiter='\t'))[1:],
list(csv.reader(m, delimiter='\t'))[1:],
list(csv.reader(p5, delimiter='\t'))[1:],
list(csv.reader(p2, delimiter='\t'))[1:],
list(csv.reader(p1, delimiter='\t'))[1:])
|
python
|
def _fabtabular():
"""
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
"""
import csv
import sys
from pkg_resources import resource_filename
data = resource_filename(__package__, 'iso-639-3.tab')
inverted = resource_filename(__package__, 'iso-639-3_Name_Index.tab')
macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab')
part5 = resource_filename(__package__, 'iso639-5.tsv')
part2 = resource_filename(__package__, 'iso639-2.tsv')
part1 = resource_filename(__package__, 'iso639-1.tsv')
# if sys.version_info[0] == 2:
# from urllib2 import urlopen
# from contextlib import closing
# data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab'))
# inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab'))
# else:
# from urllib.request import urlopen
# import io
# data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode())
# inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode())
if sys.version_info[0] == 3:
from functools import partial
global open
open = partial(open, encoding='utf-8')
data_fo = open(data)
inverted_fo = open(inverted)
macro_fo = open(macro)
part5_fo = open(part5)
part2_fo = open(part2)
part1_fo = open(part1)
with data_fo as u:
with inverted_fo as i:
with macro_fo as m:
with part5_fo as p5:
with part2_fo as p2:
with part1_fo as p1:
return (list(csv.reader(u, delimiter='\t'))[1:],
list(csv.reader(i, delimiter='\t'))[1:],
list(csv.reader(m, delimiter='\t'))[1:],
list(csv.reader(p5, delimiter='\t'))[1:],
list(csv.reader(p2, delimiter='\t'))[1:],
list(csv.reader(p1, delimiter='\t'))[1:])
|
[
"def",
"_fabtabular",
"(",
")",
":",
"import",
"csv",
"import",
"sys",
"from",
"pkg_resources",
"import",
"resource_filename",
"data",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso-639-3.tab'",
")",
"inverted",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso-639-3_Name_Index.tab'",
")",
"macro",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso-639-3-macrolanguages.tab'",
")",
"part5",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso639-5.tsv'",
")",
"part2",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso639-2.tsv'",
")",
"part1",
"=",
"resource_filename",
"(",
"__package__",
",",
"'iso639-1.tsv'",
")",
"# if sys.version_info[0] == 2:",
"# from urllib2 import urlopen",
"# from contextlib import closing",
"# data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab'))",
"# inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab'))",
"# else:",
"# from urllib.request import urlopen",
"# import io",
"# data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode())",
"# inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode())",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"from",
"functools",
"import",
"partial",
"global",
"open",
"open",
"=",
"partial",
"(",
"open",
",",
"encoding",
"=",
"'utf-8'",
")",
"data_fo",
"=",
"open",
"(",
"data",
")",
"inverted_fo",
"=",
"open",
"(",
"inverted",
")",
"macro_fo",
"=",
"open",
"(",
"macro",
")",
"part5_fo",
"=",
"open",
"(",
"part5",
")",
"part2_fo",
"=",
"open",
"(",
"part2",
")",
"part1_fo",
"=",
"open",
"(",
"part1",
")",
"with",
"data_fo",
"as",
"u",
":",
"with",
"inverted_fo",
"as",
"i",
":",
"with",
"macro_fo",
"as",
"m",
":",
"with",
"part5_fo",
"as",
"p5",
":",
"with",
"part2_fo",
"as",
"p2",
":",
"with",
"part1_fo",
"as",
"p1",
":",
"return",
"(",
"list",
"(",
"csv",
".",
"reader",
"(",
"u",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
",",
"list",
"(",
"csv",
".",
"reader",
"(",
"i",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
",",
"list",
"(",
"csv",
".",
"reader",
"(",
"m",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
",",
"list",
"(",
"csv",
".",
"reader",
"(",
"p5",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
",",
"list",
"(",
"csv",
".",
"reader",
"(",
"p2",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
",",
"list",
"(",
"csv",
".",
"reader",
"(",
"p1",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
")"
] |
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
|
[
"This",
"function",
"retrieves",
"the",
"ISO",
"639",
"and",
"inverted",
"names",
"datasets",
"as",
"tsv",
"files",
"and",
"returns",
"them",
"as",
"lists",
"."
] |
2175cf04b8b8cec79d99a6c4ad31295d67c22cd6
|
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L14-L63
|
train
|
noumar/iso639
|
iso639/iso639.py
|
Iso639.retired
|
def retired(self):
"""
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
"""
def gen():
import csv
import re
from datetime import datetime
from pkg_resources import resource_filename
with open(resource_filename(__package__, 'iso-639-3_Retirements.tab')) as rf:
rtd = list(csv.reader(rf, delimiter='\t'))[1:]
rc = [r[0] for r in rtd]
for i, _, _, m, s, d in rtd:
d = datetime.strptime(d, '%Y-%m-%d')
if not m:
m = re.findall('\[([a-z]{3})\]', s)
if m:
m = [m] if isinstance(m, str) else m
yield i, (d, [self.get(part3=x) for x in m if x not in rc], s)
else:
yield i, (d, [], s)
yield 'sh', self.get(part3='hbs') # Add 'sh' as deprecated
return dict(gen())
|
python
|
def retired(self):
"""
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
"""
def gen():
import csv
import re
from datetime import datetime
from pkg_resources import resource_filename
with open(resource_filename(__package__, 'iso-639-3_Retirements.tab')) as rf:
rtd = list(csv.reader(rf, delimiter='\t'))[1:]
rc = [r[0] for r in rtd]
for i, _, _, m, s, d in rtd:
d = datetime.strptime(d, '%Y-%m-%d')
if not m:
m = re.findall('\[([a-z]{3})\]', s)
if m:
m = [m] if isinstance(m, str) else m
yield i, (d, [self.get(part3=x) for x in m if x not in rc], s)
else:
yield i, (d, [], s)
yield 'sh', self.get(part3='hbs') # Add 'sh' as deprecated
return dict(gen())
|
[
"def",
"retired",
"(",
"self",
")",
":",
"def",
"gen",
"(",
")",
":",
"import",
"csv",
"import",
"re",
"from",
"datetime",
"import",
"datetime",
"from",
"pkg_resources",
"import",
"resource_filename",
"with",
"open",
"(",
"resource_filename",
"(",
"__package__",
",",
"'iso-639-3_Retirements.tab'",
")",
")",
"as",
"rf",
":",
"rtd",
"=",
"list",
"(",
"csv",
".",
"reader",
"(",
"rf",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
"[",
"1",
":",
"]",
"rc",
"=",
"[",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"rtd",
"]",
"for",
"i",
",",
"_",
",",
"_",
",",
"m",
",",
"s",
",",
"d",
"in",
"rtd",
":",
"d",
"=",
"datetime",
".",
"strptime",
"(",
"d",
",",
"'%Y-%m-%d'",
")",
"if",
"not",
"m",
":",
"m",
"=",
"re",
".",
"findall",
"(",
"'\\[([a-z]{3})\\]'",
",",
"s",
")",
"if",
"m",
":",
"m",
"=",
"[",
"m",
"]",
"if",
"isinstance",
"(",
"m",
",",
"str",
")",
"else",
"m",
"yield",
"i",
",",
"(",
"d",
",",
"[",
"self",
".",
"get",
"(",
"part3",
"=",
"x",
")",
"for",
"x",
"in",
"m",
"if",
"x",
"not",
"in",
"rc",
"]",
",",
"s",
")",
"else",
":",
"yield",
"i",
",",
"(",
"d",
",",
"[",
"]",
",",
"s",
")",
"yield",
"'sh'",
",",
"self",
".",
"get",
"(",
"part3",
"=",
"'hbs'",
")",
"# Add 'sh' as deprecated",
"return",
"dict",
"(",
"gen",
"(",
")",
")"
] |
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
|
[
"Function",
"for",
"generating",
"retired",
"languages",
".",
"Returns",
"a",
"dict",
"(",
"code",
"(",
"datetime",
"[",
"language",
"...",
"]",
"description",
"))",
"."
] |
2175cf04b8b8cec79d99a6c4ad31295d67c22cd6
|
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L230-L256
|
train
|
noumar/iso639
|
iso639/iso639.py
|
Iso639.get
|
def get(self, **kwargs):
"""
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
"""
if not len(kwargs) == 1:
raise AttributeError('Only one keyword expected')
key, value = kwargs.popitem()
return getattr(self, key)[value]
|
python
|
def get(self, **kwargs):
"""
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
"""
if not len(kwargs) == 1:
raise AttributeError('Only one keyword expected')
key, value = kwargs.popitem()
return getattr(self, key)[value]
|
[
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"len",
"(",
"kwargs",
")",
"==",
"1",
":",
"raise",
"AttributeError",
"(",
"'Only one keyword expected'",
")",
"key",
",",
"value",
"=",
"kwargs",
".",
"popitem",
"(",
")",
"return",
"getattr",
"(",
"self",
",",
"key",
")",
"[",
"value",
"]"
] |
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
|
[
"Simple",
"getter",
"function",
"for",
"languages",
".",
"Takes",
"1",
"keyword",
"/",
"value",
"and",
"returns",
"1",
"language",
"object",
"."
] |
2175cf04b8b8cec79d99a6c4ad31295d67c22cd6
|
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L258-L265
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
CustomerViewSet.list
|
def list(self, request, *args, **kwargs):
"""
To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can
only see connected customers:
- customers that the user owns
- customers that have a project where user has a role
Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID>
Staff also can filter customers by exists accounting_start_date, for example:
The first category:
/api/customers/?accounting_is_running=True
has accounting_start_date empty (i.e. accounting starts at once)
has accounting_start_date in the past (i.e. has already started).
Those that are not in the first:
/api/customers/?accounting_is_running=False # exists accounting_start_date
"""
return super(CustomerViewSet, self).list(request, *args, **kwargs)
|
python
|
def list(self, request, *args, **kwargs):
"""
To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can
only see connected customers:
- customers that the user owns
- customers that have a project where user has a role
Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID>
Staff also can filter customers by exists accounting_start_date, for example:
The first category:
/api/customers/?accounting_is_running=True
has accounting_start_date empty (i.e. accounting starts at once)
has accounting_start_date in the past (i.e. has already started).
Those that are not in the first:
/api/customers/?accounting_is_running=False # exists accounting_start_date
"""
return super(CustomerViewSet, self).list(request, *args, **kwargs)
|
[
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CustomerViewSet",
",",
"self",
")",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can
only see connected customers:
- customers that the user owns
- customers that have a project where user has a role
Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID>
Staff also can filter customers by exists accounting_start_date, for example:
The first category:
/api/customers/?accounting_is_running=True
has accounting_start_date empty (i.e. accounting starts at once)
has accounting_start_date in the past (i.e. has already started).
Those that are not in the first:
/api/customers/?accounting_is_running=False # exists accounting_start_date
|
[
"To",
"get",
"a",
"list",
"of",
"customers",
"run",
"GET",
"against",
"*",
"/",
"api",
"/",
"customers",
"/",
"*",
"as",
"authenticated",
"user",
".",
"Note",
"that",
"a",
"user",
"can",
"only",
"see",
"connected",
"customers",
":"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L71-L92
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
CustomerViewSet.retrieve
|
def retrieve(self, request, *args, **kwargs):
"""
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Ministry of Bells"
}
"""
return super(CustomerViewSet, self).retrieve(request, *args, **kwargs)
|
python
|
def retrieve(self, request, *args, **kwargs):
"""
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Ministry of Bells"
}
"""
return super(CustomerViewSet, self).retrieve(request, *args, **kwargs)
|
[
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CustomerViewSet",
",",
"self",
")",
".",
"retrieve",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Ministry of Bells"
}
|
[
"Optional",
"field",
"query",
"parameter",
"(",
"can",
"be",
"list",
")",
"allows",
"to",
"limit",
"what",
"fields",
"are",
"returned",
".",
"For",
"example",
"given",
"request",
"/",
"api",
"/",
"customers",
"/",
"<uuid",
">",
"/",
"?field",
"=",
"uuid&field",
"=",
"name",
"you",
"get",
"response",
"like",
"this",
":"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L94-L106
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
CustomerViewSet.create
|
def create(self, request, *args, **kwargs):
"""
A new customer can only be created:
- by users with staff privilege (is_staff=True);
- by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True;
Example of a valid request:
.. code-block:: http
POST /api/customers/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Customer A",
"native_name": "Customer A",
"abbreviation": "CA",
"contact_details": "Luhamaa 28, 10128 Tallinn",
}
"""
return super(CustomerViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
A new customer can only be created:
- by users with staff privilege (is_staff=True);
- by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True;
Example of a valid request:
.. code-block:: http
POST /api/customers/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Customer A",
"native_name": "Customer A",
"abbreviation": "CA",
"contact_details": "Luhamaa 28, 10128 Tallinn",
}
"""
return super(CustomerViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CustomerViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
A new customer can only be created:
- by users with staff privilege (is_staff=True);
- by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True;
Example of a valid request:
.. code-block:: http
POST /api/customers/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Customer A",
"native_name": "Customer A",
"abbreviation": "CA",
"contact_details": "Luhamaa 28, 10128 Tallinn",
}
|
[
"A",
"new",
"customer",
"can",
"only",
"be",
"created",
":"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L108-L132
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
CustomerViewSet.destroy
|
def destroy(self, request, *args, **kwargs):
"""
Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note,
that if a customer has connected projects, deletion request will fail with 409 response code.
Valid request example (token is user specific):
.. code-block:: http
DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
"""
return super(CustomerViewSet, self).destroy(request, *args, **kwargs)
|
python
|
def destroy(self, request, *args, **kwargs):
"""
Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note,
that if a customer has connected projects, deletion request will fail with 409 response code.
Valid request example (token is user specific):
.. code-block:: http
DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
"""
return super(CustomerViewSet, self).destroy(request, *args, **kwargs)
|
[
"def",
"destroy",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CustomerViewSet",
",",
"self",
")",
".",
"destroy",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note,
that if a customer has connected projects, deletion request will fail with 409 response code.
Valid request example (token is user specific):
.. code-block:: http
DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
|
[
"Deletion",
"of",
"a",
"customer",
"is",
"done",
"through",
"sending",
"a",
"**",
"DELETE",
"**",
"request",
"to",
"the",
"customer",
"instance",
"URI",
".",
"Please",
"note",
"that",
"if",
"a",
"customer",
"has",
"connected",
"projects",
"deletion",
"request",
"will",
"fail",
"with",
"409",
"response",
"code",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L134-L147
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
ProjectViewSet.list
|
def list(self, request, *args, **kwargs):
"""
To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects that the user owns as a customer
- projects where user has any role
Supported logic filters:
- ?can_manage - return a list of projects where current user is manager or a customer owner;
- ?can_admin - return a list of projects where current user is admin;
"""
return super(ProjectViewSet, self).list(request, *args, **kwargs)
|
python
|
def list(self, request, *args, **kwargs):
"""
To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects that the user owns as a customer
- projects where user has any role
Supported logic filters:
- ?can_manage - return a list of projects where current user is manager or a customer owner;
- ?can_admin - return a list of projects where current user is admin;
"""
return super(ProjectViewSet, self).list(request, *args, **kwargs)
|
[
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ProjectViewSet",
",",
"self",
")",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects that the user owns as a customer
- projects where user has any role
Supported logic filters:
- ?can_manage - return a list of projects where current user is manager or a customer owner;
- ?can_admin - return a list of projects where current user is admin;
|
[
"To",
"get",
"a",
"list",
"of",
"projects",
"run",
"**",
"GET",
"**",
"against",
"*",
"/",
"api",
"/",
"projects",
"/",
"*",
"as",
"authenticated",
"user",
".",
"Here",
"you",
"can",
"also",
"check",
"actual",
"value",
"for",
"project",
"quotas",
"and",
"project",
"usage"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L260-L275
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
ProjectViewSet.retrieve
|
def retrieve(self, request, *args, **kwargs):
"""
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Default"
}
"""
return super(ProjectViewSet, self).retrieve(request, *args, **kwargs)
|
python
|
def retrieve(self, request, *args, **kwargs):
"""
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Default"
}
"""
return super(ProjectViewSet, self).retrieve(request, *args, **kwargs)
|
[
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ProjectViewSet",
",",
"self",
")",
".",
"retrieve",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Optional `field` query parameter (can be list) allows to limit what fields are returned.
For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this:
.. code-block:: javascript
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Default"
}
|
[
"Optional",
"field",
"query",
"parameter",
"(",
"can",
"be",
"list",
")",
"allows",
"to",
"limit",
"what",
"fields",
"are",
"returned",
".",
"For",
"example",
"given",
"request",
"/",
"api",
"/",
"projects",
"/",
"<uuid",
">",
"/",
"?field",
"=",
"uuid&field",
"=",
"name",
"you",
"get",
"response",
"like",
"this",
":"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L277-L289
|
train
|
opennode/waldur-core
|
waldur_core/structure/views.py
|
ProjectViewSet.create
|
def create(self, request, *args, **kwargs):
"""
A new project can be created by users with staff privilege (is_staff=True) or customer owners.
Project resource quota is optional. Example of a valid request:
.. code-block:: http
POST /api/projects/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Project A",
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
}
"""
return super(ProjectViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
A new project can be created by users with staff privilege (is_staff=True) or customer owners.
Project resource quota is optional. Example of a valid request:
.. code-block:: http
POST /api/projects/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Project A",
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
}
"""
return super(ProjectViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ProjectViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
A new project can be created by users with staff privilege (is_staff=True) or customer owners.
Project resource quota is optional. Example of a valid request:
.. code-block:: http
POST /api/projects/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Project A",
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
}
|
[
"A",
"new",
"project",
"can",
"be",
"created",
"by",
"users",
"with",
"staff",
"privilege",
"(",
"is_staff",
"=",
"True",
")",
"or",
"customer",
"owners",
".",
"Project",
"resource",
"quota",
"is",
"optional",
".",
"Example",
"of",
"a",
"valid",
"request",
":"
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L291-L309
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.