code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self._manager.replace(scaling_group, name, cooldown,
min_entities, max_entities, metadata=metadata) | def replace(self, scaling_group, name, cooldown, min_entities,
max_entities, metadata=None) | Replace an existing ScalingGroup configuration. All of the attributes
must be specified. If you wish to delete any of the optional
attributes, pass them in as None. | 2.735754 | 3.403232 | 0.803869 |
return self._manager.update(scaling_group, name=name, cooldown=cooldown,
min_entities=min_entities, max_entities=max_entities,
metadata=metadata) | def update(self, scaling_group, name=None, cooldown=None, min_entities=None,
max_entities=None, metadata=None) | Updates an existing ScalingGroup. One or more of the attributes can be
specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method. | 1.909339 | 2.279016 | 0.837791 |
return self._manager.replace_launch_config(scaling_group,
launch_config_type, server_name, image, flavor,
disk_config=disk_config, metadata=metadata,
personality=personality, networks=networks,
load_balancers=load_balancers, key_name=key_name) | def replace_launch_config(self, scaling_group, launch_config_type,
server_name, image, flavor, disk_config=None, metadata=None,
personality=None, networks=None, load_balancers=None,
key_name=None) | Replace an existing launch configuration. All of the attributes must be
specified. If you wish to delete any of the optional attributes, pass
them in as None. | 1.478951 | 1.623634 | 0.91089 |
return self._manager.update_launch_config(scaling_group,
server_name=server_name, image=image, flavor=flavor,
disk_config=disk_config, metadata=metadata,
personality=personality, networks=networks,
load_balancers=load_balancers, key_name=key_name,
config_drive=config_drive, user_data=user_data) | def update_launch_config(self, scaling_group, server_name=None, image=None,
flavor=None, disk_config=None, metadata=None, personality=None,
networks=None, load_balancers=None, key_name=None, config_drive=False,
user_data=None) | Updates the server launch configuration for an existing scaling group.
One or more of the available attributes can be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_launch_metadata() method. | 1.400943 | 1.545046 | 0.906732 |
return self._manager.add_policy(scaling_group, name, policy_type,
cooldown, change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args) | def add_policy(self, scaling_group, name, policy_type, cooldown,
change=None, is_percent=False, desired_capacity=None, args=None) | Adds a policy with the given values to the specified scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which case it is treated as a percentage. | 1.838825 | 2.173676 | 0.845952 |
return self._manager.update_policy(scaling_group, policy, name=name,
policy_type=policy_type, cooldown=cooldown, change=change,
is_percent=is_percent, desired_capacity=desired_capacity,
args=args) | def update_policy(self, scaling_group, policy, name=None, policy_type=None,
cooldown=None, change=None, is_percent=False,
desired_capacity=None, args=None) | Updates the specified policy. One or more of the parameters may be
specified. | 1.606878 | 1.930087 | 0.832541 |
return self._manager.execute_policy(scaling_group=scaling_group,
policy=policy) | def execute_policy(self, scaling_group, policy) | Executes the specified policy for the scaling group. | 5.336153 | 4.939308 | 1.080344 |
return self._manager.delete_policy(scaling_group=scaling_group,
policy=policy) | def delete_policy(self, scaling_group, policy) | Deletes the specified policy from the scaling group. | 4.960647 | 5.16821 | 0.959839 |
return self._manager.add_webhook(scaling_group, policy, name,
metadata=metadata) | def add_webhook(self, scaling_group, policy, name, metadata=None) | Adds a webhook to the specified policy. | 4.261108 | 4.75714 | 0.895729 |
return self._manager.get_webhook(scaling_group, policy, webhook) | def get_webhook(self, scaling_group, policy, webhook) | Gets the detail for the specified webhook. | 4.56674 | 4.119235 | 1.108638 |
return self._manager.replace_webhook(scaling_group, policy, webhook,
name, metadata=metadata) | def replace_webhook(self, scaling_group, policy, webhook, name,
metadata=None) | Replace an existing webhook. All of the attributes must be specified.
If you wish to delete any of the optional attributes, pass them in as
None. | 3.075685 | 4.329123 | 0.710464 |
return self._manager.update_webhook(scaling_group=scaling_group,
policy=policy, webhook=webhook, name=name, metadata=metadata) | def update_webhook(self, scaling_group, policy, webhook, name=None,
metadata=None) | Updates the specified webhook. One or more of the parameters may be
specified. | 2.432724 | 3.207916 | 0.75835 |
return self._manager.update_webhook_metadata(scaling_group, policy,
webhook, metadata) | def update_webhook_metadata(self, scaling_group, policy, webhook, metadata) | Adds the given metadata dict to the existing metadata for the specified
webhook. | 4.379817 | 5.395453 | 0.811761 |
return self._manager.delete_webhook(scaling_group, policy, webhook) | def delete_webhook(self, scaling_group, policy, webhook) | Deletes the specified webhook from the policy. | 4.155046 | 4.349235 | 0.955351 |
if self.NAME_ATTR in self.__dict__ and self.HUMAN_ID:
return utils.to_slug(getattr(self, self.NAME_ATTR))
return None | def human_id(self) | Subclasses may override this to provide a pretty ID which can be used
for bash completion. | 6.799774 | 6.589183 | 1.03196 |
for (key, val) in six.iteritems(info):
if isinstance(key, six.text_type) and six.PY2:
key = key.encode(pyrax.get_encoding())
elif isinstance(key, bytes):
key = key.decode("utf-8")
setattr(self, key, val) | def _add_details(self, info) | Takes the dict returned by the API call and sets the
corresponding attributes on the object. | 3.576081 | 3.755906 | 0.952122 |
# set 'loaded' first ... so if we have to bail, we know we tried.
self.loaded = True
if not hasattr(self.manager, "get"):
return
if not self.get_details:
return
new = self.manager.get(self)
if new:
self._add_details(new._info) | def get(self) | Gets the details for the object. | 8.849798 | 8.001867 | 1.105967 |
# set 'loaded' first ... so if we have to bail, we know we tried.
self.loaded = True
if not hasattr(self.manager, "delete"):
return
self.manager.delete(self) | def delete(self) | Deletes the object. | 10.632427 | 10.439026 | 1.018527 |
return self._manager.list(limit=limit, marker=marker) | def list(self, limit=None, marker=None) | Returns a list of resource objects. Pagination is supported through the
optional 'marker' and 'limit' parameters. | 5.482921 | 6.665445 | 0.822589 |
if self.timeout:
kwargs["timeout"] = self.timeout
kwargs["verify"] = self.verify_ssl
kwargs.setdefault("headers", kwargs.get("headers", {}))
kwargs["headers"]["User-Agent"] = self.user_agent
kwargs["headers"]["Accept"] = "application/json"
if ("body" in kwargs) or ("data" in kwargs):
if "Content-Type" not in kwargs["headers"]:
kwargs["headers"]["Content-Type"] = "application/json"
elif kwargs["headers"]["Content-Type"] is None:
del kwargs["headers"]["Content-Type"]
# Allow subclasses to add their own headers
self._add_custom_headers(kwargs["headers"])
resp, body = pyrax.http.request(method, uri, *args, **kwargs)
if resp.status_code >= 400:
raise exc.from_response(resp, body)
return resp, body | def request(self, uri, method, *args, **kwargs) | Formats the request into a dict representing the headers
and body that will be used to make the API call. | 2.224459 | 2.233629 | 0.995895 |
start_time = time.time()
resp, body = self.request(uri, method, **kwargs)
self.times.append(("%s %s" % (method, uri),
start_time, time.time()))
return resp, body | def _time_request(self, uri, method, **kwargs) | Wraps the request call and records the elapsed time. | 3.068829 | 2.855229 | 1.07481 |
id_svc = self.identity
if not all((self.management_url, id_svc.token, id_svc.tenant_id)):
id_svc.authenticate()
if not self.management_url:
# We've authenticated but no management_url has been set. This
# indicates that the service is not available.
raise exc.ServiceNotAvailable("The '%s' service is not available."
% self)
if uri.startswith("http"):
parsed = list(urllib.parse.urlparse(uri))
for pos, item in enumerate(parsed):
if pos < 2:
# Don't escape the scheme or netloc
continue
parsed[pos] = _safe_quote(parsed[pos])
safe_uri = urllib.parse.urlunparse(parsed)
else:
safe_uri = "%s%s" % (self.management_url, _safe_quote(uri))
# Perform the request once. If we get a 401 back then it
# might be because the auth token expired, so try to
# re-authenticate and try again. If it still fails, bail.
try:
kwargs.setdefault("headers", {})["X-Auth-Token"] = id_svc.token
if id_svc.tenant_id:
kwargs["headers"]["X-Auth-Project-Id"] = id_svc.tenant_id
resp, body = self._time_request(safe_uri, method, **kwargs)
return resp, body
except exc.Unauthorized as ex:
try:
id_svc.authenticate()
kwargs["headers"]["X-Auth-Token"] = id_svc.token
resp, body = self._time_request(safe_uri, method, **kwargs)
return resp, body
except exc.Unauthorized:
raise ex | def _api_request(self, uri, method, **kwargs) | Manages the request by adding any auth information, and retries
the request after authenticating if the initial request returned
and Unauthorized exception. | 2.769382 | 2.708906 | 1.022325 |
uri = "/%s" % self.uri_base
pagination_items = []
if limit is not None:
pagination_items.append("limit=%s" % limit)
if marker is not None:
pagination_items.append("marker=%s" % marker)
pagination = "&".join(pagination_items)
if pagination:
uri = "%s?%s" % (uri, pagination)
return self._list(uri, return_raw=return_raw, other_keys=other_keys) | def list(self, limit=None, marker=None, return_raw=False, other_keys=None) | Returns a list of resource objects. Pagination is supported through the
optional 'marker' and 'limit' parameters.
Some APIs do not follow the typical pattern in their responses, and the
BaseManager subclasses will have to parse the raw response to get the
desired information. For those cases, pass 'return_raw=True', and the
response and response_body will be returned unprocessed.
Another use case is when additional information is returned in the
response body. To have that returned, use the 'other_keys' parameter.
This can be either a single string or a list of strings that correspond
to keys in the response body. If specified, a 2-tuple is returned, with
the first element being the list of resources, and the second a dict
whose keys are the 'other_keys' items, and whose values are the
corresponding values in the response body, or None if no such key is
present. | 2.095409 | 2.171948 | 0.96476 |
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._head(uri) | def head(self, item) | Makes a HEAD request on a specific item. | 6.142974 | 4.764509 | 1.289319 |
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._get(uri) | def get(self, item) | Gets a specific item. | 5.345276 | 4.732759 | 1.129421 |
return_none = kwargs.pop("return_none", False)
return_raw = kwargs.pop("return_raw", False)
return_response = kwargs.pop("return_response", False)
body = self._create_body(name, *args, **kwargs)
return self._create("/%s" % self.uri_base, body,
return_none=return_none, return_raw=return_raw,
return_response=return_response) | def create(self, name, *args, **kwargs) | Subclasses need to implement the _create_body() method to return a dict
that will be used for the API request body.
For cases where no response is returned from the API on creation, pass
`return_none=True` so that the _create method doesn't expect one.
For cases where you do not want the _create method to attempt to parse
the response, but instead have it returned directly, pass
`return_raw=True`.
For cases where the API returns information in the response and not the
response_body, pass `return_response=True`. | 2.504457 | 1.88939 | 1.325537 |
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._delete(uri) | def delete(self, item) | Deletes the specified item. | 5.21912 | 4.837904 | 1.078798 |
if body:
resp, resp_body = self.api.method_post(uri, body=body)
else:
resp, resp_body = self.api.method_get(uri)
if return_raw:
return (resp, resp_body)
if obj_class is None:
obj_class = self.resource_class
data = self._data_from_response(resp_body)
ret = [obj_class(self, res, loaded=False) for res in data if res]
if other_keys:
keys = utils.coerce_to_list(other_keys)
other = [self._data_from_response(resp_body, key) for key in keys]
return (ret, other)
else:
return ret | def _list(self, uri, obj_class=None, body=None, return_raw=False,
other_keys=None) | Handles the communication with the API when getting
a full listing of the resources managed by this class. | 2.229269 | 2.211453 | 1.008056 |
if key:
data = resp_body.get(key)
else:
data = resp_body.get(self.plural_response_key, resp_body)
# NOTE(ja): some services, such as keystone returns values as list as
# {"values": [ ... ]} unlike other services which just return the
# list.
if isinstance(data, dict):
try:
data = data["values"]
except KeyError:
pass
return data | def _data_from_response(self, resp_body, key=None) | This works for most API responses, but some don't structure their
listing responses the same way, so overriding this method allows
subclasses to handle extraction for those outliers. | 4.714119 | 4.483214 | 1.051504 |
resp, resp_body = self.api.method_head(uri)
return resp | def _head(self, uri) | Handles the communication with the API when performing a HEAD request
on a specific resource managed by this class. Returns the headers
contained in the response. | 7.148768 | 7.989288 | 0.894794 |
resp, resp_body = self.api.method_get(uri)
return self.resource_class(self, resp_body, self.response_key,
loaded=True) | def _get(self, uri) | Handles the communication with the API when getting
a specific resource managed by this class. | 5.852027 | 6.224874 | 0.940104 |
self.run_hooks("modify_body_for_create", body, **kwargs)
resp, resp_body = self.api.method_post(uri, body=body)
if return_none:
# No response body
return
elif return_response:
return resp
elif return_raw:
if self.response_key:
return resp_body[self.response_key]
else:
return resp_body
return self.resource_class(self, resp_body, self.response_key) | def _create(self, uri, body, return_none=False, return_raw=False,
return_response=None, **kwargs) | Handles the communication with the API when creating a new
resource managed by this class. | 2.943446 | 3.168861 | 0.928866 |
self.run_hooks("modify_body_for_update", body, **kwargs)
resp, resp_body = self.api.method_put(uri, body=body)
return resp_body | def _update(self, uri, body, **kwargs) | Handles the communication with the API when updating
a specific resource managed by this class. | 4.075742 | 4.429297 | 0.920178 |
uri = "/%s/%s/action" % (self.uri_base, utils.get_id(item))
action_body = {action_type: body}
return self.api.method_post(uri, body=action_body) | def action(self, item, action_type, body={}) | Several API calls are lumped under the 'action' API. This
is the generic handler for such calls. | 3.816095 | 4.092414 | 0.93248 |
matches = self.findall(**kwargs)
num_matches = len(matches)
if not num_matches:
msg = "No %s matching: %s." % (self.resource_class.__name__, kwargs)
raise exc.NotFound(404, msg)
if num_matches > 1:
msg = "More than one %s matching: %s." % (
self.resource_class.__name__, kwargs)
raise exc.NoUniqueMatch(400, msg)
else:
return matches[0] | def find(self, **kwargs) | Finds a single item with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side. | 2.221501 | 2.184823 | 1.016788 |
rgn = region.upper()
try:
rgn_ep = [ep for ep in list(self.endpoints.values())
if ep.region.upper() == rgn][0]
except IndexError:
# See if there is an 'ALL' region.
try:
rgn_ep = [ep for ep in list(self.endpoints.values())
if ep.region.upper() == "ALL"][0]
except IndexError:
rgn_ep = None
return rgn_ep | def _ep_for_region(self, region) | Given a region, returns the Endpoint for that region, or the Endpoint
for the ALL region if no match is found. If no match is found, None
is returned, and it is up to the calling method to handle it
appropriately. | 2.593621 | 2.336643 | 1.109978 |
ep = self._ep_for_region(region)
if not ep:
raise exc.NoEndpointForRegion("There is no endpoint defined for the "
"region '%s' for the '%s' service." % (region,
self.service_type))
return ep.client | def get_client(self, region) | Returns an instance of the appropriate client class for the given
region. If there is no endpoint for that region, a NoEndpointForRegion
exception is raised. | 4.391091 | 3.695259 | 1.188304 |
return self._get_client(public=public, cached=False) | def get_new_client(self, public=True) | Returns a new instance of the client for this endpoint. | 8.554822 | 7.13245 | 1.199423 |
lowtype = url_type.lower()
if lowtype == "public":
return self.public_url
elif lowtype == "private":
return self.private_url
else:
raise ValueError("Valid values are 'public' or 'private'; "
"received '%s'." % url_type) | def get(self, url_type) | Accepts either 'public' or 'private' as a parameter, and returns the
corresponding value for 'public_url' or 'private_url', respectively. | 3.539908 | 2.964015 | 1.194295 |
if self.service == "compute" and not special:
# Novaclient requires different parameters.
client = pyrax.connect_to_cloudservers(region=self.region,
context=self.identity, verify_ssl=self.verify_ssl)
client.identity = self.identity
else:
client = clt_class(self.identity, region_name=self.region,
management_url=url, verify_ssl=self.verify_ssl)
return client | def _create_client(self, clt_class, url, public=True, special=False) | Creates a client instance for the service. | 4.571694 | 4.315624 | 1.059335 |
if not self.authenticated:
raise exc.NotAuthenticated("You must authenticate before trying "
"to create clients.")
clt = ep = None
mapped_service = self.service_mapping.get(service) or service
svc = self.services.get(mapped_service)
if svc:
ep = svc.endpoints.get(region)
if ep:
clt = ep._get_client(public=public, cached=cached,
client_class=client_class)
if not clt:
raise exc.NoSuchClient("There is no client available for the "
"service '%s' in the region '%s'." % (service, region))
return clt | def get_client(self, service, region, public=True, cached=True,
client_class=None) | Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
By default, if a client has already been created for the given service,
region, and public values, that will be returned. To force a new client
to be created, pass 'cached=False'. | 3.01169 | 3.073903 | 0.979761 |
self.username = username
self.password = password
self.tenant_id = tenant_id
if region:
self.region = region
if authenticate:
self.authenticate() | def set_credentials(self, username, password=None, region=None,
tenant_id=None, authenticate=False) | Sets the username and password directly. | 1.916133 | 1.938417 | 0.988504 |
self._creds_file = credential_file
cfg = ConfigParser.SafeConfigParser()
try:
if not cfg.read(credential_file):
# If the specified file does not exist, the parser returns an
# empty list.
raise exc.FileNotFound("The specified credential file '%s' "
"does not exist" % credential_file)
except ConfigParser.MissingSectionHeaderError as e:
# The file exists, but doesn't have the correct format.
raise exc.InvalidCredentialFile(e)
try:
self._read_credential_file(cfg)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
raise exc.InvalidCredentialFile(e)
if region:
self.region = region
if authenticate:
self.authenticate() | def set_credential_file(self, credential_file, region=None,
tenant_id=None, authenticate=False) | Reads in the credentials from the supplied file. It should be
a standard config file in the format:
[keystone]
username = myusername
password = top_secret
tenant_id = my_id | 2.840081 | 3.260944 | 0.870938 |
resp, resp_body = self._call_token_auth(token, tenant_id, tenant_name)
self._parse_response(resp_body)
self.authenticated = True | def auth_with_token(self, token, tenant_id=None, tenant_name=None) | If a valid token is already known, this call uses it to generate the
service catalog. | 4.99203 | 4.825711 | 1.034465 |
self.username = cfg.get("keystone", "username")
self.password = cfg.get("keystone", "password", raw=True)
self.tenant_id = cfg.get("keystone", "tenant_id") | def _read_credential_file(self, cfg) | Implements the default (keystone) behavior. | 2.428915 | 2.041613 | 1.189704 |
tenant_name = self.tenant_name or self.username
tenant_id = self.tenant_id or self.username
return {"auth": {"passwordCredentials":
{"username": tenant_name,
"password": self.password,
},
"tenantId": tenant_id}} | def _format_credentials(self) | Returns the current credentials in the format expected by
the authentication service. | 3.506447 | 3.391485 | 1.033897 |
if not uri.startswith("http"):
uri = "/".join((self.auth_endpoint.rstrip("/"), uri))
if admin:
# Admin calls use a different port
uri = re.sub(r":\d+/", ":35357/", uri)
if std_headers:
hdrs = self._standard_headers()
else:
hdrs = {}
if headers:
hdrs.update(headers)
kwargs = {"headers": hdrs}
if data:
kwargs["body"] = data
if "tokens" in uri:
# We'll handle the exception here
kwargs["raise_exception"] = False
return pyrax.http.request(mthd, uri, verify=self.verify_ssl, **kwargs) | def _call(self, mthd, uri, admin, data, headers, std_headers) | Handles all the common functionality required for API calls. Returns
the resulting response object. | 3.849363 | 3.743479 | 1.028285 |
self.username = username or self.username or pyrax.get_setting(
"username")
# Different identity systems may pass these under inconsistent names.
self.password = password or self.password or api_key or self.api_key
self.api_key = api_key or self.api_key or self.password
self.tenant_id = tenant_id or self.tenant_id or pyrax.get_setting(
"tenant_id")
creds = self._format_credentials()
headers = {"Content-Type": "application/json",
"Accept": "application/json",
}
resp, resp_body = self.method_post("tokens", data=creds,
headers=headers, std_headers=False)
if resp.status_code == 401:
# Invalid authorization
raise exc.AuthenticationFailed("Incorrect/unauthorized "
"credentials received")
elif 500 <= resp.status_code < 600:
# Internal Server Error
try:
error_msg = resp_body[list(resp_body.keys())[0]]["message"]
except (KeyError, AttributeError):
error_msg = "Service Currently Unavailable"
raise exc.InternalServerError(error_msg)
elif resp.status_code > 299:
try:
msg = resp_body[list(resp_body.keys())[0]]["message"]
except (KeyError, AttributeError):
msg = None
if msg:
err = "%s - %s." % (resp.reason, msg)
else:
err = "%s." % resp.reason
raise exc.AuthenticationFailed(err)
self._parse_response(resp_body)
self.authenticated = True | def authenticate(self, username=None, password=None, api_key=None,
tenant_id=None, connect=False) | Using the supplied credentials, connects to the specified
authentication endpoint and attempts to log in.
Credentials can either be passed directly to this method, or
previously-stored credentials can be used. If authentication is
successful, the token and service catalog information is stored, and
clients for each service and region are created.
The 'connect' parameter is retained for backwards compatibility. It no
longer has any effect. | 2.90687 | 2.958934 | 0.982405 |
access = resp["access"]
token = access.get("token")
self.token = token["id"]
self.tenant_id = token["tenant"]["id"]
self.tenant_name = token["tenant"]["name"]
self.expires = self._parse_api_time(token["expires"])
self.service_catalog = access.get("serviceCatalog")
self._parse_service_catalog()
user = access["user"]
self.user = {}
self.user["id"] = user["id"]
self.username = self.user["name"] = user["name"]
self.user["roles"] = user["roles"] | def _parse_response(self, resp) | Gets the authentication information from the returned JSON. | 2.566507 | 2.42633 | 1.057773 |
if not keyring:
# Module not installed
raise exc.KeyringModuleNotInstalled("The 'keyring' Python module "
"is not installed on this system.")
if username is None:
username = pyrax.get_setting("keyring_username")
if not username:
raise exc.KeyringUsernameMissing("No username specified for "
"keyring authentication.")
password = keyring.get_password("pyrax", username)
if password is None:
raise exc.KeyringPasswordNotFound("No password was found for the "
"username '%s'." % username)
style = self._creds_style or self._default_creds_style
# Keyring username may be different than the credentials. Use the
# existing username, if present; otherwise, use the supplied username.
username = self.username or username
if style == "apikey":
return self.authenticate(username=username, api_key=password)
else:
return self.authenticate(username=username, password=password) | def keyring_auth(self, username=None) | Uses the keyring module to retrieve the user's password or api_key. | 3.50395 | 3.392343 | 1.0329 |
self.username = ""
self.password = ""
self.tenant_id = ""
self.tenant_name = ""
self.token = ""
self.expires = None
self.region = ""
self._creds_file = None
self.api_key = ""
self.services = utils.DotDict()
self.regions = utils.DotDict()
self.authenticated = False | def unauthenticate(self) | Clears out any credentials, tokens, and service catalog info. | 3.772679 | 3.317138 | 1.13733 |
self.authenticated = self._has_valid_token()
if force or not self.authenticated:
self.authenticate()
return self.token | def get_token(self, force=False) | Returns the auth token, if it is valid. If not, calls the auth endpoint
to get a new token. Passing 'True' to 'force' forces a call for a new
token, even if there already is a valid token. | 4.665604 | 3.795609 | 1.229211 |
return bool(self.token and (self.expires > datetime.datetime.now())) | def _has_valid_token(self) | This only checks the token's existence and expiration. If it has been
invalidated on the server, this method may indicate that the token is
valid when it might actually not be. | 8.38157 | 4.744931 | 1.766426 |
resp, resp_body = self.method_get("tokens/%s" % self.token, admin=True)
if resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You must be an admin to make this "
"call.")
return resp_body.get("access") | def list_tokens(self) | ADMIN ONLY. Returns a dict containing tokens, endpoints, user info, and
role metadata. | 5.405207 | 5.01067 | 1.078739 |
if token is None:
token = self.token
resp, resp_body = self.method_head("tokens/%s" % token, admin=True)
if resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You must be an admin to make this "
"call.")
return 200 <= resp.status_code < 300 | def check_token(self, token=None) | ADMIN ONLY. Returns True or False, depending on whether the current
token is valid. | 3.798326 | 3.620229 | 1.049195 |
resp, resp_body = self.method_delete("tokens/%s" % token, admin=True)
if resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You must be an admin to make this "
"call.")
return 200 <= resp.status_code < 300 | def revoke_token(self, token) | ADMIN ONLY. Returns True or False, depending on whether deletion of the
specified token was successful. | 4.096735 | 4.067643 | 1.007152 |
resp, resp_body = self.method_get("users", admin=True)
if resp.status_code in (401, 403, 404):
raise exc.AuthorizationFailure("You are not authorized to list "
"users.")
# The API is inconsistent; if only one user exists, it does not return
# a list.
if "users" in resp_body:
users = resp_body["users"]
else:
users = resp_body
# The returned values may contain password data. Strip that out.
for user in users:
bad_keys = [key for key in list(user.keys())
if "password" in key.lower()]
for bad_key in bad_keys:
user.pop(bad_key)
return [User(self, user) for user in users] | def list_users(self) | ADMIN ONLY. Returns a list of objects for all users for the tenant
(account) if this request is issued by a user holding the admin role
(identity:user-admin). | 3.323654 | 3.320531 | 1.00094 |
# NOTE: the OpenStack docs say that the name key in the following dict
# is supposed to be 'username', but the service actually expects 'name'.
data = {"user": {
"username": name,
"email": email,
"enabled": enabled,
}}
if password:
data["user"]["OS-KSADM:password"] = password
resp, resp_body = self.method_post("users", data=data, admin=True)
if resp.status_code == 201:
return User(self, resp_body.get("user", resp_body))
elif resp.status_code in (401, 403, 404):
raise exc.AuthorizationFailure("You are not authorized to create "
"users.")
elif resp.status_code == 409:
raise exc.DuplicateUser("User '%s' already exists." % name)
elif resp.status_code == 400:
message = resp_body["badRequest"]["message"]
if "Expecting valid email address" in message:
raise exc.InvalidEmail("%s is not valid" % email)
else:
raise exc.BadRequest(message) | def create_user(self, name, email, password=None, enabled=True) | ADMIN ONLY. Creates a new user for this tenant (account). The username
and email address must be supplied. You may optionally supply the
password for this user; if not, the API server generates a password and
return it in the 'password' attribute of the resulting User object.
NOTE: this is the ONLY time the password is returned; after the initial
user creation, there is NO WAY to retrieve the user's password.
You may also specify that the user should be created but not active by
passing False to the enabled parameter. | 3.062975 | 3.174479 | 0.964875 |
user_id = utils.get_id(user)
uri = "users/%s" % user_id
resp, resp_body = self.method_delete(uri)
if resp.status_code == 404:
raise exc.UserNotFound("User '%s' does not exist." % user)
elif resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You are not authorized to delete "
"users.") | def delete_user(self, user) | ADMIN ONLY. Removes the user from the system. There is no 'undo'
available, so you should be certain that the user specified is the user
you wish to delete. | 2.812135 | 2.786849 | 1.009073 |
user_id = utils.get_id(user)
uri = "users/%s/roles" % user_id
resp, resp_body = self.method_get(uri)
if resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You are not authorized to list "
"user roles.")
roles = resp_body.get("roles")
return roles | def list_roles_for_user(self, user) | ADMIN ONLY. Returns a list of roles for the specified user. Each role
will be a 3-tuple, consisting of (role_id, role_name,
role_description). | 3.114063 | 3.336914 | 0.933216 |
if not user:
user = self.user
user_id = utils.get_id(user)
uri = "users/%s/OS-KSADM/credentials" % user_id
resp, resp_body = self.method_get(uri)
return resp_body.get("credentials") | def list_credentials(self, user=None) | Returns a user's non-password credentials. If no user is specified, the
credentials for the currently authenticated user are returned.
You cannot retrieve passwords by this or any other means. | 3.324213 | 3.363164 | 0.988418 |
resp, resp_body = self.method_get("tenants", admin=admin)
if 200 <= resp.status_code < 300:
tenants = resp_body.get("tenants", [])
return [Tenant(self, tenant) for tenant in tenants]
elif resp.status_code in (401, 403):
raise exc.AuthorizationFailure("You are not authorized to list "
"tenants.")
else:
raise exc.TenantNotFound("Could not get a list of tenants.") | def _list_tenants(self, admin) | Returns either a list of all tenants (admin=True), or the tenant for
the currently-authenticated user (admin=False). | 2.545492 | 2.659125 | 0.957267 |
data = {"tenant": {
"name": name,
"enabled": enabled,
}}
if description:
data["tenant"]["description"] = description
resp, resp_body = self.method_post("tenants", data=data)
return Tenant(self, resp_body) | def create_tenant(self, name, description=None, enabled=True) | ADMIN ONLY. Creates a new tenant. | 2.876423 | 2.929576 | 0.981857 |
tenant_id = utils.get_id(tenant)
data = {"tenant": {
"enabled": enabled,
}}
if name:
data["tenant"]["name"] = name
if description:
data["tenant"]["description"] = description
resp, resp_body = self.method_put("tenants/%s" % tenant_id, data=data)
return Tenant(self, resp_body) | def update_tenant(self, tenant, name=None, description=None, enabled=True) | ADMIN ONLY. Updates an existing tenant. | 2.580384 | 2.585702 | 0.997944 |
tenant_id = utils.get_id(tenant)
uri = "tenants/%s" % tenant_id
resp, resp_body = self.method_delete(uri)
if resp.status_code == 404:
raise exc.TenantNotFound("Tenant '%s' does not exist." % tenant) | def delete_tenant(self, tenant) | ADMIN ONLY. Removes the tenant from the system. There is no 'undo'
available, so you should be certain that the tenant specified is the
tenant you wish to delete. | 3.192826 | 3.091905 | 1.03264 |
uri = "OS-KSADM/roles"
pagination_items = []
if service_id is not None:
pagination_items.append("serviceId=%s" % service_id)
if limit is not None:
pagination_items.append("limit=%s" % limit)
if marker is not None:
pagination_items.append("marker=%s" % marker)
pagination = "&".join(pagination_items)
if pagination:
uri = "%s?%s" % (uri, pagination)
resp, resp_body = self.method_get(uri)
roles = resp_body.get("roles", [])
return [Role(self, role) for role in roles] | def list_roles(self, service_id=None, limit=None, marker=None) | Returns a list of all global roles for users, optionally limited by
service. Pagination can be handled through the standard 'limit' and
'marker' parameters. | 1.997368 | 1.968426 | 1.014703 |
uri = "OS-KSADM/roles/%s" % utils.get_id(role)
resp, resp_body = self.method_get(uri)
role = Role(self, resp_body.get("role"))
return role | def get_role(self, role) | Returns a Role object representing the specified parameter. The 'role'
parameter can be either an existing Role object, or the ID of the role.
If an invalid role is passed, a NotFound exception is raised. | 4.210652 | 4.039396 | 1.042396 |
uri = "users/%s/roles/OS-KSADM/%s" % (utils.get_id(user),
utils.get_id(role))
resp, resp_body = self.method_put(uri) | def add_role_to_user(self, role, user) | Adds the specified role to the specified user.
There is no return value upon success. Passing a non-existent role or
user raises a NotFound exception. | 4.864896 | 4.753118 | 1.023517 |
uri = "users/%s/roles/OS-KSADM/%s" % (utils.get_id(user),
utils.get_id(role))
resp, resp_body = self.method_delete(uri) | def delete_role_from_user(self, role, user) | Deletes the specified role from the specified user.
There is no return value upon success. Passing a non-existent role or
user raises a NotFound exception. | 4.516836 | 4.717545 | 0.957455 |
try:
reg_groups = API_DATE_PATTERN.match(timestr).groups()
yr, mth, dy, hr, mn, sc, off_sign, off_hr, off_mn = reg_groups
except AttributeError:
# UTC dates don't show offsets.
utc_groups = UTC_API_DATE_PATTERN.match(timestr).groups()
yr, mth, dy, hr, mn, sc = utc_groups
off_sign = "+"
off_hr = off_mn = 0
base_dt = datetime.datetime(int(yr), int(mth), int(dy), int(hr),
int(mn), int(sc))
delta = datetime.timedelta(hours=int(off_hr), minutes=int(off_mn))
if off_sign == "+":
# Time is greater than UTC
ret = base_dt - delta
else:
ret = base_dt + delta
return ret | def _parse_api_time(timestr) | Typical expiration times returned from the auth server are in this
format:
2012-05-02T14:27:40.000-05:00
They can also be returned as a UTC value in this format:
2012-05-02T14:27:40.000Z
This method returns a proper datetime object from either of these
formats. | 2.772521 | 2.78087 | 0.996998 |
try:
return super(CloudNetwork, self).delete()
except exc.Forbidden as e:
# Network is in use
raise exc.NetworkInUse("Cannot delete a network in use by a server.") | def delete(self) | Wraps the standard delete() method to catch expected exceptions and
raise the appropriate pyrax exceptions. | 8.505099 | 6.15144 | 1.382619 |
label = label or name
body = {"network": {
"label": label,
"cidr": cidr,
}}
return body | def _create_body(self, name, label=None, cidr=None) | Used to create the dict required to create a network. Accepts either
'label' or 'name' as the keyword parameter for the label attribute. | 4.422954 | 3.960646 | 1.116725 |
self._manager = CloudNetworkManager(self, resource_class=CloudNetwork,
response_key="network", uri_base="os-networksv2") | def _configure_manager(self) | Creates the Manager instance to handle networks. | 16.008062 | 10.154506 | 1.576449 |
try:
return super(CloudNetworkClient, self).create(label=label,
name=name, cidr=cidr)
except exc.BadRequest as e:
msg = e.message
if "too many networks" in msg:
raise exc.NetworkCountExceeded("Cannot create network; the "
"maximum number of isolated networks already exist.")
elif "does not contain enough" in msg:
raise exc.NetworkCIDRInvalid("Networks must contain two or "
"more hosts; the CIDR '%s' is too restrictive." % cidr)
elif "CIDR is malformed" in msg:
raise exc.NetworkCIDRMalformed("The CIDR '%s' is not valid." % cidr)
else:
# Something unexpected
raise | def create(self, label=None, name=None, cidr=None) | Wraps the basic create() call to handle specific failures. | 4.226232 | 4.139718 | 1.020898 |
try:
return super(CloudNetworkClient, self).delete(network)
except exc.Forbidden as e:
# Network is in use
raise exc.NetworkInUse("Cannot delete a network in use by a server.") | def delete(self, network) | Wraps the standard delete() method to catch expected exceptions and
raise the appropriate pyrax exceptions. | 6.53441 | 5.475096 | 1.193479 |
networks = self.list()
match = [network for network in networks
if network.label == label]
if not match:
raise exc.NetworkNotFound("No network with the label '%s' exists" %
label)
elif len(match) > 1:
raise exc.NetworkLabelNotUnique("There were %s matches for the label "
"'%s'." % (len(match), label))
return match[0] | def find_network_by_label(self, label) | This is inefficient; it gets all the networks and then filters on
the client side to find the matching name. | 3.023101 | 2.874942 | 1.051535 |
return _get_server_networks(network, public=public, private=private,
key=key) | def get_server_networks(self, network, public=False, private=False,
key=None) | Creates the dict of network UUIDs required by Cloud Servers when
creating a new server with isolated networks. By default, the UUID
values are returned with the key of "net-id", which is what novaclient
expects. Other tools may require different values, such as 'uuid'. If
that is the case, pass the desired key as the 'key' parameter.
By default only this network is included. If you wish to create a
server that has either the public (internet) or private (ServiceNet)
networks, you have to pass those parameters in with values of True. | 3.314265 | 4.632028 | 0.715511 |
value = int(round2(value))
if value > 9:
value = 9
elif value < 1:
value = 1
return value | def _openTypeOS2WidthClassFormatter(value) | >>> _openTypeOS2WidthClassFormatter(-2)
1
>>> _openTypeOS2WidthClassFormatter(0)
1
>>> _openTypeOS2WidthClassFormatter(5.4)
5
>>> _openTypeOS2WidthClassFormatter(9.6)
9
>>> _openTypeOS2WidthClassFormatter(12)
9 | 3.654417 | 4.511341 | 0.810051 |
for attr, (formatter, factorIndex) in _infoAttrs.items():
if hasattr(self, attr):
v = getattr(self, attr)
if v is not None:
if formatter is not None:
v = formatter(v)
setattr(otherInfoObject, attr, v)
if hasattr(self, "postscriptWeightName"):
otherInfoObject.postscriptWeightName = self.postscriptWeightName | def extractInfo(self, otherInfoObject) | >>> from fontMath.test.test_mathInfo import _TestInfoObject, _testData
>>> from fontMath.mathFunctions import _roundNumber
>>> info1 = MathInfo(_TestInfoObject())
>>> info2 = info1 * 2.5
>>> info3 = _TestInfoObject()
>>> info2.extractInfo(info3)
>>> written = {}
>>> expected = {}
>>> for attr, value in _testData.items():
... if value is None:
... continue
... written[attr] = getattr(info2, attr)
... if isinstance(value, list):
... expectedValue = [_roundNumber(v * 2.5) for v in value]
... elif isinstance(value, int):
... expectedValue = _roundNumber(value * 2.5)
... else:
... expectedValue = value * 2.5
... expected[attr] = expectedValue
>>> sorted(expected) == sorted(written)
True | 3.580038 | 4.059968 | 0.88179 |
pairs = []
for name, anchors1 in anchorDict1.items():
if name not in anchorDict2:
continue
anchors2 = anchorDict2[name]
# align with matching identifiers
removeFromAnchors1 = []
for anchor1 in anchors1:
match = None
identifier = anchor1[0]
for anchor2 in anchors2:
if anchor2[0] == identifier:
match = anchor2
break
if match is not None:
anchor2 = match
anchors2.remove(anchor2)
removeFromAnchors1.append(anchor1)
a1 = dict(name=name, identifier=identifier)
a1["x"], a1["y"], a1["color"] = anchor1[1:]
a2 = dict(name=name, identifier=identifier)
a2["x"], a2["y"], a2["color"] = anchor2[1:]
pairs.append((a1, a2))
for anchor1 in removeFromAnchors1:
anchors1.remove(anchor1)
if not anchors1 or not anchors2:
continue
# align by index
while 1:
anchor1 = anchors1.pop(0)
anchor2 = anchors2.pop(0)
a1 = dict(name=name)
a1["identifier"], a1["x"], a1["y"], a1["color"] = anchor1
a2 = dict(name=name, identifier=identifier)
a2["identifier"], a2["x"], a2["y"], a2["color"] = anchor2
pairs.append((a1, a2))
if not anchors1:
break
if not anchors2:
break
return pairs | def _pairAnchors(anchorDict1, anchorDict2) | Anchors are paired using the following rules:
Matching Identifiers
--------------------
>>> anchors1 = {
... "test" : [
... (None, 1, 2, None),
... ("identifier 1", 3, 4, None)
... ]
... }
>>> anchors2 = {
... "test" : [
... ("identifier 1", 1, 2, None),
... (None, 3, 4, None)
... ]
... }
>>> expected = [
... (
... dict(name="test", identifier=None, x=1, y=2, color=None),
... dict(name="test", identifier=None, x=3, y=4, color=None)
... ),
... (
... dict(name="test", identifier="identifier 1", x=3, y=4, color=None),
... dict(name="test", identifier="identifier 1", x=1, y=2, color=None)
... )
... ]
>>> _pairAnchors(anchors1, anchors2) == expected
True
Mismatched Identifiers
----------------------
>>> anchors1 = {
... "test" : [
... ("identifier 1", 3, 4, None)
... ]
... }
>>> anchors2 = {
... "test" : [
... ("identifier 2", 1, 2, None),
... ]
... }
>>> expected = [
... (
... dict(name="test", identifier="identifier 1", x=3, y=4, color=None),
... dict(name="test", identifier="identifier 2", x=1, y=2, color=None)
... )
... ]
>>> _pairAnchors(anchors1, anchors2) == expected
True | 1.901875 | 1.832301 | 1.037971 |
n = MathGlyph(None)
n.name = self.name
if self.unicodes is not None:
n.unicodes = list(self.unicodes)
n.width = self.width
n.height = self.height
n.note = self.note
n.lib = deepcopy(dict(self.lib))
return n | def copyWithoutMathSubObjects(self) | return a new MathGlyph containing all data except:
contours
components
anchors
guidelines
this is used mainly for internal glyph math. | 3.07843 | 2.994777 | 1.027933 |
copiedGlyph = self.copyWithoutMathSubObjects()
# misc
copiedGlyph.width = _roundNumber(self.width, digits)
copiedGlyph.height = _roundNumber(self.height, digits)
# contours
copiedGlyph.contours = []
if self.contours:
copiedGlyph.contours = _roundContours(self.contours, digits)
# components
copiedGlyph.components = []
if self.components:
copiedGlyph.components = _roundComponents(self.components, digits)
# guidelines
copiedGlyph.guidelines = []
if self.guidelines:
copiedGlyph.guidelines = _roundGuidelines(self.guidelines, digits)
# anchors
copiedGlyph.anchors = []
if self.anchors:
copiedGlyph.anchors = _roundAnchors(self.anchors, digits)
# image
copiedGlyph.image = None
if self.image:
copiedGlyph.image = _roundImage(self.image, digits)
return copiedGlyph | def round(self, digits=None) | round the geometry. | 2.10793 | 2.051564 | 1.027475 |
if filterRedundantPoints:
pointPen = FilterRedundantPointPen(pointPen)
for contour in self.contours:
pointPen.beginPath(identifier=contour["identifier"])
for segmentType, pt, smooth, name, identifier in contour["points"]:
pointPen.addPoint(pt=pt, segmentType=segmentType, smooth=smooth, name=name, identifier=identifier)
pointPen.endPath()
for component in self.components:
pointPen.addComponent(component["baseGlyph"], component["transformation"], identifier=component["identifier"]) | def drawPoints(self, pointPen, filterRedundantPoints=False) | draw self using pointPen | 2.878642 | 2.803967 | 1.026632 |
from fontTools.pens.pointPen import PointToSegmentPen
pointPen = PointToSegmentPen(pen)
self.drawPoints(pointPen, filterRedundantPoints=filterRedundantPoints) | def draw(self, pen, filterRedundantPoints=False) | draw self using pen | 2.58038 | 2.337399 | 1.103954 |
if pointPen is None:
pointPen = glyph.getPointPen()
glyph.clearContours()
glyph.clearComponents()
glyph.clearAnchors()
glyph.clearGuidelines()
glyph.lib.clear()
cleanerPen = FilterRedundantPointPen(pointPen)
self.drawPoints(cleanerPen)
glyph.anchors = [dict(anchor) for anchor in self.anchors]
glyph.guidelines = [_compressGuideline(guideline) for guideline in self.guidelines]
glyph.image = _compressImage(self.image)
glyph.lib = deepcopy(dict(self.lib))
glyph.width = self.width
glyph.height = self.height
glyph.note = self.note
if not onlyGeometry:
glyph.name = self.name
glyph.unicodes = list(self.unicodes)
return glyph | def extractGlyph(self, glyph, pointPen=None, onlyGeometry=False) | "rehydrate" to a glyph. this requires
a glyph as an argument. if a point pen other
than the type of pen returned by glyph.getPointPen()
is required for drawing, send this the needed point pen. | 3.360618 | 3.225513 | 1.041886 |
self.contours.append(
dict(identifier=self._contourIdentifier, points=[])
)
contourPoints = self.contours[-1]["points"]
points = self._points
# move offcurves at the beginning of the contour to the end
haveOnCurve = False
for point in points:
if point[0] is not None:
haveOnCurve = True
break
if haveOnCurve:
while 1:
if points[0][0] is None:
point = points.pop(0)
points.append(point)
else:
break
# convert lines to curves
holdingOffCurves = []
for index, point in enumerate(points):
segmentType = point[0]
if segmentType == "line":
pt, smooth, name, identifier = point[1:]
prevPt = points[index - 1][1]
if index == 0:
holdingOffCurves.append((None, prevPt, False, None, None))
holdingOffCurves.append((None, pt, False, None, None))
else:
contourPoints.append((None, prevPt, False, None, None))
contourPoints.append((None, pt, False, None, None))
contourPoints.append(("curve", pt, smooth, name, identifier))
else:
contourPoints.append(point)
contourPoints.extend(holdingOffCurves) | def _flushContour(self) | This normalizes the contour so that:
- there are no line segments. in their place will be
curve segments with the off curves positioned on top
of the previous on curve and the new curve on curve.
- the contour starts with an on curve | 3.065759 | 2.923267 | 1.048744 |
if isinstance(matrix, ShallowTransform):
return matrix
off, scl, rot = MathTransform(matrix).decompose()
return ShallowTransform(off, scl, rot) | def matrixToMathTransform(matrix) | Take a 6-tuple and return a ShallowTransform object. | 7.715903 | 4.933952 | 1.563838 |
m = MathTransform().compose(mathTransform.offset, mathTransform.scale, mathTransform.rotation)
return tuple(m) | def mathTransformToMatrix(mathTransform) | Take a ShallowTransform object and return a 6-tuple. | 7.442397 | 6.200935 | 1.200206 |
return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1))) | def _linearInterpolationTransformMatrix(matrix1, matrix2, value) | Linear, 'oldstyle' interpolation of the transform matrix. | 2.936886 | 3.285596 | 0.893867 |
m1 = MathTransform(matrix1)
m2 = MathTransform(matrix2)
return tuple(m1.interpolate(m2, value)) | def _polarDecomposeInterpolationTransformation(matrix1, matrix2, value) | Interpolate using the MathTransform method. | 4.378768 | 3.426025 | 1.27809 |
off, scl, rot = MathTransform(matrix1).decompose()
m1 = ShallowTransform(off, scl, rot)
off, scl, rot = MathTransform(matrix2).decompose()
m2 = ShallowTransform(off, scl, rot)
m3 = m1 + value * (m2-m1)
m3 = MathTransform().compose(m3.offset, m3.scale, m3.rotation)
return tuple(m3) | def _mathPolarDecomposeInterpolationTransformation(matrix1, matrix2, value) | Interpolation with ShallowTransfor, wrapped by decompose / compose actions. | 3.560817 | 3.069764 | 1.159964 |
fact = lib.EnvGetNextFact(self._env, ffi.NULL)
while fact != ffi.NULL:
yield new_fact(self._env, fact)
fact = lib.EnvGetNextFact(self._env, fact) | def facts(self) | Iterate over the asserted Facts. | 5.230927 | 4.611324 | 1.134366 |
template = lib.EnvGetNextDeftemplate(self._env, ffi.NULL)
while template != ffi.NULL:
yield Template(self._env, template)
template = lib.EnvGetNextDeftemplate(self._env, template) | def templates(self) | Iterate over the defined Templates. | 6.192729 | 4.93357 | 1.255223 |
deftemplate = lib.EnvFindDeftemplate(self._env, name.encode())
if deftemplate == ffi.NULL:
raise LookupError("Template '%s' not found" % name)
return Template(self._env, deftemplate) | def find_template(self, name) | Find the Template by its name. | 4.814694 | 4.301284 | 1.119362 |
fact = lib.EnvAssertString(self._env, string.encode())
if fact == ffi.NULL:
raise CLIPSError(self._env)
return new_fact(self._env, fact) | def assert_string(self, string) | Assert a fact as string. | 10.080298 | 7.667991 | 1.314595 |
facts = facts.encode()
if os.path.exists(facts):
ret = lib.EnvLoadFacts(self._env, facts)
if ret == -1:
raise CLIPSError(self._env)
else:
ret = lib.EnvLoadFactsFromString(self._env, facts, -1)
if ret == -1:
raise CLIPSError(self._env)
return ret | def load_facts(self, facts) | Load a set of facts into the CLIPS data base.
The C equivalent of the CLIPS load-facts command.
Facts can be loaded from a string or from a text file. | 3.800544 | 3.138012 | 1.211131 |
ret = lib.EnvSaveFacts(self._env, path.encode(), mode)
if ret == -1:
raise CLIPSError(self._env)
return ret | def save_facts(self, path, mode=SaveMode.LOCAL_SAVE) | Save the facts in the system to the specified file.
The Python equivalent of the CLIPS save-facts command. | 7.54968 | 5.552894 | 1.359594 |
# https://sourceforge.net/p/clipsrules/discussion/776945/thread/4f04bb9e/
if self.index == 0:
return False
return bool(lib.EnvFactExistp(self._env, self._fact)) | def asserted(self) | True if the fact has been asserted within CLIPS. | 17.778553 | 12.197663 | 1.457538 |
return Template(
self._env, lib.EnvFactDeftemplate(self._env, self._fact)) | def template(self) | The associated Template. | 56.107574 | 35.939415 | 1.561171 |
if self.asserted:
raise RuntimeError("Fact already asserted")
lib.EnvAssignFactSlotDefaults(self._env, self._fact)
if lib.EnvAssert(self._env, self._fact) == ffi.NULL:
raise CLIPSError(self._env) | def assertit(self) | Assert the fact within the CLIPS environment. | 11.961689 | 8.740401 | 1.368551 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.