Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|>"""Installers for programming language specific libraries. """ def r_library_installer(config): """Install R libraries using CRAN and Bioconductor. """ if config.get("cran") or config.get("bioc") or config.get("github"): with shared._make_tmp_dir() as tmp_dir: with cd(tmp_dir): # Create an Rscript file with install details. out_file = os.path.join(tmp_dir, "install_packages.R") _make_install_script(out_file, config) # run the script and then get rid of it # try using either rlib_installed = False rscripts = [] conda_bin = shared._conda_cmd(env) if conda_bin: <|code_end|> . Use current file imports: import os from fabric.api import env, cd, settings from cloudbio import fabutils from cloudbio.custom import shared and context (classes, functions, or code) from other files: # Path: cloudbio/fabutils.py # SUDO_ENV_KEEPS = [] # Environment variables passed through to sudo environment when using local sudo. # def local_exists(path, use_sudo=False): # def run_local(use_sudo=False, capture=False): # def _run(command, *args, **kwags): # def local_put(orig_file, new_file): # def local_sed(filename, before, after, limit='', use_sudo=False, backup='.bak', # flags='', shell=False): # def local_comment(filename, regex, use_sudo=False, char='#', backup='.bak', shell=False): # def _escape_for_regex(text): # def _expand_path(path): # def local_contains(filename, text, exact=False, use_sudo=False, escape=True, # shell=False): # def local_append(filename, text, use_sudo=False, partial=False, escape=True, shell=False): # def run_output(*args, **kwargs): # def configure_runsudo(env): # def find_cmd(env, cmd, args): # def quiet(): # def warn_only(): # # Path: cloudbio/custom/shared.py # CBL_REPO_ROOT_URL = "https://raw.github.com/chapmanb/cloudbiolinux/master/" # def chdir(new_dir): # def safe_makedir(dname): # def which(program, env=None): # def is_exe(fpath): # def _if_not_installed(pname): # def argcatcher(func): # def decorator(*args, **kwargs): # def _all_cbl_paths(env, ext): # def _executable_not_on_path(pname): # def _galaxy_tool_install(args): # def _galaxy_tool_present(args): # def _if_not_python_lib(library): # def argcatcher(func): # def decorator(*args, **kwargs): # def make_tmp_dir_local(ext, work_dir): # def _make_tmp_dir(ext=None, work_dir=None): # def __work_dir(): # def _get_expected_file(url, dir_name=None, safe_tar=False, tar_file_name=None): # def _safe_dir_name(dir_name, need_dir=True): # def _remote_fetch(env, url, out_file=None, allow_fail=False, fix_fn=None, samedir=False): # def _fetch_and_unpack(url, need_dir=True, dir_name=None, revision=None, # safe_tar=False, tar_file_name=None): # def _configure_make(env): # def _ac_configure_make(env): # def _make_copy(find_cmd=None, premake_cmd=None, do_make=True): # def _do_work(env): # def _get_install(url, env, make_command, post_unpack_fn=None, revision=None, dir_name=None, # safe_tar=False, tar_file_name=None): # def _apply_patch(env, url): # def _get_install_local(url, env, make_command, dir_name=None, # post_unpack_fn=None, safe_tar=False, tar_file_name=None): # def _symlinked_install_dir(pname, version, env, extra_dir=None): # def _symlinked_dir_exists(pname, version, env, extra_dir=None): # def _symlinked_shared_dir(pname, version, env, extra_dir=None): # def _symlinked_java_version_dir(pname, version, env): # def _java_install(pname, version, url, env, install_fn=None, # pre_fetch_fn=None): # def _python_cmd(env): # def _pip_cmd(env): # def _conda_cmd(env): # def _is_anaconda(env): # def _python_make(env): # def _get_installed_file(env, local_file): # def _get_installed_file_contents(env, local_file): # def _write_to_file(contents, path, mode): # def _get_bin_dir(env): # def _get_include_dir(env): # def _get_lib_dir(env): # def _get_install_subdir(env, subdir): # def _set_default_config(env, install_dir, sym_dir_name="default"): # def _setup_simple_service(service_name): # def _render_config_file_template(env, name, defaults={}, overrides={}, default_source=None): # def _extend_env(env, defaults={}, overrides={}): # def _setup_conf_file(env, dest, name, defaults={}, overrides={}, default_source=None, mode="0755"): # def _add_to_profiles(line, profiles=[], use_sudo=True): # def install_venvburrito(): # def _create_python_virtualenv(env, venv_name, reqs_file=None, reqs_url=None): # def create(): # def _create_local_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _create_global_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _get_bitbucket_download_url(revision, default_repo): # def _read_boolean(env, name, default): . Output only the next line.
rscripts.append(fabutils.find_cmd(env, os.path.join(os.path.dirname(conda_bin), "Rscript"),
Predict the next line after this snippet: <|code_start|>def _build_galaxy_loc_line(env, dbkey, file_path, config, prefix, tool_name): """Prepare genome information to write to a Galaxy *.loc config file. """ if tool_name: str_parts = [] tool_conf = _get_tool_conf(env, tool_name) loc_cols = LocCols(config, dbkey, file_path) # Compose the .loc file line as str_parts list by looking for column values # from the retrieved tool_conf (as defined in tool_data_table_conf.xml). # Any column values required but missing in the tool_conf are # supplemented by the defaults defined in LocCols class for col in tool_conf.get('columns', []): str_parts.append(config.get(col, getattr(loc_cols, col))) else: str_parts = [dbkey, file_path] if prefix: str_parts.insert(0, prefix) return str_parts def update_loc_file(env, ref_file, line_parts): """Add a reference to the given genome to the base index file. """ if getattr(env, "galaxy_home", None) is not None: tools_dir = os.path.join(env.galaxy_home, "tool-data") if not os.path.exists(tools_dir): subprocess.check_call("mkdir -p %s" % tools_dir, shell=True) dt_file = os.path.join(env.galaxy_home, "tool_data_table_conf.xml") if not os.path.exists(dt_file): shutil.copy(env.tool_data_table_conf_file, dt_file) add_str = "\t".join(line_parts) <|code_end|> using the current file's imports: import os import shutil import subprocess from xml.etree import ElementTree from cloudbio.custom import shared and any relevant context from other files: # Path: cloudbio/custom/shared.py # CBL_REPO_ROOT_URL = "https://raw.github.com/chapmanb/cloudbiolinux/master/" # def chdir(new_dir): # def safe_makedir(dname): # def which(program, env=None): # def is_exe(fpath): # def _if_not_installed(pname): # def argcatcher(func): # def decorator(*args, **kwargs): # def _all_cbl_paths(env, ext): # def _executable_not_on_path(pname): # def _galaxy_tool_install(args): # def _galaxy_tool_present(args): # def _if_not_python_lib(library): # def argcatcher(func): # def decorator(*args, **kwargs): # def make_tmp_dir_local(ext, work_dir): # def _make_tmp_dir(ext=None, work_dir=None): # def __work_dir(): # def _get_expected_file(url, dir_name=None, safe_tar=False, tar_file_name=None): # def _safe_dir_name(dir_name, need_dir=True): # def _remote_fetch(env, url, out_file=None, allow_fail=False, fix_fn=None, samedir=False): # def _fetch_and_unpack(url, need_dir=True, dir_name=None, revision=None, # safe_tar=False, tar_file_name=None): # def _configure_make(env): # def _ac_configure_make(env): # def _make_copy(find_cmd=None, premake_cmd=None, do_make=True): # def _do_work(env): # def _get_install(url, env, make_command, post_unpack_fn=None, revision=None, dir_name=None, # safe_tar=False, tar_file_name=None): # def _apply_patch(env, url): # def _get_install_local(url, env, make_command, dir_name=None, # post_unpack_fn=None, safe_tar=False, tar_file_name=None): # def _symlinked_install_dir(pname, version, env, extra_dir=None): # def _symlinked_dir_exists(pname, version, env, extra_dir=None): # def _symlinked_shared_dir(pname, version, env, extra_dir=None): # def _symlinked_java_version_dir(pname, version, env): # def _java_install(pname, version, url, env, install_fn=None, # pre_fetch_fn=None): # def _python_cmd(env): # def _pip_cmd(env): # def _conda_cmd(env): # def _is_anaconda(env): # def _python_make(env): # def _get_installed_file(env, local_file): # def _get_installed_file_contents(env, local_file): # def _write_to_file(contents, path, mode): # def _get_bin_dir(env): # def _get_include_dir(env): # def _get_lib_dir(env): # def _get_install_subdir(env, subdir): # def _set_default_config(env, install_dir, sym_dir_name="default"): # def _setup_simple_service(service_name): # def _render_config_file_template(env, name, defaults={}, overrides={}, default_source=None): # def _extend_env(env, defaults={}, overrides={}): # def _setup_conf_file(env, dest, name, defaults={}, overrides={}, default_source=None, mode="0755"): # def _add_to_profiles(line, profiles=[], use_sudo=True): # def install_venvburrito(): # def _create_python_virtualenv(env, venv_name, reqs_file=None, reqs_url=None): # def create(): # def _create_local_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _create_global_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _get_bitbucket_download_url(revision, default_repo): # def _read_boolean(env, name, default): . Output only the next line.
with shared.chdir(tools_dir):
Based on the snippet: <|code_start|>"""Infrastructure for RNA-seq supporting files. """ def finalize(genomes, data_filedir): """Provide symlinks back to reference genomes so tophat avoids generating FASTA genomes. """ genome_dir = os.path.join(data_filedir, "genomes") for (orgname, gid, manager) in genomes: org_dir = os.path.join(genome_dir, orgname) for aligner in ["bowtie", "bowtie2"]: aligner_dir = os.path.join(org_dir, gid, aligner) if os.path.exists(aligner_dir): <|code_end|> , predict the immediate next line with the help of imports: import os import subprocess from cloudbio.custom import shared and context (classes, functions, sometimes code) from other files: # Path: cloudbio/custom/shared.py # CBL_REPO_ROOT_URL = "https://raw.github.com/chapmanb/cloudbiolinux/master/" # def chdir(new_dir): # def safe_makedir(dname): # def which(program, env=None): # def is_exe(fpath): # def _if_not_installed(pname): # def argcatcher(func): # def decorator(*args, **kwargs): # def _all_cbl_paths(env, ext): # def _executable_not_on_path(pname): # def _galaxy_tool_install(args): # def _galaxy_tool_present(args): # def _if_not_python_lib(library): # def argcatcher(func): # def decorator(*args, **kwargs): # def make_tmp_dir_local(ext, work_dir): # def _make_tmp_dir(ext=None, work_dir=None): # def __work_dir(): # def _get_expected_file(url, dir_name=None, safe_tar=False, tar_file_name=None): # def _safe_dir_name(dir_name, need_dir=True): # def _remote_fetch(env, url, out_file=None, allow_fail=False, fix_fn=None, samedir=False): # def _fetch_and_unpack(url, need_dir=True, dir_name=None, revision=None, # safe_tar=False, tar_file_name=None): # def _configure_make(env): # def _ac_configure_make(env): # def _make_copy(find_cmd=None, premake_cmd=None, do_make=True): # def _do_work(env): # def _get_install(url, env, make_command, post_unpack_fn=None, revision=None, dir_name=None, # safe_tar=False, tar_file_name=None): # def _apply_patch(env, url): # def _get_install_local(url, env, make_command, dir_name=None, # post_unpack_fn=None, safe_tar=False, tar_file_name=None): # def _symlinked_install_dir(pname, version, env, extra_dir=None): # def _symlinked_dir_exists(pname, version, env, extra_dir=None): # def _symlinked_shared_dir(pname, version, env, extra_dir=None): # def _symlinked_java_version_dir(pname, version, env): # def _java_install(pname, version, url, env, install_fn=None, # pre_fetch_fn=None): # def _python_cmd(env): # def _pip_cmd(env): # def _conda_cmd(env): # def _is_anaconda(env): # def _python_make(env): # def _get_installed_file(env, local_file): # def _get_installed_file_contents(env, local_file): # def _write_to_file(contents, path, mode): # def _get_bin_dir(env): # def _get_include_dir(env): # def _get_lib_dir(env): # def _get_install_subdir(env, subdir): # def _set_default_config(env, install_dir, sym_dir_name="default"): # def _setup_simple_service(service_name): # def _render_config_file_template(env, name, defaults={}, overrides={}, default_source=None): # def _extend_env(env, defaults={}, overrides={}): # def _setup_conf_file(env, dest, name, defaults={}, overrides={}, default_source=None, mode="0755"): # def _add_to_profiles(line, profiles=[], use_sudo=True): # def install_venvburrito(): # def _create_python_virtualenv(env, venv_name, reqs_file=None, reqs_url=None): # def create(): # def _create_local_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _create_global_python_virtualenv(env, venv_name, reqs_file, reqs_url): # def _get_bitbucket_download_url(revision, default_repo): # def _read_boolean(env, name, default): . Output only the next line.
with shared.chdir(aligner_dir):
Predict the next line for this snippet: <|code_start|> env.std_sources = _add_source_versions(env.dist_name, sources) def _setup_debian(): env.logger.info("Debian setup") unstable_remap = {"sid": "squeeze"} shared_sources = _setup_deb_general() sources = [ "deb http://cran.fhcrc.org/bin/linux/debian %s-cran/", # lastest R versions "deb http://nebc.nerc.ac.uk/bio-linux/ unstable bio-linux", # Bio-Linux ] + shared_sources # fill in %s dist_name = unstable_remap.get(env.dist_name, env.dist_name) env.std_sources = _add_source_versions(dist_name, sources) def _setup_deb_general(): """Shared settings for different debian based/derived distributions. """ env.logger.debug("Debian-shared setup") env.sources_file = "/etc/apt/sources.list.d/cloudbiolinux.list" env.global_sources_file = "/etc/apt/sources.list" env.apt_preferences_file = "/etc/apt/preferences" if not hasattr(env, "python_version_ext"): env.python_version_ext = "" if not hasattr(env, "ruby_version_ext"): env.ruby_version_ext = "1.9.1" if not env.has_key("java_home"): # Try to determine java location from update-alternatives java_home = "/usr/lib/jvm/java-7-openjdk-amd64" <|code_end|> with the help of current file imports: import os import subprocess from fabric.api import env from cloudbio.fabutils import quiet from cloudbio.fabutils import configure_runsudo from cloudbio.custom import system and context from other files: # Path: cloudbio/fabutils.py # def quiet(): # return settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True) # # Path: cloudbio/fabutils.py # def configure_runsudo(env): # """Setup env variable with safe_sudo and safe_run, # supporting non-privileged users and local execution. # """ # env.is_local = env.hosts == ["localhost"] # if env.is_local: # env.safe_put = local_put # env.safe_sed = local_sed # env.safe_comment = local_comment # env.safe_contains = local_contains # env.safe_append = local_append # env.safe_exists = local_exists # env.safe_run = run_local() # env.safe_run_output = run_local(capture=True) # else: # env.safe_put = put # env.safe_sed = sed # env.safe_comment = comment # env.safe_contains = contains # env.safe_append = append # env.safe_exists = exists # env.safe_run = run # env.safe_run_output = run_output # if isinstance(getattr(env, "use_sudo", "true"), six.string_types): # if getattr(env, "use_sudo", "true").lower() in ["true", "yes"]: # env.use_sudo = True # if env.is_local: # env.safe_sudo = run_local(True) # else: # env.safe_sudo = sudo # else: # env.use_sudo = False # if env.is_local: # env.safe_sudo = run_local() # else: # env.safe_sudo = run , which may contain function names, class names, or code. Output only the next line.
with quiet():
Based on the snippet: <|code_start|>"""Configuration details for specific server types. This module contains functions that help with initializing a Fabric environment for standard server types. """ def _setup_distribution_environment(ignore_distcheck=False): """Setup distribution environment. In low-level terms, this method attempts to populate various values in the fabric env data structure for use other places in CloudBioLinux. """ if "distribution" not in env: env.distribution = "__auto__" if "dist_name" not in env: env.dist_name = "__auto__" env.logger.info("Distribution %s" % env.distribution) if env.hosts == ["vagrant"]: _setup_vagrant_environment() elif env.hosts == ["localhost"]: _setup_local_environment() <|code_end|> , predict the immediate next line with the help of imports: import os import subprocess from fabric.api import env from cloudbio.fabutils import quiet from cloudbio.fabutils import configure_runsudo from cloudbio.custom import system and context (classes, functions, sometimes code) from other files: # Path: cloudbio/fabutils.py # def quiet(): # return settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True) # # Path: cloudbio/fabutils.py # def configure_runsudo(env): # """Setup env variable with safe_sudo and safe_run, # supporting non-privileged users and local execution. # """ # env.is_local = env.hosts == ["localhost"] # if env.is_local: # env.safe_put = local_put # env.safe_sed = local_sed # env.safe_comment = local_comment # env.safe_contains = local_contains # env.safe_append = local_append # env.safe_exists = local_exists # env.safe_run = run_local() # env.safe_run_output = run_local(capture=True) # else: # env.safe_put = put # env.safe_sed = sed # env.safe_comment = comment # env.safe_contains = contains # env.safe_append = append # env.safe_exists = exists # env.safe_run = run # env.safe_run_output = run_output # if isinstance(getattr(env, "use_sudo", "true"), six.string_types): # if getattr(env, "use_sudo", "true").lower() in ["true", "yes"]: # env.use_sudo = True # if env.is_local: # env.safe_sudo = run_local(True) # else: # env.safe_sudo = sudo # else: # env.use_sudo = False # if env.is_local: # env.safe_sudo = run_local() # else: # env.safe_sudo = run . Output only the next line.
configure_runsudo(env)
Continue the code snippet: <|code_start|> Raises: FIXParserError """ # pylint: disable=no-self-use delim = buf.find('=') if delim == -1: raise FIXParserError('Incorrect format: missing "="') tag_id = 0 try: tag_id = int(buf[:delim]) except ValueError: raise FIXParserError('Incorrect format: ID:' + buf[:delim]) return (tag_id, buf[delim+1:]) def _update_length(self, field, tag_id, value): """ Update the message length calculations """ # pylint: disable=unused-argument if tag_id not in {8, 9, 10}: self._message_length += len(field) + 1 if self._message_length >= self._max_length: raise FIXLengthTooLongError( 'message too long: {0}'.format(self._message_length)) def _update_checksum(self, field, tag_id, value): """ Update the message checksum calculations """ # pylint: disable=unused-argument if tag_id != 10: <|code_end|> . Use current file imports: import collections import logging from fixtest.base.utils import log_text from fixtest.fix.message import FIXMessage, checksum and context (classes, functions, or code) from other files: # Path: fixtest/base/utils.py # def log_text(log, header, text): # """Write out the name/text to the specified log object""" # log(format_log_line(header, text)) # # Path: fixtest/fix/message.py # class FIXMessage(BasicMessage): # """ Adds support for some basic FIX-specific functionality on top of # the BasicMessage class. # # Note that FIX requires a specific field ordering. This class # provides support for FIX-like protocols, but not necessarily # for a specific version. # # A FIX field is composed of (tag, value) pairs. A tag is a # numeric positive integer field. The value is a string. # """ # # def __init__(self, **kwargs): # """ Initialization # # Args: # source: A source message. This will be used to initialize # the message. # header_fields: A list of header tags. # Sequence ordering matters. (Default: [8, 9, 35, 49, 56]) # 8 = BeginString # 9 = BodyLength # 35 = MsgType # 49 = SenderCompID # 56 = TargetCompID # This setting only affects to_binary(), the input order # is not validated here. # """ # super(FIXMessage, self).__init__() # # # Preinsert header fields # header = kwargs.get('header_fields', [8, 9, 35, 49, 56]) # for tag in header: # self[tag] = '' # # if 'source' in kwargs: # self.update(kwargs['source']) # # def __keytransform__(self, key): # """ Override this to enforce the type of key expected. # # FIX only expects purely numeric keys. # """ # # pylint: disable=no-self-use # return int(key) # # def msg_type(self): # """ Returns the MessageType field (tag 35) of the message. # # Returns: a string containing the value of the tag 35 field. # """ # return self[35] # # def to_binary(self, **kwargs): # """ Converts the message into the on-the-wire format. # # This will prepare the message for sending by updating # the body length (9) and checksum (10) fields. # # Args: # include: A list of tags to explicitly include, tags not # in the list are not included. If this is not set, # then the default is to include all tags. # exclude: A list of tags to explicitly exclude, tags not # in the list are included. If this is not set, the # default is to not exclude any tags. # # Returns: # A binary string containing the message in the # FIX on-the-wire format. # """ # includes = {int(k): True for k in kwargs['include']} \ # if 'include' in kwargs else None # excludes = {int(k): True for k in kwargs['exclude']} \ # if 'exclude' in kwargs else None # # output = StringIO() # # for k, v in self.items(): # if includes is not None and k not in includes: # continue # if excludes is not None and k in excludes: # continue # # # Generate the binary without these fields # if k in {8, 9, 10}: # continue # # # write a field out, this may be a grouped value # _write_field(output, k, v) # # mess = output.getvalue() # # # prepend 8 (BeginString) and 9 (BodyLength) # # Note that 8 and 9 are the minimal set of required fields # self[9] = str(len(mess)) # mess = _single_field(8, self[8]) + _single_field(9, self[9]) + mess # # # calc and append the 10 (CheckSum) # if 10 in self: # del self[10] # self[10] = '%03d' % checksum(mess) # return mess + _single_field(10, self[10]) # # def verify(self, fields=None, exists=None, not_exists=None): # """ Checks for the existence/value of tags/values. # # Args: # fields: A list of (tag, value) pairs. The message # is searched for the tag and then checked to see if # the value is equal. # exists: A list of tags. The message is checked # for the existence of these tags (the value doesn't # matter). # not_exists: A list of tags. The message is checked # to see that it does NOT contain these tags. # # Returns: True if the conditions are satisifed. # False otherwise. # """ # fields = fields or list() # exists = exists or list() # not_exists = not_exists or list() # # for field in fields: # if field[0] not in self or str(self[field[0]]) != str(field[1]): # return False # # for tag in exists: # if tag not in self: # return False # # for tag in not_exists: # if tag in self: # return False # # return True # # def checksum(data, starting_checksum=0): # """ Calculates the checksum of the message according to FIX. # # This does not do any filtering of the data, so do not # calculate this with field 10 included. # """ # chksum = starting_checksum # for c in data: # chksum = (chksum + struct.unpack('B', c)[0]) % 256 # # return chksum . Output only the next line.
self._checksum = checksum(field, self._checksum) + 1
Continue the code snippet: <|code_start|> This is a FIX-formatted message, so this assumes that the key is a numeric string, that is only digits are allowed. Args: output: tag: value: """ output.write(_single_field(tag, value)) def _write_field(output, tag, value): """ Writes a field to the output. The value may be hiearchical. Args: output: tag: The ID portion. value: The value portion. This may be a nested group. """ if hasattr(value, '__iter__'): # write out the number of subgroups _write_single_field(output, tag, len(value)) for subgroup in value: for k, v in subgroup.iteritems(): _write_field(output, k, v) else: _write_single_field(output, tag, value) <|code_end|> . Use current file imports: from cStringIO import StringIO from fixtest.base.message import BasicMessage import struct and context (classes, functions, or code) from other files: # Path: fixtest/base/message.py # class BasicMessage(collections.MutableMapping): # """ A BasicMessage is just a collection of (ID, VALUE) pairs. # # All IDs are converted into strings, this allows users of the # BasicMessage to class to use integers or strings as keys. # e.g. message[35] == message['35'] # # If you iterate through the BasicMessage, the items will be # returned in the order they were added. This is important # because the order of the fields is important to FIX. # """ # def __init__(self, **kwargs): # """ Initialization # # Args: # source: copy over the fields from the source and # merge with this. This can be a list of (ID, VALUE) # tuples or a BasicMessage(). # """ # self.store = collections.OrderedDict() # # if 'source' in kwargs: # self.update(kwargs['source']) # # def __getitem__(self, key): # return self.store[self.__keytransform__(key)] # # def __setitem__(self, key, value): # self.store[self.__keytransform__(key)] = value # # def __delitem__(self, key): # del self.store[self.__keytransform__(key)] # # def __iter__(self): # return iter(self.store) # # def __len__(self): # return len(self.store) # # def __keytransform__(self, key): # """ Override this to enforce the type of key expected. # """ # # pylint: disable=no-self-use # return str(key) . Output only the next line.
class FIXMessage(BasicMessage):
Next line prediction: <|code_start|> self.assertEquals(19001, role_config['admin-port']) self.assertRaises(KeyError, self.config.get_role, 'serverYYY') def test_get_link(self): link_config = self.config.get_link('clientX', 'serverY') self.assertIsNotNone(link_config) self.assertEquals('client-fix-server', link_config['name']) self.assertRaises(KeyError, self.config.get_link, 'clientX', 'server') self.assertRaises(KeyError, self.config.get_link, 'clientX', 'serverY', 'fix') self.assertRaises(KeyError, self.config.get_link, 'client', 'serverY') def test_get_section(self): other_config = self.config.get_section('OTHER') self.assertIsNotNone(other_config) self.assertEquals('hello', other_config['test-id']) self.assertRaises(KeyError, self.config.get_section, 'OTHERXX') class TestFileConfig(unittest.TestCase): # pylint: disable=missing-docstring def test_fileconfig(self): file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_config.txt') <|code_end|> . Use current file imports: (import os import unittest from fixtest.base.config import FileConfig, DictConfig) and context including class names, function names, or small code snippets from other files: # Path: fixtest/base/config.py # class FileConfig(Config): # """ Provide the configuration from a file. # """ # # def __init__(self, file_name): # """ Initialize from the given fileName # # Args: # file_name: # """ # super(FileConfig, self).__init__() # execfile(file_name, globals(), self._config) # # class DictConfig(Config): # """ Provide the configuration from a pre-existing dictionary. # """ # def __init__(self, initial_config): # """ Dictionary-based configuration # # Args: # initial_config # """ # super(DictConfig, self).__init__() # self._config = initial_config . Output only the next line.
config = FileConfig(file_path)
Predict the next line for this snippet: <|code_start|>""" base.config unit tests Copyright (c) 2014 Kenn Takara See LICENSE for details """ class TestConfig(unittest.TestCase): # pylint: disable=missing-docstring def setUp(self): <|code_end|> with the help of current file imports: import os import unittest from fixtest.base.config import FileConfig, DictConfig and context from other files: # Path: fixtest/base/config.py # class FileConfig(Config): # """ Provide the configuration from a file. # """ # # def __init__(self, file_name): # """ Initialize from the given fileName # # Args: # file_name: # """ # super(FileConfig, self).__init__() # execfile(file_name, globals(), self._config) # # class DictConfig(Config): # """ Provide the configuration from a pre-existing dictionary. # """ # def __init__(self, initial_config): # """ Dictionary-based configuration # # Args: # initial_config # """ # super(DictConfig, self).__init__() # self._config = initial_config , which may contain function names, class names, or code. Output only the next line.
self.config = DictConfig({
Using the snippet: <|code_start|>""" Base client/server controller for testing. Copyright (c) 2014 Kenn Takara See LICENSE for details """ class SimpleClientServerController(BaseClientServerController): """ The base class for FIX-based TestCaseControllers. """ def __init__(self, **kwargs): super(SimpleClientServerController, self).__init__(**kwargs) self.testcase_id = 'Simple NewOrder test' self.description = 'Test of the command-line tool' self._logger = logging.getLogger(__name__) def run(self): """ Run the test. Here we send a new_order and then a modify. """ # client -> server <|code_end|> , determine the next line of code. You have imports: import logging from fixtest.base.asserts import * from fixtest.fix.messages import new_order_message, execution_report from simple_base import BaseClientServerController and context (class names, function names, or code) available: # Path: fixtest/fix/messages.py # def new_order_message(client, **kwargs): # """ Generates a new order message. # # Arguments: # # Returns: # # Raises: # ValueError # """ # # Required parameters # for sym in ['symbol', 'side', 'order_type']: # if sym not in kwargs: # raise ValueError("{0} must have a value".format(sym)) # # # optional parameters # extra_tags = kwargs.get('extra_tags', []) # # return FIXMessage(source=[ # (35, FIX.NEWORDER_SINGLE), # (49, client.sender_compid), # (56, client.target_compid), # (11, client.get_next_orderid()), # (21, '1'), # handlInst # (55, kwargs['symbol']), # (54, kwargs['side']), # (60, format_time(datetime.datetime.now())), # (40, kwargs['order_type']), # ] + extra_tags) # # def execution_report(client, prev_message, **kwargs): # """ Generates an execution report # # Arguments: # client # prev_message # exec_trans_type: # exec_type: # ord_status: # leaves_qty: # cum_qty: # avg_px: # # Returns: # Raises: # ValueError # """ # # Required parameters # for sym in ['exec_trans_type', 'exec_type', 'ord_status', # 'leaves_qty', 'cum_qty', # 'avg_px']: # if sym not in kwargs: # raise ValueError("{0} must have a value".format(sym)) # # # optional parameters # extra_tags = kwargs.get('extra_tags', []) # exec_id = kwargs.get('exec_id', None) or client.get_next_orderid() # # message = FIXMessage(source=prev_message) # message.update([ # (35, FIX.EXECUTION_REPORT), # (49, client.sender_compid), # (56, client.target_compid), # (11, prev_message[11]), # (37, client.get_next_orderid()), # (17, exec_id), # (20, kwargs['exec_trans_type']), # (150, kwargs['exec_type']), # (39, kwargs['ord_status']), # (151, kwargs['leaves_qty']), # (14, kwargs['cum_qty']), # (6, kwargs['avg_px']), # ] + extra_tags) # return message . Output only the next line.
self.client.send_message(new_order_message(self.client,
Predict the next line for this snippet: <|code_start|> class SimpleClientServerController(BaseClientServerController): """ The base class for FIX-based TestCaseControllers. """ def __init__(self, **kwargs): super(SimpleClientServerController, self).__init__(**kwargs) self.testcase_id = 'Simple NewOrder test' self.description = 'Test of the command-line tool' self._logger = logging.getLogger(__name__) def run(self): """ Run the test. Here we send a new_order and then a modify. """ # client -> server self.client.send_message(new_order_message(self.client, symbol='abc', side='0', order_type='1', extra_tags=[(38, 100), # orderQty (44, 10), # price ])) # server <- client message = self.server.wait_for_message('waiting for new order') assert_is_not_none(message) # server -> client <|code_end|> with the help of current file imports: import logging from fixtest.base.asserts import * from fixtest.fix.messages import new_order_message, execution_report from simple_base import BaseClientServerController and context from other files: # Path: fixtest/fix/messages.py # def new_order_message(client, **kwargs): # """ Generates a new order message. # # Arguments: # # Returns: # # Raises: # ValueError # """ # # Required parameters # for sym in ['symbol', 'side', 'order_type']: # if sym not in kwargs: # raise ValueError("{0} must have a value".format(sym)) # # # optional parameters # extra_tags = kwargs.get('extra_tags', []) # # return FIXMessage(source=[ # (35, FIX.NEWORDER_SINGLE), # (49, client.sender_compid), # (56, client.target_compid), # (11, client.get_next_orderid()), # (21, '1'), # handlInst # (55, kwargs['symbol']), # (54, kwargs['side']), # (60, format_time(datetime.datetime.now())), # (40, kwargs['order_type']), # ] + extra_tags) # # def execution_report(client, prev_message, **kwargs): # """ Generates an execution report # # Arguments: # client # prev_message # exec_trans_type: # exec_type: # ord_status: # leaves_qty: # cum_qty: # avg_px: # # Returns: # Raises: # ValueError # """ # # Required parameters # for sym in ['exec_trans_type', 'exec_type', 'ord_status', # 'leaves_qty', 'cum_qty', # 'avg_px']: # if sym not in kwargs: # raise ValueError("{0} must have a value".format(sym)) # # # optional parameters # extra_tags = kwargs.get('extra_tags', []) # exec_id = kwargs.get('exec_id', None) or client.get_next_orderid() # # message = FIXMessage(source=prev_message) # message.update([ # (35, FIX.EXECUTION_REPORT), # (49, client.sender_compid), # (56, client.target_compid), # (11, prev_message[11]), # (37, client.get_next_orderid()), # (17, exec_id), # (20, kwargs['exec_trans_type']), # (150, kwargs['exec_type']), # (39, kwargs['ord_status']), # (151, kwargs['leaves_qty']), # (14, kwargs['cum_qty']), # (6, kwargs['avg_px']), # ] + extra_tags) # return message , which may contain function names, class names, or code. Output only the next line.
self.server.send_message(execution_report(self.server,
Continue the code snippet: <|code_start|>""" base.message unit tests Copyright (c) 2014 Kenn Takara See LICENSE for details """ class TestBasicMessage(unittest.TestCase): # pylint: disable=missing-docstring def test_simple_basicmessage(self): """ Create a message and see if basic operations work. """ <|code_end|> . Use current file imports: import collections import unittest from fixtest.base.message import BasicMessage and context (classes, functions, or code) from other files: # Path: fixtest/base/message.py # class BasicMessage(collections.MutableMapping): # """ A BasicMessage is just a collection of (ID, VALUE) pairs. # # All IDs are converted into strings, this allows users of the # BasicMessage to class to use integers or strings as keys. # e.g. message[35] == message['35'] # # If you iterate through the BasicMessage, the items will be # returned in the order they were added. This is important # because the order of the fields is important to FIX. # """ # def __init__(self, **kwargs): # """ Initialization # # Args: # source: copy over the fields from the source and # merge with this. This can be a list of (ID, VALUE) # tuples or a BasicMessage(). # """ # self.store = collections.OrderedDict() # # if 'source' in kwargs: # self.update(kwargs['source']) # # def __getitem__(self, key): # return self.store[self.__keytransform__(key)] # # def __setitem__(self, key, value): # self.store[self.__keytransform__(key)] = value # # def __delitem__(self, key): # del self.store[self.__keytransform__(key)] # # def __iter__(self): # return iter(self.store) # # def __len__(self): # return len(self.store) # # def __keytransform__(self, key): # """ Override this to enforce the type of key expected. # """ # # pylint: disable=no-self-use # return str(key) . Output only the next line.
mess = BasicMessage()
Predict the next line after this snippet: <|code_start|>from __future__ import print_function try: except ImportError: import_module = __import__ __title__ = 'pif.discover' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013-2016 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('autodiscover',) LOGGER = logging.getLogger(__name__) def autodiscover(): """Autodiscovers the pif IP checkers in checkers directory.""" <|code_end|> using the current file's imports: import os import logging from .conf import get_setting from .helpers import PROJECT_DIR from importlib import import_module and any relevant context from other files: # Path: src/pif/conf.py # class Settings(object): # def __init__(self): # def set(self, name, value): # def get(self, name, default=None): # def reset_to_defaults(self): # # Path: src/pif/helpers.py # PROJECT_DIR = project_dir . Output only the next line.
ip_checkers_dir = get_setting('IP_CHECKERS_DIR')
Predict the next line for this snippet: <|code_start|>from __future__ import print_function try: except ImportError: import_module = __import__ __title__ = 'pif.discover' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013-2016 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('autodiscover',) LOGGER = logging.getLogger(__name__) def autodiscover(): """Autodiscovers the pif IP checkers in checkers directory.""" ip_checkers_dir = get_setting('IP_CHECKERS_DIR') ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') debug = get_setting('DEBUG') <|code_end|> with the help of current file imports: import os import logging from .conf import get_setting from .helpers import PROJECT_DIR from importlib import import_module and context from other files: # Path: src/pif/conf.py # class Settings(object): # def __init__(self): # def set(self, name, value): # def get(self, name, default=None): # def reset_to_defaults(self): # # Path: src/pif/helpers.py # PROJECT_DIR = project_dir , which may contain function names, class names, or code. Output only the next line.
for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)):
Given the following code snippet before the placeholder: <|code_start|> :return str: """ raise NotImplementedError( "You should override ``get_ip`` method in your IP checker class." ) class PublicIPCheckerRegistry(object): """Registry of public IP checkers.""" def __init__(self): self._registry = {} self._forced = [] @property def registry(self): """Registry.""" return self._registry def register(self, cls): """Register the IP checker in the registry. :param pif.base.BaseIPChecker cls: Subclass of ``pif.base.BaseIPChecker``. :param bool force: If set to True, item stays forced. It's not possible to un-register a forced item. :return bool: True if registered and False otherwise. """ if not issubclass(cls, BasePublicIPChecker): <|code_end|> , predict the next line using imports from the current file: import logging import socket from .exceptions import InvalidRegistryItemType and context including class names, function names, and sometimes code from other files: # Path: src/pif/exceptions.py # class InvalidRegistryItemType(ValueError): # """Raised when an attempt is made to register an irrelevant item. # # Raised when an attempt is made to register an item in the registry # which does not have a proper type. # """ . Output only the next line.
raise InvalidRegistryItemType(
Given the code snippet: <|code_start|> res = {} failed = [] for checker in checkers: _res = self._test_get_public_ip_using_preferred_checker(checker) if _res is None: failed.append(checker) res.update({checker: _res}) self.assertTrue( len(failed) == 0, "Failed for {}".format(','.join(failed)) ) return res @log_info def test_04_list_checkers(self): """Lists all registered checkers.""" res = list_checkers() self.assertTrue(len(res) > 0) return res @log_info def test_05_unregister_checker(self): """Test un-register checker `dyndns.com`.""" self.assertTrue('dyndns.com' in registry.registry.keys()) registry.unregister('dyndns.com') self.assertTrue('dyndns.com' not in registry.registry.keys()) @log_info def test_06_register_custom_checker(self): """Test un-register checker `dyndns`.""" <|code_end|> , generate the next line using the imports in this file: import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover and context (functions, classes, or occasionally code) from other files: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass . Output only the next line.
class MyPublicIPChecker(BasePublicIPChecker):
Next line prediction: <|code_start|>def log_info(func): """Prints some useful info.""" if not LOG_INFO: return func def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') LOGGER.info('""" %s """', func.__doc__.strip()) LOGGER.info('----------------------------') if result is not None: LOGGER.info(result) return result return inner class PifTest(unittest.TestCase): """Tests.""" def setUp(self): """Set up.""" pass @log_info def test_01_autodiscover(self): """Test ``autodiscover``.""" autodiscover() <|code_end|> . Use current file imports: (import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover) and context including class names, function names, or small code snippets from other files: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass . Output only the next line.
self.assertTrue(len(registry.registry) > 0)
Continue the code snippet: <|code_start|> def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') LOGGER.info('""" %s """', func.__doc__.strip()) LOGGER.info('----------------------------') if result is not None: LOGGER.info(result) return result return inner class PifTest(unittest.TestCase): """Tests.""" def setUp(self): """Set up.""" pass @log_info def test_01_autodiscover(self): """Test ``autodiscover``.""" autodiscover() self.assertTrue(len(registry.registry) > 0) @log_info def test_02_get_public_ip(self): """Test get IP.""" <|code_end|> . Use current file imports: import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover and context (classes, functions, or code) from other files: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass . Output only the next line.
res = get_public_ip(verbose=True)
Given snippet: <|code_start|> class PifTest(unittest.TestCase): """Tests.""" def setUp(self): """Set up.""" pass @log_info def test_01_autodiscover(self): """Test ``autodiscover``.""" autodiscover() self.assertTrue(len(registry.registry) > 0) @log_info def test_02_get_public_ip(self): """Test get IP.""" res = get_public_ip(verbose=True) self.assertIsNotNone(res) return res @log_info def _test_get_public_ip_using_preferred_checker(self, checker): """Test get_public_ip using preferred checker.""" res = get_public_ip(checker, verbose=True) return res @log_info def test_03_get_public_ip_using_preferred_checker(self): """Test get IP using preferred checker `ident.me`.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover and context: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass which might include code, classes, or functions. Output only the next line.
checkers = list_checkers()
Predict the next line after this snippet: <|code_start|> """Lists all registered checkers.""" res = list_checkers() self.assertTrue(len(res) > 0) return res @log_info def test_05_unregister_checker(self): """Test un-register checker `dyndns.com`.""" self.assertTrue('dyndns.com' in registry.registry.keys()) registry.unregister('dyndns.com') self.assertTrue('dyndns.com' not in registry.registry.keys()) @log_info def test_06_register_custom_checker(self): """Test un-register checker `dyndns`.""" class MyPublicIPChecker(BasePublicIPChecker): """MyPublicIPChecker.""" uid = 'mypublicipchecker' def get_public_ip(self): """Get public IP.""" return '8.8.8.8' registry.register(MyPublicIPChecker) self.assertTrue('mypublicipchecker' in registry.registry.keys()) @log_info def test_07_get_local_ip(self): """Test get local IP.""" <|code_end|> using the current file's imports: import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover and any relevant context from other files: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass . Output only the next line.
ensure_autodiscover()
Next line prediction: <|code_start|> def log_info(func): """Prints some useful info.""" if not LOG_INFO: return func def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') LOGGER.info('""" %s """', func.__doc__.strip()) LOGGER.info('----------------------------') if result is not None: LOGGER.info(result) return result return inner class PifTest(unittest.TestCase): """Tests.""" def setUp(self): """Set up.""" pass @log_info def test_01_autodiscover(self): """Test ``autodiscover``.""" <|code_end|> . Use current file imports: (import logging import unittest from .base import BasePublicIPChecker, registry from .utils import get_public_ip, list_checkers, ensure_autodiscover from .discover import autodiscover) and context including class names, function names, or small code snippets from other files: # Path: src/pif/base.py # class BasePublicIPChecker(object): # """Base public IP checker.""" # # uid = None # verbose = False # # def __init__(self, verbose=False): # """Constructor. # # :param bool verbose: # """ # assert self.uid # self.verbose = verbose # self.logger = logging.getLogger(__name__) # # def get_local_ip(self): # """Get local IP. # # :return str: # """ # return socket.gethostbyname(socket.gethostname()) # # def get_public_ip(self): # """Get public IP. # # :return str: # """ # raise NotImplementedError( # "You should override ``get_ip`` method in your IP checker class." # ) # # @property # def registry(self): # """Registry.""" # return self._registry # # Path: src/pif/utils.py # def get_public_ip(preferred_checker=None, verbose=False): # """Get IP using one of the services. # # :param str preferred_checker: Checker UID. If given, the preferred # checker is used. # :param bool verbose: If set to True, debug info is printed. # :return str: # """ # ensure_autodiscover() # # # If use preferred checker. # if preferred_checker: # ip_checker_cls = registry.get(preferred_checker) # # if not ip_checker_cls: # return False # # ip_checker = ip_checker_cls(verbose=verbose) # public_ip = ip_checker.get_public_ip() # # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # # Using all checkers. # # for ip_checker_name, ip_checker_cls in registry.registry.items(): # ip_checker = ip_checker_cls(verbose=verbose) # try: # public_ip = ip_checker.get_public_ip() # if public_ip: # if verbose: # LOGGER.info('provider: %s', ip_checker_cls.__name__) # return public_ip # # except Exception as err: # if verbose: # LOGGER.error(err) # # return False # # def list_checkers(): # """List available checkers. # # :return list: # """ # ensure_autodiscover() # return registry.registry.keys() # # def ensure_autodiscover(): # """Ensure the IP checkers are auto-discovered.""" # if not registry.registry: # autodiscover() # # Path: src/pif/discover.py # def autodiscover(): # """Autodiscovers the pif IP checkers in checkers directory.""" # ip_checkers_dir = get_setting('IP_CHECKERS_DIR') # ip_checker_module_name = get_setting('IP_CHECKER_MODULE_NAME') # debug = get_setting('DEBUG') # # for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)): # full_app_path = [ip_checkers_dir] # full_app_path.append(app_path) # if os.path.isdir(PROJECT_DIR(full_app_path)): # try: # import_module( # "pif.%s.%s.%s" % (ip_checkers_dir, # app_path, # ip_checker_module_name) # ) # except ImportError as err: # if debug: # LOGGER.debug(str(err)) # except Exception as err: # if debug: # LOGGER.debug(str(err)) # else: # pass . Output only the next line.
autodiscover()
Next line prediction: <|code_start|> class Grapher: ### CLASS VARIABLES ### _valid_formats = ("png", "pdf", "svg") _valid_layouts = ("circo", "dot", "fdp", "neato", "osage", "sfdp", "twopi") ### INITIALIZER ### def __init__(self, graphable, format_="pdf", layout="dot", output_directory=None): if layout not in self._valid_layouts: raise ValueError("Invalid layout: {layout!r}") if format_ not in self._valid_formats: raise ValueError("Invalid format: {format_!r}") self.graphable = graphable self.format_ = format_ self.layout = layout self.output_directory = pathlib.Path(output_directory or ".") ### SPECIAL METHODS ### def __call__(self): <|code_end|> . Use current file imports: (import datetime import hashlib import pathlib import re import subprocess import sys import tempfile from typing import Generator, Sequence, Tuple from uqbar.io import Timer) and context including class names, function names, or small code snippets from other files: # Path: uqbar/io/Timer.py # class Timer: # """ # A context manager for timing blocks of code. # # This context manager is not reentrant. Use a separate instance when nesting # multiple timers. # # :param exit_message: message to print on entering the context # :param enter_message: message to print on exiting the context # :param verbose: whether to print output # # :: # # >>> import math # >>> from uqbar.io import Timer # >>> timer = Timer("Elapsed time:", "Looping!") # >>> with timer: # ... for i in range(10000): # ... z = i ** math.pi # ... # Looping! # Elapsed time: 0.0... # # """ # # def __init__( # self, exit_message: str = None, enter_message: str = None, verbose: bool = True # ) -> None: # if enter_message is not None: # enter_message = str(enter_message) # self._enter_message = enter_message # if exit_message is not None: # exit_message = str(exit_message) # self._exit_message = exit_message # self._start_time: typing.Optional[float] = None # self._stop_time: typing.Optional[float] = None # self._verbose = bool(verbose) # # ### SPECIAL METHODS ### # # def __enter__(self) -> "Timer": # if self.enter_message and self.verbose: # print(self.enter_message) # self._stop_time = None # self._start_time = time.time() # return self # # def __exit__(self, exc_type, exc_value, traceback) -> None: # self._stop_time = time.time() # if self.exit_message and self.verbose: # print(self.exit_message, self.elapsed_time) # # ### PUBLIC PROPERTIES ### # # @property # def elapsed_time(self) -> typing.Union[float, None]: # if self.start_time is not None: # if self.stop_time is not None: # return self.stop_time - self.start_time # return time.time() - self.start_time # return None # # @property # def enter_message(self) -> typing.Union[str, None]: # return self._enter_message # # @property # def exit_message(self) -> typing.Union[str, None]: # return self._exit_message # # @property # def start_time(self) -> typing.Union[float, None]: # return self._start_time # # @property # def stop_time(self) -> typing.Union[float, None]: # return self._stop_time # # @property # def verbose(self) -> bool: # return self._verbose . Output only the next line.
with Timer() as format_timer:
Here is a snippet: <|code_start|> ) self.extensions = extensions self.errored = False self.results: List[Any] = [] self.monkeypatch = None self.proxy_options: Dict[str, Dict[str, Any]] = {} ### SPECIAL METHODS ### def __enter__(self): self.monkeypatch = MonkeyPatch() for extension in self.extensions or []: extension.setup_console(self, self.monkeypatch) return self def __exit__(self, exc_type, exc_value, traceback): self.monkeypatch.undo() for extension in self.extensions or []: extension.teardown_console(self) ### PUBLIC METHODS ### def flush(self) -> None: pass def interpret(self, lines: List[str]) -> Tuple[List[Any], bool]: self.resetbuffer() self.errored = False self.results[:] = [] is_incomplete_statement = False <|code_end|> . Write the next line using the current file imports: import code import inspect import itertools from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple from uqbar.io import RedirectedStreams and context from other files: # Path: uqbar/io/RedirectedStreams.py # class RedirectedStreams: # """ # A context manager for capturing ``stdout`` and ``stderr`` output. # # .. container:: example # # :: # # >>> import uqbar.io # >>> import io # # :: # # >>> string_io = io.StringIO() # >>> with uqbar.io.RedirectedStreams(stdout=string_io): # ... print("hello, world!") # ... # # :: # # >>> result = string_io.getvalue() # >>> string_io.close() # >>> print(result) # hello, world! # # This context manager is not reentrant. Use a separate instance when nesting # multiple timers. # """ # # ### INITIALIZER ### # # def __init__(self, stdout=None, stderr=None): # self._stdout = stdout or sys.stdout # self._stderr = stderr or sys.stderr # # ### SPECIAL METHODS ### # # def __enter__(self): # self._old_stdout, self._old_stderr = sys.stdout, sys.stderr # self._old_stdout.flush() # self._old_stderr.flush() # sys.stdout, sys.stderr = self._stdout, self._stderr # return self # # def __exit__(self, exc_type, exc_value, traceback): # try: # self._stdout.flush() # self._stderr.flush() # finally: # sys.stdout = self._old_stdout # sys.stderr = self._old_stderr # # ### PUBLIC PROPERTIES ### # # @property # def stderr(self): # return self._stderr # # @property # def stdout(self): # return self._stdout , which may include functions, classes, or code. Output only the next line.
with RedirectedStreams(self, self), self:
Based on the snippet: <|code_start|> Get graph-order tuple for node. :: >>> from uqbar.containers import UniqueTreeList, UniqueTreeNode >>> root_container = UniqueTreeList(name="root") >>> outer_container = UniqueTreeList(name="outer") >>> inner_container = UniqueTreeList(name="inner") >>> node_a = UniqueTreeNode(name="a") >>> node_b = UniqueTreeNode(name="b") >>> node_c = UniqueTreeNode(name="c") >>> node_d = UniqueTreeNode(name="d") >>> root_container.extend([node_a, outer_container]) >>> outer_container.extend([inner_container, node_d]) >>> inner_container.extend([node_b, node_c]) :: >>> for node in root_container.depth_first(): ... print(node.name, node.graph_order) ... a (0,) outer (1,) inner (1, 0) b (1, 0, 0) c (1, 0, 1) d (1, 1) """ graph_order = [] <|code_end|> , predict the immediate next line with the help of imports: import copy import typing from uqbar.iterables import nwise and context (classes, functions, sometimes code) from other files: # Path: uqbar/iterables.py # def nwise(iterable, n=2): # iterables = itertools.tee(iterable, n) # temp = [] # for idx, it in enumerate(iterables): # it = itertools.islice(it, idx, None) # temp.append(it) # return zip(*temp) . Output only the next line.
for parent, child in nwise(reversed(self.parentage)):
Here is a snippet: <|code_start|> patch_grapher() def patch_grapher(): def get_format(self): return "svg" def open_output_path(self, output_path): with output_path.open() as file_pointer: contents = file_pointer.read() delete_attributes = True document = minidom.parseString(contents) svg_element = document.getElementsByTagName("svg")[0] view_box = svg_element.getAttribute("viewBox") view_box = [float(_) for _ in view_box.split()] if delete_attributes: if svg_element.attributes.get("height", None): del svg_element.attributes["height"] if svg_element.attributes.get("width", None): del svg_element.attributes["width"] else: height = "{}pt".format(int(view_box[-1] * 0.6)) width = "{}pt".format(int(view_box[-2] * 0.6)) svg_element.setAttribute("height", height) svg_element.setAttribute("width", width) svg_element.setAttribute("preserveAspectRatio", "xMinYMin") contents = document.toprettyxml() display_svg(contents, raw=True) <|code_end|> . Write the next line using the current file imports: from xml.dom import minidom # type: ignore from uqbar.graphs import Grapher from IPython.core.display import display_svg and context from other files: # Path: uqbar/graphs/Grapher.py # class Grapher: # # ### CLASS VARIABLES ### # # _valid_formats = ("png", "pdf", "svg") # _valid_layouts = ("circo", "dot", "fdp", "neato", "osage", "sfdp", "twopi") # # ### INITIALIZER ### # # def __init__(self, graphable, format_="pdf", layout="dot", output_directory=None): # if layout not in self._valid_layouts: # raise ValueError("Invalid layout: {layout!r}") # if format_ not in self._valid_formats: # raise ValueError("Invalid format: {format_!r}") # self.graphable = graphable # self.format_ = format_ # self.layout = layout # self.output_directory = pathlib.Path(output_directory or ".") # # ### SPECIAL METHODS ### # # def __call__(self): # with Timer() as format_timer: # string = self.get_string() # format_time = format_timer.elapsed_time # layout = self.get_layout() # format_ = self.get_format() # render_prefix = self.get_render_prefix(string) # render_directory_path = self.get_render_directory() # input_path = (render_directory_path / render_prefix).with_suffix(".dot") # self.persist_string(string, input_path) # render_command = self.get_render_command(format_, input_path, layout) # with Timer() as render_timer: # log, success = self.run_command(render_command) # render_time = render_timer.elapsed_time # self.persist_log(log, input_path.with_suffix(".log")) # output_directory_path = self.get_output_directory() # output_paths = self.migrate_assets( # render_prefix, render_directory_path, output_directory_path # ) # openable_paths = [] # for output_path in self.get_openable_paths(format_, output_paths): # openable_paths.append(output_path) # self.open_output_path(output_path) # return output_path, format_time, render_time, success, log # # ### PUBLIC METHODS ### # # def get_format(self) -> str: # return self.format_ # # def get_layout(self) -> str: # return self.layout # # def get_openable_paths( # self, format_, output_paths # ) -> Generator[pathlib.Path, None, None]: # for path in output_paths: # if path.suffix == f".{format_}": # yield path # # def get_output_directory(self) -> pathlib.Path: # return self.output_directory # # def get_render_command(self, format_, input_path, layout) -> str: # parts = [ # layout, # "-v", # "-T", # format_, # "-o", # str(input_path.with_suffix("." + format_)), # str(input_path), # ] # return " ".join(parts) # # def get_render_directory(self): # return pathlib.Path(tempfile.mkdtemp()) # # def get_render_prefix(self, string) -> str: # timestamp = re.sub(r"[^\w]", "-", datetime.datetime.now().isoformat()) # checksum = hashlib.sha1(string.encode()).hexdigest()[:7] # return f"{timestamp}-{checksum}" # # def get_string(self) -> str: # try: # graphviz_graph = self.graphable.__graph__() # return format(graphviz_graph, "graphviz") # except AttributeError: # return self.graphable.__format_graphviz__() # # def migrate_assets( # self, render_prefix, render_directory, output_directory # ) -> Sequence[pathlib.Path]: # migrated_assets = [] # for old_path in render_directory.iterdir(): # if not old_path.name.startswith(render_prefix): # continue # new_path = output_directory / old_path.name # old_path.rename(new_path) # migrated_assets.append(new_path) # return migrated_assets # # def open_output_path(self, output_path): # viewer = "open" # if sys.platform.lower().startswith("linux"): # viewer = "xdg-open" # subprocess.run(f"{viewer} {output_path}", shell=True, check=True) # # def persist_log(self, string, input_path): # input_path.write_text(string) # # def persist_string(self, string, input_path): # input_path.write_text(string) # # def run_command(self, command: str) -> Tuple[str, int]: # completed_process = subprocess.run( # command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT # ) # return completed_process.stdout.decode(), completed_process.returncode == 0 , which may include functions, classes, or code. Output only the next line.
Grapher.get_format = get_format
Predict the next line after this snippet: <|code_start|> class MyObject: def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): self.arg1 = arg1 self.arg2 = arg2 self.var_args = var_args self.foo = foo self.bar = bar self.kwargs = kwargs def test_objects_get_hash_01(): object_a = MyObject("a", "b", "c", "d", foo="x", quux=["y", "z"]) object_b = MyObject("a", "b", "c", "d", foo="x", quux=["y", "z"]) object_c = MyObject("x", "y", bar=set([1, 2, 3])) <|code_end|> using the current file's imports: from uqbar.objects import get_hash and any relevant context from other files: # Path: uqbar/objects.py # def get_hash(expr): # args, var_args, kwargs = get_vars(expr) # hash_values = [type(expr)] # for key, value in args.items(): # if isinstance(value, list): # value = tuple(value) # elif isinstance(value, set): # value = frozenset(value) # elif isinstance(value, dict): # value = tuple(sorted(value.items())) # args[key] = value # hash_values.append(tuple(args.items())) # hash_values.append(tuple(var_args)) # for key, value in kwargs.items(): # if isinstance(value, list): # value = tuple(value) # elif isinstance(value, set): # value = frozenset(value) # elif isinstance(value, dict): # value = tuple(sorted(value.items())) # kwargs[key] = value # hash_values.append(tuple(sorted(kwargs.items()))) # return hash(tuple(hash_values)) . Output only the next line.
assert get_hash(object_a) == get_hash(object_b)
Continue the code snippet: <|code_start|> @pytest.mark.sphinx("text", testroot="uqbar-sphinx-api-1") def test_sphinx_api_1(app, status, warning): app.build() index_source = pathlib.Path(app.srcdir) / "api" / "index.rst" assert index_source.exists() assert "build succeeded" in status.getvalue() assert "8 added, 0 changed, 0 removed" in status.getvalue() assert "0 added, 0 changed, 0 removed" not in status.getvalue() assert not warning.getvalue().strip() path = pathlib.Path(app.srcdir) / "_build" / "text" / "api" / "index.txt" with path.open() as file_pointer: <|code_end|> . Use current file imports: import pathlib import pytest from uqbar.strings import normalize and context (classes, functions, or code) from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(file_pointer.read()) == normalize(
Given the following code snippet before the placeholder: <|code_start|> node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") uqbar.graphs.Edge().attach(node_a, node_b) def test___format___str(self): node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") edge = uqbar.graphs.Edge().attach(node_a, node_b) assert format(edge) == repr(edge) node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") attributes = uqbar.graphs.Attributes( mode="edge", color="blue", style=["dotted"] ) edge = uqbar.graphs.Edge(attributes=attributes).attach(node_a, node_b) assert format(edge) == repr(edge) def test___format___graphviz(self): node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") edge = uqbar.graphs.Edge().attach(node_a, node_b) assert format(edge, "graphviz") == "foo -> bar;" node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") attributes = uqbar.graphs.Attributes( mode="edge", color="blue", style=["dotted"] ) edge = uqbar.graphs.Edge(attributes=attributes).attach(node_a, node_b) <|code_end|> , predict the next line using imports from the current file: import unittest import uqbar.graphs from uqbar.strings import normalize and context including class names, function names, and sometimes code from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert format(edge, "graphviz") == normalize(
Based on the snippet: <|code_start|> ]: path = pathlib.Path(app.srcdir) / "_build" / "text" / filename actual_content = normalize(path.read_text()) assert actual_content == expected_content @pytest.mark.sphinx( "text", testroot="uqbar-sphinx-book", confoverrides={"uqbar_book_use_cache": False} ) def test_sphinx_book_text_uncached(app, status, warning, rm_dirs): app.build() assert not warning.getvalue().strip() assert not app.config["uqbar_book_use_cache"] for filename, expected_content in [ ("api.txt", api_content), ("directives.txt", directives_content), ("index.txt", index_content), ]: path = pathlib.Path(app.srcdir) / "_build" / "text" / filename actual_content = normalize(path.read_text()) assert actual_content == expected_content @pytest.mark.sphinx("text", testroot="uqbar-sphinx-book-broken") def test_sphinx_book_text_broken_strict(app, status, warning, rm_dirs): """ Build halts. """ with pytest.raises(sphinx.errors.ExtensionError): app.build() <|code_end|> , predict the immediate next line with the help of imports: import pathlib import shutil import sys import pytest import sphinx.errors from uqbar.strings import ansi_escape, normalize and context (classes, functions, sometimes code) from other files: # Path: uqbar/strings.py # def ansi_escape(string): # return _ansi_escape_pattern.sub("", string) # # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(ansi_escape(status.getvalue())) == normalize(
Given the code snippet: <|code_start|> @pytest.mark.sphinx("text", testroot="uqbar-sphinx-style") def test_sphinx_style_1(app, status, warning): app.build() assert "build succeeded" in status.getvalue() assert not warning.getvalue().strip() path = ( pathlib.Path(app.srcdir) / "_build" / "text" / "api" / "fake_package" / "module.txt" ) with path.open() as file_pointer: <|code_end|> , generate the next line using the imports in this file: import pathlib import pytest from uqbar.strings import normalize and context (functions, classes, or occasionally code) from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(file_pointer.read()) == normalize(
Predict the next line after this snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent docs_path = test_path / "docs" if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) if docs_path.exists(): shutil.rmtree(str(docs_path)) yield test_path if docs_path.exists(): shutil.rmtree(str(docs_path)) def test_collection_01(test_path): builder = uqbar.apis.APIBuilder([test_path / "fake_package"], test_path / "docs") source_paths = uqbar.apis.collect_source_paths(builder._initial_source_paths) node_tree = builder.build_node_tree(source_paths) <|code_end|> using the current file's imports: import pathlib import shutil import sys import pytest import uqbar.apis from uqbar.strings import normalize and any relevant context from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(str(node_tree)) == normalize(
Here is a snippet: <|code_start|> uqbar.graphs.Attributes(mode="edge") uqbar.graphs.Attributes(mode="graph") uqbar.graphs.Attributes(mode="node") def test___format___str_01(self): attributes = uqbar.graphs.Attributes(mode="node") assert format(attributes) == repr(attributes) def test___format___str_02(self): attributes = uqbar.graphs.Attributes( mode="node", color="blue", fontname="Times New Roman", fontsize=11.5, shape="oval", ) assert format(attributes) == repr(attributes) def test___format___graphviz_01(self): attributes = uqbar.graphs.Attributes(mode="node") assert format(attributes, "graphviz") == "" def test___format___graphviz_02(self): attributes = uqbar.graphs.Attributes( mode="node", color="blue", fontname="Times New Roman", fontsize=11.5, shape="oval", ) <|code_end|> . Write the next line using the current file imports: import unittest import uqbar.graphs from uqbar.strings import normalize and context from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string , which may include functions, classes, or code. Output only the next line.
assert format(attributes, "graphviz") == normalize(
Given snippet: <|code_start|> assert node_a._get_canonical_name() == "foo_0" assert node_b._get_canonical_name() == "foo_1" assert node_c._get_canonical_name() == "bar" def test___format___str(self): node = uqbar.graphs.Node() assert format(node) == repr(node) node = uqbar.graphs.Node(name="foo") assert format(node) == repr(node) attributes = uqbar.graphs.Attributes(mode="node", color="blue") node = uqbar.graphs.Node(name="foo", attributes=attributes) assert format(node) == repr(node) def test___format___graphviz(self): node = uqbar.graphs.Node() assert format(node, "graphviz") == "node_0;" node = uqbar.graphs.Node(name="foo") assert format(node, "graphviz") == "foo;" attributes = uqbar.graphs.Attributes( mode="node", color="blue", fontname="Times New Roman", fontsize=11.5, shape="oval", ) node = uqbar.graphs.Node(name="foo", attributes=attributes) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import uqbar.graphs from uqbar.strings import normalize and context: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string which might include code, classes, or functions. Output only the next line.
assert format(node, "graphviz") == normalize(
Continue the code snippet: <|code_start|> builder = uqbar.apis.APIBuilder( [test_path / "fake_package"], test_path / "docs", member_documenter_classes=[ uqbar.apis.FunctionDocumenter, uqbar.apis.SummarizingClassDocumenter, ], module_documenter_class=uqbar.apis.SummarizingModuleDocumenter, root_documenter_class=uqbar.apis.SummarizingRootDocumenter, ) builder() paths = sorted((test_path / "docs").rglob("*")) paths = [str(path.relative_to(test_path)) for path in paths] assert paths == [ "docs/fake_package", "docs/fake_package/empty_module.rst", "docs/fake_package/empty_package", "docs/fake_package/empty_package/empty.rst", "docs/fake_package/empty_package/index.rst", "docs/fake_package/enums.rst", "docs/fake_package/index.rst", "docs/fake_package/module.rst", "docs/fake_package/multi", "docs/fake_package/multi/index.rst", "docs/fake_package/multi/one.rst", "docs/fake_package/multi/two.rst", "docs/index.rst", ] base_path = test_path / "docs" / "fake_package" with (base_path / ".." / "index.rst").open() as file_pointer: <|code_end|> . Use current file imports: import pathlib import shutil import sys import pytest import uqbar.apis from uqbar.strings import normalize and context (classes, functions, or code) from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(file_pointer.read()) == normalize(
Predict the next line for this snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.SummarizingClassDocumenter( "fake_package.module.PublicClass" ) <|code_end|> with the help of current file imports: import pathlib import sys import pytest import uqbar.apis from uqbar.strings import normalize and context from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string , which may contain function names, class names, or code. Output only the next line.
assert normalize(str(documenter)) == normalize(
Using the snippet: <|code_start|> parser.add_argument("--loud", action="store_true", help="be adamant") class WoofCLI(uqbar.cli.CLI): alias = "woof" scripting_group = "mammals" short_description = "speak like a dog" def _process_args(self, arguments): if arguments.loud: print("WOOF!") else: print("Wuf.") def _setup_argument_parser(self, parser): parser.add_argument("--loud", action="store_true", help="be adamant") class VoxAggregator(uqbar.cli.CLIAggregator): @property def cli_classes(self): return [MeowCLI, SquawkCLI, WoofCLI] def test_call(): string_io = io.StringIO() with uqbar.io.RedirectedStreams(string_io, string_io): with pytest.raises(SystemExit): VoxAggregator()("mammals meow --loud") <|code_end|> , determine the next line of code. You have imports: import io import pytest import uqbar.cli import uqbar.io from uqbar.strings import normalize and context (class names, function names, or code) available: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(string_io.getvalue()) == normalize(
Based on the snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.SummarizingModuleDocumenter("fake_package.module") <|code_end|> , predict the immediate next line with the help of imports: import pathlib import sys import pytest import uqbar.apis from uqbar.strings import normalize and context (classes, functions, sometimes code) from other files: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string . Output only the next line.
assert normalize(str(documenter)) == normalize(
Continue the code snippet: <|code_start|> def from_expr(cls, expr): if isinstance(expr, cls): return expr elif isinstance(expr, float): return cls(int(expr)) elif isinstance(expr, int): return cls(expr) elif isinstance(expr, str): <|code_end|> . Use current file imports: import enum from uqbar.strings import to_snake_case and context (classes, functions, or code) from other files: # Path: uqbar/strings.py # def to_snake_case(string: str) -> str: # """ # Convert a string to underscore-delimited words. # # :: # # >>> import uqbar.strings # >>> string = 'Tô Đặc Biệt Xe Lửa' # >>> print(uqbar.strings.to_snake_case(string)) # to_dac_biet_xe_lua # # :: # # >>> string = 'alpha.beta.gamma' # >>> print(uqbar.strings.to_snake_case(string)) # alpha_beta_gamma # # """ # string = unidecode.unidecode(string) # words = (_.lower() for _ in delimit_words(string)) # string = "_".join(words) # return string . Output only the next line.
coerced_expr = to_snake_case(expr.strip()).upper()
Given snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.ClassDocumenter("fake_package.module.PublicClass") <|code_end|> , continue by predicting the next line. Consider current file imports: import pathlib import sys import pytest import uqbar.apis from uqbar.strings import normalize and context: # Path: uqbar/strings.py # def normalize(string: str) -> str: # """ # Normalizes whitespace. # # Strips leading and trailing blank lines, dedents, and removes trailing # whitespace from the result. # """ # string = string.replace("\t", " ") # lines = string.split("\n") # while lines and (not lines[0] or lines[0].isspace()): # lines.pop(0) # while lines and (not lines[-1] or lines[-1].isspace()): # lines.pop() # for i, line in enumerate(lines): # lines[i] = line.rstrip() # string = "\n".join(lines) # string = textwrap.dedent(string) # return string which might include code, classes, or functions. Output only the next line.
assert normalize(str(documenter)) == normalize(
Here is a snippet: <|code_start|> @idiokit.stream def peel_messages(): while True: elements = yield idiokit.next() for message in elements.named("message"): yield idiokit.send(message.children()) <|code_end|> . Write the next line using the current file imports: import getpass import idiokit from idiokit import xmpp from abusehelper.core import bot and context from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): , which may include functions, classes, or code. Output only the next line.
class BridgeBot(bot.Bot):
Continue the code snippet: <|code_start|>""" Bot for testing XMPP server robustness. Sends rapidly as many events to a channel as possible. Maintainer: AbuseSA team <contact@abusesa.com> """ <|code_end|> . Use current file imports: import idiokit from abusehelper.core import bot, events and context (classes, functions, or code) from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): . Output only the next line.
class StressBot(bot.FeedBot):
Given snippet: <|code_start|>""" Bot for testing XMPP server robustness. Sends rapidly as many events to a channel as possible. Maintainer: AbuseSA team <contact@abusesa.com> """ class StressBot(bot.FeedBot): data = bot.Param("event data") @idiokit.stream def feed(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import idiokit from abusehelper.core import bot, events and context: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): which might include code, classes, or functions. Output only the next line.
event = events.Event.from_unicode(self.data.decode("utf-8"))
Continue the code snippet: <|code_start|> class Receiver(bot.XMPPBot): room = bot.Param(""" the room for receiving events from """) @idiokit.stream def main(self): xmpp = yield self.xmpp_connect() room = yield xmpp.muc.join(self.room) yield idiokit.pipe( room, <|code_end|> . Use current file imports: import json import idiokit from abusehelper.core import bot, events and context (classes, functions, or code) from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): . Output only the next line.
events.stanzas_to_events(),
Continue the code snippet: <|code_start|> def normalize(value): if value.startswith("[[") and value.endswith("]]"): return value[2:-2] return value <|code_end|> . Use current file imports: import urllib import getpass import hashlib import idiokit from abusehelper.core import bot, events from opencollab import wiki and context (classes, functions, or code) from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): . Output only the next line.
class OpenCollabReader(bot.FeedBot):
Given snippet: <|code_start|>from __future__ import unicode_literals class TestString(unittest.TestCase): def test_matching(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import re import pickle import unittest from ..atoms import String, RegExp, IP, DomainName and context: # Path: abusehelper/core/rules/atoms.py # class String(Atom): # def init(self, value): # Atom.init(self) # # self._value = unicode(value) # # def unique_key(self): # return self._value # # def __repr__(self): # return Atom.__repr__(self, self._value) # # @property # def value(self): # return self._value # # def match(self, value): # return self._value == value # # def dump(self): # return self._value # # @classmethod # def load(cls, value): # return cls(value) # # class RegExp(Atom): # _forbidden_flags = [ # (re.X, "re.X / re.VERBOSE"), # (re.M, "re.M / re.MULTILINE"), # (re.L, "re.L / re.LOCALE") # ] # # @classmethod # def from_string(cls, string, ignore_case=False): # return cls(re.escape(string), ignore_case=ignore_case) # # @classmethod # def from_re(cls, re_obj): # for flag, name in cls._forbidden_flags: # if re_obj.flags & flag == flag: # raise ValueError("forbidden regular expression flag " + name) # # ignore_case = (re_obj.flags & re.I) != 0 # return cls(re_obj.pattern, ignore_case=ignore_case) # # @property # def pattern(self): # return self._regexp.pattern # # @property # def ignore_case(self): # return self._regexp.flags & re.IGNORECASE != 0 # # def init(self, pattern, ignore_case=False): # Atom.init(self) # # flags = re.U | re.S | (re.I if ignore_case else 0) # try: # self._regexp = re.compile(pattern, flags) # except re.error as error: # raise ValueError(error) # # def unique_key(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # def __repr__(self): # pattern = self._regexp.pattern # if self._regexp.flags & re.IGNORECASE == re.I: # return Atom.__repr__(self, pattern, ignore_case=True) # return Atom.__repr__(self, pattern) # # def match(self, value): # return self._regexp.search(value) # # def dump(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # @classmethod # def load(cls, (pattern, ignore_case)): # return cls(pattern, ignore_case) # # class IP(Atom): # @property # def range(self): # return self._range # # def init(self, range, extra=None): # Atom.init(self) # # if isinstance(range, iprange.IPRange): # if extra is not None: # raise TypeError("unexpected second argument") # else: # range = iprange.IPRange.from_autodetected(range, extra) # self._range = range # # def unique_key(self): # return self._range # # def __repr__(self): # return Atom.__repr__(self, unicode(self._range)) # # def __unicode__(self): # return unicode(self._range) # # def match(self, value): # try: # range = iprange.IPRange.from_autodetected(value) # except ValueError: # return False # return self._range.contains(range) # # def dump(self): # return unicode(self._range) # # @classmethod # def load(cls, value): # return cls(value) # # class DomainName(Atom): # @property # def pattern(self): # return self._pattern # # def init(self, pattern): # Atom.init(self) # # if not isinstance(pattern, _domainname.Pattern): # pattern = _domainname.Pattern.from_string(pattern) # self._pattern = pattern # # def unique_key(self): # return self._pattern # # def __repr__(self): # return Atom.__repr__(self, unicode(self._pattern)) # # def __unicode__(self): # return unicode(self._pattern) # # def match(self, value): # name = _domainname.parse_name(value) # if name is None: # return False # return self._pattern.contains(name) # # def dump(self): # return unicode(self._pattern) # # @classmethod # def load(cls, value): # return cls(value) which might include code, classes, or functions. Output only the next line.
self.assertTrue(String("atom").match("atom"))
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals class TestString(unittest.TestCase): def test_matching(self): self.assertTrue(String("atom").match("atom")) self.assertFalse(String("atom").match("ATOM")) _options = [ String("atom") ] def test_pickling_and_unpickling(self): for option in self._options: self.assertEqual(option, pickle.loads(pickle.dumps(option))) def test_repr(self): for option in self._options: self.assertEqual(option, eval(repr(option))) class TestRegExp(unittest.TestCase): def test_from_string(self): self.assertEqual( <|code_end|> , predict the next line using imports from the current file: import re import pickle import unittest from ..atoms import String, RegExp, IP, DomainName and context including class names, function names, and sometimes code from other files: # Path: abusehelper/core/rules/atoms.py # class String(Atom): # def init(self, value): # Atom.init(self) # # self._value = unicode(value) # # def unique_key(self): # return self._value # # def __repr__(self): # return Atom.__repr__(self, self._value) # # @property # def value(self): # return self._value # # def match(self, value): # return self._value == value # # def dump(self): # return self._value # # @classmethod # def load(cls, value): # return cls(value) # # class RegExp(Atom): # _forbidden_flags = [ # (re.X, "re.X / re.VERBOSE"), # (re.M, "re.M / re.MULTILINE"), # (re.L, "re.L / re.LOCALE") # ] # # @classmethod # def from_string(cls, string, ignore_case=False): # return cls(re.escape(string), ignore_case=ignore_case) # # @classmethod # def from_re(cls, re_obj): # for flag, name in cls._forbidden_flags: # if re_obj.flags & flag == flag: # raise ValueError("forbidden regular expression flag " + name) # # ignore_case = (re_obj.flags & re.I) != 0 # return cls(re_obj.pattern, ignore_case=ignore_case) # # @property # def pattern(self): # return self._regexp.pattern # # @property # def ignore_case(self): # return self._regexp.flags & re.IGNORECASE != 0 # # def init(self, pattern, ignore_case=False): # Atom.init(self) # # flags = re.U | re.S | (re.I if ignore_case else 0) # try: # self._regexp = re.compile(pattern, flags) # except re.error as error: # raise ValueError(error) # # def unique_key(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # def __repr__(self): # pattern = self._regexp.pattern # if self._regexp.flags & re.IGNORECASE == re.I: # return Atom.__repr__(self, pattern, ignore_case=True) # return Atom.__repr__(self, pattern) # # def match(self, value): # return self._regexp.search(value) # # def dump(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # @classmethod # def load(cls, (pattern, ignore_case)): # return cls(pattern, ignore_case) # # class IP(Atom): # @property # def range(self): # return self._range # # def init(self, range, extra=None): # Atom.init(self) # # if isinstance(range, iprange.IPRange): # if extra is not None: # raise TypeError("unexpected second argument") # else: # range = iprange.IPRange.from_autodetected(range, extra) # self._range = range # # def unique_key(self): # return self._range # # def __repr__(self): # return Atom.__repr__(self, unicode(self._range)) # # def __unicode__(self): # return unicode(self._range) # # def match(self, value): # try: # range = iprange.IPRange.from_autodetected(value) # except ValueError: # return False # return self._range.contains(range) # # def dump(self): # return unicode(self._range) # # @classmethod # def load(cls, value): # return cls(value) # # class DomainName(Atom): # @property # def pattern(self): # return self._pattern # # def init(self, pattern): # Atom.init(self) # # if not isinstance(pattern, _domainname.Pattern): # pattern = _domainname.Pattern.from_string(pattern) # self._pattern = pattern # # def unique_key(self): # return self._pattern # # def __repr__(self): # return Atom.__repr__(self, unicode(self._pattern)) # # def __unicode__(self): # return unicode(self._pattern) # # def match(self, value): # name = _domainname.parse_name(value) # if name is None: # return False # return self._pattern.contains(name) # # def dump(self): # return unicode(self._pattern) # # @classmethod # def load(cls, value): # return cls(value) . Output only the next line.
RegExp.from_string("www.example.com", ignore_case=False),
Continue the code snippet: <|code_start|> for flag in [re.M, re.L, re.X]: self.assertRaises(ValueError, RegExp.from_re, re.compile("a", flag)) def test_matching(self): self.assertTrue(RegExp("a").match("a")) # Matching only to the beginning of the string must be explicitly defined self.assertTrue(RegExp("a").match("ba")) self.assertFalse(RegExp("^a").match("ba")) # Matches are case sensitive by default self.assertFalse(RegExp("a").match("A")) self.assertTrue(RegExp("a", ignore_case=True).match("A")) _options = [ RegExp("a"), RegExp("a", ignore_case=True) ] def test_pickling_and_unpickling(self): for option in self._options: self.assertEqual(option, pickle.loads(pickle.dumps(option))) def test_repr(self): for option in self._options: self.assertEqual(option, eval(repr(option))) class TestIP(unittest.TestCase): def test_cidr_constructor_errors(self): <|code_end|> . Use current file imports: import re import pickle import unittest from ..atoms import String, RegExp, IP, DomainName and context (classes, functions, or code) from other files: # Path: abusehelper/core/rules/atoms.py # class String(Atom): # def init(self, value): # Atom.init(self) # # self._value = unicode(value) # # def unique_key(self): # return self._value # # def __repr__(self): # return Atom.__repr__(self, self._value) # # @property # def value(self): # return self._value # # def match(self, value): # return self._value == value # # def dump(self): # return self._value # # @classmethod # def load(cls, value): # return cls(value) # # class RegExp(Atom): # _forbidden_flags = [ # (re.X, "re.X / re.VERBOSE"), # (re.M, "re.M / re.MULTILINE"), # (re.L, "re.L / re.LOCALE") # ] # # @classmethod # def from_string(cls, string, ignore_case=False): # return cls(re.escape(string), ignore_case=ignore_case) # # @classmethod # def from_re(cls, re_obj): # for flag, name in cls._forbidden_flags: # if re_obj.flags & flag == flag: # raise ValueError("forbidden regular expression flag " + name) # # ignore_case = (re_obj.flags & re.I) != 0 # return cls(re_obj.pattern, ignore_case=ignore_case) # # @property # def pattern(self): # return self._regexp.pattern # # @property # def ignore_case(self): # return self._regexp.flags & re.IGNORECASE != 0 # # def init(self, pattern, ignore_case=False): # Atom.init(self) # # flags = re.U | re.S | (re.I if ignore_case else 0) # try: # self._regexp = re.compile(pattern, flags) # except re.error as error: # raise ValueError(error) # # def unique_key(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # def __repr__(self): # pattern = self._regexp.pattern # if self._regexp.flags & re.IGNORECASE == re.I: # return Atom.__repr__(self, pattern, ignore_case=True) # return Atom.__repr__(self, pattern) # # def match(self, value): # return self._regexp.search(value) # # def dump(self): # return self._regexp.pattern, bool(self._regexp.flags & re.I) # # @classmethod # def load(cls, (pattern, ignore_case)): # return cls(pattern, ignore_case) # # class IP(Atom): # @property # def range(self): # return self._range # # def init(self, range, extra=None): # Atom.init(self) # # if isinstance(range, iprange.IPRange): # if extra is not None: # raise TypeError("unexpected second argument") # else: # range = iprange.IPRange.from_autodetected(range, extra) # self._range = range # # def unique_key(self): # return self._range # # def __repr__(self): # return Atom.__repr__(self, unicode(self._range)) # # def __unicode__(self): # return unicode(self._range) # # def match(self, value): # try: # range = iprange.IPRange.from_autodetected(value) # except ValueError: # return False # return self._range.contains(range) # # def dump(self): # return unicode(self._range) # # @classmethod # def load(cls, value): # return cls(value) # # class DomainName(Atom): # @property # def pattern(self): # return self._pattern # # def init(self, pattern): # Atom.init(self) # # if not isinstance(pattern, _domainname.Pattern): # pattern = _domainname.Pattern.from_string(pattern) # self._pattern = pattern # # def unique_key(self): # return self._pattern # # def __repr__(self): # return Atom.__repr__(self, unicode(self._pattern)) # # def __unicode__(self): # return unicode(self._pattern) # # def match(self, value): # name = _domainname.parse_name(value) # if name is None: # return False # return self._pattern.contains(name) # # def dump(self): # return unicode(self._pattern) # # @classmethod # def load(cls, value): # return cls(value) . Output only the next line.
self.assertRaises(ValueError, IP, "192.0.2.0", 33)
Given the following code snippet before the placeholder: <|code_start|> @idiokit.stream def _rate_limiter(rate_limit): last_output = time.time() while True: if rate_limit is not None: delta = max(time.time() - last_output, 0) delay = 1.0 / rate_limit - delta if delay > 0.0: yield idiokit.sleep(delay) last_output = time.time() msg = yield idiokit.next() yield idiokit.send(msg) <|code_end|> , predict the next line using imports from the current file: import sys import json import time import idiokit from idiokit import select from abusehelper.core import bot, events and context including class names, function names, and sometimes code from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): . Output only the next line.
class Receiver(bot.XMPPBot):
Given snippet: <|code_start|>def _rate_limiter(rate_limit): last_output = time.time() while True: if rate_limit is not None: delta = max(time.time() - last_output, 0) delay = 1.0 / rate_limit - delta if delay > 0.0: yield idiokit.sleep(delay) last_output = time.time() msg = yield idiokit.next() yield idiokit.send(msg) class Receiver(bot.XMPPBot): room = bot.Param(""" the room for receiving events from """) rate_limit = bot.IntParam(""" rate limit for the sent stream """, default=None) @idiokit.stream def main(self): xmpp = yield self.xmpp_connect() room = yield xmpp.muc.join(self.room) yield idiokit.pipe( self._read_stdin(), <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import json import time import idiokit from idiokit import select from abusehelper.core import bot, events and context: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/events.py # def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): # def _normalize(value): # def _unicode_quote(string): # def _unicode_parse_part(string, start): # def _itemize(cls, *args, **keys): # def from_unicode(cls, string): # def from_elements(self, elements): # def __init__(self, *args, **keys): # def union(self, *args, **keys): # def difference(self, *args, **keys): # def add(self, key, value, *values): # def update(self, key, values): # def discard(self, key, value, *values): # def clear(self, key): # def _unkeyed(self): # def _iter(self, key, parser, filter): # def pop(self, key, parser=None, filter=None): # def values(self, key=_UNDEFINED, parser=None, filter=None): # def value(self, key=_UNDEFINED, default=_UNDEFINED, # parser=None, filter=None): # def contains(self, key=_UNDEFINED, value=_UNDEFINED, # parser=None, filter=None): # def items(self, parser=None, filter=None): # def keys(self, parser=None, filter=None): # def to_elements(self, include_body=True): # def __reduce__(self): # def __eq__(self, other): # def __ne__(self, other): # def __unicode__(self): # def __repr__(self): # def hexdigest(event, func=hashlib.sha1): # def stanzas_to_events(): # def events_to_elements(): # _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) # EVENT_NS = "abusehelper#event" # _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) # _UNICODE_QUOTE = re.compile(r'["\\]', re.U) # _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) # _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) # _UNDEFINED = object() # class Event(object): which might include code, classes, or functions. Output only the next line.
events.events_to_elements(),
Continue the code snippet: <|code_start|> for value in values: results = results | set([x for x in value.split("|") if x]) return tuple(results) @idiokit.stream def _parse(): while True: event = yield idiokit.next() for key in event.keys(): event.pop(key, filter=lambda value: not value.strip()) for key in ("ip", "asn", "cc"): event.update(key, _value_split(event.pop(key))) for timestamp in event.pop("first seen"): try: timestamp = time.strftime( "%Y-%m-%d %H:%M:%SZ", time.strptime(timestamp, "%Y-%m-%d %H:%M:%S") ) except ValueError: pass else: event.add("first seen", timestamp) yield idiokit.send(event) <|code_end|> . Use current file imports: import time import idiokit from abusehelper.core import bot, utils and context (classes, functions, or code) from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/utils.py # class CertificateError(Exception): # class FetchUrlFailed(Exception): # class FetchUrlTimeout(FetchUrlFailed): # class HTTPError(FetchUrlFailed): # class _CustomHTTPSConnection(httplib.HTTPConnection): # class _CustomHTTPSHandler(urllib2.HTTPSHandler): # class _CSVReader(object): # class TimedCache(object): # class WaitQueue(object): # class WakeUp(Exception): # class CompressedCollection(object): # def format_type(value): # def format_exception(exc): # def __init__(self, code, msg, headers, fileobj): # def __str__(self): # def _is_timeout(reason): # def __init__( # self, # host, # port=None, # strict=None, # timeout=None, # certfile=None, # keyfile=None, # require_cert=True, # ca_certs=None # ): # def connect(self): # def __init__(self, cert=None, verify=True): # def https_open(self, req): # def fetch_url( # url, # opener=None, # timeout=60.0, # chunk_size=16384, # cookies=None, # auth=None, # cert=None, # verify=True, # proxies=None # ): # def force_decode(string, encodings=["ascii", "utf-8"]): # def __init__(self, lines, charset=None, **keys): # def _iterlines(self): # def _normalize(self, value): # def _retry_last_lines(self, quotechar): # def __iter__(self): # def csv_to_events(fileobj, delimiter=",", columns=None, charset=None): # def __init__(self, cache_time): # def _expire(self): # def get(self, key, default): # def set(self, key, value): # def __init__(self): # def _now(self): # def queue(self, delay, obj): # def cancel(self, node): # def wait(self): # def __init__(self, iterable=(), _state=None): # def _close(self): # def __iter__(self): # def __reduce__(self): # def __len__(self): # def append(self, obj): # FORMAT = 1 . Output only the next line.
class RansomwareTrackerBot(bot.PollingBot):
Based on the snippet: <|code_start|> while True: event = yield idiokit.next() for key in event.keys(): event.pop(key, filter=lambda value: not value.strip()) for key in ("ip", "asn", "cc"): event.update(key, _value_split(event.pop(key))) for timestamp in event.pop("first seen"): try: timestamp = time.strftime( "%Y-%m-%d %H:%M:%SZ", time.strptime(timestamp, "%Y-%m-%d %H:%M:%S") ) except ValueError: pass else: event.add("first seen", timestamp) yield idiokit.send(event) class RansomwareTrackerBot(bot.PollingBot): feed_url = bot.Param(default="https://ransomwaretracker.abuse.ch/feeds/csv/") @idiokit.stream def poll(self): self.log.info("Downloading {0}".format(self.feed_url)) try: <|code_end|> , predict the immediate next line with the help of imports: import time import idiokit from abusehelper.core import bot, utils and context (classes, functions, sometimes code) from other files: # Path: abusehelper/core/bot.py # class ParamError(Exception): # class Param(object): # class ListParam(Param): # class BoolParam(Param): # class IntParam(Param): # class FloatParam(Param): # class LineFormatter(logging.Formatter): # class Bot(object): # class XMPPBot(Bot): # class _Service(services.Service): # class ServiceBot(XMPPBot): # class FeedBot(ServiceBot): # class PollSkipped(Exception): # class PollingBot(FeedBot): # NO_VALUE = object() # def __init__(self, help="", short=None, default=NO_VALUE): # def has_default(self): # def parse(self, value): # def __init__(self, *args, **keys): # def parse(self, value): # def __init__(self, help="", short=None): # def parse(self, value=None): # def parse(self, value): # def parse(self, value): # def optparse_name(name): # def optparse_callback(option, opt_str, value, parser, callback, parsed): # def __init__(self): # def format(self, record): # def params(cls): # def param_defaults(cls, **defaults): # def _from_sys_argv(cls, params, **defaults): # def _from_dict(cls, params, **defaults): # def from_command_line(cls, *args, **keys): # def __init__(self, *args, **keys): # def create_logger(self, log_level=logging.INFO): # def execute(self): # def showwarning(message, category, filename, fileno, file=None, line=None): # def run(self): # def __init__(self, *args, **keys): # def run(self): # def main(self): # def xmpp_connect(self): # def __init__(self, bot, *args, **keys): # def main(self, *args, **keys): # def session(self, *args, **keys): # def _run(self): # def run(self): # def throw_stop_on_signal(): # def main(self, state): # def session(self, state, **keys): # def __init__(self, *args, **keys): # def feed_keys(self, *args, **keys): # def feed(self, *args, **keys): # def _cutoff(self): # def _output_rate_limiter(self): # def session(self, state, dst_room, **keys): # def manage_room(self, name): # def manage_connection(self, feed_key, room_name): # def _stats(self, name, interval=60.0): # def counter(event): # def logger(): # def augment(self): # def __init__(self, reason): # def reason(self): # def __init__(self, *args, **keys): # def poll(self, *key): # def dedup(self, key): # def feed(self, *key): # def main(self, state): # # Path: abusehelper/core/utils.py # class CertificateError(Exception): # class FetchUrlFailed(Exception): # class FetchUrlTimeout(FetchUrlFailed): # class HTTPError(FetchUrlFailed): # class _CustomHTTPSConnection(httplib.HTTPConnection): # class _CustomHTTPSHandler(urllib2.HTTPSHandler): # class _CSVReader(object): # class TimedCache(object): # class WaitQueue(object): # class WakeUp(Exception): # class CompressedCollection(object): # def format_type(value): # def format_exception(exc): # def __init__(self, code, msg, headers, fileobj): # def __str__(self): # def _is_timeout(reason): # def __init__( # self, # host, # port=None, # strict=None, # timeout=None, # certfile=None, # keyfile=None, # require_cert=True, # ca_certs=None # ): # def connect(self): # def __init__(self, cert=None, verify=True): # def https_open(self, req): # def fetch_url( # url, # opener=None, # timeout=60.0, # chunk_size=16384, # cookies=None, # auth=None, # cert=None, # verify=True, # proxies=None # ): # def force_decode(string, encodings=["ascii", "utf-8"]): # def __init__(self, lines, charset=None, **keys): # def _iterlines(self): # def _normalize(self, value): # def _retry_last_lines(self, quotechar): # def __iter__(self): # def csv_to_events(fileobj, delimiter=",", columns=None, charset=None): # def __init__(self, cache_time): # def _expire(self): # def get(self, key, default): # def set(self, key, value): # def __init__(self): # def _now(self): # def queue(self, delay, obj): # def cancel(self, node): # def wait(self): # def __init__(self, iterable=(), _state=None): # def _close(self): # def __iter__(self): # def __reduce__(self): # def __len__(self): # def append(self, obj): # FORMAT = 1 . Output only the next line.
info, fileobj = yield utils.fetch_url(self.feed_url)
Given the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. _default_session = {} def get_session(backend_name, **options): global _default_session if not _default_session: _default_session = {} <|code_end|> , generate the next line using the imports in this file: from socketpool import ConnectionPool from restkit.conn import Connection and context (functions, classes, or occasionally code) from other files: # Path: restkit/conn.py # class Connection(Connector): # # def __init__(self, host, port, backend_mod=None, pool=None, # is_ssl=False, extra_headers=[], proxy_pieces=None, timeout=None, # **ssl_args): # # # connect the socket, if we are using an SSL connection, we wrap # # the socket. # self._s = backend_mod.Socket(socket.AF_INET, socket.SOCK_STREAM) # if timeout is not None: # self._s.settimeout(timeout) # self._s.connect((host, port)) # if proxy_pieces: # self._s.sendall(proxy_pieces) # response = cStringIO.StringIO() # while response.getvalue()[-4:] != '\r\n\r\n': # response.write(self._s.recv(1)) # response.close() # if is_ssl: # self._s = ssl.wrap_socket(self._s, **ssl_args) # # self.extra_headers = extra_headers # self.is_ssl = is_ssl # self.backend_mod = backend_mod # self.host = host # self.port = port # self._connected = True # self._life = time.time() - random.randint(0, 10) # self._pool = pool # self._released = False # # def matches(self, **match_options): # target_host = match_options.get('host') # target_port = match_options.get('port') # return target_host == self.host and target_port == self.port # # def is_connected(self): # if self._connected: # return is_connected(self._s) # return False # # def handle_exception(self, exception): # raise # # def get_lifetime(self): # return self._life # # def invalidate(self): # self.close() # self._connected = False # self._life = -1 # # def release(self, should_close=False): # if self._pool is not None: # if self._connected: # if should_close: # self.invalidate() # self._pool.release_connection(self) # else: # self._pool = None # elif self._connected: # self.invalidate() # # def close(self): # if not self._s or not hasattr(self._s, "close"): # return # try: # self._s.close() # except: # pass # # def socket(self): # return self._s # # def send_chunk(self, data): # chunk = "".join(("%X\r\n" % len(data), data, "\r\n")) # self._s.sendall(chunk) # # def send(self, data, chunked=False): # if chunked: # return self.send_chunk(data) # # return self._s.sendall(data) # # def sendlines(self, lines, chunked=False): # for line in list(lines): # self.send(line, chunked=chunked) # # # # TODO: add support for sendfile api # def sendfile(self, data, chunked=False): # """ send a data from a FileObject """ # # if hasattr(data, 'seek'): # data.seek(0) # # while True: # binarydata = data.read(CHUNK_SIZE) # if binarydata == '': # break # self.send(binarydata, chunked=chunked) # # # def recv(self, size=1024): # return self._s.recv(size) . Output only the next line.
pool = ConnectionPool(factory=Connection,
Predict the next line after this snippet: <|code_start|> filename = os.path.join(path, program) if os.access(filename, os.X_OK): return filename return False weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def http_date(timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day, monthname[month], year, hh, mm, ss) return s def parse_netloc(uri): host = uri.netloc port = None i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: <|code_end|> using the current file's imports: import os import re import time import urllib import urlparse import warnings import Cookie import subprocess from restkit.errors import InvalidUrl and any relevant context from other files: # Path: restkit/errors.py # class InvalidUrl(Exception): # """ # Not a valid url for use with this software. # """ . Output only the next line.
raise InvalidUrl("nonnumeric port: '%s'" % host[i+1:])
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): encoded = url_encode(obj, charset=charset) <|code_end|> using the current file's imports: import mimetypes import os import re import urllib from restkit.util import to_bytestring, url_quote, url_encode and any relevant context from other files: # Path: restkit/util.py # def to_bytestring(s): # if not isinstance(s, basestring): # raise TypeError("value should be a str or unicode") # # if isinstance(s, unicode): # return s.encode('utf-8') # return s # # def url_quote(s, charset='utf-8', safe='/:'): # """URL encode a single string with a given encoding.""" # if isinstance(s, unicode): # s = s.encode(charset) # elif not isinstance(s, str): # s = str(s) # return urllib.quote(s, safe=safe) # # def url_encode(obj, charset="utf8", encode_keys=False): # items = [] # if isinstance(obj, dict): # for k, v in list(obj.items()): # items.append((k, v)) # else: # items = list(items) # # tmp = [] # for k, v in items: # if encode_keys: # k = encode(k, charset) # # if not isinstance(v, (tuple, list)): # v = [v] # # for v1 in v: # if v1 is None: # v1 = '' # elif callable(v1): # v1 = encode(v1(), charset) # else: # v1 = encode(v1, charset) # tmp.append('%s=%s' % (urllib.quote(k), urllib.quote_plus(v1))) # return '&'.join(tmp) . Output only the next line.
return to_bytestring(encoded)
Continue the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): encoded = url_encode(obj, charset=charset) return to_bytestring(encoded) class BoundaryItem(object): def __init__(self, name, value, fname=None, filetype=None, filesize=None, <|code_end|> . Use current file imports: import mimetypes import os import re import urllib from restkit.util import to_bytestring, url_quote, url_encode and context (classes, functions, or code) from other files: # Path: restkit/util.py # def to_bytestring(s): # if not isinstance(s, basestring): # raise TypeError("value should be a str or unicode") # # if isinstance(s, unicode): # return s.encode('utf-8') # return s # # def url_quote(s, charset='utf-8', safe='/:'): # """URL encode a single string with a given encoding.""" # if isinstance(s, unicode): # s = s.encode(charset) # elif not isinstance(s, str): # s = str(s) # return urllib.quote(s, safe=safe) # # def url_encode(obj, charset="utf8", encode_keys=False): # items = [] # if isinstance(obj, dict): # for k, v in list(obj.items()): # items.append((k, v)) # else: # items = list(items) # # tmp = [] # for k, v in items: # if encode_keys: # k = encode(k, charset) # # if not isinstance(v, (tuple, list)): # v = [v] # # for v1 in v: # if v1 is None: # v1 = '' # elif callable(v1): # v1 = encode(v1(), charset) # else: # v1 = encode(v1, charset) # tmp.append('%s=%s' % (urllib.quote(k), urllib.quote_plus(v1))) # return '&'.join(tmp) . Output only the next line.
quote=url_quote):
Given the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): <|code_end|> , generate the next line using the imports in this file: import mimetypes import os import re import urllib from restkit.util import to_bytestring, url_quote, url_encode and context (functions, classes, or occasionally code) from other files: # Path: restkit/util.py # def to_bytestring(s): # if not isinstance(s, basestring): # raise TypeError("value should be a str or unicode") # # if isinstance(s, unicode): # return s.encode('utf-8') # return s # # def url_quote(s, charset='utf-8', safe='/:'): # """URL encode a single string with a given encoding.""" # if isinstance(s, unicode): # s = s.encode(charset) # elif not isinstance(s, str): # s = str(s) # return urllib.quote(s, safe=safe) # # def url_encode(obj, charset="utf8", encode_keys=False): # items = [] # if isinstance(obj, dict): # for k, v in list(obj.items()): # items.append((k, v)) # else: # items = list(items) # # tmp = [] # for k, v in items: # if encode_keys: # k = encode(k, charset) # # if not isinstance(v, (tuple, list)): # v = [v] # # for v1 in v: # if v1 is None: # v1 = '' # elif callable(v1): # v1 = encode(v1(), charset) # else: # v1 = encode(v1, charset) # tmp.append('%s=%s' % (urllib.quote(k), urllib.quote_plus(v1))) # return '&'.join(tmp) . Output only the next line.
encoded = url_encode(obj, charset=charset)
Predict the next line for this snippet: <|code_start|>def test_016(u, c): fn = os.path.join(os.path.dirname(__file__), "1M") with open(fn, "rb") as f: l = int(os.fstat(f.fileno())[6]) r = c.request(u, 'POST', body=f) t.eq(r.status_int, 200) t.eq(int(r.body_string()), l) @t.client_request('/large') def test_017(u, c): r = c.request(u, 'POST', body=LONG_BODY_PART) t.eq(r.status_int, 200) t.eq(int(r['content-length']), len(LONG_BODY_PART)) t.eq(r.body_string(), LONG_BODY_PART) def test_0018(): for i in range(10): t.client_request('/large')(test_017) @t.client_request('/') def test_019(u, c): r = c.request(u, 'PUT', body="test") t.eq(r.body_string(), "test") @t.client_request('/auth') def test_020(u, c): <|code_end|> with the help of current file imports: import cgi import imghdr import os import socket import threading import Queue import urlparse import sys import tempfile import time import t from restkit.filters import BasicAuth and context from other files: # Path: restkit/filters.py # class BasicAuth(object): # """ Simple filter to manage basic authentification""" # # def __init__(self, username, password): # self.credentials = (username, password) # # def on_request(self, request): # encode = base64.b64encode("%s:%s" % self.credentials) # request.headers['Authorization'] = 'Basic %s' % encode , which may contain function names, class names, or code. Output only the next line.
c.filters = [BasicAuth("test", "test")]
Here is a snippet: <|code_start|> klass = webob.exc.status_map[http_code] self.code = http_code self.title = klass.title self.status = '%s %s' % (self.code, self.title) self.explanation = msg self.response = response # default params self.msg = msg def _status_int__get(self): """ The status as an integer """ return int(self.status.split()[0]) def _status_int__set(self, value): self.status = value status_int = property(_status_int__get, _status_int__set, doc=_status_int__get.__doc__) def _get_message(self): return self.explanation def _set_message(self, msg): self.explanation = msg or '' message = property(_get_message, _set_message) webob_exceptions = False def wrap_exceptions(): """ wrap restkit exception to return WebBob exceptions""" global webob_exceptions if webob_exceptions: return <|code_end|> . Write the next line using the current file imports: import webob.exc from restkit import errors and context from other files: # Path: restkit/errors.py # class ResourceError(Exception): # class ResourceNotFound(ResourceError): # class Unauthorized(ResourceError): # class ResourceGone(ResourceError): # class RequestFailed(ResourceError): # class RedirectLimit(Exception): # class RequestError(Exception): # class RequestTimeout(Exception): # class InvalidUrl(Exception): # class ResponseError(Exception): # class ProxyError(Exception): # class BadStatusLine(Exception): # class ParserError(Exception): # class UnexpectedEOF(Exception): # class AlreadyRead(Exception): # class ProxyError(Exception): # class ParseException(Exception): # class NoMoreData(ParseException): # class InvalidRequestLine(ParseException): # class InvalidRequestMethod(ParseException): # class InvalidHTTPVersion(ParseException): # class InvalidHTTPStatus(ParseException): # class InvalidHeader(ParseException): # class InvalidHeaderName(ParseException): # class InvalidChunkSize(ParseException): # class ChunkMissingTerminator(ParseException): # class HeaderLimit(ParseException): # def __init__(self, msg=None, http_code=None, response=None): # def _get_message(self): # def _set_message(self, msg): # def __str__(self): # def __init__(self, buf=None): # def __str__(self): # def __init__(self, req): # def __str__(self): # def __init__(self, method): # def __str__(self): # def __init__(self, version): # def __str__(self): # def __init__(self, status): # def __str__(self): # def __init__(self, hdr): # def __str__(self): # def __init__(self, hdr): # def __str__(self): # def __init__(self, data): # def __str__(self): # def __init__(self, term): # def __str__(self): , which may include functions, classes, or code. Output only the next line.
errors.ResourceError = WebobResourceError
Predict the next line for this snippet: <|code_start|> You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) <|code_end|> with the help of current file imports: import base64 import urllib import time import random import urlparse import hmac import binascii import sha from urlparse import parse_qs, parse_qsl from cgi import parse_qs, parse_qsl from restkit.util import to_bytestring from hashlib import sha1 from restkit.version import __version__ and context from other files: # Path: restkit/util.py # def to_bytestring(s): # if not isinstance(s, basestring): # raise TypeError("value should be a str or unicode") # # if isinstance(s, unicode): # return s.encode('utf-8') # return s # # Path: restkit/version.py , which may contain function names, class names, or code. Output only the next line.
return to_bytestring(key), raw
Based on the snippet: <|code_start|> def __call__(self): print self class ContentTypes(object): _values = {} def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, sorted(self._values)) def __str__(self): return '\n'.join(['%-20.20s: %s' % h for h in \ sorted(self._value.items())]) ctypes = ContentTypes() for k in common_indent: attr = k.replace('/', '_').replace('+', '_') ctypes._values[attr] = attr ctypes.__dict__[attr] = k del k, attr class RestShell(InteractiveShellEmbed): def __init__(self, user_ns={}): cfg = Config() shell_config = cfg.InteractiveShellEmbed shell_config.prompt_in1 = '\C_Blue\#) \C_Greenrestcli\$ ' super(RestShell, self).__init__(config = cfg, <|code_end|> , predict the immediate next line with the help of imports: from StringIO import StringIO from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed from webob import Response as BaseResponse from restkit import __version__ from restkit.contrib.console import common_indent, json from restkit.contrib.webob_api import Request as BaseRequest import urlparse import webob import sys and context (classes, functions, sometimes code) from other files: # Path: restkit/version.py # # Path: restkit/contrib/webob_api.py # class Request(BaseRequest): # get = Method('get') # post = Method('post') # put = Method('put') # head = Method('head') # delete = Method('delete') # # def get_response(self): # if self.content_length < 0: # self.content_length = 0 # if self.method in ('DELETE', 'GET'): # self.body = '' # elif self.method == 'POST' and self.POST: # body = urllib.urlencode(self.POST.copy()) # stream = StringIO(body) # stream.seek(0) # self.body_file = stream # self.content_length = stream.len # if 'form' not in self.content_type: # self.content_type = 'application/x-www-form-urlencoded' # self.server_name = self.host # return BaseRequest.get_response(self, PROXY) # # __call__ = get_response # # def set_url(self, url): # # path = url.lstrip('/') # # if url.startswith("http://") or url.startswith("https://"): # u = urlparse.urlsplit(url) # if u.username is not None: # password = u.password or "" # encode = base64.b64encode("%s:%s" % (u.username, password)) # self.headers['Authorization'] = 'Basic %s' % encode # # self.scheme = u.scheme, # self.host = u.netloc.split("@")[-1] # self.path_info = u.path or "/" # self.query_string = u.query # url = urlparse.urlunsplit((u.scheme, u.netloc.split("@")[-1], # u.path, u.query, u.fragment)) # else: # # if '?' in path: # path, self.query_string = path.split('?', 1) # self.path_info = '/' + path # # # url = self.url # self.scheme, self.host, self.path_info = urlparse.urlparse(url)[0:3] . Output only the next line.
banner1= 'restkit shell %s' % __version__,
Here is a snippet: <|code_start|> raise ImportError('webob (http://pythonpaste.org/webob/) is required.') class Stream(StringIO): def __repr__(self): return '<Stream(%s)>' % self.len class JSON(Stream): def __init__(self, value): self.__value = value if json: Stream.__init__(self, json.dumps(value)) else: Stream.__init__(self, value) def __repr__(self): return '<JSON(%s)>' % self.__value class Response(BaseResponse): def __str__(self, skip_body=True): if self.content_length < 200 and skip_body: skip_body = False return BaseResponse.__str__(self, skip_body=skip_body) def __call__(self): print self <|code_end|> . Write the next line using the current file imports: from StringIO import StringIO from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed from webob import Response as BaseResponse from restkit import __version__ from restkit.contrib.console import common_indent, json from restkit.contrib.webob_api import Request as BaseRequest import urlparse import webob import sys and context from other files: # Path: restkit/version.py # # Path: restkit/contrib/webob_api.py # class Request(BaseRequest): # get = Method('get') # post = Method('post') # put = Method('put') # head = Method('head') # delete = Method('delete') # # def get_response(self): # if self.content_length < 0: # self.content_length = 0 # if self.method in ('DELETE', 'GET'): # self.body = '' # elif self.method == 'POST' and self.POST: # body = urllib.urlencode(self.POST.copy()) # stream = StringIO(body) # stream.seek(0) # self.body_file = stream # self.content_length = stream.len # if 'form' not in self.content_type: # self.content_type = 'application/x-www-form-urlencoded' # self.server_name = self.host # return BaseRequest.get_response(self, PROXY) # # __call__ = get_response # # def set_url(self, url): # # path = url.lstrip('/') # # if url.startswith("http://") or url.startswith("https://"): # u = urlparse.urlsplit(url) # if u.username is not None: # password = u.password or "" # encode = base64.b64encode("%s:%s" % (u.username, password)) # self.headers['Authorization'] = 'Basic %s' % encode # # self.scheme = u.scheme, # self.host = u.netloc.split("@")[-1] # self.path_info = u.path or "/" # self.query_string = u.query # url = urlparse.urlunsplit((u.scheme, u.netloc.split("@")[-1], # u.path, u.query, u.fragment)) # else: # # if '?' in path: # path, self.query_string = path.split('?', 1) # self.path_info = '/' + path # # # url = self.url # self.scheme, self.host, self.path_info = urlparse.urlparse(url)[0:3] , which may include functions, classes, or code. Output only the next line.
class Request(BaseRequest):
Using the snippet: <|code_start|># # This file is part of restkit released under the MIT license. # See the NOTICE for more information. try: except ImportError: raise ImportError('WebOb (http://pypi.python.org/pypi/WebOb) is required') __doc__ = '''Subclasses of webob.Request who use restkit to get a webob.Response via restkit.ext.wsgi_proxy.Proxy. Example:: >>> req = Request.blank('http://pypi.python.org/pypi/restkit') >>> resp = req.get_response() >>> print resp #doctest: +ELLIPSIS 200 OK Date: ... Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 Server: Apache/2... <BLANKLINE> <?xml version="1.0" encoding="UTF-8"?> ... ''' <|code_end|> , determine the next line of code. You have imports: import base64 import urlparse import urllib from StringIO import StringIO from webob import Request as BaseRequest from .wsgi_proxy import Proxy and context (class names, function names, or code) available: # Path: restkit/contrib/wsgi_proxy.py # class Proxy(object): # """A proxy wich redirect the request to SERVER_NAME:SERVER_PORT # and send HTTP_HOST header""" # # def __init__(self, manager=None, allowed_methods=ALLOWED_METHODS, # strip_script_name=True, **kwargs): # self.allowed_methods = allowed_methods # self.strip_script_name = strip_script_name # self.client = Client(**kwargs) # # def extract_uri(self, environ): # port = None # scheme = environ['wsgi.url_scheme'] # if 'SERVER_NAME' in environ: # host = environ['SERVER_NAME'] # else: # host = environ['HTTP_HOST'] # if ':' in host: # host, port = host.split(':') # # if not port: # if 'SERVER_PORT' in environ: # port = environ['SERVER_PORT'] # else: # port = scheme == 'https' and '443' or '80' # # uri = '%s://%s:%s' % (scheme, host, port) # return uri # # def __call__(self, environ, start_response): # method = environ['REQUEST_METHOD'] # if method not in self.allowed_methods: # start_response('403 Forbidden', ()) # return [''] # # if self.strip_script_name: # path_info = '' # else: # path_info = environ['SCRIPT_NAME'] # path_info += environ['PATH_INFO'] # # query_string = environ['QUERY_STRING'] # if query_string: # path_info += '?' + query_string # # host_uri = self.extract_uri(environ) # uri = host_uri + path_info # # new_headers = {} # for k, v in environ.items(): # if k.startswith('HTTP_'): # k = k[5:].replace('_', '-').title() # new_headers[k] = v # # # ctype = environ.get("CONTENT_TYPE") # if ctype and ctype is not None: # new_headers['Content-Type'] = ctype # # clen = environ.get('CONTENT_LENGTH') # te = environ.get('transfer-encoding', '').lower() # if not clen and te != 'chunked': # new_headers['transfer-encoding'] = 'chunked' # elif clen: # new_headers['Content-Length'] = clen # # if new_headers.get('Content-Length', '0') == '-1': # raise ValueError(WEBOB_ERROR) # # response = self.client.request(uri, method, body=environ['wsgi.input'], # headers=new_headers) # # if 'location' in response: # if self.strip_script_name: # prefix_path = environ['SCRIPT_NAME'] # # new_location = rewrite_location(host_uri, response.location, # prefix_path=prefix_path) # # headers = [] # for k, v in response.headerslist: # if k.lower() == 'location': # v = new_location # headers.append((k, v)) # else: # headers = response.headerslist # # start_response(response.status, headers) # # if method == "HEAD": # return StringIO() # # return response.tee() . Output only the next line.
PROXY = Proxy(allowed_methods=['GET', 'POST', 'HEAD', 'DELETE', 'PUT', 'PURGE'])
Continue the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. """ TeeInput replace old FileInput. It use a file if size > MAX_BODY or memory. It's now possible to rewind read or restart etc ... It's based on TeeInput from Gunicorn. """ try: except ImportError: class TeeInput(object): <|code_end|> . Use current file imports: import copy import os import tempfile from cStringIO import StringIO from StringIO import StringIO from restkit import conn and context (classes, functions, or code) from other files: # Path: restkit/conn.py # CHUNK_SIZE = 16 * 1024 # MAX_BODY = 1024 * 112 # DNS_TIMEOUT = 60 # class Connection(Connector): # def __init__(self, host, port, backend_mod=None, pool=None, # is_ssl=False, extra_headers=[], proxy_pieces=None, timeout=None, # **ssl_args): # def matches(self, **match_options): # def is_connected(self): # def handle_exception(self, exception): # def get_lifetime(self): # def invalidate(self): # def release(self, should_close=False): # def close(self): # def socket(self): # def send_chunk(self, data): # def send(self, data, chunked=False): # def sendlines(self, lines, chunked=False): # def sendfile(self, data, chunked=False): # def recv(self, size=1024): . Output only the next line.
CHUNK_SIZE = conn.CHUNK_SIZE
Given the following code snippet before the placeholder: <|code_start|> def do_HEAD(self): if self.path == "/ok": extra_headers = [('Content-type', 'text/plain')] self._respond(200, extra_headers, '') else: self.error_Response() def error_Response(self, message=None): req = [ ('HTTP method', self.command), ('path', self.path), ] if message: req.append(('message', message)) body_parts = ['Bad request:\r\n'] for k, v in req: body_parts.append(' %s: %s\r\n' % (k, v)) body = ''.join(body_parts) self._respond(400, [('Content-type', 'text/plain'), ('Content-Length', str(len(body)))], body) def _respond(self, http_code, extra_headers, body): self.send_response(http_code) keys = [] for k, v in extra_headers: self.send_header(k, v) keys.append(k) if body: <|code_end|> , predict the next line using imports from the current file: import base64 import cgi import os import socket import tempfile import threading import unittest import urlparse import Cookie import urllib from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from urlparse import parse_qsl, parse_qs from cgi import parse_qsl, parse_qs from restkit.util import to_bytestring and context including class names, function names, and sometimes code from other files: # Path: restkit/util.py # def to_bytestring(s): # if not isinstance(s, basestring): # raise TypeError("value should be a str or unicode") # # if isinstance(s, unicode): # return s.encode('utf-8') # return s . Output only the next line.
body = to_bytestring(body)
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. root_uri = "http://%s:%s" % (HOST, PORT) def with_webob(func): def wrapper(*args, **kwargs): req = Request.blank('/') req.environ['SERVER_NAME'] = '%s:%s' % (HOST, PORT) return func(req) wrapper.func_name = func.func_name return wrapper @with_webob def test_001(req): req.path_info = '/query' <|code_end|> , continue by predicting the next line. Consider current file imports: import t from _server_test import HOST, PORT from restkit.contrib import wsgi_proxy from webob import Request and context: # Path: restkit/contrib/wsgi_proxy.py # ALLOWED_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] # BLOCK_SIZE = 4096 * 16 # WEBOB_ERROR = ("Content-Length is set to -1. This usually mean that WebOb has " # "already parsed the content body. You should set the Content-Length " # "header to the correct value before forwarding your request to the " # "proxy: ``req.content_length = str(len(req.body));`` " # "req.get_response(proxy)") # class Proxy(object): # class TransparentProxy(Proxy): # class HostProxy(Proxy): # def __init__(self, manager=None, allowed_methods=ALLOWED_METHODS, # strip_script_name=True, **kwargs): # def extract_uri(self, environ): # def __call__(self, environ, start_response): # def extract_uri(self, environ): # def __init__(self, uri, **kwargs): # def extract_uri(self, environ): # def get_config(local_config): # def make_proxy(global_config, **local_config): # def make_host_proxy(global_config, uri=None, **local_config): which might include code, classes, or functions. Output only the next line.
proxy = wsgi_proxy.Proxy()
Predict the next line for this snippet: <|code_start|> class ModelWithChainedQuerySet(models.Model): foo = models.BooleanField(default=False) bar = models.BooleanField(default=False) <|code_end|> with the help of current file imports: from django.db import models from django.db.models.query import QuerySet from django_toolkit.db.models import QuerySetManager and context from other files: # Path: django_toolkit/db/models.py # class QuerySetManager(models.Manager): # """ # @see http://djangosnippets.org/snippets/734/ # @see http://hunterford.me/django-custom-model-manager-chaining/ # """ # def get_queryset(self): # return self.model.QuerySet(self.model) # # def __getattr__(self, name, *args): # if name.startswith('_'): # raise AttributeError # return getattr(self.get_queryset(), name, *args) , which may contain function names, class names, or code. Output only the next line.
objects = QuerySetManager()
Given the following code snippet before the placeholder: <|code_start|> class HtmlGetAnchorHrefTestCase(unittest.TestCase): def test_finds_single_href(self): self.assertEquals( <|code_end|> , predict the next line using imports from the current file: from django.utils import unittest from django_toolkit.markup.html import get_anchor_href, get_anchor_contents and context including class names, function names, and sometimes code from other files: # Path: django_toolkit/markup/html.py # def get_anchor_href(markup): # """ # Given HTML markup, return a list of hrefs for each anchor tag. # """ # soup = BeautifulSoup(markup, 'lxml') # return ['%s' % link.get('href') for link in soup.find_all('a')] # # def get_anchor_contents(markup): # """ # Given HTML markup, return a list of href inner html for each anchor tag. # """ # soup = BeautifulSoup(markup, 'lxml') # return ['%s' % link.contents[0] for link in soup.find_all('a')] . Output only the next line.
get_anchor_href('<a href="http://example.com">Test</a>'),
Next line prediction: <|code_start|> def test_finds_single_href(self): self.assertEquals( get_anchor_href('<a href="http://example.com">Test</a>'), [u'http://example.com'] ) def test_finds_two_hrefs(self): self.assertEquals( get_anchor_href('<a href="http://example.com">Test</a><a href="http://example2.com">Test 2</a>'), [u'http://example.com', u'http://example2.com'] ) def test_finds_two_duplicates(self): self.assertEquals( get_anchor_href('<a href="http://example.com">Test</a><a href="http://example.com">Test 2</a>'), [u'http://example.com', u'http://example.com'] ) def test_finds_hrefs_inside_otherstuff(self): self.assertEquals( get_anchor_href('Here is a <a href="http://example.com/?blah=1234&something-else=KKdjfkdksa">link</a> to somewhere...'), [u'http://example.com/?blah=1234&something-else=KKdjfkdksa'] ) class HtmlGetAnchorHtmlTestCase(unittest.TestCase): def test_finds_single_href(self): self.assertEquals( <|code_end|> . Use current file imports: (from django.utils import unittest from django_toolkit.markup.html import get_anchor_href, get_anchor_contents) and context including class names, function names, or small code snippets from other files: # Path: django_toolkit/markup/html.py # def get_anchor_href(markup): # """ # Given HTML markup, return a list of hrefs for each anchor tag. # """ # soup = BeautifulSoup(markup, 'lxml') # return ['%s' % link.get('href') for link in soup.find_all('a')] # # def get_anchor_contents(markup): # """ # Given HTML markup, return a list of href inner html for each anchor tag. # """ # soup = BeautifulSoup(markup, 'lxml') # return ['%s' % link.contents[0] for link in soup.find_all('a')] . Output only the next line.
get_anchor_contents('<a href="http://example.com">Test</a>'),
Predict the next line after this snippet: <|code_start|> @all_requests def response_content(url, request): if request.headers['User-Agent'] == DESKTOP_USER_AGENT: request.url = 'http://example.com/' return {'status_code': 200} elif request.headers['User-Agent'] == MOBILE_USER_AGENT: request.url = 'http://m.example.com/' return {'status_code': 200} class UrlWithProtocolTestCases(unittest.TestCase): def test_url_with_protocol(self): url = 'example.com' <|code_end|> using the current file's imports: from django.utils import unittest from django_toolkit.url.resolve import url_with_protocol, resolve_url, \ DESKTOP_USER_AGENT, MOBILE_USER_AGENT from httmock import all_requests, HTTMock, response and any relevant context from other files: # Path: django_toolkit/url/resolve.py # def url_with_protocol(url): # if '://' not in url: # return 'http://%s' % url # else: # return url # # def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): # """ # Url Resolver # Given a url a list of resolved urls is returned for desktop and mobile user agents # """ # if not desktop_user_agent: # desktop_user_agent = DESKTOP_USER_AGENT # if not mobile_user_agent: # mobile_user_agent = MOBILE_USER_AGENT # # input_urls = set() # # parsed = urlparse(url_with_protocol(url)) # netloc = parsed.netloc # # if netloc.startswith('www.'): # netloc = netloc[4:] # # input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/')) # input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/')) # # resolved_urls = set() # # for input_url in input_urls: # desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent}) # resolved_urls.add(desktop_request.url) # mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent}) # resolved_urls.add(mobile_request.url) # # return list(resolved_urls) # # DESKTOP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2' # # MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36' . Output only the next line.
url = url_with_protocol(url)
Based on the snippet: <|code_start|> class UrlWithProtocolTestCases(unittest.TestCase): def test_url_with_protocol(self): url = 'example.com' url = url_with_protocol(url) self.assertEquals(url, 'http://example.com') def test_url_with_protocol_www(self): url = 'www.example.com' url = url_with_protocol(url) self.assertEquals(url, 'http://www.example.com') def test_url_with_protocol_http(self): url = 'http://www.example.com' url = url_with_protocol(url) self.assertEquals(url, 'http://www.example.com') def test_url_with_protocol_path(self): url = 'example.com/path.html' url = url_with_protocol(url) self.assertEquals(url, 'http://example.com/path.html') class ResolveUrlTestCases(unittest.TestCase): def test_resolve_url(self): with HTTMock(response_content): url = 'exampledfasdaf.com' <|code_end|> , predict the immediate next line with the help of imports: from django.utils import unittest from django_toolkit.url.resolve import url_with_protocol, resolve_url, \ DESKTOP_USER_AGENT, MOBILE_USER_AGENT from httmock import all_requests, HTTMock, response and context (classes, functions, sometimes code) from other files: # Path: django_toolkit/url/resolve.py # def url_with_protocol(url): # if '://' not in url: # return 'http://%s' % url # else: # return url # # def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): # """ # Url Resolver # Given a url a list of resolved urls is returned for desktop and mobile user agents # """ # if not desktop_user_agent: # desktop_user_agent = DESKTOP_USER_AGENT # if not mobile_user_agent: # mobile_user_agent = MOBILE_USER_AGENT # # input_urls = set() # # parsed = urlparse(url_with_protocol(url)) # netloc = parsed.netloc # # if netloc.startswith('www.'): # netloc = netloc[4:] # # input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/')) # input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/')) # # resolved_urls = set() # # for input_url in input_urls: # desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent}) # resolved_urls.add(desktop_request.url) # mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent}) # resolved_urls.add(mobile_request.url) # # return list(resolved_urls) # # DESKTOP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2' # # MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36' . Output only the next line.
urls = resolve_url(url)
Continue the code snippet: <|code_start|> @all_requests def response_content(url, request): if request.headers['User-Agent'] == DESKTOP_USER_AGENT: request.url = 'http://example.com/' return {'status_code': 200} <|code_end|> . Use current file imports: from django.utils import unittest from django_toolkit.url.resolve import url_with_protocol, resolve_url, \ DESKTOP_USER_AGENT, MOBILE_USER_AGENT from httmock import all_requests, HTTMock, response and context (classes, functions, or code) from other files: # Path: django_toolkit/url/resolve.py # def url_with_protocol(url): # if '://' not in url: # return 'http://%s' % url # else: # return url # # def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): # """ # Url Resolver # Given a url a list of resolved urls is returned for desktop and mobile user agents # """ # if not desktop_user_agent: # desktop_user_agent = DESKTOP_USER_AGENT # if not mobile_user_agent: # mobile_user_agent = MOBILE_USER_AGENT # # input_urls = set() # # parsed = urlparse(url_with_protocol(url)) # netloc = parsed.netloc # # if netloc.startswith('www.'): # netloc = netloc[4:] # # input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/')) # input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/')) # # resolved_urls = set() # # for input_url in input_urls: # desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent}) # resolved_urls.add(desktop_request.url) # mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent}) # resolved_urls.add(mobile_request.url) # # return list(resolved_urls) # # DESKTOP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2' # # MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36' . Output only the next line.
elif request.headers['User-Agent'] == MOBILE_USER_AGENT:
Predict the next line for this snippet: <|code_start|> def get_success_url(self): if self.request.REQUEST.has_key('next'): return self.request.REQUEST.get('next') else: return super(GenericUpdateView, self).get_success_url() class GenericDeleteView(DeleteView): template_name='generic/delete.html' def get_context_data(self, **kwargs): context = DeleteView.get_context_data(self, **kwargs) if self.breadcrumbs: context['breadcrumbs'] = [] for breadcrumb in self.breadcrumbs: if 'title' not in breadcrumb: breadcrumb['title'] = self.object context['breadcrumbs'].append({ 'href': reverse(breadcrumb['viewname']), 'title': breadcrumb['title'] }) context['breadcrumbs'].append({ 'href': self.object.get_absolute_url(), 'title': self.object }) context['breadcrumbs'].append({ 'href': self.request.path, 'title': 'Update' }) return context <|code_end|> with the help of current file imports: import json import os import magic import collections from django.views.generic import DeleteView from django.views.generic.base import View, RedirectView, ContextMixin from django.core.servers.basehttp import FileWrapper from django.http.response import HttpResponse from django.utils.encoding import smart_str from django.views.generic.detail import DetailView, SingleObjectMixin from django.views.generic.edit import CreateView, UpdateView, ModelFormMixin,\ FormMixin from django.core.urlresolvers import reverse from django.contrib import messages from django_toolkit.decorators import class_login_required from django.conf import settings from django.utils.importlib import import_module from django.core.serializers.json import DjangoJSONEncoder from django.views.generic.dates import YearMixin, MonthMixin, DayMixin,\ _date_from_string from django.core.exceptions import ValidationError from django.template import Context, loader from django.http import HttpResponseServerError from django.template import Context, loader from django.http import HttpResponseServerError and context from other files: # Path: django_toolkit/decorators.py # class _cbv_decorate(object): # def __init__(self, dec): # def __call__(self, obj): # def patch_view_decorator(dec): # def _conditional(view): # def permission_required_raise(perm, login_url=None, raise_exception=True): , which may contain function names, class names, or code. Output only the next line.
@class_login_required
Here is a snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iteritems(): fields.append(get_crispy_field_helper(name, field)) return Layout(*fields) def render_layout(self, form, context, template_pack=TEMPLATE_PACK): self.layout = self.build_default_layout(form) return super(SpecialFieldsFormHelper, self).render_layout(form, context, template_pack) def get_crispy_field_helper(name, field): if isinstance(field, DateField): <|code_end|> . Write the next line using the current file imports: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, TEMPLATE_PACK, Field from django.forms.fields import DateField, DateTimeField, CharField from durationfield.forms.fields import DurationField from django_toolkit.forms.widgets import DatePickerField, DateTimePickerField,\ DurationPickerField from django.forms.forms import BoundField from django.utils.safestring import mark_safe and context from other files: # Path: django_toolkit/forms/widgets.py # class DatePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='dateinput dateinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DatePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DateTimePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='datetimeinput datetimeinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DateTimePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DurationPickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='durationinput durationinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DurationPickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) , which may include functions, classes, or code. Output only the next line.
return DatePickerField(name)
Based on the snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iteritems(): fields.append(get_crispy_field_helper(name, field)) return Layout(*fields) def render_layout(self, form, context, template_pack=TEMPLATE_PACK): self.layout = self.build_default_layout(form) return super(SpecialFieldsFormHelper, self).render_layout(form, context, template_pack) def get_crispy_field_helper(name, field): if isinstance(field, DateField): return DatePickerField(name) elif isinstance(field, DateTimeField): <|code_end|> , predict the immediate next line with the help of imports: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, TEMPLATE_PACK, Field from django.forms.fields import DateField, DateTimeField, CharField from durationfield.forms.fields import DurationField from django_toolkit.forms.widgets import DatePickerField, DateTimePickerField,\ DurationPickerField from django.forms.forms import BoundField from django.utils.safestring import mark_safe and context (classes, functions, sometimes code) from other files: # Path: django_toolkit/forms/widgets.py # class DatePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='dateinput dateinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DatePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DateTimePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='datetimeinput datetimeinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DateTimePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DurationPickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='durationinput durationinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DurationPickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) . Output only the next line.
return DateTimePickerField(name)
Given the code snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iteritems(): fields.append(get_crispy_field_helper(name, field)) return Layout(*fields) def render_layout(self, form, context, template_pack=TEMPLATE_PACK): self.layout = self.build_default_layout(form) return super(SpecialFieldsFormHelper, self).render_layout(form, context, template_pack) def get_crispy_field_helper(name, field): if isinstance(field, DateField): return DatePickerField(name) elif isinstance(field, DateTimeField): return DateTimePickerField(name) elif isinstance(field, DurationField): <|code_end|> , generate the next line using the imports in this file: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, TEMPLATE_PACK, Field from django.forms.fields import DateField, DateTimeField, CharField from durationfield.forms.fields import DurationField from django_toolkit.forms.widgets import DatePickerField, DateTimePickerField,\ DurationPickerField from django.forms.forms import BoundField from django.utils.safestring import mark_safe and context (functions, classes, or occasionally code) from other files: # Path: django_toolkit/forms/widgets.py # class DatePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='dateinput dateinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DatePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DateTimePickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='datetimeinput datetimeinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DateTimePickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) # # class DurationPickerField(AppendedText): # # def __init__(self, field, text='<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>', # css_class='durationinput durationinput-picker', extra_css_class='', # *args, **kwargs): # css_class += ' ' + extra_css_class # super(DurationPickerField, self).__init__(field, text=text, # css_class=css_class, # *args, **kwargs) . Output only the next line.
return DurationPickerField(name)
Next line prediction: <|code_start|> class UnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') <|code_end|> . Use current file imports: (from django.utils import unittest from django_toolkit.csv.unicode import UnicodeWriter, UnicodeReader, CastingUnicodeWriter from tempfile import NamedTemporaryFile) and context including class names, function names, or small code snippets from other files: # Path: django_toolkit/csv/unicode.py . Output only the next line.
csv_writer = UnicodeWriter(f, lineterminator="\n")
Predict the next line after this snippet: <|code_start|> self.assertEqual(actual, expected) class CastingUnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') csv_writer = CastingUnicodeWriter(f, lineterminator="\n") csv_writer.writerow(['NAME', 'AGE', 'THINGS']) csv_writer.writerow(['foo', 12, 12.31]) csv_writer.writerow(['bar', 16, 78.89]) f.seek(0) actual = f.read() expected = ("NAME,AGE,THINGS\n" "foo,12,12.31\n" "bar,16,78.89\n") self.assertEqual(actual, expected) class UnicodeReaderWriterTestCase(unittest.TestCase): def test_read(self): f = NamedTemporaryFile(mode='w+') csv_writer = UnicodeWriter(f, lineterminator="\n") expected = [['NAME', 'AGE'], ['foo', '12'], ['bar', '16']] csv_writer.writerows(expected) f.seek(0) <|code_end|> using the current file's imports: from django.utils import unittest from django_toolkit.csv.unicode import UnicodeWriter, UnicodeReader, CastingUnicodeWriter from tempfile import NamedTemporaryFile and any relevant context from other files: # Path: django_toolkit/csv/unicode.py . Output only the next line.
csv_reader = UnicodeReader(f)
Given the code snippet: <|code_start|> class UnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') csv_writer = UnicodeWriter(f, lineterminator="\n") csv_writer.writerow(['NAME', 'AGE']) csv_writer.writerow(['foo', '12']) csv_writer.writerow(['bar', '16']) f.seek(0) actual = f.read() expected = ("NAME,AGE\n" "foo,12\n" "bar,16\n") self.assertEqual(actual, expected) class CastingUnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') <|code_end|> , generate the next line using the imports in this file: from django.utils import unittest from django_toolkit.csv.unicode import UnicodeWriter, UnicodeReader, CastingUnicodeWriter from tempfile import NamedTemporaryFile and context (functions, classes, or occasionally code) from other files: # Path: django_toolkit/csv/unicode.py . Output only the next line.
csv_writer = CastingUnicodeWriter(f, lineterminator="\n")
Predict the next line for this snippet: <|code_start|> self.assertEquals(self.shorten_url('areallylongsubdomain.areallylongexampleecom12', 32), 'areallylongsubd...gexampleecom12') def test_no_www(self): self.assertEquals(self.shorten_url('www.example.com', 16), 'example.com') def test_www(self): self.assertEquals(self.shorten_url('www.example.com', 16, strip_www=False), 'www.example.com') def test_with_path(self): self.assertEquals(self.shorten_url('www.example.com/au', 32, strip_www=False, strip_path=False), 'www.example.com/au') self.assertEquals(self.shorten_url('www.example.com/au', 16, strip_path=False), 'example.com/au') self.assertEquals(self.shorten_url('www.example.com/au', 16, strip_www=False, strip_path=False), 'www.exa...com/au') self.assertEquals(self.shorten_url('www.example.com/au/page/n/', 16, strip_www=False, strip_path=False), 'www.exa...age/n/') self.assertEquals(self.shorten_url('www.example.com.au/au/page/n/', 16, strip_www=False, strip_path=False), 'www.exa...age/n/') self.assertEquals(self.shorten_url('http://www.example.com.au/au/page/n/', 32, strip_www=False, strip_path=False), 'www.example.com.au/au/page/n/') self.assertEquals(self.shorten_url('http://www.example.com.au/au/page/n/', 24, strip_www=False, strip_path=False), 'www.example...au/page/n/') def test_ellipsis(self): self.assertEquals(self.shorten_url('www.example.com/au', 32, strip_www=False, strip_path=False, ellipsis=True), 'www.example.com/au') self.assertEquals(self.shorten_url('www.example.com/au', 16, strip_path=False, ellipsis=True), 'example.com/au') self.assertEquals(self.shorten_url('www.example.com/au', 16, strip_www=False, strip_path=False, ellipsis=True), u'www.exa\u2026com/au') self.assertEquals(self.shorten_url('www.example.com/au/page/n/', 16, strip_www=False, strip_path=False, ellipsis=True), u'www.exa\u2026age/n/') self.assertEquals(self.shorten_url('www.example.com.au/au/page/n/', 16, strip_www=False, strip_path=False, ellipsis=True), u'www.exa\u2026age/n/') self.assertEquals(self.shorten_url('http://www.example.com.au/au/page/n/', 32, strip_www=False, strip_path=False, ellipsis=True), u'www.example.com.au/au/page/n/') self.assertEquals(self.shorten_url('http://www.example.com.au/au/page/n/', 24, strip_www=False, strip_path=False, ellipsis=True), u'www.example\u2026au/page/n/') class NetlocNoWwwTestCase(unittest.TestCase): @property <|code_end|> with the help of current file imports: from django.utils import unittest from django_toolkit.url.shorten import shorten_url, netloc_no_www and context from other files: # Path: django_toolkit/url/shorten.py # def shorten_url(url, length=32, strip_www=True, strip_path=True, ellipsis=False): # """ # Shorten a URL by chopping out the middle. # # For example if supplied with http://subdomain.example.com.au and length 16 # the following would be returned. # # sub...le.com.au # """ # if '://' not in url: # # Ensure we have a protocol # url = 'http://%s' % url # # parsed_url = urlparse(url) # ext = tldextract.extract(parsed_url.netloc) # if ext.subdomain and (not strip_www or (strip_www and ext.subdomain != 'www')): # shortened = u'%s.%s' % (ext.subdomain, ext.domain) # else: # shortened = u'%s' % ext.domain # # if ext.tld: # shortened = u'%s.%s' % (shortened, ext.tld) # # if not strip_path: # if parsed_url.path: # shortened += parsed_url.path # # if len(shortened) <= length: # return shortened # else: # domain = shortened # i = length + 1 - 3 # left = right = int(i/2) # if not i % 2: # right -= 1 # if ellipsis: # shortened = u"%s\u2026%s" % (domain[:left], domain[-right:]) # else: # shortened = '%s...%s' % (domain[:left], domain[-right:]) # # return shortened # # def netloc_no_www(url): # """ # For a given URL return the netloc with any www. striped. # """ # ext = tldextract.extract(url) # if ext.subdomain and ext.subdomain != 'www': # return '%s.%s.%s' % (ext.subdomain, ext.domain, ext.tld) # else: # return '%s.%s' % (ext.domain, ext.tld) , which may contain function names, class names, or code. Output only the next line.
def netloc_no_www(self):
Predict the next line after this snippet: <|code_start|> def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.com/recipes/476197-first-last-day-of-the-month/ """ y, m = dt.year + d_years, dt.month + d_months a, m = divmod(m-1, 12) return datetime(y+a, m+1, 1) def end_of_month(dt): """ Given a date, return the last day of the month. @param dt: The date to base the return value upon. """ return start_of_month(dt, 0, 1) + timedelta(-1) def business_days(start, stop): """ Return business days between two datetimes (inclusive). """ <|code_end|> using the current file's imports: from datetime import datetime, timedelta from dateutil import rrule, relativedelta from django_toolkit.date_util import business_days as dt_business_days from django_toolkit.date_util import days as dt_days and any relevant context from other files: # Path: django_toolkit/date_util.py # def business_days(start, stop): # """ # Return business days between two inclusive dates - ignoring public holidays. # # Note that start must be less than stop or else 0 is returned. # # @param start: Start date # @param stop: Stop date # @return int # """ # dates=rrule.rruleset() # # Get dates between start/stop (which are inclusive) # dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # # Exclude Sat/Sun # dates.exrule(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=start)) # return dates.count() # # Path: django_toolkit/date_util.py # def days(start, stop): # """ # Return days between start & stop (inclusive) # # Note that start must be less than stop or else 0 is returned. # # @param start: Start date # @param stop: Stop date # @return int # """ # dates=rrule.rruleset() # # Get dates between start/stop (which are inclusive) # dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # return dates.count() . Output only the next line.
return dt_business_days(start.date(), stop.date())
Next line prediction: <|code_start|> Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.com/recipes/476197-first-last-day-of-the-month/ """ y, m = dt.year + d_years, dt.month + d_months a, m = divmod(m-1, 12) return datetime(y+a, m+1, 1) def end_of_month(dt): """ Given a date, return the last day of the month. @param dt: The date to base the return value upon. """ return start_of_month(dt, 0, 1) + timedelta(-1) def business_days(start, stop): """ Return business days between two datetimes (inclusive). """ return dt_business_days(start.date(), stop.date()) def days(start, stop): """ Return days between two datetimes (inclusive). """ <|code_end|> . Use current file imports: (from datetime import datetime, timedelta from dateutil import rrule, relativedelta from django_toolkit.date_util import business_days as dt_business_days from django_toolkit.date_util import days as dt_days) and context including class names, function names, or small code snippets from other files: # Path: django_toolkit/date_util.py # def business_days(start, stop): # """ # Return business days between two inclusive dates - ignoring public holidays. # # Note that start must be less than stop or else 0 is returned. # # @param start: Start date # @param stop: Stop date # @return int # """ # dates=rrule.rruleset() # # Get dates between start/stop (which are inclusive) # dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # # Exclude Sat/Sun # dates.exrule(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=start)) # return dates.count() # # Path: django_toolkit/date_util.py # def days(start, stop): # """ # Return days between start & stop (inclusive) # # Note that start must be less than stop or else 0 is returned. # # @param start: Start date # @param stop: Stop date # @return int # """ # dates=rrule.rruleset() # # Get dates between start/stop (which are inclusive) # dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # return dates.count() . Output only the next line.
return dt_days(start.date(), stop.date())
Predict the next line for this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for t5x.losses.""" class LossTest(absltest.TestCase): def test_xent(self): def lossfn(logits, targets, weights): <|code_end|> with the help of current file imports: from absl.testing import absltest from t5x import losses import jax import jax.numpy as jnp import numpy as np and context from other files: # Path: t5x/losses.py # def cross_entropy_with_logits(logits: jnp.ndarray, targets: jnp.ndarray, # z_loss: float) -> jnp.ndarray: # def _cross_entropy_with_logits_fwd( # logits: jnp.ndarray, # targets: jnp.ndarray, # z_loss: float = 0.0 # ) -> Tuple[jnp.ndarray, Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp # def _cross_entropy_with_logits_bwd( # res: Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray, # jnp.ndarray, jnp.ndarray], g: Tuple[jnp.ndarray, jnp.ndarray] # ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: # def compute_weighted_cross_entropy( # logits: jnp.ndarray, # targets: jnp.ndarray, # weights: Optional[jnp.ndarray] = None, # label_smoothing: float = 0.0, # z_loss: float = 0.0, # loss_normalizing_factor: Optional[float] = None # ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: # def convert_special_loss_normalizing_factor_to_enum( # x: str) -> SpecialLossNormalizingFactor: # def get_loss_normalizing_factor_and_weights( # loss_normalizing_factor: Optional[Union[float, int, str, # SpecialLossNormalizingFactor]], # batch: Mapping[str, jnp.ndarray]): # class SpecialLossNormalizingFactor(enum.Enum): # NUM_REAL_TARGET_TOKENS = 1 # NUM_TOTAL_TARGET_TOKENS = 2 # AVERAGE_PER_SEQUENCE = 3 , which may contain function names, class names, or code. Output only the next line.
loss, z_loss, weight_sum = losses.compute_weighted_cross_entropy(
Here is a snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for state_utils.""" class StateUtilsTest(parameterized.TestCase): @parameterized.parameters( dict( state_dict={"a": { "b": 2, "c": 3 }}, intersect_state_dict={ "a": { "b": 4 }, "d": 5 }, expect_state={"a": { "b": 2 }})) def test_intersect_state(self, state_dict, intersect_state_dict, expect_state): <|code_end|> . Write the next line using the current file imports: import re import numpy as np from absl.testing import absltest from absl.testing import parameterized from t5x import state_utils and context from other files: # Path: t5x/state_utils.py # def tensorstore_leaf(_, value): # def flatten_state_dict(state_dict, keep_empty_nodes: bool = False): # def get_name_tree(state_dict, keep_empty_nodes: bool = False): # def intersect_state( # state_dict: Mapping[str, Any], # intersect_state_dict: Mapping[str, Any]) -> Mapping[str, Any]: # def merge_state(state_dict: Mapping[str, Any], # from_scratch_state: Mapping[str, Any]) -> Mapping[str, Any]: # def apply_assignment_map(ckpt_optimizer_state, # optimizer_state, # assignment_map: Sequence[Tuple[str, Optional[str]]], # require_all_rules_match: bool = True, # *, # is_resuming: bool = False): , which may include functions, classes, or code. Output only the next line.
actual_state = state_utils.intersect_state(state_dict, intersect_state_dict)
Predict the next line for this snippet: <|code_start|># You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for t5x.checkpoint_importer.""" class CheckpointImporterTest(absltest.TestCase): def test_rel_embeddings_shared_layers(self): # This represents a ckpt where the Mesh TensorFlow's # transformer_layers.SelfAttention.relative_attention_type = "bias_shared", # i.e., the same relative attention parameters are shared by all layers # within the (en|de)coder. ckpt_data = { 'encoder/block_000/layer_000/SelfAttention/relative_attention_bias': 1, 'decoder/block_000/layer_000/SelfAttention/relative_attention_bias': 2, 'decoder/block_000/layer_000/SelfAttention/relative_attention_bias_slot_v': 3, } <|code_end|> with the help of current file imports: import json import os import jax import numpy as np import tensorflow as tf from absl import flags from absl.testing import absltest from t5x import checkpoint_importer and context from other files: # Path: t5x/checkpoint_importer.py # class LazyArray(abc.ABC): # class LazyThreadPoolArray(LazyArray): # class LazyAwaitableArray(LazyArray): # class CheckpointTranslator: # def __init__(self, shape: Sequence[int], dtype: jnp.dtype, # get_fn: Callable[[], np.ndarray]): # def shape(self) -> Tuple[int, ...]: # def dtype(self) -> jnp.dtype: # def nbytes(self) -> int: # def astype(self, dtype: np.dtype) -> 'LazyArray': # def get_async(self) -> asyncio.Future: # def get(self) -> np.ndarray: # def __repr__(self): # def get_async(self) -> asyncio.Future: # def get(self) -> np.ndarray: # def get_async(self) -> asyncio.Future: # async def _get_and_cast(): # def get(self) -> np.ndarray: # def from_tensor_store_spec( # cls, ts_spec: ts.Spec, # get_fn: Callable[[], np.ndarray]) -> 'LazyAwaitableArray': # def from_array(cls, array: np.ndarray, # get_fn: Callable[[], np.ndarray]) -> 'LazyAwaitableArray': # def from_tensor_store_spec_or_array( # cls, maybe_ts_spec: Union[ts.Spec, np.ndarray], # get_fn: Callable[[], np.ndarray]) -> 'LazyAwaitableArray': # def __init__(self): # def add(self, pattern): # def register_translation_fn_decorator(fn): # def apply(self, flatdict, **opts): # def global_step(opts, key, val): # def shared_embeddings(opts, key, val, slot): # def separate_embeddings(opts, key, val, encdec, slot): # def rel_embeddings(opts, key, val, encdec, blocknum, slot): # def attention_layers(opts, key, val, encdec, blocknum, attntype, qkvo, slot): # def mlpblock(opts, key, val, encdec, blocknum, io_name, io_num, slot): # def layernorms(opts, key, val, encdec, blocknum, lyrnum, slot): # def final_layernorms(opts, key, val, encdec, slot): # def final_logits(opts, key, val, slot): # def _add_missing_param_states(t5_data): # def _maybe_correct_relpos_bias(t5_data): # def load_tf_ckpt(path): # def _update_state_dict(state_dict: Mapping[str, Any], # t5_data: MutableMapping[str, LazyArray], # strict: bool = True) -> Mapping[str, Any]: # def restore_from_t5_checkpoint( # state_dict: Mapping[str, Any], # path: str, # lazy_parameters: bool = False, # strict: bool = True, # translator: Optional[CheckpointTranslator] = None) -> Mapping[str, Any]: # SLOT_MAP = {'_slot_vc': 'v_col', '_slot_vr': 'v_row', '_slot_v': 'v'} # TOWER_MAP = {'transformer': 'decoder'} , which may contain function names, class names, or code. Output only the next line.
t5_data = checkpoint_importer.t5_importer.apply(ckpt_data)
Here is a snippet: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for attention classes.""" # Parse absl flags test_srcdir and test_tmpdir. jax.config.parse_flags_with_absl() Array = jnp.ndarray AxisMetadata = nn_partitioning.AxisMetadata # pylint: disable=invalid-name <|code_end|> . Write the next line using the current file imports: import dataclasses import jax import jax.numpy as jnp import numpy as np from typing import Optional from unittest import mock from absl.testing import absltest from absl.testing import parameterized from flax import linen as nn from flax.core import freeze from flax.linen import partitioning as nn_partitioning from jax import random from jax.nn import initializers from t5x.examples.t5 import layers and context from other files: # Path: t5x/examples/t5/layers.py # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): , which may include functions, classes, or code. Output only the next line.
class SelfAttention(layers.MultiHeadDotProductAttention):
Predict the next line for this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for clu.metrics.""" class MetricsTest(parameterized.TestCase): @parameterized.named_parameters( ("0d_values", 2., 2.), ("1d_values", [1, 2, 3], 6.), ("2d_values", [[1, 2], [2, 3], [3, 4]], 15.), ("3d_values", [[[1, 2], [2, 3]], [[2, 1], [3, 4]], [[3, 1], [4, 1]]], 27.) ) def test_sum(self, values, expected_result): self.assertAlmostEqual( <|code_end|> with the help of current file imports: from absl.testing import absltest from absl.testing import parameterized from t5x import metrics import jax import jax.numpy as jnp import numpy as np and context from other files: # Path: t5x/metrics.py # def _check_param(value, *, ndim=None, dtype=jnp.float32): # def from_model_output(cls, values: Scalar, **_) -> clu_metrics.Metric: # def merge(self, other: "Sum") -> "Sum": # def compute(self) -> Scalar: # def replace_steps(self, steps) -> "Step": # def compute(self) -> Scalar: # def from_model_output(cls, # values: Scalar, # steps: Optional[int] = 1, # **_) -> clu_metrics.Metric: # def merge(self, other: "AveragePerStep") -> "AveragePerStep": # def compute(self) -> Scalar: # def merge(self, other: "Time") -> "Time": # def compute(self) -> Scalar: # def replace_duration(self, duration: Scalar) -> "Time": # def from_model_output(cls, numerator: float, **_) -> clu_metrics.Metric: # def merge(self, other: "TimeRate") -> "TimeRate": # def compute(self) -> Scalar: # def replace_duration(self, duration: Scalar) -> "Time": # def from_model_output(cls, # steps: Optional[int] = 1, # **_) -> clu_metrics.Metric: # def merge(self, other: "StepsPerTime") -> "StepsPerTime": # def compute(self) -> Scalar: # def is_metric_obj(obj): # def is_time_metric(obj): # def create_metrics_dict(float_metrics_dict): # def shape_obj_to_defined_obj(obj: clu_metrics.Metric): # def class_attr_shape(a): # def set_time_metrics_duration(metrics, duration): # def fn(o): # def set_step_metrics_num_steps(metrics, num_steps): # def fn(o): # class Sum(clu_metrics.Metric): # class Step(clu_metrics.Metric): # class AveragePerStep(Step): # class Time(clu_metrics.Metric): # class TimeRate(Time): # class StepsPerTime(Step, Time): , which may contain function names, class names, or code. Output only the next line.
metrics.Sum.from_model_output(values).compute(), expected_result)
Predict the next line after this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for attention classes.""" # Parse absl flags test_srcdir and test_tmpdir. jax.config.parse_flags_with_absl() Array = jnp.ndarray AxisMetadata = nn_partitioning.AxisMetadata # pylint: disable=invalid-name <|code_end|> using the current file's imports: import dataclasses import jax import jax.numpy as jnp import numpy as np from typing import Optional from unittest import mock from absl.testing import absltest from absl.testing import parameterized from flax import linen as nn from flax.core import freeze from flax.linen import partitioning as nn_partitioning from jax import random from jax.nn import initializers from t5x.examples.scalable_t5 import layers and any relevant context from other files: # Path: t5x/examples/scalable_t5/layers.py # def _compute_fans(shape: jax.core.NamedShape, in_axis=-2, out_axis=-1): # def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, # dtype=jnp.float_): # def init(key, shape, dtype=dtype): # def nd_dense_init(scale, mode, distribution): # def init_fn(key, shape, dtype, in_axis, out_axis): # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): . Output only the next line.
class SelfAttention(layers.MultiHeadDotProductAttention):
Using the snippet: <|code_start|>"""Tests for gin_utils.""" class GinUtilsTest(absltest.TestCase): def test_rewrite_gin_args(self): test_args = [ '--gin_file=path/to/file', 'gin.value=3', '--gin.value=3', '--gin.value="3"', '--gin.value=\'3\'', '--gin.tricky="key = value"', '--gin.dict={"foo": 4, "bar": "four"}', '--gin.gin=bar', '--gin.scope/foo=bar', ] expected_args = [ '--gin_file=path/to/file', 'gin.value=3', '--gin_bindings=value = 3', '--gin_bindings=value = "3"', '--gin_bindings=value = \'3\'', '--gin_bindings=tricky = "key = value"', '--gin_bindings=dict = {"foo": 4, "bar": "four"}', '--gin_bindings=gin = bar', '--gin_bindings=scope/foo = bar', ] self.assertSequenceEqual( <|code_end|> , determine the next line of code. You have imports: from absl.testing import absltest from t5x import gin_utils and context (class names, function names, or code) available: # Path: t5x/gin_utils.py # def parse_gin_flags(gin_search_paths: Sequence[str], # gin_files: Sequence[str], # gin_bindings: Sequence[str], # skip_unknown: bool = False, # finalize_config: bool = True): # def rewrite_gin_args(args: Sequence[str]) -> Sequence[str]: # def _rewrite_gin_arg(arg): # def summarize_gin_config(model_dir: str, # summary_writer: Optional[metric_writers.MetricWriter], # step: int): # def run(main): # def sum_fn(var1=gin.REQUIRED, var2=gin.REQUIRED): # def bool_fn(var1=gin.REQUIRED): . Output only the next line.
gin_utils.rewrite_gin_args(test_args), expected_args)
Given snippet: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for attention classes.""" # Parse absl flags test_srcdir and test_tmpdir. jax.config.parse_flags_with_absl() Array = jnp.ndarray AxisMetadata = nn_partitioning.AxisMetadata # pylint: disable=invalid-name <|code_end|> , continue by predicting the next line. Consider current file imports: import dataclasses import jax import jax.numpy as jnp import numpy as np from typing import Optional from unittest import mock from absl.testing import absltest from absl.testing import parameterized from flax import linen as nn from flax.core import freeze from flax.linen import partitioning as nn_partitioning from jax import random from jax.nn import initializers from t5x.examples.decoder_only import layers and context: # Path: t5x/examples/decoder_only/layers.py # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def update_cache_prefill( # self, key: Array, value: Array, cached_key: variables.Variable, # cached_value: variables.Variable, cache_index: variables.Variable, # prefill_lengths: Array # ) -> Tuple[Array, Array, Array, Array, Array, Array]: # def update_cache_decode( # self, key: Array, value: Array, cached_key: variables.Variable, # cached_value: variables.Variable, cache_index: variables.Variable # ) -> Tuple[Array, Array, Array, Array, Array, Array]: # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False, # prefill: bool = False, # prefill_lengths: Optional[Array] = None) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True, decode=False): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): which might include code, classes, or functions. Output only the next line.
class SelfAttention(layers.MultiHeadDotProductAttention):
Next line prediction: <|code_start|> emb_dim: int = 512 num_heads: int = 8 num_encoder_layers: int = 6 num_decoder_layers: int = 6 head_dim: int = 64 mlp_dim: int = 2048 # Activation functions are retrieved from Flax. mlp_activations: Sequence[str] = ('relu',) dropout_rate: float = 0.1 # If `True`, the embedding weights are used in the decoder output layer. logits_via_embedding: bool = False # Whether to accumulate attention logits in float32 regardless of dtype. float32_attention_logits: bool = False class EncoderLayer(nn.Module): """Transformer encoder layer.""" config: T5Config relative_embedding: nn.Module @nn.compact def __call__(self, inputs, encoder_mask=None, deterministic=False): cfg = self.config # Relative position embedding as attention biases. encoder_bias = self.relative_embedding(inputs.shape[-2], inputs.shape[-2], True) # Attention block. assert inputs.ndim == 3 <|code_end|> . Use current file imports: (from typing import Any, Sequence from flax import linen as nn from flax import struct from t5x.examples.t5 import layers import jax.numpy as jnp) and context including class names, function names, or small code snippets from other files: # Path: t5x/examples/t5/layers.py # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): . Output only the next line.
x = layers.LayerNorm(
Next line prediction: <|code_start|># Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for partitioning.""" JaxDevice = jax.lib.xla_client.Device TpuMesh = Tuple[int, int, int, int] # (x, y, z, num_cores). OtherMesh = Tuple[int, int] HardwareMesh = Union[TpuMesh, OtherMesh] PyTreeDef = type(jax.tree_structure(None)) <|code_end|> . Use current file imports: (import abc import collections import dataclasses import typing import cached_property import jax import numpy as np from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging from flax import traverse_util from flax.linen import partitioning as flax_partitioning from jax import numpy as jnp from jax import random from jax.experimental.maps import Mesh from jax.experimental.pjit import pjit as jax_pjit from jax.interpreters.sharded_jit import PartitionSpec # pylint:disable=unused-import from t5x import train_state as train_state_lib) and context including class names, function names, or small code snippets from other files: # Path: t5x/train_state.py # EMPTY_DICT = flax.core.freeze({}) # class TrainState(typing_extensions.Protocol): # class FlaxOptimTrainState(flax.struct.PyTreeNode): # class InferenceState(flax.struct.PyTreeNode): # def step(self) -> jnp.ndarray: # def params(self) -> FrozenVariableDict: # def param_states(self) -> FrozenVariableDict: # def flax_mutables(self) -> FrozenVariableDict: # def state_dict(self) -> MutableVariableDict: # def restore_state(self, state_dict: Mapping[str, Any]) -> 'TrainState': # def replace_params(self, params: VariableDict) -> 'TrainState': # def replace_step(self, step: jnp.ndarray) -> 'TrainState': # def apply_gradient(self, # grads, # learning_rate, # flax_mutables=EMPTY_DICT) -> 'TrainState': # def as_logical_axes(self) -> 'TrainState': # def _validate_params_axes(params_axes, params): # def create(cls, optimizer_def: optim.OptimizerDef, # model_variables: FrozenVariableDict) -> 'FlaxOptimTrainState': # def step(self) -> jnp.ndarray: # def params(self) -> FrozenVariableDict: # def param_states(self) -> FrozenVariableDict: # def state_dict(self) -> MutableVariableDict: # def apply_gradient(self, # grads, # learning_rate, # flax_mutables=EMPTY_DICT) -> 'FlaxOptimTrainState': # def replace_params(self, params: VariableDict) -> 'FlaxOptimTrainState': # def replace_step(self, step: jnp.ndarray) -> 'FlaxOptimTrainState': # def restore_state(self, state_dict: VariableDict) -> 'FlaxOptimTrainState': # def as_logical_axes(self) -> 'FlaxOptimTrainState': # def create(cls, model_variables: FrozenVariableDict) -> 'InferenceState': # def param_states(self) -> FrozenVariableDict: # def apply_gradient(self, *args, **kwargs) -> 'InferenceState': # def state_dict(self) -> MutableMapping[str, Any]: # def replace_step(self, step: jnp.ndarray) -> 'InferenceState': # def replace_params(self, params: FrozenVariableDict) -> 'InferenceState': # def restore_state(self, state_dict: Mapping[str, Any]) -> 'InferenceState': # def as_logical_axes(self) -> 'InferenceState': . Output only the next line.
TrainState = train_state_lib.TrainState
Predict the next line after this snippet: <|code_start|> dropout_rate: float = 0.1 # If `True`, the embedding weights are used in the decoder output layer. logits_via_embedding: bool = False class DecoderLayer(nn.Module): """Transformer decoder layer.""" config: TransformerConfig @nn.compact def __call__(self, inputs: jnp.ndarray, decoder_mask: Optional[jnp.ndarray] = None, deterministic: bool = False, decode: bool = False, max_decode_length: Optional[int] = None, prefill: bool = False, prefill_lengths: Optional[jnp.ndarray] = None): """Applies decoder block module.""" cfg = self.config # Relative position embedding as attention biases. l = max_decode_length if decode and max_decode_length else inputs.shape[-2] # During decoding, this module will be called with `decode=True` first to # initialize the decoder cache, including a cached relpos bias. The prefill # codepath will call this once again with `decode=False`, which is slightly # wasteful but generally harmless. During subsequent decode steps, this will # be called with `decode=True` and will reuse the cached bias. This # significantly improves performance during decoding with many decode steps. <|code_end|> using the current file's imports: from typing import Any, Optional, Sequence from flax import linen as nn from flax import struct from t5x.examples.decoder_only import layers import jax.numpy as jnp and any relevant context from other files: # Path: t5x/examples/decoder_only/layers.py # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def update_cache_prefill( # self, key: Array, value: Array, cached_key: variables.Variable, # cached_value: variables.Variable, cache_index: variables.Variable, # prefill_lengths: Array # ) -> Tuple[Array, Array, Array, Array, Array, Array]: # def update_cache_decode( # self, key: Array, value: Array, cached_key: variables.Variable, # cached_value: variables.Variable, cache_index: variables.Variable # ) -> Tuple[Array, Array, Array, Array, Array, Array]: # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False, # prefill: bool = False, # prefill_lengths: Optional[Array] = None) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True, decode=False): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): . Output only the next line.
decoder_bias = layers.RelativePositionBiases(
Given the following code snippet before the placeholder: <|code_start|> """Global hyperparameters used to minimize obnoxious kwarg plumbing.""" vocab_size: int # Activation dtypes. dtype: Any = jnp.float32 emb_dim: int = 512 num_heads: int = 8 num_encoder_layers: int = 6 num_decoder_layers: int = 6 head_dim: int = 64 mlp_dim: int = 2048 # Activation functions are retrieved from Flax. mlp_activations: Sequence[str] = ('relu',) dropout_rate: float = 0.1 # If `True`, the embedding weights are used in the decoder output layer. logits_via_embedding: bool = False # minimal, full, or none remat_policy: str = 'none' scan_layers: bool = True param_scan_axis: int = 1 class EncoderLayer(nn.Module): """Transformer encoder layer.""" config: T5Config @nn.compact def __call__(self, inputs, encoder_mask=None, deterministic=False): cfg = self.config # Relative position embedding as attention biases. <|code_end|> , predict the next line using imports from the current file: from typing import Any, Sequence from flax import linen as nn from flax import struct from flax.linen import partitioning as nn_partitioning from t5x.examples.scalable_t5 import layers import jax import jax.numpy as jnp and context including class names, function names, and sometimes code from other files: # Path: t5x/examples/scalable_t5/layers.py # def _compute_fans(shape: jax.core.NamedShape, in_axis=-2, out_axis=-1): # def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, # dtype=jnp.float_): # def init(key, shape, dtype=dtype): # def nd_dense_init(scale, mode, distribution): # def init_fn(key, shape, dtype, in_axis, out_axis): # def dot_product_attention(query: Array, # key: Array, # value: Array, # bias: Optional[Array] = None, # dropout_rng: Optional[PRNGKey] = None, # dropout_rate: float = 0., # deterministic: bool = False, # dtype: DType = jnp.float32, # float32_logits: bool = False): # def __call__(self, # inputs_q: Array, # inputs_kv: Array, # mask: Optional[Array] = None, # bias: Optional[Array] = None, # *, # decode: bool = False, # deterministic: bool = False) -> Array: # def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: # def _canonicalize_tuple(x): # def __call__(self, inputs: Array) -> Array: # def _convert_to_activation_function( # fn_or_string: Union[str, Callable]) -> Callable: # def __call__(self, inputs, decode: bool = False, deterministic: bool = False): # def setup(self): # def __call__(self, inputs: Array) -> Array: # def attend(self, query: Array) -> Array: # def _relative_position_bucket(relative_position, # bidirectional=True, # num_buckets=32, # max_distance=128): # def __call__(self, qlen, klen, bidirectional=True): # def __call__(self, x: jnp.ndarray) -> jnp.ndarray: # def make_attention_mask(query_input: Array, # key_input: Array, # pairwise_fn: Callable = jnp.multiply, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def make_causal_mask(x: Array, # extra_batch_dims: int = 0, # dtype: DType = jnp.float32) -> Array: # def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): # def combine_biases(*masks: Optional[Array]): # def make_decoder_mask(decoder_target_tokens: Array, # dtype: DType, # decoder_causal_attention: Optional[Array] = None, # decoder_segment_ids: Optional[Array] = None) -> Array: # class MultiHeadDotProductAttention(nn.Module): # class DenseGeneral(nn.Module): # class MlpBlock(nn.Module): # class Embed(nn.Module): # class RelativePositionBiases(nn.Module): # class LayerNorm(nn.Module): . Output only the next line.
encoder_bias = layers.RelativePositionBiases(
Here is a snippet: <|code_start|> async for index in self.db.indexes.find({"has_json": {"$ne": True}}): index_id = index["_id"] ref_id = index["reference"]["id"] document = await self.db.references.find_one( ref_id, ["data_type", "organism", "targets"] ) otu_list = await virtool.references.db.export(self.app, ref_id) data = { "otus": otu_list, "data_type": document["data_type"], "organism": document["organism"], } try: data["targets"] = document["targets"] except KeyError: pass file_path = ( self.app["config"].data_path / "references" / ref_id / index_id / "reference.json.gz" ) # Convert the list of OTUs to a JSON-formatted string. <|code_end|> . Write the next line using the current file imports: import asyncio import json import os import shutil import aiohttp import arrow import virtool.errors import virtool.otus.db import virtool.tasks.pg from datetime import timedelta from pathlib import Path from semver import VersionInfo from virtool.api.json import CustomEncoder from virtool.github import create_update_subdocument from virtool.history.db import patch_to_version from virtool.history.utils import remove_diff_files from virtool.http.utils import download_file from virtool.references.db import ( download_and_parse_release, fetch_and_update_release, insert_change, insert_joined_otu, update_joined_otu, ) from virtool.references.utils import check_import_data, load_reference_file from virtool.tasks.task import Task from virtool.utils import compress_json_with_gzip, get_temp_dir and context from other files: # Path: virtool/api/json.py # class CustomEncoder(json.JSONEncoder): # """ # A custom :class:`JSONEncoder` that converts :class:`datetime` objects to # ISO-formatting date strings. # # """ # # def default(self, obj): # if isinstance(obj, datetime.datetime): # return isoformat(obj) # # return json.JSONEncoder.default(self, obj) # # Path: virtool/history/db.py # async def patch_to_version(app, otu_id: str, version: Union[str, int]) -> tuple: # """ # Take a joined otu back in time to the passed ``version``. # # Uses the diffs in the change documents associated with the otu. # # :param app: the application object # :param otu_id: the id of the otu to patch # :param version: the version to patch to # :return: the current joined otu, patched otu, and the ids of reverted changes # # """ # db = app["db"] # # reverted_history_ids = list() # # current = await virtool.otus.db.join(db, otu_id) or dict() # # if "version" in current and current["version"] == version: # return current, deepcopy(current), reverted_history_ids # # patched = deepcopy(current) # # # Sort the changes by descending timestamp. # async for change in db.history.find({"otu.id": otu_id}, sort=[("otu.version", -1)]): # if change["otu"]["version"] == "removed" or change["otu"]["version"] > version: # reverted_history_ids.append(change["_id"]) # # if change["diff"] == "file": # change["diff"] = await virtool.history.utils.read_diff_file( # app["config"].data_path, otu_id, change["otu"]["version"] # ) # # if change["method_name"] == "remove": # patched = change["diff"] # # elif change["method_name"] == "create": # patched = None # # else: # diff = dictdiffer.swap(change["diff"]) # patched = dictdiffer.patch(diff, patched) # else: # break # # if current == {}: # current = None # # return current, patched, reverted_history_ids # # Path: virtool/history/utils.py # async def remove_diff_files(app, id_list: List[str]): # """ # Remove multiple diff files given a list of change IDs (`id_list`). # # :param app: the application object # :param id_list: a list of change IDs to remove diff files for # # """ # data_path = app["config"].data_path # # for change_id in id_list: # otu_id, otu_version = change_id.split(".") # # path = join_diff_path(data_path, otu_id, otu_version) # # try: # await app["run_in_thread"](os.remove, path) # except FileNotFoundError: # pass , which may include functions, classes, or code. Output only the next line.
json_string = json.dumps(data, cls=CustomEncoder)
Predict the next line for this snippet: <|code_start|> class CloneReferenceTask(Task): task_type = "clone_reference" def __init__(self, app, task_id): super().__init__(app, task_id) self.steps = [self.copy_otus, self.create_history] async def copy_otus(self): manifest = self.context["manifest"] created_at = self.context["created_at"] ref_id = self.context["ref_id"] user_id = self.context["user_id"] tracker = await self.get_tracker(len(manifest)) inserted_otu_ids = list() await virtool.tasks.pg.update(self.pg, self.id, step="copy_otus") for source_otu_id, version in manifest.items(): <|code_end|> with the help of current file imports: import asyncio import json import os import shutil import aiohttp import arrow import virtool.errors import virtool.otus.db import virtool.tasks.pg from datetime import timedelta from pathlib import Path from semver import VersionInfo from virtool.api.json import CustomEncoder from virtool.github import create_update_subdocument from virtool.history.db import patch_to_version from virtool.history.utils import remove_diff_files from virtool.http.utils import download_file from virtool.references.db import ( download_and_parse_release, fetch_and_update_release, insert_change, insert_joined_otu, update_joined_otu, ) from virtool.references.utils import check_import_data, load_reference_file from virtool.tasks.task import Task from virtool.utils import compress_json_with_gzip, get_temp_dir and context from other files: # Path: virtool/api/json.py # class CustomEncoder(json.JSONEncoder): # """ # A custom :class:`JSONEncoder` that converts :class:`datetime` objects to # ISO-formatting date strings. # # """ # # def default(self, obj): # if isinstance(obj, datetime.datetime): # return isoformat(obj) # # return json.JSONEncoder.default(self, obj) # # Path: virtool/history/db.py # async def patch_to_version(app, otu_id: str, version: Union[str, int]) -> tuple: # """ # Take a joined otu back in time to the passed ``version``. # # Uses the diffs in the change documents associated with the otu. # # :param app: the application object # :param otu_id: the id of the otu to patch # :param version: the version to patch to # :return: the current joined otu, patched otu, and the ids of reverted changes # # """ # db = app["db"] # # reverted_history_ids = list() # # current = await virtool.otus.db.join(db, otu_id) or dict() # # if "version" in current and current["version"] == version: # return current, deepcopy(current), reverted_history_ids # # patched = deepcopy(current) # # # Sort the changes by descending timestamp. # async for change in db.history.find({"otu.id": otu_id}, sort=[("otu.version", -1)]): # if change["otu"]["version"] == "removed" or change["otu"]["version"] > version: # reverted_history_ids.append(change["_id"]) # # if change["diff"] == "file": # change["diff"] = await virtool.history.utils.read_diff_file( # app["config"].data_path, otu_id, change["otu"]["version"] # ) # # if change["method_name"] == "remove": # patched = change["diff"] # # elif change["method_name"] == "create": # patched = None # # else: # diff = dictdiffer.swap(change["diff"]) # patched = dictdiffer.patch(diff, patched) # else: # break # # if current == {}: # current = None # # return current, patched, reverted_history_ids # # Path: virtool/history/utils.py # async def remove_diff_files(app, id_list: List[str]): # """ # Remove multiple diff files given a list of change IDs (`id_list`). # # :param app: the application object # :param id_list: a list of change IDs to remove diff files for # # """ # data_path = app["config"].data_path # # for change_id in id_list: # otu_id, otu_version = change_id.split(".") # # path = join_diff_path(data_path, otu_id, otu_version) # # try: # await app["run_in_thread"](os.remove, path) # except FileNotFoundError: # pass , which may contain function names, class names, or code. Output only the next line.
_, patched, _ = await patch_to_version(self.app, source_otu_id, version)
Based on the snippet: <|code_start|> await self.update_context({"inserted_otu_ids": inserted_otu_ids}) async def create_history(self): user_id = self.context["user_id"] inserted_otu_ids = self.context["inserted_otu_ids"] tracker = await self.get_tracker(len(inserted_otu_ids)) await virtool.tasks.pg.update(self.pg, self.id, step="create_history") for otu_id in inserted_otu_ids: await insert_change(self.app, otu_id, "clone", user_id) await tracker.add(1) async def cleanup(self): ref_id = self.context["ref_id"] query = {"reference.id": ref_id} diff_file_change_ids = await self.db.history.distinct( "_id", {**query, "diff": "file"} ) await virtool.tasks.pg.update(self.pg, self.id, step="cleanup") await asyncio.gather( self.db.references.delete_one({"_id": ref_id}), self.db.history.delete_many(query), self.db.otus.delete_many(query), self.db.sequences.delete_many(query), <|code_end|> , predict the immediate next line with the help of imports: import asyncio import json import os import shutil import aiohttp import arrow import virtool.errors import virtool.otus.db import virtool.tasks.pg from datetime import timedelta from pathlib import Path from semver import VersionInfo from virtool.api.json import CustomEncoder from virtool.github import create_update_subdocument from virtool.history.db import patch_to_version from virtool.history.utils import remove_diff_files from virtool.http.utils import download_file from virtool.references.db import ( download_and_parse_release, fetch_and_update_release, insert_change, insert_joined_otu, update_joined_otu, ) from virtool.references.utils import check_import_data, load_reference_file from virtool.tasks.task import Task from virtool.utils import compress_json_with_gzip, get_temp_dir and context (classes, functions, sometimes code) from other files: # Path: virtool/api/json.py # class CustomEncoder(json.JSONEncoder): # """ # A custom :class:`JSONEncoder` that converts :class:`datetime` objects to # ISO-formatting date strings. # # """ # # def default(self, obj): # if isinstance(obj, datetime.datetime): # return isoformat(obj) # # return json.JSONEncoder.default(self, obj) # # Path: virtool/history/db.py # async def patch_to_version(app, otu_id: str, version: Union[str, int]) -> tuple: # """ # Take a joined otu back in time to the passed ``version``. # # Uses the diffs in the change documents associated with the otu. # # :param app: the application object # :param otu_id: the id of the otu to patch # :param version: the version to patch to # :return: the current joined otu, patched otu, and the ids of reverted changes # # """ # db = app["db"] # # reverted_history_ids = list() # # current = await virtool.otus.db.join(db, otu_id) or dict() # # if "version" in current and current["version"] == version: # return current, deepcopy(current), reverted_history_ids # # patched = deepcopy(current) # # # Sort the changes by descending timestamp. # async for change in db.history.find({"otu.id": otu_id}, sort=[("otu.version", -1)]): # if change["otu"]["version"] == "removed" or change["otu"]["version"] > version: # reverted_history_ids.append(change["_id"]) # # if change["diff"] == "file": # change["diff"] = await virtool.history.utils.read_diff_file( # app["config"].data_path, otu_id, change["otu"]["version"] # ) # # if change["method_name"] == "remove": # patched = change["diff"] # # elif change["method_name"] == "create": # patched = None # # else: # diff = dictdiffer.swap(change["diff"]) # patched = dictdiffer.patch(diff, patched) # else: # break # # if current == {}: # current = None # # return current, patched, reverted_history_ids # # Path: virtool/history/utils.py # async def remove_diff_files(app, id_list: List[str]): # """ # Remove multiple diff files given a list of change IDs (`id_list`). # # :param app: the application object # :param id_list: a list of change IDs to remove diff files for # # """ # data_path = app["config"].data_path # # for change_id in id_list: # otu_id, otu_version = change_id.split(".") # # path = join_diff_path(data_path, otu_id, otu_version) # # try: # await app["run_in_thread"](os.remove, path) # except FileNotFoundError: # pass . Output only the next line.
remove_diff_files(self.app, diff_file_change_ids),
Given snippet: <|code_start|> @pytest.mark.parametrize("version", ["3.5.9", "3.6.0", "3.6.1"]) async def test_check_mongo_version(dbi, caplog, mocker, version): mocker.patch("virtool.db.mongo.get_mongo_version", return_value=version) caplog.set_level(logging.INFO) try: <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest from virtool.db.mongo import check_mongo_version and context: # Path: virtool/db/mongo.py # async def check_mongo_version(db: AsyncIOMotorClient) -> str: # """ # Check the MongoDB version. # # Log a critical error and exit if it is too old. Return it otherwise. # # :param db: the application database object # :return: the MongoDB version # """ # mongo_version = await get_mongo_version(db) # # if VersionInfo.parse(mongo_version) < VersionInfo.parse(MINIMUM_MONGO_VERSION): # logger.critical( # f"Virtool requires MongoDB {MINIMUM_MONGO_VERSION}. Found {mongo_version}." # ) # sys.exit(1) # # logger.info(f"Found MongoDB {mongo_version}") # # return mongo_version which might include code, classes, or functions. Output only the next line.
await check_mongo_version(dbi)
Continue the code snippet: <|code_start|> "stage": None, "error": None, "progress": 0, "timestamp": self._faker.date_time(), } ], "user": {"id": await self.generator.users.get_id()}, } async def insert(self) -> dict: document = await self.create() await self._db.jobs.insert_one(document) return document async def get_id(self): id_list = await self._db.jobs.distinct("_id") if id_list: return self._faker.random_element(id_list) document = await self.insert() return document["_id"] class FakeUserGenerator(AbstractFakeDataGenerator): def __init__(self, fake_generator, db): self.generator = fake_generator self._db = db <|code_end|> . Use current file imports: from abc import ABC, abstractmethod from attr import dataclass from faker.proxy import Faker from virtool.fake.wrapper import FakerWrapper import pytest and context (classes, functions, or code) from other files: # Path: virtool/fake/wrapper.py # class FakerWrapper: # def __init__(self): # self.fake = Faker() # self.fake.seed_instance(0) # self.fake.add_provider(address) # self.fake.add_provider(misc) # self.fake.add_provider(lorem) # self.fake.add_provider(python) # self.fake.add_provider(date_time) # self.fake.add_provider(profile) # # self.country = self.fake.country # # self.text = self.fake.text # self.word = self.fake.word # self.words = self.fake.words # # self.integer = self.fake.pyint # self.list = self.fake.pylist # self.boolean = self.fake.pybool # self.profile = self.fake.profile # self.date_time = self.fake.date_time # self.random_element = self.fake.random_element # # def get_mongo_id(self) -> str: # """ # Create a predictable, fake ID for MongoDB that imitates Virtool IDs. # # :return: a fake MongoDB ID # # """ # return self.fake.password(length=8, special_chars=False) . Output only the next line.
self._faker = FakerWrapper()
Given snippet: <|code_start|> 1. Removes the ``status`` and ``args`` fields from the job document. 2. Adds a ``username`` field. 3. Adds a ``created_at`` date taken from the first status entry in the job document. 4. Adds ``state`` and ``progress`` fields derived from the most recent ``status`` entry in the job document. :param db: the application database object :param document: a document to process :return: a processed document """ status = document["status"] last_update = status[-1] return await apply_transforms( virtool.utils.base_processor( { **document, "state": last_update["state"], "stage": last_update["stage"], "created_at": status[0]["timestamp"], "progress": status[-1]["progress"], } ), [AttachUserTransform(db)], ) <|code_end|> , continue by predicting the next line. Consider current file imports: from asyncio import gather from typing import Any, Dict, Optional from virtool.db.transforms import apply_transforms from virtool.jobs.utils import JobRights from virtool.types import App from virtool.users.db import AttachUserTransform import virtool.utils and context: # Path: virtool/types.py which might include code, classes, or functions. Output only the next line.
async def delete(app: App, job_id: str):
Next line prediction: <|code_start|> @pytest.mark.parametrize( "user_id,password,result", [ ("test", "foobar", True), ("baz", "foobar", False), ("test", "baz", False), ("baz", "baz", False), ], ) @pytest.mark.parametrize("legacy", [True, False]) async def test_validate_credentials(legacy, user_id, password, result, dbi): """ Test that valid, bcrypt-based credentials work. """ document = {"_id": "test"} if legacy: salt = random_alphanumeric(24) document.update( { "salt": salt, "password": hashlib.sha512( salt.encode("utf-8") + "foobar".encode("utf-8") ).hexdigest(), } ) else: <|code_end|> . Use current file imports: (import hashlib import pytest import virtool.errors from aiohttp.test_utils import make_mocked_coro from virtool.db.transforms import apply_transforms from virtool.users.db import ( AttachUserTransform, B2CUserAttributes, compose_force_reset_update, compose_groups_update, compose_password_update, compose_primary_group_update, create, edit, find_or_create_b2c_user, generate_handle, update_sessions_and_keys, validate_credentials, ) from virtool.users.utils import hash_password from virtool.utils import random_alphanumeric) and context including class names, function names, or small code snippets from other files: # Path: virtool/users/utils.py # def hash_password(password: str) -> str: # """ # Salt and hash a unicode password. Uses bcrypt. # # :param password: a password string to salt and hash # :return: a salt and hashed password # # """ # return bcrypt.hashpw(password.encode(), bcrypt.gensalt(12)) . Output only the next line.
document["password"] = hash_password("foobar")