output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def get_dataset_meta(label): """Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be do...
Implement a function in Python 3 to give you metadata for dataset chosen via label
You are a Python code analyst, evaluating scripts for potential improvements.
def _expand_dataset_packages(dataset_label_dict): """Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :ret...
Can you create a Python 3 function that returns list of possible packages contained in dataset in multi dataset eg. lisa.
You are a Python code generator, capable of creating scripts from specifications.
def download(dataset_label=None, destination_dir=None, dry_run=False): """Download sample data by data label. Warning: function with side effect! Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files. :param dataset_label: label of data. If it is set to None, all data are download...
Can you create a Python 3 function that downloads sample data by label.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the 3D data from specified dataset with specified id.
Make a summary of the following Python 3 code def get_old(dataset_label, data_id, destination_dir=None): # TODO implement if destination_dir is None: destination_dir = op.join(dataset_path(get_root=True), "medical", "orig") destination_dir = op.expanduser(destination_dir) data_url, url, expecte...
As a Python code translator, you convert algorithms and pseudocode into Python.
def checksum(path, hashfunc="md5"): """Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return:...
How would you implement a function in Python 3 that returns checksum of files given by path.
As a python code expert, you are capable of creating scripts from specifications.
Generate donut like shape with stick inside
Given the following Python 3 function, write the documentation def generate_donut(): segmentation = np.zeros([20, 30, 40]) # generate test data segmentation[6:10, 7:24, 10:37] = 1 segmentation[6:10, 7, 10] = 0 segmentation[6:10, 23, 10] = 0 segmentation[6:10, 7, 36] = 0 segmentation[6:10, 23...
You are a Python code generator, capable of creating scripts from specifications.
Generate data with two sphere objects.
Can you generate a brief explanation for the following Python 3 code def generate_round_data( sz=32, offset=0, radius=7, seedsz=3, add_object_without_seeds=False ): """ Generate data with two sphere objects. :param sz: output data shape is [sz, sz+1, sz+2] :param offset: :param radius: :para...
As a Python code composer, you craft elegant and concise scripts.
def generate_synthetic_liver(return_dataplus=False): """ Create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta: """ # data slab = {"none": 0, "liver": 1, "porta": 2} voxelsize_mm = np.array([1.0, 1.0, 1.2...
Implement a function in Python 3 to create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta:
You are a Python code generator, capable of creating scripts from specifications.
def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): """ Create 2D binar face :param shape: :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: """ # data3d = np.zeros([1,7,7], dtype=np.int16) if shape is None: shape = [3...
Implement a Python 3 function for creating 2D binar face with 2D smiles.
You are a Python code architect, reviewing and designing scalable and efficient code
Generate 2D or 3D binar data with smile face.
Make a summary of the following Python 3 code def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): # TODO add axis (ax=0) if shape is None: shape = [32, 32] nd = len(shape) if nd == 2: sh2 = shape else: sh2 = shape[1:] fc2 = _get_face2( ...
As a python code expert, you are capable of creating scripts from specifications.
def remove(local_file_name): """Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove """ try: os.remove(local_file_name) except Exception as e: print( "Cannot remove file '" + local_file_name + "'. Please ...
Implement a Python 3 function for functioning attempts to remove file from the system
As a python code expert, you are capable of creating scripts from specifications.
def downzip(url, destination="./sample_data/"): """Download, unzip and delete. Warning: function with strong side effects! Returns downloaded data. :param str url: url from which data should be donloaded :param destination: destination to which data should be downloaded """ # url = "http://14...
Can you create a Python 3 function that downloads unzip and delete.
You are a Python code generator, capable of creating scripts from specifications.
def unzip_one(local_file_name): """Unzips one file and deletes it. Warning: function with side effects! :param str local_file_name: file name of zip file :return: list of archive members by name. """ local_file_name = op.expanduser(local_file_name) destination = op.dirname(local_file_name) ...
Can you create a Python 3 function that unzips one file and deletes it.
As a Python code composer, you craft elegant and concise scripts.
def unzip_recursive(zip_file_name): """Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name. """ logger.debug("unzipping " + zip_file_name) fnlist = unzip_one(zip_file_name) for f...
How would you code a function in Python 3 to unzip file with all recursive zip files inside and delete zip files after that.
You are a Python code architect, reviewing and designing scalable and efficient code
a wrapper around generation of an API to call the UploadCommand to upload an already existing asciinema file and return the url of the uploaded file.
How would you explain what the following Python 3 function does def upload_asciinema(filename): '''a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can...
You are a Python code architect, reviewing and designing scalable and efficient code
def make_tls_config(app_config): """Creates TLS configuration object.""" if not app_config['DOCKER_TLS']: return False cert_path = app_config['DOCKER_TLS_CERT_PATH'] if cert_path: client_cert = '{0}:{1}'.format( os.path.join(cert_path, 'cert.pem'), os.path.join(...
Write a Python 3 script for creating TLS configuration object.
You are a Python code analyst, evaluating scripts for potential improvements.
Parses the client cert pair from config item.
Can you generate a brief explanation for the following Python 3 code def parse_client_cert_pair(config_value): if not config_value: return client_cert = config_value.split(':') if len(client_cert) != 2: tips = ('client_cert should be formatted like ' '"/path/to/cert.pem:/path...
As a Python code translator, you convert algorithms and pseudocode into Python.
def init_app(self, app): """Initializes an application for using :class:`docker.Client`. :param app: an instance of :class:`~flask.Flask`. """ app.extensions = getattr(app, 'extensions', {}) app.extensions['docker.client'] = None app.config.setdefault('DOCKER_URL', None...
Implement a function in Python 3 to initialize an application for using the Docker client.
As a Python code translator, you convert algorithms and pseudocode into Python.
def client(self): """The original :class:`docker.Client` object. All docker operation calling will be forwarded here. :: docker.create_container('ubuntu') docker.client.create_container('ubuntu') # equivalent """ if not self.app.config['DOCKER_URL']: ...
Create a Python 3 function for returning the original docker. Client object.
As a python code expert, you are capable of creating scripts from specifications.
async def process_feed(self, url, send_mentions=True): """ process a feed """ self._feed_domains.add(utils.get_domain(url)) if url in self._processed_feeds: LOGGER.debug("Skipping already processed feed %s", url) return self._processed_feeds.add(url) LO...
Can you implement a function in Python 3 that processes a feed and schedule the entries.
You are a Python code architect, reviewing and designing scalable and efficient code
async def send_webmention(self, entry, url): """ send a webmention from an entry to a URL """ if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) ...
Write a Python 3 script to send a webmention from an entry to a URL.
You are a Python code architect, reviewing and designing scalable and efficient code
def makemessages(application, locale): """ Updates the locale message files """ from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
Implement a function in Python 3 to update the locale message files for the given application.
As a python code expert, you are capable of creating scripts from specifications.
Runs the django CMS check command
Given the following Python 3 function, write the documentation def cms_check(migrate_cmd=False): from django.core.management import call_command try: import cms # NOQA # nopyflakes _create_db(migrate_cmd) call_command('cms', 'check') except ImportError: print('cms_check avai...
You are a Python code architect, reviewing and designing scalable and efficient code
def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None): """ Generate migrations """ from django.core.management import call_command apps = [application] if extra_applications: if isinstance(extra_applications, text_type): apps += [e...
Write a Python 3 script for generating migrations for the specified application.
As a Python code analyst, you investigate and solve complex coding mysteries
def generate_authors(): """ Updates the authors list """ print('Generating AUTHORS') # Get our list of authors print('Collecting author names') r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'], stdout=subprocess.PIPE) seen_authors = [] au...
Create a Python 3 function for generating the list of authors for the current user
As a Python code translator, you convert algorithms and pseudocode into Python.
def setup_parse(self, inputstring, document): """Initial parse setup. Call at start of `self.parse()`.""" self.inputstring = inputstring self.document = document
Write a Python 3 function for initialing parse setup. Call at start of `self.parse()`.
As a python code expert, you are capable of creating scripts from specifications.
Check that the version of the package in setuptools matches the expected version.
How would you explain what the following Python 3 function does def check_version(expected_version): with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file: version = version_file.read().strip() if version != expected_version: raise EnvironmentError("Version mismatch during relea...
As a python code expert, you are capable of creating scripts from specifications.
def upload(dist_dir): """Upload a given component to pypi The pypi username and password must either be specified in a ~/.pypirc file or in environment variables PYPI_USER and PYPI_PASS """ if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ: pypi_user = os.environ['PYPI_USER'] ...
Can you implement a function in Python 3 that uploads a given component to pypi
You are a Python code generator, capable of creating scripts from specifications.
Simple command - line toolkit.
Explain what the following Python 3 code does def simple_cmd(): parser = argparse.ArgumentParser( prog="Simple command-line function toolkit.", description="""Input function name and args and kwargs. python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""", ) parser.add_argument("-f", "--func_n...
As a Python code translator, you convert algorithms and pseudocode into Python.
Show the proc - mem - cost with psutil use this only for lazinesssss.
Can you generate a brief explanation for the following Python 3 code def print_mem(unit="MB"): try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info("memory usa...
As a python code expert, you are capable of creating scripts from specifications.
def curlparse(string, encoding="utf-8"): """Translate curl-string into dict of request. :param string: standard curl-string, like `r'''curl ...'''`. :param encoding: encoding for post-data encoding. Basic Usage:: >>> from torequests.utils import curlparse >>> curl_string = '''curl ...
Implement a function in Python 3 to translate curl - string into dict of request.
As a Python code translator, you convert algorithms and pseudocode into Python.
Slice a sequence into n pieces return a generation of n pieces
Can you tell what is the following Python 3 function doing def slice_into_pieces(seq, n): length = len(seq) if length % n == 0: size = length // n else: size = length // n + 1 for it in slice_by_size(seq, size): yield it
As a Python code composer, you craft elegant and concise scripts.
def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yiel...
Write a Python 3 function that can slice a sequence into chunks with size.
As a Python code composer, you craft elegant and concise scripts.
def ttime(timestamp=None, tzone=None, fail="", fmt="%Y-%m-%d %H:%M:%S"): """Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S. :param timestamp: the timestamp float, or `time.time()` by default. :param tzone: time compensation, int(-time.timezone / 3600) by default, (can be set wit...
Create a Python 3 function to translate timestamp into human - readable format.
You are a Python code generator, capable of creating scripts from specifications.
Translate a string like 2018 - 03 - 15 01 - 27 - 56 into a timestamp.
Can you generate the documentation for the following Python 3 function def ptime(timestr=None, tzone=None, fail=0, fmt="%Y-%m-%d %H:%M:%S"): tzone = Config.TIMEZONE if tzone is None else tzone fix_tz = -(tzone * 3600 + time.timezone) #: str(timestr) for datetime.datetime object timestr = str(timestr or ...
As a Python code analyst, you investigate and solve complex coding mysteries
def split_seconds(seconds): """Split seconds into [day, hour, minute, second, ms] `divisor: 1, 24, 60, 60, 1000` `units: day, hour, minute, second, ms` >>> split_seconds(6666666) [77, 3, 51, 6, 0] """ ms = seconds * 1000 divisors = (1, 24, 60, 60, 1000) quotient, result = ...
Implement a function in Python 3 to split seconds into a list of time units divisors and units.
You are a Python code architect, reviewing and designing scalable and efficient code
def timeago(seconds=0, accuracy=4, format=0, lang="en"): """Translate seconds into human-readable. :param seconds: seconds (float/int). :param accuracy: 4 by default (units[:accuracy]), determine the length of elements. :param format: index of [led, literal, dict]. :param lang: en o...
Can you create a Python 3 function that translates seconds into human - readable form.
You are a Python code architect, reviewing and designing scalable and efficient code
def unparse_qs(qs, sort=False, reverse=False): """Reverse conversion for parse_qs""" result = [] items = qs.items() if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) for value in values: result....
Write a Python 3 script to reverse conversion for parse_qs
As a Python code translator, you convert algorithms and pseudocode into Python.
Reverse conversion for parse_qsl
Can you generate a brief explanation for the following Python 3 code def unparse_qsl(qsl, sort=False, reverse=False): result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.append(quer...
You are a Python code generator, capable of creating scripts from specifications.
Kill self after seconds
Given the following Python 3 function, write the documentation def kill_after(seconds, timeout=2): pid = os.getpid() kill = os.kill run_after_async(seconds, kill, pid, signal.SIGTERM) run_after_async(seconds + timeout, kill, pid, 9)
As a Python code analyst, you investigate and solve complex coding mysteries
Try import module_name except ImportError and return default.
Can you tell what is the following Python 3 function doing def try_import(module_name, names=None, default=ImportErrorModule, warn=True): try: module = importlib.import_module(module_name) except ImportError: if warn: if warn is True: Config.utils_logger.warning( ...
As a Python code composer, you craft elegant and concise scripts.
Used for requests. request with ** ensure_request ( request )
How would you explain what the following Python 3 function does def ensure_request(request): if isinstance(request, dict): result = request elif isinstance(request, (unicode, str)): request = request.strip() if request.startswith("http"): result = {"method": "get", "url": req...
As a Python code translator, you convert algorithms and pseudocode into Python.
def ensure_dict_key_title(dict_obj): """Set the dict key as key.title(); keys should be str. Always be used to headers. >>> from torequests.utils import ensure_dict_key_title >>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2}) {'Hello-World': 1, 'Helloworld': 2} """ if ...
Implement a function in Python 3 to set the dict key as key. title ; keys should be str. Always be used to headers.
You are a Python code architect, reviewing and designing scalable and efficient code
def guess_interval(nums, accuracy=0): """Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted...
Write a Python 3 function for giving a seq of number return the median of the number.
You are a Python code analyst, evaluating scripts for potential improvements.
def bg(func): """Run a function in background, will not block main thread's exit.(thread.daemon=True) :: from torequests.utils import bg, print_info import time def test1(n): time.sleep(n) print_info(n, 'done') @bg def test2(n): time...
How would you implement a function in Python 3 that runs a function in background will not block main thread s exit.
You are a Python code analyst, evaluating scripts for potential improvements.
Run a countdown function to wait something.
Can you generate a brief explanation for the following Python 3 code def countdown( seconds=None, block=True, interval=1, daemon=True, tick_callback=None, finish_callback=None, ): """Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by...
You are a Python code analyst, evaluating scripts for potential improvements.
Print a sequence of strings to stdout.
Make a summary of the following Python 3 code def flush_print(*args, **kwargs): # PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''): sep, end, flush = ( kwargs.pop("sep", " "), kwargs.pop("end", "\n"), kwargs.pop("flush", 1), ) string = sep.join((unicode(i) for i...
You are a Python code generator, capable of creating scripts from specifications.
def curlrequests(curl_string, **kwargs): """Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basi...
Implement a Python 3 function for using tPool to request for curl string.
As a Python code composer, you craft elegant and concise scripts.
def register(self, patterns, obj=None, instances=None, **reg_kwargs): """Register one object which can be matched/searched by regex. :param patterns: a list/tuple/set of regex-pattern. :param obj: return it while search/match success. :param instances: instance list will search/match th...
Implement a Python 3 function for registering one object which can be matched by regex.
As a Python code composer, you craft elegant and concise scripts.
def find(self, string, default=None): """Return match or search result. :rtype: list""" return self.match(string) or self.search(string) or default
Write a Python 3 script for returning match or search result.
You are a Python code generator, capable of creating scripts from specifications.
Use re. search to find the result of search
Make a summary of the following Python 3 code def search(self, string, default=None): default = default if default else [] result = [item[1] for item in self.container if item[0].search(string)] if self.ensure_mapping: assert len(result) < 2, "%s matches more than one pattern: %s" % ...
You are a Python code generator, capable of creating scripts from specifications.
def fuzzy(self, key, limit=5): """Give suggestion from all instances.""" instances = [i[2] for i in self.container if i[2]] if not instances: return instances = sum(instances, []) from fuzzywuzzy import process maybe = process.extract(key, instances, limit=li...
Write a Python 3 script for giving suggestion from all instances.
You are a Python code generator, capable of creating scripts from specifications.
returns a string with all the available items
Given the following Python 3 function, write the documentation def show_all(self, as_string=True): result = [] for item in self.container: pattern = str(item[0])[10:] if PY3 else item[0].pattern instances = item[2] or [] value = ( '%s "%s"' % (item[1]....
You are a Python code analyst, evaluating scripts for potential improvements.
def x(self): """Call self.log_func(self) and return expect_string.""" self._log_after_del = False passed_string = self.string if self.log_func: self.log_func(self) else: print_info( "Timer [%(passed)s]: %(name)s, start at %(start)s." ...
Write a Python 3 script for calling self. log_func and return expect_string.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the time cost string as expect.
How would you explain what the following Python 3 function does def tick(self): string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
As a Python code composer, you craft elegant and concise scripts.
Default clean the \\ n in text.
Make a summary of the following Python 3 code def default_callback(self, text): text = text.replace("\r\n", "\n") text = "%s\n" % text flush_print(text, sep="", end="") return text
As a python code expert, you are capable of creating scripts from specifications.
Block method to watch the clipboard changing.
Can you generate a brief explanation for the following Python 3 code def watch(self, limit=None, timeout=None): start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Non - block method to watch the clipboard changing.
Can you generate the documentation for the following Python 3 function def watch_async(self, limit=None, timeout=None): return self.watch(limit=limit, timeout=timeout)
As a Python code composer, you craft elegant and concise scripts.
def find_one(cls, pattern, string, flags=0): """JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <toreq...
How would you code a function in Python 3 to find one entry in the registry.
As a Python code composer, you craft elegant and concise scripts.
create a Github issue given a title body repo and token
Can you tell what is the following Python 3 function doing def create_issue(title, body, repo, token): '''create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: t...
As a Python code translator, you convert algorithms and pseudocode into Python.
Given a URL get the webmention endpoint
Explain what the following Python 3 code does async def get_target(config, url): previous = config.cache.get( 'target', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) ...
You are a Python code generator, capable of creating scripts from specifications.
async def send(self, config, entry): """ Send a webmention to this target from the specified entry """ if self.endpoint: LOGGER.debug("%s -> %s", entry.url, self.url) try: await self.endpoint.send(config, entry.url, self.url) except Exception as err: ...
Can you create a Python 3 function that sends a webmention to this target from the specified entry.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_helper(name=None, quiet=True, **kwargs): ''' get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak) ''' # Second priority, from environment from helpme.defaults import HELPME_CLIENT ...
How would you implement a function in Python 3 that returns a new Helper object based on the given name and quiet.
You are a Python code architect, reviewing and designing scalable and efficient code
def mock_bable(monkeypatch): """ Mock the BaBLEInterface class with some controllers inside. """ mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, '11:22:33:44:55:66', '#0'), Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}), ...
Write a Python 3 script to mock the BaBLEInterface class with some controllers inside.
As a Python code composer, you craft elegant and concise scripts.
def handle(self): """ Executes the actual Stratum program. """ self.output = PyStratumStyle(self.input, self.output) command = self.get_application().find('constants') ret = command.execute(self.input, self.output) if ret: return ret command ...
Implement a function in Python 3 to execute the actual Stratum program.
As a python code expert, you are capable of creating scripts from specifications.
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfil...
Implement a Python 3 function for loading a python module from its absolute filesystem path
You are a Python code generator, capable of creating scripts from specifications.
Hackish way to reset the django instance settings and AppConfig
How would you explain what the following Python 3 function does def _reset_django(settings): if settings._wrapped != empty: clear_url_caches() from django.apps import apps apps.clear_cache() settings._wrapped = empty clear_url_caches()
As a Python code translator, you convert algorithms and pseudocode into Python.
def ensure_unicoded_and_unique(args_list, application): """ Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order. """ unicoded_args = [] for argument in args_list: argument = (six.u(argument) ...
Write a Python 3 function for ensuring that the arguments in args_list are unicode and ensure that they are unique.
You are a Python code generator, capable of creating scripts from specifications.
This function removes the contents of the specified folder.
Can you generate a brief explanation for the following Python 3 code def rmtree(path): if islink(path): unlink(path) elif os.path.isdir(path): for sub in os.listdir(path): sub = os.path.join(path, sub) if os.path.isfile(sub): if not os.access(sub, os.W_OK)...
You are a Python code generator, capable of creating scripts from specifications.
def islink(path): """os.path.islink() but return True for junction points on Windows. """ if platform.system() == "Windows": if sys.version_info[:2] < (3, 5): try: # pylint: disable=undefined-variable attrs = ctypes.windll.kernel32.GetFileAttributesW(unico...
Implement a Python 3 function for returning True if the path is a link.
You are a Python code generator, capable of creating scripts from specifications.
Writes a file in two phases to the filesystem.
Make a summary of the following Python 3 code def write_two_phases(filename, data, io): write_flag = True if os.path.exists(filename): with open(filename, 'r') as file: old_data = file.read() if data == old_data: write_flag = False ...
You are a Python code analyst, evaluating scripts for potential improvements.
async def get_entry(config, url): """ Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated) """ previous = config.cache.get( 'entry', url, schema_version=SCHEMA_VERSION) if conf...
Create a Python 3 function to get an entry from the cache and return it
As a Python code composer, you craft elegant and concise scripts.
Check a link s relations against the whitelist or blacklist.
Can you tell what is the following Python 3 function doing def _check_rel(attrs, rel_whitelist, rel_blacklist): rels = attrs.get('rel', [None]) if rel_blacklist: # Never return True for a link whose rel appears in the blacklist for rel in rels: if rel in rel_bla...
As a python code expert, you are capable of creating scripts from specifications.
def _domain_differs(self, href): """ Check that a link is not on the same domain as the source URL """ target = utils.get_domain(href) if not target: return False origin = utils.get_domain(self.url) return target != origin
Can you write a function in Python 3 where it checks that a link is not on the same domain as the source URL.
As a Python code composer, you craft elegant and concise scripts.
def get_targets(self, config): """ Given an Entry object, return all of the outgoing links. """ return {urllib.parse.urljoin(self.url, attrs['href']) for attrs in self._targets if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist) and self...
Write a Python 3 function for giving an Entry object return all of the outgoing links.
You are a Python code generator, capable of creating scripts from specifications.
Run the command line.
Can you tell what is the following Python 3 function doing def run_command(self, config_file, sources): config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() loader = self.create_routine_loader(rdbms) status = loader.main(...
As a Python code composer, you craft elegant and concise scripts.
Returns a Routine Loader object for loading stored routines into a RDBMS instance.
Explain what the following Python 3 code does def create_routine_loader(self, rdbms): # Note: We load modules and classes dynamically such that on the end user's system only the required modules # and other dependencies for the targeted RDBMS must be installed (and required modules and other ...
As a Python code composer, you craft elegant and concise scripts.
Create a new VM.
Given the following Python 3 function, write the documentation async def create_vm(self, *, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnet=None): """ Dummy create_vm func. """ ...
As a Python code composer, you craft elegant and concise scripts.
List all VMs in the specified preset.
Given the following Python 3 function, write the documentation async def list_vms(self, preset_name): return list(vm for vm in self._vms.values() if vm.name == preset_name)
You are a Python code generator, capable of creating scripts from specifications.
Try if exist path and append number to its end.
Can you generate the documentation for the following Python 3 function def suggest_filename(file_path, exists=None): import os.path import re if not isinstance(exists, bool): exists = os.path.exists(file_path) if exists: file_path, file_extension = os.path.splitext(file_path) # ...
You are a Python code analyst, evaluating scripts for potential improvements.
def obj_from_file(filename='annotation.yaml', filetype='auto'): ''' Read object from file ''' if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with op...
Write a Python 3 script to read object from file.
You are a Python code analyst, evaluating scripts for potential improvements.
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True): '''Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ''' ...
Can you create a Python 3 function that writes an object to a file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Function resize input data to specific shape.
Can you generate the documentation for the following Python 3 function def resize_to_shape(data, shape, zoom=None, mode='nearest', order=0): # @TODO remove old code in except part try: # rint 'pred vyjimkou' # aise Exception ('test without skimage') # rint 'za vyjimkou' import s...
You are a Python code architect, reviewing and designing scalable and efficient code
def resize_to_mm(data3d, voxelsize_mm, new_voxelsize_mm, mode='nearest'): """ Function can resize data3d or segmentation to specifed voxelsize_mm :new_voxelsize_mm: requested voxelsize. List of 3 numbers, also can be a string 'orig', 'orgi*2' and 'orgi*4'. :voxelsize_mm: size of voxel :mode...
Create a Python 3 function for functioning can resize data3d or segmentation to specified voxelsize mm
You are a Python code architect, reviewing and designing scalable and efficient code
Check whether the given range of values can be stored into defined data type.
Explain what the following Python 3 code does def suits_with_dtype(mn, mx, dtype): type_info = np.iinfo(dtype) if mx <= type_info.max and mn >= type_info.min: return True else: return False
You are a Python code analyst, evaluating scripts for potential improvements.
Use more economic integer - like dtype if it is possible.
Can you generate a brief explanation for the following Python 3 code def use_economic_dtype(data3d, slope=1, inter=0, dtype=None): if dtype is None: dtype = data3d.dtype if issubclass(dtype.type, np.integer): mn = data3d.min() * slope + inter mx = data3d.max() * slope + inte...
You are a Python code analyst, evaluating scripts for potential improvements.
This function returns the SimpleItk Image object from the data array.
Given the following Python 3 function, write the documentation def get_sitk_image_from_ndarray(data3d): import SimpleITK as sitk rescale_intercept = None if sitk.Version.MajorVersion() > 0: if data3d.dtype == np.int8: rescale_intercept = -2**7 data3d = (data3d - rescale_inte...
As a python code expert, you are capable of creating scripts from specifications.
Get slope and intercept from pydicom file object.
Given the following Python 3 function, write the documentation def get_slope_and_intercept_from_pdcm(dcmdata): if hasattr(dcmdata, "RescaleSlope") and hasattr(dcmdata, "RescaleIntercept"): rescale_slope = dcmdata.RescaleSlope rescale_intercept = dcmdata.RescaleIntercept slope, inter = get_s...
You are a Python code architect, reviewing and designing scalable and efficient code
def split_evenly(n, chunks): """Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... Chunk...
Create a Python 3 function to split an integer into evenly distributed list of size n
You are a Python code architect, reviewing and designing scalable and efficient code
ensure that variable envar is set to some value
Can you generate the documentation for the following Python 3 function def check_env(self, envar, value): '''ensure that variable envar is set to some value, otherwise exit on error. Parameters ========== envar: the environment variable name value...
You are a Python code generator, capable of creating scripts from specifications.
def _generate_keys(self): '''the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user ''' from helpme.defaults import HELPME_CLIENT_SECRETS keypair_dir = os.path.join(os.path.dirname(HELPME_CLIENT_SECRETS), ...
How would you code a function in Python 3 to generate a keypair on behalf of the user
You are a Python code architect, reviewing and designing scalable and efficient code
Submit the question to the board.
Make a summary of the following Python 3 code def _submit(self): '''submit the question to the board. When we get here we should have (under self.data) {'record_environment': [('DISPLAY', ':0')], 'user_prompt_board': 'http://127.0.0.1', '...
As a Python code composer, you craft elegant and concise scripts.
def get(self, cls, id_field, id_val): """ Retrieve an object which `id_field` matches `id_val`. If it exists in the cache, it will be fetched from Redis. If not, it will be fetched via the `fetch` method and cached in Redis (unless the cache flag got invalidated in the meantime)....
Can you write a function in Python 3 where it retrieves an object which id_field matches id_val.
You are a Python code generator, capable of creating scripts from specifications.
def verify(self, cls, id_field, id_val, obj_from_cache): """ Verify that the object we retrieved from cache matches the requested `id_field`/`id_val`. """ return getattr(obj_from_cache, id_field) == id_val
How would you implement a function in Python 3 that verifies that the object we retrieved from cache matches the requested ID.
You are a Python code architect, reviewing and designing scalable and efficient code
def invalidate(self, cls, id_field, id_val): """ Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag. """ cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_ke...
Write a Python 3 function for invalidating the cache for a given Mongo object.
As a Python code composer, you craft elegant and concise scripts.
def update(self, aggressive=False): """ Update the state of the NukiLock :param aggressive: Whether to aggressively poll the Bridge. If set to True, this will actively query the Lock, thus using more battery. :type aggressive: bool """ if aggressive: d...
Create a Python 3 function to update the state of the NukiLock object.
As a Python code composer, you craft elegant and concise scripts.
def get_dict_properties(item, fields, mixed_case_fields=[], formatters={}): """Return a tuple containing the item properties. :param item: a single dict resource :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to preserve case :param format...
Can you implement a function in Python 3 that returns a tuple containing the item properties.
You are a Python code generator, capable of creating scripts from specifications.
A decorator that logs a method and its arguments when entered.
Here you have a function in Python 3, explain what it does def log_method(log, level=logging.DEBUG): def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_args = [] ...
You are a Python code generator, capable of creating scripts from specifications.
Checks that the required directories exist.
Explain what the following Python 3 code does def check_local() -> None: to_check = ['./replay', './replay/toDo', './replay/archive'] for i in to_check: if not os.path.exists(i): os.makedirs(i)
You are a Python code generator, capable of creating scripts from specifications.
Create file to replay.
Explain what the following Python 3 code does def create_file(project: str, environment: str, feature: str, state: str) -> None: check_local() save_path = './replay/toDo/' filename = '{0}.txt'.format(str(uuid.uuid1())) complete_name = os.path.join(save_path, filename) with open(complete_name, 'w') ...
You are a Python code analyst, evaluating scripts for potential improvements.