repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
gbiggs/rtctree | rtctree/manager.py | Manager.factory_profiles | def factory_profiles(self):
'''The factory profiles of all loaded modules.'''
with self._mutex:
if not self._factory_profiles:
self._factory_profiles = []
for fp in self._obj.get_factory_profiles():
self._factory_profiles.append(utils.nvlist_to_dict(fp.properties))
return self._factory_profiles | python | def factory_profiles(self):
'''The factory profiles of all loaded modules.'''
with self._mutex:
if not self._factory_profiles:
self._factory_profiles = []
for fp in self._obj.get_factory_profiles():
self._factory_profiles.append(utils.nvlist_to_dict(fp.properties))
return self._factory_profiles | [
"def",
"factory_profiles",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_factory_profiles",
":",
"self",
".",
"_factory_profiles",
"=",
"[",
"]",
"for",
"fp",
"in",
"self",
".",
"_obj",
".",
"get_factory_profiles",
... | The factory profiles of all loaded modules. | [
"The",
"factory",
"profiles",
"of",
"all",
"loaded",
"modules",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L265-L272 |
gbiggs/rtctree | rtctree/manager.py | Manager.set_config_parameter | def set_config_parameter(self, param, value):
'''Set a configuration parameter of the manager.
@param The parameter to set.
@value The new value for the parameter.
@raises FailedToSetConfigurationError
'''
with self._mutex:
if self._obj.set_configuration(param, value) != RTC.RTC_OK:
raise exceptions.FailedToSetConfigurationError(param, value)
# Force a reparse of the configuration
self._configuration = None | python | def set_config_parameter(self, param, value):
'''Set a configuration parameter of the manager.
@param The parameter to set.
@value The new value for the parameter.
@raises FailedToSetConfigurationError
'''
with self._mutex:
if self._obj.set_configuration(param, value) != RTC.RTC_OK:
raise exceptions.FailedToSetConfigurationError(param, value)
# Force a reparse of the configuration
self._configuration = None | [
"def",
"set_config_parameter",
"(",
"self",
",",
"param",
",",
"value",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"_obj",
".",
"set_configuration",
"(",
"param",
",",
"value",
")",
"!=",
"RTC",
".",
"RTC_OK",
":",
"raise",
"excep... | Set a configuration parameter of the manager.
@param The parameter to set.
@value The new value for the parameter.
@raises FailedToSetConfigurationError | [
"Set",
"a",
"configuration",
"parameter",
"of",
"the",
"manager",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L277-L289 |
gbiggs/rtctree | rtctree/manager.py | Manager.configuration | def configuration(self):
'''The configuration dictionary of the manager.'''
with self._mutex:
if not self._configuration:
self._configuration = utils.nvlist_to_dict(self._obj.get_configuration())
return self._configuration | python | def configuration(self):
'''The configuration dictionary of the manager.'''
with self._mutex:
if not self._configuration:
self._configuration = utils.nvlist_to_dict(self._obj.get_configuration())
return self._configuration | [
"def",
"configuration",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_configuration",
":",
"self",
".",
"_configuration",
"=",
"utils",
".",
"nvlist_to_dict",
"(",
"self",
".",
"_obj",
".",
"get_configuration",
"(",... | The configuration dictionary of the manager. | [
"The",
"configuration",
"dictionary",
"of",
"the",
"manager",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L292-L297 |
gbiggs/rtctree | rtctree/manager.py | Manager.profile | def profile(self):
'''The manager's profile.'''
with self._mutex:
if not self._profile:
profile = self._obj.get_profile()
self._profile = utils.nvlist_to_dict(profile.properties)
return self._profile | python | def profile(self):
'''The manager's profile.'''
with self._mutex:
if not self._profile:
profile = self._obj.get_profile()
self._profile = utils.nvlist_to_dict(profile.properties)
return self._profile | [
"def",
"profile",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_profile",
":",
"profile",
"=",
"self",
".",
"_obj",
".",
"get_profile",
"(",
")",
"self",
".",
"_profile",
"=",
"utils",
".",
"nvlist_to_dict",
"... | The manager's profile. | [
"The",
"manager",
"s",
"profile",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L300-L306 |
gbiggs/rtctree | rtctree/manager.py | Manager.loadable_modules | def loadable_modules(self):
'''The list of loadable module profile dictionaries.'''
with self._mutex:
if not self._loadable_modules:
self._loadable_modules = []
for mp in self._obj.get_loadable_modules():
self._loadable_modules.append(utils.nvlist_to_dict(mp.properties))
return self._loadable_modules | python | def loadable_modules(self):
'''The list of loadable module profile dictionaries.'''
with self._mutex:
if not self._loadable_modules:
self._loadable_modules = []
for mp in self._obj.get_loadable_modules():
self._loadable_modules.append(utils.nvlist_to_dict(mp.properties))
return self._loadable_modules | [
"def",
"loadable_modules",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_loadable_modules",
":",
"self",
".",
"_loadable_modules",
"=",
"[",
"]",
"for",
"mp",
"in",
"self",
".",
"_obj",
".",
"get_loadable_modules",
... | The list of loadable module profile dictionaries. | [
"The",
"list",
"of",
"loadable",
"module",
"profile",
"dictionaries",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L358-L365 |
gbiggs/rtctree | rtctree/manager.py | Manager.loaded_modules | def loaded_modules(self):
'''The list of loaded module profile dictionaries.'''
with self._mutex:
if not self._loaded_modules:
self._loaded_modules = []
for mp in self._obj.get_loaded_modules():
self._loaded_modules.append(utils.nvlist_to_dict(mp.properties))
return self._loaded_modules | python | def loaded_modules(self):
'''The list of loaded module profile dictionaries.'''
with self._mutex:
if not self._loaded_modules:
self._loaded_modules = []
for mp in self._obj.get_loaded_modules():
self._loaded_modules.append(utils.nvlist_to_dict(mp.properties))
return self._loaded_modules | [
"def",
"loaded_modules",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_loaded_modules",
":",
"self",
".",
"_loaded_modules",
"=",
"[",
"]",
"for",
"mp",
"in",
"self",
".",
"_obj",
".",
"get_loaded_modules",
"(",
... | The list of loaded module profile dictionaries. | [
"The",
"list",
"of",
"loaded",
"module",
"profile",
"dictionaries",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L368-L375 |
gbiggs/rtctree | rtctree/manager.py | Manager.slaves | def slaves(self):
'''The list of slave managers of this manager, if any.
This information can also be found by listing the children of this node
that are of type @ref Manager.
'''
with self._mutex:
if not self._slaves:
self._slaves = [c for c in self.children if c.is_manager]
return self._slaves | python | def slaves(self):
'''The list of slave managers of this manager, if any.
This information can also be found by listing the children of this node
that are of type @ref Manager.
'''
with self._mutex:
if not self._slaves:
self._slaves = [c for c in self.children if c.is_manager]
return self._slaves | [
"def",
"slaves",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_slaves",
":",
"self",
".",
"_slaves",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"children",
"if",
"c",
".",
"is_manager",
"]",
"return",
"... | The list of slave managers of this manager, if any.
This information can also be found by listing the children of this node
that are of type @ref Manager. | [
"The",
"list",
"of",
"slave",
"managers",
"of",
"this",
"manager",
"if",
"any",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L390-L400 |
jlafon/django-rest-framework-oauth | rest_framework_oauth/authentication.py | OAuth2Authentication.authenticate_credentials | def authenticate_credentials(self, request, access_token):
"""
Authenticate the request, given the access token.
"""
try:
token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user')
# provider_now switches to timezone aware datetime when
# the oauth2_provider version supports to it.
token = token.get(token=access_token, expires__gt=provider_now())
except oauth2_provider.oauth2.models.AccessToken.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
user = token.user
if not user.is_active:
msg = 'User inactive or deleted: %s' % user.username
raise exceptions.AuthenticationFailed(msg)
return (user, token) | python | def authenticate_credentials(self, request, access_token):
"""
Authenticate the request, given the access token.
"""
try:
token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user')
# provider_now switches to timezone aware datetime when
# the oauth2_provider version supports to it.
token = token.get(token=access_token, expires__gt=provider_now())
except oauth2_provider.oauth2.models.AccessToken.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
user = token.user
if not user.is_active:
msg = 'User inactive or deleted: %s' % user.username
raise exceptions.AuthenticationFailed(msg)
return (user, token) | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"request",
",",
"access_token",
")",
":",
"try",
":",
"token",
"=",
"oauth2_provider",
".",
"oauth2",
".",
"models",
".",
"AccessToken",
".",
"objects",
".",
"select_related",
"(",
"'user'",
")",
"# provider... | Authenticate the request, given the access token. | [
"Authenticate",
"the",
"request",
"given",
"the",
"access",
"token",
"."
] | train | https://github.com/jlafon/django-rest-framework-oauth/blob/05ff90623fa811f166a000d8d58aa855c07c7435/rest_framework_oauth/authentication.py#L168-L187 |
mistio/mist.client | src/mistclient/model.py | Cloud.request | def request(self, *args, **kwargs):
"""
The main purpose of this is to be a wrapper-like function to pass the api_token and all the other params to the
requests that are being made
:returns: An instance of RequestsHandler
"""
return RequestsHandler(*args, api_token=self.api_token,
verify=self.mist_client.verify,
job_id=self.mist_client.job_id, **kwargs) | python | def request(self, *args, **kwargs):
"""
The main purpose of this is to be a wrapper-like function to pass the api_token and all the other params to the
requests that are being made
:returns: An instance of RequestsHandler
"""
return RequestsHandler(*args, api_token=self.api_token,
verify=self.mist_client.verify,
job_id=self.mist_client.job_id, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"RequestsHandler",
"(",
"*",
"args",
",",
"api_token",
"=",
"self",
".",
"api_token",
",",
"verify",
"=",
"self",
".",
"mist_client",
".",
"verify",
",",
"j... | The main purpose of this is to be a wrapper-like function to pass the api_token and all the other params to the
requests that are being made
:returns: An instance of RequestsHandler | [
"The",
"main",
"purpose",
"of",
"this",
"is",
"to",
"be",
"a",
"wrapper",
"-",
"like",
"function",
"to",
"pass",
"the",
"api_token",
"and",
"all",
"the",
"other",
"params",
"to",
"the",
"requests",
"that",
"are",
"being",
"made"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L38-L47 |
mistio/mist.client | src/mistclient/model.py | Cloud.delete | def delete(self):
"""
Delete the cloud from the list of added clouds in mist.io service.
:returns: A list of mist.clients' updated clouds.
"""
req = self.request(self.mist_client.uri + '/clouds/' + self.id)
req.delete()
self.mist_client.update_clouds() | python | def delete(self):
"""
Delete the cloud from the list of added clouds in mist.io service.
:returns: A list of mist.clients' updated clouds.
"""
req = self.request(self.mist_client.uri + '/clouds/' + self.id)
req.delete()
self.mist_client.update_clouds() | [
"def",
"delete",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"id",
")",
"req",
".",
"delete",
"(",
")",
"self",
".",
"mist_client",
".",
"update_clouds",... | Delete the cloud from the list of added clouds in mist.io service.
:returns: A list of mist.clients' updated clouds. | [
"Delete",
"the",
"cloud",
"from",
"the",
"list",
"of",
"added",
"clouds",
"in",
"mist",
".",
"io",
"service",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L49-L57 |
mistio/mist.client | src/mistclient/model.py | Cloud.enable | def enable(self):
"""
Enable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "1"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post()
self.enabled = True
self.mist_client.update_clouds() | python | def enable(self):
"""
Enable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "1"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post()
self.enabled = True
self.mist_client.update_clouds() | [
"def",
"enable",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"\"new_state\"",
":",
"\"1\"",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'... | Enable the Cloud.
:returns: A list of mist.clients' updated clouds. | [
"Enable",
"the",
"Cloud",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L75-L88 |
mistio/mist.client | src/mistclient/model.py | Cloud.disable | def disable(self):
"""
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "0"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post()
self.enabled = False
self.mist_client.update_clouds() | python | def disable(self):
"""
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "0"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post()
self.enabled = False
self.mist_client.update_clouds() | [
"def",
"disable",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"\"new_state\"",
":",
"\"0\"",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/... | Disable the Cloud.
:returns: A list of mist.clients' updated clouds. | [
"Disable",
"the",
"Cloud",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L90-L103 |
mistio/mist.client | src/mistclient/model.py | Cloud.sizes | def sizes(self):
"""
Available machine sizes to be used when creating a new machine.
:returns: A list of available machine sizes.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/sizes')
sizes = req.get().json()
return sizes | python | def sizes(self):
"""
Available machine sizes to be used when creating a new machine.
:returns: A list of available machine sizes.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/sizes')
sizes = req.get().json()
return sizes | [
"def",
"sizes",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"id",
"+",
"'/sizes'",
")",
"sizes",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
"(",
... | Available machine sizes to be used when creating a new machine.
:returns: A list of available machine sizes. | [
"Available",
"machine",
"sizes",
"to",
"be",
"used",
"when",
"creating",
"a",
"new",
"machine",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L106-L114 |
mistio/mist.client | src/mistclient/model.py | Cloud.locations | def locations(self):
"""
Available locations to be used when creating a new machine.
:returns: A list of available locations.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations')
locations = req.get().json()
return locations | python | def locations(self):
"""
Available locations to be used when creating a new machine.
:returns: A list of available locations.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations')
locations = req.get().json()
return locations | [
"def",
"locations",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"id",
"+",
"'/locations'",
")",
"locations",
"=",
"req",
".",
"get",
"(",
")",
".",
"js... | Available locations to be used when creating a new machine.
:returns: A list of available locations. | [
"Available",
"locations",
"to",
"be",
"used",
"when",
"creating",
"a",
"new",
"machine",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L117-L125 |
mistio/mist.client | src/mistclient/model.py | Cloud.networks | def networks(self):
"""
Available networks.
:returns: A list of available networks associated to a provider.
"""
if self.provider in ['openstack', 'nephoscale']:
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/networks')
networks = req.get().json()
return networks
else:
print "Network actions not supported yet for %s provider" % self.provider | python | def networks(self):
"""
Available networks.
:returns: A list of available networks associated to a provider.
"""
if self.provider in ['openstack', 'nephoscale']:
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/networks')
networks = req.get().json()
return networks
else:
print "Network actions not supported yet for %s provider" % self.provider | [
"def",
"networks",
"(",
"self",
")",
":",
"if",
"self",
".",
"provider",
"in",
"[",
"'openstack'",
",",
"'nephoscale'",
"]",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"i... | Available networks.
:returns: A list of available networks associated to a provider. | [
"Available",
"networks",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L128-L139 |
mistio/mist.client | src/mistclient/model.py | Cloud.images | def images(self):
"""
Available images to be used when creating a new machine.
:returns: A list of all available images.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images')
images = req.get().json()
return images | python | def images(self):
"""
Available images to be used when creating a new machine.
:returns: A list of all available images.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images')
images = req.get().json()
return images | [
"def",
"images",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"id",
"+",
"'/images'",
")",
"images",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
"(... | Available images to be used when creating a new machine.
:returns: A list of all available images. | [
"Available",
"images",
"to",
"be",
"used",
"when",
"creating",
"a",
"new",
"machine",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L159-L167 |
mistio/mist.client | src/mistclient/model.py | Cloud.search_image | def search_image(self, search_term):
"""
Search for a specific image by providing a search term (mainly used with ec2's community and public images)
:param search_term: Search term to be used when searching for images's names containing this term.
:returns: A list of all images, whose names contain the given search_term.
"""
payload = {
'search_term': search_term
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images', data=data)
images = req.get().json()
return images | python | def search_image(self, search_term):
"""
Search for a specific image by providing a search term (mainly used with ec2's community and public images)
:param search_term: Search term to be used when searching for images's names containing this term.
:returns: A list of all images, whose names contain the given search_term.
"""
payload = {
'search_term': search_term
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images', data=data)
images = req.get().json()
return images | [
"def",
"search_image",
"(",
"self",
",",
"search_term",
")",
":",
"payload",
"=",
"{",
"'search_term'",
":",
"search_term",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
... | Search for a specific image by providing a search term (mainly used with ec2's community and public images)
:param search_term: Search term to be used when searching for images's names containing this term.
:returns: A list of all images, whose names contain the given search_term. | [
"Search",
"for",
"a",
"specific",
"image",
"by",
"providing",
"a",
"search",
"term",
"(",
"mainly",
"used",
"with",
"ec2",
"s",
"community",
"and",
"public",
"images",
")"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L169-L183 |
mistio/mist.client | src/mistclient/model.py | Cloud._list_machines | def _list_machines(self):
"""
Request a list of all added machines.
Populates self._machines dict with mist.client.model.Machine instances
"""
try:
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines')
machines = req.get().json()
except:
# Eg invalid cloud credentials
machines = {}
if machines:
for machine in machines:
self._machines[machine['machine_id']] = Machine(machine, self)
else:
self._machines = {} | python | def _list_machines(self):
"""
Request a list of all added machines.
Populates self._machines dict with mist.client.model.Machine instances
"""
try:
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines')
machines = req.get().json()
except:
# Eg invalid cloud credentials
machines = {}
if machines:
for machine in machines:
self._machines[machine['machine_id']] = Machine(machine, self)
else:
self._machines = {} | [
"def",
"_list_machines",
"(",
"self",
")",
":",
"try",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/clouds/'",
"+",
"self",
".",
"id",
"+",
"'/machines'",
")",
"machines",
"=",
"req",
".",
"get",
"(",
... | Request a list of all added machines.
Populates self._machines dict with mist.client.model.Machine instances | [
"Request",
"a",
"list",
"of",
"all",
"added",
"machines",
"."
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L185-L202 |
mistio/mist.client | src/mistclient/model.py | Cloud.machines | def machines(self, id=None, name=None, search=None):
"""
Property-like function to call the _list_machines function in order to populate self._machines dict
:returns: A list of Machine instances.
"""
if self._machines is None:
self._machines = {}
self._list_machines()
if id:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if str(id) == str(self._machines[machine_id].id)]
elif name:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if name == self._machines[machine_id].name]
elif search:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if str(search) == str(self._machines[machine_id].name)
or str(search) == str(self._machines[machine_id].id)]
else:
return [self._machines[machine_id] for machine_id in self._machines.keys()] | python | def machines(self, id=None, name=None, search=None):
"""
Property-like function to call the _list_machines function in order to populate self._machines dict
:returns: A list of Machine instances.
"""
if self._machines is None:
self._machines = {}
self._list_machines()
if id:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if str(id) == str(self._machines[machine_id].id)]
elif name:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if name == self._machines[machine_id].name]
elif search:
return [self._machines[machine_id] for machine_id in self._machines.keys()
if str(search) == str(self._machines[machine_id].name)
or str(search) == str(self._machines[machine_id].id)]
else:
return [self._machines[machine_id] for machine_id in self._machines.keys()] | [
"def",
"machines",
"(",
"self",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"search",
"=",
"None",
")",
":",
"if",
"self",
".",
"_machines",
"is",
"None",
":",
"self",
".",
"_machines",
"=",
"{",
"}",
"self",
".",
"_list_machines",
"(",
... | Property-like function to call the _list_machines function in order to populate self._machines dict
:returns: A list of Machine instances. | [
"Property",
"-",
"like",
"function",
"to",
"call",
"the",
"_list_machines",
"function",
"in",
"order",
"to",
"populate",
"self",
".",
"_machines",
"dict"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L204-L225 |
mistio/mist.client | src/mistclient/model.py | Cloud.create_machine | def create_machine(self, name, key, image_id, location_id, size_id,
image_extra="", disk="", script="", monitoring=False,
ips=[], networks=[], location_name="", async=False,
docker_command="", quantity=1, persist=False, fire_and_forget=True,
timeout=6000, script_id="", script_params="", verbose=False,
associate_floating_ip=False, provider="", tags=None,
cloud_init='', env_vars=''):
"""
Create a new machine on the given cloud
:param name: Name of the machine
:param key: Key Object to associate with the machine
:param image_id: Id of image to be used with the creation
:param location_id: Id of the cloud's location to create the machine
:param size_id: If of the size of the machine
:param image_extra: Needed only by Linode cloud
:param disk: Needed only by Linode cloud
:returns: An update list of added machines
"""
if isinstance(key, basestring):
key_id = key
else:
key_id = key.id
payload = {
'name': name,
'provider': provider,
'key': key_id,
'image': image_id,
'location': location_id,
'size': size_id,
'image_extra': image_extra,
'disk': disk,
'script': script,
'monitoring': monitoring,
'ips': ips,
'networks': networks,
'location_name': location_name,
'docker_command': docker_command,
'async': async,
'quantity': quantity,
'persist': persist,
'associate_floating_ip': associate_floating_ip,
'tags': tags,
'cloud_init': cloud_init,
'env_vars': env_vars
}
# add as params only if they are provided
if script_id:
payload['script_id'] = script_id
if script_params:
payload['script_params'] = script_params
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines', data=data)
result = req.post()
self.update_machines()
if not async or fire_and_forget:
return result.json()
else:
job_id = result.json()['job_id']
started_at = time()
while True:
job = self.mist_client.get_job(job_id)
if verbose:
summary = job.get('summary', {})
probes = summary.get('probe', {})
creates = summary.get('create', {})
scripts = summary.get('script', {})
monitoring = summary.get('monitoring', {})
states = [
'success',
'error',
'skipped',
'pending'
]
x = PrettyTable(['', 'SUCCESS', 'ERROR', 'SKIPPED', 'PENDING'])
if creates:
machines_created = {}
for state in states:
machines_created[state] = '%s/%s' % (creates.get(state, 'Undefined'), quantity)
x.add_row(["Create:", machines_created['success'], machines_created['error'],
machines_created['skipped'], machines_created['pending']])
if probes:
probed_machines = {}
for state in states:
probed_machines[state] = '%s/%s' % (probes.get(state, 'Undefined'), quantity)
x.add_row(["Probe:", probed_machines['success'], probed_machines['error'],
probed_machines['skipped'], probed_machines['pending']])
if scripts:
scripted_machines = {}
for state in states:
scripted_machines[state] = '%s/%s' % (scripts.get(state, 'Undefined'), quantity)
x.add_row(["Script:", scripted_machines['success'], scripted_machines['error'],
scripted_machines['skipped'], scripted_machines['pending']])
if monitoring:
monitored_machines = {}
for state in states:
monitored_machines[state] = '%s/%s' % (monitoring.get(state, 'Undefined'), quantity)
x.add_row(["Monitoring:", monitored_machines['success'], monitored_machines['error'],
monitored_machines['skipped'], monitored_machines['pending']])
print x
print
if job.get('finished_at', 0):
provision_finished = True
else:
# In case of nested logs, we have to make sure we parse the
# the logs correctly in order to determine whether the
# provisioned VM is running, since a story may contain logs
# of multiple machines
for log in job.get('logs', []):
if log.get('machine_name', '') == name and \
'machine_creation_finished' in log.values():
machine_id = log['machine_id']
error = log.get('error')
break
else:
sleep(5)
continue
if error:
provision_finished = True
else:
for log in job.get('logs', []):
if log.get('machine_id', '') == machine_id and \
'post_deploy_finished' in log.values():
provision_finished = True
break
else:
provision_finished = False
if provision_finished:
error = job.get('error')
if error:
print "Finished with errors:"
logs = job.get('logs', [])
for log in logs:
error = log.get('error')
if error:
print " - ", error
raise Exception("Create machine failed. Check the logs.")
elif verbose and not error:
print "Finished without errors!"
self.update_machines()
return job
elif time() - started_at > timeout:
print "Timed out!"
raise Exception("Create machine timed out. Check the logs.")
return job
sleep(5) | python | def create_machine(self, name, key, image_id, location_id, size_id,
image_extra="", disk="", script="", monitoring=False,
ips=[], networks=[], location_name="", async=False,
docker_command="", quantity=1, persist=False, fire_and_forget=True,
timeout=6000, script_id="", script_params="", verbose=False,
associate_floating_ip=False, provider="", tags=None,
cloud_init='', env_vars=''):
"""
Create a new machine on the given cloud
:param name: Name of the machine
:param key: Key Object to associate with the machine
:param image_id: Id of image to be used with the creation
:param location_id: Id of the cloud's location to create the machine
:param size_id: If of the size of the machine
:param image_extra: Needed only by Linode cloud
:param disk: Needed only by Linode cloud
:returns: An update list of added machines
"""
if isinstance(key, basestring):
key_id = key
else:
key_id = key.id
payload = {
'name': name,
'provider': provider,
'key': key_id,
'image': image_id,
'location': location_id,
'size': size_id,
'image_extra': image_extra,
'disk': disk,
'script': script,
'monitoring': monitoring,
'ips': ips,
'networks': networks,
'location_name': location_name,
'docker_command': docker_command,
'async': async,
'quantity': quantity,
'persist': persist,
'associate_floating_ip': associate_floating_ip,
'tags': tags,
'cloud_init': cloud_init,
'env_vars': env_vars
}
# add as params only if they are provided
if script_id:
payload['script_id'] = script_id
if script_params:
payload['script_params'] = script_params
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines', data=data)
result = req.post()
self.update_machines()
if not async or fire_and_forget:
return result.json()
else:
job_id = result.json()['job_id']
started_at = time()
while True:
job = self.mist_client.get_job(job_id)
if verbose:
summary = job.get('summary', {})
probes = summary.get('probe', {})
creates = summary.get('create', {})
scripts = summary.get('script', {})
monitoring = summary.get('monitoring', {})
states = [
'success',
'error',
'skipped',
'pending'
]
x = PrettyTable(['', 'SUCCESS', 'ERROR', 'SKIPPED', 'PENDING'])
if creates:
machines_created = {}
for state in states:
machines_created[state] = '%s/%s' % (creates.get(state, 'Undefined'), quantity)
x.add_row(["Create:", machines_created['success'], machines_created['error'],
machines_created['skipped'], machines_created['pending']])
if probes:
probed_machines = {}
for state in states:
probed_machines[state] = '%s/%s' % (probes.get(state, 'Undefined'), quantity)
x.add_row(["Probe:", probed_machines['success'], probed_machines['error'],
probed_machines['skipped'], probed_machines['pending']])
if scripts:
scripted_machines = {}
for state in states:
scripted_machines[state] = '%s/%s' % (scripts.get(state, 'Undefined'), quantity)
x.add_row(["Script:", scripted_machines['success'], scripted_machines['error'],
scripted_machines['skipped'], scripted_machines['pending']])
if monitoring:
monitored_machines = {}
for state in states:
monitored_machines[state] = '%s/%s' % (monitoring.get(state, 'Undefined'), quantity)
x.add_row(["Monitoring:", monitored_machines['success'], monitored_machines['error'],
monitored_machines['skipped'], monitored_machines['pending']])
print x
print
if job.get('finished_at', 0):
provision_finished = True
else:
# In case of nested logs, we have to make sure we parse the
# the logs correctly in order to determine whether the
# provisioned VM is running, since a story may contain logs
# of multiple machines
for log in job.get('logs', []):
if log.get('machine_name', '') == name and \
'machine_creation_finished' in log.values():
machine_id = log['machine_id']
error = log.get('error')
break
else:
sleep(5)
continue
if error:
provision_finished = True
else:
for log in job.get('logs', []):
if log.get('machine_id', '') == machine_id and \
'post_deploy_finished' in log.values():
provision_finished = True
break
else:
provision_finished = False
if provision_finished:
error = job.get('error')
if error:
print "Finished with errors:"
logs = job.get('logs', [])
for log in logs:
error = log.get('error')
if error:
print " - ", error
raise Exception("Create machine failed. Check the logs.")
elif verbose and not error:
print "Finished without errors!"
self.update_machines()
return job
elif time() - started_at > timeout:
print "Timed out!"
raise Exception("Create machine timed out. Check the logs.")
return job
sleep(5) | [
"def",
"create_machine",
"(",
"self",
",",
"name",
",",
"key",
",",
"image_id",
",",
"location_id",
",",
"size_id",
",",
"image_extra",
"=",
"\"\"",
",",
"disk",
"=",
"\"\"",
",",
"script",
"=",
"\"\"",
",",
"monitoring",
"=",
"False",
",",
"ips",
"=",... | Create a new machine on the given cloud
:param name: Name of the machine
:param key: Key Object to associate with the machine
:param image_id: Id of image to be used with the creation
:param location_id: Id of the cloud's location to create the machine
:param size_id: If of the size of the machine
:param image_extra: Needed only by Linode cloud
:param disk: Needed only by Linode cloud
:returns: An update list of added machines | [
"Create",
"a",
"new",
"machine",
"on",
"the",
"given",
"cloud"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L240-L402 |
mistio/mist.client | src/mistclient/model.py | Machine._machine_actions | def _machine_actions(self, action):
"""
Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines
"""
payload = {
'action': action
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.cloud.id+'/machines/'+self.id, data=data)
req.post()
self.cloud.update_machines() | python | def _machine_actions(self, action):
"""
Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines
"""
payload = {
'action': action
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.cloud.id+'/machines/'+self.id, data=data)
req.post()
self.cloud.update_machines() | [
"def",
"_machine_actions",
"(",
"self",
",",
"action",
")",
":",
"payload",
"=",
"{",
"'action'",
":",
"action",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"u... | Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines | [
"Actions",
"for",
"the",
"machine",
"(",
"e",
".",
"g",
".",
"stop",
"start",
"etc",
")"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L449-L462 |
mistio/mist.client | src/mistclient/model.py | Machine.probe | def probe(self, key_id=None, ssh_user=None):
"""
If no parameter is provided, mist.io will try to probe the machine with
the default
:param key_id: Optional. Give if you explicitly want to probe with this
key_id
:param ssh_user: Optional. Give if you explicitly want a specific user
:returns: A list of data received by the probing (e.g. uptime etc)
"""
ips = [ip for ip in self.info['public_ips'] if ':' not in ip]
if not ips:
raise Exception("No public IPv4 address available to connect to")
payload = {
'host': ips[0],
'key': key_id,
'ssh_user': ssh_user
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri + "/clouds/" + self.cloud.id +
"/machines/" + self.id + "/probe", data=data)
probe_info = req.post().json()
self.probed = True
return probe_info | python | def probe(self, key_id=None, ssh_user=None):
"""
If no parameter is provided, mist.io will try to probe the machine with
the default
:param key_id: Optional. Give if you explicitly want to probe with this
key_id
:param ssh_user: Optional. Give if you explicitly want a specific user
:returns: A list of data received by the probing (e.g. uptime etc)
"""
ips = [ip for ip in self.info['public_ips'] if ':' not in ip]
if not ips:
raise Exception("No public IPv4 address available to connect to")
payload = {
'host': ips[0],
'key': key_id,
'ssh_user': ssh_user
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri + "/clouds/" + self.cloud.id +
"/machines/" + self.id + "/probe", data=data)
probe_info = req.post().json()
self.probed = True
return probe_info | [
"def",
"probe",
"(",
"self",
",",
"key_id",
"=",
"None",
",",
"ssh_user",
"=",
"None",
")",
":",
"ips",
"=",
"[",
"ip",
"for",
"ip",
"in",
"self",
".",
"info",
"[",
"'public_ips'",
"]",
"if",
"':'",
"not",
"in",
"ip",
"]",
"if",
"not",
"ips",
"... | If no parameter is provided, mist.io will try to probe the machine with
the default
:param key_id: Optional. Give if you explicitly want to probe with this
key_id
:param ssh_user: Optional. Give if you explicitly want a specific user
:returns: A list of data received by the probing (e.g. uptime etc) | [
"If",
"no",
"parameter",
"is",
"provided",
"mist",
".",
"io",
"will",
"try",
"to",
"probe",
"the",
"machine",
"with",
"the",
"default",
":",
"param",
"key_id",
":",
"Optional",
".",
"Give",
"if",
"you",
"explicitly",
"want",
"to",
"probe",
"with",
"this"... | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L488-L511 |
mistio/mist.client | src/mistclient/model.py | Machine._toggle_monitoring | def _toggle_monitoring(self, action, no_ssh=False):
"""
Enable or disable monitoring on a machine
:param action: Can be either "enable" or "disable"
"""
payload = {
'action': action,
'name': self.name,
'no_ssh': no_ssh,
'public_ips': self.info['public_ips'],
'dns_name': self.info['extra'].get('dns_name', 'n/a')
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/monitoring",
data=data)
req.post() | python | def _toggle_monitoring(self, action, no_ssh=False):
"""
Enable or disable monitoring on a machine
:param action: Can be either "enable" or "disable"
"""
payload = {
'action': action,
'name': self.name,
'no_ssh': no_ssh,
'public_ips': self.info['public_ips'],
'dns_name': self.info['extra'].get('dns_name', 'n/a')
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/monitoring",
data=data)
req.post() | [
"def",
"_toggle_monitoring",
"(",
"self",
",",
"action",
",",
"no_ssh",
"=",
"False",
")",
":",
"payload",
"=",
"{",
"'action'",
":",
"action",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'no_ssh'",
":",
"no_ssh",
",",
"'public_ips'",
":",
"self",
"... | Enable or disable monitoring on a machine
:param action: Can be either "enable" or "disable" | [
"Enable",
"or",
"disable",
"monitoring",
"on",
"a",
"machine"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L525-L543 |
mistio/mist.client | src/mistclient/model.py | Machine.get_stats | def get_stats(self, start=int(time()), stop=int(time())+10, step=10):
"""
Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:param step: Step to fetch stats (default 10 seconds)
:returns: A dict of stats
"""
payload = {
'v': 2,
'start': start,
'stop': stop,
'step': step
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/stats", data=data)
stats = req.get().json()
return stats | python | def get_stats(self, start=int(time()), stop=int(time())+10, step=10):
"""
Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:param step: Step to fetch stats (default 10 seconds)
:returns: A dict of stats
"""
payload = {
'v': 2,
'start': start,
'stop': stop,
'step': step
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/stats", data=data)
stats = req.get().json()
return stats | [
"def",
"get_stats",
"(",
"self",
",",
"start",
"=",
"int",
"(",
"time",
"(",
")",
")",
",",
"stop",
"=",
"int",
"(",
"time",
"(",
")",
")",
"+",
"10",
",",
"step",
"=",
"10",
")",
":",
"payload",
"=",
"{",
"'v'",
":",
"2",
",",
"'start'",
"... | Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:param step: Step to fetch stats (default 10 seconds)
:returns: A dict of stats | [
"Get",
"stats",
"of",
"a",
"monitored",
"machine"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L557-L576 |
mistio/mist.client | src/mistclient/model.py | Machine.available_metrics | def available_metrics(self):
"""
List all available metrics that you can add to this machine
:returns: A list of dicts, each of which is a metric that you can add to a monitored machine
"""
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics")
metrics = req.get().json()
return metrics | python | def available_metrics(self):
"""
List all available metrics that you can add to this machine
:returns: A list of dicts, each of which is a metric that you can add to a monitored machine
"""
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics")
metrics = req.get().json()
return metrics | [
"def",
"available_metrics",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"\"/clouds/\"",
"+",
"self",
".",
"cloud",
".",
"id",
"+",
"\"/machines/\"",
"+",
"self",
".",
"id",
"+",
"\"/metri... | List all available metrics that you can add to this machine
:returns: A list of dicts, each of which is a metric that you can add to a monitored machine | [
"List",
"all",
"available",
"metrics",
"that",
"you",
"can",
"add",
"to",
"this",
"machine"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L579-L587 |
mistio/mist.client | src/mistclient/model.py | Machine.add_metric | def add_metric(self, metric_id):
"""
Add a metric to a monitored machine
:param metric_id: Metric_id (provided by self.available_metrics)
"""
payload = {
'metric_id': metric_id
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data)
req.put() | python | def add_metric(self, metric_id):
"""
Add a metric to a monitored machine
:param metric_id: Metric_id (provided by self.available_metrics)
"""
payload = {
'metric_id': metric_id
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data)
req.put() | [
"def",
"add_metric",
"(",
"self",
",",
"metric_id",
")",
":",
"payload",
"=",
"{",
"'metric_id'",
":",
"metric_id",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
... | Add a metric to a monitored machine
:param metric_id: Metric_id (provided by self.available_metrics) | [
"Add",
"a",
"metric",
"to",
"a",
"monitored",
"machine"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L589-L600 |
mistio/mist.client | src/mistclient/model.py | Machine.remove_metric | def remove_metric(self, metric_id):
"""
Remove a metric from a monitored machine
:param metric_id: Metric_id (provided by self.get_stats() )
"""
payload = {
'metric_id': metric_id
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data)
req.delete() | python | def remove_metric(self, metric_id):
"""
Remove a metric from a monitored machine
:param metric_id: Metric_id (provided by self.get_stats() )
"""
payload = {
'metric_id': metric_id
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data)
req.delete() | [
"def",
"remove_metric",
"(",
"self",
",",
"metric_id",
")",
":",
"payload",
"=",
"{",
"'metric_id'",
":",
"metric_id",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
"."... | Remove a metric from a monitored machine
:param metric_id: Metric_id (provided by self.get_stats() ) | [
"Remove",
"a",
"metric",
"from",
"a",
"monitored",
"machine"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L602-L615 |
mistio/mist.client | src/mistclient/model.py | Machine.add_python_plugin | def add_python_plugin(self, name, python_file, value_type="gauge", unit=None):
"""
Add a custom python plugin to the collectd instance of a monitored plugin
:param python_file: Path of the python file to be added as custom python plugin
:param name: Name of the plugin
:param value_type: Optional. Can be either "gauge" or "derive"
:param unit: Optional. If given the new plugin will be measured according to this unit
"""
if not os.path.isfile(python_file):
raise Exception(python_file, "is not a file or could not be found in tho given path")
with open(python_file) as f:
script = f.read()
payload = {
'plugin_type': 'python',
'name': name,
'unit': unit,
'value_type': value_type,
'read_function': script,
'host': self.info['public_ips'][0]
}
data = json.dumps(payload)
#PLugin id must be in lowercase
plugin_id = name.lower()
#PLugin id must contain only alphanumeric chars
pattern = re.compile('\W')
plugin_id = re.sub(pattern, "_", plugin_id)
#Plugin id should not have double underscores
while "__" in plugin_id:
pattern = "\r?__"
plugin_id = re.sub(pattern, "_", plugin_id)
#Plugin id should not have underscore as first or last char
if plugin_id[-1] == "_":
plugin_id = plugin_id[:-2]
if plugin_id[0] == "_":
plugin_id = plugin_id[1:]
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/plugins/"+plugin_id,
data=data)
req.post() | python | def add_python_plugin(self, name, python_file, value_type="gauge", unit=None):
"""
Add a custom python plugin to the collectd instance of a monitored plugin
:param python_file: Path of the python file to be added as custom python plugin
:param name: Name of the plugin
:param value_type: Optional. Can be either "gauge" or "derive"
:param unit: Optional. If given the new plugin will be measured according to this unit
"""
if not os.path.isfile(python_file):
raise Exception(python_file, "is not a file or could not be found in tho given path")
with open(python_file) as f:
script = f.read()
payload = {
'plugin_type': 'python',
'name': name,
'unit': unit,
'value_type': value_type,
'read_function': script,
'host': self.info['public_ips'][0]
}
data = json.dumps(payload)
#PLugin id must be in lowercase
plugin_id = name.lower()
#PLugin id must contain only alphanumeric chars
pattern = re.compile('\W')
plugin_id = re.sub(pattern, "_", plugin_id)
#Plugin id should not have double underscores
while "__" in plugin_id:
pattern = "\r?__"
plugin_id = re.sub(pattern, "_", plugin_id)
#Plugin id should not have underscore as first or last char
if plugin_id[-1] == "_":
plugin_id = plugin_id[:-2]
if plugin_id[0] == "_":
plugin_id = plugin_id[1:]
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/plugins/"+plugin_id,
data=data)
req.post() | [
"def",
"add_python_plugin",
"(",
"self",
",",
"name",
",",
"python_file",
",",
"value_type",
"=",
"\"gauge\"",
",",
"unit",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"python_file",
")",
":",
"raise",
"Exception",
"(",
"... | Add a custom python plugin to the collectd instance of a monitored plugin
:param python_file: Path of the python file to be added as custom python plugin
:param name: Name of the plugin
:param value_type: Optional. Can be either "gauge" or "derive"
:param unit: Optional. If given the new plugin will be measured according to this unit | [
"Add",
"a",
"custom",
"python",
"plugin",
"to",
"the",
"collectd",
"instance",
"of",
"a",
"monitored",
"plugin"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L617-L665 |
mistio/mist.client | src/mistclient/model.py | Key.private | def private(self):
"""
Return the private ssh-key
:returns: The private ssh-key as string
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id+"/private")
private = req.get().json()
return private | python | def private(self):
"""
Return the private ssh-key
:returns: The private ssh-key as string
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id+"/private")
private = req.get().json()
return private | [
"def",
"private",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/keys/'",
"+",
"self",
".",
"id",
"+",
"\"/private\"",
")",
"private",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
... | Return the private ssh-key
:returns: The private ssh-key as string | [
"Return",
"the",
"private",
"ssh",
"-",
"key"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L728-L736 |
mistio/mist.client | src/mistclient/model.py | Key.public | def public(self):
"""
Return the public ssh-key
:returns: The public ssh-key as string
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id+"/public")
public = req.get().json()
return public | python | def public(self):
"""
Return the public ssh-key
:returns: The public ssh-key as string
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id+"/public")
public = req.get().json()
return public | [
"def",
"public",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/keys/'",
"+",
"self",
".",
"id",
"+",
"\"/public\"",
")",
"public",
"=",
"req",
".",
"get",
"(",
")",
".",
"json",
"(... | Return the public ssh-key
:returns: The public ssh-key as string | [
"Return",
"the",
"public",
"ssh",
"-",
"key"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L739-L747 |
mistio/mist.client | src/mistclient/model.py | Key.rename | def rename(self, new_name):
"""
Rename a key
:param new_name: New name for the key (will also serve as the key's id)
:returns: An updated list of added keys
"""
payload = {
'new_name': new_name
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/keys/'+self.id, data=data)
req.put()
self.id = new_name
self.mist_client.update_keys() | python | def rename(self, new_name):
"""
Rename a key
:param new_name: New name for the key (will also serve as the key's id)
:returns: An updated list of added keys
"""
payload = {
'new_name': new_name
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/keys/'+self.id, data=data)
req.put()
self.id = new_name
self.mist_client.update_keys() | [
"def",
"rename",
"(",
"self",
",",
"new_name",
")",
":",
"payload",
"=",
"{",
"'new_name'",
":",
"new_name",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",... | Rename a key
:param new_name: New name for the key (will also serve as the key's id)
:returns: An updated list of added keys | [
"Rename",
"a",
"key"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L749-L763 |
mistio/mist.client | src/mistclient/model.py | Key.set_default | def set_default(self):
"""
Set this key as the default key
:returns: An updated list of added keys
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id)
req.post()
self.is_default = True
self.mist_client.update_keys() | python | def set_default(self):
"""
Set this key as the default key
:returns: An updated list of added keys
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id)
req.post()
self.is_default = True
self.mist_client.update_keys() | [
"def",
"set_default",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/keys/'",
"+",
"self",
".",
"id",
")",
"req",
".",
"post",
"(",
")",
"self",
".",
"is_default",
"=",
"True",
"self"... | Set this key as the default key
:returns: An updated list of added keys | [
"Set",
"this",
"key",
"as",
"the",
"default",
"key"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L765-L774 |
mistio/mist.client | src/mistclient/model.py | Key.delete | def delete(self):
"""
Delete this key from mist.io
:returns: An updated list of added keys
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id)
req.delete()
self.mist_client.update_keys() | python | def delete(self):
"""
Delete this key from mist.io
:returns: An updated list of added keys
"""
req = self.request(self.mist_client.uri+'/keys/'+self.id)
req.delete()
self.mist_client.update_keys() | [
"def",
"delete",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"(",
"self",
".",
"mist_client",
".",
"uri",
"+",
"'/keys/'",
"+",
"self",
".",
"id",
")",
"req",
".",
"delete",
"(",
")",
"self",
".",
"mist_client",
".",
"update_keys",
"... | Delete this key from mist.io
:returns: An updated list of added keys | [
"Delete",
"this",
"key",
"from",
"mist",
".",
"io"
] | train | https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L776-L784 |
AutomatedTester/Bugsy | bugsy/bug.py | Bug.status | def status(self, value):
"""
Property for getting or setting the bug status
>>> bug.status = "REOPENED"
"""
if self._bug.get('id', None):
if value in VALID_STATUS:
self._bug['status'] = value
else:
raise BugException("Invalid status type was used")
else:
raise BugException("Can not set status unless there is a bug id."
" Please call Update() before setting") | python | def status(self, value):
"""
Property for getting or setting the bug status
>>> bug.status = "REOPENED"
"""
if self._bug.get('id', None):
if value in VALID_STATUS:
self._bug['status'] = value
else:
raise BugException("Invalid status type was used")
else:
raise BugException("Can not set status unless there is a bug id."
" Please call Update() before setting") | [
"def",
"status",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_bug",
".",
"get",
"(",
"'id'",
",",
"None",
")",
":",
"if",
"value",
"in",
"VALID_STATUS",
":",
"self",
".",
"_bug",
"[",
"'status'",
"]",
"=",
"value",
"else",
":",
"rais... | Property for getting or setting the bug status
>>> bug.status = "REOPENED" | [
"Property",
"for",
"getting",
"or",
"setting",
"the",
"bug",
"status"
] | train | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L74-L87 |
AutomatedTester/Bugsy | bugsy/bug.py | Bug.update | def update(self):
"""
Update this object with the latest changes from Bugzilla
>>> bug.status
'NEW'
#Changes happen on Bugzilla
>>> bug.update()
>>> bug.status
'FIXED'
"""
if 'id' in self._bug:
result = self._bugsy.request('bug/%s' % self._bug['id'])
self._bug = dict(**result['bugs'][0])
else:
raise BugException("Unable to update bug that isn't in Bugzilla") | python | def update(self):
"""
Update this object with the latest changes from Bugzilla
>>> bug.status
'NEW'
#Changes happen on Bugzilla
>>> bug.update()
>>> bug.status
'FIXED'
"""
if 'id' in self._bug:
result = self._bugsy.request('bug/%s' % self._bug['id'])
self._bug = dict(**result['bugs'][0])
else:
raise BugException("Unable to update bug that isn't in Bugzilla") | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"'id'",
"in",
"self",
".",
"_bug",
":",
"result",
"=",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/%s'",
"%",
"self",
".",
"_bug",
"[",
"'id'",
"]",
")",
"self",
".",
"_bug",
"=",
"dict",
"(",
... | Update this object with the latest changes from Bugzilla
>>> bug.status
'NEW'
#Changes happen on Bugzilla
>>> bug.update()
>>> bug.status
'FIXED' | [
"Update",
"this",
"object",
"with",
"the",
"latest",
"changes",
"from",
"Bugzilla"
] | train | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L365-L380 |
AutomatedTester/Bugsy | bugsy/bug.py | Bug.get_comments | def get_comments(self):
"""
Obtain comments for this bug.
Returns a list of Comment instances.
"""
bug = str(self._bug['id'])
res = self._bugsy.request('bug/%s/comment' % bug)
return [Comment(bugsy=self._bugsy, **comments) for comments
in res['bugs'][bug]['comments']] | python | def get_comments(self):
"""
Obtain comments for this bug.
Returns a list of Comment instances.
"""
bug = str(self._bug['id'])
res = self._bugsy.request('bug/%s/comment' % bug)
return [Comment(bugsy=self._bugsy, **comments) for comments
in res['bugs'][bug]['comments']] | [
"def",
"get_comments",
"(",
"self",
")",
":",
"bug",
"=",
"str",
"(",
"self",
".",
"_bug",
"[",
"'id'",
"]",
")",
"res",
"=",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/%s/comment'",
"%",
"bug",
")",
"return",
"[",
"Comment",
"(",
"bugsy",
"... | Obtain comments for this bug.
Returns a list of Comment instances. | [
"Obtain",
"comments",
"for",
"this",
"bug",
"."
] | train | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L382-L392 |
AutomatedTester/Bugsy | bugsy/bug.py | Bug.add_comment | def add_comment(self, comment):
"""
Adds a comment to a bug. If the bug object does not have a bug ID
(ie you are creating a bug) then you will need to also call `put`
on the :class:`Bugsy` class.
>>> bug.add_comment("I like sausages")
>>> bugzilla.put(bug)
If it does have a bug id then this will immediately post to the server
>>> bug.add_comment("I like eggs too")
More examples can be found at:
https://github.com/AutomatedTester/Bugsy/blob/master/example/add_comments.py
"""
# If we have a key post immediately otherwise hold onto it until
# put(bug) is called
if 'id' in self._bug:
self._bugsy.request('bug/{}/comment'.format(self._bug['id']),
method='POST', json={"comment": comment}
)
else:
self._bug['comment'] = comment | python | def add_comment(self, comment):
"""
Adds a comment to a bug. If the bug object does not have a bug ID
(ie you are creating a bug) then you will need to also call `put`
on the :class:`Bugsy` class.
>>> bug.add_comment("I like sausages")
>>> bugzilla.put(bug)
If it does have a bug id then this will immediately post to the server
>>> bug.add_comment("I like eggs too")
More examples can be found at:
https://github.com/AutomatedTester/Bugsy/blob/master/example/add_comments.py
"""
# If we have a key post immediately otherwise hold onto it until
# put(bug) is called
if 'id' in self._bug:
self._bugsy.request('bug/{}/comment'.format(self._bug['id']),
method='POST', json={"comment": comment}
)
else:
self._bug['comment'] = comment | [
"def",
"add_comment",
"(",
"self",
",",
"comment",
")",
":",
"# If we have a key post immediately otherwise hold onto it until",
"# put(bug) is called",
"if",
"'id'",
"in",
"self",
".",
"_bug",
":",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/{}/comment'",
".",
... | Adds a comment to a bug. If the bug object does not have a bug ID
(ie you are creating a bug) then you will need to also call `put`
on the :class:`Bugsy` class.
>>> bug.add_comment("I like sausages")
>>> bugzilla.put(bug)
If it does have a bug id then this will immediately post to the server
>>> bug.add_comment("I like eggs too")
More examples can be found at:
https://github.com/AutomatedTester/Bugsy/blob/master/example/add_comments.py | [
"Adds",
"a",
"comment",
"to",
"a",
"bug",
".",
"If",
"the",
"bug",
"object",
"does",
"not",
"have",
"a",
"bug",
"ID",
"(",
"ie",
"you",
"are",
"creating",
"a",
"bug",
")",
"then",
"you",
"will",
"need",
"to",
"also",
"call",
"put",
"on",
"the",
"... | train | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L394-L417 |
AutomatedTester/Bugsy | bugsy/bug.py | Comment.add_tags | def add_tags(self, tags):
"""
Add tags to the comments
"""
if not isinstance(tags, list):
tags = [tags]
self._bugsy.request('bug/comment/%s/tags' % self._comment['id'],
method='PUT', json={"add": tags}) | python | def add_tags(self, tags):
"""
Add tags to the comments
"""
if not isinstance(tags, list):
tags = [tags]
self._bugsy.request('bug/comment/%s/tags' % self._comment['id'],
method='PUT', json={"add": tags}) | [
"def",
"add_tags",
"(",
"self",
",",
"tags",
")",
":",
"if",
"not",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/comment/%s/tags'",
"%",
"self",
".",
"_comment",
"[... | Add tags to the comments | [
"Add",
"tags",
"to",
"the",
"comments"
] | train | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L548-L555 |
flying-sheep/bcode | bcoding.py | _readuntil | def _readuntil(f, end=_TYPE_END):
"""Helper function to read bytes until a certain end byte is hit"""
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
buf += byte
byte = f.read(1)
return buf | python | def _readuntil(f, end=_TYPE_END):
"""Helper function to read bytes until a certain end byte is hit"""
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
buf += byte
byte = f.read(1)
return buf | [
"def",
"_readuntil",
"(",
"f",
",",
"end",
"=",
"_TYPE_END",
")",
":",
"buf",
"=",
"bytearray",
"(",
")",
"byte",
"=",
"f",
".",
"read",
"(",
"1",
")",
"while",
"byte",
"!=",
"end",
":",
"if",
"byte",
"==",
"b''",
":",
"raise",
"ValueError",
"(",... | Helper function to read bytes until a certain end byte is hit | [
"Helper",
"function",
"to",
"read",
"bytes",
"until",
"a",
"certain",
"end",
"byte",
"is",
"hit"
] | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L41-L50 |
flying-sheep/bcode | bcoding.py | _decode_buffer | def _decode_buffer(f):
"""
String types are normal (byte)strings
starting with an integer followed by ':'
which designates the string’s length.
Since there’s no way to specify the byte type
in bencoded files, we have to guess
"""
strlen = int(_readuntil(f, _TYPE_SEP))
buf = f.read(strlen)
if not len(buf) == strlen:
raise ValueError(
'string expected to be {} bytes long but the file ended after {} bytes'
.format(strlen, len(buf)))
try:
return buf.decode()
except UnicodeDecodeError:
return buf | python | def _decode_buffer(f):
"""
String types are normal (byte)strings
starting with an integer followed by ':'
which designates the string’s length.
Since there’s no way to specify the byte type
in bencoded files, we have to guess
"""
strlen = int(_readuntil(f, _TYPE_SEP))
buf = f.read(strlen)
if not len(buf) == strlen:
raise ValueError(
'string expected to be {} bytes long but the file ended after {} bytes'
.format(strlen, len(buf)))
try:
return buf.decode()
except UnicodeDecodeError:
return buf | [
"def",
"_decode_buffer",
"(",
"f",
")",
":",
"strlen",
"=",
"int",
"(",
"_readuntil",
"(",
"f",
",",
"_TYPE_SEP",
")",
")",
"buf",
"=",
"f",
".",
"read",
"(",
"strlen",
")",
"if",
"not",
"len",
"(",
"buf",
")",
"==",
"strlen",
":",
"raise",
"Valu... | String types are normal (byte)strings
starting with an integer followed by ':'
which designates the string’s length.
Since there’s no way to specify the byte type
in bencoded files, we have to guess | [
"String",
"types",
"are",
"normal",
"(",
"byte",
")",
"strings",
"starting",
"with",
"an",
"integer",
"followed",
"by",
":",
"which",
"designates",
"the",
"string’s",
"length",
".",
"Since",
"there’s",
"no",
"way",
"to",
"specify",
"the",
"byte",
"type",
"... | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L60-L78 |
flying-sheep/bcode | bcoding.py | bdecode | def bdecode(f_or_data):
"""
bdecodes data by looking up the type byte,
and using it to look up the respective decoding function,
which in turn is used to return the decoded object
The parameter can be a file opened in bytes mode,
bytes or a string (the last of which will be decoded)
"""
if isinstance(f_or_data, str):
f_or_data = f_or_data.encode()
if isinstance(f_or_data, bytes):
f_or_data = BytesIO(f_or_data)
#TODO: the following line is the only one that needs readahead.
#peek returns a arbitrary amount of bytes, so we have to slice.
if f_or_data.seekable():
first_byte = f_or_data.read(1)
f_or_data.seek(-1, SEEK_CUR)
else:
first_byte = f_or_data.peek(1)[:1]
btype = TYPES.get(first_byte)
if btype is not None:
return btype(f_or_data)
else: #Used in dicts and lists to designate an end
assert_btype(f_or_data.read(1), _TYPE_END)
return None | python | def bdecode(f_or_data):
"""
bdecodes data by looking up the type byte,
and using it to look up the respective decoding function,
which in turn is used to return the decoded object
The parameter can be a file opened in bytes mode,
bytes or a string (the last of which will be decoded)
"""
if isinstance(f_or_data, str):
f_or_data = f_or_data.encode()
if isinstance(f_or_data, bytes):
f_or_data = BytesIO(f_or_data)
#TODO: the following line is the only one that needs readahead.
#peek returns a arbitrary amount of bytes, so we have to slice.
if f_or_data.seekable():
first_byte = f_or_data.read(1)
f_or_data.seek(-1, SEEK_CUR)
else:
first_byte = f_or_data.peek(1)[:1]
btype = TYPES.get(first_byte)
if btype is not None:
return btype(f_or_data)
else: #Used in dicts and lists to designate an end
assert_btype(f_or_data.read(1), _TYPE_END)
return None | [
"def",
"bdecode",
"(",
"f_or_data",
")",
":",
"if",
"isinstance",
"(",
"f_or_data",
",",
"str",
")",
":",
"f_or_data",
"=",
"f_or_data",
".",
"encode",
"(",
")",
"if",
"isinstance",
"(",
"f_or_data",
",",
"bytes",
")",
":",
"f_or_data",
"=",
"BytesIO",
... | bdecodes data by looking up the type byte,
and using it to look up the respective decoding function,
which in turn is used to return the decoded object
The parameter can be a file opened in bytes mode,
bytes or a string (the last of which will be decoded) | [
"bdecodes",
"data",
"by",
"looking",
"up",
"the",
"type",
"byte",
"and",
"using",
"it",
"to",
"look",
"up",
"the",
"respective",
"decoding",
"function",
"which",
"in",
"turn",
"is",
"used",
"to",
"return",
"the",
"decoded",
"object",
"The",
"parameter",
"c... | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L108-L134 |
flying-sheep/bcode | bcoding.py | _encode_buffer | def _encode_buffer(string, f):
"""Writes the bencoded form of the input string or bytes"""
if isinstance(string, str):
string = string.encode()
f.write(str(len(string)).encode())
f.write(_TYPE_SEP)
f.write(string) | python | def _encode_buffer(string, f):
"""Writes the bencoded form of the input string or bytes"""
if isinstance(string, str):
string = string.encode()
f.write(str(len(string)).encode())
f.write(_TYPE_SEP)
f.write(string) | [
"def",
"_encode_buffer",
"(",
"string",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"string",
"=",
"string",
".",
"encode",
"(",
")",
"f",
".",
"write",
"(",
"str",
"(",
"len",
"(",
"string",
")",
")",
".",
"encod... | Writes the bencoded form of the input string or bytes | [
"Writes",
"the",
"bencoded",
"form",
"of",
"the",
"input",
"string",
"or",
"bytes"
] | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L145-L151 |
flying-sheep/bcode | bcoding.py | _encode_mapping | def _encode_mapping(mapping, f):
"""Encodes the mapping items in lexical order (spec)"""
f.write(_TYPE_DICT)
for key, value in sorted(mapping.items()):
_encode_buffer(key, f)
bencode(value, f)
f.write(_TYPE_END) | python | def _encode_mapping(mapping, f):
"""Encodes the mapping items in lexical order (spec)"""
f.write(_TYPE_DICT)
for key, value in sorted(mapping.items()):
_encode_buffer(key, f)
bencode(value, f)
f.write(_TYPE_END) | [
"def",
"_encode_mapping",
"(",
"mapping",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"_TYPE_DICT",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"mapping",
".",
"items",
"(",
")",
")",
":",
"_encode_buffer",
"(",
"key",
",",
"f",
")",
"ben... | Encodes the mapping items in lexical order (spec) | [
"Encodes",
"the",
"mapping",
"items",
"in",
"lexical",
"order",
"(",
"spec",
")"
] | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L159-L165 |
flying-sheep/bcode | bcoding.py | bencode | def bencode(data, f=None):
"""
Writes a serializable data piece to f
The order of tests is nonarbitrary,
as strings and mappings are iterable.
If f is None, it writes to a byte buffer
and returns a bytestring
"""
if f is None:
f = BytesIO()
_bencode_to_file(data, f)
return f.getvalue()
else:
_bencode_to_file(data, f) | python | def bencode(data, f=None):
"""
Writes a serializable data piece to f
The order of tests is nonarbitrary,
as strings and mappings are iterable.
If f is None, it writes to a byte buffer
and returns a bytestring
"""
if f is None:
f = BytesIO()
_bencode_to_file(data, f)
return f.getvalue()
else:
_bencode_to_file(data, f) | [
"def",
"bencode",
"(",
"data",
",",
"f",
"=",
"None",
")",
":",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"BytesIO",
"(",
")",
"_bencode_to_file",
"(",
"data",
",",
"f",
")",
"return",
"f",
".",
"getvalue",
"(",
")",
"else",
":",
"_bencode_to_file",
... | Writes a serializable data piece to f
The order of tests is nonarbitrary,
as strings and mappings are iterable.
If f is None, it writes to a byte buffer
and returns a bytestring | [
"Writes",
"a",
"serializable",
"data",
"piece",
"to",
"f",
"The",
"order",
"of",
"tests",
"is",
"nonarbitrary",
"as",
"strings",
"and",
"mappings",
"are",
"iterable",
".",
"If",
"f",
"is",
"None",
"it",
"writes",
"to",
"a",
"byte",
"buffer",
"and",
"retu... | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L181-L195 |
flying-sheep/bcode | bcoding.py | main | def main(args=None):
"""Decodes bencoded files to python syntax (like JSON, but with bytes support)"""
import sys, pprint
from argparse import ArgumentParser, FileType
parser = ArgumentParser(description=main.__doc__)
parser.add_argument('infile', nargs='?', type=FileType('rb'), default=sys.stdin.buffer,
help='bencoded file (e.g. torrent) [Default: stdin]')
parser.add_argument('outfile', nargs='?', type=FileType('w'), default=sys.stdout,
help='python-syntax serialization [Default: stdout]')
args = parser.parse_args(args)
data = bdecode(args.infile)
pprint.pprint(data, stream=args.outfile) | python | def main(args=None):
"""Decodes bencoded files to python syntax (like JSON, but with bytes support)"""
import sys, pprint
from argparse import ArgumentParser, FileType
parser = ArgumentParser(description=main.__doc__)
parser.add_argument('infile', nargs='?', type=FileType('rb'), default=sys.stdin.buffer,
help='bencoded file (e.g. torrent) [Default: stdin]')
parser.add_argument('outfile', nargs='?', type=FileType('w'), default=sys.stdout,
help='python-syntax serialization [Default: stdout]')
args = parser.parse_args(args)
data = bdecode(args.infile)
pprint.pprint(data, stream=args.outfile) | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"import",
"sys",
",",
"pprint",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"FileType",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_a... | Decodes bencoded files to python syntax (like JSON, but with bytes support) | [
"Decodes",
"bencoded",
"files",
"to",
"python",
"syntax",
"(",
"like",
"JSON",
"but",
"with",
"bytes",
"support",
")"
] | train | https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L197-L209 |
darkfeline/animanager | animanager/commands/watch.py | command | def command(state, args):
"""Watch an anime."""
if len(args) < 2:
print(f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]')
return
aid = state.results.parse_aid(args[1], default_key='db')
anime = query.select.lookup(state.db, aid)
if len(args) < 3:
episode = anime.watched_episodes + 1
else:
episode = int(args[2])
anime_files = query.files.get_files(state.db, aid)
files = anime_files[episode]
if not files:
print('No files.')
return
file = state.file_picker.pick(files)
ret = subprocess.call(state.config['anime'].getargs('player') + [file])
if ret == 0 and episode == anime.watched_episodes + 1:
user_input = input('Bump? [Yn]')
if user_input.lower() in ('n', 'no'):
print('Not bumped.')
else:
query.update.bump(state.db, aid)
print('Bumped.') | python | def command(state, args):
"""Watch an anime."""
if len(args) < 2:
print(f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]')
return
aid = state.results.parse_aid(args[1], default_key='db')
anime = query.select.lookup(state.db, aid)
if len(args) < 3:
episode = anime.watched_episodes + 1
else:
episode = int(args[2])
anime_files = query.files.get_files(state.db, aid)
files = anime_files[episode]
if not files:
print('No files.')
return
file = state.file_picker.pick(files)
ret = subprocess.call(state.config['anime'].getargs('player') + [file])
if ret == 0 and episode == anime.watched_episodes + 1:
user_input = input('Bump? [Yn]')
if user_input.lower() in ('n', 'no'):
print('Not bumped.')
else:
query.update.bump(state.db, aid)
print('Bumped.') | [
"def",
"command",
"(",
"state",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"print",
"(",
"f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]'",
")",
"return",
"aid",
"=",
"state",
".",
"results",
".",
"parse_aid",
"(",
"args",
"[",
"1"... | Watch an anime. | [
"Watch",
"an",
"anime",
"."
] | train | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/commands/watch.py#L23-L49 |
seppo0010/rlite-py | hirlite/patch_conn.py | patch_connection | def patch_connection(filename=':memory:'):
"""
``filename``: rlite filename to store db in, or memory
Patch the redis-py Connection and the
static from_url() of Redis and StrictRedis to use RliteConnection
"""
if no_redis:
raise Exception("redis package not found, please install redis-py via 'pip install redis'")
RliteConnection.set_file(filename)
global orig_classes
# already patched
if orig_classes:
return
orig_classes = (redis.connection.Connection,
redis.connection.ConnectionPool)
_set_classes(RliteConnection, RliteConnectionPool) | python | def patch_connection(filename=':memory:'):
"""
``filename``: rlite filename to store db in, or memory
Patch the redis-py Connection and the
static from_url() of Redis and StrictRedis to use RliteConnection
"""
if no_redis:
raise Exception("redis package not found, please install redis-py via 'pip install redis'")
RliteConnection.set_file(filename)
global orig_classes
# already patched
if orig_classes:
return
orig_classes = (redis.connection.Connection,
redis.connection.ConnectionPool)
_set_classes(RliteConnection, RliteConnectionPool) | [
"def",
"patch_connection",
"(",
"filename",
"=",
"':memory:'",
")",
":",
"if",
"no_redis",
":",
"raise",
"Exception",
"(",
"\"redis package not found, please install redis-py via 'pip install redis'\"",
")",
"RliteConnection",
".",
"set_file",
"(",
"filename",
")",
"globa... | ``filename``: rlite filename to store db in, or memory
Patch the redis-py Connection and the
static from_url() of Redis and StrictRedis to use RliteConnection | [
"filename",
":",
"rlite",
"filename",
"to",
"store",
"db",
"in",
"or",
"memory",
"Patch",
"the",
"redis",
"-",
"py",
"Connection",
"and",
"the",
"static",
"from_url",
"()",
"of",
"Redis",
"and",
"StrictRedis",
"to",
"use",
"RliteConnection"
] | train | https://github.com/seppo0010/rlite-py/blob/298a6780fb5c32081b14b60b3b1595ecf5ccdce7/hirlite/patch_conn.py#L104-L125 |
rdireen/spherepy | spherepy/ops.py | fix_even_row_data_fc | def fix_even_row_data_fc(fdata):
"""When the number of rows in fdata is even, there is a subtlety that must
be taken care of if fdata is to satisfy the symmetry required for further
processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1]
this routine simply sets the row corresponding to the -3 index equal to
zero. It is an unfortunate subtlety, but not taking care of this has
resulted in answers that are not double precision. This operation should
be applied before any other operators are applied to fdata."""
L = fdata.shape[0]
if np.mod(L, 2) == 0:
fdata[int(L / 2), :] = 0 | python | def fix_even_row_data_fc(fdata):
"""When the number of rows in fdata is even, there is a subtlety that must
be taken care of if fdata is to satisfy the symmetry required for further
processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1]
this routine simply sets the row corresponding to the -3 index equal to
zero. It is an unfortunate subtlety, but not taking care of this has
resulted in answers that are not double precision. This operation should
be applied before any other operators are applied to fdata."""
L = fdata.shape[0]
if np.mod(L, 2) == 0:
fdata[int(L / 2), :] = 0 | [
"def",
"fix_even_row_data_fc",
"(",
"fdata",
")",
":",
"L",
"=",
"fdata",
".",
"shape",
"[",
"0",
"]",
"if",
"np",
".",
"mod",
"(",
"L",
",",
"2",
")",
"==",
"0",
":",
"fdata",
"[",
"int",
"(",
"L",
"/",
"2",
")",
",",
":",
"]",
"=",
"0"
] | When the number of rows in fdata is even, there is a subtlety that must
be taken care of if fdata is to satisfy the symmetry required for further
processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1]
this routine simply sets the row corresponding to the -3 index equal to
zero. It is an unfortunate subtlety, but not taking care of this has
resulted in answers that are not double precision. This operation should
be applied before any other operators are applied to fdata. | [
"When",
"the",
"number",
"of",
"rows",
"in",
"fdata",
"is",
"even",
"there",
"is",
"a",
"subtlety",
"that",
"must",
"be",
"taken",
"care",
"of",
"if",
"fdata",
"is",
"to",
"satisfy",
"the",
"symmetry",
"required",
"for",
"further",
"processing",
".",
"Fo... | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L55-L66 |
rdireen/spherepy | spherepy/ops.py | sin_fc | def sin_fc(fdata):
"""Apply sine in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
M = nrows / 2
fdata[int(M - 1), :] = 0
fdata[int(M + 1), :] = 0
work1 = np.zeros([nrows, ncols], dtype=np.complex128)
work2 = np.zeros([nrows, ncols], dtype=np.complex128)
work1[0, :] = fdata[-1, :]
work1[1:, :] = fdata[0:-1, :]
work2[0:-1] = fdata[1:, :]
work2[-1, :] = fdata[0, :]
fdata[:, :] = 1.0 / (2 * 1j) * (work1 - work2) | python | def sin_fc(fdata):
"""Apply sine in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
M = nrows / 2
fdata[int(M - 1), :] = 0
fdata[int(M + 1), :] = 0
work1 = np.zeros([nrows, ncols], dtype=np.complex128)
work2 = np.zeros([nrows, ncols], dtype=np.complex128)
work1[0, :] = fdata[-1, :]
work1[1:, :] = fdata[0:-1, :]
work2[0:-1] = fdata[1:, :]
work2[-1, :] = fdata[0, :]
fdata[:, :] = 1.0 / (2 * 1j) * (work1 - work2) | [
"def",
"sin_fc",
"(",
"fdata",
")",
":",
"nrows",
"=",
"fdata",
".",
"shape",
"[",
"0",
"]",
"ncols",
"=",
"fdata",
".",
"shape",
"[",
"1",
"]",
"M",
"=",
"nrows",
"/",
"2",
"fdata",
"[",
"int",
"(",
"M",
"-",
"1",
")",
",",
":",
"]",
"=",
... | Apply sine in the Fourier domain. | [
"Apply",
"sine",
"in",
"the",
"Fourier",
"domain",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L83-L102 |
rdireen/spherepy | spherepy/ops.py | divsin_fc | def divsin_fc(fdata):
"""Apply divide by sine in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
L = int(nrows / 2) # Assuming nrows is even, which it should be.
L2 = L - 2 # This is the last index in the recursion for division by sine.
g = np.zeros([nrows, ncols], dtype=np.complex128)
g[L2, :] = 2 * 1j * fdata[L - 1, :]
for k in xrange(L2, -L2, -1):
g[k - 1, :] = 2 * 1j * fdata[k, :] + g[k + 1, :]
fdata[:, :] = g | python | def divsin_fc(fdata):
"""Apply divide by sine in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
L = int(nrows / 2) # Assuming nrows is even, which it should be.
L2 = L - 2 # This is the last index in the recursion for division by sine.
g = np.zeros([nrows, ncols], dtype=np.complex128)
g[L2, :] = 2 * 1j * fdata[L - 1, :]
for k in xrange(L2, -L2, -1):
g[k - 1, :] = 2 * 1j * fdata[k, :] + g[k + 1, :]
fdata[:, :] = g | [
"def",
"divsin_fc",
"(",
"fdata",
")",
":",
"nrows",
"=",
"fdata",
".",
"shape",
"[",
"0",
"]",
"ncols",
"=",
"fdata",
".",
"shape",
"[",
"1",
"]",
"L",
"=",
"int",
"(",
"nrows",
"/",
"2",
")",
"# Assuming nrows is even, which it should be.",
"L2",
"="... | Apply divide by sine in the Fourier domain. | [
"Apply",
"divide",
"by",
"sine",
"in",
"the",
"Fourier",
"domain",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L104-L119 |
rdireen/spherepy | spherepy/ops.py | dphi_fc | def dphi_fc(fdata):
"""Apply phi derivative in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
B = int(ncols / 2) # As always, we assume nrows and ncols are even
a = list(range(0, int(B)))
ap = list(range(-int(B), 0))
a.extend(ap)
dphi = np.zeros([nrows, ncols], np.complex128)
for k in xrange(0, nrows):
dphi[k, :] = a
fdata[:, :] = 1j * dphi * fdata | python | def dphi_fc(fdata):
"""Apply phi derivative in the Fourier domain."""
nrows = fdata.shape[0]
ncols = fdata.shape[1]
B = int(ncols / 2) # As always, we assume nrows and ncols are even
a = list(range(0, int(B)))
ap = list(range(-int(B), 0))
a.extend(ap)
dphi = np.zeros([nrows, ncols], np.complex128)
for k in xrange(0, nrows):
dphi[k, :] = a
fdata[:, :] = 1j * dphi * fdata | [
"def",
"dphi_fc",
"(",
"fdata",
")",
":",
"nrows",
"=",
"fdata",
".",
"shape",
"[",
"0",
"]",
"ncols",
"=",
"fdata",
".",
"shape",
"[",
"1",
"]",
"B",
"=",
"int",
"(",
"ncols",
"/",
"2",
")",
"# As always, we assume nrows and ncols are even",
"a",
"=",... | Apply phi derivative in the Fourier domain. | [
"Apply",
"phi",
"derivative",
"in",
"the",
"Fourier",
"domain",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L140-L157 |
rdireen/spherepy | spherepy/ops.py | sinLdot_fc | def sinLdot_fc(tfdata, pfdata):
"""Apply sin of theta times the L operator to the data in the Fourier
domain."""
dphi_fc(tfdata)
sin_fc(pfdata)
dtheta_fc(pfdata)
return 1j * (tfdata - pfdata) | python | def sinLdot_fc(tfdata, pfdata):
"""Apply sin of theta times the L operator to the data in the Fourier
domain."""
dphi_fc(tfdata)
sin_fc(pfdata)
dtheta_fc(pfdata)
return 1j * (tfdata - pfdata) | [
"def",
"sinLdot_fc",
"(",
"tfdata",
",",
"pfdata",
")",
":",
"dphi_fc",
"(",
"tfdata",
")",
"sin_fc",
"(",
"pfdata",
")",
"dtheta_fc",
"(",
"pfdata",
")",
"return",
"1j",
"*",
"(",
"tfdata",
"-",
"pfdata",
")"
] | Apply sin of theta times the L operator to the data in the Fourier
domain. | [
"Apply",
"sin",
"of",
"theta",
"times",
"the",
"L",
"operator",
"to",
"the",
"data",
"in",
"the",
"Fourier",
"domain",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L159-L168 |
rdireen/spherepy | spherepy/ops.py | L_fc | def L_fc(fdata):
"""Apply L in the Fourier domain."""
fd = np.copy(fdata)
dphi_fc(fdata)
divsin_fc(fdata)
dtheta_fc(fd)
return (1j * fdata, -1j * fd) | python | def L_fc(fdata):
"""Apply L in the Fourier domain."""
fd = np.copy(fdata)
dphi_fc(fdata)
divsin_fc(fdata)
dtheta_fc(fd)
return (1j * fdata, -1j * fd) | [
"def",
"L_fc",
"(",
"fdata",
")",
":",
"fd",
"=",
"np",
".",
"copy",
"(",
"fdata",
")",
"dphi_fc",
"(",
"fdata",
")",
"divsin_fc",
"(",
"fdata",
")",
"dtheta_fc",
"(",
"fd",
")",
"return",
"(",
"1j",
"*",
"fdata",
",",
"-",
"1j",
"*",
"fd",
")"... | Apply L in the Fourier domain. | [
"Apply",
"L",
"in",
"the",
"Fourier",
"domain",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L170-L180 |
mediawiki-utilities/python-mwcites | mwcites/utilities/extract.py | extract | def extract(dump_files, extractors=ALL_EXTRACTORS):
"""
Extracts cites from a set of `dump_files`.
:Parameters:
dump_files : str | `file`
A set of files MediaWiki XML dump files
(expects: pages-meta-history)
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites
"""
# Dump processor function
def process_dump(dump, path):
for page in dump:
if page.namespace != 0: continue
else:
for cite in extract_cite_history(page, extractors):
yield cite
# Map call
return mwxml.map(process_dump, dump_files) | python | def extract(dump_files, extractors=ALL_EXTRACTORS):
"""
Extracts cites from a set of `dump_files`.
:Parameters:
dump_files : str | `file`
A set of files MediaWiki XML dump files
(expects: pages-meta-history)
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites
"""
# Dump processor function
def process_dump(dump, path):
for page in dump:
if page.namespace != 0: continue
else:
for cite in extract_cite_history(page, extractors):
yield cite
# Map call
return mwxml.map(process_dump, dump_files) | [
"def",
"extract",
"(",
"dump_files",
",",
"extractors",
"=",
"ALL_EXTRACTORS",
")",
":",
"# Dump processor function",
"def",
"process_dump",
"(",
"dump",
",",
"path",
")",
":",
"for",
"page",
"in",
"dump",
":",
"if",
"page",
".",
"namespace",
"!=",
"0",
":... | Extracts cites from a set of `dump_files`.
:Parameters:
dump_files : str | `file`
A set of files MediaWiki XML dump files
(expects: pages-meta-history)
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites | [
"Extracts",
"cites",
"from",
"a",
"set",
"of",
"dump_files",
"."
] | train | https://github.com/mediawiki-utilities/python-mwcites/blob/2adf4b669cdbeef7d2a0ef168dd7fc26fadb6922/mwcites/utilities/extract.py#L70-L94 |
mediawiki-utilities/python-mwcites | mwcites/utilities/extract.py | extract_cite_history | def extract_cite_history(page, extractors):
"""
Extracts cites from the history of a `page` (`mwxml.Page`).
:Parameters:
page : `iterable`(`mwxml.Revision`)
The page to extract cites from
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites
"""
appearances = {} # For tracking the first appearance of an ID
ids = set() # For holding onto the ids in the last revision.
for revision in page:
ids = set(extract_ids(revision.text, extractors))
# For each ID, check to see if we have seen it before
for id in ids:
if id not in appearances:
appearances[id] = (revision.id, revision.timestamp)
for id in ids: #For the ids in the last version of the page
rev_id, timestamp = appearances[id]
yield (page.id, page.title, rev_id, timestamp, id.type, id.id) | python | def extract_cite_history(page, extractors):
"""
Extracts cites from the history of a `page` (`mwxml.Page`).
:Parameters:
page : `iterable`(`mwxml.Revision`)
The page to extract cites from
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites
"""
appearances = {} # For tracking the first appearance of an ID
ids = set() # For holding onto the ids in the last revision.
for revision in page:
ids = set(extract_ids(revision.text, extractors))
# For each ID, check to see if we have seen it before
for id in ids:
if id not in appearances:
appearances[id] = (revision.id, revision.timestamp)
for id in ids: #For the ids in the last version of the page
rev_id, timestamp = appearances[id]
yield (page.id, page.title, rev_id, timestamp, id.type, id.id) | [
"def",
"extract_cite_history",
"(",
"page",
",",
"extractors",
")",
":",
"appearances",
"=",
"{",
"}",
"# For tracking the first appearance of an ID",
"ids",
"=",
"set",
"(",
")",
"# For holding onto the ids in the last revision.",
"for",
"revision",
"in",
"page",
":",
... | Extracts cites from the history of a `page` (`mwxml.Page`).
:Parameters:
page : `iterable`(`mwxml.Revision`)
The page to extract cites from
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted cites | [
"Extracts",
"cites",
"from",
"the",
"history",
"of",
"a",
"page",
"(",
"mwxml",
".",
"Page",
")",
"."
] | train | https://github.com/mediawiki-utilities/python-mwcites/blob/2adf4b669cdbeef7d2a0ef168dd7fc26fadb6922/mwcites/utilities/extract.py#L96-L122 |
mediawiki-utilities/python-mwcites | mwcites/utilities/extract.py | extract_ids | def extract_ids(text, extractors):
"""
Uses `extractors` to extract citation identifiers from a text.
:Parameters:
text : str
The text to process
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted identifiers
"""
for extractor in extractors:
for id in extractor.extract(text):
yield id | python | def extract_ids(text, extractors):
"""
Uses `extractors` to extract citation identifiers from a text.
:Parameters:
text : str
The text to process
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted identifiers
"""
for extractor in extractors:
for id in extractor.extract(text):
yield id | [
"def",
"extract_ids",
"(",
"text",
",",
"extractors",
")",
":",
"for",
"extractor",
"in",
"extractors",
":",
"for",
"id",
"in",
"extractor",
".",
"extract",
"(",
"text",
")",
":",
"yield",
"id"
] | Uses `extractors` to extract citation identifiers from a text.
:Parameters:
text : str
The text to process
extractors : `list`(`extractor`)
A list of extractors to apply to the text
:Returns:
`iterable` -- a generator of extracted identifiers | [
"Uses",
"extractors",
"to",
"extract",
"citation",
"identifiers",
"from",
"a",
"text",
"."
] | train | https://github.com/mediawiki-utilities/python-mwcites/blob/2adf4b669cdbeef7d2a0ef168dd7fc26fadb6922/mwcites/utilities/extract.py#L124-L139 |
gbiggs/rtctree | rtctree/component.py | Component.add_members | def add_members(self, rtcs):
'''Add other RT Components to this composite component as members.
This component must be a composite component.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
for rtc in rtcs:
if self.is_member(rtc):
raise exceptions.AlreadyInCompositionError(self.name, rtc.instance_name)
org = self.organisations[0].obj
org.add_members([x.object for x in rtcs])
# Force a reparse of the member information
self._orgs = [] | python | def add_members(self, rtcs):
'''Add other RT Components to this composite component as members.
This component must be a composite component.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
for rtc in rtcs:
if self.is_member(rtc):
raise exceptions.AlreadyInCompositionError(self.name, rtc.instance_name)
org = self.organisations[0].obj
org.add_members([x.object for x in rtcs])
# Force a reparse of the member information
self._orgs = [] | [
"def",
"add_members",
"(",
"self",
",",
"rtcs",
")",
":",
"if",
"not",
"self",
".",
"is_composite",
":",
"raise",
"exceptions",
".",
"NotCompositeError",
"(",
"self",
".",
"name",
")",
"for",
"rtc",
"in",
"rtcs",
":",
"if",
"self",
".",
"is_member",
"(... | Add other RT Components to this composite component as members.
This component must be a composite component. | [
"Add",
"other",
"RT",
"Components",
"to",
"this",
"composite",
"component",
"as",
"members",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L352-L366 |
gbiggs/rtctree | rtctree/component.py | Component.remove_members | def remove_members(self, rtcs):
'''Remove other RT Components from this composite component.
rtcs is a list of components to remove. Each element must be either an
rtctree.Component object or a string containing a component's instance
name. rtctree.Component objects are more reliable.
This component must be a composite component.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
org = self.organisations[0].obj
members = org.get_members()
for rtc in rtcs:
if type(rtc) == str:
rtc_name = rtc
else:
rtc_name = rtc.instance_name
# Check if the RTC actually is a member
if not self.is_member(rtc):
raise exceptions.NotInCompositionError(self.name, rtc_name)
# Remove the RTC from the composition
org.remove_member(rtc_name)
# Force a reparse of the member information
self._orgs = [] | python | def remove_members(self, rtcs):
'''Remove other RT Components from this composite component.
rtcs is a list of components to remove. Each element must be either an
rtctree.Component object or a string containing a component's instance
name. rtctree.Component objects are more reliable.
This component must be a composite component.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
org = self.organisations[0].obj
members = org.get_members()
for rtc in rtcs:
if type(rtc) == str:
rtc_name = rtc
else:
rtc_name = rtc.instance_name
# Check if the RTC actually is a member
if not self.is_member(rtc):
raise exceptions.NotInCompositionError(self.name, rtc_name)
# Remove the RTC from the composition
org.remove_member(rtc_name)
# Force a reparse of the member information
self._orgs = [] | [
"def",
"remove_members",
"(",
"self",
",",
"rtcs",
")",
":",
"if",
"not",
"self",
".",
"is_composite",
":",
"raise",
"exceptions",
".",
"NotCompositeError",
"(",
"self",
".",
"name",
")",
"org",
"=",
"self",
".",
"organisations",
"[",
"0",
"]",
".",
"o... | Remove other RT Components from this composite component.
rtcs is a list of components to remove. Each element must be either an
rtctree.Component object or a string containing a component's instance
name. rtctree.Component objects are more reliable.
This component must be a composite component. | [
"Remove",
"other",
"RT",
"Components",
"from",
"this",
"composite",
"component",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L368-L393 |
gbiggs/rtctree | rtctree/component.py | Component.is_member | def is_member(self, rtc):
'''Is the given component a member of this composition?
rtc may be a Component object or a string containing a component's
instance name. Component objects are more reliable.
Returns False if the given component is not a member of this
composition.
Raises NotCompositeError if this component is not a composition.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
members = self.organisations[0].obj.get_members()
if type(rtc) is str:
for m in members:
if m.get_component_profile().instance_name == rtc:
return True
else:
for m in members:
if m._is_equivalent(rtc.object):
return True
return False | python | def is_member(self, rtc):
'''Is the given component a member of this composition?
rtc may be a Component object or a string containing a component's
instance name. Component objects are more reliable.
Returns False if the given component is not a member of this
composition.
Raises NotCompositeError if this component is not a composition.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
members = self.organisations[0].obj.get_members()
if type(rtc) is str:
for m in members:
if m.get_component_profile().instance_name == rtc:
return True
else:
for m in members:
if m._is_equivalent(rtc.object):
return True
return False | [
"def",
"is_member",
"(",
"self",
",",
"rtc",
")",
":",
"if",
"not",
"self",
".",
"is_composite",
":",
"raise",
"exceptions",
".",
"NotCompositeError",
"(",
"self",
".",
"name",
")",
"members",
"=",
"self",
".",
"organisations",
"[",
"0",
"]",
".",
"obj... | Is the given component a member of this composition?
rtc may be a Component object or a string containing a component's
instance name. Component objects are more reliable.
Returns False if the given component is not a member of this
composition.
Raises NotCompositeError if this component is not a composition. | [
"Is",
"the",
"given",
"component",
"a",
"member",
"of",
"this",
"composition?"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L414-L437 |
gbiggs/rtctree | rtctree/component.py | Component.members | def members(self):
'''Member components if this component is composite.'''
with self._mutex:
if not self._members:
self._members = {}
for o in self.organisations:
# TODO: Search for these in the tree
self._members[o.org_id] = o.obj.get_members()
return self._members | python | def members(self):
'''Member components if this component is composite.'''
with self._mutex:
if not self._members:
self._members = {}
for o in self.organisations:
# TODO: Search for these in the tree
self._members[o.org_id] = o.obj.get_members()
return self._members | [
"def",
"members",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_members",
":",
"self",
".",
"_members",
"=",
"{",
"}",
"for",
"o",
"in",
"self",
".",
"organisations",
":",
"# TODO: Search for these in the tree",
"... | Member components if this component is composite. | [
"Member",
"components",
"if",
"this",
"component",
"is",
"composite",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L440-L448 |
gbiggs/rtctree | rtctree/component.py | Component.organisations | def organisations(self):
'''The organisations of this composition.'''
class Org:
def __init__(self, sdo_id, org_id, members, obj):
self.sdo_id = sdo_id
self.org_id = org_id
self.members = members
self.obj = obj
with self._mutex:
if not self._orgs:
for org in self._obj.get_owned_organizations():
owner = org.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = org.get_organization_id()
members = [m.get_sdo_id() for m in org.get_members()]
self._orgs.append(Org(sdo_id, org_id, members, org))
return self._orgs | python | def organisations(self):
'''The organisations of this composition.'''
class Org:
def __init__(self, sdo_id, org_id, members, obj):
self.sdo_id = sdo_id
self.org_id = org_id
self.members = members
self.obj = obj
with self._mutex:
if not self._orgs:
for org in self._obj.get_owned_organizations():
owner = org.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = org.get_organization_id()
members = [m.get_sdo_id() for m in org.get_members()]
self._orgs.append(Org(sdo_id, org_id, members, org))
return self._orgs | [
"def",
"organisations",
"(",
"self",
")",
":",
"class",
"Org",
":",
"def",
"__init__",
"(",
"self",
",",
"sdo_id",
",",
"org_id",
",",
"members",
",",
"obj",
")",
":",
"self",
".",
"sdo_id",
"=",
"sdo_id",
"self",
".",
"org_id",
"=",
"org_id",
"self"... | The organisations of this composition. | [
"The",
"organisations",
"of",
"this",
"composition",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L451-L471 |
gbiggs/rtctree | rtctree/component.py | Component.parent_org_sdo_ids | def parent_org_sdo_ids(self):
'''The SDO IDs of the compositions this RTC belongs to.'''
return [sdo.get_owner()._narrow(SDOPackage.SDO).get_sdo_id() \
for sdo in self._obj.get_organizations() if sdo] | python | def parent_org_sdo_ids(self):
'''The SDO IDs of the compositions this RTC belongs to.'''
return [sdo.get_owner()._narrow(SDOPackage.SDO).get_sdo_id() \
for sdo in self._obj.get_organizations() if sdo] | [
"def",
"parent_org_sdo_ids",
"(",
"self",
")",
":",
"return",
"[",
"sdo",
".",
"get_owner",
"(",
")",
".",
"_narrow",
"(",
"SDOPackage",
".",
"SDO",
")",
".",
"get_sdo_id",
"(",
")",
"for",
"sdo",
"in",
"self",
".",
"_obj",
".",
"get_organizations",
"(... | The SDO IDs of the compositions this RTC belongs to. | [
"The",
"SDO",
"IDs",
"of",
"the",
"compositions",
"this",
"RTC",
"belongs",
"to",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L486-L489 |
gbiggs/rtctree | rtctree/component.py | Component.parent_organisations | def parent_organisations(self):
'''The organisations this RTC belongs to.'''
class ParentOrg:
def __init__(self, sdo_id, org_id):
self.sdo_id = sdo_id
self.org_id = org_id
with self._mutex:
if not self._parent_orgs:
for sdo in self._obj.get_organizations():
if not sdo:
continue
owner = sdo.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = sdo.get_organization_id()
self._parent_orgs.append(ParentOrg(sdo_id, org_id))
return self._parent_orgs | python | def parent_organisations(self):
'''The organisations this RTC belongs to.'''
class ParentOrg:
def __init__(self, sdo_id, org_id):
self.sdo_id = sdo_id
self.org_id = org_id
with self._mutex:
if not self._parent_orgs:
for sdo in self._obj.get_organizations():
if not sdo:
continue
owner = sdo.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = sdo.get_organization_id()
self._parent_orgs.append(ParentOrg(sdo_id, org_id))
return self._parent_orgs | [
"def",
"parent_organisations",
"(",
"self",
")",
":",
"class",
"ParentOrg",
":",
"def",
"__init__",
"(",
"self",
",",
"sdo_id",
",",
"org_id",
")",
":",
"self",
".",
"sdo_id",
"=",
"sdo_id",
"self",
".",
"org_id",
"=",
"org_id",
"with",
"self",
".",
"_... | The organisations this RTC belongs to. | [
"The",
"organisations",
"this",
"RTC",
"belongs",
"to",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L492-L511 |
gbiggs/rtctree | rtctree/component.py | Component.activate_in_ec | def activate_in_ec(self, ec_index):
'''Activate this component in an execution context.
@param ec_index The index of the execution context to activate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.activate_component(self._obj) | python | def activate_in_ec(self, ec_index):
'''Activate this component in an execution context.
@param ec_index The index of the execution context to activate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.activate_component(self._obj) | [
"def",
"activate_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_index",
... | Activate this component in an execution context.
@param ec_index The index of the execution context to activate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs. | [
"Activate",
"this",
"component",
"in",
"an",
"execution",
"context",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L532-L552 |
gbiggs/rtctree | rtctree/component.py | Component.deactivate_in_ec | def deactivate_in_ec(self, ec_index):
'''Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.deactivate_component(self._obj) | python | def deactivate_in_ec(self, ec_index):
'''Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.deactivate_component(self._obj) | [
"def",
"deactivate_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_index"... | Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index is greater than the length of
@ref owned_ecs, that length is subtracted from
ec_index and the result used as an index into
@ref participating_ecs. | [
"Deactivate",
"this",
"component",
"in",
"an",
"execution",
"context",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L554-L574 |
gbiggs/rtctree | rtctree/component.py | Component.get_ec | def get_ec(self, ec_handle):
'''Get a reference to the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return A reference to the ExecutionContext object corresponding to
the ec_handle.
@raises NoECWithHandleError
'''
with self._mutex:
for ec in self.owned_ecs:
if ec.handle == ec_handle:
return ec
for ec in self.participating_ecs:
if ec.handle == ec_handle:
return ec
raise exceptions.NoECWithHandleError | python | def get_ec(self, ec_handle):
'''Get a reference to the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return A reference to the ExecutionContext object corresponding to
the ec_handle.
@raises NoECWithHandleError
'''
with self._mutex:
for ec in self.owned_ecs:
if ec.handle == ec_handle:
return ec
for ec in self.participating_ecs:
if ec.handle == ec_handle:
return ec
raise exceptions.NoECWithHandleError | [
"def",
"get_ec",
"(",
"self",
",",
"ec_handle",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"ec",
"in",
"self",
".",
"owned_ecs",
":",
"if",
"ec",
".",
"handle",
"==",
"ec_handle",
":",
"return",
"ec",
"for",
"ec",
"in",
"self",
".",
"part... | Get a reference to the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return A reference to the ExecutionContext object corresponding to
the ec_handle.
@raises NoECWithHandleError | [
"Get",
"a",
"reference",
"to",
"the",
"execution",
"context",
"with",
"the",
"given",
"handle",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L576-L593 |
gbiggs/rtctree | rtctree/component.py | Component.get_ec_index | def get_ec_index(self, ec_handle):
'''Get the index of the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return The index into the owned + participated arrays, suitable for
use in methods such as @ref activate_in_ec, or -1 if the EC was not
found.
@raises NoECWithHandleError
'''
with self._mutex:
for ii, ec in enumerate(self.owned_ecs):
if ec.handle == ec_handle:
return ii
for ii, ec in enumerate(self.participating_ecs):
if ec.handle == ec_handle:
return ii + len(self.owned_ecs)
raise exceptions.NoECWithHandleError | python | def get_ec_index(self, ec_handle):
'''Get the index of the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return The index into the owned + participated arrays, suitable for
use in methods such as @ref activate_in_ec, or -1 if the EC was not
found.
@raises NoECWithHandleError
'''
with self._mutex:
for ii, ec in enumerate(self.owned_ecs):
if ec.handle == ec_handle:
return ii
for ii, ec in enumerate(self.participating_ecs):
if ec.handle == ec_handle:
return ii + len(self.owned_ecs)
raise exceptions.NoECWithHandleError | [
"def",
"get_ec_index",
"(",
"self",
",",
"ec_handle",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"ii",
",",
"ec",
"in",
"enumerate",
"(",
"self",
".",
"owned_ecs",
")",
":",
"if",
"ec",
".",
"handle",
"==",
"ec_handle",
":",
"return",
"ii",... | Get the index of the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return The index into the owned + participated arrays, suitable for
use in methods such as @ref activate_in_ec, or -1 if the EC was not
found.
@raises NoECWithHandleError | [
"Get",
"the",
"index",
"of",
"the",
"execution",
"context",
"with",
"the",
"given",
"handle",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L596-L614 |
gbiggs/rtctree | rtctree/component.py | Component.get_state_string | def get_state_string(self, add_colour=True):
'''Get the state of this component as an optionally-coloured string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the state of this component.
'''
with self._mutex:
if self.state == self.INACTIVE:
result = 'Inactive', ['bold', 'blue']
elif self.state == self.ACTIVE:
result = 'Active', ['bold', 'green']
elif self.state == self.ERROR:
result = 'Error', ['bold', 'white', 'bgred']
elif self.state == self.UNKNOWN:
result = 'Unknown', ['bold', 'red']
elif self.state == self.CREATED:
result = 'Created', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset', supported=add_colour)
else:
return result[0] | python | def get_state_string(self, add_colour=True):
'''Get the state of this component as an optionally-coloured string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the state of this component.
'''
with self._mutex:
if self.state == self.INACTIVE:
result = 'Inactive', ['bold', 'blue']
elif self.state == self.ACTIVE:
result = 'Active', ['bold', 'green']
elif self.state == self.ERROR:
result = 'Error', ['bold', 'white', 'bgred']
elif self.state == self.UNKNOWN:
result = 'Unknown', ['bold', 'red']
elif self.state == self.CREATED:
result = 'Created', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset', supported=add_colour)
else:
return result[0] | [
"def",
"get_state_string",
"(",
"self",
",",
"add_colour",
"=",
"True",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"state",
"==",
"self",
".",
"INACTIVE",
":",
"result",
"=",
"'Inactive'",
",",
"[",
"'bold'",
",",
"'blue'",
"]",
... | Get the state of this component as an optionally-coloured string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the state of this component. | [
"Get",
"the",
"state",
"of",
"this",
"component",
"as",
"an",
"optionally",
"-",
"coloured",
"string",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L616-L639 |
gbiggs/rtctree | rtctree/component.py | Component.get_state_in_ec_string | def get_state_in_ec_string(self, ec_index, add_colour=True):
'''Get the state of the component in an execution context as a string.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
state = self.participating_ec_states[ec_index]
else:
state = self.owned_ec_states[ec_index]
if state == self.INACTIVE:
result = 'Inactive', ['bold', 'blue']
elif state == self.ACTIVE:
result = 'Active', ['bold', 'green']
elif state == self.ERROR:
result = 'Error', ['bold', 'white', 'bgred']
elif state == self.UNKNOWN:
result = 'Unknown', ['bold', 'red']
elif state == self.CREATED:
result = 'Created', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset',
supported=add_colour)
else:
return result[0] | python | def get_state_in_ec_string(self, ec_index, add_colour=True):
'''Get the state of the component in an execution context as a string.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
state = self.participating_ec_states[ec_index]
else:
state = self.owned_ec_states[ec_index]
if state == self.INACTIVE:
result = 'Inactive', ['bold', 'blue']
elif state == self.ACTIVE:
result = 'Active', ['bold', 'green']
elif state == self.ERROR:
result = 'Error', ['bold', 'white', 'bgred']
elif state == self.UNKNOWN:
result = 'Unknown', ['bold', 'red']
elif state == self.CREATED:
result = 'Created', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset',
supported=add_colour)
else:
return result[0] | [
"def",
"get_state_in_ec_string",
"(",
"self",
",",
"ec_index",
",",
"add_colour",
"=",
"True",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
"... | Get the state of the component in an execution context as a string.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs. | [
"Get",
"the",
"state",
"of",
"the",
"component",
"in",
"an",
"execution",
"context",
"as",
"a",
"string",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L641-L676 |
gbiggs/rtctree | rtctree/component.py | Component.reset_in_ec | def reset_in_ec(self, ec_index):
'''Reset this component in an execution context.
@param ec_index The index of the execution context to reset in. This
index is into the total array of contexts, that is both
owned and participating contexts. If the value of
ec_index is greater than the length of @ref owned_ecs,
that length is subtracted from ec_index and the result
used as an index into @ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.reset_component(self._obj) | python | def reset_in_ec(self, ec_index):
'''Reset this component in an execution context.
@param ec_index The index of the execution context to reset in. This
index is into the total array of contexts, that is both
owned and participating contexts. If the value of
ec_index is greater than the length of @ref owned_ecs,
that length is subtracted from ec_index and the result
used as an index into @ref participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.participating_ecs[ec_index]
else:
ec = self.owned_ecs[ec_index]
ec.reset_component(self._obj) | [
"def",
"reset_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_index",
"... | Reset this component in an execution context.
@param ec_index The index of the execution context to reset in. This
index is into the total array of contexts, that is both
owned and participating contexts. If the value of
ec_index is greater than the length of @ref owned_ecs,
that length is subtracted from ec_index and the result
used as an index into @ref participating_ecs. | [
"Reset",
"this",
"component",
"in",
"an",
"execution",
"context",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L678-L697 |
gbiggs/rtctree | rtctree/component.py | Component.state_in_ec | def state_in_ec(self, ec_index):
'''Get the state of the component in an execution context.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
return self.participating_ec_states[ec_index]
else:
return self.owned_ec_states[ec_index] | python | def state_in_ec(self, ec_index):
'''Get the state of the component in an execution context.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
return self.participating_ec_states[ec_index]
else:
return self.owned_ec_states[ec_index] | [
"def",
"state_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_index",
"... | Get the state of the component in an execution context.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs. | [
"Get",
"the",
"state",
"of",
"the",
"component",
"in",
"an",
"execution",
"context",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L699-L718 |
gbiggs/rtctree | rtctree/component.py | Component.refresh_state_in_ec | def refresh_state_in_ec(self, ec_index):
'''Get the up-to-date state of the component in an execution context.
This function will update the state, rather than using the cached
value. This may take time, if the component is executing on a remote
node.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
state = self._get_ec_state(self.participating_ecs[ec_index])
self.participating_ec_states[ec_index] = state
else:
state = self._get_ec_state(self.owned_ecs[ec_index])
self.owned_ec_states[ec_index] = state
return state | python | def refresh_state_in_ec(self, ec_index):
'''Get the up-to-date state of the component in an execution context.
This function will update the state, rather than using the cached
value. This may take time, if the component is executing on a remote
node.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs.
'''
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
state = self._get_ec_state(self.participating_ecs[ec_index])
self.participating_ec_states[ec_index] = state
else:
state = self._get_ec_state(self.owned_ecs[ec_index])
self.owned_ec_states[ec_index] = state
return state | [
"def",
"refresh_state_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_ind... | Get the up-to-date state of the component in an execution context.
This function will update the state, rather than using the cached
value. This may take time, if the component is executing on a remote
node.
@param ec_index The index of the execution context to check the state
in. This index is into the total array of contexts,
that is both owned and participating contexts. If the
value of ec_index is greater than the length of @ref
owned_ecs, that length is subtracted from ec_index and
the result used as an index into @ref
participating_ecs. | [
"Get",
"the",
"up",
"-",
"to",
"-",
"date",
"state",
"of",
"the",
"component",
"in",
"an",
"execution",
"context",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L720-L746 |
gbiggs/rtctree | rtctree/component.py | Component.alive | def alive(self):
'''Is this component alive?'''
with self._mutex:
if self.exec_contexts:
for ec in self.exec_contexts:
if self._obj.is_alive(ec):
return True
return False | python | def alive(self):
'''Is this component alive?'''
with self._mutex:
if self.exec_contexts:
for ec in self.exec_contexts:
if self._obj.is_alive(ec):
return True
return False | [
"def",
"alive",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"exec_contexts",
":",
"for",
"ec",
"in",
"self",
".",
"exec_contexts",
":",
"if",
"self",
".",
"_obj",
".",
"is_alive",
"(",
"ec",
")",
":",
"return",
"Tr... | Is this component alive? | [
"Is",
"this",
"component",
"alive?"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L749-L756 |
gbiggs/rtctree | rtctree/component.py | Component.owned_ec_states | def owned_ec_states(self):
'''The state of each execution context this component owns.'''
with self._mutex:
if not self._owned_ec_states:
if self.owned_ecs:
states = []
for ec in self.owned_ecs:
states.append(self._get_ec_state(ec))
self._owned_ec_states = states
else:
self._owned_ec_states = []
return self._owned_ec_states | python | def owned_ec_states(self):
'''The state of each execution context this component owns.'''
with self._mutex:
if not self._owned_ec_states:
if self.owned_ecs:
states = []
for ec in self.owned_ecs:
states.append(self._get_ec_state(ec))
self._owned_ec_states = states
else:
self._owned_ec_states = []
return self._owned_ec_states | [
"def",
"owned_ec_states",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_owned_ec_states",
":",
"if",
"self",
".",
"owned_ecs",
":",
"states",
"=",
"[",
"]",
"for",
"ec",
"in",
"self",
".",
"owned_ecs",
":",
"s... | The state of each execution context this component owns. | [
"The",
"state",
"of",
"each",
"execution",
"context",
"this",
"component",
"owns",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L759-L770 |
gbiggs/rtctree | rtctree/component.py | Component.owned_ecs | def owned_ecs(self):
'''A list of the execution contexts owned by this component.'''
with self._mutex:
if not self._owned_ecs:
self._owned_ecs = [ExecutionContext(ec,
self._obj.get_context_handle(ec)) \
for ec in self._obj.get_owned_contexts()]
return self._owned_ecs | python | def owned_ecs(self):
'''A list of the execution contexts owned by this component.'''
with self._mutex:
if not self._owned_ecs:
self._owned_ecs = [ExecutionContext(ec,
self._obj.get_context_handle(ec)) \
for ec in self._obj.get_owned_contexts()]
return self._owned_ecs | [
"def",
"owned_ecs",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_owned_ecs",
":",
"self",
".",
"_owned_ecs",
"=",
"[",
"ExecutionContext",
"(",
"ec",
",",
"self",
".",
"_obj",
".",
"get_context_handle",
"(",
"e... | A list of the execution contexts owned by this component. | [
"A",
"list",
"of",
"the",
"execution",
"contexts",
"owned",
"by",
"this",
"component",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L773-L780 |
gbiggs/rtctree | rtctree/component.py | Component.participating_ec_states | def participating_ec_states(self):
'''The state of each execution context this component is participating
in.
'''
with self._mutex:
if not self._participating_ec_states:
if self.participating_ecs:
states = []
for ec in self.participating_ecs:
states.append(self._get_ec_state(ec))
self._participating_ec_states = states
else:
self._participating_ec_states = []
return self._participating_ec_states | python | def participating_ec_states(self):
'''The state of each execution context this component is participating
in.
'''
with self._mutex:
if not self._participating_ec_states:
if self.participating_ecs:
states = []
for ec in self.participating_ecs:
states.append(self._get_ec_state(ec))
self._participating_ec_states = states
else:
self._participating_ec_states = []
return self._participating_ec_states | [
"def",
"participating_ec_states",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_participating_ec_states",
":",
"if",
"self",
".",
"participating_ecs",
":",
"states",
"=",
"[",
"]",
"for",
"ec",
"in",
"self",
".",
... | The state of each execution context this component is participating
in. | [
"The",
"state",
"of",
"each",
"execution",
"context",
"this",
"component",
"is",
"participating",
"in",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L783-L797 |
gbiggs/rtctree | rtctree/component.py | Component.participating_ecs | def participating_ecs(self):
'''A list of the execution contexts this component is participating in.
'''
with self._mutex:
if not self._participating_ecs:
self._participating_ecs = [ExecutionContext(ec,
self._obj.get_context_handle(ec)) \
for ec in self._obj.get_participating_contexts()]
return self._participating_ecs | python | def participating_ecs(self):
'''A list of the execution contexts this component is participating in.
'''
with self._mutex:
if not self._participating_ecs:
self._participating_ecs = [ExecutionContext(ec,
self._obj.get_context_handle(ec)) \
for ec in self._obj.get_participating_contexts()]
return self._participating_ecs | [
"def",
"participating_ecs",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_participating_ecs",
":",
"self",
".",
"_participating_ecs",
"=",
"[",
"ExecutionContext",
"(",
"ec",
",",
"self",
".",
"_obj",
".",
"get_cont... | A list of the execution contexts this component is participating in. | [
"A",
"list",
"of",
"the",
"execution",
"contexts",
"this",
"component",
"is",
"participating",
"in",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L800-L809 |
gbiggs/rtctree | rtctree/component.py | Component.state | def state(self):
'''The merged state of all the execution context states, which can be
used as the overall state of this component.
The order of precedence is:
Error > Active > Inactive > Created > Unknown
'''
def merge_state(current, new):
if new == self.ERROR:
return self.ERROR
elif new == self.ACTIVE and current != self.ERROR:
return self.ACTIVE
elif new == self.INACTIVE and \
current not in [self.ACTIVE, self.ERROR]:
return self.INACTIVE
elif new == self.CREATED and \
current not in [self.ACTIVE, self.ERROR, self.INACTIVE]:
return self.CREATED
elif current not in [self.ACTIVE, self.ERROR, self.INACTIVE,
self.CREATED]:
return self.UNKNOWN
return current
with self._mutex:
if not self.owned_ec_states and not self.participating_ec_states:
return self.UNKNOWN
merged_state = self.CREATED
if self.owned_ec_states:
for ec_state in self.owned_ec_states:
merged_state = merge_state(merged_state, ec_state)
if self.participating_ec_states:
for ec_state in self.participating_ec_states:
merged_state = merge_state(merged_state, ec_state)
return merged_state | python | def state(self):
'''The merged state of all the execution context states, which can be
used as the overall state of this component.
The order of precedence is:
Error > Active > Inactive > Created > Unknown
'''
def merge_state(current, new):
if new == self.ERROR:
return self.ERROR
elif new == self.ACTIVE and current != self.ERROR:
return self.ACTIVE
elif new == self.INACTIVE and \
current not in [self.ACTIVE, self.ERROR]:
return self.INACTIVE
elif new == self.CREATED and \
current not in [self.ACTIVE, self.ERROR, self.INACTIVE]:
return self.CREATED
elif current not in [self.ACTIVE, self.ERROR, self.INACTIVE,
self.CREATED]:
return self.UNKNOWN
return current
with self._mutex:
if not self.owned_ec_states and not self.participating_ec_states:
return self.UNKNOWN
merged_state = self.CREATED
if self.owned_ec_states:
for ec_state in self.owned_ec_states:
merged_state = merge_state(merged_state, ec_state)
if self.participating_ec_states:
for ec_state in self.participating_ec_states:
merged_state = merge_state(merged_state, ec_state)
return merged_state | [
"def",
"state",
"(",
"self",
")",
":",
"def",
"merge_state",
"(",
"current",
",",
"new",
")",
":",
"if",
"new",
"==",
"self",
".",
"ERROR",
":",
"return",
"self",
".",
"ERROR",
"elif",
"new",
"==",
"self",
".",
"ACTIVE",
"and",
"current",
"!=",
"se... | The merged state of all the execution context states, which can be
used as the overall state of this component.
The order of precedence is:
Error > Active > Inactive > Created > Unknown | [
"The",
"merged",
"state",
"of",
"all",
"the",
"execution",
"context",
"states",
"which",
"can",
"be",
"used",
"as",
"the",
"overall",
"state",
"of",
"this",
"component",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L817-L851 |
gbiggs/rtctree | rtctree/component.py | Component.get_extended_fsm_service | def get_extended_fsm_service(self):
'''Get a reference to the ExtendedFsmService.
@return A reference to the ExtendedFsmService object
@raises InvalidSdoServiceError
'''
with self._mutex:
try:
return self._obj.get_sdo_service(RTC.ExtendedFsmService._NP_RepositoryId)._narrow(RTC.ExtendedFsmService)
except:
raise exceptions.InvalidSdoServiceError('ExtendedFsmService') | python | def get_extended_fsm_service(self):
'''Get a reference to the ExtendedFsmService.
@return A reference to the ExtendedFsmService object
@raises InvalidSdoServiceError
'''
with self._mutex:
try:
return self._obj.get_sdo_service(RTC.ExtendedFsmService._NP_RepositoryId)._narrow(RTC.ExtendedFsmService)
except:
raise exceptions.InvalidSdoServiceError('ExtendedFsmService') | [
"def",
"get_extended_fsm_service",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"try",
":",
"return",
"self",
".",
"_obj",
".",
"get_sdo_service",
"(",
"RTC",
".",
"ExtendedFsmService",
".",
"_NP_RepositoryId",
")",
".",
"_narrow",
"(",
"RTC",
... | Get a reference to the ExtendedFsmService.
@return A reference to the ExtendedFsmService object
@raises InvalidSdoServiceError | [
"Get",
"a",
"reference",
"to",
"the",
"ExtendedFsmService",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L861-L872 |
gbiggs/rtctree | rtctree/component.py | Component.get_port_by_name | def get_port_by_name(self, port_name):
'''Get a port of this component by name.'''
with self._mutex:
for p in self.ports:
if p.name == port_name:
return p
return None | python | def get_port_by_name(self, port_name):
'''Get a port of this component by name.'''
with self._mutex:
for p in self.ports:
if p.name == port_name:
return p
return None | [
"def",
"get_port_by_name",
"(",
"self",
",",
"port_name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"p",
"in",
"self",
".",
"ports",
":",
"if",
"p",
".",
"name",
"==",
"port_name",
":",
"return",
"p",
"return",
"None"
] | Get a port of this component by name. | [
"Get",
"a",
"port",
"of",
"this",
"component",
"by",
"name",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L883-L889 |
gbiggs/rtctree | rtctree/component.py | Component.get_port_by_ref | def get_port_by_ref(self, port_ref):
'''Get a port of this component by reference to a CORBA PortService
object.
'''
with self._mutex:
for p in self.ports:
if p.object._is_equivalent(port_ref):
return p
return None | python | def get_port_by_ref(self, port_ref):
'''Get a port of this component by reference to a CORBA PortService
object.
'''
with self._mutex:
for p in self.ports:
if p.object._is_equivalent(port_ref):
return p
return None | [
"def",
"get_port_by_ref",
"(",
"self",
",",
"port_ref",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"p",
"in",
"self",
".",
"ports",
":",
"if",
"p",
".",
"object",
".",
"_is_equivalent",
"(",
"port_ref",
")",
":",
"return",
"p",
"return",
"N... | Get a port of this component by reference to a CORBA PortService
object. | [
"Get",
"a",
"port",
"of",
"this",
"component",
"by",
"reference",
"to",
"a",
"CORBA",
"PortService",
"object",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L891-L900 |
gbiggs/rtctree | rtctree/component.py | Component.has_port_by_name | def has_port_by_name(self, port_name):
'''Check if this component has a port by the given name.'''
with self._mutex:
if self.get_port_by_name(port_name):
return True
return False | python | def has_port_by_name(self, port_name):
'''Check if this component has a port by the given name.'''
with self._mutex:
if self.get_port_by_name(port_name):
return True
return False | [
"def",
"has_port_by_name",
"(",
"self",
",",
"port_name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"get_port_by_name",
"(",
"port_name",
")",
":",
"return",
"True",
"return",
"False"
] | Check if this component has a port by the given name. | [
"Check",
"if",
"this",
"component",
"has",
"a",
"port",
"by",
"the",
"given",
"name",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L902-L907 |
gbiggs/rtctree | rtctree/component.py | Component.has_port_by_ref | def has_port_by_ref(self, port_ref):
'''Check if this component has a port by the given reference to a CORBA
PortService object.
'''
with self._mutex:
if self.get_port_by_ref(self, port_ref):
return True
return False | python | def has_port_by_ref(self, port_ref):
'''Check if this component has a port by the given reference to a CORBA
PortService object.
'''
with self._mutex:
if self.get_port_by_ref(self, port_ref):
return True
return False | [
"def",
"has_port_by_ref",
"(",
"self",
",",
"port_ref",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"get_port_by_ref",
"(",
"self",
",",
"port_ref",
")",
":",
"return",
"True",
"return",
"False"
] | Check if this component has a port by the given reference to a CORBA
PortService object. | [
"Check",
"if",
"this",
"component",
"has",
"a",
"port",
"by",
"the",
"given",
"reference",
"to",
"a",
"CORBA",
"PortService",
"object",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L909-L917 |
gbiggs/rtctree | rtctree/component.py | Component.connected_inports | def connected_inports(self):
'''The list of all input ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'DataInPort' and p.is_connected] | python | def connected_inports(self):
'''The list of all input ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'DataInPort' and p.is_connected] | [
"def",
"connected_inports",
"(",
"self",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"ports",
"if",
"p",
".",
"__class__",
".",
"__name__",
"==",
"'DataInPort'",
"and",
"p",
".",
"is_connected",
"]"
] | The list of all input ports belonging to this component that are
connected to one or more other ports. | [
"The",
"list",
"of",
"all",
"input",
"ports",
"belonging",
"to",
"this",
"component",
"that",
"are",
"connected",
"to",
"one",
"or",
"more",
"other",
"ports",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L920-L926 |
gbiggs/rtctree | rtctree/component.py | Component.connected_outports | def connected_outports(self):
'''The list of all output ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'DataOutPort' \
and p.is_connected] | python | def connected_outports(self):
'''The list of all output ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'DataOutPort' \
and p.is_connected] | [
"def",
"connected_outports",
"(",
"self",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"ports",
"if",
"p",
".",
"__class__",
".",
"__name__",
"==",
"'DataOutPort'",
"and",
"p",
".",
"is_connected",
"]"
] | The list of all output ports belonging to this component that are
connected to one or more other ports. | [
"The",
"list",
"of",
"all",
"output",
"ports",
"belonging",
"to",
"this",
"component",
"that",
"are",
"connected",
"to",
"one",
"or",
"more",
"other",
"ports",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L929-L936 |
gbiggs/rtctree | rtctree/component.py | Component.connected_svcports | def connected_svcports(self):
'''The list of all service ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'CorbaPort' and p.is_connected] | python | def connected_svcports(self):
'''The list of all service ports belonging to this component that are
connected to one or more other ports.
'''
return [p for p in self.ports \
if p.__class__.__name__ == 'CorbaPort' and p.is_connected] | [
"def",
"connected_svcports",
"(",
"self",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"ports",
"if",
"p",
".",
"__class__",
".",
"__name__",
"==",
"'CorbaPort'",
"and",
"p",
".",
"is_connected",
"]"
] | The list of all service ports belonging to this component that are
connected to one or more other ports. | [
"The",
"list",
"of",
"all",
"service",
"ports",
"belonging",
"to",
"this",
"component",
"that",
"are",
"connected",
"to",
"one",
"or",
"more",
"other",
"ports",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L947-L953 |
gbiggs/rtctree | rtctree/component.py | Component.ports | def ports(self):
'''The list of all ports belonging to this component.'''
with self._mutex:
if not self._ports:
self._ports = [ports.parse_port(port, self) \
for port in self._obj.get_ports()]
return self._ports | python | def ports(self):
'''The list of all ports belonging to this component.'''
with self._mutex:
if not self._ports:
self._ports = [ports.parse_port(port, self) \
for port in self._obj.get_ports()]
return self._ports | [
"def",
"ports",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_ports",
":",
"self",
".",
"_ports",
"=",
"[",
"ports",
".",
"parse_port",
"(",
"port",
",",
"self",
")",
"for",
"port",
"in",
"self",
".",
"_ob... | The list of all ports belonging to this component. | [
"The",
"list",
"of",
"all",
"ports",
"belonging",
"to",
"this",
"component",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L966-L972 |
gbiggs/rtctree | rtctree/component.py | Component.add_logger | def add_logger(self, cb, level='NORMAL', filters='ALL'):
'''Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component the log record came from, time is a
floating-point time stamp, source is the name of the logger that
provided the log record, level is the log level of the record and
message is a text string.
@param level The maximum level of log records to receive.
@param filters Filter the objects from which to receive log messages.
@return An ID for this logger. Use this ID in future operations such as
removing this logger.
@raises AddLoggerError
'''
with self._mutex:
obs = sdo.RTCLogger(self, cb)
uuid_val = uuid.uuid4()
intf_type = obs._this()._NP_RepositoryId
props = {'logger.log_level': level,
'logger.filter': filters}
props = utils.dict_to_nvlist(props)
sprof = SDOPackage.ServiceProfile(id=uuid_val.get_bytes(),
interface_type=intf_type, service=obs._this(),
properties=props)
conf = self.object.get_configuration()
res = conf.add_service_profile(sprof)
if res:
self._loggers[uuid_val] = obs
return uuid_val
raise exceptions.AddLoggerError(self.name) | python | def add_logger(self, cb, level='NORMAL', filters='ALL'):
'''Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component the log record came from, time is a
floating-point time stamp, source is the name of the logger that
provided the log record, level is the log level of the record and
message is a text string.
@param level The maximum level of log records to receive.
@param filters Filter the objects from which to receive log messages.
@return An ID for this logger. Use this ID in future operations such as
removing this logger.
@raises AddLoggerError
'''
with self._mutex:
obs = sdo.RTCLogger(self, cb)
uuid_val = uuid.uuid4()
intf_type = obs._this()._NP_RepositoryId
props = {'logger.log_level': level,
'logger.filter': filters}
props = utils.dict_to_nvlist(props)
sprof = SDOPackage.ServiceProfile(id=uuid_val.get_bytes(),
interface_type=intf_type, service=obs._this(),
properties=props)
conf = self.object.get_configuration()
res = conf.add_service_profile(sprof)
if res:
self._loggers[uuid_val] = obs
return uuid_val
raise exceptions.AddLoggerError(self.name) | [
"def",
"add_logger",
"(",
"self",
",",
"cb",
",",
"level",
"=",
"'NORMAL'",
",",
"filters",
"=",
"'ALL'",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"obs",
"=",
"sdo",
".",
"RTCLogger",
"(",
"self",
",",
"cb",
")",
"uuid_val",
"=",
"uuid",
".",
... | Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component the log record came from, time is a
floating-point time stamp, source is the name of the logger that
provided the log record, level is the log level of the record and
message is a text string.
@param level The maximum level of log records to receive.
@param filters Filter the objects from which to receive log messages.
@return An ID for this logger. Use this ID in future operations such as
removing this logger.
@raises AddLoggerError | [
"Add",
"a",
"callback",
"to",
"receive",
"log",
"events",
"from",
"this",
"component",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1007-L1038 |
gbiggs/rtctree | rtctree/component.py | Component.remove_logger | def remove_logger(self, cb_id):
'''Remove a logger.
@param cb_id The ID of the logger to remove.
@raises NoLoggerError
'''
if cb_id not in self._loggers:
raise exceptions.NoLoggerError(cb_id, self.name)
conf = self.object.get_configuration()
res = conf.remove_service_profile(cb_id.get_bytes())
del self._loggers[cb_id] | python | def remove_logger(self, cb_id):
'''Remove a logger.
@param cb_id The ID of the logger to remove.
@raises NoLoggerError
'''
if cb_id not in self._loggers:
raise exceptions.NoLoggerError(cb_id, self.name)
conf = self.object.get_configuration()
res = conf.remove_service_profile(cb_id.get_bytes())
del self._loggers[cb_id] | [
"def",
"remove_logger",
"(",
"self",
",",
"cb_id",
")",
":",
"if",
"cb_id",
"not",
"in",
"self",
".",
"_loggers",
":",
"raise",
"exceptions",
".",
"NoLoggerError",
"(",
"cb_id",
",",
"self",
".",
"name",
")",
"conf",
"=",
"self",
".",
"object",
".",
... | Remove a logger.
@param cb_id The ID of the logger to remove.
@raises NoLoggerError | [
"Remove",
"a",
"logger",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1040-L1051 |
gbiggs/rtctree | rtctree/component.py | Component.activate_conf_set | def activate_conf_set(self, set_name):
'''Activate a configuration set by name.
@raises NoSuchConfSetError
'''
with self._mutex:
if not set_name in self.conf_sets:
raise exceptions.NoSuchConfSetError(set_name)
self._conf.activate_configuration_set(set_name) | python | def activate_conf_set(self, set_name):
'''Activate a configuration set by name.
@raises NoSuchConfSetError
'''
with self._mutex:
if not set_name in self.conf_sets:
raise exceptions.NoSuchConfSetError(set_name)
self._conf.activate_configuration_set(set_name) | [
"def",
"activate_conf_set",
"(",
"self",
",",
"set_name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"set_name",
"in",
"self",
".",
"conf_sets",
":",
"raise",
"exceptions",
".",
"NoSuchConfSetError",
"(",
"set_name",
")",
"self",
".",
"_con... | Activate a configuration set by name.
@raises NoSuchConfSetError | [
"Activate",
"a",
"configuration",
"set",
"by",
"name",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1056-L1065 |
gbiggs/rtctree | rtctree/component.py | Component.set_conf_set_value | def set_conf_set_value(self, set_name, param, value):
'''Set a configuration set parameter value.
@param set_name The name of the configuration set the destination
parameter is in.
@param param The name of the parameter to set.
@param value The new value for the parameter.
@raises NoSuchConfSetError, NoSuchConfParamError
'''
with self._mutex:
if not set_name in self.conf_sets:
raise exceptions.NoSuchConfSetError(set_name)
if not self.conf_sets[set_name].has_param(param):
raise exceptions.NoSuchConfParamError(param)
self.conf_sets[set_name].set_param(param, value)
self._conf.set_configuration_set_values(\
self.conf_sets[set_name].object) | python | def set_conf_set_value(self, set_name, param, value):
'''Set a configuration set parameter value.
@param set_name The name of the configuration set the destination
parameter is in.
@param param The name of the parameter to set.
@param value The new value for the parameter.
@raises NoSuchConfSetError, NoSuchConfParamError
'''
with self._mutex:
if not set_name in self.conf_sets:
raise exceptions.NoSuchConfSetError(set_name)
if not self.conf_sets[set_name].has_param(param):
raise exceptions.NoSuchConfParamError(param)
self.conf_sets[set_name].set_param(param, value)
self._conf.set_configuration_set_values(\
self.conf_sets[set_name].object) | [
"def",
"set_conf_set_value",
"(",
"self",
",",
"set_name",
",",
"param",
",",
"value",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"set_name",
"in",
"self",
".",
"conf_sets",
":",
"raise",
"exceptions",
".",
"NoSuchConfSetError",
"(",
"set_n... | Set a configuration set parameter value.
@param set_name The name of the configuration set the destination
parameter is in.
@param param The name of the parameter to set.
@param value The new value for the parameter.
@raises NoSuchConfSetError, NoSuchConfParamError | [
"Set",
"a",
"configuration",
"set",
"parameter",
"value",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1067-L1084 |
gbiggs/rtctree | rtctree/component.py | Component.active_conf_set | def active_conf_set(self):
'''The currently-active configuration set.'''
with self._mutex:
if not self.conf_sets:
return None
if not self._active_conf_set:
return None
return self.conf_sets[self._active_conf_set] | python | def active_conf_set(self):
'''The currently-active configuration set.'''
with self._mutex:
if not self.conf_sets:
return None
if not self._active_conf_set:
return None
return self.conf_sets[self._active_conf_set] | [
"def",
"active_conf_set",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"conf_sets",
":",
"return",
"None",
"if",
"not",
"self",
".",
"_active_conf_set",
":",
"return",
"None",
"return",
"self",
".",
"conf_sets",
"[... | The currently-active configuration set. | [
"The",
"currently",
"-",
"active",
"configuration",
"set",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1087-L1094 |
gbiggs/rtctree | rtctree/component.py | Component.active_conf_set_name | def active_conf_set_name(self):
'''The name of the currently-active configuration set.'''
with self._mutex:
if not self.conf_sets:
return ''
if not self._active_conf_set:
return ''
return self._active_conf_set | python | def active_conf_set_name(self):
'''The name of the currently-active configuration set.'''
with self._mutex:
if not self.conf_sets:
return ''
if not self._active_conf_set:
return ''
return self._active_conf_set | [
"def",
"active_conf_set_name",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"conf_sets",
":",
"return",
"''",
"if",
"not",
"self",
".",
"_active_conf_set",
":",
"return",
"''",
"return",
"self",
".",
"_active_conf_se... | The name of the currently-active configuration set. | [
"The",
"name",
"of",
"the",
"currently",
"-",
"active",
"configuration",
"set",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1097-L1104 |
gbiggs/rtctree | rtctree/component.py | Component.conf_sets | def conf_sets(self):
'''The dictionary of configuration sets in this component, if any.'''
with self._mutex:
if not self._conf_sets:
self._parse_configuration()
return self._conf_sets | python | def conf_sets(self):
'''The dictionary of configuration sets in this component, if any.'''
with self._mutex:
if not self._conf_sets:
self._parse_configuration()
return self._conf_sets | [
"def",
"conf_sets",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_conf_sets",
":",
"self",
".",
"_parse_configuration",
"(",
")",
"return",
"self",
".",
"_conf_sets"
] | The dictionary of configuration sets in this component, if any. | [
"The",
"dictionary",
"of",
"configuration",
"sets",
"in",
"this",
"component",
"if",
"any",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1107-L1112 |
darkfeline/animanager | animanager/sqlite/cachetable.py | CacheTableManager.setup | def setup(self):
"""Setup cache tables."""
for table_spec in self._table_specs:
with self._conn:
table_spec.setup(self._conn) | python | def setup(self):
"""Setup cache tables."""
for table_spec in self._table_specs:
with self._conn:
table_spec.setup(self._conn) | [
"def",
"setup",
"(",
"self",
")",
":",
"for",
"table_spec",
"in",
"self",
".",
"_table_specs",
":",
"with",
"self",
".",
"_conn",
":",
"table_spec",
".",
"setup",
"(",
"self",
".",
"_conn",
")"
] | Setup cache tables. | [
"Setup",
"cache",
"tables",
"."
] | train | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/sqlite/cachetable.py#L35-L39 |
darkfeline/animanager | animanager/sqlite/cachetable.py | CacheTableManager.teardown | def teardown(self):
"""Cleanup cache tables."""
for table_spec in reversed(self._table_specs):
with self._conn:
table_spec.teardown(self._conn) | python | def teardown(self):
"""Cleanup cache tables."""
for table_spec in reversed(self._table_specs):
with self._conn:
table_spec.teardown(self._conn) | [
"def",
"teardown",
"(",
"self",
")",
":",
"for",
"table_spec",
"in",
"reversed",
"(",
"self",
".",
"_table_specs",
")",
":",
"with",
"self",
".",
"_conn",
":",
"table_spec",
".",
"teardown",
"(",
"self",
".",
"_conn",
")"
] | Cleanup cache tables. | [
"Cleanup",
"cache",
"tables",
"."
] | train | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/sqlite/cachetable.py#L41-L45 |
SylvanasSun/FishFishJump | fish_core/search_engine.py | append_condition | def append_condition(statement, condition, key, value):
"""
>>> list = []
>>> append_condition(list, 'match', 'name', 'Jack')
>>> list
[{'match': {'name': 'Jack'}}]
>>> dict = {}
>>> append_condition(dict, 'match', 'name', 'Marry')
>>> dict
{'match': {'name': 'Marry'}}
"""
if isinstance(statement, list):
statement.append({condition: {key: value}})
if isinstance(statement, dict):
statement[condition] = {key: value} | python | def append_condition(statement, condition, key, value):
"""
>>> list = []
>>> append_condition(list, 'match', 'name', 'Jack')
>>> list
[{'match': {'name': 'Jack'}}]
>>> dict = {}
>>> append_condition(dict, 'match', 'name', 'Marry')
>>> dict
{'match': {'name': 'Marry'}}
"""
if isinstance(statement, list):
statement.append({condition: {key: value}})
if isinstance(statement, dict):
statement[condition] = {key: value} | [
"def",
"append_condition",
"(",
"statement",
",",
"condition",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"statement",
",",
"list",
")",
":",
"statement",
".",
"append",
"(",
"{",
"condition",
":",
"{",
"key",
":",
"value",
"}",
"}",
... | >>> list = []
>>> append_condition(list, 'match', 'name', 'Jack')
>>> list
[{'match': {'name': 'Jack'}}]
>>> dict = {}
>>> append_condition(dict, 'match', 'name', 'Marry')
>>> dict
{'match': {'name': 'Marry'}} | [
">>>",
"list",
"=",
"[]",
">>>",
"append_condition",
"(",
"list",
"match",
"name",
"Jack",
")",
">>>",
"list",
"[",
"{",
"match",
":",
"{",
"name",
":",
"Jack",
"}}",
"]",
">>>",
"dict",
"=",
"{}",
">>>",
"append_condition",
"(",
"dict",
"match",
"na... | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/search_engine.py#L528-L542 |
SylvanasSun/FishFishJump | fish_core/search_engine.py | ElasticsearchClient.from_normal | def from_normal(self, hosts=default.ELASTICSEARCH_HOSTS, **kwargs):
"""
Initialize a Elasticsearch client by specified hosts list.
:param hosts: list of nodes we should connect to. Node should be a
dictionary ({"host": "localhost", "port": 9200}), the entire dictionary
will be passed to the :class:`~elasticsearch.Connection` class as
kwargs, or a string in the format of ``host[:port]`` which will be
translated to a dictionary automatically. If no value is given the
:class:`~elasticsearch.Urllib3HttpConnection` class defaults will be used
:return: void
"""
self.client = Elasticsearch(hosts=hosts, **kwargs)
logger.info('Initialize normal Elasticsearch Client: %s.' % self.client) | python | def from_normal(self, hosts=default.ELASTICSEARCH_HOSTS, **kwargs):
"""
Initialize a Elasticsearch client by specified hosts list.
:param hosts: list of nodes we should connect to. Node should be a
dictionary ({"host": "localhost", "port": 9200}), the entire dictionary
will be passed to the :class:`~elasticsearch.Connection` class as
kwargs, or a string in the format of ``host[:port]`` which will be
translated to a dictionary automatically. If no value is given the
:class:`~elasticsearch.Urllib3HttpConnection` class defaults will be used
:return: void
"""
self.client = Elasticsearch(hosts=hosts, **kwargs)
logger.info('Initialize normal Elasticsearch Client: %s.' % self.client) | [
"def",
"from_normal",
"(",
"self",
",",
"hosts",
"=",
"default",
".",
"ELASTICSEARCH_HOSTS",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
"=",
"Elasticsearch",
"(",
"hosts",
"=",
"hosts",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"info"... | Initialize a Elasticsearch client by specified hosts list.
:param hosts: list of nodes we should connect to. Node should be a
dictionary ({"host": "localhost", "port": 9200}), the entire dictionary
will be passed to the :class:`~elasticsearch.Connection` class as
kwargs, or a string in the format of ``host[:port]`` which will be
translated to a dictionary automatically. If no value is given the
:class:`~elasticsearch.Urllib3HttpConnection` class defaults will be used
:return: void | [
"Initialize",
"a",
"Elasticsearch",
"client",
"by",
"specified",
"hosts",
"list",
"."
] | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/search_engine.py#L30-L44 |
SylvanasSun/FishFishJump | fish_core/search_engine.py | ElasticsearchClient.from_sniffing | def from_sniffing(self,
active_nodes,
sniff_on_start=True,
sniff_on_connection_fail=True,
sniffer_timeout=60, **kwargs):
"""
Initialize a Elasticsearch client for specify to sniff on startup to
inspect the cluster and load balance across all nodes.
The client can be configured to inspect the cluster state to get
a list of nodes upon startup, periodically and/or on failure.
:param active_nodes: the list of active nodes
:param sniff_on_start: flag indicating whether to obtain a list of nodes
from the cluser at startup time
:param sniff_on_connection_fail: flag controlling if connection failure triggers a sniff
:param sniffer_timeout: number of seconds between automatic sniffs
:return: void
"""
self.client = Elasticsearch(active_nodes,
sniff_on_start=sniff_on_start,
sniff_on_connection_fail=sniff_on_connection_fail,
sniffer_timeout=sniffer_timeout, **kwargs)
logger.info('Initialize sniffing Elasticsearch Client: %s.' % self.client) | python | def from_sniffing(self,
active_nodes,
sniff_on_start=True,
sniff_on_connection_fail=True,
sniffer_timeout=60, **kwargs):
"""
Initialize a Elasticsearch client for specify to sniff on startup to
inspect the cluster and load balance across all nodes.
The client can be configured to inspect the cluster state to get
a list of nodes upon startup, periodically and/or on failure.
:param active_nodes: the list of active nodes
:param sniff_on_start: flag indicating whether to obtain a list of nodes
from the cluser at startup time
:param sniff_on_connection_fail: flag controlling if connection failure triggers a sniff
:param sniffer_timeout: number of seconds between automatic sniffs
:return: void
"""
self.client = Elasticsearch(active_nodes,
sniff_on_start=sniff_on_start,
sniff_on_connection_fail=sniff_on_connection_fail,
sniffer_timeout=sniffer_timeout, **kwargs)
logger.info('Initialize sniffing Elasticsearch Client: %s.' % self.client) | [
"def",
"from_sniffing",
"(",
"self",
",",
"active_nodes",
",",
"sniff_on_start",
"=",
"True",
",",
"sniff_on_connection_fail",
"=",
"True",
",",
"sniffer_timeout",
"=",
"60",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
"=",
"Elasticsearch",
"("... | Initialize a Elasticsearch client for specify to sniff on startup to
inspect the cluster and load balance across all nodes.
The client can be configured to inspect the cluster state to get
a list of nodes upon startup, periodically and/or on failure.
:param active_nodes: the list of active nodes
:param sniff_on_start: flag indicating whether to obtain a list of nodes
from the cluser at startup time
:param sniff_on_connection_fail: flag controlling if connection failure triggers a sniff
:param sniffer_timeout: number of seconds between automatic sniffs
:return: void | [
"Initialize",
"a",
"Elasticsearch",
"client",
"for",
"specify",
"to",
"sniff",
"on",
"startup",
"to",
"inspect",
"the",
"cluster",
"and",
"load",
"balance",
"across",
"all",
"nodes",
".",
"The",
"client",
"can",
"be",
"configured",
"to",
"inspect",
"the",
"c... | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/search_engine.py#L46-L68 |
SylvanasSun/FishFishJump | fish_core/search_engine.py | ElasticsearchClient.from_ssl | def from_ssl(self,
ca_certs,
client_cert,
client_key,
hosts=default.ELASTICSEARCH_HOSTS,
use_ssl=True,
verify_certs=True, **kwargs):
"""
Initialize a Elasticsearch client by SSL.
:param ca_certs: optional path to CA bundle. See
https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3
:param client_cert: path to the file containing the private key and the
certificate, or cert only if using client_key
:param client_key: path to the file containing the private key if using
separate cert and key files (client_cert will contain only the cert)
:param hosts: hostname of the node
:param use_ssl: use ssl for the connection if `True`
:param verify_certs: whether to verify SSL certificates
:return: void
"""
self.client = Elasticsearch(hosts=hosts,
use_ssl=use_ssl,
verify_certs=verify_certs,
ca_certs=ca_certs,
client_cert=client_cert,
client_key=client_key, **kwargs)
logger.info('Initialize SSL Elasticsearch Client: %s.' % self.client) | python | def from_ssl(self,
ca_certs,
client_cert,
client_key,
hosts=default.ELASTICSEARCH_HOSTS,
use_ssl=True,
verify_certs=True, **kwargs):
"""
Initialize a Elasticsearch client by SSL.
:param ca_certs: optional path to CA bundle. See
https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3
:param client_cert: path to the file containing the private key and the
certificate, or cert only if using client_key
:param client_key: path to the file containing the private key if using
separate cert and key files (client_cert will contain only the cert)
:param hosts: hostname of the node
:param use_ssl: use ssl for the connection if `True`
:param verify_certs: whether to verify SSL certificates
:return: void
"""
self.client = Elasticsearch(hosts=hosts,
use_ssl=use_ssl,
verify_certs=verify_certs,
ca_certs=ca_certs,
client_cert=client_cert,
client_key=client_key, **kwargs)
logger.info('Initialize SSL Elasticsearch Client: %s.' % self.client) | [
"def",
"from_ssl",
"(",
"self",
",",
"ca_certs",
",",
"client_cert",
",",
"client_key",
",",
"hosts",
"=",
"default",
".",
"ELASTICSEARCH_HOSTS",
",",
"use_ssl",
"=",
"True",
",",
"verify_certs",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".... | Initialize a Elasticsearch client by SSL.
:param ca_certs: optional path to CA bundle. See
https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3
:param client_cert: path to the file containing the private key and the
certificate, or cert only if using client_key
:param client_key: path to the file containing the private key if using
separate cert and key files (client_cert will contain only the cert)
:param hosts: hostname of the node
:param use_ssl: use ssl for the connection if `True`
:param verify_certs: whether to verify SSL certificates
:return: void | [
"Initialize",
"a",
"Elasticsearch",
"client",
"by",
"SSL",
"."
] | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/search_engine.py#L70-L97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.