output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Moves the text cursor to the specified line and column.
How would you explain what the following Python 3 function does def goto_line(self, line, column=0, move=True): text_cursor = self.move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if move:...
As a Python code analyst, you investigate and solve complex coding mysteries
def select_lines(self, start=0, end=-1, apply_selection=True): """ Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being ...
Create a Python 3 function for selecting all lines between start and end line numbers.
As a python code expert, you are capable of creating scripts from specifications.
Returns the indentation level of the specified line.
Here you have a function in Python 3, explain what it does def line_indent(self, line_nbr=None): if line_nbr is None: line_nbr = self.current_line_nbr() elif isinstance(line_nbr, QtGui.QTextBlock): line_nbr = line_nbr.blockNumber() line = self.line_text(line_nbr) ...
As a python code expert, you are capable of creating scripts from specifications.
def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.tex...
Can you create a Python 3 function that gets the word that is on the right of the text cursor.
As a Python code translator, you convert algorithms and pseudocode into Python.
def search_text(self, text_cursor, search_txt, search_flags): """ Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occ...
Can you implement a function in Python 3 that searches a text in a text document.
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks if a block or cursor is a string or a comment.
Can you generate the documentation for the following Python 3 function def is_comment_or_string(self, cursor_or_block, formats=None): if formats is None: formats = ["comment", "string", "docstring"] layout = None pos = 0 if isinstance(cursor_or_block, QtGui.QTextBlock): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Performs matched selection on the current text.
Explain what the following Python 3 code does def match_select(self, ignored_symbols=None): def filter_matching(ignored_symbols, matching): """ Removes any ignored symbol from the match dict. """ if ignored_symbols is not None: for symbol in matchi...
As a Python code analyst, you investigate and solve complex coding mysteries
Entrypoint for the console script gcp - devrel - py - tools.
Explain what the following Python 3 code does def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() appengine.register_commands(subparsers) requirements.register_commands(subparsers) pylint.register_commands(subparsers) args = parser.parse_args() args.func(arg...
As a Python code composer, you craft elegant and concise scripts.
async def run(websession): """Run.""" try: client = Client('17015', websession) print('Client instantiated for ZIP "{0}"'.format(client.zip_code)) print() print('CURRENT ALLERGENS') print(await client.allergens.current()) print() print('EXTENDED ALLERGEN...
Write a Python 3 script for running the main loop.
As a python code expert, you are capable of creating scripts from specifications.
Install Postgres on remote
Can you tell what is the following Python 3 function doing def install_postgres(user=None, dbname=None, password=None): execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a list of fields into a dictionary that can be used to build a tree structure.
Explain what the following Python 3 code does def field_to_dict(fields): field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], ...
You are a Python code analyst, evaluating scripts for potential improvements.
def alias_field(model, field): """ Return the prefix name of a field """ for part in field.split(LOOKUP_SEP)[:-1]: model = associate_model(model,part) return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
Implement a function in Python 3 to return the prefix name of a field
As a Python code composer, you craft elegant and concise scripts.
def associate_model(model, field): """ Return the model associate to the ForeignKey or ManyToMany relation """ class_field = model._meta.get_field(field) if hasattr(class_field, "field"): return class_field.field.related.related_model else: return class_field.related_model
Can you implement a function in Python 3 that returns the model associate to the ForeignKey or ManyToMany relation
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the formfied associate to the field of the model
How would you explain what the following Python 3 function does def get_formfield(model, field): class_field = model._meta.get_field(field) if hasattr(class_field, "field"): formfield = class_field.field.formfield() else: formfield = class_field.formfield() # Otherwise the formfiel...
As a Python code analyst, you investigate and solve complex coding mysteries
Build Q object to filter the queryset by the relevant fields
Can you tell what is the following Python 3 function doing def get_q_object(self): q_object = Q() for field in self.searchable_fields: value = self.request.GET.getlist(alias_field(self.model, field), None) mini_q = Q() for val in value: attr = "{0}{1}"...
As a python code expert, you are capable of creating scripts from specifications.
def get_search_form(self): """ Return list of form based on model """ magic_dico_form = self.get_dict_for_forms() forms = [] initial = list(self.request.GET.lists()) for key, value in magic_dico_form.items(): form = Form() model = value["m...
Implement a Python 3 function for returning list of form based on model
You are a Python code analyst, evaluating scripts for potential improvements.
Build a dictionnary where searchable_fields are the fields of the related objects.
Can you generate the documentation for the following Python 3 function def get_dict_for_forms(self): magic_dico = field_to_dict(self.searchable_fields) dico = {} def dict_from_fields_r(mini_dict, dico, model): """ Create the dico recursively from the magic_dico ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator that raises an exception when there s no data for a bad ZIP code.
Can you tell what is the following Python 3 function doing def raise_on_invalid_zip(func: Callable) -> Callable: async def decorator(*args: list, **kwargs: dict) -> dict: """Decorate.""" data = await func(*args, **kwargs) if not data['Location']['periods']: raise InvalidZipError(...
You are a Python code analyst, evaluating scripts for potential improvements.
Parses a GIT URL and returns a Parsed object.
Can you tell what is the following Python 3 function doing def parse(self): d = { 'pathname': None, 'protocols': self._get_protocols(), 'protocol': 'ssh', 'href': self._url, 'resource': None, 'user': None, 'port': None, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Make a request against AirVisual.
How would you explain what the following Python 3 function does async def _request( self, method: str, url: str, *, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against AirVisual.""" ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a handler for each of the available HTTP error responses.
Given the following Python 3 function, write the documentation def setup_errors(app, error_template="error.html"): def error_handler(error): if isinstance(error, HTTPException): description = error.get_description(request.environ) code = error.code name = error.name ...
As a Python code composer, you craft elegant and concise scripts.
Search for email addresses for a given domain.
Can you generate the documentation for the following Python 3 function def domain_search(self, domain=None, company=None, limit=None, offset=None, emails_type=None, raw=False): """ Return all the email addresses found for a given domain. :param domain: The domain on which ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def email_finder(self, domain=None, company=None, first_name=None, last_name=None, full_name=None, raw=False): """ Find the email address of a person given its name and company's domain. :param domain: The domain of the company where the person works. Must be define...
Create a Python 3 function for finding the email address of a person given its name and company's domain. :param domain: The domain of the company where the person works. Must be defined if company is not. :param company: The name of the company where the person works. Must be defined if domain is not. :param first_nam...
You are a Python code analyst, evaluating scripts for potential improvements.
def email_verifier(self, email, raw=False): """ Verify the deliverability of a given email adress.abs :param email: The email adress to check. :param raw: Gives back the entire response instead of just the 'data'. :return: Full payload of the query as a dict. """ ...
Can you implement a function in Python 3 that verifies the deliverability of a given email adress.
As a Python code analyst, you investigate and solve complex coding mysteries
def email_count(self, domain=None, company=None, raw=False): """ Give back the number of email adresses Hunter has for this domain/company. :param domain: The domain of the company where the person works. Must be defined if company is not. If both 'domain' and 'company' are given, ...
Create a Python 3 function to give back the number of email adresses Hunter has for this domain/company. :param domain: The domain of the company where the person works. Must be defined if company is not. If both 'domain' and 'company' are given, the 'domain' will be used. :param company: The name of the company where ...
As a python code expert, you are capable of creating scripts from specifications.
def account_information(self, raw=False): """ Gives the information about the account associated with the api_key. :param raw: Gives back the entire response instead of just the 'data'. :return: Full payload of the query as a dict. """ params = self.base_params ...
Write a Python 3 function for returning the account information for the current api_key.
As a Python code composer, you craft elegant and concise scripts.
def get_leads(self, offset=None, limit=None, lead_list_id=None, first_name=None, last_name=None, email=None, company=None, phone_number=None, twitter=None): """ Gives back all the leads saved in your account. :param offset: Number of leads to skip. :...
Implement a Python 3 function for returning a list of all leads in a lead list.
As a Python code composer, you craft elegant and concise scripts.
Get a specific lead from the account.
Given the following Python 3 function, write the documentation def get_lead(self, lead_id): params = self.base_params endpoint = self.base_endpoint.format('leads/' + str(lead_id)) return self._query_hunter(endpoint, params)
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new lead on your account.
How would you explain what the following Python 3 function does def create_lead(self, first_name, last_name, email=None, position=None, company=None, company_industry=None, company_size=None, confidence_score=None, website=None, country_code=None, postal_code=...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_leads_lists(self, offset=None, limit=None): """ Gives back all the leads lists saved on your account. :param offset: Number of lists to skip. :param limit: Maximum number of lists to return. :return: Leads lists found as a dict. """ params = self.base_p...
Write a Python 3 function that can return a dict of all the leads lists saved on your account.
You are a Python code analyst, evaluating scripts for potential improvements.
def create_leads_list(self, name, team_id=None): """ Create a leads list. :param name: Name of the list to create. Must be defined. :param team_id: The id of the list to share this list with. :return: The created leads list as a dict. """ params = self.base_par...
Implement a Python 3 function for creating a leads list.
You are a Python code architect, reviewing and designing scalable and efficient code
def update_leads_list(self, leads_list_id, name, team_id=None): """ Update a leads list. :param name: Name of the list to update. Must be defined. :param team_id: The id of the list to share this list with. :return: 204 Response. """ params = self.base_params ...
Can you create a Python 3 function that updates a leads list.
You are a Python code analyst, evaluating scripts for potential improvements.
Delete a leads list.
Make a summary of the following Python 3 code def delete_leads_list(self, leads_list_id): params = self.base_params endpoint = self.base_endpoint.format( 'leads_lists/' + str(leads_list_id) ) return self._query_hunter(endpoint, params, 'delete')
You are a Python code architect, reviewing and designing scalable and efficient code
converts a string to an integer
Can you generate the documentation for the following Python 3 function def to_int(s): try: return int(s.replace('_', '')) except ValueError: return int(ast.literal_eval(s))
As a Python code analyst, you investigate and solve complex coding mysteries
def dicts_from_lines(lines): """ returns a generator producing dicts from json lines 1 JSON object per line is supported: {"name": "n1"} {"name": "n2"} Or 1 JSON object: { "name": "n1" } Or a list of JSON objects: [ {"name": "n1"}, ...
Write a Python 3 function for returning a generator producing dicts from json lines
As a Python code analyst, you investigate and solve complex coding mysteries
def compose(*funcs): """ Compose any number of unary functions into a single unary function. >>> import textwrap >>> from six import text_type >>> stripped = text_type.strip(textwrap.dedent(compose.__doc__)) >>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped True Compose also allows th...
Write a Python 3 script to compose any number of unary functions into a single unary function.
You are a Python code generator, capable of creating scripts from specifications.
def method_caller(method_name, *args, **kwargs): """ Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring' """ def call_method(target): func = getattr(target, method_name) ret...
How would you code a function in Python 3 to return a function that will call a named method on the object with optional positional and keyword arguments.
As a Python code analyst, you investigate and solve complex coding mysteries
def once(func): """ Decorate func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6 To...
Write a Python 3 function for decorating func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6 To re...
You are a Python code generator, capable of creating scripts from specifications.
def method_cache(method, cache_wrapper=None): """ Wrap lru_cache to support storing the cache data in the object instances. Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently. >>> class MyClass: ... calls = 0...
How would you implement a function in Python 3 that wraps lru_cache to support storing the cache data in the object instances. Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently. >>> class MyClass: ... calls = 0 ... ... @...
You are a Python code generator, capable of creating scripts from specifications.
This is a hack to handle special methods that are not cached by the same name.
Make a summary of the following Python 3 code def _special_method_cache(method, cache_wrapper): name = method.__name__ special_names = '__getattr__', '__getitem__' if name not in special_names: return wrapper_name = '__cached' + name def proxy(self, *args, **kwargs): if wrapper_name not in vars(self): bou...
As a Python code translator, you convert algorithms and pseudocode into Python.
A function that is invoked on the results returned by the decorated function and then return the original result.
Can you generate the documentation for the following Python 3 function def result_invoke(action): def wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) action(result) return result return wrapper return wrap
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a function that when invoked will invoke func1 with any parameters passed in func2 with whatever parameters were passed.
Explain what the following Python 3 code does def first_invoke(func1, func2): def wrapper(*args, **kwargs): func1() return func2(*args, **kwargs) return wrapper
As a Python code translator, you convert algorithms and pseudocode into Python.
Attempts to call a function func with the specified exceptions and cleanups the exception if any.
Here you have a function in Python 3, explain what it does def retry_call(func, cleanup=lambda: None, retries=0, trap=()): attempts = count() if retries == float('inf') else range(retries) for attempt in attempts: try: return func() except trap: cleanup() return func()
As a python code expert, you are capable of creating scripts from specifications.
Decorator for retry_call. Accepts arguments to retry_call except func then returns a decorator for the decorated function.
Given the following Python 3 function, write the documentation def retry(*r_args, **r_kwargs): def decorate(func): @functools.wraps(func) def wrapper(*f_args, **f_kwargs): bound = functools.partial(func, *f_args, **f_kwargs) return retry_call(bound, *r_args, **r_kwargs) return wrapper return decorate
You are a Python code generator, capable of creating scripts from specifications.
def print_yielded(func): """ Convert a generator into a function that prints all yielded elements >>> @print_yielded ... def x(): ... yield 3; yield None >>> x() 3 None """ print_all = functools.partial(map, print) print_results = compose(more_itertools.recipes.consume, print_all, func) return functool...
Write a Python 3 script to convert a generator into a function that prints all yielded elements ...
As a Python code composer, you craft elegant and concise scripts.
A function that prints None if the first param is None.
Can you generate the documentation for the following Python 3 function def pass_none(func): @functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) return wrapper
As a Python code translator, you convert algorithms and pseudocode into Python.
def assign_params(func, namespace): """ Assign parameters from namespace where func solicits. >>> def func(x, y=3): ... print(x, y) >>> assigned = assign_params(func, dict(x=2, z=4)) >>> assigned() 2 3 The usual errors are raised if a function doesn't receive its required parameters: >>> assigned = ass...
Can you create a Python 3 function that assigns parameters from namespace where func solicits.
As a Python code composer, you craft elegant and concise scripts.
def save_method_args(method): """ Wrap a method such that when it is called, the args and kwargs are saved on the method. >>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2)...
Create a Python 3 function for wrapping a method such that when it is called, the args and kwargs are saved on the method. >>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwa...
As a python code expert, you are capable of creating scripts from specifications.
def _wait(self): "ensure at least 1/max_rate seconds from last call" elapsed = time.time() - self.last_called must_wait = 1 / self.max_rate - elapsed time.sleep(max(0, must_wait)) self.last_called = time.time()
Create a Python 3 function to ensure at least 1 / max_rate seconds from last call
You are a Python code architect, reviewing and designing scalable and efficient code
Creates and returns a row and column object.
Can you generate the documentation for the following Python 3 function def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix=''): row_col = nodes.entry() para_col = nodes.paragraph() if need_key in need_info and need_info[need_key] is not None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def insert_blob(filename, hosts=None, table=None): """Upload a file into a blob table """ conn = connect(hosts) container = conn.get_blob_container(table) with open(filename, 'rb') as f: digest = container.put(f) return '{server}/_blobs/{table}/{digest}'.format( server=conn.client.ac...
Write a Python 3 script to upload a file into a blob table
You are a Python code architect, reviewing and designing scalable and efficient code
def update_dois(csv_source, write_file=True): """ Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs listed in a single column. The output is LiPD-formatted publication data for each entry. :param str csv_source: Local path to CSV file ...
How would you implement a function in Python 3 that updates the list of DOIs in a single csv file.
As a Python code composer, you craft elegant and concise scripts.
def write_json_to_file(json_data, filename="metadata"): """ Write all JSON in python dictionary to a new json file. :param any json_data: JSON data :param str filename: Target filename (defaults to 'metadata.jsonld') :return None: """ # Use demjson to maintain unicode characters in output ...
Can you implement a function in Python 3 that writes all JSON in python dictionary to a new json file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of Author objects representing the authors in the last and first order.
Here you have a function in Python 3, explain what it does def compile_authors(authors): author_list = [] for person in authors: author_list.append({'name': person['family'] + ", " + person['given']}) return author_list
You are a Python code architect, reviewing and designing scalable and efficient code
def compile_fetch(raw, doi_id): """ Loop over Raw and add selected items to Fetch with proper formatting :param dict raw: JSON data from doi.org :param str doi_id: :return dict: """ fetch_dict = OrderedDict() order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title'...
Create a Python 3 function for looping over Raw and add selected items to Fetch with proper formatting
As a python code expert, you are capable of creating scripts from specifications.
Resolve DOI and compile all attributes into one dictionary
Given the following Python 3 function, write the documentation def get_data(doi_id): fetch_dict = {} try: # Send request to grab metadata at URL print("Requesting : {}".format(doi_id)) url = "http://dx.doi.org/" + doi_id headers = {"accept": "application/rdf+xml;q=0.5, applicat...
As a Python code analyst, you investigate and solve complex coding mysteries
def clean_doi(doi_string): """ Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215) :param str doi_string: Raw DOI string value from input file. Often not properly formatted. :return list: DOI ids. May contain 0, 1, or multiple ids. """ regex = re.compile(r'\b(10[.][0-9]{3,}...
Can you write a function in Python 3 where it uses regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215) :param str doi_string: Raw DOI string value from input file. Often not properly formatted. :return list: DOI ids. May contain 0, 1, or multiple ids.
You are a Python code analyst, evaluating scripts for potential improvements.
def log_benchmark(fn, start, end): """ Log a given function and how long the function takes in seconds :param str fn: Function name :param float start: Function start time :param float end: Function end time :return none: """ elapsed = round(end - start, 2) line = ("Benchmark - Funct...
Write a Python 3 function that can log a given function and how long it takes in seconds
You are a Python code generator, capable of creating scripts from specifications.
def update_changelog(): """ Create or update the changelog txt file. Prompt for update description. :return None: """ # description = input("Please enter a short description for this update:\n ") description = 'Placeholder for description here.' # open changelog file for appending. if doesn...
How would you code a function in Python 3 to create or update the changelog txt file. Prompt for update description.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a logger for function benchmark
Can you tell what is the following Python 3 function doing def create_benchmark(name, log_file, level=logging.INFO): handler = logging.FileHandler(log_file) rtf_handler = RotatingFileHandler(log_file, maxBytes=30000, backupCount=0) formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(messa...
You are a Python code architect, reviewing and designing scalable and efficient code
def create_logger(name): """ Creates a logger with the below attributes. :param str name: Name of the logger :return obj: Logger """ logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'forma...
Write a Python 3 function for creating a logger with the below attributes.
You are a Python code generator, capable of creating scripts from specifications.
Run a given statement a number of times and return the runtime stats.
Can you generate the documentation for the following Python 3 function def timeit(hosts=None, stmt=None, warmup=30, repeat=None, duration=None, concurrency=1, output_fmt=None, fail_if=None, sample_mode='reservoir'): """Run the g...
As a Python code composer, you craft elegant and concise scripts.
def get_download_path(): """ Determine the OS and the associated download folder. :return str Download path: """ if os.name == 'nt': import winreg sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' downloads_guid = '{374DE290-123F-4565-9164-39C4925E...
Implement a function in Python 3 to determine the OS and the associated download folder.
You are a Python code architect, reviewing and designing scalable and efficient code
def download_file(src_url, dst_path): """ Use the given URL and destination to download and save a file :param str src_url: Direct URL to lipd file download :param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd :return none: """ if "MD9821...
Write a Python 3 function that can download a file from a given URL and save it to a local path.
As a Python code analyst, you investigate and solve complex coding mysteries
Wait until predicate returns a truthy value or the timeout is reached.
Make a summary of the following Python 3 code def wait_until(predicate, timeout=30): not_expired = Timeout(timeout) while not_expired(): r = predicate() if r: break
As a Python code translator, you convert algorithms and pseudocode into Python.
def _find_matching_version(versions, version_pattern): """ Return the first matching version >>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x') '1.0.12' >>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x') """ pattern = fnmatch.translate(version_pattern.replace('...
Can you implement a function in Python 3 that finds the first matching version in a list of versions.
As a python code expert, you are capable of creating scripts from specifications.
def _build_tarball(src_repo) -> str: """ Build a tarball from src and return the path to it """ run = partial(subprocess.run, cwd=src_repo, check=True) run(['git', 'clean', '-xdff']) src_repo = Path(src_repo) if os.path.exists(src_repo / 'es' / 'upstream'): run(['git', 'submodule', 'update',...
Can you write a function in Python 3 where it builds a tarball from src and return the path to it
As a Python code composer, you craft elegant and concise scripts.
Return the path to the crates cache folder
Explain what the following Python 3 code does def _crates_cache() -> str: return os.environ.get( 'XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates'))
As a python code expert, you are capable of creating scripts from specifications.
def get_crate(version, crate_root=None): """Retrieve a Crate tarball, extract it and return the path. Args: version: The Crate version to get. Can be specified in different ways: - A concrete version like '0.55.0' - A version including a `x` as wildcards. Like: '1.1...
How would you implement a function in Python 3 that retrieves a Crate tarball extract it and return the path.
As a python code expert, you are capable of creating scripts from specifications.
Parse repeatable CLI options into a single dict.
Can you generate the documentation for the following Python 3 function def _parse_options(options: List[str]) -> Dict[str, str]: try: return dict(i.split('=', maxsplit=1) for i in options) except ValueError: raise ArgumentError( f'Option must be in format <key>=<value>, got: {options...
You are a Python code architect, reviewing and designing scalable and efficient code
Launch a crate instance.
Here you have a function in Python 3, explain what it does def run_crate( version, env=None, setting=None, crate_root=None, keep_data=False, disable_java_magic=False, ): """Launch a crate instance. Supported version specifications: - Concrete version like...
As a Python code composer, you craft elegant and concise scripts.
def start(self): """Start the process. This will block until the Crate cluster is ready to process requests. """ log.info('Starting Crate process') self.process = proc = self.enter_context(subprocess.Popen( self.cmd, stdin=subprocess.DEVNULL, ...
Create a Python 3 function for starting the process. This will block until the Crate cluster is ready to process requests.
As a Python code composer, you craft elegant and concise scripts.
Parse the log line and return the protocol and bound address.
Can you tell what is the following Python 3 function doing def _parse(line): m = AddrConsumer.ADDRESS_RE.match(line) if not m: return None, None protocol = m.group('protocol') protocol = AddrConsumer.PROTOCOL_MAP.get(protocol, protocol) return protocol, m.group('addr'...
As a Python code analyst, you investigate and solve complex coding mysteries
Adaptively determines image background and mean variance.
Can you tell what is the following Python 3 function doing def _calc_block_mean_variance(image, mask, blocksize): I = image.copy() I_f = I.astype(np.float32) / 255. # Used for mean and std. result = np.zeros( (image.shape[0] / blocksize, image.shape[1] / blocksize), dtype=np.float32) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None): """Applies adaptive thresholding to the given image. Args: image: BGRA image. block_size: optional int block_size to use for adaptive thresholding. mask: optional mask. Returns: Thresholded image. """ if ...
Implement a Python 3 function for applying adaptive thresholding to the given image.
As a Python code analyst, you investigate and solve complex coding mysteries
Find an appropriate version number from version control.
Here you have a function in Python 3, explain what it does def find_version(include_dev_version=True, root='%(pwd)s', version_file='%(root)s/version.txt', version_module_paths=(), git_args=None, vcs_args=None, decrement_dev_version=None, strip_prefix='v', ...
As a python code expert, you are capable of creating scripts from specifications.
A hook for simplifying vcversioner use from distutils.
Make a summary of the following Python 3 code def setup(dist, attr, value): dist.metadata.version = find_version(**value).version
As a Python code analyst, you investigate and solve complex coding mysteries
def to_insert(table, d): """Generate an insert statement using the given table and dictionary. Args: table (str): table name d (dict): dictionary with column names as keys and values as values. Returns: tuple of statement and arguments >>> to_insert('doc.foobar', {'name': 'Marv...
Can you implement a function in Python 3 that generates an insert statement using the given table and dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
def insert_json(table=None, bulk_size=1000, concurrency=25, hosts=None, output_fmt=None): """Insert JSON lines fed into stdin into a Crate cluster. If no hosts are specified the statements will be printed. Args: table: Target table na...
Can you implement a function in Python 3 that inserts JSON lines fed into stdin into a Crate cluster.
You are a Python code generator, capable of creating scripts from specifications.
def _get_dominant_angle(lines, domination_type=MEDIAN): """Picks dominant angle of a set of lines. Args: lines: iterable of (x1, y1, x2, y2) tuples that define lines. domination_type: either MEDIAN or MEAN. Returns: Dominant angle value in radians. Raises: ValueError: ...
Can you write a function in Python 3 where it picks dominant angle of a set of lines.
You are a Python code analyst, evaluating scripts for potential improvements.
Normalizes an angle in a given range.
Explain what the following Python 3 code does def _normalize_angle(angle, range, step): while angle <= range[0]: angle += step while angle >= range[1]: angle -= step return angle
You are a Python code generator, capable of creating scripts from specifications.
def get_collectors(self, limit=1000, offset=0): """Returns a dict of collectors. Args: limit (int): number of collectors to return offset (int): the offset of where the list of collectors should begin from """ options = { 'limit': limit, '...
Write a Python 3 function for returning a dict of collectors. is a list of collectors.
As a python code expert, you are capable of creating scripts from specifications.
Returns a dict of collector s details if found.
Given the following Python 3 function, write the documentation def find(self, name): collectors = self.get_collectors() for collector in collectors: if name.lower() == collector['name'].lower(): self.collector_id = collector['id'] return collector re...
As a Python code composer, you craft elegant and concise scripts.
Delete a collector from inventory.
Can you tell what is the following Python 3 function doing def delete(self, collector_id=None): cid = self.collector_id if collector_id: cid = collector_id # param to delete id url = '{0}/{1}'.format(self.url, cid) request = requests.delete(url, auth=self.auth) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a dict of collector.
Explain what the following Python 3 code does def info(self, collector_id): cid = self.collector_id if collector_id: cid = collector_id url = '{0}/{1}'.format(self.url, cid) request = requests.get(url, auth=self.auth) return request.json()
As a Python code composer, you craft elegant and concise scripts.
def _dotnotation_for_nested_dictionary(d, key, dots): """ Flattens nested data structures using dot notation. :param dict d: Original or nested dictionary :param str key: :param dict dots: Dotted dictionary so far :return dict: Dotted dictionary so far """ if key == 'chronData': ...
How would you implement a function in Python 3 that flattens nested dictionary into a single dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def create_dataframe(ensemble): """ Create a data frame from given nested lists of ensemble data :param list ensemble: Ensemble data :return obj: Dataframe """ logger_dataframes.info("enter ens_to_df") # "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ ...
Write a Python 3 script for creating a data frame from given nested lists of ensemble data
You are a Python code generator, capable of creating scripts from specifications.
Create an organized collection of data frames from LiPD data and csv data.
How would you explain what the following Python 3 function does def lipd_to_df(metadata, csvs): dfs = {} logger_dataframes.info("enter lipd_to_df") # Flatten the dictionary, but ignore the chron data items dict_in_dotted = {} logger_dataframes.info("enter dot_notation") _dotnotation_for_nested_...
As a Python code analyst, you investigate and solve complex coding mysteries
def ts_to_df(metadata): """ Create a data frame from one TimeSeries object :param dict metadata: Time Series dictionary :return dict: One data frame per table, organized in a dictionary by name """ logger_dataframes.info("enter ts_to_df") dfs = {} # Plot the variable + values vs year, a...
How would you code a function in Python 3 to create a data frame from one TimeSeries object
As a Python code analyst, you investigate and solve complex coding mysteries
Get variable + values vs year age depth columns from a TimeSeries dictionary
Can you tell what is the following Python 3 function doing def _plot_ts_cols(ts): logger_dataframes.info("enter get_ts_cols()") d = {} # Not entirely necessary, but this will make the column headers look nicer for the data frame # The column header will be in format "variableName (units)" try: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_dfs(csvs): """ LiPD Version 1.2 Create a data frame for each table for the given key :param dict csvs: LiPD metadata dictionary :return dict: paleo data data frames """ logger_dataframes.info("enter get_lipd_cols") # placeholders for the incoming data frames dfs = {"chronDat...
Create a Python 3 function for creating a data frame for each column in the LiPD metadata dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
Main function to get all data frames that match the given expression
Here you have a function in Python 3, explain what it does def get_filtered_dfs(lib, expr): logger_dataframes.info("enter get_filtered_dfs") dfs = {} tt = None # Process all lipds files or one lipds file? specific_files = _check_expr_filename(expr) # Determine the table type wanted if "ch...
You are a Python code generator, capable of creating scripts from specifications.
def _match_dfs_expr(lo_meta, expr, tt): """ Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables") :param dict lo_meta: Lipd object metadata :param str expr: Search expression :param str tt: Table type (chron or paleo) :return list: All filename...
Write a Python 3 script to get all data frames that match the given expression
You are a Python code analyst, evaluating scripts for potential improvements.
def _match_filenames_w_dfs(filenames, lo_dfs): """ Match a list of filenames to their data frame counterparts. Return data frames :param list filenames: Filenames of data frames to retrieve :param dict lo_dfs: All data frames :return dict: Filenames and data frames (filtered) """ logger_data...
Can you implement a function in Python 3 that matches a list of filenames to their data frame counterparts. Return data frames with matching filenames.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _check_expr_filename(expr): """ Split the expression and look to see if there's a specific filename that the user wants to process. :param str expr: Search expression :return str: Filename or None """ expr_lst = expr.split() f = [x for x in expr_lst if x not in DATA_FRAMES and x.endswith...
Write a Python 3 function that can split the expression and check if there s a specific filename that the user wants to process.
As a Python code composer, you craft elegant and concise scripts.
Loads a LiPD file from local path. Unzips read and processes data and converts it into a dictionary.
Given the following Python 3 function, write the documentation def lipd_read(path): _j = {} dir_original = os.getcwd() # Import metadata into object try: print("reading: {}".format(print_filename(path))) # bigger than 2mb file? This could take a while if os.stat(path).st_size > ...
You are a Python code analyst, evaluating scripts for potential improvements.
def lipd_write(_json, path): """ Saves current state of LiPD object data. Outputs to a LiPD file. Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit, zip up bag folder, place lipd in target dst, move to original dir, delete tmp :par...
How would you code a function in Python 3 to save current state of LiPD object data to a LiPD file.
As a Python code composer, you craft elegant and concise scripts.
def _bulk_size_generator(num_records, bulk_size, active): """ Generate bulk_size until num_records is reached or active becomes false >>> gen = _bulk_size_generator(155, 50, [True]) >>> list(gen) [50, 50, 50, 5] """ while active and num_records > 0: req_size = min(num_records, bulk_size...
Can you write a function in Python 3 where it generates bulk_size until num_records is reached or active becomes false
As a Python code analyst, you investigate and solve complex coding mysteries
Generate random data and insert it into a table.
Can you tell what is the following Python 3 function doing def insert_fake_data(hosts=None, table=None, num_records=1e5, bulk_size=1000, concurrency=25, mapping_file=None): """Generate random data and insert it ...
As a python code expert, you are capable of creating scripts from specifications.
This function gets file and creates outputs and runs all operations.
Can you generate the documentation for the following Python 3 function def main(self): logger_doi_resolver.info("enter doi_resolver") for idx, pub in enumerate(self.root_dict['pub']): # Retrieve DOI id key-value from the root_dict doi_string, doi_found = self.find_doi(pub) ...
As a Python code analyst, you investigate and solve complex coding mysteries