output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Load a configuration file into an options object.
Here you have a function in Python 3, explain what it does def load_config(cls, opts, path=None, profile=None): if path and os.path.exists(path): if os.path.isdir(path): cls.config_searchpath.insert(0, path) else: cls.config_files.insert(0, path) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Load the standard config file.
Given the following Python 3 function, write the documentation def load_config_file(self, path, profile=None): config_cls = self.get_config_reader() return config_cls.load_config(self, path, profile=profile)
As a python code expert, you are capable of creating scripts from specifications.
def load_creds_file(self, path, profile=None): """Load the credentials config file.""" config_cls = self.get_creds_reader() return config_cls.load_config(self, path, profile=profile)
Can you create a Python 3 function that loads the credentials config file.
You are a Python code analyst, evaluating scripts for potential improvements.
Set value for API headers.
Given the following Python 3 function, write the documentation def api_headers(self, value): value = validators.validate_api_headers("api_headers", value) self._set_option("api_headers", value)
As a Python code analyst, you investigate and solve complex coding mysteries
Set value for error_retry_codes.
Explain what the following Python 3 code does def error_retry_codes(self, value): if isinstance(value, six.string_types): value = [int(x) for x in value.split(",")] self._set_option("error_retry_codes", value)
As a Python code analyst, you investigate and solve complex coding mysteries
def _set_option(self, name, value, allow_clear=False): """Set value for an option.""" if not allow_clear: # Prevent clears if value was set try: current_value = self._get_option(name) if value is None and current_value is not None: ...
Implement a Python 3 function for setting value for an option.
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve status and optionally rate limit information from the API.
Explain what the following Python 3 code does def get_rate_limits(): client = get_rates_api() with catch_raise_api_exception(): data, _, headers = client.rates_limits_list_with_http_info() ratelimits.maybe_rate_limit(client, headers) return { k: RateLimitsInfo.from_dict(v) for...
You are a Python code architect, reviewing and designing scalable and efficient code
Attempt to load a string - based value into the native representation.
Make a summary of the following Python 3 code def loads(self, value, context=None): if value == '' or (hasattr(value, 'strip') and value.strip() == ''): return None return self.native(value)
As a python code expert, you are capable of creating scripts from specifications.
Transform and write a string - based foreign value to the given file - like object.
Explain what the following Python 3 code does def dump(self, fh, value, context=None): value = self.dumps(value) fh.write(value) return len(value)
You are a Python code architect, reviewing and designing scalable and efficient code
Convert a value from a foriegn type ( i. e. web - safe to Python - native.
How would you explain what the following Python 3 function does def native(self, value, context=None): if self.strip and hasattr(value, 'strip'): value = value.strip() if self.none and value == '': return None if self.encoding and isinstance(value, bytes): return value.decode(self.encoding) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def native(self, value, context=None): """Convert a value from a foriegn type (i.e. web-safe) to Python-native.""" value = super().native(value, context) if value is None: return try: return self.ingress(value) except Exception as e: raise Concern("Unable to transform incoming value: {0}", str(...
Write a Python 3 script to convert a value from a foriegn type ( i. e. web - safe to Python - native.
You are a Python code architect, reviewing and designing scalable and efficient code
Check current API rate limits.
Make a summary of the following Python 3 code def rates(ctx, opts): click.echo("Retrieving rate limits ... ", nl=False) context_msg = "Failed to retrieve status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): resources_limits = get_rate_l...
As a Python code analyst, you investigate and solve complex coding mysteries
def service(ctx, opts): """Check the status of the Cloudsmith service.""" click.echo("Retrieving service status ... ", nl=False) context_msg = "Failed to retrieve status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): status, version ...
Write a Python 3 function for checking the status of the Cloudsmith service.
As a python code expert, you are capable of creating scripts from specifications.
def total_seconds(td): """For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(...
How would you implement a function in Python 3 that returns the total number of seconds in the current node.
As a Python code composer, you craft elegant and concise scripts.
def dt_to_timestamp(dt): """Converts from a :class:`~datetime.datetime` object to an integer timestamp, suitable interoperation with :func:`time.time` and other `Epoch-based timestamps`. .. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time >>> abs(round(time.time() - dt_to_timestamp...
How would you implement a function in Python 3 that converts a datetime object to an integer timestamp suitable interoperation with time. time and naïve other epoch - based timestamps.
You are a Python code generator, capable of creating scripts from specifications.
def isoparse(iso_str): """Parses the limited subset of `ISO8601-formatted time`_ strings as returned by :meth:`datetime.datetime.isoformat`. >>> epoch_dt = datetime.utcfromtimestamp(0) >>> iso_str = epoch_dt.isoformat() >>> print(iso_str) 1970-01-01T00:00:00 >>> isoparse(iso_str) dateti...
Create a Python 3 function to parse the limited subset of ISO8601 - formatted time strings as .
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a tuple representing the relative time difference between two log files or the current time.
Explain what the following Python 3 code does def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True): if other is None: other = datetime.utcnow() diff = other - d diff_seconds = total_seconds(diff) abs_diff = abs(diff) b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1 bbo...
As a Python code composer, you craft elegant and concise scripts.
def relative_time(d, other=None, ndigits=0): """Get a string representation of the difference between two :class:`~datetime.datetime` objects or one :class:`~datetime.datetime` and the current time. Handles past and future times. Args: d (datetime): The first datetime object. other ...
Can you implement a function in Python 3 that returns a short string representation of the difference between two or one time objects or the current time.
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the date string according to the format in format.
Given the following Python 3 function, write the documentation def strpdate(string, format): whence = datetime.strptime(string, format) return whence.date()
As a Python code translator, you convert algorithms and pseudocode into Python.
def packages(ctx, opts, owner_repo, page, page_size, query): """ List packages for a repository. OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name to list packages for that namespace and repository. All separated by a slash. You can use the search query (-q|--query)...
Create a Python 3 function for listing packages in a repository.
As a Python code translator, you convert algorithms and pseudocode into Python.
def repos(ctx, opts, owner, page, page_size): """ List repositories for a namespace (owner). OWNER: Specify the OWNER namespace (i.e. user or org) to list the repositories for that namespace. If OWNER isn't specified it'll default to the currently authenticated user (if any). If you're unauthe...
Can you implement a function in Python 3 that lists all repositories for a namespace.
As a python code expert, you are capable of creating scripts from specifications.
Get the status for a package.
Can you generate a brief explanation for the following Python 3 code def _get_package_status(package): status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "stage...
You are a Python code generator, capable of creating scripts from specifications.
def boolify(value, nullable=False, return_string=False): """Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ...
Create a Python 3 function for converting a number string or sequence type into a pure boolean.
As a Python code translator, you convert algorithms and pseudocode into Python.
Takes a primitive value usually a string and attempts to make a more relevant type out of it.
Make a summary of the following Python 3 code def typify(value, type_hint=None): # value must be a string, or there at least needs to be a type hint if isinstance(value, string_types): value = value.strip() elif type_hint is None: # can't do anything because value isn't a string and there's ...
You are a Python code generator, capable of creating scripts from specifications.
def open(rootdir, mode='a'): # ---------------------------------------------------------------------- # https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132 # ---------------------------------------------------------------------- """ open(rootdir, mode='a') Open a disk-based c...
Can you implement a function in Python 3 that opens a disk - based carray or ctable object.
As a Python code composer, you craft elegant and concise scripts.
def delete(ctx, opts, owner_repo_package, yes): """ Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your...
How would you code a function in Python 3 to delete a package from a repository.
You are a Python code analyst, evaluating scripts for potential improvements.
def validate_owner_repo_identifier(ctx, param, value): """Ensure that owner/repo/identifier is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/IDENTIFIER" return validators.validate_slashes(param, value, minimum=3, maximum=3, form=form)
Can you create a Python 3 function that ensures that owner and repo identifier is formatted correctly.
As a Python code composer, you craft elegant and concise scripts.
Add common options for entitlement commands.
Given the following Python 3 function, write the documentation def common_entitlements_options(f): @click.option( "--show-tokens", default=False, is_flag=True, help="Show entitlement token string contents in output.", ) @click.pass_context @functools.wraps(f) def wra...
You are a Python code generator, capable of creating scripts from specifications.
Options for list entitlements subcommand.
Can you generate the documentation for the following Python 3 function def list_entitlements_options(f): @common_entitlements_options @decorators.common_cli_config_options @decorators.common_cli_list_options @decorators.common_cli_output_options @decorators.common_api_auth_options @decorators.i...
As a Python code analyst, you investigate and solve complex coding mysteries
List the entitlements for a repository.
Can you generate the documentation for the following Python 3 function def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens): owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo( ...
You are a Python code architect, reviewing and designing scalable and efficient code
Print entitlements as a table or output in another format.
Explain what the following Python 3 code does def print_entitlements(opts, data, page_info=None, show_list_info=True): if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Updated", "Identifier"] rows = [] for entitlement in sorted(data, key=itemge...
You are a Python code architect, reviewing and designing scalable and efficient code
def create(ctx, opts, owner_repo, show_tokens, name, token): """ Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Ful...
How would you code a function in Python 3 to create a new entitlement in a repository.
You are a Python code architect, reviewing and designing scalable and efficient code
def delete(ctx, opts, owner_repo_identifier, yes): """ Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your...
Write a Python 3 function for deleting an entitlement from a repository.
You are a Python code architect, reviewing and designing scalable and efficient code
Update a single resource in a repository.
Can you generate a brief explanation for the following Python 3 code def update(ctx, opts, owner_repo_identifier, show_tokens, name, token): owner, repo, identifier = owner_repo_identifier # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" cli...
You are a Python code analyst, evaluating scripts for potential improvements.
Refresh an entitlement in a repository.
How would you explain what the following Python 3 function does def refresh(ctx, opts, owner_repo_identifier, show_tokens, yes): owner, repo, identifier = owner_repo_identifier refresh_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } ...
As a python code expert, you are capable of creating scripts from specifications.
Counts the time spent in some context
How would you explain what the following Python 3 function does def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
You are a Python code analyst, evaluating scripts for potential improvements.
Pause the process based on suggested rate interval.
Can you tell what is the following Python 3 function doing def rate_limit(client, headers, atexit=False): if not client or not headers: return False if not getattr(client.config, "rate_limit", False): return False rate_info = RateLimitsInfo.from_headers(headers) if not rate_info or not...
As a python code expert, you are capable of creating scripts from specifications.
def get_status(with_version=False): """Retrieve status (and optionally) version from the API.""" client = get_status_api() with catch_raise_api_exception(): data, _, headers = client.status_check_basic_with_http_info() ratelimits.maybe_rate_limit(client, headers) if with_version: ...
Can you write a function in Python 3 where it retrieves status and optionally version from the API.
You are a Python code generator, capable of creating scripts from specifications.
Give the first value that satisfies the key test.
How would you explain what the following Python 3 function does def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x): return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
You are a Python code architect, reviewing and designing scalable and efficient code
def call_each(seq): """Calls each element of sequence to invoke the side effect. Args: seq: Returns: None """ try: reduce(lambda _, y: y(), seq) except TypeError as e: if text_type(e) != "reduce() of empty sequence with no initial value": raise
Write a Python 3 function that can call each element of sequence to invoke the side effect.
You are a Python code architect, reviewing and designing scalable and efficient code
Transform a username password value into a base64 string.
Can you generate the documentation for the following Python 3 function def transform_api_header_authorization(param, value): try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", ...
You are a Python code generator, capable of creating scripts from specifications.
def validate_api_headers(param, value): """Validate that API headers is a CSV of k=v pairs.""" # pylint: disable=unused-argument if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=", 1) k = k.strip() for bad...
Can you create a Python 3 function that validates that API headers are a CSV of k = v pairs.
You are a Python code analyst, evaluating scripts for potential improvements.
Ensure that parameter has slashes and minimum parts.
Can you generate a brief explanation for the following Python 3 code def validate_slashes(param, value, minimum=2, maximum=None, form=None): try: value = value.split("/") except ValueError: value = None if value: if len(value) < minimum: value = None elif maximum...
As a Python code composer, you craft elegant and concise scripts.
def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
Implement a Python 3 function for ensuring that owner and repo are formatted correctly.
You are a Python code analyst, evaluating scripts for potential improvements.
Ensure that owner. repo. package is formatted correctly.
Make a summary of the following Python 3 code def validate_owner_repo_package(ctx, param, value): # pylint: disable=unused-argument form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
As a Python code translator, you convert algorithms and pseudocode into Python.
def validate_owner_repo_distro(ctx, param, value): """Ensure that owner/repo/distro/version is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/DISTRO[/RELEASE]" return validate_slashes(param, value, minimum=3, maximum=4, form=form)
Implement a Python 3 function for ensuring that owner repo distro version is formatted correctly.
As a Python code composer, you craft elegant and concise scripts.
Ensure that a valid value for page is chosen.
How would you explain what the following Python 3 function does def validate_page(ctx, param, value): # pylint: disable=unused-argument if value == 0: raise click.BadParameter( "Page is not zero-based, please set a value to 1 or higher.", param=param ) return value
You are a Python code analyst, evaluating scripts for potential improvements.
Ensure that a valid value for page size is chosen.
Can you generate a brief explanation for the following Python 3 code def validate_page_size(ctx, param, value): # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
As a Python code translator, you convert algorithms and pseudocode into Python.
def getbalance(self, **params): """Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance """ if not all([self.api_key, self.api_secret]): raise Auth...
Write a Python 3 script to get Account Asset Balance
You are a Python code architect, reviewing and designing scalable and efficient code
Removes all overridden and inherited variables from hosts and groups
How would you explain what the following Python 3 function does def tidy_all_the_variables(host, inventory_mgr): ''' removes all overridden and inherited variables from hosts and groups ''' global _vars _vars = dict() _vars[host] = inventory_mgr.inventory.get_host_vars(host) for group in hos...
You are a Python code generator, capable of creating scripts from specifications.
def _plugins_inventory(self, entities): import os from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars ''' merges all entities by inventory source ''' data = {} for inventory_dir in self.variable_manager._inventory._sources: ...
Implement a Python 3 function for merging all entities by inventory source
As a python code expert, you are capable of creating scripts from specifications.
gets data from WordPress site
Explain what the following Python 3 code does def handle(self, *args, **options): # TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: self.password = option...
As a python code expert, you are capable of creating scripts from specifications.
def create_images_from_urls_in_content(self, body): """create Image objects and transfer image files to media root""" soup = BeautifulSoup(body, "html5lib") for img in soup.findAll('img'): old_url = img['src'] if 'width' in img: width = img['width'] ...
Create a Python 3 function to create Image objects and transfer image files to media root
As a Python code composer, you craft elegant and concise scripts.
def lookup_comment_by_wordpress_id(self, comment_id, comments): """ Returns Django comment object with this wordpress id """ for comment in comments: if comment.wordpress_id == comment_id: return comment
Can you write a function in Python 3 where it returns the comment object with this wordpress id
As a python code expert, you are capable of creating scripts from specifications.
def create_blog_pages(self, posts, blog_index, *args, **options): """create Blog post entries from wordpress data""" for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title = self.convert_html_entities(title) ...
Write a Python 3 function that can create blog entries from wordpress data
You are a Python code architect, reviewing and designing scalable and efficient code
def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): """ Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check aga...
How would you code a function in Python 3 to calculate and stores a unique slug of value for an instance.
As a Python code analyst, you investigate and solve complex coding mysteries
def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separator = separato...
Create a Python 3 function for cleaning up a slug by removing separator characters that occur at the beginning and end of a slug.
As a Python code translator, you convert algorithms and pseudocode into Python.
def limit_author_choices(): """ Limit choices in blog author field based on config settings """ LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None) if LIMIT_AUTHOR_CHOICES: if isinstance(LIMIT_AUTHOR_CHOICES, str): limit = Q(groups__name=LIMIT_AUTHOR_CHOICES...
How would you code a function in Python 3 to limit choices in blog author field based on config settings
As a Python code translator, you convert algorithms and pseudocode into Python.
Get context data useful on all blog related pages
Explain what the following Python 3 code does def get_blog_context(context): context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all_categories'] = ...
As a python code expert, you are capable of creating scripts from specifications.
removes the xmlns from the string representation of the key
Given the following Python 3 function, write the documentation def remove_xmlns(xml_string): # splitting xml into sections, pre_chan is preamble before <channel> pre_chan, chan, post_chan= xml_string.partition('<channel>') # replace xmlns statements on preamble pre_chan = re.sub(r'xmlns:...
You are a Python code analyst, evaluating scripts for potential improvements.
create a default dict of values including categories and tags
Given the following Python 3 function, write the documentation def item_dict(self, item): # mocking wierd JSON structure ret_dict = {"terms":{"category":[],"post_tag":[]}} for e in item: # is it a category or tag?? if "category" in e.tag: # get details ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def convert_date(d, custom_date_string=None, fallback=None): """ for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incident...
Create a Python 3 function for converting a date string to a date string.
You are a Python code generator, capable of creating scripts from specifications.
Translate a dictionary of items to the API json format
Can you tell what is the following Python 3 function doing def translate_item(self, item_dict): if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ret_dict = {} # slugify post ...
You are a Python code generator, capable of creating scripts from specifications.
Translate the comment into a dictionary.
Make a summary of the following Python 3 code def translate_wp_comment(self, e): comment_dict = {} comment_dict['ID'] = e.find('./{wp}comment_id').text comment_dict['date'] = e.find('{wp}comment_date').text comment_dict['content'] = e.find('{wp}comment_content').text comment_dict...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of post data for a WordPress xml export file
Here you have a function in Python 3, explain what it does def get_posts_data(self): items = self.chan.findall("item") #(e for e in chan.getchildren() if e.tag=='item') # turn item element into a generic dict item_dict_gen = (self.item_dict(item) for item in items) # transform the generi...
As a python code expert, you are capable of creating scripts from specifications.
def get_comments_data(self, slug): """ Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' ...
Write a Python 3 script for returning a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API.
You are a Python code analyst, evaluating scripts for potential improvements.
Formats the content of the log entry into HTML.
Here you have a function in Python 3, explain what it does def _format_content(self, content): content = re.sub(r'\n', '<br/>\n', content) content = re.sub(r' ', '&#160;&#160;', content) content = re.sub(r'&#160; ', '&#160;&#160;', content) return content
You are a Python code architect, reviewing and designing scalable and efficient code
Returns text with each consituent token wrapped in HTML markup for later match annotation.
Here you have a function in Python 3, explain what it does def _prepare_text(self, text): # Remove characters that should be escaped for XML input (but # which cause problems when escaped, since they become # tokens). text = re.sub(r'[<>&]', '', text) pattern = r'({})'.format(sel...
As a Python code composer, you craft elegant and concise scripts.
Generates HTML reports for each witness to work showing its text with the n - grams in n - grams highlighted.
Can you generate a brief explanation for the following Python 3 code def generate(self, output_dir, work, ngrams, labels, minus_ngrams): template = self._get_template() colours = generate_colours(len(ngrams)) for siglum in self._corpus.get_sigla(work): ngram_data = zip(labels, ngrams...
As a python code expert, you are capable of creating scripts from specifications.
Highlights the n - grams in the content with their n - grams from ngrams.
How would you explain what the following Python 3 function does def _highlight(self, content, ngrams, highlight): self._add_highlight = highlight for ngram in ngrams: pattern = self._get_regexp_pattern(ngram) content = re.sub(pattern, self._annotate_tokens, content) self....
As a Python code analyst, you investigate and solve complex coding mysteries
Generates HTML reports showing the text of each witness to work with its matches in matches in highlighted.
Here you have a function in Python 3, explain what it does def generate(self, output_dir, work, matches_filename): template = self._get_template() matches = pd.read_csv(matches_filename) for siglum in self._corpus.get_sigla(work): subm = matches[(matches[constants.WORK_FIELDNAME] != ...
As a Python code analyst, you investigate and solve complex coding mysteries
Pull out the metadata about each packet from the input_stream and return a generator that contains the metadata about each packet in the form of a dictionary.
Here you have a function in Python 3, explain what it does def packet_meta_data(self): # For each packet in the pcap process the contents for item in self.input_stream: # Output object output = {} # Grab the fields I need timestamp = item['timestamp'] ...
You are a Python code generator, capable of creating scripts from specifications.
def print_flow_info(flow): """Print a summary of the flow information""" print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']), len(flow['payload']), repr(flow['payload'])[:30]))
Write a Python 3 script to print a summary of the flow information
As a Python code composer, you craft elegant and concise scripts.
def packets_to_flows(self): """Combine packets into flows""" # For each packet, place it into either an existing flow or a new flow for packet in self.input_stream: # Compute flow tuple and add the packet to the flow flow_id = flow_utils.flow_tuple(packet) s...
Write a Python 3 function that can combine packets into flows
You are a Python code architect, reviewing and designing scalable and efficient code
Copy static assets for the report to output_dir.
How would you explain what the following Python 3 function does def _copy_static_assets(self, output_dir): base_directory = 'assets/{}'.format(self._report_name) for asset in resource_listdir(self._package_name, base_directory): filename = resource_filename( self._package_nam...
As a Python code composer, you craft elegant and concise scripts.
Returns a jinja2. Template object for this report.
Given the following Python 3 function, write the documentation def _get_template(self): loader = PackageLoader(self._package_name, 'assets/templates') env = Environment(extensions=['jinja2.ext.with_'], loader=loader) return env.get_template('{}.html'.format(self._report_name))
You are a Python code analyst, evaluating scripts for potential improvements.
def _write(self, context, report_dir, report_name, assets_dir=None, template=None): """Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. ...
Write a Python 3 function that can write the data in context in the template to report_dir.
As a Python code translator, you convert algorithms and pseudocode into Python.
Print out summary information about each packet from the input_stream
Given the following Python 3 function, write the documentation def pull(self): # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transport info ...
You are a Python code generator, capable of creating scripts from specifications.
Print out information about each packet from the input_stream
Here you have a function in Python 3, explain what it does def pull(self): # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('Timestamp: %s' % item['timestamp']) # Unpack the Ethernet frame (mac...
You are a Python code generator, capable of creating scripts from specifications.
Load the client adaptor module of django_peeringdb Assumes config is valid.
Explain what the following Python 3 code does def load_backend(**orm_config): settings = {} settings['SECRET_KEY'] = orm_config.get('secret_key', '') db_config = orm_config['database'] if db_config: settings['DATABASES'] = { 'default': database_settings(db_config) } fro...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_label_count(self): """Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work. """ self._logger.info('Adding label count') def add_label_count(df): ...
Implement a function in Python 3 to add to each result row a count of the number of occurrences of the n - gram across all works within the label.
As a python code expert, you are capable of creating scripts from specifications.
def add_label_work_count(self): """Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a ...
How would you code a function in Python 3 to add to each result row a count of the number of works within the n - gram containing that n - gram. This counts works that have at least one witness carrying the n - gram and that n - gram.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a dataframe with the n - grams that are bifurcated in the row.
Explain what the following Python 3 code does def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize, join): """Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count i...
As a Python code composer, you craft elegant and concise scripts.
Replaces the results with those n - grams that contain any of the original n - grams and that represent points at which a lower label count is a constituent of multiple larger n - grams with a lower label count.
Can you tell what is the following Python 3 function doing def bifurcated_extend(self, corpus, max_size): temp_fd, temp_path = tempfile.mkstemp(text=True) try: self._prepare_bifurcated_extend_data(corpus, max_size, temp_path, temp_fd) ...
As a python code expert, you are capable of creating scripts from specifications.
Collapse witnesses for the same n - gram and work that have the same count and outputs a single row for each group.
Can you tell what is the following Python 3 function doing def collapse_witnesses(self): # In order to allow for additional columns to be present in # the input data (such as label count), copy the siglum # information into a new final column, then put the sigla # information into the si...
You are a Python code architect, reviewing and designing scalable and efficient code
Writes the results data to fh in CSV format and returns fh.
Can you generate the documentation for the following Python 3 function def csv(self, fh): self._matches.to_csv(fh, encoding='utf-8', float_format='%d', index=False) return fh
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes all rows whose n - gram contains ngram.
Can you generate the documentation for the following Python 3 function def excise(self, ngram): self._logger.info('Excising results containing "{}"'.format(ngram)) if not ngram: return self._matches = self._matches[~self._matches[ constants.NGRAM_FIELDNAME].str.contains(n...
You are a Python code generator, capable of creating scripts from specifications.
def extend(self, corpus): """Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus` """ self._log...
Implement a Python 3 function for adding rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus`
As a Python code composer, you craft elegant and concise scripts.
def _generate_extended_matches(self, extended_ngrams, highest_n, work, siglum, label): """Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :pa...
Create a Python 3 function to generate the extended matches for the given n - grams within each extended n - gram.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _generate_extended_ngrams(self, matches, work, siglum, label, corpus, highest_n): """Returns the n-grams of the largest size that exist in `siglum` witness to `work` under `label`, generated from adding together overlapping n-grams in `matches`. :pa...
Write a Python 3 script for generating the n - grams that exist in the witness to work under label and adds them to the matches dataframe.
As a Python code analyst, you investigate and solve complex coding mysteries
def _generate_filter_ngrams(self, data, min_size): """Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` ...
How would you implement a function in Python 3 that returns the n - grams in data that do not contain any other n - gram in data.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of all substrings of ngram.
Can you tell what is the following Python 3 function doing def _generate_substrings(self, ngram, size): text = Text(ngram, self._tokenizer) substrings = [] for sub_size, ngrams in text.get_ngrams(1, size-1): for sub_ngram, count in ngrams.items(): substrings.extend([s...
You are a Python code analyst, evaluating scripts for potential improvements.
def group_by_ngram(self, labels): """Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order...
Can you implement a function in Python 3 that groups the result rows by n - gram and label.
As a python code expert, you are capable of creating scripts from specifications.
Groups results by witness providing a single summary field giving the n - grams found in it a count of their number and the count of their combined occurrences.
Can you generate a brief explanation for the following Python 3 code def group_by_witness(self): if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[constants.WORK_FI...
As a Python code composer, you craft elegant and concise scripts.
def _is_intersect_results(results): """Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool` """ sample = results.iloc[0] ngram = sample...
Implement a function in Python 3 to return False if results has an n - gram that exists in only one label True otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
Removes results rows whose n - gram is in ngrams.
Here you have a function in Python 3, explain what it does def prune_by_ngram(self, ngrams): self._logger.info('Pruning results by n-gram') self._matches = self._matches[ ~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
As a python code expert, you are capable of creating scripts from specifications.
def prune_by_ngram_count(self, minimum=None, maximum=None, label=None): """Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all ...
Write a Python 3 function that can remove results rows whose total n - gram count is outside the range specified by minimum and maximum.
You are a Python code architect, reviewing and designing scalable and efficient code
Removes the results rows if the n - gram count for all works bearing that n - gram is outside the specified range.
Can you generate a brief explanation for the following Python 3 code def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None): """Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `min...
You are a Python code generator, capable of creating scripts from specifications.
Removes results rows whose n - gram size is outside the specified minimum and maximum.
How would you explain what the following Python 3 function does def prune_by_ngram_size(self, minimum=None, maximum=None): self._logger.info('Pruning results by n-gram size') if minimum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] >= minimum] ...
As a Python code composer, you craft elegant and concise scripts.
def prune_by_work_count(self, minimum=None, maximum=None, label=None): """Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in mult...
Create a Python 3 function for removing rows for n - grams that are not attested in a specific n - gram with a number of works in the range specified by minimum and maximum.
You are a Python code architect, reviewing and designing scalable and efficient code