output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
this function will simply copy the file from the source path to the destination path given as input
| Can you generate a brief explanation for the following Python 3 code
def copy_dir(src, dst):
try:
debug.log("copy dir from "+ src, "to "+ dst)
shutil.copytree(src, dst)
except Exception as e:
debug.log("Error: happened while copying!\n%s\n"%e) | As a Python code composer, you craft elegant and concise scripts. |
Print list of strings to the predefined stdout. | Can you tell what is the following Python 3 function doing
def print_out(self, *lst):
self.print2file(self.stdout, True, True, *lst) | You are a Python code analyst, evaluating scripts for potential improvements. |
def print_err(self, *lst):
""" Print list of strings to the predefined stdout. """
self.print2file(self.stderr, False, True, *lst) | Write a Python 3 function that can
print list of strings to the predefined stderr. | You are a Python code generator, capable of creating scripts from specifications. |
This function prints to the screen and logs to a file. | Here you have a function in Python 3, explain what it does
def print2file(self, logfile, print2screen, addLineFeed, *lst):
if addLineFeed:
linefeed = '\n'
else: linefeed = ''
if print2screen: print(linefeed.join(str(string) for string in lst))
try: file_instance = isinstance(logfile, fi... | You are a Python code generator, capable of creating scripts from specifications. |
Print list of strings to the predefined logfile if debug is set. | Can you generate the documentation for the following Python 3 function
def log(self, *lst):
self.print2file(self.logfile, self.debug, True, *lst)
if 'Error' in '\n'.join([str(x) for x in lst]):
self.caught_error = '\n'.join([str(x) for x in lst]) | You are a Python code architect, reviewing and designing scalable and efficient code |
def log_no_newline(self, msg):
""" print the message to the predefined log file without newline """
self.print2file(self.logfile, False, False, msg) | Write a Python 3 script for
printing a message to the predefined log file without a newline. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function will extract the value from a nested dictionary and return it. | Can you generate the documentation for the following Python 3 function
def get_tree(self, list_of_keys):
cur_obj = self
for key in list_of_keys:
cur_obj = cur_obj.get(key)
if not cur_obj: break
return cur_obj | You are a Python code analyst, evaluating scripts for potential improvements. |
def invert(self):
''' Return inverse mapping of dictionary with sorted values.
USAGE
>>> # Switch the keys and values
>>> adv_dict({
... 'A': [1, 2, 3],
... 'B': [4, 2],
... 'C': [1, 4],
... }).invert()
{1: ['A', 'C'], 2: ['A', 'B'],... | Implement a function in Python 3 to
return inverse mapping of dictionary with sorted values. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sub(self, replace, string, count=0):
""" returns new string where the matching cases (limited by the count) in
the string is replaced. """
return self.re.sub(replace, string, count) | Write a Python 3 function for
replacing the string with the given string. | You are a Python code generator, capable of creating scripts from specifications. |
def match(self, s):
""" Matches the string to the stored regular expression, and stores all
groups in mathches. Returns False on negative match. """
self.matches = self.re.search(s)
return self.matches | Can you write a function in Python 3 where it
matches the given string to the stored regular expression and stores all groups in mathches. Returns True on success. | You are a Python code architect, reviewing and designing scalable and efficient code |
def match(self, s):
""" Matching the pattern to the input string, returns True/False and
saves the matched string in the internal list
"""
if self.re.match(s):
self.list.append(s)
return True
else: return False | Can you create a Python 3 function that
returns True if the pattern matches the input string returns False otherwise | You are a Python code generator, capable of creating scripts from specifications. |
def reporter(self):
"""
Create the MASH report
"""
logging.info('Creating {} report'.format(self.analysistype))
make_path(self.reportpath)
header = 'Strain,ReferenceGenus,ReferenceFile,ReferenceGenomeMashDistance,Pvalue,NumMatchingHashes\n'
data = ''
for s... | Implement a Python 3 function for
creating the MASH report | As a python code expert, you are capable of creating scripts from specifications. |
Take a full path to a python method or class for example
mypkg. subpkg. method and return the method or class | Make a summary of the following Python 3 code
def get_function(pkgpath):
# Extract the module and function name from pkgpath
elems = pkgpath.split('.')
if len(elems) <= 1:
raise PyMacaronCoreException("Path %s is too short. Should be at least module.func." % elems)
func_name = elems[-1]
func... | As a python code expert, you are capable of creating scripts from specifications. |
Run the necessary methods in the correct order. | Explain what the following Python 3 code does
def runner(self):
printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.objectprep()
self.runmetadata = objects.samples
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
word = split(word) # detect any non-delimited compounds
compound = True if re.search(r'-| |\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
syll, rules = syllabify(word)
yield syll... | Create a Python 3 function for
syllabifying the given word whether simplex or complex. | As a python code expert, you are capable of creating scripts from specifications. |
Return the edge characters of this node. | How would you explain what the following Python 3 function does
def edges(self):
edge_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_edges(self.gdg, self.node, edge_str)
return [char for char in edge_str.value.decode("ascii")] | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the letter set of this node. | Can you generate a brief explanation for the following Python 3 code
def letter_set(self):
end_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_letter_set(self.gdg, self.node, end_str)
return [char for char in end_str.value.decode("ascii")] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_end(self, char):
"""
Return `True` if this `char` is part of this node's letter set,
`False` otherwise.
"""
char = char.lower()
return bool(cgaddag.gdg_is_end(self.gdg, self.node, char.encode("ascii"))) | Create a Python 3 function to
return True if this char is part of this node s letter set False otherwise. | As a Python code composer, you craft elegant and concise scripts. |
Traverse the GADDAG to the node at the end of the given characters. | Make a summary of the following Python 3 code
def follow(self, chars):
chars = chars.lower()
node = self.node
for char in chars:
node = cgaddag.gdg_follow_edge(self.gdg, node, char.encode("ascii"))
if not node:
raise KeyError(char)
return Node(se... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _split_docker_link(alias_name):
"""
Splits a docker link string into a list of 3 items (protocol, host, port).
- Assumes IPv4 Docker links
ex: _split_docker_link('DB') -> ['tcp', '172.17.0.82', '8080']
"""
sanitized_name = alias_name.strip().upper()
split_list = re.split(r':|//', core.s... | Create a Python 3 function to
split a docker link string into a list of 3 items. | As a python code expert, you are capable of creating scripts from specifications. |
def read(alias_name, allow_none=False):
"""Get the raw docker link value.
Get the raw environment variable for the docker link
Args:
alias_name: The environment variable name
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. ... | Write a Python 3 function for
getting the raw docker link value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a boolean if the docker link is set or not. | Here you have a function in Python 3, explain what it does
def isset(alias_name):
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2)
raw_value = read(alias_name, allow_none=True)
if raw_value:
if re.compile(r'.+://.+:\d+').match(raw_value):
return True
els... | As a python code expert, you are capable of creating scripts from specifications. |
def protocol(alias_name, default=None, allow_none=False):
"""Get the protocol from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
... | Write a Python 3 script for
getting the protocol from the docker link alias or return the default value. | As a Python code analyst, you investigate and solve complex coding mysteries |
def port(alias_name, default=None, allow_none=False):
"""Get the port from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
Examp... | Can you implement a function in Python 3 that
gets the port from the docker link alias or return the default value. | As a python code expert, you are capable of creating scripts from specifications. |
def runner(self):
"""
Run the necessary methods in the correct order
"""
printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
if not self.pipeline:
# If the metadata has been passed from the method script, self.pipeline must still be fa... | Implement a function in Python 3 to
run the necessary methods in the correct order. | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses the 16S target files to link accession numbers stored in the. fai and the. metadata files to the genera stored in the. genera file. | Here you have a function in Python 3, explain what it does
def attributer(self):
from Bio import SeqIO
import operator
for sample in self.runmetadata.samples:
# Load the records from the target file into a dictionary
record_dict = SeqIO.to_dict(SeqIO.parse(sample[self.ana... | As a Python code analyst, you investigate and solve complex coding mysteries |
def spawn_server_api(api_name, app, api_spec, error_callback, decorator):
"""Take a a Flask app and a swagger file in YAML format describing a REST
API, and populate the app with routes handling all the paths and methods
declared in the swagger file.
Also handle marshaling and unmarshaling between json... | Can you implement a function in Python 3 that
spawns a REST API. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _responsify(api_spec, error, status):
"""Take a bravado-core model representing an error, and return a Flask Response
with the given error code and error instance as body"""
result_json = api_spec.model_to_json(error)
r = jsonify(result_json)
r.status_code = status
return r | Write a Python 3 script to
take a bravado - core model representing an error and return a Flask Response containing the given error code and error instance as body | You are a Python code analyst, evaluating scripts for potential improvements. |
def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator):
"""Generate a handler method for the given url method+path and operation"""
# Decorate the handler function, if Swagger spec tells us to
if endpoint.decorate_server:
endpoint_decorator = get... | How would you code a function in Python 3 to
generate a handler function for the given url method + path and operation | As a Python code composer, you craft elegant and concise scripts. |
def format_escape( foreground=None, background=None, bold=False, faint=False,
italic=False, underline=False, blink=False, inverted=False ):
"""Returns the ANSI escape sequence to set character formatting.
foreground
Foreground colour to use. Accepted types: None, int (xterm
palette ID), tup... | How would you implement a function in Python 3 that
returns the ANSI escape sequence to set character formatting. | As a Python code composer, you craft elegant and concise scripts. |
Returns a Unicode string formatted with an ANSI escape sequence. | Can you tell what is the following Python 3 function doing
def format_string( string, foreground=None, background=None, reset=True, bold=False,
faint=False, italic=False, underline=False, blink=False, inverted=False ):
"""Returns a Unicode string formatted with an ANSI escape sequence.
string
Strin... | You are a Python code architect, reviewing and designing scalable and efficient code |
def format_pixels( top, bottom, reset=True, repeat=1 ):
"""Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom colou... | Create a Python 3 function for
returning the ANSI escape sequence to render two vertically - stacked pixels as a single monospace character. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return ANSI escape sequence to render a bitmap image. | Can you generate the documentation for the following Python 3 function
def format_image_iter( data_fetch, x_start=0, y_start=0, width=32, height=32, frame=0, columns=1, downsample=1 ):
frames = []
try:
frame_iter = iter( frame )
frames = [f for f in frame_iter]
except TypeError:
fram... | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_buffer_with_value( self, value, buffer, parent=None ):
"""Write a Python object into a byte array, using the field definition.
value
Input Python object to process.
buffer
Output byte array to encode value into.
parent
Parent block object... | Write a Python 3 script for
writing a Python object into a byte array using the field definition. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the end offset of the field s data. Used for chainloading. | Given the following Python 3 function, write the documentation
def get_end_offset( self, value, parent=None, index=None ):
return self.get_start_offset( value, parent, index ) + self.get_size( value, parent, index ) | You are a Python code analyst, evaluating scripts for potential improvements. |
Split string along any punctuation or whitespace. | Can you tell what is the following Python 3 function doing
def nonalpha_split(string):
'''Split 'string' along any punctuation or whitespace.'''
return re.findall(r'[%s]+|[^%s]+' % (A, A), string, flags=FLAGS) | You are a Python code architect, reviewing and designing scalable and efficient code |
Split string into ( stressed ) syllables and punctuation and whitespace. | Make a summary of the following Python 3 code
def syllable_split(string):
'''Split 'string' into (stressed) syllables and punctuation/whitespace.'''
p = r'\'[%s]+|`[%s]+|[%s]+|[^%s\'`\.]+|[^\.]{1}' % (A, A, A, A)
return re.findall(p, string, flags=FLAGS) | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract all alphabetic syllabified forms from string. | Make a summary of the following Python 3 code
def extract_words(string):
'''Extract all alphabetic syllabified forms from 'string'.'''
return re.findall(r'[%s]+[%s\.]*[%s]+' % (A, A, A), string, flags=FLAGS) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def thread_with_callback(on_error, on_done, requete_with_callback):
"""
Return a thread emiting `state_changed` between each sub-requests.
:param on_error: callback str -> None
:param on_done: callback object -> None
:param requete_with_callback: Job to execute. monitor_callable -> None
:return... | Write a Python 3 function for
returning a thread that emits state_changed between each sub - request. | You are a Python code generator, capable of creating scripts from specifications. |
def protege_data(datas_str, sens):
"""
Used to crypt/decrypt data before saving locally.
Override if securit is needed.
bytes -> str when decrypting
str -> bytes when crypting
:param datas_str: When crypting, str. when decrypting bytes
:param sens: True to crypt, False to decrypt
"""
... | Write a Python 3 function that can
use to crypt and decrypt data before saving locally. | You are a Python code generator, capable of creating scripts from specifications. |
Build a parser for CLI arguments and options. | Given the following Python 3 function, write the documentation
def build_parser(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'--delimiter',
help='a delimiter for the samples (teeth) in the key',
default=' ',
)
parser.add_argument(
'--encoding',
help=... | You are a Python code architect, reviewing and designing scalable and efficient code |
def default_parser() -> argparse.ArgumentParser:
"""Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser(
prog=CONSOLE_SCRIPT,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
build_parser(parser)
return parser | Write a Python 3 function for
creating a parser for CLI arguments and options. | You are a Python code generator, capable of creating scripts from specifications. |
Return a random string from the sequence seq. | Can you tell what is the following Python 3 function doing
def key(
seq: Sequence,
tooth: Callable[[Sequence], str] = (
lambda seq: str(random.SystemRandom().choice(seq)).strip()
),
nteeth: int = 6,
delimiter: str = ' ',
) -> str:
"""Concatenate strings generated ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_firewalld_service(service, permanent=True):
""" adds a firewall rule """
yum_install(packages=['firewalld'])
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
p = ''
if permanent:
p = '--permanent'
sud... | Can you write a function in Python 3 where it
adds a firewall rule to the firewalld service | As a python code expert, you are capable of creating scripts from specifications. |
Adds a firewall rule to the firewalld system | Can you tell what is the following Python 3 function doing
def add_firewalld_port(port, permanent=True):
yum_install(packages=['firewalld'])
log_green('adding a new fw rule: %s' % port)
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
... | As a Python code composer, you craft elegant and concise scripts. |
def apt_add_repository_from_apt_string(apt_string, apt_file):
""" adds a new repository file for apt """
apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file
if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True):
file_append(apt_file_path, apt_string.lower(), use_sudo=True)
... | Write a Python 3 script to
add a new repository file for apt | As a Python code composer, you craft elegant and concise scripts. |
def arch():
""" returns the current cpu archictecture """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo('rpm -E %dist').strip()
return result | Write a Python 3 script to
return the current cpu archictecture | You are a Python code analyst, evaluating scripts for potential improvements. |
def disable_openssh_rdns(distribution):
"""
Set 'UseDNS no' in openssh config to disable rDNS lookups
On each request for a new channel openssh defaults to an
rDNS lookup on the client IP. This can be slow, if it fails
for instance, adding 10s of overhead to every request
for a new channel (not... | How would you code a function in Python 3 to
disable rDNS lookups on the given binary node. | You are a Python code analyst, evaluating scripts for potential improvements. |
def connect_to_ec2(region, access_key_id, secret_access_key):
""" returns a connection object to AWS EC2 """
conn = boto.ec2.connect_to_region(region,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key)
return... | How would you implement a function in Python 3 that
connects to AWS EC2 | You are a Python code generator, capable of creating scripts from specifications. |
def connect_to_rackspace(region,
access_key_id,
secret_access_key):
""" returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(access_key_id, secret_access_key)... | Create a Python 3 function for
returning a connection object to Rackspace | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a GCE image from the disk. | Can you tell what is the following Python 3 function doing
def create_gce_image(zone,
project,
instance_name,
name,
description):
"""
Shuts down the instance and creates and image from the disk.
Assumes that the disk name i... | You are a Python code architect, reviewing and designing scalable and efficient code |
proxy call for ec2 rackspace create ami backend functions | How would you explain what the following Python 3 function does
def create_image(cloud, **kwargs):
if cloud == 'ec2':
return create_ami(**kwargs)
if cloud == 'rackspace':
return create_rackspace_image(**kwargs)
if cloud == 'gce':
return create_gce_image(**kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a new instance of the server. | Given the following Python 3 function, write the documentation
def create_server(cloud, **kwargs):
if cloud == 'ec2':
_create_server_ec2(**kwargs)
elif cloud == 'rackspace':
_create_server_rackspace(**kwargs)
elif cloud == 'gce':
_create_server_gce(**kwargs)
else:
raise V... | As a Python code composer, you craft elegant and concise scripts. |
This function will wait until the operation completes. | Can you generate the documentation for the following Python 3 function
def gce_wait_until_done(operation):
operation_name = operation['name']
if 'zone' in operation:
zone_url_parts = operation['zone'].split('/')
project = zone_url_parts[-3]
zone = zone_url_parts[-1]
def get_zone... | As a Python code composer, you craft elegant and concise scripts. |
Create a new GCE Slave Instance. | How would you explain what the following Python 3 function does
def startup_gce_instance(instance_name, project, zone, username, machine_type,
image, public_key, disk_name=None):
"""
For now, jclouds is broken for GCE and we will have static slaves
in Jenkins. Use this to boot them... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _create_server_ec2(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_type,
username,
... | Can you create a Python 3 function that
creates a new EC2 server and return a new EC2 instance | As a Python code analyst, you investigate and solve complex coding mysteries |
def _create_server_rackspace(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_... | Write a Python 3 script to
create a new server in Rackspace and save it locally. | As a Python code composer, you craft elegant and concise scripts. |
destroys an EBS volume | Make a summary of the following Python 3 code
def destroy_ebs_volume(region, volume_id, access_key_id, secret_access_key):
conn = connect_to_ec2(region, access_key_id, secret_access_key)
if ebs_volume_exists(region, volume_id, access_key_id, secret_access_key):
log_yellow('destroying EBS volume ...')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def destroy_rackspace(region, instance_id, access_key_id, secret_access_key):
""" terminates the instance """
nova = connect_to_rackspace(region,
access_key_id,
secret_access_key)
server = nova.servers.get(instance_id)
log_yellow('deleting... | Can you write a function in Python 3 where it
deletes the rackspace instance. | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks if an ebs volume exists | Given the following Python 3 function, write the documentation
def ebs_volume_exists(region, volume_id, access_key_id, secret_access_key):
conn = connect_to_ec2(region, access_key_id, secret_access_key)
for vol in conn.get_all_volumes():
if vol.id == volume_id:
return True | You are a Python code architect, reviewing and designing scalable and efficient code |
configure marathon to start with basic authentication | Can you generate the documentation for the following Python 3 function
def enable_marathon_basic_authentication(principal, password):
upstart_file = '/etc/init/marathon.conf'
with hide('running', 'stdout'):
sudo('echo -n "{}" > /etc/marathon-mesos.credentials'.format(password))
boot_args = ' '.join(... | As a Python code analyst, you investigate and solve complex coding mysteries |
enables and adds a new authorized principal | Explain what the following Python 3 code does
def enable_mesos_basic_authentication(principal, password):
restart = False
secrets_file = '/etc/mesos/secrets'
secrets_entry = '%s %s' % (principal, password)
if not file_contains(filename=secrets_file,
text=secrets_entry, use_sudo=... | You are a Python code analyst, evaluating scripts for potential improvements. |
Updates the mode owner group for the remote file at the given location. | Can you generate a brief explanation for the following Python 3 code
def file_attribs(location, mode=None, owner=None, group=None, sudo=False):
return dir_attribs(location, mode, owner, group, False, sudo) | You are a Python code analyst, evaluating scripts for potential improvements. |
queries EC2 for details about a particular instance_id
| Can you generate the documentation for the following Python 3 function
def get_ec2_info(instance_id,
region,
access_key_id,
secret_access_key,
username):
""" queries EC2 for details about a particular instance_id
"""
conn = connect_to_ec2(r... | As a python code expert, you are capable of creating scripts from specifications. |
def get_ip_address_from_rackspace_server(server_id):
"""
returns an ipaddress for a rackspace instance
"""
nova = connect_to_rackspace()
server = nova.servers.get(server_id)
# the server was assigned IPv4 and IPv6 addresses, locate the IPv4 address
ip_address = None
for network in server... | Create a Python 3 function for
returning an ipaddress for a rackspace instance | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_rackspace_info(server_id,
region,
access_key_id,
secret_access_key,
username):
""" queries Rackspace for details about a particular server id
"""
nova = connect_to_rackspace(region, access_key_id, secret_acce... | Can you write a function in Python 3 where it
queries Rackspace for details about a particular server id and region | As a Python code composer, you craft elegant and concise scripts. |
def install_mesos_single_box_mode(distribution):
""" install mesos (all of it) on a single node"""
if 'ubuntu' in distribution:
log_green('adding mesosphere apt-key')
apt_add_key(keyid='E56151BF')
os = lsb_release()
apt_string = 'deb http://repos.mesosphere.io/%s %s main' % (
... | Can you write a function in Python 3 where it
installs mesos on a single node | You are a Python code generator, capable of creating scripts from specifications. |
inserts a line in the middle of a file | Can you tell what is the following Python 3 function doing
def insert_line_in_file_after_regex(path, line, after_regex, use_sudo=False):
tmpfile = str(uuid.uuid4())
get_file(path, tmpfile, use_sudo=use_sudo)
with open(tmpfile) as f:
original = f.read()
if line not in original:
outfile ... | As a python code expert, you are capable of creating scripts from specifications. |
installs a python module | Given the following Python 3 function, write the documentation
def install_python_module(name):
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
run('pip --quiet install %s' % name) | You are a Python code analyst, evaluating scripts for potential improvements. |
installs a python module locally | How would you explain what the following Python 3 function does
def install_python_module_locally(name):
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
local('pip --quiet install %s' % name) | You are a Python code analyst, evaluating scripts for potential improvements. |
install a particular gem | Can you generate a brief explanation for the following Python 3 code
def install_system_gem(gem):
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
sudo("gem install %s --no-rdoc --no-ri" % gem) | As a Python code translator, you convert algorithms and pseudocode into Python. |
checks if vagrant plugin is installed | Can you tell what is the following Python 3 function doing
def is_vagrant_plugin_installed(plugin, use_sudo=False):
cmd = 'vagrant plugin list'
if use_sudo:
results = sudo(cmd)
else:
results = run(cmd)
installed_plugins = []
for line in results:
plugin = re.search('^(\S.*)... | As a python code expert, you are capable of creating scripts from specifications. |
checks if a particular deb package is installed | Given the following Python 3 function, write the documentation
def is_deb_package_installed(pkg):
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo('dpkg-query -l "%s" | grep -q ^.i' % pkg)
return not bool(result.return_co... | You are a Python code analyst, evaluating scripts for potential improvements. |
checks if ssh port is open | Can you generate the documentation for the following Python 3 function
def is_ssh_available(host, port=22):
s = socket.socket()
try:
s.connect((host, port))
return True
except:
return False | As a Python code composer, you craft elegant and concise scripts. |
def os_release(username, ip_address):
""" returns /etc/os-release in a dictionary """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
_os_release = {}
with settings(host_string=username + '@' + ip_address):
data = run('... | Write a Python 3 script to
return the os - release for a user | As a python code expert, you are capable of creating scripts from specifications. |
loads the state from a local data. json file | Explain what the following Python 3 code does
def load_state_from_disk():
if is_there_state():
with open('data.json', 'r') as f:
data = json.load(f)
return data
else:
return False | You are a Python code generator, capable of creating scripts from specifications. |
Prints info about our EC2 instance | Make a summary of the following Python 3 code
def print_ec2_info(region,
instance_id,
access_key_id,
secret_access_key,
username):
""" outputs information about our EC2 instance """
data = get_ec2_info(instance_id=instance_id,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prints out information about our Rackspace instance | Can you tell what is the following Python 3 function doing
def print_gce_info(zone, project, instance_name, data):
try:
instance_info = _get_gce_compute().instances().get(
project=project,
zone=zone,
instance=instance_name
).execute()
log_yellow(pformat(in... | You are a Python code analyst, evaluating scripts for potential improvements. |
def print_rackspace_info(region,
instance_id,
access_key_id,
secret_access_key,
username):
""" outputs information about our Rackspace instance """
data = get_rackspace_info(server_id=instance_id,
... | How would you code a function in Python 3 to
print out information about our Rackspace instance | As a Python code translator, you convert algorithms and pseudocode into Python. |
syncs the source code to the remote box | Can you tell what is the following Python 3 function doing
def rsync():
log_green('syncing code to remote box...')
data = load_state_from_disk()
if 'SOURCE_PATH' in os.environ:
with lcd(os.environ['SOURCE_PATH']):
local("rsync -a "
"--info=progress2 "
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Save the state of the EC2 instance in the local machine. | Explain what the following Python 3 code does
def save_ec2_state_locally(instance_id,
region,
username,
access_key_id,
secret_access_key):
""" queries EC2 for details about a particular instance_id and
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def ssh_session(key_filename,
username,
ip_address,
*cli):
""" opens a ssh shell to the host """
local('ssh -t -i %s %s@%s %s' % (key_filename,
username,
ip_address,
... | Write a Python 3 script for
opening a ssh shell to the host | As a Python code composer, you craft elegant and concise scripts. |
def up_ec2(region,
access_key_id,
secret_access_key,
instance_id,
username):
""" boots an existing ec2_instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# boot the ec2 instance
instance = conn.start_instances(instance_ids=instance_i... | Implement a Python 3 function for
booting an ec2 instance and update the ec2 state file | You are a Python code architect, reviewing and designing scalable and efficient code |
def wait_for_ssh(host, port=22, timeout=600):
""" probes the ssh port and waits until it is available """
log_yellow('waiting for ssh...')
for iteration in xrange(1, timeout): #noqa
sleep(1)
if is_ssh_available(host, port):
return True
else:
log_yellow('waitin... | Can you write a function in Python 3 where it
waits until the ssh port is available | As a python code expert, you are capable of creating scripts from specifications. |
Returns a tuple of QPixmap et QLabel | Given the following Python 3 function, write the documentation
def _get_visuals(user):
pixmap = SuperUserAvatar() if user["status"] == "admin" else UserAvatar()
label = user["label"]
return pixmap, QLabel(label) | You are a Python code architect, reviewing and designing scalable and efficient code |
save a directory to a certain alias | Explain what the following Python 3 code does
def saveDirectory(alias):
if not settings.platformCompatible():
return False
dataFile = open(settings.getDataFile(), "wb")
currentDirectory = os.path.abspath(".")
directory = {alias : currentDirectory}
pickle.dump(directory, dataFile)
speech.success(alias + " will n... | As a python code expert, you are capable of creating scripts from specifications. |
def goToDirectory(alias):
"""go to a saved directory"""
if not settings.platformCompatible():
return False
data = pickle.load(open(settings.getDataFile(), "rb"))
try:
data[alias]
except KeyError:
speech.fail("Sorry, it doesn't look like you have saved " + alias + " yet.")
speech.fail("Go to the directory y... | Can you implement a function in Python 3 that
goes to a saved directory | As a python code expert, you are capable of creating scripts from specifications. |
This method returns a list of all the container task type related objects in the API. | How would you explain what the following Python 3 function does
def list(self, filters=None):
# Add in the page and page_size parameters to the filter, such
# that our request gets *all* objects in the list. However,
# don't do this if the user has explicitly included these
# parameters ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the object with a given id. | Make a summary of the following Python 3 code
def get(self, id):
# Get the object
request_url = self._client.base_api_url + self.detail_url.format(id=id)
response = self._client.session.get(request_url)
# Validate that the request was successful
self.validate_request_success(
... | As a Python code composer, you craft elegant and concise scripts. |
def validate_request_success(
response_text, request_url, status_code, expected_status_code
):
"""Validates that a request was successful.
Args:
response_text (str): The response body of the request.
request_url (str): The URL the request was made at.
sta... | How would you code a function in Python 3 to
validate that a request was successful. | You are a Python code generator, capable of creating scripts from specifications. |
Syncs this object with latest data on the saltant server. | How would you explain what the following Python 3 function does
def sync(self):
self = self.manager.get(uuid=self.uuid)
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
Wait until a task instance with the given UUID is finished. | Given the following Python 3 function, write the documentation
def wait_until_finished(
self, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD
):
"""Wait until a task instance with the given UUID is finished.
Args:
refresh_period (int, optional): How many seconds to wait... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a new task instance. | Given the following Python 3 function, write the documentation
def create(self, task_type_id, task_queue_id, arguments=None, name=""):
# Make arguments an empty dictionary if None
if arguments is None:
arguments = {}
# Create the object
request_url = self._client.base_api_ur... | You are a Python code generator, capable of creating scripts from specifications. |
Clone the task instance with given UUID. | Given the following Python 3 function, write the documentation
def clone(self, uuid):
# Clone the object
request_url = self._client.base_api_url + self.clone_url.format(
id=uuid
)
response = self._client.session.post(request_url)
# Validate that the request was succ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def terminate(self, uuid):
"""Terminate the task instance with given UUID.
Args:
uuid (str): The UUID of the task instance to terminate.
Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstance`:
A task instance model instance representing the... | How would you code a function in Python 3 to
terminate the task instance with given UUID. | You are a Python code architect, reviewing and designing scalable and efficient code |
def wait_until_finished(
self, uuid, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD
):
"""Wait until a task instance with the given UUID is finished.
Args:
uuid (str): The UUID of the task instance to wait for.
refresh_period (float, optional): How many sec... | Write a Python 3 function for
waiting until a task instance with the given UUID is finished. | You are a Python code generator, capable of creating scripts from specifications. |
def response_data_to_model_instance(self, response_data):
"""Convert response data to a task instance model.
Args:
response_data (dict): The data from the request's response.
Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstance`:
A task in... | Can you create a Python 3 function that
converts the response data to a task instance model instance. | As a python code expert, you are capable of creating scripts from specifications. |
Ensure all column names are unique identifiers. | Given the following Python 3 function, write the documentation
def _ids_and_column_names(names, force_lower_case=False):
fixed = OrderedDict()
for name in names:
identifier = RowWrapper._make_identifier(name)
if force_lower_case:
identifier = identifier.lower()
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Attempt to convert string into a valid identifier by replacing invalid characters with _s and prefix with a_. | How would you explain what the following Python 3 function does
def _make_identifier(string):
string = re.sub(r"[ \-+/\\*%&$£#@.,;:'" "?<>]", "_", string)
if re.match(r"^\d", string):
string = "a_{0}".format(string)
return string | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _increment_numeric_suffix(s):
"""Increment (or add) numeric suffix to identifier."""
if re.match(r".*\d+$", s):
return re.sub(r"\d+$", lambda n: str(int(n.group(0)) + 1), s)
return s + "_2" | Implement a function in Python 3 to
increment numeric suffix to identifier. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.