Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def line_plot(df, x='year', y='value', ax=None, legend=None, title=True,
color=None, marker=None, linestyle=None, cmap=None,
fill_between=None, final_ranges=None,
rm_legend_label=[], **kwargs):
if ax is None:
fig, ax... | [
"Plot data as lines with or without markers.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n x : string, optional\n The column to use for x-axis values\n default: year\n y : string, optional\n The column to use for y-axis values\n... |
Please provide a description of the function:def set_panel_label(label, ax=None, x=0.05, y=0.9):
def _lim_loc(lim, loc):
return lim[0] + (lim[1] - lim[0]) * loc
if ax is not None:
ax.text(_lim_loc(ax.get_xlim(), x), _lim_loc(ax.get_ylim(), y), label)
else:
plt.text(_lim_loc(plt... | [
"Add a panel label to the figure/axes, by default in the top-left corner\n\n Parameters\n ----------\n label : str\n text to be added as panel label\n ax : matplotlib.Axes, optional\n panel to which to add the panel label\n x : number, default 0.05\n relative location of label to... |
Please provide a description of the function:def logger():
global _LOGGER
if _LOGGER is None:
logging.basicConfig()
_LOGGER = logging.getLogger()
_LOGGER.setLevel('INFO')
return _LOGGER | [
"Access global logger"
] |
Please provide a description of the function:def nodes(self):
if not hasattr(self, '_nodes'):
base_url = "{}/{}".format(NodeBalancerConfig.api_endpoint, NodeBalancerNode.derived_url_path)
result = self._client._get_objects(base_url, NodeBalancerNode, model=self, parent_id=(self.... | [
"\n This is a special derived_class relationship because NodeBalancerNode is the\n only api object that requires two parent_ids\n "
] |
Please provide a description of the function:def load_ssl_data(self, cert_file, key_file):
# we're disabling warnings here because these attributes are defined dynamically
# through linode.objects.Base, and pylint isn't privy
if os.path.isfile(os.path.expanduser(cert_file)):
... | [
"\n A convenience method that loads a cert and a key from files and sets them\n on this object. This can make enabling ssl easier (instead of you needing\n to load the files yourself).\n\n This does *not* change protocol/port for you, or save anything. Once this\n is called, you... |
Please provide a description of the function:def load_and_validate_keys(authorized_keys):
if not authorized_keys:
return None
if not isinstance(authorized_keys, list):
authorized_keys = [authorized_keys]
ret = []
for k in authorized_keys:
accepted_types = ('ssh-dss', 'ssh... | [
"\n Loads authorized_keys as taken by :any:`instance_create`,\n :any:`disk_create` or :any:`rebuild`, and loads in any keys from any files\n provided.\n\n :param authorized_keys: A list of keys or paths to keys, or a single key\n\n :returns: A list of raw keys\n :raises: ValueError if keys in auth... |
Please provide a description of the function:def attach(self, to_linode, config=None):
result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self,
data={
"linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode,
... | [
"\n Attaches this Volume to the given Linode\n "
] |
Please provide a description of the function:def detach(self):
self._client.post('{}/detach'.format(Volume.api_endpoint), model=self)
return True | [
"\n Detaches this Volume if it is attached\n "
] |
Please provide a description of the function:def resize(self, size):
result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self,
data={ "size": size }))
self._populate(result.json)
return True | [
"\n Resizes this Volume\n "
] |
Please provide a description of the function:def clone(self, label):
result = self._client.post('{}/clone'.format(Volume.api_endpoint),
model=self, data={'label': label})
if not 'id' in result:
raise UnexpectedResponseError('Unexpected response cloning volume!')
... | [
"\n Clones this volume to a new volume in the same region with the given label\n\n :param label: The label for the new volume.\n\n :returns: The new volume object.\n "
] |
Please provide a description of the function:def _get_raw_objects(self):
if not hasattr(self, '_raw_objects'):
result = self._client.get(type(self).api_endpoint, model=self)
# I want to cache this to avoid making duplicate requests, but I don't
# want it in the __in... | [
"\n Helper function to populate the first page of raw objects for this tag.\n This has the side effect of creating the ``_raw_objects`` attribute of\n this object.\n "
] |
Please provide a description of the function:def objects(self):
data = self._get_raw_objects()
return PaginatedList.make_paginated_list(data, self._client, TaggedObjectProxy,
page_url=type(self).api_endpoint.format(**vars(self))) | [
"\n Returns a list of objects with this Tag. This list may contain any\n taggable object type.\n "
] |
Please provide a description of the function:def make_instance(cls, id, client, parent_id=None, json=None):
make_cls = CLASS_MAP.get(id) # in this case, ID is coming in as the type
if make_cls is None:
# we don't recognize this entity type - do nothing?
return None
... | [
"\n Overrides Base's ``make_instance`` to allow dynamic creation of objects\n based on the defined type in the response json.\n\n :param cls: The class this was called on\n :param id: The id of the instance to create\n :param client: The client to use for this instance\n :p... |
Please provide a description of the function:def resize(self, new_size):
self._client.post('{}/resize'.format(Disk.api_endpoint), model=self, data={"size": new_size})
return True | [
"\n Resizes this disk. The Linode Instance this disk belongs to must have\n sufficient space available to accommodate the new size, and must be\n offline.\n\n **NOTE** If resizing a disk down, the filesystem on the disk must still\n fit on the new disk size. You may need to resi... |
Please provide a description of the function:def _populate(self, json):
from .volume import Volume
DerivedBase._populate(self, json)
devices = {}
for device_index, device in json['devices'].items():
if not device:
devices[device_index] = None
... | [
"\n Map devices more nicely while populating.\n "
] |
Please provide a description of the function:def ips(self):
if not hasattr(self, '_ips'):
result = self._client.get("{}/ips".format(Instance.api_endpoint), model=self)
if not "ipv4" in result:
raise UnexpectedResponseError('Unexpected response loading IPs', json... | [
"\n The ips related collection is not normalized like the others, so we have to\n make an ad-hoc object to return for its response\n "
] |
Please provide a description of the function:def available_backups(self):
if not hasattr(self, '_avail_backups'):
result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self)
if not 'automatic' in result:
raise UnexpectedResponseError('Unexp... | [
"\n The backups response contains what backups are available to be restored.\n "
] |
Please provide a description of the function:def invalidate(self):
if hasattr(self, '_avail_backups'):
del self._avail_backups
if hasattr(self, '_ips'):
del self._ips
Base.invalidate(self) | [
" Clear out cached properties "
] |
Please provide a description of the function:def config_create(self, kernel=None, label=None, devices=[], disks=[],
volumes=[], **kwargs):
from .volume import Volume
hypervisor_prefix = 'sd' if self.hypervisor == 'kvm' else 'xvd'
device_names = [hypervisor_prefix + string.a... | [
"\n Creates a Linode Config with the given attributes.\n\n :param kernel: The kernel to boot with.\n :param label: The config label\n :param disks: The list of disks, starting at sda, to map to this config.\n :param volumes: The volumes, starting after the last disk, to map to thi... |
Please provide a description of the function:def enable_backups(self):
self._client.post("{}/backups/enable".format(Instance.api_endpoint), model=self)
self.invalidate()
return True | [
"\n Enable Backups for this Instance. When enabled, we will automatically\n backup your Instance's data so that it can be restored at a later date.\n For more information on Instance's Backups service and pricing, see our\n `Backups Page`_\n\n .. _Backups Page: https://www.linode... |
Please provide a description of the function:def ip_allocate(self, public=False):
result = self._client.post(
"{}/ips".format(Instance.api_endpoint),
model=self,
data={
"type": "ipv4",
"public": public,
})
if not '... | [
"\n Allocates a new :any:`IPAddress` for this Instance. Additional public\n IPs require justification, and you may need to open a :any:`SupportTicket`\n before you can add one. You may only have, at most, one private IP per\n Instance.\n\n :param public: If the new IP should be ... |
Please provide a description of the function:def rebuild(self, image, root_pass=None, authorized_keys=None, **kwargs):
ret_pass = None
if not root_pass:
ret_pass = Instance.generate_root_password()
root_pass = ret_pass
authorized_keys = load_and_validate_keys(au... | [
"\n Rebuilding an Instance deletes all existing Disks and Configs and deploys\n a new :any:`Image` to it. This can be used to reset an existing\n Instance or to install an Image on an empty Instance.\n\n :param image: The Image to deploy to this Instance\n :type image: str or Ima... |
Please provide a description of the function:def mutate(self):
self._client.post('{}/mutate'.format(Instance.api_endpoint), model=self)
return True | [
"\n Upgrades this Instance to the latest generation type\n "
] |
Please provide a description of the function:def initiate_migration(self):
self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self) | [
"\n Initiates a pending migration that is already scheduled for this Linode\n Instance\n "
] |
Please provide a description of the function:def clone(self, to_linode=None, region=None, service=None, configs=[], disks=[],
label=None, group=None, with_backups=None):
if to_linode and region:
raise ValueError('You may only specify one of "to_linode" and "region"')
if... | [
" Clones this linode into a new linode or into a new linode in the given region "
] |
Please provide a description of the function:def stats(self):
# TODO - this would be nicer if we formatted the stats
return self._client.get('{}/stats'.format(Instance.api_endpoint), model=self) | [
"\n Returns the JSON stats for this Instance\n "
] |
Please provide a description of the function:def stats_for(self, dt):
# TODO - this would be nicer if we formatted the stats
if not isinstance(dt, datetime):
raise TypeError('stats_for requires a datetime object!')
return self._client.get('{}/stats/'.format(dt.strftime('%Y/%... | [
"\n Returns stats for the month containing the given datetime\n "
] |
Please provide a description of the function:def _populate(self, json):
Base._populate(self, json)
mapped_udfs = []
for udf in self.user_defined_fields:
t = UserDefinedFieldType.text
choices = None
if hasattr(udf, 'oneof'):
t = UserDe... | [
"\n Override the populate method to map user_defined_fields to\n fancy values\n "
] |
Please provide a description of the function:def _populate(self, json):
super(InvoiceItem, self)._populate(json)
self.from_date = datetime.strptime(json['from'], DATE_FORMAT)
self.to_date = datetime.strptime(json['to'], DATE_FORMAT) | [
"\n Allows population of \"from_date\" from the returned \"from\" attribute which\n is a reserved word in python. Also populates \"to_date\" to be complete.\n "
] |
Please provide a description of the function:def reset_secret(self):
result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self)
if not 'id' in result:
raise UnexpectedResponseError('Unexpected response when resetting secret!', json=result)
s... | [
"\n Resets the client secret for this client.\n "
] |
Please provide a description of the function:def thumbnail(self, dump_to=None):
headers = {
"Authorization": "token {}".format(self._client.token)
}
result = requests.get('{}/{}/thumbnail'.format(self._client.base_url,
OAuthClient.api_endpoint.format(id=self... | [
"\n This returns binary data that represents a 128x128 image.\n If dump_to is given, attempts to write the image to a file\n at the given location.\n "
] |
Please provide a description of the function:def set_thumbnail(self, thumbnail):
headers = {
"Authorization": "token {}".format(self._client.token),
"Content-type": "image/png",
}
# TODO this check needs to be smarter - python2 doesn't do it right
if not... | [
"\n Sets the thumbnail for this OAuth Client. If thumbnail is bytes,\n uploads it as a png. Otherwise, assumes thumbnail is a path to the\n thumbnail and reads it in as bytes before uploading.\n "
] |
Please provide a description of the function:def grants(self):
from linode_api4.objects.account import UserGrants
if not hasattr(self, '_grants'):
resp = self._client.get(UserGrants.api_endpoint.format(username=self.username))
grants = UserGrants(self._client, self.user... | [
"\n Retrieves the grants for this user. If the user is unrestricted, this\n will result in an ApiError. This is smart, and will only fetch from the\n api once unless the object is invalidated.\n\n :returns: The grants for this user.\n :rtype: linode.objects.account.UserGrants\n ... |
Please provide a description of the function:def entity(self):
# there are no grants for derived types, so this shouldn't happen
if not issubclass(self.cls, Base) or issubclass(self.cls, DerivedBase):
raise ValueError("Cannot get entity for non-base-class {}".format(self.cls))
... | [
"\n Returns the object this grant is for. The objects type depends on the\n type of object this grant is applied to, and the object returned is\n not populated (accessing its attributes will trigger an api request).\n\n :returns: This grant's entity\n :rtype: Linode, NodeBalancer... |
Please provide a description of the function:def make_list(json_arr, client, cls, parent_id=None):
result = []
for obj in json_arr:
id_val = None
if 'id' in obj:
id_val = obj['id']
elif hasattr(cls, 'id_attribute') and getattr(cls, 'id_attri... | [
"\n Returns a list of Populated objects of the given class type. This\n should not be called outside of the :any:`LinodeClient` class.\n\n :param json_arr: The array of JSON data to make into a list\n :param client: The LinodeClient to pass to new objects\n :param parent_id: The ... |
Please provide a description of the function:def make_paginated_list(json, client, cls, parent_id=None, page_url=None,
filters=None):
l = PaginatedList.make_list(json["data"], client, cls, parent_id=parent_id)
p = PaginatedList(client, page_url, page=l, max_pages=json['pages'],
... | [
"\n Returns a PaginatedList populated with the first page of data provided,\n and the ability to load additional pages. This should not be called\n outside of the :any:`LinodeClient` class.\n\n :param json: The JSON list to use as the first page\n :param client: A LinodeClient to... |
Please provide a description of the function:def save(self):
resp = self._client.put(type(self).api_endpoint, model=self,
data=self._serialize())
if 'error' in resp:
return False
return True | [
"\n Send this object's mutable values to the server in a PUT request\n "
] |
Please provide a description of the function:def delete(self):
resp = self._client.delete(type(self).api_endpoint, model=self)
if 'error' in resp:
return False
self.invalidate()
return True | [
"\n Sends a DELETE request for this object\n "
] |
Please provide a description of the function:def invalidate(self):
for key in [k for k in type(self).properties.keys()
if not type(self).properties[k].identifier]:
self._set(key, None)
self._set('_populated', False) | [
"\n Invalidates all non-identifier Properties this object has locally,\n causing the next access to re-fetch them from the server\n "
] |
Please provide a description of the function:def _serialize(self):
result = { a: getattr(self, a) for a in type(self).properties
if type(self).properties[a].mutable }
for k, v in result.items():
if isinstance(v, Base):
result[k] = v.id
return re... | [
"\n A helper method to build a dict of all mutable Properties of\n this object\n "
] |
Please provide a description of the function:def _api_get(self):
json = self._client.get(type(self).api_endpoint, model=self)
self._populate(json) | [
"\n A helper method to GET this object from the server\n "
] |
Please provide a description of the function:def _populate(self, json):
if not json:
return
# hide the raw JSON away in case someone needs it
self._set('_raw_json', json)
for key in json:
if key in (k for k in type(self).properties.keys()
... | [
"\n A helper method that, given a JSON object representing this object,\n assigns values based on the properties dict and the attributes of\n its Properties.\n "
] |
Please provide a description of the function:def make(id, client, cls, parent_id=None, json=None):
from .dbase import DerivedBase
if issubclass(cls, DerivedBase):
return cls(client, id, parent_id, json)
else:
return cls(client, id, json) | [
"\n Makes an api object based on an id and class.\n\n :param id: The id of the object to create\n :param client: The LinodeClient to give the new object\n :param cls: The class type to instantiate\n :param parent_id: The parent id for derived classes\n :param json: The JSON... |
Please provide a description of the function:def make_instance(cls, id, client, parent_id=None, json=None):
return Base.make(id, client, cls, parent_id=parent_id, json=json) | [
"\n Makes an instance of the class this is called on and returns it.\n\n The intended usage is:\n instance = Linode.make_instance(123, client, json=response)\n\n :param cls: The class this was called on.\n :param id: The id of the instance to create\n :param client: The c... |
Please provide a description of the function:def or_(a, b):
if not isinstance(a, Filter) or not isinstance(b, Filter):
raise TypeError
return a.__or__(b) | [
"\n Combines two :any:`Filters<Filter>` with an \"or\" operation, matching\n any results that match any of the given filters.\n\n :param a: The first filter to consider.\n :type a: Filter\n :param b: The second filter to consider.\n :type b: Filter\n\n :returns: A filter that matches either a o... |
Please provide a description of the function:def to(self, linode):
from .linode import Instance
if not isinstance(linode, Instance):
raise ValueError("IP Address can only be assigned to a Linode!")
return { "address": self.address, "linode_id": linode.id } | [
"\n This is a helper method for ip-assign, and should not be used outside\n of that context. It's used to cleanly build an IP Assign request with\n pretty python syntax.\n "
] |
Please provide a description of the function:def stackscripts(self, *filters, **kwargs):
# python2 can't handle *args and a single keyword argument, so this is a workaround
if 'mine_only' in kwargs:
if kwargs['mine_only']:
new_filter = Filter({"mine":True})
... | [
"\n Returns a list of :any:`StackScripts<StackScript>`, both public and\n private. You may filter this query to return only\n :any:`StackScripts<StackScript>` that match certain criteria. You may\n also request only your own private :any:`StackScripts<StackScript>`::\n\n my_s... |
Please provide a description of the function:def instance_create(self, ltype, region, image=None,
authorized_keys=None, **kwargs):
ret_pass = None
if image and not 'root_pass' in kwargs:
ret_pass = Instance.generate_root_password()
kwargs['root_pass'] = ret_p... | [
"\n Creates a new Linode Instance. This function has several modes of operation:\n\n **Create an Instance from an Image**\n\n To create an Instance from an :any:`Image`, call `instance_create` with\n a :any:`Type`, a :any:`Region`, and an :any:`Image`. All three of\n these fields... |
Please provide a description of the function:def stackscript_create(self, label, script, images, desc=None, public=False, **kwargs):
image_list = None
if type(images) is list or type(images) is PaginatedList:
image_list = [d.id if issubclass(type(d), Base) else d for d in images ]
... | [
"\n Creates a new :any:`StackScript` on your account.\n\n :param label: The label for this StackScript.\n :type label: str\n :param script: The script to run when an :any:`Instance` is deployed with\n this StackScript. Must begin with a shebang (#!).\n :type... |
Please provide a description of the function:def token_create(self, label=None, expiry=None, scopes=None, **kwargs):
if label:
kwargs['label'] = label
if expiry:
if isinstance(expiry, datetime):
expiry = datetime.strftime(expiry, "%Y-%m-%dT%H:%M:%S")
... | [
"\n Creates and returns a new Personal Access Token\n "
] |
Please provide a description of the function:def ssh_key_upload(self, key, label):
if not key.startswith(SSH_KEY_TYPES):
# this might be a file path - look for it
path = os.path.expanduser(key)
if os.path.isfile(path):
with open(path) as f:
... | [
"\n Uploads a new SSH Public Key to your profile This key can be used in\n later Linode deployments.\n\n :param key: The ssh key, or a path to the ssh key. If a path is provided,\n the file at the path must exist and be readable or an exception\n will be ... |
Please provide a description of the function:def client_create(self, label=None):
result = self.client.post('/longview/clients', data={
"label": label
})
if not 'id' in result:
raise UnexpectedResponseError('Unexpected response when creating Longivew '
... | [
"\n Creates a new LongviewClient, optionally with a given label.\n\n :param label: The label for the new client. If None, a default label based\n on the new client's ID will be used.\n\n :returns: A new LongviewClient\n\n :raises ApiError: If a non-200 status code is returned... |
Please provide a description of the function:def events_mark_seen(self, event):
last_seen = event if isinstance(event, int) else event.id
self.client.post('{}/seen'.format(Event.api_endpoint), model=Event(self.client, last_seen)) | [
"\n Marks event as the last event we have seen. If event is an int, it is treated\n as an event_id, otherwise it should be an event object whose id will be used.\n "
] |
Please provide a description of the function:def settings(self):
result = self.client.get('/account/settings')
if not 'managed' in result:
raise UnexpectedResponseError('Unexpected response when getting account settings!',
json=result)
s = AccountSettin... | [
"\n Resturns the account settings data for this acocunt. This is not a\n listing endpoint.\n "
] |
Please provide a description of the function:def oauth_client_create(self, name, redirect_uri, **kwargs):
params = {
"label": name,
"redirect_uri": redirect_uri,
}
params.update(kwargs)
result = self.client.post('/account/oauth-clients', data=params)
... | [
"\n Make a new OAuth Client and return it\n "
] |
Please provide a description of the function:def transfer(self):
result = self.client.get('/account/transfer')
if not 'used' in result:
raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!')
return MappedObject(**result) | [
"\n Returns a MappedObject containing the account's transfer pool data\n "
] |
Please provide a description of the function:def user_create(self, email, username, restricted=True):
params = {
"email": email,
"username": username,
"restricted": restricted,
}
result = self.client.post('/account/users', data=params)
if not... | [
"\n Creates a new user on your account. If you create an unrestricted user,\n they will immediately be able to access everything on your account. If\n you create a restricted user, you must grant them access to parts of your\n account that you want to allow them to manage (see :any:`Us... |
Please provide a description of the function:def ips_assign(self, region, *assignments):
for a in assignments:
if not 'address' in a or not 'linode_id' in a:
raise ValueError("Invalid assignment: {}".format(a))
if isinstance(region, Region):
region = regi... | [
"\n Redistributes :any:`IP Addressees<IPAddress>` within a single region.\n This function takes a :any:`Region` and a list of assignments to make,\n then requests that the assignments take place. If any :any:`Instance`\n ends up without a public IP, or with more than one private IP, all... |
Please provide a description of the function:def ip_allocate(self, linode, public=True):
result = self.client.post('/networking/ipv4/', data={
"linode_id": linode.id if isinstance(linode, Base) else linode,
"type": "ipv4",
"public": public,
})
if not... | [
"\n Allocates an IP to a Instance you own. Additional IPs must be requested\n by opening a support ticket first.\n\n :param linode: The Instance to allocate the new IP for.\n :type linode: Instance or int\n :param public: If True, allocate a public IP address. Defaults to True.\... |
Please provide a description of the function:def shared_ips(self, linode, *ips):
if not isinstance(linode, Instance):
# make this an object
linode = Instance(self.client, linode)
params = []
for ip in ips:
if isinstance(ip, str):
para... | [
"\n Shares the given list of :any:`IPAddresses<IPAddress>` with the provided\n :any:`Instance`. This will enable the provided Instance to bring up the\n shared IP Addresses even though it does not own them.\n\n :param linode: The Instance to share the IPAddresses with. This Instance\n ... |
Please provide a description of the function:def load(self, target_type, target_id, target_parent_id=None):
result = target_type.make_instance(target_id, self, parent_id=target_parent_id)
result._api_get()
return result | [
"\n Constructs and immediately loads the object, circumventing the\n lazy-loading scheme by immediately making an API request. Does not\n load related objects.\n\n For example, if you wanted to load an :any:`Instance` object with ID 123,\n you could do this::\n\n loaded... |
Please provide a description of the function:def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
if not self.token:
raise RuntimeError("You do not have an API token!")
if not method:
raise ValueError("Method is required for API calls!")
... | [
"\n Makes a call to the linode api. Data should only be given if the method is\n POST or PUT, and should be a dictionary\n "
] |
Please provide a description of the function:def image_create(self, disk, label=None, description=None):
params = {
"disk_id": disk.id if issubclass(type(disk), Base) else disk,
}
if label is not None:
params["label"] = label
if description is not None:... | [
"\n Creates a new Image from a disk you own.\n\n :param disk: The Disk to imagize.\n :type disk: Disk or int\n :param label: The label for the resulting Image (defaults to the disk's\n label.\n :type label: str\n :param description: The description for ... |
Please provide a description of the function:def nodebalancer_create(self, region, **kwargs):
params = {
"region": region.id if isinstance(region, Base) else region,
}
params.update(kwargs)
result = self.post('/nodebalancers', data=params)
if not 'id' in re... | [
"\n Creates a new NodeBalancer in the given Region.\n\n :param region: The Region in which to create the NodeBalancer.\n :type region: Region or str\n\n :returns: The new NodeBalancer\n :rtype: NodeBalancer\n "
] |
Please provide a description of the function:def domain_create(self, domain, master=True, **kwargs):
params = {
'domain': domain,
'type': 'master' if master else 'slave',
}
params.update(kwargs)
result = self.post('/domains', data=params)
if not... | [
"\n Registers a new Domain on the acting user's account. Make sure to point\n your registrar to Linode's nameservers so that Linode's DNS manager will\n correctly serve your domain.\n\n :param domain: The domain to register to Linode's DNS manager.\n :type domain: str\n :p... |
Please provide a description of the function:def tag_create(self, label, instances=None, domains=None, nodebalancers=None,
volumes=None, entities=[]):
linode_ids, nodebalancer_ids, domain_ids, volume_ids = [], [], [], []
# filter input into lists of ids
sorter = zip(... | [
"\n Creates a new Tag and optionally applies it to the given entities.\n\n :param label: The label for the new Tag\n :type label: str\n :param entities: A list of objects to apply this Tag to upon creation.\n May only be taggable types (Linode Instances, Domains,\... |
Please provide a description of the function:def volume_create(self, label, region=None, linode=None, size=20, **kwargs):
if not (region or linode):
raise ValueError('region or linode required!')
params = {
"label": label,
"size": size,
"region":... | [
"\n Creates a new Block Storage Volume, either in the given Region or\n attached to the given Instance.\n\n :param label: The label for the new Volume.\n :type label: str\n :param region: The Region to create this Volume in. Not required if\n `linode` is pro... |
Please provide a description of the function:def generate_login_url(self, scopes=None, redirect_uri=None):
url = self.base_url + "/oauth/authorize"
split = list(urlparse(url))
params = {
"client_id": self.client_id,
"response_type": "code", # needed for all login... | [
"\n Generates a url to send users so that they may authenticate to this\n application. This url is suitable for redirecting a user to. For\n example, in `Flask`_, a login route might be implemented like this::\n\n @app.route(\"/login\")\n def begin_oauth_login():\n ... |
Please provide a description of the function:def finish_oauth(self, code):
r = requests.post(self._login_uri("/oauth/token"), data={
"code": code,
"client_id": self.client_id,
"client_secret": self.client_secret
})
if r.status_code !=... | [
"\n Given an OAuth Exchange Code, completes the OAuth exchange with the\n authentication server. This should be called once the user has already\n been directed to the login_uri, and has been sent back after successfully\n authenticating. For example, in `Flask`_, this might be impleme... |
Please provide a description of the function:def expire_token(self, token):
r = requests.post(self._login_uri("/oauth/token/expire"),
data={
"client_id": self.client_id,
"client_secret": self.client_secret,
"token": token,
})
... | [
"\n Given a token, makes a request to the authentication server to expire\n it immediately. This is considered a responsible way to log out a\n user. If you simply remove the session your application has for the\n user without expiring their token, the user is not _really_ logged out.\... |
Please provide a description of the function:def grants(self):
from linode_api4.objects.account import UserGrants
resp = self._client.get('/profile/grants') # use special endpoint for restricted users
grants = None
if resp is not None:
# if resp is None, we're unres... | [
"\n Returns grants for the current user\n "
] |
Please provide a description of the function:def add_whitelist_entry(self, address, netmask, note=None):
result = self._client.post("{}/whitelist".format(Profile.api_endpoint),
data={
"address": address,
"netmask": netmask,
"no... | [
"\n Adds a new entry to this user's IP whitelist, if enabled\n "
] |
Please provide a description of the function:def confirm_login_allowed(self, user):
if not user.is_active:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
) | [
"\n Controls whether the given User may log in. This is a policy setting,\n independent of end-user authentication. This default behavior is to\n allow login by active users, and reject login by inactive users.\n\n If the given user cannot log in, this method should raise a\n ``fo... |
Please provide a description of the function:def broken_chains(samples, chains):
samples = np.asarray(samples)
if samples.ndim != 2:
raise ValueError("expected samples to be a numpy 2D array")
num_samples, num_variables = samples.shape
num_chains = len(chains)
broken = np.zeros((num_s... | [
"Find the broken chains.\n\n Args:\n samples (array_like):\n Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n number of variables. The values should all be 0/1 or -1/+1.\n\n chains (list[array_like]):\n List of chains of lengt... |
Please provide a description of the function:def discard(samples, chains):
samples = np.asarray(samples)
if samples.ndim != 2:
raise ValueError("expected samples to be a numpy 2D array")
num_samples, num_variables = samples.shape
num_chains = len(chains)
broken = broken_chains(samples... | [
"Discard broken chains.\n\n Args:\n samples (array_like):\n Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n number of variables. The values should all be 0/1 or -1/+1.\n\n chains (list[array_like]):\n List of chains of length... |
Please provide a description of the function:def majority_vote(samples, chains):
samples = np.asarray(samples)
if samples.ndim != 2:
raise ValueError("expected samples to be a numpy 2D array")
num_samples, num_variables = samples.shape
num_chains = len(chains)
unembedded = np.empty((n... | [
"Use the most common element in broken chains.\n\n Args:\n samples (array_like):\n Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n number of variables. The values should all be 0/1 or -1/+1.\n\n chains (list[array_like]):\n L... |
Please provide a description of the function:def weighted_random(samples, chains):
samples = np.asarray(samples)
if samples.ndim != 2:
raise ValueError("expected samples to be a numpy 2D array")
# it sufficies to choose a random index from each chain and use that to construct the matrix
id... | [
"Determine the sample values of chains by weighed random choice.\n\n Args:\n samples (array_like):\n Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n number of variables. The values should all be 0/1 or -1/+1.\n\n chains (list[array_like... |
Please provide a description of the function:def sample_ising(self, h, J, **kwargs):
if isinstance(h, list):
h = dict(enumerate(h))
variables = set(h).union(*J)
try:
active_variables = sorted(variables)
except TypeError:
active_variables = li... | [
"Sample from the specified Ising model.\n\n Args:\n h (list/dict):\n Linear biases of the Ising model. If a list, the list's indices are\n used as variable labels.\n\n J (dict[(int, int): float]):\n Quadratic biases of the Ising model.\n\n ... |
Please provide a description of the function:def sample_qubo(self, Q, **kwargs):
variables = set().union(*Q)
try:
active_variables = sorted(variables)
except TypeError:
active_variables = list(variables)
num_variables = len(active_variables)
futu... | [
"Sample from the specified QUBO.\n\n Args:\n Q (dict):\n Coefficients of a quadratic unconstrained binary optimization (QUBO) model.\n\n **kwargs:\n Optional keyword arguments for the sampling method, specified per solver in\n :attr:`.DWaveSa... |
Please provide a description of the function:def validate_anneal_schedule(self, anneal_schedule):
if 'anneal_schedule' not in self.parameters:
raise RuntimeError("anneal_schedule is not an accepted parameter for this sampler")
properties = self.properties
try:
... | [
"Raise an exception if the specified schedule is invalid for the sampler.\n\n Args:\n anneal_schedule (list):\n An anneal schedule variation is defined by a series of pairs of floating-point\n numbers identifying points in the schedule at which to change slope. The fi... |
Please provide a description of the function:def target_to_source(target_adjacency, embedding):
# the nodes in the source adjacency are just the keys of the embedding
source_adjacency = {v: set() for v in embedding}
# we need the mapping from each node in the target to its source node
reverse_embe... | [
"Derive the source adjacency from an embedding and target adjacency.\n\n Args:\n target_adjacency (dict/:class:`networkx.Graph`):\n A dict of the form {v: Nv, ...} where v is a node in the target graph and Nv is the\n neighbors of v as an iterable. This can also be a networkx graph.\... |
Please provide a description of the function:def chain_to_quadratic(chain, target_adjacency, chain_strength):
quadratic = {} # we will be adding the edges that make the chain here
# do a breadth first search
seen = set()
try:
next_level = {next(iter(chain))}
except StopIteration:
... | [
"Determine the quadratic biases that induce the given chain.\n\n Args:\n chain (iterable):\n The variables that make up a chain.\n\n target_adjacency (dict/:class:`networkx.Graph`):\n Should be a dict of the form {s: Ns, ...} where s is a variable\n in the target gr... |
Please provide a description of the function:def chain_break_frequency(samples_like, embedding):
if isinstance(samples_like, dimod.SampleSet):
labels = samples_like.variables
samples = samples_like.record.sample
num_occurrences = samples_like.record.num_occurrences
else:
sam... | [
"Determine the frequency of chain breaks in the given samples.\n\n Args:\n samples_like (samples_like/:obj:`dimod.SampleSet`):\n A collection of raw samples. 'samples_like' is an extension of NumPy's array_like.\n See :func:`dimod.as_samples`.\n\n embedding (dict):\n ... |
Please provide a description of the function:def edgelist_to_adjacency(edgelist):
adjacency = dict()
for u, v in edgelist:
if u in adjacency:
adjacency[u].add(v)
else:
adjacency[u] = {v}
if v in adjacency:
adjacency[v].add(u)
else:
... | [
"Converts an iterator of edges to an adjacency dict.\n\n Args:\n edgelist (iterable):\n An iterator over 2-tuples where each 2-tuple is an edge.\n\n Returns:\n dict: The adjacency dict. A dict of the form {v: Nv, ...} where v is a node in a graph and\n Nv is the neighbors of v ... |
Please provide a description of the function:def sample(self, bqm, **kwargs):
# apply the embeddings to the given problem to tile it across the child sampler
embedded_bqm = dimod.BinaryQuadraticModel.empty(bqm.vartype)
__, __, target_adjacency = self.child.structure
for embeddi... | [
"Sample from the specified binary quadratic model.\n\n Args:\n bqm (:obj:`dimod.BinaryQuadraticModel`):\n Binary quadratic model to be sampled from.\n\n **kwargs:\n Optional keyword arguments for the sampling method, specified per solver.\n\n Returns... |
Please provide a description of the function:def cache_connect(database=None):
if database is None:
database = cache_file()
if os.path.isfile(database):
# just connect to the database as-is
conn = sqlite3.connect(database)
else:
# we need to populate the database
... | [
"Returns a connection object to a sqlite database.\n\n Args:\n database (str, optional): The path to the database the user wishes\n to connect to. If not specified, a default is chosen using\n :func:`.cache_file`. If the special database name ':memory:'\n is given, then a ... |
Please provide a description of the function:def insert_chain(cur, chain, encoded_data=None):
if encoded_data is None:
encoded_data = {}
if 'nodes' not in encoded_data:
encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':'))
if 'chain_length' not in encoded_data:
... | [
"Insert a chain into the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n chain (iterable):\n A collection of nodes. Chains in embedding act as one node.\n\n encoded_data (dict, o... |
Please provide a description of the function:def iter_chain(cur):
select = "SELECT nodes FROM chain"
for nodes, in cur.execute(select):
yield json.loads(nodes) | [
"Iterate over all of the chains in the database.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n Yields:\n list: The chain.\n\n "
] |
Please provide a description of the function:def insert_system(cur, system_name, encoded_data=None):
if encoded_data is None:
encoded_data = {}
if 'system_name' not in encoded_data:
encoded_data['system_name'] = system_name
insert = "INSERT OR IGNORE INTO system(system_name) VALUES (:... | [
"Insert a system name into the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n system_name (str):\n The unique name of a system\n\n encoded_data (dict, optional):\n If... |
Please provide a description of the function:def insert_flux_bias(cur, chain, system, flux_bias, chain_strength, encoded_data=None):
if encoded_data is None:
encoded_data = {}
insert_chain(cur, chain, encoded_data)
insert_system(cur, system, encoded_data)
if 'flux_bias' not in encoded_dat... | [
"Insert a flux bias offset into the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n chain (iterable):\n A collection of nodes. Chains in embedding act as one node.\n\n system (st... |
Please provide a description of the function:def iter_flux_bias(cur):
select = \
for nodes, system, flux_bias, chain_strength in cur.execute(select):
yield json.loads(nodes), system, _decode_real(flux_bias), _decode_real(chain_strength) | [
"Iterate over all flux biases in the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n Yields:\n tuple: A 4-tuple:\n\n list: The chain.\n\n str: The system name.\n\n ... |
Please provide a description of the function:def get_flux_biases_from_cache(cur, chains, system_name, chain_strength, max_age=3600):
select = \
encoded_data = {'chain_strength': _encode_real(chain_strength),
'system_name': system_name,
'time_limit': dateti... | [
"Determine the flux biases for all of the the given chains, system and chain strength.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n chains (iterable):\n An iterable of chains. Each chain is... |
Please provide a description of the function:def insert_graph(cur, nodelist, edgelist, encoded_data=None):
if encoded_data is None:
encoded_data = {}
if 'num_nodes' not in encoded_data:
encoded_data['num_nodes'] = len(nodelist)
if 'num_edges' not in encoded_data:
encoded_data['... | [
"Insert a graph into the cache.\n\n A graph is stored by number of nodes, number of edges and a\n json-encoded list of edges.\n\n Args:\n cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function\n is meant to be run within a :obj:`with` statement.\n nodelist (list): The node... |
Please provide a description of the function:def iter_graph(cur):
select =
for num_nodes, num_edges, edges in cur.execute(select):
yield list(range(num_nodes)), json.loads(edges) | [
"Iterate over all graphs in the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function\n is meant to be run within a :obj:`with` statement.\n\n Yields:\n tuple: A 2-tuple containing:\n\n list: The nodelist for a graph in the cache.\n\n ... |
Please provide a description of the function:def insert_embedding(cur, source_nodelist, source_edgelist, target_nodelist, target_edgelist,
embedding, embedding_tag):
encoded_data = {}
# first we need to encode the graphs and create the embedding id
source_data = {}
insert_gra... | [
"Insert an embedding into the cache.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n source_nodelist (list):\n The nodes in the source graph. Should be integer valued.\n\n source_edgeli... |
Please provide a description of the function:def select_embedding_from_tag(cur, embedding_tag, target_nodelist, target_edgelist):
encoded_data = {'num_nodes': len(target_nodelist),
'num_edges': len(target_edgelist),
'edges': json.dumps(target_edgelist, separators=(',', '... | [
"Select an embedding from the given tag and target graph.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n source_nodelist (list):\n The nodes in the source graph. Should be integer valued.\n\n... |
Please provide a description of the function:def select_embedding_from_source(cur, source_nodelist, source_edgelist,
target_nodelist, target_edgelist):
encoded_data = {'target_num_nodes': len(target_nodelist),
'target_num_edges': len(target_edgelist),
... | [
"Select an embedding from the source graph and target graph.\n\n Args:\n cur (:class:`sqlite3.Cursor`):\n An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n target_nodelist (list):\n The nodes in the target graph. Should be integer valued.\... |
Please provide a description of the function:def find_clique_embedding(k, m=None, target_graph=None):
# Organize parameter values
if target_graph is None:
if m is None:
raise TypeError("m and target_graph cannot both be None.")
target_graph = pegasus_graph(m)
m = target_gra... | [
"Find an embedding of a k-sized clique on a Pegasus graph (target_graph).\n\n This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then\n applying a Chimera clique finding algorithm. The results are then converted back in terms of\n Pegasus coordinates.\n\n Note: If targe... |
Please provide a description of the function:def draw_chimera_bqm(bqm, width=None, height=None):
linear = bqm.linear.keys()
quadratic = bqm.quadratic.keys()
if width is None and height is None:
# Create a graph large enough to fit the input networkx graph.
graph_size = ceil(sqrt((max(... | [
"Draws a Chimera Graph representation of a Binary Quadratic Model.\n\n If cell width and height not provided assumes square cell dimensions.\n Throws an error if drawing onto a Chimera graph of the given dimensions fails.\n\n Args:\n bqm (:obj:`dimod.BinaryQuadraticModel`):\n Should be eq... |
Please provide a description of the function:def embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=1.0,
smear_vartype=None):
if smear_vartype is dimod.SPIN and source_bqm.vartype is dimod.BINARY:
return embed_bqm(source_bqm.spin, embedding, target_adjacency,
... | [
"Embed a binary quadratic model onto a target graph.\n\n Args:\n source_bqm (:obj:`.BinaryQuadraticModel`):\n Binary quadratic model to embed.\n\n embedding (dict):\n Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...},\n where s is a sour... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.