_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254500 | get_client | validation | def get_client(
client, profile_name, aws_access_key_id, aws_secret_access_key,
region=None,
):
"""Shortcut for getting an initialized instance of the boto3 client."""
boto3.setup_default_session(
profile_name=profile_name,
| python | {
"resource": ""
} |
q254501 | create_function | validation | def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None):
"""Register and upload a function to AWS Lambda."""
print('Creating your new Lambda function')
byte_stream = read(path_to_zip_file, binary_file=True)
profile_name = cfg.get('profile')
aws_access_key_id = cfg.get('aws_access_key_id')
aws_secret_access_key = cfg.get('aws_secret_access_key')
account_id = get_account_id(
profile_name, aws_access_key_id, aws_secret_access_key, cfg.get(
'region',
),
)
role = get_role_name(
cfg.get('region'), account_id,
cfg.get('role', 'lambda_basic_execution'),
)
client = get_client(
'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
cfg.get('region'),
)
# Do we prefer development variable over config?
buck_name = (
os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')
)
func_name = (
os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')
)
print('Creating lambda function with name: {}'.format(func_name))
if use_s3:
kwargs = {
'FunctionName': func_name,
'Runtime': cfg.get('runtime', 'python2.7'),
'Role': role,
'Handler': cfg.get('handler'),
'Code': {
'S3Bucket': '{}'.format(buck_name),
'S3Key': '{}'.format(s3_file),
},
'Description': cfg.get('description', ''),
'Timeout': cfg.get('timeout', 15),
'MemorySize': cfg.get('memory_size', 512),
'VpcConfig': {
'SubnetIds': cfg.get('subnet_ids', []),
'SecurityGroupIds': cfg.get('security_group_ids', []),
},
'Publish': True,
}
else:
kwargs = {
'FunctionName': func_name,
'Runtime': cfg.get('runtime', 'python2.7'),
'Role': role,
'Handler': cfg.get('handler'),
| python | {
"resource": ""
} |
q254502 | upload_s3 | validation | def upload_s3(cfg, path_to_zip_file, *use_s3):
"""Upload a function to AWS S3."""
print('Uploading your new Lambda function')
profile_name = cfg.get('profile')
aws_access_key_id = cfg.get('aws_access_key_id')
aws_secret_access_key = cfg.get('aws_secret_access_key')
client = get_client(
's3', profile_name, aws_access_key_id, aws_secret_access_key,
cfg.get('region'),
)
byte_stream = b''
with open(path_to_zip_file, mode='rb') as fh:
byte_stream = fh.read()
s3_key_prefix = cfg.get('s3_key_prefix', '/dist')
| python | {
"resource": ""
} |
q254503 | get_function_config | validation | def get_function_config(cfg):
"""Check whether a function exists or not and return its config"""
function_name = cfg.get('function_name')
profile_name = cfg.get('profile')
aws_access_key_id = cfg.get('aws_access_key_id')
aws_secret_access_key = cfg.get('aws_secret_access_key')
client = get_client(
'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
cfg.get('region'),
)
| python | {
"resource": ""
} |
q254504 | cached_download | validation | def cached_download(url, name):
"""Download the data at a URL, and cache it under the given name.
The file is stored under `pyav/test` with the given name in the directory
:envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:
- the current virtualenv
- ``/usr/local/share``
- ``/usr/local/lib``
- ``/usr/share``
- ``/usr/lib``
- the user's home
"""
clean_name = os.path.normpath(name)
if clean_name != name:
raise ValueError("{} is not normalized.".format(name))
for dir_ in iter_data_dirs():
path = os.path.join(dir_, name)
if os.path.exists(path):
return path
dir_ = next(iter_data_dirs(True))
path = os.path.join(dir_, name)
log.info("Downloading {} to {}".format(url, path))
| python | {
"resource": ""
} |
q254505 | fate | validation | def fate(name):
"""Download and return a path to a sample from the FFmpeg test suite.
Data is handled by :func:`cached_download`.
See the `FFmpeg Automated | python | {
"resource": ""
} |
q254506 | curated | validation | def curated(name):
"""Download and return a path to a sample that is curated by the PyAV developers.
Data is handled by :func:`cached_download`.
"""
| python | {
"resource": ""
} |
q254507 | get_library_config | validation | def get_library_config(name):
"""Get distutils-compatible extension extras for the given library.
This requires ``pkg-config``.
"""
try:
proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)
except OSError:
print('pkg-config is required for building PyAV')
exit(1)
raw_cflags, err | python | {
"resource": ""
} |
q254508 | update_extend | validation | def update_extend(dst, src):
"""Update the `dst` with the `src`, extending values where lists.
Primiarily useful for integrating results from `get_library_config`.
"""
for k, v in src.items(): | python | {
"resource": ""
} |
q254509 | _CCompiler_spawn_silent | validation | def _CCompiler_spawn_silent(cmd, dry_run=None):
"""Spawn a process, and eat the stdio."""
| python | {
"resource": ""
} |
q254510 | new_compiler | validation | def new_compiler(*args, **kwargs):
"""Create a C compiler.
:param bool silent: Eat all stdio? Defaults to ``True``.
All other arguments passed to ``distutils.ccompiler.new_compiler``.
"""
make_silent = kwargs.pop('silent', True)
cc = _new_compiler(*args, **kwargs)
# If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.
# See Python issue 4431 (https://bugs.python.org/issue4431)
if is_msvc(cc):
from distutils.msvc9compiler import get_build_version
if get_build_version() == 10:
cc.initialize()
for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:
| python | {
"resource": ""
} |
q254511 | iter_cython | validation | def iter_cython(path):
'''Yield all ``.pyx`` and ``.pxd`` files in the given root.'''
for dir_path, dir_names, file_names in os.walk(path):
for file_name in file_names:
if file_name.startswith('.'):
continue
| python | {
"resource": ""
} |
q254512 | split_grafs | validation | def split_grafs (lines):
"""
segment the raw text into paragraphs
"""
graf = []
for line in lines:
line = line.strip()
if len(line) < 1:
if len(graf) > 0:
| python | {
"resource": ""
} |
q254513 | filter_quotes | validation | def filter_quotes (text, is_email=True):
"""
filter the quoted text out of a message
"""
global DEBUG
global PAT_FORWARD, PAT_REPLIED, PAT_UNSUBSC
if is_email:
text = filter(lambda x: x in string.printable, text)
if DEBUG:
print("text:", text)
# strip off quoted text in a forward
m = PAT_FORWARD.split(text, re.M)
if m and len(m) > 1:
text = m[0]
# strip off quoted text in a reply
m = PAT_REPLIED.split(text, re.M)
if m and len(m) > 1:
| python | {
"resource": ""
} |
q254514 | fix_hypenation | validation | def fix_hypenation (foo):
"""
fix hyphenation in the word list for a parsed sentence
"""
i = 0
bar = []
while i < len(foo):
text, lemma, pos, tag = foo[i]
if (tag == "HYPH") and (i > 0) | python | {
"resource": ""
} |
q254515 | parse_doc | validation | def parse_doc (json_iter):
"""
parse one document to prep for TextRank
"""
global DEBUG
for meta in json_iter:
base_idx = 0
for graf_text in filter_quotes(meta["text"], is_email=False):
if DEBUG:
print("graf_text:", graf_text)
| python | {
"resource": ""
} |
q254516 | get_tiles | validation | def get_tiles (graf, size=3):
"""
generate word pairs for the TextRank graph
"""
keeps = list(filter(lambda w: w.word_id > 0, graf))
keeps_len = len(keeps)
for i in iter(range(0, keeps_len - 1)):
w0 = keeps[i]
for j in iter(range(i | python | {
"resource": ""
} |
q254517 | build_graph | validation | def build_graph (json_iter):
"""
construct the TextRank graph from parsed paragraphs
"""
global DEBUG, WordNode
graph = nx.DiGraph()
for meta in json_iter:
if DEBUG:
print(meta["graf"])
for pair in get_tiles(map(WordNode._make, meta["graf"])):
if DEBUG:
print(pair)
for word_id in pair:
if not graph.has_node(word_id):
| python | {
"resource": ""
} |
q254518 | write_dot | validation | def write_dot (graph, ranks, path="graph.dot"):
"""
output the graph in Dot file format
"""
dot = Digraph()
for node in graph.nodes():
dot.node(node, "%s %0.3f" % (node, ranks[node]))
| python | {
"resource": ""
} |
q254519 | render_ranks | validation | def render_ranks (graph, ranks, dot_file="graph.dot"):
"""
render the | python | {
"resource": ""
} |
q254520 | text_rank | validation | def text_rank (path):
"""
run the TextRank algorithm
"""
graph = build_graph(json_iter(path))
| python | {
"resource": ""
} |
q254521 | find_chunk | validation | def find_chunk (phrase, np):
"""
leverage noun phrase chunking
"""
for i in iter(range(0, len(phrase))):
| python | {
"resource": ""
} |
q254522 | enumerate_chunks | validation | def enumerate_chunks (phrase, spacy_nlp):
"""
iterate through the noun phrases
"""
if (len(phrase) > 1):
found = False
text = " ".join([rl.text for rl in phrase])
doc = spacy_nlp(text.strip(), parse=True)
| python | {
"resource": ""
} |
q254523 | collect_keyword | validation | def collect_keyword (sent, ranks, stopwords):
"""
iterator for collecting the single-word keyphrases
"""
for w in sent:
if (w.word_id > 0) and (w.root in ranks) and (w.pos[0] in "NV") and (w.root not in stopwords):
| python | {
"resource": ""
} |
q254524 | collect_entities | validation | def collect_entities (sent, ranks, stopwords, spacy_nlp):
"""
iterator for collecting the named-entities
"""
global DEBUG
sent_text = " ".join([w.raw for w in sent])
if DEBUG:
print("sent:", sent_text)
for ent in spacy_nlp(sent_text).ents:
if DEBUG:
print("NER:", ent.label_, ent.text)
if (ent.label_ not in ["CARDINAL"]) and (ent.text.lower() not in stopwords):
| python | {
"resource": ""
} |
q254525 | collect_phrases | validation | def collect_phrases (sent, ranks, spacy_nlp):
"""
iterator for collecting the noun phrases
"""
tail = 0
last_idx = sent[0].idx - 1
phrase = []
while tail < len(sent):
w = sent[tail]
if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1):
# keep collecting...
rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root], ids=w.word_id, pos=w.pos.lower(), count=1)
phrase.append(rl)
else:
# just hit a phrase boundary
for text, p in enumerate_chunks(phrase, spacy_nlp):
| python | {
"resource": ""
} |
q254526 | mh_digest | validation | def mh_digest (data):
"""
create a MinHash digest
"""
num_perm = | python | {
"resource": ""
} |
q254527 | top_sentences | validation | def top_sentences (kernel, path):
"""
determine distance for each sentence
"""
key_sent = {}
i = 0
if isinstance(path, str):
path = json_iter(path)
for meta in path:
graf = meta["graf"]
tagged_sent = [WordNode._make(x) for x in graf]
text = " ".join([w.raw for w in tagged_sent])
m_sent = mh_digest([str(w.word_id) for w in tagged_sent]) | python | {
"resource": ""
} |
q254528 | limit_keyphrases | validation | def limit_keyphrases (path, phrase_limit=20):
"""
iterator for the most significant key phrases
"""
rank_thresh = None
if isinstance(path, str):
lex = []
for meta in json_iter(path):
rl = RankedLexeme(**meta)
lex.append(rl)
else:
lex = path
if len(lex) > 0:
rank_thresh = statistics.mean([rl.rank for rl in lex])
else:
rank_thresh = 0
| python | {
"resource": ""
} |
q254529 | limit_sentences | validation | def limit_sentences (path, word_limit=100):
"""
iterator for the most significant sentences, up to a specified limit
"""
word_count = 0
if isinstance(path, str):
path = json_iter(path)
for meta in path:
| python | {
"resource": ""
} |
q254530 | make_sentence | validation | def make_sentence (sent_text):
"""
construct a sentence text, with proper spacing
"""
lex = []
idx = 0
for word in sent_text:
if len(word) > 0:
if (idx > 0) and not (word[0] in ",.:;!?-\"'"):
| python | {
"resource": ""
} |
q254531 | json_iter | validation | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
| python | {
"resource": ""
} |
q254532 | pretty_print | validation | def pretty_print (obj, indent=False):
"""
pretty print a JSON object
"""
if indent:
return | python | {
"resource": ""
} |
q254533 | Snapshot.get_object | validation | def get_object(cls, api_token, snapshot_id):
"""
Class method that will return a Snapshot object by ID.
"""
| python | {
"resource": ""
} |
q254534 | Tag.load | validation | def load(self):
"""
Fetch data about tag
"""
tags = self.get_data("tags/%s" % self.name)
tag = tags['tag']
| python | {
"resource": ""
} |
q254535 | Tag.create | validation | def create(self, **kwargs):
"""
Create the tag.
"""
for attr in kwargs.keys():
setattr(self, attr, kwargs[attr])
| python | {
"resource": ""
} |
q254536 | Tag.__extract_resources_from_droplets | validation | def __extract_resources_from_droplets(self, data):
"""
Private method to extract from a value, the resources.
It will check the type of object in the array provided and build
the right structure for the API.
"""
resources = []
if not isinstance(data, list): return data
for a_droplet in data:
res = {}
try:
if isinstance(a_droplet, unicode):
res = {"resource_id": a_droplet, "resource_type": "droplet"}
except NameError: | python | {
"resource": ""
} |
q254537 | Tag.add_droplets | validation | def add_droplets(self, droplet):
"""
Add the Tag to a Droplet.
Attributes accepted at creation time:
droplet: array of string or array of int, or array of Droplets.
"""
| python | {
"resource": ""
} |
q254538 | Tag.remove_droplets | validation | def remove_droplets(self, droplet):
"""
Remove the Tag from the Droplet.
Attributes accepted at creation time:
droplet: array of string or array of int, or array of Droplets.
| python | {
"resource": ""
} |
q254539 | Action.get_object | validation | def get_object(cls, api_token, action_id):
"""
Class method that will return a Action object by ID.
"""
| python | {
"resource": ""
} |
q254540 | Action.wait | validation | def wait(self, update_every_seconds=1):
"""
Wait until the action is marked as completed or with an error.
It will return True in case of success, otherwise False.
Optional Args:
update_every_seconds - int : number of seconds to wait before
| python | {
"resource": ""
} |
q254541 | Droplet.get_object | validation | def get_object(cls, api_token, droplet_id):
"""Class method that will return a Droplet object by ID.
Args:
api_token (str): token
droplet_id (int): droplet id
| python | {
"resource": ""
} |
q254542 | Droplet._perform_action | validation | def _perform_action(self, params, return_dict=True):
"""
Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action
"""
action = self.get_data(
"droplets/%s/actions/" % self.id,
type=POST,
params=params
| python | {
"resource": ""
} |
q254543 | Droplet.take_snapshot | validation | def take_snapshot(self, snapshot_name, return_dict=True, power_off=False):
"""Take a snapshot!
Args:
snapshot_name (str): name of snapshot
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
power_off (bool): Before taking the snapshot the droplet will be
turned off with another API call. It will wait until the
droplet will be powered off.
Returns dict or Action
| python | {
"resource": ""
} |
q254544 | Droplet.change_kernel | validation | def change_kernel(self, kernel, return_dict=True):
"""Change the kernel to a new one
Args:
kernel : instance of digitalocean.Kernel.Kernel
Optional Args:
return_dict (bool): Return a dict when True | python | {
"resource": ""
} |
q254545 | Droplet.__get_ssh_keys_id_or_fingerprint | validation | def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name):
"""
Check and return a list of SSH key IDs or fingerprints according
to DigitalOcean's API. This method is used to check and create a
droplet with the correct SSH keys.
"""
ssh_keys_id = list()
for ssh_key in ssh_keys:
if type(ssh_key) in [int, type(2 ** 64)]:
ssh_keys_id.append(int(ssh_key))
elif type(ssh_key) == SSHKey:
ssh_keys_id.append(ssh_key.id)
elif type(ssh_key) in [type(u''), type('')]:
# ssh_key could either be a fingerprint or a public key
#
# type(u'') and type('') is the same in python 3 but
# different in 2. See:
# https://github.com/koalalorenzo/python-digitalocean/issues/80
regexp_of_fingerprint = '([0-9a-fA-F]{2}:){15}[0-9a-fA-F]'
match = re.match(regexp_of_fingerprint, ssh_key)
if match is not None and match.end() == len(ssh_key) - 1:
ssh_keys_id.append(ssh_key)
| python | {
"resource": ""
} |
q254546 | Droplet.create | validation | def create(self, *args, **kwargs):
"""
Create the droplet with object properties.
Note: Every argument and parameter given to this method will be
assigned to the object.
"""
for attr in kwargs.keys():
setattr(self, attr, kwargs[attr])
# Provide backwards compatibility
if not self.size_slug and self.size:
self.size_slug = self.size
ssh_keys_id = Droplet.__get_ssh_keys_id_or_fingerprint(self.ssh_keys,
self.token,
self.name)
data = {
"name": self.name,
"size": self.size_slug,
"image": self.image,
"region": self.region,
"ssh_keys": ssh_keys_id, | python | {
"resource": ""
} |
q254547 | Droplet.get_actions | validation | def get_actions(self):
"""
Returns a list of Action objects
This actions can be used to check the droplet's status
"""
answer = self.get_data("droplets/%s/actions/" % self.id, type=GET)
actions = []
for action_dict in answer['actions']:
| python | {
"resource": ""
} |
q254548 | Droplet.get_action | validation | def get_action(self, action_id):
"""Returns a specific Action by its ID.
Args:
action_id (int): id of action
""" | python | {
"resource": ""
} |
q254549 | Droplet.get_kernel_available | validation | def get_kernel_available(self):
"""
Get a list of kernels available
"""
kernels = list()
data = self.get_data("droplets/%s/kernels/" % self.id)
while True:
for jsond in data[u'kernels']:
kernel = Kernel(**jsond)
kernel.token = self.token
kernels.append(kernel)
try:
| python | {
"resource": ""
} |
q254550 | Domain.get_object | validation | def get_object(cls, api_token, domain_name):
"""
Class method that will return a Domain object by ID.
"""
| python | {
"resource": ""
} |
q254551 | Domain.create | validation | def create(self):
"""
Create new doamin
"""
# URL https://api.digitalocean.com/v2/domains
data = {
"name": self.name,
| python | {
"resource": ""
} |
q254552 | Domain.get_records | validation | def get_records(self, params=None):
"""
Returns a list of Record objects
"""
if params is None:
params = {}
# URL https://api.digitalocean.com/v2/domains/[NAME]/records/
records = []
data = self.get_data("domains/%s/records/" % self.name, type=GET, params=params)
for | python | {
"resource": ""
} |
q254553 | Account.get_object | validation | def get_object(cls, api_token):
"""
Class method that will return an Account object.
"""
| python | {
"resource": ""
} |
q254554 | FloatingIP.get_object | validation | def get_object(cls, api_token, ip):
"""
Class method that will return a FloatingIP object by its IP.
Args:
api_token: str - token
| python | {
"resource": ""
} |
q254555 | FloatingIP.load | validation | def load(self):
"""
Load the FloatingIP object from DigitalOcean.
Requires self.ip to be set.
"""
data = self.get_data('floating_ips/%s' % self.ip, type=GET)
floating_ip = data['floating_ip']
| python | {
"resource": ""
} |
q254556 | FloatingIP.create | validation | def create(self, *args, **kwargs):
"""
Creates a FloatingIP and assigns it to a Droplet.
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
droplet_id: int - droplet id
"""
data = self.get_data('floating_ips/',
type=POST,
| python | {
"resource": ""
} |
q254557 | FloatingIP.reserve | validation | def reserve(self, *args, **kwargs):
"""
Creates a FloatingIP in a region without assigning
it to a specific Droplet.
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
region_slug: str - region's slug (e.g. 'nyc3')
"""
data = self.get_data('floating_ips/',
| python | {
"resource": ""
} |
q254558 | FloatingIP.assign | validation | def assign(self, droplet_id):
"""
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id
"""
return self.get_data(
"floating_ips/%s/actions/" % | python | {
"resource": ""
} |
q254559 | Firewall.get_object | validation | def get_object(cls, api_token, firewall_id):
"""
Class method that will return a Firewall object by ID.
"""
| python | {
"resource": ""
} |
q254560 | Firewall.add_tags | validation | def add_tags(self, tags):
"""
Add tags to this Firewall.
"""
return self.get_data(
| python | {
"resource": ""
} |
q254561 | Firewall.remove_tags | validation | def remove_tags(self, tags):
"""
Remove tags from this Firewall.
"""
return self.get_data(
| python | {
"resource": ""
} |
q254562 | SSHKey.get_object | validation | def get_object(cls, api_token, ssh_key_id):
"""
Class method that will return a SSHKey object by ID.
"""
| python | {
"resource": ""
} |
q254563 | SSHKey.load | validation | def load(self):
"""
Load the SSHKey object from DigitalOcean.
Requires either self.id or self.fingerprint to be set.
"""
identifier = None
if self.id:
identifier = self.id
elif self.fingerprint is not None:
identifier = self.fingerprint
| python | {
"resource": ""
} |
q254564 | SSHKey.load_by_pub_key | validation | def load_by_pub_key(self, public_key):
"""
This method will load a SSHKey object from DigitalOcean
from a public_key. This method will avoid problems like
uploading the same public_key twice.
"""
data = self.get_data("account/keys/")
for jsoned in | python | {
"resource": ""
} |
q254565 | SSHKey.create | validation | def create(self):
"""
Create the SSH Key
"""
input_params = {
"name": self.name,
| python | {
"resource": ""
} |
q254566 | SSHKey.edit | validation | def edit(self):
"""
Edit the SSH Key
"""
input_params = {
"name": self.name,
"public_key": self.public_key,
}
data = self.get_data(
"account/keys/%s" % | python | {
"resource": ""
} |
q254567 | Manager.get_all_regions | validation | def get_all_regions(self):
"""
This function returns a list of Region object.
"""
data = self.get_data("regions/")
regions = list()
for jsoned in data['regions']:
region | python | {
"resource": ""
} |
q254568 | Manager.get_all_droplets | validation | def get_all_droplets(self, tag_name=None):
"""
This function returns a list of Droplet object.
"""
params = dict()
if tag_name:
params["tag_name"] = tag_name
data = self.get_data("droplets/", params=params)
droplets = list()
for jsoned in data['droplets']:
droplet = Droplet(**jsoned)
droplet.token = self.token
for net in droplet.networks['v4']:
if net['type'] == 'private':
droplet.private_ip_address = net['ip_address']
if net['type'] == 'public':
droplet.ip_address = net['ip_address']
if droplet.networks['v6']:
droplet.ip_v6_address = droplet.networks['v6'][0]['ip_address']
if "backups" in droplet.features:
droplet.backups = True
else:
| python | {
"resource": ""
} |
q254569 | Manager.get_droplet | validation | def get_droplet(self, droplet_id):
"""
Return a Droplet by its ID.
"""
| python | {
"resource": ""
} |
q254570 | Manager.get_all_sizes | validation | def get_all_sizes(self):
"""
This function returns a list of Size object.
"""
data = self.get_data("sizes/")
sizes = list()
for jsoned in data['sizes']:
size | python | {
"resource": ""
} |
q254571 | Manager.get_images | validation | def get_images(self, private=False, type=None):
"""
This function returns a list of Image object.
"""
params = {}
if private:
params['private'] = 'true'
if type:
params['type'] = type
data = | python | {
"resource": ""
} |
q254572 | Manager.get_all_domains | validation | def get_all_domains(self):
"""
This function returns a list of Domain object.
"""
data = self.get_data("domains/")
domains = list()
for jsoned in data['domains']:
domain | python | {
"resource": ""
} |
q254573 | Manager.get_domain | validation | def get_domain(self, domain_name):
"""
Return a Domain by its domain_name
"""
| python | {
"resource": ""
} |
q254574 | Manager.get_all_sshkeys | validation | def get_all_sshkeys(self):
"""
This function returns a list of SSHKey object.
"""
data = self.get_data("account/keys/")
ssh_keys = list()
for jsoned in data['ssh_keys']:
ssh_key | python | {
"resource": ""
} |
q254575 | Manager.get_ssh_key | validation | def get_ssh_key(self, ssh_key_id):
"""
Return a SSHKey object by its ID.
"""
| python | {
"resource": ""
} |
q254576 | Manager.get_all_tags | validation | def get_all_tags(self):
"""
This method returns a list of all tags.
| python | {
"resource": ""
} |
q254577 | Manager.get_all_floating_ips | validation | def get_all_floating_ips(self):
"""
This function returns a list of FloatingIP objects.
"""
data = self.get_data("floating_ips")
floating_ips = list()
for jsoned in data['floating_ips']:
floating_ip | python | {
"resource": ""
} |
q254578 | Manager.get_floating_ip | validation | def get_floating_ip(self, ip):
"""
Returns a of FloatingIP object by its IP address.
"""
| python | {
"resource": ""
} |
q254579 | Manager.get_all_load_balancers | validation | def get_all_load_balancers(self):
"""
Returns a list of Load Balancer objects.
"""
data = self.get_data("load_balancers")
load_balancers = list()
for jsoned in data['load_balancers']:
load_balancer = LoadBalancer(**jsoned)
load_balancer.token = self.token
load_balancer.health_check = HealthCheck(**jsoned['health_check'])
load_balancer.sticky_sessions = StickySesions(**jsoned['sticky_sessions'])
| python | {
"resource": ""
} |
q254580 | Manager.get_load_balancer | validation | def get_load_balancer(self, id):
"""
Returns a Load Balancer object by its ID.
Args:
id (str): Load Balancer ID
| python | {
"resource": ""
} |
q254581 | Manager.get_certificate | validation | def get_certificate(self, id):
"""
Returns a Certificate object by its ID.
Args:
id (str): Certificate ID
| python | {
"resource": ""
} |
q254582 | Manager.get_all_certificates | validation | def get_all_certificates(self):
"""
This function returns a list of Certificate objects.
"""
data = self.get_data("certificates")
certificates = list()
for jsoned in data['certificates']:
cert | python | {
"resource": ""
} |
q254583 | Manager.get_snapshot | validation | def get_snapshot(self, snapshot_id):
"""
Return a Snapshot by its ID.
"""
| python | {
"resource": ""
} |
q254584 | Manager.get_all_snapshots | validation | def get_all_snapshots(self):
"""
This method returns a list of all Snapshots.
"""
| python | {
"resource": ""
} |
q254585 | Manager.get_droplet_snapshots | validation | def get_droplet_snapshots(self):
"""
This method returns a list of all Snapshots based on Droplets.
"""
| python | {
"resource": ""
} |
q254586 | Manager.get_volume_snapshots | validation | def get_volume_snapshots(self):
"""
This method returns a list of all Snapshots based on volumes.
"""
| python | {
"resource": ""
} |
q254587 | Manager.get_all_volumes | validation | def get_all_volumes(self, region=None):
"""
This function returns a list of Volume objects.
"""
if region:
url = "volumes?region={}".format(region)
else:
url = "volumes"
data = self.get_data(url)
| python | {
"resource": ""
} |
q254588 | Manager.get_volume | validation | def get_volume(self, volume_id):
"""
Returns a Volume object by its ID.
"""
| python | {
"resource": ""
} |
q254589 | Manager.get_all_firewalls | validation | def get_all_firewalls(self):
"""
This function returns a list of Firewall objects.
"""
data = self.get_data("firewalls")
firewalls = list()
for jsoned in data['firewalls']:
firewall = Firewall(**jsoned)
firewall.token = self.token
in_rules = list()
for rule in jsoned['inbound_rules']:
in_rules.append(InboundRule(**rule))
firewall.inbound_rules = in_rules
| python | {
"resource": ""
} |
q254590 | Manager.get_firewall | validation | def get_firewall(self, firewall_id):
"""
Return a Firewall by its ID.
| python | {
"resource": ""
} |
q254591 | LoadBalancer.get_object | validation | def get_object(cls, api_token, id):
"""
Class method that will return a LoadBalancer object by its ID.
Args:
api_token (str): DigitalOcean API token
id (str): Load Balancer ID
| python | {
"resource": ""
} |
q254592 | LoadBalancer.load | validation | def load(self):
"""
Loads updated attributues for a LoadBalancer object.
Requires self.id to be set.
"""
data = self.get_data('load_balancers/%s' % self.id, type=GET)
load_balancer = data['load_balancer']
# Setting the attribute values
for attr in load_balancer.keys():
if attr == 'health_check':
health_check = HealthCheck(**load_balancer['health_check'])
setattr(self, attr, health_check)
elif attr == 'sticky_sessions':
sticky_ses = StickySesions(**load_balancer['sticky_sessions'])
setattr(self, | python | {
"resource": ""
} |
q254593 | LoadBalancer.create | validation | def create(self, *args, **kwargs):
"""
Creates a new LoadBalancer.
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name (str): The Load Balancer's name
region (str): The slug identifier for a DigitalOcean region
algorithm (str, optional): The load balancing algorithm to be
used. Currently, it must be either "round_robin" or
"least_connections"
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
health_check (obj, optional): A `HealthCheck` object
sticky_sessions (obj, optional): A `StickySessions` object
redirect_http_to_https (bool, optional): A boolean indicating
whether HTTP requests to the Load Balancer should be
redirected to HTTPS
droplet_ids (obj:`list` of `int`): A list of IDs representing
Droplets to be added to the Load Balancer (mutually
exclusive with 'tag')
tag (str): A string representing a DigitalOcean Droplet tag
(mutually exclusive with 'droplet_ids')
"""
rules_dict = [rule.__dict__ for rule in self.forwarding_rules]
params = {'name': self.name, 'region': self.region,
'forwarding_rules': rules_dict,
'redirect_http_to_https': self.redirect_http_to_https}
if self.droplet_ids and self.tag:
raise | python | {
"resource": ""
} |
q254594 | LoadBalancer.save | validation | def save(self):
"""
Save the LoadBalancer
"""
forwarding_rules = [rule.__dict__ for rule in self.forwarding_rules]
data = {
'name': self.name,
'region': self.region['slug'],
'forwarding_rules': forwarding_rules,
'redirect_http_to_https': self.redirect_http_to_https
}
if self.tag:
data['tag'] = self.tag
else:
data['droplet_ids'] = self.droplet_ids
if self.algorithm:
| python | {
"resource": ""
} |
q254595 | LoadBalancer.add_droplets | validation | def add_droplets(self, droplet_ids):
"""
Assign a LoadBalancer to a Droplet.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs
"""
return self.get_data(
| python | {
"resource": ""
} |
q254596 | LoadBalancer.remove_droplets | validation | def remove_droplets(self, droplet_ids):
"""
Unassign a LoadBalancer.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs
"""
return self.get_data(
| python | {
"resource": ""
} |
q254597 | LoadBalancer.add_forwarding_rules | validation | def add_forwarding_rules(self, forwarding_rules):
"""
Adds new forwarding rules to a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
"""
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.get_data( | python | {
"resource": ""
} |
q254598 | LoadBalancer.remove_forwarding_rules | validation | def remove_forwarding_rules(self, forwarding_rules):
"""
Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
"""
rules_dict = [rule.__dict__ for rule in forwarding_rules]
| python | {
"resource": ""
} |
q254599 | Metadata.get_data | validation | def get_data(self, url, headers=dict(), params=dict(), render_json=True):
"""
Customized version of get_data to directly get the data without
using the authentication method.
"""
url = urljoin(self.end_point, url)
response = requests.get(url, headers=headers, params=params, | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.