text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ExecuteCmd(cmd, quiet=False): """ Run a command in a shell. """
result = None if quiet: with open(os.devnull, "w") as fnull: result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull) else: result = subprocess.call(cmd, shell=True) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CheckOutput(*popenargs, **kwargs): """ Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as p...
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, _ = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subprocess.CalledProcessError(retcode, cmd) error.output = output...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def UrlGet(url, timeout=10, retries=0): """ Retrieve content from the given URL. """
# in Python 2.6 we can pass timeout to urllib2.urlopen socket.setdefaulttimeout(timeout) attempts = 0 content = None while not content: try: content = urllib2.urlopen(url).read() except urllib2.URLError: attempts = attempts + 1 if attempts > retries: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ReadRemoteFile(remote_file_path, hostname, ssh_key): """ Reads a remote file into a string. """
cmd = 'sudo cat %s' % remote_file_path exit_code, output = RunCommandOnHost(cmd, hostname, ssh_key) if exit_code: raise IOError('Can not read remote path: %s' % (remote_file_path)) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __RemoteExecuteHelper(args): """ Helper for multiprocessing. """
cmd, hostname, ssh_key = args #Random.atfork() # needed to fix bug in old python 2.6 interpreters private_key = paramiko.RSAKey.from_private_key(StringIO.StringIO(ssh_key)) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) while True: try: client.co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WaitForHostsReachable(hostnames, ssh_key): """ Blocks until host is reachable via ssh. """
while True: unreachable = GetUnreachableHosts(hostnames, ssh_key) if unreachable: print 'waiting for unreachable hosts: %s' % unreachable time.sleep(5) else: break return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetUnreachableInstances(instances, ssh_key): """ Returns list of instances unreachable via ssh. """
hostnames = [i.private_ip for i in instances] ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_instances = [instance for (instance, ssh_ok) in zip(instances, ssh_status) if not ssh_ok] return nonresponsive_instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetUnreachableHosts(hostnames, ssh_key): """ Returns list of hosts unreachable via ssh. """
ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok] return nonresponsive_hostnames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AreHostsReachable(hostnames, ssh_key): """ Returns list of bools indicating if host reachable via ssh. """
# validate input for hostname in hostnames: assert(len(hostname)) ssh_ok = [exit_code == 0 for (exit_code, _) in RunCommandOnHosts('echo test > /dev/null', hostnames, ssh_key)] return ssh_ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AmiName(ami_release_name, ubuntu_release_name, virtualization_type, mapr_version, role): """ Returns AMI name using Cirrus ami naming convention. """
if not role in valid_instance_roles: raise RuntimeError('Specified role (%s) not a valid role: %s' % (role, valid_instance_roles)) if virtualization_type not in valid_virtualization_types: raise RuntimeError('Specified virtualization type (%s) not valid: %s' % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LookupCirrusAmi(ec2, instance_type, ubuntu_release_name, mapr_version, role, ami_release_name, ami_owner_id): """ Returns AMI satisfying provided constraints...
if not role in valid_instance_roles: raise RuntimeError('Specified role (%s) not a valid role: %s' % (role, valid_instance_roles)) virtualization_type = 'paravirtual' if IsHPCInstanceType(instance_type): virtualization_type = 'hvm' assert(ami_owner_id) images = ec2.get_all_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetRegion(region_name): """ Converts region name string into boto Region object. """
regions = boto_ec2.regions() region = None valid_region_names = [] for r in regions: valid_region_names.append(r.name) if r.name == region_name: region = r break if not region: logging.info( 'invalid region name: %s ' % (region_name)) logging.info( 'Try one of these:\n %s' % (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PrivateToPublicOpenSSH(key, host): """ Computes the OpenSSH public key format given a private key. """
# Create public key from private key. ssh_rsa = '00000007' + base64.b16encode('ssh-rsa') # Exponent. exponent = '%x' % (key.e,) if len(exponent) % 2: exponent = '0' + exponent ssh_rsa += '%08x' % (len(exponent) / 2,) ssh_rsa += exponent modulus = '%x' % (key.n,) if len(modulus) % 2: modul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def InitKeypair(aws_id, aws_secret, ec2, s3, keypair_name, src_region, dst_regions): """ Returns the ssh private key for the given keypair name Cirrus created bu...
# check if a keypair has been created metadata = CirrusAccessIdMetadata(s3, aws_id) keypair = ec2.get_key_pair(keypair_name) ssh_key = None if keypair: # if created, check that private key is available in s3 ssh_key = metadata.GetSshKey(keypair_name) # if the private key is not created or not av...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __WaitForVolume(volume, desired_state): """ Blocks until EBS volume is in desired state. """
print 'Waiting for volume %s to be %s...' % (volume.id, desired_state) while True: volume.update() sys.stdout.write('.') sys.stdout.flush() #print 'status is: %s' % volume.status if volume.status == desired_state: break time.sleep(5) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WaitForSnapshotCompleted(snapshot): """ Blocks until snapshot is complete. """
print 'Waiting for snapshot %s to be completed...' % (snapshot) while True: snapshot.update() sys.stdout.write('.') sys.stdout.flush() #print 'status is: %s' % snapshot.status if snapshot.status == 'completed': break time.sleep(5) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __WaitForInstance(instance, desired_state): """ Blocks until instance is in desired_state. """
print 'Waiting for instance %s to change to %s' % (instance.id, desired_state) while True: try: instance.update() state = instance.state sys.stdout.write('.') sys.stdout.flush() if state == desired_state: break except boto_exception.EC2Res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SearchUbuntuAmiDatabase(release_name, region_name, root_store_type, virtualization_type): """ Returns the ubuntu created ami matching the given criteria. """
ami_list_url = 'http://cloud-images.ubuntu.com/query/%s/server/released.txt' \ % (release_name) url_file = urllib2.urlopen(ami_list_url) # The mapping of columns names to col ids in the ubuntu release txt file. release_name_col = 0 release_tag_col = 2 release_date_col = 3 root_store_type_col = 4 arc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render(self, request, context, status=codes.ok, content_type=None, args=None, kwargs=None): "Expects the method handler to return the `context` for the template." if isinstance(self.template_name, (list, tuple)): template = loader.select_template(self.template_name) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_autocomplete(prompt, complete, default=None, contains_spaces=True, show_default=True, prompt_suffix=': ', color=None): """ Prompt a string with autoco...
def real_completer(text, state): possibilities = complete(text) + [None] if possibilities: return possibilities[state] return None readline.set_completer_delims('\t\n' + ' ' * (not contains_spaces)) readline.parse_and_bind("tab: complete") readline.set_completer(r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_file(prompt, default=None, must_exist=True, is_dir=False, show_default=True, prompt_suffix=': ', color=None): """ Prompt a filename using using glob f...
if must_exist: while True: r = prompt_autocomplete(prompt, path_complete(is_dir), default, show_default=show_default, prompt_suffix=prompt_suffix, color=color) if os.path.exists(r): break print('This path does not exis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_choice(prompt, possibilities, default=None, only_in_poss=True, show_default=True, prompt_suffix=': ', color=None): """ Prompt for a string in a given ...
assert len(possibilities) >= 1 assert not only_in_poss or default is None or default in possibilities, '$s not in possibilities' % default contains_spaces = any(' ' in poss for poss in possibilities) possibilities = sorted(possibilities) readline.clear_history() for kw in possibilities: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_glide_depths(depths, mask_tag_filt): '''Plot depth at glides Args ---- depths: ndarray Depth values at each sensor sampling mask_tag_filt: ndarray Boolean mask to slice filtered sub-glides from tag data ''' import numpy from . import plotutils fig, ax = pl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_keys(self): """Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise"""
verify_keys_endpoint = Template("${rest_root}/site/${public_key}") url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) data = { "clientName": "mollom_python", "clientVersion": "1.0" } self._client.headers["Content-Type"] = "application...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_captcha(self, captcha_id, solution, author_name=None, author_url=None, author_mail=None, author_ip=None, author_id=None, author_open_id=None, honeypot=N...
check_catpcha_endpoint = Template("${rest_root}/captcha/${captcha_id}") url = check_catpcha_endpoint.substitute(rest_root=self._rest_root, captcha_id=captcha_id) data = {"solution": solution} response = self.__post_request(url, data) # Mollom returns "1" for su...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_blacklist_entries(self): """Get a list of all blacklist entries. """
get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) response = self.__get_request(url) return response["list"]["entry"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_blacklist_entry(self, blacklist_entry_id): """Get a single blacklist entry Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklis...
get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/${blacklist_entry_id}") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key, blacklist_entry_id=blacklist_entry_id) response = self.__get_request(url) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_deployment(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ create a deployment with the specified name """
headers = token_manager.get_access_token_headers() payload = { 'name': deployment_name, 'isAdmin': True } deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments' % deployment_url, data=json.dump...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_deployments(token_manager=None, app_url=defaults.APP_URL): """ return the list of deployments that the current access_token gives you access to """
headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: return response.json() else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_deployment_id(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the deployment id for the deployment with the specified name """
headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: deployments = response.json() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_space_id(deployment_name, space_name, token_manager=None, app_url=defaults.APP_URL): """ get the space id that relates to the space name provided """
spaces = get_spaces(deployment_name, token_manager=token_manager, app_url=app_url) for space in spaces: if space['name'] == space_name: return space['id'] raise JutException('Unable to find space "%s" within deployment "%s"' % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.AP...
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) payload = { 'name': space_name, 'security_policy': security_policy, 'events_retention_days': events_retention_day...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_users(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ get all users in the deployment specified """
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_user(username, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ add user to deployment """
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) account_id = accounts.get_account_id(username, token_manager=token_manager, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """
return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_string(self, chars, current_linkable=False, class_current="active_link"): """ It returns menu as string """
return self.__do_menu("as_string", current_linkable, class_current, chars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as ul """
return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as p """
return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as string """
return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_config(filename, header): """ Parses the provided filename and returns ``SettingParser`` if the parsing was successful and header matches the header de...
parser = SettingParser(filename) if parser.header != header: header_value = parser.header or '' raise ParseError(u"Unexpected header '{0}', expecting '{1}'" .format(common.from_utf8(header_value), header)) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_variable(obj, **kwargs): """Print the variable out. Limit the string length to, by default, 300 characters."""
variable_print_length = kwargs.get("variable_print_length", 1000) s = str(obj) if len(s) < 300: return "Printing the object:\n" + str(obj) else: return "Printing the object:\n" + str(obj)[:variable_print_length] + ' ...'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encompasses(self, span): """ Returns true if the given span fits inside this one """
if isinstance(span, list): return [sp for sp in span if self._encompasses(sp)] return self._encompasses(span)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encompassed_by(self, span): """ Returns true if the given span encompasses this span. """
if isinstance(span, list): return [sp for sp in span if sp.encompasses(self)] return span.encompasses(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adds(self, string): """ Add a string child. """
if isinstance(string, unicode): string = string.encode("utf-8") self.children.append((STRING, str(string)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """ Delete this record without deleting any dependent or child records. This can orphan records, so use with care. """
if self.id: with Repo.db: Repo(self.__table).where(id=self.id).delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def shorten(string, max_length=80, trailing_chars=3): ''' trims the 'string' argument down to 'max_length' to make previews to long string values ''' assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string)) assert type(max_length) == int, 'shorte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_prettytable(string): """ returns true if the input looks like a prettytable """
return type(string).__name__ in {'str','unicode'} and ( len(string.splitlines()) > 1 ) and ( all(string[i] == string[-i-1] for i in range(3)) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_published_ships_basic(db_connection): """ Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID...
if not hasattr(get_all_published_ships_basic, '_results'): sql = 'CALL get_all_published_ships_basic();' results = execute_sql(sql, db_connection) get_all_published_ships_basic._results = results return get_all_published_ships_basic._results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ships_that_have_variations(db_connection): """ Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list """
if not hasattr(get_ships_that_have_variations, '_results'): sql = 'CALL get_ships_that_have_variations();' results = execute_sql(sql, db_connection) get_ships_that_have_variations._results = results return get_ships_that_have_variations._results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def c14n(xml): ''' Applies c14n to the xml input @param xml: str @return: str ''' tree = etree.parse(StringIO(xml)) output = StringIO() tree.write_c14n(output, exclusive=False, with_comments=True, compression=0) output.flush() c14nized = output.getvalue() output.close() r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sign(xml, private, public): ''' Return xmldsig XML string from xml_string of XML. @param xml: str of bytestring xml to sign @param private: publicKey Private key @param public: publicKey Public key @return str: signed XML byte string ''' xml = xml.encode('utf-8', 'xmlcharrefreplace')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify(xml): '''Verifies whether the validity of the signature contained in an XML document following the XMLDSig standard''' try: from cStringIO import cStringIO as StringIO except ImportError: from StringIO import StringIO xml = xml.encode('utf-8', 'xmlcharrefreplace') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodiscover(): """ Perform an autodiscover of an api.py file in the installed apps to generate the routes of the registered viewsets. """
for app in settings.INSTALLED_APPS: try: import_module('.'.join((app, 'api'))) except ImportError as e: if e.msg != "No module named '{0}.api'".format(app): print(e.msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identify_module(arg): """Import and return the Python module named in `arg`. If the module cannot be imported, a `pywhich.ModuleNotFound` exception is raised...
try: __import__(arg) except Exception: exc = sys.exc_info()[1] raise ModuleNotFound("%s: %s" % (type(exc).__name__, str(exc))) mod = sys.modules[arg] return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identify_modules(*args, **kwargs): """Find the disk locations of the given named modules, printing the discovered paths to stdout and errors discovering path...
if len(args) == 1: path_template = "%(file)s" error_template = "Module '%(mod)s' not found (%(error)s)" else: path_template = "%(mod)s: %(file)s" error_template = "%(mod)s: not found (%(error)s)" for modulename in args: try: filepath = identify_filepath(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_version(*args): """Find the versions of the given named modules, printing the discovered versions to stdout and errors discovering versions to stderr.""...
if len(args) == 1: ver_template = "%(version)s" error_template = "Distribution/module '%(mod)s' not found (%(error)s)" else: ver_template = "%(mod)s: %(version)s" error_template = "%(mod)s: not found (%(error)s)" import pkg_resources for modulename in args: try:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=None): """Run the pywhich command as if invoked with arguments `argv`. If `argv` is `None`, arguments from `sys.argv` are used. """
if argv is None: argv = sys.argv parser = OptionParser() parser.add_option('-v', '--verbose', dest="verbose", action="count", default=2, help="be chattier (stackable)") def quiet(option, opt_str, value, parser): parser.values.verbose -= 1 parser.add_option('-q', '--quiet',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_json_file(cls, path): """ Read an instance from a JSON-formatted file. :return: A new instance """
with open(path, 'r') as f: return cls.from_dict(json.load(f))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_json_file(self, path): """ Write the instance in JSON format to a file. """
with open(path, 'w') as f: json.dump(self.to_dict(), f, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(email): """Email address validation method. :param email: Email address to be saved. :type email: basestring :returns: True if email address is corr...
if isinstance(email, basestring) and EMAIL_RE.match(email): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_password(self, raw_password): """Validates the given raw password against the intance's encrypted one. :param raw_password: Raw password to be checked ...
bcrypt = self.get_bcrypt() return bcrypt.hashpw(raw_password, self.value)==self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_archlinux(): """return True if the current distribution is running on debian like OS."""
if platform.system().lower() == 'linux': if platform.linux_distribution() == ('', '', ''): # undefined distribution. Fixed in python 3. if os.path.exists('/etc/arch-release'): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_or_clear(self, path, **kwargs): """Create path and recursively clear contents."""
try: yield self.create(path, **kwargs) except NodeExistsException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursive_delete(self, path, **kwargs): """Recursively delete path."""
while True: try: yield self.delete(path, **kwargs) except NoNodeException: break except NotEmptyException: children = yield self.get_children(path) for name in children: yield self.recursive...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_path(self, path, **kwargs): """Create nodes required to complete path."""
i = 0 while i < len(path): i = path.find("/", i) if i < 0: return subpath = path[:i] if i > 0: try: yield self.create(subpath, **kwargs) except NodeExistsException: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_or_create(self, path, *args, **kwargs): """Sets the data of a node at the given path, or creates it."""
d = self.set(path, *args, **kwargs) @d.addErrback def _error(result): return self.create(path, *args, **kwargs) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_or_wait(self, path, name): """Get data of node under path, or wait for it."""
# First, get children and watch folder. d, watch = self.get_children_and_watch(path) deferred = Deferred() path += "/" + name @watch.addCallback def _notify(event): if event.type_name == "child": d = self.get(path) d.addCall...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def contiguous_regions(condition): '''Finds contiguous True regions of the boolean array 'condition'. Args ---- condition: numpy.ndarray, dtype bool boolean mask array, but can pass the condition itself (e.g. x > 5) Returns ------- start_ind: numpy.ndarray, dtype int array ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has oc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recursive_input(input_label, type_class): '''Recursive user input prompter with type checker Args ---- type_class: type name of python type (e.g. float, no parentheses) Returns ------- output: str value entered by user converted to type `type_class` Note ---- ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def models_for_pages(*args): """ Create a select list containing each of the models that subclass the ``Page`` model. """
from warnings import warn warn("template tag models_for_pages is deprectaed, use " "PageAdmin.get_content_models instead") from yacms.pages.admin import PageAdmin return PageAdmin.get_content_models()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_model_permissions(context, token): """ Assigns a permissions dict to the given model, much like Django does with its dashboard app list. Used within the ...
model = context[token.split_contents()[1]] opts = model._meta perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(model, "perms", {}) for perm_type in ("add", "change", "delete"): model.perms[perm_type] = request.user.has_perm(perm_name % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_page_permissions(context, token): """ Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a per...
page = context[token.split_contents()[1]] model = page.get_content_model() try: opts = model._meta except AttributeError: if model is None: error = _("Could not load the model for the following page, " "was it removed?") obj = page e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, *args, **kwargs): """ Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. """
if kwargs.has_key('author'): kwargs['created_by'] = kwargs['author'] kwargs['last_modified_by'] = kwargs['author'] del kwargs['author'] return super(CMSPageManager, self).create(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_template_options(): """ Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_R...
template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT turrentine_dir = turrentine_settings.TURRENTINE_TEMPLATE_SUBDIR output = [] for root, dirs, files in os.walk(turrentine_dir): for file_name in files: full_path = os.path.join(root, file_name) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_shell(username, hostname, password, port=22): """ Launches an ssh shell """
if not username or not hostname or not password: return False with tempfile.NamedTemporaryFile() as tmpFile: os.system(sshCmdLine.format(password, tmpFile.name, username, hostname, port)) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_match(self, key): """ Gets a MatchObject for the given key. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match....
return self._get_string_match(key=key) or \ self._get_non_string_match(key=key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_non_string_match(self, key): """ Gets a MatchObject for the given key, assuming a non-string value. Args: key (str): Key of the property to look-up. Re...
expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'(.*)', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_string_match(self, key): """ Gets a MatchObject for the given key, assuming a string value. Args: key (str): Key of the property to look-up. Return: Ma...
expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'\'(.*)\'', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match ...
value = match.groups(1)[0] clean_value = str(value).lstrip().rstrip() if clean_value == 'true': self._log.info('Got value of "%s" as boolean true.', key) return True if clean_value == 'false': self._log.info('Got value of "%s" as boolean false.', k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key): """ Gets the value of the property of the given key. Args: key (str): Key of the property to look-up. """
match = self._get_match(key=key) if not match: return None return self._get_value_from_match(key=key, match=match)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, key, value): """ Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value...
match = self._get_match(key=key) if not match: self._log.info('"%s" does not exist, so it will be added.', key) if isinstance(value, str): self._log.info('"%s" will be added as a PHP string value.', key) value_str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_buildout_config(buildout_filename): """Parse buildout config with zc.buildout ConfigParser """
print("[localhost] get_buildout_config: {0:s}".format(buildout_filename)) buildout = Buildout(buildout_filename, [('buildout', 'verbosity', '-100')]) while True: try: len(buildout.items()) break except OSError: pass return buildout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_buildout_parts(buildout, query=None): """Return buildout parts matching the given query """
parts = names = (buildout['buildout'].get('parts') or '').split('\n') for name in names: part = buildout.get(name) or {} for key, value in (query or {}).items(): if value not in (part.get(key) or ''): parts.remove(name) break return parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_buildout_eggs(buildout, query=None): """Return buildout eggs matching the parts for the given query """
eggs = set() for name in get_buildout_parts(buildout, query=query): if name == 'buildout': continue # skip eggs from the buildout script itself path = os.path.join(buildout['buildout'].get('bin-directory'), name) if os.path.isfile(path): eggs.update(parse_eggs_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_eggs_list(path): """Parse eggs list from the script at the given path """
with open(path, 'r') as script: data = script.readlines() start = 0 end = 0 for counter, line in enumerate(data): if not start: if 'sys.path[0:0]' in line: start = counter + 1 if counter >= start and not end: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tidy_eggs_list(eggs_list): """Tidy the given eggs list """
tmp = [] for line in eggs_list: line = line.lstrip().rstrip() line = line.replace('\'', '') line = line.replace(',', '') if line.endswith('site-packages'): continue tmp.append(line) return tmp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, filename=None): """Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters filename...
tmp_file, f_suffix = download_file(self.url) if not filename is None: shutil.move(tmp_file, filename) return filename else: return tmp_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_file(self, filename, resource_id=None): """Upload an attachment for the model run. Paramerers filename : string Path to uploaded file resource_id : st...
# Use file base name as resource identifier if none given if resource_id is None: resource_id = os.path.basename(filename) # Need to append resource identifier to base attachment Url upload_url = self.links[REF_MODEL_RUN_ATTACHMENTS] + '/' + resource_id # Upload mode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(url, model_id, name, arguments, properties=None): """Create a new model run using the given SCO-API create model run Url. Parameters url : string Url ...
# Create list of model run arguments. Catch TypeErrors if arguments is # not a list. obj_args = [] try: for arg in arguments: obj_args.append({'name' : arg, 'value' : arguments[arg]}) except TypeError as ex: raise ValueError('invalid argum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_state(url, state_obj): """Update the state of a given model run. The state object is a Json representation of the state as created by the SCO-Server. ...
# POST update run state request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(state_obj)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Throw exce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_state_active(self): """Update the state of the model run to active. Raises an exception if update fails or resource is unknown. Returns ------- ModelR...
# Update state to active self.update_state(self.links[REF_UPDATE_STATE_ACTIVE], {'type' : RUN_ACTIVE}) # Returned refreshed verion of the handle return self.refresh()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_state_error(self, errors): """Update the state of the model run to 'FAILED'. Expects a list of error messages. Raises an exception if update fails or ...
# Update state to active self.update_state( self.links[REF_UPDATE_STATE_ERROR], {'type' : RUN_FAILED, 'errors' : errors} ) # Returned refreshed verion of the handle return self.refresh()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_state_success(self, model_output): """Update the state of the model run to 'SUCCESS'. Expects a model output result file. Will upload the file before ...
# Upload model output response = requests.post( self.links[REF_UPDATE_STATE_SUCCESS], files={'file': open(model_output, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """
is_ready = False try: s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret) if s3: if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized(): is_ready = True except boto.exception.BotoServerError as e: print e return is_ready
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def NoSuchEntityOk(f): """ Decorator to remove NoSuchEntity exceptions, and raises all others. """
def ExceptionFilter(*args): try: return f(*args) except boto.exception.BotoServerError as e: if e.error_code == 'NoSuchEntity': pass else: raise except: raise return False return ExceptionFilter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __IsInitialized(self): """ Returns true if IAM user initialization has completed. """
is_initialized = False iam_id = self.GetAccessKeyId() if iam_id: if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized(): is_initialized = True return is_initialized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __GetInstances(self, group_name = None, state_filter=None): """ Get all the instances in a group, filtered by state. @param group_name: the name of the group...
all_instances = self.ec2.get_all_instances() instances = [] for res in all_instances: for group in res.groups: if group_name and group.name != group_name: continue for instance in res.instances: if state_filter == None or instance.state == state_filter: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load(self, mkey, mdesc, mdict=None, merge=False): ''' Loads a dictionary into current meta :param mkey: Type of data to load. Is be used to reference the data from the 'header' within meta :param mdesc: Either filename of json-file to load or furt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, user_id=None, user_name=None): """ Get a user object from the API. If no ``user_id`` or ``user_name`` is specified, it will return the User ob...
if user_id: endpoint = '/api/user_id/{0}'.format(user_id) elif user_name: endpoint = '/api/user_name/{0}'.format(user_name) else: # Return currently authorized user endpoint = '/api/user' data = self._make_request(verb="GET", endpoint=en...